TypeScript#
The TypeScript generator emits types paired with
valibot schemas, so the model’s
constraints are checked at runtime rather than only described to the
compiler. Enable it with a [tool.model.typescript] table, which takes
out, and svelte for a Svelte module beside it:
[tool.model.typescript]
out = "src/catalog.mts"
Dependencies#
pnpm add valibot decimal.js
The schemas need valibot 1.2 or newer.
Generated code also imports this library’s own runtime,
@omniblack/model-runtime: the ModelMap and Ref that map and ref
fields hold, the helpers schemas decode through, Resp, and the
metadata types. It ships with model rather than on the npm
registry. The flake builds it as packages.<system>.model-runtime, a package
directory that pnpm-nix installs, so
the runtime always matches the generator that wrote the code:
env.PNPM_NIX_PACKAGES = pnpm-nix.lib.mkPackages pkgs {
"@omniblack/model-runtime" = model.packages.${system}.model-runtime;
};
"dependencies": { "@omniblack/model-runtime": "nix:" }
A generated module imports only the runtime names it uses.
A decimal field becomes a Decimal from
decimal.js, and every schema is built from valibot. A datetime field
becomes a Temporal.ZonedDateTime and a date field a
Temporal.PlainDate. Temporal is assumed to be a global rather
than imported — Node 26 and current browsers provide it. A url field becomes
the global URL.
A nerd_font_glyph field becomes a Glyph,
and its schema looks names up with lookup.
Both come from the libnerd_font npm package, which only a model with such a
field needs. It is an ES module that awaits its WebAssembly at the top level,
so a CommonJS consumer needs a bundler, whose target must allow top-level
await.
Structs#
Each struct exports three things under two names.
export const ProductSchema = v.object({ /* ... */ });
export interface Product {
sku: string;
name: string;
price: Decimal;
tags: Array<string>;
}
export const Product = Object.freeze({
type: "struct",
name: "Product",
// ... the rest of its metadata
fields: {
sku: { type: "string", /* ... */ schema: v.string() },
// ...
},
validate(input: unknown): Product {
return v.parse(ProductSchema, input);
},
} as const);
An interface and a const may share one name in TypeScript, because they live
in different declaration spaces. So Product is both the type you annotate
with and the object you call validate on:
const product: Product = Product.validate(await response.json());
ProductShape is also exported. It is the same field-by-field, and exists for
code that wants to name the shape separately from the validator.
The const also carries the struct’s metadata: each field’s
type, constraints and own schema, under fields.
Validating#
validate throws on failure. When you want the failure as a value instead,
hand the schema to v.safeParse yourself, and
read the issues it returns with v.flatten:
import * as v from "valibot";
import { ProductSchema } from "./catalog.mjs";
const result = v.safeParse(ProductSchema, input);
if (!result.success) {
console.error(v.flatten(result.issues));
}
Exporting the schema rather than only a validator is the point: a schema
composes. Wrap it in
v.array, put it in a larger
v.object, or v.pipe it
through your own checks, and the model’s constraints come along.
Coercion#
The schemas do more than reject bad input — they normalize it, so one shape comes out of several reasonable inputs:
An
integeraccepts abigint, a number that is a whole number, or a string of digits with an optional leading-, and always produces abigint.A
decimalaccepts a string, a number, or an existingDecimal, and always produces aDecimal.A
mapaccepts aModelMap, a realMapor a plain object, and always produces aModelMap, which compares keys by value. Class instances that are not plain objects are rejected, which is whatisPlainObjectis for. A plain object’s keys are text, so aninteger,estimate,booleanor integer enum key is read from its text first:{"1": "one"}gives the key1n.A
datetimeaccepts an existingTemporal.ZonedDateTime, or its RFC 9557 text,2026-10-06T21:00:00-04:00[America/New_York], and keeps the zone the text names. A plain RFC 3339 timestamp is read too:Zis the zoneUTC, and-04:00a zone fixed at that offset. ItstoJSONwrites the bracket form back, as Go and Python do. ATemporal.Instanthas no zone, so it is rejected; give it one withtoZonedDateTimeISO.A list or map field that stands in for emptiness accepts
nullandundefined, and produces[]ornew ModelMap().A scalar field (anything but a list, map, struct,
externaloropaque) reads"", a form’s cleared input, as missing. A field that is not required givesundefined. A required one reportsis required, as it does fornullandundefined. Only""counts: whitespace is a value, so trim it before validating if it should not be.
So v.parse is a decode step, not only a check. Its
output is what your code should hold.
Enums#
An enum becomes a frozen object,
a value union type sharing its name, and a v.enum schema.
TypeScript’s own enum keyword requires runtime support
and therefore is unsupported by many type stripping runtimes and is therefore
not used in our generated model.
export const Priority = Object.freeze({ low: 0, medium: 1, high: 2 } as const);
export type Priority = (typeof Priority)[keyof typeof Priority];
export const PrioritySchema = v.enum(Priority);
Unions#
Each variant gets a schema, an interface holding its tag and its value, and a validator; then the union itself gets all three.
export const AnimalDogSchema = v.object({
tag: v.literal("dog"),
value: PetSchema,
});
export interface AnimalDog { tag: "dog"; value: Pet }
export const AnimalDog = Object.freeze({ /* validate */ });
export type Animal = AnimalDog | AnimalCat;
export const AnimalSchema = v.variant("tag", [AnimalDogSchema, AnimalCatSchema]);
export const Animal = Object.freeze({ /* validate */ });
v.variant reads the discriminator first and then
applies only that variant’s schema, so a failure reports the variant’s own
problem rather than every variant’s.
Because the union is a plain type union, narrowing is just TypeScript:
const animal = Animal.validate(input);
if (animal.tag === "dog") {
// animal is AnimalDog here
}
The discriminator key is the model’s tag_name, which defaults to tag.
An inlined variant (inline_value: true) has no value. Its schema spreads
the struct’s entries beside the tag, and its interface extends the struct:
export const AnimalCatSchema = v.object({
...PetSchema.entries,
tag: v.literal("Cat"),
});
export interface AnimalCat extends Pet { tag: "Cat" }
Time windows#
A time field that declares a window exports it beside the struct:
export const TaskStartTimeWindow = Object.freeze({
from: "09:00",
to: "21:00",
});
The name is <Struct><Field>Window. It is metadata for a user interface, not
a constraint — nothing in the schema consults it. Time input behavior
states the behavior a time input built on it should have.
Routes#
A route emits an interface, a function calling the route on the Go server
(see Calling the server), and its URL helpers. There
is no TypeScript server wiring: the interface is there for a server you
write yourself.
export interface RouteBytes {
handle(request: OptimizedStop): Promise<Resp<OptimizedStop, ErrorResponse>>;
}
Resp<S, E> is the discriminated union @omniblack/model-runtime exports:
export type Resp<S, E> =
| ({ is_success: true } & S)
| ({ is_success: false } & E);
Narrow on is_success to tell the two apart. A route without a
success_response passes Record<never, never> as S, so its success arm is
only { is_success: true }.
Every route also exports its path pattern, and a route with {name}
placeholders exports a function that fills them in, percent-encoding each
value and writing an enum by its member name. A {name...} wildcard takes a
path value and keeps its / separators. The function writes an absolute
path’s leading / as %2F, and a . or .. segment as %2E or %2E%2E:
export const RouteStopPath = "/route/owners/{owner}/stops/{stop}/{priority}";
export function routeStopUrl(params: {
owner: NonNullable<StopLookup["owner"]>;
stop: NonNullable<StopLookup["stop"]>;
priority: NonNullable<StopLookup["priority"]>;
}): string;
Calling the server#
A module with routes, root endpoints, or REST resources, exports Client,
which calls the endpoints the Go output serves with
fetch(). Build one with the server’s base URL, which every endpoint’s
path follows:
const api = new Client(); // the server serving the page
const auth = new Client({
base: "https://auth.example.com",
init: { credentials: "include" },
});
base is "" by default, for the page’s own server, and may be a path such
as "/api" or an absolute URL. A trailing / is dropped, and one with a
query or fragment throws a RangeError. init is a RequestInit
every call sends.
Every call also takes an optional CallInit last: a RequestInit, for an
AbortSignal, credentials, or headers of your own, over the client’s, a
header at a time, plus a base overriding the client’s for that call alone:
await api.routeMe(request, { base: "https://staging.example.com" });
The client sets Accept, and Content-Type for a body, only where neither
init sets them.
Bodies are the model’s JSON wire form. An integer field’s bigint is
written as a bare number of every digit, and an integer in a response too
large for a number is read as a bigint. Both lean on
JSON.rawJSON and the source text a JSON.parse reviver is handed (ES2025),
which every current browser and Node 22 have.
Calling a route#
Each route is a method of Client named for it in camelCase, which has the
interface’s handle signature plus the init:
class Client {
routeStop(
request: StopLookup,
init?: CallInit,
): Promise<RouteResp<StopLookup, ErrorResponse>>;
}
RouteResp<S, E> is the interface’s Resp<S, E>, so the method still
implements it, plus the response’s HTTP status, on either arm:
export type RouteResp<S, E> = Resp<S, E> & {
readonly status: number;
readonly is_created: boolean; // 201
readonly is_accepted: boolean; // 202
readonly is_no_content: boolean; // 204
};
const resp = await api.routeMe(request);
if (!resp.is_success && resp.status === 401) {
// not logged in, as distinct from any other error
}
It fills the path’s placeholders from request, and throws a
RangeError when a field filling one is absent. A route with a body
sends request as JSON. A GET or HEAD route has none, so it sends each
field its path does not name in the query string: an enum by member name, a
list as its key repeated per item, and a field that is absent, null, or
"" not at all. The Go server reads them back from there (see
query strings).
A merge_patch route’s request,
and its interface’s, is a MergePatch<Request>, the type the REST
resources’ patch takes, and its nulls are sent as written.
A success status is decoded with the success_response’s schema, any other
with the error_response’s, and the two arms of the RouteResp tell them
apart.
A body neither reads, such as the router’s 404, throws an HttpError
carrying the status and the body’s text; a network failure throws as
fetch() does.
Root endpoints#
Each root endpoint is a member of
Client named for it in camelCase, a RootFiles below the endpoint’s
literal prefix. Each of its methods takes a /-separated path in the root,
"" for the root itself, and encodes each segment of it:
api.bookFiles.url("covers/moby dick.jpg"); // "/files/books/covers/moby%20dick.jpg"
api.bookFiles.dirUrl("covers"); // "/files/books/covers/"
const listing = await api.bookFiles.list("covers");
if (listing.is_success) {
for (const entry of listing.value) {
// entry.name, entry.dir, entry.size, entry.modified?
}
}
const file = await api.bookFiles.fetch("covers/moby dick.jpg");
if (file.is_success) {
const image = await file.value.blob();
}
url and dirUrl build URLs on the client’s server, for an <img> or a
link; a directory’s ends in /, where a browser is answered with its
index.html, when it has one. list reads a directory’s entries, each a
DirEntry whose modified is a Temporal.Instant. fetch returns a file’s
Response unread, to read as a blob, text, or stream. Either answers an
error with the server’s Problem, as a REST resource’s
methods do.
REST resources#
With [tool.model.go.rest] configured, a Client has
rest, an object holding each resource under its struct’s name:
const resp = await api.rest.Book.read(42n);
if (resp.is_success) {
resp.value; // Linked<Book, BookUrls>: a Book, with its URLs
resp.etag; // the row's entity tag, for a conditional write
} else {
resp.problem; // the RFC 9457 problem the server answered with
}
Method |
Request |
|---|---|
|
The collection’s path. |
|
The row’s URL on the client’s server, built as the server parses it. |
|
|
|
|
|
|
|
|
|
|
|
|
|
Only on a searchable table: |
|
Only on a struct that declares queries: a declared query, named for it in camelCase. |
|
|
|
Only on a struct something refers to. |
|
Only on a struct that holds a ref or that one names: a |
|
Only with rooted paths: the URL of a file on the client’s server. |
|
Only with rooted paths: |
With searchable tables, rest.search(text, { page }) searches them all.
Each declared query takes its params as a <Query><Struct>Params, and a query
with no params takes no params argument. A query that selects any number
of rows resolves to a Page. A query that finds one row resolves to that row,
and to a 404 problem when it finds none:
const page = await api.rest.Record.queries.inCity({ city: "Springfield" });
const account = await api.rest.Account.queries.byLogin({ login: "ada" });
A write given an etag sends it as If-Match, so it is refused with a 412
problem if the row changed since it was read. A listing is a Page, whose
next and prev are the tokens to pass back as page, read from the
response’s Link header; prev is "" for the first page, and either is
null when there is no such page. A table keyed by a path lists the rows
under a path no row has, so its read resolves to a Row | Page; tell them
apart with instanceof Page.
Each item’s fields is decoded, as a row is: a struct with a summary lists
its <Name>Summary, holding the fields the summary reads and the row’s key,
and one without lists an object of its key fields. A listing of several
structs’ rows, rest.search, referencedBy and related, is a union of
TypedItems, one per struct it can list, which an item’s type narrows:
const resp = await api.rest.search("ada");
if (resp.is_success) {
for (const item of resp.value.items) {
if (item.type === "Tag") {
item.fields.caption; // a TagSummary's
}
}
}
An item whose fields does not decode makes the call throw an HttpError.
Following a row’s URLs#
The server sends each row’s URLs: in Link headers
with the row, and in each listing item’s urls. The client keeps them on the
row or item it decoded, and client.follow follows one by name:
const resp = await api.rest.Tag.read(1n);
if (resp.is_success) {
const tag = resp.value; // Linked<Tag, TagUrls>
const related = await api.follow(tag, "related", { page });
// RestResp<Page<TagRelatedItem>>, from the URL the server sent
}
<Name>Urls types each URL a row has: self, a Link to the row,
summary, a Link to its listing item, and, where the struct serves them,
related and referencedBy, each a Link to a page of the listing, and
file, a FileLink. client.urls(row) reads
them, and client.get(link) fetches a Link already in hand, typed by it.
A FileLink is not fetched: link.url(client, field, ...steps) builds a
file’s URL, as fileUrl does. A listing item works the same way, so
api.follow(item, "related") lists what an item’s row is related to. An item
of a row the request may not read has no URLs, as it has no url.
A row or item carries its URLs under a symbol, so they are not part of its
fields: { ...row } keeps them, JSON.stringify and a request body leave
them out, and structuredClone drops them. client.urls of an object the
client did not decode, such as a fresh literal or a clone, throws a
TypeError. Because the symbol is an enumerable property, a test comparing
a decoded row with toEqual sees it; compare with toMatchObject instead.
A Linked<Tag, TagUrls> is still a Tag, so it can be passed to replace
as it is.
A method that takes a row’s keys, such as read(id), related(id) or
fileUrl(id, ...), takes a row or listing item the client decoded in their
place, and calls the URL the server sent with it rather than building one
from the keys. The row stands for all the keys of a struct keyed by several:
const resp = await api.rest.Tag.read(1n);
if (resp.is_success) {
const tag = resp.value;
await api.rest.Tag.related(tag, { page }); // GET of urls.related
await api.rest.Tag.replace(tag, { ...tag, caption: "renamed" });
}
Like client.urls, one given an object carrying no URLs throws a
TypeError. Keys still work, for when you hold only a key.
Resolving references#
A ref field holds a <Target>Ref, a class the module declares for every
top_level struct with a single key. Its resolve takes the Client to read
the row through, with client.rest.<Target>.read, so it resolves to the same
RestResp:
const resp = await book.author.resolve(api);
if (resp.is_success) {
resp.value; // Linked<Person, PersonUrls>
}
A ref into another model
takes that model’s Client, since its <Target>Ref is imported from there,
so it reads the row from that model’s server, wherever it is:
import { Client as AuthClient } from "./auth.ts";
const auth = new AuthClient({ base: "https://auth.example.com" });
const owner = await note.owner.resolve(auth);
A struct the server serves no REST resource of, or one keyed by a path,
does not resolve: its resolve rejects. So does every ref of a module
generated without [tool.model.go.rest].