Skip to content

fix: honour useDefineForClassFields instead of inverting it - #742

Merged
Brooooooklyn merged 1 commit into
oxc-project:mainfrom
cjnoname:fix/use-define-for-class-fields
Sep 12, 2026
Merged

Brooooooklyn merged 1 commit into
oxc-project:mainfrom
cjnoname:fix/use-define-for-class-fields

Conversation

@cjnoname

@cjnoname cjnoname commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Summary

useDefineForClassFields selects [[Define]] semantics for public class fields: the field is installed with Object.defineProperty, so a setter inherited from a base class is not called. Oxc's setPublicClassFields assumption selects the opposite — [[Set]] semantics, a plain assignment — so it has to be the negation of the tsconfig option.

It was assigned it directly, which inverts every explicit setting:

assumptions: CompilerAssumptions {
    set_public_class_fields: use_define_for_class_fields,   // inverted
    ...
},

useDefineForClassFields: false is what NestJS, MobX, TypeORM and every other decorator/DI based framework asks for, and oxc-node was doing the exact opposite of it.

The default was wrong too. It came from unwrap_or_default(), i.e. always false, ignoring target. TypeScript defaults the option to true from target: ES2022 — the first target with native class fields — and to false below that. An unset target also means true: since TypeScript 6, tsc defaults the target to the stable ECMAScript version preceding ESNext (before TypeScript 6 it defaulted to ES5, which meant false; target: es5 itself was removed in TypeScript 7).

Two companion behaviours of [[Set]] mode come along for fidelity:

  • tsc drops class fields without an initializer instead of assigning undefined through the prototype chain (which would fire an inherited setter). Oxc only does that under removeClassFieldsWithoutInitializer, whose own documentation says to pair it with setPublicClassFields — so the two are now set together.
  • The class-properties loose option stays false: besides public fields it also lowers #private fields to string-keyed properties, leaking their names and freezing them with Object.freeze — something tsc never does. The assumption alone selects [[Set]] for public fields (the transformer ORs the two), so loose was never needed for the fix.

Verification

Ground truth is tsc from this repository's own devDependencies (7.0.2 at the time of writing), compiling

class Base {
  set x(value: unknown) {
    (this as any).setterCalled = true;
  }
}
export class Derived extends Base {
  x = 1;
}
target useDefineForClassFields tsc before after
ES2022 unset [[Define]] [[Define]] [[Define]]
ES2022 true [[Define]] [[Set]] [[Define]]
ES2022 false [[Set]] [[Define]] [[Set]]
ESNext unset [[Define]] [[Define]] [[Define]]
ESNext true [[Define]] [[Set]] [[Define]]
ESNext false [[Set]] [[Define]] [[Set]]
ES2017 unset [[Set]] [[Define]] [[Set]]
ES2017 true [[Define]] [[Set]] [[Define]]
ES2017 false [[Set]] [[Define]] [[Set]]
ES5 unset [[Set]] (TS≤5 config; tsc 7 rejects es5 outright) [[Define]] [[Set]]
ES5 true [[Define]] (ditto) [[Set]] [[Define]]
ES5 false [[Set]] (ditto) [[Define]] [[Set]]
(none) unset [[Define]] (TS≥6 default target) [[Define]] [[Define]]

All thirteen combinations now agree with tsc. Fields without an initializer were checked too: tsc elides them under [[Set]] and defines them as undefined under [[Define]], legacy decorators on elided fields still run, and #private fields stay private and mutation survives Object.freeze under both — all pinned by the new spec.

packages/integrate-vitest/__tests__/class-fields.spec.ts pins each row by observing whether the inherited setter runs, so the direction is asserted rather than just "the two settings differ".

integrate-module (21/21), integrate-module-bundler (22/22 — it sets useDefineForClassFields: false and exercises NestJS decorators and DI) and integrate-vitest (55/55, 19 of them the new class-fields specs) pass with OXC_TRANSFORM_ALL both set and unset. cargo clippy --all-targets --all-features -- -D warnings, cargo fmt --check and vp check are clean. No napi surface change, so the generated bindings are untouched.

Compatibility

This changes the emitted semantics for any project that set useDefineForClassFields explicitly, or that targets below ES2022 — in every case to what tsc produces for the same tsconfig, which is the point.

Note

