// Errors as values. A fallible function returns Result; it does not throw. `throw` is reserved for // programmer bugs (assertNever). Plain frozen-shape objects: no classes, no runtime dependency, nothing to tree-shake. export type Ok = { readonly ok: true; readonly value: T }; export type Err = { readonly ok: false; readonly error: E }; export type Result = Ok | Err; export const ok = (value: T): Ok => ({ ok: true, value }); export const err = (error: E): Err => ({ ok: false, error }); // The compile-time exhaustiveness check. A switch over a union lists every member and has no `default`; // the next statement is `assertNever(x)`. A new member leaves `x` short of `never`, so the call does not type-check. export function assertNever(x: never): never { throw new Error(`unreachable: ${String(x)}`); } // Sequencing without exceptions. `andThen` short-circuits on the first Err; the error types union. export const map = (r: Result, f: (t: T) => U): Result => (r.ok ? ok(f(r.value)) : r); export const mapErr = (r: Result, f: (e: E) => F): Result => (r.ok ? r : err(f(r.error))); export const andThen = (r: Result, f: (t: T) => Result): Result => (r.ok ? f(r.value) : r); // Exhaustive match over a tagged union: one handler per tag, checked by the compiler (a missing or extra tag // does not type-check), each handler receiving the narrowed member. export type Handlers = { readonly [K in U['code']]: (u: Extract) => R }; export const match = (u: U, h: Handlers): R => // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- h[u.code] is the handler for u's own member (Handlers) (h[u.code as U['code']] as (u: U) => R)(u); // The same check for a union discriminated by `kind` (a typed miss, or one operation's error union). export type KindHandlers = { readonly [K in U['kind']]: (u: Extract) => R }; export const matchKind = (u: U, h: KindHandlers): R => // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- h[u.kind] is the handler for u's own member (KindHandlers) (h[u.kind as U['kind']] as (u: U) => R)(u); // What a span records as `error.kind`. A typed miss is the discriminant callers switch on (#131); an operation // that distinguishes variants of one code sets `kind`; `reason` is the closed sub-reason (#76); otherwise the code. const FALLBACK_KIND = 'Error'; const isRecord = (v: unknown): v is Record => typeof v === 'object' && v !== null; const stringField = (v: Record, key: string): string | null => { if (!Object.hasOwn(v, key)) return null; const value = v[key]; return typeof value === 'string' ? value : null; }; export function errorKind(e: unknown): string { if (!isRecord(e)) return FALLBACK_KIND; const miss = e['miss']; if (isRecord(miss)) { const missKind = stringField(miss, 'kind'); if (missKind !== null) return missKind; } const kind = stringField(e, 'kind'); if (kind !== null) return kind; const reason = stringField(e, 'reason'); if (reason !== null) return reason; const code = stringField(e, 'code'); if (code !== null) return code; return FALLBACK_KIND; } export const errorKindAttr = (e: unknown): { readonly 'error.kind': string } => ({ 'error.kind': errorKind(e) }); // Absence, in the same closed-tag style as a typed miss (t134u). A missing value is None. // Result keeps its `ok` discriminant (the 0.2.0 decision). Option uses `tag`. The helpers below are the composition. export type Some = { readonly tag: 'some'; readonly value: T }; export type None = { readonly tag: 'none' }; export type Option = Some | None; export const some = (value: T): Some => ({ tag: 'some', value }); export const none: None = { tag: 'none' }; // Total over any input (#296): a value that is not an Option (null, a number, an object with another tag) is neither // some nor none, so both answer false for it rather than throwing on the property read. const isTagged = (o: unknown, tag: Option['tag']): boolean => isRecord(o) && o['tag'] === tag; export const isSome = (o: Option): o is Some => isTagged(o, 'some'); export const isNone = (o: Option): o is None => isTagged(o, 'none'); export type OptionHandlers = { readonly some: (value: T) => R; readonly none: (absent: None) => R }; export const matchOption = (o: Option, h: OptionHandlers): R => { if (o.tag === 'none') return h.none(o); // Not a method call named `some`: that is Array#some to the linter. const present = h.some; return present(o.value); }; // Ok becomes Some. Err becomes None; the error is dropped on purpose (None carries no reason). export const resultToOption = (r: Result): Option => (r.ok ? some(r.value) : none); // Some becomes Ok. None becomes Err(error). The error is required: None has nothing to put there. export const optionToResult = (o: Option, error: E): Result => (o.tag === 'some' ? ok(o.value) : err(error)); // Ok(Some(v)) → Some(Ok(v)); Ok(None) → None; Err(e) → Some(Err(e)). export const transposeResultOption = (r: Result, E>): Option> => { if (!r.ok) return some(err(r.error)); return r.value.tag === 'some' ? some(ok(r.value.value)) : none; }; // Some(Ok(v)) → Ok(Some(v)); Some(Err(e)) → Err(e); None → Ok(None). export const transposeOptionResult = (o: Option>): Result, E> => { if (o.tag === 'none') return ok(none); return o.value.ok ? ok(some(o.value.value)) : err(o.value.error); }; // map, flatMap, and getOrElse. matchOption is the exhaustive eliminator; these are its two branches. // Names follow matchOption: `map` is already Result's. None is returned as itself, so a chain does not allocate a fresh absence. // getOrElse takes a value the caller already computed. A fallback that should run only on None belongs in matchOption. export const mapOption = (o: Option, f: (value: T) => U): Option => (o.tag === 'some' ? some(f(o.value)) : o); export const flatMapOption = (o: Option, f: (value: T) => Option): Option => (o.tag === 'some' ? f(o.value) : o); export const getOrElse = (o: Option, fallback: T): T => (o.tag === 'some' ? o.value : fallback);