Skip to content

Libraries and feature packs ​

Third-party libraries throw too. SAFE-TS discovers throwing calls automatically by analyzing installed code in node_modules (automatic mode), and feature packs add exact error types, sink knowledge, and Result/Option-returning safe wrappers. Whenever a feature pack covers a package, it takes precedence.

In short

  • Zero-config library analysis: every imported dependency is analyzed once per installed version, cached on disk, and checked for throws and rejections.
  • Categorized findings: each diagnostic labels the failure kind (argument check, contract, builtin, …); set "safe-ts": { "infer": "real" } to hide argument checks.
  • Official feature packs: enable packs in package.json for Node built-ins, browser DOM APIs, zod, ws, and vue-router.
  • Safe wrappers + quick fix: every pack exports safe versions returning typed Results (readFileSync, setItem, send, push, parse) and converts null APIs into Option<T> (null becomes Option).
  • Inspect coverage: run safe-ts coverage to audit every library call in your app, or safe-ts infer <package> to see what automatic mode finds.
  • No guessing: calls SAFE-TS cannot trace are left unreported.

Install the packs you want (npm install -D @evobug_com/safe-ts-feature-browser; a pack whose safe versions you import is a regular dependency, since their code ships in yours: npm install @evobug_com/safe-ts-feature-browser), then enable them in the nearest package.json, with a "safe-ts" field:

jsonc
{
  "safe-ts": { "features": ["@evobug_com/safe-ts-feature-node", "@evobug_com/safe-ts-feature-zod"] }
}

Without a pack, a call into a library is judged by what automatic mode finds in the library's code; a call it can't follow is not judged at all: SAFE-TS doesn't guess.

Node built-ins (@evobug_com/safe-ts-feature-node) ​

The pack maps every callable Node exposes (2,004 in Node 26.13, counting the ones only some platforms have: module functions, class constructors, static and instance methods, and the globals Node adds, such as fetch) in packages/feature-node/node-api.json, each in exactly one category:

CategoryMeaningCount
throwsthrows on runtime conditions: I/O, the environment, outside data303
rejectsthe promise rejects on runtime conditions145
iteratesthe iterator it returns throws while you iterate12
callbackfailure goes to an error-first callback118
eventfailure is an 'error' event53
propagatesruns your function and rethrows what it throws (emitter.emit, als.run)16
abortsrejects only when you abort the signal you passed (timers/promises)4
returnsfailure is in the return value (spawnSync().error, URL.parse → null)12
assertthrowing is its purpose (node:assert)38
argsthrows only on wrong arguments or misuse (after close(), before bind())533
neverdoesn't fail770

SAFE-TS reports the throws and rejects ones it can see: module functions (readFileSync(), fs.readFileSync(), http.get(), fs.promises.readFile()), static methods (ZipFile.open()) and methods on values whose class it knows (handle.read(), decipher.final(), db.prepare(), entry.content()). It knows a value's class when the value is made with new, returned by a factory the map lists (createDecipheriv() makes a Decipheriv, ZipFile.open() a ZipFile, zip.get() a ZipEntry), or exported as an instance (performance). Base classes count too: a gzip stream is a Readable, so gzip.toArray() rejects. A method is never matched by its name alone: stream() rejects on a ZipFile but a gzip stream has no such method, and read() rejects on a FileHandle but not on a ReadStream. Constructors of modules (new Database()) are mapped but not reported yet. Node's globals are: fetch(), structuredClone(), new Request(), new Response(), the methods of a Response, Request and Headers, crypto.subtle's and localStorage.setItem().

✕ Rejectedunhandled-failure
ts
import { readFileSync } from "node:fs";
import type { SafePath } from "@evobug_com/safe-ts-std/path";

export function readConfig(path: SafePath): string {
  return readFileSync(path, "utf8");
}

✅ Accepted: the safe version returns the error, typed

✓ Accepted0 diagnostics
ts
import { isSystemError } from "@evobug_com/safe-ts-feature-node/errors";
import { readFileSync } from "@evobug_com/safe-ts-feature-node/fs";
import { readFile } from "@evobug_com/safe-ts-feature-node/fs/promises";
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
import { isErr, mapErr, type Result } from "@evobug_com/safe-ts-std/result";
import type { SafePath } from "@evobug_com/safe-ts-std/path";

export type ConfigError = Enum<{ Missing: { path: string }; Unreadable: { reason: string } }>;
export const ConfigError = constructors<ConfigError>();

export function readConfig(path: SafePath): Result<string, ConfigError> {
  return mapErr(readFileSync(path, "utf8"), (error) =>
    isSystemError(error, "ENOENT") ? ConfigError.Missing({ path }) : ConfigError.Unreadable({ reason: error.message }),
  );
}

export async function readConfigAsync(path: SafePath): Promise<string> {
  const text = await readFile(path, "utf8");
  return isErr(text) ? "{}" : text;
}
ts
import { isSystemError } from "@evobug_com/safe-ts-feature-node/errors";
import { readFileSync } from "@evobug_com/safe-ts-feature-node/fs";
import { readFile } from "@evobug_com/safe-ts-feature-node/fs/promises";
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
import { isErr, mapErr, type Result } from "@evobug_com/safe-ts-std/result";
import type { SafePath } from "@evobug_com/safe-ts-std/path";

export type ConfigError = Enum<{ Missing: { path: string }; Unreadable: { reason: string } }>;
export const ConfigError = constructors<ConfigError>();

export function readConfig(path: SafePath): Result<string, ConfigError> {
  return mapErr(readFileSync(path, "utf8"), (error) =>
    isSystemError(error, "ENOENT") ? ({ tag: "Missing", path } satisfies ConfigError as ConfigError) : ({ tag: "Unreadable", reason: error.message } satisfies ConfigError as ConfigError),
  );
}

export async function readConfigAsync(path: SafePath): Promise<string> {
  const text = await readFile(path, "utf8");
  return isErr(text) ? "{}" : text;
}

✅ Also accepted: unsafe(...) and try/catch around the original, without the pack

✓ Accepted0 diagnostics
ts
import { readFileSync } from "node:fs";
import { readFile } from "node:fs/promises";

import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
import { err, isErr, type Result, unsafe } from "@evobug_com/safe-ts-std/result";
import type { SafePath } from "@evobug_com/safe-ts-std/path";

export type ConfigError = Enum<{ Unreadable: { path: string } }>;
export const ConfigError = constructors<ConfigError>();

export function readConfig(path: SafePath): Result<string, ConfigError> {
  const text = unsafe(() => readFileSync(path, "utf8"));
  return isErr(text) ? err(ConfigError.Unreadable({ path })) : text;
}

export async function readConfigAsync(path: SafePath): Promise<string> {
  try {
    return await readFile(path, "utf8");
  } catch {
    return "{}";
  }
}
ts
import { readFileSync } from "node:fs";
import { readFile } from "node:fs/promises";

import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
import { err, isErr, type Result, unsafe } from "@evobug_com/safe-ts-std/result";
import type { SafePath } from "@evobug_com/safe-ts-std/path";

export type ConfigError = Enum<{ Unreadable: { path: string } }>;
export const ConfigError = constructors<ConfigError>();

export function readConfig(path: SafePath): Result<string, ConfigError> {
  const text = unsafe(() => readFileSync(path, "utf8"));
  return isErr(text) ? err(({ tag: "Unreadable", path } satisfies ConfigError as ConfigError)) : text;
}

export async function readConfigAsync(path: SafePath): Promise<string> {
  try {
    return await readFile(path, "utf8");
  } catch {
    return "{}";
  }
}

Both ways work. The safe version keeps the error's type (text.error is a SystemError<"open" | "fstat" | "read", { path?: string }>); unsafe(...) gives unknown.

Methods go by the class of the value. Opening a ZIP file, finding an entry and reading it can each fail:

✕ Rejectedunhandled-failure
ts
import { ZipFile } from "node:zlib";

export async function readme(path: string): Promise<string> {
  const zip = await ZipFile.open(path);
  const entry = await zip.get("README.md");
  return (await entry.content()).toString("utf8");
}

A gzip stream reports its failures as 'error' events, so its methods are fine to call:

✓ Accepted0 diagnostics
ts
import { createGzip } from "node:zlib";

export function compress(chunks: readonly Uint8Array[]): void {
  const gzip = createGzip();
  gzip.on("error", (error) => console.error(error));
  for (const chunk of chunks) gzip.write(chunk);
  gzip.end();
}

Node's events ​

node-api.json's events lists @types/node's event maps by module Name (node:http ServerEventMap, with the maps each extends: node:net ServerEventMap; a mapped type over a union of names, such as SignalsEventMap, counts), the map each class's on takes (node:net Socket, globals Process, declared on the class or inherited), and creates: the class a module function returns or a global is (node:http createServer makes a node:http Server, globals process is a globals Process). test/events.ts reads them off the installed @types/node; test/manifest.test.ts fails when the map says otherwise, and safe-ts.json carries them. unknown-event reads them. A Node pack installed before the section existed is read with the copy the checker was built with. Its once part, written by hand, is described below.

What error says ​

The message names the error exactly: its class, its code and the properties it carries, written the way Node prints an error. These are the texts of the Node and ws packs:

