Resolve a document
A document is a tree of nodes, and each node names a registration by $type. Resolving it is the same pattern in every domain: look each $type up in the registry for its kind, validate the node against the registration's schema, collect what is wrong with its path, and, only when nothing is, render. safeParseTree does the first three for the whole document in one call. This page builds that pattern with no framework: the output is a string. A renderer for a UI does the same with its own output.
Start from the Overview and quick start if registrations and registries are new.
A registry per kind
A kind is a group of registrations that play the same role. This document has two: leaves, which draw themselves, and containers, which draw their children. Each kind is its own registry, so a $type is looked up where it belongs and a leaf cannot be used where a container is meant.
Both kinds share one registration shape. A node's render receives its validated configuration and the already rendered children, which a leaf ignores. A registration says where its children are with childPaths, a list of key paths into the node: the stack keeps its children in children, so its path is ['children']; a leaf has none.
import * as z from 'zod/mini';
import { createRegistry, type BaseRegistration } from '@schema-engine/registry';
z.config(z.locales.en());
export interface Block extends BaseRegistration {
render(config: unknown, children: string[]): string;
}
const textSchema = z.object({ $type: z.literal('text'), value: z.string() });
const badgeSchema = z.object({
$type: z.literal('badge'),
label: z.string(),
tone: z.optional(z.enum(['info', 'success'])),
});
const stackSchema = z.object({
$type: z.literal('stack'),
gap: z.optional(z.enum(['small', 'large'])),
children: z.array(z.unknown()),
});
const text: Block = {
$type: 'text',
schema: textSchema,
metadata: { name: 'Text' },
render({ value }: z.output<typeof textSchema>) {
return `<p>${value}</p>`;
},
};
const badge: Block = {
$type: 'badge',
schema: badgeSchema,
metadata: { name: 'Badge' },
render({ label, tone = 'info' }: z.output<typeof badgeSchema>) {
return `<span class="badge badge-${tone}">${label}</span>`;
},
};
const stack: Block = {
$type: 'stack',
schema: stackSchema,
metadata: { name: 'Stack' },
childPaths: [['children']],
render({ gap = 'small' }: z.output<typeof stackSchema>, children: string[]) {
return `<div class="stack stack-${gap}">${children.join('')}</div>`;
},
};
export const leaves = createRegistry('Leaf', [text, badge]);
export const containers = createRegistry('Container', [stack]);The stack schema accepts children as a list of anything. Its children are validated one by one when safeParseTree reaches them, each against its own registration.
The resolve step
resolve is one call. safeParseTree reads each node's childPaths, validates the node with safeParseNode at its full path, walks into its children and keeps going after a problem, so every issue is collected and starts at the root. safeParseNode takes any object with a get(key), so one lookup can answer for both kinds.
import { safeParseTree, type NodeLookup, type SafeParseTreeResult } from '@schema-engine/registry';
import { containers, leaves, type Block } from './kinds';
export type Resolution = SafeParseTreeResult<Block>;
const blocks: NodeLookup<Block> = { get: (type) => containers.get(type) ?? leaves.get(type) };
export function resolve(document: unknown): Resolution {
return safeParseTree(blocks, document);
}A node whose own schema fails reports its issues and is not walked further, but its siblings still are. The result is either a tree that is safe to render or every issue found, never a half-valid tree. A value at a child path that is not a node, and a node that contains itself, are issues too, at the path where they sit.
The render step
Rendering takes a resolved tree and maps each node to output. It does no validation, because resolving has already done it. A ParsedNode holds the registration, the data its schema returned, the path of the node in the document and its children, keyed by the child path ('children' here; ['engine', 'controls'] would be 'engine.controls'), a list of nodes for an array:
import type { ParsedNode } from '@schema-engine/registry';
import type { Block } from './kinds';
export function render({ registration, data, children }: ParsedNode<Block>): string {
const inner = children.children;
const nodes = inner === undefined ? [] : [inner].flat();
return registration.render(data, nodes.map(render));
}Use it
A valid document renders. An invalid one reports an unknown $type and a configuration that its schema rejects, each with its path:
import { formatIssuePath } from '@schema-engine/registry';
import { render } from './render';
import { resolve } from './resolve';
const confirmation = {
$type: 'stack',
gap: 'large',
children: [
{ $type: 'text', value: 'Order 1042 confirmed' },
{
$type: 'stack',
children: [
{ $type: 'badge', label: 'Paid', tone: 'success' },
{ $type: 'badge', label: 'Shipping soon' },
],
},
],
};
const broken = {
$type: 'stack',
children: [
{ $type: 'text', value: 'Order 1042 confirmed' },
{
$type: 'stack',
children: [
{ $type: 'badge', label: 5 },
{ $type: 'chip', label: 'Shipping soon' },
],
},
],
};
for (const document of [confirmation, broken]) {
const resolution = resolve(document);
if (resolution.success) console.log(render(resolution.tree));
else for (const issue of resolution.issues) console.log(`${formatIssuePath(issue.path)}: ${issue.message}`);
}<div class="stack stack-large">
<p>Order 1042 confirmed</p>
<div class="stack stack-small">
<span class="badge badge-success">Paid</span>
<span class="badge badge-info">Shipping soon</span>
</div>
</div>children[1].children[0].label: Invalid input: expected string, received number
children[1].children[1].$type: No registration for $type 'chip'.Each issue names the node that failed: children[1].children[0].label is the label of the first badge inside the second child of the root. A tool can mark that node in an editor, and a log can say exactly what to fix. formatIssuePath writes the path this way.
Take it further
- A document a server sends. Serialized documents validates a document that arrives over the network and shows the issues a caller sees.
- Override a default. Offer
[...defaults, ...extra]where you build a registry, so replacing a registration is a change to a list: Read-only and mutable registries. - Keep the registry out of the global scope. Pass a registry to the code that needs it, as the forms engine does. There is no module-level registry to fall back to.
- A kind of the forms engine. Elements, recipes, actions and axes are kinds like these: What the forms engine registers.