• Home
Name Date Size #Lines LOC

..--

src/12-May-2024-5,9744,472

tests/12-May-2024-364,274360,974

tools/12-May-2024-152104

typings/12-May-2024-96

CHANGELOG.mdD12-May-202447.5 KiB1,015360

LICENSED12-May-20241.3 KiB2721

README.mdD12-May-202411.9 KiB339265

jest.config.jsD12-May-2024668 2724

package.jsonD12-May-20242.2 KiB8887

tsconfig.build.jsonD12-May-2024389 1615

tsconfig.jsonD12-May-2024384 1514

README.md

1<h1 align="center">TypeScript ESTree</h1>
2
3<p align="center">A parser that converts TypeScript source code into an <a href="https://github.com/estree/estree">ESTree</a>-compatible form</p>
4
5<p align="center">
6    <img src="https://github.com/typescript-eslint/typescript-eslint/workflows/CI/badge.svg" alt="CI" />
7    <a href="https://www.npmjs.com/package/@typescript-eslint/typescript-estree"><img src="https://img.shields.io/npm/v/@typescript-eslint/typescript-estree.svg?style=flat-square" alt="NPM Version" /></a>
8    <a href="https://www.npmjs.com/package/@typescript-eslint/typescript-estree"><img src="https://img.shields.io/npm/dm/@typescript-eslint/typescript-estree.svg?style=flat-square" alt="NPM Downloads" /></a>
9</p>
10
11## Getting Started
12
13**[You can find our Getting Started docs here](../../docs/getting-started/linting/README.md)**
14
15## About
16
17This parser is somewhat generic and robust, and could be used to power any use-case which requires taking TypeScript source code and producing an ESTree-compatible AST.
18
19In fact, it is already used within these hyper-popular open-source projects to power their TypeScript support:
20
21- [ESLint](https://eslint.org), the pluggable linting utility for JavaScript and JSX
22- [Prettier](https://prettier.io), an opinionated code formatter
23
24## Installation
25
26```sh
27yarn add -D @typescript-eslint/typescript-estree
28```
29
30## API
31
32### Parsing
33
34#### `parse(code, options)`
35
36Parses the given string of code with the options provided and returns an ESTree-compatible AST.
37
38```ts
39interface ParseOptions {
40  /**
41   * create a top-level comments array containing all comments
42   */
43  comment?: boolean;
44
45  /**
46   * An array of modules to turn explicit debugging on for.
47   * - 'typescript-eslint' is the same as setting the env var `DEBUG=typescript-eslint:*`
48   * - 'eslint' is the same as setting the env var `DEBUG=eslint:*`
49   * - 'typescript' is the same as setting `extendedDiagnostics: true` in your tsconfig compilerOptions
50   *
51   * For convenience, also supports a boolean:
52   * - true === ['typescript-eslint']
53   * - false === []
54   */
55  debugLevel?: boolean | ('typescript-eslint' | 'eslint' | 'typescript')[];
56
57  /**
58   * Cause the parser to error if it encounters an unknown AST node type (useful for testing).
59   * This case only usually occurs when TypeScript releases new features.
60   */
61  errorOnUnknownASTType?: boolean;
62
63  /**
64   * Absolute (or relative to `cwd`) path to the file being parsed.
65   */
66  filePath?: string;
67
68  /**
69   * Enable parsing of JSX.
70   * For more details, see https://www.typescriptlang.org/docs/handbook/jsx.html
71   *
72   * NOTE: this setting does not effect known file types (.js, .jsx, .ts, .tsx, .json) because the
73   * TypeScript compiler has its own internal handling for known file extensions.
74   *
75   * For the exact behavior, see https://github.com/typescript-eslint/typescript-eslint/tree/master/packages/parser#parseroptionsecmafeaturesjsx
76   */
77  jsx?: boolean;
78
79  /**
80   * Controls whether the `loc` information to each node.
81   * The `loc` property is an object which contains the exact line/column the node starts/ends on.
82   * This is similar to the `range` property, except it is line/column relative.
83   */
84  loc?: boolean;
85
86  /*
87   * Allows overriding of function used for logging.
88   * When value is `false`, no logging will occur.
89   * When value is not provided, `console.log()` will be used.
90   */
91  loggerFn?: Function | false;
92
93  /**
94   * Controls whether the `range` property is included on AST nodes.
95   * The `range` property is a [number, number] which indicates the start/end index of the node in the file contents.
96   * This is similar to the `loc` property, except this is the absolute index.
97   */
98  range?: boolean;
99
100  /**
101   * Set to true to create a top-level array containing all tokens from the file.
102   */
103  tokens?: boolean;
104
105  /*
106   * The JSX AST changed the node type for string literals
107   * inside a JSX Element from `Literal` to `JSXText`.
108   * When value is `true`, these nodes will be parsed as type `JSXText`.
109   * When value is `false`, these nodes will be parsed as type `Literal`.
110   */
111  useJSXTextNode?: boolean;
112}
113
114const PARSE_DEFAULT_OPTIONS: ParseOptions = {
115  comment: false,
116  errorOnUnknownASTType: false,
117  filePath: 'estree.ts', // or 'estree.tsx', if you pass jsx: true
118  jsx: false,
119  loc: false,
120  loggerFn: undefined,
121  range: false,
122  tokens: false,
123  useJSXTextNode: false,
124};
125
126declare function parse(
127  code: string,
128  options: ParseOptions = PARSE_DEFAULT_OPTIONS,
129): TSESTree.Program;
130```
131
132Example usage:
133
134```js
135import { parse } from '@typescript-eslint/typescript-estree';
136
137const code = `const hello: string = 'world';`;
138const ast = parse(code, {
139  loc: true,
140  range: true,
141});
142```
143
144#### `parseAndGenerateServices(code, options)`
145
146Parses the given string of code with the options provided and returns an ESTree-compatible AST. Accepts additional options which can be used to generate type information along with the AST.
147
148```ts
149interface ParseAndGenerateServicesOptions extends ParseOptions {
150  /**
151   * Causes the parser to error if the TypeScript compiler returns any unexpected syntax/semantic errors.
152   */
153  errorOnTypeScriptSyntacticAndSemanticIssues?: boolean;
154
155  /**
156   * ***EXPERIMENTAL FLAG*** - Use this at your own risk.
157   *
158   * Causes TS to use the source files for referenced projects instead of the compiled .d.ts files.
159   * This feature is not yet optimized, and is likely to cause OOMs for medium to large projects.
160   *
161   * This flag REQUIRES at least TS v3.9, otherwise it does nothing.
162   *
163   * See: https://github.com/typescript-eslint/typescript-eslint/issues/2094
164   */
165  EXPERIMENTAL_useSourceOfProjectReferenceRedirect?: boolean;
166
167  /**
168   * When `project` is provided, this controls the non-standard file extensions which will be parsed.
169   * It accepts an array of file extensions, each preceded by a `.`.
170   */
171  extraFileExtensions?: string[];
172
173  /**
174   * Absolute (or relative to `tsconfigRootDir`) path to the file being parsed.
175   * When `project` is provided, this is required, as it is used to fetch the file from the TypeScript compiler's cache.
176   */
177  filePath?: string;
178
179  /**
180   * Allows the user to control whether or not two-way AST node maps are preserved
181   * during the AST conversion process.
182   *
183   * By default: the AST node maps are NOT preserved, unless `project` has been specified,
184   * in which case the maps are made available on the returned `parserServices`.
185   *
186   * NOTE: If `preserveNodeMaps` is explicitly set by the user, it will be respected,
187   * regardless of whether or not `project` is in use.
188   */
189  preserveNodeMaps?: boolean;
190
191  /**
192   * Absolute (or relative to `tsconfigRootDir`) paths to the tsconfig(s).
193   * If this is provided, type information will be returned.
194   */
195  project?: string | string[];
196
197  /**
198   * If you provide a glob (or globs) to the project option, you can use this option to ignore certain folders from
199   * being matched by the globs.
200   * This accepts an array of globs to ignore.
201   *
202   * By default, this is set to ["/node_modules/"]
203   */
204  projectFolderIgnoreList?: string[];
205
206  /**
207   * The absolute path to the root directory for all provided `project`s.
208   */
209  tsconfigRootDir?: string;
210
211  /**
212   ***************************************************************************************
213   * IT IS RECOMMENDED THAT YOU DO NOT USE THIS OPTION, AS IT CAUSES PERFORMANCE ISSUES. *
214   ***************************************************************************************
215   *
216   * When passed with `project`, this allows the parser to create a catch-all, default program.
217   * This means that if the parser encounters a file not included in any of the provided `project`s,
218   * it will not error, but will instead parse the file and its dependencies in a new program.
219   */
220  createDefaultProgram?: boolean;
221}
222
223interface ParserServices {
224  program: ts.Program;
225  esTreeNodeToTSNodeMap: WeakMap<TSESTree.Node, ts.Node | ts.Token>;
226  tsNodeToESTreeNodeMap: WeakMap<ts.Node | ts.Token, TSESTree.Node>;
227  hasFullTypeInformation: boolean;
228}
229
230interface ParseAndGenerateServicesResult<T extends TSESTreeOptions> {
231  ast: TSESTree.Program;
232  services: ParserServices;
233}
234
235const PARSE_AND_GENERATE_SERVICES_DEFAULT_OPTIONS: ParseOptions = {
236  ...PARSE_DEFAULT_OPTIONS,
237  errorOnTypeScriptSyntacticAndSemanticIssues: false,
238  extraFileExtensions: [],
239  preserveNodeMaps: false, // or true, if you do not set this, but pass `project`
240  project: undefined,
241  projectFolderIgnoreList: ['/node_modules/'],
242  tsconfigRootDir: process.cwd(),
243};
244
245declare function parseAndGenerateServices(
246  code: string,
247  options: ParseOptions = PARSE_DEFAULT_OPTIONS,
248): ParseAndGenerateServicesResult;
249```
250
251Example usage:
252
253```js
254import { parseAndGenerateServices } from '@typescript-eslint/typescript-estree';
255
256const code = `const hello: string = 'world';`;
257const { ast, services } = parseAndGenerateServices(code, {
258  filePath: '/some/path/to/file/foo.ts',
259  loc: true,
260  project: './tsconfig.json',
261  range: true,
262});
263```
264
265#### `parseWithNodeMaps(code, options)`
266
267Parses the given string of code with the options provided and returns both the ESTree-compatible AST as well as the node maps.
268This allows you to work with both ASTs without the overhead of types that may come with `parseAndGenerateServices`.
269
270```ts
271interface ParseWithNodeMapsResult<T extends TSESTreeOptions> {
272  ast: TSESTree.Program;
273  esTreeNodeToTSNodeMap: ParserServices['esTreeNodeToTSNodeMap'];
274  tsNodeToESTreeNodeMap: ParserServices['tsNodeToESTreeNodeMap'];
275}
276
277declare function parseWithNodeMaps(
278  code: string,
279  options: ParseOptions = PARSE_DEFAULT_OPTIONS,
280): ParseWithNodeMapsResult;
281```
282
283Example usage:
284
285```js
286import { parseWithNodeMaps } from '@typescript-eslint/typescript-estree';
287
288const code = `const hello: string = 'world';`;
289const { ast, esTreeNodeToTSNodeMap, tsNodeToESTreeNodeMap } = parseWithNodeMaps(
290  code,
291  {
292    loc: true,
293    range: true,
294  },
295);
296```
297
298### `TSESTree`, `AST_NODE_TYPES` and `AST_TOKEN_TYPES`
299
300Types for the AST produced by the parse functions.
301
302- `TSESTree` is a namespace which contains object types representing all of the AST Nodes produced by the parser.
303- `AST_NODE_TYPES` is an enum which provides the values for every single AST node's `type` property.
304- `AST_TOKEN_TYPES` is an enum which provides the values for every single AST token's `type` property.
305
306## Supported TypeScript Version
307
308See the [Supported TypeScript Version](../../README.md#supported-typescript-version) section in the project root.
309
310If you use a non-supported version of TypeScript, the parser will log a warning to the console.
311
312**Please ensure that you are using a supported version before submitting any issues/bug reports.**
313
314## Reporting Issues
315
316Please check the current list of open and known issues and ensure the issue has not been reported before. When creating a new issue provide as much information about your environment as possible. This includes:
317
318- TypeScript version
319- The `typescript-estree` version
320
321## AST Alignment Tests
322
323A couple of years after work on this parser began, the TypeScript Team at Microsoft began [officially supporting TypeScript parsing via Babel](https://blogs.msdn.microsoft.com/typescript/2018/08/27/typescript-and-babel-7/).
324
325I work closely with the TypeScript Team and we are gradually aligning the AST of this project with the one produced by Babel's parser. To that end, I have created a full test harness to compare the ASTs of the two projects which runs on every PR, please see [the code](https://github.com/typescript-eslint/typescript-eslint/tree/master/packages/typescript-estree/tests/ast-alignment) for more details.
326
327## Debugging
328
329If you encounter a bug with the parser that you want to investigate, you can turn on the debug logging via setting the environment variable: `DEBUG=typescript-eslint:*`.
330I.e. in this repo you can run: `DEBUG=typescript-eslint:* yarn lint`.
331
332## License
333
334TypeScript ESTree inherits from the the original TypeScript ESLint Parser license, as the majority of the work began there. It is licensed under a permissive BSD 2-clause license.
335
336## Contributing
337
338[See the contributing guide here](../../CONTRIBUTING.md)
339