Safe versions at the null boundary: T | null as Option, in every pack #61
Loading…
Reference in a new issue
No description provided.
Delete branch "evobug/safe-option"
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?
What
The feature packs' safe versions now cover the
nullboundary as well. A member whose declarations returnT | nullor take a requiredT | nullgets a safe version in its pack's module, named by the same rule as the others:Option<T>.nullbecomesundefinedthrough?? undefined, so"",0andfalsecome back unchanged. In a promise,Promise<T | null>becomesPromise<Option<T>>.T | nulltakesOption<T>, and anundefinedpassed there reaches the original asnull(function insertBefore(self, a0, a1) { return self.insertBefore(a0, a1 ?? null); }). An optionalT | nullis typedTand passed on unchanged, so anundefinedthere still means "not passed".Result<Option<T>, E>, for exampledirReadSync(dir)andget(cookieStore, name).querySelector(document, "input")is anOption<HTMLInputElement>.Counts
OptionOptionnullkept (nullSkipped)WebSocketServer#address)Browser categories:
querySelector,getElementById,closest,getAttribute*,insertAdjacentElement,lookupNamespaceURIcreateElementNS(document, undefined, name),setAttributeNS,getElementsByTagNameNSinsertBefore(list, item, undefined),TreeWalker,NodeIterator,XPathResultitem,namedItem,NamedNodeMapgetItem,keygetofHeaders,URLSearchParamsandFormDataURL.parse(urlParse)getContext, and WebGL'sbind*,delete*,is*,uniform*and gettersprompt,open,getSelectionNode categories:
urlParse, andgetofURLSearchParamsandMIMEParamsServer#addressDatabase#location,setAuthorizer(db, undefined)setUncaughtExceptionCaptureCallback(undefined)Dir#readandreadSync, which also failcreateCipheriv'siv,ffi.dlopen(undefined)stream.isReadableandisWritablereadvandwritev'spositiongetItem,keyandgeton the globalsWhat keeps its
null, and whyEach skip is recorded with its reason in
safe-api.jsonundernullSkipped.nullandundefinedboth in one parameter or return: they may mean different things. 10 such parameters in Node (mkdir/readFile/openwith a callback,crypto.sign,readlinewrite). 2 such returns (Agent#createConnection).nullat an argument in some overloads, nothing there in others. 13 in Node (exec,execFile,computeSecret,read, ...) and 6 in the browser (texImage2D,new KeyframeEffect,addIceCandidate, ...).nullthrough a type alias: 6 in Node (WriteFileOptions,EncodingOption). It can't be removed from the type as written.thisparameter:MediaQueryList#addListenerandremoveListenerdeclare one.A failing member in this list keeps its
Resultsafe version,nullincluded.SQLite decision: rows are not changed.
NULLis a value there, not absence. The row values sit insideRecord<string, SQLOutputValue>, so the generator never touches them.get(statement)returns{ note: null }as the original does, andundefinedonly when there is no row, again as the original does. Rows go throughvalidate<T>, as #46 set up. A test asserts this, in both the types and the runtime.JSON and
structuredClone: their values are typedanyorT, so the rule never matches them. They are left as they are; std'sparseJsonandvalidatealready convert.Property decision: properties get no safe version.
el.parentElement,response.bodyand the like stay as they are. Most reads are property accesses where?? undefinedreads naturally, and a getter turned into a function (parentElement(el)) doesn't. Methods that look like getters, such asTreeWalker#parentNode(), are callables, so they are covered.Out of scope:
RegExp#execandString#matchare language built-ins and appear in neither API map, so no pack has them. For those, the checker only offers Compare with null.Side effects
x?: T | nullparameter, the safe version's type drops thenull(mkdirSync(path, options?)). What you pass still reaches the original unchanged.Checker
no-undefined-check-for-null: when an enabled pack has the API'sOptionsafe version, the rule's help names it. A second fix, Use the safe version, which returns an Option, rewrites the call and adds the import:localStorage.getItem(k) !== undefinedbecomesgetItem(localStorage, k) !== undefined. This also works through theconstthe value was stored in.Element#closest,Storage#getItem, ...), sore.exec(s)is never pointed atURLPattern#exec.no-null: reports a strict comparison withnullof a safe version'sOption, directly or through aconst. Such a comparison is always false or always true. The quick fix is Compare with undefined.Optionsafe versions are not Results, somust-use-resultdoesn't apply andunhandled-failurenever fires on them.safe-ts.jsonhas a new top-leveloptionfield: module → function → the members it stands for.safenow lists only what returns a Result.safeModulesandmanifestSafebuild both lists for every pack.unhandled-failurequick fix keeps working, including on members that now returnResult<Option<T>, E>(cookieStore.get→get(cookieStore, ...)).Tests
safe-api.test.tscovers the new members,resultsandoptionsper module,nullSkipped, and the manifests.feature-node/test/option.test.ts):undefined; present"",0,falseandNaNcome back unchanged;Result<Option<Dirent>>fromdirReadSync;undefinedreaches the original asnull: the originalsdb.setAuthorizer(undefined)andprocess.setUncaughtExceptionCaptureCallback(undefined)throwERR_INVALID_ARG_TYPE, and the safe versions work;null.feature-browser/test/browsers/option.test.ts, part ofnpm run test:browsers): the same checks in Chromium, Firefox and WebKit, on DOM queries and attributes, storage,get,urlParse,getContext,insertBeforeandsetAttributeNSpassingnull,pushState's optionalurl, andcookieStore.get.test/types/infer.ts):querySelector(document, "input")isOption<HTMLInputElement>, and"svg"isOption<SVGSVGElement>;querySelector<HTMLDialogElement>;closest(el, "form"),getContext(canvas, "2d" | "webgl2");insertBefore(list, li, undefined)isHTMLLIElement;createElementNS(document, undefined, "x");Result<Option<...>>forget(cookieStore, ...)anddirReadSync;null.crates/safe_ts_core/tests/fixes.rs.get(params, key)againstparams.get(key), with half the keys missing, measures 1.00x. It is added tobench:checkas amaxratio with a 1.0 baseline.Docs changed
docs/guide/libraries.md: the new section "nullbecomesOption", the browser modules, and the manifest'soptionfielddocs/guide/absence.md: "nullfrom outside", with the safe versionsdocs/rules/no-undefined-check-for-null.mddocs/rules/no-null.mddocs/rules/must-use-result.mdREADME.md: the pack table, the layout list, and the manifest notesCHANGELOG.md: Unreleasedpackages/pack-kit/README.mdpackages/feature-browser/test/browsers/README.mdVerification
All of these pass on
origin/main(1d83085) with this commit on top:cargo nextest run --workspace(210 tests)cargo clippy -q --workspace --all-targets: nothing newnpm run buildnpm run test:std(285)npm run typecheck, includingtypecheck:emitnode scripts/docs-typecheck.mjs(380 examples)npm run test:docsnpm run test:vitenpm run test:browsers: errors in the three engines, plus the newoptiontest in eachnode scripts/verify-packages.mjsnpm run bench:check🤖 Generated with Claude Code