Node pack: safe versions that return a Result, with typed errors, and a quick fix to use them #59

Merged
sionzee merged 1 commit from evobug/safe-node-apis into main 2026-11-16 21:42:19 +01:00
Owner

Builds on #57 (base: evobug/pack-globals) and also contains #58 (automatic mode leaves @evobug_com/safe-ts-* packages alone), which the safe versions depend on: without it, automatic mode would read the wrappers from node_modules and report their try/catch as library failures.

What

The Node pack stops being checker-only. For 433 of the 448 members that throw or reject, it ships a safe version: a function that returns the failure as a Result (Promise<Result> for one that rejects; the promise never rejects). The error type E is exactly what the member's error text says.

Module layout

One module per Node module, under exports subpaths:

  • @evobug_com/safe-ts-feature-node/fs, /fs/promises, /child_process, /sqlite, /crypto, /zlib, /dns/promises, ... (35 Node modules)
  • /globals: Node's globals (fetch, structuredClone, newResponse, json(response), ...)
  • /errors: the error types and guards

Each module re-exports everything that doesn't fail unchanged, types included, so it can replace import ... from "node:fs" (named and import * as imports; there is no default export). Modules that @types/node declares with export = (events, stream, process, module, ...) can't use export * (TS2498), so their names are listed explicitly. 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>. The files are generated .js + .d.ts under packages/feature-node/safe/. The runtime is a thin try/catch → Err (.then(ok, err) for promises) in // @safe-ts std files. The package is "sideEffects": false, and a test bundles one wrapper with Vite and checks that only it and the runtime come along.

Method naming rule

  • A function keeps its name (readFileSync, fetch, realpathSync.native).
  • A method becomes a function that takes the object first, named after the method: run(statement, x), read(handle, ...), json(response). One function serves every class of the module that has that method and fails the same way (run(statement), run(tagStore)), as overloads.
  • When the name is taken (an export of the Node module, another safe version, a reserved word), or the classes' methods fail in different ways, the camelCased class goes first: dirClose(dir) (node:fs exports close), fileHandleReadFile(handle) (readFile is a function's safe version), zipFileGet / zipBufferGet (one rejects, one throws), resolverResolve4.
  • A constructor is new plus the class (newDatabaseSync, newResponse); a static is class plus method (responseJson, zipFileOpen).

Error types (/errors)

Text Type Guard
Error [E*] {errno, syscall: 'open', path} SystemError<"open", { path: string }> (code: ErrnoCode, errno, syscall, the listed props) isSystemError(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?} SqliteError isSqliteError(e)
Error [ERR_OSSL_*] {...} OpenSSLError isOpenSSLError(e)
TypeError {cause} PlainError<"TypeError", { cause: unknown }> isPlainError(e, "TypeError")
DOMException [AbortError] DOMError<"AbortError"> isDOMException(e, "AbortError")
(passed through) unknown (so the whole E is)

ErrnoCode and DnsCode are literal unions; a test checks them against util.getSystemErrorMap() and node:dns. For callback/event members, which get no wrapper, the guards narrow the unknown (or ErrnoException) a callback, catch or 'error' listener gets. The docs show this.

Wrapped vs skipped

433 wrapped (198 functions/constructors/statics, 235 methods), 15 skipped, each listed with its reason in safe-api.json:

  • 13 aren't in @types/node 26.6: crypto.createMac, parsePKCS12, fs.openAsBlobSync, vm.createScript, Module#load, Url#parse, url.resolveObject, perf_hooks.importHistogram, process.initgroups, http.validateHeader{Name,Value}.withoutStackTrace, Http2ServerResponse#setTrailer, require.resolve.
  • Decipheriv#setAuthTag exists only on DecipherGCM/CCM/OCB in the types.
  • util.parseArgs returns ParsedResults, which node:util doesn't export.

