Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
142 commits
Select commit Hold shift + click to select a range
7c38e50
doc: add documentation for process.features
marco-ippolito Sep 14, 2024
697a392
doc: fix history of `process.features`
aduh95 Sep 17, 2024
132a5c1
module: eliminate performance cost of detection for cjs entry
GeoffreyBooth Mar 20, 2024
b07ad39
module: detect ESM syntax by trying to recompile as SourceTextModule
joyeecheung Apr 19, 2024
f13589f
lib,src: iterate module requests of a module wrap in JS
legendecas Apr 25, 2024
a03faf2
module: support ESM detection in the CJS loader
joyeecheung Apr 29, 2024
30ed93d
module: cache synchronous module jobs before linking
joyeecheung May 7, 2024
b86f575
module: do not set CJS variables for Worker eval
aduh95 May 25, 2024
34221a1
lib: allow CJS source map cache to be reclaimed
legendecas May 28, 2024
533afe8
lib: reduce amount of caught URL errors
anonrig Jun 13, 2024
18593b7
src: refactor embedded entrypoint loading
joyeecheung Jul 5, 2024
f9dc1ea
module: add __esModule to require()'d ESM
joyeecheung Mar 20, 2024
0d327c8
esm: refactor `get_format`
aduh95 Jul 18, 2024
9916458
module: unflag detect-module
GeoffreyBooth Jul 20, 2024
d1331fc
module: do not warn for typeless package.json when there isn't one
joyeecheung Jul 29, 2024
4813a6a
esm: throw `ERR_REQUIRE_ESM` instead of `ERR_INTERNAL_ASSERTION`
aduh95 Sep 11, 2024
1925d72
module: remove bogus assertion in CJS entrypoint handling with --import
joyeecheung Aug 27, 2024
249d82b
module: report unfinished TLA in ambiguous modules
aduh95 Sep 19, 2024
df8a045
module: implement the "module-sync" exports condition
joyeecheung Sep 25, 2024
683c93f
module: refator ESM loader for adding future synchronous hooks
joyeecheung Sep 17, 2024
1ac1dda
module: unflag --experimental-require-module
joyeecheung Sep 26, 2024
dc66632
module: support 'module.exports' interop export in require(esm)
guybedford Jul 14, 2024
64ce95b
doc: update `require(ESM)` history and stability status
aduh95 Oct 2, 2024
cf8701c
module: use kNodeModulesRE to detect node_modules
joyeecheung Oct 4, 2024
4fba019
process: add process.features.require_module
joyeecheung Oct 7, 2024
ececd22
src: implement IsInsideNodeModules() in C++
joyeecheung Oct 8, 2024
1db210a
module: check --experimental-require-module separately from detection
joyeecheung Oct 8, 2024
8192dd6
module: include module information in require(esm) warning
joyeecheung Oct 22, 2024
8d33f78
module: allow ESM that failed to be required to be re-imported
joyeecheung Oct 28, 2024
fdf5028
module: trim off internal stack frames for require(esm) warnings
joyeecheung Oct 18, 2024
011e6e0
module: fix error thrown from require(esm) hitting TLA repeatedly
joyeecheung Oct 29, 2024
e01dd4b
module: do not warn when require(esm) comes from node_modules
joyeecheung Nov 23, 2024
3d89e6b
module: mark evaluation rejection in require(esm) as handled
joyeecheung Dec 5, 2024
de313b2
module: only emit require(esm) warning under --trace-require-module
joyeecheung Dec 9, 2024
ed2d373
module: disable require(esm) for policy and network import
joyeecheung Feb 6, 2025
8342233
deps: update corepack to 0.31.0
nodejs-github-bot Jan 28, 2025
5c9a397
deps: V8: backport 9ab40592f697
luyahan Dec 9, 2024
9e975f1
doc: fix link and history of `SourceMap` sections
aduh95 Feb 18, 2025
73b5c16
worker: add postMessageToThread
ShogunPanda Jul 9, 2024
9097de0
src: don't match after `--` in `Dotenv::GetPathFromArgs`
avivkeller Aug 13, 2024
b8c89a6
src: add `--env-file-if-exists` flag
BoscoDomingo Sep 16, 2024
9fda8e2
doc: mark `--env-file-if-exists` flag as experimental
juanarbol Feb 5, 2025
561493d
deps,src: simplify base64 encoding
lemire Apr 30, 2024
bb57e90
src: remove `base64` from `process.versions`
richardlau Jun 15, 2024
8e76cc6
doc: move dual package shipping docs to separate repo
joyeecheung Oct 22, 2024
f507c05
module: simplify --inspect-brk handling
joyeecheung Nov 3, 2024
d69107f
deps: update icu to 76.1
nodejs-github-bot Nov 7, 2024
e87db6c
events: add hasEventListener util for validate
sungpaks Nov 14, 2024
674b932
http: don't emit error after destroy
ronag Oct 28, 2024
8af1b53
src: safely remove the last line from dotenv
islandryu Nov 26, 2024
182be26
test: update WPT for url to 67880a4eb83ca9aa732eec4b35a1971ff5bf37ff
nodejs-github-bot Nov 28, 2024
4d72412
meta: move MoLow to TSC regular member
MoLow Dec 18, 2024
1cc8d69
build: build v8 with -fvisibility=hidden on macOS
joyeecheung Dec 19, 2024
b4b26e9
test: deflake test-esm-loader-hooks-inspect-brk
lpinca Dec 19, 2024
5083bbb
test: remove async-hooks/test-writewrap flaky designation
lpinca Dec 20, 2024
fe5f7bc
stream: validate undefined sizeAlgorithm in WritableStream
jazelly Dec 20, 2024
55a57a1
node-api: remove deprecated attribute from napi_module_register
vmoroz Dec 20, 2024
1ee4bf9
build: test macos-13 on GitHub actions
targos Dec 20, 2024
3b13000
tools: add release line label when opening release proposal
aduh95 Dec 21, 2024
c0d45e7
deps: update simdutf to 5.7.0
nodejs-github-bot Dec 24, 2024
82461af
test: migrate message eval tests from Python to JS
yiyunlei Oct 31, 2023
d6aca0c
test: increase spin for eventloop test on s390
mhdawson Dec 10, 2024
ad59c82
doc: clarify that WASM is trusted
mcollina Dec 25, 2024
bc756da
doc: use `<ul>` instead of `<ol>` in `SECURITY.md`
aduh95 Dec 23, 2024
48f9ca0
meta: move one or more collaborators to emeritus
nodejs-github-bot Dec 25, 2024
e675c3a
doc: expand description of `parseArg`'s `default`
bakkot Dec 27, 2024
e1b71a8
deps: update googletest to e54519b
nodejs-github-bot Dec 28, 2024
b92ff7b
deps: update googletest to 7d76a23
nodejs-github-bot Dec 31, 2024
1ef9c9a
doc: add example for piping ReadableStream
gabrielschulhof Jan 1, 2025
1e44f5d
deps: update simdutf to 5.7.2
nodejs-github-bot Jan 2, 2025
bc8c39b
tools: disable unneeded rule ignoring in Python linting
Trott Jan 3, 2025
51ff71a
test: update test-child-process-windows-hide to use node:test
cjihrig Jan 4, 2025
cfe5380
test: update test-set-http-max-http-headers to use node:test
cjihrig Jan 4, 2025
721e9e1
test: add initial test426 coverage
legendecas Jan 4, 2025
597a39b
test: update error code in tls-psk-circuit for for OpenSSL 3.4
sebastianas Jan 6, 2025
cf25a5e
src: drain platform tasks before creating startup snapshot
legendecas Jan 7, 2025
589d0ae
tools: fix loong64 build failed
Xiao-Tao Jan 7, 2025
500f3cc
src: lock the thread properly in snapshot builder
joyeecheung Jan 7, 2025
020c939
doc: allow request for TSC reviews via the GitHub UI
aduh95 Jan 8, 2025
4274c6a
test_runner: run single test file benchmark
pmarchini Jan 9, 2025
c06ac66
src: fix undefined script name in error source
legendecas Jan 9, 2025
4ff9aa7
tools: validate commit list as part of `lint-release-commit`
aduh95 Jan 9, 2025
27b9cfd
doc: add message for Ambassadors to promote
mhdawson Dec 11, 2024
ff8af58
doc: add esm examples to node:trace_events
mfdebian Jan 10, 2025
c85b386
esm: fix jsdoc type refs to `ModuleJobBase` in esm/loader
JakobJingleheimer Jan 10, 2025
3fe80c3
doc: include CVE to EOL lines as sec release process
RafaelGSS Jan 10, 2025
914b467
tools: edit `create-release-proposal` workflow
aduh95 Jan 11, 2025
acbbd7c
doc: fix parentheses in options
tniessen Jan 12, 2025
03878b0
doc: update gcc-version for ubuntu-lts
KunalKumar-1 Jan 12, 2025
d84be84
benchmark: add validateStream to styleText bench
RafaelGSS Jan 12, 2025
d7aefc0
stream: fix typo in ReadableStreamBYOBReader.readIntoRequests
MattiasBuelens Jan 13, 2025
861c99f
test: make test-crypto-hash compatible with OpenSSL > 3.4.0
jelly Dec 6, 2024
5660b99
test: disable openssl 3.4.0 incompatible tests
jelly Dec 6, 2024
d17bf2f
test: update test-child-process-bad-stdio to use node:test
cjihrig Jan 13, 2025
4b3e7fe
doc: document CLI way to open the nodejs/bluesky PR
aduh95 Jan 13, 2025
285bb4e
crypto: update root certificates to NSS 3.107
nodejs-github-bot Jan 14, 2025
15214e6
deps: update simdutf to 6.0.3
nodejs-github-bot Jan 14, 2025
85bb738
meta: add codeowners of security release document
RafaelGSS Jan 15, 2025
40a0f6f
test: mark test-worker-prof as flaky on smartos
joyeecheung Jan 15, 2025
b0b77d7
doc: improve internal documentation on built-in snapshot
joyeecheung Jan 15, 2025
d2f09e2
doc: add type stripping to ambassadors program
marco-ippolito Jan 16, 2025
0a009a5
doc: tweak info on reposts in ambassador program
mhdawson Jan 16, 2025
e67a849
test_runner: remove unused errors
pmarchini Jan 17, 2025
08bde67
test: add maxCount and gcOptions to gcUntil()
joyeecheung Jan 14, 2025
e162476
tools: fix permissions in `lint-release-proposal` workflow
aduh95 Jan 17, 2025
5ef3c3c
crypto: add missing return value check
mhdawson Jan 17, 2025
aba280c
doc: mention prepare --security
RafaelGSS Jan 17, 2025
52f1f7e
child_process: fix parsing messages with splitted length field
MGorkov Jan 18, 2025
a7c1d8c
src: initialize FSReqWrapSync in path that uses it
targos Jan 19, 2025
ca79914
test: test-stream-compose.js doesn't need internals
nektro Jan 19, 2025
4c24ef8
http2: omit server name when HTTP2 host is IP address
islandryu Dec 29, 2024
9782639
doc: `WeakSet` and `WeakMap` comparison details
ishon19 Jan 20, 2025
e890c86
doc: clarify cjs/esm diff in `queueMicrotask()` vs `process.nextTick()`
dario-piotrowicz Jan 21, 2025
d6469b5
tools: do not throw on missing `create-release-proposal.sh`
aduh95 Jan 22, 2025
337cfb2
doc: add RafaelGSS as latest sec release stewards
RafaelGSS Jan 23, 2025
68548dc
doc: fix inconsistencies in `WeakSet` and `WeakMap` comparison details
ishon19 Jan 23, 2025
9a1e314
tools: fix tools-deps-update
lemire Jan 23, 2025
ad39367
test: enforce strict mode in test-zlib-const
Trott Jan 24, 2025
e039f2b
tools: do not throw on missing `create-release-proposal.sh`
aduh95 Jan 24, 2025
3bc8d27
test: add missing test for env file
JonasBa Jan 24, 2025
4f0cf47
test: add test that uses multibyte for path and resolves modules
yamachu Jan 22, 2025
e3b69e5
src: fix build with GCC 15
tjuhaszrh Jan 25, 2025
627f299
doc: fix typo in example code for util.styleText
rmehner Jan 25, 2025
5b88d48
src: add default value for RSACipherConfig mode field
wooffie Jan 22, 2025
5e2dab7
module: fix bad `require.resolve` with option paths for `.` and `..`
dario-piotrowicz Jan 25, 2025
b514438
doc: add note regarding commit message trailers
dario-piotrowicz Jan 26, 2025
c0fad18
src: add nullptr handling from X509_STORE_new()
wooffie Jan 22, 2025
792ce98
test: do not use common.isMainThread
lpinca Jan 26, 2025
f9d6e35
test: cleanup and simplify test-crypto-aes-wrap
jasnell Jan 26, 2025
33ee464
doc: improve accessibility of expandable lists
aduh95 Jan 26, 2025
53e4dc2
doc: add "Skip to content" button
aduh95 Jan 26, 2025
d4ca38f
deps: macro ENODATA is deprecated in libc++
zcbenz Jan 26, 2025
b0ab483
doc: fix styles of the expandable TOC
aduh95 Jan 26, 2025
11b82de
test: use strict mode in global setters test
Trott Jan 27, 2025
e121d7d
test: fix invalid common.mustSucceed() usage
lpinca Jan 27, 2025
12744c1
test: reduce number of written chunks
lpinca Jan 27, 2025
6207b29
doc: move anatoli to emeritus
mhdawson Jan 27, 2025
6afee9e
meta: move one or more collaborators to emeritus
nodejs-github-bot Jan 27, 2025
e570044
tools: update doc to new version
nodejs-github-bot Dec 15, 2024
46ceb9d
deps: update timezone to 2025a
nodejs-github-bot Feb 4, 2025
d8eaf5b
build: fix compatibility with V8's `depot_tools`
richardlau Mar 7, 2025
bb1a61d
2025-03-13, Version 20.19.0 'Iron' (LTS)
marco-ippolito Mar 6, 2025
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
Prev Previous commit
Next Next commit
module: unflag --experimental-require-module
This unflags --experimental-require-module so require(esm) can be
used without the flag. For now, when require() actually encounters
an ESM, it will still emit an experimental warning. To opt out
of the feature, --no-experimental-require-module can be used.

