CLI: safe-ts migrate, codemods for throw, null and enum #20

Merged
sionzee merged 2 commits from codemods into main 2026-11-04 21:22:20 +01:00
Owner

What

safe-ts migrate <codemod> <files or dirs...> adds codemods for the three rewrites that repeat across an existing codebase. By default it prints a unified diff to stdout, and a report to stderr: what changed, what was left as written and why, and uses that need a decision. Files change only with --write. The report on stderr means > changes.patch gives a clean patch for git apply.

Built on oxc's AST. The edits are byte-offset TextEdits (the quick-fix type from fixes.rs; imports go through its ImportContext). Only the rewritten ranges change, so comments and formatting elsewhere stay. Every rewritten file is re-parsed; if edits overlap or the result doesn't parse, the file is left unchanged and the report says so.

  • throw-to-result: a top-level function whose throws the no-throw rule reports gets Result<T, E>, and each throw x becomes return err(x). Callers that return a Result, or are converted too, get q(...), including await, namespace imports and nested arrows that declare a Result.
    • Error type: the union of the thrown classes, plus what converted callees pass up through q. new Error("text") and throw "text" become a string error, as the errors guide recommends; a new Error(...) built from anything else stays an Error.
    • A function is converted only when every use in the given files can take a Result. Every other use is listed as needing a decision, and the function is left alone so the code keeps compiling: a caller that doesn't return one, a call inside a larger expression or a try, the function passed as a value, a re-export, or a caller whose declared error type doesn't include the new errors.
    • Also refused, with the reason: no declared return type, returning unknown/any, throws inside the function's own try, throws in callbacks or methods, throws of a value whose class it can't tell (throw wrap(e)), overloads, default exports, generators, and files that define their own q/err/Result.
    • Legacy files are migrated too.
  • null-to-undefined: null becomes undefined, T | null becomes Option<T> (the std import is added, or T | undefined if the file has its own Option), === null becomes === undefined, and x ?? null becomes x. Nested unions are handled, and parentheses that are no longer needed are dropped.
    • null from or to outside code stays and is reported: JSON (JSON.parse, .json()), DOM and Web APIs, packages, values typed with types not declared in the given files, your types that describe such data (followed across files), arguments to outside code (Object.create(null), values passed to JSON.stringify), callbacks it calls, on*/DOM property assignments, and conditional types.
  • ts-enum: a string enum whose uses are all plain becomes a string union, and Status.Draft becomes "draft" as a value, as a type, and inside template literals. Imports in other files become type imports, or are removed when nothing is left.
    • Otherwise the enum becomes the quick fix's const object + type, with the same values: when it's used as an object, when a bare string would widen to string, or for numeric enums. E.A as a type becomes typeof E.A, and an unannotated let x = E.A gets : E.
    • Refused: computed members, declare enum, merged declarations, re-exported, default-exported or namespace-imported enums, and numeric enums used as objects (reverse mapping).

Docs: a "Migrating with codemods" section in docs/guide/adoption.md, with a before/after for each codemod and what each refuses; a CLI line in the README.

Tests

crates/safe_ts_core/tests/migrate.rs covers 7 cases under tests/migrate/<codemod>/<case>/: input/, expected/, and report.txt for the notes. Each codemod has a refusal case; refusals are marked // left: <rule> in the input. The test checks:

  • the output matches expected/ and the report matches report.txt;
  • the targeted rule remains only on left: lines;
  • tsc (strict, noUncheckedIndexedAccess, exactOptionalPropertyTypes) compiles the input, the output, and the output after the build-time transform, so a q passing up an undeclared error type fails;
  • each adoption-guide before example run through the codemod gives exactly its after example.

I checked that a wrong expected file and a drifted docs example both make it fail.

Rebased onto main at 1fe2d1d

