Skip to content

Commit 16777e3

Browse files
committed
esm: add experimental support for addon modules
1 parent c39875a commit 16777e3

File tree

20 files changed

+312
-22
lines changed

20 files changed

+312
-22
lines changed

β€Ždoc/api/cli.mdβ€Ž

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,8 +45,11 @@ Otherwise, the file is loaded using the CommonJS module loader. See
4545

4646
When loading, the [ES module loader][Modules loaders] loads the program
4747
entry point, the `node` command will accept as input only files with `.js`,
48-
`.mjs`, or `.cjs` extensions; and with `.wasm` extensions when
49-
[`--experimental-wasm-modules`][] is enabled.
48+
`.mjs`, or `.cjs` extensions. With the following flags, additional file
49+
extensions are enabled:
50+
51+
* [`--experimental-wasm-modules`][] for files with `.wasm` extension.
52+
* [`--experimental-addon-modules`][] for files with `.node` extension.
5053

5154
## Options
5255

@@ -880,6 +883,16 @@ and `"` are usable.
880883
It is possible to run code containing inline types by passing
881884
[`--experimental-strip-types`][].
882885

886+
### `--experimental-addon-modules`
887+
888+
<!-- YAML
889+
added: REPLACEME
890+
-->
891+
892+
> Stability: 1.0 - Early development
893+
894+
Enable experimental import support for `.node` addons.
895+
883896
### `--experimental-eventsource`
884897

885898
<!-- YAML
@@ -3043,6 +3056,7 @@ one is included in the list below.
30433056
* `--enable-source-maps`
30443057
* `--entry-url`
30453058
* `--experimental-abortcontroller`
3059+
* `--experimental-addon-modules`
30463060
* `--experimental-detect-module`
30473061
* `--experimental-eventsource`
30483062
* `--experimental-import-meta-resolve`
@@ -3612,6 +3626,7 @@ node --stack-trace-limit=12 -p -e "Error.stackTraceLimit" # prints 12
36123626
[`--diagnostic-dir`]: #--diagnostic-dirdirectory
36133627
[`--env-file-if-exists`]: #--env-file-if-existsconfig
36143628
[`--env-file`]: #--env-fileconfig
3629+
[`--experimental-addon-modules`]: #--experimental-addon-modules
36153630
[`--experimental-sea-config`]: single-executable-applications.md#generating-single-executable-preparation-blobs
36163631
[`--experimental-strip-types`]: #--experimental-strip-types
36173632
[`--experimental-wasm-modules`]: #--experimental-wasm-modules

β€Ždoc/api/esm.mdβ€Ž

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1045,18 +1045,21 @@ _isImports_, _conditions_)
10451045
> 5. If `--experimental-wasm-modules` is enabled and _url_ ends in
10461046
> _".wasm"_, then
10471047
> 1. Return _"wasm"_.
1048-
> 6. Let _packageURL_ be the result of **LOOKUP\_PACKAGE\_SCOPE**(_url_).
1049-
> 7. Let _pjson_ be the result of **READ\_PACKAGE\_JSON**(_packageURL_).
1050-
> 8. Let _packageType_ be **null**.
1051-
> 9. If _pjson?.type_ is _"module"_ or _"commonjs"_, then
1052-
> 1. Set _packageType_ to _pjson.type_.
1053-
> 10. If _url_ ends in _".js"_, then
1048+
> 6. If `--experimental-addon-modules` is enabled and _url_ ends in
1049+
> _".node"_, then
1050+
> 1. Return _"addon"_.
1051+
> 7. Let _packageURL_ be the result of **LOOKUP\_PACKAGE\_SCOPE**(_url_).
1052+
> 8. Let _pjson_ be the result of **READ\_PACKAGE\_JSON**(_packageURL_).
1053+
> 9. Let _packageType_ be **null**.
1054+
> 10. If _pjson?.type_ is _"module"_ or _"commonjs"_, then
1055+
> 1. Set _packageType_ to _pjson.type_.
1056+
> 11. If _url_ ends in _".js"_, then
10541057
> 1. If _packageType_ is not **null**, then
10551058
> 1. Return _packageType_.
10561059
> 2. If the result of **DETECT\_MODULE\_SYNTAX**(_source_) is true, then
10571060
> 1. Return _"module"_.
10581061
> 3. Return _"commonjs"_.
1059-
> 11. If _url_ does not have any extension, then
1062+
> 12. If _url_ does not have any extension, then
10601063
> 1. If _packageType_ is _"module"_ and `--experimental-wasm-modules` is
10611064
> enabled and the file at _url_ contains the header for a WebAssembly
10621065
> module, then
@@ -1066,7 +1069,7 @@ _isImports_, _conditions_)
10661069
> 3. If the result of **DETECT\_MODULE\_SYNTAX**(_source_) is true, then
10671070
> 1. Return _"module"_.
10681071
> 4. Return _"commonjs"_.
1069-
> 12. Return **undefined** (will throw during load phase).
1072+
> 13. Return **undefined** (will throw during load phase).
10701073
10711074
**LOOKUP\_PACKAGE\_SCOPE**(_url_)
10721075

