Skip to content

Adopting SAFE-TS ​

How to add SAFE-TS to a greenfield project or roll it out incrementally across an existing codebase.

In short

  • Install & wire up: add the packages, extend the oxlint preset, and enable the Vite plugin.
  • Run transforms outside Vite: Node scripts, workers, and node --test need --import @evobug_com/safe-ts-transform/register (Running TypeScript in Node); Bun uses its bunfig.toml preload (Bun). Vite loads its own config without plugins (The Vite config).
  • Turn on the strict tsconfig flags: enable strict, noUncheckedIndexedAccess, exactOptionalPropertyTypes, and "types": ["@evobug_com/safe-ts-std/strict-lib"] (why each matters; for legacy repos, measure then ratchet).
  • Run whole-program CI checks: safe-ts check src/main.ts follows imports across tsconfig.json paths; pass --deny-warnings to gate warnings too, and configure overrides per directory in package.json (rule levels).
  • Migrate incrementally: keep new files strict from day one, tag legacy files with // @safe-ts legacy, automate repetitive conversions with safe-ts migrate, and lock escape-hatch counts with --baseline.
  • Migrating with an AI agent? Install the migration skill.

Setup ​

sh
npm install -D @evobug_com/safe-ts-transform @evobug_com/oxlint-plugin-safe-ts oxlint
npm install @evobug_com/safe-ts-std

Node needs the loader

q(...), parseJson<T>(...) and the prelude are rewritten at build time. Code that skips the rewrite fails when it gets there: q() throws "q() was not compiled". The bundler plugin rewrites an app; for code Node runs directly, start Node with --import @evobug_com/safe-ts-transform/register. See Running TypeScript in Node. For Bun, see Bun. match, is and variant imported by name need no rewrite: they run anywhere.

  • tsconfig: turn on strict, noUncheckedIndexedAccess and exactOptionalPropertyTypes. Each keeps something true that a rule counts on, and safe-ts check warns when the tsconfig that applies leaves one off (the table); the rules about absence, for one, assume items[i] is typed T | undefined (why). And load @evobug_com/safe-ts-std/strict-lib in types: TypeScript's own declarations hand out any (JSON.parse, response.json(), Array.isArray, new Map(), a promise's rejection reason), which switches the type checks off for that value; strict-lib makes them unknown, so tsc refuses JSON.parse(text).name until the value is checked (no-hidden-any). safe-ts check warns when the tsconfig doesn't load it. A types list replaces TypeScript's default of every @types package: list the ones you use ("node"), and the prelude if you use it.
jsonc
// tsconfig.json
{
  "compilerOptions": {
    "strict": true,
    "noUncheckedIndexedAccess": true,
    "exactOptionalPropertyTypes": true,
    // and the @types packages you use: "node", ...
    "types": ["@evobug_com/safe-ts-std/strict-lib"]
  }
}

The tsconfig flags SAFE-TS relies on ​

safe-ts check reads the tsconfig that applies to each entry (the nearest one, through extends; for a solution file, "files": [] with references, one of its projects having the flag is enough) and warns, once per flag, when it leaves one of these off. Each program below is accepted by tsc with the flag off, safe-ts check --idiomatic reports nothing in it, and it fails at run time (or computes the wrong thing); tsc refuses it once the flag is on (crates/safe_ts_core/tests/tsconfig_flags.rs checks each, with the TypeScript the repository installs).

FlagWithout ittsc then accepts
strictNullChecksundefined and null leave every type: Option<T> is T, items[i] is always there, and no absence check is asked forfunction size(o: Option<string>): number { return o.length; }
noImplicitAnya parameter written without a type is any, and so is everything read through itfunction first(x): number { return x.a.b; }
strictFunctionTypesa function type's parameters are compared in both directions; no-method-signature's rewrite exists to get this check, and checks nothing without itconst h: (x: string | number) => number = (x: string) => x.length;
strictBindCallApplyf.call(t, ...), .apply and .bind take any arguments, and the checker reads f.call(t, x) as f(x)fixed.call(undefined, "x") for fixed(n: number)
strictPropertyInitializationa class field typed as always there is undefined until something assigns itclass Box { name: string; }, then new Box().name.length
noImplicitThisthis in a function that doesn't declare it is anyfunction read(): number { return this.value.deep; }
useUnknownInCatchVariablesthe value a catch gets is anycatch (e) { return e.message.trim(); }
strictBuiltinIteratorReturniterator.next().value is any, where a finished iterator gives undefinednew Map<string, number>().keys().next().value.toUpperCase()
exactOptionalPropertyTypesan optional property accepts undefined written out, so { ...defaults, ...changes } is typed with every default there while a key: undefined in changes erases itmerge({ theme: undefined }).theme.length for merge(changes: Partial<Settings>): Settings

strict turns on every one of the first eight. A tsconfig without strict (with TypeScript 5, where it is off unless set; 6 and later turn it on) gets one warning naming the members it leaves off, and a member set to false on its own gets its own. noUncheckedIndexedAccess and strict-lib have their warnings too (above).

