API reference

createFormEngine

interface CreateFormEngineOptions<TElements, TRecipes, TActions, TLayout> {
	elements?: TElements;
	recipes?: TRecipes;
	actions?: TActions;
	/** Custom validation rules, after the built-in ones and the validations elements declare; the last `$type` wins. */
	validations?: readonly ValidationRegistrationConstraint[];
	/** Extra schema metadata entries; copied, with every registration's entry written over it. */
	catalog?: SchemaMetadataCatalog;
	/**
	 * The layout theme: a compiled theme from `createLayoutTheme`, or inline
	 * `{ grid, appearance }` options. `grid` holds breakpoint thresholds, gap tokens and the
	 * default min column width; `appearance` is the list of axes built with `defineAxis`
	 * (default `builtInAxes`: `size` and `surface`). The last axis of a `$type` wins.
	 */
	layout?: TLayout;
	/** Turns an issue into the text to show: the one formatter both renderers read. Inherited by `extend()`. */
	formatIssue?: FormIssueFormatter;
	/**
	 * The request function every request the engine makes goes through; the global `fetch` by default. Inherited by
	 * `extend()`.
	 */
	fetch?: FormFetch;
	/**
	 * Where a CSRF token comes from, from `csrf.fromMeta`, `csrf.fromCookie` or `csrf.custom`. Off unless set.
	 * Inherited by `extend()`.
	 */
	csrf?: CsrfPolicy;
}

function createFormEngine<
	const TElements extends readonly ElementRegistrationConstraint[] = readonly [],
	const TRecipes extends readonly RecipeRegistrationConstraint[] = readonly [],
	const TActions extends readonly ActionRegistrationConstraint[] = readonly [],
	const TLayout extends LayoutInput = Record<never, never>,
>(
	options?: CreateFormEngineOptions<TElements, TRecipes, TActions, TLayout>,
): FormEngineFromOptions<TElements, TRecipes, TActions, TLayout>;

FormEngineFromOptions is the FormEngine typed from the merged registration lists. layout is accepted by createFormEngine and by createRadiantFormEngine, which forwards it. Pass one theme compiled with createLayoutTheme (from @schema-engine/layout) to several engines and they carry the same data-se-theme and the same stylesheet content (how each renderer emits it); inline options compile a theme of the engine's own. engine.extend() does not take layout; extended engines inherit the source engine's layout theme, which engine.getLayout() returns (id, grid, axes, appearance, css).

Each array is structurally constrained: $type, a Standard Schema (~standard.validate), and the registration's render/execute function. Duplicate $type values follow last-wins at runtime. Tuples and inline arrays use last-wins typing; open T[] values use a union of configs for the same $type. Spread shared registration barrels and append overrides when needed.

formatIssue is the engine's issue formatter, engine.getIssueFormatter(). engine.fetch is the request function with the CSRF policy applied, and engine.getCsrf() returns the policy. engine.getValidationRegistry() is the registry a state container is made with.

engine.getSchemaCatalog() returns the metadata the JSON Schema export reads (title, description and category by id, such as element:input), not a list of what is registered. Read what is registered with engine.getAllElements(), getAllRecipes(), getAllActions() and engine.getValidationRegistry() (What the engine registers).

validations takes validation registrations ($type, schema, metadata, category, handler) and is not typed per engine: field rules keep their $type string. See Custom and async rules.

Authors supply schema input. After validation, render functions receive schema output. Register elements with defineInput / defineStatic so the schema input/output relationship is preserved.

defineInput / defineStatic

import { defineInput, elementChildrenSchema } from '@schema-engine/forms';

export const FieldSetRegistration = defineInput({
	$type: 'fieldSet',
	schema: FieldSetConfigSchema,
	metadata: { name: 'FieldSet', category: 'input' },
	render: FormFieldSet,
});

An input declares what its control writes with value, a function of the configured element that returns a Standard Schema (value: ({ options }) => z.literal(options.map((option) => option.value))). defineInput requires it, except on a container (a schema that declares elements; containerKind may sit beside it), whose value is its children's, and createFormEngine rejects an input that has none. defineStatic has none. The two helpers set a kind ('input' or 'static') on the registration, which is what the engine reads, not the element's metadata.category; a registration written by hand states its kind. See Submitted values.

defineInput keeps the concrete schema type. Container schemas should use elementChildrenSchema for elements; the engine validates those children against its registrations. The render function then receives frozen, normalized children, not authoring JSON.

Default element contracts

@schema-engine/forms/default-elements holds the contract of each of the 18 default elements (input, textarea, number, select, checkbox, checkbox-group, switch, radio, slider, combobox, drop-zone, fieldSet, input-otp, phone-input, masked-input, arrayElements, submit and submission-alert): its schema (CheckboxFieldConfigSchema), the types and the xFieldValue declaration that go with it, and the contract itself (CheckboxElementContract). A contract is a registration without render and validations, the part of an element that belongs to one renderer, so every renderer of an element agrees on its schema and on the value its control writes. defaultElementContracts is the registry of all of them, built with createRegistry and duplicates: 'error'.

