Skip to content

Commit 01fb148

Browse files
Retry parsing without "jsx" plugin if required
1 parent 044551d commit 01fb148

File tree

2 files changed

+50
-11
lines changed

2 files changed

+50
-11
lines changed

index.js

Lines changed: 49 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,24 @@ const babelParserOptions = {
8585
],
8686
};
8787

88+
const babelSafeParserOptions = {
89+
sourceType: "module",
90+
allowImportExportEverywhere: true,
91+
allowAwaitOutsideFunction: true,
92+
allowReturnOutsideFunction: true,
93+
errorRecovery: true,
94+
plugins: [
95+
"optionalChaining",
96+
"classProperties",
97+
"decorators-legacy",
98+
"exportDefaultFrom",
99+
"doExpressions",
100+
"numericSeparator",
101+
"dynamicImport",
102+
"typescript",
103+
],
104+
};
105+
88106
/**
89107
* Return paths to all (j|tsx?) files.
90108
*/
@@ -101,11 +119,35 @@ const getAllSrcJSAndTSFiles = (src) =>
101119
/**
102120
* Convert a single JS/TS file to AST
103121
*/
104-
const toJSAst = (file) => {
105-
return babelParser.parse(
106-
fs.readFileSync(file, "utf-8"),
107-
babelParserOptions
108-
);
122+
const fileToJsAst = (file) => {
123+
try {
124+
return babelParser.parse(
125+
fs.readFileSync(file, "utf-8"),
126+
babelParserOptions
127+
);
128+
} catch {
129+
return babelParser.parse(
130+
fs.readFileSync(file, "utf-8"),
131+
babelSafeParserOptions
132+
);
133+
}
134+
};
135+
136+
/**
137+
* Convert a single JS/TS code snippet to AST
138+
*/
139+
const codeToJsAst = (code) => {
140+
try {
141+
return babelParser.parse(
142+
code,
143+
babelParserOptions
144+
);
145+
} catch {
146+
return babelParser.parse(
147+
code,
148+
babelSafeParserOptions
149+
);
150+
}
109151
};
110152

111153
const vueCleaningRegex = /<\/*script.*>|<style[\s\S]*style>|<\/*br>/ig;
@@ -141,10 +183,7 @@ const toVueAst = (file) => {
141183
.replaceAll("}}", " }") +
142184
grC
143185
});
144-
return babelParser.parse(
145-
cleanedCode,
146-
babelParserOptions
147-
);
186+
return codeToJsAst(cleanedCode);
148187
};
149188

150189
function createTsc(srcFiles) {
@@ -229,7 +268,7 @@ const createJSAst = async (options) => {
229268

230269
for (const file of srcFiles) {
231270
try {
232-
const ast = toJSAst(file);
271+
const ast = fileToJsAst(file);
233272
writeAstFile(file, ast, options);
234273
} catch (err) {
235274
console.error(file, err.message);

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@joernio/astgen",
3-
"version": "2.22.0",
3+
"version": "2.23.0",
44
"description": "Generate JS/TS AST in json format with Babel",
55
"exports": "./index.js",
66
"keywords": [

0 commit comments

Comments
 (0)