Files
zeekayandHanzo Dev fba217fa78 A require() consumer gets CommonJS types
Every `require` branch pointed at the same .d.ts as `import`, and
"type": "module" makes TypeScript read that as an ES module. A .cts consumer
on module node16 got TS1479 on all 17 subpaths, for a .cjs file that loads
fine.

scripts/cts.mjs copies each .d.ts to a .d.cts whose relative imports name
.cjs. The exports map drops its `types` conditions: TypeScript types a .js by
the .d.ts beside it and a .cjs by the .d.cts.

The new test installs the package into a throwaway consumer and typechecks
a .cts and a .mts that import every subpath, with skipLibCheck off. On the
old build it fails with 17 TS1479.

Co-authored-by: Hanzo Dev <[email protected]>
2026-09-19 04:29:01 -07:00

19 lines
788 B
JavaScript

// Writes dist/*.d.cts, the declarations for the `require` condition.
//
// tsc emits one .d.ts per source file, and "type": "module" makes TypeScript
// read each of them as an ES module. A consumer that require()s dist/x.cjs is
// typed by its sibling dist/x.d.cts: the same declarations, with every relative
// import naming the .cjs twin, so everything it reaches is CommonJS too.
import { readdirSync, readFileSync, writeFileSync } from "node:fs";
const dist = new URL("../dist/", import.meta.url);
for (const name of readdirSync(dist)) {
if (!name.endsWith(".d.ts")) continue;
const text = readFileSync(new URL(name, dist), "utf8");
writeFileSync(
new URL(name.replace(/\.d\.ts$/, ".d.cts"), dist),
text.replace(/(["'])(\.\.?\/[^"']*)\.js\1/g, "$1$2.cjs$1"),
);
}