Rebasely Beta: data may be purged

justintypescript-ultra-strict Public

TypeScript · 242 lines · 12.1 KiB · at 9c48a39

// @tsus/v2: the type library of TypeScript-Ultra-Strict v2.//// Everything here is ordinary TypeScript that erases: there is no macro and no new file// extension, so esbuild, wrangler and node's type stripping handle files that use it unchanged.// What the types cannot express, the checker enforces (`tsus check --v2`, codes TSUS5xx/TSUS6xx).// The brands below are `unique symbol` keys that are declared but not exported, so no code// outside this file can write a literal of a branded type: a Sql, a Permit, a Secret or an// Untrusted value only comes from the function that makes it, or from a cast, and casts are// banned outside *.boundary.ts files (TSUS506).// --- Option ---------------------------------------------------------------------------------/** * A value that may be absent. It is `T | undefined` underneath: no wrapper object, no * allocation, nothing to unwrap. The checker makes it safe: `null` is banned outside boundary * files (TSUS502), so there is one absent value, and a truthiness test on an Option whose value * can itself be falsy (`if (name)` on an `Option<string>`) is an error (TSUS503), so "" and 0 are * never mistaken for absent. */export type Option<T> = T | undefined;/** True when the Option holds a value. Same as `o !== undefined`. */export declare function isSome<T>(o: Option<T>): o is T;/** True when the Option is absent. Same as `o === undefined`. */export declare function isNone<T>(o: Option<T>): o is undefined;/** The boundary conversion: `null` and `undefined` become `undefined`. */export declare function fromNullable<T>(value: T | null | undefined): Option<T>;/** Exhaustive two-armed match over an Option. */export declare function matchOption<T, S, N>(o: Option<T>, arms: { readonly some: (value: T) => S; readonly none: () => N }): S | N;// --- Result ---------------------------------------------------------------------------------/** The success half of a Result: a plain frozen-shape object, `{ ok: true, value }`. */export type Ok<T> = { readonly ok: true; readonly value: T };/** The failure half of a Result: `{ ok: false, error }`. */export type Err<E> = { readonly ok: false; readonly error: E };/** * A computation that succeeded with a T or failed with an E. A plain tagged object, so it costs * one small allocation and narrows with `if (r.ok)`. An unused Result is an error (TSUS505). */export type Result<T, E> = Ok<T> | Err<E>;/** `const` keeps literal types (`Err({ kind: "missing" })` is `Err<{ readonly kind: "missing" }>`). */export declare function Ok<const T>(value: T): Ok<T>;export declare function Err<const E>(error: E): Err<E>;/** Exhaustive two-armed match over a Result. */export declare function matchResult<T, E, A, B>(r: Result<T, E>, arms: { readonly ok: (value: T) => A; readonly err: (error: E) => B }): A | B;/** Runs f, turning a throw into Err(the thrown value). */export declare function tryCatch<T>(f: () => T): Result<T, unknown>;/** Awaits f(), turning a rejection into Err(the reason). */export declare function tryAsync<T>(f: () => Promise<T>): Promise<Result<T, unknown>>;// --- match ----------------------------------------------------------------------------------type Key = string | number;type IsFinite<T> = [T] extends [never] ? false : string extends T ? false : number extends T ? false : true;type ArmResult<A> = { [P in keyof A]: A[P] extends (...args: never[]) => infer R ? R : never }[keyof A];type NoExtra<A, Allowed> = A & { readonly [X in Exclude<keyof A, Allowed>]: never };/** The arms of a match over the union V discriminated by its field K: one per value of V[K]. */// The arms return `any` in the constraint only: when the arms are wrong, TypeScript falls back to// the constraint, and an `unknown` there would add a second, misleading error at every use of the// match. When they are right, the result is the union of what the arms really return.export type TagArms<V, K extends keyof V> = {  readonly [P in V[K] & Key]: (variant: Extract<V, { readonly [_ in K]: P }>) => any;};/** * Exhaustive match over a discriminated union, by its discriminant field: * *     match(shape, "kind", { *       circle: (c) => Math.PI * c.r ** 2, *       square: (s) => s.side ** 2, *     }) * * Every value of `shape.kind` needs an arm (a missing one is a type error), an arm the union * cannot hold is a type error, and each arm's parameter is narrowed to its variant. The result is * the union of the arms' results. A plain function call: no macro, nothing to compile. */export declare function match<V, const K extends keyof V, A extends TagArms<V, K>>(  value: V,  key: K,  arms: IsFinite<V[K]> extends true ? NoExtra<A, V[K]> : "match: the discriminant must be a finite union of literals",): ArmResult<A>;/** * Exhaustive match over a finite union of string or number literals: * *     matchLiteral(method, { GET: () => read(), POST: () => write() }) * * A plain `string` subject is rejected: narrow it first, or use a switch with a default. */export declare function matchLiteral<V extends Key, A extends { readonly [P in V]: (value: P) => any }>(  value: V,  arms: IsFinite<V> extends true ? NoExtra<A, V> : "matchLiteral: the subject must be a finite union of literals",): ArmResult<A>;/** For the default branch of a switch the checker proved exhaustive: a type error if it is reachable. */export declare function exhaustive(value: never): never;/** Marks a parameter as mutable on purpose. Parameters are read-only by default (TSUS510). */export type Mutable<T> = T;// --- Sql ------------------------------------------------------------------------------------declare const SqlBrand: unique symbol;declare const UntrustedBrand: unique symbol;/** A value a query binds as a parameter. `undefined` binds as SQL NULL, booleans as 1 and 0. */export type SqlValue = string | number | bigint | boolean | undefined | ArrayBuffer | Uint8Array | Untrusted;/** * A query whose text was written by the program and whose values are bound parameters. It can * only be made by the `sql` tag (or composed from other Sql values), so a database adapter that * accepts only Sql cannot receive a string built from user input. */export interface Sql {  readonly text: string;  readonly params: readonly SqlValue[];  readonly [SqlBrand]: true;}/** * The only way to make a Sql: a tagged template. Every `${value}` becomes a `?` placeholder and * a bound parameter; a nested Sql is spliced in with its own parameters. * *     sql`SELECT id, title FROM issues WHERE repo_id = ${repoId} AND title LIKE ${pattern}` */export declare function sql(strings: TemplateStringsArray, ...values: readonly (SqlValue | Sql)[]): Sql;export declare namespace sql {  /** Joins fragments, by default with ", ". */  function join(parts: readonly Sql[], separator?: Sql): Sql;  /** A column or table name chosen by the program: only a string literal type is accepted. */  function ident<const N extends string>(name: string extends N ? never : N): Sql;  /** The empty fragment. */  const empty: Sql;}/** The part of a Cloudflare D1 binding the adapter uses (structurally typed, no import needed). */export interface D1StatementLike {  bind(...values: unknown[]): D1StatementLike;  all<T = Record<string, unknown>>(): Promise<{ results: T[] }>;  first<T = Record<string, unknown>>(): Promise<T | null>;  run(): Promise<{ meta?: { changes?: number } }>;}export interface D1Like {  prepare(query: string): D1StatementLike;  batch?(statements: D1StatementLike[]): Promise<{ results: unknown[] }[]>;}/** A database handle that accepts only Sql. Rows come back with SQL NULL as `undefined`. */export interface SafeDb {  all<R>(query: Sql): Promise<readonly R[]>;  first<R>(query: Sql): Promise<Option<R>>;  run(query: Sql): Promise<{ readonly changes: number }>;  batch(queries: readonly Sql[]): Promise<readonly (readonly unknown[])[]>;}/** Wraps a D1 binding (or anything shaped like one). */export declare function safeDb(db: D1Like): SafeDb;// --- Permit ---------------------------------------------------------------------------------declare const PermitBrand: unique symbol;/** * Proof that an access check allowed `action` on `resource`. Only `issuePermit` from * `@tsus/v2/authority` makes one, and the checker allows that import only in `*.access.ts` * files (TSUS602), the designated access-check modules. A function that reads private data takes * a Permit and reads the resource id from it (TSUS603), so it cannot be called without a check * and cannot be pointed at a different resource than the one that was checked. */export interface Permit<A extends string, R> {  readonly action: A;  readonly resource: R;  readonly [PermitBrand]: true;}/** Runtime defense in depth: true only for a Permit that issuePermit made. */export declare function isGenuinePermit(value: unknown): boolean;// --- Secret ---------------------------------------------------------------------------------declare const SecretBrand: unique symbol;/** * A value that must not leave the program by accident. It is not a string, so it cannot be * passed where one is expected; `reveal()` is the one explicit way out. At runtime it prints and * serializes as "[secret]" (String, templates, JSON.stringify, console.log, node:util inspect), * and the checker rejects it in templates, concatenation, logs, URLs, JSON and Response bodies * (TSUS604), so the redaction is a backstop, not the plan. */export interface Secret<T = string> {  readonly [SecretBrand]: T;  toString(): "[secret]";  toJSON(): "[secret]";}export declare function secret<T>(value: T): Secret<T>;/** The explicit way to use a secret: at the call that needs the raw value, and nowhere else. */export declare function reveal<T>(s: Secret<T>): T;// --- Untrusted ------------------------------------------------------------------------------/** * Text that came from a user (a form field, a query parameter, a bug report). It is the raw * string at runtime, so marking costs nothing, but its type is not a string: it cannot reach a * string sink without going through `escapeHtml`/`html` (HTML), `sql` (a bound parameter), * `fence` (an LLM prompt) or `validate` (a pattern). The checker rejects it in untagged * templates and concatenation (TSUS605 HTML, TSUS606 prompts, TSUS607 anything else). */export interface Untrusted<T extends string = string> {  readonly [UntrustedBrand]: T;}/** Marks text as user-provided. */export declare function untrusted(text: string): Untrusted;/** The length of the text, without letting it out. */export declare function untrustedLength(text: Untrusted): number;/** Transforms the text and keeps it marked (trim, lowercase, slice). */export declare function mapUntrusted(text: Untrusted, f: (raw: string) => string): Untrusted;/** The text as a plain string when the whole of it matches `pattern` (an id, a slug, a number). */export declare function validate(text: Untrusted, pattern: RegExp): Option<string>;declare const SafeHtmlBrand: unique symbol;/** HTML whose every interpolation was escaped. `.html` is the markup, for a Response body. */export interface SafeHtml {  readonly html: string;  readonly [SafeHtmlBrand]: true;}export type HtmlValue = SafeHtml | Untrusted | string | number | boolean | undefined | readonly HtmlValue[];/** Escapes & < > " ' in text. */export declare function escapeHtml(text: Untrusted | string): SafeHtml;/** HTML template: every interpolation is escaped unless it is already SafeHtml. */export declare function html(strings: TemplateStringsArray, ...values: readonly HtmlValue[]): SafeHtml;declare const FencedBrand: unique symbol;/** Untrusted text wrapped as data for an LLM prompt. */export type Fenced = string & { readonly [FencedBrand]: true };/** * Wraps user text for a prompt as `<untrusted source="...">...</untrusted>`, with any closing tag * or role marker inside it neutralized, so the model is told where the user's words begin and end. */export declare function fence(text: Untrusted, source: string): Fenced;/** Prompt template: interpolations must be program text or Fenced; Untrusted is a type error. */export declare function prompt(strings: TemplateStringsArray, ...values: readonly (string | number | Fenced)[]): string;