β€Ždoc/api/module.mdβ€Ž

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1161,6 +1161,7 @@ The final value of `format` must be one of the following:
11611161
11621162
| `format` | Description | Acceptable types for `source` returned by `load` |
11631163
| ------------ | ------------------------------ | -------------------------------------------------------------------------- |
1164+
| `'addon'` | Load a Node.js addon | { `null` } |
11641165
| `'builtin'` | Load a Node.js builtin module | Not applicable |
11651166
| `'commonjs'` | Load a Node.js CommonJS module | { [`string`][], [`ArrayBuffer`][], [`TypedArray`][], `null`, `undefined` } |
11661167
| `'json'` | Load a JSON file | { [`string`][], [`ArrayBuffer`][], [`TypedArray`][] } |

β€Ždoc/node.1β€Ž

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,9 @@ Enable Source Map V3 support for stack traces.
163163
.It Fl -entry-url
164164
Interpret the entry point as a URL.
165165
.
166+
.It Fl -experimental-addon-modules
167+
Enable experimental addon module support.
168+
.
166169
.It Fl -experimental-import-meta-resolve
167170
Enable experimental ES modules support for import.meta.resolve().
168171
.

β€Žlib/internal/modules/esm/formats.jsβ€Ž

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ const fsBindings = internalBinding('fs');
1010
const { fs: fsConstants } = internalBinding('constants');
1111

1212
const experimentalWasmModules = getOptionValue('--experimental-wasm-modules');
13+
const experimentalAddonModules = getOptionValue('--experimental-addon-modules');
1314