Not warned about, and why:

  • skipLibCheck: with it on, a type that a package's declarations import from a package that isn't installed is any, and nothing says so (import { load } from "lib"; load().size.deep compiles when lib's declarations name a type from a package missing from the install). It is a hole, but warning on it would cost more than it finds: nearly every scaffold sets it, and turning it off under the flags above reports errors in third-party declarations a project can't fix. Run tsc with "skipLibCheck": false once after adding a package, and look at any Cannot find module it reports in node_modules.

  • noImplicitOverride: no rule finds an override by its override keyword. override-parameter and failure-contract compare a method with the one of the same name in the class it extends, keyword or not.

  • noFallthroughCasesInSwitch: a case that runs into the next is the code's choice; TypeScript types it right, and no rule reads a case as ending where it doesn't.

  • noPropertyAccessFromIndexSignature: with noUncheckedIndexedAccess, record.key is T | undefined either way; the flag only asks for record["key"], which the checker reads as record.key.

  • alwaysStrict: every ES module is strict code already.

  • verbatimModuleSyntax, erasableSyntaxOnly: they don't let a wrong value through; they keep a module from failing to load under Node's own type stripping, which fails loudly, at once, and never under Vite or Bun. Recommended for code Node runs itself (Running TypeScript in Node).

    On a new project that costs nothing. On an existing one, measure it first: each flag is a type-checker setting, so the errors come from tsc (or vue-tsc), not from SAFE-TS. One Vue app of 113,000 lines with strict already on got 958 errors from noUncheckedIndexedAccess and 348 from exactOptionalPropertyTypes. They cluster: most of the 958 were in three algorithmic modules (a diff walkthrough, a rebase resolver), and were fixed by hand there; no codemod does it. See the tsconfig flags for a route that doesn't stop the team.

  • The safe-ts command (safe-ts check, explain, migrate, lsp): it comes with the packages above, in @evobug_com/safe-ts-native, and is on the PATH of package.json scripts, npx and bunx. pnpm links the commands of direct dependencies only: there, add it with pnpm add -D @evobug_com/safe-ts-native. safe-ts --version prints the version, for bug reports and CI logs.

jsonc
// package.json
{ "scripts": { "check": "safe-ts check src/main.ts", "check:summary": "safe-ts check src/main.ts --summary" } }

npx safe-ts check src/main.ts and bunx safe-ts check src/main.ts run the installed one. In a folder where it isn't installed they would download an unrelated npm package named safe-ts: there, name the package, npx -p @evobug_com/safe-ts-native safe-ts check ....

  • Editor: the SAFE-TS language server shows problems as you type, in .ts and .vue files, with quick fixes. It is the safe-ts command above (safe-ts lsp). For VS Code there is an extension: Editor.
  • CI checks: extend the recommended oxlint config. The oxlint language server can also show the problems in the editor. In .vue files oxlint hands the plugin one script block at a time; the plugin checks the whole component (template included) from the file on disk (Vue setup).
jsonc
// .oxlintrc.json
{ "extends": ["./node_modules/@evobug_com/oxlint-plugin-safe-ts/recommended.json"] }

It turns on every safe-ts/* rule, plus oxlint's own rules that the v8.dev review pointed at: precision loss in number literals (no-loss-of-precision), Object.hasOwn over hasOwnProperty (prefer-object-has-own), holes in array literals (no-sparse-arrays), keeping the caught error as cause (preserve-caught-error), eval and friends, and suggestions such as .at(-1), replaceAll and flatMap. Rules that would fight the build-time transforms (for example unicorn/no-array-for-each, while forEach is turned into a loop) are left out, and so is unicorn/prefer-global-this: with both @types/web and @types/node loaded, its fix turns window.setTimeout(...) (a number) into globalThis.setTimeout(...) (Node's NodeJS.Timeout), so timer: number fields stop compiling. Rules that need type information (require-array-sort-compare, prefer-nullish-coalescing) only work in oxlint's --type-aware mode.

On an existing codebase, extending the preset changes more than SAFE-TS. Its 33 oxlint rules (listed below) are ordinary lint: // @safe-ts legacy silences only the safe-ts/* rules, so they report in legacy files too. One Vue app got 7 new errors and about 140 new warnings in files that were all marked legacy. Your own rules win over the preset's, so set the ones you aren't ready for to "warn" or "off" while files are legacy, and delete those lines once the code is fixed. Running oxlint once with the extends and once without shows what it adds.

The preset's oxlint rules

Errors: no-loss-of-precision, no-prototype-builtins, prefer-object-has-own, no-sparse-arrays, no-proto, no-extend-native, no-constructor-return, no-misleading-character-class, no-useless-backreference, preserve-caught-error, no-unsafe-finally, no-empty, guard-for-in, no-sequences, no-shadow-restricted-names, no-eval, no-new-func, no-implied-eval, unicorn/no-thenable, unicorn/no-invalid-remove-event-listener, oxc/bad-replace-all-arg, typescript/no-dynamic-delete.

Warnings: prefer-rest-params, prefer-spread, prefer-object-spread, prefer-exponentiation-operator, unicorn/prefer-at, unicorn/prefer-string-replace-all, unicorn/prefer-string-trim-start-end, unicorn/prefer-includes, unicorn/prefer-array-flat-map, unicorn/prefer-array-find, unicorn/no-new-array.

unicorn/numeric-separators-style is not in it: it only changes how a number is written, and its fix breaks a program that reads the number's text, such as a server config reading a port from a .ts file with a regular expression (below). Nor are oxlint's promise/* rules: if oxlint --deny-warnings asks for a return at the end of a .then((x) => { ... }) callback (promise/always-return), that rule comes from your own config.

  • Build: add the bundler plugin, which rewrites q(...), match(...), parseJson<T>(...) and prelude names at build time:
ts
// vite.config.ts
import { safeTs } from "@evobug_com/safe-ts-transform";
import { defineConfig } from "vite";

export default defineConfig({ plugins: [safeTs()] });

The plugin also runs the SAFE-TS rules on every file it transforms, so problems show up in the dev server too: safeTs({ check: "warn" }) (the default) prints them in the terminal, "error" shows Vite's error overlay in the browser and fails the build when a finding is an error (warnings are printed, rule levels), false turns it off. It resolves imports with tsconfig.json paths and the string aliases of Vite's resolve.alias, and warns once per import and file about one it can't follow (How imports are followed). vite build ends with one line saying what the plugin saw:

text
safe-ts: 1,293 files checked, 960 legacy, 0 problems

(The dev server transforms files as the browser asks for them, so it has no end to report at.) Files the plugin should leave alone entirely, such as vendored or generated code, go in exclude: globs relative to Vite's root, regular expressions tested on the absolute path, or a function of the path:

ts
safeTs({ exclude: ["src/vendor/**", "**/*.generated.ts", (file) => file.includes("/third-party/")] });

An excluded file is neither checked nor transformed, so it must not use q, match, parseJson or prelude names. For your own code that isn't migrated yet, use the legacy marker instead.

In the dev server (and the Node loader) the transform also adds dev checks: runtime checks for a few things the rules can't see, such as q(...) given a Promise. vite build leaves them out; safeTs({ devChecks: false }) turns them off in development too.

Each named type's JSON validator is generated once, in a module every file using it imports (One validator per type). safeTs({ sharedValidators: false }) gives every file its own copies instead.

  • Faster startup in Chrome (opt-in): safeTs({ compileHints: true }) adds //# allFunctionsCalledOnLoad to entry chunks, so Chrome 136+ compiles their functions in the background while loading, instead of on first call. V8 measured 630 ms less main-thread parse and compile time on average across 20 sites (v8.dev). It also compiles functions that never run, which costs memory: use it for chunks whose code runs at startup, or pass chunk names (compileHints: ["main"]). The plugin checks the finished chunks too, so the comment survives a minifier that drops comments after the plugins ran (Rolldown's, in Vite 8).
  • Large data in code (opt-in): /** @json */ on a module-level const holding plain data (a table, translations, a config) turns its literal into JSON.parse("..."), which loads faster: 2.6x for 180 kB, measured on Node 26 with a cold start each time. JSON is a simpler grammar to parse (v8.dev). Only data JSON keeps exactly qualifies; anything else is reported by json-literal.
  • Node without a bundler (servers, workers, scripts, tests): node --import @evobug_com/safe-ts-transform/register main.ts, on every command. See Running TypeScript in Node.
  • Bun (bun run, bun test, bun build): preload @evobug_com/safe-ts-transform/bun in bunfig.toml, and bundle with Bun.build({ plugins: [safeTsBun()] }). See Bun.
  • A project inside the project (a folder with its own package.json and tsconfig.json, such as a CLI next to the app) needs the setup too: @evobug_com/safe-ts-std in its own package.json, and "@evobug_com/safe-ts-prelude" in its own tsconfig.json's types. The transform reads the nearest tsconfig.json, not the one it extends, so without that entry prelude names get no imports there (details).
  • Checking the whole program (CI): safe-ts check src/main.ts follows every import from the entry (relative paths, tsconfig.json paths aliases and workspace packages; see How imports are followed), workers started with new Worker(new URL("./worker.ts", import.meta.url)), and modules loaded with import(): lazy routes (component: () => import("./views/Home.vue")), defineAsyncComponent, code loaded on demand. import(`./locales/${lang}.ts`) and import.meta.glob("./widgets/*.ts") bring in every file they can match, by Vite's rules (each ${...} stands for one path segment). Calls into a loaded module are followed: m.f() after const m = await import("./x"), a destructured f(), and import("./x").then((m) => m.f()). In a monorepo, give every app's entry in one run: safe-ts check apps/web/src/main.ts apps/server/src/main.ts. A package several apps use is then checked, and its problems reported, once. A file nothing imports or loads with its path written out (a worker or module whose path is built at runtime, a script, a file nothing uses yet) is checked only when it is an entry too, so a directory is an entry for each of its source files: safe-ts check src checks every .ts, .tsx, .mts, .cts and .vue file under src (not .d.ts files, node_modules or hidden directories) as one program, and files and directories mix (safe-ts check src scripts/seed.ts). Symlinked directories are followed, and each file is checked once, also when a link leads back up or two paths lead to it (as fix and migrate take directories too). With file entries, check looks through each entry's directory for source files the run didn't reach, and names them (the first ten, then how many more):
text
warning: 1 source file under the entries' directories is not checked: nothing the entries import reaches it: src/orphan.ts. Pass the directory to check every file in it (`safe-ts check src`), or add the file as an entry

Build output (dist, build, out, coverage, target), a directory with its own package.json (another package, checked from its own entries), tool configs (vite.config.ts, vitest.config.ts: the tool loads them) and the validator modules safe-ts emit writes (*.safe-ts-json.ts) don't count. --json prints the problems as JSON (below). --summary counts them by rule and by directory instead of listing each one, which is the table to start a migration from. It exits with 1 when there are errors; warnings are printed and counted, and fail the run only with --deny-warnings or --max-warnings <n> (rule levels). An import that resolves to nothing (below) and a source file the run didn't reach count as warnings there: both are code that wasn't checked, and the status line says ⚠ 1 unresolved import or ⚠ 2 files not checked instead of ✓ no problems. --idiomatic also reports the idiomatic rules, for one run. --write-baseline <file> and --baseline <file> hold the escape hatches down (a ratchet).

  • Which rewrites happened: safe-ts explain src/orders.ts lists every place a build-time rewrite could apply (q, match, loops, enum constructors, @inline, @loop), whether it did, and why not when it didn't, e.g. "a callback before the last step has side effects". Rewrites that don't apply leave correct, slower code, so nothing else would tell you.
  • Type-checking the rewritten code: safe-ts emit <out-dir> <entry.ts>... writes the program the entries reach, rewritten, in the project's layout under <out-dir>: what they import, workers started with new Worker(new URL(...)) and modules loaded with import(), as check follows them. Then run tsc on it, with allowImportingTsExtensions (see the next point). This catches, for example, a q(...) that propagates an error type the function doesn't declare.
  • Running without the loader (a production build step): the emitted program runs with plain node out/apps/server/src/main.ts, or bun out/apps/server/src/main.ts (Bun). An import of a package that resolves to your own source (a workspace package, linked into node_modules) is pointed at its emitted copy: from "@acme/pricing" becomes from "../../../packages/pricing/src/index.ts". Otherwise the package name would load the source without the rewrites. Packages installed in node_modules keep their names. Relative imports stay as written, so for Node they need their extension (./config.ts); the loader adds a missing one, plain Node doesn't. Imports in .vue files aren't changed.

How imports are followed ​

safe-ts check, the editor, the oxlint plugin, the Vite plugin and the Node loader resolve an import the same way, so they agree on what it means. It is resolved as a bundler does with "moduleResolution": "Bundler":

  • Relative paths, with the extension or /index.ts left out, and ./x.js for ./x.ts.
  • compilerOptions.paths and baseUrl of the tsconfig.json that includes the importing file: "@utils/*": ["./src/utils/*"], exact keys ("config": ["./src/config.ts"]), and several targets, tried in order. Also when they come through extends (a file or a package, such as @vue/tsconfig), and from the references of a solution tsconfig.json, as in Vite's scaffold. A .vue file gets the paths of the tsconfig.json that includes the .ts files next to it.
  • Workspace packages linked into node_modules, whose source is in the project.

Vite's resolve.alias is read by the Vite plugin only: it hands the aliases with a string find to its checks and to the transform. safe-ts check, the editor and the oxlint plugin don't load the Vite config, so tsconfig.json paths is the source of truth: write every alias there too (TypeScript needs it there anyway), and a regular-expression alias as the paths patterns it stands for.

An import that resolves to nothing isn't followed, so what it would bring in goes unchecked. safe-ts check names each one, once per specifier, with the files importing it:

text
warning: could not resolve "@utils/b" from src/a.ts: the checker doesn't follow it (for an alias, check tsconfig.json `paths`)

Each one counts as a warning: the run ends ⚠ 1 unresolved import, not ✓ no problems, and fails with --deny-warnings (--json --summary has the count, unresolvedImports).

The editor underlines the specifier, the oxlint plugin and the Vite plugin print the same line once per import and file. Packages aren't named: an installed one (also one with only types, or with no JavaScript for this import), a Node or Bun built-in, virtual: and other scheme: imports, or any bare name before dependencies are installed. Nor are stylesheets, images and data (/vite.svg from Vite's public directory, ./logo.svg?raw), which the checker doesn't follow anyway. A bare name that no installed package provides is named: usually an alias Vite knows and tsconfig.json doesn't.

Library code is what is under a node_modules directory below the project root: the directory safe-ts check runs in, the Vite root, the directory oxlint runs in. It isn't checked, and its types can't be validated (json-type). A project that itself lives under some node_modules (a copy in node_modules/.cache) is checked as a project when you run in it.

Running TypeScript in Node ​

Node strips the types from a .ts file, but doesn't rewrite q(...), parseJson<T>(...), validate<T>(...), arbitrary<T>() or prelude names. The loader does:

sh
node --import @evobug_com/safe-ts-transform/register src/main.ts