The checker

  • safe-ts.json gets safe on entries ("<module> <name>") and a top-level safe list of each safe module's functions. Each safe module is also a specifier of its Node module, so the names it passes on keep what the pack knows. Its own creates entries keep classes known through it: prepare(db, sql) gives a Statement, so statement.run() is still checked.

  • A call of a safe version is a Result: must-use-result applies, unhandled-failure doesn't.

  • unhandled-failure on a covered call says in its help that a safe version exists, and offers Use the safe version. The fix rewrites the call (readFileSync(p), stmt.run(x) → run(stmt, x), new Response(b) → newResponse(b)) and the import. It reuses an existing import or namespace import from the safe module, appends to an existing import { } from it, and aliases to safeX when the name is bound anywhere in the file (for example by import { readFileSync } from "node:fs").

  • So that the fix produces code that compiles, it is offered only where a Result fits:

    • as is, as the value of a const/let without a type annotation;
    • with q(...) in a function returning Result<_, unknown>, as a declaration's value, an assignment's value, or a statement of its own (q(writeFileSync(p, s));, const t: string = q(readFileSync(p, "utf8"))). This keeps the value's type and is accepted by must-use-result.

    It is not offered on readdirSync(dir).sort(), on arguments, on returns, or on dropped calls elsewhere; there the help still names the safe version. On TwitchRTS's Node scripts, 1 of 4 Node findings gets the fix (fs.readdirSync(dir).sort() was the case that showed why the restriction is needed); the other 3 are dropped writeFileSync/mkdirSync calls in non-Result functions.

Generator interface (for the browser, ws and vue-router follow-up)

packages/pack-kit/ (private; its README has the details):

  • notation.ts: the error-text parser, moved here from the Node and browser packs (the ws test uses it too).
  • errors.ts: an error text → TS type and guards, driven by ErrorRules.
  • generate.ts: generate(config: PackConfig, members: Member[]) returns { files, wrappers, skipped, exports }.
    • Member is { scope, name, category, error }, with names as the API maps write them (f, f.g, new C, C.s, C#m).
    • PackConfig:
      • compilerOptions: the TS program the declarations are read from (lib: ["dom"] for the browser, types: ["ws"] for ws).
      • targets: scope → output module and specifier; null for globals (calls go through globalThis).
      • classes: map name → declared name (Statement → StatementSync).
      • errors: the ErrorRules.
      • errorsModule, header, runtimeExports, skip.
      • packages: packages whose types the declarations may import. Anything else from a package file is written as the same-named global or as an inlined alias, or the member is skipped. This is why undici-types never leaks into the Node pack's declarations.
  • runtime/: the shared runtime.js and core.js (PlainError, CodedError, DOMError and their guards). The generator copies both into each pack.
  • How it works: declarations are read with TypeScript 7's API (typescript/unstable/sync). Overloads are copied as written, and each name is resolved by the checker and rewritten to resolve from the generated module ($fs.PathOrFileDescriptor, this → the object's type).

A follow-up pack writes three things: a map → members function, a PackConfig, and its own errors module. The Node pack's configuration is packages/feature-node/test/safe-api.ts; npm run generate:safe regenerates everything.

Found on the way

node:sqlite Statement#iterate throws both when called (binding fails) and while iterating. The existing trigger only exercised the iterator, so the wrapper returned the iterator, not an Err. I added a call-time trigger. The wrapper test now requires an Err from at least one trigger per member.

Verification

  • cargo nextest run --workspace: 201 passed
  • cargo clippy -q --workspace --all-targets: nothing new (the warnings are the same pre-existing ones)
  • npm run build, npm run test:std (267 passed), npm run typecheck (now also packages/feature-node/test/types and packages/pack-kit), npm run typecheck:emit
  • node scripts/docs-typecheck.mjs (373 examples), npm run test:docs, npm run test:vite, npm run bench:check
  • node scripts/verify-packages.mjs: all package checks passed: a safe version imported from the packed tarball runs (readFileSync / readFile of a missing file is an Err passing isSystemError(e, "ENOENT")), and a strict project using /fs, /sqlite, /child_process and /errors compiles with skipLibCheck off

