CLI: api-diff, breaking API changes since a git ref #7

Merged
sionzee merged 4 commits from api-diff into main 2026-11-04 21:29:13 +01:00
Owner

Adds safe-ts api-diff <git-ref> [entry files...] [--json]. It compares a package's public API at a git ref with the working tree and exits with 1 when a change breaks callers (0 otherwise, 2 for a bad ref or missing entries), in the spirit of cargo-semver-checks.

What changed

  • crates/safe_ts_core/src/api.rs (new): reads a module's exports from syntax (functions with overloads, constants, classes, type aliases, interfaces, export *, export { a as b } from, export * as ns, default exports) into a normalised type model, then compares two versions.
    • Normalisation: unions are flattened and sorted, and true | false is boolean. Aliases callers can't name are expanded where they're declared, including through relative imports. Recursive aliases stop after one level. Option, Result, Enum, Mut, Readonly, ReadonlyArray, Array, Partial, Required, and Pick/Omit with literal keys are understood. An interface that extends an exported object type gets that type's fields merged in.
    • Classification depends on which way a value goes: callers read it (returns, constants, class members), write it (parameters), or both. An exported type takes its direction from the exports that mention it. A type no other export uses counts as both.
    • Breaking: removed export, new required parameter or key in an input, narrowed parameter, widened return, new error kind on the error side of Result (also inside Promise<Result>), a new PropagateError kind that can escape, a new Enum variant in a returned type, T → Mut<T>, and sync → async when the return type isn't written. Compatible: the mirror images.
    • When two types can't be related (library generics, conditional/mapped types, inferred values), the change is reported as "can't classify" rather than guessed.
  • Project::escaping_kinds (project.rs): exposes the existing whole-program fn_propagation for a list of functions. resolve and display_path are now pub(crate).
  • crates/safe_ts_cli/src/api_diff.rs (new):
    • Checks the ref out into a temporary git worktree (with core.hooksPath pointed at nothing, so no hooks run) and removes it afterwards. This works from a package subdirectory of a monorepo.
    • Default entries come from package.json exports (each subpath; prefers source/types conditions and .ts files; uses the .ts twin of a missing .js target; skips * patterns), then main/module/types.
    • Text output is grouped by entry and export, with colours only on a terminal. --json gives counts and per-export status, location, usage and changes.
  • Docs:
    • docs/guide/api-diff.md covers how to run it, what counts as breaking (tables by direction, callbacks, Enum errors) and a "What it can't see" section. Its sample outputs come from real runs.
    • The page is added to the sidebar and docs/README.md.
    • README: a CLI paragraph and the Layout line.

One deliberate deviation from the brief: removing an Enum variant is breaking even in return position, including on the error side of a Result. I checked with tsc that match(v, { ..., Gone: ... }) fails with "Object literal may only specify known properties". Removing a member from a union of values stays compatible, as the brief says. The guide notes that TypeScript also rejects a case for a literal that can no longer occur.

How it was tested

Rebased onto main at 1fe2d1d: first onto 04a5576, then again after #11 (Promise-returning functions, with #18's narrowing catches) and #6 were merged. The only conflict was the README paragraph next to #16's bench:check one; both are kept. Results on the rebased branch (head below):

  • cargo nextest run --workspace: 110/110 pass.
  • npm run test:std: 130/130 pass. npm run test:vite, npm run typecheck, npm run test:docs (docs typecheck, wasm, VitePress build): pass. bench:check not run, because this touches no bench or transform code.
  • cargo nextest run -p safe_ts_core --test api_diff: 15 fixture pairs (tests/api_diff/<case>/{old,new} plus expected.txt), plus a check that an unchanged API reports nothing. They cover removed/added exports, parameters, returns, Result errors, PropagateError propagation, enums in each direction, object keys/readonly/optional, local and recursive aliases, Partial, interface extends, callbacks, classes, re-exports, constants, and "can't classify". UPDATE_EXPECT=1 regenerates the expected files. The 13 fixtures from before the rebase produce the same output under #5's and #11's analysis.
  • cargo nextest run -p safe_ts_cli: 4 end-to-end tests on a temporary git repo with the package in a subdirectory: unchanged (exit 0), breaking (exit 1, JSON and text), explicit entries, compatible-only (exit 0), bad ref (exit 2), temporary worktree removed. New: a workspace sibling reached through a node_modules symlink. This test fails without the resolver fallback below (1 spurious "can't classify").
  • By hand, default discovery on every package in packages/ against 0e01fb3, the commit before #12 (details below).

