Storage reads return a Result: the browser pack's getItem, key, removeItem and clear catch what Storage throws #158
Loading…
Reference in a new issue
No description provided.
Delete branch "storage-pack-catches"
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?
Adopter feedback (marked serious): the browser pack's
getItemletStorage's exceptions through. An adopter movedunsafe(() => localStorage.getItem(key))to the pack'sgetItem, as the escape-hatch policy asks, and a page with blocked storage failed to boot.What was wrong
safe/storage.jshadand
keythe same.browser-api.jsonhadStorage#getItem,#removeItemand#clearasneverand#keyasargs. The HTML spec says onlysetItemthrows (and thelocalStoragegetter), but the engines do throw from the other members. I made each one fail in Playwright, on thelocalStorageof a removed frame:lengthException [NS_ERROR_FAILURE]nullnull0Chromium's message is "Access is denied for this document", from the same per-call access check that refuses blocked site data. Firefox also throws
NS_ERROR_FILE_CORRUPTEDfrom a damaged store; no trigger makes that one. Reduced example of the bug:What changed
browser-api.json:Storage#getItem,#key,#removeItemand#clearare nowthrows, each with its own error text, andsetItemgains the same alternatives:DOMException [SecurityError] @Chromium | Exception [NS_ERROR_*] @FirefoxDOMException [InvalidAccessError] @WebKitnpm run generate:safe:getItemandkeyare nowResult<Option<string>, DOMError<"SecurityError"> | FirefoxException<`NS_ERROR_${string}`>>.removeItemandclearare new safe versions returningResult<void, … | DOMError<"InvalidAccessError"> | …>.safe-api.jsonandsafe-ts.jsonfollow: storage'soptionentry is gone, and they are nowresults.setItemalready used (DOMError,FirefoxException), so they stay consistent.localStorage.getItem(),key(),removeItem()andclear()(also onsessionStorageand on values typedStorage) asunhandled-failure, with Use the safe version.no-undefined-check-for-nullno longer offers the storage safe version forgetItem(k) !== undefined, because aResultcompared withundefinedwould treat anErras a value. It still offers Compare with null. Nothing in the crate was hard-coded to the old type: the change is all in the pack data.safe/(every wrapper not returning aResult, checked against its category and spec): one more clear case. The Push API spec saysPushManager#getSubscription()rejects with anAbortError("If there is an error with subscription, … reject promise with an AbortError"). It wasneverand returnedPromise<Option<PushSubscription>>. Now it isrejectsand returnsPromise<Result<Option<PushSubscription>, DOMError<"AbortError">>>. No trigger can make it fail, so it is inspecOnly. The rest arenever/args/returns/propagatesby design: the null lookups,TreeWalker(which rethrows your filter's error),window.open/getContextreturningnull, andpopErrorScope. The hand-written IndexedDB wrappers all returnResults already.Still reported / not changed
setItem's quota errors and their guards are unchanged; the new alternatives are added to its union.localStorage/sessionStoragegetters throwSecurityErrorthemselves where storage is blocked when the page loads, or in an opaque origin.getItem(localStorage, k)evaluates the getter before the safe version runs. A property read has no safe version and isn't reported, so the guide and the migrate skill now say to read the object insideunsafe(() => localStorage)where that must not crash. The adopter already does this. A safe accessor (or reporting the getter) would be a new kind of pack entry, so I left it as an open question.Storage#lengthis a getter too (it throws in Chromium/Firefox, as in the table). Same open question.Migrating (CHANGELOG, under Changed)
Unwrap first, then compare the
Option:Result:const saved = q(getItem(localStorage, k)).if (isErr(saved)) return fallback;.removeItem/clearvalues that are dropped are nowmust-use-result:q(...)them orvoidthem.Tests
packages/feature-browser/test/browsers/triggers.ts: a trigger per member, on a removed frame'slocalStorage, given this page'sStorage.prototypeso the error is made in this realm and the call goes through the routed safe version.npm run test:browsers: all pass.specOnly).Errthat passes its guard (159/147/126).run.ts firefox Storage, and a Firefox-only run of every trigger). In the three-engine run they came out "did not fail" for Firefox, so only Chromium and WebKit verified them there.test/safe-api.test.ts: a stubStoragewhose members throw aSecurityError(each safe version returns it as anErrthat passesisDOMException), and a working stub (values,undefinedfornull,undefinedfrom the writers).test/types/infer.ts: the new types ofgetItem,removeItem,setItemandgetSubscription.crates/safe_ts_core/tests/fixes.rs:Optionsafe-version tests now useget(params, k)(URLSearchParams#get, still a plainOption).storage_reads_fail_and_their_safe_version_is_a_result:localStorage.getItem(...) !== undefinedgets bothno-undefined-check-for-null(with Compare with null only) andunhandled-failure.q(getItem(...))then compared is clean. A droppedremoveItem/clear/getItemismust-use-result.sessionStorage.removeItem,localStorage.clear()andstorage.key(0)are reported.npm run test:std: 456 pass, 0 fail.cargo nextest run -p safe_ts_core: 364 pass.npm run test:soundness: pass, with no change in the escaping classes.npm run test:docs: pass (the docs examples run with the browser pack on).npm run test:rewrites(full): fails on two lines that this change doesn't touch:new missing-mut hoist-const226 → 229 andtext aliased-mut call14 → 16.misses.txtwas last updated in #144, before #150 changed howmutlends, so they come from main. I leftmisses.txtas it is; they need their own fix.Adopter tree
safe-ts check apps/client/{src,tests} apps/admin/{src,tests} --idiomatic, with main's browser pack against this branch's: 2381 diagnostics in both runs, with no differences. Their code already passesunsafe(() => localStorage)to the safe versions. Their two raw calls (localStorage.removeItemandlocalStorage.clear()in test helpers) aren't reported, because their client lists@evobug_com/safe-ts-feature-nodebefore the browser pack in"features". As documented, the first pack that describes a global decides, and the Node pack'sStoragehas no failinggetItem/clear. With the browser pack first, both are reported. The type change will show up for them intsc: theirgetItem(...)uses treat the value as anOption.Docs:
docs/guide/libraries.md: counts, the storage paragraph with an example, the getter note, the modules table.docs/guide/absence.md.docs/rules/no-undefined-check-for-null.md,no-null-check-for-undefined.md,must-use-result.md.🤖 Generated with Claude Code