There are some tests specifically testing ERR_REQUIRE_ESM. Some
of them are repurposed to test --no-experimental-require-module.
Some of them are modified to just expect loading require(esm) to
work, when it's appropriate.

PR-URL: #55085
Backport-PR-URL: #56927
Refs: #52697
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Marco Ippolito <marcoippolito54@gmail.com>
Reviewed-By: Rafael Gonzaga <rafael.nunu@hotmail.com>
Reviewed-By: Yagiz Nizipli <yagiz@nizipli.com>
Reviewed-By: LiviaMedeiros <livia@cirno.name>
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
Reviewed-By: Filip Skokan <panva.ip@gmail.com>
Reviewed-By: Michael Dawson <midawson@redhat.com>
Reviewed-By: Richard Lau <rlau@redhat.com>
  • Loading branch information
joyeecheung authored and marco-ippolito committed Feb 11, 2025
commit 1ac1dda9a48d5da123f3e1d5d30d24ab5195961c
30 changes: 26 additions & 4 deletions doc/api/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -992,7 +992,13 @@ Use the specified file as a security policy.
### `--experimental-require-module`

<!-- YAML
added: v20.17.0
added:
- v22.0.0
- v20.17.0
changes:
- version: REPLACEME
pr-url: https://github.com/nodejs/node/pull/55085
description: This is now true by default.
-->

