Skip to content

Ship the dual ESM/CJS entry and the CommonJS types (regressions 1 and 6) - #35

Open
codeKonami wants to merge 10 commits into
wayfinder/20-tooling-biomefrom
wayfinder/28-dual-entry
Open

codeKonami wants to merge 10 commits into
wayfinder/20-tooling-biomefrom
wayfinder/28-dual-entry

Conversation

@codeKonami

Copy link
Copy Markdown
Owner

Part of the 1.1.0 map (Carte : publier poker-hand-evaluator 1.1.0 rétrocompatible avec la 1.0.1), ticket Livrer la double entrée ESM/CJS et les types (régressions 1 et 6). Stacked on #34. It applies Double entrée ESM/CJS, Dual package hazard, Cibles d'exécution and Types publics. The UMD (#19), the deep-path shims (#29), CI (#21) and the tables (#33) are left to their own tickets.

Summary

Two tsdown entries, because a CommonJS file can only be module.exports = PokerHand when its entry has nothing but a default export:

src/index.ts      ─ esm ─▶ dist/index.mjs    export { PokerHand, HandRank, CompareResult, default }
                           dist/index.d.mts  the same, plus types Card, Rank, Suit
src/index.cjs.ts  ─ cjs ─▶ dist/index.cjs    module.exports = PokerHand
                           dist/index.d.cts  declare namespace PokerHand { … }  export = PokerHand

src/poker-hand.ts gets the merged namespace and the static properties that export = needs. Oxc copies the namespace into both declaration files as written, so #11's .d.cts (validated with tsc 5.9) comes out the same with Oxc:

export declare namespace PokerHand {
  export type { Card, Rank, Suit };
  export { CompareResult, HandRank, PokerHand, PokerHand as default };
}
Object.assign(PokerHand, { PokerHand, default: PokerHand, HandRank, CompareResult });

