Node pack: safe versions that return a Result, with typed errors, and a quick fix to use them #59
Loading…
Reference in a new issue
No description provided.
Delete branch "evobug/safe-node-apis"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
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 fromnode_modulesand report theirtry/catchas 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 typeEis exactly what the member'serrortext says.Module layout
One module per Node module, under
exportssubpaths:@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 guardsEach module re-exports everything that doesn't fail unchanged, types included, so it can replace
import ... from "node:fs"(named andimport * asimports; there is no default export). Modules that@types/nodedeclares withexport =(events, stream, process, module, ...) can't useexport *(TS2498), so their names are listed explicitly. Every overload is kept with only the return type wrapped:readFileSync(p, "utf8")is aResult<string, E>andreadFileSync(p)aResult<Buffer, E>. The files are generated.js+.d.tsunderpackages/feature-node/safe/. The runtime is a thintry/catch→Err(.then(ok, err)for promises) in// @safe-ts stdfiles. 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
readFileSync,fetch,realpathSync.native).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.dirClose(dir)(node:fs exportsclose),fileHandleReadFile(handle)(readFileis a function's safe version),zipFileGet/zipBufferGet(one rejects, one throws),resolverResolve4.newplus the class (newDatabaseSync,newResponse); a static is class plus method (responseJson,zipFileOpen).Error types (
/errors)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?}SqliteErrorisSqliteError(e)Error [ERR_OSSL_*] {...}OpenSSLErrorisOpenSSLError(e)TypeError {cause}PlainError<"TypeError", { cause: unknown }>isPlainError(e, "TypeError")DOMException [AbortError]DOMError<"AbortError">isDOMException(e, "AbortError")(passed through)unknown(so the wholeEis)ErrnoCodeandDnsCodeare literal unions; a test checks them againstutil.getSystemErrorMap()andnode:dns. Forcallback/eventmembers, which get no wrapper, the guards narrow theunknown(orErrnoException) a callback,catchor'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:@types/node26.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#setAuthTagexists only onDecipherGCM/CCM/OCBin the types.util.parseArgsreturnsParsedResults, whichnode:utildoesn't export.The checker
safe-ts.jsongetssafeon entries ("<module> <name>") and a top-levelsafelist 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 owncreatesentries keep classes known through it:prepare(db, sql)gives a Statement, sostatement.run()is still checked.A call of a safe version is a Result:
must-use-resultapplies,unhandled-failuredoesn't.unhandled-failureon 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 existingimport { }from it, and aliases tosafeXwhen the name is bound anywhere in the file (for example byimport { readFileSync } from "node:fs").So that the fix produces code that compiles, it is offered only where a Result fits:
const/letwithout a type annotation;q(...)in a function returningResult<_, 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 bymust-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 droppedwriteFileSync/mkdirSynccalls 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 byErrorRules.generate.ts:generate(config: PackConfig, members: Member[])returns{ files, wrappers, skipped, exports }.Memberis{ 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;nullfor globals (calls go throughglobalThis).classes: map name → declared name (Statement→StatementSync).errors: theErrorRules.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 sharedruntime.jsandcore.js(PlainError,CodedError,DOMErrorand their guards). The generator copies both into each pack.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 →
membersfunction, aPackConfig, and its own errors module. The Node pack's configuration ispackages/feature-node/test/safe-api.ts;npm run generate:saferegenerates everything.Found on the way
node:sqlite Statement#iteratethrows both when called (binding fails) and while iterating. The existing trigger only exercised the iterator, so the wrapper returned the iterator, not anErr. I added a call-time trigger. The wrapper test now requires anErrfrom at least one trigger per member.Verification
cargo nextest run --workspace: 201 passedcargo 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 alsopackages/feature-node/test/typesandpackages/pack-kit),npm run typecheck:emitnode scripts/docs-typecheck.mjs(373 examples),npm run test:docs,npm run test:vite,npm run bench:checknode scripts/verify-packages.mjs: all package checks passed: a safe version imported from the packed tarball runs (readFileSync/readFileof a missing file is anErrpassingisSystemError(e, "ENOENT")), and a strict project using/fs,/sqlite,/child_processand/errorscompiles withskipLibCheckoffNew tests:
test/errors.test.ts: routes every trigger through its safe version. 375 of the 413 triggered members are checked: each returns anErrwhose 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.jsonand the exports match the generator's output (drift fromnode-api.jsonor@types/nodefails);test/types/infer.ts: overload inference forreadFileSyncwith 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 withskipLibCheckoff and all generated declarations included.tests/fixes.rscovers aliasing, namespace and existing imports, methods, a rejecting member, a global constructor,qfor dropped values and annotated declarations, no fix on.sort()or arguments, and that the fixed code has no new diagnostics. A new fixturesafe_versions/coversmust-use-resulton wrapper calls, nounhandled-failureon them, classes known throughprepare, 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);safein Writing a feature pack.docs/guide/async.md: a safe-version example next tounsafeAsync.docs/rules/unhandled-failure.md,docs/rules/must-use-result.mdREADME.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.jsondescription no longer says "checker-only".🤖 Generated with Claude Code
c7b25716c3ea4151000d