Skip to content

std helpers ​

@evobug_com/safe-ts-std provides focused, tree-shakeable modules that replace common JavaScript footguns: promise combinators returning Result, cryptographic randomness, prototype-safe dictionaries, scoped event listeners, and safe parsing. Each module is imported individually so you ship only what you use.

In short

  • Zero-bloat subpath imports: every category lives under its own entrypoint (@evobug_com/safe-ts-std/async, /dict, /random, /url, /path, …).
  • Drop-in SAFE-TS idioms: helpers return Result<T, E> or Option<T> instead of throwing or returning null.
  • Recognized by the checker: proof constructors (safeUrl, pathUnder, fromOperator) and listen satisfy SAFE-TS's sink and cleanup rules directly.
ModuleHelpers
@evobug_com/safe-ts-std/asyncsettleAll, firstOk, withTimeout (resolves to a Timed<T> enum), mapLimit, latest (with Superseded)
@evobug_com/safe-ts-std/randomrandomToken, randomInt, Rng
@evobug_com/safe-ts-std/dictgetOwn, KeyedMap, recordOf, keysOf, omit
@evobug_com/safe-ts-std/eventslisten
@evobug_com/safe-ts-std/regexpescapeRegExp
@evobug_com/safe-ts-std/numberparseNumber, parseInteger
@evobug_com/safe-ts-std/base64toBase64, fromBase64, fromBase64Bytes: base64 that doesn't throw, URL-safe too
@evobug_com/safe-ts-std/arrayupdateEach, indexIn, maxOf, minOf, inlineArray, InlineArray; filter(Boolean) that narrows, with the prelude
@evobug_com/safe-ts-std/arbitraryarbitrary<T>, check: see property tests
@evobug_com/safe-ts-std/resultPropagateError with { cause }, mapErr, Panic (see Errors), panic, describeError, trust, LegacyNull
@evobug_com/safe-ts-std/enumvariants<T>(), the tags of an enum (see Enums)
@evobug_com/safe-ts-std/testingfixture, testDouble, unchecked, expectPresent: test files only (see testing)
@evobug_com/safe-ts-std/async-stateAsyncState<T, E>: where async work stands, as one enum (what useTask keeps, in Vue and React)
@evobug_com/safe-ts-std/urlsafeUrl, safeHref: only URLs that can't run script, and the schemes you list (Vue, React, url-sink)
@evobug_com/safe-ts-std/pathpathUnder(root, ...parts): a SafePath that stays under root, or an Err (proof types, path-sink)
@evobug_com/safe-ts-std/operatorfromOperator(text): a FromOperator, text whoever runs the program gave it (proof types)
@evobug_com/safe-ts-std/brandBrand<"Name">, brandConstructor, brandSinks: brands of your own

Promises that return errors ​

Promise.allSettled and Promise.any (promise combinators) are the right tools for "wait for all of them" and "the first one that works", but their results don't fit Result: allSettled gives { status, value | reason } objects, and any rejects with an AggregateError. settleAll and firstOk give you Results instead, so a failure is checked with isErr like every other error:

✓ Accepted0 diagnostics
ts
import { firstOk, settleAll } from "@evobug_com/safe-ts-std/async";
import { isErr, type Result } from "@evobug_com/safe-ts-std/result";

export async function fetchAll(urls: readonly string[], signal: AbortSignal): Promise<Response[]> {
  const results = await settleAll(urls.map((url) => fetch(url, { signal })));
  // Each result is a Response, or an Err holding why that request failed.
  return results.flatMap((result) => (isErr(result) ? [] : [result]));
}

export function fromAnyMirror(mirrors: readonly string[], signal: AbortSignal): Promise<Result<Response, AggregateError>> {
  // An Err when every mirror failed: its AggregateError lists why.
  return firstOk(mirrors.map((url) => fetch(url, { signal })));
}
ts
import { firstOk, settleAll } from "@evobug_com/safe-ts-std/async";
import { isErr, type Result } from "@evobug_com/safe-ts-std/result";

export async function fetchAll(urls: readonly string[], signal: AbortSignal): Promise<Response[]> {
  const __la1 = urls; const __lr1: any[] = new Array(__la1.length); for (let __li1 = 0, __ln1 = __la1.length; __li1 < __ln1; __li1++) { if (!(__li1 in __la1)) continue; const __le1 = __la1[__li1]!; { let url = __le1; __lr1[__li1] = (fetch(url, { signal })); }} const results = await settleAll(__lr1);
  // Each result is a Response, or an Err holding why that request failed.
  return results.flatMap((result) => (isErr(result) ? [] : [result]));
}

export function fromAnyMirror(mirrors: readonly string[], signal: AbortSignal): Promise<Result<Response, AggregateError>> {
  // An Err when every mirror failed: its AggregateError lists why.
  { const __la2 = mirrors; const __lr2: any[] = new Array(__la2.length); for (let __li2 = 0, __ln2 = __la2.length; __li2 < __ln2; __li2++) { if (!(__li2 in __la2)) continue; const __le2 = __la2[__li2]!; { let url = __le2; __lr2[__li2] = (fetch(url, { signal })); }} return firstOk(__lr2); }
}

withTimeout runs work with a time limit. A timeout isn't an error the way a failed request is: it is one of the ways the work can end, next to finishing, failing and being cancelled. So the result is an Enum with one case for each, and match makes you handle all four:

✓ Accepted0 diagnostics
ts
import { withTimeout } from "@evobug_com/safe-ts-std/async";
import { match } from "@evobug_com/safe-ts-std/enum";

export async function load(url: string, signal: AbortSignal): Promise<string> {
  const outcome = await withTimeout((stop) => fetch(url, { signal: stop }), 5_000, signal);
  return match(outcome, {
    Done: ({ value }) => value.statusText,
    Failed: () => "network error",
    TimedOut: ({ ms }) => `no answer within ${ms} ms`,
    Cancelled: () => "cancelled",
  });
}
ts
import { withTimeout } from "@evobug_com/safe-ts-std/async";
import { unreachable as __matchUnreachable } from "@evobug_com/safe-ts-std/enum"; import { match } from "@evobug_com/safe-ts-std/enum";

export async function load(url: string, signal: AbortSignal): Promise<string> {
  const outcome = await withTimeout((stop) => fetch(url, { signal: stop }), 5_000, signal);
  { const __ms1 = outcome; let __mv1: string; switch (__ms1.tag) {
    case "Done": { const { value } = __ms1; __mv1 = value.statusText; break; }
    case "Failed": { __mv1 = "network error"; break; }
    case "TimedOut": { const { ms } = __ms1; __mv1 = `no answer within ${ms} ms`; break; }
    case "Cancelled": { __mv1 = "cancelled"; break; } default: __mv1 = __matchUnreachable(__ms1); } return __mv1; }

}

The work gets its own AbortSignal, which aborts when time runs out or when the caller's signal does. Pass it on (to fetch, a stream, a child process), and the work really stops instead of running on in the background after withTimeout has given up. A rejection of the work is the Failed case, so nothing needs wrapping in unsafeAsync, and withTimeout never rejects. Its timer and abort listener are removed as soon as the outcome is known, so a fast answer doesn't keep the process alive for the rest of the timeout.

mapLimit(items, limit, fn, signal?) is Promise.all(items.map(fn)) with at most limit calls running at once (bounded-concurrency). It resolves to the values in order, or to an Err with the first failure, and never rejects:

✓ Accepted0 diagnostics
ts
import { mapLimit } from "@evobug_com/safe-ts-std/async";
import { parseInteger } from "@evobug_com/safe-ts-std/number";
import { q, type Result, unwrapOr } from "@evobug_com/safe-ts-std/result";

export async function sizes(urls: readonly string[], signal: AbortSignal): Promise<Result<number[], unknown>> {
  const responses = q(await mapLimit(urls, 8, (url, _, stop) => fetch(url, { signal: stop }), signal));
  return responses.map((response) => unwrapOr(parseInteger(response.headers.get("content-length") ?? "0"), 0));
}
ts
import { mapLimit } from "@evobug_com/safe-ts-std/async";
import { parseInteger } from "@evobug_com/safe-ts-std/number";
import { Err as __qErr } from "@evobug_com/safe-ts-std/result"; import { q, type Result, unwrapOr } from "@evobug_com/safe-ts-std/result";

export async function sizes(urls: readonly string[], signal: AbortSignal): Promise<Result<number[], unknown>> {
  const __q1 = await mapLimit(urls, 8, (url, _, stop) => fetch(url, { signal: stop }), signal); if (__q1 instanceof __qErr) return __q1; const responses = __q1;
  return responses.map((response) => unwrapOr(parseInteger(response.headers.get("content-length") ?? "0"), 0));
}

Each call gets a signal that aborts after the first failure, or when the caller's signal does; no new calls start then. To go on past failures and get one Result per item, as settleAll does, return one from fn: (item) => unsafeAsync(() => work(item)).

latest(work, signal?) keeps only the newest run's answer: each run(...) aborts the previous run's signal, and an older run resolves to err(Superseded). It is useTask without a framework or a state, for plain DOM code, a CLI or a worker: Latest run wins.

✓ Accepted0 diagnostics
ts
import { latest, Superseded } from "@evobug_com/safe-ts-std/async";
import { type Enum, match } from "@evobug_com/safe-ts-std/enum";
import { isErr, type Option, type Result } from "@evobug_com/safe-ts-std/result";

type PriceError = Enum<{ NotSold: {}; Offline: {} }>;

declare function loadPrice(sku: string, signal: AbortSignal): Promise<Result<number, PriceError>>;

/** The price line to show, or `undefined` when a newer lookup replaced this one. */
export function pricer(page: AbortSignal): (sku: string) => Promise<Option<string>> {
  const price = latest((signal, sku: string) => loadPrice(sku, signal), page);
  return async (sku) => {
    const found = await price.run(sku);
    if (!isErr(found)) return `${found} €`;
    if (found.error instanceof Superseded) return undefined;
    return match(found.error, { NotSold: () => "not sold here", Offline: () => "price unavailable offline" });
  };
}

The checker knows that these helpers catch: a PropagateError that the work of withTimeout or mapLimit throws or rejects with, or that a promise given to settleAll or firstOk rejects with, ends there, like in unsafeAsync. latest doesn't catch: a PropagateError from its work is reported in the callback, as escaping it. Return the failure as an Err instead.

Random numbers ​

Math.random is fast but not cryptographically secure: its output can be predicted from earlier outputs, so it must never make tokens, ids or passwords. And min + Math.floor(x * range) or n % range on random integers favours some values over others whenever the range doesn't divide the generator's range (modulo bias).