compareWith() checks a marker instead of instanceof (#12, a Relaxation per #14):

 compareWith(hand)
-  if !(hand instanceof PokerHand)            throw 'Incorrect hand to compare with'
+  if hand?.[Symbol.for('poker-hand-evaluator.PokerHand')] !== true
+                                             throw 'Incorrect hand to compare with'
   if scores don't compare                    throw 'Incorrect hand'   // Object.create(PokerHand.prototype)

The marker is a non-enumerable property of the prototype, so Object.keys() of an instance is still hand, score, rank.

HandRank and CompareResult become as const objects, each with a literal union of the same name (#30). The member names don't change.

package.json:

-  "type": "module",
+  "type": "commonjs",
   "main": "./dist/index.cjs",
-  "module": "./dist/index.mjs",
-  "types": "./dist/index.d.mts",
+  "types": "./dist/index.d.cts",
   "exports": {
-    ".": { "import": "./dist/index.mjs", "require": "./dist/index.cjs", "types": "./dist/index.d.mts" }
+    ".": {
+      "import":  { "types": "./dist/index.d.mts", "default": "./dist/index.mjs" },
+      "require": { "types": "./dist/index.d.cts", "default": "./dist/index.cjs" }
+    },
+    "./package.json": "./package.json"
   },
+  "engines": { "node": ">=6" },

Why "type": "module" goes

The package becomes CommonJS-scoped again, which is what 1.0.1 got by default. publint suggests writing "commonjs" explicitly. The library files keep their .mjs and .cjs extensions, so they don't change. The change applies to every .js file the package ships, and two tickets need those files to be CommonJS:

What it costs: tsdown.config.ts, vite.config.ts and compat/vitest.config.ts become .mts, so they stay ES modules. Without the rename, Node warns MODULE_TYPELESS_PACKAGE_JSON when tsdown loads its config, and Vite warns about ESM syntax in a CommonJS file. The compat script points at the new file name.

Why "module" goes

webpack 4 ignores exports, and it prefers module over main even for require(). Measured with webpack 4.47 on the packed tarball:

                      require('poker-hand-evaluator')                     import PokerHand from
with "module"         { CompareResult, HandRank, PokerHand, default }     class ✓
                      → TypeError: PokerHand is not a constructor
without "module"      class ✓                                             class ✓

1.0.1 had no module field, so with it the Contrat v1 would break for webpack 4 users. Bundlers that read exports are not affected by the removal.

Commits

  1. New compat/ tests: the class name, mixed import/require(), and named exports on the class. All of them pass against 1.0.1.
  2. The CommonJS entry: require() returns the class.
  3. The ESM default export.
  4. The Symbol.for marker.
  5. compat/types.test.ts: TypeScript consumer projects.
  6. HandRank and CompareResult as as const objects.
  7. exports, types and engines, with types first.
  8. "type": "commonjs", no module field, and the configs renamed to .mts.
  9. The compat/README.md table.
  10. engines in package-lock.json.

Evidence

  • Before (npm ci && npm run build && npm run compat on Update the tooling (tsdown, Vite 8, Vitest 5, TypeScript 7) and add Biome lint + format #34's branch): 34 failed, 48 passed (82).
    After: 31 failed, 59 passed (90), on Node 22.23.4, 24.4.0 and 26.9.0. No test went from green to red.

    red → green  require-api › returns the PokerHand class itself
                 esm-import  › the default import is the PokerHand class
                 esm-import  › named exports (new in 1.1.0) › the named PokerHand is the default export
    new, green   require-api › the class is named PokerHand
                 esm-import  › the default import is named PokerHand
                 esm-import  › compareWith() compares a hand from import with a hand from require()
                 require-api › named exports on the class (new in 1.1.0) › const { PokerHand, HandRank, CompareResult } = require() works
                 require-api › named exports on the class (new in 1.1.0) › .PokerHand and .default are the class itself
                 types       › TypeScript types (new in 1.1.0) › a node16, CommonJS project compiles
                 types       › TypeScript types (new in 1.1.0) › a node16, ES module project compiles
                 types       › TypeScript types (new in 1.1.0) › a bundler compiles
    still red    28 deep-imports (#29), 3 umd (#19)
    

    The new tests were red at the right step. The mixed import/require() test failed on instanceof until the marker commit. The three type projects failed with TS2322: Type '"FLUSH"' is not assignable to type 'HandRank' until the as const commit.

  • COMPAT_TARGET=reference npm run compat: 80 passed, 2 skipped before. 83 passed, 7 skipped after. The class-name and mixed import/require() tests run against 1.0.1 and pass. The five "new in 1.1.0" tests are skipped.

  • npm run compat:lint (regression 6): red → green.

    publint --strict   2 errors → none (one suggestion left: the repository.url form)
    attw --pack .      node10              🟢                                → 🟢
                       node16 (from CJS)   fallback condition + masquerading  → 🟢 (CJS)
                       node16 (from ESM)   🟢 (ESM)                           → 🟢 (ESM)
                       bundler             🟢                                 → 🟢
                       "No problems found", including "poker-hand-evaluator/package.json"
    
  • Consumer type check. Double entrée ESM/CJS : comment faire que require() renvoie la classe avec des types corrects ? #11's bench was re-run on the Oxc declarations, outside the repo, with skipLibCheck: false. Every project uses import PokerHand = require() where the mode allows it, import PokerHand from, import { PokerHand, HandRank }, const r: HandRank = 'FLUSH', Card/Rank/Suit and CompareResult. Each also has @ts-expect-error lines, so types that collapsed to any would fail.

                         TS 4.7.4  5.9.3  6.0.3  7.0.2
    node16, CommonJS        ✓       ✓      ✓      ✓
    nodenext, CommonJS      ✓       ✓      ✓      ✓
    node16, ES module       ✓       ✓      ✓      ✓
    nodenext, ES module     ✓       ✓      ✓      ✓
    bundler (preserve)      –       ✓      ✓      ✓      (needs TS ≥ 5.4)
    bundler (esnext)        –       ✓      ✓      ✓
    node10, no interop      ✓       ✓      ✓      –      (TS 7 removed node10)
    

    The node16 CJS/ESM and bundler projects, compiled with the repo's TypeScript 7.0.2, are now compat/types.test.ts.

  • ES2015. es-check es6 --checkFeatures passes on dist/index.cjs and, with --module, on dist/index.mjs. A probe that uses Object.values fails it.

  • Old Node. Official darwin-x64 binaries, checked against SHASUMS256.txt, were run on the packed tarball. The script ran require(), .name, the static properties, compareWith, the 1.0.1 error message and require('poker-hand-evaluator/package.json'). It ran import too, from 12.22 on.

    6.17.1  8.17.0  10.24.1  12.16.3   require → main (dist/index.cjs)     class ✓
    12.22.12  14.21.3  16.20.2         require → exports.require            class ✓
                                       import  → exports.import             class ✓, two copies, compareWith across them → 1
    
  • npm test: 45 passed. npm run typecheck and npm run lint are clean. npm run bench runs, and the Vite config of npm run dev loads.

  • Emitted files:

    before  dist/index.cjs  dist/index.mjs  dist/index.d.mts
    after   dist/index.cjs  dist/index.mjs  dist/index.d.mts  dist/index.d.cts
    

Merge Danger

Door: two-way until 1.1.0 is published, then one-way for the public surface.

Nothing is published here, and a revert restores the old build. Once 1.1.0 is out, several things become part of what 1.x must keep: the four static properties, default on both entries, the as const types (going back to enums would break code that writes literals, #30), and the Symbol.for key (#12).

Blast Radius: packaging

  • The class now has four enumerable static properties (PokerHand, default, HandRank, CompareResult). In 1.0.1, Object.keys(PokerHand) was []. They stay enumerable on purpose. Older import * as interop helpers copy only enumerable keys: TypeScript 4.7's __importStar walks them with for…in, while 5.9 uses Object.getOwnPropertyNames.
  • Two copies of the class still load when a program mixes import and require(). compareWith accepts hands from either copy now, but === between the two classes stays false.
  • For CI GitHub Actions et release (changesets, provenance npm) #21: the compat config is now compat/vitest.config.mts. compat:lint is green, so CI can gate on it. es-check isn't a dependency yet.
  • For Rétablir le build UMD minifié dist/pokerhand.min.js #19 and Servir les chemins profonds de la 1.0.1 (régression 5) #29: "type": "commonjs" lets them ship plain .js CommonJS files. Each path must also be listed in exports, because exports now closes every path except . and ./package.json.
  • Branches that touch tsdown.config.ts or vite.config.ts need to follow the rename.

🤖 Generated with Claude Code

codeKonami and others added 10 commits November 26, 2026 11:27
…mpat/

- PokerHand.name is 'PokerHand' through require() and import, as in 1.0.1.
  Nothing pinned it since the builds stopped being minified.
- An ES module that also require()s the package can compare hands from
  both: 1.0.1 had a single CommonJS copy, a dual package loads two classes.
- new in 1.1.0: destructured require() keeps working, and .PokerHand and
  .default are the class itself.

All pass against 1.0.1 (COMPAT_TARGET=reference).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A second tsdown entry, src/index.cjs.ts, has a single default export, so
tsdown's cjsDefault writes dist/index.cjs as `module.exports = PokerHand`
and dist/index.d.cts as `export = PokerHand` (#11).

The named exports stay reachable from require(): PokerHand, default,
HandRank and CompareResult are static properties of the class, and a
`declare namespace PokerHand` merged with the class carries them, and
Card, Rank and Suit, into index.d.cts. Oxc emits that namespace as is.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
`import PokerHand from 'poker-hand-evaluator'` gave the class in 1.0.1,
through Node's CommonJS interop, and failed since the ESM build.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A dual package loads two PokerHand classes when a program both imports
and requires it, and `instanceof` rejected a hand from the other copy
with "Incorrect hand to compare with". 1.0.1 had one CommonJS copy, so
that mixed use worked there.

compareWith() now checks Symbol.for('poker-hand-evaluator.PokerHand'),
set on the prototype and not enumerable (#12). Any copy of the package
is accepted, which #14 validated as a relaxation. Anything else still
throws the same Error, and Object.create(PokerHand.prototype) still
throws "Incorrect hand".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
compat/types.test.ts compiles three small projects with the repo's
TypeScript and skipLibCheck off: node16 from CommonJS, node16 from an ES
module, and bundler (module: preserve). They use the class as a value and
a type, HandRank and CompareResult, Card/Rank/Suit, through
`import PokerHand = require()`, `import PokerHand from` and named imports,
and `const r: HandRank = 'FLUSH'` (#30).

Skipped against 1.0.1, which shipped no types.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Each is now an object `as const` plus a union type of its values under
the same name (#30). Member names don't change (HandRank.Flush,
CompareResult.Win), and a literal is accepted where a HandRank is
expected: `const r: HandRank = 'FLUSH'` compiles. The enums were never
published, so nothing breaks; CompareResult loses the reverse mapping
of a numeric enum.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- exports: `types` comes first in the `import` and `require` branches,
  each pointing at its own declaration file (index.d.mts, index.d.cts),
  as #11 validated.
- types at the root: index.d.cts, the pair of `main`, for TypeScript's
  node10 resolution, which ignores exports.
- "./package.json" stays reachable, as it was in 1.0.1.
- engines: node >=6 (#15).

publint --strict and attw --pack now pass: no problems for node10,
node16 from CJS, node16 from ESM and bundler.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
"type": "module" becomes "type": "commonjs", the scope 1.0.1 had by
default. The library files keep their explicit .mjs/.cjs extensions and
don't change. What changes is every .js file in the package, which is
now CommonJS:

- dist/pokerhand.min.js (#19) and the 1.0.1 deep paths (index.js,
  src/**/*.js, #29) have fixed .js names. They must load with require()
  on every Node, and exist as plain files for Node < 12.7, which ignores
  exports. Under "type": "module", Node >= 12.17 reads them as ES modules
  (require() gives {} or ERR_REQUIRE_ESM), so each would need a .cjs
  twin or a nested package.json. A nested package.json also overrides the
  root "sideEffects" for webpack.
- publint suggests the explicit value over an absent field.

The "module" field goes: webpack 4 ignores exports and prefers "module"
to "main" even for require(), so require('poker-hand-evaluator') got the
ES module namespace and `new PokerHand()` threw "PokerHand is not a
constructor" (measured with webpack 4.47). 1.0.1 had no "module" field.
Bundlers that read exports are unaffected.

The tsdown and Vite configs become .mts, so that they stay ES modules
without a package-wide "type": "module".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
npm copies the root package's engines into the lockfile.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Two critical active findings block verification: the renamed Vitest ES-module config uses undefined __dirname, and src/poker-hand.ts fails TypeScript compilation because POKER_HAND is inferred as a non-unique symbol.

1 open issue
What changed in this PR

This PR delivers the dual ESM/CommonJS package surface for poker-hand-evaluator, preserving the legacy CommonJS entry behavior while adding public TypeScript declarations and cross-entry hand recognition.

Changes:

  • Replaces the single tsdown build with separate ESM and CommonJS entries, including .d.mts and .d.cts declarations.
  • Changes HandRank and CompareResult to literal-valued as const objects with matching union types, and adds static exports to PokerHand.
  • Updates package exports, CommonJS scoping, Node engine metadata, compatibility tests, and mixed ESM/CJS behavior.
File Description
vite.config.mts Updates the tooling configuration reference to the renamed tsdown configuration.
tsdown.config.ts Removes the former single-entry build configuration.
tsdown.config.mts Defines separate ESM and CommonJS builds with declaration generation.
src/​types.ts Replaces enums with const objects and literal-union types.
src/​poker-hand.ts Adds cross-copy hand recognition, namespace declarations, and static class exports.
src/​index.ts Adds the ESM default and named exports.
src/​index.cjs.ts Adds the CommonJS default entry.
package.json Updates module type, conditional exports, declaration paths, engines, and compatibility scripts.
package-lock.json Records the package Node engine constraint.
compat/​vitest.config.mts Provides the renamed compatibility test configuration.
compat/​types.test.ts Validates the published declarations across CommonJS, ESM, and bundler consumer projects.
compat/​require-api.test.ts Covers CommonJS class identity, naming, and static exports.
compat/​README.md Documents the expanded compatibility test coverage.
compat/​esm-import.test.ts Covers ESM default imports, named exports, and mixed-entry comparisons.

Review effort: Lite

Comment thread src/poker-hand.ts
const POKER_HAND = Symbol.for('poker-hand-evaluator.PokerHand');

function isPokerHand(value: unknown): value is PokerHand {
return value != null && (value as { [POKER_HAND]?: unknown })[POKER_HAND] === true;

This branch has not been deployed

No deployments
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