/
js-parser.ts
53 lines (49 loc) · 1.39 KB
/
js-parser.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import { ParserPlugin } from '@babel/parser';
import { parseAsync, types } from '@babel/core';
import { AstFormat, JSAst } from '../syntax';
import { ParserOptions } from './parser-options';
const defaultPlugins: ParserPlugin[] = [
'doExpressions',
'objectRestSpread',
'classProperties',
'exportDefaultFrom',
'exportNamespaceFrom',
'asyncGenerators',
'functionBind',
'functionSent',
'dynamicImport',
'numericSeparator',
'importMeta',
'optionalCatchBinding',
'optionalChaining',
'classPrivateProperties',
['pipelineOperator', { proposal: 'minimal' }],
'nullishCoalescingOperator',
'bigInt',
'throwExpressions',
'logicalAssignment',
'classPrivateMethods',
'v8intrinsic',
'partialApplication',
['decorators', { decoratorsBeforeExport: false }],
];
export function createParser({ plugins: pluginsOverride }: ParserOptions) {
return async function parse(text: string, fileName: string): Promise<JSAst> {
const ast = await parseAsync(text, {
parserOpts: {
plugins: [...(pluginsOverride ?? defaultPlugins)] as ParserPlugin[],
},
filename: fileName,
sourceType: 'module',
});
if (types.isProgram(ast)) {
throw new Error(`Expected ${fileName} to contain a babel.types.file, but was a program`);
}
return {
originFileName: fileName,
rawContent: text,
format: AstFormat.JS,
root: ast!,
};
};
}