randomToken returns cryptographically random bytes as hex (16 bytes, 32 characters, by default). randomInt(min, max) returns an integer with min <= n < max (max excluded, like Node's crypto.randomInt), from crypto.getRandomValues, using rejection sampling so every value is equally likely:

✓ Accepted0 diagnostics
ts
import { randomInt, randomToken } from "@evobug_com/safe-ts-std/random";

export const sessionId = randomToken(); // 32 hex characters, 128 bits
export const die = randomInt(1, 7); // 1, 2, 3, 4, 5 or 6

For code you want to test, take an Rng parameter. Rng.crypto() is secure; Rng.seeded(n) is a small deterministic generator (mulberry32) that gives the same numbers for the same seed, for tests, simulations and procedural content. Never use it for secrets.

✓ Accepted0 diagnostics
ts
import { Rng } from "@evobug_com/safe-ts-std/random";

export function shuffle<T>(items: readonly T[], rng: Rng = Rng.crypto()): T[] {
  const result = [...items];
  for (let i = result.length - 1; i > 0; i--) {
    const j = rng.int(0, i + 1);
    const a = result[i];
    const b = result[j];
    if (a === undefined || b === undefined) continue; // can't happen: both indexes are in range
    result[i] = b;
    result[j] = a;
  }
  return result;
}

// In a test: the same order on every run.
export const order = shuffle([1, 2, 3, 4], Rng.seeded(42));

Lookups by key ​

record[key] on a plain object also finds what the object inherits: prices["constructor"] is the Object function, prices["toString"] a method. When the key comes from outside (a query string, JSON, a form), getOwn only returns the record's own properties, and undefined otherwise, typed as Option<V>:

✓ Accepted0 diagnostics
ts
import type { Option } from "@evobug_com/safe-ts-std/result";
import { getOwn } from "@evobug_com/safe-ts-std/dict";

const prices: Record<string, number> = { apple: 1, pear: 2 };

export function price(name: string): Option<number> {
  return getOwn(prices, name); // getOwn(prices, "constructor") is undefined
}

A table checked with satisfies Record<State, ...> has a row for every state this build knows. The server may send one it doesn't (a state added after the build), and TABLE[state] is then undefined, typed as a row. Give getOwn a fallback: it is typed like the table's values, so a literal stays a literal, and one that isn't a value of the table is a type error.

✓ Accepted0 diagnostics
ts
import { getOwn } from "@evobug_com/safe-ts-std/dict";

type State = "open" | "closed";

const ICONS = { open: "circle", closed: "check", unknown: "help" } as const satisfies Record<State | "unknown", string>;

export function icon(state: string): "circle" | "check" | "help" {
  return getOwn(ICONS, state, ICONS.unknown); // "help" for a state this build doesn't know
}

A Map compares keys by identity: two [1, 2] arrays are two different keys, so map.get([1, 2]) never finds what map.set([1, 2], ...) stored. (Objects don't have a content hash to compare by: a Map looks them up by an identity hash, see hash codes in V8.) KeyedMap takes a function that turns a key into a string or number, and compares those:

✓ Accepted0 diagnostics
ts
import { KeyedMap } from "@evobug_com/safe-ts-std/dict";

type Cell = readonly [row: number, column: number];

const sheet = new KeyedMap<Cell, string>(([row, column]) => `${row},${column}`);
sheet.set([1, 2], "Total");

export const found = sheet.get([1, 2]); // "Total"
export const cells = [...sheet.keys()]; // the original Cell keys

The key function must give equal results exactly for equal keys; its results compare like Map keys, so 1 and "1" are different.

For a table keyed by a value from the server's list (Open<K>), lookup(table, value, fallback) from @evobug_com/safe-ts-std/open reads the row of a known value and gives the fallback for one this build doesn't know: see Proof types.

Event listeners that remove themselves ​

addEventListener without a matching removeEventListener keeps the handler, and everything it references, alive as long as the target. listen returns a handle that removes the listener, and it is Disposable, so with explicit resource managementusing removes it when the block ends, however it ends:

✓ Accepted0 diagnostics
ts
import { listen } from "@evobug_com/safe-ts-std/events";

export function trackWhileOpen(dialog: HTMLDialogElement, log: (x: number) => void): void {
  using _moves = listen<MouseEvent>(dialog, "mousemove", (event) => log(event.clientX));
  // ... the listener is removed when this function returns
}

export function subscribe(target: EventTarget, onPing: () => void): () => void {
  const sub = listen(target, "ping", onPing);
  return () => sub.dispose(); // or keep the handle
}

Escaping text for a regular expression ​

new RegExp(userInput) treats . * ( and friends as syntax. escapeRegExp turns text into a pattern that matches exactly that text. It uses the built-in RegExp.escape where the runtime has it; elsewhere it escapes the syntax characters and punctuators itself, which matches the same strings and is valid with the u and v flags. (The built-in also escapes a leading letter or digit and whitespace, which only matters if you glue the result right after an escape like \0.) A pattern built only from escaped text, literals and numbers (in a template, with +, words.map(escapeRegExp).join("|"), or a RegexSource[] joined) can't make new RegExp throw, and unhandled-failure doesn't report it.

✓ Accepted0 diagnostics
ts
import { escapeRegExp } from "@evobug_com/safe-ts-std/regexp";

export function highlight(text: string, query: string): string {
  return text.replace(new RegExp(escapeRegExp(query), "gi"), (match) => `<mark>${match}</mark>`);
}

It returns a RegexSource, which new RegExp can't throw for: keep one in a const or pass it to another function, and unhandled-failure still knows (Proof types).

Text and markup: escapeHtml, isAscii ​

escapeHtml(text) (from @evobug_com/safe-ts-std/html) turns &, <, >, " and ' into entities, so the text shows as written; it returns an Html, which v-html accepts. defineSanitizer(fn) declares the project's sanitizer as the other way to make one. isAscii(text) (from @evobug_com/safe-ts-std/ascii) says whether every character is ASCII and narrows text to Ascii, which btoa can encode without throwing; asciiOf(n) writes a number as one. See Proof types.

Numbers from text ​

Number("abc") is NaN, Number("") is 0 and parseInt("12px") is 12, all without a word (number-parse-nan). parseNumber and parseInteger return a Result instead, whose error says what was wrong:

✓ Accepted0 diagnostics
ts
import { type NumberError, parseInteger, parseNumber } from "@evobug_com/safe-ts-std/number";
import { q, type Result } from "@evobug_com/safe-ts-std/result";

export function price(cents: string, rate: string): Result<number, NumberError> {
  const amount = q(parseInteger(cents));
  const factor = q(parseNumber(rate));
  return Math.round(amount * factor);
}
ts
import { type NumberError, parseInteger, parseNumber } from "@evobug_com/safe-ts-std/number";
import { Err as __qErr } from "@evobug_com/safe-ts-std/result"; import { q, type Result } from "@evobug_com/safe-ts-std/result";

export function price(cents: string, rate: string): Result<number, NumberError> {
  const __q1 = parseInteger(cents); if (__q1 instanceof __qErr) return __q1; const amount = __q1;
  const __q2 = parseNumber(rate); if (__q2 instanceof __qErr) return __q2; const factor = __q2;
  return Math.round(amount * factor);
}

Both take decimal notation only, with whitespace around it allowed: no empty text, no trailing characters, no hex or Infinity. parseNumber needs a finite result ("1e999" fails); parseInteger needs a safe integer, so "9007199254740993" fails instead of silently becoming ...992. The error is { text, reason, message }, with reason one of "empty", "not a number", "not finite", "not an integer", "not a safe integer", and message both in one line (not a number: "12px").

Base64 ​

btoa(text) throws for a character above U+00FF (btoa("€")), and atob(text) throws for text that isn't base64. toBase64 encodes text as UTF-8, so every string has a base64 form and the call can't fail. fromBase64 decodes it back and returns a Result: not base64 for a character outside the alphabet, a length no base64 has, or = in the middle, and not UTF-8 for bytes that aren't text. Both take { alphabet: "base64url" } for the URL-safe alphabet (- and _, no padding by default), and toBase64 takes bytes too (fromBase64Bytes gives them back).

✓ Accepted0 diagnostics
ts
import { type Base64Error, fromBase64, toBase64 } from "@evobug_com/safe-ts-std/base64";
import type { Result } from "@evobug_com/safe-ts-std/result";

export const pathOf = (id: string): string => `/requests/${toBase64(id, { alphabet: "base64url" })}`;

export const idOf = (segment: string): Result<string, Base64Error> => fromBase64(segment, { alphabet: "base64url" });

For ASCII text toBase64(text) is what btoa(text) gives. For other characters they differ (btoa encodes é as the one byte 0xE9, toBase64 as its two UTF-8 bytes), so decode with fromBase64, not atob. The checker doesn't report btoa where it can't throw: text written out without such a character, numbers written as text (btoa(String(id)), btoa(`${id}:${page}`) with id and page declared as numbers), and an Ascii (isAscii(id) ? btoa(id) : ..., btoa(asciiOf(n)), a parameter declared Ascii), also as a part of such a template or a branch of ?: and ??.

One message for any std error ​

describeError(error) (from @evobug_com/safe-ts-std/result) gives one line for any std error, so a test helper or a log line can take every std Result: a JsonError as $.path: message, a NumberError (or anything with a message) as its message, an Err or a Panic as what it holds, an Error as Name: message. It is for readers who want the error's own words, such as a log; text a user reads comes from a match over a named error (Give errors names).

✓ Accepted0 diagnostics
ts
import { parseJson } from "@evobug_com/safe-ts-std/json";
import { parseInteger } from "@evobug_com/safe-ts-std/number";
import { describeError, isErr } from "@evobug_com/safe-ts-std/result";

// A log line for an operator: the error's own words are what they need.
export function startupLog(port: string, limitsJson: string): readonly string[] {
  const parsedPort = parseInteger(port);
  const limits = parseJson<{ readonly maxUsers: number }>(limitsJson);
  return [
    isErr(parsedPort) ? `PORT: ${describeError(parsedPort)}` : `listening on ${parsedPort}`,
    isErr(limits) ? `limits.json: ${describeError(limits)}` : `up to ${limits.maxUsers} users`,
  ];
}
ts
import { parseJsonWith as __jsonParse, validateWith as __jsonValidate, jsonFail as __jsonFail, isJsonErr as __jsonIsErr, isJsonObject as __jsonIsObject, type JsonResult as __JsonResult } from "@evobug_com/safe-ts-std/json"; import { parseJson } from "@evobug_com/safe-ts-std/json";
import { parseInteger } from "@evobug_com/safe-ts-std/number";
import { describeError, isErr } from "@evobug_com/safe-ts-std/result";

// A log line for an operator: the error's own words are what they need.
export function startupLog(port: string, limitsJson: string): readonly string[] {
  const parsedPort = parseInteger(port);
  const limits = __jsonParse<{ readonly maxUsers: number }>(limitsJson, __va0);
  return [
    isErr(parsedPort) ? `PORT: ${describeError(parsedPort)}` : `listening on ${parsedPort}`,
    isErr(limits) ? `limits.json: ${describeError(limits)}` : `up to ${limits.maxUsers} users`,
  ];
}
// ---- generated by safe-ts: JSON validators ----
function __va0(v: unknown, p: string): __JsonResult<{ "maxUsers": number; }> {
  if (!__jsonIsObject(v)) return __jsonFail(p, "object", v);
  const __j1 = v["maxUsers"];
  if (typeof __j1 !== "number") return __jsonFail(p + ".maxUsers", "number", __j1);
  const __j2 = __j1;
  const out: { "maxUsers": number; } = { "maxUsers": __j2 };
  return out;
}

Tables keyed by a literal union ​

A table with one value per member of a union ("small" | "medium" | "large") needs a cast with Object.fromEntries, which is typed { [k: string]: V }; so do Object.keys(table) (a string[]) and TUPLE.indexOf(x as never). The typed versions:

  • recordOf(keys, f) (dict): a Record<K, V> with f(key) for every key;
  • keysOf(table) (dict): the keys of a table you declared (as const, Object.freeze), typed as its keys. Only for such tables: an object typed by an interface may have more keys at runtime than its type lists;
  • indexIn(tuple, value) (array): the index of value, typed as one of the tuple's indexes (0 | 1 | 2), or undefined. On any array it is indexOf without the -1 (not-found-index reports a -1 used as a position).
✓ Accepted0 diagnostics
ts
import { indexIn } from "@evobug_com/safe-ts-std/array";
import { keysOf, recordOf } from "@evobug_com/safe-ts-std/dict";
import type { Option } from "@evobug_com/safe-ts-std/result";

const SIZES = ["small", "medium", "large"] as const;
type Size = (typeof SIZES)[number];

export const LABELS: Record<Size, string> = recordOf(SIZES, (size) => size.toUpperCase());

export const PRICES = Object.freeze({ coffee: 3, tea: 2 });

export function menu(): string[] {
  return keysOf(PRICES).map((drink) => `${drink}: ${PRICES[drink]}`);
}

export function sizeRank(input: string): Option<0 | 1 | 2> {
  return indexIn(SIZES, input);
}

Dropping keys: omit ​

omit(value, ...keys) (dict) is a copy without those keys, typed Omit<T, K>: the way to drop optional keys, where { ...settings, theme: undefined } keeps the key (and exactOptionalPropertyTypes refuses it) and delete copy[key] changes the object's shape. Own enumerable properties are copied, as a spread copies them. See Absence.

filter(Boolean) that narrows ​

TypeScript's filter(Boolean) keeps the element type: (string | false)[] stays (string | false)[]. With the prelude enabled in tsconfig.json, it is typed to keep what is truthy: string[] (Truthy<T> from the array module). filter(Boolean) drops 0 and "" too; where those are values, filter on what you mean ((p) => p !== false).

Stopping the program: panic ​

Some invariants nothing can handle: a table built while its module loads, with a name listed twice after a merge. A PropagateError there would need a try around the import, and throw new Error is no-throw. panic(message) (result, also in the prelude) stops the program: it throws an Error named Panic, its type is never so the branch ends there, the checker treats it as a crash rather than an error to catch (no uncaught-propagation), and safe-ts check counts the calls in its escape-hatches line. For anything a caller can handle, return a Result.

Never use it for a value that isn't there yet: a store that has no answer from the server, a field filled in on load. Something on the page can wait for those, so a panic crashes a page that should show a spinner. Keep the waiting in an AsyncState or an Option instead.

✓ Accepted0 diagnostics
ts
import { panic } from "@evobug_com/safe-ts-std/result";

function codesOf(names: readonly string[]): ReadonlyMap<string, number> {
  if (new Set(names).size !== names.length) panic(`a code is listed twice in ${names.join(", ")}`);
  return new Map(names.map((name, i) => [name, i]));
}

export const ORDER_STATUS = codesOf(["draft", "sent", "paid"]);
ts
import { panic } from "@evobug_com/safe-ts-std/result";

function codesOf(names: readonly string[]): ReadonlyMap<string, number> {
  if (new Set(names).size !== names.length) panic(`a code is listed twice in ${names.join(", ")}`);
  return new Map((() => { const __la1 = names; const __lr1: any[] = new Array(__la1.length); for (let __li1 = 0, __ln1 = __la1.length; __li1 < __ln1; __li1++) { if (!(__li1 in __la1)) continue; const __le1 = __la1[__li1]!; { let name = __le1; let i = __li1; __lr1[__li1] = ([name, i]); }} return __lr1; })());
}

export const ORDER_STATUS = codesOf(["draft", "sent", "paid"]);

A trusted boundary: trust ​

Sometimes a value can't be checked, or the check isn't worth its cost: data another part of the program made (a worker that posts only Progress messages), a library typed too loosely. value as T says so, but no-unchecked-cast reports it, and the ways around it (an overload <T>(x: Partial<T>): T over an unknown implementation, a type guard that checks only the outer shape) are casts too, reported by no-overload and no-type-predicate. trust<T>(value) (result) is the named form: it does nothing at runtime, it can be searched for, and safe-ts check counts the calls in its escape-hatches line, like unsafe() and panic(). Say why in a comment. Where the value comes from outside the program (the network, storage, a file), validate it instead: validate<T>.

✓ Accepted0 diagnostics
ts
import { trust } from "@evobug_com/safe-ts-std/result";

type Progress = { readonly done: number; readonly total: number };

export function onProgress(event: MessageEvent<unknown>, show: (progress: Progress) => void): void {
  // The worker posts only `Progress` messages (worker.ts, same build).
  show(trust<Progress>(event.data));
}

A bridge for legacy null: LegacyNull ​

While a codebase migrates, strict code may still be called by code that passes null. A prop or parameter typed Option<T> | LegacyNull (result) accepts it, without a null written in the strict file. It is a bridge, meant to go: turn the null into undefined where it comes in (name ?? undefined), and drop | LegacyNull once no caller passes null. Search for it to find what is left; safe-ts check counts its uses in the escape-hatches line. A null that means something of its own (in JSON) is JsonNull, not this.

✓ Accepted0 diagnostics
ts
import type { LegacyNull, Option } from "@evobug_com/safe-ts-std/result";

// Legacy callers (modules/reports) still pass `null` for "no title".
export function heading(title: Option<string> | LegacyNull): string {
  return title ?? "Untitled";
}

Updating an array in place ​

items = items.map(f) allocates a new array; when the function owns the array and only changes its elements, updateEach writes them back in place. Its parameter is Mut<T[]>, so the signature says the array is changed and the call lends it (updateEach(mut(prices), f)), and update must return the same element type. Holes are skipped, like forEach.

✓ Accepted0 diagnostics
ts
import { updateEach } from "@evobug_com/safe-ts-std/array";
import { type Mut, mut } from "@evobug_com/safe-ts-std/mut";

export function applyDiscount(prices: Mut<number[]>, percent: number): void {
  updateEach(mut(prices), (price) => Math.round(price * (100 - percent)) / 100);
}
ts
import { updateEach } from "@evobug_com/safe-ts-std/array";
import { type Mut, mut } from "@evobug_com/safe-ts-std/mut";

export function applyDiscount(prices: Mut<number[]>, percent: number): void {
  { const __la1 = prices; for (let __li1 = 0, __ln1 = __la1.length; __li1 < __ln1; __li1++) { if (!(__li1 in __la1)) continue; const __le1 = __la1[__li1]!; { let price = __le1; __la1[__li1] = (Math.round(price * (100 - percent)) / 100); }} }
}

Chains that are always loops ​

inlineArray(xs) gives xs typed as an InlineArray: every chain of methods on it becomes loops at build time, and one that can't is an error. See Loops.

The largest and smallest of a list ​

Math.max(...values) passes every element as an argument: past about 100,000 it throws RangeError: Maximum call stack size exceeded, and for an empty list it returns -Infinity, a number that looks like an answer (unbounded-spread). maxOf and minOf take the list itself and return an Option<number>: undefined for an empty list, otherwise what Math.max / Math.min gives (NaN if an element is NaN), at any length.

✓ Accepted0 diagnostics
ts
import { maxOf, minOf } from "@evobug_com/safe-ts-std/array";

export function spread(readings: readonly number[]): string {
  const high = maxOf(readings);
  const low = minOf(readings);
  return high === undefined || low === undefined ? "no readings" : `${low} to ${high}`;
}

For two or three values, Math.max(a, b) is fine: only a spread of a list is reported.

Errors with a cause ​

When you turn one error into another, keep the original as its cause: Node and browser consoles print the whole chain. PropagateError passes { cause } through to Error:

✓ Accepted0 diagnostics
ts
import { parseJson } from "@evobug_com/safe-ts-std/json";
import { isErr, PropagateError } from "@evobug_com/safe-ts-std/result";

export class ConfigError extends PropagateError {}

type Config = { readonly port: number };

// Without a config the server can't start: the error ends the command, with its cause.
export function loadConfig(text: string): Config {
  const config = parseJson<Config>(text);
  if (isErr(config)) throw new ConfigError("config.json is not a valid config", { cause: config.error });
  return config;
}
ts
import { parseJsonWith as __jsonParse, validateWith as __jsonValidate, jsonFail as __jsonFail, isJsonErr as __jsonIsErr, isJsonObject as __jsonIsObject, type JsonResult as __JsonResult } from "@evobug_com/safe-ts-std/json"; import { parseJson } from "@evobug_com/safe-ts-std/json";
import { isErr, PropagateError } from "@evobug_com/safe-ts-std/result";

export class ConfigError extends PropagateError {}

type Config = { readonly port: number };

// Without a config the server can't start: the error ends the command, with its cause.
export function loadConfig(text: string): Config {
  const config = __jsonParse<Config>(text, __v0);
  if (isErr(config)) throw new ConfigError("config.json is not a valid config", { cause: config.error });
  return config;
}
// ---- generated by safe-ts: JSON validators ----
type __T0 = { "port": number; };
function __v0(v: unknown, p: string): __JsonResult<__T0> {
  if (!__jsonIsObject(v)) return __jsonFail(p, "object", v);
  const __j1 = v["port"];
  if (typeof __j1 !== "number") return __jsonFail(p + ".port", "number", __j1);
  const __j2 = __j1;
  const out: { "port": number; } = { "port": __j2 };
  return out;
}

MIT OR Apache-2.0 · Docs by Gemini 4 Neon Extra