# AI & Skills # AI & Skills [#ai--skills] Feed RilayKit docs to AI agents directly, or install the RilayKit skill for context-aware assistance. ## LLM-Ready Documentation [#llm-ready-documentation] | Endpoint | Description | | ---------------------------------- | ----------------------------------------------- | | [`/llms.txt`](/llms.txt) | Index of all pages with titles and descriptions | | [`/llms-full.txt`](/llms-full.txt) | Complete documentation as plain markdown | Use these with any AI tool that supports `llms.txt`. ## Install the RilayKit Skill [#install-the-rilaykit-skill] The skill gives coding agents deep knowledge of the framework: builder patterns, validation, conditions, hooks, and real-world patterns. It uses progressive disclosure — only the relevant reference loads into context when needed. ```bash npx skills add andyoucreate/rilaykit -a claude-code ``` ```bash npx skills add andyoucreate/rilaykit --all ``` ```bash npx skills add andyoucreate/rilaykit -g --all ``` ## What's Included [#whats-included] Three reference files cover the API: | Reference | Coverage | | --------- | ----------------------------------------------------------------------------------- | | Core | `ril` instance, component registry, Standard Schema validation, `when()` conditions | | Forms | Form builder, row layouts, components, field/form/condition hooks | | Workflow | Flow builder, navigation, step data helpers, persistence, analytics | ## Supported Agents [#supported-agents] Works with any agent in the [skills.sh](https://skills.sh) ecosystem: Claude Code, Cursor, Windsurf, OpenCode, and 40+ more. ## Verify Installation [#verify-installation] Ask your agent: ``` How do I create a multi-step workflow with conditional steps using RilayKit? ``` It should reference the `@rilaykit/workflow` builder API with `when()` conditions — not generic form library patterns. # API Reference # API Reference [#api-reference] Package mains are React-free (RSC/server-safe): import builders, validators, and schema compilers from `@rilaykit/core`, `@rilaykit/forms`, `@rilaykit/workflow`, `@rilaykit/agent` (or the all-in-one `rilaykit`). Import components and hooks from the matching `/react` entry. *** ## @rilaykit/core [#rilaykitcore] Catalog (`ril`), validators, conditions, effects, and error classes shared by all packages. ### ril [#ril] The immutable catalog: registered components, tools, and parts. Every mutation returns a **new instance**. ```ts import { ril } from '@rilaykit/core'; import { z } from 'zod'; const catalog = ril.create() .component('email', { description: 'Email input', propsSchema: z.object({ label: z.string() }), renderer: (ctx) => ( ctx.field?.onChange(e.target.value)} onBlur={ctx.field?.onBlur} /> ), }) .tool('lookup_company', { description: 'Fetch company data by SIREN', inputSchema: z.object({ siren: z.string() }), }) .part('text', { renderer: ({ part }) =>