1415
const extensionFormatMap = {
1516
'__proto__': null,
@@ -23,6 +24,10 @@ if (experimentalWasmModules) {
2324
extensionFormatMap['.wasm'] = 'wasm';
2425
}
2526

27+
if (experimentalAddonModules) {
28+
extensionFormatMap['.node'] = 'addon';
29+
}
30+
2631
if (getOptionValue('--experimental-strip-types')) {
2732
extensionFormatMap['.ts'] = 'module-typescript';
2833
extensionFormatMap['.mts'] = 'module-typescript';

β€Žlib/internal/modules/esm/load.jsβ€Ž

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,9 @@ async function defaultLoad(url, context = kEmptyObject) {
105105
if (urlInstance.protocol === 'node:') {
106106
source = null;
107107
format ??= 'builtin';
108+
} else if (format === 'addon') {
109+
// Skip loading addon file content. It must be loaded with dlopen from file system.
110+
source = null;
108111
} else if (format !== 'commonjs') {
109112
if (source == null) {
110113
({ responseURL, source } = await getSource(urlInstance, context));

β€Žlib/internal/modules/esm/translators.jsβ€Ž

Lines changed: 85 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
const {
44
ArrayPrototypeMap,
55
ArrayPrototypePush,
6-
Boolean,
76
FunctionPrototypeCall,
87
JSONParse,
98
ObjectKeys,
@@ -52,6 +51,7 @@ let debug = require('internal/util/debuglog').debuglog('esm', (fn) => {
5251
});
5352
const { emitExperimentalWarning, kEmptyObject, setOwnProperty, isWindows } = require('internal/util');
5453
const {
54+
ERR_INVALID_RETURN_PROPERTY_VALUE,
5555
ERR_UNKNOWN_BUILTIN_MODULE,
5656
} = require('internal/errors').codes;
5757
const { maybeCacheSourceMap } = require('internal/source_map/source_map_cache');
@@ -229,6 +229,47 @@ function createCJSModuleWrap(url, source, isMain, format, loadCJS = loadCJSModul
229229
}, module);
230230
}
231231

232+
/**
233+
* Creates a ModuleWrap object for a CommonJS module without source texts.
234+
* @param {string} url - The URL of the module.
235+
* @param {boolean} isMain - Whether the module is the main module.
236+
* @returns {ModuleWrap} The ModuleWrap object for the CommonJS module.
237+
*/
238+
function createCJSNoSourceModuleWrap(url, isMain) {
239+
debug(`Translating CJSModule without source ${url}`);
240+
241+
const filename = urlToFilename(url);
242+
243+
const module = cjsEmplaceModuleCacheEntry(filename);
244+
cjsCache.set(url, module);
245+
246+
if (isMain) {
247+
setOwnProperty(process, 'mainModule', module);
248+
}
249+
250+
// Addon export names are not known until the addon is loaded.
251+
const exportNames = ['default', 'module.exports'];
252+
return new ModuleWrap(url, undefined, exportNames, function evaluationCallback() {
253+
debug(`Loading CJSModule ${url}`);
254+
255+
if (!module.loaded) {
256+
wrapModuleLoad(filename, null, isMain);
257+
}
258+
259+
/** @type {import('./loader').ModuleExports} */
260+
let exports;
261+
if (module[kModuleExport] !== undefined) {
262+
exports = module[kModuleExport];
263+
module[kModuleExport] = undefined;
264+
} else {
265+
({ exports } = module);
266+
}
267+
268+
this.setExport('default', exports);
269+
this.setExport('module.exports', exports);
270+
}, module);
271+
}
272+
232273
translators.set('commonjs-sync', function requireCommonJS(url, source, isMain) {
233274
initCJSParseSync();
234275

@@ -280,26 +321,39 @@ translators.set('commonjs', function commonjsStrategy(url, source, isMain) {
280321
return createCJSModuleWrap(url, source, isMain, 'commonjs', cjsLoader);
281322
});
282323

324+
/**
325+
* Get or create an entry in the CJS module cache for the given filename.
326+
* @param {string} filename CJS module filename
327+
* @returns {CJSModule} the cached CJS module entry
328+
*/
329+
function cjsEmplaceModuleCacheEntry(filename, exportNames) {
330+
// TODO: Do we want to keep hitting the user mutable CJS loader here?
331+
let cjsMod = CJSModule._cache[filename];
332+
if (cjsMod) {
333+
return cjsMod;
334+
}
335+
336+
cjsMod = new CJSModule(filename);
337+
cjsMod.filename = filename;
338+
cjsMod.paths = CJSModule._nodeModulePaths(cjsMod.path);
339+
cjsMod[kIsCachedByESMLoader] = true;
340+
CJSModule._cache[filename] = cjsMod;
341+
342+
return cjsMod;
343+
}
344+
283345
/**
284346
* Pre-parses a CommonJS module's exports and re-exports.
285347
* @param {string} filename - The filename of the module.
286348
* @param {string} [source] - The source code of the module.
287349
* @param {boolean} isMain - Whether it is pre-parsing for the entry point.
288350
* @param {string} format
289351
*/
290-
function cjsPreparseModuleExports(filename, source, isMain, format) {
291-
let module = CJSModule._cache[filename];
292-
if (module && module[kModuleExportNames] !== undefined) {
352+
function cjsPreparseModuleExports(filename, source) {
353+
const module = cjsEmplaceModuleCacheEntry(filename);
354+
if (module[kModuleExportNames] !== undefined) {
293355
return { module, exportNames: module[kModuleExportNames] };
294356
}
295-
const loaded = Boolean(module);
296-
if (!loaded) {
297-
module = new CJSModule(filename);
298-
module.filename = filename;
299-
module.paths = CJSModule._nodeModulePaths(module.path);
300-
module[kIsCachedByESMLoader] = true;
301-
CJSModule._cache[filename] = module;
302-
}
303357

304358
if (source === undefined) {
305359
({ source } = loadSourceForCJSWithHooks(module, filename, format));
@@ -462,6 +516,25 @@ translators.set('wasm', async function(url, source) {
462516
}).module;
463517
});
464518

519+
// Strategy for loading a addon
520+
translators.set('addon', function translateAddon(url, source, isMain) {
521+
emitExperimentalWarning('Importing addons');
522+
523+
// The addon must be loaded from file system with dlopen. Assert
524+
// the source is null.
525+
if (source !== null) {
526+
throw new ERR_INVALID_RETURN_PROPERTY_VALUE(
527+
'null',
528+
'load',
529+
'source',
530+
source);
531+
}
532+
533+
debug(`Translating addon ${url}`);
534+
535+
return createCJSNoSourceModuleWrap(url, isMain);
536+
});
537+
465538
// Strategy for loading a commonjs TypeScript module
466539
translators.set('commonjs-typescript', function(url, source) {
467540
emitExperimentalWarning('Type Stripping');

β€Žsrc/node_options.ccβ€Ž

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -409,6 +409,10 @@ EnvironmentOptionsParser::EnvironmentOptionsParser() {
409409
"Treat the entrypoint as a URL",
410410
&EnvironmentOptions::entry_is_url,
411411
kAllowedInEnvvar);
412+
AddOption("--experimental-addon-modules",
413+
"experimental import support for addons",
414+
&EnvironmentOptions::experimental_addon_modules,
415+
kAllowedInEnvvar);
412416
AddOption("--experimental-abortcontroller", "", NoOp{}, kAllowedInEnvvar);
413417
AddOption("--experimental-eventsource",
414418
"experimental EventSource API",

β€Žsrc/node_options.hβ€Ž

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,7 @@ class EnvironmentOptions : public Options {
120120
bool require_module = true;
121121
std::string dns_result_order;
122122
bool enable_source_maps = false;
123+
bool experimental_addon_modules = false;
123124
bool experimental_eventsource = false;
124125
bool experimental_fetch = true;
125126
bool experimental_websocket = true;

β€Žtest/addons/esm-package-dependent/node_modules/esm-packageβ€Ž

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
Β (0)