This branch is rebased on current main (past #569's per-file tsconfig discovery, which changed the oxc_transform signature this code touches). #743 touches oxc_transform a few lines away and still applies on its own; its helper-imports fixture uses target: ES2022 with the option unset, which is [[Define]] both before and after this change, so the two remain independent of merge order.

cjnoname added a commit to cjnoname/oxc-node that referenced this pull request Sep 3, 2026
The fixture forced a helper with `useDefineForClassFields: false`, which is
`[[Define]]` under the current mapping but `[[Set]]` once oxc-project#742 corrects it — and
`[[Set]]` needs no helper at all, so the fixture would stop testing anything and
the assertion would fail.

`target: ES2022` with the option left unset is `[[Define]]` both ways: it is
TypeScript's own default for that target, and it is what `unwrap_or_default()`
produces today. Verified against both builds.
cjnoname added a commit to cjnoname/oxc-node that referenced this pull request Sep 3, 2026
…lass-field polarity

The spec asserted the transformed dependency reports `setterCalled: true`, which
holds under the current `useDefineForClassFields` mapping and flips once oxc-project#742
corrects it. It now runs the dependency under both values of the option and
asserts they disagree when it was transformed and agree when it was not, which is
true under either mapping.
@cjnoname

cjnoname commented Sep 3, 2026

Copy link
Copy Markdown
Contributor Author

Cross-PR note, found by merging all three of these together and running the suites rather than assuming they compose.

They do not conflict textually — git merges all three cleanly — but #742 changes the class-field semantics that fixtures in the other two relied on, so whichever landed second would have had red CI:

Both fixtures are now independent of it:

With those in place, all three merged together: 73/73 on Node.js 22.22.3, 24.8.0, 24.20.0, 26.2.0 and 26.8.1, 71 passed + 2 skipped on 22.18.0 and 24.7.0 (the two specs that need the synchronous hooks), and the engines floor job green on 20.19.0. Merge order does not matter now.

No product code changed for this — only the two fixtures.

@Brooooooklyn
Brooooooklyn force-pushed the fix/use-define-for-class-fields branch 2 times, most recently from 9edd4d6 to d7d9bf6 Compare September 12, 2026 08:53
@Brooooooklyn

Copy link
Copy Markdown
Member

Maintainer pass over the branch (rebased onto current main, one amended commit, authorship unchanged). Three substantive changes, each verified against tsc 7.0.2 from this repo's devDependencies:

  1. Rebase fix (compile break): feat: discover the nearest tsconfig.json that claims each file #569 changed oxc_transform to take Option<&CompilerOptions> per file, so the helper's Option<&'static CompilerOptions> parameter no longer compiled after a clean textual merge (E0521: borrowed data escapes). Dropped the 'static.

  2. No-target default flipped to [[Define]]: the original table row claimed no target → [[Set]] "because tsc then defaults the target to ES5". That was true through TypeScript 5, but TypeScript 6/7 default target to the stable ECMAScript version preceding ESNext (and tsc 7 rejects target: es5 with TS5108). Empirically, this repo's tsc compiles a no-target fixture to native class fields — [[Define]]. The pre-PR code accidentally agreed (unwrap_or_default() → inverted mapping), and the PR as written would have flipped no-target projects to [[Set]], regressing them. Explicit targets below ES2022 still default to [[Set]], matching tsc for those configs.

  3. loose stays false; removeClassFieldsWithoutInitializer pairs with [[Set]]: two fidelity gaps found by probing the built loader against tsc output:

    • With useDefineForClassFields: false, tsc elides fields without an initializer, but the transform was emitting this.field = void 0, which fires an inherited setter. Now remove_class_fields_without_initializer follows the same negated value, as oxc's docs for that option recommend. Legacy decorators on such elided fields still run (pinned).
    • The original commit also set class-properties loose: true in [[Set]] mode. In oxc, loose additionally lowers #private fields to string-keyed properties (__private_0_x): they leak via Object.getOwnPropertyNames and throw on mutation after Object.freeze, while tsc keeps them WeakMap-private under both option values. Since the transformer ORs loose with the setPublicClassFields assumption, the assumption alone selects [[Set]] for public fields and loose was never needed.

The spec grew from 13 to 19 cases: the two corrected defaults (no target, no tsconfig at all), plus new pins for field elision, decorator-on-elided-field, and #private privacy/freeze behaviour under both option values. Full suites pass with OXC_TRANSFORM_ALL set and unset; clippy, cargo fmt --check and vp check are clean.

`useDefineForClassFields` selects `[[Define]]` semantics for public class fields —
the field is installed with `Object.defineProperty`, so an inherited setter is not
called. Oxc's `setPublicClassFields` assumption selects the opposite, `[[Set]]`
semantics, so it has to be the negation of the tsconfig option. It was assigned it
directly, which inverted every explicit setting:

| `target` | `useDefineForClassFields` | tsc          | before       |
| -------- | ------------------------- | ------------ | ------------ |
| ES2022   | unset                     | `[[Define]]` | `[[Define]]` |
| ES2022   | `true`                    | `[[Define]]` | `[[Set]]`    |
| ES2022   | `false`                   | `[[Set]]`    | `[[Define]]` |
| ES2017   | unset                     | `[[Set]]`    | `[[Define]]` |
| ES2017   | `true`                    | `[[Define]]` | `[[Set]]`    |
| ES2017   | `false`                   | `[[Set]]`    | `[[Define]]` |

`useDefineForClassFields: false` is what NestJS, MobX, TypeORM and every other
decorator-based framework asks for, and it was doing the exact opposite.

The default was wrong too. It came from `unwrap_or_default()`, i.e. always
`false`, while TypeScript defaults the option to `true` from `target: ES2022` —
the first target with native class fields. An unset `target` also means `true`:
since TypeScript 6, `tsc` defaults the target to the stable ECMAScript version
preceding `ESNext` (before TypeScript 6 it defaulted to `ES5`, which meant
`false`; `target: es5` itself was removed in TypeScript 7).

Two companion behaviours of `[[Set]]` mode come along for fidelity:

- `tsc` drops class fields without an initializer instead of assigning
  `undefined` through the prototype chain, which would fire an inherited setter.
  oxc only does that under `removeClassFieldsWithoutInitializer`, whose docs say
  to pair it with `setPublicClassFields` — so the two are now set together.
- The class-properties `loose` option stays `false`: besides public fields it
  also lowers `#private` fields to string-keyed properties, leaking their names
  and freezing them with `Object.freeze` — something `tsc` never does. The
  assumption alone selects `[[Set]]` for public fields (the transformer ORs the
  two), so `loose` was never needed for the fix.

Verified against `tsc` from the repository's own devDependencies: every
combination of `target` in ES2022/ESNext/ES2017/ES5 and the option unset, `true`
and `false` agrees, plus the no-target and no-tsconfig cases.
`packages/integrate-vitest/__tests__/class-fields.spec.ts` pins each of them by
observing whether the inherited setter runs, and pins the field-elision,
legacy-decorator and `#private`-field behaviour that comes with them.

This changes the emitted semantics for any project that set the option
explicitly, or that targets below ES2022 — in every case to what `tsc` produces
for the same tsconfig.
@Brooooooklyn
Brooooooklyn force-pushed the fix/use-define-for-class-fields branch from d7d9bf6 to 0a0a617 Compare September 12, 2026 09:03
@Brooooooklyn
Brooooooklyn merged commit 9a4c088 into oxc-project:main Sep 12, 2026
53 checks passed
Brooooooklyn pushed a commit to cjnoname/oxc-node that referenced this pull request Sep 12, 2026
The fixture forced a helper with `useDefineForClassFields: false`, which is
`[[Define]]` under the current mapping but `[[Set]]` once oxc-project#742 corrects it — and
`[[Set]]` needs no helper at all, so the fixture would stop testing anything and
the assertion would fail.

`target: ES2022` with the option left unset is `[[Define]]` both ways: it is
TypeScript's own default for that target, and it is what `unwrap_or_default()`
produces today. Verified against both builds.
Brooooooklyn added a commit that referenced this pull request Sep 12, 2026
## Summary

When a transform needs a runtime helper, oxc injects an import of it and
picks `import` or `require()` based on the module kind of the source.
For `.js`, `.jsx`, `.ts` and `.tsx` that module kind is
`ModuleKind::Unambiguous`, so oxc infers it from the presence of
`import`/`export` syntax — and a file that happens to have none is
treated as a script, which gets `require()`.

Node.js decides from the nearest `package.json` instead. A file with no
module syntax inside a `"type": "module"` package is therefore executed
as an ES module with a `require()` call in it:

```jsonc
// package.json
{ "type": "module" }
```

```ts
// a.ts — no import or export anywhere in the file
class Base {
  set field(value: unknown) {
    (this as any).setterCalled = true;
  }
}
class Derived extends Base {
  field = 1;
}
console.log(new Derived().field);
```

```
$ node --import @oxc-node/core/register ./a.ts
var _defineProperty = require("@oxc-node/core/helpers/defineProperty");
                      ^
ReferenceError: require is not defined in ES module scope, you can use import instead
```

Any transform that needs a helper hits this — lowered class fields,
decorators, `using`, object rest/spread, and so on — as long as the file
itself has no `import` or `export`.

## Fix

The `load` hook already knows which it is, because Node.js reports the
format, so it passes that down and the parser is told the module kind
outright instead of guessing from the syntax:

```rust
let source_type = SourceType::from_path(src_path).unwrap_or_default().with_module(is_es_module);
```

The `pirates` hook and the public `transform()` API keep inferring it:
both target CommonJS, where `require()` is the correct output.

Only files that have no module syntax at all change — anything with an
`import` or `export` was already resolved to an ES module by the parser,
and `with_module(false)` is a no-op.

## Verification

`packages/integrate-vitest/__tests__/helper-imports.spec.ts` covers both
module kinds, with and without module syntax:

| package `type` | entry | module syntax | before | after |
| --- | --- | --- | --- | --- |
| `module` | `.ts` | none | `ReferenceError` | ok |
| `module` | `.mts` | none | ok | ok |
| `module` | `.ts` | has `export` | ok | ok |
| `commonjs` | `.ts` | none | ok | ok |
| `commonjs` | `.cts` | none | ok | ok |

plus an imported (rather than entry-point) module with no module syntax.

`integrate-module` (21/21), `integrate-module-bundler` (22/22) and
`integrate-vitest` pass on Node.js 22.23.2 and 24.20.0 with
`OXC_TRANSFORM_ALL` both set and unset. `cargo clippy --all-targets
--all-features -- -D warnings` and `pnpm lint` are clean. No napi
surface change, so the generated bindings are untouched.

## Note

#742 touches `oxc_transform` a few lines away. The two are logically
independent; whichever lands second needs a trivial rebase.

---------

Co-authored-by: LongYinan <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants