mirror of
https://github.com/nodejs/node.git
synced 2026-11-24 21:50:36 -05:00
src,lib: retrieve parsed source map url from v8
V8 already parses the source map magic comments. Currently, only scripts and functions expose the parsed source map URLs. It is unnecessary to parse the source map magic comments again when the parsed information is available. PR-URL: https://github.com/nodejs/node/pull/44798 Reviewed-By: Joyee Cheung <joyeec9h3@gmail.com> Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Yagiz Nizipli <yagiz@nizipli.com> Reviewed-By: Jan Krems <jan.krems@gmail.com>
This commit is contained in:
1 parent
3ddb6ccb2a
commit
12779b3e02
10 files changed
+282
-143
No files matched your search
@@ -344,6 +344,41 @@ console.log(globalVar);
|
||||
// 1000
|
||||
```
|
||||
|
||||
### `script.sourceMapURL`
|
||||
|
||||
<!-- YAML
|
||||
added: REPLACEME
|
||||
-->
|
||||
|
||||
* {string|undefined}
|
||||
|
||||
When the script is compiled from a source that contains a source map magic
|
||||
comment, this property will be set to the URL of the source map.
|
||||
|
||||
```mjs
|
||||
import vm from 'node:vm';
|
||||
|
||||
const script = new vm.Script(`
|
||||
function myFunc() {}
|
||||
//# sourceMappingURL=sourcemap.json
|
||||
`);
|
||||
|
||||
console.log(script.sourceMapURL);
|
||||
// Prints: sourcemap.json
|
||||
```
|
||||
|
||||
```cjs
|
||||
const vm = require('node:vm');
|
||||
|
||||
const script = new vm.Script(`
|
||||
function myFunc() {}
|
||||
//# sourceMappingURL=sourcemap.json
|
||||
`);
|
||||
|
||||
console.log(script.sourceMapURL);
|
||||
// Prints: sourcemap.json
|
||||
```
|
||||
|
||||
## Class: `vm.Module`
|
||||
|
||||
<!-- YAML
|
||||
|
||||
@@ -86,7 +86,8 @@ const {
|
||||
filterOwnProperties,
|
||||
setOwnProperty,
|
||||
} = require('internal/util');
|
||||
const vm = require('vm');
|
||||
const { Script } = require('vm');
|
||||
const { internalCompileFunction } = require('internal/vm');
|
||||
const assert = require('internal/assert');
|
||||
const fs = require('fs');
|
||||
const internalFS = require('internal/fs/utils');
|
||||
@@ -1073,19 +1074,28 @@ let hasPausedEntry = false;
|
||||
function wrapSafe(filename, content, cjsModuleInstance) {
|
||||
if (patched) {
|
||||
const wrapper = Module.wrap(content);
|
||||
return vm.runInThisContext(wrapper, {
|
||||
const script = new Script(wrapper, {
|
||||
filename,
|
||||
lineOffset: 0,
|
||||
displayErrors: true,
|
||||
importModuleDynamically: async (specifier, _, importAssertions) => {
|
||||
const loader = asyncESM.esmLoader;
|
||||
return loader.import(specifier, normalizeReferrerURL(filename),
|
||||
importAssertions);
|
||||
},
|
||||
});
|
||||
|
||||
// Cache the source map for the module if present.
|
||||
if (script.sourceMapURL) {
|
||||
maybeCacheSourceMap(filename, content, this, false, undefined, script.sourceMapURL);
|
||||
}
|
||||
|
||||
return script.runInThisContext({
|
||||
displayErrors: true,
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
return vm.compileFunction(content, [
|
||||
const result = internalCompileFunction(content, [
|
||||
'exports',
|
||||
'require',
|
||||
'module',
|
||||
@@ -1099,6 +1109,13 @@ function wrapSafe(filename, content, cjsModuleInstance) {
|
||||
importAssertions);
|
||||
},
|
||||
});
|
||||
|
||||
// Cache the source map for the module if present.
|
||||
if (result.sourceMapURL) {
|
||||
maybeCacheSourceMap(filename, content, this, false, undefined, result.sourceMapURL);
|
||||
}
|
||||
|
||||
return result.function;
|
||||
} catch (err) {
|
||||
if (process.mainModule === cjsModuleInstance)
|
||||
enrichCJSError(err, content);
|
||||
@@ -1119,7 +1136,6 @@ Module.prototype._compile = function(content, filename) {
|
||||
policy.manifest.assertIntegrity(moduleURL, content);
|
||||
}
|
||||
|
||||
maybeCacheSourceMap(filename, content, this);
|
||||
const compiledWrapper = wrapSafe(filename, content, this);
|
||||
|
||||
let inspectorWrapper = null;
|
||||
|
||||
@@ -596,9 +596,11 @@ function initializeESMLoader() {
|
||||
}
|
||||
|
||||
function initializeSourceMapsHandlers() {
|
||||
const { setSourceMapsEnabled } =
|
||||
const { setSourceMapsEnabled, getSourceMapsEnabled } =
|
||||
require('internal/source_map/source_map_cache');
|
||||
process.setSourceMapsEnabled = setSourceMapsEnabled;
|
||||
// Initialize the environment flag of source maps.
|
||||
getSourceMapsEnabled();
|
||||
}
|
||||
|
||||
function initializeFrozenIntrinsics() {
|
||||
|
||||
@@ -97,7 +97,21 @@ function extractSourceURLMagicComment(content) {
|
||||
return sourceURL;
|
||||
}
|
||||
|
||||
function maybeCacheSourceMap(filename, content, cjsModuleInstance, isGeneratedSource, sourceURL) {
|
||||
function extractSourceMapURLMagicComment(content) {
|
||||
let match;
|
||||
let lastMatch;
|
||||
// A while loop is used here to get the last occurrence of sourceMappingURL.
|
||||
// This is needed so that we don't match sourceMappingURL in string literals.
|
||||
while ((match = RegExpPrototypeExec(kSourceMappingURLMagicComment, content))) {
|
||||
lastMatch = match;
|
||||
}
|
||||
if (lastMatch == null) {
|
||||
return null;
|
||||
}
|
||||
return lastMatch.groups.sourceMappingURL;
|
||||
}
|
||||
|
||||
function maybeCacheSourceMap(filename, content, cjsModuleInstance, isGeneratedSource, sourceURL, sourceMapURL) {
|
||||
const sourceMapsEnabled = getSourceMapsEnabled();
|
||||
if (!(process.env.NODE_V8_COVERAGE || sourceMapsEnabled)) return;
|
||||
try {
|
||||
@@ -108,52 +122,52 @@ function maybeCacheSourceMap(filename, content, cjsModuleInstance, isGeneratedSo
|
||||
return;
|
||||
}
|
||||
|
||||
let match;
|
||||
let lastMatch;
|
||||
// A while loop is used here to get the last occurrence of sourceMappingURL.
|
||||
// This is needed so that we don't match sourceMappingURL in string literals.
|
||||
while ((match = RegExpPrototypeExec(kSourceMappingURLMagicComment, content))) {
|
||||
lastMatch = match;
|
||||
if (sourceMapURL === undefined) {
|
||||
sourceMapURL = extractSourceMapURLMagicComment(content);
|
||||
}
|
||||
|
||||
// Bail out when there is no source map url.
|
||||
if (typeof sourceMapURL !== 'string') {
|
||||
return;
|
||||
}
|
||||
|
||||
if (sourceURL === undefined) {
|
||||
sourceURL = extractSourceURLMagicComment(content);
|
||||
}
|
||||
if (lastMatch) {
|
||||
const data = dataFromUrl(filename, lastMatch.groups.sourceMappingURL);
|
||||
const url = data ? null : lastMatch.groups.sourceMappingURL;
|
||||
if (cjsModuleInstance) {
|
||||
cjsSourceMapCache.set(cjsModuleInstance, {
|
||||
filename,
|
||||
lineLengths: lineLengths(content),
|
||||
data,
|
||||
url,
|
||||
sourceURL,
|
||||
});
|
||||
} else if (isGeneratedSource) {
|
||||
const entry = {
|
||||
lineLengths: lineLengths(content),
|
||||
data,
|
||||
url,
|
||||
sourceURL
|
||||
};
|
||||
generatedSourceMapCache.set(filename, entry);
|
||||
if (sourceURL) {
|
||||
generatedSourceMapCache.set(sourceURL, entry);
|
||||
}
|
||||
} else {
|
||||
// If there is no cjsModuleInstance and is not generated source assume we are in a
|
||||
// "modules/esm" context.
|
||||
const entry = {
|
||||
lineLengths: lineLengths(content),
|
||||
data,
|
||||
url,
|
||||
sourceURL,
|
||||
};
|
||||
esmSourceMapCache.set(filename, entry);
|
||||
if (sourceURL) {
|
||||
esmSourceMapCache.set(sourceURL, entry);
|
||||
}
|
||||
|
||||
const data = dataFromUrl(filename, sourceMapURL);
|
||||
const url = data ? null : sourceMapURL;
|
||||
if (cjsModuleInstance) {
|
||||
cjsSourceMapCache.set(cjsModuleInstance, {
|
||||
filename,
|
||||
lineLengths: lineLengths(content),
|
||||
data,
|
||||
url,
|
||||
sourceURL,
|
||||
});
|
||||
} else if (isGeneratedSource) {
|
||||
const entry = {
|
||||
lineLengths: lineLengths(content),
|
||||
data,
|
||||
url,
|
||||
sourceURL
|
||||
};
|
||||
generatedSourceMapCache.set(filename, entry);
|
||||
if (sourceURL) {
|
||||
generatedSourceMapCache.set(sourceURL, entry);
|
||||
}
|
||||
} else {
|
||||
// If there is no cjsModuleInstance and is not generated source assume we are in a
|
||||
// "modules/esm" context.
|
||||
const entry = {
|
||||
lineLengths: lineLengths(content),
|
||||
data,
|
||||
url,
|
||||
sourceURL,
|
||||
};
|
||||
esmSourceMapCache.set(filename, entry);
|
||||
if (sourceURL) {
|
||||
esmSourceMapCache.set(sourceURL, entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
'use strict';
|
||||
|
||||
const {
|
||||
ArrayPrototypeForEach,
|
||||
} = primordials;
|
||||
|
||||
const {
|
||||
compileFunction,
|
||||
isContext: _isContext,
|
||||
} = internalBinding('contextify');
|
||||
const {
|
||||
validateArray,
|
||||
validateBoolean,
|
||||
validateBuffer,
|
||||
validateFunction,
|
||||
validateObject,
|
||||
validateString,
|
||||
validateUint32,
|
||||
} = require('internal/validators');
|
||||
const {
|
||||
ERR_INVALID_ARG_TYPE,
|
||||
} = require('internal/errors').codes;
|
||||
|
||||
function isContext(object) {
|
||||
validateObject(object, 'object', { __proto__: null, allowArray: true });
|
||||
|
||||
return _isContext(object);
|
||||
}
|
||||
|
||||
function internalCompileFunction(code, params, options) {
|
||||
validateString(code, 'code');
|
||||
if (params !== undefined) {
|
||||
validateArray(params, 'params');
|
||||
ArrayPrototypeForEach(params,
|
||||
(param, i) => validateString(param, `params[${i}]`));
|
||||
}
|
||||
|
||||
const {
|
||||
filename = '',
|
||||
columnOffset = 0,
|
||||
lineOffset = 0,
|
||||
cachedData = undefined,
|
||||
produceCachedData = false,
|
||||
parsingContext = undefined,
|
||||
contextExtensions = [],
|
||||
importModuleDynamically,
|
||||
} = options;
|
||||
|
||||
validateString(filename, 'options.filename');
|
||||
validateUint32(columnOffset, 'options.columnOffset');
|
||||
validateUint32(lineOffset, 'options.lineOffset');
|
||||
if (cachedData !== undefined)
|
||||
validateBuffer(cachedData, 'options.cachedData');
|
||||
validateBoolean(produceCachedData, 'options.produceCachedData');
|
||||
if (parsingContext !== undefined) {
|
||||
if (
|
||||
typeof parsingContext !== 'object' ||
|
||||
parsingContext === null ||
|
||||
!isContext(parsingContext)
|
||||
) {
|
||||
throw new ERR_INVALID_ARG_TYPE(
|
||||
'options.parsingContext',
|
||||
'Context',
|
||||
parsingContext
|
||||
);
|
||||
}
|
||||
}
|
||||
validateArray(contextExtensions, 'options.contextExtensions');
|
||||
ArrayPrototypeForEach(contextExtensions, (extension, i) => {
|
||||
const name = `options.contextExtensions[${i}]`;
|
||||
validateObject(extension, name, { __proto__: null, nullable: true });
|
||||
});
|
||||
|
||||
const result = compileFunction(
|
||||
code,
|
||||
filename,
|
||||
lineOffset,
|
||||
columnOffset,
|
||||
cachedData,
|
||||
produceCachedData,
|
||||
parsingContext,
|
||||
contextExtensions,
|
||||
params
|
||||
);
|
||||
|
||||
if (produceCachedData) {
|
||||
result.function.cachedDataProduced = result.cachedDataProduced;
|
||||
}
|
||||
|
||||
if (result.cachedData) {
|
||||
result.function.cachedData = result.cachedData;
|
||||
}
|
||||
|
||||
if (importModuleDynamically !== undefined) {
|
||||
validateFunction(importModuleDynamically,
|
||||
'options.importModuleDynamically');
|
||||
const { importModuleDynamicallyWrap } =
|
||||
require('internal/vm/module');
|
||||
const { callbackMap } = internalBinding('module_wrap');
|
||||
const wrapped = importModuleDynamicallyWrap(importModuleDynamically);
|
||||
const func = result.function;
|
||||
callbackMap.set(result.cacheKey, {
|
||||
importModuleDynamically: (s, _k, i) => wrapped(s, func, i),
|
||||
});
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
internalCompileFunction,
|
||||
isContext,
|
||||
};
|
||||
@@ -32,9 +32,7 @@ const {
|
||||
ContextifyScript,
|
||||
MicrotaskQueue,
|
||||
makeContext,
|
||||
isContext: _isContext,
|
||||
constants,
|
||||
compileFunction: _compileFunction,
|
||||
measureMemory: _measureMemory,
|
||||
} = internalBinding('contextify');
|
||||
const {
|
||||
@@ -45,9 +43,7 @@ const {
|
||||
isArrayBufferView,
|
||||
} = require('internal/util/types');
|
||||
const {
|
||||
validateArray,
|
||||
validateBoolean,
|
||||
validateBuffer,
|
||||
validateFunction,
|
||||
validateInt32,
|
||||
validateObject,
|
||||
@@ -60,6 +56,10 @@ const {
|
||||
kEmptyObject,
|
||||
kVmBreakFirstLineSymbol,
|
||||
} = require('internal/util');
|
||||
const {
|
||||
internalCompileFunction,
|
||||
isContext,
|
||||
} = require('internal/vm');
|
||||
const kParsingContext = Symbol('script parsing context');
|
||||
|
||||
class Script extends ContextifyScript {
|
||||
@@ -213,12 +213,6 @@ function getContextOptions(options) {
|
||||
return contextOptions;
|
||||
}
|
||||
|
||||
function isContext(object) {
|
||||
validateObject(object, 'object', { allowArray: true });
|
||||
|
||||
return _isContext(object);
|
||||
}
|
||||
|
||||
let defaultContextNameIndex = 1;
|
||||
function createContext(contextObject = {}, options = kEmptyObject) {
|
||||
if (isContext(contextObject)) {
|
||||
@@ -314,83 +308,7 @@ function runInThisContext(code, options) {
|
||||
}
|
||||
|
||||
function compileFunction(code, params, options = kEmptyObject) {
|
||||
validateString(code, 'code');
|
||||
if (params !== undefined) {
|
||||
validateArray(params, 'params');
|
||||
ArrayPrototypeForEach(params,
|
||||
(param, i) => validateString(param, `params[${i}]`));
|
||||
}
|
||||
|
||||
const {
|
||||
filename = '',
|
||||
columnOffset = 0,
|
||||
lineOffset = 0,
|
||||
cachedData = undefined,
|
||||
produceCachedData = false,
|
||||
parsingContext = undefined,
|
||||
contextExtensions = [],
|
||||
importModuleDynamically,
|
||||
} = options;
|
||||
|
||||
validateString(filename, 'options.filename');
|
||||
validateUint32(columnOffset, 'options.columnOffset');
|
||||
validateUint32(lineOffset, 'options.lineOffset');
|
||||
if (cachedData !== undefined)
|
||||
validateBuffer(cachedData, 'options.cachedData');
|
||||
validateBoolean(produceCachedData, 'options.produceCachedData');
|
||||
if (parsingContext !== undefined) {
|
||||
if (
|
||||
typeof parsingContext !== 'object' ||
|
||||
parsingContext === null ||
|
||||
!isContext(parsingContext)
|
||||
) {
|
||||
throw new ERR_INVALID_ARG_TYPE(
|
||||
'options.parsingContext',
|
||||
'Context',
|
||||
parsingContext
|
||||
);
|
||||
}
|
||||
}
|
||||
validateArray(contextExtensions, 'options.contextExtensions');
|
||||
ArrayPrototypeForEach(contextExtensions, (extension, i) => {
|
||||
const name = `options.contextExtensions[${i}]`;
|
||||
validateObject(extension, name, { nullable: true });
|
||||
});
|
||||
|
||||
const result = _compileFunction(
|
||||
code,
|
||||
filename,
|
||||
lineOffset,
|
||||
columnOffset,
|
||||
cachedData,
|
||||
produceCachedData,
|
||||
parsingContext,
|
||||
contextExtensions,
|
||||
params
|
||||
);
|
||||
|
||||
if (produceCachedData) {
|
||||
result.function.cachedDataProduced = result.cachedDataProduced;
|
||||
}
|
||||
|
||||
if (result.cachedData) {
|
||||
result.function.cachedData = result.cachedData;
|
||||
}
|
||||
|
||||
if (importModuleDynamically !== undefined) {
|
||||
validateFunction(importModuleDynamically,
|
||||
'options.importModuleDynamically');
|
||||
const { importModuleDynamicallyWrap } =
|
||||
require('internal/vm/module');
|
||||
const { callbackMap } = internalBinding('module_wrap');
|
||||
const wrapped = importModuleDynamicallyWrap(importModuleDynamically);
|
||||
const func = result.function;
|
||||
callbackMap.set(result.cacheKey, {
|
||||
importModuleDynamically: (s, _k, i) => wrapped(s, func, i),
|
||||
});
|
||||
}
|
||||
|
||||
return result.function;
|
||||
return internalCompileFunction(code, params, options).function;
|
||||
}
|
||||
|
||||
const measureMemoryModes = {
|
||||
|
||||
@@ -275,6 +275,7 @@
|
||||
V(sni_context_err_string, "Invalid SNI context") \
|
||||
V(sni_context_string, "sni_context") \
|
||||
V(source_string, "source") \
|
||||
V(source_map_url_string, "sourceMapURL") \
|
||||
V(stack_string, "stack") \
|
||||
V(standard_name_string, "standardName") \
|
||||
V(start_time_string, "startTime") \
|
||||
|
||||
+20
-8
@@ -843,12 +843,11 @@ void ContextifyScript::New(const FunctionCallbackInfo<Value>& args) {
|
||||
ShouldNotAbortOnUncaughtScope no_abort_scope(env);
|
||||
Context::Scope scope(parsing_context);
|
||||
|
||||
MaybeLocal<UnboundScript> v8_script = ScriptCompiler::CompileUnboundScript(
|
||||
isolate,
|
||||
&source,
|
||||
compile_options);
|
||||
MaybeLocal<UnboundScript> maybe_v8_script =
|
||||
ScriptCompiler::CompileUnboundScript(isolate, &source, compile_options);
|
||||
|
||||
if (v8_script.IsEmpty()) {
|
||||
Local<UnboundScript> v8_script;
|
||||
if (!maybe_v8_script.ToLocal(&v8_script)) {
|
||||
errors::DecorateErrorStack(env, try_catch);
|
||||
no_abort_scope.Close();
|
||||
if (!try_catch.HasTerminated())
|
||||
@@ -857,7 +856,7 @@ void ContextifyScript::New(const FunctionCallbackInfo<Value>& args) {
|
||||
"ContextifyScript::New");
|
||||
return;
|
||||
}
|
||||
contextify_script->script_.Reset(isolate, v8_script.ToLocalChecked());
|
||||
contextify_script->script_.Reset(isolate, v8_script);
|
||||
|
||||
Local<Context> env_context = env->context();
|
||||
if (compile_options == ScriptCompiler::kConsumeCodeCache) {
|
||||
@@ -866,8 +865,8 @@ void ContextifyScript::New(const FunctionCallbackInfo<Value>& args) {
|
||||
env->cached_data_rejected_string(),
|
||||
Boolean::New(isolate, source.GetCachedData()->rejected)).Check();
|
||||
} else if (produce_cached_data) {
|
||||
std::unique_ptr<ScriptCompiler::CachedData> cached_data {
|
||||
ScriptCompiler::CreateCodeCache(v8_script.ToLocalChecked()) };
|
||||
std::unique_ptr<ScriptCompiler::CachedData> cached_data{
|
||||
ScriptCompiler::CreateCodeCache(v8_script)};
|
||||
bool cached_data_produced = cached_data != nullptr;
|
||||
if (cached_data_produced) {
|
||||
MaybeLocal<Object> buf = Buffer::Copy(
|
||||
@@ -883,6 +882,13 @@ void ContextifyScript::New(const FunctionCallbackInfo<Value>& args) {
|
||||
env->cached_data_produced_string(),
|
||||
Boolean::New(isolate, cached_data_produced)).Check();
|
||||
}
|
||||
|
||||
args.This()
|
||||
->Set(env_context,
|
||||
env->source_map_url_string(),
|
||||
v8_script->GetSourceMappingURL())
|
||||
.Check();
|
||||
|
||||
TRACE_EVENT_END0(TRACING_CATEGORY_NODE2(vm, script), "ContextifyScript::New");
|
||||
}
|
||||
|
||||
@@ -1230,6 +1236,12 @@ void ContextifyContext::CompileFunction(
|
||||
if (result->Set(parsing_context, env->cache_key_string(), cache_key)
|
||||
.IsNothing())
|
||||
return;
|
||||
if (result
|
||||
->Set(parsing_context,
|
||||
env->source_map_url_string(),
|
||||
fn->GetScriptOrigin().SourceMapUrl())
|
||||
.IsNothing())
|
||||
return;
|
||||
|
||||
if (produce_cached_data) {
|
||||
const std::unique_ptr<ScriptCompiler::CachedData> cached_data(
|
||||
|
||||
@@ -148,6 +148,7 @@ const expectedModules = new Set([
|
||||
'NativeModule internal/util/parse_args/parse_args',
|
||||
'NativeModule internal/util/types',
|
||||
'NativeModule internal/validators',
|
||||
'NativeModule internal/vm',
|
||||
'NativeModule internal/vm/module',
|
||||
'NativeModule internal/wasm_web_api',
|
||||
'NativeModule internal/webstreams/adapters',
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
'use strict';
|
||||
|
||||
require('../common');
|
||||
const assert = require('assert');
|
||||
const vm = require('vm');
|
||||
|
||||
function checkSourceMapUrl(source, expectedSourceMapURL) {
|
||||
const script = new vm.Script(source);
|
||||
assert.strictEqual(script.sourceMapURL, expectedSourceMapURL);
|
||||
}
|
||||
|
||||
// No magic comment
|
||||
checkSourceMapUrl(`
|
||||
function myFunc() {}
|
||||
`, undefined);
|
||||
|
||||
// Malformed magic comment
|
||||
checkSourceMapUrl(`
|
||||
function myFunc() {}
|
||||
// sourceMappingURL=sourcemap.json
|
||||
`, undefined);
|
||||
|
||||
// Expected magic comment
|
||||
checkSourceMapUrl(`
|
||||
function myFunc() {}
|
||||
//# sourceMappingURL=sourcemap.json
|
||||
`, 'sourcemap.json');
|
||||
Reference in new issue
Block a user