Skip to content

Commit

Permalink
fix(esbuildHelperChecker): catch js parse error (#12285)
Browse files Browse the repository at this point in the history
Co-authored-by: hanzebang.hzb <[email protected]>
  • Loading branch information
hanzebang and hanzebang.hzb authored Apr 18, 2024
1 parent 2c3d95e commit bdcb296
Showing 1 changed file with 30 additions and 16 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ async function checkDir(opts: { dir: string }) {
for (const jsFile of jsFiles) {
const vars = await getGlobalVars({
content: fs.readFileSync(path.join(opts.dir, jsFile), 'utf-8'),
fileName: jsFile,
});
for (const v of vars) {
varMap[v] = varMap[v] || [];
Expand All @@ -40,24 +41,37 @@ async function checkDir(opts: { dir: string }) {
logger.info(`[esbuildHelperChecker] No conflicts found.`);
}

export async function getGlobalVars(opts: { content: string }) {
const ast = parser.parse(opts.content, {
sourceType: 'module',
sourceFilename: 'foo.js',
plugins: [],
});
export async function getGlobalVars(opts: {
content: string;
fileName: string;
}) {
const vars: string[] = [];
ast.program.body.forEach((node) => {
if (t.isVariableDeclaration(node)) {
node.declarations.forEach((declaration) => {
if (t.isVariableDeclarator(declaration)) {
if (t.isIdentifier(declaration.id)) {
vars.push(declaration.id.name);
/**
* 产物目录可能会有用户自定义的非标准 js 文件,会导致 parse 异常,这里转为 error 提示,不中断程序
* eg. git lfs 会生成不符合 js 规范的 js 文件
*/
try {
const ast = parser.parse(opts.content, {
sourceType: 'module',
sourceFilename: 'foo.js',
plugins: [],
});
ast.program.body.forEach((node) => {
if (t.isVariableDeclaration(node)) {
node.declarations.forEach((declaration) => {
if (t.isVariableDeclarator(declaration)) {
if (t.isIdentifier(declaration.id)) {
vars.push(declaration.id.name);
}
}
}
});
}
});
});
}
});
} catch (error: any) {
logger.error(
`[esbuildHelperChecker] Failed to parse ${opts.fileName}, ${error.message}`,
);
}
return vars;
}

Expand Down

0 comments on commit bdcb296

Please sign in to comment.