Proof types
A plain string doesn't tell callers—or static analyzers—whether it was sanitized, checked against javascript: URLs, escaped for a regex, or constrained inside a root directory. When a value travels through a computed, prop, or separate module, local inspection can't see how it was constructed. Proof types attach that guarantee to the type itself so tsc, vue-tsc, and safe-ts check verify it anywhere the value flows.
In short
- Brands (
Html,SafeUrl,RegexSource,Ascii,SafePath,FromOperator, customBrand<"Name">): zero-overhead branded strings produced only by sanctioned constructors (brand-constructor). - Wire types:
Open<K>for extensible server enums, andPatch<T>for distinguishing "keep", "clear", and "set" in update payloads. - Loans:
Mut<T>values created exclusively viamut(value)and checked invariantly (State). - Checker-only bounds:
Int<Min, Max>validates integer ranges atparseJson<T>boundaries while erasing tonumber.
None of them adds runtime overhead: brands erase to plain strings, Patch<T> is the plain payload object, and mut(value) erases at build time (only Open<K> wraps decoded values in a small tagged object).
Brands
| Type | Import | Made by | What it proves | Accepted by |
|---|---|---|---|---|
Html | @evobug_com/safe-ts-std/html (or safe-ts-vue/html) | escapeHtml(text), a sanitizer declared with defineSanitizer | markup that can't run script | markup-sink, vue-v-html, react-dangerous-html |
SafeUrl | @evobug_com/safe-ts-std/url (or safe-ts-vue/url) | safeHref(url), safeUrl(url) | a URL that can't run script when followed | url-sink, vue-unsafe-url |
RegexSource | @evobug_com/safe-ts-std/regexp | escapeRegExp(text) | a pattern that matches the text literally | pattern-sink, unhandled-failure on new RegExp |
Ascii | @evobug_com/safe-ts-std/ascii | isAscii(text) (narrows), asciiOf(n) | only ASCII characters | unhandled-failure on btoa |
SafePath | @evobug_com/safe-ts-std/path | pathUnder(root, ...parts) | a file path that stays under root | path-sink |
FromOperator | @evobug_com/safe-ts-std/operator | fromOperator(text) (counted with the escape hatches) | text whoever runs the program gave it | path-sink, code-sink, command-sink |
Brand<"Name"> | @evobug_com/safe-ts-std/brand | the functions declared with brandConstructor("Name", make) | what the project says it does | brand-sink, at the members brandSinks("Name", [...]) lists |
A brand is a string wherever one is asked for, so the functions that return one changed nothing for existing code: const href: string = safeHref(url) still compiles.
Html
Declare the sanitizer the project uses once, with defineSanitizer. The function it returns is the sanitizer itself, typed to return Html. Then the sanitized value can be kept in a computed, passed as a prop, or chosen in a ?:, and v-html accepts it:
✓ Accepted0 diagnostics
vue
<script setup lang="ts">
import DOMPurify from "dompurify";
import { computed } from "vue";
import { defineSanitizer, escapeHtml, type Html } from "@evobug_com/safe-ts-vue/html";
const sanitizeHtml = defineSanitizer((raw) => DOMPurify.sanitize(raw));
const props = defineProps<{ comment: string; preview: boolean; signature: Html }>();
const body = computed(() => (props.preview ? escapeHtml(props.comment) : sanitizeHtml(props.comment)));
</script>
<template>
<div v-html="body"></div>
<footer v-html="props.signature"></footer>
</template>defineSanitizer can't check that the function sanitizes: it is where the project vouches for it. Keep it in one module, next to the sanitizer's configuration, and review it like one.
vue-v-html also accepts sanitized HTML it can see without the type: DOMPurify.sanitize(x) and the other known sanitizers, a function of yours that returns their result, and a computed of it. The two ways combine (one branch of a ?: sanitized, the other typed Html). The type is what reaches further: a prop, a value from another component, a function in a package, and vue-tsc checking that nothing else is passed in.
SafeUrl
safeHref(url) returns a SafeUrl, so does safeUrl(url) when it accepts the URL. A prop typed SafeUrl can only be given a checked URL (TypeScript and vue-tsc refuse a string), and the component binding it needs no check of its own:
✓ Accepted0 diagnostics
vue
<script setup lang="ts">
import { computed } from "vue";
import { safeHref, type SafeUrl } from "@evobug_com/safe-ts-vue/url";
import type { Option } from "@evobug_com/safe-ts-std/result";
const props = defineProps<{ to: SafeUrl; website: Option<string> }>();
const site = computed(() => (props.website === undefined ? undefined : safeHref(props.website)));
</script>
<template>
<a :href="to">Open</a>
<a :href="site">Website</a>
<a :href="props.website === undefined ? undefined : safeHref(props.website)">Website</a>
</template>safeHref(url, fallback) and safeHref(url, { schemes, fallback }) check the fallback too, with the same schemes (one that isn't safe gives "#"), so the result is always a SafeUrl and vue-unsafe-url accepts any safeHref(...) call. It still reports one that is given a URL written out that it would refuse (safeHref('flow://watch') without schemes: ['flow']).
RegexSource
escapeRegExp(text) gives a RegexSource: valid with or without the u and v flags. new RegExp can't throw for one, nor for a pattern built from such sources, numbers and written text, with +, a template or .join(sep) of a RegexSource[], when the written parts are valid. This is the same check that accepts escapeRegExp(word) written in the pattern and words.map(escapeRegExp).join("|") (unhandled-failure); the type lets the source come from a parameter, a const or another file:
✓ Accepted0 diagnostics
ts
import { escapeRegExp, type RegexSource } from "@evobug_com/safe-ts-std/regexp";
export function wordPattern(word: string): RegExp {
return new RegExp(`\\b${escapeRegExp(word)}\\b`, "i");
}
export function anyOf(first: RegexSource, second: RegexSource): RegExp {
return new RegExp("^(?:" + first + "|" + second + ")$", "u");
}
export function anyWord(words: readonly RegexSource[]): RegExp {
return new RegExp(`^(?:${words.join("|")})$`);
}Text that isn't escaped is still reported, and so is a source changed by another string method (source.toLowerCase(), source.slice(1)), since its result is a string again:
✕ Rejectedunhandled-failure
ts
import type { RegexSource } from "@evobug_com/safe-ts-std/regexp";
export function search(query: string): RegExp {
return new RegExp(query);
}
export function lower(source: RegexSource): RegExp {
return new RegExp(source.slice(1));
}Ascii
btoa(text) throws for a character above U+00FF. The checker knows the text can't hold one when it is written out, when it is String(n) or a template of a number, bigint or boolean, or when its type is Ascii:
✓ Accepted0 diagnostics
ts
import { type Ascii, isAscii } from "@evobug_com/safe-ts-std/ascii";
import type { Option } from "@evobug_com/safe-ts-std/result";
export function pageId(id: number): string {
return btoa(`Page:${id}`);
}
export function encoded(id: Ascii): string {
return btoa(id);
}
export function fromRoute(slug: string): Option<string> {
return isAscii(slug) ? btoa(slug) : undefined;
}A plain string is still reported, and so is a function that encodes one, at each call (unhandled-failure).
SafePath
pathUnder(root, name) joins name under root and resolves . and .. in the text, as the file system would, before anything touches the disk; a path that would leave root, an absolute part (/etc/passwd, C:\x) and a NUL are an Err. What it returns is a SafePath, which every node:fs function takes as a path (path-sink), and which a function of yours can ask for:
✓ Accepted0 diagnostics
ts
import { readFile } from "@evobug_com/safe-ts-feature-node/fs/promises";
import { join } from "node:path";
import { pathUnder, type SafePath } from "@evobug_com/safe-ts-std/path";
import { isErr } from "@evobug_com/safe-ts-std/result";
const UPLOADS = join(import.meta.dirname, "uploads");
async function readUpload(file: SafePath): Promise<string> {
const text = await readFile(file, "utf8");
return isErr(text) ? "" : text;
}
export async function upload(name: string): Promise<string> {
const file = pathUnder(UPLOADS, name);
return isErr(file) ? "" : readUpload(file);
}It checks the text, not the disk: a symbolic link under root that points elsewhere is followed.
FromOperator
Whoever runs the program can already open any file and run any program: a path, a module or a command they give it (a command-line argument, an environment variable, their config file) is theirs. The sink rules accept those where the code shows where they come from (process.argv, process.env, import.meta.dirname, a name readdir returned, a function returning one). Past that (a parameter, a field), the type has to carry it: fromOperator(text) says the text is the operator's, and path-sink, code-sink and command-sink take a FromOperator:
✓ Accepted0 diagnostics
ts
import { readFileSync } from "@evobug_com/safe-ts-feature-node/fs";
import { type FromOperator, fromOperator } from "@evobug_com/safe-ts-std/operator";
import { isErr } from "@evobug_com/safe-ts-std/result";
function readConfig(file: FromOperator): string {
const text = readFileSync(file, "utf8");
return isErr(text) ? "{}" : text;
}
export const config = readConfig(fromOperator(process.env.APP_CONFIG ?? "app.json"));Nothing checks the claim, so safe-ts check counts each fromOperator call with the escape hatches. Make it where the operator's input enters (the entry point, the config loader), never around a value from a request; a name from a request goes through pathUnder instead. Markup, URLs, SQL and patterns don't take it: those reach other people.
Brands of your own
A fact std has no brand for (this SQL came from the tagged template, this id from the parser) can be a brand of the project's: Brand<"Name"> from @evobug_com/safe-ts-std/brand is a string with that mark, the functions declared with brandConstructor("Name", make) are the only ones that make it, and brandSinks("Name", [...]) names the library members that take only it. TypeScript holds every function of yours typed with the brand to it; the checker holds the rest: a cast, trust<Name>(...) or a type argument that would make one is brand-constructor, and a declared sink given anything else is brand-sink. brandConstructor returns make itself; it is where the project vouches that what make returns has the fact, so safe-ts check counts each call with the escape hatches, like defineSanitizer. Keep the brand, its constructors and its sinks in one module, and review it like one.
An SQL fragment that can only come from a tagged template (the substitutions become placeholders, bound with the statement) or a placeholder for one parameter:
✓ Accepted0 diagnostics
ts
// db/sql.ts: the project's SQL. A fragment is written in the source; data is bound to its placeholders.
import { DatabaseSync, type SQLInputValue } from "node:sqlite";
import { type Brand, brandConstructor, brandSinks } from "@evobug_com/safe-ts-std/brand";
import { unsafe } from "@evobug_com/safe-ts-std/result";
export type Sql = Brand<"Sql">;
/** `sql\`... ${value} ...\``: the text with a `?` for each substitution. */
export const sql = brandConstructor("Sql", (parts: TemplateStringsArray, ..._values: readonly SQLInputValue[]): string =>
parts.join("?"),
);
/** A placeholder for one parameter, to build a fragment from parts the source shows. */
export const placeholder = brandConstructor("Sql", (): string => "?");
brandSinks("Sql", ["node:sqlite Database#prepare", "node:sqlite Database#exec"]);
export function usersSince(db: DatabaseSync, day: string): unknown {
return unsafe(() => db.prepare(sql`SELECT name FROM users WHERE joined >= ${day}`).all(day));
}Then db.prepare(`SELECT ... '${day}'`) anywhere in the project is brand-sink, and so is a constant: only what sql and placeholder make goes there.
An id that can only come from a parser. The constructor returns a Result: its Err stays what it was, and the value, once the Err is handled, is the brand.
✓ Accepted0 diagnostics
ts
// users/id.ts: a user id is checked once, where it enters.
import { type Brand, brandConstructor } from "@evobug_com/safe-ts-std/brand";
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
import { err, q, type Result } from "@evobug_com/safe-ts-std/result";
export type UserId = Brand<"UserId">;
export type IdError = Enum<{ Malformed: { text: string } }>;
export const IdError = constructors<IdError>();
export const parseUserId = brandConstructor("UserId", (text: string): Result<string, IdError> =>
/^u_[0-9a-z]{12}$/.test(text) ? text : err(IdError.Malformed({ text })),
);
export function profilePath(id: UserId): string {
return `/users/${id}`;
}
export function fromRequest(text: string): Result<string, IdError> {
const id = q(parseUserId(text));
return profilePath(id);
}ts
// users/id.ts: a user id is checked once, where it enters.
import { type Brand, brandConstructor } from "@evobug_com/safe-ts-std/brand";
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
import { Err as __qErr } from "@evobug_com/safe-ts-std/result"; import { err, q, type Result } from "@evobug_com/safe-ts-std/result";
export type UserId = Brand<"UserId">;
export type IdError = Enum<{ Malformed: { text: string } }>;
export const IdError = constructors<IdError>();
export const parseUserId = brandConstructor("UserId", (text: string): Result<string, IdError> =>
/^u_[0-9a-z]{12}$/.test(text) ? text : err(({ tag: "Malformed", text } satisfies IdError as IdError)),
);
export function profilePath(id: UserId): string {
return `/users/${id}`;
}
export function fromRequest(text: string): Result<string, IdError> {
const __q1 = parseUserId(text); if (__q1 instanceof __qErr) return __q1; const id = __q1;
return profilePath(id);
}profilePath(text) with a plain string doesn't compile, and text as UserId or trust<UserId>(text) is brand-constructor, also in another file than the one declaring the brand. A brand's sinks are written as the maps write members: "module member", "module Class#method". A feature pack can declare them too, for its library ("sinks": { "members": { "pg Pool#query": { "brand": "Sql", "takes": "argument 0" } } }), with the constructor its package exports.
Making a brand some other way
A cast adds the mark without the check, and so do a type argument that only says what a call returns (inject<SafeUrl>(key), axios.get<Html>(url)) and a type predicate that claims one ((text: string): text is SafeUrl => text.length > 0: TypeScript doesn't check a predicate's body). brand-constructor reports all three. The one guard that makes a brand is std's: isAscii(text) narrows text to Ascii.
✕ Rejectedbrand-constructor
ts
import type { SafeUrl } from "@evobug_com/safe-ts-std/url";
export function home(path: string): SafeUrl {
return path as SafeUrl;
}When a value is safe for a reason the checker can't see (the router built the URL from its own route table), make it in one module marked // @safe-ts std and listed under "trustedFiles" in package.json. There the rules are off, the cast is reviewed with the module, and safe-ts check counts the file with the other escape hatches:
✓ Accepted0 diagnostics
ts
// @safe-ts std
// URLs our router builds from its route table: they start with `/`.
import type { SafeUrl } from "@evobug_com/safe-ts-std/url";
export function routeUrl(path: `/${string}`): SafeUrl {
return path as SafeUrl;
}parseJson<T> refuses a brand in T (json-type): data can't vouch for itself. Parse a string and make the brand from it.
Open<K>: a value from a list that can grow
A status, a type or a state comes from the server as a string. Typed as a union of the strings this build knows, parseJson fails the whole response when the server adds one. Typed as string, a lookup table answers undefined for the new one, and the page crashes a few calls later (Cannot read properties of undefined (reading 'tooltip')). Open<K> keeps both cases:
ts
type Open<K> = { tag: K; value: K } /* for each K */ | { tag: "Unknown"; value: string };parseJson turns a string the type lists into its variant and any other string into Unknown; something that isn't a string is still an error. match, is and variant work on it like on any enum, and match needs an Unknown handler:
✓ Accepted0 diagnostics
ts
import { match } from "@evobug_com/safe-ts-std/enum";
import { type JsonResult, parseJson } from "@evobug_com/safe-ts-std/json";
import { type Known, lookup, type Open } from "@evobug_com/safe-ts-std/open";
export type Issue = { readonly title: string; readonly state: Open<"todo" | "doing" | "done"> };
const ICONS = { todo: "circle", doing: "half", done: "check" } satisfies Record<Known<Issue["state"]>, string>;
export function readIssue(text: string): JsonResult<Issue> {
return parseJson<Issue>(text);
}
export function label(issue: Issue): string {
return match(issue.state, {
todo: () => "To do",
doing: () => "Doing",
done: () => "Done",
Unknown: ({ value }) => value,
});
}
export function icon(issue: Issue): string {
return lookup(ICONS, issue.state, "question");
}ts
import { unreachable as __matchUnreachable } from "@evobug_com/safe-ts-std/enum"; import { match } from "@evobug_com/safe-ts-std/enum";
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 { type JsonResult, parseJson } from "@evobug_com/safe-ts-std/json";
import { type Known, lookup, type Open } from "@evobug_com/safe-ts-std/open";
export type Issue = { readonly title: string; readonly state: Open<"todo" | "doing" | "done"> };
const ICONS = { todo: "circle", doing: "half", done: "check" } satisfies Record<Known<Issue["state"]>, string>;
export function readIssue(text: string): JsonResult<Issue> {
return __jsonParse<Issue>(text, __v0);
}
export function label(issue: Issue): string {
{ const __ms1 = issue.state; let __mv1: string; switch (__ms1.tag) {
case "todo": { __mv1 = "To do"; break; }
case "doing": { __mv1 = "Doing"; break; }
case "done": { __mv1 = "Done"; break; }
case "Unknown": { const { value } = __ms1; __mv1 = value; break; } default: __mv1 = __matchUnreachable(__ms1); } return __mv1; }
}
export function icon(issue: Issue): string {
return lookup(ICONS, issue.state, "question");
}
// ---- generated by safe-ts: JSON validators ----
type __T0 = { "title": string; "state": { tag: "doing"; value: "doing" } | { tag: "done"; value: "done" } | { tag: "todo"; value: "todo" } | { tag: "Unknown"; value: string }; };
function __v0(v: unknown, p: string): __JsonResult<__T0> {
if (!__jsonIsObject(v)) return __jsonFail(p, "object", v);
const __j1 = v["title"];
if (typeof __j1 !== "string") return __jsonFail(p + ".title", "string", __j1);
const __j2 = __j1;
const __j3 = v["state"];
if (typeof __j3 !== "string") return __jsonFail(p + ".state", "string", __j3);
const __j4 = ((__j3 === "doing" || __j3 === "done" || __j3 === "todo") ? { tag: __j3, value: __j3 } : { tag: "Unknown", value: __j3 }) as { tag: "doing"; value: "doing" } | { tag: "done"; value: "done" } | { tag: "todo"; value: "todo" } | { tag: "Unknown"; value: string };
const out: { "title": string; "state": { tag: "doing"; value: "doing" } | { tag: "done"; value: "done" } | { tag: "todo"; value: "todo" } | { tag: "Unknown"; value: string }; } = { "title": __j2, "state": __j4 };
return out;
}lookup(table, value, fallback) reads the table's row for a known value and gives fallback for Unknown. The fallback can't be left out, and ICONS[issue.state.tag] doesn't compile, since "Unknown" isn't a key. For a key that is any string, not an Open value, use getOwn instead.
value is the text as it came, so send issue.state.value back. JSON.stringify of the object itself writes {"tag":…,"value":…}, which the server doesn't expect. toOpen(known, text) makes an Open from text that doesn't come through parseJson (a route parameter).
Patch<T>: keep, clear or set a field
A PATCH request says, for each field, "leave it", "clear it" or "set it to this". With undefined and null both meaning "nothing", code ends up with two spellings of "clear" and a stray undefined that clears data on the server. Patch<T> names the three:
✓ Accepted0 diagnostics
ts
import type { Option } from "@evobug_com/safe-ts-std/result";
import { clear, keep, type Patch } from "@evobug_com/safe-ts-std/patch";
type Issue = { readonly title: string; readonly dueAt: Option<string> };
export function reschedule(title: Option<string>, dueAt: Option<string>): string {
const body: Patch<Issue> = { title: title ?? keep, dueAt: dueAt ?? clear };
return JSON.stringify(body);
}The object is already the wire form: keep is undefined (the key is left out), clear is a JSON null, a value sets the field. So JSON.stringify is the serializer, and it isn't reported. Only a field that may be missing (Option<T>, field?:) can be cleared; { title: clear } doesn't compile. On the server, parseJson<Patch<Issue>> gives the same three cases back. The Absence guide has more.
Truthiness
if (count) hides 0 along with undefined, v-if="name" hides "". strict-truthiness, an opt-in rule, reports a test of a value whose type includes number, string or bigint, and asks for the comparison that is meant.
A value that may be undefined (id?: string, Option<string>, a?.b, map.get(k)) has two values a test for truth treats as false, undefined and "", and replacing the test means deciding about both. id !== "" alone is true for undefined: the missing value now passes, and here prints acting as undefined. compare-misses-undefined, on by default, reports that comparison:
✕ Rejectedcompare-misses-undefined
ts
export function act(unitId?: string): string {
if (unitId !== "") return `acting as ${unitId}`;
return "pick a unit";
}✅ Accepted: both halves
✓ Accepted0 diagnostics
ts
export function act(unitId?: string): string {
if (unitId !== undefined && unitId !== "") return `acting as ${unitId}`;
return "pick a unit";
}Adopting them
- Turn the string helpers' results into the types: nothing to do,
safeHref,safeUrlandescapeRegExpreturn them already. - Declare the project's sanitizer with
defineSanitizer, and type props that take markup or a URL asHtmlorSafeUrl. The findings ofvue-v-htmlandvue-unsafe-urlon values that came from them go away; the rest are the values nobody checked. - For
btoaon ids: if they are numbers, nothing to do; if they are strings, narrow withisAsciiwhere they come in, or type themAscii. - Type server values from a list as
Open<K>, and look tables up withlookup. - Write request bodies that change records as
Patch<T>.
The proof types aren't in the prelude: a brand is worth as much as where it comes from, so it is imported from the module that makes it, and Open and Patch belong to the few files that talk to the server.