> Stability: 1.1 - Active Development
Expand Down Expand Up @@ -1555,6 +1561,24 @@ added: v16.6.0

Use this flag to disable top-level await in REPL.

### `--no-experimental-require-module`

<!-- YAML
added:
- v22.0.0
- v20.17.0
changes:
- version: REPLACEME
pr-url: https://github.com/nodejs/node/pull/55085
description: This is now false by default.
-->

> Stability: 1.1 - Active Development

Disable support for loading a synchronous ES module graph in `require()`.

See [Loading ECMAScript modules using `require()`][].

### `--no-extra-info-on-fatal-exception`

<!-- YAML
Expand Down Expand Up @@ -1764,9 +1788,7 @@ Identical to `-e` but prints the result.
added: v20.17.0
-->

This flag is only useful when `--experimental-require-module` is enabled.

If the ES module being `require()`'d contains top-level await, this flag
If the ES module being `require()`'d contains top-level `await`, this flag
allows Node.js to evaluate the module, try to locate the
top-level awaits, and print their location to help users find them.

Expand Down
23 changes: 16 additions & 7 deletions doc/api/errors.md
Original file line number Diff line number Diff line change
Expand Up @@ -2535,8 +2535,8 @@ object.

> Stability: 1 - Experimental

When trying to `require()` a [ES Module][] under `--experimental-require-module`,
a CommonJS to ESM or ESM to CommonJS edge participates in an immediate cycle.
When trying to `require()` a [ES Module][], a CommonJS to ESM or ESM to CommonJS edge
participates in an immediate cycle.
This is not allowed because ES Modules cannot be evaluated while they are
already being evaluated.