Rebased onto main at 1fe2d1d (after #2, #3, #4, #5, #6, #8, #9, #10, #11, #12, #13, #16, #23). What had to change:

  • A README conflict: #16's bench paragraph and this PR's CLI line, both kept.
  • #11 changed no-throw: throw e of the unchanged catch (e) binding is no longer reported. The refuses case's throw error; // left: no-throw stopped being one, and that exposed a bug: refusals that don't depend on a throw (returning unknown/any, overloads, default export, generator) were reported for every function, including ones with nothing to convert, so rethrows showed up as "skipped: it returns unknown". A function is now converted or reported only if it has a throw no-throw reports (new commit). The refuses case now rethrows a new value (throw wrap(error), still a no-throw), and a new passesOn rethrows the caught binding and returns unknown: no note, no change. That case fails on the previous code. The adoption guide's "not converted" list says the same (a rethrow of the caught error stays as written).
  • Other merged rules: I ran safe-ts check on every case's input and output and compared all rules other than each codemod's own. No new diagnostics in any output: none of no-accumulating-copy (#3), stable-shape (#8), fetch-signal (#6), floating-rejection (#11), or the others fire. Every other rule's count is the same before and after, except the unhandled-failures that throw-to-result resolves (callers now q(...) a Result). No expected file or report changed, apart from the refuses case above. The adoption-guide examples test passes unchanged.

Results after the rebase:

  • cargo nextest run --workspace: 108 passed, 0 failed (the features fixture failure is fixed on main by #23).
  • crates/safe_ts_core/tests/migrate.rs: 4/4, including tsc on input, output and emitted output (TypeScript 7.0.2; I checked it still reports a deliberate type error in the same setup).
  • npm run test:std: 130 passed, 0 failed. npm run test:vite: passed. npm run typecheck: passed. npm run test:docs: passed (docs typecheck, wasm, VitePress build).
  • All three codemods on examples/demo/src: exit 0, no diff, the same kind of reasoned refusals.
  • npm run bench:check not run: no benches or transform code changed.

Before the rebase (on 0e01fb3): cargo nextest run --workspace 98 passed, 1 failed (the features fixture, also failing on 0e01fb3); npm run test:std 115 passed, 1 failed (feature-node inventory drift, since fixed by #23); test:vite and test:docs passed; clippy clean for the new code.

Left out / uncertain

  • What the codemods see: the given files are the whole program. Uses in other files aren't seen, and the report notes this for every exported function or enum it changes. .vue files are skipped, with a warning.
  • throw-to-result converts top-level function declarations only, not arrow functions assigned to consts or methods.
  • null-to-undefined: deciding what is "outside" is a heuristic: a list of null-returning APIs and DOM properties, plus any type not declared in the given files. A null reaching a value through a path it doesn't follow (an unusual library method, several hops through functions) can be converted wrongly. tsc catches most of these, since the converted types reject null; a runtime-only case wouldn't be caught. The docs say this.
  • ts-enum: a numeric enum's type accepted any number; after conversion, tsc flags code that relied on that. That's intended, but it means "keeps compiling" holds only for code that didn't pass non-members.
  • Formatting: comments inside a rewritten enum body, or inside a removed | null, are lost; they're within the edited range.
  • Rustfmt: the repo isn't formatted with one rustfmt config, so I formatted only the new files (max_width=120, use_small_heuristics=Max, the width the existing core files match) and left existing code alone.

🤖 Generated with Claude Code

## What `safe-ts migrate <codemod> <files or dirs...>` adds codemods for the three rewrites that repeat across an existing codebase. By default it prints a unified diff to stdout, and a report to stderr: what changed, what was left as written and why, and uses that need a decision. Files change only with `--write`. The report on stderr means `> changes.patch` gives a clean patch for `git apply`. Built on oxc's AST. The edits are byte-offset `TextEdit`s (the quick-fix type from `fixes.rs`; imports go through its `ImportContext`). Only the rewritten ranges change, so comments and formatting elsewhere stay. Every rewritten file is re-parsed; if edits overlap or the result doesn't parse, the file is left unchanged and the report says so. - **`throw-to-result`**: a top-level function whose throws the `no-throw` rule reports gets `Result<T, E>`, and each `throw x` becomes `return err(x)`. Callers that return a `Result`, or are converted too, get `q(...)`, including `await`, namespace imports and nested arrows that declare a `Result`. - Error type: the union of the thrown classes, plus what converted callees pass up through `q`. `new Error("text")` and `throw "text"` become a `string` error, as the errors guide recommends; a `new Error(...)` built from anything else stays an `Error`. - A function is converted only when every use in the given files can take a `Result`. Every other use is listed as needing a decision, and the function is left alone so the code keeps compiling: a caller that doesn't return one, a call inside a larger expression or a `try`, the function passed as a value, a re-export, or a caller whose declared error type doesn't include the new errors. - Also refused, with the reason: no declared return type, returning `unknown`/`any`, throws inside the function's own `try`, throws in callbacks or methods, throws of a value whose class it can't tell (`throw wrap(e)`), overloads, default exports, generators, and files that define their own `q`/`err`/`Result`. - Legacy files are migrated too. - **`null-to-undefined`**: `null` becomes `undefined`, `T | null` becomes `Option<T>` (the std import is added, or `T | undefined` if the file has its own `Option`), `=== null` becomes `=== undefined`, and `x ?? null` becomes `x`. Nested unions are handled, and parentheses that are no longer needed are dropped. - `null` from or to outside code stays and is reported: JSON (`JSON.parse`, `.json()`), DOM and Web APIs, packages, values typed with types not declared in the given files, your types that describe such data (followed across files), arguments to outside code (`Object.create(null)`, values passed to `JSON.stringify`), callbacks it calls, `on*`/DOM property assignments, and conditional types. - **`ts-enum`**: a string enum whose uses are all plain becomes a string union, and `Status.Draft` becomes `"draft"` as a value, as a type, and inside template literals. Imports in other files become `type` imports, or are removed when nothing is left. - Otherwise the enum becomes the quick fix's `const` object + type, with the same values: when it's used as an object, when a bare string would widen to `string`, or for numeric enums. `E.A` as a type becomes `typeof E.A`, and an unannotated `let x = E.A` gets `: E`. - Refused: computed members, `declare enum`, merged declarations, re-exported, default-exported or namespace-imported enums, and numeric enums used as objects (reverse mapping). Docs: a "Migrating with codemods" section in `docs/guide/adoption.md`, with a before/after for each codemod and what each refuses; a CLI line in the README. ## Tests `crates/safe_ts_core/tests/migrate.rs` covers 7 cases under `tests/migrate/<codemod>/<case>/`: `input/`, `expected/`, and `report.txt` for the notes. Each codemod has a refusal case; refusals are marked `// left: <rule>` in the input. The test checks: - the output matches `expected/` and the report matches `report.txt`; - the targeted rule remains only on `left:` lines; - tsc (strict, `noUncheckedIndexedAccess`, `exactOptionalPropertyTypes`) compiles the input, the output, and the output after the build-time transform, so a `q` passing up an undeclared error type fails; - each adoption-guide before example run through the codemod gives exactly its after example. I checked that a wrong expected file and a drifted docs example both make it fail. ## Rebased onto main at 1fe2d1d Rebased onto `main` at 1fe2d1d (after #2, #3, #4, #5, #6, #8, #9, #10, #11, #12, #13, #16, #23). What had to change: - A README conflict: #16's bench paragraph and this PR's CLI line, both kept. - **#11 changed `no-throw`:** `throw e` of the unchanged `catch (e)` binding is no longer reported. The refuses case's `throw error; // left: no-throw` stopped being one, and that exposed a bug: refusals that don't depend on a throw (returning `unknown`/`any`, overloads, default export, generator) were reported for every function, including ones with nothing to convert, so `rethrows` showed up as "skipped: it returns `unknown`". A function is now converted or reported only if it has a throw `no-throw` reports (new commit). The refuses case now rethrows a new value (`throw wrap(error)`, still a `no-throw`), and a new `passesOn` rethrows the caught binding and returns `unknown`: no note, no change. That case fails on the previous code. The adoption guide's "not converted" list says the same (a rethrow of the caught error stays as written). - **Other merged rules:** I ran `safe-ts check` on every case's input and output and compared all rules other than each codemod's own. No new diagnostics in any output: none of no-accumulating-copy (#3), stable-shape (#8), fetch-signal (#6), floating-rejection (#11), or the others fire. Every other rule's count is the same before and after, except the `unhandled-failure`s that throw-to-result resolves (callers now `q(...)` a `Result`). No expected file or report changed, apart from the refuses case above. The adoption-guide examples test passes unchanged. Results after the rebase: - `cargo nextest run --workspace`: 108 passed, 0 failed (the `features` fixture failure is fixed on main by #23). - `crates/safe_ts_core/tests/migrate.rs`: 4/4, including tsc on input, output and emitted output (TypeScript 7.0.2; I checked it still reports a deliberate type error in the same setup). - `npm run test:std`: 130 passed, 0 failed. `npm run test:vite`: passed. `npm run typecheck`: passed. `npm run test:docs`: passed (docs typecheck, wasm, VitePress build). - All three codemods on `examples/demo/src`: exit 0, no diff, the same kind of reasoned refusals. - `npm run bench:check` not run: no benches or transform code changed. Before the rebase (on 0e01fb3): `cargo nextest run --workspace` 98 passed, 1 failed (the `features` fixture, also failing on 0e01fb3); `npm run test:std` 115 passed, 1 failed (feature-node inventory drift, since fixed by #23); test:vite and test:docs passed; clippy clean for the new code. ## Left out / uncertain - **What the codemods see**: the given files are the whole program. Uses in other files aren't seen, and the report notes this for every exported function or enum it changes. `.vue` files are skipped, with a warning. - **throw-to-result** converts top-level `function` declarations only, not arrow functions assigned to consts or methods. - **null-to-undefined**: deciding what is "outside" is a heuristic: a list of null-returning APIs and DOM properties, plus any type not declared in the given files. A `null` reaching a value through a path it doesn't follow (an unusual library method, several hops through functions) can be converted wrongly. tsc catches most of these, since the converted types reject `null`; a runtime-only case wouldn't be caught. The docs say this. - **ts-enum**: a numeric enum's type accepted any `number`; after conversion, tsc flags code that relied on that. That's intended, but it means "keeps compiling" holds only for code that didn't pass non-members. - **Formatting**: comments inside a rewritten enum body, or inside a removed `| null`, are lost; they're within the edited range. - **Rustfmt**: the repo isn't formatted with one rustfmt config, so I formatted only the new files (`max_width=120`, `use_small_heuristics=Max`, the width the existing core files match) and left existing code alone. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
sionzee force-pushed codemods from ff5a4c3725 to 7103943a6e
All checks were successful
Benchmarks / bench (pull_request) Successful in 3m34s
2026-11-03 23:34:53 +01:00
Compare
sionzee deleted branch codemods 2026-11-04 21:22:20 +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!20
No description provided.