Repository navigation
fix(core): run files whose only imports and exports are type-only as CommonJS - #910
Conversation
9e55fb1 to
bda8cec
Compare
|
@codex review |
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: bda8ceca66
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
- Don't compile a file whose only imports and exports are type-only as CommonJS when Node.js runs it as an ES module whatever its syntax: a `.mts` file, or a `.ts` file in a "type": "module" package. The `pirates` hook and `transform()` pass `is_es_module: false` for every file, so a `require()`d one ran as CommonJS, and ran a second time when it was also imported. - Keep such a file an ES module when it binds `require`, `module`, `exports`, `__filename` or `__dirname` with `let`, `const`, `using` or `class`, as Node.js' syntax detection does. It crashed with ERR_REQUIRE_CYCLE_MODULE. - Skip the second `parsed_as_esm` call on the load-hook path. - Test both cases and the `transform()` output; README: type-only imports and exports don't make an importer file an ES module. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 381db7196c
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
… CommonJS - Don't compile a type-only file as CommonJS for `require()` when its tsconfig sets an ES `module`: the resolve hook reports it as an ES module for `import`, so `require()` and `import()` of the same file ran it twice. The check shares `is_es_module_setting` with `default_module_from_tsconfig`. - Treat `import type X = require()` as erased: it no longer vetoes ES module detection, so a file that also has top-level await runs as an ES module again instead of failing the CommonJS transform, and it counts as a type-only declaration, so alone it stays CommonJS. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c72d3e1fdf
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
…ommonJS The importer decides a file's format from its syntax and package.json alone, whatever the tsconfig says. Under an ES tsconfig `module`, the previous commit kept a type-only file's source type a module on that path too, so a helper it needed (a legacy decorator's, for one) was emitted as an import, which the importer's CommonJS wrapper cannot run. Apply the tsconfig check only outside the importer. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 775c46a854
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
An alias such as `import C = N.C` compiles to a plain binding, not to `require()`, but it vetoed ES module detection like `import x = require()`. With a type-only import no longer counting as module syntax, a file with such an alias and top-level await went to the CommonJS transform, which rejects the await. Only an external module reference now vetoes. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e093b02ad4
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
… (#911) #908 and #910 are merged; this branch is up to date with `main`. AI generated, but ran the fix against a full live CJS project. The project uses `package.json` type as `commonjs` with all file extensions as `.ts` running NestJS 12 (ESM) and tests mocked using nodes test module `mock.method`. I needed to upgrade to TypeScript 7.0.2 from 5.9.3 which ts-node doesn't support. tsx and other don't support legacy TypeScript decorators (or rather `emitDecoratorMetadata`, which NestJS uses). I'm not aware of any other JIT that supports CJS projects needing emit decorator metadata on TS7+. Closes #905 ### Problem In a `"type": "commonjs"` package, a `.ts` file that uses `import`/`export` runs as an ES module under oxc-node, even when tsconfig compiles it to CommonJS. Its namespace object is then frozen, so `mock.method()` from `node:test` can't replace its exports. Under `tsc` it can. ``` package.json "type": "commonjs", tsconfig "module": "node20" test.ts: import * as lib from "../src/lib"; mock.method(lib, "compute", …) main this PR tsc oxnode --test TypeError: Cannot redefine property pass pass ``` Node.js' own type stripping doesn't run this file as an ES module either: it rejects it with `SyntaxError: Cannot use import statement outside a module`. ### Fix A file with ES module syntax is compiled to CommonJS the way `tsc` compiles it when all of these hold: - its package is `"type": "commonjs"` - its tsconfig `module` is `commonjs`, `node16`, `node18`, `node20` or `nodenext` (any case) - its extension is ambiguous: `.ts`, `.tsx`, `.js`, `.jsx` or none - it uses neither `import.meta` nor top-level await, which have no CommonJS form - it declares none of the names the CommonJS wrapper or the helpers below use: `exports`, `require`, `module`, `__filename`, `__dirname`, `__importDefault`, `__importStar`, `__exportStar` Anywhere else, such as a package with no `"type"`, `"type": "module"`, or an ES `module` setting, the file runs as an ES module, as before. Switching a project's `"type"` to `"module"` turns the compilation off. The output has `tsc`'s shape. It's built from the module runner transform's output: - An export of a local that is never reassigned is a plain data property (`exports.a = void 0; … exports.a = a;`). It's writable, so `mock.method(namespace, "a")` reaches every importer. A hoisted function is exported up front. - A reassigned local, a decorated class and a namespace are `exports.a` itself, as `tsc` emits them: live, writable, and `undefined` (not a TDZ error) when an import cycle reads them early. Re-exports stay live through getters, in the form `cjs-module-lexer` detects, defined after their `require()`. A reassigned local exported under two names, declared by destructuring or set to an anonymous function also gets a getter. - An anonymous default function is hoisted as `default_1` and exported up front. A side-effect import is a bare `require()`. - A named import is `require()`'s result. Default and namespace imports go through `__importDefault`/`__importStar`, `export *` through `__exportStar`, and `import()` stays `import()`. - On the load-hook path the compiled source is returned with `format: "commonjs"`, so an ES module importer gets the named exports. The compiled code `require()`s `./lib.js` where the source imported `./lib.js`. So `Module._resolveFilename` in `register.mjs` falls back to the TypeScript source (`.js` → `.ts`/`.tsx`, `.jsx` → `.tsx`/`.ts`, `.mjs` → `.mts`, `.cjs` → `.cts`). When the output is missing, `./x.js` also finds `x.jsx` and `./x.jsx` finds `x.js`. For a TypeScript importer outside `node_modules`, it also prefers the source over compiled output sitting beside it, as the ES module resolver does since #840, and `config.ts` over `config.json` for `./config`; a file inside `node_modules` keeps its compiled `.js`. A bare request tries tsconfig `paths` and `baseUrl` first, through the new `tsconfigPathCandidates` binding. The hook thread's helper tag is registered on the main thread too, so the compiled files can `require()` their helpers. Under `node16`, `node18` and `nodenext`, the resolve hook no longer reports every `.ts` file as an ES module; the package's `"type"` decides, as it does for `tsc`. #908 made that change and is merged. ### Behaviour changes These apply only to projects with `"type": "commonjs"` and one of the `module` settings above: - A file with `import`/`export` now runs as CommonJS. An ES module's default import of it is `module.exports`, with the file's default export at `.default`, the same as TypeScript types it under `nodenext`. - An ES module importer doesn't see names the file re-exports with `export *` from another TypeScript file: Node.js only follows re-exports into `.js` and `.cjs` files. - Under `node16`/`node18`/`nodenext`, a `.ts` file without module syntax is CommonJS, also when an ES module imports it. - An ES module importer's named imports are a snapshot taken when the file finishes loading, as for any CommonJS module. - The compiled file's dependencies resolve with the `require` condition, as under `tsc`; a package whose `exports` offers only `import` fails. - Node.js caches a relative `require()` per directory and request, so when a `.js` file and a `.ts` file in one directory both `require("./lib.js")` next to `lib.ts`, whichever asks first decides which file both get. - `require()` of an ES module from a compiled file loaded through the module hooks needs nodejs/node#59679 (22.22.3 on the 22.x line). Earlier versions fail with `TypeError: Cannot read properties of undefined (reading 'exports')`. The README has a new "ES module syntax in a CommonJS package" section covering this. ### Tests - Rust: `commonjs_lowering` covers each `module` setting, the output shape (reassigned exports, side-effect imports, the anonymous default function), the cases that stay ES modules (`import.meta`, reserved names, `esnext`, `preserve`, `.mts`, a package without `"type"`), and type-only or `declare`d reserved names that still compile. - New `packages/integrate-commonjs` package (`"type": "commonjs"`, `module: nodenext`, run with `oxnode --test`), 20 tests: - mocking a namespace export, a function and a class, with importers seeing the mock - live reassigned exports - default, star and CommonJS imports - `.js` names finding `.ts`, with the source preferred over compiled output beside it - an ES module importer's named and default imports - import cycles: hoisted functions, and `undefined` for a reassigned `let`, a decorated class, a namespace and a re-export read early - a namespace import of a CommonJS class keeping its static members - a tsconfig `paths` alias and the `.js` → `.jsx` fallback - stack trace lines - `import.meta` and top-level await staying ES modules - runtime helpers - `commonjs.test.ts` fails to load on `main`. `helpers.test.ts` passes on both and guards what must not change. - `commonjs-lowering.spec.ts` (vitest) covers `paths` and `baseUrl`, `config.ts` beside `config.json`, the `.js`/`.jsx` fallbacks, `node_modules` files and non-enumerable exports. - The #905 repro passes on Node.js 26.12.1 and 22.22.1. `vp run test` (643 vitest tests plus the three `node --test` packages), `cargo test`, clippy and fmt pass. --------- Co-authored-by: DArcy Rush <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: LongYinan <[email protected]>
AI generated, but ran the fix against a dummy repo locally.
Fixes #909
Summary
Type erasure removes
import typeand the other type-only declarations whole, soNode.js' type stripping runs a file whose only module syntax is type-only as CommonJS.
oxc-node ran it as an ES module, without
require,moduleorexports."type": "commonjs"unless noted)import type+require: entry point,require()d, or imported from.mtsrequire is not defined in ES module scopeexport type { … }(±from),export type *,export type X =,export interface,export default interface,export declare …"type"ReferenceErrorimport type+export =TS(1203)import { type X }, a value export,import.meta, top-level await,export {}, or alet/const/classnamedrequire/module/exports/__filename/__dirname.mts, or.tsin a"type": "module"package, loaded any wayFix
parsed_as_esmandhas_module_declarationskip declarations that type erasureremoves whole (
is_type_only_module_declaration).import { type X } from "x"stillcounts: it leaves
import {} from "x", which is module syntax to Node.js.oxc_transformcompiles such a file the way a.ctsfile is compiled: no trailingexport {}, helpers arerequire()d. This applies only to.ts/.tsx/.js/.jsxand extensionless files outside a
"type": "module"package, and not when the file'stsconfig sets an ES
module(the resolve hook reports those as ES modules). Theimporter ignores the tsconfig
module, as it always has, so there the switch stays.let/const/classstays ESM,as Node.js' syntax detection does.
import type X = require()is erased too, and an alias such asimport C = N.Cis aplain binding: neither holds the file to CommonJS the way
import x = require()does,so top-level await beside them still makes the file an ES module.
transform()output for such a file no longer ends inexport {};.@oxc-node/core/importerchanges the same way.On the #759 test
This replaces #759's
a file whose only module syntax is a type-only import runs as an ES module. That held while the output kept the injectedexport {}. Compiled as a.ctsfile is, nothing module-like is left, so the CommonJS path runs it and it getsrequire,moduleandexports, as under Node.js and tsc. The no-crash intent of#759 is still checked: every test asserts exit code 0.
Tests
.mtsimport /require()"type"import type+export =,require()dtype, value export,import.meta, TLA, enum, class, function, namespace with a value)require()of a type-only.mts, and of a.tsin a module package, stays ESMtransform()output:import typedropsexport {};import { type X }and.mtskeep itvar exportsstays CommonJSvar exports)require()+import()of a type-only.tsunder tsconfigmodule: esnextruns once, as ESMimport type X = require(): alone CommonJS, beside top-level await ESMmodule: esnext: type-only file with a legacy decorator runs as CommonJSimport C = N.Calias: beside top-level await ESM, besiderequireCommonJShelper-imports.spec.ts: commonjsentry.tswith a type-only importhelper-imports.spec.ts: 2 module rowsVerification
Node.js v26.13.0, darwin-arm64, branch merged with current main (#908 included):
vp run test(633 passed, 7 skipped),cargo test --all-features,cargo clippy --all-targets --all-features -- -D warnings,cargo fmt --check,vp fmt --checkandvp lintall pass. Against the first commit of this PR, therequire()of type-only ESM tests, the.mtstransform()row, 3 of theredeclaration rows, the
module: esnexttest, theimport type =+ await row and the importer testand the alias + await row fail at the commit before each fix; they cover six bugs Codex found in review.
Not covered
import { x } from "./file.ts") of such a filestill fails with
does not provide an export named, as on main (and for.cts):cjs-module-lexerreads the raw.ts, where theimport typeline stops it.Default imports and
require()work.export namespace N { export type T = number })still counts as module syntax, although Node.js strips it. Same as main.
require()of a.tsfile with no module syntax in a"type": "module"package runsas CommonJS. Same as main.