diff --git a/doc/api/errors.md b/doc/api/errors.md
index e6ab55bab058..31d3b7de17f1 100644
--- a/doc/api/errors.md
+++ b/doc/api/errors.md
@@ -3622,7 +3622,8 @@ 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.
+Cached data cannot be created for a module whose status is `'evaluating'` or
+`'errored'`.
diff --git a/doc/api/vm.md b/doc/api/vm.md
index 14cd1f269b12..1ac5b37b9ff8 100644
--- a/doc/api/vm.md
+++ b/doc/api/vm.md
@@ -976,13 +976,20 @@ 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 after the module has been
+ evaluated.
-->
* 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.
+of times before the module is evaluated, and after the module has been
+evaluated. It throws [`ERR_VM_MODULE_CANNOT_CREATE_CACHED_DATA`][] if the
+status of the module is `'evaluating'` or `'errored'`.
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 +999,15 @@ 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.
+
+If the module or one of its dependencies uses top-level `await`,
+`sourceTextModule.status` is `'evaluated'` while the `await` is pending. In
+this case, the code cache can contain only the functions that are compiled at
+the time of the call.
```js
// Create an initial module
@@ -2574,6 +2589,7 @@ const { Script, SyntheticModule } = require('node:vm');
[WithClause]: https://tc39.es/ecma262/#prod-WithClause
[`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING_FLAG`]: errors.md#err_vm_dynamic_import_callback_missing_flag
[`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`]: errors.md#err_vm_dynamic_import_callback_missing
+[`ERR_VM_MODULE_CANNOT_CREATE_CACHED_DATA`]: errors.md#err_vm_module_cannot_create_cached_data
[`Error`]: errors.md#class-error
[`URL`]: url.md#class-url
[`eval()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval
diff --git a/lib/internal/errors.js b/lib/internal/errors.js
index 88518563bc6b..35a3d76808de 100644
--- a/lib/internal/errors.js
+++ b/lib/internal/errors.js
@@ -1965,7 +1965,8 @@ E('ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING_FLAG',
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);
+ 'Cached data cannot be created for a module whose status is evaluating ' +
+ 'or errored', 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..0ab166db0a76 100644
--- a/lib/internal/vm/module.js
+++ b/lib/internal/vm/module.js
@@ -449,9 +449,7 @@ class SourceTextModule extends Module {
createCachedData() {
const { status } = this;
- if (status === 'evaluating' ||
- status === 'evaluated' ||
- status === 'errored') {
+ if (status === 'evaluating' || status === 'errored') {
throw new ERR_VM_MODULE_CANNOT_CREATE_CACHED_DATA();
}
return this[kWrap].createCachedData();
diff --git a/src/module_wrap.cc b/src/module_wrap.cc
index 444d31337531..7c1cadd64dd1 100644
--- a/src/module_wrap.cc
+++ b/src/module_wrap.cc
@@ -1511,7 +1511,11 @@ void ModuleWrap::CreateCachedData(const FunctionCallbackInfo& args) {
Local module = obj->module_.Get(isolate);
- CHECK_LT(module->GetStatus(), Module::Status::kEvaluating);
+ // A code cache that is created after evaluation also contains the functions
+ // that were compiled lazily while the module ran.
+ Module::Status status = module->GetStatus();
+ CHECK_NE(status, Module::Status::kEvaluating);
+ CHECK_NE(status, Module::Status::kErrored);
Local unbound_module_script =
module->GetUnboundModuleScript();
diff --git a/test/parallel/test-vm-module-cached-data.js b/test/parallel/test-vm-module-cached-data.js
index fef68a8c1890..9602383c27a7 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, createContext } = require('vm');
{
const m = new SourceTextModule('const a = 1');
@@ -20,11 +20,115 @@ const { SourceTextModule } = require('vm');
});
}
-assert.rejects(async () => {
- const m = new SourceTextModule('const a = 1');
- await m.link(() => {});
- m.evaluate();
+// 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';
+ const m = new SourceTextModule(source);
+ await m.link(common.mustNotCall());
+ await m.evaluate();
+ assert.strictEqual(m.status, 'evaluated');
+ 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);
+})().then(common.mustCall());
+
+// A code cache that is created after an exported function was called is
+// accepted by a new module.
+(async () => {
+ const source = 'export function work(n) {\n' +
+ ' let total = 0;\n' +
+ ' for (let i = 0; i < n; i++) {\n' +
+ ' total += i * 2;\n' +
+ ' }\n' +
+ ' return total;\n' +
+ '}\n';
+ const m = new SourceTextModule(source);
+ await m.link(common.mustNotCall());
+ await m.evaluate();
+ assert.strictEqual(m.namespace.work(4), 12);
+ const after = m.createCachedData();
+
+ const m2 = new SourceTextModule(source, { cachedData: after });
+ await m2.link(common.mustNotCall());
+ await m2.evaluate();
+ assert.strictEqual(m2.namespace.work(4), 12);
+})().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();
+ 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 a top-level await is pending, but not
+// after the awaited promise rejects.
+(async () => {
+ const { promise, reject } = Promise.withResolvers();
+ const m = new SourceTextModule('await pending;', {
+ context: createContext({ pending: promise }),
+ });
+ await m.link(common.mustNotCall());
+ const evaluation = m.evaluate();
+ assert.strictEqual(m.status, 'evaluated');
m.createCachedData();
-}, {
- code: 'ERR_VM_MODULE_CANNOT_CREATE_CACHED_DATA',
-}).then(common.mustCall());
+ reject(new Error('boom'));
+ await assert.rejects(evaluation, { message: 'boom' });
+ assert.strictEqual(m.status, 'errored');
+ assert.throws(() => m.createCachedData(), {
+ code: 'ERR_VM_MODULE_CANNOT_CREATE_CACHED_DATA',
+ });
+})().then(common.mustCall());
+
+// A code cache cannot be created while the module is evaluating.
+(async () => {
+ const context = createContext({ check: null });
+ const m = new SourceTextModule('check();', { context });
+ context.check = common.mustCall(() => {
+ assert.strictEqual(m.status, 'evaluating');
+ assert.throws(() => m.createCachedData(), {
+ code: 'ERR_VM_MODULE_CANNOT_CREATE_CACHED_DATA',
+ });
+ });
+ await m.link(common.mustNotCall());
+ await m.evaluate();
+})().then(common.mustCall());
+
+// A code cache cannot be created after the evaluation failed.
+(async () => {
+ const m = new SourceTextModule('throw new Error("boom");');
+ await m.link(common.mustNotCall());
+ await assert.rejects(m.evaluate(), { message: 'boom' });
+ assert.strictEqual(m.status, 'errored');
+ assert.throws(() => m.createCachedData(), {
+ code: 'ERR_VM_MODULE_CANNOT_CREATE_CACHED_DATA',
+ });
+})().then(common.mustCall());