From b810e6703968ea3cd82262aa9acc57fabc894cd1 Mon Sep 17 00:00:00 2001 From: Gus Caplan Date: Thu, 9 Jan 2020 08:34:55 -0800 Subject: [PATCH] vm: add code cache support for SourceTextModule PR-URL: https://github.com/nodejs/node/pull/31278 Reviewed-By: James M Snell Reviewed-By: Rich Trott Reviewed-By: Anna Henningsen --- doc/api/errors.md | 10 +++ doc/api/vm.md | 26 ++++++++ lib/internal/errors.js | 2 + lib/internal/vm/module.js | 29 +++++++- src/module_wrap.cc | 73 ++++++++++++++++++--- src/module_wrap.h | 1 + src/node_errors.h | 1 + test/parallel/test-vm-module-cached-data.js | 30 +++++++++ 8 files changed, 162 insertions(+), 10 deletions(-) create mode 100644 test/parallel/test-vm-module-cached-data.js diff --git a/doc/api/errors.md b/doc/api/errors.md index c5041c796be011..4d9651be8ddd2a 100644 --- a/doc/api/errors.md +++ b/doc/api/errors.md @@ -1988,6 +1988,16 @@ the following reasons: * It is being linked (`linkingStatus` is `'linking'`) * Linking has failed for this module (`linkingStatus` is `'errored'`) + +### `ERR_VM_MODULE_CACHED_DATA_REJECTED` + +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` diff --git a/doc/api/vm.md b/doc/api/vm.md index 9e832ac8bb8606..57109f143a0f4d 100644 --- a/doc/api/vm.md +++ b/doc/api/vm.md @@ -566,6 +566,10 @@ defined in the ECMAScript specification. * `identifier` {string} String used in stack traces. **Default:** `'vm:module(i)'` where `i` is a context-specific ascending index. + * `cachedData` {Buffer|TypedArray|DataView} Provides an optional `Buffer` or + `TypedArray`, or `DataView` with V8's code cache data for the supplied + source. The `code` must be the same as the module from which this + `cachedData` was created. * `context` {Object} The [contextified][] object as returned by the `vm.createContext()` method, to compile and evaluate this `Module` in. * `lineOffset` {integer} Specifies the line number offset that is displayed @@ -621,6 +625,28 @@ const contextifiedObject = vm.createContext({ secret: 42 }); })(); ``` +### `sourceTextModule.createCachedData()` + + +* 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. + +```js +// Create an initial module +const module = new vm.SourceTextModule('const a = 1;'); + +// Create cached data from this module +const cachedData = module.createCachedData(); + +// Create a new module using the cached data. The code must be the same. +const module2 = new vm.SourceTextModule('const a = 1;', { cachedData }); +``` + ## Class: `vm.SyntheticModule`