{(part as { text: string }).text}

}); ``` | Method | Returns | Description | | ----------------------------------------------------------- | --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `ril.create()` | `ril` | New empty catalog | | `.component(type, entry)` | new instance | Register a component (`entry`: `name?`, `description?`, `propsSchema?`, `propsJsonSchema?`, `renderer?`, `defaultProps?`, `validation?`, `meta?`, `replace?`) | | `.tool(name, entry)` | new instance | Register a tool (`description?`, `inputSchema?`, `inputJsonSchema?`, `renderer?`, `meta?`, `replace?`) | | `.part(type, entry)` | new instance | Register a message-part renderer (`renderer` required) | | `.use(plugin)` | new instance | Apply a `RilayPlugin` (`(r) => r.component(...)...`) | | `.renderers({ components?, tools?, parts? })` | new instance | Attach renderers to already-registered entries | | `.getComponent(id)` / `.getTool(name)` / `.getPart(type)` | entry or `undefined` | Lookup | | `.getAllComponents()` / `.getAllTools()` / `.getAllParts()` | arrays | Enumerate | | `.hasComponent(id)` | `boolean` | Existence check | | `.validateProps(type, props)` | `PropsValidationResult` | Check props against the component's `propsSchema` | | `.validate()` / `.validateAsync()` | `string[]` / `Promise` | Configuration validation | | `.getStats()` | `{ total, components, tools, parts }` | Counts | | `.clone()` / `.removeComponent(id)` / `.clear()` | new instance | Immutability utilities | Registering an existing key throws `DuplicateError` unless the entry sets `replace: true`. ### ComponentRenderContext [#componentrendercontext] Passed to every component renderer: ```ts interface ComponentRenderContext> { readonly id: string; readonly props: TProps; readonly field?: FieldBinding; // value, onChange, onBlur, error?, disabled?, isValidating?, touched? readonly conditions?: FieldConditions; // visible, disabled, required, readonly readonly children?: React.ReactNode; readonly meta?: Record; } ``` `field.error` and `conditions.{required,disabled,readonly}` carry what WCAG-AA rendering needs (`aria-invalid`, `role="alert"`, ARIA attributes); `field.touched` gates error display. ### Validators [#validators] All built-ins implement [Standard Schema](https://standardschema.dev) (`StandardSchemaV1`) and mix freely with Zod, Valibot, ArkType, etc. ```ts import { required, email, url, minLength, maxLength, pattern, number, min, max, custom, async, combine, } from '@rilaykit/core'; ``` | Validator | Signature | | ------------------------- | ------------------------------------------------------- | | `required` | `required(msg?)` | | `email` | `email(msg?)` | | `url` | `url(msg?)` | | `minLength` / `maxLength` | `minLength(min, msg?)` / `maxLength(max, msg?)` | | `pattern` | `pattern(regex, msg?)` | | `number` | `number(msg?)` | | `min` / `max` | `min(val, msg?)` / `max(val, msg?)` | | `custom` | `custom(fn, msg?)` — sync `(value: T) => boolean` | | `async` | `async(fn, msg?)` — `(value: T) => Promise` | | `combine` | `combine(...schemas)` — merge Standard Schemas | ### Conditional Logic [#conditional-logic] `when(field)` returns a `ConditionBuilder`: ```ts import { when } from '@rilaykit/core'; when('role').equals('admin').or(when('permissions').contains('write')) when('address.country').equals('FR') // nested paths work ``` **Operators**: `.equals()`, `.notEquals()`, `.greaterThan()`, `.lessThan()`, `.greaterThanOrEqual()`, `.lessThanOrEqual()`, `.contains()`, `.notContains()`, `.in()`, `.notIn()`, `.matches()`, `.exists()`, `.notExists()`. **Combinators**: `.and(condition)`, `.or(condition)`. **Terminals**: `.build()` → `ConditionConfig`, `.evaluate(data)` → `boolean`. A field with only `conditions.required` (no `validation` block) is enforced: submit blocks while the condition holds and the field is empty. ### Field Effects [#field-effects] `onChange(fieldId, handler)` declares reactive field-to-field logic — `fieldId` is the field being **watched**, not the field the effect is declared on. ```ts import { onChange } from '@rilaykit/core'; onChange('country', async (value, { setValue, setProps }) => { setValue('city', ''); setProps('city', { options: await fetchCities(value) }); }); ``` | Context method | Description | | -------------------------- | ------------------------------------ | | `setValue(fieldId, value)` | Set another field's value (cascades) | | `setProps(fieldId, props)` | Merge dynamic props into a field | | `getValues()` | Snapshot of all form values | | `getFieldValue(fieldId)` | One field's current value | Protections: cascade depth cap (10), cycle detection, async abort (only the latest handler wins). Effects run regardless of field visibility; a repeatable-template effect watching a global field fans out per live row with row-scoped `setValue`/`getFieldValue`. ### Errors and Constants [#errors-and-constants] ```ts import { RilayError, ValidationError, DuplicateError, NotFoundError } from '@rilaykit/core'; ``` `RilayError` carries `code: RilayErrorCode` and `meta?`. Subclasses: `ValidationError` (`VALIDATION`), `DuplicateError` (`DUPLICATE`), `NotFoundError` (`NOT_FOUND`), `InvalidSchemaError` (`INVALID_SCHEMA`), `ConfigurationError` (`CONFIGURATION`), `MaxDepthExceededError` (`MAX_DEPTH`). `FORM_LEVEL_ERROR_KEY` (`'__form__'`) and `FORM_LEVEL_ERROR_CODE` (`'FORM_LEVEL'`) are the reserved bucket/code of the path-keyed error map (see `useFormErrors`). *** ## @rilaykit/forms [#rilaykitforms] Builder and schema compiler from `@rilaykit/forms`; components and hooks from `@rilaykit/forms/react`. ### Components [#components] ```tsx import { Form } from '@rilaykit/forms/react';
``` #### `Form` [#form] Compound root (`Form.Body`, `Form.Field`, `Form.Submit`, `Form.List`). Wraps `FormProvider`. | Prop | Type | Description | | -------------------------- | ------------------------------------ | --------------------------------------------------------------------------------------------------------- | | `of` | `FormConfiguration \| form` | Built configuration or builder (auto-built) | | `defaults?` | `Record` | Initial values. Live upgrade channel: changing it re-seeds **untouched** fields; edited fields are immune | | `onSubmit?` | `(data) => void \| Promise` | Receives only visible fields' values | | `onFieldChange?` | `(fieldId, value, formData) => void` | Per-change callback | | `onFieldsRemove?` | `(fieldIds, formData) => void` | Fired when repeatable-row removal deletes keys | | `onRepeatableOrderChange?` | `(order) => void` | Live row-order mirror | | `defaultRepeatableOrder?` | `Record` | Row order to restore | | `instanceId?` | `string` | Owner identity; same config + different `instanceId` = different form | | `conditionValues?` | `Record` | Read-only extra values conditions may reference (cross-step) | | `className?` | `string` | CSS class | #### `Form.Body` / `Form.Field` / `Form.Submit` / `Form.List` [#formbody--formfield--formsubmit--formlist] | Component | Props | | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | | `Form.Body` | `children?: ({ rows }) => ReactNode`, `className?` — renders all visible rows by default | | `Form.Field` | `id`, `config?`, `disabled?`, `overrides?` (extra props merged in), `forceVisible?`, `className?` | | `Form.Submit` | `children?: ReactNode \| (({ submitting, submit }) => ReactNode)`, `className?` | | `Form.List` | `id`, `children?: (ctx: FormListContext) => ReactNode`, `className?` — `ctx`: `items`, `add()`, `remove(key)`, `move(from, to)`, `canAdd`, `canRemove` | `FormProvider` is the lower-level provider (`formConfig`, `defaultValues`, same callbacks); `useForm()` reads its context: `formConfig`, `conditionsHelpers`, `validateField`, `validateForm`, `validateFormLevel`, `submit`. ### form (FormBuilder) [#form-formbuilder] ```ts import { form } from '@rilaykit/forms'; const contact = form.create(catalog, 'contact') // formId optional .add({ id: 'email', type: 'email', props: { label: 'Email' } }) .add( // multiple fields in one call = one row { id: 'firstName', type: 'input', props: { label: 'First' } }, { id: 'lastName', type: 'input', props: { label: 'Last' } }, ) .setValidation({ mode: 'onTouched', // when a field FIRST validates (default) reValidateMode: 'onChange', // re-validation after an error (default) validate: z.object({ password: z.string().min(8), confirmPassword: z.string() }) .refine((d) => d.password === d.confirmPassword, { message: "Passwords don't match", path: ['confirmPassword'], // routed to that field's errors }), }); ``` | Method | Description | | --------------------------------------------------------------------- | -------------------------------------------------------------------------------- | | `.add(...fields)` / `.add([fields])` | Add fields; one call = one row | | `.addSeparateRows(fields)` | Each field on its own row | | `.addRepeatable(id, (r) => r.add(...).min(n).max(n).defaultValue(v))` | Repeatable group (strictly one level — no nesting) | | `.setValidation(config)` | Form-level `FormValidationConfig`: `validate?`, `mode?`, `reValidateMode?` | | `.setSubmitOptions(options)` | Default submit options | | `.addFieldValidation(fieldId, config)` | Attach validation after creation | | `.addFieldConditions(fieldId, conditions)` | Attach `ConditionalBehavior` (`visible?`, `disabled?`, `required?`, `readonly?`) | | `.updateField(fieldId, updates)` / `.removeField(fieldId)` | Mutate fields | | `.getField(id)` / `.getFields()` / `.getRows()` | Read back | | `.setId(id)` / `.clear()` / `.clone(newId?)` | Utilities | | `.validate()` | Structural issues as `string[]` | | `.build()` | `FormConfiguration`; throws on invalid | | `.toJSON()` / `.fromJSON(json)` / `.getStats()` | Serialization, stats | **Validation timing** — form-level, two-phase (mirrors React Hook Form): * `mode`: `'onSubmit' | 'onBlur' | 'onChange' | 'onTouched' | 'all'` — when a field first validates. Default `'onTouched'` (first blur, then live). RHF's own default is `onSubmit`; RilayKit keeps its historical behavior. * `reValidateMode`: `'onChange' | 'onBlur' | 'onSubmit'` — re-validation once a field has errored. Default `'onChange'` (errors clear live). * Per field: `validation: { validate, debounceMs }`. `debounceMs` defers change-triggered async validation only; blur and submit always validate immediately. * Submit always validates and marks errored fields `touched`, so touched-gated renderers show submit errors, and they clear live. **Error routing** — cross-field issues from `setValidation`'s `validate` are written to the store by `issue.path`: a path naming a known field attaches to that field (tagged `FORM_LEVEL_ERROR_CODE`); empty or unmatched paths land in the `__form__` bucket read by `useFormErrors()`. Form-level rules re-run on the same `mode`/`reValidateMode` cadence and on repeatable row add/remove/move. ### Hooks [#hooks] All from `@rilaykit/forms/react`, Zustand-backed: field-level hooks re-render only when their field changes (a keystroke re-renders only the typed field). | Field hook | Returns | | ---------------------------------- | ---------------------------------------------------------------------- | | `useFieldValue(fieldId)` | `T` | | `useFieldErrors(fieldId)` | `FieldError[]` (includes routed cross-field issues) | | `useFieldTouched(fieldId)` | `boolean` | | `useFieldValidationState(fieldId)` | `'idle' \| 'validating' \| 'valid' \| 'invalid'` | | `useFieldConditions(fieldId)` | `{ visible, disabled, required, readonly }` | | `useFieldState(fieldId)` | `{ value, errors, validationState, touched, dirty }` | | `useFieldProps(fieldId)` | `Record` | | `useFieldActions(fieldId)` | `{ setValue, setTouched, setErrors, clearErrors, setValidationState }` | | Form hook | Returns | | ----------------------------------------------------------- | --------------------------------------------------------------------------------------- | | `useFormErrors()` | `FieldError[]` — the `__form__` bucket; use for a form-level error banner (`aria-live`) | | `useFormValues()` | `Record` | | `useFormSubmitting()` / `useFormValid()` / `useFormDirty()` | `boolean` (`isValid` counts the whole map, `__form__` included) | | `useFormSubmitState()` | `{ isSubmitting, isValid, isDirty }` | | `useFormActions()` | `{ setValue, setTouched, setErrors, setSubmitting, reset, setFieldConditions }` | | `useRepeatableKeys(repeatableId)` | `string[]` — live row keys | | `useFormStoreApi()` | Store ref for imperative `getState()` reads | | `useForm()` | Form context (config, validation, `submit`) | `reset(values?, repeatableOrder?)` restores defaults or explicit values; the second argument restores repeatable row order. ### Server-Driven Forms (JSON schemas) [#server-driven-forms-json-schemas] ```ts import { compileForm, fromSchema, validateSchema, isFormSchema } from '@rilaykit/forms'; const { formConfig, defaultValues } = compileForm(schema, catalog, { bindings }); ``` | Export | Description | | -------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `compileForm(schema, catalog, options?)` | Compile a `FormSchema` → `{ formConfig, defaultValues? }`. `options.bindings` resolves custom validator/effect string references; `options` can also enable per-field props validation | | `fromSchema(schema, catalog, registry?)` | Same result, registry-style signature | | `validateSchema(schema, catalog, registry?)` | Throws `SchemaValidationError` (with pathed `issues[]`) on invalid structure | | `isFormSchema(value)` | Type guard | ```ts interface FormSchema { readonly version?: 1; readonly id: string; readonly defaultValues?: Record; readonly fields?: FormSchemaField[]; // flat layout readonly rows?: FormSchemaRow[]; // row-based layout (incl. repeatables) readonly validation?: FormSchemaValidationConfig; // { rules?, mode?, reValidateMode? } readonly submitOptions?: SubmitOptions; } interface FormSchemaField { readonly id: string; readonly type: string; readonly props?: Record; readonly validation?: { rules?: ValidationDescriptor | ValidationDescriptor[]; debounceMs?: number }; readonly conditions?: ConditionalBehavior; readonly effects?: FieldSchemaEffect[]; } // rules: 'required' | 'email' | 'url' | 'number' (shortcuts) // or { type: string; message?: string; params?: Record } interface SchemaRegistry { // alias: Bindings readonly validators?: Record; readonly effects?: Record; } ``` *** ## @rilaykit/workflow [#rilaykitworkflow] Builder and flow-schema compiler from `@rilaykit/workflow`; components and hooks from `@rilaykit/workflow/react`. ### Components [#components-1] ```tsx import { Flow } from '@rilaykit/workflow/react'; save(data, meta)}> ``` #### `Flow` [#flow] Compound root (`Flow.Body`, `Flow.Progress`, `Flow.Next`, `Flow.Back`, `Flow.Skip`). Wraps `WorkflowProvider`. | Prop | Type | Description | | --------------- | --------------------------------------------------------------- | ------------------------------------------- | | `of` | `WorkflowConfig \| flow` | Built configuration or builder (auto-built) | | `defaults?` | `Record` | Initial data | | `defaultStep?` | `string` | Step ID to start on | | `onStepChange?` | `(from: number, to: number, context) => void` | Step transition callback | | `onComplete?` | `(data, meta: WorkflowCompletionMeta) => void \| Promise` | See below | | `className?` | `string` | CSS class | **Completion**: `data` is a pure projection — only answered visible steps; a skipped or never-visible step is absent (no `{}` placeholder). `meta` (`{ visitedSteps, skippedSteps, passedSteps }`, `string[]` in insertion order, exported from `@rilaykit/workflow/react`) is additive: `onComplete(data)` callers keep working. `visitedSteps` records steps navigated *to*; the entry step is not included. | Component | Props | | --------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | | `Flow.Body` | `stepId?` (render only for that step), `children?: ReactNode \| (({ step }) => ReactNode)` — falls back to the step's `renderer`, then `` | | `Flow.Progress` | `children?: (ctx: FlowStepsContext) => ReactNode` (`{ steps, currentIndex, goTo }`), `className?` | | `Flow.Next` / `Flow.Back` / `Flow.Skip` | `children?: ReactNode \| ((ctx: FlowNavContext) => ReactNode)` (`{ go, canGo, submitting, isLastStep, step }`), `className?` | `useFlow()` returns the full `WorkflowContextValue`: workflow state, `currentStep`, navigation (`goToStep`, `goNext`, `goPrevious`, `skipStep`, `canGoNext`, …), data actions (`setValue`, `setStepData`, `resetWorkflow`), submission (`submitWorkflow`, `canSubmit`), and persistence (`persistNow`, `isPersisting`, `persistenceError`). ### flow (FlowBuilder) [#flow-flowbuilder] ```ts import { flow } from '@rilaykit/workflow'; const onboarding = flow.create(catalog, 'onboarding', 'User Onboarding') .step({ id: 'basics', title: 'Basics', formConfig: basicsForm, after: async (step) => { const company = await fetchCompany(step.data.siren); step.next.prefill({ companyName: company.name }); }, }) .step([ { title: 'Company', formConfig: companyForm }, { title: 'Review', formConfig: reviewForm, allowSkip: true }, ]); ``` **StepDefinition**: `id?`, `title`, `description?`, `formConfig` (built config or builder), `allowSkip?` (boolean or predicate on workflow data), `renderer?`, `conditions?` (`{ visible?, skippable? }`), `metadata?`, `after?`. **`after(step)`** runs after successful validation, before navigating. `StepContext`: | Member | Description | | --------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `step.data` | The step's validated data | | `step.next.prefill(fields)` | Write fields into the next **visible** step (a conditionally hidden step never swallows the prefill). Overwrite-always and re-runs on every forward transition — guard on the value for seed-if-empty | | `step.workflow.get(stepId)` / `step.workflow.all()` | Other steps' data | | `step.meta`, `step.isFirst`, `step.isLast` | Metadata and position | The legacy `onAfterValidation(stepData, helper, context)` signature still works but is deprecated — use `after`. | Method | Description | | ------------------------------------------------------- | ----------------------------------------------------------------------------- | | `.step(def)` / `.step([defs])` (alias `.addStep`) | Add steps | | `.configure({ analytics?, persistence? })` | `analytics: WorkflowAnalytics`; `persistence: { adapter, options?, userId? }` | | `.use(plugin)` / `.removePlugin(name)` | Plugins (dependencies validated on install) | | `.updateStep(id, updates)` / `.removeStep(id)` | Mutate steps | | `.addStepConditions(id, { visible?, skippable? })` | Conditions after creation | | `.getStep(id)` / `.getSteps()` / `.clearSteps()` | Read back / reset | | `.clone(newId?, newName?)` / `.validate()` / `.build()` | Utilities; `.build()` throws on invalid | | `.toJSON()` / `.fromJSON(json)` / `.getStats()` | Serialization, stats | Skip semantics: a step is re-skippable after navigating back onto it; a step later completed stops counting as skipped. `onStepSkip(stepId, reason)` currently always reports `'user_skip'`. ### Hooks [#hooks-1] From `@rilaykit/workflow/react`. | Hook | Returns | | -------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `useFlow()` | Full workflow context (see above) | | `useFlowStepIndex()` | `number` | | `useFlowTransitioning()` / `useFlowInitializing()` / `useFlowSubmitting()` | `boolean` | | `useFlowData()` | All data across steps | | `useStepData()` / `useStepDataById(stepId)` | Current / specific step data | | `useVisitedSteps()` / `usePassedSteps()` / `useSkippedSteps()` | `Set` | | `useIsStepVisited(id)` / `useIsStepPassed(id)` / `useIsStepSkipped(id)` | `boolean` | | `useFlowNavigationState()` | `{ currentStepIndex, isTransitioning, isSubmitting }` | | `useFlowSubmitState()` | `{ isSubmitting, isTransitioning, isInitializing }` | | `useFlowActions()` | Store actions: `setCurrentStep`, `setStepData`, `setAllData`, `setFieldValue`, `setSubmitting`, `setTransitioning`, `setInitializing`, `markStepVisited/Passed/Skipped`, `reset`, `loadPersistedState` | | `useFlowSteps()` | `{ steps, currentIndex, goTo }` (drives `Flow.Progress`) | | `useStepMetadata()` | `current`, `getByStepId`, `getByStepIndex`, `hasCurrentKey`, `getCurrentValue`, `getAllStepsMetadata`, `findStepsByMetadata` | | `useFlowStoreApi()` | Store ref for imperative reads | ### Persistence [#persistence] Configured via `.configure({ persistence: { adapter, options?, userId? } })`. * Values survive save→load byte-faithfully: `Date`, `NaN`, `±Infinity`, `-0`, `BigInt` are tag-encoded; legacy plain-JSON blobs still load. * A pending debounced autosave is flushed on unmount; completion clears persisted data and a late in-flight save cannot resurrect it. * Corrupted blobs degrade to a fresh start (`LOAD_FAILED` on `persistenceError`); out-of-range step indexes clamp; resume into a now-hidden step relocates forward to the next visible step. ### Analytics [#analytics] Every workflow error path routes through `analytics.onError(error, context)` and the monitoring adapter: step-transition failures, `after` throws, submission throws, and persistence save/load/remove failures (`WorkflowPersistenceError`). A validation error blocking Next is **not** an error path. The last step fires no `onStepComplete` — completion is carried by `onWorkflowComplete(id, duration, data)` with the same projected data as `onComplete`. ### Flow Schemas [#flow-schemas] ```ts import { compileFlow, validateFlowSchema, isFlowSchema } from '@rilaykit/workflow'; const { workflowConfig } = compileFlow(schema, catalog, { bindings }); ``` `validateFlowSchema` reports pathed issues; `SchemaValidationError` is re-exported from `@rilaykit/workflow` for flow-schema failures. *** ## @rilaykit/agent [#rilaykitagent] AI-agent integration (re-exported by `rilaykit`). Mains are React-free. See the [AI guide](/docs/ai) for the full walkthrough. | Export | Entry | Description | | ------------------------------------------------------------------- | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `manifest(catalog)` | main | Markdown catalog manifest for the system prompt | | `uiTools()` | main | Registers `show_form` / `show_flow` / `show_component` (schema-only tools, no `execute`) | | `parsePartialJson(text)` | main | Streaming-tolerant JSON parsing | | `Part`, `isTextPart`, `isToolPart`, `isDataPart` | main | Normalized message-part model | | `Catalog`, `Parts`, `Part`, `ShowForm`, `ShowFlow`, `ShowComponent` | `/react` | HITL rendering components | | `tools(catalog)`, `toParts(message)` | `rilaykit/ai-sdk` | Vercel AI SDK adapter — `tools()` is assignable to `ToolSet` with no cast; `toParts` maps `UIMessage` parts (all four tool states, `dynamic-tool`, `data-*`) | | `tools(catalog)`, `toParts(message)` | `rilaykit/anthropic` | Anthropic SDK adapter — `Anthropic.Tool[]`-compatible, maps `text` / `tool_use` blocks | Tool JSON schemas come from the Standard Schema's `~standard.jsonSchema.output` or a manual `inputJsonSchema`; a tool with neither is dropped and logged. Hosts must register a `.part('text', …)` renderer — there is no default. `show_form` resolves `{ status: 'submitted', values }` or `{ status: 'cancelled' }` exactly once per `toolCallId`. *** ## Types [#types] ### Validation [#validation] ```ts interface FieldError { readonly message: string; readonly code?: string; readonly path?: string; } interface ValidationResult { readonly isValid: boolean; readonly errors: FieldError[]; readonly value?: any; } type ValidationState = 'idle' | 'validating' | 'valid' | 'invalid'; interface FieldValidationConfig { readonly validate?: StandardSchema | StandardSchema[]; readonly debounceMs?: number; // async cost control; blur/submit validate immediately } type FormValidationMode = 'onSubmit' | 'onBlur' | 'onChange' | 'onTouched' | 'all'; type FormReValidateMode = 'onChange' | 'onBlur' | 'onSubmit'; interface FormValidationConfig = Record> { readonly validate?: StandardSchema | StandardSchema[]; readonly mode?: FormValidationMode; // default 'onTouched' readonly reValidateMode?: FormReValidateMode; // default 'onChange' readonly validateOnStepChange?: boolean; } ``` ### Conditions [#conditions] ```ts interface ConditionConfig { field: string; operator: ConditionOperator; value?: ConditionValue; conditions?: ConditionConfig[]; logicalOperator?: 'and' | 'or'; } type ConditionValue = | string | number | boolean | null | undefined | RegExp | Array; interface ConditionalBehavior { readonly visible?: ConditionConfig; readonly disabled?: ConditionConfig; readonly required?: ConditionConfig; readonly readonly?: ConditionConfig; } interface StepConditionalBehavior { readonly visible?: ConditionConfig; readonly skippable?: ConditionConfig; } ``` ### Workflow [#workflow] ```ts interface WorkflowCompletionMeta { readonly visitedSteps: string[]; readonly skippedSteps: string[]; readonly passedSteps: string[]; } interface WorkflowAnalytics { readonly onWorkflowStart?: (workflowId: string, context: WorkflowContext) => void; readonly onWorkflowComplete?: (workflowId: string, duration: number, data: any) => void; readonly onWorkflowAbandon?: (workflowId: string, currentStep: string, data: any) => void; readonly onStepStart?: (stepId: string, timestamp: number, context: WorkflowContext) => void; readonly onStepComplete?: (stepId: string, duration: number, data: any, context: WorkflowContext) => void; readonly onStepSkip?: (stepId: string, reason: string, context: WorkflowContext) => void; readonly onError?: (error: Error, context: WorkflowContext) => void; } interface WorkflowPlugin { readonly name: string; readonly version?: string; readonly install: (workflow: any) => void; readonly dependencies?: string[]; } ``` For `MonitoringConfig` and the monitoring pipeline, see the [monitoring docs](/docs/monitoring). # Examples Gallery # Examples Gallery [#examples-gallery] Copy-paste examples covering common setups. For full production scenarios (SaaS onboarding, KYC verification, dynamic pricing), see the [Real-World Examples](/docs/guides/real-world-examples) guide. ## Simple Contact Form [#simple-contact-form] Register a renderer, build a form, render it. ```tsx title="ContactForm.tsx" import { ril, required, email, minLength } from 'rilaykit'; import type { ComponentRenderContext } from 'rilaykit'; import { Form } from 'rilaykit/react'; interface InputProps { label: string; type?: string; placeholder?: string; } function Input({ id, props, field }: ComponentRenderContext) { return (
field?.onChange(e.target.value)} onBlur={() => field?.onBlur()} disabled={field?.disabled} placeholder={props.placeholder} className="mt-1 block w-full rounded-md border p-2" /> {field?.error &&

{field.error[0].message}

}
); } const r = ril.create().component('input', { renderer: Input }); const contactForm = r .form('contact') .add({ id: 'name', type: 'input', props: { label: 'Full Name' }, validation: { validate: [required(), minLength(2)] }, }) .add({ id: 'email', type: 'input', props: { label: 'Email', type: 'email' }, validation: { validate: [required(), email()] }, }) .add({ id: 'message', type: 'input', props: { label: 'Message' }, validation: { validate: [required(), minLength(10)] }, }); interface ContactFormProps { onSubmit?: (data: Record) => void; } export function ContactForm({ onSubmit }: ContactFormProps) { return (
onSubmit?.(data)}> ); } ``` ## Registration with Conditional Fields [#registration-with-conditional-fields] `when()` drives conditional visibility; Zod schemas plug in directly as Standard Schema validators — no adapter. Validation timing is configured form-level with `setValidation`. ```tsx title="RegistrationForm.tsx" import { ril, required, email, when } from 'rilaykit'; import { Form } from 'rilaykit/react'; import { z } from 'zod'; // Input and Select renderers as in the contact example const r = ril .create() .component('input', { renderer: Input }) .component('select', { renderer: Select }); const registrationForm = r .form('registration') .add({ id: 'email', type: 'input', props: { label: 'Email', type: 'email' }, validation: { validate: [required(), email()] }, }) .add({ id: 'password', type: 'input', props: { label: 'Password', type: 'password' }, validation: { validate: [z.string().min(8, 'Password must be at least 8 characters')] }, }) .add({ id: 'accountType', type: 'select', props: { label: 'Account Type', options: [ { value: 'personal', label: 'Personal' }, { value: 'business', label: 'Business' }, ], }, validation: { validate: [required()] }, }) .add({ id: 'companyName', type: 'input', props: { label: 'Company Name' }, validation: { validate: [required('Company name is required')] }, conditions: { visible: when('accountType').equals('business').build(), }, }) // mode: when a field FIRST validates (default 'onTouched' — first blur, then live). // reValidateMode: how an errored field re-validates (default 'onChange'). .setValidation({ mode: 'onTouched', reValidateMode: 'onChange' }); export function RegistrationForm() { return (
console.log(data)}> ); } ``` A field hidden via `conditions.visible` is not validated: `companyName` only blocks submit while `accountType` is `"business"`. ## UI Library Integration [#ui-library-integration] RilayKit is headless — a renderer maps the `ComponentRenderContext` (`id`, `props`, `field` bindings) onto your component library. Material-UI: ```tsx title="MaterialInput.tsx" import { TextField } from '@mui/material'; import { ril } from 'rilaykit'; import type { ComponentRenderContext } from 'rilaykit'; interface MaterialInputProps { label: string; multiline?: boolean; rows?: number; } function MaterialInput({ id, props, field }: ComponentRenderContext) { return ( field?.onChange(e.target.value)} onBlur={() => field?.onBlur()} error={!!field?.error} helperText={field?.error?.[0]?.message} disabled={field?.disabled} fullWidth margin="normal" /> ); } export const muiRil = ril .create() .component('input', { renderer: MaterialInput }) .component('textarea', { renderer: MaterialInput, defaultProps: { multiline: true, rows: 4 }, }); ``` The exact same pattern applies to shadcn/ui, Chakra, Ant Design, or plain HTML: wire `field.value` / `field.onChange` / `field.onBlur`, surface `field.error`, and register the renderer with `.component()`. ## Multi-Step Workflow [#multi-step-workflow] Compose forms into a flow with `.step()`, render with the `Flow` compound component. ```tsx title="OnboardingFlow.tsx" import { ril, required, email, minLength } from 'rilaykit'; import { Flow } from 'rilaykit/react'; const r = ril .create() .component('input', { renderer: Input }) .component('checkbox', { renderer: Checkbox }); const accountForm = r .form('account') .add({ id: 'email', type: 'input', props: { label: 'Email', type: 'email' }, validation: { validate: [required(), email()] }, }) .add({ id: 'password', type: 'input', props: { label: 'Password', type: 'password' }, validation: { validate: [required(), minLength(8)] }, }); const profileForm = r .form('profile') .add( { id: 'firstName', type: 'input', props: { label: 'First Name' } }, { id: 'lastName', type: 'input', props: { label: 'Last Name' } }, ); const confirmForm = r.form('confirm').add({ id: 'terms', type: 'checkbox', props: { label: 'I agree to the terms and conditions' }, validation: { validate: [required('You must accept the terms')] }, }); const onboarding = r .flow('onboarding', 'User Onboarding') .step({ id: 'account', title: 'Create Account', formConfig: accountForm }) .step({ id: 'profile', title: 'Your Profile', formConfig: profileForm, allowSkip: true }) .step({ id: 'confirm', title: 'Confirmation', formConfig: confirmForm }); export function OnboardingFlow() { return ( { // data holds answered visible steps only — a skipped step is absent console.log('Completed:', data, 'skipped:', meta.skippedSteps); }} > ); } ``` ## Async Validation [#async-validation] Use the `async()` validator for server-side checks. `debounceMs` debounces validation while typing; blur and submit always validate immediately. ```tsx title="AsyncValidationForm.tsx" import { ril, required, email, minLength, async as asyncValidator } from 'rilaykit'; import { Form } from 'rilaykit/react'; const checkEmailAvailability = asyncValidator(async (value: string) => { const response = await fetch(`/api/check-email?email=${value}`); const { available } = await response.json(); return available; }, 'This email is already taken'); const r = ril.create().component('input', { renderer: Input }); const signupForm = r .form('signup') .add({ id: 'email', type: 'input', props: { label: 'Email', type: 'email' }, validation: { validate: [required(), email(), checkEmailAvailability], debounceMs: 500, }, }) .add({ id: 'password', type: 'input', props: { label: 'Password', type: 'password' }, validation: { validate: [required(), minLength(8)] }, }); export function AsyncValidationForm() { return (
console.log(data)}> ); } ``` Zod's async `.refine()` also works as a Standard Schema validator. See the [Validation](/docs/forms/validation) guide. ## Next.js App Router [#nextjs-app-router] The main `rilaykit` entry is isomorphic — `ril`, builders, and validators are safe in Server Components. Only `rilaykit/react` (components, hooks) needs a client boundary. ```tsx title="app/contact/page.tsx" 'use client'; import { Form } from 'rilaykit/react'; import { contactForm } from '@/config/forms'; // built with the isomorphic entry export default function ContactPage() { async function handleSubmit(data: Record) { const response = await fetch('/api/contact', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data), }); if (!response.ok) throw new Error('Failed to submit'); } return (
); } ``` Keep your `ril` catalog and form configurations in shared modules (e.g. `lib/ril.ts`, `config/forms.ts`) so they are reusable across pages and server code. ## Testing with Vitest [#testing-with-vitest] RilayKit forms test with standard Testing Library patterns. ```tsx title="ContactForm.test.tsx" import { describe, it, expect, vi } from 'vitest'; import { render, screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { ContactForm } from './ContactForm'; describe('ContactForm', () => { it('validates email format on first blur (default mode: onTouched)', async () => { const user = userEvent.setup(); render(); await user.type(screen.getByLabelText(/email/i), 'not-an-email'); await user.tab(); // triggers onBlur await waitFor(() => { expect(screen.getByText(/valid email/i)).toBeInTheDocument(); }); }); it('calls onSubmit with valid data', async () => { const user = userEvent.setup(); const handleSubmit = vi.fn(); render(); await user.type(screen.getByLabelText(/name/i), 'Jane Doe'); await user.type(screen.getByLabelText(/email/i), 'jane@example.com'); await user.type(screen.getByLabelText(/message/i), 'Hello, this is a test message.'); await user.click(screen.getByRole('button', { name: /send message/i })); await waitFor(() => { expect(handleSubmit).toHaveBeenCalledWith({ name: 'Jane Doe', email: 'jane@example.com', message: 'Hello, this is a test message.', }); }); }); }); ``` More examples and starter templates are available in the [GitHub repository](https://github.com/andyoucreate/rilaykit/tree/main/apps/playground). # Introduction ## Is RilayKit for you? [#is-rilaykit-for-you] RilayKit is **not** a React Hook Form replacement for simple forms. **Building a login, contact, or settings form?** → Use [React Hook Form](https://react-hook-form.com/) + [Zod](https://zod.dev/). **RilayKit is for you if** you're building one of these: ### ✅ You need RilayKit when: [#-you-need-rilaykit-when] * **Forms are generated dynamically** from server config or database schemas * **Multi-tenant SaaS** where each client customizes form fields and workflows * **Visual form builder** for non-technical users * **Complex multi-step workflows** with cross-step conditional logic (onboarding, KYC, checkout) * **Same logic, multiple UIs** — one form schema across design systems * **AI-driven UI** — an agent that renders forms and flows as tool calls * **Form versioning & A/B testing** — store forms as data, diff them, roll back ### ❌ You don't need RilayKit when: [#-you-dont-need-rilaykit-when] * Standard CRUD forms with static field sets * Forms defined once that never change dynamically * Simple wizard flows with no cross-step dependencies *** ## The tipping point [#the-tipping-point] **Scenario:** multi-step onboarding where step visibility depends on earlier answers, and a step is skipped if revenue \< $50k. With React Hook Form this means a hand-rolled state machine, `useEffect` cross-step wiring, and 200+ lines of conditional rendering. With RilayKit it's configuration: ```tsx const basicsForm = rilay.form('basics') .add({ id: 'userType', type: 'select', props: { options: ['freelance', 'business'] } }) .add({ id: 'revenue', type: 'number', props: { label: 'Annual Revenue' } }) .build(); const onboarding = rilay.flow('onboarding', 'User Onboarding') .step({ id: 'basics', title: 'Basic Information', formConfig: basicsForm }) .step({ id: 'business', title: 'Business Details', formConfig: businessForm, conditions: { visible: when('basics.userType').equals('business').build(), skippable: when('basics.revenue').lessThan(50000).build(), }, }) .step({ id: 'freelance', title: 'Freelance Details', formConfig: freelanceForm, conditions: { visible: when('basics.userType').equals('freelance').build() }, }); // Serialize to DB, version control, A/B test (toJSON lives on the builder) const json = onboarding.toJSON(); const config = onboarding.build(); ``` Business logic lives in declarative configuration — data you can store, diff, version, and generate. *** ## Quick example [#quick-example] ```tsx import { ril, required, email, when } from 'rilaykit'; import { Form } from 'rilaykit/react'; // 1. Register your components once (shadcn, MUI, custom — your choice) const rilay = ril.create() .component('input', { renderer: YourInput }) .component('select', { renderer: YourSelect }); // 2. Define forms as data (not JSX) const signupForm = rilay.form('signup') .add({ id: 'email', type: 'input', validation: { validate: [required(), email()] } }) .add({ id: 'plan', type: 'select', props: { options: ['free', 'pro', 'enterprise'] } }) .add({ id: 'company', type: 'input', conditions: { visible: when('plan').in(['pro', 'enterprise']).build() }, }) .build(); // 3. Render anywhere with full type safety
{/* auto-hidden unless plan is pro/enterprise */} ``` RilayKit is fully **headless** — it manages state, validation, and logic. You own the components, the markup, and the styling. *** ## React Hook Form vs RilayKit [#react-hook-form-vs-rilaykit] | Criteria | React Hook Form | RilayKit | | ------------------------------ | --------------------------- | ---------------------------------- | | **Learning curve** | ✅ Simple, familiar patterns | ⚠️ Steeper (new concepts) | | **Simple forms** | ✅ Perfect fit | ❌ Overkill | | **Multi-step with conditions** | ⚠️ Custom state machine | ✅ Built-in workflow engine | | **Forms as data** | ❌ Not possible | ✅ Core feature (`.toJSON()`) | | **Dynamic form generation** | ❌ Challenging | ✅ Designed for it | | **Multiple design systems** | ⚠️ Requires refactoring | ✅ Swap renderers, logic stays | | **Ecosystem maturity** | ✅ Huge, battle-tested | ⚠️ Young but growing | | **Type safety** | ✅ Good (with Zod/TS) | ✅ Excellent (built-in propagation) | **Rule of thumb:** if you're not sure you need RilayKit, you probably don't. Start with React Hook Form; migrate when you hit the limitations above. [Read the detailed comparison](/why-rilaykit) *** ## What makes RilayKit different [#what-makes-rilaykit-different] ### 1. Forms are data, not JSX [#1-forms-are-data-not-jsx] Your form definition is a serializable data structure: ```tsx const pricingForm = rilay.form('pricing') .add({ id: 'plan', type: 'select', props: { options: ['free', 'pro'] } }); const json = pricingForm.toJSON(); // serialize from the builder await db.forms.save(json); // Load it later, even from a different server const loaded = rilay.form().fromJSON(json).build(); ``` Multi-tenant customization, visual builders, A/B testing, and versioning all fall out of this. ### 2. Type propagation end-to-end [#2-type-propagation-end-to-end] Register a component once and TypeScript propagates its types everywhere: ```tsx const rilay = ril.create() .component('input', { renderer: Input }); // Input has InputProps rilay.form('test') .add({ type: 'input', // ✅ Autocompletes from registry props: { label: '' } // ✅ Typed as InputProps }) .add({ type: 'unknown', // ❌ Compile error — not registered }); ``` No `any` escape hatches — the registry is the single source of truth for types. [Learn more](/core-concepts/typescript-support) ### 3. Universal validation (Standard Schema) [#3-universal-validation-standard-schema] Any [Standard Schema](https://github.com/standard-schema/standard-schema) library works directly — zod, valibot, arktype — and mixes with the built-in helpers: ```tsx validation: { validate: [required(), z.string().min(8)] } ``` Validation timing is form-level and mirrors React Hook Form: `.setValidation({ mode, reValidateMode })` — `mode` defaults to `'onTouched'` (validate on first blur, then live), `reValidateMode` to `'onChange'`. [Learn more](/core-concepts/validation) ### 4. Declarative conditions (no `useEffect`) [#4-declarative-conditions-no-useeffect] ```tsx .add({ id: 'company', type: 'input', conditions: { visible: when('accountType').equals('business').build(), required: when('plan').in(['pro', 'enterprise']).build(), disabled: when('revenue').lessThan(10000).build(), } }) ``` Cross-step conditions work the same way in workflows — reference another step's field as `when('stepId.fieldId')`. [Learn more](/core-concepts/conditions) ### 5. Production-ready workflow engine [#5-production-ready-workflow-engine] Multi-step flows with navigation, persistence, analytics, and plugins: ```tsx import { LocalStorageAdapter } from 'rilaykit'; import { Flow } from 'rilaykit/react'; const onboarding = rilay.flow('onboarding', 'User Onboarding') .step({ id: 'account', title: 'Account', formConfig: accountForm }) .step({ id: 'profile', title: 'Profile', formConfig: profileForm }) .configure({ persistence: { adapter: new LocalStorageAdapter({ keyPrefix: 'onboarding_' }) }, analytics: { onStepComplete: (id) => analytics.track('step_done', { step: id }) }, }) .build(); save(data)}> ``` `onComplete(data, meta)` receives only answered visible steps (skipped or hidden steps are absent), plus `meta.visitedSteps` / `skippedSteps` / `passedSteps`. Persistence adapters (localStorage, custom), navigation guards, and a plugin system are built in. [Learn more](/workflow/building-workflows) ### 6. AI-native (agent package) [#6-ai-native-agent-package] Because forms and flows are data, an LLM can emit them. `@rilaykit/agent` (bundled in `rilaykit`) turns your catalog into a system-prompt manifest and schema-only UI tools, with adapters for the AI SDK and the Anthropic SDK: ```tsx import { manifest, uiTools } from 'rilaykit'; const catalog = rilay.use(uiTools()); // registers show_form / show_flow / show_component const systemPrompt = manifest(catalog); // Markdown catalog for the model ``` The model calls `show_form`, your app renders it, and the user's submission resolves back as the tool result. [Learn more](/ai) *** ## Architecture [#architecture] RilayKit generates **zero HTML and zero CSS** — it's pure logic. Bring shadcn/ui, Material UI, Mantine, or your own design system: register different renderers, the form config stays identical. One schema, N brands. Install the all-in-one package: ```bash pnpm add rilaykit ``` Builders and validators import from `rilaykit`; components and hooks from `rilaykit/react`. Granular packages (`@rilaykit/core`, `@rilaykit/forms`, `@rilaykit/workflow`, `@rilaykit/agent`) are also available — see [Installation](/getting-started/installation). *** ## Get Started [#get-started] *** # Quick Start # Quick Start [#quick-start] A working, validated form in 5 minutes. ## 1. Install [#1-install] ```bash pnpm add rilaykit ``` ```bash npm install rilaykit ``` ```bash yarn add rilaykit ``` ## 2. Create a Component [#2-create-a-component] A renderer receives a `ComponentRenderContext`: your `props`, plus a `field` binding (`value`, `onChange`, `onBlur`, `error`, `touched`). ```tsx title="components/Input.tsx" import type { ComponentRenderContext } from 'rilaykit'; interface InputProps { label: string; type?: string; placeholder?: string; } export function Input({ id, props, field }: ComponentRenderContext) { return (
field?.onChange(e.target.value)} onBlur={field?.onBlur} placeholder={props.placeholder} className="w-full p-2 border rounded" /> {field?.error && (

{field.error[0].message}

)}
); } ``` ## 3. Register Components [#3-register-components] ```tsx title="lib/rilay.ts" import { ril } from 'rilaykit'; import { Input } from '../components/Input'; export const rilay = ril.create().component('input', { renderer: Input }); ``` ## 4. Build the Form [#4-build-the-form] ```tsx title="forms/login.ts" import { email, required } from 'rilaykit'; import { rilay } from '../lib/rilay'; export const loginForm = rilay.form('login') .add({ id: 'email', type: 'input', props: { label: 'Email', type: 'email' }, validation: { validate: [required(), email()] }, }) .add({ id: 'password', type: 'input', props: { label: 'Password', type: 'password' }, validation: { validate: [required()] }, }) .build(); ``` By default fields validate on first blur, then re-validate on every keystroke. Tune with `.setValidation({ mode, reValidateMode })`. ## 5. Render It [#5-render-it] Components and hooks import from `rilaykit/react`: ```tsx title="components/LoginForm.tsx" import { Form, FormField } from 'rilaykit/react'; import { loginForm } from '../forms/login'; export function LoginForm() { return (
console.log('Login:', data)}> ); } ``` Done — mount `` anywhere. ## Common Patterns [#common-patterns] ### Multiple Input Types [#multiple-input-types] ```tsx export const rilay = ril.create() .component('input', { renderer: Input }) .component('textarea', { renderer: TextareaInput }) .component('select', { renderer: SelectInput }); ``` ### Validation with Zod [#validation-with-zod] Any Standard Schema library works directly — no adapter: ```tsx import { z } from 'zod'; const userForm = rilay.form('user') .add({ id: 'email', type: 'input', validation: { validate: z.string().email() }, }); ``` ### Conditional Fields [#conditional-fields] ```tsx import { when } from 'rilaykit'; const accountForm = rilay.form('account') .add({ id: 'accountType', type: 'select', props: { options: [{ value: 'business', label: 'Business' }] }, }) .add({ id: 'companyName', type: 'input', conditions: { visible: when('accountType').equals('business') }, }); ``` ### Cross-Field Validation [#cross-field-validation] Form-level rules run on the same cadence as field validation. An issue whose `path` names a field attaches to that field; pathless issues land in the `__form__` bucket, read via `useFormErrors()`: ```tsx import { z } from 'zod'; const signupForm = rilay.form('signup') .add({ id: 'password', type: 'input', props: { label: 'Password', type: 'password' } }) .add({ id: 'confirmPassword', type: 'input', props: { label: 'Confirm', type: 'password' } }) .setValidation({ validate: z .object({ password: z.string(), confirmPassword: z.string() }) .refine((d) => d.password === d.confirmPassword, { message: 'Passwords do not match', path: ['confirmPassword'], }), }) .build(); ``` ## What's Next? [#whats-next] * [Your First Form](/getting-started/your-first-form) — step-by-step tutorial * [Validation](/core-concepts/validation) — timing modes, Standard Schema, async * [Advanced Forms](/forms/advanced-forms) — conditions, effects, repeatables * [Workflows](/workflow/building-workflows) — multi-step flows and wizards * [Examples](/examples) — real-world patterns * [Discord](https://discord.gg/rilay) — get help from the community # Roadmap # Roadmap [#roadmap] Public roadmap, organized by phase. Priorities may shift with community feedback. Code samples in unshipped phases are proposals, not final APIs. Want to influence the roadmap? [Open a discussion](https://github.com/andyoucreate/rilaykit/discussions) or upvote existing proposals. *** ## Phase 5 — AI-Assisted Form Filling [#phase-5--ai-assisted-form-filling] **Status:** Next up The foundation shipped: `@rilaykit/agent` lets an LLM *render* forms and flows as chat tools (`show_form`, `show_flow`, `show_component`) with AI SDK and Anthropic adapters. Next: letting an LLM *fill* an existing form from unstructured text. Since RilayKit forms are data, the AI knows every field's type, constraints, and validation rules. ### `useAIFormFill()` — Text-to-Form Mapping [#useaiformfill--text-to-form-mapping] ```tsx const { fillFromText, isProcessing } = useAIFormFill(formConfig, { provider: 'openai', // or 'anthropic', 'custom' }); await fillFromText( "My name is Karl, I live in Paris, my email is karl@example.com" ); // → setValue('name', 'Karl') // → setValue('city', 'Paris') // → setValue('email', 'karl@example.com') ``` Unlocks paste-to-fill from emails or transcripts, voice-to-form via speech-to-text, and bulk import from unstructured sources. Opt-in and provider-agnostic — RilayKit will not bundle an AI SDK. *** ## Phase 2 — Data Transform Pipeline [#phase-2--data-transform-pipeline] **Status:** Planned Declarative transforms around submission — sanitization, field exclusion, reshaping — without `onSubmit` boilerplate. ### `transform()` — Pre/Post Submission Hooks [#transform--prepost-submission-hooks] ```tsx form.create(r, 'register') .add(/* fields */) .transform({ before: (data) => ({ ...data, email: data.email.trim().toLowerCase(), }), after: (data) => omit(data, ['confirmPassword', 'acceptTerms']), }) .build(); ``` *** ## Phase 3 — Cross-Step Workflow Validation [#phase-3--cross-step-workflow-validation] **Status:** Planned Form-level cross-field validation already shipped (`setValidation({ validate })`, path-routed errors, `useFormErrors()`), but each workflow step still validates independently. This phase adds rules that span steps, reusing the same path-keyed error routing. ### `crossValidate()` — Multi-Step Validation Rules [#crossvalidate--multi-step-validation-rules] ```tsx flow.create(r, 'checkout', 'Checkout') .step({ id: 'shipping', title: 'Shipping', formConfig: shippingForm }) .step({ id: 'billing', title: 'Billing', formConfig: billingForm }) .crossValidate({ validate: (allData) => { const errors: Record = {}; if (allData.billing.sameAsShipping && !allData.shipping.address) { errors['shipping.address'] = 'Required when "same as shipping" is checked'; } return errors; }, trigger: 'before-complete' // or 'on-step-leave' }) .build(); ``` *** ## Phase 6 — DevTools [#phase-6--devtools] **Status:** Planned A visual inspector panel (similar to React Query DevTools) surfacing form and workflow state in real time. ### `` — Visual Inspector [#rilaydevtools---visual-inspector] ```tsx
{process.env.NODE_ENV === 'development' && } ``` **Planned capabilities:** * **Field Inspector** — live values, errors, touched state, active conditions * **Condition Graph** — which fields affect which conditions * **Validation Timeline** — validation runs with timing and results * **Workflow Navigator** — step state, visited/passed steps, accumulated data * **Performance Panel** — render counts and hotspots, powered by the existing monitoring system in `@rilaykit/core` *** ## Phase 7 — Plugin System [#phase-7--plugin-system] **Status:** Exploring A public plugin API for extending form and workflow behavior. The `WorkflowPlugin` type already exists internally — this phase promotes and documents it. ### `createPlugin()` — Lifecycle Hooks [#createplugin--lifecycle-hooks] ```tsx import { createPlugin } from 'rilaykit'; const autosavePlugin = createPlugin({ id: 'autosave', onFieldChange: debounce(async (fieldId, value, { allValues }) => { await saveDraft(allValues); }, 1000), onStepComplete: (stepId, stepData) => { analytics.track('step_completed', { stepId }); }, }); flow.create(r, 'onboarding', 'Onboarding') .configure({ plugins: [autosavePlugin] }) .build(); ``` Community plugin ideas: autosave, analytics, A/B testing, feature flags, undo/redo. *** ## Completed [#completed] Shipped in the current release: | Feature | Package | Status | | ------------------------------------------------------------------------------------------------- | ------------------------------------ | ------- | | Immutable component registry | `@rilaykit/core` | Shipped | | Standard Schema validation (Zod, Valibot, Yup, ArkType) | `@rilaykit/core` | Shipped | | Declarative conditions with `when()` builder | `@rilaykit/core` | Shipped | | Performance monitoring & adapters | `@rilaykit/core` | Shipped | | Form builder with type-safe field config | `@rilaykit/forms` | Shipped | | Granular Zustand store selectors | `@rilaykit/forms` | Shipped | | Repeatable fields with min/max | `@rilaykit/forms` | Shipped | | Async field validation with `debounceMs` | `@rilaykit/forms` | Shipped | | Validation timing — `mode` / `reValidateMode` (RHF model) | `@rilaykit/forms` | Shipped | | Path-keyed error map + `useFormErrors()` form-level bucket | `@rilaykit/forms` | Shipped | | Multi-step workflow builder | `@rilaykit/workflow` | Shipped | | Step navigation with validation guards | `@rilaykit/workflow` | Shipped | | Workflow persistence (LocalStorage, type-faithful serialization) | `@rilaykit/workflow` | Shipped | | Completion meta — `onComplete(data, meta)` with visited/skipped/passed steps | `@rilaykit/workflow` | Shipped | | Workflow analytics hooks | `@rilaykit/workflow` | Shipped | | Step conditions (visible, skippable) | `@rilaykit/workflow` | Shipped | | All-in-one `rilaykit` package with `.form()` / `.flow()` | `rilaykit` | Shipped | | Field effects with `onChange()` — cascades, dynamic props, calculated fields | `@rilaykit/core` + `@rilaykit/forms` | Shipped | | `useFieldProps` hook for dynamic field props | `@rilaykit/forms` | Shipped | | Server-driven forms — `fromSchema()`, `compileForm`, `validateSchema`, `isFormSchema` | `@rilaykit/forms` | Shipped | | Server-driven flows — `compileFlow` | `@rilaykit/workflow` | Shipped | | Agent chat tools — `show_form` / `show_flow` / `show_component` with human-in-the-loop resolution | `@rilaykit/agent` | Shipped | | `manifest()` — catalog to Markdown for system prompts | `@rilaykit/agent` | Shipped | | AI SDK & Anthropic adapters (`rilaykit/ai-sdk`, `rilaykit/anthropic`) | `rilaykit` | Shipped | | RSC-safe isomorphic entries (React-free mains, `/react` client entries) | all packages | Shipped | # What's New # What's New [#whats-new] P3 ships the agent package, an honest forms API, and reliability work across the stack. ## Agent package [#agent-package] `@rilaykit/agent` (re-exported by `rilaykit`) lets a model emit real RilayKit forms and flows as tool calls, and lets your users answer them — human-in-the-loop, typed end to end. * `manifest(catalog)` renders your catalog as Markdown for the system prompt. * `uiTools()` registers `show_form` / `show_flow` / `show_component` — schema-only tools, no `execute`. * Adapters: `rilaykit/ai-sdk` and `rilaykit/anthropic`. `tools(catalog)` is assignable to the SDK's tool type with no cast; `toParts(message)` maps real message parts, all tool states covered. Verified against `ai@5.0.215` and `@anthropic-ai/sdk@0.112.1`. * Standard Schema is vendor-neutral: zod, valibot, arktype. Tool JSON schema comes from `~standard.jsonSchema.output` or a manual `inputJsonSchema`; a tool with neither is dropped and logged. * Mains are React-free (RSC/server-safe). Components and hooks come from `/react`. ```tsx // server import { manifest } from 'rilaykit'; import { tools } from 'rilaykit/ai-sdk'; streamText({ model, system: manifest(catalog), tools: tools(catalog) }); // client — show_form resolves { status: 'submitted', values } exactly once addToolResult(output)} /> ``` Built-in `ShowFlow` renders binding-free schemas (built-in validators, conditions, repeatables). For custom logic or persistence, plug a host renderer via `.renderers({ tools: {…} })`. Hosts must register `.part('text', …)` — there is no default text renderer. ## Honest API refactor [#honest-api-refactor] ### Two-phase validation timing [#two-phase-validation-timing] Per-field timing flags are gone. One form-level call controls when a field first validates and how it re-validates after an error: ```ts form.setValidation({ mode: 'onTouched', reValidateMode: 'onChange' }); ``` | Option | Values | Default | | ---------------- | -------------------------------------------------------------- | ------------- | | `mode` | `'onSubmit' \| 'onBlur' \| 'onChange' \| 'onTouched' \| 'all'` | `'onTouched'` | | `reValidateMode` | `'onChange' \| 'onBlur' \| 'onSubmit'` | `'onChange'` | Default behavior: validate on first blur, then live. Submit always validates and marks errored fields `touched`. Per-field `debounceMs` stays for async cost control; blur and submit always validate immediately. ### Path-keyed error map [#path-keyed-error-map] Cross-field issues now route by `issue.path`: a path naming a known field attaches to that field; empty or unmatched paths land in the reserved `__form__` bucket. The new `useFormErrors()` hook (from `rilaykit/react`) returns that bucket — use it for a form-level error banner. `isValid` counts the whole map. Form-level rules re-run on the same `mode`/`reValidateMode` cadence as fields, and on repeatable row add/remove/move — cross-field errors appear and clear live, no resubmit. ### Completion payload projection [#completion-payload-projection] `onComplete(data, meta)` — `data` contains only answered visible steps. A skipped or never-visible step is absent, not an `{}` placeholder. The new `meta` argument carries `{ visitedSteps, skippedSteps, passedSteps }`. Additive: existing `onComplete(data)` callers keep working. ## Reliability & performance [#reliability--performance] | Area | Change | | ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Persistence | `Date`, `NaN`, `±Infinity`, `-0`, `BigInt` survive save→load byte-faithfully; a pending debounced autosave is flushed on unmount; completion clears persisted data; corrupted blobs degrade to a fresh start (`LOAD_FAILED` on `persistenceError`). | | Observability | Every workflow error path routes through `trackError` → both `analytics.onError(error, workflowContext)` and the monitoring adapter: step transitions, `onAfterValidation` throws, submission throws, persistence failures. | | Render isolation | A keystroke re-renders only the typed field — O(1) even at 200 fields with conditionals. Appending a repeatable row does not re-render surviving rows. | ## Breaking changes [#breaking-changes] | Removed | Replacement | | ----------------------------------------------------------- | ------------------------- | | Per-field `validateOnChange` / `validateOnBlur` | Form-level `mode` | | Form-level `validateOnSubmit` | `mode` + `reValidateMode` | | `next.skip()` / `workflow.goto()` (never-implemented stubs) | — | Migration — per-field `validate` is unchanged; only the timing flags move: ```diff - .validation({ validateOnChange: true, validateOnBlur: true, validate: schema }) + .validation({ validate: schema }) + form.setValidation({ mode: 'onChange', reValidateMode: 'onChange' }); ``` # Why RilayKit ## The Problem [#the-problem] Forms in React are usually built imperatively: JSX mixed with state management, validation scattered across components, nothing serializable, and every multi-step flow a hand-rolled state machine. UI and business logic end up coupled, every form is a one-off, and type safety is bolted on. RilayKit treats forms as data structures instead of UI trees. ## Schema-First: Forms as Data [#schema-first-forms-as-data] Form configurations are plain, serializable objects. You describe what a form contains; the library handles rendering and behavior. ```tsx import { ril, required, email } from '@rilaykit/core'; import { form } from '@rilaykit/forms'; const rilay = ril.create() .component('input', { renderer: YourInputComponent }); const onboardingForm = form.create(rilay, 'onboarding') .add({ id: 'email', type: 'input', props: { label: 'Email' }, validation: { validate: [required(), email()] }, }); // A form config is just data -- serialize it, store it, version it const json = onboardingForm.toJSON(); ``` Because a form is data, it is introspectable (iterate fields, read rules), serializable (store in a database, send over the network), clonable (`form.clone()` for A/B variants or per-tenant customization), and generatable from a server, CMS, or visual editor. ## Component Registry: Define Once, Use Everywhere [#component-registry-define-once-use-everywhere] Components are registered once on the `ril` instance; every form uses them. The same schema renders with completely different design systems: ```tsx // Design system A const rilayMaterial = ril.create() .component('input', { renderer: MaterialInput }); // Design system B const rilayShadcn = ril.create() .component('input', { renderer: ShadcnInput }); // Same form definition works with both const loginForm = form.create(rilayMaterial, 'login') .add({ id: 'email', type: 'input', props: { label: 'Email' } }); ``` Your UI components stay in your design system. RilayKit handles state, validation, conditions, and rendering orchestration -- no imposed styling, no vendor lock-in on the visual layer. ## Type Propagation: Safety Without Boilerplate [#type-propagation-safety-without-boilerplate] `.component('input', { renderer: MyInput })` captures `MyInput`'s exact props interface. Every later `.add({ type: 'input', props })` gets autocompletion and compile-time checking. You never write type annotations for forms -- types flow from component definitions through the builder chain. ```tsx const rilay = ril.create() .component('text', { renderer: TextInput }) // captures TextInputProps .component('select', { renderer: SelectInput }); // captures SelectProps form.create(rilay, 'example') .add({ id: 'country', type: 'select', // 'type' narrowed to 'text' | 'select' props: { label: 'Country', options: [{ value: 'us', label: 'US' }], // required by SelectProps }, }); ``` ## Universal Validation [#universal-validation] A single `validation.validate` field accepts built-in validators, custom functions, and any [Standard Schema](https://standardschema.dev) library (Zod, Valibot, ArkType, ...) -- mixed in the same array, no adapters: ```tsx import { z } from 'zod'; import { required, custom } from '@rilaykit/core'; .add({ id: 'email', type: 'input', props: { label: 'Email' }, validation: { validate: [ required('Email is required'), z.string().email('Invalid format'), custom((value) => !value.endsWith('.test'), 'No test domains'), ], }, }) ``` Validation timing is configured once at the form level with `.setValidation({ mode, reValidateMode })` -- the same two-phase model as React Hook Form (`mode` for first validation, `reValidateMode` once a field has errored). ## Declarative Conditions [#declarative-conditions] Conditional logic is declared with `when()` -- no `useEffect`, no manual subscriptions: ```tsx import { when } from '@rilaykit/core'; .add({ id: 'companyName', type: 'input', props: { label: 'Company Name' }, conditions: { visible: when('accountType').equals('business'), required: when('accountType').equals('business'), }, }) ``` Conditions drive visibility, required, disabled, and readonly state. They compose with `.and()` / `.or()`, support dot-notation paths, and offer operators from `equals` through `greaterThanOrEqual`, `contains`, `in`, `matches`, and `exists`. A field hidden by a condition skips validation automatically. ## Real Workflow Engine [#real-workflow-engine] `@rilaykit/workflow` is a workflow engine on the same schema-first foundation, not a wizard with hidden divs: ```tsx import { flow, LocalStorageAdapter } from '@rilaykit/workflow'; const onboarding = flow.create(rilay, 'onboarding', 'User Onboarding') .step({ id: 'account', title: 'Create Account', formConfig: accountForm }) .step({ id: 'profile', title: 'Your Profile', formConfig: profileForm, allowSkip: true }) .configure({ persistence: { adapter: new LocalStorageAdapter({ maxAge: 7 * 24 * 60 * 60 * 1000 }), options: { autoPersist: true, debounceMs: 500 }, }, analytics: { onStepComplete: (stepId, duration) => trackEvent('step_complete', { stepId, duration }), onWorkflowComplete: (id, duration) => trackEvent('workflow_complete', { id, duration }), }, }); ``` The engine provides step navigation with guards and step-level validation, persistence through an adapter interface (localStorage or any backend), analytics callbacks, a plugin system (`.use(plugin)`), and cross-step conditions via `when('stepId.fieldId')`. On completion, `onComplete(data, meta)` receives only the answered visible steps, plus `meta.visitedSteps` / `skippedSteps` / `passedSteps`. ## Agent-Ready [#agent-ready] Because forms and flows are data, `@rilaykit/agent` can hand them to an LLM: `manifest(catalog)` documents your catalog in the system prompt, `uiTools()` exposes `show_form` / `show_flow` / `show_component` as schema-only tools, and adapters for the Vercel AI SDK (`rilaykit/ai-sdk`) and Anthropic (`rilaykit/anthropic`) plug into real chat loops. The model asks; the user answers through your validated, type-safe form. ## Who Is RilayKit For? [#who-is-rilaykit-for] Teams building complex user-facing flows (SaaS onboarding, KYC, insurance claims, multi-step checkout), products with multiple design systems that share form logic, and developers who want multi-step workflows without hand-rolling state machines. MIT licensed, free, open source. Head to the [installation guide](/getting-started/installation) to set up RilayKit, or jump to the [quickstart](/quickstart) to build your first form. # Advanced Forms Beyond one-time configuration, the form builder can inspect, modify, clone, and serialize form definitions. ## Dynamic Form Management [#dynamic-form-management] Modify a form configuration after creation: | Method | Description | | -------------------------------- | ------------------------------------------------ | | `.updateField(fieldId, updates)` | Modifies an existing field's configuration | | `.removeField(fieldId)` | Removes a field | | `.getField(fieldId)` | Returns a field's configuration, or `undefined` | | `.getFields()` | Returns a flat array of all field configurations | | `.getRows()` | Returns all row configurations | | `.clear()` | Removes all fields and rows | ```tsx import { rilay } from '@/lib/rilay'; import { form } from '@rilaykit/forms'; const myDynamicForm = form.create(rilay, 'dynamic-form') .add({ id: 'username', type: 'text', props: { label: 'Username' } }); if (shouldAddEmail) { myDynamicForm.add({ id: 'email', type: 'email', props: { label: 'Email' } }); } myDynamicForm.updateField('username', { props: { label: 'Please enter your desired username' } }); const formConfig = myDynamicForm.build(); ``` Builder methods mutate the builder instance. To create variations, use `.clone()` first. ## Cloning [#cloning] `.clone(newFormId?)` deep-copies the builder so variations don't affect the original. ```tsx const baseForm = form.create(rilay, 'base-form') .add({ id: 'name', type: 'text', props: { label: 'Name' } }); const adminForm = baseForm.clone('admin-form') .add({ id: 'adminNotes', type: 'textarea', props: { label: 'Admin Notes' } }); // baseForm is unaffected ``` ## Serialization (JSON Import/Export) [#serialization-json-importexport] `.toJSON()` exports the form structure as a JSON-serializable object; `.fromJSON(json)` populates a builder from one. Use this to store definitions in a database, drive a visual form builder, or send structures over the network. ```tsx const originalForm = form.create(rilay, 'question-form') .add({ id: 'question', type: 'text', props: { label: 'Your Question' } }); const jsonString = JSON.stringify(originalForm.toJSON()); // Later, or in another environment const rehydratedForm = form.create(rilay).fromJSON(JSON.parse(jsonString)); const formConfig = rehydratedForm.build(); ``` `fromJSON` replaces the content of an existing builder — call it on a freshly created builder to avoid mutating a shared instance. ## Introspection [#introspection] `.getStats()` returns a structural overview, useful for debugging: ```ts const stats = myFormBuilder.getStats(); /* { totalFields: 5, totalRows: 4, averageFieldsPerRow: 1.25, maxFieldsInRow: 2, minFieldsInRow: 1, totalRepeatables: 0, totalRepeatableFields: 0 } */ ``` # Building Forms `rilay.form(id)` (or `form.create(rilay, id)` with modular packages) returns a form builder wired to your component registry. This page covers adding fields, submit options, and field effects — it assumes a configured `rilay` instance ([Your First Form](/docs/getting-started/your-first-form)). ## Adding Fields [#adding-fields] `.add()` is polymorphic: * `.add(field)` — one field on its own row * `.add(field1, field2)` — multiple fields on the same row * `.add([field1, field2])` — equivalent array syntax ```tsx import { rilay } from '@/lib/rilay'; const registrationForm = rilay .form('registration') // Two fields on the same row .add( { id: 'firstName', type: 'text', props: { label: 'First Name' } }, { id: 'lastName', type: 'text', props: { label: 'Last Name' } } ) // One field on its own row .add({ id: 'email', type: 'email', props: { label: 'Email Address' } }); ``` `type` must exist in your component registry. `addSeparateRows([...])` places each field of an array on its own row. ## Field Configuration [#field-configuration] ```ts interface FieldConfig { id?: string; // Auto-generated ('field-1', 'field-2', …) if omitted type: string; // Component type from your registry props?: Record; // Passed to your component renderer validation?: FieldValidationConfig; // { validate?, debounceMs? } — see Validation conditions?: ConditionalBehavior; // visible/required/disabled/readonly — see Conditions effects?: FieldEffect[]; // Reactive side effects (below) } ``` ## When to use `.build()` [#when-to-use-build] `` and workflow steps build the configuration for you. Call `.build()` only when you need the final serializable `FormConfiguration` — to save it as JSON, pass it to a third-party tool, or inspect it while debugging. ```tsx const formConfig = rilay.form('my-form').add({ id: 'field1', type: 'text' }).build(); console.log(formConfig.allFields); ``` ## Submit Options [#submit-options] `.setSubmitOptions()` sets default submission behavior: | Option | Behavior | | ------------- | ------------------------------------------------------------------------------------------------- | | `force` | Bypass validation entirely and submit all current values as-is (e.g. "save draft"). | | `skipInvalid` | Run validation (errors still show in the UI) but exclude invalid fields from the `onSubmit` data. | When both are set, `force` wins. Defaults can be overridden at submit time via the `useForm()` hook (from `rilaykit/react`): ```tsx import { useForm } from 'rilaykit/react'; const { submit } = useForm(); await submit({ force: true }); ``` ## Field Effects [#field-effects] Effects declare reactive side effects in the field configuration — no `useEffect`. RilayKit handles subscriptions, cascading, and cleanup. Create them with the `onChange()` helper from `rilaykit`: ```tsx import { onChange } from 'rilaykit'; const addressForm = rilay .form('address') .add({ id: 'country', type: 'select', props: { label: 'Country', options: countries }, effects: [ onChange('country', async (value, { setValue, setProps }) => { setValue('city', ''); // reset the child setProps('city', { options: await fetchCities(value) }); // reload its options }), ], }) .add({ id: 'city', type: 'select', props: { label: 'City', options: [] } }); ``` The first argument of `onChange()` names the field being **watched**, not the field the effect is declared on — you can attach an effect to a `total` field that watches `price`. Effects also run at mount for fields with non-undefined `defaultValues`, so the example above loads cities immediately when `defaultValues={{ country: 'France' }}`. ### Context API [#context-api] Each handler receives the new value and a context: | Method | Description | | -------------------------- | ----------------------------------- | | `setValue(fieldId, value)` | Set another field's value | | `setProps(fieldId, props)` | Merge dynamic props into a field | | `getValues()` | Snapshot of all current form values | | `getFieldValue(fieldId)` | Get a single field's value | The engine has built-in protections — cascade depth limit (10), cycle detection, async abort on rapid changes. Don't handle these manually. # Form Hooks RilayKit forms expose granular Zustand selector hooks: subscribe to exactly the state slice you need instead of re-rendering the whole form on every change. All hooks require a `FormProvider` ancestor (the `` component includes one) and import from the `/react` entry: ```tsx import { useFieldValue, useFieldActions, useFormSubmitState } from '@rilaykit/forms/react'; ``` ## Context Hook [#context-hook] `useForm()` returns the full form context: configuration, condition helpers, validation, and submission. ```ts interface FormConfigContextValue { formConfig: FormConfiguration; formInstanceKey: string; // opaque identity of the mounted form — compare by equality only; changes on form swap conditionsHelpers: { hasConditionalFields: boolean; getFieldCondition(fieldId: string): ConditionEvaluationResult | undefined; isFieldVisible(fieldId: string): boolean; isFieldDisabled(fieldId: string): boolean; isFieldRequired(fieldId: string): boolean; isFieldReadonly(fieldId: string): boolean; }; validateField(fieldId: string, value?: unknown): Promise; validateForm(): Promise; validateFormLevel(): Promise; // re-run cross-field rules, route issues into the error map submit(eventOrOptions?: React.FormEvent | SubmitOptions): Promise; } ``` `submit` accepts a `React.FormEvent` (for ``) or options: ```ts const { submit } = useForm(); await submit(); // Validate, then submit await submit({ force: true }); // Skip validation entirely await submit({ skipInvalid: true }); // Validate, exclude invalid fields ``` `useForm()` re-renders whenever **any** part of the context changes. Prefer the granular hooks below for performance-sensitive components. ## Field State Hooks [#field-state-hooks] Read-only selectors scoped to one field — each re-renders only when its slice changes. | Hook | Returns | | ---------------------------------- | ----------------------------------------------------------------- | | `useFieldValue(fieldId)` | `T` | | `useFieldErrors(fieldId)` | `FieldError[]` (includes cross-field issues routed to this field) | | `useFieldTouched(fieldId)` | `boolean` | | `useFieldValidationState(fieldId)` | `ValidationState` | | `useFieldConditions(fieldId)` | `FieldConditions` | | `useFieldProps(fieldId)` | `Record` — dynamic props set by effects | | `useFieldState(fieldId)` | `FieldState` (value, errors, validationState, touched, dirty) | | `useRepeatableKeys(repeatableId)` | `string[]` — stable row keys of a repeatable | A typical field component pairs a read hook with `useFieldActions` (write): ```tsx import { useFieldValue, useFieldErrors, useFieldActions } from '@rilaykit/forms/react'; function CustomInput({ fieldId }: { fieldId: string }) { const value = useFieldValue(fieldId); const errors = useFieldErrors(fieldId); const { setValue, setTouched } = useFieldActions(fieldId); return (
setValue(e.target.value)} onBlur={() => setTouched()} /> {errors.map((err) => (

{err.message}

))}
); } ``` ### Types [#types] ```ts interface FieldError { readonly message: string; readonly code?: string; readonly path?: string; } type ValidationState = 'idle' | 'validating' | 'valid' | 'invalid'; interface FieldConditions { readonly visible: boolean; readonly disabled: boolean; readonly required: boolean; readonly readonly: boolean; } interface FieldState { readonly value: unknown; readonly errors: FieldError[]; readonly validationState: ValidationState; readonly touched: boolean; readonly dirty: boolean; } ``` ## Form State Hooks [#form-state-hooks] Form-level selectors, same granularity rules. | Hook | Returns | | ---------------------- | ------------------------------------------------------------------------------ | | `useFormSubmitting()` | `boolean` | | `useFormValid()` | `boolean` — counts the whole error map, `__form__` included | | `useFormDirty()` | `boolean` | | `useFormValues()` | `Record` — re-renders on **any** value change | | `useFormErrors()` | `FieldError[]` — the `__form__` bucket (cross-field issues targeting no field) | | `useFormSubmitState()` | `{ isSubmitting, isValid, isDirty }` | ```tsx import { useFormSubmitState, useFormErrors } from '@rilaykit/forms/react'; function SubmitBar() { const { isSubmitting, isValid, isDirty } = useFormSubmitState(); const formErrors = useFormErrors(); return ( <> {formErrors.length > 0 && (
{formErrors.map((e) => e.message).join(' ')}
)} ); } ``` ## Action Hooks [#action-hooks] Action hooks return **stable function references** that call directly into the store. They never subscribe to state, so they never cause re-renders — safe to pass as props or use in event handlers. ### Field Actions [#field-actions] ```ts import { useFieldActions } from '@rilaykit/forms/react'; const { setValue, setTouched, setErrors, clearErrors, setValidationState } = useFieldActions('email'); interface UseFieldActionsResult { setValue: (value: unknown) => void; setTouched: () => void; setErrors: (errors: FieldError[]) => void; clearErrors: () => void; setValidationState: (state: ValidationState) => void; } ``` ### Form Actions [#form-actions] ```ts import { useFormActions } from '@rilaykit/forms/react'; const { setValue, setTouched, setErrors, setSubmitting, reset, setFieldConditions } = useFormActions(); setValue('firstName', 'Ada'); reset(); // Back to default values reset({ firstName: 'Ada' }); // Explicit values reset(values, { items: ['k2', 'k0'] }); // Also restore repeatable row order interface UseFormActionsResult { setValue: (fieldId: string, value: unknown) => void; setTouched: (fieldId: string) => void; setErrors: (fieldId: string, errors: FieldError[]) => void; setSubmitting: (isSubmitting: boolean) => void; reset: (values?: Record, repeatableOrder?: Record) => void; setFieldConditions: (fieldId: string, conditions: FieldConditions) => void; } ``` `useFormStoreApi()` returns the raw Zustand store (no subscription) — useful for reading `store.getState()` imperatively, e.g. in tests. ## Condition Hooks [#condition-hooks] Evaluate conditional behaviors (visible, disabled, required, readonly) against form data. ### useConditionEvaluation [#useconditionevaluation] Evaluates one `ConditionalBehavior` against provided data. Memoized on `conditions` and `formData`. ```ts import { useConditionEvaluation } from '@rilaykit/forms/react'; const { visible, disabled, required, readonly } = useConditionEvaluation( fieldConfig.conditions, // ConditionalBehavior | undefined formData, // Record { visible: true }, // optional default state overrides ); ``` ### useFormConditions [#useformconditions] Evaluates all field conditions for a form configuration at once — what `FormProvider` uses internally. ```ts import { useFormConditions } from '@rilaykit/forms/react'; const { fieldConditions, hasConditionalFields, isFieldVisible, isFieldDisabled, isFieldRequired, isFieldReadonly, getFieldCondition } = useFormConditions({ formConfig, formValues }); ``` ### useFieldConditionsLazy [#usefieldconditionslazy] Reads conditions from the store and re-evaluates only when form values actually change (values hash). ```ts import { useFieldConditionsLazy } from '@rilaykit/forms/react'; const conditions = useFieldConditionsLazy('myField', { conditions: fieldConfig.conditions, skip: false, }); if (!conditions.visible) return null; ``` ### useConditionEvaluator [#useconditionevaluator] Returns a memoized evaluator to call imperatively for any field, without subscribing. ```ts import { useConditionEvaluator } from '@rilaykit/forms/react'; const evaluate = useConditionEvaluator(); const nameConditions = evaluate('name', nameFieldConfig.conditions); ``` ## Internal Hooks [#internal-hooks] Used internally by RilayKit components; exported for advanced cases. | Hook | Purpose | | ---------------------------- | ---------------------------------------------------------- | | `useFormValidationWithStore` | Wires field and form validation to the store | | `useFormSubmissionWithStore` | Handles the submission lifecycle | | `useFormMonitoring` | Tracks renders, validations, and submissions for profiling | ## Best Practices [#best-practices] 1. Prefer granular hooks over `useForm()` — a component that needs one value should use `useFieldValue(fieldId)`. 2. Use `useFormErrors()` for a form-level error banner (`aria-live`); field-targeted cross-field issues surface through `useFieldErrors(id)`. # Rendering Forms `rilaykit/react` (or `@rilaykit/forms/react`) exports the components that render a built form using the components registered on your `ril` instance. ## The `` Component [#the-form-component] The root component. Pass a form builder or built configuration via `of` — builders are auto-built. ```tsx import { Form } from 'rilaykit/react'; import { userForm } from '@/config/user-form'; function UserFormPage() { return ( console.log('Form submitted:', data)} > Save ); } ``` `
` renders a native `` element. Submit always validates; `onSubmit` is called only when the form is valid, and errored fields are marked touched so their errors show and clear live. ### Props [#props] | Prop | Description | | ----------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | | `of` | A built `FormConfiguration` or a form builder (auto-built). | | `defaults` | Initial values keyed by field id. Live: changing it re-seeds untouched fields; edited fields keep their value. | | `onSubmit(data)` | Receives the values when submission passes validation. | | `onFieldChange(fieldId, value, formData)` | Fires on every value change. | | `onFieldsRemove(fieldIds, formData)` | Fires when ids leave the store (a repeatable row was removed). | | `instanceId` | Distinguishes two mounts of the same config; changing it resets the store. | | `conditionValues` | Read-only external values that field conditions may reference (e.g. another step's data). Never stored or submitted. | | `className` | Passed to the underlying ``. | Subcomponents are also exported standalone: `FormBody`, `FormField`, `FormSubmit`, `FormList`. ## Layout Components [#layout-components] ### `` [#formbody] Renders every visible row: regular rows as a `div` of fields, repeatables as ``. Pass a render prop to lay rows out yourself: ```tsx {({ rows }) => rows.map((row) => /* your layout */)} ``` ### `` for Custom Layouts [#formfield-for-custom-layouts] Place any field anywhere; ``'s row structure is not used, the layout is yours. ```tsx
Save changes ``` ### `` [#formsubmit] Renders a ` )} ``` For rendering repeatable rows with ``, see [Repeatable Fields](/docs/forms/repeatable-fields). # Repeatable Fields Repeatable fields let users add, remove, and reorder groups of fields at runtime — "Add another item", "Add another contact", any list-like structure. ## Defining Repeatable Fields [#defining-repeatable-fields] Use `.addRepeatable()` on the form builder. It takes an ID and a callback that receives a `RepeatableBuilder`. ```tsx import { form } from '@rilaykit/forms'; import { required } from '@rilaykit/core'; import { rilay } from '@/lib/rilay'; const orderForm = form .create(rilay, 'order') .add({ id: 'customerName', type: 'text', props: { label: 'Customer' } }) .addRepeatable('items', (r) => r .add( { id: 'name', type: 'text', props: { label: 'Item' }, validation: { validate: required() } }, { id: 'qty', type: 'number', props: { label: 'Qty' } } ) .min(1) .max(10) .defaultValue({ name: '', qty: 1 }) ); ``` ### RepeatableBuilder API [#repeatablebuilder-api] All methods are chainable. | Method | Description | | -------------------------- | --------------------------------------------------------------------------------------------- | | `.add(...fields)` | Add fields to the template. Same API as `form.add()` — fields passed in one call share a row. | | `.addSeparateRows(fields)` | Add fields each on their own row. | | `.min(n)` | Minimum number of items (default 0). | | `.max(n)` | Maximum number of items (unlimited if not set). | | `.defaultValue(obj)` | Default values used when appending new items. | | `.validation(config)` | Group-level validation for the entire array. | Repeatables are strictly one level deep. Nesting a repeatable inside another throws at build time. ## Rendering Repeatable Fields [#rendering-repeatable-fields] ### Automatic with `` [#automatic-with-formbody] `` renders each repeatable as a `` with default markup (item rows plus an Add button). ```tsx import { Form, FormBody, FormSubmit } from '@rilaykit/forms/react'; function OrderPage() { return (
console.log(data)}> Place Order ); } ``` ### Custom Markup with `` [#custom-markup-with-formlist] `` accepts a render prop for custom layout: ```tsx import { FormList, FormField } from '@rilaykit/forms/react'; {({ items, add, remove, canAdd, canRemove }) => (
{items.map((item) => (
{item.allFields.map((field) => ( ))} {canRemove && ( )}
))} {canAdd && ( )}
)}
``` ### Full Control with `useRepeatableField` [#full-control-with-userepeatablefield] The hook behind ``: ```ts interface UseRepeatableFieldReturn { config: RepeatableFieldConfig | undefined; // undefined when the id is unknown items: RepeatableFieldItem[]; // Scoped items with composite field IDs append: (defaultValue?: Record) => void; remove: (key: string) => void; move: (fromIndex: number, toIndex: number) => void; canAdd: boolean; // false when count >= max canRemove: boolean; // false when count <= min count: number; } interface RepeatableFieldItem { key: string; // Unique stable key for React index: number; // Current position rows: FormFieldRow[]; // Scoped row configs allFields: FormFieldConfig[]; // Scoped field configs with composite IDs } ``` `move(fromIndex, toIndex)` reorders items — wire it to drag-and-drop or up/down buttons: ```tsx import { useRepeatableField } from '@rilaykit/forms/react'; function ReorderableList() { const { items, move } = useRepeatableField('items'); return items.map((item, index) => (
{/* fields... */}
)); } ``` ## Default Values [#default-values] Pass arrays at the top level of `defaults` — RilayKit handles the flat-to-nested conversion both ways, so `onSubmit` receives the same nested shape back: ```tsx
{/* ... */}
``` ## Validation [#validation] Fields inside a repeatable validate like static fields, independently per item. Timing follows the form-level `.setValidation({ mode, reValidateMode })` configuration — see [Validation](/docs/forms/validation). If the item count is below `min`, validation produces an error with code `REPEATABLE_MIN_COUNT`. At runtime, `canAdd` / `canRemove` reflect the constraints so you can disable buttons before validation runs. Cross-field (form-level) rules that target repeatable fields by dot path (`items.0.price`) never match the composite ids (`items[k0].price`) — their issues land in the `__form__` bucket, readable via `useFormErrors()`. ## Conditions [#conditions] [Conditions](/docs/core-concepts/conditions) inside a repeatable are scoped to the current item: `when('type')` reads that item's `type`, not another item's. ```tsx import { when } from '@rilaykit/core'; .addRepeatable('contacts', (r) => r .add( { id: 'type', type: 'select', props: { label: 'Type', options: ['email', 'phone'] } }, { id: 'email', type: 'email', props: { label: 'Email' }, conditions: { visible: when('type').equals('email') }, }, { id: 'phone', type: 'tel', props: { label: 'Phone' }, conditions: { visible: when('type').equals('phone') }, }, ) ) ``` # Server-Driven Forms # Server-Driven Forms [#server-driven-forms] `compileForm()` turns a JSON schema — validation, conditions, effects, repeatables included — into the same `FormConfiguration` the `form` builder produces. ## Quick Start [#quick-start] ```tsx import { compileForm } from '@rilaykit/forms'; import type { FormSchema } from '@rilaykit/forms'; import { Form, FormBody, FormSubmit } from '@rilaykit/forms/react'; import { rilay } from '@/lib/rilay'; // your ril catalog const schema: FormSchema = await fetch('/api/forms/contact').then(r => r.json()); const { formConfig, defaultValues } = compileForm(schema, rilay);
``` *** ## Schema Format [#schema-format] A `FormSchema` is plain JSON — no functions: ```json { "id": "contact", "defaultValues": { "country": "FR" }, "validation": { "mode": "onTouched", "reValidateMode": "onChange" }, "fields": [ { "id": "name", "type": "text", "props": { "label": "Full Name" }, "validation": { "rules": "required" } }, { "id": "email", "type": "text", "props": { "label": "Email" }, "validation": { "rules": ["required", "email"] } } ] } ``` Form-level `validation` accepts `mode`, `reValidateMode`, and `rules` (cross-field descriptors). Field-level `validation` accepts `rules` and `debounceMs`. ### Two Layout Modes [#two-layout-modes] Each field gets its own row: ```json { "id": "login", "fields": [ { "id": "email", "type": "text", "props": { "label": "Email" } }, { "id": "password", "type": "text", "props": { "label": "Password" } } ] } ``` Multiple fields per row, mixable with repeatable groups: ```json { "id": "address", "rows": [ { "kind": "fields", "fields": [ { "id": "firstName", "type": "text", "props": { "label": "First" } }, { "id": "lastName", "type": "text", "props": { "label": "Last" } } ] } ] } ``` A schema must have exactly **one** of `fields` or `rows` — not both. *** ## Validation Descriptors [#validation-descriptors] Rules are string shortcuts or parameterized objects — data only. ```json { "validation": { "rules": [ "required", { "type": "minLength", "params": { "min": 3 } }, { "type": "maxLength", "params": { "max": 100 }, "message": "Too long!" } ], "debounceMs": 300 } } ``` String shortcuts: `"required"`, `"email"`, `"url"`, `"number"`. | Type | Params | | ----------- | --------------------- | | `minLength` | `{ min: number }` | | `maxLength` | `{ max: number }` | | `min` | `{ min: number }` | | `max` | `{ max: number }` | | `pattern` | `{ pattern: string }` | `debounceMs` throttles async validation; blur and submit always validate immediately. Timing (`mode`, `reValidateMode`) is form-level — see the schema format above. ### Custom Validators via Bindings [#custom-validators-via-bindings] Logic that can't be JSON lives in `bindings`, referenced by key: ```tsx import { compileForm } from '@rilaykit/forms'; import type { Bindings } from '@rilaykit/forms'; import { custom } from '@rilaykit/core'; const bindings: Bindings = { validators: { postalCode: (params, message) => custom((v: string) => /^\d{5}$/.test(v), message ?? 'Invalid postal code'), }, }; // Schema side: // { "validation": { "rules": { "type": "postalCode", "message": "Enter a 5-digit ZIP" } } } const { formConfig } = compileForm(schema, rilay, { bindings }); ``` *** ## Conditions [#conditions] Conditions pass through unchanged — `ConditionConfig` is already JSON-serializable: ```json { "id": "companyName", "type": "text", "props": { "label": "Company Name" }, "conditions": { "visible": { "field": "accountType", "operator": "equals", "value": "business" }, "required": { "field": "accountType", "operator": "equals", "value": "business" } } } ``` All operators are supported: `equals`, `notEquals`, `greaterThan`, `lessThan`, `contains`, `in`, `exists`, `matches`, etc. *** ## Effects [#effects] Effects reference **handler keys** from the bindings — no inline functions. Optional `params` let one handler serve many fields: ```json { "id": "city", "type": "select", "props": { "label": "City", "options": [] }, "effects": [ { "trigger": "change", "watch": "country", "handler": "loadCities" }, { "trigger": "change", "watch": "country", "handler": "clearField", "params": { "target": "city" } } ] } ``` ```tsx const bindings: Bindings = { effects: { loadCities: async (newValue, { setValue, setProps }) => { setValue('city', ''); setProps('city', { options: await fetchCities(newValue as string) }); }, clearField: (newValue, { setValue }, params) => { setValue(params?.target as string, ''); }, }, }; ``` Handlers receive the same `FieldEffectContext` as programmatic effects (`setValue`, `setProps`, `getValues`, `getFieldValue`), plus the descriptor's `params` as a third argument. *** ## Repeatable Groups [#repeatable-groups] Via the `rows` format: ```json { "id": "team-form", "rows": [ { "kind": "repeatable", "repeatable": { "id": "members", "min": 1, "max": 5, "defaultValue": { "role": "member" }, "rows": [ { "fields": [ { "id": "name", "type": "text", "props": { "label": "Name" } }, { "id": "role", "type": "select", "props": { "label": "Role", "options": [] } } ] } ] } } ] } ``` *** ## Schema Validation [#schema-validation] `compileForm()` validates structure before building and throws `SchemaValidationError` with detailed issues: ```tsx import { compileForm, SchemaValidationError } from '@rilaykit/forms'; try { const { formConfig } = compileForm(schema, rilay, { bindings }); } catch (error) { if (error instanceof SchemaValidationError) { console.log(error.issues); // [{ path: "fields[0]", message: "Unknown component type: 'foo'", severity: "error" }] } } ``` To check without building, `validateSchema(schema, rilay, bindings)` throws the same error; `isFormSchema(value)` is a type guard that narrows to `FormSchema`. *** ## API Reference [#api-reference] ### `compileForm(schema, config, options?)` [#compileformschema-config-options] | Parameter | Type | Description | | ---------- | -------------------- | ------------------------------------------- | | `schema` | `FormSchema` | The JSON schema definition | | `config` | `RilayInstance` | Your ril catalog with registered components | | `options?` | `CompileFormOptions` | See below | | Option | Description | | --------------- | -------------------------------------------------------------------------------------------------------------------------------- | | `bindings` | Custom validators and effect handlers, resolved by key | | `validateProps` | Check each field's `props` against its component's `propsSchema`; violations become issues pathed to the exact prop | | `lenient` | Streaming tolerance: compile the compilable subset of a partial schema instead of throwing — only for schemas still streaming in | **Returns** `FormSchemaResult`: ```ts interface FormSchemaResult { readonly formConfig: FormConfiguration; readonly defaultValues?: Record; } ``` `fromSchema(schema, config, registry?)` still works but is deprecated — it's an alias for `compileForm(schema, config, { bindings: registry })`. Same for the `SchemaRegistry` type, renamed `Bindings`. ### `Bindings` [#bindings] ```ts interface Bindings { readonly validators?: Record; readonly effects?: Record; } type CustomValidatorFactory = ( params?: Record, message?: string ) => StandardSchema; type SchemaEffectHandler = ( newValue: unknown, context: FieldEffectContext, params?: Record ) => void | Promise; ``` ### `SchemaValidationError` [#schemavalidationerror] ```ts class SchemaValidationError extends Error { readonly code = 'SCHEMA_VALIDATION_ERROR'; readonly issues: SchemaIssue[]; } interface SchemaIssue { readonly path: string; readonly message: string; readonly severity: 'error' | 'warning'; } ``` # Universal Validation with Standard Schema RilayKit validates with any [Standard Schema](https://standardschema.dev) compatible library — Zod (3.24+), Yup (1.7+), Joi (18+), Valibot (1.0+), ArkType (2.0+) — no adapters needed. ## Field Validation [#field-validation] Each field's `validation` object accepts: | Property | Description | | ------------ | ------------------------------------------------------------------------------------------ | | `validate` | A Standard Schema validator, or an array of them | | `debounceMs` | Debounce validation runs (async cost control); blur and submit always validate immediately | Built-ins and external schemas mix freely in the same array: ```tsx import { z } from 'zod'; import { rilay } from '@/lib/rilay'; import { form } from '@rilaykit/forms'; import { required } from '@rilaykit/core'; const registrationForm = form.create(rilay, 'registration') .add({ id: 'email', type: 'email', props: { label: 'Email Address' }, validation: { validate: [ required('Email is required'), // RilayKit built-in z.string().email('Invalid email format'), // Zod schema ], }, }) .add({ id: 'password', type: 'password', props: { label: 'Password' }, validation: { validate: z.string().min(8, 'Password too short'), }, }); ``` ## Validation Timing [#validation-timing] Timing is configured form-wide via `.setValidation({ mode, reValidateMode })`, mirroring React Hook Form: | Option | Values | Default | Meaning | | ---------------- | ---------------------------------------------------------------------- | ------------- | ----------------------------------------- | | `mode` | `'onSubmit'` \| `'onBlur'` \| `'onChange'` \| `'onTouched'` \| `'all'` | `'onTouched'` | When a field validates for the first time | | `reValidateMode` | `'onChange'` \| `'onBlur'` \| `'onSubmit'` | `'onChange'` | When an errored field re-validates | ```tsx const strictForm = form.create(rilay, 'strict') .add({ id: 'email', type: 'email', validation: { validate: email() } }) .setValidation({ mode: 'onBlur', reValidateMode: 'onChange' }); ``` The default `'onTouched'` validates a field on its first blur, then live. Submit always validates everything and marks errored fields `touched`, so touched-gated renderers show submit errors — and they clear live as the user types. ## Built-in Validators [#built-in-validators] All from `@rilaykit/core`, all Standard Schema compatible: * `required(message?)`, `email(message?)`, `url(message?)` * `minLength(min, message?)`, `maxLength(max, message?)`, `pattern(regex, message?)` * `number(message?)`, `min(value, message?)`, `max(value, message?)` * `custom(fn, message?)`, `async(fn, message?)`, `combine(...validators)` ## Creating Custom Standard Schema Validators [#creating-custom-standard-schema-validators] ```ts import type { StandardSchemaV1 } from '@standard-schema/spec'; export function containsRilay(message = 'Value must contain "rilay"'): StandardSchemaV1 { return { '~standard': { version: 1, vendor: 'my-app', validate: (value: unknown) => { if (typeof value === 'string' && value.includes('rilay')) { return { value }; } return { issues: [{ message }] }; }, }, }; } ``` Use it like any other validator: `validation: { validate: [required(), containsRilay()] }`. ## Form-Level Validation [#form-level-validation] For cross-field rules, pass an object schema (or a `custom` validator over the form data) to `.setValidation`: ```tsx import { z } from 'zod'; const userSchema = z.object({ password: z.string().min(8, 'Password too short'), confirmPassword: z.string(), }).refine(data => data.password === data.confirmPassword, { message: "Passwords don't match", path: ['confirmPassword'], }); const changePasswordForm = form.create(rilay, 'change-password') .add({ type: 'password', id: 'password', props: { label: 'New Password' } }) .add({ type: 'password', id: 'confirmPassword', props: { label: 'Confirm Password' } }) .setValidation({ validate: userSchema }); ``` Form-level issues are routed by `issue.path`: * A path naming a known field attaches the error to that field — `useFieldErrors(id)` receives it alongside the field's own errors. * An empty or unmatched path lands in a reserved `__form__` bucket, read via `useFormErrors()`: ```tsx import { useFormErrors } from 'rilaykit/react'; function FormErrorBanner() { const errors = useFormErrors(); if (errors.length === 0) return null; return (
{errors.map(e =>

{e.message}

)}
); } ``` Form-level rules re-run on the same `mode`/`reValidateMode` cadence as field rules and on repeatable row changes, so cross-field errors appear and clear live — no resubmit needed. `isValid` counts the whole error map, `__form__` included. Repeatable fields use composite ids (`items[k0].price`) that never match a schema's dot path (`items.0.price`): cross-field issues over repeatable rows land in `__form__`. ## Async Validation [#async-validation] Standard Schema supports async validators; pair them with `debounceMs` to limit API calls: ```tsx const emailField = { id: 'email', type: 'email', props: { label: 'Email' }, validation: { validate: z.string() .email('Invalid email format') .refine(async (email) => { const response = await fetch(`/api/check-email?email=${email}`); const { isUnique } = await response.json(); return isUnique; }, 'Email is already taken'), debounceMs: 500, }, }; ``` # Component Registry Rilaykit is headless: you provide the components, Rilaykit provides the logic. The registry — a `ril` catalog — maps a `type` string to your renderer. ## Registering a Component [#registering-a-component] Use `.component(type, entry)` on a `ril` instance. Each call returns a new instance (immutable, chainable). Registering an existing type throws `DuplicateError` unless the entry sets `replace: true`. ```tsx title="lib/rilay.ts" import { ril } from 'rilaykit'; import { TextInput } from '@/components/TextInput'; import { Select } from '@/components/Select'; export const r = ril .create() .component('text', { name: 'Text Input', renderer: TextInput, }) .component('select', { name: 'Select', description: 'A dropdown for selecting options.', renderer: Select, defaultProps: { options: [] }, }); ``` ### Entry options [#entry-options] | Option | Description | | -------------- | ---------------------------------------------------------------- | | `renderer` | `(ctx: ComponentRenderContext) => React.ReactElement` | | `name` | Human-readable name | | `description` | Purpose of the component (also surfaced to agent manifests) | | `defaultProps` | Merged under each field's `props` (field props win) | | `propsSchema` | Standard Schema validating `props` — must validate synchronously | | `meta` | Arbitrary metadata, passed through to the render context | | `replace` | Allow overwriting an already-registered type | The same catalog also registers `.tool()` and `.part()` entries for agent UIs, and `.renderers({ components: {...} })` attaches renderers to schema-only entries later — useful when the catalog is built server-side and renderers attach on the client. ## The `ComponentRenderContext` [#the-componentrendercontext] Your renderer receives a single context object. Form state lives under `field` (absent for static, non-field components): ```ts interface ComponentRenderContext> { id: string; // unique field id props: TProps; // your custom props (defaultProps merged in) field?: FieldBinding; // form binding, when rendered as a field conditions?: FieldConditions; // required/disabled/readonly resolution children?: React.ReactNode; meta?: Record; } interface FieldBinding { value: unknown; onChange: (value: unknown) => void; onBlur: () => void; // feeds validation timing (mode/reValidateMode) error?: FieldError[]; disabled?: boolean; isValidating?: boolean; touched?: boolean; } ``` ### Example: a `TextInput` renderer [#example-a-textinput-renderer] ```tsx title="components/TextInput.tsx" import type { ComponentRenderContext } from 'rilaykit'; interface TextInputProps { label: string; placeholder?: string; required?: boolean; } export function TextInput({ id, props, field }: ComponentRenderContext) { const showError = field?.touched && field.error?.length; return (
field?.onChange(e.target.value)} onBlur={() => field?.onBlur()} placeholder={props.placeholder} disabled={field?.disabled} aria-invalid={!!showError} /> {showError ? (

{field.error?.[0]?.message}

) : null}
); } ``` Gating on `field.touched` pairs with the default validation timing (`mode: 'onTouched'`): errors appear after first blur — or on submit, which marks errored fields touched — then clear live. # Conditions System Conditions control field visibility, requirement, disabled/readonly state, and workflow step navigation. They re-evaluate live as values change. ## The `when()` Function [#the-when-function] `when(fieldPath)` returns a `ConditionBuilder`: ```typescript import { when } from 'rilaykit'; const condition = when('age').greaterThan(18); condition.evaluate({ age: 25 }); // true condition.build(); // serializable ConditionConfig, useful for logging ``` ## Operators [#operators] | Operator | True when | | ---------------------------------------------- | -------------------------------------------------- | | `equals(value)` / `notEquals(value)` | Strict (in)equality | | `greaterThan(n)` / `lessThan(n)` | Numeric comparison | | `greaterThanOrEqual(n)` / `lessThanOrEqual(n)` | Numeric comparison, inclusive | | `contains(value)` / `notContains(value)` | String includes substring, or array includes value | | `in(values)` / `notIn(values)` | Field value is (not) in the given list | | `matches(pattern)` | String matches a `RegExp` or pattern string | | `exists()` / `notExists()` | Value is (not) `null`/`undefined` | Combine with `.and()` / `.or()` — nesting groups sub-conditions: ```typescript when('userType').equals('premium') .and( when('subscription.plan').equals('pro') .or(when('subscription.legacy').equals(true)) ); ``` ## Field Path Resolution [#field-path-resolution] Paths use dot notation for nested data: `when('user.profile.age').greaterThan(18)` reads `data.user.profile.age`. A key that exists verbatim (e.g. a repeatable composite id like `items[k0].type`) is matched directly before dot-path traversal. ## Field-Level Conditions [#field-level-conditions] Fields accept four condition keys: `visible`, `required`, `disabled`, `readonly`. ```typescript form.create(rilay, 'checkout') .add({ id: 'creditCardNumber', type: 'text', props: { label: 'Credit Card Number' }, conditions: { visible: when('paymentMethod').equals('credit_card'), required: when('paymentMethod').equals('credit_card'), }, }) .add({ id: 'email', type: 'email', props: { label: 'Email Address' }, conditions: { disabled: when('emailVerified').equals(true), readonly: when('accountLocked').equals(true), }, }); ``` `conditions.required` is enforced on its own — no `validation` block needed. When the condition is true and the field is empty, submit is blocked. ## Step-Level Conditions (Workflows) [#step-level-conditions-workflows] Steps accept `visible` and `skippable`. Reference previous steps' data with `"stepId.fieldId"`: ```typescript const workflow = flow.create(rilay, 'user-onboarding') .step({ id: 'personal-info', title: 'Personal Information', formConfig: personalInfoForm, }) .step({ id: 'payment-info', title: 'Payment Information', conditions: { visible: when('personal-info.planType').equals('premium') .or(when('company-info.employees').greaterThan(50)), skippable: when('personal-info.planType').notEquals('premium'), }, formConfig: paymentForm, }); ``` A hidden step is treated as nonexistent: navigation jumps over it and it is absent from the `onComplete(data, meta)` payload (`meta.skippedSteps` / `meta.passedSteps` record why). ## Conditions and Validation [#conditions-and-validation] An invisible field is treated as nonexistent: its validation is skipped, its errors are cleared, and it never blocks submit — even if it becomes invisible mid-async-validation. ## Best Practices [#best-practices] * Prefer several simple conditions over one deeply nested tree. * Test conditions against empty, `null`, and `undefined` values — numeric operators return `false` for non-numbers. * Avoid circular dependencies between fields' conditions. # Philosophy RilayKit rests on a few deliberate architectural decisions. Knowing them helps you use the library well. ## Schema-First Design [#schema-first-design] Forms are data, not imperative code. Instead of scattering state, handlers, and validation effects across JSX, a RilayKit form is a **declarative data structure**: plain, serializable, introspectable, and composable — "JSON Schema for forms, but type-safe." ```tsx import { form, required, email } from 'rilaykit'; const contactForm = form.create(rilay, 'contact') .add({ id: 'name', type: 'input', props: { label: 'Name' }, validation: { validate: [required()] } }) .add({ id: 'email', type: 'input', props: { label: 'Email' }, validation: { validate: [required(), email()] } }); ``` The builder separates the **what** (fields, rules, conditions) from the **how** (rendering, events). The resulting configuration can be passed to a React provider, stored in a database, or inspected by tooling — without touching rendering code. ## Headless by Design [#headless-by-design] RilayKit generates **zero HTML** and **zero CSS**. It is a pure logic layer: state management, validation orchestration, condition evaluation, workflow navigation. You provide everything visual — markup, styling, ARIA, animations. Your renderers are plain React components that receive standardized props from the engine, so RilayKit works with any design system. Headless means you own accessibility: ARIA attributes, focus management, keyboard navigation. See [Renderers](/docs/core-concepts/renderers) for patterns. ## Immutability and Type Accumulation [#immutability-and-type-accumulation] Each builder method returns a **new typed instance**. `.component('input', …)` extends the type to include `'input'`; adding `'select'` grows it to `'input' | 'select'`. This gives full autocompletion on `.add({ type: '…' })`, catches typos at compile time, and propagates component prop types through the chain. ```tsx const rilay = ril.create() .component('input', { renderer: Input }) .component('select', { renderer: Select }); form.create(rilay, 'test') .add({ id: 'field', type: 'input', props: { /* Input props autocompleted */ } }) .add({ id: 'field2', type: 'unknown' }); // Compile error ``` Because the API is immutable, calling `.component()` without capturing the return value has no effect — by design. ## Separation of Layers [#separation-of-layers] 1. **Registry** (`ril.create().component(...)`) — maps type names to renderers and default props. Configured once per application. 2. **Builder** (`form.create(rilay).add(...)`) — constructs form and workflow configurations as data. No React dependency. 3. **Provider** (`
`) — React context managing state, validation, and rendering orchestration. 4. **Renderer** (your components) — receives props, renders UI. Entirely yours. ``` Registry (ril.create) | component definitions Builder (form.create / flow.create) | form/workflow config Provider ( / ) | state + props Renderer (your components) | HTML + CSS User ``` Registry and Builder run anywhere — Node, tests, build scripts. Only the Provider touches React. So you can test configurations without rendering, generate configs server-side, share registries across apps, and swap renderers without touching configuration. ## Serialization as a First-Class Concern [#serialization-as-a-first-class-concern] Configurations serialize with `.toJSON()` and restore with `.fromJSON()` — natural, since they are already plain data. This enables visual form builders, server-driven forms, version-controlled form definitions, and A/B variants via `.clone()`. ```tsx const json = JSON.stringify(myForm.toJSON()); // Later, rehydrate it const restored = form.create(rilay).fromJSON(JSON.parse(json)); ``` Serialization is structural — field definitions, validation rules, and conditions, but not renderer functions. After `fromJSON()`, use the same `ril` instance to supply the renderers. # Renderers Rilaykit is headless: every pixel comes from a renderer you own. Rendering has two layers — **catalog renderers** draw registered components, tools, and parts; **structural components** provide overridable layout (body, submit, flow navigation). ## Catalog renderers [#catalog-renderers] Attach a `renderer` when registering an entry, or later with `.renderers()`. Both are immutable and return a new instance. ```tsx title="lib/catalog.tsx" import { ril } from 'rilaykit'; export const catalog = ril.create().component('text', { name: 'Text Input', renderer: ({ id, props, field }) => (
field?.onChange(e.target.value)} onBlur={field?.onBlur} disabled={field?.disabled} aria-invalid={!!field?.error?.length} {...props} /> {field?.touched && field?.error?.map((e) => (

{e.message}

))}
), }); ``` `.renderers()` attaches or overrides renderers on already-registered entries — useful when definitions live server-side and UI lives in a client file: ```tsx export const uiCatalog = catalog.renderers({ components: { text: (ctx) => }, tools: { my_tool: (ctx) => }, parts: { text: ({ part }) => {part.text} }, }); ``` | Bag | Renders | Context | | ------------ | ------------------ | ----------------------------------------------------------------------------- | | `components` | form fields | `ComponentRenderContext` — `{ id, props, field, conditions, children, meta }` | | `tools` | agent tool calls | `ToolRenderContext` — `{ toolCallId, state, input, output, resolve, … }` | | `parts` | chat message parts | `PartRenderContext` — `{ part, meta }` | `ctx.field` is the binding: `value`, `onChange`, `onBlur`, `error`, `touched`, `disabled`, `isValidating`. An entry without a renderer is a valid blueprint (server-side builds, agent manifests) — `validate()` doesn't flag it; `validateAsync()` surfaces it as a warning. Rendering it through `FormField` throws, so every component a form displays needs one. ## Structural components [#structural-components] Structural components ship minimal unstyled defaults tagged with `data-*` attributes for CSS. Pass a render-prop `children` to replace the markup entirely. | Component | Default | Render-prop context | | ------------------------------------ | ----------------------------------------------------------------- | --------------------------------------------- | | `FormBody` | `
`, one `
` per visible row | `{ rows: VisibleRow[] }` | | `FormSubmit` | ` )} ; ``` # The `ril` Instance The `ril` instance is RilayKit's central catalog: it registers components, tools, and message parts, and creates type-safe `form` and `flow` builders that inherit its configuration. Create one shared instance and export it from a central file (e.g. `lib/rilay.ts`). ## Creating and Configuring [#creating-and-configuring] Call `ril.create()` and chain registrations. Every method is **immutable** — it returns a new instance, so keep the final result of the chain. ```tsx title="lib/rilay.ts" import { ril } from 'rilaykit'; import { TextInput } from '@/components/TextInput'; export const rilay = ril .create() // Register a component type named 'text' .component('text', { name: 'Text Input', renderer: TextInput, }) // Register an agent tool and a message-part renderer (optional) .tool('search_flights', { description: 'Search flights', inputSchema: flightSchema }) .part('text', { renderer: TextPart }); ``` A component entry accepts `name`, `description`, `renderer`, `propsSchema` (Standard Schema, validated via `validateProps`), `defaultProps`, `validation`, `meta`, and `replace` (allow overwriting — otherwise a duplicate id throws). Two more chaining methods: * **`use(plugin)`** — applies a `RilayPlugin` (a function that registers entries and returns the extended instance). * **`renderers({ components, tools, parts })`** — attaches or overrides renderers on already-registered entries; schemas and metadata are preserved. ## Builder Methods [#builder-methods] With the all-in-one `rilaykit` package, the instance creates builders directly: ```tsx const myForm = rilay.form('my-form') .add({ type: 'text', props: { label: 'Name' } }); const myWorkflow = rilay.flow('my-workflow', 'My Workflow') .step({ title: 'Step 1', formConfig: myForm }); ``` * **`.form(formId?)`** — equivalent to `form.create(rilay, formId)` * **`.flow(workflowId?, name?, description?)`** — equivalent to `flow.create(rilay, workflowId, name, description)` With the modular packages (`@rilaykit/forms`, `@rilaykit/workflow`), use `form.create(rilay)` and `flow.create(rilay)` instead. ## Catalog API [#catalog-api] | Method | Returns | | -------------------------------------------------------- | ------------------------------------------------------------ | | `getComponent(id)` / `getTool(name)` / `getPart(type)` | The entry, or `undefined` | | `getAllComponents()` / `getAllTools()` / `getAllParts()` | All entries of that kind | | `hasComponent(id)` | `boolean` | | `validateProps(type, props)` | Success/failure result against the component's `propsSchema` | | `removeComponent(id)` | New instance without the component | | `clear()` | New instance with an empty catalog | | `clone()` | Copy of the instance | ## Introspection & Debugging [#introspection--debugging] ### `getStats()` [#getstats] Entry counts by kind: ```ts rilay.getStats(); // { total: 3, components: 1, tools: 1, parts: 1 } ``` ### `validate()` and `validateAsync()` [#validate-and-validateasync] `validate()` returns an array of error strings (e.g. duplicate component types) — empty means valid. `validateAsync()` additionally reports warnings such as renderer-less components, and throws a `ValidationError` when errors are found. # TypeScript Support RilayKit is built around **type propagation**: each registered component extends the catalog's `{ type → props }` map on the `ril` generic, so form definitions are checked against your components at compile time. ## Type Propagation [#type-propagation] ### Step 1: Component Registration [#step-1-component-registration] Each `.component()` call extends the generic. `TProps` is inferred from the renderer's `ComponentRenderContext` parameter (or from `propsSchema`): ```tsx title="lib/rilay.ts" import { ril, type ComponentRenderContext } from 'rilaykit'; interface TextInputProps { label: string; placeholder?: string; } interface SelectInputProps { label: string; options: Array<{ value: string; label: string }>; } function TextInput(ctx: ComponentRenderContext) { /* ... */ } function SelectInput(ctx: ComponentRenderContext) { /* ... */ } export const rilay = ril .create() .component('text', { name: 'Text Input', renderer: TextInput }) .component('select', { name: 'Select Input', renderer: SelectInput }); // rilay: ril<{ text: TextInputProps; select: SelectInputProps }> ``` ### Step 2: Form Building [#step-2-form-building] In `.add()`, `type` autocompletes from the registered keys and `props` narrows to that component's own props — per argument, so a variadic `.add(a, b)` checks each field against its own `type`: ```tsx import { form, required, email } from 'rilaykit'; import { rilay } from '@/lib/rilay'; const loginForm = form.create(rilay, 'login') .add({ id: 'email', type: 'text', // autocompletes: 'text' | 'select' props: { label: 'Email' }, // checked against Partial validation: { validate: [required(), email()] }, }); ``` `props` is typed `Partial`: unknown keys and wrong value types are compile errors, but a *missing* required prop is not. Register a `propsSchema` on the component to catch that at runtime (`rilay.validateProps(type, props)`, or `compileForm(..., { validateProps: true })`). ## Error Prevention at Compile Time [#error-prevention-at-compile-time] ```tsx form.create(rilay, 'test').add({ type: 'checkbox', // Error: '"checkbox"' is not assignable to '"text" | "select"' props: { label: 'Accept' }, }); form.create(rilay, 'test').add({ id: 'email', type: 'text', props: { label: 'Email', options: [], // Error: 'options' does not exist on Partial }, }); ``` ## Immutable API [#immutable-api] `ril` is immutable — `.component()` returns a **new** instance with an extended type. Chain calls or assign the result; a discarded return value registers nothing: ```tsx const base = ril.create(); base.component('text', { renderer: TextInput }); // base is unchanged — 'text' was registered on a discarded instance const rilay = ril.create().component('text', { renderer: TextInput }); // rilay: ril<{ text: TextInputProps }> ``` ## Workflows [#workflows] Step definitions are type-checked too — `formConfig` accepts a built `FormConfiguration` or a `form` builder: ```tsx import { flow } from 'rilaykit'; const workflow = flow.create(rilay, 'onboarding', 'Onboarding') .step({ id: 'personal', title: 'Personal Information', formConfig: loginForm, // type-checked }); ``` ## Best Practices [#best-practices] * Define an explicit props interface per component and annotate the renderer's `ComponentRenderContext` — inference flows from there * Export a single shared `rilay` instance from a central file (e.g. `lib/rilay.ts`) * Let TypeScript infer the generics — don't specify them manually * Enable `strict` mode in `tsconfig.json` # Validation RilayKit's validation engine implements [Standard Schema](https://standardschema.dev): use the built-in validators **or** any compliant library (Zod 3.24+, Valibot 1.0+, ArkType 2.0+) interchangeably, without adapters. ## Built-in Validators [#built-in-validators] All built-ins are imported from `@rilaykit/core`. Each accepts an optional custom message and returns a `StandardSchemaV1` object. | Validator | Validates | Default message | | -------------------------- | --------------------------------------------------------- | -------------------------------------------- | | `required(message?)` | Non-empty (rejects `''`, `null`, `undefined`, `[]`, `{}`) | `This field is required` | | `email(message?)` | Email format | `Please enter a valid email address` | | `url(message?)` | URL format (native `URL` constructor) | `Please enter a valid URL` | | `minLength(min, message?)` | Minimum string length | `Must be at least {min} characters long` | | `maxLength(max, message?)` | Maximum string length | `Must be no more than {max} characters long` | | `pattern(regex, message?)` | Regular expression match | `Value does not match required pattern` | | `number(message?)` | Valid number (coerces strings) | `Must be a valid number` | | `min(minValue, message?)` | Minimum numeric value (coerces strings) | `Must be at least {minValue}` | | `max(maxValue, message?)` | Maximum numeric value (coerces strings) | `Must be no more than {maxValue}` | | `custom(fn, message?)` | Sync predicate `(value) => boolean` | `Validation failed` | | `async(fn, message?)` | Async predicate `(value) => Promise` | `Async validation failed` | | `combine(...schemas)` | Runs schemas in sequence, accumulates all issues | — | ```ts import { required, minLength, custom, async } from '@rilaykit/core'; required('Please fill this in'); minLength(8, 'Password is too short'); custom((value) => value.startsWith('SK_'), 'Must start with SK_'); async(async (value) => (await fetch(`/api/check?name=${value}`)).ok, 'Already taken'); ``` ## Standard Schema Support [#standard-schema-support] Any library implementing `StandardSchemaV1` works directly — Zod (3.24+), Valibot (1.0+), and ArkType (2.0+) all support it natively. Built-ins and third-party schemas mix freely in the same `validate` array; they run in order and all issues accumulate. ```tsx import { required, minLength } from '@rilaykit/core'; import { form } from '@rilaykit/forms'; import { z } from 'zod'; const profileForm = form.create(rilay, 'profile').add({ id: 'username', type: 'input', props: { label: 'Username' }, validation: { validate: [ required(), // RilayKit built-in minLength(3), // RilayKit built-in z.string().regex(/^[a-z0-9]+$/), // Zod schema // v.pipe(v.string(), v.email()) // Valibot works too // type('string.email') // ...and ArkType ], }, }); ``` The `validation` property is always an **object** with a `validate` key -- never a bare array. Use `{ validate: [...] }`, not `[...]`. ## Validation Timing [#validation-timing] Timing is configured **form-level** via `setValidation()`, mirroring React Hook Form's two-phase model: | Option | Values | Default | Controls | | ---------------- | -------------------------------------------------------------- | ------------- | ------------------------------------------------- | | `mode` | `'onSubmit' \| 'onBlur' \| 'onChange' \| 'onTouched' \| 'all'` | `'onTouched'` | When a field **first** validates | | `reValidateMode` | `'onChange' \| 'onBlur' \| 'onSubmit'` | `'onChange'` | When a field **re-validates** once it has errored | The defaults mean: a field validates on its first blur, then live -- and once it shows an error, the error clears live as the user types the fix. (Note: RHF's own `mode` default is `onSubmit`; RilayKit keeps its historical `onTouched`.) Submit always validates everything and marks errored fields `touched`, so touched-gated renderers show submit errors immediately. ```tsx const contactForm = form.create(rilay, 'contact') .add({ id: 'email', type: 'input', props: { label: 'Email' }, validation: { validate: [required(), email()], debounceMs: 300, // per-field async cost control }, }) .setValidation({ mode: 'onBlur', reValidateMode: 'onChange' }); ``` ### Field-Level: `FieldValidationConfig` [#field-level-fieldvalidationconfig] ```ts interface FieldValidationConfig { /** One or more Standard Schema validators */ validate?: StandardSchema | StandardSchema[]; /** Debounce change-triggered validation (async cost control). Blur and submit always validate immediately. */ debounceMs?: number; } ``` ## Form-Level Validation [#form-level-validation] For cross-field rules (e.g. "confirm password must match"), pass `validate` to `setValidation()`. Form-level schemas receive the entire form data. ```tsx import { z } from 'zod'; import { form } from '@rilaykit/forms'; const passwordSchema = z .object({ password: z.string().min(8, 'Password too short'), confirmPassword: z.string(), }) .refine((data) => data.password === data.confirmPassword, { message: "Passwords don't match", path: ['confirmPassword'], // routes the error to that field }); const changePasswordForm = form.create(rilay, 'change-password') .add({ id: 'password', type: 'password', props: { label: 'New Password' } }) .add({ id: 'confirmPassword', type: 'password', props: { label: 'Confirm Password' } }) .setValidation({ validate: passwordSchema }); ``` ### Error routing [#error-routing] Form-level issues are written to the error store, routed by `issue.path`: * A path naming a known field attaches the error to **that field** -- `useFieldErrors('confirmPassword')` receives it (tagged with `FORM_LEVEL_ERROR_CODE`). * An empty or unmatched path lands in the reserved `__form__` bucket. Read it with `useFormErrors()` (from `@rilaykit/forms/react` or `rilaykit/react`) to render a form-level error banner. * `isValid` counts the whole map, `__form__` included. ```tsx import { useFormErrors } from '@rilaykit/forms/react'; function FormErrorBanner() { const errors = useFormErrors(); if (errors.length === 0) return null; return
{errors.map((e) => e.message).join(' ')}
; } ``` Form-level rules re-run on the same `mode`/`reValidateMode` cadence as fields, and on repeatable row add/remove/move -- cross-field errors appear and clear live, no resubmit needed. The constants `FORM_LEVEL_ERROR_KEY` (`'__form__'`) and `FORM_LEVEL_ERROR_CODE` (`'FORM_LEVEL'`) are exported from `@rilaykit/core`. Repeatable composite ids (`items[k0].price`) never match a schema's dot path (`items.0.price`), so cross-field issues over repeatable rows land in `__form__`. ## Utility Functions [#utility-functions] ### `isStandardSchema(value)` [#isstandardschemavalue] Type guard for the Standard Schema interface. ```ts import { isStandardSchema } from '@rilaykit/core'; isStandardSchema(required()); // true isStandardSchema(z.string().email()); // true isStandardSchema('not a schema'); // false ``` ### `combineSchemas(...schemas)` [#combineschemasschemas] Merges multiple Standard Schema objects into one -- useful where a single schema is expected instead of an array. Equivalent to `combine()` from the validators; use whichever import reads clearest. ```ts import { combineSchemas, required, email } from '@rilaykit/core'; const emailSchema = combineSchemas(required('Email is required'), email(), z.string().min(5)); ``` # Installation ## Quick Start (Recommended) [#quick-start-recommended] The all-in-one `rilaykit` package bundles core, forms, workflows, and the agent toolkit: ```bash pnpm add rilaykit ``` ```bash npm install rilaykit ``` ```bash yarn add rilaykit ``` ```bash bun add rilaykit ``` Two entry points: the main entry is React-free (safe in Server Components); components and hooks come from `rilaykit/react`: ```tsx import { ril, required, when } from 'rilaykit'; import { Form, FormField, Flow } from 'rilaykit/react'; ``` The `ril` instance exposes `.form()` and `.flow()` directly: ```tsx const r = ril.create().component('input', { renderer: renderInput }); const contactForm = r.form('contact') .add({ id: 'name', type: 'input', props: { label: 'Name' } }) .build(); const onboarding = r.flow('onboarding', 'Onboarding') .step({ title: 'Step 1', formConfig: contactForm }) .build(); ``` AI adapters ship as sub-entries: `rilaykit/ai-sdk` (Vercel AI SDK, requires the optional `ai >= 5` peer) and `rilaykit/anthropic` (requires `@anthropic-ai/sdk`). ## Package Overview [#package-overview] | Package | Description | | -------------------- | -------------------------------------------------------------------------------------------- | | `rilaykit` | **Recommended** — all-in-one, re-exports everything below plus the enhanced `ril` | | `@rilaykit/core` | Engine: component catalog, types, validation, conditions | | `@rilaykit/forms` | Form builder + React components | | `@rilaykit/workflow` | Multi-step workflows: navigation, persistence, analytics | | `@rilaykit/agent` | AI chat tools (`show_form` / `show_flow` / `show_component`) + AI SDK and Anthropic adapters | All packages are MIT-licensed. Each pairs a React-free main entry with a `/react` entry for components and hooks. ## Modular Installation [#modular-installation] `@rilaykit/core` is the required foundation: ```bash pnpm add @rilaykit/core @rilaykit/forms # forms only pnpm add @rilaykit/core @rilaykit/forms @rilaykit/workflow # + workflows pnpm add @rilaykit/core @rilaykit/forms @rilaykit/workflow @rilaykit/agent # + agent ``` ## Validation Libraries [#validation-libraries] Any [Standard Schema](https://standardschema.dev) library works — no adapters: ```bash pnpm add zod # or valibot, arktype, ... ``` ## Requirements [#requirements] * React `>= 18` (peer dependency) * TypeScript `>= 5` recommended * `ai >= 5` — optional peer, only needed for the `rilaykit/ai-sdk` adapter Works with any React framework: Next.js (main entries are RSC-safe; `/react` entries ship `'use client'`), Vite, Remix, and others. ## Next Steps [#next-steps] * [Your First Form](/getting-started/your-first-form) * [Examples](/examples) # Your First Form Build a contact form with validation, a conditionally visible field, and full type safety. ### 1. Create a Component Renderer [#1-create-a-component-renderer] RilayKit is headless: it handles the logic, you provide the UI. A renderer is a function that receives a `ComponentRenderContext` — the field's `id`, your `props`, and a `field` binding (`value`, `onChange`, `onBlur`, `error`, `touched`) — and returns your markup. ```tsx title="lib/components.tsx" import type { ChangeEvent } from 'react'; import type { ComponentRenderContext } from 'rilaykit'; interface InputProps { label: string; type?: 'text' | 'email'; placeholder?: string; required?: boolean; multiline?: boolean; rows?: number; } export function InputRenderer({ id, props, field }: ComponentRenderContext) { const error = field?.error?.[0]; const shared = { id, value: (field?.value as string) ?? '', onChange: (e: ChangeEvent) => field?.onChange(e.target.value), onBlur: field?.onBlur, placeholder: props.placeholder, className: error ? 'input input-error' : 'input', }; return (
{props.multiline ? (