@@ -1368,17 +1368,19 @@ Local<Object> ContextifyContext::CompileFunctionAndCacheResult(
13681368 return result;
13691369}
13701370
1371- // These are the error messages thrown due to ESM syntax in a CommonJS module.
1371+ // When compiling as CommonJS source code that contains ESM syntax, the
1372+ // following error messages are returned:
1373+ // - `import` statements: "Cannot use import statement outside a module"
1374+ // - `export` statements: "Unexpected token 'export'"
1375+ // - `import.meta` references: "Cannot use 'import.meta' outside a module"
1376+ // Dynamic `import()` is permitted in CommonJS, so it does not error.
1377+ // While top-level `await` is not permitted in CommonJS, it returns the same
1378+ // error message as when `await` is used in a sync function, so we don't use it
1379+ // as a disambiguation.
13721380constexpr std::array<std::string_view, 3 > esm_syntax_error_messages = {
1373- // `import` statements return an error with the message:
1374- " Cannot use import statement outside a module" ,
1375- // `export` statements return an error with the message:
1376- " Unexpected token 'export'" ,
1377- // `import.meta` returns an error with the message:
1378- " Cannot use 'import.meta' outside a module" };
1379- // Top-level `await` currently returns the same error message as when `await` is
1380- // used in a sync function, so we don't use it as a disambiguation. Dynamic
1381- // `import()` is permitted in CommonJS, so we don't use it as a disambiguation.
1381+ " Cannot use import statement outside a module" , // `import` statements
1382+ " Unexpected token 'export'" , // `export` statements
1383+ " Cannot use 'import.meta' outside a module" }; // `import.meta` references
13821384
13831385void ContextifyContext::ContainsModuleSyntax (
13841386 const FunctionCallbackInfo<Value>& args) {
@@ -1387,8 +1389,11 @@ void ContextifyContext::ContainsModuleSyntax(
13871389 Local<String> code = args[0 ].As <String>();
13881390
13891391 // Argument 2: filename
1390- CHECK (args[1 ]->IsString ());
1391- Local<String> filename = args[1 ].As <String>();
1392+ Local<String> filename = String::Empty (args.GetIsolate ());
1393+ if (!args[1 ]->IsUndefined ()) {
1394+ CHECK (args[1 ]->IsString ());
1395+ filename = args[1 ].As <String>();
1396+ }
13921397
13931398 Environment* env = Environment::GetCurrent (args);
13941399 Isolate* isolate = env->isolate ();
0 commit comments