New tests:

  • test/errors.test.ts: routes every trigger through its safe version. 375 of the 413 triggered members are checked: each returns an Err whose error passes the guard of its declared type, and the rejecting ones resolve and never reject. The remaining 38 are 15 without a safe version and 23 that can't be routed (child-process triggers; non-configurable natives: dns/promises functions, SQLTagStore and ZipFile methods).
  • test/safe-api.test.ts:
    • safe/, safe-api.json and the exports match the generator's output (drift from node-api.json or @types/node fails);
    • the error code unions match the running Node;
    • every module loads and passes on the originals;
    • sample calls behave;
    • the one-wrapper bundle stays small.
  • test/types/infer.ts: overload inference for readFileSync with and without an encoding, readdirSync (the same type as the original's), execSync, newDatabaseSync → prepare → run, fs/promises, globals, and guard narrowing. It compiles under strict options with skipLibCheck off and all generated declarations included.
  • Rust: tests/fixes.rs covers aliasing, namespace and existing imports, methods, a rejecting member, a global constructor, q for dropped values and annotated declarations, no fix on .sort() or arguments, and that the fixed code has no new diagnostics. A new fixture safe_versions/ covers must-use-result on wrapper calls, no unhandled-failure on them, classes known through prepare, and pass-through names.

Docs changed

  • docs/guide/libraries.md: new sections Safe versions, Error types and guards and The quick fix; the Node example uses the safe version and says both ways work; install note (now a regular dependency); safe in Writing a feature pack.
  • docs/guide/async.md: a safe-version example next to unsafeAsync.
  • docs/rules/unhandled-failure.md, docs/rules/must-use-result.md
  • README.md: repo map, pack section, and the pack table's Runtime column for Node.
  • CHANGELOG.md (Unreleased)
  • packages/pack-kit/README.md (new), packages/feature-browser/test/browsers/README.md (notation path)
  • package.json description no longer says "checker-only".

🤖 Generated with Claude Code

Builds on #57 (base: `evobug/pack-globals`) and also contains #58 (automatic mode leaves `@evobug_com/safe-ts-*` packages alone), which the safe versions depend on: without it, automatic mode would read the wrappers from `node_modules` and report their `try`/`catch` as library failures. ## What The Node pack stops being checker-only. For **433 of the 448** members that throw or reject, it ships a safe version: a function that returns the failure as a `Result` (`Promise<Result>` for one that rejects; the promise never rejects). The error type `E` is exactly what the member's `error` text says. ### Module layout One module per Node module, under `exports` subpaths: - `@evobug_com/safe-ts-feature-node/fs`, `/fs/promises`, `/child_process`, `/sqlite`, `/crypto`, `/zlib`, `/dns/promises`, ... (35 Node modules) - `/globals`: Node's globals (`fetch`, `structuredClone`, `newResponse`, `json(response)`, ...) - `/errors`: the error types and guards Each module re-exports everything that doesn't fail unchanged, types included, so it can replace `import ... from "node:fs"` (named and `import * as` imports; there is no default export). Modules that `@types/node` declares with `export =` (events, stream, process, module, ...) can't use `export *` (TS2498), so their names are listed explicitly. 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>`. The files are generated `.js` + `.d.ts` under `packages/feature-node/safe/`. The runtime is a thin `try`/`catch` → `Err` (`.then(ok, err)` for promises) in `// @safe-ts std` files. The package is `"sideEffects": false`, and a test bundles one wrapper with Vite and checks that only it and the runtime come along. ### Method naming rule - A function keeps its name (`readFileSync`, `fetch`, `realpathSync.native`). - A method becomes a function that takes the object first, named after the method: `run(statement, x)`, `read(handle, ...)`, `json(response)`. One function serves every class of the module that has that method and fails the same way (`run(statement)`, `run(tagStore)`), as overloads. - When the name is taken (an export of the Node module, another safe version, a reserved word), or the classes' methods fail in different ways, the camelCased class goes first: `dirClose(dir)` (node:fs exports `close`), `fileHandleReadFile(handle)` (`readFile` is a function's safe version), `zipFileGet` / `zipBufferGet` (one rejects, one throws), `resolverResolve4`. - A constructor is `new` plus the class (`newDatabaseSync`, `newResponse`); a static is class plus method (`responseJson`, `zipFileOpen`). ### Error types (`/errors`) | Text | Type | Guard | |---|---|---| | `Error [E*] {errno, syscall: 'open', path}` | `SystemError<"open", { path: string }>` (`code: ErrnoCode`, `errno`, `syscall`, the listed props) | `isSystemError(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?}` | `SqliteError` | `isSqliteError(e)` | | `Error [ERR_OSSL_*] {...}` | `OpenSSLError` | `isOpenSSLError(e)` | | `TypeError {cause}` | `PlainError<"TypeError", { cause: unknown }>` | `isPlainError(e, "TypeError")` | | `DOMException [AbortError]` | `DOMError<"AbortError">` | `isDOMException(e, "AbortError")` | | `(passed through)` | `unknown` (so the whole `E` is) | | `ErrnoCode` and `DnsCode` are literal unions; a test checks them against `util.getSystemErrorMap()` and `node:dns`. For `callback`/`event` members, which get no wrapper, the guards narrow the `unknown` (or `ErrnoException`) a callback, `catch` or `'error'` listener gets. The docs show this. ### Wrapped vs skipped 433 wrapped (198 functions/constructors/statics, 235 methods), 15 skipped, each listed with its reason in `safe-api.json`: - 13 aren't in `@types/node` 26.6: `crypto.createMac`, `parsePKCS12`, `fs.openAsBlobSync`, `vm.createScript`, `Module#load`, `Url#parse`, `url.resolveObject`, `perf_hooks.importHistogram`, `process.initgroups`, `http.validateHeader{Name,Value}.withoutStackTrace`, `Http2ServerResponse#setTrailer`, `require.resolve`. - `Decipheriv#setAuthTag` exists only on `DecipherGCM`/`CCM`/`OCB` in the types. - `util.parseArgs` returns `ParsedResults`, which `node:util` doesn't export. ### The checker - `safe-ts.json` gets `safe` on entries (`"<module> <name>"`) and a top-level `safe` list of each safe module's functions. Each safe module is also a specifier of its Node module, so the names it passes on keep what the pack knows. Its own `creates` entries keep classes known through it: `prepare(db, sql)` gives a Statement, so `statement.run()` is still checked. - A call of a safe version is a Result: `must-use-result` applies, `unhandled-failure` doesn't. - `unhandled-failure` on a covered call says in its help that a safe version exists, and offers **Use the safe version**. The fix rewrites the call (`readFileSync(p)`, `stmt.run(x)` → `run(stmt, x)`, `new Response(b)` → `newResponse(b)`) and the import. It reuses an existing import or namespace import from the safe module, appends to an existing `import { }` from it, and aliases to `safeX` when the name is bound anywhere in the file (for example by `import { readFileSync } from "node:fs"`). - So that the fix produces code that compiles, it is offered only where a Result fits: - as is, as the value of a `const`/`let` without a type annotation; - with `q(...)` in a function returning `Result<_, unknown>`, as a declaration's value, an assignment's value, or a statement of its own (`q(writeFileSync(p, s));`, `const t: string = q(readFileSync(p, "utf8"))`). This keeps the value's type and is accepted by `must-use-result`. It is not offered on `readdirSync(dir).sort()`, on arguments, on returns, or on dropped calls elsewhere; there the help still names the safe version. On TwitchRTS's Node scripts, 1 of 4 Node findings gets the fix (`fs.readdirSync(dir).sort()` was the case that showed why the restriction is needed); the other 3 are dropped `writeFileSync`/`mkdirSync` calls in non-Result functions. ### Generator interface (for the browser, ws and vue-router follow-up) `packages/pack-kit/` (private; its README has the details): - `notation.ts`: the error-text parser, moved here from the Node and browser packs (the ws test uses it too). - `errors.ts`: an error text → TS type and guards, driven by `ErrorRules`. - `generate.ts`: `generate(config: PackConfig, members: Member[])` returns `{ files, wrappers, skipped, exports }`. - `Member` is `{ scope, name, category, error }`, with names as the API maps write them (`f`, `f.g`, `new C`, `C.s`, `C#m`). - `PackConfig`: - `compilerOptions`: the TS program the declarations are read from (`lib: ["dom"]` for the browser, `types: ["ws"]` for ws). - `targets`: scope → output module and specifier; `null` for globals (calls go through `globalThis`). - `classes`: map name → declared name (`Statement` → `StatementSync`). - `errors`: the `ErrorRules`. - `errorsModule`, `header`, `runtimeExports`, `skip`. - `packages`: packages whose types the declarations may import. Anything else from a package file is written as the same-named global or as an inlined alias, or the member is skipped. This is why undici-types never leaks into the Node pack's declarations. - `runtime/`: the shared `runtime.js` and `core.js` (`PlainError`, `CodedError`, `DOMError` and their guards). The generator copies both into each pack. - How it works: declarations are read with TypeScript 7's API (`typescript/unstable/sync`). Overloads are copied as written, and each name is resolved by the checker and rewritten to resolve from the generated module (`$fs.PathOrFileDescriptor`, `this` → the object's type). A follow-up pack writes three things: a map → `members` function, a `PackConfig`, and its own errors module. The Node pack's configuration is `packages/feature-node/test/safe-api.ts`; `npm run generate:safe` regenerates everything. ## Found on the way `node:sqlite Statement#iterate` throws both when called (binding fails) and while iterating. The existing trigger only exercised the iterator, so the wrapper returned the iterator, not an `Err`. I added a call-time trigger. The wrapper test now requires an `Err` from at least one trigger per member. ## Verification - `cargo nextest run --workspace`: 201 passed - `cargo clippy -q --workspace --all-targets`: nothing new (the warnings are the same pre-existing ones) - `npm run build`, `npm run test:std` (267 passed), `npm run typecheck` (now also `packages/feature-node/test/types` and `packages/pack-kit`), `npm run typecheck:emit` - `node scripts/docs-typecheck.mjs` (373 examples), `npm run test:docs`, `npm run test:vite`, `npm run bench:check` - `node scripts/verify-packages.mjs`: all package checks passed: a safe version imported from the packed tarball runs (`readFileSync` / `readFile` of a missing file is an `Err` passing `isSystemError(e, "ENOENT")`), and a strict project using `/fs`, `/sqlite`, `/child_process` and `/errors` compiles with `skipLibCheck` off New tests: - `test/errors.test.ts`: routes every trigger through its safe version. 375 of the 413 triggered members are checked: each returns an `Err` whose error passes the guard of its declared type, and the rejecting ones resolve and never reject. The remaining 38 are 15 without a safe version and 23 that can't be routed (child-process triggers; non-configurable natives: dns/promises functions, SQLTagStore and ZipFile methods). - `test/safe-api.test.ts`: - `safe/`, `safe-api.json` and the exports match the generator's output (drift from `node-api.json` or `@types/node` fails); - the error code unions match the running Node; - every module loads and passes on the originals; - sample calls behave; - the one-wrapper bundle stays small. - `test/types/infer.ts`: overload inference for `readFileSync` with and without an encoding, `readdirSync` (the same type as the original's), `execSync`, `newDatabaseSync` → `prepare` → `run`, fs/promises, globals, and guard narrowing. It compiles under strict options with `skipLibCheck` off and all generated declarations included. - Rust: `tests/fixes.rs` covers aliasing, namespace and existing imports, methods, a rejecting member, a global constructor, `q` for dropped values and annotated declarations, no fix on `.sort()` or arguments, and that the fixed code has no new diagnostics. A new fixture `safe_versions/` covers `must-use-result` on wrapper calls, no `unhandled-failure` on them, classes known through `prepare`, and pass-through names. ## Docs changed - `docs/guide/libraries.md`: new sections *Safe versions*, *Error types and guards* and *The quick fix*; the Node example uses the safe version and says both ways work; install note (now a regular dependency); `safe` in *Writing a feature pack*. - `docs/guide/async.md`: a safe-version example next to `unsafeAsync`. - `docs/rules/unhandled-failure.md`, `docs/rules/must-use-result.md` - `README.md`: repo map, pack section, and the pack table's Runtime column for Node. - `CHANGELOG.md` (Unreleased) - `packages/pack-kit/README.md` (new), `packages/feature-browser/test/browsers/README.md` (notation path) - `package.json` description no longer says "checker-only". 🤖 Generated with [Claude Code](https://claude.com/claude-code)
Automatic mode: leave SAFE-TS's own packages alone
All checks were successful
Benchmarks / bench (pull_request) Successful in 2m13s
8ea6cd911d
Installed from npm, @evobug_com/safe-ts-std was analyzed like any library:
std's `match` throws a bug guard for a variant the types rule out, so every
`match(...)` call was reported as unhandled-failure, and the Vite build in
scripts/verify-packages.mjs (check: "error") failed. This repo never saw it:
std is a workspace here, so project code.

`@evobug_com/safe-ts-*` packages are skipped by automatic mode now. A fixture
with a stand-in package checks it (reported under another name, not under the
prefix).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Node pack: safe versions of what throws or rejects, typed from the error texts
All checks were successful
Benchmarks / bench (pull_request) Successful in 2m14s
c7b25716c3
The Node pack ships, for 433 of the 448 members that throw or reject, a function that
returns the failure as a Result (Promise<Result> for one that rejects), one module per Node
module (@evobug_com/safe-ts-feature-node/fs, /sqlite, /globals, ...), each passing on what
doesn't fail. Every overload of @types/node is kept with only the return type wrapped; the
error type is exactly the member's `error` text. /errors exports SystemError, NodeError,
SqliteError, ... and guards (isSystemError(e, "ENOENT"), isNodeError(e, code), ...).

The generator (packages/pack-kit, with the error notation moved there) reads the
declarations with TypeScript 7's API; npm run generate:safe rewrites the files and a test
fails when they drift. The checker knows the safe versions: calls of them are Results
(must-use-result), unhandled-failure names the safe version and offers "Use the safe
version" where the fixed code compiles.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
sionzee changed target branch from evobug/pack-globals to main 2026-11-16 21:34:40 +01:00
sionzee force-pushed evobug/safe-node-apis from c7b25716c3
All checks were successful
Benchmarks / bench (pull_request) Successful in 2m14s
to ea4151000d
All checks were successful
Benchmarks / bench (pull_request) Successful in 2m22s
2026-11-16 21:42:15 +01:00
Compare
sionzee deleted branch evobug/safe-node-apis 2026-11-16 21:42:19 +01:00
Sign in to join this conversation.
No reviewers
No labels
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

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