What changed in the rebase (second and third commits)

  • #5 (calls into methods, re-exports): api-diff resolves re-exports itself and passes the declaring (file, name) to the whole-program pass, which still matches #5's keys. Calls through ns.f(), barrels and this.#helper() are now followed. Two fixes:
    • A named default export (export default function load) was looked up as default, but the checker keys it load, so its PropagateErrors were never reported. This bug was already in the PR.
    • Public class methods, static methods and the constructor (field initializers included) now report escaping kinds too (Repo (class) | static open | can now propagate ...), because the checker follows them now.
    • New fixture propagate-calls covers both, plus a namespace import, an error class from an export * barrel, and a method that stops propagating.
  • Old and new versions resolved packages differently. In packages/safe-ts-vue, api-diff HEAD reported 8 "can't classify" changes with nothing changed: the old checkout (in the temp dir) has no node_modules, so @evobug/safe-ts-std/enum stayed a name there but was expanded in the working tree. Project::with_packages_from lets the old version resolve package imports from the working tree's node_modules. That covers the type model and the PropagateError pass. Relative imports are unchanged.
  • #12 (package layouts): the source package.jsons in git still export ./src/*.ts, so default discovery works as before. Against 0e01fb3:
    • std, safe-ts-vue, feature-zod, prelude, safe-ts-native: no API changes.
    • safe-ts-transform: #12 added index.d.ts under a types condition, and the old entry was the untyped index.mjs. The result is 1 compatible change (SafeTsOptions added) and 9 "type now declared" can't-classify changes. That is accurate.
    • feature-browser/node/vue-router: no code entry (data-only packs), so exit 2 with "no entry files".
    • oxlint-plugin-safe-ts: #12's new ./recommended.json subpath was parsed as TypeScript. Default discovery now skips non-code targets (in line with #2), and the result is no changes.
    • The built .release/<pkg>/ manifests point at dist/*.d.ts / dist/*.js, which are gitignored, so no ref has an old version of them. Run there, api-diff used to list every export as "added" and exit 0. It now exits 2 and says to run it in the source directory.
  • #11 / #18 (rejections, narrowing catches), third commit: each escaping kind is now either thrown or a rejected promise, and a kind can be both. escaping_kinds returned only kind names, so a kind could be listed twice, and a function whose NotFound moved from a synchronous throw into a rejection (same signature) reported nothing. That is breaking, because callers' try { load(id) } without await no longer catches it. Kinds now carry their mode:
    • a new rejection reports can now reject with;
    • a kind that changes mode, or gains one, reports what callers' try or .catch(...) no longer catches.
    • #18's narrowing catches come through the same pass: a new kind that catch (e) { if (e instanceof NotFound) ...; throw e } lets through is reported.
    • New fixture: propagate-async.
  • The guide's tables and its "What it can't see" section were updated to match.

Left out / uncertain

  • No type checker, so the limits are in the guide's "What it can't see":
    • library generic types are names (except built-in containers);
    • unannotated return types are compared only for sync/async;
    • inferred constants are "can't classify" when their expression changes;
    • overloads are compared as a whole;
    • inherited class members aren't merged in;
    • renames show up as removal plus addition.
  • PropagateError kinds: methods of exported object literals and inherited class members aren't tracked, and calls the checker can't tie to one function aren't followed.
  • Both versions use the dependencies installed now. A dependency whose version changed since the ref is read at its current version.
  • Literal constants (export const NAME = "x") count as their primitive type, so value changes aren't reported.
  • .vue entries aren't supported; JavaScript entries have no types, so only exports and parameter counts are compared.
  • In export * cycles, the module reached second may see an incomplete export list (memoised placeholder).
  • No npm wrapper for the CLI: it's the safe-ts binary, as for the other subcommands.

🤖 Generated with Claude Code

Adds `safe-ts api-diff <git-ref> [entry files...] [--json]`. It compares a package's public API at a git ref with the working tree and exits with 1 when a change breaks callers (0 otherwise, 2 for a bad ref or missing entries), in the spirit of cargo-semver-checks. ## What changed - **`crates/safe_ts_core/src/api.rs`** (new): reads a module's exports from syntax (functions with overloads, constants, classes, type aliases, interfaces, `export *`, `export { a as b } from`, `export * as ns`, default exports) into a normalised type model, then compares two versions. - Normalisation: unions are flattened and sorted, and `true | false` is `boolean`. Aliases callers can't name are expanded where they're declared, including through relative imports. Recursive aliases stop after one level. `Option`, `Result`, `Enum`, `Mut`, `Readonly`, `ReadonlyArray`, `Array`, `Partial`, `Required`, and `Pick`/`Omit` with literal keys are understood. An interface that `extends` an exported object type gets that type's fields merged in. - Classification depends on which way a value goes: callers read it (returns, constants, class members), write it (parameters), or both. An exported type takes its direction from the exports that mention it. A type no other export uses counts as both. - Breaking: removed export, new required parameter or key in an input, narrowed parameter, widened return, new error kind on the error side of `Result` (also inside `Promise<Result>`), a new `PropagateError` kind that can escape, a new `Enum` variant in a returned type, `T` → `Mut<T>`, and sync → async when the return type isn't written. Compatible: the mirror images. - When two types can't be related (library generics, conditional/mapped types, inferred values), the change is reported as "can't classify" rather than guessed. - **`Project::escaping_kinds`** (project.rs): exposes the existing whole-program `fn_propagation` for a list of functions. `resolve` and `display_path` are now `pub(crate)`. - **`crates/safe_ts_cli/src/api_diff.rs`** (new): - Checks the ref out into a temporary `git worktree` (with `core.hooksPath` pointed at nothing, so no hooks run) and removes it afterwards. This works from a package subdirectory of a monorepo. - Default entries come from `package.json` `exports` (each subpath; prefers `source`/`types` conditions and `.ts` files; uses the `.ts` twin of a missing `.js` target; skips `*` patterns), then `main`/`module`/`types`. - Text output is grouped by entry and export, with colours only on a terminal. `--json` gives counts and per-export `status`, `location`, `usage` and `changes`. - **Docs**: - `docs/guide/api-diff.md` covers how to run it, what counts as breaking (tables by direction, callbacks, Enum errors) and a "What it can't see" section. Its sample outputs come from real runs. - The page is added to the sidebar and `docs/README.md`. - README: a CLI paragraph and the Layout line. One deliberate deviation from the brief: removing an `Enum` variant is breaking even in return position, including on the error side of a `Result`. I checked with tsc that `match(v, { ..., Gone: ... })` fails with "Object literal may only specify known properties". Removing a member from a union of values stays compatible, as the brief says. The guide notes that TypeScript also rejects a `case` for a literal that can no longer occur. ## How it was tested Rebased onto main at 1fe2d1d: first onto 04a5576, then again after #11 (Promise-returning functions, with #18's narrowing catches) and #6 were merged. The only conflict was the README paragraph next to #16's bench:check one; both are kept. Results on the rebased branch (head below): - `cargo nextest run --workspace`: 110/110 pass. - `npm run test:std`: 130/130 pass. `npm run test:vite`, `npm run typecheck`, `npm run test:docs` (docs typecheck, wasm, VitePress build): pass. `bench:check` not run, because this touches no bench or transform code. - `cargo nextest run -p safe_ts_core --test api_diff`: 15 fixture pairs (`tests/api_diff/<case>/{old,new}` plus `expected.txt`), plus a check that an unchanged API reports nothing. They cover removed/added exports, parameters, returns, `Result` errors, `PropagateError` propagation, enums in each direction, object keys/readonly/optional, local and recursive aliases, `Partial`, interface `extends`, callbacks, classes, re-exports, constants, and "can't classify". `UPDATE_EXPECT=1` regenerates the expected files. The 13 fixtures from before the rebase produce the same output under #5's and #11's analysis. - `cargo nextest run -p safe_ts_cli`: 4 end-to-end tests on a temporary git repo with the package in a subdirectory: unchanged (exit 0), breaking (exit 1, JSON and text), explicit entries, compatible-only (exit 0), bad ref (exit 2), temporary worktree removed. New: a workspace sibling reached through a `node_modules` symlink. This test fails without the resolver fallback below (1 spurious "can't classify"). - By hand, default discovery on every package in `packages/` against 0e01fb3, the commit before #12 (details below). ### What changed in the rebase (second and third commits) - **#5 (calls into methods, re-exports):** api-diff resolves re-exports itself and passes the declaring `(file, name)` to the whole-program pass, which still matches #5's keys. Calls through `ns.f()`, barrels and `this.#helper()` are now followed. Two fixes: - A named default export (`export default function load`) was looked up as `default`, but the checker keys it `load`, so its `PropagateError`s were never reported. This bug was already in the PR. - Public class methods, static methods and the constructor (field initializers included) now report escaping kinds too (`Repo (class) | static open | can now propagate ...`), because the checker follows them now. - New fixture `propagate-calls` covers both, plus a namespace import, an error class from an `export *` barrel, and a method that stops propagating. - **Old and new versions resolved packages differently.** In `packages/safe-ts-vue`, `api-diff HEAD` reported 8 "can't classify" changes with nothing changed: the old checkout (in the temp dir) has no `node_modules`, so `@evobug/safe-ts-std/enum` stayed a name there but was expanded in the working tree. `Project::with_packages_from` lets the old version resolve package imports from the working tree's `node_modules`. That covers the type model and the `PropagateError` pass. Relative imports are unchanged. - **#12 (package layouts):** the source `package.json`s in git still export `./src/*.ts`, so default discovery works as before. Against 0e01fb3: - std, safe-ts-vue, feature-zod, prelude, safe-ts-native: no API changes. - safe-ts-transform: #12 added `index.d.ts` under a `types` condition, and the old entry was the untyped `index.mjs`. The result is 1 compatible change (`SafeTsOptions` added) and 9 "type now declared" can't-classify changes. That is accurate. - feature-browser/node/vue-router: no code entry (data-only packs), so exit 2 with "no entry files". - oxlint-plugin-safe-ts: #12's new `./recommended.json` subpath was parsed as TypeScript. Default discovery now skips non-code targets (in line with #2), and the result is no changes. - The built `.release/<pkg>/` manifests point at `dist/*.d.ts` / `dist/*.js`, which are gitignored, so no ref has an old version of them. Run there, api-diff used to list every export as "added" and exit 0. It now exits 2 and says to run it in the source directory. - **#11 / #18 (rejections, narrowing catches), third commit:** each escaping kind is now either thrown or a rejected promise, and a kind can be both. `escaping_kinds` returned only kind names, so a kind could be listed twice, and a function whose `NotFound` moved from a synchronous throw into a rejection (same signature) reported nothing. That is breaking, because callers' `try { load(id) }` without `await` no longer catches it. Kinds now carry their mode: - a new rejection reports `can now reject with`; - a kind that changes mode, or gains one, reports what callers' `try` or `.catch(...)` no longer catches. - #18's narrowing catches come through the same pass: a new kind that `catch (e) { if (e instanceof NotFound) ...; throw e }` lets through is reported. - New fixture: `propagate-async`. - The guide's tables and its "What it can't see" section were updated to match. ## Left out / uncertain - No type checker, so the limits are in the guide's "What it can't see": - library generic types are names (except built-in containers); - unannotated return types are compared only for sync/async; - inferred constants are "can't classify" when their expression changes; - overloads are compared as a whole; - inherited class members aren't merged in; - renames show up as removal plus addition. - `PropagateError` kinds: methods of exported object literals and inherited class members aren't tracked, and calls the checker can't tie to one function aren't followed. - Both versions use the dependencies installed now. A dependency whose version changed since the ref is read at its current version. - Literal constants (`export const NAME = "x"`) count as their primitive type, so value changes aren't reported. - `.vue` entries aren't supported; JavaScript entries have no types, so only exports and parameter counts are compared. - In `export *` cycles, the module reached second may see an incomplete export list (memoised placeholder). - No npm wrapper for the CLI: it's the `safe-ts` binary, as for the other subcommands. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
sionzee force-pushed api-diff from 7a1b6ed024 to ed859d0fc8
Some checks failed
Benchmarks / bench (pull_request) Failing after 2m37s
2026-11-03 23:27:02 +01:00
Compare
sionzee force-pushed api-diff from ed859d0fc8
Some checks failed
Benchmarks / bench (pull_request) Failing after 2m37s
to 4fb2e54850
All checks were successful
Benchmarks / bench (pull_request) Successful in 1m54s
2026-11-03 23:48:31 +01:00
Compare
Merge main into api-diff
All checks were successful
Benchmarks / bench (pull_request) Successful in 3m2s
380f157638
Resolve conflicts with the PRs merged before this one: both sides kept
(rule lists, std exports, package checks, CLI usage, README).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
sionzee deleted branch api-diff 2026-11-04 21:29:13 +01:00
Sign in to join this conversation.
No reviewers
No labels
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
Evobug/Safe-Ts!7
No description provided.