diff --git a/doc/api/errors.md b/doc/api/errors.md
index 0d621087bd4b..16a13850d6fd 100644
--- a/doc/api/errors.md
+++ b/doc/api/errors.md
@@ -3637,12 +3637,6 @@ the following reasons:
The `cachedData` option passed to a module constructor is invalid.
-
-
-### `ERR_VM_MODULE_CANNOT_CREATE_CACHED_DATA`
-
-Cached data cannot be created for modules which have already been evaluated.
-
### `ERR_VM_MODULE_DIFFERENT_CONTEXT`
@@ -4546,6 +4540,16 @@ removed: v10.0.0
Used when a given value is out of the accepted range.
+
+
+### `ERR_VM_MODULE_CANNOT_CREATE_CACHED_DATA`
+
+
+
+Cached data cannot be created for modules which have already been evaluated.
+
### `ERR_VM_MODULE_LINKING_ERRORED`
diff --git a/doc/api/vm.md b/doc/api/vm.md
index 14cd1f269b12..330fab02283a 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 28f7409ec7f1..0e5b6d0fad89 100644
--- a/lib/internal/errors.js
+++ b/lib/internal/errors.js
@@ -1969,8 +1969,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 ce2350f6cd16..cbe4638f0d18 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 66500b7c6ae5..2e5b1810d4f2 100644
--- a/src/module_wrap.cc
+++ b/src/module_wrap.cc
@@ -1519,8 +1519,6 @@ void ModuleWrap::CreateCachedData(const FunctionCallbackInfo& args) {
Local module = obj->module_.Get(isolate);
- CHECK_LT(module->GetStatus(), Module::Status::kEvaluating);
-
Local unbound_module_script =
module->GetUnboundModuleScript();
std::unique_ptr cached_data(
diff --git a/test/parallel/test-vm-module-cached-data.js b/test/parallel/test-vm-module-cached-data.js
index fef68a8c1890..e590666dcf75 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',
+ });
+ }
+}