A renderer binds render to a contract. For one element, spread the contract into defineInput, which checks render against the schema output as it does for any element:

import { createFormEngine, defineInput } from '@schema-engine/forms';
import { CheckboxElementContract, type CheckboxFieldConfig } from '@schema-engine/forms/default-elements';

const checkbox = defineInput({
	...CheckboxElementContract,
	render: (config: CheckboxFieldConfig) => `<input type="checkbox" name="${config.name}">`,
});

export const engine = createFormEngine({ elements: [checkbox] });

A renderer that draws every element binds the whole registry with bindRegistry from @schema-engine/registry: a contract without a binding fails to compile, and ElementBindings<typeof defaultElementContracts> with satisfies checks each render against its own schema. @schema-engine/forms-radiant does this; the registry items of Forms React spread one contract each, because they are copied one at a time. See One contract, a binding per renderer.

FormEngine

FormEngine retrieves registered elements, recipes, and actions; validates form configuration; and generates JSON Schema and authoring catalog artifacts. defineForm and validateForm return NormalizedFormConfig. Use validateElement for a standalone field that is not already inside a form.

engine.getElement('text');
engine.getRecipe('card');
engine.getAllRecipes();
engine.defineForm(config);
engine.validateForm(json);
engine.validateForm(json, { values: Profile });
engine.safeValidateForm(json);
engine.submissionSchema(config);
engine.validateElement(field);
engine.extend({ actions: [extraAction] });
engine.getFormConfigStandardSchema();
engine.describeViewCatalog();

validateForm throws a FormValidationError when the form is invalid.

defineForm with a literal config returns a NormalizedFormConfig carrying the values type its elements declare (ValuesOf), and FormValues when the config is not a literal. validateForm(json, { values }) binds the application's Standard Schema: the form parses every submission with it after the schema derived from the form, and the values type is its output. submissionSchema(config) is that derived schema, with ~standard.jsonSchema (its input() and output() throw for a value schema that has no JSON Schema) and a partial for defaultValues. DefaultValuesOf<TValues>, exported with ValuesOf, is the type of defaultValues: the values type with every key optional at every depth and an empty value allowed in place of any leaf field. The rows of a list are as the values type has them: an optional scalar row may be empty, and the rows of a field whose declared value is a list (a checkbox group) may not. safeValidateForm runs the same validation and returns a result instead:

type FormValidationIssue = {
	message: string;
	path: ReadonlyArray<PropertyKey>; // ['steps', 0, 'elements', 2, 'grid', 'width']
	code?: string; // the schema's code on a schema issue, such as 'too_small'
	/** Its details, such as `{ origin: 'string', minimum: 3, inclusive: true }`. */
	params?: Readonly<Record<string, unknown>>;
};

type FormValidationResult<T> = { success: true; data: T } | { success: false; issues: FormValidationIssue[] };

params holds the details a code reports and only those that are set: values, expected, origin, minimum, maximum, inclusive, format, pattern and keys. error.issues on a FormValidationError has the same shape. See Form configuration errors for the paths and a copy-pasteable example.

