Safe versions for the browser, ws, vue-router and zod packs, written out in full #60

Merged
sionzee merged 1 commit from evobug/safe-pack-apis into main 2026-11-16 21:43:20 +01:00
Owner

What

Every feature pack now ships safe versions, like the Node pack in #59, so none of them is checker-only any more.

Pack Safe versions Modules
browser 184 of 184 members that throw or reject (generated from browser-api.json + lib.dom.d.ts) one per area: /fetch, /storage, /indexeddb, /crypto, /canvas, /clipboard, /url, /encoding, /messaging, /workers, /dom, /file, /streams, /media, /codecs, /cache, /cookies, /credentials, /payment, /navigator, /midi, /webrtc, /webgpu, /webtransport, /wasm, plus /errors
ws 5 of 5 (from ws-api.json + @types/ws): send, ping, pong, handleUpgrade, newWebSocket the main module, which passes ws's exports on, plus /errors
vue-router 4 of 4 (from the new vue-router-api.json + vue-router's own types): push, replace, isReady, resolve the main module, which passes vue-router's exports on, plus /errors
zod parse(schema, x) / parseAsync(schema, x), hand-written; fromZod kept .

No member is skipped in these packs. The Node pack still has 433 of 448 (unchanged).

The design is #59's: overloads are kept with only the return type wrapped, methods take the object first, the error is typed from the exact text, the error types and guards are exported, and a drift test covers the generated files.

  • Browser error types. The type is the union over the engines' alternatives, e.g. QuotaExceededError | DOMError<"QuotaExceededError">. The new types are QuotaExceededError, DOMSubclassError<Class, Name, Props> (for RTCError, OverconstrainedError, WebTransportError and GPUPipelineError) and FirefoxException, with guards for each.
  • Quick fix on globals. Use the safe version now works on globals: localStorage.setItem(k, v) becomes setItem(localStorage, k, v), with the import added. This needed no checker change, only the data; Rust tests cover it.
  • zod. Its safe versions are hand-written because zod's parse is typed through this. One signature over safeParse serves zod 3, zod 4 and zod/mini without depending on zod. A misused schema (an async refinement under parse) still throws, as schema.parse does.

vue-router errors

The texts were free-text ("Error (a guard threw, or a lazy route component failed to load)"). They are rewritten in the exact notation and checked against real vue-router 4.0.0, 4.1.6, 4.2.5 and 4.6.5:

  • resolve() throws Error {type: 1, location}: No match for or Error: Missing required param.
  • push() / replace() throw those two synchronously, before their promise exists. They reject with whatever a navigation guard throws, returns or passes to next, or whatever a lazy component's import rejects with. A lazy import that resolves to nothing rejects with Error: Couldn't resolve component. In 4.0 a rejecting import also turns into that error.
  • isReady() rejects with whatever the initial navigation failed with.
  • An aborted, cancelled or duplicated navigation resolves to a NavigationFailure, so it isn't a failure. The safe push keeps vue-router's NavigationFailure | void | undefined as the value.
  • safe-ts.json now knows a router from createRouter() / useRouter(), so the quick fix can rewrite router.push(to) to push(router, to).

Generator changes (packages/pack-kit)

Safe versions written out in full. This was the parent's request; the numbers are measured on Node 26. Each wrapper now has its own call site, for example try { return self.readUInt32LE(...args); } catch (error) { return new Err(error); }. Functions are $module.f(...args), constructors new $module.C(...args), and async ones Promise.resolve(...).then(ok, failed) plus a sync catch. runtime.js keeps only ok / failed.

Hot loop with buf.readUInt32LE(o):

Call ns per call
direct 1.19
safe version, now 2.2 (1.84×)
shared attempt helper, before 11.8 (10×)

npm run bench:check now runs packages/feature-node/bench/safe.bench.ts. The ratio is checked as max (baseline 1.84, allowed ≤ 3.68), and the shared-helper ratio is reported as info. The bench is a script rather than a docs bench block because the docs site runs those in the browser, which has no Buffer.

New options and rules:

  • Target.namespace handles WebAssembly.*.
  • Target.main puts a pack's safe versions in its main module.
  • Package module files are resolved: @types/ws (a module with export =) and vue-router's hashed dist/router-*.d.mts (mapped by the names the package exports).
  • typeof of a package namespace is handled.
  • unexported lists names an export = module lists but can't be imported by (WebSocketEventMap of @types/ws, TS2614).
  • A method inherited from a generic base is skipped only when its signature uses the base's type parameters. Before, every such method was skipped.

core.js fix. isError is now Error.isError(e) || e instanceof Error. Firefox's OverconstrainedError extends Error but isn't one to Error.isError, so isPlainError failed on it in the browser test.

Node pack. It is regenerated with written-out bodies. The diff is only the .js bodies, runtime.js/.d.ts and the isError line in core.js; the .d.ts files are identical.

Packages

  • browser, ws and vue-router: files include safe/, "sideEffects": false, and peerDependencies on std (ws and vue-router also on their library). Their descriptions no longer say checker-only.
  • build-packages.mjs lists them as runtime installs. They are still copied as generated .js + .d.ts, not compiled.
  • npm run generate:safe regenerates all four generated packs.
  • npm run typecheck now compiles each pack's declarations strictly (test/types/).

Verification

  • Browser, npm run test:browsers (Playwright 1.64.1): each triggered call goes through its safe version in the page, frames and sandboxed frames included, and must return an Err that passes the guard of its declared type. Results:

    • Chromium: 155 of 155 verified members with a safe version;
    • Firefox: 147 of 147;
    • WebKit: 124 of 124;
    • 226 members verified in at least one engine.
  • ws: the real-library test calls the safe versions; it passes with ws 8.0.0, 8.2.0, 8.7.0 and 8.23.0 (SAFE_TS_WS).

  • vue-router: the new real-library test (SAFE_TS_VUE_ROUTER) passes with 4.0.0, 4.1.6, 4.2.5 and 4.6.5.

  • Node: the errors test still checks 375 triggered members through their safe versions (same as #59).

  • node scripts/verify-packages.mjs: one safe version per pack (node, browser, ws, vue-router, zod) imports and runs from the packed tarballs, and tsc accepts their declarations.

  • The brief's list:

    • cargo nextest run --workspace
    • cargo clippy -q --workspace --all-targets
    • npm run build
    • npm run test:std
    • npm run typecheck
    • npm run typecheck:emit
    • node scripts/docs-typecheck.mjs
    • npm run test:docs
    • npm run test:vite
    • npm run bench:check

    All pass: nextest 205/205, test:std 280/280, bench:check 31 ratios, safe version 1.85x (allowed ≤ 3.68); no new clippy warnings.

Docs changed

  • docs/guide/libraries.md:
    • tip and install;
    • safe-versions speed;
    • new Safe versions in the browser (module table, error types, how engine tags map to types);
    • browser verification numbers;
    • the zod, ws and new vue-router sections;
    • writing a pack.
  • docs/vue/router.md: shows the safe push, and says both forms work.
  • README.md: repo map and the pack table's Runtime column.
  • packages/pack-kit/README.md
  • packages/feature-browser/test/browsers/README.md
  • CHANGELOG.md

Examples that wrapped these APIs in unsafe(...) now show the safe version first and say both work: localStorage.setItem in the libraries guide, and router.push on the vue-router page.

🤖 Generated with Claude Code

## What Every feature pack now ships safe versions, like the Node pack in #59, so none of them is checker-only any more. | Pack | Safe versions | Modules | |---|---|---| | browser | 184 of 184 members that throw or reject (generated from `browser-api.json` + `lib.dom.d.ts`) | one per area: `/fetch`, `/storage`, `/indexeddb`, `/crypto`, `/canvas`, `/clipboard`, `/url`, `/encoding`, `/messaging`, `/workers`, `/dom`, `/file`, `/streams`, `/media`, `/codecs`, `/cache`, `/cookies`, `/credentials`, `/payment`, `/navigator`, `/midi`, `/webrtc`, `/webgpu`, `/webtransport`, `/wasm`, plus `/errors` | | ws | 5 of 5 (from `ws-api.json` + `@types/ws`): `send`, `ping`, `pong`, `handleUpgrade`, `newWebSocket` | the main module, which passes ws's exports on, plus `/errors` | | vue-router | 4 of 4 (from the new `vue-router-api.json` + vue-router's own types): `push`, `replace`, `isReady`, `resolve` | the main module, which passes vue-router's exports on, plus `/errors` | | zod | `parse(schema, x)` / `parseAsync(schema, x)`, hand-written; `fromZod` kept | `.` | No member is skipped in these packs. The Node pack still has 433 of 448 (unchanged). The design is #59's: overloads are kept with only the return type wrapped, methods take the object first, the error is typed from the exact text, the error types and guards are exported, and a drift test covers the generated files. - **Browser error types.** The type is the union over the engines' alternatives, e.g. `QuotaExceededError | DOMError<"QuotaExceededError">`. The new types are `QuotaExceededError`, `DOMSubclassError<Class, Name, Props>` (for `RTCError`, `OverconstrainedError`, `WebTransportError` and `GPUPipelineError`) and `FirefoxException`, with guards for each. - **Quick fix on globals.** *Use the safe version* now works on globals: `localStorage.setItem(k, v)` becomes `setItem(localStorage, k, v)`, with the import added. This needed no checker change, only the data; Rust tests cover it. - **zod.** Its safe versions are hand-written because zod's `parse` is typed through `this`. One signature over `safeParse` serves zod 3, zod 4 and zod/mini without depending on zod. A misused schema (an async refinement under `parse`) still throws, as `schema.parse` does. ### vue-router errors The texts were free-text ("Error (a guard threw, or a lazy route component failed to load)"). They are rewritten in the exact notation and checked against real vue-router 4.0.0, 4.1.6, 4.2.5 and 4.6.5: - `resolve()` throws `Error {type: 1, location}: No match for` or `Error: Missing required param`. - `push()` / `replace()` throw those two **synchronously**, before their promise exists. They reject with whatever a navigation guard throws, returns or passes to `next`, or whatever a lazy component's import rejects with. A lazy import that resolves to nothing rejects with `Error: Couldn't resolve component`. In 4.0 a rejecting import also turns into that error. - `isReady()` rejects with whatever the initial navigation failed with. - An aborted, cancelled or duplicated navigation resolves to a `NavigationFailure`, so it isn't a failure. The safe `push` keeps vue-router's `NavigationFailure | void | undefined` as the value. - `safe-ts.json` now knows a router from `createRouter()` / `useRouter()`, so the quick fix can rewrite `router.push(to)` to `push(router, to)`. ### Generator changes (`packages/pack-kit`) **Safe versions written out in full.** This was the parent's request; the numbers are measured on Node 26. Each wrapper now has its own call site, for example `try { return self.readUInt32LE(...args); } catch (error) { return new Err(error); }`. Functions are `$module.f(...args)`, constructors `new $module.C(...args)`, and async ones `Promise.resolve(...).then(ok, failed)` plus a sync `catch`. `runtime.js` keeps only `ok` / `failed`. Hot loop with `buf.readUInt32LE(o)`: | Call | ns per call | |---|---| | direct | 1.19 | | safe version, now | 2.2 (1.84×) | | shared `attempt` helper, before | 11.8 (10×) | `npm run bench:check` now runs `packages/feature-node/bench/safe.bench.ts`. The ratio is checked as `max` (baseline 1.84, allowed ≤ 3.68), and the shared-helper ratio is reported as info. The bench is a script rather than a docs ```bench``` block because the docs site runs those in the browser, which has no `Buffer`. **New options and rules:** - `Target.namespace` handles `WebAssembly.*`. - `Target.main` puts a pack's safe versions in its main module. - Package module files are resolved: `@types/ws` (a module with `export =`) and vue-router's hashed `dist/router-*.d.mts` (mapped by the names the package exports). - `typeof` of a package namespace is handled. - `unexported` lists names an `export =` module lists but can't be imported by (`WebSocketEventMap` of @types/ws, TS2614). - A method inherited from a generic base is skipped only when its signature uses the base's type parameters. Before, every such method was skipped. **`core.js` fix.** `isError` is now `Error.isError(e) || e instanceof Error`. Firefox's `OverconstrainedError` extends `Error` but isn't one to `Error.isError`, so `isPlainError` failed on it in the browser test. **Node pack.** It is regenerated with written-out bodies. The diff is only the `.js` bodies, `runtime.js/.d.ts` and the `isError` line in `core.js`; the `.d.ts` files are identical. ### Packages - browser, ws and vue-router: `files` include `safe/`, `"sideEffects": false`, and `peerDependencies` on std (ws and vue-router also on their library). Their descriptions no longer say checker-only. - `build-packages.mjs` lists them as runtime installs. They are still copied as generated `.js` + `.d.ts`, not compiled. - `npm run generate:safe` regenerates all four generated packs. - `npm run typecheck` now compiles each pack's declarations strictly (`test/types/`). ## Verification - Browser, `npm run test:browsers` (Playwright 1.64.1): each triggered call goes through its safe version in the page, frames and sandboxed frames included, and must return an `Err` that passes the guard of its declared type. Results: - Chromium: 155 of 155 verified members with a safe version; - Firefox: 147 of 147; - WebKit: 124 of 124; - 226 members verified in at least one engine. - ws: the real-library test calls the safe versions; it passes with ws 8.0.0, 8.2.0, 8.7.0 and 8.23.0 (`SAFE_TS_WS`). - vue-router: the new real-library test (`SAFE_TS_VUE_ROUTER`) passes with 4.0.0, 4.1.6, 4.2.5 and 4.6.5. - Node: the errors test still checks 375 triggered members through their safe versions (same as #59). - `node scripts/verify-packages.mjs`: one safe version per pack (node, browser, ws, vue-router, zod) imports and runs from the packed tarballs, and tsc accepts their declarations. - The brief's list: - `cargo nextest run --workspace` - `cargo clippy -q --workspace --all-targets` - `npm run build` - `npm run test:std` - `npm run typecheck` - `npm run typecheck:emit` - `node scripts/docs-typecheck.mjs` - `npm run test:docs` - `npm run test:vite` - `npm run bench:check` All pass: nextest 205/205, test:std 280/280, bench:check 31 ratios, safe version 1.85x (allowed ≤ 3.68); no new clippy warnings. ## Docs changed - `docs/guide/libraries.md`: - tip and install; - safe-versions speed; - new *Safe versions in the browser* (module table, error types, how engine tags map to types); - browser verification numbers; - the zod, ws and new vue-router sections; - writing a pack. - `docs/vue/router.md`: shows the safe `push`, and says both forms work. - `README.md`: repo map and the pack table's Runtime column. - `packages/pack-kit/README.md` - `packages/feature-browser/test/browsers/README.md` - `CHANGELOG.md` Examples that wrapped these APIs in `unsafe(...)` now show the safe version first and say both work: `localStorage.setItem` in the libraries guide, and `router.push` on the vue-router page. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
Safe versions for the browser, ws, vue-router and zod packs; written out in full
All checks were successful
Benchmarks / bench (pull_request) Successful in 2m0s
6e8450702c
Every feature pack now ships safe versions, as the Node pack does since #59: functions that
return what a member throws or rejects with as a Result, every overload kept, the error typed
from the pack's exact text, with error types and guards.

- browser: all 184 members that throw or reject, generated from browser-api.json and
  lib.dom.d.ts, in modules by area (/storage, /fetch, /crypto, /indexeddb, /canvas, /clipboard,
  /url, /encoding, ...). The error type is the union over the engines; /errors adds
  QuotaExceededError, DOMSubclassError, FirefoxException and their guards. The browser test
  sends every triggered call through its safe version in Chromium, Firefox and WebKit.
- ws: send, ping, pong, handleUpgrade, newWebSocket in the main module (it passes ws on).
- vue-router: push, replace, isReady, resolve in the main module, keeping vue-router's
  NavigationFailure. Its error texts are rewritten in the exact notation, checked against
  vue-router 4.0.0, 4.1.6, 4.2.5 and 4.6.5 (push/replace throw an unknown name synchronously;
  "Couldn't resolve component" for an empty lazy import).
- zod: parse(schema, x) and parseAsync(schema, x), hand-written over safeParse (zod 3, 4, mini).

The generator writes each safe version out in full instead of calling a shared
attempt(f, self, args): a hot readUInt32LE(buf, o) goes from 10x to 1.8x the bare call.
npm run bench:check measures it. It also learns namespaces (WebAssembly), a pack's main module,
package module files (@types/ws's export =, vue-router's dist chunks) and methods of generic
bases. The Node pack is regenerated (same declarations; written-out bodies).

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

No due date set.

Dependencies

No dependencies set

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