Node strips the types itself, so for code it runs, turn on verbatimModuleSyntax and erasableSyntaxOnly in that code's tsconfig: without them, tsc accepts a type imported without type (import { Point } from "./types.ts", which then fails to load: does not provide an export named 'Point') and syntax Node can't strip (a constructor's parameter properties, enum, a namespace holding values), which fails to load too. Loud and at once, so safe-ts check doesn't warn about them; a project Vite or Bun builds never meets it.

Every process that runs your TypeScript needs it, and a missing one shows only at runtime, where the first q(...) throws. What Node can't resolve, the loader resolves the way safe-ts check does (How imports are followed): tsconfig.json paths aliases (@utils/router), baseUrl, and an import without its extension or /index.ts. So a test imports the same files the check followed, and a validator finds a type imported through an alias. Checked on Node 26.13:

  • Entry points and scripts. Each node command: the scripts in package.json, a Dockerfile's CMD, a systemd unit. --import goes before the file. safe-ts check warns about scripts in the package.json nearest each entry that run a .ts file with plain node, when the program uses something the loader rewrites:

    text
    warning: package.json: script `start` runs `node src/main.ts` without the safe-ts transform, but this program uses `q(...)`, ...

    It looks only at commands that start with node itself; tsx, nodemon and shell scripts aren't read. Nor are the commands written for people: a script's header comment (// Run: node scripts/import-products.ts), a README, a runbook. A script that uses what the loader rewrites (q(...), parseJson<T>, prelude names such as unsafe) needs --import in those too, so update them when you migrate the script.

  • worker_threads workers. A Worker inherits its parent's execArgv, --import included, so a worker started from a process that has the loader has it too. Passing execArgv to the Worker replaces the inherited one: put the --import in it. The loader imported from code (import "@evobug_com/safe-ts-transform/register" in the entry file, rather than --import) applies to that thread only, and workers don't get it.

  • Child processes. child_process.fork inherits execArgv the same way. spawn("node", ...) doesn't: give it the --import too.

  • Tests. node --import @evobug_com/safe-ts-transform/register --test "test/*.test.ts": the test runner passes --import on to the process that runs each test file. Vitest uses the Vite plugin from your config instead.

  • Everything at once. NODE_OPTIONS="--import @evobug_com/safe-ts-transform/register" reaches every Node process started with that environment, workers with their own execArgv included.

The loader keeps what it rewrote in a cache on disk, so a restart, a worker or a test process doesn't rewrite the same file again. An entry is used while the file, every file the rewrite read for it (the types behind parseJson<T>, @inline functions, enum tables, the tsconfig), the options (dev checks) and the transform itself are unchanged. It lives in node_modules/.cache/safe-ts of the nearest directory above the current one that has a node_modules, or in the system's temporary directory when that isn't writable.

  • SAFE_TS_CACHE=0 turns it off; SAFE_TS_CACHE_DIR=<dir> puts it somewhere else.
  • Entries are written to a temporary file and renamed into place, so threads and processes starting at once share it safely.
  • Each file has one entry per set of options; a new version of the file replaces it, so the cache doesn't grow as you edit. Writing an entry keeps the file's three newest (entries made by an older transform, or with options no longer used, go), and about once a day a write also drops the entries of files that no longer exist. Deleting the directory is always safe: rm -rf node_modules/.cache/safe-ts.
  • A shared validator module (types.ts?safe-ts-json=v$User) has an entry of its own, used while types.ts and the other declarations it was built from are unchanged.
  • The checker keeps what automatic mode found in each library in the same directory (<package>@<version>....json, in the node_modules the package is installed in), and honours the same two variables.

Resolve hooks of your own. The loader already resolves an extensionless relative import (./config) to ./config.ts, as bundlers do, so code written for Vite needs no hook for that. A hook you register yourself (module.registerHooks) also sees the shared validator modules a rewritten file imports, ./types.ts?safe-ts-json=v$User. Keep the query as it is: a hook that appends .ts to every relative specifier turns it into ...?safe-ts-json=v$User.ts, and the load fails ("no type User.ts is declared", or ENOENT). Add the extension before the ?, or pass on a specifier with a query unchanged:

js
// hooks.mjs: node --import @evobug_com/safe-ts-transform/register --import ./hooks.mjs ...
import { registerHooks } from "node:module";

registerHooks({
  resolve(specifier, context, nextResolve) {
    const [path, query = ""] = specifier.split(/(?=\?)/);
    if (/^\.\.?\//.test(path) && !/\.[cm]?[jt]sx?$/.test(path)) {
      return nextResolve(`${path}.ts${query}`, context);
    }
    return nextResolve(specifier, context);
  },
});

SAFE_TS_SHARED_VALIDATORS=0 also avoids it, at the cost of a validator copy in every file.

Generic arrows in .mts files. const first = <T>(items: T[]) => items[0] is a parse-error in a .mts or .cts file under the loader, because TypeScript reserves that syntax there. Node's own type stripping runs it, so a test file that worked before the loader was added stops at it. Write <T,>(items: T[]) => ...; the message says so.

A file that uses prelude names (q, unsafe, err, ...) where no tsconfig.json above it turns the prelude on runs without those imports, and fails with ReferenceError: q is not defined. The loader warns first, naming the file and the names: typically a script copied out of the project (to /tmp, with a node_modules link), which leaves its tsconfig.json behind. Keep it inside the project, or import the names from @evobug_com/safe-ts-std.

The loader costs memory in every thread that has it: about 10 MB for the transform and its native addon, before any file is loaded (Node 26, Linux). A server with several workers pays it once per worker. Two ways to avoid it in production: run the program safe-ts emit wrote, without the loader, or start workers that only run plain JavaScript with execArgv: [], so they don't inherit --import.

The Vite config ​

Vite loads vite.config.ts, and every file it imports, before any plugin runs, so safeTs() doesn't rewrite them. Code there that needs the rewrite fails as soon as it runs: a prelude name throws ReferenceError: PropagateError is not defined, and q(...) throws "q() was not compiled". Tests of the same code pass, because their process has the loader. Three setups work (checked with Vite 8.3):

  • Load what needs the rewrite with loadTransformed. It registers the loader's hooks in Vite's process and imports the module through them, so it and everything it imports are rewritten. You get the module's exports, plugins and functions included, with any config loader:

    ts
    // vite.config.ts
    import { loadTransformed, safeTs } from "@evobug_com/safe-ts-transform";
    import { defineConfig } from "vite";
    
    const { offlinePage } = await loadTransformed<typeof import("./scripts/offline-page.ts")>(
      new URL("./scripts/offline-page.ts", import.meta.url),
    );
    
    export default defineConfig({ plugins: [safeTs(), offlinePage()] });

    Only what goes through loadTransformed (or a later import()) is rewritten: a module the config also imports the usual way is loaded first, without the hooks, and stays as it was. import type of the same module is fine.

  • Load the config through the loader. Vite's default config loader bundles the config with its imports, which bypasses Node's module hooks. With --configLoader native, Node loads it, and the loader rewrites it:

    sh
    NODE_OPTIONS="--import @evobug_com/safe-ts-transform/register" vite build --configLoader native
  • Keep the config's imports free of what needs the rewrite. Import std names explicitly (import { PropagateError } from "@evobug_com/safe-ts-std/result") instead of using the prelude, and don't use q(...), parseJson<T> or validate<T> in files the config imports.

import "@evobug_com/safe-ts-transform/register" as the config's first line is not enough on its own: Node loads every file the config imports before running any of them, so the loader is registered too late for them. It does apply to modules the config loads later with await import("./dev/api.ts") (with the default and the native config loader).

In such a file, needs-transform reports each q(...), parseJson<T> and prelude name used without its import, with the plain form as a quick fix (const x = make(); if (isErr(x)) return x;, or the import). It looks for vite.config.*, vitest.config.* and vitest.workspace.* in the file's folder and the folders above it, and follows what they import. There, the other rules' quick fixes don't write q(...) and import the std names they add.

safe-ts check warns about it: when the folder of an entry's nearest package.json has a vite.config.* that imports, directly or not, a file needing the rewrite (unless the package.json passes --configLoader native). safeTs() prints the same warning when Vite starts with such a config, naming the files. Only code that runs when the config loads counts: imports of types (import type, or names used only as types), prelude types such as Option<T>, and import() or loadTransformed(...) in the config are left out. When the config imports the register hooks, the warning says why they don't cover its own imports.

JSON output ​

safe-ts check --json prints the problems as one JSON array on stdout, and nothing else (the propagation map and the summary are left out). What the run couldn't see goes to stderr, so it stays in a CI log: the warnings (unresolved imports, config problems), the source files not checked, and what package.json weakens below the defaults. With --summary it prints one object instead: the checker's version, files, lines, problems (of them errors and warnings), legacyFiles, rules (the count of each rule), directories (for each directory: problems, and rules as before), escapeHatches (each count of the escape-hatch line), weakened (each rule or setting package.json sets below the defaults: the package.json, the setting (a rule's name, or infer, infer.exclude, testRunners, vue.sanitizers, vue.ssr), its value and, for an "overrides" entry, its files), configs (per package.json, what a baseline compares with its earlier state), setupWarnings (the warning: lines about the setup), unresolvedImports and unreachedFiles (every source file not checked).

jsonc
{ "version": "0.6.0", "files": 1293, "lines": 113000, "problems": 5484, "errors": 5400, "warnings": 84,
  "legacyFiles": 0,
  "rules": { "no-null": 421, "unhandled-failure": 163 },
  "directories": { "src/stores": { "problems": 58, "rules": { "no-null": 40, "unhandled-failure": 18 } } },
  "escapeHatches": { "unsafeBlocks": 12, "panicCalls": 0, "trustCalls": 3, "legacyNulls": 0, "cacheMarks": 1,
    "safeTsIgnores": 2, "legacyFiles": 0, "stdFiles": 1, "tsIgnores": 0, "tsExpectErrors": 1,
    "testExpectErrors": 14, "tsNochecks": 0, "vueSkips": 0, "lintSuppressions": 2, "skippedTests": 4,
    "ambientDeclarations": 3, "sanitizers": 1 },
  "weakened": [{ "config": "package.json", "setting": "no-mutable-global", "value": "off", "files": ["src/stores/**"] }],
  "configs": { "package.json": { "idiomatic": true, "features": ["@evobug_com/safe-ts-feature-browser"],
    "emitters": [], "requestFunctions": ["api"], "vueSsr": false } },
  "setupWarnings": 0,
  "unresolvedImports": 0,
  "unreachedFiles": ["src/legacy/old-report.ts"] }

Each problem in the array has:

Field
filethe file, relative to the current directory
rulethe rule, without the safe-ts/ prefix: unhandled-failure
severity"error" or "warning": the rule's level for this file
message, helpthe text check prints; help may be null
line, column, endLine, endColumnwhere it is: 1-based, columns counted in UTF-16 code units, as editors count them
paththe functions the failure passes through, from the called one to the one it starts in: ["readConfig"]. [] when the call itself fails
originwhere the failure starts: "JSON.parse() at src/config.ts:10:10". Findings with the same origin have one root cause
pathsone { "path", "origin", "kind" } per error that can get out, kind being the PropagateError class (null for unhandled-failure). path and origin above are the first one

unhandled-failure, uncaught-propagation and floating-rejection fill in path, origin and paths when they report a failure they traced. Other findings have null, null and [].

json
[
  {
    "file": "src/main.ts",
    "rule": "unhandled-failure",
    "severity": "error",
    "message": "`readConfig` can throw, but the failure is not handled",
    "help": "Failure path: readConfig → JSON.parse() at src/config.ts:10:10. Wrap it: `unsafe(() => ...)` returns a Result",
    "line": 7,
    "column": 42,
    "endLine": 7,
    "endColumn": 57,
    "path": ["readConfig"],
    "origin": "JSON.parse() at src/config.ts:10:10",
    "paths": [{ "path": ["readConfig"], "origin": "JSON.parse() at src/config.ts:10:10", "kind": null }]
  }
]

Checker.checkFile in @evobug_com/safe-ts-native (one file, as the editor checks it) gives its diagnostics severity, path and origin too, but not paths.

The prelude: no imports ​

Install it (npm install -D @evobug_com/safe-ts-prelude), add "@evobug_com/safe-ts-prelude" to compilerOptions.types, and use Result, Option, q, match, Enum, parseJson, PropagateError, ... without importing them. The transform adds the imports a file needs at build time; nothing is put on globalThis.

jsonc
// tsconfig.json
{ "compilerOptions": { "types": ["@evobug_com/safe-ts-prelude", "@evobug_com/safe-ts-std/strict-lib"] } }

The prelude doesn't load strict-lib itself: keep both in the list (Setup).

A tsconfig that sets typeRoots makes TypeScript look up types entries in those folders only, so the line above fails with TS2688: Cannot find type definition file for '@evobug_com/safe-ts-prelude'. Add "node_modules" to typeRoots:

jsonc
// tsconfig.json
{
  "compilerOptions": {
    "typeRoots": ["node_modules/@types", "node_modules", "src/types"],
    "types": ["node", "@evobug_com/safe-ts-prelude"]
  }
}

A local with a prelude name wins in its own scope only, so a helper q in one function and the prelude's q in another both work; prelude-shadow reports a local named unsafe, and one named q, match, is, err or Result in a file that uses the prelude's too. In a function Playwright runs in the page (page.evaluate(fn)), the module's imports don't exist: prelude-in-page reports prelude values there.

Existing code: start strict, mark legacy ​

Turning the rules on for a large codebase at once produces thousands of errors. Instead:

  1. New code is strict from day one.

  2. Old code gets a marker in its first lines:

    ts
    // @safe-ts legacy

    In a .vue file, put it on the first line inside either <script> block, or as an HTML comment at the top of the file. Either marks the whole component, template included:

    vue
    <!-- @safe-ts legacy -->
    <script setup lang="ts">
    // ...or here: // @safe-ts legacy
    </script>

    A marker anywhere else in a component marks nothing, and is reported (vue-sfc).

    The file must also be listed in the package.json, under "legacyFiles" (patterns relative to it, as in "overrides"):

    json
    { "safe-ts": { "legacyFiles": ["src/old/**", "src/forms.vue"] } }

    A marker in a file the list doesn't name is reported (unlisted-marker) and the file is checked as if it weren't there: anyone can write a comment, and the list puts the decision in package.json, where it is reviewed. safe-ts check prints the "legacyFiles" and "trustedFiles" lines that list every marked file it found, for a project upgrading in one step. // @safe-ts std works the same way, with "trustedFiles".

    The rules are not reported inside that file, but strict code calling into it still is: if a legacy function can throw, the strict caller gets unhandled-failure with the full failure path through the legacy code. Legacy code is quarantined, not ignored. This holds for every import the checker follows: a relative path, a tsconfig.json paths alias (import { f } from "@utils/leg"), a workspace package. An import it can't follow is named in a could not resolve warning (How imports are followed): behind it, the quarantine doesn't reach, so fix those first.

    The bundler plugin and the Node loader give a legacy file only the rewrites it needs to run: prelude imports (a legacy file using unsafe or isErr without importing them still works), q(...), match(...) and parseJson<T> / validate<T>. The rewrites that only make code faster (loops, @inline, @json, @loop, enum constructors) and the dev checks are left out, so adopting SAFE-TS doesn't change the code you ship until a file is migrated. safe-ts explain lists them as "not applied, the file is marked legacy".

  3. Migrate file by file. Remove the marker, apply the quick fixes, commit. safe-ts check prints how many legacy files and escape hatches are left: your progress report (below). For the changes that repeat across a codebase, use a codemod. One line in a migrated file that must stay as it is takes an ignore comment, not a marker.

Where to start. One throw in a small helper (a byId(id) that throws when the element is missing) is reported at every caller that doesn't handle it, and their callers. When findings share an origin, safe-ts check ends with a summary:

text
Root causes: 312 unhandled-failure findings come from 9 places
  187  throw at src/dom.ts:12:5
   64  JSON.parse() at src/storage.ts:30:18
  ...

Fixing the helper (returning a Result, or handling the failure inside it) clears all of its findings at once.

Markers are a staging device, with a burn-down. Mark every file that fails on day one (a short script does it), so CI is green from the start, and from then on only remove markers. The legacy count in the escape-hatches line (below) is the burn-down: record it per week or per release, and treat a file that gains a marker as a review question, like a new unsafe(...). Don't keep legacy files away from the transform (with exclude, or a wrapper around the plugin): it gives them the prelude imports, so prelude names (unsafe, isErr) work in them. Without it, a legacy file using one fails with ReferenceError: unsafe is not defined in the browser, and neither tsc nor the checker says so.

Run the app in a browser, and compare. tsc, the checker and unit tests all passed while a migration broke two things that only a browser showed: a startup check that validated data another module decorates with functions as it loads, and a legacy file using a prelude name the build didn't rewrite. A smoke run of every page, with the browser console watched for errors and Vue warnings, is a gate no tool replaces. It is worth more as a comparison: build the baseline and the branch, run both against one database with outside services blocked, and compare what they render and the bodies of the requests they send (a null that became a missing key shows up there, on the wire). One team compared 490 formatted dates, 44 screenshots and 16 write requests that way; cheap once the harness existed, it caught more than any rule.

With an agent. The migration skill has an agent plan the target architecture first, take a census of what the checker reports (with the idiomatic rules) and of the hand-rolled patterns it doesn't (loading flags, sentinels, string if-chains, casts), and migrate area by area behind gates that let those counts only fall. An agent told to make the checker pass stops at the first run that exits 0, and a run with only warnings does: give it safe-ts check ... --deny-warnings as the gate.

Rule levels: errors, warnings, off ​

Each rule is an error, a warning or off. The defaults are the oxlint preset's (recommended.json): the rules that protect data and control flow are errors; the ones about cost and style (stable-shape, hoist-intl, vue-render-cost, prefer-nullish-default, ...) are warnings. safe-ts check prints error[rule] or warning[rule] and exits with 1 only when there is an error. To fail on warnings too, add --deny-warnings, or --max-warnings 20 to allow up to 20. Those count every warning the run prints: a rule's, each warning: line about the setup (the tsconfig doesn't load strict-lib or leaves off one of the flags SAFE-TS relies on, a feature pack is enabled but not installed, a package.json script or the Vite config runs code without the transform; the status line says ⚠ 1 setup warning), an unresolved import, and a file not checked.

Change a rule's level in package.json, for the whole package or for some files:

jsonc
// package.json
"safe-ts": {
  "rules": { "stable-shape": "error", "no-mutable-global": "warn" },
  "overrides": [
    { "files": ["src/stores/**"], "rules": { "no-mutable-global": "off" } },
    { "files": ["src/generated/**"], "rules": { "no-null": "off", "no-any": "warn" } }
  ]
}
  • A level is "off", "warn" or "error". A rule name may have the safe-ts/ prefix.
  • files are patterns relative to the package.json: * within one directory, ** any number of them, {ts,vue} either. A pattern without a / matches the file name in any directory: "*.d.ts".
  • For each file the last word wins: the default, then "rules", then each entry of "overrides" that matches, in order.
  • A name, a level or an entry check doesn't understand is reported as a warning: line at the top of the run, and left out.
  • A rule set below the preset's level ("off", or "warn" where the preset says "error") is an escape hatch too: safe-ts check names each one under its escape-hatch line, weakened below the defaults: no-mutable-global warn, no-mutable-global off for src/stores/** (package.json), --json --summary lists them in weakened, and a baseline fails the run when one is added. Naming an idiomatic rule while the layer is off only turns it on.

The setting is read wherever the rules run: safe-ts check, the editor (warnings are shown as warnings), the Vite plugin (with check: "error", only errors stop the build), --json and the Node addon (severity on each finding). In oxlint, "off" in package.json wins: the finding isn't produced, so no oxlint setting brings it back. The level of what is produced is oxlint's: the preset's, or what your .oxlintrc.json sets ("safe-ts/stable-shape": "error", its own overrides for paths). A plugin can't pick the level of its reports, so for oxlint set "warn" and "error" in .oxlintrc.json, and "off" in either place.

Declaration files. In .d.ts files (.d.mts, .d.cts), no-null, prefer-option, no-mutable-global, no-method-signature and no-optional-field are off. A declaration describes values something else makes, such as types generated from a backend or the shape of a library: its null says what is there at run time, and the file can't change it. Where the values are made, the rules apply. The rules about types that hand callers something unchecked stay on: no-any, no-nested-option, no-unknown-in-result, no-ts-enum, and no-unchecked-declare, since nothing checks that a value a declaration file says exists (declare let current: User, export function load(): User) is there with that type (no-unchecked-declare). safe-ts check reads the project's declaration files under the entries' directories, and counts their declarations among the escape hatches. To check your own declarations for null too, turn it back on: { "files": ["src/**/*.d.ts"], "rules": { "no-null": "error" } }.

Ignoring one finding ​

When one line is right as it is, say so next to it:

✓ Accepted0 diagnostics
ts
// safe-ts-ignore no-null: the payment SDK tells "no locale" (null) from "the default" (undefined)
export const locale = null;
  • The comment silences the named rules on the next line. Name several with commas: // safe-ts-ignore no-null, no-unchecked-cast: .... A few ignore comments in a row all cover the line after them.
  • The rule and the reason are required. A comment without them, with a rule that doesn't exist, or that silences nothing (the finding was fixed, or is on another line) is reported as safe-ts-ignore, as TypeScript reports an unused @ts-expect-error. An ignore for a rule only safe-ts check reports (such as no-optional-field or unused-code) is called unused by safe-ts check only: the editor and the oxlint plugin don't see the whole program, so they can't tell.
  • In a Vue template, write it as an HTML comment before the element: <!-- safe-ts-ignore vue-unsafe-url: the server checks every link it sends -->. It covers the element's start tag, attributes on later lines included.
  • // safe-ts-ignore-file no-null: generated from the backend schema covers the whole file. For a directory, set the rule "off" in "overrides".
  • safe-ts check counts the comments in its escape-hatch line (below).

An ignore hides a finding; it doesn't change the code. A q(...) the transform can't rewrite still stops the build, ignored or not. Prefer // @safe-ts legacy for a file that isn't migrated yet, and an ignore for one line in a migrated file that the rule gets wrong or that must stay as it is. oxlint's own // oxlint-disable-next-line safe-ts/no-null works in oxlint only, says no reason and is reported (no-lint-suppression); safe-ts-ignore works everywhere and keeps a reason.

The tsconfig flags on an existing project ​

noUncheckedIndexedAccess, exactOptionalPropertyTypes and strict-lib are type-checker settings: the errors they bring come from tsc or vue-tsc, and can number in the hundreds (above). strict-lib's are where a value of JSON.parse, response.json() or Array.isArray was used unchecked (JSON.parse(raw).id, const user: User = JSON.parse(raw)): validate<T> or parseJson<T> fixes each in migrated code; a legacy file can keep its old behaviour by writing the any out (const data: any = JSON.parse(raw)), which no-any reports once the file is migrated. A route that keeps the build green:

  1. Measure. Add a tsconfig.strict.json that extends your tsconfig and turns the flags on (and adds strict-lib to types), and count: npx vue-tsc -p tsconfig.strict.json --noEmit | grep -c "error TS" (or tsc). Sort the errors by folder; they tend to sit in a few modules.
  2. Ratchet. Run the strict config in CI, and fail when its error count rises above the number committed next to it; lower the number as modules are fixed. New code then meets the flags from the first day, and old errors are fixed one module at a time.
  3. Move the flags into tsconfig.json when the count is 0, and delete the second file.

Do the last step as early as you can, even before the other markers are gone, because other tools read tsconfig.json only:

  • exactOptionalPropertyTypes errors come late, and in templates. In a migration where tsconfig.json lacked the flag, safe-ts check and vue-tsc stayed clean for weeks, and the strict config listed 14 errors after the merge, all of one kind: an optional prop x?: string given a string | undefined in a template. Builders working against the main tsconfig never saw them.
  • oxlint and SAFE-TS disagree about items[i]! without noUncheckedIndexedAccess. SAFE-TS treats items[i] as possibly missing whatever the flag says. oxlint's type-aware typescript/no-unnecessary-type-assertion follows the flag in the tsconfig it reads: without it, export const first = (items: string[]) => items[0]! is an error there ("unnecessary"), with it there is no finding. Until the flag is in tsconfig.json, avoid ! on an index: check the bound, or give a fallback with ??.

Migrating with codemods ​

safe-ts migrate rewrites existing code for one rule at a time. It prints a diff and changes nothing until you add --write:

sh
safe-ts migrate throw-to-result src/            # show the diff and the report
safe-ts migrate throw-to-result src/ --write    # change the files
CodemodRewritesFor the rule
throw-to-resultfunctions that throw into functions returning Resultno-throw
null-to-undefinednull and T | null into undefined and Option<T>no-null
ts-enumTypeScript enum into a union of strings or a const objectno-ts-enum
undefined-to-optionT | undefined into Option<T>prefer-option
union-to-enum <Type>a union discriminated by type into an Enum, with its producers and consumersEnums
module-statenothing: reports the module state each function uses, to plan a context parameterno-mutable-global
muta value passed to a Mut<T> parameter or prop into a loan, mut(value) (the upgrade to the nominal Mut<T>)missing-mut
  • Only what it can do safely. Anything else is left as written and listed in the report, with the reason. The report goes to stderr, so > changes.patch gives a patch for git apply.
  • Edits are small. Only the rewritten code changes; comments and formatting around it stay. Legacy files are migrated too (the marker doesn't stop a codemod).
  • The files you give are the whole program. Callers and uses in other files aren't seen, so give it the source folder, not one file. The report says when an exported function or enum changed. Vue components are part of the program: their scripts and templates are rewritten with the .ts files they use (below).
  • Check afterwards. Run tsc (vue-tsc in a Vue project) and safe-ts check, as for any change. The codemods are tested to produce code that compiles and passes the rule, but they can't see your whole build.

throw-to-result ​

A function whose throw the no-throw rule reports returns a Result instead. Callers that already return a Result get q(...).

❌ Before

✕ Rejectedno-throw
ts
import { type Result } from "@evobug_com/safe-ts-std/result";

export class NotFound extends Error {}
export class InvalidAge extends Error {}

const names = new Map([["1", "Ada"]]);

export function findName(id: string): string {
  const name = names.get(id);
  if (name === undefined) throw new NotFound(`no user ${id}`);
  return name;
}

export function parseAge(input: string): number {
  const age = Number(input);
  if (!Number.isInteger(age) || age < 0) throw new InvalidAge(`not an age: ${input}`);
  return age;
}

export function profile(id: string, age: string): Result<string, NotFound | InvalidAge> {
  const name = findName(id);
  const years = parseAge(age);
  return `${name}, ${years}`;
}

✅ After safe-ts migrate throw-to-result --write

✓ Accepted0 diagnostics
ts
import { type Result, err, q } from "@evobug_com/safe-ts-std/result";

export class NotFound extends Error {}
export class InvalidAge extends Error {}

const names = new Map([["1", "Ada"]]);

export function findName(id: string): Result<string, NotFound> {
  const name = names.get(id);
  if (name === undefined) return err(new NotFound(`no user ${id}`));
  return name;
}

export function parseAge(input: string): Result<number, InvalidAge> {
  const age = Number(input);
  if (!Number.isInteger(age) || age < 0) return err(new InvalidAge(`not an age: ${input}`));
  return age;
}

export function profile(id: string, age: string): Result<string, NotFound | InvalidAge> {
  const name = q(findName(id));
  const years = q(parseAge(age));
  return `${name}, ${years}`;
}
ts
import { Err as __qErr } from "@evobug_com/safe-ts-std/result"; import { type Result, err, q } from "@evobug_com/safe-ts-std/result";

export class NotFound extends Error {}
export class InvalidAge extends Error {}

const names = new Map([["1", "Ada"]]);

export function findName(id: string): Result<string, NotFound> {
  const name = names.get(id);
  if (name === undefined) return err(new NotFound(`no user ${id}`));
  return name;
}

export function parseAge(input: string): Result<number, InvalidAge> {
  const age = Number(input);
  if (!Number.isInteger(age) || age < 0) return err(new InvalidAge(`not an age: ${input}`));
  return age;
}

export function profile(id: string, age: string): Result<string, NotFound | InvalidAge> {
  const __q1 = findName(id); if (__q1 instanceof __qErr) return __q1; const name = __q1;
  const __q2 = parseAge(age); if (__q2 instanceof __qErr) return __q2; const years = __q2;
  return `${name}, ${years}`;
}
  • The error type is the union of the thrown classes, plus what converted functions pass up through q. throw new Error("text") and throw "text" become err("text") with a string error, and a new Error(...) built from anything else stays an Error. Give those a name afterwards, an Enum of the failures the callers handle (Give errors names). A method the class had (describe(), isRetryable()) becomes a method of the enum: declared in its type (Enum<V, { readonly describe: () => string }>), written on its table (constructors<LookupError>().impl({ describe: (error) => ... })), and still called error.describe() (Methods on an enum). What the class kept in fields goes in the variant's data, a retry count included. A method the class named toString or get takes a name of its own (describe, valueOrDefault).

  • Callers decide whether it happens. A function is converted only when every use of it can take a Result: a caller that returns one (or is converted too), with the call where q(...) fits (const x = f(), x = f(), f();, return f(), with await for an async function). Any other use is listed under Needs a decision, and the function stays as it is, so the code still compiles:

    text
    Needs a decision
      src/report.ts:14:10  `parsePort` would return a Result here, but `portOrDefault`, which calls it, doesn't return a Result
      src/ports.ts:8:20  `parsePort` would return a Result here, but it is used as a value here (passed, stored, re-exported or `typeof`), not called

    Make those callers return a Result (or handle the error), and run it again.

  • Files a Vite config loads (what vite.config.* or vitest.config.* imports) run without the transform (needs-transform), so the codemod doesn't write q(...) there: a caller there gets const x = f(); and if (isErr(x)) return x; (a new result binding for f();), and return f() stays as it is. A call there in another shape (x = f(), const x: T = f(), a destructuring, an unbraced if body) is listed under Needs a decision.

  • Top-level functions. A function declaration, or a const holding an arrow function or a function expression (export const load = async (id: string): Promise<User> => { ... }). Without a declared return type, a function that returns no value gets Result<void, E> (Promise<Result<void, E>> when async).

  • Not converted: functions without a declared return type that return a value, or returning unknown/any; throws inside the function's own try (it catches them today), inside callbacks, methods and nested functions, or in a function held by a let (it can be given another one); throws of a value whose class it can't tell (throw wrap(error)); functions with overloads, default exports, and generators. PropagateError throws are allowed and stay, and so is rethrowing the caught error unchanged (throw error).

null-to-undefined ​

null becomes undefined, T | null becomes Option<T>, and x === null becomes x === undefined. A parameter that defaults to null, near: T | null = null, becomes near?: Option<T> when every parameter after it may be left out too (otherwise near: Option<T> = undefined, which is the same).

❌ Before

✕ Rejectedno-null
ts
export type User = { readonly name: string; readonly email: string | null };

export function findUser(users: readonly User[], name: string): User | null {
  return users.find((user) => user.name === name) ?? null;
}

export function contactLine(user: User): string {
  return user.email === null ? user.name : `${user.name} <${user.email}>`;
}

✅ After

✓ Accepted0 diagnostics
ts
import type { Option } from "@evobug_com/safe-ts-std/result";

export type User = { readonly name: string; readonly email: Option<string> };

export function findUser(users: readonly User[], name: string): Option<User> {
  return users.find((user) => user.name === name);
}

export function contactLine(user: User): string {
  return user.email === undefined ? user.name : `${user.name} <${user.email}>`;
}

null from outside is real, so it stays wherever it can appear, and the report says where:

  • values from JSON (JSON.parse, response.json()), DOM and Web APIs (querySelector, getItem, match, parentElement, ...) and packages, and the variables that hold them. A check like localStorage.getItem(key) !== null stays as it is: as !== undefined it would always be true. If a hand edit or a search-and-replace does that, no-undefined-check-for-null reports it. The other way round, code merged later that still tests an Option for null (next === null, expect(x).not.toBeNull()) is no-null-check-for-undefined;
  • variables, parameters, properties and return types whose type mentions a type that isn't declared in your files (HTMLElement, a package's types);
  • your types that describe such data (JSON.parse(text) as User keeps null in User, and in the types User uses);
  • null passed to code outside your files (Object.create(null)), or in a value that is (JSON.stringify(payload) would print the field differently).
text
Left as written
  src/page.ts:3:20  `null` kept: compares `element`, which may be `null` from outside; `== undefined` matches both

What it can't see: null reaching a value through a path it doesn't follow, such as a library method with an unusual name, or a value passed through several functions first. A type-check catches most of these, since the converted types no longer accept null.

ts-enum ​

A string enum becomes a union of its values, and its uses become the strings:

❌ Before

✕ Rejectedno-ts-enum
ts
export enum Status {
  Draft = "draft",
  Published = "published",
}

export function isLive(status: Status): boolean {
  return status === Status.Published;
}

export const fallback: Status = Status.Draft;

✅ After

✓ Accepted0 diagnostics
ts
export type Status = "draft" | "published";

export function isLive(status: Status): boolean {
  return status === "published";
}

export const fallback: Status = "draft";
  • A const object instead, with the same values, when the strings alone wouldn't do: the enum is used as an object (Object.values(Status)), a member sits where a bare string would be typed string (an unannotated object literal), or the enum has numbers. That's the quick fix's form: Status.Draft keeps working, and Status.Draft as a type becomes typeof Status.Draft.
  • Not converted: members with computed values (1 << 2), declare enum, an enum merged with a namespace, enums re-exported, default-exported or imported through import * as (their uses aren't followed), and numeric enums used as objects (Color[0] is "Red" only for a real enum).
  • A numeric enum's type accepts any number; the const object's type doesn't. If tsc complains after the conversion, that code was passing numbers that aren't members.

undefined-to-option ​

T | undefined becomes Option<T>, in every position a type can be written, and the import is added where the file doesn't have one (none with the prelude). It applies prefer-option's quick fix everywhere at once, so run it after null-to-undefined, or on code where a bulk rewrite left T | undefined behind:

❌ Before

✕ Rejectedprefer-option
ts
export type Sale = { readonly startsAt: number; readonly coupon?: string | undefined };

export function discount(sale: Sale, t: number): { readonly percent: number } | undefined {
  return t < sale.startsAt ? undefined : { percent: t - sale.startsAt };
}

export const prices: (number | undefined)[] = [];

✅ After

✓ Accepted0 diagnostics
ts
import type { Option } from "@evobug_com/safe-ts-std/result";

export type Sale = { readonly startsAt: number; readonly coupon?: Option<string> };

export function discount(sale: Sale, t: number): Option<{ readonly percent: number }> {
  return t < sale.startsAt ? undefined : { percent: t - sale.startsAt };
}

export const prices: Option<number>[] = [];
  • The same type. Option<T> is T | undefined, so nothing changes for tsc or at runtime, and callers in other files don't need to change.
  • Not converted: unions with null (that's null-to-undefined), with void, any, unknown or never, and files that have their own Option type (listed in the report).

union-to-enum ​

safe-ts migrate union-to-enum Upload src/ turns the union Upload, discriminated by a type field, into an Enum with constructors, and updates the values of that type in the given files:

❌ Before

✕ Rejected0 diagnostics
ts
export type Upload =
  | { type: "queued"; file: string }
  | { type: "sending" | "retrying"; file: string; sent: number }
  | { type: "failed"; file: string; reason: string };

export function isFailed(upload: Upload): boolean {
  return upload.type === "failed";
}

export function progress(upload: Upload): string {
  switch (upload.type) {
    case "queued":
      return "waiting";
    case "sending":
    case "retrying":
      return `${upload.sent} bytes sent`;
    case "failed":
      return upload.reason;
  }
}

export const first: Upload = { type: "queued", file: "photo.jpg" };

✅ After

✓ Accepted0 diagnostics
ts
import { constructors, type Enum, is, match } from "@evobug_com/safe-ts-std/enum";

export type Upload = Enum<{
  Queued: { file: string };
  Sending: { file: string; sent: number };
  Retrying: { file: string; sent: number };
  Failed: { file: string; reason: string };
}>;
export const Upload = constructors<Upload>();

export function isFailed(upload: Upload): boolean {
  return is(upload, Upload.Failed);
}

export function progress(upload: Upload): string {
  return match(upload, {
    Queued: () => "waiting",
    Sending: (upload) => `${upload.sent} bytes sent`,
    Retrying: (upload) => `${upload.sent} bytes sent`,
    Failed: (upload) => upload.reason,
  });
}

export const first: Upload = Upload.Queued({ file: "photo.jpg" });
ts
import { unreachable as __matchUnreachable } from "@evobug_com/safe-ts-std/enum"; import { constructors, type Enum, is, match } from "@evobug_com/safe-ts-std/enum";

export type Upload = Enum<{
  Queued: { file: string };
  Sending: { file: string; sent: number };
  Retrying: { file: string; sent: number };
  Failed: { file: string; reason: string };
}>;
export const Upload = constructors<Upload>();

export function isFailed(upload: Upload): boolean {
  return (upload?.tag === "Failed");
}

export function progress(upload: Upload): string {
  { const __ms1 = upload; let __mv1: string; switch (__ms1.tag) {
    case "Queued": { __mv1 = "waiting"; break; }
    case "Sending": { const upload = __ms1; __mv1 = `${upload.sent} bytes sent`; break; }
    case "Retrying": { const upload = __ms1; __mv1 = `${upload.sent} bytes sent`; break; }
    case "Failed": { const upload = __ms1; __mv1 = upload.reason; break; } default: __mv1 = __matchUnreachable(__ms1); } return __mv1; }

}

export const first: Upload = ({ tag: "Queued", file: "photo.jpg" } satisfies Upload as Upload);
  • One variant per literal. A member whose type is itself a union ("sending" | "retrying") becomes one variant for each, sharing the payload. Names are the literals in PascalCase ("order-placed" is OrderPlaced).
  • Only values of that type. Other unions often use the same literals under type; they are left alone. A value counts when an annotation says so, followed through variables, fields of your interfaces, array elements, for...of, array callbacks (events.filter((e) => ...)) and the signatures of functions in the given files. Producers ({ type: "queued", ... } where an Upload is expected, uploads.push({ ... })) become constructor calls. Checks become is: u.type === "queued" is is(u, Upload.Queued), !== is !is(...). A switch (u.type) whose every case returns a value becomes return match(u, { ... }), one handler per variant (cases that shared a body each get a copy). Extract<Upload, { type: "queued" }> becomes Variant<Upload, "Queued">. Files that need them get the imports.
  • Listed for a decision: u.type read as a value (stored, printed, compared with a variable), type destructured, Upload["type"]. These are rewritten to tag, which holds the variant name now ("Queued", not "queued"): check what they are compared with or written to. A switch (u.type) where a case doesn't return (a break, a statement before the return), or with a comment between its cases, stays a switch, over u.tag with case "Queued":; it is listed, and prefer-is-over-tag reports it with the idiomatic rules on. Producers that spread another object or compute type are listed and left as written.
  • Not converted: members that aren't written out as object types (a named Refund in the union), a member without type or with a tag field, two literals giving the same name.
  • Run tsc afterwards. A value the codemod couldn't see the type of still has its old shape, and tsc points at each one.
  • A value outside the union. match calls unreachable for a value no handler takes, where the old switch fell through: only data that never had the union's type (an unchecked cast, JSON read without parseJson<T>) behaves differently.

module-state ​

safe-ts migrate module-state src/ changes nothing: it prints, for each function, the module-level state it uses (what no-mutable-global calls state), directly or through the functions it calls, and for each piece of state the functions that use it. That is the list of functions a "module state → context parameter" change has to touch:

ts
let visits = 0;
const recent: string[] = [];

export function track(page: string): void {
  visits += 1;
  recent.push(page);
}

export function report(): string {
  return `${visits} visits, last ${latest()}`;
}

function latest(): string {
  return recent.at(-1) ?? "none";
}
text
1:5 module state `visits`: used by `report`, `track`
2:7 module state `recent`: used by `latest`, `track`; through calls by `report`
4:8 `track` uses module state `visits` (changes it), `recent` (changes it)
9:8 `report` uses module state `visits`, `recent` (through `latest`)
13:1 `latest` uses module state `recent`

The given files are the program: a module's state is followed into the functions of other given files that import it. A /** @cache */ constant isn't state, nor a const nothing changes.

mut ​

Mut<T> is a type of its own, and a value is lent to a Mut parameter by writing mut(value) at the call, like Rust's &mut value (State without globals). safe-ts migrate mut src/ writes the loan at every call, method call, JSX prop and Vue template binding that passes a value to a parameter or prop declared Mut<...>, across the files you give, with the import of mut where the file doesn't have the prelude. It is missing-mut's quick fix, applied in one pass over the program.

❌ Before (TypeScript refuses it with the nominal Mut<T>)

✕ Rejectedmissing-mut
ts
import type { Mut } from "@evobug_com/safe-ts-std/mut";

type Cart = { items: string[] };

function addItem(cart: Mut<Cart>, item: string): void {
  cart.items.push(item);
}

export function fill(cart: Mut<Cart>, items: readonly string[]): void {
  for (const item of items) addItem(cart, item);
}

✅ After safe-ts migrate mut --write

✓ Accepted0 diagnostics
ts
import { type Mut, mut } from "@evobug_com/safe-ts-std/mut";

type Cart = { items: string[] };

function addItem(cart: Mut<Cart>, item: string): void {
  cart.items.push(item);
}

export function fill(cart: Mut<Cart>, items: readonly string[]): void {
  for (const item of items) addItem(mut(cart), item);
}
ts
import { type Mut, mut } from "@evobug_com/safe-ts-std/mut";

type Cart = { items: string[] };

function addItem(cart: Mut<Cart>, item: string): void {
  cart.items.push(item);
}

export function fill(cart: Mut<Cart>, items: readonly string[]): void {
  for (const item of items) addItem(cart, item);
}

It also lends a value put into a place declared Mut<...> outside a call (an initializer or an assignment, a parameter's default, a field, a return, the elements of an array literal where readonly Mut<T>[] is asked), writes a fresh literal's loan with the place's type (mut<Cost>({ ... }), mut<number[]>([])), and rewrites Mut<Option<T>> and Mut<T | undefined> as Option<Mut<T>> and Mut<T> | undefined: a missing value can't be changed in place, and mut(maybe) keeps the undefined. Under "Needs a decision" it lists what it leaves to you: a call the checker can't follow whose name is a function's that takes Mut (TypeScript says whether it is), a [] or {} whose type it can't name in that file, and Mut inside another type built by a call (readonly Mut<T>[]: whoever builds the list lends each element). Lines under // @ts-expect-error are left as written. Then run tsc (or vue-tsc): what it still refuses is a hole the old Mut let through, such as a function taking Mut<T> passed as a callback that only lends to read, a Dog[] lent as Mut<Animal[]>, or a property narrower in the value where the function may write it (State without globals says what to write for each).

What remains is a short list of kinds. On one real program of about 700 files, after the migration (and the Mut declarations the new findings asked for), tsc refused 52 places:

What tsc still refusesPlacesDeclarations to changeWhat to write
A Mut<A> lent where Mut<B> lets the function write a property A has narrower or optional (an Inventory whose gold is optional, lent to addGood(target: Mut<Goods>) that may write gold)164A correct refusal, fixed where the function is declared: give the parameter the type it changes (Mut<Inventory>), or make the property the same
A value the migration couldn't follow, without mut(...): a method of an object it can't resolve, a [] whose type it can't name, a default value200The loan, where it is lent (mut(x), mut<T>([])): the migration lists each under "Needs a decision"
A function taking Mut<T> in a slot that only lends to read: a table of handlers, a plugin hook, an array callback8one per slotDeclare the slot's parameter Mut<T> in your own type, or take the value borrowed where the function only reads it; for a package's hook, wrap it in a function that lends
A fresh object lent where the parameter's type has an optional property the object doesn't have (a dependencies object)40Lend it with the type written, mut<Deps>({ ... }), or build it in a local of that type
A subclass, a wider element type or a generic Mut<T> lent as another type's Mut (a point type for its base, a WeakSet<Texture> for WeakSet<object>)33As in the first row: the parameter's type is what the function changes
An overload that no longer matches11Pick the signature the call means, or lend the argument it asks for

Two kinds that used to be on this list are gone: a member lent where its union is asked (Mut<number[]> where Mut<number[] | Int32Array> is) is accepted, and a list passed where each element is lent (readonly Mut<Unit>[]) is lent with mutEach(units), which the migration writes: the list itself, without a copy.

Vue components ​

Give the codemods the folder with your components: .vue files are read like the checker reads them, <script> and <script setup> (lang="ts") with the template's expressions, as one program with the .ts files they import. Each change is written back into the component, in the script, or in the attribute or {{ }} it came from; the rest of the file stays as it is. A type changed in a .ts file reaches the components that use it in the same run, so don't run a codemod on the .ts files alone: that leaves the components behind.

text
Left as written
  src/components/UserBadge.vue:7:48  `null` type kept: in a prop type, which describes what parent components pass
  src/App.vue:12:25  `null` kept: bound to the prop `fallback` of `<UserBadge>`, whose type keeps `null`
  • null-to-undefined. A Pinia store's own state is the program's own: in an options store (state: () => ({ name: null as string | null })) its nulls go, and components reading user.name === null become user.name === undefined with it. A setup store returning a ref<T | null>(null) keeps it, as ref(...) does everywhere, and then every read of that store keeps its null too. The same holds for any module-level value or function result in your files that holds outside data (a composable returning a template ref). Prop types (defineProps<{ user: User | null }>()), event types and slot props keep their null, since parent components pass them, and values a parent binds to such a prop keep theirs: <UserBadge :fallback="null" /> stays.
  • undefined-to-option rewrites prop types too: Vue's compiler reads Option<string> like string | undefined, so the prop works the same at runtime.
  • ts-enum and union-to-enum update uses in templates. A string written into an attribute gets the other quotes, so v-if="status === Status.Live" becomes v-if="status === 'live'". union-to-enum follows props declared as an interface (defineProps<Props>()) into v-for and template comparisons, which become is(event, UploadEvent.Failed).
  • throw-to-result converts functions of <script setup> like any other, but a function the template calls ({{ years(age) }}, @click="save") stays: nothing there would receive the error. The report lists those calls.
  • module-state counts a plain <script> block as module state, shared by every instance of the component. What <script setup> declares belongs to each instance, so it isn't.
  • Left unchanged: a component whose change would go into code Vue generates from the template (a handler written as a name, @click="save", or an expression with HTML entities, a &amp;&amp; b) is left as written, and the report points at the expression. Scripts that aren't TypeScript and other template languages (Pug) aren't read.

Applying one rule's quick fixes ​

safe-ts fix <rule> applies the quick fixes of one rule, the ones the editor offers, to the files and folders you give. Like migrate, it prints a diff and changes nothing until you add --write:

sh
safe-ts fix prefer-is-over-tag src/             # show the diff and the report
safe-ts fix prefer-is-over-tag src/ --write     # change the files
safe-ts fix unhandled-failure src/ --fix "Wrap in try/catch"
  • One fix per site, or none. A site with exactly one fix gets it. Among several, the one --fix "<start of the title>" picks; else the only one whose title says (the same as now), which keeps the result for every input (What quick fixes keep): if (name) on an optional string gets Test for undefined and "" (the same as now) without --fix. Otherwise the site is left alone and listed with its fixes and why: each fix changes the result for some input (a number's Compare with 0 (NaN counts as true) and Test for a positive number), or more than one keeps it and which one is meant is a choice. The report ends with the --fix for each kind of site left, with how many sites offer it.
  • Checked again until nothing changes. Each round applies the fixes whose edits don't touch each other, checks the file again, and goes on with what is left, so two fixes adding to one import both land. A round that would leave the file unparsable is undone, and its fixes are tried one by one; one that still breaks it is listed as not applied.
  • Checked as check checks. The program resolves the same way (tsconfig.json paths, workspace packages), failures are followed into other files, and a changed file is seen by the files after it. Legacy files report nothing, so nothing in them changes. The idiomatic rules are on for the run, unless the project turns the rule off.
  • The report goes to stderr: sites skipped (with their fixes and why), not applied, without a fix, and fixed, then a summary (sites fixed, skipped, files changed). --json prints one object instead: the counts, each site with its status and fix or options (a skipped site's "skipped" is "none-keeps-meaning" or "several-keep-meaning"), and each changed file's diff.
  • The whole program, for the rules only it shows (unused-code, the event rules): one check of the files given, every file an entry when nothing imports it (as checking a directory does), and each site's fix once. safe-ts fix unused-code apps packages deletes what nothing refers to; what that leaves (the helpers only the deleted code called) is found by the next run.

Apply one rule at a time, and review the diff before --write: a quick fix is the usual answer, not always the right one (unsafe(...) around a call still leaves the Result to handle). oxlint --fix-suggestions applies the first suggestion of every rule at once: prefer safe-ts fix, one rule per run.

Upgrading and bulk fixes ​

  • Bump every @evobug_com package in one step. They are released together, and each peer range is its own minor (^0.4.0), so a mix of versions doesn't install. Changing the pins and running npm install can stop with ERESOLVE while the lockfile still holds an old version: install them all in one command (npm install @evobug_com/[email protected] @evobug_com/[email protected] ...), or delete their node_modules/@evobug_com/... entries from package-lock.json first. Then apply the new rules' fixes one rule at a time and review them, strict-truthiness on values that may be undefined most of all. The steps: Upgrading between versions.
  • Scripts need the loader too. A script that uses q(...), unsafe, parseJson<T> or any prelude name runs only through the rewrite: write its command as node --import @evobug_com/safe-ts-transform/register scripts/report.ts, in package.json and in the comment at its top, not plain node. safe-ts check warns about package.json scripts that miss it (above).
  • unicorn/numeric-separators-style changes text that other programs may read. The preset no longer turns it on. If you turn it on yourself, its fix (oxlint --fix, vp lint --fix) groups decimals in thousands and hex in bytes: the values stay the same for JavaScript, but the text changes. A Rails initializer reading CONSOLE_PORT = 47474 from a .ts file with /CONSOLE_PORT = (\d+)/ read 47_474 as 47, so its content security policy allowed port 47 and the browser refused the real one; only running the app in a browser showed it. Before applying the fix, search for programs that read your source files (build scripts, configs in other languages, grep in a deploy script). To apply only that fix: oxlint --fix -A all -D unicorn/numeric-separators-style src/.
  • Review unicorn/prefer-at's fix. It turns a.length ? a[a.length - 1] : fallback into a.length ? a.at(-1) : fallback, which is typed T | undefined (at doesn't know the length was checked), so tsc then reports each such place. Write it as a.at(-1) ?? fallback, which says the same thing. The preset keeps the rule: on its own, .at(-1) is the form SAFE-TS wants, since a[a.length - 1]! is an unchecked cast.
  • Copies in a for...of. Iterate a copy with Array.from(items), not [...items], when the loop changes the collection: oxlint's unicorn/no-useless-spread reports the spread (it can't see the change), and no-mutation-while-iterating accepts both. Deleting the entry the loop is on from a Map or Set needs no copy.
  • Lint output. oxlint prints a summary ("Found 0 warnings and 0 errors") after the problems. In a terminal it detects as an AI agent's (CLAUDECODE, AI_AGENT, ...), it prints only the problems, so a clean file prints nothing; --format default brings the summary back. A plugin can't add to it. Each problem is printed once per rule and place.

Idiomatic rules ​

The rules above catch defects. A second, opt-in layer holds code to the framework's own way of writing things, so a codebase doesn't drift into two spellings of one idea:

jsonc
// package.json
"safe-ts": { "idiomatic": true }

To see what they would report without turning them on, run safe-ts check src/main.ts --idiomatic once. check reminds you of the layer in its last line while it is off. Naming an idiomatic rule in "rules" turns that one on alone ("rules": { "prefer-option": "warn" }), and "off" turns one off while the others are on.

RuleAsks for
prefer-optionOption<T>, not T | undefined
no-optional-fieldkey: Option<T>, not key?: T, in the project's own types (JSON types, props, a library's options and declarations keep ?:); by safe-ts check only
no-swallowed-errorthe Result, not undefined, when something failed (if (isErr(r)) return undefined)
sentinel-errorResult<void, E> or Option<string>, not '' for "no error" and a message otherwise
wide-paramthe fields a function reads, not the whole context (cart, not shop read as shop.state.cart)
unneeded-mutT, not Mut<T>, for a parameter the function never changes, and no mut(x) where the parameter isn't Mut
prefer-is-over-tagis, variant or match, not x.tag === "Ready" or switch (x.tag)
prefer-constructor-tagis(x, Status.Published), not is(x, "Published"), when the enum has constructors
prefer-qconst x = q(...), not if (isErr(x)) return x
prefer-map-errmapErr(x, f), not err(f(x.error)) in an isErr branch
json-null-in-appan Enum or AsyncState<Option<T>, E>, not JsonNull as app state
null-or-undefined-checkone absence per value, or a test for both
undefined-to-nullnull written where one body needs it, not for every undefined
latest-wins-counteruseTask (or std latest outside components), not a hand-written "latest run wins" ticket
unused-task-signalthe task's signal passed to the request
catch-on-resultthe Result checked, not a .catch that never runs
misplaced-axios-checkthe function's own error type read
unsafe-project-calla direct call, or unsafe(..., Panic), around the project's own code
key-presence-unionan Enum, not variants told apart by their keys
panic-on-loadinga state the page shows, not a crash before the first answer
cast-in-testfixture, testDouble or unchecked from @evobug_com/safe-ts-std/testing
strict-truthinesscount > 0, name !== undefined, not if (count) / v-if="name" on a number or string
no-positional-childrena reference to the child, or a lookup by name, not children[2]
string-dispatcha string parsed once into a closed type, not compared with three or more words
undeclared-return-typea declared return type where the checker can't read a function's result off its returns
unused-codeno export nothing imports, and no code only such code uses; by safe-ts check only
unused-privateno private member nothing in its class uses, no field written and never read

safe-ts check, the Vite plugin, the Node loader, the editor and the oxlint plugin all follow the setting. The oxlint preset lists all of them (prefer-option an error, the others warnings), but they report nothing until the setting is on: the setting lives in package.json, where every tool reads it, so neither the preset nor a stricter preset turns them on. The layer is off by default because its findings change signatures one by one, which is the second step of an adoption, after the defects. Turning it on in an existing codebase: run undefined-to-option first, then decide the other rules' findings one by one: each changes a function's signature, and its callers with it. unneeded-mut's quick fix changes no caller; fixing one finding can reveal the next one up the call chain.

The rules from prefer-is-over-tag down catch the forms an agent-led migration falls back to: each compiles and passes the other rules, but writes a SAFE-TS idea by hand or works around it (the migration skill uses them as gates). They are warnings, so safe-ts check reports them without failing unless it runs with --deny-warnings. Most are decided from the code as written, without types; panic-on-loading goes by names and is the roughest, and its page says what it can't tell apart. prefer-q, prefer-is-over-tag and prefer-constructor-tag have quick fixes.

Dead code on day one ​

unused-code on an existing project finds what agents and refactors left behind: on an adopter's monorepo, 58 declarations in a run of its directories (46 from its entries alone), each dead on reading. Start with the baseline, which records each rule's warnings so the count can only fall, then delete in reviewed steps with safe-ts fix unused-code on the same directories (a diff; --write to apply), and again for what each step leaves. unreachable-code is a defect more often than not, so it is on by default as an error.

Escape hatches, and keeping them few ​

Every escape hatch is visible and countable:

Escape hatchMeaningUse when
unsafe(() => ...) / unsafeAsyncthis call may throw; I turn it into a Resultcalling code that throws (built-ins, libraries, legacy)
panic(message)this can't happen; stop the programan invariant nothing can handle, never a loading state (std helpers)
// @safe-ts legacythis file isn't migrated yetgradual adoption; the file is listed under "legacyFiles" in package.json (unlisted-marker)
// @safe-ts stdtrusted library codewriting low-level helpers like @evobug_com/safe-ts-std itself; the file is listed under "trustedFiles"
// safe-ts-ignore <rule>: <reason>this line is right as it is, for this ruleone line in a migrated file (above)
void f()I'm ignoring this Result on purposebest-effort work whose failure really doesn't matter
trust<T>(value)I vouch for this value's type without checking ita boundary no check fits: data another part of the program made, a result type the body can't build (std helpers). Not an overload over a looser implementation or a value is T predicate: they say the same uncounted, and no-overload and no-type-predicate report them
LegacyNullstrict code still accepts null from callers not migrated yetthe bridge while legacy callers pass null (std helpers)
/** @cache */this module-level value is a memo, not statea cache that can be thrown away and computed again (no-mutable-global)
// @ts-expect-error <reason>TypeScript is wrong about this line, for this reasonone line no type fits yet; @ts-ignore, @ts-nocheck and a reasonless @ts-expect-error are reported (no-ts-suppression)
"rules" / "overrides" in package.jsonthis rule is quieter here than the preseta rule turned "off" or lowered to "warn" for the package or some files (rule levels)
"infer" below "all", "infer": { "exclude" }automatic mode finds fewer library failures, or none in those packagesa package whose inferred failures are wrong, while a pack is written (Libraries)
"testRunners"files importing this module are test filesa package re-exporting a test runner in a way the checker can't follow
"vue": { "sanitizers" }v-html takes this function's output uncheckedthe one sanitizer the project vouches for; defineSanitizer says it in the code
defineSanitizer(fn)this function's output is safe HTML (Html)the one sanitizer the project vouches for; counted however it is imported or re-exported
// eslint-disable-next-line rule -- whyanother linter's rule is off for the next linea rule of another linter that is wrong here; a blanket one, or one naming a safe-ts/ rule, is reported (no-lint-suppression)
declare const x: unknown, declare module "*.svg", a .d.ts of the projectthis value exists, made by something the checker doesn't seea constant a bundler injects, an asset module, a global the project sets; one that asserts a type nothing checks is reported (no-unchecked-declare)

safe-ts check counts them after each run, however each one is spelled (a copy, a namespace member, .call, a re-export: a hatch handed on or exported under another name counts too), names the std files, since each one turns the rules off for a whole file, and names what package.json sets below the defaults: the rules above, infer, infer.exclude, testRunners, vue.sanitizers, "vue": { "ssr": false } in a project that depends on Nuxt, and a package.json inside another one's directory that leaves out what the outer one turns on (the idiomatic rules, a pack, an emitter, a request function, Vue SSR), since its files lose it (idiomatic off (on in package.json)). It also reads the .oxlintrc.json next to the package.json, since the preset is how a project gated by oxlint gets SAFE-TS's rules and some of oxlint's own (no-eval, no-proto): a config that doesn't extend the preset (oxlint not extending the SAFE-TS preset), turns one of its rules off or down (oxlint.rules no-eval off, oxlint.overrides no-new-func off for scripts/**), or leaves files out (oxlint.ignorePatterns legacy/**). It reads JSON with comments; not the files extends names, nested configs, oxlint -c, or a config in JavaScript (one next to the package.json is a setup warning):

text
escape hatches: 2 unsafe() block(s), 0 panic() call(s), 0 trust() call(s), 0 LegacyNull use(s), 0 @cache mark(s), 1 safe-ts-ignore comment(s), 0 legacy file(s), 1 std file(s) (src/protocol/trusted.ts), 0 @ts-ignore, 1 @ts-expect-error (and 14 in test files), 0 @ts-nocheck comment(s), 0 @vue-skip comment(s), 2 eslint-disable / oxlint-disable comment(s), 4 skipped test(s), 3 ambient declaration(s), 1 defineSanitizer() call(s)
weakened below the defaults: infer documented, no-mutable-global off for src/stores/** (package.json)

A @ts-expect-error <reason> in a test file is a compile-time test ("this must not compile"), so it is counted apart. Treat an increase in any count as a code review question, the way Rust projects treat new unsafe blocks. Code the run didn't see is shown next to them: imports that resolve to nothing and source files no entry reaches (checking the whole program).

A ratchet: baseline ​

--write-baseline <file> records the counts, and --baseline <file> fails the run when any of them rose: every escape hatch above, what package.json weakens below the defaults, the source files not checked, the unresolved imports, the setup warnings (setupWarnings), and the warnings of each rule. Some settings only weaken against what they were, so the baseline records them per package.json and fails when one got weaker: the idiomatic rules turned off ("idiomatic": false, or a gate run without --idiomatic), a feature pack no longer loaded (taken out of "features", or no longer installed), a class taken out of "emitters" or a wrapper out of "requestFunctions", and the Vue SSR rules turned off. A package.json the run no longer reads counts as one with nothing set. It names each rise:

sh
safe-ts check src --write-baseline safe-ts-baseline.json   # once, and after a reviewed exception
safe-ts check src --baseline safe-ts-baseline.json         # in CI
text
baseline gate: 3 counts rose against safe-ts-baseline.json
  @ts-expect-error comments: 0 -> 1 (+1)
  weakened: package.json: no-any off
  weakened: the idiomatic rules are off (package.json)
Fix them, or (for a reviewed exception) write a new baseline with --write-baseline.

A count missing from the file is 0; a value that isn't a count stops the run (exit 2). That holds for a baseline written by an earlier SAFE-TS, before it counted lint suppressions, ambient declarations, @vue-skip comments and defineSanitizer calls: the gate fails on those until the baseline is written again, and says why (defineSanitizer() calls (the baseline has no escapeHatches.sanitizers: written before SAFE-TS counted them?): 0 -> 2 (+2)). Failing is the choice that keeps the ratchet closed: a count it skipped would let it rise unseen. When counts fell, the run says so: write the baseline again to hold them there. The baseline doesn't excuse errors, which fail the run either way, and doesn't hold warnings at zero (--deny-warnings does). Commit the file, so a raised count shows in the diff that raises it. With --json the gate's lines go to stderr.

MIT OR Apache-2.0 · Docs by Gemini 4 Neon Extra