Use io: 'input' for authoring input (where defaulted fields are optional) or io: 'output' for parsed output. Every generator defaults to 'input', since the export describes what authors write. An element whose schema pipes a transform (Radiant's input-otp) has no JSON Schema for its output side, so io: 'output' throws for an engine that registers one.

The collection also holds the validation-rule entry: the union of every registered rule, which the form config schema defines once and each element's rules refers to.

engine.generateJSONSchemaCollection(); // io: 'input'
engine.generateFormConfigSchema(); // io: 'input'
engine.generateActionConfigSchema('submit', { io: 'output' });

In these schemas an appearance pick is closed over the axes its owner declares. The form and each step list every axis of the layout theme; an element lists the axes in its appearanceAxes and a recipe slot the axes in the recipe's appearanceAxes, each as an enum of the axis's values. Any other axis is rejected, as it is by validateForm. The export checks elements, the children of a fieldset or an array row (typed as a union of every element's schema) and the recipe slots. It does not check the appearance of an element whose schema is lazy; validateForm does.

getFormConfigStandardSchema() and getActionConfigStandardSchema() expose the same input/output converters through the Standard JSON Schema contract.

How each schema is exported

Standard Schema is the contract for a definition; JSON Schema is what the export gives AI, agents and tools. One rule reads the schema of every registration kind the export lists: an element, an action, a validation rule and a recipe slot.

  1. A Zod schema (classic or Mini) goes through the Zod converter. The export composes an element's, action's or slot's Zod schema before converting it: it closes appearance over the axes the owner declares, types an element's children and rules, and adds an action's envelope (id, enabled, triggers). Classic Zod also provides ~standard.jsonSchema, but its output is already final and cannot take part in that composition, so reading it would drop those additions and export a classic Zod element differently from the same element written in Zod Mini. Zod therefore always goes through the converter.
  2. Any other schema that provides Standard JSON Schema (~standard.jsonSchema) is exported as what its input() or output() returns for the io and target you ask for, embedded as described below. The export adds no appearance, children or rules to it, so state them in the schema.
  3. A schema that provides neither is listed by its shape: an element by its $type and its appearance axes, an action or a rule by its $type, a recipe slot as an open object with its appearance axes.

How a rule 2 schema is embedded in the export:

  • Its $schema is dropped, because the document it is embedded in already declares the dialect.
  • A schema whose $refs point into itself from its root (ArkType writes a recursive type as a root $ref with $defs) is moved to a place where those references still resolve. In a document it goes under the document's $defs (or definitions) as embedded-1, embedded-2 and so on, with its references rewritten to that place. In generateJSONSchemaCollection() it becomes an entry of its own, referred to by its URI. A schema that is already the root of a collection entry, or that sets its own $id, stays as it is. References stay #/... pointers, which AI tool APIs resolve, rather than $id URIs. Only the schema's own resource is rewritten: a subschema that sets its own $id is a resource of its own, so its references stay relative to it.
  • A plain-name anchor ($anchor, $dynamicAnchor, or a draft-07 $id: '#node') is global to a document, so two rule 2 schemas that each declare node would declare it twice. Each schema's anchors, and the #node references to them, are renamed to carry its place (embedded-1-node), whether it is moved to the definitions or embedded where it stands.
  • A document (not the collection) lists catalog metadata (title, description, componentType, category) on every registration. It adds them beside a rule 2 schema's keywords where the schema does not set the same key. They are annotations, so what the schema accepts does not change.
  • A converter that throws for the target you ask for (ArkType supports only draft-2020-12 and draft-07, so it throws for openapi-3.0) does not stop the export. That schema is listed by its shape, as in rule 3, and a warning names its vendor and the target.

submissionSchema(config) reads each value schema by rules 1 and 2 and embeds it the same way. It throws for a value schema that has neither, rather than listing it by its shape.

Which libraries export exactly, checked against these versions (ArkType is not a dependency of this repository):

LibraryVersionExports exactly
Zod (classic and Mini)4.6.5Through the Zod converter (rule 1), the same either way
ArkType2.2.10Yes, ~standard.jsonSchema (rule 2), for draft-2020-12 and draft-07
Valibot1.5.0No: listed by shape (rule 3)
Effect Schema3.22.2No: listed by shape (rule 3)
A schema you write-Yes, when it sets ~standard.jsonSchema (rule 2)

Zod Mini does not implement ~standard.jsonSchema, and Valibot and Effect Schema do not without an adapter, so the Zod converter and the listing by shape stand in for them. A schema of your own that spreads a library's ~standard and adds jsonSchema (built with that library's converter) is exported exactly.

State container, server errors and CSRF

EntryExportsGuide
@schema-engine/forms/state-containercreateFormStateContainer, the FormStateContainer, FormStateSnapshot and FormIssueFormatter types, selectFieldState, selectValue, toFieldArrayValue, toHydration and FORM_ROOTState container
@schema-engine/forms/server-errorsfromProblemDetails, fromJsonApiErrors and ServerErrorsInputErrorServer errors
@schema-engine/forms/csrfcsrf (fromMeta, fromCookie, custom), csrfFieldFor and the CsrfPolicy typeCSRF
@schema-engine/forms/testingformStateContainerConformance(createStore, { describe, test }) and the ConformanceRunner typeState container

FormValidationFailure, which container.validate() rejects with when a rule cannot run, is exported by @schema-engine/forms itself.

createFormRuntime, which a renderer calls for each form it draws, is also exported by @schema-engine/forms. An app does not call it: the Form runtime page of the Renderer authors section describes it.

RecipeRegistration

interface RecipeRegistration<TType, TSchema, TRender = unknown> {
	$type: TType;
	kind: 'single-step' | 'wizard';
	slots: Array<'shell' | 'header' | 'progress' | 'actions'>;
	schema: TSchema;
	metadata: RecipeMetadata;
	/** Slot config applied beneath the view's own slot config. */
	slotDefaults?: Partial<Record<'shell' | 'header' | 'progress' | 'actions', Record<string, unknown>>>;
	/** Appearance axes each slot supports, for example `{ shell: ['size', 'surface'] }`. */
	appearanceAxes?: Partial<Record<'shell' | 'header' | 'progress' | 'actions', readonly string[]>>;
	/** The schema of each declared slot, any Standard Schema; set by `defineFormRecipe`. */
	slotSchemas?: Partial<Record<'shell' | 'header' | 'progress' | 'actions', StandardSchemaV1>>;
	render: TRender;
}

slotSchemas is what the JSON Schema export lists a recipe's slots from, and schema is what validates a view. A registration written by hand may leave slotSchemas out; when it sets them, they must list exactly its slots, each a Standard Schema, or createFormEngine throws.

The recipe protocol (the slots, the kinds, the rules that check them) is declared once per domain with defineRecipeProtocol from @schema-engine/layout; forms declares shell | header | progress | actions and single-step | wizard. See Custom recipes.

See Engine and registrations for the registrations an engine takes and the rules they follow.