Skip to content

About

Load a dual CJS/ESM package's require() and import() builds in child processes and diff their actual runtime exports. attw and publint only read package.json and types statically; neither executes the package.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

Β 

History

2 Commits

Folders and files

Repository files navigation

dual-parity

Loads a dual CJS/ESM package's require() build and import() build in child processes and diffs what they actually export at runtime.

import { checkParity } from 'dual-parity';

const report = await checkParity('./my-package');
if (!report.clean) {
  for (const f of report.findings) console.log(f.severity, f.message);
}

Safety: this executes the target package's code. Each load runs in a disposable child Node process with a timeout, never in this process, but a compromised or malicious package still runs arbitrary code when loaded. Only point this at code you trust, the same way you would trust npm install on it.

Why

attw (@arethetypeswrong/cli) and publint catch a lot of dual-package mistakes, but both only read package.json and the .d.ts files statically β€” neither ever runs require() or import() on the actual built files. A stale partial rebuild, where the CJS output falls behind the ESM output but the types still claim both, passes both tools clean and only breaks at runtime.

Measured: npm run demo, against a package whose ESM build exports foo and bar, whose CJS build only exports foo (a stale rebuild), and whose types declare both:

require() consumer:
  threw: mod.bar is not a function

dual-parity:
  [error] "bar" is exported by the ESM build (import) but not by the CJS build (require)

exit code this CLI run would use: 1

The same layout run through the real tools, by hand:

$ npx @arethetypeswrong/cli --pack .
 No problems found 🌟

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                   β”‚ "stale-pkg" β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ node10            β”‚ 🟒          β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ node16 (from CJS) β”‚ 🟒 (CJS)    β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ node16 (from ESM) β”‚ 🟒 (ESM)    β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ bundler           β”‚ 🟒          β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

$ npx publint .
Running publint v0.3.24 for stale-pkg...
Suggestions:
1. The package does not specify the "engines.node" field. ...

Neither notices bar is missing. Checked for an existing tool that does (four npm search phrasings β€” "dual package parity", "cjs esm export parity", "export surface diff", "dual build verify"): nothing turned up except builders (dual-publish) and lexers (cjs-module-lexer) that parse a CJS file's exports statically but don't compare two builds against each other.

Installation

npm install --save-dev dual-parity

Node >= 20.6. No required runtime dependencies. typescript is an optional peer dependency, needed only for --types (see below).

Usage

From the CLI

npx dual-parity .
npx dual-parity ./packages/my-lib --json
npx dual-parity --installed some-dependency

From code

import { checkParity } from 'dual-parity';

const report = await checkParity('./my-package', {
  subpaths: ['.', './utils'],
  conditions: ['worker'],
  timeoutMs: 15_000,
  types: true,
});

Checking a package already in node_modules

npx dual-parity --installed axios

Resolves axios by walking up from the current directory looking for node_modules/axios, then runs the same check against it.

Reference

checkParity(packageDir, options?)

Returns a Promise<ParityReport>.

Option Type Default Description
subpaths string[] every public entry Only check these exports subpaths (e.g. ["."]).
conditions string[] [] Extra active conditions merged into both the require and the import condition sets.
timeoutMs number 10000 Per-load timeout in the child process.
types boolean false Also compare declared .d.ts/.d.cts export names (needs typescript).

ParityReport: { packageDir, packageName?, entries, findings, clean, hadLoadError }. entries is one EntryReport per public export ({ subpath, requireTarget?, importTarget?, skippedIdentical?, findings }); findings on the report is the flattened list from every entry.

Finding kinds

Kind Severity Meaning
missing-in-cjs error Named export exists under import(), not under require().
missing-in-esm error Named export exists under require(), not under import().
type-mismatch error Same export name, different typeof or class-ness.
default-mismatch error The effective default value differs in typeof or class-ness.
arity-mismatch warning Same function, different .length. Doesn't affect the exit code.
cjs-import-lexer-gap info require() sees a name that Node's own static import analysis of the same CJS file (cjs-module-lexer) won't detect.
load-error error require() or import() itself threw, or crashed the child process.
types-missing-in-cjs / types-missing-in-esm error (--types) A name is declared for one condition's types but not the other's.
types-runtime-mismatch error (--types) A declared top-level export doesn't actually exist at runtime.
types-skipped info --types requested but typescript isn't installed.

CLI

dual-parity [dir] [options]

  --json                 Print the full report as JSON.
  --types                Also compare declared .d.ts/.d.cts export names.
  --installed <name>     Resolve <name> under ./node_modules instead of [dir].
  --subpaths a,b         Only check these exports subpaths.
  --conditions a,b       Extra active conditions.
  --timeout <ms>         Per-load timeout (default 10000).