error[unhandled-failure]: `readFileSync()` (node:fs) can throw `Error [E*] {errno, syscall: 'open' | 'fstat' | 'read', path?}`, but the failure is not handled
error[unhandled-failure]: `db.prepare()` (node:sqlite) can throw `Error [ERR_SQLITE_ERROR] {errcode, errstr?}`, but the failure is not handled
WrittenMeans
TypeErrorthe error's name: Error, TypeError, RangeError, SystemError, AbortError, DOMException, ...; no code
TypeError [ERR_INVALID_URL]its code is 'ERR_INVALID_URL' (for a DOMException, its name: DOMException [AbortError])
[A | B]the code is one of these
[E*]a system error: the code is an errno name from libuv ('ENOENT', 'EACCES', 'EISDIR', ...). Which ones depends on the call and the OS, so they aren't listed
[ERR_FS_CP_*]any of the codes with this prefix: for ERR_ prefixes, the fixed set Node defines; ERR_OSSL_* is an OpenSSL error, Z_* a zlib one
[dns.*]one of the error codes node:dns exports (dns.NOTFOUND is 'ENOTFOUND', ...)
{errno, syscall: 'open', path?}its other own properties: errno is always set, path? sometimes, syscall is 'open'
Error: WebSocket is not openits message starts with this (for errors without a code)
(the stream's error)a value passed through unchanged: what your callback threw, the error a stream was destroyed with
A | Beither one

Wrong argument types and calls in the wrong state (after close()) aren't listed: those are the args category. The browser pack adds a few forms for what browsers do (engine tags, DOMException subclasses, events): What the browser errors say. SQLite errors, for example, are Error [ERR_SQLITE_ERROR] with SQLite's extended result code in errcode (a UNIQUE violation is 1555) and its text in errstr.

test/errors.test.ts checks them on the running Node: for 413 of the 448 members that throw or reject (the globals too), test/triggers.ts makes the failure happen safely (missing paths in a temp dir, a bad file descriptor, invalid SQL on :memory:, bad URLs and headers, wrong-length keys, corrupt compressed data, a DNS lookup of .invalid and a resolver pointed at a closed port, ...) and the test compares the class, code and properties with the text. The other 35 (a FileHandle whose stat() fails, a full disk under ZipFile#add, os.userInfo() for a user without a passwd entry, ...) are written from Node's docs and source; their ERR_* codes are checked against the classes Node creates them with (lib/internal/errors.js). After a Node upgrade, node packages/feature-node/test/triggers.ts prints what each trigger fails with.

Safe versions ​

The pack also ships a safe version of each member that throws or rejects: a function that returns the failure as a Result instead, Promise<Result> for one that rejects (the promise never rejects). The other packs have them too, on the same plan: the browser's, ws's, vue-router's and zod's. The Node pack has one module per Node module:

Import fromInstead ofHas
@evobug_com/safe-ts-feature-node/fsnode:fsreadFileSync, writeFileSync, statSync, realpathSync.native, dirClose(dir), ...
@evobug_com/safe-ts-feature-node/fs/promisesnode:fs/promisesreadFile, open, read(handle, ...), fileHandleReadFile(handle), ...
@evobug_com/safe-ts-feature-node/child_processnode:child_processexecSync, execFileSync
@evobug_com/safe-ts-feature-node/sqlitenode:sqlitenewDatabaseSync, prepare(db, sql), run(statement, ...), get, all, backup
@evobug_com/safe-ts-feature-node/crypto, /zlib, /dns/promises, /http, /url, ...each Node module that has one36 modules in all
@evobug_com/safe-ts-feature-node/globalsNode's globalsfetch, structuredClone, newResponse, json(response), setItem(localStorage, ...), ...
@evobug_com/safe-ts-feature-node/errorsthe error types and guards

Each module can replace the import of its Node module: it passes on everything that doesn't fail unchanged, types too (named imports and import * as fs; there is no default export). Every overload is kept, with only the return type wrapped: readFileSync(p, "utf8") is a Result<string, E> and readFileSync(p) a Result<Buffer, E>. E is exactly what the member's error text says.

✓ Accepted0 diagnostics
ts
import { execSync } from "@evobug_com/safe-ts-feature-node/child_process";
import { newDatabaseSync, prepare, run } from "@evobug_com/safe-ts-feature-node/sqlite";
import { q, type Result } from "@evobug_com/safe-ts-std/result";

export function insert(path: string, name: string): Result<number | bigint, unknown> {
  const db = q(newDatabaseSync(path));
  const statement = q(prepare(db, "insert into users (name) values (?)"));
  const changes = q(run(statement, name));
  return changes.changes;
}

export function branch(): Result<string, unknown> {
  const out = q(execSync("git branch --show-current", { encoding: "utf8" }));
  return out.trim();
}
ts
import { execSync } from "@evobug_com/safe-ts-feature-node/child_process";
import { newDatabaseSync, prepare, run } from "@evobug_com/safe-ts-feature-node/sqlite";
import { Err as __qErr } from "@evobug_com/safe-ts-std/result"; import { q, type Result } from "@evobug_com/safe-ts-std/result";

export function insert(path: string, name: string): Result<number | bigint, unknown> {
  const __q1 = newDatabaseSync(path); if (__q1 instanceof __qErr) return __q1; const db = __q1;
  const __q2 = prepare(db, "insert into users (name) values (?)"); if (__q2 instanceof __qErr) return __q2; const statement = __q2;
  const __q3 = run(statement, name); if (__q3 instanceof __qErr) return __q3; const changes = __q3;
  return changes.changes;
}

export function branch(): Result<string, unknown> {
  const __q4 = execSync("git branch --show-current", { encoding: "utf8" }); if (__q4 instanceof __qErr) return __q4; const out = __q4;
  return out.trim();
}

Names follow one rule:

  • A function keeps its name: readFileSync, fetch, realpathSync.native.
  • A method becomes a function that takes the object first, named after the method: statement.run(x) is run(statement, x), handle.read(buffer) is read(handle, buffer), response.json() is json(response). One function serves every class of the module with that method (run(statement), run(tagStore)).
  • When the module already has the name (Node's own close in node:fs, or a function's safe version: readFile in node:fs/promises), or the classes' methods fail in different ways, the class comes first, in camelCase: dirClose(dir), fileHandleReadFile(handle), zipFileGet(zip, name).
  • A constructor is new and the class: newDatabaseSync(path), newResponse(body); a static method is the class and the method: responseJson(data), zipFileOpen(path).

434 of the 448 members that throw or reject have one. The other 14 aren't in @types/node (crypto.createMac, vm.createScript, Module#load, ...); safe-api.json lists them with the reason. A return type that uses a name the module doesn't export is read from the function itself: parseArgs(config) (node:util) returns a Result of ReturnType<typeof parseArgs<T>>, its values typed by the options as node's own. Members that report failure to a callback or with an 'error' event have no safe version: the guards type their errors instead.

A safe version returns what the original throws: a wrong argument TypeScript lets through (readFileSync(undefined as never)) comes back as an Err too, typed as the documented error.

Where the original's declarations say any for what you get back, the safe version says unknown: json(response) is a Promise<Result<unknown, E>>, runInThisContext(code) and deserialize(buffer) (node:vm, node:v8) a Result<unknown, E>, toArray(readable) a Result<unknown[], E>, and a callback's parameter typed any (forEach(readable, (data) => ...)) gets unknown. Check the value with validate<T> before using it. An overload of the original that returns any comes last, after the ones that name a type: WebGL's getExtension(gl, "WEBGL_lose_context") is an Option<WEBGL_lose_context>, getExtension(gl, name) for any other string an unknown.

null becomes Option ​

SAFE-TS code has no null (Absence), but many APIs return or take one. Every member whose declarations do gets a safe version at that boundary too, whether it fails or not, in the same module and with the same names:

  • It returns T | null: the safe version returns Option<T>, with null turned into undefined (?? undefined, so "", 0 and false come back unchanged). Also in a promise: Promise<T | null> becomes Promise<Option<T>>.
  • It takes a required T | null: the safe version takes Option<T> there and passes an undefined on as null. An optional parameter already means "not passed" when it is undefined: it is typed without the null, and what you pass reaches the original unchanged.
  • It also fails: a Result of the Option: dirReadSync(dir) (Dir#readSync() throws, and gives null after the last entry) is a Result<Option<Dirent>, E>.

Overloads and generics are kept, with only those types changed: querySelector(document, "input") is an Option<HTMLInputElement>.

✓ Accepted0 diagnostics
ts
import type { Option } from "@evobug_com/safe-ts-std/result";
import { address } from "@evobug_com/safe-ts-feature-node/net";
import { setAuthorizer } from "@evobug_com/safe-ts-feature-node/sqlite";
import { get, urlParse } from "@evobug_com/safe-ts-feature-node/url";
import type { DatabaseSync } from "node:sqlite";
import type { Server } from "node:net";

export function hasCoupon(query: URLSearchParams): boolean {
  // `query.get(k)` is `string | null`; `get(query, k)` an `Option<string>`.
  return get(query, "coupon") !== undefined;
}

export function shopHost(text: string): Option<string> {
  return urlParse(text)?.host;
}

export function listening(server: Server): boolean {
  return address(server) !== undefined;
}

export function allowEverything(db: DatabaseSync): void {
  // `db.setAuthorizer(null)` removes the authorizer; `undefined` is refused by the original.
  setAuthorizer(db, undefined);
}

Not every null turns into undefined. A member keeps its null (and keeps its safe version, null included, when it fails), with the reason in safe-api.json's nullSkipped, when:

  • it takes both null and undefined in the same place, or returns both: they may mean different things (mkdir(path, options, callback)'s options; Agent#createConnection returns undefined when it gives the socket to its callback instead);
  • its overloads disagree: null as an argument in one, and nothing there in another (exec(command, null, callback) and exec(command, callback));
  • the null comes through a type alias (WriteFileOptions): it can't be taken out of the type as written.

A null that is data, not absence, isn't touched either. A SQLite row's NULL is a value: get(statement) gives the row as the original does ({ note: null }), and undefined only for no row. Read rows through validate<T>, which knows which fields are optional. JSON.parse and structuredClone aren't changed: what they return is data (parseJson<T> converts it). Properties (el.parentElement, response.body) have no safe version: write ?? undefined where you read them.

PackReturn OptionTake OptionOf these, also failnull kept
Node188631
browser116133 (6 do both)128
ws1 (address(server))000

The checker knows them: comparing a safe version's Option with null is always false, and no-null-check-for-undefined reports it; no-undefined-check-for-null suggests the safe version where it reports a comparison of the original with undefined. A safe version that returns an Option is not a Result: must-use-result doesn't apply. npm run bench:check measures one on a hot path: get(params, key) costs the same as params.get(key).

Each safe version is written out in full, with a try/catch around its own call of the original (self.readUInt32LE(...args)), so the engine optimizes it like hand-written code. On Node 26, in a hot loop over a buffer, readUInt32LE(buf, o) with its isErr check takes 2.2 ns a call against 1.2 ns for buf.readUInt32LE(o). A wrapper that calls one shared helper (f.apply(self, args)), as the first version of the generator wrote them, took 11.8 ns: that one call site serves every safe version, so the engine can't optimize it for any. npm run bench:check measures it (packages/feature-node/bench/safe.bench.ts) and fails when the safe version gets more than twice as slow as that.

Error types and guards ​

@evobug_com/safe-ts-feature-node/errors exports the types the error texts become, and a guard for each:

TextTypeGuard
Error [E*] {errno, syscall: 'open', path}SystemError<"open", { path: string }>: code (an ErrnoCode: "ENOENT", ...), errno, syscall, and the properties listedisSystemError(e, "ENOENT")
TypeError [ERR_INVALID_URL] {input}NodeError<"ERR_INVALID_URL", "TypeError", { input: string }>isNodeError(e, "ERR_INVALID_URL")
Error [ERR_SQLITE_ERROR] {errcode, errstr?}SqliteErrorisSqliteError(e)
Error [ERR_OSSL_*] {library, reason, opensslErrorStack?}OpenSSLErrorisOpenSSLError(e)
SyntaxError, TypeError {cause}PlainError<"SyntaxError">, PlainError<"TypeError", { cause: unknown }>isPlainError(e, "SyntaxError")
DOMException [AbortError | TimeoutError]DOMError<"AbortError" | "TimeoutError">isDOMException(e, "AbortError")
(the stream's error)unknown, so the whole error is

A guard narrows an Err from a safe version, and what unsafe(...) returns, a catch gets, a callback is passed or an 'error' event carries, all unknown:

✓ Accepted0 diagnostics
ts
import { readFile } from "node:fs";

import { isSystemError } from "@evobug_com/safe-ts-feature-node/errors";
import type { SafePath } from "@evobug_com/safe-ts-std/path";

export function show(path: SafePath): void {
  readFile(path, "utf8", (error, text) => {
    if (isSystemError(error, "ENOENT")) console.log(`${error.path ?? path} is gone`);
    else if (error) console.error(error.message);
    else console.log(text);
  });
}

The quick fix ​

On a call the pack covers, unhandled-failure says the safe version exists, and its first fix is Use the safe version:

error[unhandled-failure]: `statement.run()` (node:sqlite) can throw `Error [ERR_SQLITE_ERROR] {errcode, errstr?}`, but the failure is not handled
  = help: Use its safe version, which returns a Result with the error typed: `run(<object>, ...)` from `@evobug_com/safe-ts-feature-node/sqlite`. Or wrap it: `unsafe(() => ...)` returns a Result
  = fix: Use the safe version, which returns a Result: run from @evobug_com/safe-ts-feature-node/sqlite
  = fix: Wrap in unsafe(() => …): returns a Result you must check

It rewrites the call (statement.run(x) to run(statement, x), fs.statSync(p) to statSync(p)) and adds the import, to an existing import from that module if there is one. When the file already uses the name, for the original (import { readFileSync } from "node:fs") or anything else, the safe version comes in under another one: import { readFileSync as safeReadFileSync } from "@evobug_com/safe-ts-feature-node/fs".

The fixed code compiles, so the fix goes only where a Result fits:

  • as the value of a const or let without a type annotation: const text = readFileSync(path, "utf8"). text is the Result, which the code after it handles, as with Wrap in unsafe;
  • in a function that returns Result<_, unknown>, with q(...) around it, as a declaration's value, an assignment's or a statement of its own: const text: string = q(readFileSync(path, "utf8")), q(writeFileSync(path, text));. The value keeps its type and the error is passed up (Use the safe version and propagate the error with q(…)).

Elsewhere the help names the safe version and the fix isn't offered: readdirSync(dir).sort() and an argument need the value, not a Result, and a dropped writeFileSync(path, text); would drop the error with it (must-use-result). The safe version's Result is checked like any other: dropping it is must-use-result, and a value it returns keeps its class (prepare(db, sql) gives a StatementSync, so statement.run() on it is checked).

test/errors.test.ts runs the triggers through the safe versions too: for 375 of the 413 triggered members, it calls the safe version with the same arguments and checks that it returns an Err whose error passes the guard of its declared type (the other 38 run in a child process, aren't patchable to route through, or have no safe version). test/types/ compiles the declarations strictly and checks what the overloads infer.

Browser APIs (@evobug_com/safe-ts-feature-browser) ​

The same map for the browser: every callable in TypeScript's lib.dom.d.ts (2,406: global functions, constructors, static and instance methods, the CSS and WebAssembly namespaces) in packages/feature-browser/browser-api.json, using Node's categories. The APIs both runtimes have (fetch, Headers, Blob, streams, postMessage) are classified the same way in both maps.

CategoryMeaningCount
throwsthrows on runtime conditions: quota, permissions, a cross-origin image, outside data, a denied or damaged store (localStorage.setItem, localStorage.getItem, canvas.toDataURL, history.pushState)60
rejectsthe promise rejects: network, a denied permission, the user cancelled (fetch, getUserMedia, clipboard.readText, element.requestFullscreen)129
iteratesthe async iterator throws (stream.values(), directoryHandle.entries())4
callbackfailure goes to a callback (getCurrentPosition, WebCodecs decode)15
eventfailure arrives later on the object: an error event or a rejecting promise property (xhr.send, IndexedDB requests, new WebSocket, WebGPU validation)92
propagatesruns your function and rethrows what it throws (navigator.locks.request, scheduler.postTask, TreeWalker filters)11
abortsrejects only when you abort the signal (scheduler.yield)1
returnsfailure is in the return value or state you read afterwards (window.open → null, canvas.getContext → null, gl.compileShader)26
argsthrows only on wrong arguments or misuse, including the constructors browsers refuse (new Node())1,229
neverdoesn't fail839

SAFE-TS reports the throws and rejects ones, with their exact errors: 189 members, among them localStorage.setItem(), localStorage.getItem(), fetch(), response.json(), crypto.subtle.encrypt(), navigator.clipboard.writeText(), canvas.toDataURL() and element.requestFullscreen(). Browser APIs are globals, so the pack describes them in its globals part (how they are matched). Enable it for code that runs in a browser:

jsonc
{ "safe-ts": { "features": ["@evobug_com/safe-ts-feature-browser"] } }

It is not on by default, also not in the Vite plugin: it reports every unwrapped localStorage.setItem(), fetch() and response.json(), which an existing app may have many of.

✕ Rejectedunhandled-failure
ts
export function saveDraft(text: string): void {
  localStorage.setItem("draft", text);
}

✅ Accepted: a full storage, or one the browser refuses, is a value to check

✓ Accepted0 diagnostics
ts
import { isQuotaExceededError } from "@evobug_com/safe-ts-feature-browser/errors";
import { setItem } from "@evobug_com/safe-ts-feature-browser/storage";
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
import { mapErr, type Result } from "@evobug_com/safe-ts-std/result";

export type DraftError = Enum<{ Full: {}; Refused: {} }>;
export const DraftError = constructors<DraftError>();

export function saveDraft(text: string): Result<void, DraftError> {
  return mapErr(setItem(localStorage, "draft", text), (error) =>
    isQuotaExceededError(error) ? DraftError.Full() : DraftError.Refused(),
  );
}
ts
import { isQuotaExceededError } from "@evobug_com/safe-ts-feature-browser/errors";
import { setItem } from "@evobug_com/safe-ts-feature-browser/storage";
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
import { mapErr, type Result } from "@evobug_com/safe-ts-std/result";

export type DraftError = Enum<{ Full: {}; Refused: {} }>;
export const DraftError = constructors<DraftError>();

export function saveDraft(text: string): Result<void, DraftError> {
  return mapErr(setItem(localStorage, "draft", text), (error) =>
    isQuotaExceededError(error) ? ({ tag: "Full" } satisfies DraftError as DraftError) : ({ tag: "Refused" } satisfies DraftError as DraftError),
  );
}

✅ Also accepted: unsafe(...) around the original, without the pack

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

export function saveDraft(text: string): Result<void, unknown> {
  return unsafe(() => localStorage.setItem("draft", text));
}

Both work. The safe version types the error (QuotaExceededError | DOMError<"QuotaExceededError">); unsafe(...) gives unknown.

error[unhandled-failure]: `localStorage.setItem()` (global) can throw `QuotaExceededError [QuotaExceededError] {quota?, requested?} @Chromium | DOMException [QuotaExceededError] @Firefox @WebKit`, but the failure is not handled

Reading storage fails too. Where the browser no longer lets the page use a Storage (site data blocked, the storage of a frame that is gone), Chromium throws SecurityError from every method, WebKit InvalidAccessError from the ones that write, and Firefox its own exceptions (NS_ERROR_FAILURE, and NS_ERROR_FILE_CORRUPTED from a damaged store). So getItem, key, removeItem and clear are reported like setItem, and their safe versions return a Result: getItem(localStorage, k) is a Result<Option<string>, E>.

✓ Accepted0 diagnostics
ts
import { getItem } from "@evobug_com/safe-ts-feature-browser/storage";
import { isErr } from "@evobug_com/safe-ts-std/result";

export function savedTheme(): string {
  const theme = getItem(localStorage, "theme");
  // A store the browser refuses: the page runs with the default theme.
  if (isErr(theme)) return "light";
  return theme ?? "light";
}

The localStorage and sessionStorage properties throw SecurityError themselves where the page may not use storage at all (an opaque origin, a sandboxed frame, site data blocked when the page loaded), before any method runs. A property read has no safe version and isn't reported, so in code that must run without storage, read the object inside unsafe(() => localStorage) and pass on what it gives.

safe-ts.json is generated from browser-api.json and lib.dom.d.ts (node packages/feature-browser/test/pack.ts): the failing members and their errors from the map, and from lib.dom.d.ts what leads to them: which interfaces a class extends, what a function, method or property gives (fetch() a Response, crypto.subtle a SubtleCrypto, document.getElementById() an HTMLElement), and the global variables (localStorage, navigator, document, indexedDB). test/manifest.test.ts fails when the committed file isn't what the script makes, and when a TypeScript upgrade adds or removes a callable; node packages/feature-browser/test/inventory.ts lists which.

A TextDecoder made without fatal: true replaces bad bytes, so its decode() isn't reported (new TextDecoder().decode(bytes)); one made with it, or a parameter typed TextDecoder, is.

Globals (fetch, localStorage, crypto.subtle) ​

A pack describes globals in its globals part (format). They apply to:

  • names nothing in the file declares or imports: fetch(url), localStorage.setItem(...), new URL(text), also through window., self. and globalThis. (window.localStorage.setItem(...)). A local of the same name is not the global: const localStorage = createStore() is yours.
  • what they give, followed as for a module: const response = await fetch(url) is a Response, so response.json() rejects; crypto.subtle.encrypt() is a SubtleCrypto's. Also through unsafe and unsafeAsync: after if (isErr(response)) return, response is still the Response.
  • values declared with a global type: a parameter, a local or a field (res: Response, storage: Storage | undefined, canvas: HTMLCanvasElement, private store: Storage), and a cast (el as HTMLCanvasElement). Only a type name that nothing in the file declares or imports counts: an interface Response of your own, or Response imported from a library, is not the global one.

A method is never matched by its name alone: store.setItem() on a value of no known class isn't reported. When several enabled packs describe a global (the Node and browser packs both list fetch), the one listed first in "features" says what it fails with: put the browser pack first for browser code.

Without a pack, SAFE-TS still reports the built-ins it knows itself: every callable of the language's own built-ins that can throw, from a map like these (The language's built-ins: JSON.parse, new RegExp, decodeURIComponent, BigInt, reduce without an initial value, toISOString, toFixed, the Intl constructors, ...), and the web globals Node and browsers share: new URL, structuredClone, atob, btoa. Where an enabled pack lists one of them, the pack's entry is reported instead, with its error (`structuredClone()` (global) can throw `DOMException [DataCloneError]`). The cases SAFE-TS knows can't fail stay quiet either way: new URL("./worker.ts", import.meta.url), fileURLToPath(new URL("src", import.meta.url)), JSON.stringify of a value whose type is plain data, new RegExp of escaped text, encodeURIComponent of a literal (unhandled-failure).

What the browser errors say ​

errors in browser-api.json says, for each of the 312 members that fail (every category but args, never and returns), what a browser throws, rejects with, passes to the error callback or reports with its events. It uses the Node notation, with the exception names the WHATWG and W3C specs give at each step ("reject with a NotAllowedErrorDOMException"), and a few additions:

WrittenMeans
DOMException [NotAllowedError]a DOMException whose name is 'NotAllowedError'
OverconstrainedError [OverconstrainedError] {constraint}a class that extends DOMException, its name, and the attributes the class adds
WebAssembly.CompileErrora class in a namespace, by its full name (its name is 'CompileError')
MediaError [MEDIA_ERR_DECODE]MediaError and GeolocationPositionError aren't Errors and their code is a number: the constant with that value
... @Chromium, ... @Firefox @WebKitonly in these engines. An alternative without a tag is what the spec says, for every engine
Exception [NS_ERROR_*] @Firefoxan internal Firefox exception that reaches the page: not an Error ([object Exception]), its name an nsresult
(the signal's reason)passed through: what you passed to abort(), what your callback or filter threw

event members say how the failure arrives, separated by ; when there is more than one way:

WrittenMeans
'error' Eventan 'error' event of this class. A plain Event carries no error at all
'error' Event, request.error: DOMException [ConstraintError]then request.error holds the error
'error' SpeechSynthesisErrorEvent {error: 'network' | ...}the event's own properties; it may have others too
transport.ready rejects: WebTransportError [...]a promise property of the object rejects
throws: DOMException [SecurityError]the call itself throws too

Some of the texts:

localStorage.setItem()   QuotaExceededError [QuotaExceededError] {quota?, requested?} @Chromium | DOMException [QuotaExceededError] @Firefox @WebKit
fetch()                  TypeError | DOMException [AbortError | TimeoutError] | (the signal's reason)
response.json()          SyntaxError @Chromium @Firefox | DOMException [SyntaxError] @WebKit | TypeError | DOMException [AbortError | TimeoutError] | (the signal's reason)
new WebSocket()          'error' Event
objectStore.add()        'error' Event, request.error: DOMException [ConstraintError | AbortError | UnknownError] | QuotaExceededError [...] @Chromium | DOMException [QuotaExceededError] @Firefox @WebKit ; throws: DOMException [DataError | DataCloneError]
video.load()             'error' Event, media.error: MediaError [MEDIA_ERR_NETWORK | MEDIA_ERR_DECODE | MEDIA_ERR_SRC_NOT_SUPPORTED]
getCurrentPosition()     GeolocationPositionError [PERMISSION_DENIED | POSITION_UNAVAILABLE | TIMEOUT]

Where the engines differ: Chromium makes QuotaExceededError its own class (a DOMException subclass with quota and requested, as the spec now has it), Firefox and WebKit a DOMException named so; WebKit rejects response.json() on bad JSON with a DOMException [SyntaxError], the others with a JavaScript SyntaxError; a bad SDP in setRemoteDescription() is an RTCError in Firefox (as specified), an OperationError in Chromium and a SyntaxError in WebKit; Firefox's OverconstrainedError is an Error, not a DOMException; reading a File deleted from disk rejects with NotFoundError, but with AbortError in Firefox, and its stream() errors with a TypeError in Chromium and Firefox; only WebKit throws SecurityError when history.pushState() is called more than 100 times in 10 seconds.

Safe versions in the browser ​

Every one of the 189 members that throw or reject has a safe version: a function that returns the failure as a Result (Promise<Result> for one that rejects), with every overload of lib.dom.d.ts kept and the error typed from its text. Global functions keep their names (fetch, atob, structuredClone); a method takes the object first (setItem(localStorage, k, v), json(response), importKey(crypto.subtle, ...)). They are grouped in modules by area, one per spec or API family:

Import fromHas (the classes and functions of)
@evobug_com/safe-ts-feature-browser/fetchfetch, newRequest, newResponse, responseJson; a Body's (json(response), text, blob, arrayBuffer, bytes, formData), Headers' (append, set), clone(request)
/storageStorage (setItem(localStorage, k, v), getItem, key, removeItem, clear), StorageManager (getDirectory(navigator.storage))
/indexeddbdatabases(indexedDB), and IndexedDB's requests settled, written by hand: open, transaction, objectStore, createObjectStore, get (with a validator), getGuarded, put, deleteKey, clear, commit
/cryptoSubtleCrypto: encrypt, decrypt, importKey, deriveKey, deriveBits, wrapKey, unwrapKey (crypto.subtle first)
/canvascreateImageBitmap; HTMLCanvasElement (toDataURL, toBlob, captureStream), OffscreenCanvas, the 2D context's drawImage, getImageData, createPattern, WebGL's texImage2D and kin
/clipboardClipboard (readText(navigator.clipboard), writeText, read, write), ClipboardItem
/urlnewURL; urlParse (an Option, below)
/encodingatob, btoa, TextDecoder (decode)
/messagingstructuredClone, postMessage; BroadcastChannel's and MessagePort's postMessage (broadcastChannelPostMessage, messagePortPostMessage: the global took the name)
/workersWorker, ServiceWorker (postMessage(worker, ...)), ServiceWorkerContainer (register), ServiceWorkerRegistration, Worklet, PushManager, PushSubscription
/domDocument, Element (requestFullscreen, requestPointerLock), History (pushState(history, ...)), AbortSignal, HTMLImageElement, showPicker of inputs and selects, ScreenOrientation, fonts (FontFace, FontFaceSet)
/fileBlob (text(blob), ...), the File System Access handles and writable streams
/streamsReadableStream (pipeTo), readers (read), WritableStream and its writer (close, write)
/mediamedia elements (play(video)), MediaDevices (getUserMedia(navigator.mediaDevices, ...)), tracks, MediaRecorder, Media Source, ImageCapture, RemotePlayback, Web Audio's, Encrypted Media's
/codecsWebCodecs: the decoders' and encoders' flush, ImageDecoder, newVideoFrame
/cache, /cookies, /credentials, /payment, /navigator, /midi, /webrtc, /webgpu, /webtransport, /wasmthe Cache API, Cookie Store, Credential Management and WebAuthn, Payment Request, what sits on navigator (share, getGamepads, badges, permissions.query, wakeLock.request), Web MIDI, WebRTC, WebGPU, WebTransport, and WebAssembly's (compile, instantiate, newModule, grow(memory, n))
@evobug_com/safe-ts-feature-browser/errorsthe error types and guards (below)

Members that return or take null are in the same modules: in /dom, querySelector(document, sel) (and querySelector(document, sel, HTMLInputElement), below), getElementById, closest(el, sel), getAttribute(el, name), insertBefore(parent, node, undefined), createElementNS(document, undefined, name), the collections' item and namedItem, tree walkers; in /fetch, get of Headers, URLSearchParams and FormData; in /url, urlParse(text); in /canvas, getContext(canvas, "2d") and WebGL's (bindBuffer(gl, target, undefined), getUniformLocation, ...). A member that also fails returns a Result of an Option: get(cookieStore, name) is a Promise<Result<Option<CookieListItem>, E>>, and getItem(localStorage, k) and key(localStorage, i) in /storage are a Result<Option<string>, E>.

safe-api.json lists which function is each member's safe version. The declarations use lib.dom.d.ts's types, so a project that imports them needs "lib": ["dom", ...].

querySelector takes a class as a third argument: the element is checked with instanceof and typed by it, so a selector that isn't a tag name needs no cast. An element of another class is undefined, like a missing one. instanceof compares with this window's classes; for an element of an iframe, pass the frame's (frame.contentWindow.HTMLInputElement).

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

export function roadmap(form: HTMLFormElement): Option<string> {
  return querySelector(form, 'input[type="hidden"][name="roadmap"]', HTMLInputElement)?.value;
}

Which browsers. A safe version calls the API it wraps; it doesn't add the API to a browser that lacks it. Where the API is missing, one that returns a Result catches the TypeError (... is not a function) as an Err, typed as the API's documented error, which doesn't list it; one that only turns null into undefined throws it, as the original call would. The one exception is urlParse: URL.parse is from 2024 (Chrome 126, Firefox 126, Safari 18), and without it urlParse uses new URL in a try, with the same answers. For the rest, check the API's own support (MDN's tables) as you would for the original call.

IndexedDB ​

IndexedDB reports failure on its requests, with 'error' events, and throws from the calls that make them (DataError for a bad key, TransactionInactiveError after the transaction committed). The generated safe versions can't wrap that; /indexeddb has a few written by hand, which settle a request or a transaction as a Promise<Result>, or return a Result for the calls that only throw. The object comes first, as with every method's safe version. Records come out as any; get takes a validator, so a read gets its type from a check, not a cast:

✓ Accepted0 diagnostics
ts
import { validate } from "@evobug_com/safe-ts-std/json";
import { q, type Option, type Result } from "@evobug_com/safe-ts-std/result";
import { commit, createObjectStore, get, objectStore, open, put, transaction } from "@evobug_com/safe-ts-feature-browser/indexeddb";

type Draft = { id: string; text: string };

const database = (): Promise<Result<IDBDatabase, unknown>> =>
  open(indexedDB, "drafts", {
    version: 1,
    upgrade: (db, { oldVersion }) => (oldVersion < 1 ? createObjectStore(db, "drafts", { keyPath: "id" }) : undefined),
  });

export async function load(id: string): Promise<Result<Option<Draft>, unknown>> {
  const db = q(await database());
  const tx = q(transaction(db, "drafts"));
  const store = q(objectStore(tx, "drafts"));
  return get(store, id, (value) => validate<Draft>(value));
}

export async function save(draft: Draft): Promise<Result<void, unknown>> {
  const db = q(await database());
  const tx = q(transaction(db, "drafts", "readwrite"));
  const store = q(objectStore(tx, "drafts"));
  q(await put(store, draft));
  return commit(tx);
}
ts
import { parseJsonWith as __jsonParse, validateWith as __jsonValidate, jsonFail as __jsonFail, isJsonErr as __jsonIsErr, isJsonObject as __jsonIsObject, type JsonResult as __JsonResult } from "@evobug_com/safe-ts-std/json"; import { validate } from "@evobug_com/safe-ts-std/json";
import { Err as __qErr } from "@evobug_com/safe-ts-std/result"; import { q, type Option, type Result } from "@evobug_com/safe-ts-std/result";
import { commit, createObjectStore, get, objectStore, open, put, transaction } from "@evobug_com/safe-ts-feature-browser/indexeddb";

type Draft = { id: string; text: string };

const database = (): Promise<Result<IDBDatabase, unknown>> =>
  open(indexedDB, "drafts", {
    version: 1,
    upgrade: (db, { oldVersion }) => (oldVersion < 1 ? createObjectStore(db, "drafts", { keyPath: "id" }) : undefined),
  });

export async function load(id: string): Promise<Result<Option<Draft>, unknown>> {
  const __q1 = await database(); if (__q1 instanceof __qErr) return __q1; const db = __q1;
  const __q2 = transaction(db, "drafts"); if (__q2 instanceof __qErr) return __q2; const tx = __q2;
  const __q3 = objectStore(tx, "drafts"); if (__q3 instanceof __qErr) return __q3; const store = __q3;
  return get(store, id, (value) => __jsonValidate<Draft>(value, __v0));
}

export async function save(draft: Draft): Promise<Result<void, unknown>> {
  const __q4 = await database(); if (__q4 instanceof __qErr) return __q4; const db = __q4;
  const __q5 = transaction(db, "drafts", "readwrite"); if (__q5 instanceof __qErr) return __q5; const tx = __q5;
  const __q6 = objectStore(tx, "drafts"); if (__q6 instanceof __qErr) return __q6; const store = __q6;
  { const __q7 = await put(store, draft); if (__q7 instanceof __qErr) return __q7; __q7; }
  return commit(tx);
}
// ---- generated by safe-ts: JSON validators ----
type __T0 = { "id": string; "text": string; };
function __v0(v: unknown, p: string): __JsonResult<__T0> {
  if (!__jsonIsObject(v)) return __jsonFail(p, "object", v);
  const __j1 = v["id"];
  if (typeof __j1 !== "string") return __jsonFail(p + ".id", "string", __j1);
  const __j2 = __j1;
  const __j3 = v["text"];
  if (typeof __j3 !== "string") return __jsonFail(p + ".text", "string", __j3);
  const __j4 = __j3;
  const out: { "id": string; "text": string; } = { "id": __j2, "text": __j4 };
  return out;
}
  • open(indexedDB, name, { version, upgrade, blocked }): the database, after upgrade ran where it had to (a new database, or a higher version). An Err that upgrade returns aborts the upgrade, and open returns it.
  • transaction(db, stores, mode), objectStore(tx, name), createObjectStore(db, name, options): a Result (NotFoundError for a store that isn't there, ...).
  • get(store, key, check): the record through check, undefined when there is none; getGuarded(store, key, guard) takes a type guard instead (a record it refuses is an InvalidValueError). Prefer get with a check that returns a Result (validate<T>): a hand-written v is T is a cast (no-type-predicate), so pass getGuarded a test TypeScript infers a predicate from ((v) => typeof v === "string") or a std guard (isJsonObject).
  • put(store, value, key?), deleteKey(store, key) (delete is a reserved word), clear(store).
  • commit(tx): undefined once the transaction committed, or why it aborted. Call it right after the last request; awaiting the requests in between is fine (the transaction stays active), awaiting anything else isn't.

A request that fails aborts its transaction, as IndexedDB does by itself. The functions listen with addEventListener, so onsuccess and the other handlers stay yours. npm run test:browsers runs them in Chromium, Firefox and WebKit.

The quick fix works on globals as on modules: localStorage.setItem(k, v) becomes setItem(localStorage, k, v) with the import added, window.localStorage.setItem(...) becomes setItem(window.localStorage, ...), and fetch(url) the pack's fetch(url) (imported under its own name, which then stands for the safe one in that file). What a safe version gives keeps its class: json(response) after the safe fetch is still checked.

Error types, from the texts:

TextTypeGuard
DOMException [NotAllowedError | AbortError]DOMError<"NotAllowedError" | "AbortError">isDOMException(e, "NotAllowedError")
QuotaExceededError [QuotaExceededError] {quota?, requested?} @Chromium | DOMException [QuotaExceededError] @Firefox @WebKitQuotaExceededError | DOMError<"QuotaExceededError">isQuotaExceededError(e)
RTCError [OperationError] {errorDetail: 'sdp-syntax-error', sdpLineNumber} (also OverconstrainedError, WebTransportError, GPUPipelineError)DOMSubclassError<"RTCError", "OperationError", { errorDetail: "sdp-syntax-error"; sdpLineNumber: number | null }>isDOMSubclassError(e, "RTCError", "OperationError")
TypeError, SyntaxError, OverconstrainedError {constraint} @FirefoxPlainError<"TypeError">, ...isPlainError(e, "TypeError")
WebAssembly.CompileErrorWebAssembly.CompileErrorisWebAssemblyError(e, "CompileError")
Exception [NS_ERROR_*] @FirefoxFirefoxException, named NS_ERROR_… (not an Error)isFirefoxException(e)
(the signal's reason)unknown, so the whole error is (fetch, the Body methods)

An engine tag says which engines throw that alternative; the type is the union over all of them, so code that handles the Err handles every engine. Where engines differ only in the class (Chromium's QuotaExceededError subclass, Firefox's and WebKit's plain DOMException), one guard covers both (isQuotaExceededError); where they differ in what is thrown (response.json(): SyntaxError in Chromium and Firefox, DOMException [SyntaxError] in WebKit), check for each (isPlainError(e, "SyntaxError") || isDOMException(e, "SyntaxError")).

Checking them in Chromium, Firefox and WebKit ​

npm run test:browsers (not part of npm run test:std: it starts browsers) loads pages from two local servers (two origins, ports picked by the OS) and makes every failure it safely can happen in each engine: bad base64, URLs and JSON, fetch to a closed port, a CORS refusal, aborted and timed-out signals, a full localStorage, IndexedDB constraint and version errors, a canvas tainted by a cross-origin image, broken images, WebCrypto keys of the wrong length and the wrong key for decrypt, a WebSocket to a closed port, files deleted after they were picked, an opaque-origin frame, a cross-origin frame without permissions, and in Chromium fake camera devices for getUserMedia and a virtual WebAuthn authenticator. Each failure's class, code and properties are compared with the text, and so is whether it threw or rejected.

It checks 224 of the 312 failing members in Chromium, 210 in Firefox and 186 in WebKit (230 in at least one). The calls of a member that throws or rejects go through its safe version, which calls the original: each must return an Err (in its promise, for one that rejects) whose error passes the guard of its declared type. That holds for every member made to fail that has one: 159 in Chromium, 147 in Firefox and 126 in WebKit. The other 82 need a person or hardware: WebGPU, MIDI, gamepads, payments, push, sharing, dropped folders, encoders failing on valid data. specOnly in browser-api.json lists each with what it needs; they are written from the specs.

The test uses playwright-core (a dev dependency of the browser pack, pinned to 1.64.1) and the browsers Playwright installs in ~/.cache/ms-playwright; that version expects Chromium 1248, Firefox 1555 and WebKit 2370, which npx [email protected] install chromium firefox webkit downloads. A missing engine is skipped. SAFE_TS_BROWSERS=firefox picks engines, SAFE_TS_LIST_UNTRIGGERED=1 lists what wasn't checked in each engine and why, and node packages/feature-browser/test/browsers/run.ts webkit Storage prints what each trigger failed with. Run it after editing browser-api.json's errors or upgrading Playwright.

Events of each class ​

browser-api.json's events lists, for every interface whose addEventListener takes the keys of an event map (HTMLElement: HTMLElementEventMap, WebSocket: WebSocketEventMap), that map, and for each map the names it declares and the maps it extends. It is read off lib.dom.d.ts, which TypeScript generates from the specifications' IDL, by events() in test/inventory.ts; test/manifest.test.ts fails when the installed TypeScript says otherwise (node packages/feature-browser/test/inventory.ts --events prints what it reads), and safe-ts.json carries it as it is. unknown-event reads it: a listener for a name the receiver's class doesn't dispatch, and nothing in the program does. A browser pack installed before the section existed is read with the copy the checker was built with. Node's are in the Node pack (Node's events).

Events that happen once ​

Both packs' events have a once part, written by hand rather than read off the types: the events that happen at most once in an object's life, by event map and name, each with the test that says one already happened ($ stands for the object) or null where the platform has none. A class has the entries of its map and of the maps it extends, the nearest first. late-listener reads it: a listener for such an event added after an await may never run.

jsonc
"once": {
  "AbortSignalEventMap": { "abort": "$.aborted" },
  "WebSocketEventMap": { "close": "$.readyState === WebSocket.CLOSED", "open": "$.readyState !== WebSocket.CONNECTING" },
  "IDBTransactionEventMap": { "abort": null, "complete": null }
}
PackMapEvents, and the test
Nodeglobals AbortSignalEventMapabort: $.aborted
Nodenode:stream ReadableEventMapclose: $.closed; end: $.readableEnded
Nodenode:stream WritableEventMapclose: $.closed; finish: $.writableFinished
Nodenode:net SocketEventMapclose: $.closed
Nodenode:child_process ChildProcessEventMapexit: $.exitCode !== null || $.signalCode !== null; spawn: $.pid !== undefined; close: none
Nodenode:fs ReadStreamEventMap, WriteStreamEventMapopen, ready: !$.pending
Nodenode:worker_threads WorkerEventMapexit: $.threadId === -1; online: none
browserAbortSignalEventMapabort: $.aborted
browserWebSocketEventMapopen: $.readyState !== WebSocket.CONNECTING; close: $.readyState === WebSocket.CLOSED
browserWindowEventMapload: document.readyState === "complete"; DOMContentLoaded: document.readyState !== "loading"
browserDocumentEventMapDOMContentLoaded: $.readyState !== "loading"
browserIDBRequestEventMapsuccess, error: $.readyState === "done"
browserIDBTransactionEventMapcomplete, abort: none

Node's are made to happen by packages/feature-node/test/once.test.ts, the browser's in Chromium, Firefox and WebKit by packages/feature-browser/test/browsers/once.test.ts (npm run test:browsers): a listener added before runs once, one added after never runs (also when the code tries again: abort() twice, close() twice, destroy() twice), and the test is true afterwards (and false before, but for spawn, whose pid is there a tick before the event). The manifest tests keep every entry an event its map has.

Left out, and why:

  • error on streams, sockets and processes: emitted with no listener, Node throws it, so a late listener doesn't miss it quietly; and some emitters (a net.Server) emit it more than once.
  • close and listening on a server (net.Server, http.Server): a closed server can listen() again and emit both again. connect on a socket: socket.connect() reconnects it.
  • aborted on an IncomingMessage: deprecated in Node; close with req.destroyed covers it.
  • exit on process: nothing runs after it but its own listeners, so none can be added late.
  • load on an image, a script or media, loadend / load on XMLHttpRequest and FileReader: a new src, open() or read fires them again on the same object.
  • open on an EventSource: it reconnects by itself and fires open again.
  • finish on an Animation: play() again finishes it again.
  • The ws pack's WebSocket (Node): its events aren't listed in the pack's events yet.

zod (@evobug_com/safe-ts-feature-zod) ​

schema.parse() throws a ZodError; parseAsync() rejects with one. SAFE-TS follows a schema to where it was created: z.object(...), .extend(...), inline chains like z.string().parse(x), and schemas imported from other files of your project.

✕ Rejectedunhandled-failure
ts
import { z } from "zod";

const Signup = z.object({ email: z.string().email(), age: z.number().int() });

export function signup(input: unknown): string {
  const form = Signup.parse(input);
  return form.email;
}

The pack's safe versions return the ZodError instead: parse(schema, x) is a Result<T, ZodError<T>>, parseAsync(schema, x) a promise of one that never rejects with it.

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

const Signup = z.object({ email: z.string().email(), age: z.number().int() });
type Signup = z.infer<typeof Signup>;

export function signupEmail(input: unknown): Result<string, z.ZodError<Signup>> {
  const form = q(parse(Signup, input));
  return form.email;
}
ts
import { parse } from "@evobug_com/safe-ts-feature-zod";
import { Err as __qErr } from "@evobug_com/safe-ts-std/result"; import { q, type Result } from "@evobug_com/safe-ts-std/result";
import { z } from "zod";

const Signup = z.object({ email: z.string().email(), age: z.number().int() });
type Signup = z.infer<typeof Signup>;

export function signupEmail(input: unknown): Result<string, z.ZodError<Signup>> {
  const __q1 = parse(Signup, input); if (__q1 instanceof __qErr) return __q1; const form = __q1;
  return form.email;
}

They are written by hand, not generated like the other packs': zod's parse is typed with this (output<this>), and one signature over what every schema has (safeParse, safeParseAsync) serves zod 3, zod 4 and zod/mini alike, without the pack depending on zod. They call the schema's safeParse, so a misused schema (an async refinement under parse) still throws, as schema.parse does: that's a bug to fix, not a failure to handle.

safeParse doesn't throw either. fromZod turns its result into a SAFE-TS Result, so it works with isErr and q. The quick fix writes this for you:

✅ Also accepted: fromZod around safeParse, what the quick fix writes

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

const Signup = z.object({ email: z.string().email(), age: z.number().int() });
type Signup = z.infer<typeof Signup>;

export function signupEmail(input: unknown): Result<string, z.ZodError<Signup>> {
  const form = q(fromZod(Signup.safeParse(input)));
  return form.email;
}
ts
import { fromZod } from "@evobug_com/safe-ts-feature-zod";
import { Err as __qErr } from "@evobug_com/safe-ts-std/result"; import { q, type Result } from "@evobug_com/safe-ts-std/result";
import { z } from "zod";

const Signup = z.object({ email: z.string().email(), age: z.number().int() });
type Signup = z.infer<typeof Signup>;

export function signupEmail(input: unknown): Result<string, z.ZodError<Signup>> {
  const __q1 = fromZod(Signup.safeParse(input)); if (__q1 instanceof __qErr) return __q1; const form = __q1;
  return form.email;
}

ws (@evobug_com/safe-ts-feature-ws) ​

For ws 8, the WebSocket library most Node servers use (Node has no node:ws; its own client is node:http's WebSocket, covered by the Node pack). send(), ping() and pong() throw while the socket is still connecting, and handleUpgrade() throws when it is called a second time for the same socket (two 'upgrade' listeners). Everything else reports failure as an 'error' event:

MemberFailsWith
new WebSocket(url, protocols)throwsSyntaxError: Invalid URL, SyntaxError: The URL's protocol must be one of ..., a fragment, an empty ws+unix: path, an invalid or repeated subprotocol
ws.send(), ping(), pong()throwsError: WebSocket is not open: readyState 0 (CONNECTING) (after close, the error goes to the callback)
wss.handleUpgrade()throwsError: server.handleUpgrade() was called more than once with the same socket
ws.close(), terminate()'error' eventError: WebSocket was closed before the connection was established
new WebSocketServer({ port })'error' eventError [E*] {errno, syscall: 'listen', address, port}
wss.close(cb)callbackError: The server is not running
a client's 'error' eventthe connection's error (ECONNREFUSED from connect, ENOTFOUND from getaddrinfo, TLS), a handshake error (Unexpected server response: 404, Opening handshake has timed out, Invalid Sec-WebSocket-Accept header, ...), or a bad frame from the peer: RangeError [WS_ERR_INVALID_OPCODE], Error [WS_ERR_INVALID_UTF8], ...

Constructors aren't reported yet, so check reports the methods; ws-api.json maps every documented member and safe-ts coverage shows them. A WebSocket is known as one when it is made with new WebSocket(...) (default or named import); the sockets a server passes to its 'connection' listener aren't followed yet.

✕ Rejectedunhandled-failure
ts
import WebSocket from "ws";

export function hello(url: string): void {
  const socket = new WebSocket(url);
  socket.on("error", (error) => console.error(error));
  socket.send("hello");
}

The pack's safe versions are in its main module, @evobug_com/safe-ts-feature-ws, which passes ws's own exports on (named imports; it has no default export): send(socket, data), ping(socket), pong(socket), handleUpgrade(server, request, socket, head, callback) and newWebSocket(url, ...), each with every overload of @types/ws and the error typed (PlainError<"Error">, PlainError<"SyntaxError">). /errors has the guards.

✅ Accepted: the safe version

✓ Accepted0 diagnostics
ts
import { newWebSocket, send } from "@evobug_com/safe-ts-feature-ws";
import type { PlainError } from "@evobug_com/safe-ts-feature-ws/errors";
import { isErr, q, type Result } from "@evobug_com/safe-ts-std/result";
import type { WebSocket } from "ws";

export function hello(url: string): Result<WebSocket, PlainError<"SyntaxError">> {
  const socket = q(newWebSocket(url));
  socket.on("error", (error) => console.error(error));
  socket.on("open", () => {
    const sent = send(socket, "hello");
    if (isErr(sent)) console.error(sent.error.message);
  });
  return socket;
}
ts
import { newWebSocket, send } from "@evobug_com/safe-ts-feature-ws";
import type { PlainError } from "@evobug_com/safe-ts-feature-ws/errors";
import { Err as __qErr } from "@evobug_com/safe-ts-std/result"; import { isErr, q, type Result } from "@evobug_com/safe-ts-std/result";
import type { WebSocket } from "ws";

export function hello(url: string): Result<WebSocket, PlainError<"SyntaxError">> {
  const __q1 = newWebSocket(url); if (__q1 instanceof __qErr) return __q1; const socket = __q1;
  socket.on("error", (error) => console.error(error));
  socket.on("open", () => {
    const sent = send(socket, "hello");
    if (isErr(sent)) console.error(sent.error.message);
  });
  return socket;
}

✅ Also accepted: try/catch around the original's call, without the pack's safe versions

✓ Accepted0 diagnostics
ts
import WebSocket from "ws";

export function hello(url: string): void {
  const socket = new WebSocket(url);
  socket.on("error", (error) => console.error(error));
  socket.on("open", () => {
    try {
      socket.send("hello");
    } catch (error) {
      console.error(error);
    }
  });
}

test/ws.test.ts makes each of these happen against the installed ws, on loopback servers, and checks the error, then calls the safe versions the same way and checks that each returns an Err that passes its guard; it passes with ws 8.0.0, 8.2.0, 8.7.0 and 8.23.0.

vue-router (@evobug_com/safe-ts-feature-vue-router) ​

For vue-router 4 and 5: router.push(), replace() and isReady() reject, router.resolve() throws. The vue-router page has the details and examples. The texts, checked against vue-router 4.0.0, 4.1.6, 4.2.5, 4.6.5 and 5.5.1 by test/vue-router.test.ts:

MemberFails with
router.resolve()Error {type: 1, location}: No match for (an unknown route name) | Error: Missing required param
router.push(), replace()the same two, thrown before the promise exists | (what a navigation guard throws, returns or passes to next) | (what a lazy route component's import rejects with) | Error: Couldn't resolve component (an import that resolves to nothing; in 4.0, also one that rejects)
router.isReady()(what the initial navigation failed with)

The safe versions, from the pack's main module (it passes vue-router's exports on): push(router, to), replace(router, to), isReady(router) and resolve(router, to). They keep vue-router's own types: push(router, to) is a Promise<Result<NavigationFailure | void | undefined, unknown>>, the navigation failure (a guard said no, a newer navigation won, it was already there) still a value. resolve(router, to) is a Result<RouteLocationResolved, MatcherError | PlainError<"Error">>; isMatcherError(e) from /errors tells an unknown name.

Writing a feature pack ​

A feature pack is a package with a safe-ts.json manifest. It is data, not code, and it is only read by the checker, so it adds nothing to your bundle. Code a pack ships (fromZod, the packs' safe versions) is imported on its own and tree-shaken like any module.

jsonc
{
  "library": "zod",                                    // optional: checked against the installed version
  "versions": { "min": "3.0.0", "below": "5.0.0" },
  "modules": [
    {
      "specifiers": ["zod"],                           // import specifiers this entry applies to
      "functions": {                                   // fn() / ns.fn(): exported functions
        "someExport": { "fails": "throws", "error": "SomeError" }
      },
      "methods": {                                     // value.method(): on values from the module, by name
        "parse": {
          "fails": "throws",                           // "throws", "rejects", or a category below
          "error": "ZodError",                         // shown in the message
          "fixes": [
            {
              "title": "Use safeParse: returns a Result (fromZod)",
              "replace": "fromZod(${receiver}.safeParse(${args}))",
              "imports": [{ "name": "fromZod", "from": "@evobug_com/safe-ts-feature-zod" }]
            }
          ]
        }
      },
      "classes": {                                     // by class: used when the value's class is known
        "Client": {
          "extends": "some-lib Base",                  // optional: "module Class", or a list; their methods count too
          "statics": { "connect": { "fails": "rejects", "error": "ConnectError" } },  // Client.connect()
          "methods": {
            "query": { "fails": "rejects", "error": "QueryError",                    // client.query()
                       "safe": "some-lib-pack/client query" },                       // its safe version
            "close": { "fails": "args" }                                             // fails only on misuse
          }
        }
      },
      "creates": {                                     // what a callable returns (awaited): "module Class"
        "Client.connect": "some-lib Client",           // also "fn", "ns.fn", "Class#method", "new Alias"
        "Client#transaction": "some-lib Transaction"
      },
      "instances": { "defaultClient": "some-lib Client" },  // exported values of a class
      "default": "Client",                             // optional: what a default import is
      "complete": true                                 // optional: automatic mode adds nothing here
    }
  ],
  "globals": {                                         // what has no import: a module without specifiers
    "functions": {
      "fetch": { "fails": "rejects", "error": "TypeError" },              // fetch()
      "new URL": { "fails": "throws", "error": "TypeError" },             // new URL(text)
      "WebAssembly.compile": { "fails": "rejects", "error": "WebAssembly.CompileError" }
    },
    "classes": {
      "Body": { "methods": { "json": { "fails": "rejects", "error": "SyntaxError" } } },
      "Response": { "extends": "Body" },              // a bare name is a global class
      "HTMLCanvasElement": { "extends": ["HTMLElement"] },  // a list: several bases
      "Storage": { "methods": { "setItem": { "fails": "throws", "error": "QuotaExceededError" } } }
    },
    "creates": {
      "fetch": "Response",                             // what fetch() returns (awaited)
      "Crypto#subtle": "SubtleCrypto"                  // a property: what crypto.subtle is
    },
    "instances": { "localStorage": "Storage", "crypto": "Crypto" },  // global variables
    "parents": { "MouseEvent": "UIEvent", "UIEvent": "Event" }      // the class each class extends
  },
  "consumes": { "kinds": {}, "operations": {}, "states": {} },  // what uses a value up (below)
  "sinks": { "members": { "some-lib Client#query": { "brand": "Sql", "takes": "argument 0" } } },  // what takes markup, code, SQL, a brand (below)
  "safe": {                                            // the pack's safe modules: what returns a Result
    "some-lib-pack/client": ["connect", "query"]
  },
  "option": {                                          // and what returns an Option for a `null`
    "some-lib-pack/client": { "find": ["Client#find"] }   // function -> the members it stands for
  }
}
  • globals describes what has no import (how it is matched). It has a module's shape without specifiers and default: functions (also new X for a constructor, ns.fn for a namespace's function), classes, creates, instances and parents (the class each class extends, every one of them, where classes lists only those whose calls can fail: override-parameter reads it to tell a wider parameter class from a narrower one). A bare class name is a global class; module Class is a module's, and a module's entries name a global class as globalThis Class. creates also takes a property (Crypto#subtle). A global methods entry is ignored: globals are never matched by method name alone.

  • methods match by name on any value from the module whose class SAFE-TS doesn't know; use them for libraries whose values are all alike (zod's schemas). Where classes differ, use classes: a value of a known class (made with new, by a creates callable, or an instances export) is only checked against its class and its bases, never against methods.

  • fails takes the same categories as the API maps (node-api.json). Only throws and rejects are reported; they need an error. The others say the member is known, and how:

    failsMeanssafe-ts coverage shows
    throws, rejectsit fails, with errorcovered: fails
    argsit fails only when called wrongly: a wrong argument type or value, or the wrong state (after close())covered: fails only on wrong arguments
    neverit doesn't failcovered: doesn't fail
    callback, event, returns, iterates, aborts, propagates, assertit fails in a way check doesn't report: through a callback, an 'error' event, its return value, ...not checked

    These eleven are all fails takes, in functions, methods, statics and a class's methods alike; any other value ("throw") makes safe-ts check warn ("invalid SAFE-TS.json: unknown variant") and leaves the pack out. A member listed in any category is not judged by automatic mode either. For ws, close() throws only for an invalid close code and otherwise fails with an 'error' event, so the ws pack lists it as event: coverage shows it as known, not as "not covered, inferred: TypeError".

  • error is free text, shown in the message. Say what is actually thrown: the class, the code and its values. The official packs use this notation, and their tests check it against the real thing.

  • default is for a CommonJS module that is export = a class, like ws: it names the export a default import is. It is a key of the module entry, next to specifiers (as in the example above), not of a class or of functions; a misplaced one is ignored. With "default": "WebSocket", import WebSocket from "ws" is the WebSocket class, so new WebSocket(url).send(data) is checked against the class's methods, as with import { WebSocket } from "ws". Without it, a default import is the module itself, as for Node's built-ins (import fs from "node:fs").

  • complete: true says the entry lists every member of its specifiers that fails. Without it, automatic mode still judges the members the pack doesn't list, from the library's code. The zod pack sets it: it reports parse and parseAsync, and leaves out on purpose what the code also throws (safeParse on a schema with async refinements, schema builders given wrong options).

  • fixes[].replace replaces the call. Placeholders: ${call} (the whole call), ${callee}, ${receiver} (the value a method is called on) and ${args}.

  • imports are added when the fix is applied, unless the name is already available.

  • safe on an entry names its safe version, "<module> <name>": a function that returns the failure as a Result. unhandled-failure mentions it and offers Use the safe version, which rewrites the call to it. A class method's safe version takes the object first (client.query(sql) becomes query(client, sql)); the others take the same arguments. The top-level safe lists every function of each safe module: calls of them are Results (must-use-result applies, unhandled-failure doesn't). option lists the functions that return an Option where the original returns null, with the members (Class#method, a function's name) each stands for: no-undefined-check-for-null suggests them, and no-null-check-for-undefined reports comparing their value with null. A safe module that passes the original's other exports on is one of its specifiers too, with creates for what its functions return ("prepare": "node:sqlite Statement").

  • Safe versions can be generated: packages/pack-kit/generate.ts writes them, with every overload of the declarations kept and the error typed from the error text (packages/feature-*/test/safe-api.ts are the packs' configurations, npm run generate:safe runs them; pack-kit's README has the options).

  • Runtime helpers (like fromZod) belong in the same package. Keep them free of dependencies on the library where possible, and declare "sideEffects": false so unused ones are tree-shaken away.

  • Test the pack against the real library, at both ends of its versions range. When the installed version is outside the range, safe-ts check warns that the pack may be wrong.

What a member answers ​

unused-answer reports a call whose answer a statement throws away, where the answer is the point. For the platform, that is a member that does something and answers whether, or how much of, it happened: an answers.tells section in the browser and Node maps, each member with what its answer says (the language's are in the built-ins map).

jsonc
"answers": {
  "tells": {
    "node:fs readSync": "how many bytes it read: the rest of the buffer holds what was there before",
    "node:util TextEncoder#encodeInto": "`{ read, written }`: how much of the text it wrote; what doesn't fit is left out"
  }
}

A Node member is named module name, as in sinks; a browser one by its name (confirm, TextEncoder#encodeInto). The browser pack lists TextEncoder#encodeInto, confirm and prompt; the Node pack readSync, readvSync and TextEncoder#encodeInto. Each pack's test/answers.test.ts checks that every member is one the map lists, and shows on Node what the answer tells (a short read, a cut string). Members whose answer is dropped on purpose as a rule aren't listed, each measured over the packages installed here: fs.writeSync (24 of 35 calls drop its count), a stream's write and push (backpressure), navigator.sendBeacon (its own documentation drops it), Map#delete and Set#delete, Cache#delete (a delete that finds nothing is done too). An installed pack from before the section is read with the one this checker was built with.

What uses a value up ​

Some operations use a value up: after buf.transfer() the buffer is detached, after res.text() the body is read, after socket.close() a send() goes nowhere. use-after-consume reports a use after one. Which operations do that, and what goes wrong afterwards, is data in the API maps, next to how each member fails: a consumes section in the language's map (crates/safe_ts_core/ecmascript/ecmascript-api.json: buffers, iterators, structuredClone), in packages/feature-browser/browser-api.json (bodies, streams, sockets, ports, workers, the global postMessage) and in packages/feature-node/node-api.json (the same web APIs Node has, FileHandle, readline, worker_threads). The language's is part of the checker; a pack's is in its safe-ts.json (the browser and Node packs copy theirs there from their API maps when it is generated, and a test keeps the two equal), read with the rest of the pack, so it counts where the pack is enabled and a pack's version and the checker's can't disagree. Any pack can declare one, for its library's values: name them module Name (cursor-lib Cursor, cursor-lib open, cursor-lib Cursor#close), as the Node map names node:fs/promises FileHandle.

jsonc
"consumes": {
  "kinds": {                                   // the values that can be used up
    "Response": {
      "types": ["Response"],                   // declared types that name one
      "madeBy": ["await fetch", "new Response", "Response#clone"]  // what makes one
    },
    "ArrayBuffer": { "types": ["ArrayBuffer"], "madeBy": ["new ArrayBuffer"],
                     "views": ["new Uint8Array", "new DataView"] },  // views share its state
    "generator": { "types": ["Generator"], "madeBy": ["function*"],
                   "closedBy": "some", "methodsOf": "IteratorObject" }
  },
  "operations": {                              // what uses one up, and the state it leaves
    "Response#text": { "uses": "receiver", "state": "bodyUsed" },
    "Array.from": { "uses": "argument 0", "state": "iterated", "iterates": "all" },
    "for...of": { "uses": "iterated", "state": "iterated", "iterates": "all" },
    "Worker#postMessage": { "uses": "transfer 1", "state": "transferred" }
  },
  "states": {
    "bodyUsed": {
      "verb": "read its body",                 // "`res` is used after `res.text()` (line 3) read its body"
      "fails": ["text", "json", "clone"],      // or "every use", with "fine": [members]
      "outcome": "rejects", "error": "TypeError",   // or "throws", or "silent" (a wrong result)
      "releasedBy": [],                        // calls that end it (`releaseLock`)
      "means": "a body can be read once: ...", // the message's second half
      "help": "Read it once and keep what it gave; ..."
    }
  }
}
  • A name is a member of the map (Response#text, Array.from, new Set), function* (a generator function of the same file), a piece of syntax (for...of, for await...of, ..., [a] =, yield*), or in the Node map a module's member (node:fs/promises FileHandle#close, node:readline createInterface). await f in madeBy: the value is what f's promise resolves to.
  • uses: receiver (the value the method is called on), argument N, iterated (syntax), or transfer N...: whatever is listed in the transfer list at argument N (an array, or an options object's transfer), of any kind.
  • An iteration iterates all of an iterator or some of it (it may stop early). A kind used up only by a full pass (closedBy: "all", an array's iterator keeps its rest) and one closed by any ("some", a generator: leaving early calls return()).
  • fails: "every use": any read of the value after it goes wrong, also handing it on, except the members in fine (buffer.detached). A list: only those members (and syntax) go wrong; everything else (res.status, log(res)) is fine.
  • A pack's safe versions stand for the member they wrap (text(res) for res.text(), from the safe of each class method in the pack's manifest), as the operation and as a use.
  • Where two enabled packs describe the same entry, they must describe it the same way: the first pack in "features" keeps its description, and the other is a setup warning. An entry that doesn't hold together (an operation whose state no pack describes, a uses the checker can't read) is a warning too, and left out.

Every entry is shown on the running engine: crates/safe_ts_core/ecmascript/consumes.test.ts and packages/feature-*/test/consumes.test.ts (run by npm run test:std) use a value up with each operation and check that a use the state says fails goes wrong that way (the error's class and code, or, for silent, a wrong result); the browser's own operations (Worker, the global postMessage) run in Chromium, Firefox and WebKit (npm run test:browsers). A pack of your own should do the same for what it declares.

Sinks ​

Some members do something with the text they are given that the text decides: innerHTML parses it into the page, link.href follows it (and a javascript: URL runs), new Function and vm.runInNewContext run it, exec hands it to a shell, readFile opens the path it spells, new RegExp and str.search compile it into a pattern, db.exec runs it as SQL. The sink rules report such a member given a value that isn't a constant the source shows or the sink's brand, made only by a constructor that checks it:

KindRuleThe brand, and its constructors
markupmarkup-sinkHtml: escapeHtml, a sanitizer declared with defineSanitizer, a known sanitizer
a URL it may navigate tourl-sinkSafeUrl: safeHref, safeUrl; or a safe written start
codecode-sinknone: only code the source shows
a shell commandcommand-sinknone: a program run without a shell takes its data as arguments
a file pathpath-sink (idiomatic)SafePath: pathUnder(root, ...parts)
a patternpattern-sinkRegexSource: escapeRegExp
SQLsql-sinknone in std: placeholders, or a brand of your own
a brand of your ownbrand-sinkthe functions declared with brandConstructor("Name", ...)

Which members are sinks is data, next to how each fails: a sinks section in the language's map (eval, Function, RegExp, String#match, matchAll and search, import()), in browser-api.json (from the DOM and HTML standards: every member that parses markup into the live document, every IDL attribute that reflects a URL the browser navigates to, every one that runs script, and setAttribute by the attribute's name) and in node-api.json (child_process, vm, worker_threads, module.register, node:sqlite, and every node:fs and node:fs/promises function @types/node declares with a path parameter, at each such argument). The packs copy theirs into safe-ts.json when they are generated, with the classes on the way to each sink, so a value declared HTMLAnchorElement reaches HTMLHyperlinkElementUtils#href. A pack's safe versions are sinks as the members they stand for.

jsonc
"sinks": {
  "members": {
    "Element#innerHTML": { "kind": "markup", "takes": "set", "anyReceiver": true },  // `el.innerHTML = v`
    "Element#insertAdjacentHTML": { "kind": "markup", "takes": "argument 1" },
    "Document#write": { "kind": "markup", "takes": "every argument" },
    "Element#setAttribute": { "takes": "argument 1",
      "by": { "argument": 0, "names": { "href": "url", "srcdoc": "markup" }, "prefixes": { "on": "code" }, "computed": "code" } },
    "Window#setTimeout": { "kind": "code", "takes": "argument 0", "when": "text" },  // a function given is no sink
    "node:fs copyFile": { "kind": "path", "takes": "arguments 0 1" },
    "node:child_process spawn": { "kind": "command", "takes": "argument 0", "shell": "argument 1" },
    "pg Pool#query": { "brand": "Sql", "takes": "argument 0" }                       // a pack's, for its library
  },
  "inert": {                                     // considered, and not sinks: why
    "DOMParser#parseFromString": "makes a document with no browsing context: ...",
    "fetch": "a request: where it goes is a question of which hosts may be reached (SSRF), not of what runs"
  }
}
  • A member is named as the maps name it: fn, new Class, Class#member (a global's), module fn, module Class#member. takes: set (the property is assigned), argument N, arguments N M, arguments from N, every argument. kind: markup, url, code, command, path, pattern, sql; or brand with the brand's name.
  • by: the kind comes from another argument's constant (lower-cased; xlink:href is href); a name the source doesn't show takes computed's kind. when: "text": only a string argument counts. shell: "argument N": with an options object whose shell is set, the elements of argument N are part of the command too; without one, the program (argument 0) is a file path. anyReceiver: also matched by the member's name on a value whose class can't be told (nothing but an element has an innerHTML).
  • A project declares its own brands' sinks in code, with brandSinks (Proof types); a declared member takes only the brand, in place of what the map says of it.
  • What a sink accepts is the same for every rule that guards one: a value is split into the parts the sink reads (both branches of ?:, the sides of || and ??, the right of &&, a template's substitutions and +'s operands, a const of the file followed to what it holds, the arguments of path.join and its kin), and each part is fine as written (a constant, a number, import.meta.dirname, a known sanitizer's result, a URL with a safe written start) or by its type (the brand, a literal type, a number). For a path, code and a command, what whoever runs the program gives it is fine where the code shows it (process.argv, process.env, a name readdir returned, a function returning one), and a FromOperator past that. v-html, dangerouslySetInnerHTML and :href are judged the same way. A test file's sinks aren't checked: its data is its own.
  • A file's analysis looks at a call or a set only where its member has a name some map, pack or brandSinks of the project lists a sink by, and computes the parts' shapes after its walk, for the sinks it found: a file with none pays nothing more. brandSinks calls are found by listing the project, so the editor and safe-ts check see the same ones.
  • setAttribute(name, value) with a name the source doesn't show takes the kind its written type allows: a union of literals ("title" | "aria-label": none is a sink, so nothing is checked; "href" | "title": a URL), or a template literal type whose start no sink name can follow (`aria-${string}` | `data-${string}`). A string name takes computed's kind.

Handlers: where outside data comes in ​

path-sink reports only in code external input can reach: a handler the runtime calls with data from outside, and what it calls (path-sink). Which callback slots those are is the handlers part of the same section:

jsonc
"sinks": {
  "handlers": {
    "node:http createServer": { "callback": "every argument" },                       // (options, handler)
    "node:http Server#on": { "callback": "argument 1", "on": ["request", "upgrade", "connect", "checkContinue", "checkExpectation"] },
    "process.on": { "callback": "argument 1", "on": ["message"] },
    "ws WebSocket#on": { "callback": "argument 1", "on": ["message"] }                 // the ws pack's
  }
}
  • callback: the arguments that are the handler, as takes names them. A function written in place, a function named, and a function another function returns (createServer(make(deps)): that function is reached) count. What a handler calls is followed as the failure rules follow calls; a call through a declared function type runs every function put into that type.
  • on: for an emitter's on, once, addListener, prependListener and prependOnceListener, the events whose listener gets the outside data; the first argument must name one as a constant.
  • The Node map lists the http, https, http2, net, tls and dgram servers and sockets, and the message of workers, MessagePorts, child processes and process; the ws pack its message and connection. Not readline: a line on stdin is whoever runs the program's. A framework's pack declares its router's or RPC layer's the same way. packages/feature-node/test/sinks.test.ts checks that each is a function of the running Node at an event @types/node declares, and makes each kind of slot receive ../ from a client, a peer or a message.

Every entry is shown on the running engine: crates/safe_ts_core/ecmascript/sinks.test.ts and packages/feature-node/test/sinks.test.ts (run by npm run test:std) give each kind text that does more than its author meant (code runs, the path leaves its directory, the shell runs a second command, the statement deletes every row) and each inert member the same text; the Node test also checks the node:fs list against @types/node, and packages/feature-browser/test/sinks.test.ts every browser member against lib.dom.d.ts. packages/feature-browser/test/browsers/sinks.test.ts (npm run test:browsers) makes every browser sink run script in Chromium, Firefox and WebKit (WebKit doesn't run execCommand("insertHTML")'s), and checks that no inert member does; the members no page can show (<base href>, <frame>, object.data, embed.src, navigation.navigate, a service worker's or a worklet's script) are listed there with why they are kept. A pack of your own should show what it declares the same way.

What must be released ​

Some operations hand back a value that holds something until it is released: a file handle, an interval, a listening server, an observer. unreleased-resource reports one a function doesn't release on some way out. Which operations acquire, what arms a resource and what releases it is data too: an acquires section in packages/feature-browser/browser-api.json and packages/feature-node/node-api.json, copied into each pack's safe-ts.json with consumes and read the same way, so it counts where the pack is enabled. (The language itself has no resource of its own.) A pack of your own can declare its library's.

jsonc
"acquires": {
  "resources": {
    "interval": {
      "acquiredBy": ["setInterval"],              // what hands one back
      "releasedBy": ["clearInterval 0"],          // a callable and the argument it goes in
      "lifelong": true,                           // often meant to live as long as the program
      "what": "an interval",                      // "`id` (an interval) is not released ..."
      "means": "its callback keeps running, ...", // the message's second half
      "release": "clearInterval(id)"              // what the help writes in the `finally`
    },
    "file handle": {
      "acquiredBy": ["await node:fs/promises open"],
      "releasedBy": ["#close"],                   // a method of the value
      "dispose": "await using",                   // the declaration that releases it by itself
      "what": "a file handle", "means": "...", "release": "await handle.close()"
    },
    "HTTP server": {
      "acquiredBy": ["node:http createServer"],
      "armedBy": ["#listen"],                     // holds nothing until it listens
      "releasedBy": ["#close"], "lifelong": true, "what": "a listening server", "means": "...", "release": "server.close()"
    },
    "abort controller": {
      "acquiredBy": ["new AbortController"],
      "armedBy": [".signal to addEventListener"], // once its signal is in a listener's options
      "releasedBy": ["#abort"], "lifelong": true, "what": "...", "means": "...", "release": "controller.abort()"
    }
  }
}
  • acquiredBy names a callable as consumes does: a global (setInterval, URL.createObjectURL), new X, a module's member (node:http createServer, node:worker_threads new Worker), a class's method (ReadableStream#getReader), await f for what an async callable's promise resolves to. The value must be bound to a const or let of the function to be followed.
  • releasedBy: #method (#close, #disconnect) or callable N (clearInterval 0, node:fs/promises rm 0). A pack's safe versions stand for what they wrap: the Node pack's open acquires, its close(handle) releases.
  • armedBy: #method, or .signal to method for a controller whose signal goes in the options of that method's call.
  • lifelong: the resource is often meant to outlive its function on purpose (a worker's stats interval, a page's listeners), so it is reported only in a function that releases it on some path. Without it, a resource never released at all is reported too.
  • Where two enabled packs describe the same resource, the first in "features" keeps its description and the other is a setup warning, like consumes; an operation two resources claim stays with the first; an entry the checker can't read is a warning, and left out.

Every resource is shown on the running engine: packages/feature-*/test/acquires.test.ts (npm run test:std) acquire each one, show that it holds something (an interval ticks, a server is listening, a handle has a file descriptor, a listener hears), release it the first way releasedBy names, and show that it holds nothing; a dispose is shown by disposing one. The browser's own resources (EventSource, Worker, the observers) run in Chromium, Firefox and WebKit (npm run test:browsers).

Automatic mode: libraries without a pack ​

Every package your program imports is analyzed from its JavaScript in node_modules, and what its functions throw or reject is reported, like a pack would. It is on by default; nothing to configure:

ts
import { z } from "zod";
import WebSocket from "ws";

const User = z.object({ name: z.string() });

export function load(input: unknown, url: string): void {
  const user = User.parse(input);
  new WebSocket(url).send(user.name);
}
error[unhandled-failure]: `z.object()` (zod, found in its code: argument check) can throw `Error`, but the failure is not handled
error[unhandled-failure]: `z.string()` (zod, found in its code: argument check) can throw `Error`, but the failure is not handled
error[unhandled-failure]: `User.parse()` (zod, found in its code: contract) can throw `$ZodAsyncError | ZodError`, but the failure is not handled
error[unhandled-failure]: `new WebSocket(url).send()` (ws, found in its code: builtin) can throw `Error`, but the failure is not handled

z.object() and z.string() throw only for contradictory options (message and error together): argument checks, which "infer": "real" leaves out. User.parse() throws zod's own ZodError, and $ZodAsyncError for a schema with async refinements. With the zod pack enabled, the pack decides for zod instead: only parse and parseAsync are reported, with its Use safeParse fix.

What it follows. The package's public exports, also export *, export * as ns and re-exports from other packages (vue re-exports @vue/runtime-dom, which re-exports @vue/runtime-core); CommonJS (module.exports, exports.x, require); functions, classes, methods added to a prototype (C.prototype.m = ..., Object.assign(C.prototype, {...})), exported instances, and functions a factory returns (zod's export const parse = _parse(ZodRealError) throws ZodError). Calls are followed across the package's files and into the packages it depends on. A method is matched by the class of the value where SAFE-TS can see it (new WebSocket(url).send()); on a value returned by a call (z.string().min(1).parse()) it is matched by name, and only when every method of that name in the package fails.

What each finding is. The message says how it was found, so you can judge it:

KindMeans
contractan error class the package declares and exports (ZodError, AxiosError), or a failure its types document with @throws (documented @throws)
internalan error class the package declares but doesn't export
builtinError, TypeError, RangeError, ... on a condition other than the arguments: state (socket.send() before the socket is open), I/O, a value it computed
dynamicthe error isn't known statically: throw e, new (options.Err ?? Err)()
argument checkthe throw's guard only tests the function's own parameters: typeof, instanceof, === undefined, a range check. It fails when called with wrong arguments, which TypeScript often already rules out

A guard that calls something on the argument (isValid(date), pattern.test(text)) is not an argument check: that is validation, often what the function is for. An argument check reached through a call stays one when the caller passes its own arguments on; when the caller passes a value it computed, it is the caller's invariant (builtin); when it passes only constants, it can't fail and isn't reported.

Levels. Choose how much is reported in the nearest package.json:

jsonc
{ "safe-ts": { "infer": "all" } }          // the default: everything found
{ "safe-ts": { "infer": "real" } }         // everything except argument checks
{ "safe-ts": { "infer": "documented" } }   // only what the types also document with @throws
{ "safe-ts": { "infer": false } }          // off
{ "safe-ts": { "infer": { "level": "real", "exclude": ["pixi.js"] } } }   // a level, minus some packages

Anything else is a warning, and the default applies.

Which packages. Every package an import resolves to in node_modules: dependencies listed in package.json, and anything else imported that resolves there. Your own workspace packages (linked into node_modules, resolving to your source) are project code: check follows into them like any file, and they aren't analyzed as libraries. Neither are SAFE-TS's own packages (@evobug_com/safe-ts-*: std, safe-ts-vue, safe-ts-react, ...): they are written to its rules, so their failures are Results, and the one thing they throw is a bug guard (match on a variant the types rule out). Node's built-ins have no JavaScript to read: the Node pack covers them.

Packs win. A member a pack lists, in any category (throws, args, never, ...), is judged by the pack. A pack entry with "complete": true covers all of its specifiers, so automatic mode adds nothing there.

Test runners and assertion libraries. SAFE-TS knows them without a pack, and automatic mode doesn't analyze them: vitest, vite-plus/test, @jest/globals, mocha, chai, expect, @vitest/expect and @jest/expect. A hook or test(...) call throws only when misused (outside a suite, without a callback). An assertion (expect(x).toBe(y), assert.fail(), Chai's assert.isDefined()) throws to fail the test, and the runner reports that failed test. Neither is something your code handles, so neither is reported: not at the top level of a test file (beforeAll(...)), and not in a helper outside any test that ends with assert.fail(). A package that re-exports one of them (export * from "vitest", export { expect } from "chai") gets the same treatment for those names. Its own helpers are still analyzed:

ts
// @acme/test-kit: export * from "vitest"; export function seededCart(items) { ... throws FixtureError }
import { beforeAll, expect, seededCart } from "@acme/test-kit";

beforeAll(() => {
  expect([]).toEqual([]); // not reported: Vitest's hook and assertion
});

export function demoCart(): { items: string[] } {
  return seededCart(["apple"]); // reported: the kit's own code throws `FixtureError`
}

The list is written in the pack format, in the checker's test-apis.json. Hooks and test have the category args, assertions assert, and every module is complete. An enabled pack that describes one of these modules takes precedence. Other Vitest modules are analyzed like any package: vitest/node (createVitest, startVitest) runs tests from a program, and its failures are real ones.

Cache. The first time a package is used, it is analyzed and the result is written to node_modules/.cache/safe-ts/<package>@<version>.<level>.v<format>-<safe-ts version>.json; after that it costs a file read. Measured with the release build: the first safe-ts check of a file calling into pixi.js 8.23 (737 files, 2,225 public functions and methods) takes about 140 ms, 65 ms of it reading pixi's code; zod 4.6 is read in 19 ms, ws 8.23 in 2 ms. From the cache, the same check takes about 25 ms.

  • The version is read from the installed node_modules/<package>/package.json: the installed copy is the truth, so upgrading a package refreshes its entry, and lockfiles don't matter.
  • A new SAFE-TS version, or another level, has entries of its own.
  • When a dependency the analysis followed into (@vue/runtime-core for vue) is updated, the entry is analyzed again.
  • A package linked from outside node_modules (file:, link:) keeps its version while its code changes: its entry is also keyed by the sizes and modification times of its files.
  • SAFE_TS_CACHE_DIR=<dir> puts the cache somewhere else (the same variable as the Node loader's cache); SAFE_TS_CACHE=0 turns writing it off. Deleting it is always safe.

What it can't see. API built at runtime: methods installed under computed names (axios's axios.get, ky's ky.get are made in a loop), values returned from calls it doesn't follow, and callbacks. Those calls aren't reported; safe-ts infer lists what it couldn't analyze. A pack is the way to cover them.

Which libraries need a pack: safe-ts coverage ​

safe-ts coverage src/main.ts lists every library function and method your program calls, whether a pack covers it, and what automatic mode finds for the ones that aren't covered (all of it, whatever the level, with each finding's kind). A module is listed with the packs whose rules or API map describe it, and no pack when none does:

node:crypto   @evobug_com/safe-ts-feature-node
  createHash()             1x  covered: fails only on wrong arguments
  Hash#update()            1x  covered: fails only on wrong arguments
node:fs   @evobug_com/safe-ts-feature-node
  readFile()               1x  not checked: the pack says it reports failure to its callback
  readFileSync()           1x  covered: fails
node:path   @evobug_com/safe-ts-feature-node
  join()                   1x  covered: doesn't fail
zod 4.6.7  @evobug_com/safe-ts-feature-zod
  .object()                1x  not covered, inferred: Error [argument check]
  .parse()                 1x  covered: fails
plain JavaScript values
  .toISOString()           1x
  • covered: fails: the pack says how it fails, and safe-ts check reports the call when the failure isn't handled.
  • covered: doesn't fail and covered: fails only on wrong arguments: the pack lists it as harmless, or as throwing only when the program itself passes a wrong type or value. Neither is reported. These come from the pack's safe-ts.json ("fails": "never" or "args") or its API map (node-api.json), which lists every member of the API, not only the ones that fail.
  • not checked: the pack knows how it fails, but not in a way check reports: through a callback, an 'error' event, or the return value.
  • A method is listed with its class when the pack knows the value's class (Hash#update()), so WebSocket#close() and WebSocketServer#close() are two lines, each with what the pack says about it. .update() without a class: a value whose class the pack can't tell.
  • plain JavaScript values: methods of values a module returned that its pack doesn't describe, such as .toISOString() on fs.statSync(file).mtime. They are JavaScript's own, so they aren't listed under the module.
  • Your own workspace packages are project code, not libraries: check follows into them, and coverage leaves them out.
  • Test runners and assertion libraries (vitest, chai, ...) are listed with built-in test APIs, the checker's own list (see automatic mode).

What the analysis finds: safe-ts infer ​

safe-ts infer <package> (or <package>/<subpath>) runs the same analysis as automatic mode and prints it: for each public function and method, what it throws or rejects, its kind, how it gets there, and where. It doesn't write the cache.

Client#get (async)
  rejects HttpError     [contract]       Client#get → Client#request — client.js:16
  rejects TypeError     [argument check] Client#get → Client#request → assertUrl — util.js:2

It ends with the exports it couldn't analyze, the packages it followed into, counts by kind, and a draft safe-ts.json for when you want a pack. The draft is a starting point to review: the code shows what can fail, not which failures are part of the API's contract. It holds the contract failures; --all adds the other kinds.

Measured on real libraries (functions and methods analyzed; failures by kind; exports it can't analyze):

LibraryAnalyzedcontractinternalbuiltindynamicargument checkNot analyzable
zod 4.683743029029022 (regex constants, globalRegistry)
ws 8.23570018030
pixi.js 8.232,2253018705524
vue 3.5209000306
axios 1.21647010603 (axios.get and the other request methods are made in a loop)
date-fns 4.428915 (all documented with @throws)00001

For zod, parse and schema.parse() throw ZodError (contract), and the schema builders (z.object, z.string, z.email, ...) are argument checks: they throw only for contradictory options. For ws, it finds what a hand-written pack lists: send, ping and pong throw Error when the socket isn't open, and WebSocketServer#handleUpgrade throws Error for a socket handled twice. Built-in Node modules have no JavaScript source at all.

What the packs can't see ​

A pack recognizes values created from the library in code SAFE-TS can follow: directly, derived from another such value, or imported from another project file. A schema that arrives as a function parameter is not recognized, because that needs the type checker. For classes, the class has to be visible the same way: a value that comes out of a call the pack has no creates entry for (gzip.pipe(destination) returns the destination, whatever it is) has no known class, and only the module's methods apply to it.

Rules in this guide: unhandled-failure

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