Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion doc/api/errors.md
Original file line number Diff line number Diff line change
Expand Up @@ -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'`.

<a id="ERR_VM_MODULE_DIFFERENT_CONTEXT"></a>

Expand Down
20 changes: 18 additions & 2 deletions doc/api/vm.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion lib/internal/errors.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
4 changes: 1 addition & 3 deletions lib/internal/vm/module.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
6 changes: 5 additions & 1 deletion src/module_wrap.cc
Original file line number Diff line number Diff line change
Expand Up @@ -1511,7 +1511,11 @@ void ModuleWrap::CreateCachedData(const FunctionCallbackInfo<Value>& args) {

Local<Module> 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<UnboundModuleScript> unbound_module_script =
module->GetUnboundModuleScript();
Expand Down
120 changes: 112 additions & 8 deletions test/parallel/test-vm-module-cached-data.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand All @@ -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());