@@ -19,6 +19,15 @@ const {
1919} = require ( 'internal/errors' ) . codes ;
2020const { BuiltinModule } = require ( 'internal/bootstrap/realm' ) ;
2121
22+ const {
23+ shouldRetryAsESM : contextifyShouldRetryAsESM ,
24+ constants : {
25+ syntaxDetectionErrors : {
26+ esmSyntaxErrorMessages,
27+ throwsOnlyInCommonJSErrorMessages,
28+ } ,
29+ } ,
30+ } = internalBinding ( 'contextify' ) ;
2231const { validateString } = require ( 'internal/validators' ) ;
2332const fs = require ( 'fs' ) ; // Import all of `fs` so that it can be monkey-patched.
2433const internalFS = require ( 'internal/fs/utils' ) ;
@@ -320,31 +329,22 @@ function normalizeReferrerURL(referrerName) {
320329}
321330
322331
323- const esmSyntaxErrorMessages = new SafeSet ( [
324- 'Cannot use import statement outside a module' , // `import` statements
325- "Unexpected token 'export'" , // `export` statements
326- "Cannot use 'import.meta' outside a module" , // `import.meta` references
327- ] ) ;
328- const throwsOnlyInCommonJSErrorMessages = new SafeSet ( [
329- "Identifier 'module' has already been declared" ,
330- "Identifier 'exports' has already been declared" ,
331- "Identifier 'require' has already been declared" ,
332- "Identifier '__filename' has already been declared" ,
333- "Identifier '__dirname' has already been declared" ,
334- 'await is only valid in async functions and the top level bodies of modules' , // Top-level `await`
335- ] ) ;
332+ let esmSyntaxErrorMessagesSet ; // Declared lazily in shouldRetryAsESM
333+ let throwsOnlyInCommonJSErrorMessagesSet ; // Declared lazily in shouldRetryAsESM
336334/**
337335 * After an attempt to parse a module as CommonJS throws an error, should we try again as ESM?
338336 * @param {string } errorMessage The string message thrown by V8 when attempting to parse as CommonJS
339337 * @param {string } source Module contents
340338 */
341339function shouldRetryAsESM ( errorMessage , source ) {
342- if ( esmSyntaxErrorMessages . has ( errorMessage ) ) {
340+ esmSyntaxErrorMessagesSet ??= new SafeSet ( esmSyntaxErrorMessages ) ;
341+ if ( esmSyntaxErrorMessagesSet . has ( errorMessage ) ) {
343342 return true ;
344343 }
345344
346- if ( throwsOnlyInCommonJSErrorMessages . has ( errorMessage ) ) {
347- return /** @type {boolean } */ ( internalBinding ( 'contextify' ) . shouldRetryAsESM ( source ) ) ;
345+ throwsOnlyInCommonJSErrorMessagesSet ??= new SafeSet ( throwsOnlyInCommonJSErrorMessages ) ;
346+ if ( throwsOnlyInCommonJSErrorMessagesSet . has ( errorMessage ) ) {
347+ return /** @type {boolean } */ ( contextifyShouldRetryAsESM ( source ) ) ;
348348 }
349349
350350 return false ;
0 commit comments