Expand All @@ -2550,8 +2550,8 @@ module, and should be done lazily in an inner function.

> Stability: 1 - Experimental

When trying to `require()` a [ES Module][] under `--experimental-require-module`,
the module turns out to be asynchronous. That is, it contains top-level await.
When trying to `require()` a [ES Module][], the module turns out to be asynchronous.
That is, it contains top-level await.

To see where the top-level await is, use
`--experimental-print-required-tla` (this would execute the modules
Expand All @@ -2561,12 +2561,20 @@ before looking for the top-level awaits).

### `ERR_REQUIRE_ESM`

> Stability: 1 - Experimental
<!-- YAML
changes:
- version: REPLACEME
pr-url: https://github.com/nodejs/node/pull/55085
description: require() now supports loading synchronous ES modules by default.
-->

> Stability: 0 - Deprecated

An attempt was made to `require()` an [ES Module][].

To enable `require()` for synchronous module graphs (without
top-level `await`), use `--experimental-require-module`.
This error has been deprecated since `require()` now supports loading synchronous
ES modules. When `require()` encounters an ES module that contains top-level
`await`, it will throw [`ERR_REQUIRE_ASYNC_MODULE`][] instead.

<a id="ERR_SCRIPT_EXECUTION_INTERRUPTED"></a>

