Skip to content

Commit fb42a72

Browse files
authored
fix: register regex backtracking (#396)
1 parent dfce0ab commit fb42a72

File tree

2 files changed

+18
-9
lines changed

2 files changed

+18
-9
lines changed

src/trace/analysis.ts

+17-8
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
import { JspmError } from "../common/err.js";
22
import { getIntegrity } from "../common/integrity.js";
33

4-
export type Analysis = AnalysisData | {
5-
parseError: JspmError | Error
6-
};
4+
export type Analysis =
5+
| AnalysisData
6+
| {
7+
parseError: JspmError | Error;
8+
};
79

810
export interface AnalysisData {
911
deps: string[];
@@ -31,8 +33,9 @@ export async function createEsmAnalysis(
3133
imports: any[],
3234
source: string,
3335
url: string
34-
): Promise<Analysis> { // Change the return type to Promise<Analysis>
35-
if (!imports.length && registerRegEx.test(source))
36+
): Promise<Analysis> {
37+
// Change the return type to Promise<Analysis>
38+
if (!imports.length && systemMatch(source))
3639
return createSystemAnalysis(source, imports, url);
3740
const deps: string[] = [];
3841
const dynamicDeps: string[] = [];
@@ -67,15 +70,21 @@ export async function createEsmAnalysis(
6770
integrity: await getIntegrity(source),
6871
};
6972
}
73+
const leadingCommentRegex = /^\s*(\/\*[\s\S]*?\*\/|\s*\/\/[^\n]*)*/;
74+
const registerRegex = /^\s*System\s*\.\s*register\s*\(\s*(\[[^\]]*\])\s*,\s*\(?function\s*\(\s*([^\),\s]+\s*(,\s*([^\),\s]+)\s*)?\s*)?\)/;
75+
76+
function systemMatch(code) {
77+
const commentMatch = code.match(leadingCommentRegex);
78+
const offset = commentMatch ? commentMatch[0].length : 0;
79+
return code.slice(offset).match(registerRegex);
80+
}
7081

71-
const registerRegEx =
72-
/^\s*(\/\*[^\*]*(\*(?!\/)[^\*]*)*\*\/|\s*\/\/[^\n]*)*\s*System\s*\.\s*register\s*\(\s*(\[[^\]]*\])\s*,\s*\(?function\s*\(\s*([^\),\s]+\s*(,\s*([^\),\s]+)\s*)?\s*)?\)/;
7382
export async function createSystemAnalysis(
7483
source: string,
7584
imports: string[],
7685
url: string
7786
): Promise<Analysis> {
78-
const [, , , rawDeps, , , contextId] = source.match(registerRegEx) || [];
87+
const [, rawDeps, contextId] = systemMatch(source) || [];
7988
if (!rawDeps) return createEsmAnalysis(imports, source, url);
8089
const deps = JSON.parse(rawDeps.replace(/'/g, '"'));
8190
const dynamicDeps: string[] = [];

test/resolve/unused-cjs.test.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ await (async () => {
2020
await generator.install({ target: './cjspkg', subpath: './browser.js' });
2121
assert.deepStrictEqual(generator.getMap(), {
2222
imports: {
23-
'./cjspkg/browser-dep-exclude.js': 'https://ga.jspm.io/npm:@jspm/core@2.0.1/nodelibs/@empty.js',
23+
'./cjspkg/browser-dep-exclude.js': 'https://ga.jspm.io/npm:@jspm/core@2.1.0/nodelibs/@empty.js',
2424
'cjspkg/browser.js': './cjspkg/browser.js',
2525
unusedcjspkg: './unusedcjspkg/index.js'
2626
},

0 commit comments

Comments
 (0)