Skip to content

Commit cb86df8

Browse files
committed
Replace old helper with new
1 parent a8dfd58 commit cb86df8

File tree

5 files changed

+76
-83
lines changed

5 files changed

+76
-83
lines changed

lib/internal/modules/cjs/loader.js

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,7 @@ const {
9090
makeContextifyScript,
9191
runScriptInThisContext,
9292
} = require('internal/vm');
93+
const { containsModuleSyntax } = internalBinding('contextify');
9394

9495
const assert = require('internal/assert');
9596
const fs = require('fs');
@@ -104,7 +105,6 @@ const {
104105
const {
105106
getCjsConditions,
106107
initializeCjsConditions,
107-
hasEsmSyntax,
108108
loadBuiltinModule,
109109
makeRequireFunction,
110110
normalizeReferrerURL,
@@ -1315,7 +1315,7 @@ function wrapSafe(filename, content, cjsModuleInstance, codeCache) {
13151315
} catch (err) {
13161316
if (process.mainModule === cjsModuleInstance) {
13171317
const { enrichCJSError } = require('internal/modules/esm/translators');
1318-
enrichCJSError(err, content);
1318+
enrichCJSError(err, content, filename);
13191319
}
13201320
throw err;
13211321
}
@@ -1400,10 +1400,11 @@ Module._extensions['.js'] = function(module, filename) {
14001400
const pkg = packageJsonReader.readPackageScope(filename) || { __proto__: null };
14011401
// Function require shouldn't be used in ES modules.
14021402
if (pkg.data?.type === 'module') {
1403+
// This is an error path, because `require` of a `.js` file in a `"type": "module"` scope is not allowed.
14031404
const parent = moduleParentCache.get(module);
14041405
const parentPath = parent?.filename;
14051406
const packageJsonPath = path.resolve(pkg.path, 'package.json');
1406-
const usesEsm = hasEsmSyntax(content);
1407+
const usesEsm = containsModuleSyntax(content, filename);
14071408
const err = new ERR_REQUIRE_ESM(filename, usesEsm, parentPath,
14081409
packageJsonPath);
14091410
// Attempt to reconstruct the parent require frame.

lib/internal/modules/esm/translators.js

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -30,11 +30,11 @@ function lazyTypes() {
3030
return _TYPES = require('internal/util/types');
3131
}
3232

33+
const { containsModuleSyntax } = internalBinding('contextify');
3334
const assert = require('internal/assert');
3435
const { readFileSync } = require('fs');
3536
const { dirname, extname, isAbsolute } = require('path');
3637
const {
37-
hasEsmSyntax,
3838
loadBuiltinModule,
3939
stripBOM,
4040
} = require('internal/modules/helpers');
@@ -166,11 +166,11 @@ translators.set('module', async function moduleStrategy(url, source, isMain) {
166166
* Provide a more informative error for CommonJS imports.
167167
* @param {Error | any} err
168168
* @param {string} [content] Content of the file, if known.
169-
* @param {string} [filename] Useful only if `content` is unknown.
169+
* @param {string} [filename] The filename of the erroring module.
170170
*/
171171
function enrichCJSError(err, content, filename) {
172172
if (err != null && ObjectGetPrototypeOf(err) === SyntaxErrorPrototype &&
173-
hasEsmSyntax(content || readFileSync(filename, 'utf-8'))) {
173+
containsModuleSyntax(content, filename ?? '')) {
174174
// Emit the warning synchronously because we are in the middle of handling
175175
// a SyntaxError that will throw and likely terminate the process before an
176176
// asynchronous warning would be emitted.
@@ -217,7 +217,7 @@ function loadCJSModule(module, source, url, filename) {
217217
importModuleDynamically, // importModuleDynamically
218218
).function;
219219
} catch (err) {
220-
enrichCJSError(err, source, url);
220+
enrichCJSError(err, source, filename);
221221
throw err;
222222
}
223223

@@ -344,7 +344,7 @@ translators.set('commonjs', async function commonjsStrategy(url, source,
344344
assert(module === CJSModule._cache[filename]);
345345
CJSModule._load(filename);
346346
} catch (err) {
347-
enrichCJSError(err, source, url);
347+
enrichCJSError(err, source, filename);
348348
throw err;
349349
}
350350
} : loadCJSModule;

lib/internal/modules/helpers.js

Lines changed: 0 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
const {
44
ArrayPrototypeForEach,
55
ArrayPrototypeJoin,
6-
ArrayPrototypeSome,
76
ObjectDefineProperty,
87
ObjectPrototypeHasOwnProperty,
98
SafeMap,
@@ -299,32 +298,10 @@ function normalizeReferrerURL(referrer) {
299298
return new URL(referrer).href;
300299
}
301300

302-
/**
303-
* For error messages only, check if ESM syntax is in use.
304-
* @param {string} code
305-
*/
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');
321-
}
322-
323301
module.exports = {
324302
addBuiltinLibsToObject,
325303
getCjsConditions,
326304
initializeCjsConditions,
327-
hasEsmSyntax,
328305
loadBuiltinModule,
329306
makeRequireFunction,
330307
normalizeReferrerURL,

src/node_contextify.cc

Lines changed: 55 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -1206,32 +1206,17 @@ void ContextifyContext::CompileFunction(
12061206
data + cached_data_buf->ByteOffset(), cached_data_buf->ByteLength());
12071207
}
12081208

1209-
// Set host_defined_options
12101209
Local<PrimitiveArray> host_defined_options =
1211-
PrimitiveArray::New(isolate, loader::HostDefinedOptions::kLength);
1212-
host_defined_options->Set(
1213-
isolate, loader::HostDefinedOptions::kID, id_symbol);
1214-
1215-
ScriptOrigin origin(isolate,
1216-
filename,
1217-
line_offset, // line offset
1218-
column_offset, // column offset
1219-
true, // is cross origin
1220-
-1, // script id
1221-
Local<Value>(), // source map URL
1222-
false, // is opaque (?)
1223-
false, // is WASM
1224-
false, // is ES Module
1225-
host_defined_options);
1226-
1210+
GetHostDefinedOptions(isolate, id_symbol);
12271211
ScriptCompiler::Source source =
1228-
ScriptCompiler::Source(code, origin, cached_data);
1229-
ScriptCompiler::CompileOptions options;
1230-
if (source.GetCachedData() == nullptr) {
1231-
options = ScriptCompiler::kNoCompileOptions;
1232-
} else {
1233-
options = ScriptCompiler::kConsumeCodeCache;
1234-
}
1212+
GetCommonJSSourceInstance(isolate,
1213+
code,
1214+
filename,
1215+
line_offset,
1216+
column_offset,
1217+
host_defined_options,
1218+
cached_data);
1219+
ScriptCompiler::CompileOptions options = GetCompileOptions(source);
12351220

12361221
Context::Scope scope(parsing_context);
12371222

@@ -1279,6 +1264,48 @@ void ContextifyContext::CompileFunction(
12791264
args.GetReturnValue().Set(result);
12801265
}
12811266

1267+
Local<PrimitiveArray> ContextifyContext::GetHostDefinedOptions(
1268+
Isolate* isolate, Local<Symbol> id_symbol) {
1269+
Local<PrimitiveArray> host_defined_options =
1270+
PrimitiveArray::New(isolate, loader::HostDefinedOptions::kLength);
1271+
host_defined_options->Set(
1272+
isolate, loader::HostDefinedOptions::kID, id_symbol);
1273+
return host_defined_options;
1274+
}
1275+
1276+
ScriptCompiler::Source ContextifyContext::GetCommonJSSourceInstance(
1277+
Isolate* isolate,
1278+
Local<String> code,
1279+
Local<String> filename,
1280+
int line_offset,
1281+
int column_offset,
1282+
Local<PrimitiveArray> host_defined_options,
1283+
ScriptCompiler::CachedData* cached_data) {
1284+
ScriptOrigin origin(isolate,
1285+
filename,
1286+
line_offset, // line offset
1287+
column_offset, // column offset
1288+
true, // is cross origin
1289+
-1, // script id
1290+
Local<Value>(), // source map URL
1291+
false, // is opaque (?)
1292+
false, // is WASM
1293+
false, // is ES Module
1294+
host_defined_options);
1295+
return ScriptCompiler::Source(code, origin, cached_data);
1296+
}
1297+
1298+
ScriptCompiler::CompileOptions ContextifyContext::GetCompileOptions(
1299+
const ScriptCompiler::Source& source) {
1300+
ScriptCompiler::CompileOptions options;
1301+
if (source.GetCachedData() != nullptr) {
1302+
options = ScriptCompiler::kConsumeCodeCache;
1303+
} else {
1304+
options = ScriptCompiler::kNoCompileOptions;
1305+
}
1306+
return options;
1307+
}
1308+
12821309
Local<Object> ContextifyContext::CompileFunctionAndCacheResult(
12831310
Environment* env,
12841311
Local<Context> parsing_context,
@@ -1375,35 +1402,11 @@ void ContextifyContext::ContainsModuleSyntax(
13751402
filename))
13761403
.As<Symbol>();
13771404

1378-
// TODO: Abstract this into a separate function
1379-
// Set host_defined_options
13801405
Local<PrimitiveArray> host_defined_options =
1381-
PrimitiveArray::New(isolate, loader::HostDefinedOptions::kLength);
1382-
host_defined_options->Set(
1383-
isolate, loader::HostDefinedOptions::kID, id_symbol);
1384-
1385-
ScriptOrigin origin(isolate,
1386-
filename,
1387-
0, // line offset
1388-
0, // column offset
1389-
true, // is cross origin
1390-
-1, // script id
1391-
Local<Value>(), // source map URL
1392-
false, // is opaque (?)
1393-
false, // is WASM
1394-
false, // is ES Module
1395-
host_defined_options);
1396-
1397-
ScriptCompiler::CachedData* cached_data = nullptr;
1398-
ScriptCompiler::Source source =
1399-
ScriptCompiler::Source(code, origin, cached_data);
1400-
ScriptCompiler::CompileOptions options;
1401-
if (source.GetCachedData() == nullptr) {
1402-
options = ScriptCompiler::kNoCompileOptions;
1403-
} else {
1404-
options = ScriptCompiler::kConsumeCodeCache;
1405-
}
1406-
// End TODO
1406+
GetHostDefinedOptions(isolate, id_symbol);
1407+
ScriptCompiler::Source source = GetCommonJSSourceInstance(
1408+
isolate, code, filename, 0, 0, host_defined_options, nullptr);
1409+
ScriptCompiler::CompileOptions options = GetCompileOptions(source);
14071410

14081411
std::vector<Local<String>> params = {
14091412
String::NewFromUtf8(isolate, "exports").ToLocalChecked(),

src/node_contextify.h

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,18 @@ class ContextifyContext : public BaseObject {
9393
bool produce_cached_data,
9494
v8::Local<v8::Symbol> id_symbol,
9595
const errors::TryCatchScope& try_catch);
96+
static v8::Local<v8::PrimitiveArray> GetHostDefinedOptions(
97+
v8::Isolate* isolate, v8::Local<v8::Symbol> id_symbol);
98+
static v8::ScriptCompiler::Source GetCommonJSSourceInstance(
99+
v8::Isolate* isolate,
100+
v8::Local<v8::String> code,
101+
v8::Local<v8::String> filename,
102+
int line_offset,
103+
int column_offset,
104+
v8::Local<v8::PrimitiveArray> host_defined_options,
105+
v8::ScriptCompiler::CachedData* cached_data);
106+
static v8::ScriptCompiler::CompileOptions GetCompileOptions(
107+
const v8::ScriptCompiler::Source& source);
96108
static void ContainsModuleSyntax(
97109
const v8::FunctionCallbackInfo<v8::Value>& args);
98110
static void WeakCallback(

0 commit comments

Comments
 (0)