@vielzeug/codex 26.11.8 → 26.11.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  # Vielzeug: Full Documentation
2
2
 
3
- > Complete documentation for 43 packages. Version: 26.11.7
3
+ > Complete documentation for 43 packages. Version: 26.11.9
4
4
 
5
5
  ---
6
6
 
@@ -16817,7 +16817,7 @@ define('my-counter', {
16817
16817
 
16818
16818
  ## API Overview
16819
16819
 
16820
- All browser-runtime symbols below are imported from `@vielzeug/ore`. Lifecycle/context/binding functions (`onMounted`, `onCleanup`, `onEvent`, `onElement`, `watchEffect`, `bind`, `provide`, `useEmit`, `useSlots`, `getHost`) resolve the active component through an implicit "current component" context: they work when called synchronously during `setup()`, or from any composable function `setup()` calls (transitively), but throw if called outside that window.
16820
+ All browser-runtime symbols below are imported from `@vielzeug/ore`. Lifecycle/context/binding functions (`onMounted`, `onCleanup`, `onEvent`, `onElement`, `watchEffect`, `bind`, `provide`, `useEmit`, `useSlots`, `getHost`) resolve the active component through an implicit "current component" context: they work when called synchronously during `setup()`, or from any composable function `setup()` calls (transitively), but throw if called outside that window. The one exception is `bind()` with an explicit `options.target`: it also works outside setup (for example from an event handler), where only its returned disposer stops it.
16821
16821
 
16822
16822
  > `watchEffect` is not named `watch`: `@vielzeug/ripple` already exports a `watch(source, callback)` with different semantics (explicit source + old/new value pair), and the two are frequently imported in the same file.
16823
16823
 
@@ -16831,10 +16831,9 @@ All browser-runtime symbols below are imported from `@vielzeug/ore`. Lifecycle/c
16831
16831
  | `createContext()` | Create a unique typed injection key | Sync | Context is scoped to the component tree |
16832
16832
  | `each()` | Keyed list rendering with DOM diffing | Sync | Duplicate keys report `ore:error`; plain `T[]` is a one-time static render |
16833
16833
  | `when()` | Conditional branch rendering | Sync | Getter-fn computed disposed on cleanup; static bool skips subscription |
16834
- | `live(signal)` | One-way binding that skips stale writes during input | Sync | Use for controlled inputs alongside a manual `@input` handler |
16835
16834
  | `model(signal)` | Two-way form-control binding (value/checked + write-back) | Sync | Plain `value`/`checked` attribute only; pass `get` to keep numeric signals numeric |
16836
16835
  | `onMounted(fn)` | DOM-ready callback | Setup only | Must be called synchronously during `setup()` |
16837
- | `onCleanup(fn)` | Register teardown | Setup only | Called on component disconnect |
16836
+ | `onCleanup(fn)` | Register teardown | Setup only | Called on disconnect, one microtask later, unless the element reconnects (a same-turn move) |
16838
16837
  | `onEvent(target, …)` | Scoped event listener with auto-cleanup | Setup only | No-ops on null target; removed on disconnect |
16839
16838
  | `useField(options)` | Wire signal to form `ElementInternals` | Setup only | Requires `formAssociated: true` on the component definition |
16840
16839
  | `onFormReset(fn)` | Run work when the ancestor `` resets | Setup only | Fires every reset (not one-shot); only for `formAssociated: true` components |
@@ -16860,6 +16859,9 @@ define(tag: string, definition: ComponentDefinition): CustomElementConstructor;
16860
16859
 
16861
16860
  Returns the registered class (for `instanceof` or subclassing); registration itself is the only global side effect.
16862
16861
 
16862
+ Omit `Props` to infer prop types from `props`. Pass it explicitly when a public props type already exists: every key it
16863
+ declares must then have a definition in `props`.
16864
+
16863
16865
  The `setup()` function receives only typed prop signals:
16864
16866
 
16865
16867
  ```ts
@@ -16883,7 +16885,8 @@ define('my-card', {
16883
16885
  // emit() returns dispatchEvent's boolean: false if a listener called preventDefault()
16884
16886
  const notCancelled = emit('close');
16885
16887
 
16886
- return html`${when(slots.has('header'), () => html``)}`;
16888
+ // Render the unconditionally: has() observes rendered slots, so gating the slot itself on has() never shows it.
16889
+ return html` !slots.has('header').value}>`;
16887
16890
  },
16888
16891
  });
16889
16892
  ```
@@ -16957,7 +16960,7 @@ setup(_props) {
16957
16960
  > - **`prop.json`**: value can be declared in HTML (``); attribute string is `JSON.parse`d.
16958
16961
  > - **`prop.data`**: value is always set from JavaScript (objects, arrays, callbacks, class instances); the attribute is never read. Use this for both data and function props.
16959
16962
 
16960
- When you need custom parsing or `reflect: false`, use a raw `PropDef` object:
16963
+ When you need custom parsing or `reflect: false`, use a raw `PropDef` object. Any `{ default, parse, reflect? }` object is a valid prop definition; `reflect` defaults to `false` for raw objects (the `prop.*` helpers reflect, except `prop.json` and `prop.data`). `define()` reports every invalid definition in one `OreApiError`:
16961
16964
 
16962
16965
  ```ts
16963
16966
  props: {
@@ -16989,6 +16992,10 @@ Tagged template literal that returns an `HTMLResult`. Supports text interpolatio
16989
16992
  boolean attributes (`?attr=`), explicit property bindings (`.prop=`), events (`@event=` with optional
16990
16993
  `.stop`/`.prevent`/`.once`/`.capture` modifiers), refs (`ref=`), and nested templates.
16991
16994
 
16995
+ An `HTMLResult` is opaque and single-use: each one owns the DOM nodes and bindings for one rendering. Rendering the
16996
+ same result twice (mounting it again, interpolating it twice, or returning a cached result from a reactive getter)
16997
+ throws `OreApiError`. Call the template function again when you need another copy.
16998
+
16992
16999
  `.prop=${value}` always writes the element property (never an attribute): the explicit channel for structured
16993
17000
  values (arrays, objects, callbacks). Prototype-polluting names (`__proto__`, `constructor`, `prototype`) and
16994
17001
  raw-HTML-parsing names (`innerHTML`, `outerHTML`, `srcdoc`) are rejected at compile time: render sanitized
@@ -17010,7 +17017,6 @@ Tagged template literal that returns a `CSSResult` for use in `styles`.
17010
17017
  | `when(condition, truthy, falsy?)` | Conditional rendering |
17011
17018
  | `classMap(record)` | Reactive class string from object map |
17012
17019
  | `styleMap(record)` | Reactive inline style string from object map |
17013
- | `live(signal)` | One-way binding that skips stale writes during active user input; use with `@input` handler |
17014
17020
  | `model(signal, options?)` | Two-way form-control binding: writes the signal to `value`/`checked` and writes user input back on the control's change event |
17015
17021
  | `unsafeHtml(value)` | HTML rendering sink; sanitize untrusted values before calling |
17016
17022
 
@@ -17018,7 +17024,7 @@ Tagged template literal that returns a `CSSResult` for use in `styles`.
17018
17024
 
17019
17025
  ### `model(signal, options?)`
17020
17026
 
17021
- Two-way binding for a form control: `value=${model(signal)}`. It writes the signal to the control's `value`/`checked` property on every change and writes user input back into the signal on the control's change event (`'change'` for checkboxes, radios, and ``; `'input'` otherwise). This is the complete controlled-input loop that the `live()` + manual `@input` handler pair used to require.
17027
+ Two-way binding for a form control: `value=${model(signal)}`. It writes the signal to the control's `value`/`checked` property on every change and writes user input back into the signal on the control's change event (`'change'` for checkboxes, radios, and ``; `'input'` otherwise). While the control holds an in-progress edit the signal has not received yet, stale writes to the signal are skipped.
17022
17028
 
17023
17029
  ```ts
17024
17030
  const text = signal('');
@@ -17098,6 +17104,8 @@ Static values are applied once. Getters and signals create reactive effects. Cal
17098
17104
 
17099
17105
  Slot signals update reactively when assigned content changes, including when slots are inserted dynamically (via `when()` or `each()`) after mount.
17100
17106
 
17107
+ Presence is measured through the `` elements the component has rendered: content assigned to a slot that isn't rendered reports `false`. Always render the `` and use `has()` to hide or style its wrapper; ``when(slots.has('x'), () => html``)`` never shows the slot.
17108
+
17101
17109
  ## Context API
17102
17110
 
17103
17111
  - `createContext(description)`: Create a unique typed injection key; the description is diagnostic only
@@ -17185,14 +17193,14 @@ useField({
17185
17193
 
17186
17194
  Import from `@vielzeug/ore/testing`.
17187
17195
 
17188
- | API | Purpose |
17189
- | ------------------------ | ------------------------------------------------------------------------------------------ |
17190
- | `mount(setup, options?)` | Mount a component and return a test fixture |
17191
- | `cleanup()` | Remove all mounted elements and reset test state |
17192
- | `install(afterEach)` | Register auto-cleanup after each test |
17193
- | `flush(options?)` | Drain reactive updates and animation frames |
17194
- | `renderHook(setup)` | Run lifecycle hooks in isolation; overload accepts `propDefs` as first arg for typed props |
17195
- | `OreTimeoutError` | Error thrown when `flush()` cannot settle tracked Ore work |
17196
+ | API | Purpose |
17197
+ | ----------------------------- | ------------------------------------------------------------------------------------------------- |
17198
+ | `mount(setup, options?)` | Mount a component and return a test fixture |
17199
+ | `cleanup()` | Remove all mounted elements and reset test state |
17200
+ | `install(afterEach)` | Register auto-cleanup after each test |
17201
+ | `flush(options?)` | Drain reactive updates and animation frames |
17202
+ | `renderHook(setup, options?)` | Run a composable in a generated host component; overload accepts `propDefs` first for typed props |
17203
+ | `OreTimeoutError` | Error thrown when `flush()` cannot settle tracked Ore work |
17196
17204
 
17197
17205
  > **Test isolation:** `cleanup()` removes mounted elements and resets Ore's cross-test caches and counters. Call it in `afterEach`, or use `install(afterEach)`.
17198
17206
 
@@ -17237,7 +17245,7 @@ interface Fixture {
17237
17245
 
17238
17246
  #### `renderHook`
17239
17247
 
17240
- Useful for testing composable lifecycle hooks (`onMounted`, `watchEffect`, `inject`, etc.) without a template. `onMounted`/`onCleanup`/`watchEffect`/... work exactly as inside a real `setup()`, since they resolve the same implicit current-component context:
17248
+ Useful for testing composable lifecycle hooks (`onMounted`, `watchEffect`, `inject`, etc.) without a template. The setup runs inside a real, generated host component (exposed as `element`), so every hook behaves exactly as it does in `define()`. Pass `{ formAssociated: true }` for composables that call `useField()` or `onFormReset()`. Like `mount().dispose()`, `dispose()` removes the host and its cleanups run one microtask later:
17241
17249
 
17242
17250
  ```ts
17243
17251
  // Without props
@@ -17281,7 +17289,7 @@ type PropDef = {
17281
17289
  };
17282
17290
 
17283
17291
  type PropsDef> = {
17284
- [K in keyof Required]: PropDef;
17292
+ [K in keyof T]-?: PropDef;
17285
17293
  };
17286
17294
 
17287
17295
  type PropInputDefs = Record>;
@@ -17317,7 +17325,7 @@ declare function onEvent(
17317
17325
  options?: AddEventListenerOptions,
17318
17326
  ): void;
17319
17327
  declare function onFormReset(fn: OnFormResetCallback): void; // Runs on every ancestor reset; formAssociated only
17320
- declare function watchEffect(fn: () => Cleanup | undefined): () => void; // Scoped reactive effect; auto-cleaned on disconnect
17328
+ declare function watchEffect(fn: () => Cleanup | undefined): () => void; // Component-owned reactive effect; disposed on disconnect, throws outside setup
17321
17329
  declare function bind(config: HostBindConfig, options?: BindOptions): () => void; // Bindings for host or any target element
17322
17330
  declare function provide(key: InjectionKey, value: T): void; // Register a context value on the host element
17323
17331
  declare function inject(key: InjectionKey): T | undefined;
@@ -17362,17 +17370,13 @@ type RefCallback = (el: T | null) => void;
17362
17370
 
17363
17371
  type InjectionKey = symbol & { readonly __ore_injection_key?: T };
17364
17372
 
17365
- interface HTMLResult {
17366
- mount(parent: ParentNode, anchor: Node | null, registerCleanup: (fn: () => void) => void): Node[];
17367
- }
17373
+ interface HTMLResult {} // Opaque, single-use: render it once (return, interpolate, or return from a directive callback)
17368
17374
 
17369
17375
  type CSSResult = {
17370
17376
  content: string;
17371
17377
  toString(): string;
17372
17378
  };
17373
17379
 
17374
- type LiveBinding = { readonly source: Readable };
17375
-
17376
17380
  type ModelOptions = {
17377
17381
  /** Write-back event (default: 'change' for checkbox/radio/select, 'input' otherwise). */
17378
17382
  event?: string;
@@ -17622,11 +17626,17 @@ Each reactive reconciliation is transactional. Ore creates missing entries befor
17622
17626
  entries; if a render callback throws, entries created during that pass are rolled back and the last successful list
17623
17627
  remains on screen. Ore reports the failure through `ore:error` with phase `each-reconcile`.
17624
17628
 
17629
+ Reused items keep their DOM nodes in place: when the surviving items stay in the same relative order (prepend, append,
17630
+ interleaved inserts, or replacing list contents), `each()` never moves a reused node, so CSS transitions, animations,
17631
+ focus, and nested component state survive the update untouched. Only genuine reorders move nodes, and a moved item
17632
+ travels with everything its inner directives rendered. New items are built detached and inserted exactly once at their
17633
+ final position, so each item's custom elements connect a single time per render.
17634
+
17625
17635
  ## model: two-way form bindings
17626
17636
 
17627
17637
  Use `model(signal)` for a controlled input: it writes the signal to the control's `value`/`checked` property and
17628
17638
  writes user input back on the control's change event (`'change'` for checkboxes, radios, and selects; `'input'`
17629
- otherwise). This replaces the `live()` + manual `@input` handler pair with one binding.
17639
+ otherwise).
17630
17640
 
17631
17641
  ```ts
17632
17642
  import { signal } from '@vielzeug/ripple';
@@ -17657,26 +17667,8 @@ html`
17657
17667
  `;
17658
17668
  ```
17659
17669
 
17660
- ## live: one-way bindings that preserve user edits
17661
-
17662
- Use `live(signal)` when a binding must skip a stale app-state write while the user is mid-edit, without writing
17663
- user input back. `model()` covers the common controlled-input case; `live()` is for one-way bindings that only
17664
- need the stale-write guard.
17665
-
17666
- ```ts
17667
- import { signal } from '@vielzeug/ripple';
17668
- import { define, html, live } from '@vielzeug/ore';
17669
-
17670
- define('live-search', {
17671
- setup() {
17672
- const query = signal('');
17673
-
17674
- return html`
17675
- (query.value = (e.target as HTMLInputElement).value)} />
17676
- `;
17677
- },
17678
- });
17679
- ```
17670
+ `model()` also guards in-progress edits: while the control holds a value the signal has not received yet, a stale
17671
+ app-state write to the signal is skipped instead of clobbering what the user is typing.
17680
17672
 
17681
17673
  ## host bindings
17682
17674
 
@@ -17791,7 +17783,7 @@ define('button-wrapper', {
17791
17783
  ## slots and emits
17792
17784
 
17793
17785
  ```ts
17794
- import { define, html, useEmit, useSlots, when } from '@vielzeug/ore';
17786
+ import { define, html, useEmit, useSlots } from '@vielzeug/ore';
17795
17787
 
17796
17788
  define('card-with-footer', {
17797
17789
  setup(_props) {
@@ -17802,7 +17794,7 @@ define('card-with-footer', {
17802
17794
 
17803
17795
 
17804
17796
 
17805
- ${when(slots.has('footer'), () => html``)}
17797
+ !slots.has('footer').value}>
17806
17798
 
17807
17799
  emit('action')}>Go
17808
17800
  `;
@@ -17812,6 +17804,8 @@ define('card-with-footer', {
17812
17804
 
17813
17805
  Pass a `SlotNames` type parameter to `useSlots()` to get typed `slots.has()` and `slots.elements()` calls.
17814
17806
 
17807
+ Keep the `` rendered and toggle its wrapper with `slots.has()`: presence is read from rendered slots, so a `` inside `when(slots.has(...))` would never appear.
17808
+
17815
17809
  ## context provide/inject
17816
17810
 
17817
17811
  ```ts
@@ -18025,7 +18019,7 @@ define('signup-form', {
18025
18019
  - Bind host attributes and classes via `bind()` rather than mutating the element directly.
18026
18020
  - Provide context at the nearest ancestor: avoid global context singletons.
18027
18021
  - Call `onCleanup()` for every resource allocated in `setup()` (WebSockets, intervals, external subscriptions).
18028
- - Use `model(signal)` for two-way form inputs; use `live(signal)` for a one-way binding that must not clobber user-in-progress edits.
18022
+ - Use `model(signal)` for form inputs: it writes both ways and never clobbers an in-progress user edit.
18029
18023
  - Extract composable helper functions freely: `onMounted`/`onCleanup`/`bind`/... resolve the active component through implicit context, so they work from any function called (transitively) during `setup()`, with no need to pass them in as parameters.
18030
18024
  - Test component mounting and lifecycle with `@vielzeug/ore/testing`; import generic DOM events, queries, and waits
18031
18025
  from `@vielzeug/assay`.
@@ -22664,8 +22658,9 @@ ripple.dispose();
22664
22658
 
22665
22659
  - `createRipple({ onError })` creates an isolated graph with one runtime failure callback.
22666
22660
  - `signal()` stores writable values with configurable equality.
22667
- - `computed()` derives lazy read-only values.
22661
+ - `computed()` derives lazy, glitch-free read-only values: at most once per flush, never from a stale source.
22668
22662
  - `effect()` reacts to dependency changes with cleanup support.
22663
+ - `onCleanup()` runs a callback when the active scope or effect run is disposed.
22669
22664
  - `batch()` coalesces synchronous writes and notifications.
22670
22665
  - `createScope()` groups owned reactive work.
22671
22666
  - `watch()` observes one selected source transition.
@@ -22696,6 +22691,7 @@ ripple.dispose();
22696
22691
  | `signal()` | Create writable value | Sync | Default graph is process-wide |
22697
22692
  | `computed()` | Create lazy derived value | Sync | Keep derivation pure |
22698
22693
  | `effect()` | React to dependency reads | Sync | Dispose handle or return cleanup |
22694
+ | `onCleanup()` | Run when the active owner disposes | Sync | Call it inside a scope or effect |
22699
22695
  | `batch()` | Coalesce synchronous writes | Sync | Does not roll back writes |
22700
22696
  | `createScope()` | Group owned reactive work | Sync | Call `run()` to activate it |
22701
22697
  | `untrack()` | Read without tracking | Sync | Read still happens immediately |
@@ -22723,12 +22719,12 @@ function createRipple(options?: RippleOptions): Ripple;
22723
22719
 
22724
22720
  Creates one isolated reactive graph. Factories on the returned object share scheduling, ownership, and error boundaries. `dispose()` is terminal: `ripple.disposed` becomes `true`, existing owned work is disposed, and creating more graph work throws `RippleDisposedError`. Create a new graph for a new lifetime.
22725
22721
 
22726
- | Parameter | Type | Description |
22727
- | ----------------- | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
22728
- | `options.onError` | `(error, context) => void` | Handles computed refresh, effect, cleanup, listener, and flush-loop failures. Default rethrows asynchronously via `queueMicrotask`; pass a no-op to silence. A failure in one node never interrupts sibling propagation. |
22722
+ | Parameter | Type | Description |
22723
+ | ----------------- | -------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
22724
+ | `options.onError` | `(error, context) => void` | Handles effect, cleanup, listener, and flush-loop failures, including computed errors those consumers read. Default rethrows asynchronously via `queueMicrotask`; pass a no-op to silence. A failure in one node never interrupts its siblings. |
22729
22725
 
22730
- `onError` is the only runtime option. `RippleErrorContext.kind` is `cleanup`, `computed`,
22731
- `effect`, `flush`, or `listener`; `name` is optional. There is no event stream or error-policy option.
22726
+ `onError` is the only runtime option. `RippleErrorContext.kind` is `cleanup`, `effect`, `flush`,
22727
+ or `listener`; `name` is optional. There is no event stream or error-policy option.
22732
22728
 
22733
22729
  **Returns:** `Ripple`.
22734
22730
 
@@ -22767,7 +22763,7 @@ console.log(isReactive(signal(0)));
22767
22763
 
22768
22764
  ## Default Graph Functions
22769
22765
 
22770
- Root helpers (`signal`, `computed`, `effect`, `batch`, `createScope`, `untrack`, `watch`, `resource`, `fromSubscribable`) operate on a process-lifetime default graph. The graph itself has no public disposal handle; effects, scopes, resources, and bridges still require owner-managed disposal. For isolated, disposable graphs (tests, SSR, embedded features) use `createRipple()`.
22766
+ Root helpers (`signal`, `computed`, `effect`, `onCleanup`, `batch`, `createScope`, `untrack`, `watch`, `resource`, `fromSubscribable`) operate on a process-lifetime default graph. The graph itself has no public disposal handle; effects, scopes, resources, and bridges still require owner-managed disposal. For isolated, disposable graphs (tests, SSR, embedded features) use `createRipple()`.
22771
22767
 
22772
22768
  ### `signal(initial, options?)`
22773
22769
 
@@ -22799,7 +22795,7 @@ cart.update((state) => ({ ...state, items: state.items + 1 }));
22799
22795
  function computed(derive: () => T, options?: ComputedOptions): Readable;
22800
22796
  ```
22801
22797
 
22802
- Creates a lazy read-only value from reactive reads in `derive`. `peek()` may trigger derivation and throw directly. During dependency propagation, a computed refresh failure is reported to `onError` with context kind `computed` and does not prevent sibling dependents from updating. A disposed computed returns its last cached value from `peek()` without recomputing; a computed disposed before its first evaluation throws `RippleDisposedError` instead of returning a value.
22798
+ Creates a lazy read-only value from reactive reads in `derive`. A write only marks the computed stale; it derives on the next read, at most once per flush, and always from up-to-date sources. A derivation error is cached and rethrown by every read (`value` or `peek()`) until a source changes; consumers that read it report it through `onError` in their own context. A disposed computed returns its last cached value from `peek()` without recomputing; a computed disposed before its first evaluation throws `RippleDisposedError` instead of returning a value.
22803
22799
 
22804
22800
  **Returns:** `Readable`.
22805
22801
 
@@ -22821,7 +22817,7 @@ console.log(doubled.value);
22821
22817
  function effect(callback: () => Cleanup | undefined, options?: EffectOptions): EffectHandle;
22822
22818
  ```
22823
22819
 
22824
- Runs immediately and reruns when its tracked reads change. A returned cleanup runs before the next callback or disposal.
22820
+ Runs immediately and reruns when its tracked reads change. An effect that only reads computeds reruns only when one of them derives a different value. A returned cleanup runs before the next callback or disposal.
22825
22821
 
22826
22822
  | Parameter | Type | Description |
22827
22823
  | -------------- | -------- | ------------------------------- |
@@ -22848,6 +22844,37 @@ stop.dispose();
22848
22844
 
22849
22845
  ---
22850
22846
 
22847
+ ### `onCleanup(fn)`
22848
+
22849
+ ```ts
22850
+ function onCleanup(fn: Cleanup): void;
22851
+ ```
22852
+
22853
+ Registers `fn` on the active owner: the current effect run when called inside an effect, otherwise the active scope. The callback runs when that owner is disposed, after the owner's effects and computeds, newest first. For an effect run that means before the next run, and after the cleanup function the effect itself returned. A callback that calls `onCleanup()`, `effect()`, or `computed()` while its owner is being disposed gets that work torn down immediately. A throwing callback is reported through `onError` and does not skip the others.
22854
+
22855
+ Called with no scope or effect active, it registers on the graph root. The default graph is never disposed, so use `createRipple()` or an explicit scope when the callback must run.
22856
+
22857
+ **Example:**
22858
+
22859
+ ```ts
22860
+ import { createScope, effect, onCleanup, signal } from '@vielzeug/ripple';
22861
+
22862
+ const scope = createScope('panel');
22863
+ const count = signal(0);
22864
+
22865
+ scope.run(() => {
22866
+ effect(() => {
22867
+ console.log(count.value);
22868
+ onCleanup(() => console.log('effect run ended'));
22869
+ });
22870
+ onCleanup(() => console.log('panel closed'));
22871
+ });
22872
+
22873
+ scope.dispose();
22874
+ ```
22875
+
22876
+ ---
22877
+
22851
22878
  ### `batch(fn)` and `untrack(fn)`
22852
22879
 
22853
22880
  ```ts
@@ -22972,7 +22999,7 @@ function fromSubscribable(source: Subscribable, options?: FromSubscribableOption
22972
22999
 
22973
23000
  Bridges an external `{ getSnapshot, subscribe }` source into a disposable reactive readable. The bridge subscribes and then rereads the snapshot to avoid missing a change during registration. The root helper uses the default graph; `ripple.fromSubscribable()` binds ownership to an isolated graph. An optional signal disposes the bridge.
22974
23001
 
22975
- **Returns:** `BridgedReadable`. Disposal invokes the source unsubscribe function. Reads remain available afterward, while new subscriptions throw.
23002
+ **Returns:** `BridgedReadable`. Disposal invokes the source unsubscribe function. Reads remain available afterward, while new subscriptions throw `RippleDisposedError`.
22976
23003
 
22977
23004
  **Example:**
22978
23005
 
@@ -23010,7 +23037,7 @@ type EffectOptions = { name?: string };
23010
23037
  type WatchOptions = { equals?: Equality; immediate?: boolean; name?: string };
23011
23038
 
23012
23039
  type RippleErrorContext = {
23013
- readonly kind: 'cleanup' | 'computed' | 'effect' | 'flush' | 'listener';
23040
+ readonly kind: 'cleanup' | 'effect' | 'flush' | 'listener';
23014
23041
  readonly name?: string;
23015
23042
  };
23016
23043
  type RippleOptions = { onError?: (error: unknown, context: RippleErrorContext) => void };
@@ -23062,6 +23089,7 @@ interface Ripple extends Disposable {
23062
23089
  computed(derive: () => T, options?: ComputedOptions): Readable;
23063
23090
  createScope(name?: string): Scope;
23064
23091
  effect(callback: () => Cleanup | undefined, options?: EffectOptions): EffectHandle;
23092
+ onCleanup(fn: Cleanup): void;
23065
23093
  fromSubscribable(source: Subscribable, options?: FromSubscribableOptions): BridgedReadable;
23066
23094
  resource(
23067
23095
  source: () => Source,
@@ -23080,15 +23108,15 @@ interface Ripple extends Disposable {
23080
23108
 
23081
23109
  ## Errors
23082
23110
 
23083
- | Error | Trigger | Notable properties |
23084
- | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------- |
23085
- | `RippleError` | Base Ripple error; a new subscription to a disposed external-source bridge | Use `instanceof RippleError` to narrow unknown values. |
23086
- | `RippleCycleError` | A computed reads itself, or a flush exceeds the iteration limit | Extends `RippleError`. A flush-loop breach is reported to `onError` (context kind `flush`) instead of throwing from the write site. |
23087
- | `RippleDisposedError` | New graph work, writes, or subscriptions on a disposed runtime; `run()` on a disposed scope; `reload()` or new subscriptions on a disposed resource; reading a never-evaluated disposed computed | Extends `RippleError`. Cached reads and repeated disposal remain valid. |
23111
+ | Error | Trigger | Notable properties |
23112
+ | --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
23113
+ | `RippleError` | Base class of every Ripple error | Use `instanceof RippleError` to narrow unknown values. |
23114
+ | `RippleCycleError` | A computed reads itself, directly or through other computeds, or a flush exceeds the iteration limit | Extends `RippleError`. A flush-loop breach is reported to `onError` (context kind `flush`) instead of throwing from the write site. |
23115
+ | `RippleDisposedError` | New graph work, writes, or subscriptions on a disposed runtime; `run()` on a disposed scope; `reload()` or new subscriptions on a disposed resource or bridge; reading a never-evaluated disposed computed | Extends `RippleError`. Cached reads and repeated disposal remain valid. |
23088
23116
 
23089
23117
  These are the three exported error classes. User callback failures are reported as their original
23090
- values through `onError`; they are not wrapped in `RippleError`. A direct computed read can throw
23091
- its derivation error to the caller.
23118
+ values through `onError`; they are not wrapped in `RippleError`. A direct computed read rethrows
23119
+ its cached derivation error to the caller.
23092
23120
 
23093
23121
  ### Usage Guide
23094
23122
 
@@ -23147,7 +23175,7 @@ ripple.batch(() => {
23147
23175
 
23148
23176
  ## Scheduling and Subscriptions
23149
23177
 
23150
- Ripple propagates every synchronous write before flushing effects. Each flush pass runs effects queued at its
23178
+ A synchronous write marks everything downstream stale before any effect runs. Each flush pass runs effects queued at its
23151
23179
  start before direct `subscribe()` listeners queued at its start. Work queued by either runs in a later pass.
23152
23180
  Effects coalesce writes made inside the same synchronous flush: a `batch()` (or any writes during a flush) produces a single effect run.
23153
23181
  Each `subscribe()` registration fires once per flush, even when several subscriptions share one callback function.
@@ -23183,7 +23211,9 @@ count.value = 1;
23183
23211
  scope.dispose();
23184
23212
  ```
23185
23213
 
23186
- Effects and computeds created directly during an effect run belong to that run and are disposed before rerun. Explicit scopes intentionally attach to the enclosing scope and survive effect reruns; create them outside rerunning effects or retain and dispose each scope yourself.
23214
+ Effects and computeds created directly during an effect run belong to that run and are disposed before rerun. `onCleanup(fn)` registers on that same owner: inside an effect it runs before the next run, and inside `scope.run()` it runs when the scope is disposed, after the scope's effects. Explicit scopes intentionally attach to the enclosing scope and survive effect reruns; create them outside rerunning effects or retain and dispose each scope yourself. A call with no scope or effect active registers on the graph root.
23215
+
23216
+ Cleanups run with their disposed owner still active, so an `onCleanup()`, `effect()`, or `computed()` called from inside a cleanup is torn down immediately instead of leaking to the parent.
23187
23217
 
23188
23218
  Disposed owned nodes detach from their parent immediately, so long-lived graphs do not retain released effects or scopes.
23189
23219
 
@@ -23203,12 +23233,12 @@ stopWatch.dispose();
23203
23233
 
23204
23234
  ## Error Handling
23205
23235
 
23206
- Failures inside effect callbacks, computed derivations, cleanups, and listeners never corrupt the graph: the failing node is reported and siblings keep propagating. The `onError` option decides what reporting means. By default failures rethrow asynchronously (via `queueMicrotask`), surfacing as unhandled errors; pass a handler to route them to a logger or error boundary instead:
23236
+ Failures inside effect callbacks, computed derivations, cleanups, and listeners never corrupt the graph: the failing node is reported and siblings keep updating. The `onError` option decides what reporting means. By default failures rethrow asynchronously (via `queueMicrotask`), surfacing as unhandled errors; pass a handler to route them to a logger or error boundary instead:
23207
23237
 
23208
23238
  ```ts
23209
23239
  const ripple = createRipple({
23210
23240
  onError: (error, context) => {
23211
- // context.kind: 'cleanup' | 'computed' | 'effect' | 'flush' | 'listener'
23241
+ // context.kind: 'cleanup' | 'effect' | 'flush' | 'listener'
23212
23242
  console.error(`${context.kind}:`, error);
23213
23243
  },
23214
23244
  });
@@ -23217,8 +23247,9 @@ const ripple = createRipple({
23217
23247
  `onError` is the only runtime option. Effect options accept only a `name`; effects do not have a
23218
23248
  microtask scheduler. Use `batch()` to coalesce related writes.
23219
23249
 
23220
- A direct computed read can throw its derivation error to the caller. `onError` handles computed
23221
- refresh failures during propagation, not every possible synchronous exception. The exported
23250
+ A computed caches a derivation error like a value: every read rethrows it until a source changes.
23251
+ The failure therefore reaches `onError` through whatever reads it (context kind `effect` for an
23252
+ effect, `listener` for a subscription), and a direct read throws it to the caller. The exported
23222
23253
  hierarchy is `RippleError`, `RippleCycleError`, and `RippleDisposedError`; callback failures retain
23223
23254
  their original values.
23224
23255
 
@@ -23394,17 +23425,17 @@ ripple.dispose();
23394
23425
 
23395
23426
  `Readable.subscribe(listener)` never calls the listener on subscribe: it fires only after a tracked source changes. Read the current value at the call site when you need an initial state.
23396
23427
 
23397
- ### `subscribe()` forces computed evaluation
23428
+ ### `subscribe()` evaluates a computed once
23398
23429
 
23399
- `Readable.subscribe()` calls `peek()` before registering the listener. For signals this is a no-op, but for computeds it forces `refresh()`: the derivation runs immediately even if no one reads `.value`. This ensures `equals` comparison works on the first dependency change. Avoid subscribing to expensive computeds unless you need their value.
23430
+ Subscribing to a computed derives it immediately so the computed knows its sources, even if no one reads `.value`. A derivation error is cached, not thrown from `subscribe()`. After that, the listener fires only when the derived value actually changes under its `equals`. Avoid subscribing to expensive computeds unless you need their value.
23400
23431
 
23401
- ### Diamonds recompute each path once per write
23432
+ ### Computeds are lazy and glitch-free
23402
23433
 
23403
- A computed with dependents refreshes eagerly during propagation, so effects never re-run for unchanged derived values. The tradeoff: in a diamond (`a → b, c → d`), one write to `a` recomputes both `b` and `c` and then `d` once per changed path. Values a consumer observes are always consistent: a dependent reading a stale intermediate pulls the fresh value on read, so no glitched state is ever visible. Prefer keeping diamond depth shallow when a derivation is expensive.
23434
+ A write only marks downstream computeds stale; nothing re-derives until something reads it. When an effect or subscription might be affected, the flush first re-derives the computeds it depends on, in the order they were read, and reruns it only if one of them actually changed. In a diamond (`a → b, c → d`), one write to `a` derives `b`, `c`, and `d` once each, and `d` never sees a fresh `b` next to a stale `c`. Inside `batch()`, a computed derives at most once however many of its sources were written. A computed no one reads costs nothing after a write.
23404
23435
 
23405
- ### Computed first-run failure is recoverable
23436
+ ### Computed failures are recoverable
23406
23437
 
23407
- If a computed's `derive` throws on its first run (e.g., a source is `null`), the computed commits the partial dependencies it tracked before the throw. When a dependency changes and the derivation can succeed, the computed refreshes and notifies its dependents. Effects that read a failing computed report the error through `onError` and re-run when the computed recovers.
23438
+ If a computed's `derive` throws (e.g., a source is `null`), the computed keeps the sources it read before the throw and caches the error. When one of those sources changes, the next read derives again; effects that read the failing computed report the error through `onError` and rerun once it recovers.
23408
23439
 
23409
23440
  ## Best Practices
23410
23441
 
@@ -29726,17 +29757,42 @@ function toSvg(matrix: QrMatrix, options?: QrSvgOptions): string;
29726
29757
 
29727
29758
  Returns a complete `` string. Runs in any environment: no DOM required.
29728
29759
 
29729
- | Parameter | Type | Default | Description |
29730
- | ---------------------- | --------- | ---------------- | ---------------------------------------------- |
29731
- | `options.dark` | `string` | `'currentColor'` | Dark module color |
29732
- | `options.light` | `string` | `'transparent'` | Background color |
29733
- | `options.margin` | `number` | `4` | Quiet-zone modules |
29734
- | `options.scale` | `number` | `1` | User units per module |
29735
- | `options.optimizePath` | `boolean` | `true` | Merge dark runs into one `` |
29736
- | `options.label` | `string` | N/A | `` + `aria-label`; enables `role="img"` |
29760
+ | Parameter | Type | Default | Description |
29761
+ | ---------------------- | ---------------------- | ---------------- | -------------------------------------------------- |
29762
+ | `options.dark` | `string` | `'currentColor'` | Dark module color (ignored when `gradient` is set) |
29763
+ | `options.light` | `string` | `'transparent'` | Background color |
29764
+ | `options.margin` | `number` | `4` | Quiet-zone modules |
29765
+ | `options.scale` | `number` | `1` | User units per module |
29766
+ | `options.optimizePath` | `boolean` | `true` | Merge dark runs into one `` |
29767
+ | `options.label` | `string` | N/A | `` + `aria-label`; enables `role="img"` |
29768
+ | `options.dotStyle` | `QrDotStyle` | `'square'` | Data-module shape; finder zones stay square |
29769
+ | `options.gradient` | `QrSvgGradientOptions` | N/A | Two-stop linear gradient replacing module paint |
29770
+ | `options.image` | `QrSvgImageOptions` | N/A | Centered logo; modules under it are not painted |
29771
+
29772
+ ```ts
29773
+ type QrDotStyle = 'dots' | 'rounded' | 'square';
29774
+
29775
+ type QrSvgGradientOptions = {
29776
+ from: string; // first stop
29777
+ to: string; // second stop
29778
+ angle?: number; // degrees, 0 = top-to-bottom (default)
29779
+ id?: string; // stable id; auto-unique otherwise
29780
+ };
29781
+
29782
+ type QrSvgImageOptions = {
29783
+ href: string; // logo URL (resolved by the consumer, embedded verbatim)
29784
+ size?: number; // fraction of the code edge (default 0.22)
29785
+ spacing?: number; // clear gap in modules around the logo (default 1)
29786
+ background?: string; // optional patch behind the logo
29787
+ radius?: number; // corner radius of the background patch
29788
+ };
29789
+ ```
29790
+
29791
+ Styling output stays scanner-friendly: finder patterns never lose their square shape, and the carve around a logo is a gap, not painted noise. Prefer `errorCorrection: 'H'` when overlaying a logo.
29737
29792
 
29738
29793
  ```ts
29739
29794
  const svg = toSvg(matrix, { label: 'Pairing code', dark: 'var(--qr-dark)' });
29795
+ const styled = toSvg(matrix, { dotStyle: 'rounded', gradient: { from: '#0ea5e9', to: '#7c3aed' } });
29740
29796
  ```
29741
29797
 
29742
29798
  ---
@@ -29852,7 +29908,7 @@ type SigilEvent =
29852
29908
  | { readonly type: 'dispose' };
29853
29909
  ```
29854
29910
 
29855
- `QrEncodeOptions`, `QrSvgOptions`, `QrCanvasOptions`, `QrScannerOptions`, and `QrScanner` are documented under their factories above.
29911
+ `QrEncodeOptions`, `QrSvgOptions`, `QrCanvasOptions`, `QrScannerOptions`, and `QrScanner` are documented under their factories above. `QrDotStyle`, `QrSvgGradientOptions`, and `QrSvgImageOptions` are documented under `toSvg`.
29856
29912
 
29857
29913
  ## Errors
29858
29914
 
@@ -30965,7 +31021,7 @@ Use Scout to compute indexed local matches, Ripple to project state into reactiv
30965
31021
 
30966
31022
  ## Why Spell?
30967
31023
 
30968
- Spell keeps runtime validation, static inference, and portable definitions in one API. Use `s` for schema construction; import JSON conversion and predicates from dedicated subpaths.
31024
+ Spell keeps runtime validation, static inference, and portable definitions in one API. Checks and transforms run in the order you chain them, and every built-in constraint appears in the exported definition.
30969
31025
 
30970
31026
  This example shows the difference between manual branching and a single reusable schema.
30971
31027
 
@@ -31062,16 +31118,16 @@ const user = result.data;
31062
31118
 
31063
31119
  ## Features
31064
31120
 
31065
- - Namespace and tree-shakeable schema builders.
31066
- - Sync and async parsing with `parse()`, `safeParse()`, `parseAsync()`, and `safeParseAsync()`.
31067
- - Dependency-free Standard Schema v1 interoperability through `schema['~standard']`.
31068
- - Explicit `check()` and `checkAsync()` rules; sync parsing never skips an async check.
31069
- - Wrapper modes for `optional`, `nullable`, `nullish`, `default`, `catch`, and `required`.
31070
- - Frozen declarative definitions through `definition()` and JSON Schema export via `fromDefinition()` from `@vielzeug/spell/json`.
31071
- - Request-local message customization through `createParseContext()`.
31072
- - Ordered union parsing produces the same selected branch in sync and async modes.
31073
- - Structured errors with direct path lookup and flattened views.
31074
- - Object parsing is hardened against prototype-pollution-style keys.
31121
+ - `s` builders for primitives, collections, objects, unions, and recursive schemas.
31122
+ - `parse()`, `safeParse()`, `parseAsync()`, and `safeParseAsync()`; parsing stays synchronous unless a check is async.
31123
+ - `check()` and `checkAsync()` run in chain order with transforms; sync parsing never skips an async check.
31124
+ - `optional`, `nullable`, `nullish`, `default`, `catch`, and `required` modifiers; defaults are copied per parse.
31125
+ - `extend()`, `pick()`, `omit()`, `partial()`, and `tolerate()` for object composition and schema evolution.
31126
+ - `definition()` returns frozen data; `toJsonSchema()` from `@vielzeug/spell/json` converts it to JSON Schema.
31127
+ - `schema['~standard']` implements Standard Schema v1 without an adapter.
31128
+ - `createParseContext()` customizes messages per request, locale, or form.
31129
+ - `SpellValidationError` offers `flatten()`, `flattenFirst()`, and `messagesAt()` for UI errors.
31130
+ - Object and record parsing is hardened against prototype-pollution keys.
31075
31131
 
31076
31132
  ## Documentation
31077
31133
 
@@ -31090,184 +31146,307 @@ const user = result.data;
31090
31146
 
31091
31147
  ## API Overview
31092
31148
 
31093
- | Symbol | Purpose | Execution mode | Common gotcha |
31094
- | ---------------------- | ------------------------------- | ---------------------------------- | ------------------------------------------- |
31095
- | `s` | Creates schemas | Sync or async, depending on checks | `checkAsync()` requires async parsing |
31096
- | `createParseContext()` | Creates request-local messages | Sync | Pass the context to each parse call |
31097
- | `joinIssuePath()` | Flattens issue paths to UI keys | Sync | Empty or undefined paths join to `''` |
31098
- | `SpellValidationError` | Provides validation issues | Sync/async parse failures | Use `safeParse()` for expected invalid data |
31149
+ | Symbol | Purpose | Execution mode | Common gotcha |
31150
+ | ---------------------- | ------------------------------------------- | ------------------------------------ | --------------------------------------------------------------- |
31151
+ | `s` | Creates schemas | Sync, or async when checks are async | `checkAsync()` anywhere in the tree requires `parseAsync()` |
31152
+ | `Schema` | Base class of every schema | Sync or async | Modifiers return copies; schemas are never mutated |
31153
+ | `createParseContext()` | Creates request-local messages | Sync | Pass the context to each parse call |
31154
+ | `joinIssuePath()` | Flattens issue paths to UI keys | Sync | Empty or undefined paths join to `''` |
31155
+ | `SpellValidationError` | Carries validation issues | Sync/async parse failures | Use `safeParse()` for expected invalid data |
31156
+ | `SpellDefinitionError` | Rejects non-portable or invalid definitions | Sync | Thrown by `definition()` and object derivations, not by parsing |
31157
+ | `ErrorCode` | Issue code constants | n/a | Narrow `Issue` on `code` to read typed `params` |
31158
+ | `toJsonSchema()` | Converts a definition to JSON Schema | Sync | Imported from `@vielzeug/spell/json` |
31099
31159
 
31100
31160
  ## Package Entry Point
31101
31161
 
31102
- | Import | Purpose |
31103
- | ---------------------------- | -------------------------------------------------- |
31104
- | `@vielzeug/spell` | Schema builders, errors, types, and parse contexts |
31105
- | `@vielzeug/spell/json` | Convert portable definitions to JSON Schema |
31106
- | `@vielzeug/spell/predicates` | Standalone format and type predicates |
31162
+ | Import | Purpose |
31163
+ | ---------------------------- | ------------------------------------------------------- |
31164
+ | `@vielzeug/spell` | Schema builders, base class, errors, types, and context |
31165
+ | `@vielzeug/spell/json` | `toJsonSchema()` and the `JsonSchema` type |
31166
+ | `@vielzeug/spell/predicates` | Standalone string format predicates |
31107
31167
 
31108
31168
  ```ts
31109
31169
  import { createParseContext, s, type Infer } from '@vielzeug/spell';
31110
- import { fromDefinition } from '@vielzeug/spell/json';
31170
+ import { toJsonSchema } from '@vielzeug/spell/json';
31111
31171
  import { isEmail } from '@vielzeug/spell/predicates';
31112
31172
  ```
31113
31173
 
31114
- ## `s`
31174
+ ## Builders
31115
31175
 
31116
31176
  All builders live under `s`.
31117
31177
 
31118
- | Builder | Purpose |
31119
- | ---------------------------------------------------------- | -------------------------- |
31120
- | `string`, `number`, `boolean`, `bigint`, `date` | Primitive values |
31121
- | `literal`, `enum`, `null`, `undefined`, `unknown`, `never` | Exact and universal values |
31122
- | `array`, `tuple`, `set`, `map`, `record`, `object` | Collections |
31123
- | `union`, `intersect`, `discriminatedUnion`, `lazy` | Composition |
31124
- | `coerce.*` | Coercing primitive schemas |
31178
+ | Builder | Returns | Notes |
31179
+ | ---------------------------------------------- | ------------------------------------- | ----------------------------------------------------- |
31180
+ | `s.string()` | `StringSchema` | |
31181
+ | `s.number()` | `NumberSchema` | Rejects `NaN` |
31182
+ | `s.bigint()` | `BigIntSchema` | |
31183
+ | `s.boolean()` | `BooleanSchema` | |
31184
+ | `s.date()` | `DateSchema` | Rejects invalid dates with `invalid_date` |
31185
+ | `s.literal(value)` | `LiteralSchema` | `string`, `number`, `boolean`, `null`, or `undefined` |
31186
+ | `s.enum(values)` | `EnumSchema` | Non-empty tuple of strings or numbers |
31187
+ | `s.null()`, `s.undefined()` | `LiteralSchema` | |
31188
+ | `s.unknown()` | `Schema` | Accepts any value |
31189
+ | `s.never()` | `NeverSchema` | Rejects every value |
31190
+ | `s.instanceof(cls)` | `InstanceOfSchema` | Accepts abstract constructors |
31191
+ | `s.array(item)` | `ArraySchema` | |
31192
+ | `s.tuple(items)` | `TupleSchema` | Exact length unless `.rest()` is used |
31193
+ | `s.set(item)` | `SetSchema` | |
31194
+ | `s.map(key, value)` | `MapSchema` | |
31195
+ | `s.record(key, value)` | `RecordSchema` | Drops unsafe keys (`__proto__`, `constructor`, …) |
31196
+ | `s.object(shape)` | `ObjectSchema` | Strict by default |
31197
+ | `s.union(...schemas)` | `UnionSchema` | At least two schemas; first match wins |
31198
+ | `s.intersect(...schemas)` | `IntersectSchema` | At least two schemas; object outputs are deep-merged |
31199
+ | `s.discriminatedUnion(key, branches)` | `DiscriminatedUnionSchema` | Branches are object schemas keyed by tag |
31200
+ | `s.lazy(getter)` | `LazySchema` | Recursive schemas |
31201
+ | `s.coerce.string/number/boolean/bigint/date()` | Primitive schema with `unknown` input | Coercion runs before the type check |
31202
+
31203
+ ### `s.coerce`
31204
+
31205
+ | Builder | Converts |
31206
+ | -------------------- | --------------------------------------------------------- |
31207
+ | `s.coerce.string()` | Any non-nullish value with `String()` |
31208
+ | `s.coerce.number()` | Numeric strings and booleans with `Number()` |
31209
+ | `s.coerce.boolean()` | `'true'`/`'1'`/`1` and `'false'`/`'0'`/`0` |
31210
+ | `s.coerce.bigint()` | Safe-integer numbers and integer strings up to 1000 chars |
31211
+ | `s.coerce.date()` | Strings and epoch milliseconds with `new Date()` |
31212
+
31213
+ Values the coercer cannot convert reach the type check unchanged and fail with `invalid_type`.
31214
+
31215
+ ## Schema Methods
31216
+
31217
+ Every schema extends `Schema`.
31218
+
31219
+ ### Parsing
31220
+
31221
+ ```ts
31222
+ parse(value: unknown, context?: ParseContext): Output;
31223
+ safeParse(value: unknown, context?: ParseContext): ParseResult;
31224
+ parseAsync(value: unknown, context?: ParseContext): Promise;
31225
+ safeParseAsync(value: unknown, context?: ParseContext): Promise>;
31226
+ is(value: unknown): value is Output;
31227
+ assert(value: unknown, label?: string): asserts value is Output;
31228
+ ```
31229
+
31230
+ **Returns:** `parse()` returns the parsed output or throws `SpellValidationError`. `safeParse()` returns a `ParseResult`.
31231
+
31232
+ `parse()`, `safeParse()`, `is()`, and `assert()` are synchronous. If the schema or any nested schema has a `checkAsync()` step, they throw `SpellError` ("Schema contains async checks; use parseAsync() or safeParseAsync().") before running the async check. This is a usage error, not a validation issue, so `catch()` does not intercept it. `assert(value, label)` prefixes root-level messages with `label`.
31233
+
31234
+ **Example:**
31125
31235
 
31126
31236
  ```ts
31127
- const User = s.object({
31128
- email: s.string().email(),
31129
- id: s.string().uuid(),
31130
- role: s.enum(['admin', 'member'] as const),
31131
- });
31237
+ import { s } from '@vielzeug/spell';
31132
31238
 
31133
- type User = Infer;
31239
+ const result = s.string().email().safeParse('ada@example.com');
31240
+
31241
+ if (result.success) console.log(result.data);
31134
31242
  ```
31135
31243
 
31136
- Object schemas reject unknown keys. Use `.relaxed()` to retain extras.
31244
+ ### Checks
31137
31245
 
31138
- ## Standard Schema interoperability
31246
+ ```ts
31247
+ check(fn: (value: Output, ctx: CheckContext) => ValidateResult): this;
31248
+ checkAsync(fn: (value: Output, ctx: CheckContext) => Promise): this;
31249
+ ```
31250
+
31251
+ **Returns:** A copy of the schema with the rule appended.
31139
31252
 
31140
- Every schema implements the dependency-free Standard Schema v1 structural protocol through `schema['~standard']`. Consumers that accept Standard Schema validators can use Spell schemas directly without an adapter.
31253
+ A check runs only when the structural type check passed. It returns `true`, `null`, or `undefined` to pass, a string to fail with that message, or `false` to fail with the default message. `ctx.addIssue({ code, message, params?, path? })` reports issues at paths relative to the schema. Passing an async function to `check()` is a type error.
31254
+
31255
+ **Example:**
31141
31256
 
31142
31257
  ```ts
31143
- const User = s.object({ name: s.string() });
31144
- const result = await User['~standard'].validate({ name: 'Ada' });
31258
+ const Signup = s.object({ confirm: s.string(), password: s.string() }).check((value, ctx) => {
31259
+ if (value.password !== value.confirm)
31260
+ ctx.addIssue({ code: 'custom', message: 'Passwords must match', path: ['confirm'] });
31261
+ });
31145
31262
  ```
31146
31263
 
31147
- Successful results contain `value`; failures contain portable `{ message, path }` issues. Failed unions remain one stable union issue instead of selecting a branch heuristically.
31264
+ ### Modifiers
31148
31265
 
31149
- The exported `StandardSchemaV1` interface mirrors the full v1 protocol, including `validate(value, options?)` and the `InferInput` and `InferOutput` namespace helpers.
31266
+ | Method | Returns | Effect |
31267
+ | ----------------- | ------------------------------------------------- | ------------------------------------------------------------------------ |
31268
+ | `optional()` | `Schema` | Accepts `undefined` |
31269
+ | `nullable()` | `Schema` | Accepts `null` |
31270
+ | `nullish()` | `Schema` | Accepts `null` and `undefined` |
31271
+ | `required()` | `Schema, …>` | Rejects `undefined` again; clears `optional()` and `default()` |
31272
+ | `default(value)` | `this` | Returns a fresh copy of `value` for `undefined`; a function is a factory |
31273
+ | `catch(fallback)` | `this` | Returns a fresh copy of `fallback` when validation fails |
31274
+ | `transform(fn)` | `Schema` | Maps the value in chain order; skipped once an earlier step failed |
31275
+ | `preprocess(fn)` | `this` | Maps raw input before the type check |
31276
+ | `pipe(next)` | `PipeSchema` | Parses with this schema, then feeds the output to `next` |
31277
+ | `describe(text)` | `this` | Sets `description`, which `definition()` includes |
31150
31278
 
31151
- ## Parsing
31279
+ `optional()`, `nullable()`, `nullish()`, `required()`, and `transform()` change the value type, so they return a base `Schema`. Chain type-specific methods such as `.min()` or `.extend()` before them.
31152
31280
 
31153
- Every schema provides:
31281
+ ### Properties and definitions
31154
31282
 
31155
- ```ts
31156
- schema.parse(value, context?); // Output or SpellValidationError
31157
- schema.safeParse(value, context?); // ParseResult
31158
- schema.parseAsync(value, context?); // Promise
31159
- schema.safeParseAsync(value, context?); // Promise>
31160
- schema.is(value); // value is Output
31161
- schema.assert(value, label?); // assertion
31162
- ```
31283
+ | Member | Type | Description |
31284
+ | -------------- | --------------------------------------- | ---------------------------------------------------------------- |
31285
+ | `kind` | `SchemaKind` | Schema kind, e.g. `'string'` or `'object'` |
31286
+ | `description` | `string \| undefined` | Text set with `describe()` |
31287
+ | `isOptional` | `boolean` | `true` with `optional()`, `nullish()`, `default()`, or `catch()` |
31288
+ | `isNullable` | `boolean` | `true` with `nullable()` or `nullish()` |
31289
+ | `'~standard'` | `StandardSchemaV1.Props` | Standard Schema v1 protocol |
31290
+ | `definition()` | `SchemaDescriptor` | Frozen declarative descriptor |
31291
+
31292
+ `definition()` throws `SpellDefinitionError` when the schema, or a nested schema, has runtime-only behavior: `check()`, `checkAsync()`, `transform()`, `preprocess()` (including `s.coerce.*`, `trim()`, `lowercase()`, `uppercase()`), `default()`, `catch()`, or `array().unique({ by })`.
31163
31293
 
31164
- `parse()`, `safeParse()`, `is()`, and `assert()` run synchronous parsing. When a schema, or any schema nested inside it: carries an async check added with `checkAsync()`, the synchronous methods throw at runtime with "cannot evaluate async checks"; use `parseAsync()` or `safeParseAsync()` instead. Async checks compose at any nesting depth, so `s.object({ tags: s.array(s.string().checkAsync(fn)) })` parses correctly through `parseAsync()`.
31294
+ ### Standard Schema
31165
31295
 
31166
- UI adapters that accept `AnySchema` cannot call `safeParse()` on it: the structural surface type omits it. Type adapter parameters against `SyncParsable` instead:
31296
+ `schema['~standard'].validate(value)` returns a result synchronously unless the schema has async checks, in which case it returns a Promise. Successful results contain `value`; failures contain `{ message, path }` issues. A failed union stays one union issue.
31167
31297
 
31168
31298
  ```ts
31169
- import type { SyncParsable } from '@vielzeug/spell';
31299
+ const User = s.object({ name: s.string() });
31300
+ const result = await User['~standard'].validate({ name: 'Ada' });
31301
+ ```
31170
31302
 
31171
- function spellValidator(schema: SyncParsable) {
31172
- const result = schema.safeParse(value); // types cleanly, no shim or cast
31173
- }
31303
+ ## String Schema
31304
+
31305
+ ```ts
31306
+ min(length: number, message?): this;
31307
+ max(length: number, message?): this;
31308
+ length(exact: number, message?): this;
31309
+ nonEmpty(message?): this;
31310
+ startsWith(prefix: string, message?): this;
31311
+ endsWith(suffix: string, message?): this;
31312
+ includes(substr: string, message?): this;
31313
+ regex(pattern: RegExp, message?): this;
31314
+ url(options?: { message?: MessageFn; protocols?: readonly string[] }): this;
31315
+ nanoid(length?: number, message?): this;
31316
+ trim(): this;
31317
+ lowercase(): this;
31318
+ uppercase(): this;
31174
31319
  ```
31175
31320
 
31176
- The shape is structural, so a schema with async checks is assignable to `SyncParsable`; calling `safeParse()` on one returns a failed result ("parse() cannot evaluate async checks"). When async checks may be present, use `safeParseAsync()` instead.
31321
+ Format methods take an optional `message`: `email`, `url`, `uuid`, `isoDate`, `isoDateTime`, `time`, `duration`, `ip`, `cuid`, `cuid2`, `ulid`, `nanoid`, `base64`, `base64url`, `hex`, `hexColor`, `emoji`, `jwt`, `semver`, `slug`, `numeric`.
31177
31322
 
31178
- ## Custom Checks
31323
+ Format and pattern failures use code `invalid_format` with `params.format` set to the method name, such as `'email'`, `'isoDate'`, `'startsWith'`, or `'regex'`. `url()` accepts `http` and `https` unless `protocols` is given. `regex()` drops the stateful `g` and `y` flags. `trim()`, `lowercase()`, and `uppercase()` are ordered transforms: constraints chained after them see the normalized value.
31179
31324
 
31180
- `check()` is synchronous. `checkAsync()` is asynchronous. Do not return a Promise from `check()`.
31325
+ ## Number, BigInt, and Date Schemas
31181
31326
 
31182
- ```ts
31183
- const Signup = s.object({ confirm: s.string(), password: s.string() }).check((value, context) => {
31184
- if (value.password !== value.confirm) {
31185
- context.addIssue({ code: 'custom', message: 'Passwords must match', path: ['confirm'] });
31186
- }
31187
- });
31327
+ | Schema | Methods |
31328
+ | -------------- | --------------------------------------------------------------------------------------------------------- |
31329
+ | `NumberSchema` | `min`, `max`, `positive`, `negative`, `nonNegative`, `nonPositive`, `int`, `safe`, `finite`, `multipleOf` |
31330
+ | `BigIntSchema` | `min`, `max`, `positive`, `negative`, `nonNegative`, `nonPositive`, `multipleOf` |
31331
+ | `DateSchema` | `min(date)`, `max(date)` |
31188
31332
 
31189
- const AvailableEmail = s
31190
- .string()
31191
- .email()
31192
- .checkAsync(async (value) => {
31193
- return (await emailAvailable(value)) || 'Email is already registered';
31194
- });
31195
- ```
31333
+ Each method takes an optional trailing `message`. `safe()` requires an integer within `Number.MIN_SAFE_INTEGER`…`Number.MAX_SAFE_INTEGER`.
31196
31334
 
31197
- `CheckContext.addIssue()` takes `{ code, message, params?, path? }`. Paths are relative to current schema.
31335
+ ## Collection Schemas
31198
31336
 
31199
- ## Modifiers and Transforms
31337
+ | Schema | Methods and members |
31338
+ | -------------- | ------------------------------------------------------ |
31339
+ | `ArraySchema` | `min`, `max`, `length`, `nonEmpty`, `unique(options?)` |
31340
+ | `TupleSchema` | `items`, `rest(schema)` |
31341
+ | `SetSchema` | `min`, `max`, `size`, `nonEmpty` |
31342
+ | `MapSchema` | `min`, `max`, `size`, `nonEmpty` |
31343
+ | `RecordSchema` | (none) |
31200
31344
 
31201
31345
  ```ts
31202
- s.string().optional();
31203
- s.string().nullable();
31204
- s.string().nullish();
31205
- s.string().required();
31206
- s.string().default('guest');
31207
- s.string().catch('guest');
31208
- s.string()
31209
- .trim()
31210
- .transform((value) => value.toLowerCase());
31211
- s.string().pipe(s.string().slug());
31212
- s.string().label('User name');
31346
+ unique(options?: { by?: (item: InferOutput) => unknown; message?: MessageFn }): this;
31213
31347
  ```
31214
31348
 
31215
- `default()`, `catch()`, preprocessors, transforms, and checks are runtime behavior. They cannot become portable definitions.
31349
+ `unique()` compares items with `Set` semantics, or compares the keys returned by `by`. A `by` selector makes `definition()` throw.
31216
31350
 
31217
- ## `tolerate()`
31218
-
31219
- Wraps an object schema so records saved by older schema versions still parse: the named keys are accepted and stripped instead of failing `invalid_keys`. The parsed output never contains the tolerated keys.
31351
+ ## Object Schema
31220
31352
 
31221
31353
  ```ts
31222
- const Person = tolerate(s.object({ name: s.string() }), 'address');
31354
+ readonly shape: T;
31355
+ relaxed(): this;
31356
+ strict(): this;
31357
+ tolerate(...keys: string[]): this;
31358
+ extend(extra: U): ObjectSchema & U>;
31359
+ pick(...keys: K[]): ObjectSchema>;
31360
+ omit(...keys: K[]): ObjectSchema>;
31361
+ partial(): ObjectSchema }>;
31362
+ partial(...keys: K[]): ObjectSchema & { [P in K]: Optional }>;
31363
+ keyof(): EnumSchema;
31223
31364
  ```
31224
31365
 
31225
- The implementation is a preprocessor on the wrapped schema: non-object input reaches the wrapped schema untouched, declared fields keep their validation, and unknown keys outside the tolerated set still fail.
31366
+ | Method | Description |
31367
+ | ------------ | ---------------------------------------------------------------------------- |
31368
+ | `strict()` | Rejects unknown keys with one `invalid_keys` issue (default) |
31369
+ | `relaxed()` | Copies unknown keys to the output, skipping unsafe keys |
31370
+ | `tolerate()` | Accepts and drops the named keys; other unknown keys follow the current mode |
31371
+ | `extend()` | Adds fields; same-named fields are replaced |
31372
+ | `pick()` | Keeps the named fields |
31373
+ | `omit()` | Removes the named fields |
31374
+ | `partial()` | Makes all or the named fields optional |
31375
+ | `keyof()` | Enum schema of the shape keys |
31226
31376
 
31227
- ## Definitions and JSON Schema
31377
+ `extend()`, `pick()`, `omit()`, and `partial()` keep the unknown-key mode, tolerated keys, description, and `optional`/`nullable` flags. They throw `SpellDefinitionError` when the object has checks, transforms, preprocessors, a default, or a catch, because those were written for the old shape.
31228
31378
 
31229
- `definition()` is only for schemas containing declarative structure. It returns frozen data and throws `SpellDefinitionError` when runtime behavior is present.
31379
+ Absent keys whose field returns `undefined` are left out of the output. Field defaults are written for absent keys.
31230
31380
 
31231
- ```ts
31232
- import { s } from '@vielzeug/spell';
31233
- import { fromDefinition } from '@vielzeug/spell/json';
31381
+ ## Composition Schemas
31234
31382
 
31235
- const Product = s.object({
31236
- id: s.string().uuid(),
31237
- name: s.string().min(1),
31238
- });
31383
+ | Schema | Members | Failure |
31384
+ | -------------------------- | ------------------------------------------- | --------------------------------------------------------------------- |
31385
+ | `UnionSchema` | `schemas` | One `invalid_union` issue; `params.errors` holds each branch's issues |
31386
+ | `IntersectSchema` | `schemas` | Issues from every failing branch |
31387
+ | `DiscriminatedUnionSchema` | `discriminator`, `branches` (`ReadonlyMap`) | `invalid_discriminator` for an unknown tag; branch issues otherwise |
31388
+ | `LazySchema` | (none) | Issues of the resolved schema |
31389
+ | `PipeSchema` | `from`, `to` | Issues of the first failing stage |
31239
31390
 
31240
- const definition = Product.definition();
31241
- const jsonSchema = fromDefinition(definition);
31242
- ```
31391
+ `s.discriminatedUnion(key, branches)` adds `key` as a literal of the branch tag when a branch omits it. It throws `SpellDefinitionError` when a branch is not an object schema or declares `key` with a different schema.
31243
31392
 
31244
- No implicit schema-to-JSON conversion exists. Make definition boundary explicit.
31393
+ Intersections of object schemas need `.relaxed()` branches, because each strict branch rejects the other branch's keys.
31245
31394
 
31246
31395
  ## Parse Contexts
31247
31396
 
31248
- `createParseContext()` creates immutable request-local validation messages.
31249
-
31250
31397
  ```ts
31251
31398
  function createParseContext(messages?: DeepPartial): ParseContext;
31252
31399
  ```
31253
31400
 
31254
- **Returns:** A parse context with built-in messages merged with the supplied overrides.
31401
+ **Returns:** A frozen parse context with the built-in messages merged with the supplied overrides. Unsafe override keys such as `__proto__` are ignored with a development warning.
31402
+
31403
+ **Example:**
31255
31404
 
31256
31405
  ```ts
31257
31406
  import { createParseContext, s } from '@vielzeug/spell';
31258
31407
 
31259
- const context = createParseContext({
31260
- object: { invalidKeys: () => 'Unsupported field' },
31261
- });
31262
-
31408
+ const context = createParseContext({ object: { invalidKeys: () => 'Unsupported field' } });
31263
31409
  const result = s.object({ email: s.string().email() }).safeParse({ email: 'ada@example.com', extra: true }, context);
31264
31410
 
31265
- if (!result.success) {
31266
- const messages = result.error.messagesAt('email');
31267
- console.log(messages);
31268
- }
31411
+ if (!result.success) console.log(result.error.issues[0].message); // 'Unsupported field'
31412
+ ```
31413
+
31414
+ ## JSON Schema
31415
+
31416
+ ```ts
31417
+ import { toJsonSchema, type JsonSchema } from '@vielzeug/spell/json';
31418
+
31419
+ function toJsonSchema(definition: SchemaDescriptor): JsonSchema;
31420
+ ```
31421
+
31422
+ **Returns:** A JSON Schema 2020-12 object.
31423
+
31424
+ | Definition | JSON Schema |
31425
+ | ------------------------------- | ------------------------------------------------------------------- |
31426
+ | `isoDate`, `isoDateTime`, `url` | `format: 'date'`, `'date-time'`, `'uri'` |
31427
+ | `base64`, `base64url` | `contentEncoding` |
31428
+ | `ip` | `anyOf` of `ipv4` and `ipv6` formats |
31429
+ | Several formats or patterns | `allOf` |
31430
+ | `bigint` bounds | Numeric bounds (may lose precision above `Number.MAX_SAFE_INTEGER`) |
31431
+ | `date`, `instanceof` | `$comment` only |
31432
+ | `set`, `map` | Array with `uniqueItems`, object with `additionalProperties` |
31433
+ | `isNullable` | `anyOf` with `{ type: 'null' }` |
31434
+
31435
+ **Example:**
31436
+
31437
+ ```ts
31438
+ import { s } from '@vielzeug/spell';
31439
+ import { toJsonSchema } from '@vielzeug/spell/json';
31440
+
31441
+ const jsonSchema = toJsonSchema(s.object({ id: s.string().uuid() }).definition());
31269
31442
  ```
31270
31443
 
31444
+ ## Predicates
31445
+
31446
+ `@vielzeug/spell/predicates` exports the format tests used by `StringSchema`. Each takes a string and returns `boolean`.
31447
+
31448
+ `isBase64`, `isBase64url`, `isCuid`, `isCuid2`, `isDuration`, `isEmail`, `isEmoji`, `isHex`, `isHexColor`, `isIp`, `isIsoDate`, `isIsoDateTime`, `isJwt`, `isNanoid(value, length = 21)`, `isNumeric`, `isSemver`, `isSlug`, `isTime`, `isUlid`, `isUrl(value, protocols = ['http', 'https'])`, `isUuid`.
31449
+
31271
31450
  ## Types
31272
31451
 
31273
31452
  ### Inference types
@@ -31277,43 +31456,9 @@ if (!result.success) {
31277
31456
  | `Infer` | Parsed output; alias of `InferOutput` |
31278
31457
  | `InferInput` | Input accepted before parsing or transformation |
31279
31458
  | `InferOutput` | Value returned after parsing and transformation |
31459
+ | `AnySchema` | `Schema`; any schema |
31280
31460
 
31281
- Composite schemas preserve child input types. Object input types make fields optional when their field schema accepts `undefined`.
31282
-
31283
- ### Standard Schema
31284
-
31285
- ```ts
31286
- interface StandardSchemaV1 {
31287
- readonly '~standard': StandardSchemaV1.Props;
31288
- }
31289
-
31290
- namespace StandardSchemaV1 {
31291
- interface Props {
31292
- readonly version: 1;
31293
- readonly vendor: string;
31294
- readonly validate: (value: unknown, options?: Options) => Result | Promise>;
31295
- readonly types?: Types;
31296
- }
31297
-
31298
- type Result = { readonly value: Output; readonly issues?: undefined } | { readonly issues: readonly Issue[] };
31299
- interface Options {
31300
- readonly libraryOptions?: Record;
31301
- }
31302
- interface Issue {
31303
- readonly message: string;
31304
- readonly path?: readonly (PropertyKey | PathSegment)[];
31305
- }
31306
- interface PathSegment {
31307
- readonly key: PropertyKey;
31308
- }
31309
- interface Types {
31310
- readonly input: Input;
31311
- readonly output: Output;
31312
- }
31313
- type InferInput = NonNullable['input'];
31314
- type InferOutput = NonNullable['output'];
31315
- }
31316
- ```
31461
+ Object input types make a field optional when its schema accepts a missing value (`optional()`, `nullish()`, `default()`, `catch()`). Use `AnySchema` as a generic constraint, and `Schema` for a parameter that must parse to `T`.
31317
31462
 
31318
31463
  ### Parse result and issues
31319
31464
 
@@ -31322,33 +31467,30 @@ type ParseResult = { data: T; success: true } | { error: SpellValidationError; s
31322
31467
 
31323
31468
  type Issue =
31324
31469
  | { code: 'custom'; message: string; params?: Record; path: (string | number)[] }
31325
- | { code: 'invalid_base64'; message: string; params: { format: string }; path: (string | number)[] }
31326
31470
  | { code: 'invalid_date'; message: string; params?: undefined; path: (string | number)[] }
31327
- | { code: 'invalid_duration'; message: string; params: { format: string }; path: (string | number)[] }
31471
+ | {
31472
+ code: 'invalid_discriminator';
31473
+ message: string;
31474
+ params: { discriminator: string; expected: string[] };
31475
+ path: (string | number)[];
31476
+ }
31328
31477
  | { code: 'invalid_enum'; message: string; params: { values: readonly unknown[] }; path: (string | number)[] }
31329
31478
  | { code: 'invalid_finite'; message: string; params?: undefined; path: (string | number)[] }
31479
+ | {
31480
+ code: 'invalid_format';
31481
+ message: string;
31482
+ params: { format: string; includes?: string; pattern?: string; prefix?: string; suffix?: string };
31483
+ path: (string | number)[];
31484
+ }
31330
31485
  | { code: 'invalid_integer'; message: string; params?: undefined; path: (string | number)[] }
31331
31486
  | { code: 'invalid_keys'; message: string; params: { keys: string[] }; path: (string | number)[] }
31332
31487
  | { code: 'invalid_length'; message: string; params: { exact: number }; path: (string | number)[] }
31333
31488
  | { code: 'invalid_literal'; message: string; params: { expected: unknown }; path: (string | number)[] }
31334
31489
  | { code: 'invalid_multiple_of'; message: string; params: { step: number | bigint }; path: (string | number)[] }
31335
31490
  | { code: 'invalid_safe'; message: string; params?: undefined; path: (string | number)[] }
31336
- | {
31337
- code: 'invalid_string';
31338
- message: string;
31339
- params: { format?: string; includes?: string; pattern?: string; prefix?: string; suffix?: string };
31340
- path: (string | number)[];
31341
- }
31342
31491
  | { code: 'invalid_type'; message: string; params?: undefined; path: (string | number)[] }
31343
31492
  | { code: 'invalid_union'; message: string; params: { errors: Issue[][] }; path: (string | number)[] }
31344
- | { code: 'invalid_unique'; message: string; params: { unique: true }; path: (string | number)[] }
31345
- | { code: 'invalid_url'; message: string; params: { format: string }; path: (string | number)[] }
31346
- | {
31347
- code: 'invalid_variant';
31348
- message: string;
31349
- params: { discriminator: string; expected: string[] };
31350
- path: (string | number)[];
31351
- }
31493
+ | { code: 'invalid_unique'; message: string; params?: undefined; path: (string | number)[] }
31352
31494
  | {
31353
31495
  code: 'too_big';
31354
31496
  message: string;
@@ -31364,12 +31506,12 @@ type Issue =
31364
31506
  | { code: string & {}; message: string; params?: Record; path: (string | number)[] };
31365
31507
  ```
31366
31508
 
31367
- `ErrorCode` is a const object mapping each issue code to its string literal.
31509
+ `ErrorCode` is a const object mapping each built-in code to its string literal.
31368
31510
 
31369
31511
  ### Validation contracts
31370
31512
 
31371
31513
  ```ts
31372
- type ParseContext = { messages: Messages };
31514
+ type ParseContext = { readonly messages: Messages };
31373
31515
 
31374
31516
  type CheckContext = {
31375
31517
  addIssue: (issue: {
@@ -31381,151 +31523,162 @@ type CheckContext = {
31381
31523
  };
31382
31524
 
31383
31525
  type ValidateResult = boolean | null | undefined | string;
31526
+
31527
+ type MessageFn = Record> = string | ((ctx: Ctx) => string);
31528
+
31529
+ type DeepPartial = { [K in keyof T]?: T[K] extends Record ? DeepPartial : T[K] };
31384
31530
  ```
31385
31531
 
31386
31532
  ### Messages
31387
31533
 
31388
- ```ts
31389
- type MessageFn = Record> = string | ((ctx: Ctx) => string);
31534
+ `Messages` has one group per schema type. Each entry is a function of the constraint context.
31390
31535
 
31536
+ ```ts
31391
31537
  type Messages = {
31392
- array: {
31393
- length: (ctx: { exact: number; value: unknown[] }) => string;
31394
- max: (ctx: { max: number; value: unknown[] }) => string;
31395
- min: (ctx: { min: number; value: unknown[] }) => string;
31396
- nonEmpty: () => string;
31397
- type: () => string;
31398
- unique: () => string;
31399
- };
31400
- bigint: {
31401
- max: (ctx: { max: bigint; value: bigint }) => string;
31402
- min: (ctx: { min: bigint; value: bigint }) => string;
31403
- multipleOf: (ctx: { step: bigint; value: bigint }) => string;
31404
- negative: () => string;
31405
- nonNegative: () => string;
31406
- nonPositive: () => string;
31407
- positive: () => string;
31408
- type: () => string;
31409
- };
31410
- boolean: { type: () => string };
31411
- check: { default: () => string };
31412
- date: {
31413
- max: (ctx: { max: Date; value: Date }) => string;
31414
- min: (ctx: { min: Date; value: Date }) => string;
31415
- type: () => string;
31416
- };
31538
+ array: { length; max; min; nonEmpty; type; unique };
31539
+ bigint: { max; min; multipleOf; negative; nonNegative; nonPositive; positive; type };
31540
+ boolean: { type };
31541
+ check: { default };
31542
+ date: { max; min; type };
31543
+ discriminatedUnion: { invalidDiscriminator: (ctx: { discriminator: string; expected: string[] }) => string; type };
31417
31544
  enum: { invalid: (ctx: { values: readonly unknown[] }) => string };
31418
31545
  instanceof: { type: (ctx: { className: string }) => string };
31419
31546
  literal: { expected: (ctx: { expected: unknown }) => string };
31420
- map: {
31421
- max: (ctx: { max: number; value: Map }) => string;
31422
- min: (ctx: { min: number; value: Map }) => string;
31423
- nonEmpty: () => string;
31424
- size: (ctx: { exact: number; value: Map }) => string;
31425
- type: () => string;
31426
- };
31427
- never: { invalid: () => string };
31428
- number: {
31429
- finite: () => string;
31430
- int: () => string;
31431
- max: (ctx: { max: number; value: number }) => string;
31432
- min: (ctx: { min: number; value: number }) => string;
31433
- multipleOf: (ctx: { step: number; value: number }) => string;
31434
- negative: () => string;
31435
- nonNegative: () => string;
31436
- nonPositive: () => string;
31437
- positive: () => string;
31438
- safe: () => string;
31439
- type: () => string;
31440
- };
31441
- object: { invalidKeys: (ctx: { keys: string[] }) => string; type: () => string };
31442
- set: {
31443
- max: (ctx: { max: number; value: Set }) => string;
31444
- min: (ctx: { min: number; value: Set }) => string;
31445
- nonEmpty: () => string;
31446
- size: (ctx: { exact: number; value: Set }) => string;
31447
- type: () => string;
31448
- };
31547
+ map: { max; min; nonEmpty; size; type };
31548
+ never: { invalid };
31549
+ number: { finite; int; max; min; multipleOf; negative; nonNegative; nonPositive; positive; safe; type };
31550
+ object: { invalidKeys: (ctx: { keys: string[] }) => string; type };
31551
+ set: { max; min; nonEmpty; size; type };
31449
31552
  string: {
31450
- base64: () => string;
31451
- base64url: () => string;
31452
- cuid: () => string;
31453
- cuid2: () => string;
31454
- date: () => string;
31455
- dateTime: () => string;
31456
- duration: () => string;
31457
- email: () => string;
31458
- emoji: () => string;
31459
- endsWith: (ctx: { suffix: string; value: string }) => string;
31460
- hex: () => string;
31461
- hexColor: () => string;
31462
- includes: (ctx: { substr: string; value: string }) => string;
31463
- ip: () => string;
31464
- jwt: () => string;
31465
- length: (ctx: { exact: number; value: string }) => string;
31466
- max: (ctx: { max: number; value: string }) => string;
31467
- min: (ctx: { min: number; value: string }) => string;
31468
- nanoid: () => string;
31469
- nonEmpty: () => string;
31470
- numeric: () => string;
31471
- regex: (ctx: { value: string }) => string;
31472
- semver: () => string;
31473
- slug: () => string;
31474
- startsWith: (ctx: { prefix: string; value: string }) => string;
31475
- time: () => string;
31476
- type: () => string;
31477
- ulid: () => string;
31478
- url: () => string;
31479
- uuid: () => string;
31553
+ base64;
31554
+ base64url;
31555
+ cuid;
31556
+ cuid2;
31557
+ duration;
31558
+ email;
31559
+ emoji;
31560
+ endsWith;
31561
+ hex;
31562
+ hexColor;
31563
+ includes;
31564
+ ip;
31565
+ isoDate;
31566
+ isoDateTime;
31567
+ jwt;
31568
+ length;
31569
+ max;
31570
+ min;
31571
+ nanoid;
31572
+ nonEmpty;
31573
+ numeric;
31574
+ regex;
31575
+ semver;
31576
+ slug;
31577
+ startsWith;
31578
+ time;
31579
+ type;
31580
+ ulid;
31581
+ url;
31582
+ uuid;
31480
31583
  };
31481
- tuple: { length: (ctx: { exact: number }) => string; min: (ctx: { min: number }) => string; type: () => string };
31482
- union: { invalid: () => string };
31483
- variant: { invalidDiscriminator: (ctx: { discriminator: string; expected: string[] }) => string; type: () => string };
31584
+ tuple: { length: (ctx: { exact: number }) => string; min: (ctx: { min: number }) => string; type };
31585
+ union: { invalid };
31484
31586
  };
31587
+ ```
31485
31588
 
31486
- type DeepPartial = {
31487
- [K in keyof T]?: T[K] extends Record ? DeepPartial : T[K];
31488
- };
31589
+ Constraint messages receive `value` plus the constraint's parameters, e.g. `string.min` receives `{ min, value }` and `string.includes` receives `{ substr, value }`.
31590
+
31591
+ ### Descriptors
31592
+
31593
+ ```ts
31594
+ type PatternDescriptor = { readonly flags: string; readonly source: string };
31595
+
31596
+ type SchemaDescriptor = { description?: string; isNullable?: true; isOptional?: true } & (
31597
+ | { kind: 'unknown' | 'never' | 'boolean' | 'lazy' }
31598
+ | {
31599
+ kind: 'bigint';
31600
+ exclusiveMaximum?: bigint;
31601
+ exclusiveMinimum?: bigint;
31602
+ maximum?: bigint;
31603
+ minimum?: bigint;
31604
+ multipleOf?: bigint;
31605
+ }
31606
+ | {
31607
+ kind: 'number';
31608
+ exclusiveMaximum?: number;
31609
+ exclusiveMinimum?: number;
31610
+ finite?: true;
31611
+ integer?: true;
31612
+ maximum?: number;
31613
+ minimum?: number;
31614
+ multipleOf?: number;
31615
+ }
31616
+ | {
31617
+ kind: 'string';
31618
+ formats?: readonly string[];
31619
+ maxLength?: number;
31620
+ minLength?: number;
31621
+ patterns?: readonly PatternDescriptor[];
31622
+ }
31623
+ | { kind: 'date'; maximum?: string; minimum?: string }
31624
+ | { className: string; kind: 'instanceof' }
31625
+ | { kind: 'literal'; value: string | number | boolean | null | undefined }
31626
+ | { kind: 'enum'; values: readonly (string | number)[] }
31627
+ | { items: SchemaDescriptor; kind: 'array'; maxItems?: number; minItems?: number; uniqueItems?: true }
31628
+ | { items: readonly SchemaDescriptor[]; kind: 'tuple'; rest: SchemaDescriptor | null }
31629
+ | {
31630
+ fields: Readonly>;
31631
+ kind: 'object';
31632
+ strict: boolean;
31633
+ tolerated?: readonly string[];
31634
+ }
31635
+ | { key: SchemaDescriptor; kind: 'record'; value: SchemaDescriptor }
31636
+ | { items: SchemaDescriptor; kind: 'set'; maxSize?: number; minSize?: number }
31637
+ | { key: SchemaDescriptor; kind: 'map'; maxSize?: number; minSize?: number; value: SchemaDescriptor }
31638
+ | { branches: readonly SchemaDescriptor[]; kind: 'union' | 'intersect' }
31639
+ | { branches: Readonly>; discriminator: string; kind: 'discriminatedUnion' }
31640
+ | { from: SchemaDescriptor; kind: 'pipe'; to: SchemaDescriptor }
31641
+ );
31642
+
31643
+ type SchemaKind = SchemaDescriptor['kind'];
31644
+
31645
+ type JsonSchema = Record; // from '@vielzeug/spell/json'
31489
31646
  ```
31490
31647
 
31491
- ### Descriptor and JSON Schema
31648
+ Date bounds are ISO strings. `formats` lists format method names in chain order; `patterns` lists `regex()`, `startsWith()`, `endsWith()`, `includes()`, and `url()` protocol patterns.
31649
+
31650
+ ### Standard Schema
31492
31651
 
31493
31652
  ```ts
31494
- type SchemaDescriptor = BaseDescriptor &
31495
- (
31496
- | { kind: 'unknown' | 'never' | 'boolean' | 'bigint' | 'date' | 'lazy' }
31497
- | { className: string; kind: 'instanceof' }
31498
- | {
31499
- contentEncoding?: string;
31500
- format?: string;
31501
- kind: 'string';
31502
- maxLength?: number;
31503
- minLength?: number;
31504
- pattern?: string | null;
31505
- }
31506
- | {
31507
- exclusiveMaximum?: number;
31508
- exclusiveMinimum?: number;
31509
- kind: 'number';
31510
- maximum?: number;
31511
- minimum?: number;
31512
- multipleOf?: number;
31513
- typeHint?: 'integer';
31514
- }
31515
- | { kind: 'literal'; value: string | number | boolean | null | undefined }
31516
- | { kind: 'enum'; values: readonly (string | number)[] }
31517
- | { items: SchemaDescriptor; kind: 'array'; maxItems?: number; minItems?: number }
31518
- | { items: SchemaDescriptor[]; kind: 'tuple'; rest: SchemaDescriptor | null }
31519
- | { fields: Record; kind: 'object'; strict: boolean }
31520
- | { key: SchemaDescriptor; kind: 'record'; value: SchemaDescriptor }
31521
- | { items: SchemaDescriptor; kind: 'set' }
31522
- | { key: SchemaDescriptor; kind: 'map'; value: SchemaDescriptor }
31523
- | { branches: SchemaDescriptor[]; kind: 'union' | 'intersect' }
31524
- | { branches: Record; discriminator: string; kind: 'variant' }
31525
- | { from: SchemaDescriptor; kind: 'pipe'; to: SchemaDescriptor }
31526
- );
31653
+ interface StandardSchemaV1 {
31654
+ readonly '~standard': StandardSchemaV1.Props;
31655
+ }
31527
31656
 
31528
- type JsonSchema = Record;
31657
+ namespace StandardSchemaV1 {
31658
+ interface Props {
31659
+ readonly types?: Types | undefined;
31660
+ readonly validate: (value: unknown, options?: Options | undefined) => Result | Promise>;
31661
+ readonly vendor: string;
31662
+ readonly version: 1;
31663
+ }
31664
+ type Result = { readonly issues: readonly Issue[] } | { readonly issues?: undefined; readonly value: Output };
31665
+ interface Options {
31666
+ readonly libraryOptions?: Record | undefined;
31667
+ }
31668
+ interface Issue {
31669
+ readonly message: string;
31670
+ readonly path?: readonly (PropertyKey | PathSegment)[] | undefined;
31671
+ }
31672
+ interface PathSegment {
31673
+ readonly key: PropertyKey;
31674
+ }
31675
+ interface Types {
31676
+ readonly input: Input;
31677
+ readonly output: Output;
31678
+ }
31679
+ type InferInput = NonNullable['input'];
31680
+ type InferOutput = NonNullable['output'];
31681
+ }
31529
31682
  ```
31530
31683
 
31531
31684
  ### Error helpers
@@ -31534,23 +31687,23 @@ type JsonSchema = Record;
31534
31687
  type FlatError = { messages: string[]; path: (string | number)[] };
31535
31688
  type FlatErrorFirst = { message: string; path: (string | number)[] };
31536
31689
 
31537
- /** An issue path in either shape: spell-native segments or Standard Schema `{ key }` segments. */
31538
31690
  type IssuePathSegment = PropertyKey | { readonly key: PropertyKey };
31539
31691
  type IssuePath = readonly IssuePathSegment[];
31540
31692
 
31541
- /** The synchronous parse surface; `AnySchema` omits `safeParse`, adapter parameters use this. */
31542
- type SyncParsable = { safeParse(value: unknown): ParseResult };
31543
-
31544
31693
  function joinIssuePath(path: IssuePath | undefined, separator?: string): string;
31545
31694
  ```
31546
31695
 
31547
- `joinIssuePath()` flattens an issue path into a UI key such as `'permissions.0.slug'`. It accepts spell-native `(string | number)[]` paths and Standard Schema paths with `{ key }` segments, and returns `''` for empty or undefined paths.
31696
+ `joinIssuePath()` flattens a Spell or Standard Schema issue path into a UI key such as `'permissions.0.slug'`.
31548
31697
 
31549
31698
  ## Errors
31550
31699
 
31551
- - `SpellError`: base class. Use `instanceof SpellError` for cross-boundary narrowing.
31552
- - `SpellValidationError`: validation failure with `issues`, `messagesAt()`, `flatten()`, and `flattenFirst()`.
31553
- - `SpellDefinitionError`: schema cannot create portable definition.
31700
+ | Class | Thrown when | Members |
31701
+ | ---------------------- | ------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------- |
31702
+ | `SpellError` | Base class; thrown directly when synchronous parsing meets an async check | `name`, `message` |
31703
+ | `SpellValidationError` | `parse()`, `parseAsync()`, or `assert()` receives invalid input | `issues` (frozen), `flatten()`, `flattenFirst()`, `messagesAt(...path)` |
31704
+ | `SpellDefinitionError` | `definition()` on a non-portable schema; invalid object derivation or discriminated branch | `name`, `message` |
31705
+
31706
+ `SpellValidationError.message` lists one `path: message [code]` line per issue; root issues use `value` as the path.
31554
31707
 
31555
31708
  ```ts
31556
31709
  const result = s.object({ email: s.string().email() }).safeParse({ email: 'invalid' });
@@ -31588,42 +31741,27 @@ if (!result.success) {
31588
31741
  }
31589
31742
  ```
31590
31743
 
31591
- Use `parse()` when invalid input should throw immediately. Use `safeParse()` when invalid input is part of normal control flow.
31744
+ Use `parse()` when invalid input should throw. Use `safeParse()` when invalid input is part of normal control flow.
31592
31745
 
31593
31746
  ## Building Schemas
31594
31747
 
31595
- Use the namespace form when readability matters more than bundle trimming.
31748
+ Compose schemas from the `s` builders. Every method returns a new schema, so you can share and extend base schemas safely.
31596
31749
 
31597
31750
  ```ts
31598
31751
  import { s } from '@vielzeug/spell';
31599
31752
 
31600
31753
  const Article = s.object({
31601
31754
  id: s.string().uuid(),
31602
- title: s.string().trim().min(1).max(120),
31755
+ meta: s.object({ published: s.boolean(), publishedAt: s.date().nullable() }).relaxed(),
31603
31756
  slug: s.string().slug(),
31604
- tags: s.array(s.string().min(1)).default(() => []),
31605
- meta: s
31606
- .object({
31607
- published: s.boolean(),
31608
- publishedAt: s.date().nullable(),
31609
- })
31610
- .relaxed(),
31611
- });
31612
- ```
31613
-
31614
- ```ts
31615
- import { s } from '@vielzeug/spell';
31616
-
31617
- const Todo = s.object({
31618
- done: s.boolean(),
31619
- tags: s.array(s.string().min(1)).default(() => []),
31620
- title: s.string().min(1),
31757
+ tags: s.array(s.string().min(1)).default([]),
31758
+ title: s.string().trim().min(1).max(120),
31621
31759
  });
31622
31760
  ```
31623
31761
 
31624
- Object schemas reject unknown keys by default. Call `.relaxed()` when you need to preserve extra properties.
31762
+ Object schemas reject unknown keys by default. Call `.relaxed()` to keep extra properties in the output.
31625
31763
 
31626
- Call `.defaults()` to get a fully default-filled object without providing any input. Every required field must have a `.default()` set, or a `SpellValidationError` is thrown. Call `.partialDefaults()` when only some fields have defaults: fields without a default are silently omitted instead of throwing.
31764
+ Fields with a `default()` are filled in when their key is absent, so `parse({})` returns a fully default-filled object.
31627
31765
 
31628
31766
  ```ts
31629
31767
  const Config = s.object({
@@ -31631,92 +31769,68 @@ const Config = s.object({
31631
31769
  port: s.number().default(3000),
31632
31770
  });
31633
31771
 
31634
- Config.defaults(); // { host: 'localhost', port: 3000 }
31635
-
31636
- const Form = s.object({ name: s.string(), role: s.string().default('viewer') });
31637
- Form.partialDefaults(); // { role: 'viewer' }
31772
+ Config.parse({}); // { host: 'localhost', port: 3000 }
31638
31773
  ```
31639
31774
 
31640
- ## Wrapper Modes, Defaults, and Fallbacks
31641
-
31642
- Chain wrappers to describe missing values and recovery rules without losing schema metadata.
31643
-
31644
- ```ts
31645
- import { s } from '@vielzeug/spell';
31775
+ `default()` and `catch()` return a fresh copy of object, array, `Map`, `Set`, and `Date` values on every parse, so callers cannot mutate a shared default.
31646
31776
 
31647
- const DisplayName = s.string().trim().min(2).label('Display name').optional().default('Guest').nullable();
31777
+ ## Ordering Checks and Transforms
31648
31778
 
31649
- DisplayName.parse(undefined); // 'Guest'
31650
- DisplayName.parse(null); // null
31651
- DisplayName.description; // 'Display name'
31652
- ```
31653
-
31654
- Call `.required()` to remove `undefined` without removing `null`.
31779
+ Checks, built-in constraints, and transforms run in the order you chain them. A constraint after a transform sees the transformed value.
31655
31780
 
31656
31781
  ```ts
31657
31782
  import { s } from '@vielzeug/spell';
31658
31783
 
31659
- const NullableButRequired = s.string().optional().nullable().required();
31784
+ // trim() runs first, so ' ' fails min(1)
31785
+ const Title = s.string().trim().min(1);
31660
31786
 
31661
- NullableButRequired.parse('Ada');
31662
- NullableButRequired.parse(null);
31663
- // NullableButRequired.parse(undefined); // throws
31787
+ // The check receives the length, not the string
31788
+ const ShortCode = s
31789
+ .string()
31790
+ .transform((value) => value.length)
31791
+ .check((length) => length value.password === value.confirm || 'Passwords must match');
31664
31792
  ```
31665
31793
 
31666
- Use `.catch()` when you want a fallback output after validation fails.
31667
-
31668
- ```ts
31669
- import { s } from '@vielzeug/spell';
31670
-
31671
- const Port = s.number().int().min(1).max(65535).catch(3000);
31672
-
31673
- Port.parse('not-a-number'); // 3000
31674
- ```
31794
+ Deriving from an object with checks, transforms, preprocessors, a default, or a catch throws `SpellDefinitionError`. A check written for the old shape could read a field that `omit()` removed, so Spell refuses instead of guessing.
31675
31795
 
31676
31796
  ## Tolerating Removed Fields
31677
31797
 
31678
- When a persisted record shape evolves, records saved by older versions carry keys the current schema no longer declares. `tolerate` accepts and drops exactly the named keys, so one call documents one removed field: no optional placeholder in the schema and no strip step after parsing.
31798
+ Records saved by older schema versions can carry keys the current schema no longer declares. `tolerate()` accepts and drops exactly the named keys, and other unknown keys still fail.
31679
31799
 
31680
31800
  ```ts
31681
- import { s, tolerate } from '@vielzeug/spell';
31801
+ import { s } from '@vielzeug/spell';
31682
31802
 
31683
- const Person = tolerate(s.object({ name: s.string(), email: s.number() }), 'address');
31803
+ const Person = s.object({ email: s.string(), name: s.string() }).tolerate('address');
31684
31804
 
31685
- const parsed = Person.parse({
31686
- name: 'John Doe',
31687
- address: 'p sherman 42 wallaby way sydney',
31688
- email: 'johndoe@mail.com',
31689
- });
31690
- // { name: 'John Doe', email: 'johndoe@mail.com' }: the tolerated key never reaches the output
31805
+ Person.parse({ address: '42 Wallaby Way', email: 'johndoe@mail.com', name: 'John Doe' });
31806
+ // { email: 'johndoe@mail.com', name: 'John Doe' }
31691
31807
  ```
31692
31808
 
31693
- Fields added to later schema versions do not need `tolerate`: give them `default()` and older records repair on parse.
31809
+ Fields added in later schema versions do not need `tolerate()`: give them a `default()` and older records are repaired on parse.
31694
31810
 
31695
31811
  ## Custom Validation
31696
31812
 
31697
- Use `check()` for synchronous domain rules and `checkAsync()` for asynchronous rules. Sync parsing rejects schemas with asynchronous checks.
31813
+ Use `check()` for synchronous domain rules and `checkAsync()` for asynchronous rules.
31698
31814
 
31699
31815
  ```ts
31700
31816
  import { s } from '@vielzeug/spell';
31701
31817
 
31702
- // Boolean shorthand: return false to fail with default message
31818
+ // Return false to fail with the default message
31703
31819
  const EvenNumber = s.number().check((n) => n % 2 === 0);
31704
31820
 
31705
- // String shorthand: return the message as a string
31821
+ // Return a string to fail with that message
31706
31822
  const Username = s
31707
31823
  .string()
31708
31824
  .min(3)
31709
31825
  .check((v) => !v.startsWith('_') || 'Cannot start with underscore');
31710
31826
 
31711
- // Multiple issues via ctx.addIssue()
31827
+ // Report issues at specific paths with ctx.addIssue()
31712
31828
  const Signup = s.object({ confirm: s.string(), password: s.string() }).check((v, ctx) => {
31713
- if (v.password !== v.confirm) {
31714
- ctx.addIssue({ code: 'custom', message: 'Passwords must match', path: ['confirm'] });
31715
- }
31829
+ if (v.password !== v.confirm) ctx.addIssue({ code: 'custom', message: 'Passwords must match', path: ['confirm'] });
31716
31830
  });
31717
31831
  ```
31718
31832
 
31719
- `checkAsync()` marks a schema as asynchronous: synchronous parsing throws at runtime instead of accepting an unchecked value, so async checks require `parseAsync()` or `safeParseAsync()`. Async checks compose at any nesting depth: arrays, objects, unions, intersections, tuples, maps, records, sets, lazy schemas, pipelines, and `s.discriminatedUnion(...)` branches all evaluate nested async checks correctly through `parseAsync()`.
31833
+ A schema containing `checkAsync()` at any depth needs `parseAsync()` or `safeParseAsync()`. The synchronous methods throw `SpellError` before running the async check, because accepting an unchecked value would be unsafe.
31720
31834
 
31721
31835
  ```ts
31722
31836
  import { s } from '@vielzeug/spell';
@@ -31726,28 +31840,14 @@ const takenEmails = new Set(['ada@example.com']);
31726
31840
  const AccountEmail = s
31727
31841
  .string()
31728
31842
  .email()
31729
- .checkAsync(async (value, ctx) => {
31730
- if (takenEmails.has(value)) {
31731
- ctx.addIssue({ code: 'custom', message: 'Email is already taken', path: [] });
31732
- }
31733
- });
31843
+ .checkAsync(async (value) => !takenEmails.has(value) || 'Email is already taken');
31734
31844
 
31735
- // Async checks require parseAsync
31736
31845
  await AccountEmail.parseAsync('grace@example.com');
31737
31846
  ```
31738
31847
 
31739
- Use `check()` for predicate-only rules too. Return `true` on success or message on failure.
31848
+ ## Strings, Numbers, and Regex Safety
31740
31849
 
31741
- ```ts
31742
- import { s } from '@vielzeug/spell';
31743
-
31744
- const PositivePrice = s.number().check((value) => value > 0 || 'Must be positive');
31745
- PositivePrice.parse(9.99);
31746
- ```
31747
-
31748
- ## Strings, Numbers, and Safe Regex Usage
31749
-
31750
- Use schema helpers for common string and number constraints instead of hand-written predicates.
31850
+ Use the built-in constraints instead of hand-written predicates.
31751
31851
 
31752
31852
  ```ts
31753
31853
  import { s } from '@vielzeug/spell';
@@ -31755,13 +31855,14 @@ import { s } from '@vielzeug/spell';
31755
31855
  const Password = s.string().min(12).regex(/[A-Z]/).regex(/[0-9]/);
31756
31856
  const Price = s.number().nonNegative().multipleOf(0.01);
31757
31857
  const LaunchWindow = s.date().min(new Date('2025-01-01T00:00:00.000Z'));
31858
+ const Website = s.string().url({ protocols: ['https'] });
31758
31859
  ```
31759
31860
 
31760
- Spell strips stateful `/g` and `/y` flags from `regex()` patterns before validation. Repeated parses stay deterministic even when the original regular expression is reused.
31861
+ Format failures use the `invalid_format` code with `params.format` set to the method name. `regex()` drops the stateful `g` and `y` flags, so repeated parses agree even when you reuse a global regular expression.
31761
31862
 
31762
- ## Coercion and Transforms
31863
+ ## Coercion and Pipelines
31763
31864
 
31764
- Use coercion when input arrives as strings, query parameters, or form values.
31865
+ Use `s.coerce.*` when input arrives as strings, such as query parameters or form values.
31765
31866
 
31766
31867
  ```ts
31767
31868
  import { s } from '@vielzeug/spell';
@@ -31773,30 +31874,25 @@ const Query = s.object({
31773
31874
  search: s.coerce.string().trim().min(1).optional(),
31774
31875
  });
31775
31876
 
31776
- const parsed = Query.parse({
31777
- draft: 'true',
31778
- limit: '50',
31779
- publishedAt: '2025-04-01T12:00:00.000Z',
31780
- search: ' vielzeug ',
31781
- });
31877
+ Query.parse({ draft: 'true', limit: '50', publishedAt: '2025-04-01T12:00:00.000Z', search: ' vielzeug ' });
31782
31878
  ```
31783
31879
 
31784
- Use `transform()` or `pipe()` after validation when downstream code needs a different output shape.
31880
+ Use `transform()` or `pipe()` when downstream code needs a different output.
31785
31881
 
31786
31882
  ```ts
31787
31883
  import { s } from '@vielzeug/spell';
31788
31884
 
31789
- const TrimmedTags = s.array(s.string().trim().min(1)).transform((tags) => tags.map((tag) => tag.toLowerCase()));
31790
- const Slug = s.string().trim().min(1).pipe(s.string().slug());
31885
+ const LowercaseTags = s.array(s.string().trim().min(1)).transform((tags) => tags.map((tag) => tag.toLowerCase()));
31886
+ const Slug = s.string().trim().pipe(s.string().slug());
31791
31887
  ```
31792
31888
 
31793
- ## Introspection, Round-Trips, and JSON Schema
31889
+ ## Definitions and JSON Schema
31794
31890
 
31795
- Use declarative definitions when schemas need to cross process boundaries or feed tooling.
31891
+ Use declarative definitions when schemas feed external tooling.
31796
31892
 
31797
31893
  ```ts
31798
31894
  import { s } from '@vielzeug/spell';
31799
- import { fromDefinition } from '@vielzeug/spell/json';
31895
+ import { toJsonSchema } from '@vielzeug/spell/json';
31800
31896
 
31801
31897
  const Product = s
31802
31898
  .object({
@@ -31804,93 +31900,69 @@ const Product = s
31804
31900
  name: s.string().min(1),
31805
31901
  price: s.number().positive().multipleOf(0.01),
31806
31902
  })
31807
- .label('Product');
31903
+ .describe('Product');
31808
31904
 
31809
- const definition = Product.definition();
31810
- const jsonSchema = fromDefinition(definition);
31811
-
31812
- Product.parse({ id: '550e8400-e29b-41d4-a716-446655440000', name: 'Keyboard', price: 129.99 });
31813
- console.log(jsonSchema.title);
31905
+ const jsonSchema = toJsonSchema(Product.definition());
31906
+ console.log(jsonSchema.description); // 'Product'
31814
31907
  ```
31815
31908
 
31816
- Definitions are frozen serializable snapshots of declarative schema structure. Use `definition()` and `fromDefinition()` for external tooling. Schemas with runtime checks, transforms, defaults, catches, or preprocessors intentionally have no definition.
31909
+ Definitions are frozen, serializable data. Schemas with checks, transforms, preprocessors (including `s.coerce.*` and `trim()`), defaults, or catches have no definition, and `definition()` throws `SpellDefinitionError`.
31817
31910
 
31818
31911
  ## Messages
31819
31912
 
31820
- Spell has no mutable process-wide configuration. Build one parse context per request, locale, or form, then pass it explicitly.
31913
+ Spell has no process-wide configuration. Build one parse context per request, locale, or form, and pass it explicitly.
31821
31914
 
31822
31915
  ```ts
31823
31916
  import { createParseContext, s } from '@vielzeug/spell';
31824
31917
 
31825
31918
  const User = s.object({ email: s.string().email() });
31826
- const german = createParseContext({
31827
- object: { invalidKeys: () => 'Keine unbekannten Felder erlaubt' },
31828
- });
31919
+ const german = createParseContext({ object: { invalidKeys: () => 'Keine unbekannten Felder erlaubt' } });
31829
31920
 
31830
31921
  User.safeParse({ email: 'ada@example.com', extra: true }, german);
31831
31922
  ```
31832
31923
 
31833
- Internal development warnings always use `console.warn` in development builds. Route application diagnostics in application code instead of mutating library-wide logger state.
31924
+ Development builds warn through `console.warn` when a message override uses an unsafe key such as `__proto__`.
31834
31925
 
31835
31926
  ## Working with Validation Errors
31836
31927
 
31837
- Use `SpellValidationError` helpers when you need UI-ready error structures.
31928
+ Use `SpellValidationError` helpers to build UI-ready error structures.
31838
31929
 
31839
31930
  ```ts
31840
- import { s, SpellValidationError } from '@vielzeug/spell';
31841
-
31842
- const User = s.object({
31843
- email: s.string().email(),
31844
- profile: s.object({
31845
- name: s.string().min(2),
31846
- }),
31847
- });
31931
+ import { joinIssuePath, s } from '@vielzeug/spell';
31848
31932
 
31933
+ const User = s.object({ email: s.string().email(), profile: s.object({ name: s.string().min(2) }) });
31849
31934
  const result = User.safeParse({ email: 'nope', profile: { name: '' } });
31850
31935
 
31851
- if (!result.success && result.error instanceof SpellValidationError) {
31852
- const profileErrors = result.error.messagesAt('profile', 'name');
31853
- console.log(profileErrors);
31854
- }
31855
- ```
31856
-
31857
- Key inline errors by dot-path with `joinIssuePath()`, which also unwraps Standard Schema `{ key }` segments:
31858
-
31859
- ```ts
31860
- import { joinIssuePath } from '@vielzeug/spell';
31936
+ if (!result.success) {
31937
+ console.log(result.error.messagesAt('profile', 'name'));
31861
31938
 
31862
- for (const issue of result.error.issues) {
31863
- console.log(joinIssuePath(issue.path), issue.message); // 'profile.name: ...'
31939
+ for (const issue of result.error.issues) console.log(joinIssuePath(issue.path), issue.message);
31864
31940
  }
31865
31941
  ```
31866
31942
 
31867
- Union failures produce one stable `invalid_union` issue. Use `s.discriminatedUnion()` when a discriminator can identify the intended object branch and provide field-specific errors.
31943
+ Union failures produce one `invalid_union` issue. Use `s.discriminatedUnion()` when a tag field identifies the intended branch, so errors point at that branch's fields.
31868
31944
 
31869
- ## Validating synchronously in React
31945
+ ## Typing Schema Parameters
31870
31946
 
31871
- Adapters that validate inside a render or `validate` callback need the sync parse surface. `AnySchema` does not expose `safeParse`; type the adapter parameter against `SyncParsable` instead:
31947
+ Type a function that accepts any schema with `AnySchema`, or with `Schema` when it needs the parsed type.
31872
31948
 
31873
31949
  ```ts
31874
- import { type SyncParsable } from '@vielzeug/spell';
31950
+ import { type AnySchema, type ParseResult, type Schema, s } from '@vielzeug/spell';
31875
31951
 
31876
- function spellValidator(schema: SyncParsable) {
31877
- return (values: unknown) => {
31878
- const result = schema.safeParse(values);
31879
- if (result.success) return undefined;
31952
+ function isValid(schema: AnySchema, value: unknown): boolean {
31953
+ return schema.safeParse(value).success;
31954
+ }
31880
31955
 
31881
- return result.error.issues.map((issue) => ({
31882
- message: issue.message,
31883
- path: issue.path,
31884
- }));
31885
- };
31956
+ function parseWith(schema: Schema, value: unknown): ParseResult {
31957
+ return schema.safeParse(value);
31886
31958
  }
31887
31959
 
31888
- spellValidator(s.object({ email: s.string() })); // no shim or cast
31960
+ parseWith(s.object({ email: s.string() }), { email: 'ada@example.com' });
31889
31961
  ```
31890
31962
 
31891
31963
  ## Framework Integration
31892
31964
 
31893
- Spell works anywhere you can call a function before state enters your app.
31965
+ Spell works anywhere you can call a function before data enters your app.
31894
31966
 
31895
31967
  ```tsx [React]
31896
31968
  import { s } from '@vielzeug/spell';
@@ -31918,36 +31990,39 @@ import { computed, ref } from 'vue';
31918
31990
  import { s } from '@vielzeug/spell';
31919
31991
 
31920
31992
  const Settings = s.object({
31921
- locale: s.string().min(2),
31922
31993
  compact: s.coerce.boolean().default(false),
31994
+ locale: s.string().min(2),
31923
31995
  });
31924
31996
 
31925
- const raw = ref({ locale: 'en', compact: 'true' });
31997
+ const raw = ref({ compact: 'true', locale: 'en' });
31926
31998
  const settings = computed(() => Settings.parse(raw.value));
31927
31999
  ```
31928
32000
 
31929
- Use `safeParse()` at event boundaries and `parse()` inside trusted data flows.
32001
+ ```svelte [Svelte]
32002
+
32003
+ import { s } from '@vielzeug/spell';
32004
+
32005
+ const Email = s.string().email();
32006
+ let value = '';
32007
+ $: error = Email.safeParse(value).success ? '' : 'Enter a valid email';
32008
+
32009
+ {#if error}{error}{/if}
32010
+ ```
31930
32011
 
31931
32012
  ## Working with Other Vielzeug Libraries
31932
32013
 
31933
- Use Spell as the validation layer and let other packages focus on transport, forms, or storage.
32014
+ Spell schemas implement Standard Schema, so packages that accept Standard Schema validators use them directly.
31934
32015
 
31935
32016
  ```ts
32017
+ import { createCourier } from '@vielzeug/courier';
31936
32018
  import { createForm } from '@vielzeug/forge';
31937
32019
  import { schemaValidator } from '@vielzeug/forge/schema';
31938
- import { createCourier } from '@vielzeug/courier';
31939
32020
  import { s } from '@vielzeug/spell';
31940
32021
 
31941
- const Profile = s.object({
31942
- displayName: s.string().min(2),
31943
- newsletter: s.boolean(),
31944
- });
32022
+ const Profile = s.object({ displayName: s.string().min(2), newsletter: s.boolean() });
31945
32023
 
31946
32024
  const form = createForm({
31947
- initialValues: {
31948
- displayName: '',
31949
- newsletter: false,
31950
- },
32025
+ initialValues: { displayName: '', newsletter: false },
31951
32026
  validate: schemaValidator(Profile),
31952
32027
  });
31953
32028
 
@@ -31955,18 +32030,16 @@ const courier = createCourier({ baseUrl: '/api' });
31955
32030
  const profile = Profile.parse(await courier.get('/profile'));
31956
32031
  ```
31957
32032
 
31958
- Use Spell definitions with `@vielzeug/codex` or other tooling when you need generated docs or external schema consumers.
31959
-
31960
32033
  ## Best Practices
31961
32034
 
31962
32035
  - Keep schemas close to the boundary where unknown data enters your app.
31963
- - Use `s` consistently for construction; use explicit `/json` and `/predicates` subpaths for tooling.
31964
- - Use `.default(() => value)` for mutable defaults such as arrays, objects, `Map`, and `Set`.
31965
- - Call `.required()` when you want to remove `undefined` but keep `null` semantics intact.
31966
- - Use `check()` with a `ctx` argument when you need `ctx.addIssue()`; return a message for simple predicate failures.
31967
- - Use `checkAsync()` and `parseAsync()` for every asynchronous domain rule.
31968
- - Build a parse context per request or test; never rely on mutable process-wide configuration.
31969
- - Use `definition()` with `fromDefinition()` from `@vielzeug/spell/json` for external tooling.
32036
+ - Chain constraints in the order they should apply; put `trim()` before length checks.
32037
+ - Derive object shapes with `extend()`, `pick()`, `omit()`, or `partial()` before adding checks.
32038
+ - Chain type-specific methods before `optional()`, `nullable()`, `transform()`, or `required()`.
32039
+ - Use `check()` with `ctx.addIssue()` for multi-field rules; return a message for single predicates.
32040
+ - Use `checkAsync()` with `parseAsync()` for every asynchronous domain rule.
32041
+ - Build a parse context per request, locale, or test instead of relying on global state.
32042
+ - Use `definition()` with `toJsonSchema()` for external tooling, and keep runtime-only schemas separate.
31970
32043
 
31971
32044
  ### Examples
31972
32045
 
@@ -31976,7 +32049,7 @@ Use Spell definitions with `@vielzeug/codex` or other tooling when you need gene
31976
32049
  - [Form-Safe Parsing](./examples/forms.md)
31977
32050
  - [Async Business Rules](./examples/async.md)
31978
32051
  - [Schema Introspection and Round-Trips](./examples/introspection.md)
31979
- - [Unions, Intersections, and Variants](./examples/unions.md)
32052
+ - [Unions, Intersections, and Discriminated Unions](./examples/unions.md)
31980
32053
 
31981
32054
  ### REPL Examples
31982
32055
 
@@ -31991,8 +32064,8 @@ Use Spell definitions with `@vielzeug/codex` or other tooling when you need gene
31991
32064
  - Request-local messages (id: `messages-override`)
31992
32065
  - Variant Responses (id: `nested-objects`)
31993
32066
  - Number Validation (id: `number-validation`)
32067
+ - Object Composition (id: `object-composition`)
31994
32068
  - Object Defaults (id: `object-defaults`)
31995
- - Object Merge & Aliases (id: `object-merge`)
31996
32069
  - Optional and Nullable Fields (id: `optional-nullable`)
31997
32070
  - Custom Validation (id: `refinements`)
31998
32071
  - String Validation (id: `string-validation`)
@@ -33807,7 +33880,7 @@ import { s } from '@vielzeug/spell';
33807
33880
  import { table } from '@vielzeug/vault';
33808
33881
  import { createLocalStorage } from '@vielzeug/vault/local-storage';
33809
33882
 
33810
- const PreferenceSchema = s.object({ id: s.string(), theme: s.union('dark', 'light') });
33883
+ const PreferenceSchema = s.object({ id: s.string(), theme: s.enum(['dark', 'light']) });
33811
33884
  const store = createLocalStorage({
33812
33885
  name: 'app-v2',
33813
33886
  schema: { preferences: table('id') },
@@ -34332,7 +34405,7 @@ interface Preference {
34332
34405
  theme: 'dark' | 'light';
34333
34406
  }
34334
34407
 
34335
- const PreferenceSchema = s.object({ id: s.string(), theme: s.union('dark', 'light') });
34408
+ const PreferenceSchema = s.object({ id: s.string(), theme: s.enum(['dark', 'light']) });
34336
34409
  const store = createLocalStorage({
34337
34410
  name: 'app-v2',
34338
34411
  schema: { preferences: table('id') },
@@ -34615,7 +34688,7 @@ interface Job {
34615
34688
  status: 'queued' | 'running' | 'done';
34616
34689
  }
34617
34690
 
34618
- const JobSchema = s.object({ id: s.string(), status: s.union('queued', 'running', 'done') });
34691
+ const JobSchema = s.object({ id: s.string(), status: s.enum(['queued', 'running', 'done']) });
34619
34692
  const database = new DatabaseSync(':memory:');
34620
34693
  const store = createSQLite({
34621
34694
  database,