Expand Down Expand Up @@ -3908,6 +3916,7 @@ An error occurred trying to allocate memory. This should never happen.
[`ERR_INVALID_ARG_TYPE`]: #err_invalid_arg_type
[`ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST`]: #err_missing_message_port_in_transfer_list
[`ERR_MISSING_TRANSFERABLE_IN_TRANSFER_LIST`]: #err_missing_transferable_in_transfer_list
[`ERR_REQUIRE_ASYNC_MODULE`]: #err_require_async_module
[`EventEmitter`]: events.md#class-eventemitter
[`MessagePort`]: worker_threads.md#class-messageport
[`Object.getPrototypeOf`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf
Expand Down
2 changes: 1 addition & 1 deletion doc/api/esm.md
Original file line number Diff line number Diff line change
Expand Up @@ -450,7 +450,7 @@ compatibility.
### `require`

The CommonJS module `require` currently only supports loading synchronous ES
modules when `--experimental-require-module` is enabled.
modules (that is, ES modules that do not use top-level `await`).

See [Loading ECMAScript modules using `require()`][] for details.

Expand Down
34 changes: 17 additions & 17 deletions doc/api/modules.md
Original file line number Diff line number Diff line change
Expand Up @@ -172,20 +172,17 @@ relative, and based on the real path of the files making the calls to

<!-- YAML
added: v20.17.0
changes:
- version: REPLACEME
pr-url: https://github.com/nodejs/node/pull/55085
description: require() now supports loading synchronous ES modules by default.
-->

> Stability: 1.1 - Active Development. Enable this API with the
> [`--experimental-require-module`][] CLI flag.

The `.mjs` extension is reserved for [ECMAScript Modules][].
Currently, if the flag `--experimental-require-module` is not used, loading
an ECMAScript module using `require()` will throw a [`ERR_REQUIRE_ESM`][]
error, and users need to use [`import()`][] instead. See
[Determining module system][] section for more info
See [Determining module system][] section for more info
regarding which files are parsed as ECMAScript modules.

If `--experimental-require-module` is enabled, and the ECMAScript module being
loaded by `require()` meets the following requirements:
`require()` only supports loading ECMAScript modules that meet the following requirements:

* The module is fully synchronous (contains no top-level `await`); and
* One of these conditions are met:
Expand All @@ -194,8 +191,8 @@ loaded by `require()` meets the following requirements:
3. The file has a `.js` extension, the closest `package.json` does not contain
`"type": "commonjs"`, and the module contains ES module syntax.

`require()` will load the requested module as an ES Module, and return
the module namespace object. In this case it is similar to dynamic
If the ES Module being loaded meet the requirements, `require()` can load it and
return the module namespace object. In this case it is similar to dynamic
`import()` but is run synchronously and returns the name space object
directly.

Expand All @@ -214,7 +211,7 @@ class Point {
export default Point;
```

A CommonJS module can load them with `require()` under `--experimental-detect-module`:
A CommonJS module can load them with `require()`:

```cjs
const distance = require('./distance.mjs');
Expand Down Expand Up @@ -243,13 +240,19 @@ conventions. Code authored directly in CommonJS should avoid depending on it.
If the module being `require()`'d contains top-level `await`, or the module
graph it `import`s contains top-level `await`,
[`ERR_REQUIRE_ASYNC_MODULE`][] will be thrown. In this case, users should
load the asynchronous module using `import()`.
load the asynchronous module using [`import()`][].

If `--experimental-print-required-tla` is enabled, instead of throwing
`ERR_REQUIRE_ASYNC_MODULE` before evaluation, Node.js will evaluate the
module, try to locate the top-level awaits, and print their location to
help users fix them.

Support for loading ES modules using `require()` is currently
experimental and can be disabled using `--no-experimental-require-module`.
When `require()` actually encounters an ES module for the
first time in the process, it will emit an experimental warning. The
warning is expected to be removed when this feature stablizes.

## All together

<!-- type=misc -->
Expand Down Expand Up @@ -279,8 +282,7 @@ require(X) from module at path Y

MAYBE_DETECT_AND_LOAD(X)
1. If X parses as a CommonJS module, load X as a CommonJS module. STOP.
2. Else, if `--experimental-require-module` is
enabled, and the source code of X can be parsed as ECMAScript module using
2. Else, if the source code of X can be parsed as ECMAScript module using
<a href="esm.md#resolver-algorithm-specification">DETECT_MODULE_SYNTAX defined in
the ESM resolver</a>,
a. Load X as an ECMAScript module. STOP.
Expand Down Expand Up @@ -1196,9 +1198,7 @@ This section was moved to
[GLOBAL_FOLDERS]: #loading-from-the-global-folders
[`"main"`]: packages.md#main
[`"type"`]: packages.md#type
[`--experimental-require-module`]: cli.md#--experimental-require-module
[`ERR_REQUIRE_ASYNC_MODULE`]: errors.md#err_require_async_module
[`ERR_REQUIRE_ESM`]: errors.md#err_require_esm
[`ERR_UNSUPPORTED_DIR_IMPORT`]: errors.md#err_unsupported_dir_import
[`MODULE_NOT_FOUND`]: errors.md#module_not_found
[`__dirname`]: #__dirname
Expand Down
6 changes: 2 additions & 4 deletions doc/api/packages.md
Original file line number Diff line number Diff line change
Expand Up @@ -172,8 +172,7 @@ There is the CommonJS module loader:
* It treats all files that lack `.json` or `.node` extensions as JavaScript
text files.
* It can only be used to [load ECMASCript modules from CommonJS modules][] if
the module graph is synchronous (that contains no top-level `await`) when
`--experimental-require-module` is enabled.
the module graph is synchronous (that contains no top-level `await`).
When used to load a JavaScript text file that is not an ECMAScript module,
the file will be loaded as a CommonJS module.

Expand Down Expand Up @@ -662,8 +661,7 @@ specific to least specific as conditions should be defined:
* `"require"` - matches when the package is loaded via `require()`. The
referenced file should be loadable with `require()` although the condition
matches regardless of the module format of the target file. Expected
formats include CommonJS, JSON, native addons, and ES modules
if `--experimental-require-module` is enabled. _Always mutually
formats include CommonJS, JSON, native addons, and ES modules. _Always mutually
exclusive with `"import"`._
* `"module-sync"` - matches no matter the package is loaded via `import`,
`import()` or `require()`. The format is expected to be ES modules that does
Expand Down
2 changes: 1 addition & 1 deletion lib/internal/modules/cjs/loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -435,7 +435,6 @@ function initializeCJS() {
require('internal/modules/run_main').executeUserEntryPoint;

if (getOptionValue('--experimental-require-module')) {
emitExperimentalWarning('Support for loading ES Module in require()');
Module._extensions['.mjs'] = loadESMFromCJS;
}
}
Expand Down Expand Up @@ -1341,6 +1340,7 @@ function loadESMFromCJS(mod, filename) {
// ESM won't be accessible via process.mainModule.
setOwnProperty(process, 'mainModule', undefined);
} else {
emitExperimentalWarning('Support for loading ES Module in require()');
const {
wrap,
namespace,
Expand Down
10 changes: 0 additions & 10 deletions lib/internal/modules/esm/load.js
Original file line number Diff line number Diff line change
Expand Up @@ -152,11 +152,6 @@ async function defaultLoad(url, context = kEmptyObject) {

validateAttributes(url, format, importAttributes);

// Use the synchronous commonjs translator which can deal with cycles.
if (format === 'commonjs' && getOptionValue('--experimental-require-module')) {
format = 'commonjs-sync';
}

return {
__proto__: null,
format,
Expand Down Expand Up @@ -206,11 +201,6 @@ function defaultLoadSync(url, context = kEmptyObject) {

validateAttributes(url, format, importAttributes);

// Use the synchronous commonjs translator which can deal with cycles.
if (format === 'commonjs' && getOptionValue('--experimental-require-module')) {
format = 'commonjs-sync';
}

return {
__proto__: null,
format,
Expand Down
8 changes: 4 additions & 4 deletions lib/internal/modules/esm/loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -364,15 +364,15 @@ class ModuleLoader {

defaultLoadSync ??= require('internal/modules/esm/load').defaultLoadSync;
const loadResult = defaultLoadSync(url, { format, importAttributes });
const {
format: finalFormat,
source,
} = loadResult;

// Use the synchronous commonjs translator which can deal with cycles.
const finalFormat = loadResult.format === 'commonjs' ? 'commonjs-sync' : loadResult.format;

if (finalFormat === 'wasm') {
assert.fail('WASM is currently unsupported by require(esm)');
}

const { source } = loadResult;
const isMain = (parentURL === undefined);
const wrap = this.#translate(url, finalFormat, source, isMain);
assert(wrap instanceof ModuleWrap, `Translator used for require(${url}) should not be async`);
Expand Down
1 change: 1 addition & 0 deletions lib/internal/modules/esm/module_job.js
Original file line number Diff line number Diff line change
Expand Up @@ -353,6 +353,7 @@ class ModuleJobSync extends ModuleJobBase {
}

runSync() {
// TODO(joyeecheung): add the error decoration logic from the async instantiate.
this.module.instantiateSync();
setHasStartedUserESMExecution();
const namespace = this.module.evaluateSync();
Expand Down
6 changes: 2 additions & 4 deletions lib/internal/modules/esm/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -75,17 +75,15 @@ function initializeDefaultConditions() {
const userConditions = getOptionValue('--conditions');
const noAddons = getOptionValue('--no-addons');
const addonConditions = noAddons ? [] : ['node-addons'];

const moduleConditions = getOptionValue('--experimental-require-module') ? ['module-sync'] : [];
defaultConditions = ObjectFreeze([
'node',
'import',
...moduleConditions,
...addonConditions,
...userConditions,
]);
defaultConditionsSet = new SafeSet(defaultConditions);
if (getOptionValue('--experimental-require-module')) {
defaultConditionsSet.add('module-sync');
}
}

/**
Expand Down
5 changes: 3 additions & 2 deletions src/node_options.cc
Original file line number Diff line number Diff line change
Expand Up @@ -374,9 +374,10 @@ EnvironmentOptionsParser::EnvironmentOptionsParser() {
&EnvironmentOptions::print_required_tla,
kAllowedInEnvvar);
AddOption("--experimental-require-module",
"Allow loading explicit ES Modules in require().",
"Allow loading synchronous ES Modules in require().",
&EnvironmentOptions::require_module,
kAllowedInEnvvar);
kAllowedInEnvvar,
true);
AddOption("--diagnostic-dir",
"set dir for all output files"
" (default: current working directory)",
Expand Down
2 changes: 1 addition & 1 deletion src/node_options.h
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ class EnvironmentOptions : public Options {
std::vector<std::string> conditions;
bool detect_module = true;
bool print_required_tla = false;
bool require_module = false;
bool require_module = true;
std::string dns_result_order;
bool enable_source_maps = false;
bool experimental_eventsource = false;
Expand Down
11 changes: 9 additions & 2 deletions test/es-module/test-cjs-esm-warn.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
// Previously, this tested that require(esm) throws ERR_REQUIRE_ESM, which is no longer applicable
// since require(esm) is now supported. The test has been repurposed to ensure that the old behavior
// is preserved when the --no-experimental-require-module flag is used.
'use strict';

const { spawnPromisified } = require('../common');
Expand All @@ -22,7 +25,9 @@ describe('CJS ↔︎ ESM interop warnings', { concurrency: true }, () => {
fixtures.path('/es-modules/package-type-module/cjs.js')
);
const basename = 'cjs.js';
const { code, signal, stderr } = await spawnPromisified(execPath, [requiringCjsAsEsm]);
const { code, signal, stderr } = await spawnPromisified(execPath, [
'--no-experimental-require-module', requiringCjsAsEsm,
]);

assert.ok(
stderr.replaceAll('\r', '').includes(
Expand All @@ -48,7 +53,9 @@ describe('CJS ↔︎ ESM interop warnings', { concurrency: true }, () => {
fixtures.path('/es-modules/package-type-module/esm.js')
);
const basename = 'esm.js';
const { code, signal, stderr } = await spawnPromisified(execPath, [requiringEsm]);
const { code, signal, stderr } = await spawnPromisified(execPath, [
'--no-experimental-require-module', requiringEsm,
]);

assert.ok(
stderr.replace(/\r/g, '').includes(
Expand Down
7 changes: 4 additions & 3 deletions test/es-module/test-esm-detect-ambiguous.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -402,15 +402,16 @@ describe('Module syntax detection', { concurrency: !process.env.TEST_PARALLEL },
});
});

// Validate temporarily disabling `--abort-on-uncaught-exception`
// while running `containsModuleSyntax`.
// Checks the error caught during module detection does not trigger abort when
// `--abort-on-uncaught-exception` is passed in (as that's a caught internal error).
// Ref: https://github.com/nodejs/node/issues/50878
describe('Wrapping a `require` of an ES module while using `--abort-on-uncaught-exception`', () => {
it('should work', async () => {
const { code, signal, stdout, stderr } = await spawnPromisified(process.execPath, [
'--abort-on-uncaught-exception',
'--no-warnings',
'--eval',
'assert.throws(() => require("./package-type-module/esm.js"), { code: "ERR_REQUIRE_ESM" })',
'require("./package-type-module/esm.js")',
], {
cwd: fixtures.path('es-modules'),
});
Expand Down
1 change: 1 addition & 0 deletions test/es-module/test-esm-loader-hooks.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -739,6 +739,7 @@ describe('Loader hooks', { concurrency: true }, () => {

describe('should use hooks', async () => {
const { code, signal, stdout, stderr } = await spawnPromisified(process.execPath, [
'--no-experimental-require-module',
'--import',
fixtures.fileURL('es-module-loaders/builtin-named-exports.mjs'),
fixtures.path('es-modules/require-esm-throws-with-loaders.js'),
Expand Down
Loading