Transform: dev checks for what the rules can't see #10
Loading…
Reference in a new issue
No description provided.
Delete branch "dev-checks"
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?
Dev-only runtime checks, like Rust's debug assertions. In development the transform wraps a few values in a check. Production builds never contain them, and their output is the same bytes as before this change.
What is checked, and why these
I went through the "What the rule can't see" sections and README "Known gaps", looking for places where a value breaks its type at runtime and the program then carries on quietly. I kept a check only if it is cheap and has a clear message:
q(...)given a Promise. A missingawaittype-checks:Result<T, E>letsTbe a Promise. No rule reports it either. I checked:q(saveUser(u));with anasyncsaveUsergives no problems fromsafe-ts checkand none fromtsc. Without the check, the Promise is treated as the value and theErrinside it is never returned. This was the strongest candidate.q(...)given anErrit doesn't recognize.qtestsinstanceofagainst theErrthe file imports. If std is loaded twice (two versions, or one module reached through two paths), the other copy'sErrpasses through as a success value. The check reports any object whose class is namedErr, that has anerrorfield and failsinstanceof.matchwithout_, given a variant it has no handler for, or a value with notag. This catches data that skipped validation: a cast ofJSON.parseoutput, a type guard that lies, a server that added a variant. The message lists the tags the match handles. It covers everymatchwhose handlers are an object literal, including the ones the switch rewrite leaves as calls..sort(f)/.toSorted(f)comparators returningNaNor a non-number.sort-comparatorsays it can't see these. Witha.price - b.priceand a missingprice, the sort finishes in an order that depends on the engine. The message shows the two values compared.Candidates I left out (explained in the guide too):
Mutparameters. It freezes the caller's object permanently, so the caller's own later, correct changes would throw in dev and work in prod. A Proxy changes identity (===, Map keys,#private).How it works
crates/safe_ts_core/src/devchecks.rs. It runs first, on the text as written, so the locations it reports are the developer's own line and column. It wraps each argument where it stands, so lines don't move:q(__safeTsDevQ(x, "src/a.ts:3:16")),match(__safeTsDevMatch(s, "…", ["Circle", "Rect"]), …),.sort(__safeTsDevSort(f, "…")). Then the existing rewrites run as before. The helper functions are plain JS added after the file's last line (the same way JSON validators are), and only the ones the file uses. std files (@safe-ts std) are skipped. Vue script blocks get their own helper names and component-relative locations.safe-ts dev check failed at <file>:<line>:<col>: …\n See https://safe-ts.evobug-pages.com/<page>. The error's name isSafeTsDevCheck. Pages:rules/floating-rejection(Promise),rules/no-unchecked-cast(match),rules/sort-comparator. The foreignErrcase has no rule, so it links toguide/dev-checks#q.Project::transform_with(path, text, TransformOptions { dev_checks })(transformis unchanged and leaves the checks out). The napitransform(filename, source, { devChecks })and the JStransform(file, code, { devChecks })default to off.safeTs({ devChecks }), when set, decides. Otherwise it follows Vite'scommand:serve(dev server, Vitest) means on,buildmeans off. Rollup/Rolldown without Vite means off. The Node loader is on unlessNODE_ENV=production, andSAFE_TS_DEV_CHECKS=1|0overrides that.safe-ts emit/explain, the wasm playground and the docs' compiled tabs stay off.typeoftests perq; one call plus an array of the handled tags permatch; one extra call and atypeofper comparison; a few hundred bytes of helpers per file.Tests
crates/safe_ts_core/tests/transform.rs: exact output with dev checks for q, match (also_→ not wrapped, and a non-rewritten call), sort (and.sort()/ two-argument.sortleft alone), nested wraps on one line, Vue locations, std files skipped. Each test also checks that the defaulttransformcontains no__safeTsDev.scripts/vite-check.mjs(npm run test:vite) uses the demo's real build output.dist/run.jsmust contain none of__safeTsDev,safe-ts dev checkorSafeTsDevCheck. The dev server, with the same config, must serve the wrappedmatch/qwith the right location, andssrLoadModuleofshapes.tsmust throw the located check for an unknown variant.packages/std/test/dev-checks.test.ts(runtime, through the Node loader) shows each check firing, with exact file:line:col and page URL: q with a Promise; q with anErrfrom a second instance ofresult.ts; match with an unknown variant or no tag; NaN and boolean comparators. Correct values pass through unchanged.packages/safe-ts-transform/test/dev-checks.test.ts: JStransform()default off; the loader's env logic; the plugin's defaults for serve/build/no Vite and the overrides. It also runs the same code both ways: the prod output sorts NaN silently, the dev output throws.Results:
cargo nextest run --workspace: 100 passed, 1 failed. The failure isfixtures_match_annotations: thefeaturesfixture reportsmain.ts:55 unhandled-failure(createDecipheriv). It fails the same way on a clean checkout ofmain(I checked in a separate worktree), so it is not from this change.npm run test:std: 129 tests, 128 passed, 1 failed. The failure ispackages/feature-node/test/manifest.test.ts"every Node callable is mapped exactly once". It also fails withSAFE_TS_DEV_CHECKS=0, so it is not from the dev checks; it looks like the same Node feature-pack drift as the fixture failure. The 13 new dev-check tests pass.npm run test:vite: passed.npm run test:docs: passed (214 examples compile, wasm build, VitePress build without dead links).npm run typecheck: passed.Docs
docs/guide/dev-checks.md, in the sidebar (Going further) and indocs/README.md. It covers when the checks are on, exactly what is checked, what the transform adds, the cost, and what isn't checked and why.q(...)section),guide/adoption.mdandguide/transforms.md.Left out / uncertain
q(...)calls the transform rewrites get theErrcheck.isErr(...)and hand-writteninstanceof Errdon't, and neither does<Match>in Vue templates.Errtest goes by the class nameErr. A minifier that renames classes in dev would hide it (dev builds usually aren't minified).Resultwhose success value really is a Promise would be flagged too. I expect that to be rare enough to accept, and the docs say what is checked.🤖 Generated with Claude Code
Like Rust's debug assertions: in development the transform wraps a few values in a runtime check, and production builds never emit them. The checks cover gaps the static rules document, where a value breaks its type and the program carries on quietly: - q(...) given a Promise (a missing await type-checks, since a Result may hold any value) or an Err from a second copy of std, which instanceof misses; - match without `_` given a variant it has no handler for, or no tag at all (data that bypassed its type); - sort/toSorted comparators returning NaN or a non-number. Each failure names file:line:column and the docs page. On for the Vite dev server and the Node loader (unless NODE_ENV=production), off for vite build; safeTs({ devChecks }) and SAFE_TS_DEV_CHECKS override. The checks are inserted on the text as written, so locations are what the developer wrote, and every wrap stays on its line. Co-Authored-By: Claude Opus 5.5 <[email protected]>