|
3 | 3 | const { |
4 | 4 | ArrayPrototypeForEach, |
5 | 5 | ArrayPrototypeJoin, |
6 | | - ArrayPrototypeSome, |
7 | 6 | ObjectDefineProperty, |
| 7 | + ObjectGetPrototypeOf, |
8 | 8 | ObjectPrototypeHasOwnProperty, |
9 | 9 | SafeMap, |
10 | 10 | SafeSet, |
11 | 11 | StringPrototypeCharCodeAt, |
12 | 12 | StringPrototypeIncludes, |
13 | 13 | StringPrototypeSlice, |
14 | 14 | StringPrototypeStartsWith, |
| 15 | + SyntaxErrorPrototype, |
15 | 16 | } = primordials; |
16 | 17 | const { |
17 | 18 | ERR_INVALID_ARG_TYPE, |
@@ -300,31 +301,28 @@ function normalizeReferrerURL(referrer) { |
300 | 301 | } |
301 | 302 |
|
302 | 303 | /** |
303 | | - * For error messages only, check if ESM syntax is in use. |
304 | | - * @param {string} code |
| 304 | + * Check if the error is a syntax error due to ESM syntax in CommonJS. |
| 305 | + * - `import` statements return an error with a message `Cannot use import statement outside a module`. |
| 306 | + * - `export` statements return an error with a message `Unexpected token 'export'`. |
| 307 | + * - `import.meta` returns an error with a message `Cannot use 'import.meta' outside a module`. |
| 308 | + * Top-level `await` currently returns the same error message as when `await` is used in a sync function, |
| 309 | + * so we don't use it as a disambiguation. |
| 310 | + * Dynamic `import()` is permitted in CommonJS, so we don't use it as a disambiguation. |
| 311 | + * @param {Error} err |
305 | 312 | */ |
306 | | -function hasEsmSyntax(code) { |
307 | | - debug('Checking for ESM syntax'); |
308 | | - const parser = require('internal/deps/acorn/acorn/dist/acorn').Parser; |
309 | | - let root; |
310 | | - try { |
311 | | - root = parser.parse(code, { sourceType: 'module', ecmaVersion: 'latest' }); |
312 | | - } catch { |
313 | | - return false; |
314 | | - } |
315 | | - |
316 | | - return ArrayPrototypeSome(root.body, (stmt) => |
317 | | - stmt.type === 'ExportDefaultDeclaration' || |
318 | | - stmt.type === 'ExportNamedDeclaration' || |
319 | | - stmt.type === 'ImportDeclaration' || |
320 | | - stmt.type === 'ExportAllDeclaration'); |
| 313 | +function isModuleSyntaxError(err) { |
| 314 | + return err != null && ObjectGetPrototypeOf(err) === SyntaxErrorPrototype && ( |
| 315 | + err.message === 'Cannot use import statement outside a module' || |
| 316 | + err.message === "Unexpected token 'export'" || |
| 317 | + err.message === "Cannot use 'import.meta' outside a module" |
| 318 | + ); |
321 | 319 | } |
322 | 320 |
|
323 | 321 | module.exports = { |
324 | 322 | addBuiltinLibsToObject, |
325 | 323 | getCjsConditions, |
326 | 324 | initializeCjsConditions, |
327 | | - hasEsmSyntax, |
| 325 | + isModuleSyntaxError, |
328 | 326 | loadBuiltinModule, |
329 | 327 | makeRequireFunction, |
330 | 328 | normalizeReferrerURL, |
|
0 commit comments