Boundary narrowing helpers (isRecord, asRecord, field); evals references follow the new rules
TSUS410 accepts kind/type/_tag discriminants as well as tag, since the eval tasks (and plenty of real code) discriminate on kind. The eval reference solutions drop their casts and parameter mutation, json-api-handler keeps a tagged FieldError until the edge, and LANGUAGE.md lists the new codes so the primer matches the checker. node evals/validate.mjs: 30 tasks, 0 problems. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Changed files
16 files changed110 additions77 deletionsagainst 2cc04ee
- Changeddocs/rules.md+1−1
- Changedevals/LANGUAGE.md+19−4
- Changedevals/tasks/deep-get/reference.tsus+2−6
- Changedevals/tasks/feature-flag/reference.tsus+8−5
- Changedevals/tasks/inventory-ledger/reference.tsus+18−28
- Changedevals/tasks/json-api-handler/mutant.tsus+4−4
- Changedevals/tasks/json-api-handler/reference.tsus+12−8
- Changedevals/tasks/lru-cache/reference.tsus+9−7
- Changedevals/tasks/manager-chain/reference.tsus+1−1
- Changedevals/tasks/order-state-machine/reference.tsus+1−6
- Changedevals/tasks/parse-log-line/reference.tsus+7−4
- Changedevals/tasks/topo-sort/reference.tsus+3−1
- Changedpackages/cli/src/rules/registry.js+1−1
- Changedpackages/cli/src/rules/results.js+5−1
- Changedpackages/runtime/boundary.d.ts+9−0
- Changedpackages/runtime/boundary.js+10−0
Changeddocs/rules.md+1−1
| @@ -458,7 +458,7 @@ | ||
| id === "" ? Err("missing id") : Ok({ id }); | ||
| ``` | ||
| -Hint: Use literals (Result<T, "not found" | "timeout">) or tagged variants (Tagged<"NotFound", string> | { tag: "Timeout"; ms: number }). | ||
| +Hint: Use literals (Result<T, "not found" | "timeout">) or variants with a literal tag (or kind/type) field: Tagged<"NotFound", string> | { tag: "Timeout"; ms: number }. | ||
| Fix: No automatic fix: the right change depends on intent. | ||
Changedevals/LANGUAGE.md+19−4
| @@ -4,7 +4,7 @@ | ||
| ## What a .tsus file is | ||
| -A `.tsus` file is TypeScript with five things removed and one macro added. It compiles to plain ESM JavaScript. | ||
| +A `.tsus` file is TypeScript with its escape hatches removed and one macro added. It compiles to plain ESM JavaScript. | ||
| Removed, each with a stable diagnostic code: | ||
| @@ -15,14 +15,29 @@ | ||
| | TSUS003 | the identifier `undefined` | `Option<T>`; `fromNullable` at the boundary | | ||
| | TSUS004 | `var` | `const` (preferred) or `let` | | ||
| | TSUS005 | `throw` | return `Result<T, E>` (`Ok(v)` / `Err(e)`) | | ||
| +| TSUS401 | `any` | `unknown`, then narrow | | ||
| +| TSUS402 | `as` casts (except `as const`) | narrow with `typeof`/`Array.isArray`, or `isRecord`/`asRecord`/`field` from the boundary | | ||
| +| TSUS403 | non-null `x!` | `fromNullable(x)` and `match` or `unwrapOr` | | ||
| +| TSUS404 | `enum` | a union of string literals | | ||
| +| TSUS405 | `==` and `!=` | `===` and `!==` | | ||
| +| TSUS406 | default exports | named exports | | ||
| +| TSUS407 | reassigning a parameter | a new `const` | | ||
| +| TSUS408 | `let` that is never reassigned | `const` | | ||
| +| TSUS409 | mutating a parameter (`p.x = 1`, `p.push(x)`, `map.set` on a `Map` parameter, `Object.assign(p, ...)`) | return a new value: `{ ...p, x }`, `[...xs, x]`, `toSorted()`; mutate only values the function created | | ||
| +| TSUS410 | a `Result` error type that is not a string literal union or a tagged union (`Result<T, string>`, `Result<T, Error>`) | `"not_found" \| "timeout"`, or objects with a literal `kind` or `tag` field | | ||
| +| TSUS411 | a promise that is neither awaited nor returned (also `void p` and `xs.forEach(async ...)`) | `await` it or return it | | ||
| +| TSUS412 | calling a function that returns a `Result` and ignoring it | `match` on it or return it | | ||
| +| TSUS413 | `@ts-ignore`, `@ts-expect-error`, `@ts-nocheck` | fix the code | | ||
| +`tsus check --json` diagnostics carry a `hint` and often a `fix` with exact text edits; `tsus explain <CODE>` prints the full rule. | ||
| + | ||
| Also do not use optional properties (`x?: T`), optional parameters, or optional chaining (`a?.b`). They produce `undefined` at runtime, which defeats the point. Model absence as an `Option<T>` field instead. The one exception is describing the shape of external data (parsed JSON, a `.ts` dependency) right before you convert it with `fromNullable`. | ||
| ## The runtime | ||
| ```ts | ||
| import { Some, None, Ok, Err, tag, type Option, type Result, type Tagged } from "@tsus/runtime"; | ||
| -import { fromNullable, wrapSync, wrapAsync } from "@tsus/runtime/boundary"; | ||
| +import { fromNullable, wrapSync, wrapAsync, isRecord, asRecord, field } from "@tsus/runtime/boundary"; | ||
| ``` | ||
| `Option<T>` methods: `isSome()`, `isNone()`, `map(f)`, `andThen(f)` (f returns an Option), `unwrapOr(fallback)`, `okOr(error)` (to a Result). | ||
| @@ -84,7 +99,7 @@ | ||
| - Nullable values: `fromNullable(map.get(key))`, `fromNullable(arr.find(p))`, `fromNullable(arr[i])` for an index that may be out of range, `fromNullable(obj[key])` for data from JSON, `fromNullable(str.match(re))`. | ||
| - Throwing calls: `wrapSync(JSON.parse)(text)` returns `Result<any, Error>`; likewise `wrapSync(decodeURIComponent)(s)`. `wrapAsync(fn)` does the same for async functions and returns `Promise<Result<...>>`. | ||
| -- Values typed `unknown` (parsed JSON, request bodies): check with `typeof`, `Array.isArray`, `Number.isInteger`, and `fromNullable` for missing keys. `typeof v === "undefined"` is a string comparison and is allowed, but `fromNullable(v).isNone()` reads better. | ||
| +- Values typed `unknown` (parsed JSON, request bodies): check with `typeof`, `Array.isArray`, `Number.isInteger`, and `fromNullable` for missing keys. Since `as` casts are banned, use the boundary's narrowing helpers: `isRecord(v)` (a type guard for a plain object, not null, not an array), `asRecord(v)` (an `Option<Record<string, unknown>>`) and `field(v, key)` (an own property as an `Option<unknown>`). `typeof v === "undefined"` is a string comparison and is allowed, but `fromNullable(v).isNone()` reads better. | ||
| Inside the boundary, everything you write returns `Option` or `Result`, never `undefined` and never an exception. | ||
| @@ -115,4 +130,4 @@ | ||
| ## Checker status | ||
| -`tsus check` enforces the bans and the macro syntax, then type-checks the whole file with TypeScript in strict mode. Type errors are reported at their `.tsus` line and column as `TSUS200`, with the TypeScript code in `tsCode`, so fix them the way you would fix a `tsc` error. | ||
| +`tsus check` enforces the bans above and the macro syntax, then type-checks the whole file with TypeScript in strict mode. Type errors are reported at their `.tsus` line and column as `TSUS200`, with the TypeScript code in `tsCode`, so fix them the way you would fix a `tsc` error. | ||
Changedevals/tasks/deep-get/reference.tsus+2−6
| @@ -1,5 +1,5 @@ | ||
| import { Some, None, Ok, Err, type Option, type Result } from "@tsus/runtime"; | ||
| -import { fromNullable } from "@tsus/runtime/boundary"; | ||
| +import { fromNullable, field } from "@tsus/runtime/boundary"; | ||
| export type PathError = { kind: "invalid_path"; path: string }; | ||
| @@ -52,16 +52,12 @@ | ||
| return Some(steps); | ||
| }; | ||
| -const isPlainObject = (v: unknown): boolean => typeof v === "object" && fromNullable(v).isSome() && !Array.isArray(v); | ||
| - | ||
| const applyStep = (cur: unknown, step: Step): Option<unknown> => | ||
| step.isIndex | ||
| ? Array.isArray(cur) && step.index < cur.length | ||
| ? fromNullable(cur[step.index]) | ||
| : None | ||
| - : isPlainObject(cur) && Object.hasOwn(cur as object, step.key) | ||
| - ? fromNullable((cur as Record<string, unknown>)[step.key]) | ||
| - : None; | ||
| + : field(cur, step.key); | ||
| const walk = (obj: unknown, steps: Step[]): Option<unknown> => | ||
| steps.reduce((acc: Option<unknown>, step: Step) => acc.andThen((cur) => applyStep(cur, step)), fromNullable(obj)); | ||
Changedevals/tasks/feature-flag/reference.tsus+8−5
| @@ -17,8 +17,11 @@ | ||
| const finite = (v: unknown): boolean => typeof v === "number" && Number.isFinite(v); | ||
| +// Rules come from outside data, so op may hold any string at runtime. | ||
| +const opName = (rule: Rule): string => rule.op; | ||
| + | ||
| const validRule = (rule: Rule): boolean => | ||
| - match (rule.op as string) { | ||
| + match (opName(rule)) { | ||
| "eq" => true, | ||
| "in" => Array.isArray(rule.value), | ||
| "gte" => finite(rule.value), | ||
| @@ -26,10 +29,10 @@ | ||
| }; | ||
| const opMatches = (rule: Rule, v: unknown): boolean => | ||
| - match (rule.op as string) { | ||
| + match (opName(rule)) { | ||
| "eq" => v === rule.value, | ||
| - "in" => (rule.value as unknown[]).some((x) => x === v), | ||
| - "gte" => typeof v === "number" && v >= (rule.value as number), | ||
| + "in" => Array.isArray(rule.value) && rule.value.some((x) => x === v), | ||
| + "gte" => typeof v === "number" && typeof rule.value === "number" && v >= rule.value, | ||
| _ => false, | ||
| }; | ||
| @@ -38,7 +41,7 @@ | ||
| const validate = (flag: Flag): Result<true, FlagError> => { | ||
| const pct: unknown = flag.rolloutPercent; | ||
| - if (!finite(pct) || (pct as number) < 0 || (pct as number) > 100) { | ||
| + if (typeof pct !== "number" || !Number.isFinite(pct) || pct < 0 || pct > 100) { | ||
| return Err({ kind: "invalid_rollout" }); | ||
| } | ||
| const bad = flag.rules.findIndex((rule) => !validRule(rule)); | ||
Changedevals/tasks/inventory-ledger/reference.tsus+18−28
| @@ -1,5 +1,5 @@ | ||
| import { Some, None, Ok, Err, type Option, type Result } from "@tsus/runtime"; | ||
| -import { fromNullable } from "@tsus/runtime/boundary"; | ||
| +import { fromNullable, asRecord } from "@tsus/runtime/boundary"; | ||
| export type Stock = Record<string, number>; | ||
| @@ -16,11 +16,7 @@ | ||
| kind === "receive" || kind === "ship" ? qty > 0 : kind === "adjust" ? qty !== 0 : false; | ||
| const toMovement = (raw: unknown): Option<Movement> => | ||
| - fromNullable(raw).andThen((e) => { | ||
| - if (typeof e !== "object") { | ||
| - return None; | ||
| - } | ||
| - const r = e as Record<string, unknown>; | ||
| + asRecord(raw).andThen((r) => { | ||
| const sku = r.sku; | ||
| const qty = r.qty; | ||
| if (typeof sku !== "string" || sku === "" || typeof qty !== "number" || !Number.isInteger(qty) || !qtyOk(r.kind, qty)) { | ||
| @@ -29,36 +25,30 @@ | ||
| return Some({ sku, delta: r.kind === "ship" ? -qty : qty }); | ||
| }); | ||
| -const applyOne = (stock: Map<string, number>, raw: unknown, index: number): Option<LedgerError> => | ||
| +// The new on-hand count for one entry, or why the entry cannot apply. | ||
| +const applyOne = (stock: ReadonlyMap<string, number>, raw: unknown, index: number): Result<[string, number], LedgerError> => | ||
| match (toMovement(raw)) { | ||
| - None => Some({ kind: "invalid_entry", index }), | ||
| + None => Err({ kind: "invalid_entry", index }), | ||
| Some(m) => move(stock, m, index), | ||
| }; | ||
| -const move = (stock: Map<string, number>, m: Movement, index: number): Option<LedgerError> => { | ||
| +const move = (stock: ReadonlyMap<string, number>, m: Movement, index: number): Result<[string, number], LedgerError> => { | ||
| const onHand = fromNullable(stock.get(m.sku)).unwrapOr(0); | ||
| - if (onHand + m.delta < 0) { | ||
| - return Some({ kind: "insufficient_stock", sku: m.sku, index, onHand }); | ||
| - } | ||
| - stock.set(m.sku, onHand + m.delta); | ||
| - return None; | ||
| + return onHand + m.delta < 0 | ||
| + ? Err({ kind: "insufficient_stock", sku: m.sku, index, onHand }) | ||
| + : Ok([m.sku, onHand + m.delta]); | ||
| }; | ||
| -const firstProblem = (stock: Map<string, number>, entries: readonly LedgerEntry[]): Option<LedgerError> => { | ||
| - for (let i = 0; i < entries.length; i += 1) { | ||
| - const problem = applyOne(stock, entries[i], i); | ||
| - if (problem.isSome()) { | ||
| - return problem; | ||
| - } | ||
| - } | ||
| - return None; | ||
| -}; | ||
| - | ||
| export const applyLedger = (opening: Readonly<Stock>, entries: readonly LedgerEntry[]): Result<Stock, LedgerError> => { | ||
| // Work on a private copy so a failure leaves nothing behind. | ||
| const stock = new Map<string, number>(Object.entries(opening)); | ||
| - return match (firstProblem(stock, entries)) { | ||
| - Some(e) => Err(e), | ||
| - None => Ok(Object.fromEntries(stock)), | ||
| - }; | ||
| + for (let i = 0; i < entries.length; i += 1) { | ||
| + const outcome = applyOne(stock, entries[i], i); | ||
| + if (outcome.isErr()) { | ||
| + return outcome.map(() => Object.fromEntries(stock)); | ||
| + } | ||
| + const [sku, onHand] = outcome.unwrapOr(["", 0]); | ||
| + stock.set(sku, onHand); | ||
| + } | ||
| + return Ok(Object.fromEntries(stock)); | ||
| }; | ||
Changedevals/tasks/json-api-handler/mutant.tsus+4−4
| @@ -14,10 +14,10 @@ | ||
| None => false, | ||
| }; | ||
| -const ageOf = (v: Option<unknown>): Result<Option<number>, Response> => | ||
| +const ageOf = (v: Option<unknown>): Result<Option<number>, "invalid_age"> => | ||
| match (v) { | ||
| None => Ok(None), | ||
| - Some(a) => typeof a === "number" && Number.isInteger(a) && a >= 0 && a <= 150 ? Ok(Some(a)) : Err(invalidField("age")), | ||
| + Some(a) => typeof a === "number" && Number.isInteger(a) && a >= 0 && a <= 150 ? Ok(Some(a)) : Err("invalid_age"), | ||
| }; | ||
| const build = (obj: Record<string, unknown>, nextId: () => string): Response => { | ||
| @@ -30,7 +30,7 @@ | ||
| return invalidField("email"); | ||
| } | ||
| return match (ageOf(fromNullable(obj.age))) { | ||
| - Err(r) => r, | ||
| + Err(_e) => invalidField("age"), | ||
| Ok(age) => ({ | ||
| status: 201, | ||
| body: match (age) { | ||
| @@ -45,7 +45,7 @@ | ||
| match (wrapSync(JSON.parse)(raw)) { | ||
| Err(_e) => ({ status: 400, body: { error: "invalid_json" } }), | ||
| Ok(data) => match (fromNullable(data)) { | ||
| - Some(d) => typeof d === "object" ? build(d as Record<string, unknown>, nextId) : invalidField("body"), | ||
| + Some(d) => typeof d === "object" ? build(Object.fromEntries(Object.entries(d)), nextId) : invalidField("body"), | ||
| None => invalidField("body"), | ||
| }, | ||
| }; | ||
Changedevals/tasks/json-api-handler/reference.tsus+12−8
| @@ -1,5 +1,5 @@ | ||
| import { Some, None, Ok, Err, type Option, type Result } from "@tsus/runtime"; | ||
| -import { fromNullable, wrapSync } from "@tsus/runtime/boundary"; | ||
| +import { fromNullable, wrapSync, asRecord } from "@tsus/runtime/boundary"; | ||
| export type Request = { method: string; headers: Record<string, string>; body: string }; | ||
| export type Response = { status: number; body: Record<string, unknown> }; | ||
| @@ -8,8 +8,13 @@ | ||
| type User = { name: string; email: string; age: Option<number> }; | ||
| -const invalidField = (field: string): Response => ({ status: 422, body: { error: "invalid_field", field } }); | ||
| +// Validation failures stay a tagged error until the edge turns them into a Response. | ||
| +type FieldError = { kind: "invalid_field"; field: string }; | ||
| +const invalidField = (field: string): FieldError => ({ kind: "invalid_field", field }); | ||
| + | ||
| +const toResponse = (e: FieldError): Response => ({ status: 422, body: { error: "invalid_field", field: e.field } }); | ||
| + | ||
| const contentType = (headers: Record<string, string>): Option<string> => | ||
| fromNullable(Object.entries(headers).find(([k]) => k.toLowerCase() === "content-type")).map(([, v]) => v); | ||
| @@ -19,16 +24,15 @@ | ||
| None => false, | ||
| }; | ||
| -const asObject = (data: unknown): Option<Record<string, unknown>> => | ||
| - fromNullable(data).andThen((d) => (typeof d === "object" && !Array.isArray(d) ? Some(d as Record<string, unknown>) : None)); | ||
| +const asObject = (data: unknown): Option<Record<string, unknown>> => asRecord(data); | ||
| -const parseAge = (v: Option<unknown>): Result<Option<number>, Response> => | ||
| +const parseAge = (v: Option<unknown>): Result<Option<number>, FieldError> => | ||
| match (v) { | ||
| None => Ok(None), | ||
| Some(a) => typeof a === "number" && Number.isInteger(a) && a >= 0 && a <= 150 ? Ok(Some(a)) : Err(invalidField("age")), | ||
| }; | ||
| -const parseUser = (obj: Record<string, unknown>): Result<User, Response> => { | ||
| +const parseUser = (obj: Record<string, unknown>): Result<User, FieldError> => { | ||
| const name = obj.name; | ||
| if (typeof name !== "string" || name.trim() === "") { | ||
| return Err(invalidField("name")); | ||
| @@ -55,10 +59,10 @@ | ||
| match (wrapSync(JSON.parse)(raw)) { | ||
| Err(_e) => ({ status: 400, body: { error: "invalid_json" } }), | ||
| Ok(data) => match (asObject(data)) { | ||
| - None => invalidField("body"), | ||
| + None => toResponse(invalidField("body")), | ||
| Some(obj) => match (parseUser(obj)) { | ||
| Ok(user) => created(user, nextId), | ||
| - Err(res) => res, | ||
| + Err(e) => toResponse(e), | ||
| }, | ||
| }, | ||
| }; | ||
Changedevals/tasks/lru-cache/reference.tsus+9−7
| @@ -1,4 +1,5 @@ | ||
| -import { Some, None, Ok, Err, type Option, type Result } from "@tsus/runtime"; | ||
| +import { Some, Ok, Err, type Option, type Result } from "@tsus/runtime"; | ||
| +import { fromNullable } from "@tsus/runtime/boundary"; | ||
| export type LruError = { kind: "invalid_capacity" }; | ||
| @@ -12,11 +13,12 @@ | ||
| const build = <V>(capacity: number): Lru<V> => { | ||
| // Map iteration order is insertion order: oldest first, newest last. | ||
| - const map = new Map<string, V>(); | ||
| - const touch = (key: string, value: V): Option<V> => { | ||
| + // Values are boxed so a stored falsy value still counts as present. | ||
| + const map = new Map<string, { value: V }>(); | ||
| + const touch = (key: string, box: { value: V }): Option<V> => { | ||
| map.delete(key); | ||
| - map.set(key, value); | ||
| - return Some(value); | ||
| + map.set(key, box); | ||
| + return Some(box.value); | ||
| }; | ||
| const evictOldest = (): void => { | ||
| const oldest = map.keys().next(); | ||
| @@ -25,7 +27,7 @@ | ||
| } | ||
| }; | ||
| return { | ||
| - get: (key) => (map.has(key) ? touch(key, map.get(key) as V) : None), | ||
| + get: (key) => fromNullable(map.get(key)).andThen((box) => touch(key, box)), | ||
| set: (key, value) => { | ||
| if (capacity === 0) { | ||
| return; | ||
| @@ -35,7 +37,7 @@ | ||
| } else if (map.size >= capacity) { | ||
| evictOldest(); | ||
| } | ||
| - map.set(key, value); | ||
| + map.set(key, { value }); | ||
| }, | ||
| delete: (key) => map.delete(key), | ||
| size: () => map.size, | ||
Changedevals/tasks/manager-chain/reference.tsus+1−1
| @@ -24,7 +24,7 @@ | ||
| ? Err({ kind: "cycle", id: m.id }) | ||
| : usableEmail(m).isSome() | ||
| ? Ok(usableEmail(m)) | ||
| - : walk(byId, m.managerId, reached.add(m.id)), | ||
| + : walk(byId, m.managerId, new Set([...reached, m.id])), | ||
| }; | ||
| export const escalationEmail = (users: readonly User[], userId: string): Result<Option<string>, ChainError> => { | ||
Changedevals/tasks/order-state-machine/reference.tsus+1−6
| @@ -1,5 +1,5 @@ | ||
| import { Some, None, Ok, Err, tag, type Option, type Result, type Tagged } from "@tsus/runtime"; | ||
| -import { fromNullable } from "@tsus/runtime/boundary"; | ||
| +import { fromNullable, field } from "@tsus/runtime/boundary"; | ||
| export type OrderState = | ||
| | Tagged<"Pending", {}> | ||
| @@ -17,11 +17,6 @@ | ||
| | { kind: "invalid_payload"; event: string }; | ||
| const EVENTS: readonly string[] = ["Pay", "Ship", "Deliver", "Cancel", "Refund"]; | ||
| - | ||
| -const field = (payload: unknown, key: string): Option<unknown> => | ||
| - fromNullable(payload).andThen((p) => | ||
| - typeof p === "object" && Object.hasOwn(p as object, key) ? fromNullable((p as Record<string, unknown>)[key]) : None, | ||
| - ); | ||
| const badPayload = (ev: string): Result<OrderState, OrderError> => Err({ kind: "invalid_payload", event: ev }); | ||
Changedevals/tasks/parse-log-line/reference.tsus+7−4
| @@ -13,7 +13,7 @@ | ||
| export type LogParseError = { kind: "empty_line" } | { kind: "bad_timestamp" } | { kind: "bad_level"; level: string }; | ||
| -const LEVELS: readonly string[] = ["DEBUG", "INFO", "WARN", "ERROR"]; | ||
| +const LEVELS: readonly Level[] = ["DEBUG", "INFO", "WARN", "ERROR"]; | ||
| const FIELD = /^([a-z_][a-z0-9_]*)=(.+)$/; | ||
| const daysIn = (y: number, mo: number): number => { | ||
| @@ -45,6 +45,8 @@ | ||
| return { timestamp: tokens[0], level, module, message: tokens.slice(start, end).join(" "), fields: Object.fromEntries(entries) }; | ||
| }; | ||
| +const toLevel = (text: string): Option<Level> => fromNullable(LEVELS.find((l) => l === text)); | ||
| + | ||
| export const parseLogLine = (line: string): Result<LogLine, LogParseError> => { | ||
| const tokens = line.split(" ").filter((t) => t !== ""); | ||
| const level = fromNullable(tokens[1]).unwrapOr(""); | ||
| @@ -52,7 +54,8 @@ | ||
| ? Err({ kind: "empty_line" }) | ||
| : !validTimestamp(tokens[0]) | ||
| ? Err({ kind: "bad_timestamp" }) | ||
| - : !LEVELS.includes(level) | ||
| - ? Err({ kind: "bad_level", level }) | ||
| - : Ok(build(tokens, level as Level)); | ||
| + : match (toLevel(level)) { | ||
| + Some(known) => Ok(build(tokens, known)), | ||
| + None => Err({ kind: "bad_level", level }), | ||
| + }; | ||
| }; | ||
Changedevals/tasks/topo-sort/reference.tsus+3−1
| @@ -25,7 +25,9 @@ | ||
| const unique = [...new Set(deps[name])]; | ||
| remaining.set(name, unique.length); | ||
| for (const d of unique) { | ||
| - fromNullable(dependents.get(d)).map((list) => list.push(name)); | ||
| + if (dependents.has(d)) { | ||
| + dependents.set(d, [...fromNullable(dependents.get(d)).unwrapOr([]), name]); | ||
| + } | ||
| } | ||
| } | ||
| const ready = names.filter((n) => remaining.get(n) === 0); | ||
Changedpackages/cli/src/rules/registry.js+1−1
| @@ -271,7 +271,7 @@ | ||
| name: "tagged-errors", | ||
| title: "Result error types must be tagged", | ||
| message: "Result error type must be a string literal union or a tagged union", | ||
| - hint: "Use literals (Result<T, \"not found\" | \"timeout\">) or tagged variants (Tagged<\"NotFound\", string> | { tag: \"Timeout\"; ms: number }).", | ||
| + hint: "Use literals (Result<T, \"not found\" | \"timeout\">) or variants with a literal tag (or kind/type) field: Tagged<\"NotFound\", string> | { tag: \"Timeout\"; ms: number }.", | ||
| why: "Result<T, string> or Result<T, Error> says that something failed but not what, so callers cannot match on the cases. A tagged error type is a closed set the caller can handle exhaustively.", | ||
| bad: `const load = (id: string): Result<User, string> => | ||
| id === "" ? Err("missing id") : Ok({ id });`, | ||
Changedpackages/cli/src/rules/results.js+5−1
| @@ -7,13 +7,17 @@ | ||
| // --- TSUS410 --------------------------------------------------------------- | ||
| +// Property names accepted as a union's discriminant. match's Variant(x) | ||
| +// patterns read `tag`; the others are common spellings of the same idea. | ||
| +const DISCRIMINANTS = new Set(["tag", "kind", "type", "_tag"]); | ||
| + | ||
| const hasLiteralTag = (members) => | ||
| members.some( | ||
| (m) => | ||
| ts.isPropertySignature(m) && | ||
| m.name && | ||
| (ts.isIdentifier(m.name) || ts.isStringLiteral(m.name)) && | ||
| - m.name.text === "tag" && | ||
| + DISCRIMINANTS.has(m.name.text) && | ||
| m.type && | ||
| isStringLiteralUnion(m.type), | ||
| ); | ||
Changedpackages/runtime/boundary.d.ts+9−0
| @@ -9,3 +9,12 @@ | ||
| export declare const wrapAsync: <A extends unknown[], R>( | ||
| fn: (...args: A) => R | Promise<R>, | ||
| ) => (...args: A) => Promise<Result<Awaited<R>, Error>>; | ||
| + | ||
| +/** A plain object (not null, not an array). Narrows unknown without a cast. */ | ||
| +export declare const isRecord: (value: unknown) => value is Record<string, unknown>; | ||
| + | ||
| +/** Some(value) when value is a plain object, otherwise None. */ | ||
| +export declare const asRecord: (value: unknown) => Option<Record<string, unknown>>; | ||
| + | ||
| +/** The own property `key` of a plain object, as an Option (None when absent, null or undefined). */ | ||
| +export declare const field: (value: unknown, key: string) => Option<unknown>; | ||
Changedpackages/runtime/boundary.js+10−0
| @@ -20,3 +20,13 @@ | ||
| return Err(error); | ||
| } | ||
| }; | ||
| + | ||
| +// Narrowing helpers for values typed unknown (parsed JSON, request bodies). | ||
| +// They exist so .tsus code can inspect outside data without `as` casts | ||
| +// (TSUS402) or null checks (TSUS002). | ||
| +export const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value); | ||
| + | ||
| +export const asRecord = (value) => (isRecord(value) ? Some(value) : None); | ||
| + | ||
| +export const field = (value, key) => | ||
| + isRecord(value) && Object.hasOwn(value, key) ? fromNullable(value[key]) : None; | ||
Checks
No checks reported for this commit.
Runs
No runs for this commit.