shim: simplify importParser regexp and fix line number detection
MODIFY
src/sourceParser.js
src/sourceParser.js
// something like that from something like importnotreally('power.js') which
// is perfectly safe.
-const importParser = /^(.*)\bimport\s*(\(|\/\/|\/\*)/m;
+const importParser = /\bimport\s*(?:\(|\/[/*])/;
export function rejectImportExpressions(s) {
- const matches = importParser.exec(s);
- if (matches) {
+ const index = s.search(importParser);
+ if (index !== -1) {
// todo: if we have a full parser available, use it here. If there is no
// 'import' token in the string, we're safe.
- // if (!parse(s).contains('import')) return;
- const linenum = matches[1].split('\n').length; // more or less
+ // if (!parse(s).includes('import')) return;
+ const linenum = s.slice(0, index).split('\n').length; // more or less
throw new SyntaxError(`possible import expression rejected around line ${linenum}`);
}
}

MODIFY
test/realm/test-import-expression.js
test/realm/test-import-expression.js
@@ -58,6 +58,10 @@ const doubleslashcomment = `const a = import // hah
const newline = `const a = import
('evil')`;
+const multiline = `
+import('a')
+import('b')`;
+
test('no-import-expression regexp', t => {
// note: we cannot define these as regular functions (and then stringify)
// because the 'esm' module loader that we use for running the tests (i.e.
@@ -72,6 +76,11 @@ test('no-import-expression regexp', t => {
t.throws(() => rejectImportExpressions(comment), SyntaxError, 'comment');
t.throws(() => rejectImportExpressions(doubleslashcomment), SyntaxError, 'doubleslashcomment');
t.throws(() => rejectImportExpressions(newline), SyntaxError, 'newline');
+ t.throws(
+ () => rejectImportExpressions(multiline),
+ /SyntaxError: possible import expression rejected around line 2/,
+ 'multiline'
+ );
// mentioning import() in a comment *should* be safe, but requires a full
// parser to check, and a cheap regexp test will conservatively reject it.

shim: simplify importParser regexp and fix line number detection