Validators: constants without as const, Int ranges, error kinds, compact tables #64
Loading…
Reference in a new issue
No description provided.
Delete branch "evobug/fb3-std-validators"
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?
Round 3 of the 0.2.0 adoption feedback, std area, part 1 of 2: validators and the types they read (feedback items 1–5 of this area; "Std library" and "Performance", top-ten #6 and #10). The std helpers (items 6–14) are in a second PR, also from
main.Per feedback item
1. Validated types without a written
as const: done for the feedback's shapes; partly for RTSS's fullPackettype.typeof XofObject.freeze(Y)isY's type, forYanas constvalue or another suchconst. So(typeof STATUSES)[number]withSTATUSES = Object.freeze(STATUS_NAMES)works.Object.freeze({ a: 1 })keeps its primitives' literal types, as TypeScript'sfreezeoverload does.constholding a call of a function with a declared return type is evaluated for the arguments: aconsttype parameter gets the argument's literal types, one constrained to primitives gets a literal (0x10), defaults count, and a single overload signature over an untyped implementation is used (that's the cast-free way to write such a function). An object literal of spreads of such calls works too (Object.freeze({ ...slotsOf(A, 0x01, 15), ... })).extends(`${number}`,`${infer N extends number}`,`${infer H}${infer T}`);keyofa tuple (item by item over a type parameter; withas, over its index keys, checking thatlengthand the methods are dropped);[...T, 0]) and readsT["length"]and[...infer R];Tuple<N>arithmetic overflowed the stack in a debug build at about 80 levels.0x10is16), and only the generated type aliases the validators use are written.packages/protocol, copied to /tmp):Op,OpCodeandCommandOp, built by the realslotsOfwith itsAdd<From, N>tuple arithmetic, now evaluate, and so doescodesOf'sConstNametable (GroupOrderCode).tscaccepts the emitted validators against the real types. Before this PR all of them were refused with "Opisn't declaredas const".fromFields<Packet>for the protocol's wholePacketstill can't replacetrusted.ts. That type hasUint8Arrayfields (not JSON), a table with number keys ([Op.Hello]: {...}), and mapped types over a union of tuples ([E in F[number] as E[0]]). Each of those is a separate type-model feature, not theas constproblem the feedback described.2. Compact validator mode: done.
compact: truein the options (and by default, for object types with 64+ fields) generates a table per object type: each field's key, then a code for string/number/boolean/SafeInt/finite number or the field type's validator, plus flags for optional fields, odd keys and own-property keys.std's
jsonTableinterprets it. Paths, messages, kinds, key order,unknownKeys,allErrorsandfiniteall behave the same.compact: falsewrites everything out.Measured with
node scripts/compact-validators-size.mjs: 570 fields in 51 interfaces, a plain and a strict collecting validator, minified Vite build, Node 26. The script asserts that all bundles print identical results and errors.compact: false(today)compact: trueTrade-off: a table is about 4× smaller and up to 9× slower, because every field is a megamorphic keyed load. That's why the automatic threshold is high (RTSS's
Ruleshas 111 direct fields; its other 58 interfaces average about 8), and whycompact: trueis the switch for a whole tree.json-compact.test.tsruns about 200 inputs (missing,null, wrong kinds,NaN, 2^60, extra keys, a class instance with a getter, odd keys) through both modes under five option combinations and compares results and key order.3. Validators' messages: done (kinds); not done (
@errorJSDoc). EveryJsonProblemandJsonErrorhas:kind:missing,wrongType,unknownKey,duplicateKey,fieldCountorinvalidJson;expected(formissingandwrongType): what the type asks for there.Callers word their own messages from
kind,expectedand the path (the docs example is in Czech). I didn't add a per-field@errorJSDoc message: with the path and kind it is a lookup on the caller's side, and it would add messages to the type model and to every shared validator key. Breaking for tests thatdeepEquala whole error (noted under Changed).4.
objectin a conditional type's test: done.T extends objectmeans "is an object type": an object, a dictionary, an array or a tuple. The feedback'sDeepPartialworks as written.objectanywhere else is reported with a hint.5. Integer ranges: done.
Int<Min, Max>from std's json module:validate,parseJsonandfromFieldscheck it (expected integer from 1 to 12, got 13);arbitrarygenerates values only in the range, the ends often, shrinking towards the value closest to 0 (genIntIn);Docs changed
docs/guide/json.md: messages of your own, integer ranges, values from constants withoutas const, conditional types (object, template patterns, tuples), big types / compact validators with the numbers, the type tables.docs/rules/json-type.md,docs/guide/testing.md(Introw),README.md(json section and std table),CHANGELOG.md(Added, Changed).Verification
npm run build: ok.cargo nextest run --workspace: 214 passed.cargo clippy -q --workspace --all-targets: nothing new in the changed code.npm run test:std: 290 passed. New tests: compact equivalence,Intgeneration and shrinking, the frozen code table throughfromFields/arbitrary, kinds.npm run typecheckandnpm run typecheck:emit: ok.typecheck:emitnow includesjson-compact.test.ts, so tsc checks the generated tables.node scripts/docs-typecheck.mjs,npm run test:docs,npm run test:vite,npm run bench:check,node scripts/verify-packages.mjs: all ok.🤖 Generated with Claude Code
as const, Int ranges, error kinds, compact tables- Validated types read constants built without `as const`: Object.freeze of an `as const` value (and `(typeof FROZEN)[number]`), frozen object literals, and calls of functions with a declared return type (evaluated for the arguments; a single overload signature counts), also as spreads. For code tables built from name lists, the evaluator matches template literal patterns (`${number}`, `${infer N extends number}`), maps over `keyof` a tuple, spreads tuples, reads `T["length"]` and `[...infer R]`, takes type-parameter defaults, and evaluates tail-recursive conditional types in a loop (up to 1000, as TypeScript). - `T extends object` in a conditional type's test. - `Int<Min, Max>`: validated and generated in range. - `kind` and `expected` on every JSON problem, for messages of your own. - Compact validators: a table of fields checked by std's `jsonTable`, with the same results and errors; `compact: true/false`, default for object types with 64+ fields. Co-Authored-By: Claude Opus 5.5 <[email protected]>