Commit 4b26c7208df for nodejs
commit 4b26c7208df2b009ca9d8c7060d5620d7c868660
Author: YT <wing0920@gmail.com>
Date: Mon Nov 30 01:56:26 2026 +0900
vm: allow createCachedData() in any module status
sourceTextModule.createCachedData() threw
ERR_VM_MODULE_CANNOT_CREATE_CACHED_DATA after the module started
evaluation. V8 removed this restriction in 2020, and it handles
every module status when it creates a code cache. A code cache
that is created after evaluation can also contain the functions
that V8 compiled lazily during the evaluation, so a new module
that uses this code cache can compile less.
Allow the call in any module status, and remove
ERR_VM_MODULE_CANNOT_CREATE_CACHED_DATA, which is no longer
thrown. Throw ERR_INVALID_THIS if the receiver is not a
SourceTextModule. A SyntheticModule receiver could reach a CHECK
in ModuleWrap::CreateCachedData() and abort the process.
Assisted-by: claude:opus-5.5
Signed-off-by: Yusuke "YT" Tanaka <ytanaka@cloudflare.com>
PR-URL: https://github.com/nodejs/node/pull/67508
Refs: https://chromium-review.googlesource.com/c/v8/v8/+/2504256
Refs: https://chromium-review.googlesource.com/c/v8/v8/+/8811778
Reviewed-By: James M Snell <jasnell@gmail.com>
diff --git a/doc/api/errors.md b/doc/api/errors.md
index 6948ada70cf..05203e3cd66 100644
--- a/doc/api/errors.md
+++ b/doc/api/errors.md
@@ -3644,12 +3644,6 @@ the following reasons:
The `cachedData` option passed to a module constructor is invalid.
-<a id="ERR_VM_MODULE_CANNOT_CREATE_CACHED_DATA"></a>
-
-### `ERR_VM_MODULE_CANNOT_CREATE_CACHED_DATA`
-
-Cached data cannot be created for modules which have already been evaluated.
-
<a id="ERR_VM_MODULE_DIFFERENT_CONTEXT"></a>
### `ERR_VM_MODULE_DIFFERENT_CONTEXT`
@@ -4553,6 +4547,16 @@ removed: v10.0.0
Used when a given value is out of the accepted range.
+<a id="ERR_VM_MODULE_CANNOT_CREATE_CACHED_DATA"></a>
+
+### `ERR_VM_MODULE_CANNOT_CREATE_CACHED_DATA`
+
+<!-- YAML
+removed: REPLACEME
+-->
+
+Cached data cannot be created for modules which have already been evaluated.
+
<a id="ERR_VM_MODULE_LINKING_ERRORED"></a>
### `ERR_VM_MODULE_LINKING_ERRORED`
diff --git a/doc/api/vm.md b/doc/api/vm.md
index 14cd1f269b1..330fab02283 100644
--- a/doc/api/vm.md
+++ b/doc/api/vm.md
@@ -976,13 +976,17 @@ const contextifiedObject = vm.createContext({ secret: 42 });
added:
- v13.7.0
- v12.17.0
+changes:
+ - version: REPLACEME
+ pr-url: https://github.com/nodejs/node/pull/67508
+ description: This method can be called at any time.
-->
* Returns: {Buffer}
Creates a code cache that can be used with the `SourceTextModule` constructor's
-`cachedData` option. Returns a `Buffer`. This method may be called any number
-of times before the module has been evaluated.
+`cachedData` option. Returns a `Buffer`. This method may be called at any
+time and any number of times.
The code cache of the `SourceTextModule` doesn't contain any JavaScript
observable states. The code cache is safe to be saved along side the script
@@ -992,7 +996,10 @@ Functions in the `SourceTextModule` source can be marked as lazily compiled
and they are not compiled at construction of the `SourceTextModule`. These
functions are going to be compiled when they are invoked the first time. The
code cache serializes the metadata that V8 currently knows about the
-`SourceTextModule` that it can use to speed up future compilations.
+`SourceTextModule` that it can use to speed up future compilations. If you
+create the code cache after the module has been evaluated, the code cache can
+also contain the functions that were compiled while the module ran, or when
+they were called later.
```js
// Create an initial module
diff --git a/lib/internal/errors.js b/lib/internal/errors.js
index 000a36c4489..83731d42d12 100644
--- a/lib/internal/errors.js
+++ b/lib/internal/errors.js
@@ -2035,8 +2035,6 @@ E('ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING_FLAG',
'A dynamic import callback was invoked without --experimental-vm-modules',
TypeError);
E('ERR_VM_MODULE_ALREADY_LINKED', 'Module has already been linked', Error);
-E('ERR_VM_MODULE_CANNOT_CREATE_CACHED_DATA',
- 'Cached data cannot be created for a module which has been evaluated', Error);
E('ERR_VM_MODULE_DIFFERENT_CONTEXT',
'Linked modules must use the same context', Error);
E('ERR_VM_MODULE_LINK_FAILURE', function(message, cause) {
diff --git a/lib/internal/vm/module.js b/lib/internal/vm/module.js
index ce2350f6cd1..cbe4638f0d1 100644
--- a/lib/internal/vm/module.js
+++ b/lib/internal/vm/module.js
@@ -35,9 +35,9 @@ const {
const {
ERR_INVALID_ARG_TYPE,
ERR_INVALID_ARG_VALUE,
+ ERR_INVALID_THIS,
ERR_VM_MODULE_ALREADY_LINKED,
ERR_VM_MODULE_DIFFERENT_CONTEXT,
- ERR_VM_MODULE_CANNOT_CREATE_CACHED_DATA,
ERR_VM_MODULE_LINK_FAILURE,
ERR_MODULE_LINK_MISMATCH,
ERR_VM_MODULE_NOT_MODULE,
@@ -448,11 +448,9 @@ class SourceTextModule extends Module {
}
createCachedData() {
- const { status } = this;
- if (status === 'evaluating' ||
- status === 'evaluated' ||
- status === 'errored') {
- throw new ERR_VM_MODULE_CANNOT_CREATE_CACHED_DATA();
+ if (typeof this !== 'object' || this === null ||
+ !(#moduleRequests in this)) {
+ throw new ERR_INVALID_THIS('SourceTextModule');
}
return this[kWrap].createCachedData();
}
diff --git a/src/module_wrap.cc b/src/module_wrap.cc
index 66500b7c6ae..2e5b1810d4f 100644
--- a/src/module_wrap.cc
+++ b/src/module_wrap.cc
@@ -1519,8 +1519,6 @@ void ModuleWrap::CreateCachedData(const FunctionCallbackInfo<Value>& args) {
Local<Module> module = obj->module_.Get(isolate);
- CHECK_LT(module->GetStatus(), Module::Status::kEvaluating);
-
Local<UnboundModuleScript> unbound_module_script =
module->GetUnboundModuleScript();
std::unique_ptr<ScriptCompiler::CachedData> cached_data(
diff --git a/test/parallel/test-vm-module-cached-data.js b/test/parallel/test-vm-module-cached-data.js
index fef68a8c189..e590666dcf7 100644
--- a/test/parallel/test-vm-module-cached-data.js
+++ b/test/parallel/test-vm-module-cached-data.js
@@ -5,7 +5,7 @@
const common = require('../common');
const assert = require('assert');
-const { SourceTextModule } = require('vm');
+const { SourceTextModule, SyntheticModule, createContext } = require('vm');
{
const m = new SourceTextModule('const a = 1');
@@ -20,11 +20,101 @@ const { SourceTextModule } = require('vm');
});
}
-assert.rejects(async () => {
- const m = new SourceTextModule('const a = 1');
- await m.link(() => {});
- m.evaluate();
- m.createCachedData();
-}, {
- code: 'ERR_VM_MODULE_CANNOT_CREATE_CACHED_DATA',
-}).then(common.mustCall());
+// A code cache that is created after evaluation is accepted by a new module
+// in another context.
+(async () => {
+ const source = 'export function add(a, b) { return a + b; }\n' +
+ 'export const sum = add(1, 2);\n' +
+ 'export function double(n) { return n * 2; }\n';
+ const m = new SourceTextModule(source);
+ await m.link(common.mustNotCall());
+ await m.evaluate();
+ assert.strictEqual(m.status, 'evaluated');
+ // V8 compiles double() here, after the evaluation.
+ assert.strictEqual(m.namespace.double(2), 4);
+ const cachedData = m.createCachedData();
+ assert(cachedData.length > 0);
+
+ const m2 = new SourceTextModule(source, {
+ context: createContext(),
+ cachedData,
+ });
+ await m2.link(common.mustNotCall());
+ await m2.evaluate();
+ assert.strictEqual(m2.namespace.sum, 3);
+ assert.strictEqual(m2.namespace.add(2, 3), 5);
+ assert.strictEqual(m2.namespace.double(3), 6);
+})().then(common.mustCall());
+
+// A code cache can be created while a top-level await is pending.
+(async () => {
+ const { promise, resolve } = Promise.withResolvers();
+ const source = 'export function later() { return 42; }\n' +
+ 'await pending;\n';
+ const m = new SourceTextModule(source, {
+ context: createContext({ pending: promise }),
+ });
+ await m.link(common.mustNotCall());
+ const evaluation = m.evaluate();
+ // V8 reports a pending top-level await as evaluated
+ assert.strictEqual(m.status, 'evaluated');
+ const cachedData = m.createCachedData();
+ assert(cachedData.length > 0);
+ resolve();
+ await evaluation;
+
+ const m2 = new SourceTextModule(source, {
+ context: createContext({ pending: Promise.resolve() }),
+ cachedData,
+ });
+ await m2.link(common.mustNotCall());
+ await m2.evaluate();
+ assert.strictEqual(m2.namespace.later(), 42);
+})().then(common.mustCall());
+
+// A code cache can be created while the module is evaluating.
+(async () => {
+ const source = 'check();';
+ let cachedData;
+ const context = createContext({ check: null });
+ const m = new SourceTextModule(source, { context });
+ context.check = common.mustCall(() => {
+ assert.strictEqual(m.status, 'evaluating');
+ cachedData = m.createCachedData();
+ });
+ await m.link(common.mustNotCall());
+ await m.evaluate();
+ assert(cachedData.length > 0);
+
+ const m2 = new SourceTextModule(source, {
+ context: createContext({ check: common.mustCall() }),
+ cachedData,
+ });
+ await m2.link(common.mustNotCall());
+ await m2.evaluate();
+})().then(common.mustCall());
+
+// A code cache can be created after the evaluation failed.
+(async () => {
+ const source = 'throw new Error("boom");';
+ const m = new SourceTextModule(source);
+ await m.link(common.mustNotCall());
+ await assert.rejects(m.evaluate(), { message: 'boom' });
+ assert.strictEqual(m.status, 'errored');
+ const cachedData = m.createCachedData();
+ assert(cachedData.length > 0);
+
+ const m2 = new SourceTextModule(source, { cachedData });
+ await m2.link(common.mustNotCall());
+ await assert.rejects(m2.evaluate(), { message: 'boom' });
+})().then(common.mustCall());
+
+// createCachedData() throws if the receiver is not a SourceTextModule.
+{
+ const { createCachedData } = SourceTextModule.prototype;
+ for (const receiver of [new SyntheticModule([], () => {}), {}, null, 1]) {
+ assert.throws(() => createCachedData.call(receiver), {
+ code: 'ERR_INVALID_THIS',
+ });
+ }
+}