Exit codes: 0 clean, 1 parity problems found, 2 could not analyse (a load crashed, or the directory has no package.json).

How it works

For every public entry (., subpaths, and * patterns expanded against files that actually exist on disk), dual-parity resolves the file the require condition set (require, node, default) targets and the file the import condition set (import, node, default) targets, using the same first-matching-key algorithm as Node's own PACKAGE_EXPORTS_RESOLVE. If the two conditions land on the same file, there is nothing dual to check β€” Node itself would give every caller the same code, and the entry is silently skipped.

Otherwise the CJS target is loaded two ways (require(), and import() of that same CJS file) and the ESM target is loaded with import(), each in its own disposable child process with a timeout. Own enumerable keys of each result are compared:

  • __esModule is bookkeeping, never a real export. It is dropped from every named-export comparison.
  • ESM's default is never compared as a named export (ESM structurally sets it apart). Its CJS counterpart is the whole require() result β€” UNLESS the CJS module carries __esModule: true and an own default property (the Babel/esModuleInterop convention), in which case the counterpart is that default property instead. This makes module.exports = fn matching export default fn, and Babel-style __esModule + exports.default matching export default, both come out clean β€” the "ESM has named exports, CJS has them on module.exports" case reduces to plain key-set comparison once default is handled this way.
  • A default that just aliases an already-equal named export (export function add() {} plus export default add;, common so import add from '...' also works) is not re-flagged β€” detected structurally (type/arity/class-ness), since object identity can't be compared across the two child processes that observed it.
  • A callable-with-methods default (module.exports = fn with fn.get = ... etc attached, axios's actual shape) has those methods reachable only via the default on both sides, not as standalone top-level bindings; a name missing from one side's flat export list is still accepted if it's an own property of the other side's default value.
  • Everything else is a straight name-for-name diff, with typeof, class-ness (isClass, a /^class / heuristic on Function.prototype.toString), and arity compared per shared name.

--types adds a third comparison using the TypeScript compiler API: the names TypeScript would resolve for each condition's .d.ts/.d.cts, against each other and against the runtime names above. interface/type exports are excluded β€” they're erased at compile time and were never going to exist at runtime. export = X (TypeScript's CJS-style declaration idiom) is handled by enumerating X's structural members, since there's no per-name export statement for them at all.

Limitations

  • Compares runtime shape (name, typeof, arity, class-ness), not behavior. Two functions with the same name and arity that compute different results are not caught.
  • --types only checks declared-vs-runtime for top-level declared names. A name only reachable through a default's structural members (e.g. export = x files, or a .d.ts's export default type) is compared across the two type files but not re-verified against the runtime load, to avoid a second layer of guessing about default-property equivalence.
  • No exports field means require() and import() resolve to the same file under real Node (the legacy module field is a bundler-only convention Node itself ignores) β€” nothing to compare, and dual-parity says so by finding zero dual entries rather than guessing.
  • * pattern subpaths are expanded by recursively scanning the filesystem under each pattern's literal prefix directory; very large trees add to the scan time before any loads happen.
  • cjs-import-lexer-gap describes Node's own static CJS-from-ESM interop limits; it is informational and does not affect the exit code, since code that only ever uses require() of that file is unaffected.
  • No sandboxing beyond a child process and a timeout. See "Safety" at the top.

Compatibility

Tested on macOS, Node 24.20.0. npm run build && npm run test:dist (the pure-JS smoke suite) is designed to also run on Node 20 and 22, but was only actually run on 24 here.

Run against 22 real published dual packages (installed from npm, node 24): zod, date-fns, uuid, nanoid@3, axios, @tanstack/query-core, react-redux, zustand, immer, rxjs, lodash-es, yup, ajv, chalk, commander, yargs, dayjs, ms, semver, picomatch, node-fetch, p-limit, p-queue. Every package exited 0. The only two non-empty reports were both cjs-import-lexer-gap (info, doesn't affect the exit code): axios's callable module.exports has .get/.post/etc. attached as plain properties, and date-fns's fp/ curried re-exports β€” both are real, both manually confirmed as Node's own static-import limitation rather than a dual-parity bug, and neither is a build-vs-build mismatch.

Development

npm install
npx tsc --noEmit
node --test "test/*.test.ts"
npm run build && npm run test:dist
npm run demo

License

MIT. See LICENSE.

About

Load a dual CJS/ESM package's require() and import() builds in child processes and diff their actual runtime exports. attw and publint only read package.json and types statically; neither executes the package.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages