@vielzeug/codex 26.11.12 → 26.11.14

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.
Files changed (69) hide show
  1. package/data/catalog.json +188 -62
  2. package/data/llms-full.txt +1711 -921
  3. package/data/llms.txt +4 -1
  4. package/data/manifest.json +2 -6
  5. package/data/packages/archive.json +1 -1
  6. package/data/packages/arsenal.json +4 -2
  7. package/data/packages/clockwork.json +3 -3
  8. package/data/packages/codex.json +20 -11
  9. package/data/packages/coins.json +22 -24
  10. package/data/packages/courier.json +12 -11
  11. package/data/packages/flux.json +2 -2
  12. package/data/packages/forge.json +3 -3
  13. package/data/packages/herald.json +2 -2
  14. package/data/packages/ledger.json +1 -1
  15. package/data/packages/lingua.json +37 -42
  16. package/data/packages/patchwork.json +50 -0
  17. package/data/packages/postmaster.json +8 -8
  18. package/data/packages/refine.json +2 -2
  19. package/data/packages/scribe.json +57 -0
  20. package/data/packages/sentinel.json +1 -1
  21. package/data/packages/sourcerer.json +2 -2
  22. package/data/packages/tabula.json +39 -0
  23. package/data/packages/tavern.json +20 -18
  24. package/data/packages/tempo.json +48 -63
  25. package/data/packages/vault.json +29 -31
  26. package/data/packages/wayfinder.json +12 -7
  27. package/data/refine.json +76 -0
  28. package/dist/catalog.d.ts +13 -1
  29. package/dist/catalog.js +80 -53
  30. package/dist/catalog.js.map +1 -1
  31. package/dist/cli.js +5 -5
  32. package/dist/cli.js.map +1 -1
  33. package/dist/consumer.d.ts +17 -0
  34. package/dist/consumer.js +114 -0
  35. package/dist/consumer.js.map +1 -0
  36. package/dist/errors.js +0 -1
  37. package/dist/errors.js.map +1 -1
  38. package/dist/http.d.ts +0 -1
  39. package/dist/http.js +0 -5
  40. package/dist/http.js.map +1 -1
  41. package/dist/index.d.ts +5 -5
  42. package/dist/index.js +3 -3
  43. package/dist/index.js.map +1 -1
  44. package/dist/port.js +2 -2
  45. package/dist/port.js.map +1 -1
  46. package/dist/server.d.ts +5 -3
  47. package/dist/server.js +10 -6
  48. package/dist/server.js.map +1 -1
  49. package/dist/snapshot.d.ts +11 -8
  50. package/dist/snapshot.js +24 -128
  51. package/dist/snapshot.js.map +1 -1
  52. package/dist/tools/index.d.ts +0 -2
  53. package/dist/tools/index.js +0 -2
  54. package/dist/tools/index.js.map +1 -1
  55. package/dist/tools/packages.js +50 -0
  56. package/dist/tools/packages.js.map +1 -1
  57. package/dist/tools/refine.d.ts +2 -2
  58. package/dist/tools/refine.js.map +1 -1
  59. package/dist/types.d.ts +2 -30
  60. package/dist/types.js +1 -1
  61. package/package.json +2 -13
  62. package/skills/vielzeug/SKILL.md +4 -1
  63. package/data/search.json +0 -1688
  64. package/dist/refine-catalog.d.ts +0 -15
  65. package/dist/refine-catalog.js +0 -27
  66. package/dist/refine-catalog.js.map +0 -1
  67. package/dist/refine.d.ts +0 -7
  68. package/dist/refine.js +0 -9
  69. package/dist/refine.js.map +0 -1
@@ -2,8 +2,8 @@
2
2
  "apiSource": "export { toAsyncIterable } from './async.js';\nexport type { Channel, ChannelOptions } from './channel.js';\nexport { createChannel } from './channel.js';\nexport { fromStore, fromSubscribe, stream } from './core.js';\nexport { FluxCapacityError, FluxEmptyError, FluxError, FluxTimeoutError } from './errors.js';\nexport { combineLatest, concat, merge } from './operators/combination.js';\nexport type { TimerOptions } from './operators/creation.js';\nexport { from, fromEvent, interval, of, timer } from './operators/creation.js';\nexport { debounce, take, takeUntil, timeout } from './operators/filtering.js';\nexport type { FlattenOptions } from './operators/transformation.js';\nexport { concatMap, filter, map, mergeMap, scan, switchMap } from './operators/transformation.js';\nexport type { RetryOptions, ToArrayOptions, ValueOptions } from './operators/utility.js';\nexport { first, last, retry, toArray } from './operators/utility.js';\nexport { pipe } from './pipe.js';\nexport type {\n AsyncIterableOptions,\n Observer,\n Operator,\n OverflowPolicy,\n Producer,\n Sink,\n Stream,\n SubscribeOptions,\n Subscription,\n Teardown,\n} from './types.js';\n",
3
3
  "docs": {
4
4
  "index": "---\ntitle: 'Flux: Explicit push streams for TypeScript'\ndescription: Reusable push streams with subscription-owned cancellation, bounded buffering, channels, and dependency-free structural bridges.\npackage: flux\ncategory: reactive\nkeywords: [streams, reactive, operators, cancellation, buffering, channels]\nrelated: [ripple, herald, pulse, sourcerer, courier]\nexports:\n [\n stream,\n fromStore,\n fromSubscribe,\n pipe,\n of,\n from,\n fromEvent,\n interval,\n timer,\n map,\n filter,\n scan,\n switchMap,\n mergeMap,\n concatMap,\n take,\n takeUntil,\n debounce,\n timeout,\n merge,\n concat,\n combineLatest,\n retry,\n toArray,\n first,\n last,\n toAsyncIterable,\n ]\nenvironments: [browser, node, ssr, deno]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"flux\" />\n\n## Why Flux?\n\nUse Flux when an API pushes many values over time and consumers need independent cancellation. Streams describe reusable work; subscriptions own cleanup. Explicit queue capacity keeps async iteration from silently growing memory.\n\n```ts\n// Before\nconst controller = new AbortController();\nconst render = (value: string) => console.log(value);\nconst handler = (event: Event) => render((event.target as HTMLInputElement).value);\ninput.addEventListener('input', handler);\nsetTimeout(() => controller.abort(), 5_000);\n\n// After\nimport { fromEvent, map, pipe, takeUntil } from '@vielzeug/flux';\n\nconst updates = pipe(\n fromEvent<InputEvent>(input, 'input'),\n map((event) => (event.target as HTMLInputElement).value),\n takeUntil(controller.signal),\n);\n\nupdates.subscribe({ error: console.error, next: render });\n```\n\n| Feature | Flux | RxJS | TC39 Observable |\n| ------------------------------- | -------------------------------------------- | -------------------------------------------- | ----------------------------------------------------- |\n| Bundle size | <PackageInfo package=\"flux\" type=\"size\" /> | Varies by imported operators | Native proposal / polyfill |\n| Runtime dependencies | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> |\n| Subscription-owned cancellation | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"triangle-alert\" size=\"16\"></ore-icon> |\n| Explicit async queue policy | <ore-icon name=\"check\" size=\"16\"></ore-icon> | Operator-dependent | No standard policy |\n| Vielzeug adapters | Ripple, Courier, Herald, Pulse | Manual adapters | Manual adapters |\n\n<div class=\"decision-callout\">\n\n**Use Flux when** you need a small TypeScript stream primitive, explicit cancellation, and first-party Vielzeug adapters.\n\n**Consider RxJS when** you need its larger operator catalog or third-party Observable integrations.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/flux\n```\n\n```sh [npm]\nnpm install @vielzeug/flux\n```\n\n```sh [yarn]\nyarn add @vielzeug/flux\n```\n\n:::\n\n## Quick Start\n\n```ts\nimport { toArray, interval, map, pipe, take } from '@vielzeug/flux';\n\nconst firstThree = pipe(\n interval(100),\n map((value) => value * 2),\n take(3),\n);\n\ntry {\n console.log(await toArray(firstThree, { maxItems: 3 })); // [0, 2, 4]\n} catch (reason) {\n console.error('Stream failed', reason);\n}\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- `stream()`: define cold reusable work with one teardown function\n- `pipe()`: compose any number of typed operators\n- `Subscription`: own cancellation through `unsubscribe()` or `AbortSignal`\n- `createChannel()`: mutable multicast state with bounded replay\n- `toAsyncIterable()`: explicit capacity and overflow policy for pull consumers\n- `retry()`: retry failures with optional backoff\n- `fromStore()`: bridge snapshot-based state such as Ripple signals or Sourcerer queries\n- `fromSubscribe()`: bridge callback-delivered Herald or Pulse events\n\n</div>\n\n## Documentation\n\n<div class=\"doc-links\">\n\n- [Usage Guide](./usage.md)\n- [API Reference](./api.md)\n- [Examples](./examples.md)\n- [Migration Guide](./migration.md)\n\n</div>\n\n## See Also\n\n<div class=\"see-also\">\n\n- [Ripple](/ripple/): bridge snapshot state with `fromStore()`.\n- [Courier](/courier/): compose transport promises with `from()` or custom producers.\n- [Herald](/herald/): bridge explicit subscriptions with `stream()`.\n- [Pulse](/pulse/): bridge events with `fromSubscribe()` and presence snapshots with `fromStore()`.\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
5
- "api": "---\ntitle: 'Flux: API Reference'\ndescription: Complete reference for @vielzeug/flux streams, operators, channels, and structural bridges.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| -------------------------------------------- | -------------------------------- | -------------- | ------------------------------------------------------------------------------ |\n| `stream()` | Create cold stream | Lazy | Return one teardown function |\n| `pipe()` | Compose operators | Lazy | Source is first argument |\n| `of()` / `from()` | Convert known values | Sync / mixed | `from()` promise cannot be aborted |\n| `fromEvent()` | Adapt event target | Async | Unsubscribe removes listener |\n| `interval()` / `timer()` | Create timed values | Async | Use `take()` or unsubscribe for intervals |\n| `map()` / `filter()` / `scan()` | Transform values | Sync | Callback throws terminate stream |\n| `switchMap()` / `mergeMap()` / `concatMap()` | Flatten streams | Mixed | `mergeMap()` concurrency and queue are bounded; `concatMap()` queue is bounded |\n| `take()` / `takeUntil()` | Stop values | Mixed | Notifier emission completes output |\n| `debounce()` / `timeout()` / `retry()` | Control time and failures | Async | `timeout()` measures inactivity |\n| `merge()` / `concat()` / `combineLatest()` | Combine streams | Mixed | `combineLatest()` waits for every source |\n| `toArray()` / `first()` / `last()` | Consume finite values | Async | Bound `toArray()` with `maxItems` |\n| `toAsyncIterable()` | Use `for await` | Async | Capacity and overflow required |\n| `createChannel()` | Imperative multicast boundary | Sync | Dispose to complete subscribers |\n| `fromStore()` | Bridge snapshot-based state | Lazy | Snapshot and subscribe are both required |\n| `fromSubscribe()` | Bridge callback-delivered values | Lazy | Registration must return teardown |\n\n## Package Entry Point\n\n| Import | Purpose |\n| ---------------------- | ------------------------------------------------------------------------ |\n| `@vielzeug/flux` | Core streams, operators, consumers, errors, types, and `createChannel()` |\n| `@vielzeug/flux/async` | `toAsyncIterable()` only |\n\n## Core\n\n### `stream()`\n\n```ts\nstream<T>(producer: Producer<T>): Stream<T>\n```\n\nCreates cold reusable work. Producer runs once for every subscription.\n\n| Parameter | Type | Description |\n| ---------- | ------------- | ------------------------------------------------ |\n| `producer` | `Producer<T>` | Emits through sink and returns optional teardown |\n\n**Returns:** `Stream<T>`.\n\n```ts\nimport { stream } from '@vielzeug/flux';\n\nconst ticks = stream<number>((sink) => {\n const id = setInterval(() => sink.next(Date.now()), 1_000);\n return () => clearInterval(id);\n});\n```\n\n---\n\n### `pipe()`\n\n```ts\npipe<Input, Operators>(source: Stream<Input>, ...operators: Operators): Stream<Output>\n```\n\nApplies operators left to right while inferring output value type.\n\n| Parameter | Type | Description |\n| ----------- | --------------- | -------------------------- |\n| `source` | `Stream<Input>` | Source stream |\n| `operators` | `Operator[]` | Operators applied in order |\n\n**Returns:** transformed `Stream<Output>`.\n\n```ts\nimport { map, of, pipe } from '@vielzeug/flux';\n\nconst labels = pipe(\n of(1, 2),\n map((value) => `#${value}`),\n);\n```\n\n## Creation\n\n### `of()`\n\n```ts\nof<T>(...values: T[]): Stream<T>\n```\n\nEmits every value synchronously, then completes.\n\n```ts\nimport { of } from '@vielzeug/flux';\n\nof(1, 2, 3).subscribe(console.log);\n```\n\n---\n\n### `from()`\n\n```ts\nfrom<T>(source: Iterable<T> | AsyncIterable<T> | Promise<T>): Stream<T>\n```\n\nConverts iterable, async iterable, or promise into a stream. Cancellation stops iterable consumption and calls `return()` when available.\n\n```ts\nimport { from } from '@vielzeug/flux';\n\nfrom(Promise.resolve('ready')).subscribe({ error: console.error, next: console.log });\n```\n\n---\n\n### `fromEvent()`\n\n```ts\nfromEvent<T = Event>(\n target: {\n addEventListener(type: string, listener: (event: T) => void): void;\n removeEventListener(type: string, listener: (event: T) => void): void;\n },\n type: string,\n): Stream<T>\n```\n\nEmits target events until subscription ends.\n\n```ts\nimport { fromEvent } from '@vielzeug/flux';\n\nfromEvent<MouseEvent>(document, 'click').subscribe(console.log);\n```\n\n---\n\n### `interval()`\n\n```ts\ninterval(every: number): Stream<number>\n```\n\nEmits incrementing values starting at zero.\n\n| Parameter | Type | Description |\n| --------- | -------- | ----------------------------------------------------------- |\n| `every` | `number` | Interval duration from 0 through 2,147,483,647 milliseconds |\n\n---\n\n### `timer()`\n\n```ts\ntimer(options: TimerOptions): Stream<number>\n```\n\nEmits zero after `delay`; optionally continues at `interval`.\n\n| Option | Type | Description |\n| ---------- | -------- | ------------------------------------------------------------------ |\n| `delay` | `number` | Initial delay from 0 through 2,147,483,647 milliseconds |\n| `interval` | `number` | Optional repeat duration from 0 through 2,147,483,647 milliseconds |\n\n## Transformation Operators\n\n### `map()`\n\n```ts\nmap<A, B>(project: (value: A) => B): Operator<A, B>\n```\n\nMaps every value. A thrown callback error terminates output.\n\n---\n\n### `filter()`\n\n```ts\nfilter<T>(predicate: (value: T) => boolean): Operator<T, T>\n```\n\nForwards values matching predicate.\n\n---\n\n### `scan()`\n\n```ts\nscan<T, A>(reducer: (state: A, value: T) => A, initial: A): Operator<T, A>\n```\n\nEmits accumulated state after every source value.\n\n---\n\n### `switchMap()`\n\n```ts\nswitchMap<A, B>(project: (value: A) => Stream<B>): Operator<A, B>\n```\n\nCancels previous inner stream when source emits.\n\n---\n\n### `mergeMap()`\n\n```ts\nmergeMap<A, B>(project: (value: A) => Stream<B>, options: FlattenOptions): Operator<A, B>\n```\n\nRuns inner streams with bounded concurrency and queue capacity. Exceeding capacity errors output with `FluxCapacityError`.\n\n| Option | Type | Description |\n| ------------- | -------------------- | ----------------------------------------------------------------------------- |\n| `concurrency` | `number \\| Infinity` | Maximum concurrently active inner subscriptions |\n| `capacity` | `number` | Positive maximum queued source values (required when `concurrency` is finite) |\n\n---\n\n### `concatMap()`\n\n```ts\nconcatMap<A, B>(project: (value: A) => Stream<B>, options: { capacity: number }): Operator<A, B>\n```\n\nRuns inner streams in order (`concurrency: 1`). Exceeding capacity errors output with `FluxCapacityError`.\n\n| Option | Type | Description |\n| ---------- | -------- | ------------------------------------- |\n| `capacity` | `number` | Positive maximum queued source values |\n\n## Control Operators\n\n### `take()`\n\n```ts\ntake<T>(count: number): Operator<T, T>\n```\n\nForwards `count` values, cancels upstream, then completes. Count must be non-negative integer.\n\n---\n\n### `takeUntil()`\n\n```ts\ntakeUntil<T>(notifier: AbortSignal | Stream<unknown>): Operator<T, T>\n```\n\nCompletes when notifier aborts or emits.\n\n---\n\n### `debounce()`\n\n```ts\ndebounce<T>(duration: number): Operator<T, T>\n```\n\nEmits latest value after configured silence. Pending value flushes on source completion.\n\n| Parameter | Type | Description |\n| ---------- | -------- | ---------------------------------------------------------- |\n| `duration` | `number` | Silence duration from 0 through 2,147,483,647 milliseconds |\n\n---\n\n### `timeout()`\n\n```ts\ntimeout<T>(duration: number): Operator<T, T>\n```\n\nErrors with `FluxTimeoutError` when source is silent too long.\n\n| Parameter | Type | Description |\n| ---------- | -------- | ------------------------------------------------------------- |\n| `duration` | `number` | Inactivity duration from 0 through 2,147,483,647 milliseconds |\n\n---\n\n### `retry()`\n\n```ts\nretry<T>(options: RetryOptions): Operator<T, T>\n```\n\nResubscribes after source errors until attempts are exhausted.\n\n| Option | Type | Description |\n| ------- | --------------------------------------- | --------------------------------------------------------------------- |\n| `times` | `number` | Non-negative retry count |\n| `delay` | `number \\| (attempt: number) => number` | Optional delay/backoff returning 0 through 2,147,483,647 milliseconds |\n\n## Combination\n\n### `merge()`\n\n```ts\nmerge<T>(...sources: Stream<T>[]): Stream<T>\n```\n\nForwards values from all sources and completes after every source completes.\n\n---\n\n### `concat()`\n\n```ts\nconcat<T>(...sources: Stream<T>[]): Stream<T>\n```\n\nSubscribes to each source only after previous source completes.\n\n---\n\n### `combineLatest()`\n\n```ts\ncombineLatest<T extends readonly Stream<unknown>[]>(...sources: T): Stream<{ [K in keyof T]: T[K] extends Stream<infer V> ? V : never }>\n```\n\nEmits latest tuple after every source emits once. Completes without emission when a source completes before first value.\n\n## Value Consumers\n\n### `toArray()`\n\n```ts\ntoArray<T>(source: Stream<T>, options: ToArrayOptions): Promise<T[]>\n```\n\nCollects finite output. Rejects on source error, the supplied signal's abort reason, or `maxItems` overflow.\n\n| Option | Type | Description |\n| ---------- | ------------- | ------------------------------------- |\n| `maxItems` | `number` | Non-negative maximum toArrayed values |\n| `signal` | `AbortSignal` | Optional cancellation signal |\n\n---\n\n### `first()`\n\n```ts\nfirst<T>(source: Stream<T>, options?: ValueOptions<T>): Promise<T>\n```\n\nResolves first value and cancels source. Rejects on source error, the supplied signal's abort reason, or empty completion (`FluxEmptyError`); pass `defaultValue` to resolve instead.\n\n---\n\n### `last()`\n\n```ts\nlast<T>(source: Stream<T>, options?: ValueOptions<T>): Promise<T>\n```\n\nResolves last value on completion. Rejects on source error, the supplied signal's abort reason, or empty completion (`FluxEmptyError`); pass `defaultValue` to resolve instead.\n\n## Async Conversion\n\n### `toAsyncIterable()`\n\n```ts\ntoAsyncIterable<T>(source: Stream<T>, options: AsyncIterableOptions): AsyncIterable<T>\n```\n\nConverts a push stream to an async iterable with a bounded queue. External cancellation rejects pending iteration with `signal.reason`; explicit iterator `return()` completes normally. Overflow `\"error\"` rejects with `FluxCapacityError`; unsupported policies throw `RangeError` before subscription.\n\n| Option | Type | Description |\n| ---------- | ---------------- | ---------------------------------------- |\n| `capacity` | `number` | Positive queue capacity |\n| `overflow` | `OverflowPolicy` | `error`, `drop-oldest`, or `drop-newest` |\n| `signal` | `AbortSignal` | Optional cancellation signal |\n\n## Channels\n\n### `createChannel()`\n\n```ts\ncreateChannel<T>(options?: ChannelOptions<T>): Channel<T>\n```\n\nCreates an imperative multicast boundary. Disposal completes subscribers and releases replay and pending values.\n\n> **`initial` + `replay` interaction:** When `initial` is set and `replay` is omitted, `replay` defaults to `1` so the initial value is retained. Setting `replay: 0` with `initial` throws `RangeError`: the initial value would be immediately dropped.\n\n| Option | Type | Description |\n| --------- | -------- | --------------------------------- |\n| `initial` | `T` | Optional initial replay value |\n| `replay` | `number` | Non-negative retained value count |\n\n## Structural adapters\n\n### `fromStore()`\n\n```ts\nfromStore<T>(source: {\n getSnapshot(): T;\n subscribe(listener: () => void): () => void;\n}): Stream<T>\n```\n\nBridges snapshot-based state without package-specific dependencies. It emits the current snapshot, subscribes, rechecks for a subscription-time change, and reads the latest snapshot after each notification. Snapshot failure terminates without subscribing.\n\n### `fromSubscribe()`\n\n```ts\nfromSubscribe<T>(subscribe: (listener: (value: T) => void) => () => void): Stream<T>\n```\n\nBridges callback-delivered event values. Registration runs once per Flux subscription and its teardown runs when that subscription closes.\n\n## Types\n\n```ts\ntype Teardown = () => void;\n\ntype Subscription = {\n [Symbol.dispose](): void;\n readonly closed: boolean;\n unsubscribe(): void;\n};\n\ntype Observer<T> = {\n complete?: () => void;\n error?: (reason: unknown) => void;\n next: (value: T) => void;\n};\n\ntype SubscribeOptions = { signal?: AbortSignal };\n\ntype Sink<T> = {\n complete(): void;\n error(reason: unknown): void;\n next(value: T): void;\n};\n\ntype Producer<T> = (sink: Sink<T>, signal: AbortSignal) => Teardown | undefined;\ntype Operator<A = unknown, B = unknown> = (source: Stream<A>) => Stream<B>;\n\ninterface Stream<T> {\n subscribe(observer: Observer<T> | ((value: T) => void), options?: SubscribeOptions): Subscription;\n}\n\ntype OverflowPolicy = 'drop-newest' | 'drop-oldest' | 'error';\ntype AsyncIterableOptions = { capacity: number; overflow: OverflowPolicy; signal?: AbortSignal };\ntype TimerOptions = { delay: number; interval?: number };\ntype FlattenOptions = { concurrency: number; capacity: number };\ntype RetryOptions = { times: number; delay?: number | ((attempt: number) => number) };\ntype ToArrayOptions = { maxItems: number; signal?: AbortSignal };\ntype ValueOptions<T> = { signal?: AbortSignal; defaultValue?: T };\ntype ChannelOptions<T> = { initial?: T; replay?: number };\ntype Channel<T> = {\n [Symbol.dispose](): void;\n readonly disposalSignal: AbortSignal;\n dispose(): void;\n readonly disposed: boolean;\n send(value: T): void;\n readonly stream: Stream<T>;\n};\n```\n\n## Errors\n\n### `FluxError`\n\nBase Flux error. Use `instanceof FluxError` to narrow unknown values.\n\n### `FluxTimeoutError`\n\nRaised by `timeout()`. `ms` contains configured inactivity duration.\n\n### `FluxEmptyError`\n\nRaised by `first()` and `last()` when the source completes without emitting any value.\n\n### `FluxCapacityError`\n\nRaised when a bounded buffer (`mergeMap`, `concatMap`, `toArray`, async iteration) overflows. `capacity` contains the configured limit.\n",
6
- "usage": "---\ntitle: 'Flux: Usage Guide'\ndescription: Create streams, compose operators, consume values safely, and bridge Vielzeug primitives.\n---\n\n[[toc]]\n\n## Basic Usage\n\nDefine one cold stream. Return teardown work from producer. Every subscription runs producer independently.\n\n```ts\nimport { stream } from '@vielzeug/flux';\n\nconst clock = stream<number>((sink) => {\n let value = 0;\n const id = setInterval(() => sink.next(value++), 1_000);\n\n return () => clearInterval(id);\n});\n\nconst subscription = clock.subscribe({\n error: console.error,\n next: console.log,\n});\n\nsubscription.unsubscribe();\n```\n\nPass `AbortSignal` when another owner controls lifetime.\n\n```ts\nconst controller = new AbortController();\nclock.subscribe(console.log, { signal: controller.signal });\ncontroller.abort();\n```\n\n## Compose Streams\n\nPass source first to `pipe()`. Operators retain inferred value types across chains.\n\n```ts\nimport { filter, fromEvent, map, pipe, take } from '@vielzeug/flux';\n\nconst clicks = pipe(\n fromEvent<MouseEvent>(document, 'click'),\n filter((event) => event.button === 0),\n map((event) => ({ x: event.clientX, y: event.clientY })),\n take(10),\n);\n\nclicks.subscribe({\n complete: () => console.log('done'),\n error: console.error,\n next: console.log,\n});\n```\n\nUse `switchMap()` for latest-only work, `mergeMap()` for concurrent work with bounded concurrency and queue capacity, and `concatMap()` for ordered work with bounded queue capacity.\n\n```ts\nimport { from, pipe, retry, switchMap } from '@vielzeug/flux';\n\nconst results = pipe(\n queries,\n switchMap((query) => from(fetch(`/api/search?q=${encodeURIComponent(query)}`).then((response) => response.json()))),\n retry({ times: 2, delay: (attempt) => 250 * (attempt + 1) }),\n);\n```\n\n## Consume Values\n\nUse bounded array conversion for finite streams. `toArray()` rejects once source exceeds `maxItems`.\n\n```ts\nimport { toArray, of } from '@vielzeug/flux';\n\ntry {\n const values = await toArray(of(1, 2, 3), { maxItems: 3 });\n console.log(values);\n} catch (reason) {\n console.error('Collection failed', reason);\n}\n```\n\nUse `first()` for first emission and `last()` for last value before completion. Both reject with `FluxEmptyError` when the source completes without emitting; pass `{ defaultValue }` to resolve instead. Pass `{ signal }` to cancel waiting; cancellation rejects with `signal.reason` (the default reason is `AbortError`).\n\n## Channels\n\nUse channels only at imperative boundaries. Expose `channel.stream` to consumers; keep `send()` near event producer.\n\n```ts\nimport { createChannel } from '@vielzeug/flux';\n\nconst status = createChannel({ initial: 'starting', replay: 1 });\nstatus.stream.subscribe({ error: console.error, next: console.log });\nstatus.send('ready');\nstatus.dispose();\n```\n\nDisposal completes active and future subscribers. Replay retains only configured latest values.\n\n## Async Iteration and Bounds\n\nConvert push stream only when pull syntax is required. Capacity and overflow policy are mandatory.\n\n```ts\nimport { interval, toAsyncIterable } from '@vielzeug/flux';\n\nconst values = toAsyncIterable(interval(100), {\n capacity: 32,\n overflow: 'error',\n});\n\nfor await (const value of values) {\n console.log(value);\n if (value === 2) break;\n}\n```\n\n`return()` from a loop permanently completes its iterator; external signal cancellation rejects with `signal.reason`. Use `drop-oldest` or `drop-newest` only when loss is acceptable.\n\n## Testing\n\nUse fake timers for time operators. Test producer cleanup through returned subscription.\n\n```ts\nimport { expect, it, vi } from 'vitest';\nimport { first, pipe, stream, timeout } from '@vielzeug/flux';\n\nit('fails after inactivity', async () => {\n vi.useFakeTimers();\n const result = first(\n pipe(\n stream(() => {}),\n timeout(500),\n ),\n );\n const expectation = expect(result).rejects.toThrow('Timeout after 500ms');\n\n await vi.advanceTimersByTimeAsync(500);\n await expectation;\n vi.useRealTimers();\n});\n```\n\n## Framework Integration\n\n::: code-group\n\n```tsx [React]\nimport { useEffect, useState } from 'react';\nimport type { Stream } from '@vielzeug/flux';\n\nexport function useStream<T>(source: Stream<T>, initial: T): T {\n const [value, setValue] = useState(initial);\n\n useEffect(() => {\n const subscription = source.subscribe({ error: console.error, next: setValue });\n return () => subscription.unsubscribe();\n }, [source]);\n\n return value;\n}\n```\n\n```ts [Vue 3]\nimport { onUnmounted, ref } from 'vue';\nimport type { Stream } from '@vielzeug/flux';\n\nexport function useStream<T>(source: Stream<T>, initial: T) {\n const value = ref(initial);\n const subscription = source.subscribe({ error: console.error, next: (next) => (value.value = next) });\n\n onUnmounted(() => subscription.unsubscribe());\n\n return value;\n}\n```\n\n```ts [Svelte]\nimport type { Stream } from '@vielzeug/flux';\n\nexport function streamStore<T>(source: Stream<T>, initial: T) {\n return {\n subscribe(run: (value: T) => void) {\n run(initial);\n const subscription = source.subscribe({ error: console.error, next: run });\n return () => subscription.unsubscribe();\n },\n };\n}\n```\n\n:::\n\n## Working with Other Vielzeug Libraries\n\nUse `fromStore()` for snapshot state and `fromSubscribe()` for callback-delivered event values. Write stream output into the owning state or event layer explicitly.\n\n```ts\nimport { fromStore, fromSubscribe } from '@vielzeug/flux';\n\nconst state = fromStore({\n getSnapshot: () => store.value,\n subscribe: (listener) => store.subscribe(listener),\n});\n\nconst events = fromSubscribe<Message>((listener) => bus.on('message', listener));\n```\n\n## Best Practices\n\n- Return one idempotent producer teardown function.\n- Pass `{ signal }` from component, request, or task owner.\n- Provide `error` when subscription can recover locally.\n- Use `pipe(source, ...)`; never mutate stream definitions.\n- Bound `mergeMap()` concurrency and queue capacity.\n- Bound `concatMap()` queue capacity.\n- Bound `toArray()` with realistic `maxItems`.\n- Choose async iterator overflow policy deliberately.\n- Keep timer-backed durations between 0 and 2,147,483,647 milliseconds.\n- Keep `Channel.send()` at integration boundaries.\n",
5
+ "api": "---\ntitle: 'Flux: API Reference'\ndescription: Complete reference for @vielzeug/flux streams, operators, channels, and structural bridges.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| -------------------------------------------- | -------------------------------- | -------------- | ------------------------------------------------------------------------------ |\n| `stream()` | Create cold stream | Lazy | Return one teardown function |\n| `pipe()` | Compose operators | Lazy | Source is first argument |\n| `of()` / `from()` | Convert known values | Sync / mixed | `from()` promise cannot be aborted |\n| `fromEvent()` | Adapt event target | Async | Unsubscribe removes listener |\n| `interval()` / `timer()` | Create timed values | Async | Use `take()` or unsubscribe for intervals |\n| `map()` / `filter()` / `scan()` | Transform values | Sync | Callback throws terminate stream |\n| `switchMap()` / `mergeMap()` / `concatMap()` | Flatten streams | Mixed | `mergeMap()` concurrency and queue are bounded; `concatMap()` queue is bounded |\n| `take()` / `takeUntil()` | Stop values | Mixed | Notifier emission completes output |\n| `debounce()` / `timeout()` / `retry()` | Control time and failures | Async | `timeout()` measures inactivity |\n| `merge()` / `concat()` / `combineLatest()` | Combine streams | Mixed | `combineLatest()` waits for every source |\n| `toArray()` / `first()` / `last()` | Consume finite values | Async | Bound `toArray()` with `maxItems` |\n| `toAsyncIterable()` | Use `for await` | Async | Capacity and overflow required |\n| `createChannel()` | Imperative multicast boundary | Sync | Dispose to complete subscribers |\n| `fromStore()` | Bridge snapshot-based state | Lazy | Snapshot and subscribe are both required |\n| `fromSubscribe()` | Bridge callback-delivered values | Lazy | Registration must return teardown |\n\n## Package Entry Point\n\n| Import | Purpose |\n| ---------------- | --------------------------------------------------------------------------------------------- |\n| `@vielzeug/flux` | Core streams, operators, consumers, errors, types, `createChannel()`, and `toAsyncIterable()` |\n\n## Core\n\n### `stream()`\n\n```ts\nstream<T>(producer: Producer<T>): Stream<T>\n```\n\nCreates cold reusable work. Producer runs once for every subscription.\n\n| Parameter | Type | Description |\n| ---------- | ------------- | ------------------------------------------------ |\n| `producer` | `Producer<T>` | Emits through sink and returns optional teardown |\n\n**Returns:** `Stream<T>`.\n\n```ts\nimport { stream } from '@vielzeug/flux';\n\nconst ticks = stream<number>((sink) => {\n const id = setInterval(() => sink.next(Date.now()), 1_000);\n return () => clearInterval(id);\n});\n```\n\n---\n\n### `pipe()`\n\n```ts\npipe<Input, Operators>(source: Stream<Input>, ...operators: Operators): Stream<Output>\n```\n\nApplies operators left to right while inferring output value type.\n\n| Parameter | Type | Description |\n| ----------- | --------------- | -------------------------- |\n| `source` | `Stream<Input>` | Source stream |\n| `operators` | `Operator[]` | Operators applied in order |\n\n**Returns:** transformed `Stream<Output>`.\n\n```ts\nimport { map, of, pipe } from '@vielzeug/flux';\n\nconst labels = pipe(\n of(1, 2),\n map((value) => `#${value}`),\n);\n```\n\n## Creation\n\n### `of()`\n\n```ts\nof<T>(...values: T[]): Stream<T>\n```\n\nEmits every value synchronously, then completes.\n\n```ts\nimport { of } from '@vielzeug/flux';\n\nof(1, 2, 3).subscribe(console.log);\n```\n\n---\n\n### `from()`\n\n```ts\nfrom<T>(source: Iterable<T> | AsyncIterable<T> | Promise<T>): Stream<T>\n```\n\nConverts iterable, async iterable, or promise into a stream. Cancellation stops iterable consumption and calls `return()` when available.\n\n```ts\nimport { from } from '@vielzeug/flux';\n\nfrom(Promise.resolve('ready')).subscribe({ error: console.error, next: console.log });\n```\n\n---\n\n### `fromEvent()`\n\n```ts\nfromEvent<T = Event>(\n target: {\n addEventListener(type: string, listener: (event: T) => void): void;\n removeEventListener(type: string, listener: (event: T) => void): void;\n },\n type: string,\n): Stream<T>\n```\n\nEmits target events until subscription ends.\n\n```ts\nimport { fromEvent } from '@vielzeug/flux';\n\nfromEvent<MouseEvent>(document, 'click').subscribe(console.log);\n```\n\n---\n\n### `interval()`\n\n```ts\ninterval(every: number): Stream<number>\n```\n\nEmits incrementing values starting at zero.\n\n| Parameter | Type | Description |\n| --------- | -------- | ----------------------------------------------------------- |\n| `every` | `number` | Interval duration from 0 through 2,147,483,647 milliseconds |\n\n---\n\n### `timer()`\n\n```ts\ntimer(options: TimerOptions): Stream<number>\n```\n\nEmits zero after `delay`; optionally continues at `interval`.\n\n| Option | Type | Description |\n| ---------- | -------- | ------------------------------------------------------------------ |\n| `delay` | `number` | Initial delay from 0 through 2,147,483,647 milliseconds |\n| `interval` | `number` | Optional repeat duration from 0 through 2,147,483,647 milliseconds |\n\n## Transformation Operators\n\n### `map()`\n\n```ts\nmap<A, B>(project: (value: A) => B): Operator<A, B>\n```\n\nMaps every value. A thrown callback error terminates output.\n\n---\n\n### `filter()`\n\n```ts\nfilter<T>(predicate: (value: T) => boolean): Operator<T, T>\n```\n\nForwards values matching predicate.\n\n---\n\n### `scan()`\n\n```ts\nscan<T, A>(reducer: (state: A, value: T) => A, initial: A): Operator<T, A>\n```\n\nEmits accumulated state after every source value.\n\n---\n\n### `switchMap()`\n\n```ts\nswitchMap<A, B>(project: (value: A) => Stream<B>): Operator<A, B>\n```\n\nCancels previous inner stream when source emits.\n\n---\n\n### `mergeMap()`\n\n```ts\nmergeMap<A, B>(project: (value: A) => Stream<B>, options: FlattenOptions): Operator<A, B>\n```\n\nRuns inner streams with bounded concurrency and queue capacity. Exceeding capacity errors output with `FluxCapacityError`.\n\n| Option | Type | Description |\n| ------------- | ----------------------- | ---------------------------------------------------------------------------------------------------------- |\n| `concurrency` | `number \\| 'unbounded'` | Maximum concurrently active inner subscriptions; `'unbounded'` starts every value immediately |\n| `capacity` | `number` | Positive maximum queued source values (required when `concurrency` is a number; unused when `'unbounded'`) |\n\nFinite `concurrency` without a `capacity` throws `RangeError` when the operator is created.\n\n---\n\n### `concatMap()`\n\n```ts\nconcatMap<A, B>(project: (value: A) => Stream<B>, options: { capacity: number }): Operator<A, B>\n```\n\nRuns inner streams in order (`concurrency: 1`). Exceeding capacity errors output with `FluxCapacityError`.\n\n| Option | Type | Description |\n| ---------- | -------- | ------------------------------------- |\n| `capacity` | `number` | Positive maximum queued source values |\n\n## Control Operators\n\n### `take()`\n\n```ts\ntake<T>(count: number): Operator<T, T>\n```\n\nForwards `count` values, cancels upstream, then completes. Count must be non-negative integer.\n\n---\n\n### `takeUntil()`\n\n```ts\ntakeUntil<T>(notifier: AbortSignal | Stream<unknown>): Operator<T, T>\n```\n\nCompletes when notifier aborts or emits.\n\n---\n\n### `debounce()`\n\n```ts\ndebounce<T>(duration: number): Operator<T, T>\n```\n\nEmits latest value after configured silence. Pending value flushes on source completion.\n\n| Parameter | Type | Description |\n| ---------- | -------- | ---------------------------------------------------------- |\n| `duration` | `number` | Silence duration from 0 through 2,147,483,647 milliseconds |\n\n---\n\n### `timeout()`\n\n```ts\ntimeout<T>(duration: number): Operator<T, T>\n```\n\nErrors with `FluxTimeoutError` when source is silent too long.\n\n| Parameter | Type | Description |\n| ---------- | -------- | ------------------------------------------------------------- |\n| `duration` | `number` | Inactivity duration from 0 through 2,147,483,647 milliseconds |\n\n---\n\n### `retry()`\n\n```ts\nretry<T>(options: RetryOptions): Operator<T, T>\n```\n\nResubscribes after source errors until attempts are exhausted.\n\n| Option | Type | Description |\n| ------- | --------------------------------------- | --------------------------------------------------------------------- |\n| `times` | `number` | Non-negative retry count |\n| `delay` | `number \\| (attempt: number) => number` | Optional delay/backoff returning 0 through 2,147,483,647 milliseconds |\n\n## Combination\n\n### `merge()`\n\n```ts\nmerge<T>(...sources: Stream<T>[]): Stream<T>\n```\n\nForwards values from all sources and completes after every source completes.\n\n---\n\n### `concat()`\n\n```ts\nconcat<T>(...sources: Stream<T>[]): Stream<T>\n```\n\nSubscribes to each source only after previous source completes.\n\n---\n\n### `combineLatest()`\n\n```ts\ncombineLatest<T extends readonly Stream<unknown>[]>(...sources: T): Stream<{ [K in keyof T]: T[K] extends Stream<infer V> ? V : never }>\n```\n\nEmits latest tuple after every source emits once. Completes without emission when a source completes before first value.\n\n## Value Consumers\n\n### `toArray()`\n\n```ts\ntoArray<T>(source: Stream<T>, options: ToArrayOptions): Promise<T[]>\n```\n\nCollects finite output. Rejects on source error, the supplied signal's abort reason, or `maxItems` overflow.\n\n| Option | Type | Description |\n| ---------- | ------------- | ------------------------------------- |\n| `maxItems` | `number` | Non-negative maximum toArrayed values |\n| `signal` | `AbortSignal` | Optional cancellation signal |\n\n---\n\n### `first()`\n\n```ts\nfirst<T>(source: Stream<T>, options?: ValueOptions<T>): Promise<T>\n```\n\nResolves first value and cancels source. Rejects on source error, the supplied signal's abort reason, or empty completion (`FluxEmptyError`); pass `defaultValue` to resolve instead.\n\n---\n\n### `last()`\n\n```ts\nlast<T>(source: Stream<T>, options?: ValueOptions<T>): Promise<T>\n```\n\nResolves last value on completion. Rejects on source error, the supplied signal's abort reason, or empty completion (`FluxEmptyError`); pass `defaultValue` to resolve instead.\n\n## Async Conversion\n\n### `toAsyncIterable()`\n\n```ts\ntoAsyncIterable<T>(source: Stream<T>, options: AsyncIterableOptions): AsyncIterable<T>\n```\n\nConverts a push stream to an async iterable with a bounded queue. External cancellation rejects pending iteration with `signal.reason`; explicit iterator `return()` completes normally. Overflow `\"error\"` rejects with `FluxCapacityError`; unsupported policies throw `RangeError` before subscription.\n\n| Option | Type | Description |\n| ---------- | ---------------- | ---------------------------------------- |\n| `capacity` | `number` | Positive queue capacity |\n| `overflow` | `OverflowPolicy` | `error`, `drop-oldest`, or `drop-newest` |\n| `signal` | `AbortSignal` | Optional cancellation signal |\n\n## Channels\n\n### `createChannel()`\n\n```ts\ncreateChannel<T>(options?: ChannelOptions<T>): Channel<T>\n```\n\nCreates an imperative multicast boundary. Disposal completes subscribers and releases replay and pending values.\n\n> **`initial` + `replay` interaction:** When `initial` is set and `replay` is omitted, `replay` defaults to `1` so the initial value is retained. Setting `replay: 0` with `initial` throws `RangeError`: the initial value would be immediately dropped.\n\n| Option | Type | Description |\n| --------- | -------- | --------------------------------- |\n| `initial` | `T` | Optional initial replay value |\n| `replay` | `number` | Non-negative retained value count |\n\n## Structural adapters\n\n### `fromStore()`\n\n```ts\nfromStore<T>(source: {\n getSnapshot(): T;\n subscribe(listener: () => void): () => void;\n}): Stream<T>\n```\n\nBridges snapshot-based state without package-specific dependencies. It emits the current snapshot, subscribes, rechecks for a subscription-time change, and reads the latest snapshot after each notification. Snapshot failure terminates without subscribing.\n\n### `fromSubscribe()`\n\n```ts\nfromSubscribe<T>(subscribe: (listener: (value: T) => void) => () => void): Stream<T>\n```\n\nBridges callback-delivered event values. Registration runs once per Flux subscription and its teardown runs when that subscription closes.\n\n## Types\n\n```ts\ntype Teardown = () => void;\n\ntype Subscription = {\n [Symbol.dispose](): void;\n readonly closed: boolean;\n unsubscribe(): void;\n};\n\ntype Observer<T> = {\n complete?: () => void;\n error?: (reason: unknown) => void;\n next: (value: T) => void;\n};\n\ntype SubscribeOptions = { signal?: AbortSignal };\n\ntype Sink<T> = {\n complete(): void;\n error(reason: unknown): void;\n next(value: T): void;\n};\n\ntype Producer<T> = (sink: Sink<T>, signal: AbortSignal) => Teardown | undefined;\ntype Operator<A = unknown, B = unknown> = (source: Stream<A>) => Stream<B>;\n\ninterface Stream<T> {\n subscribe(observer: Observer<T> | ((value: T) => void), options?: SubscribeOptions): Subscription;\n}\n\ntype OverflowPolicy = 'drop-newest' | 'drop-oldest' | 'error';\ntype AsyncIterableOptions = { capacity: number; overflow: OverflowPolicy; signal?: AbortSignal };\ntype TimerOptions = { delay: number; interval?: number };\ntype FlattenOptions = { concurrency: number; capacity: number } | { concurrency: 'unbounded'; capacity?: undefined };\ntype RetryOptions = { times: number; delay?: number | ((attempt: number) => number) };\ntype ToArrayOptions = { maxItems: number; signal?: AbortSignal };\ntype ValueOptions<T> = { signal?: AbortSignal; defaultValue?: T };\ntype ChannelOptions<T> = { initial?: T; replay?: number };\ntype Channel<T> = {\n [Symbol.dispose](): void;\n readonly disposalSignal: AbortSignal;\n dispose(): void;\n readonly disposed: boolean;\n send(value: T): void;\n readonly stream: Stream<T>;\n};\n```\n\n## Errors\n\n### `FluxError`\n\nBase Flux error. Use `instanceof FluxError` to narrow unknown values.\n\n### `FluxTimeoutError`\n\nRaised by `timeout()`. `ms` contains configured inactivity duration.\n\n### `FluxEmptyError`\n\nRaised by `first()` and `last()` when the source completes without emitting any value.\n\n### `FluxCapacityError`\n\nRaised when a bounded buffer (`mergeMap`, `concatMap`, `toArray`, async iteration) overflows. `capacity` contains the configured limit.\n",
6
+ "usage": "---\ntitle: 'Flux: Usage Guide'\ndescription: Create streams, compose operators, consume values safely, and bridge Vielzeug primitives.\n---\n\n[[toc]]\n\n## Basic Usage\n\nDefine one cold stream. Return teardown work from producer. Every subscription runs producer independently.\n\n```ts\nimport { stream } from '@vielzeug/flux';\n\nconst clock = stream<number>((sink) => {\n let value = 0;\n const id = setInterval(() => sink.next(value++), 1_000);\n\n return () => clearInterval(id);\n});\n\nconst subscription = clock.subscribe({\n error: console.error,\n next: console.log,\n});\n\nsubscription.unsubscribe();\n```\n\nPass `AbortSignal` when another owner controls lifetime.\n\n```ts\nconst controller = new AbortController();\nclock.subscribe(console.log, { signal: controller.signal });\ncontroller.abort();\n```\n\n## Compose Streams\n\nPass source first to `pipe()`. Operators retain inferred value types across chains.\n\n```ts\nimport { filter, fromEvent, map, pipe, take } from '@vielzeug/flux';\n\nconst clicks = pipe(\n fromEvent<MouseEvent>(document, 'click'),\n filter((event) => event.button === 0),\n map((event) => ({ x: event.clientX, y: event.clientY })),\n take(10),\n);\n\nclicks.subscribe({\n complete: () => console.log('done'),\n error: console.error,\n next: console.log,\n});\n```\n\nUse `switchMap()` for latest-only work, `mergeMap()` for concurrent work with bounded concurrency and queue capacity (`{ concurrency: 'unbounded' }` starts every value immediately), and `concatMap()` for ordered work with bounded queue capacity.\n\n```ts\nimport { from, pipe, retry, switchMap } from '@vielzeug/flux';\n\nconst results = pipe(\n queries,\n switchMap((query) => from(fetch(`/api/search?q=${encodeURIComponent(query)}`).then((response) => response.json()))),\n retry({ times: 2, delay: (attempt) => 250 * (attempt + 1) }),\n);\n```\n\n## Consume Values\n\nUse bounded array conversion for finite streams. `toArray()` rejects once source exceeds `maxItems`.\n\n```ts\nimport { toArray, of } from '@vielzeug/flux';\n\ntry {\n const values = await toArray(of(1, 2, 3), { maxItems: 3 });\n console.log(values);\n} catch (reason) {\n console.error('Collection failed', reason);\n}\n```\n\nUse `first()` for first emission and `last()` for last value before completion. Both reject with `FluxEmptyError` when the source completes without emitting; pass `{ defaultValue }` to resolve instead. Pass `{ signal }` to cancel waiting; cancellation rejects with `signal.reason` (the default reason is `AbortError`).\n\n## Channels\n\nUse channels only at imperative boundaries. Expose `channel.stream` to consumers; keep `send()` near event producer.\n\n```ts\nimport { createChannel } from '@vielzeug/flux';\n\nconst status = createChannel({ initial: 'starting', replay: 1 });\nstatus.stream.subscribe({ error: console.error, next: console.log });\nstatus.send('ready');\nstatus.dispose();\n```\n\nDisposal completes active and future subscribers. Replay retains only configured latest values.\n\n## Async Iteration and Bounds\n\nConvert push stream only when pull syntax is required. Capacity and overflow policy are mandatory.\n\n```ts\nimport { interval, toAsyncIterable } from '@vielzeug/flux';\n\nconst values = toAsyncIterable(interval(100), {\n capacity: 32,\n overflow: 'error',\n});\n\nfor await (const value of values) {\n console.log(value);\n if (value === 2) break;\n}\n```\n\n`return()` from a loop permanently completes its iterator; external signal cancellation rejects with `signal.reason`. Use `drop-oldest` or `drop-newest` only when loss is acceptable.\n\n## Testing\n\nUse fake timers for time operators. Test producer cleanup through returned subscription.\n\n```ts\nimport { expect, it, vi } from 'vitest';\nimport { first, pipe, stream, timeout } from '@vielzeug/flux';\n\nit('fails after inactivity', async () => {\n vi.useFakeTimers();\n const result = first(\n pipe(\n stream(() => {}),\n timeout(500),\n ),\n );\n const expectation = expect(result).rejects.toThrow('Timeout after 500ms');\n\n await vi.advanceTimersByTimeAsync(500);\n await expectation;\n vi.useRealTimers();\n});\n```\n\n## Framework Integration\n\n::: code-group\n\n```tsx [React]\nimport { useEffect, useState } from 'react';\nimport type { Stream } from '@vielzeug/flux';\n\nexport function useStream<T>(source: Stream<T>, initial: T): T {\n const [value, setValue] = useState(initial);\n\n useEffect(() => {\n const subscription = source.subscribe({ error: console.error, next: setValue });\n return () => subscription.unsubscribe();\n }, [source]);\n\n return value;\n}\n```\n\n```ts [Vue 3]\nimport { onUnmounted, ref } from 'vue';\nimport type { Stream } from '@vielzeug/flux';\n\nexport function useStream<T>(source: Stream<T>, initial: T) {\n const value = ref(initial);\n const subscription = source.subscribe({ error: console.error, next: (next) => (value.value = next) });\n\n onUnmounted(() => subscription.unsubscribe());\n\n return value;\n}\n```\n\n```ts [Svelte]\nimport type { Stream } from '@vielzeug/flux';\n\nexport function streamStore<T>(source: Stream<T>, initial: T) {\n return {\n subscribe(run: (value: T) => void) {\n run(initial);\n const subscription = source.subscribe({ error: console.error, next: run });\n return () => subscription.unsubscribe();\n },\n };\n}\n```\n\n:::\n\n## Working with Other Vielzeug Libraries\n\nUse `fromStore()` for snapshot state and `fromSubscribe()` for callback-delivered event values. Write stream output into the owning state or event layer explicitly.\n\n```ts\nimport { fromStore, fromSubscribe } from '@vielzeug/flux';\n\nconst state = fromStore({\n getSnapshot: () => store.value,\n subscribe: (listener) => store.subscribe(listener),\n});\n\nconst events = fromSubscribe<Message>((listener) => bus.on('message', listener));\n```\n\n## Best Practices\n\n- Return one idempotent producer teardown function.\n- Pass `{ signal }` from component, request, or task owner.\n- Provide `error` when subscription can recover locally.\n- Use `pipe(source, ...)`; never mutate stream definitions.\n- Bound `mergeMap()` concurrency and queue capacity, or choose `'unbounded'` explicitly.\n- Bound `concatMap()` queue capacity.\n- Bound `toArray()` with realistic `maxItems`.\n- Choose async iterator overflow policy deliberately.\n- Keep timer-backed durations between 0 and 2,147,483,647 milliseconds.\n- Keep `Channel.send()` at integration boundaries.\n",
7
7
  "examples": "---\ntitle: 'Flux: Examples'\ndescription: Practical examples and recipes for @vielzeug/flux.\n---\n\n## Examples\n\n- [Debounced Search Input](./examples/debounce-search.md)\n- [Combining Streams with combineLatest](./examples/combine-streams.md)\n- [Structural State Integration](./examples/signal-integration.md)\n"
8
8
  },
9
9
  "examples": [
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "apiSource": "export { ForgeConfigError, ForgeDisposedError, ForgeError, ForgeSubmitError, ForgeValidationError } from './errors.js';\nexport { createForm } from './form.js';\nexport { toPlainValues } from './plain.js';\nexport * from './types.js';\n",
3
3
  "docs": {
4
- "index": "---\ntitle: 'Forge: Immutable typed form state'\ndescription: Framework-neutral form and field state with nested handles, flat validation issues, and explicit integration helpers.\npackage: forge\ncategory: state\nkeywords: [forms, validation, fields, immutable, standard schema, formdata]\nexports: [createForm, toPlainValues]\nrelated: [spell, vault, assay]\nenvironments: [browser, node, ssr, deno]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"forge\" />\n\n## Why Forge?\n\nForge owns form state without owning rendering or validation timing. Nested field handles keep access typed, flat validation issues compose across arrays and unions, and Forge-owned validation and persistence operations settle on cancellation.\n\n## Quick Start\n\n```ts\nimport { createForm } from '@vielzeug/forge';\n\nconst form = createForm({\n initialValues: { email: '', profile: { name: '' } },\n validate: (values) => (values.email.includes('@') ? undefined : [{ path: ['email'], message: 'Invalid email' }]),\n});\n\nform.field('profile').field('name').set('Ada');\nconst result = await form.validate();\n```\n\n| Feature | Forge | Local component state |\n| ----------------------------- | -------------------------------------------- | -------------------------------------------- |\n| Bundle size | <PackageInfo package=\"forge\" type=\"size\" /> | n/a |\n| Nested typed fields | <ore-icon name=\"check\" size=\"16\"></ore-icon> | Manual |\n| Flat validation issues | <ore-icon name=\"check\" size=\"16\"></ore-icon> | Manual |\n| Abortable validation | <ore-icon name=\"check\" size=\"16\"></ore-icon> | Manual |\n| Framework-neutral | <ore-icon name=\"check\" size=\"16\"></ore-icon> | Varies |\n| Zero third-party dependencies | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n\n<div class=\"decision-callout\">\n\n**Use Forge when** several fields need coordinated validation, submission, dirty/touched state, nested updates, or explicit persistence.\n\n**Use local state when** a form has only one or two fields and no shared validation lifecycle.\n\n</div>\n\n## Installation\n\n```sh\npnpm add @vielzeug/forge\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- `createForm()`: deeply readonly form state with structural sharing and cloned dates\n- `field().field()`: typed nested field handles\n- `patch()`: shallow top-level merge without spread casts\n- `normalize` + `toPlainValues()`: hold domain-model classes in form state\n- Flat `{ path, message }` validation issues\n- Explicit `validate()` and `submit()` timing\n- `/dom`: optional element binding\n- `/schema`: validator-agnostic Standard Schema adapter\n- `/persist`: explicit structural store integration\n- `/form-data`: browser submission serialization\n\n</div>\n\n## Documentation\n\n<div class=\"doc-links\">\n\n- [Usage Guide](./usage.md)\n- [API Reference](./api.md)\n- [Examples](./examples.md)\n- [Migration Guide](./migration.md)\n\n</div>\n\n## See Also\n\n- [Spell](/spell/): Standard Schema-compatible validation.\n- [Vault](/vault/): durable typed storage for drafts.\n- [Assay](/assay/): DOM test helpers for form interaction.\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
5
- "api": "---\ntitle: 'Forge: API Reference'\ndescription: Immutable typed form state, flat validation issues, and optional integration helpers.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| --------------------------- | ------------------------------------------------ | -------------- | -------------------------------------- |\n| `createForm()` | Create immutable form and field state | Sync | Dispose with its owner |\n| `toPlainValues()` | Flatten class instances to the plain value shape | Sync | Drops circular branches |\n| `validate()` | Run the configured full-form validator | Async | Superseded work returns `aborted` |\n| `submit()` | Validate and submit one captured snapshot | Async | Concurrent submission rejects |\n| `bindField()` | Bind a field to an HTML element | Sync | Caller owns returned cleanup |\n| `schemaValidator()` | Adapt Standard Schema validation | Async | Transform output is not applied |\n| `loadForm()` / `saveForm()` | Explicit structural draft persistence | Async | Loading will not overwrite newer edits |\n| `toFormData()` | Serialize supported values | Sync | Dotted keys and object arrays reject |\n\n## Package Entry Point\n\n| Import | Purpose |\n| --------------------------- | ---------------------------------- |\n| `@vielzeug/forge` | Form and field state |\n| `@vielzeug/forge/dom` | `bindField()` DOM binding |\n| `@vielzeug/forge/form-data` | `toFormData()` serialization |\n| `@vielzeug/forge/schema` | Standard Schema validation adapter |\n| `@vielzeug/forge/persist` | Explicit draft save/load helpers |\n\n## createForm\n\n```ts\nfunction createForm<TValues extends Record<string, unknown>>(options: FormOptions<TValues>): Form<TValues>;\n```\n\n`initialValues` is required. Validation is explicit and returns flat issues.\n\n```ts\nconst form = createForm({\n initialValues: { email: '' },\n validate: (values) => (values.email.includes('@') ? undefined : [{ path: ['email'], message: 'Invalid email' }]),\n});\n```\n\n`normalize` runs before value validation at every write boundary (`initialValues`, `set`, `patch`, `reset`, `field().set`), so a caller that normalizes once at `createForm` stays correct everywhere. Pair it with `toPlainValues()` to hold domain-model classes in form state.\n\n```ts\nimport { createForm, toPlainValues } from '@vielzeug/forge';\n\nconst form = createForm({ initialValues: { user: new UserModel() }, normalize: toPlainValues });\n\nform.reset({ user: new UserModel() }); // same normalization as init\n```\n\n## toPlainValues\n\n```ts\nfunction toPlainValues<T>(value: T): T;\n```\n\nDeeply converts a value into the plain shape Forge accepts: primitives pass through, `Date` is cloned, `File`/`Blob` keep identity, arrays map, and class instances flatten to their own enumerable entries. Unsafe keys (`__proto__`, `constructor`, `prototype`) are dropped, so the output always passes value validation. The returned type parameter is a convenience cast: the flattened shape differs from the input type whenever class instances are present.\n\nLossy conversions replace the error an un-normalized write would throw: `Map`, `Set`, and other keyless built-ins flatten to `{}`; sparse array slots are dropped, shifting later indexes; `NaN`, `Infinity`, functions, and circular branches become `undefined`. Normalize model classes, not arbitrary graphs.\n\n```ts\nimport { createForm, toPlainValues } from '@vielzeug/forge';\n\nclass UserModel {\n email = '';\n name = '';\n}\n\ntoPlainValues(new UserModel()); // { email: '', name: '' }\nconst form = createForm({ initialValues: { user: new UserModel() }, normalize: toPlainValues });\n```\n\n## Form\n\n```ts\ninterface Form<TValues extends Record<string, unknown>> {\n readonly value: ReadonlyDeep<TValues>;\n readonly state: FormState;\n readonly disposed: boolean;\n readonly disposalSignal: AbortSignal;\n field<K extends keyof TValues & string>(key: K): Field<TValues[K]>;\n set(next: TValues | ((previous: ReadonlyDeep<TValues>) => TValues)): void;\n patch(next: Partial<TValues>): void;\n patch(updater: (previous: ReadonlyDeep<TValues>) => Partial<TValues>): void;\n reset(next?: TValues): void;\n validate(signal?: AbortSignal): Promise<ValidationResult>;\n submit<TResult>(handler, signal?: AbortSignal): Promise<SubmitResult<TResult>>;\n subscribe(listener, options?: { immediate?: boolean }): () => void;\n dispose(): void;\n [Symbol.dispose](): void;\n}\n```\n\n`validate()` and `submit()` return `{ status: 'valid' }`, `{ status: 'invalid', issues }`, or `{ status: 'aborted' }`. Successful submission returns `{ status: 'ok', value }`. Submission handlers receive the exact snapshot that passed validation. `form.state` retains one stable reference until the next transition for framework external-store adapters.\n\n`patch()` shallow-merges top-level keys: `form.patch({ count: 1 })` equals `form.set((prev) => ({ ...prev, count: 1 }))` without the `as T` cast a spread requires. Nested values replace by identity; there is no deep merge.\n\n```ts\ntype FormState = Readonly<{\n formError: string | undefined;\n hasErrors: boolean;\n issues: readonly ValidationIssue[] | undefined;\n submitCount: number;\n submitting: boolean;\n touched: boolean;\n validity: 'invalid' | 'unknown' | 'valid';\n validating: boolean;\n}>;\n```\n\n## Field\n\n```ts\ninterface Field<Value> {\n readonly value: ReadonlyDeep<Value>;\n readonly state: FieldState<Value>;\n readonly dirty: boolean;\n readonly touched: boolean;\n readonly error: string | undefined;\n field(keyOrIndex): Field<unknown>;\n set(next: Value | ((previous: Value) => Value)): void;\n reset(): void;\n touch(): void;\n subscribe(listener, options?: { immediate?: boolean }): () => void;\n}\n```\n\nNested `field().field()` handles avoid string paths while preserving type inference.\n\n## Value types\n\n```ts\ntype Atomic = Date | File | Blob;\ntype ReadonlyDate = Omit<Date, Extract<keyof Date, `set${string}`>>;\ntype ReadonlyDeep<T> = T extends Date\n ? ReadonlyDate\n : T extends File | Blob\n ? T\n : T extends readonly (infer Item)[]\n ? readonly ReadonlyDeep<Item>[]\n : T extends Record<string, unknown>\n ? { readonly [K in keyof T]: ReadonlyDeep<T[K]> }\n : T;\n```\n\nForge clones valid dates, preserves binary identity, freezes plain containers, and rejects unsupported, circular, sparse, or non-finite values.\n\n## ValidationIssue\n\n```ts\ntype ValidationIssue = Readonly<{\n path: readonly (string | number)[];\n message: string;\n}>;\n```\n\n`path: []` denotes a form-level issue. A field derives its first matching error from the flat issue list.\n\n## bindField\n\n```ts\nimport { bindField } from '@vielzeug/forge/dom';\n\nconst stop = bindField(input, form.field('email'), {\n read: (element) => element.value,\n write: (element, value) => {\n element.value = value;\n },\n});\n```\n\nThe binding reads the configured event (`input` by default), marks the field touched on blur, writes external state changes, and returns cleanup.\n\n## schemaValidator\n\n```ts\nimport { schemaValidator } from '@vielzeug/forge/schema';\n\nconst form = createForm({\n initialValues: { email: '' },\n validate: schemaValidator(UserSchema),\n});\n```\n\nAccepts any Standard Schema-compatible validator. Portable issues are copied into Forge-owned immutable `{ path, message }` values. Cancellation settles promptly, although the underlying schema operation may continue. Successful transformed output is intentionally not written into the form.\n\n## Draft persistence\n\n```ts\nimport { loadForm, saveForm } from '@vielzeug/forge/persist';\n\nawait saveForm(form, store, 'drafts', codec);\nawait loadForm(form, store, 'drafts', 'profile', codec, { signal });\n```\n\nThe store is structural: it only needs typed `get(table, key)` and `put(table, value)` methods. The codec owns record conversion. The optional signal and form disposal cancel pending work; a load returns `false` when values changed before the record arrived.\n\n## FormData\n\n```ts\nimport { toFormData } from '@vielzeug/forge/form-data';\n\nconst body = toFormData(form.value);\n```\n\nFlattens nested plain objects to dotted keys and repeats scalar or binary array entries. Dots in object keys and nested objects or arrays inside arrays throw `ForgeConfigError` to prevent ambiguous or lossy output.\n\n## Errors\n\n- `ForgeError`: base package error.\n- `ForgeConfigError`: invalid value, path, issue, or serialization configuration.\n- `ForgeDisposedError`: operation attempted after disposal.\n- `ForgeSubmitError`: concurrent submission attempt.\n- `ForgeValidationError`: unexpected validator execution failure, with the original `cause`.\n",
6
- "usage": "---\ntitle: 'Forge: Usage Guide'\ndescription: Build, validate, submit, bind, and persist typed forms with Forge.\n---\n\n[[toc]]\n\n## Basic Usage\n\n```ts\nimport { createForm } from '@vielzeug/forge';\n\nconst form = createForm({\n initialValues: {\n email: '',\n profile: { name: '' },\n },\n});\n```\n\nRead `form.value` for the current deeply readonly snapshot. Use `set()` for whole-form replacement and field handles for focused updates.\n\n```ts\nform.field('email').set('ada@example.com');\nform.field('profile').field('name').set('Ada');\n```\n\n`patch()` shallow-merges top-level keys without the cast a spread `set()` needs:\n\n```ts\nform.patch({ email: 'ada@example.com' }); // siblings keep their values\n```\n\n## Hold domain-model classes\n\nForge values must be plain JSON-safe data. When your app stores class instances (models, DTOs with behavior), pass `normalize: toPlainValues` once at `createForm`; it runs before validation at every write boundary: init, `set`, `patch`, `reset`, and nested `field().set`, so a reset with fresh models behaves like init.\n\n```ts\nimport { createForm, toPlainValues } from '@vielzeug/forge';\n\nclass ProviderUserModel {\n id: number;\n email = '';\n constructor(id: number) {\n this.id = id;\n }\n}\n\nconst form = createForm<{ users: ProviderUserModel[] }>({\n initialValues: { users: [new ProviderUserModel(1)] },\n normalize: toPlainValues,\n});\n\nform.field('users').field(0).set(new ProviderUserModel(2)); // flattened like init\nform.reset({ users: [new ProviderUserModel(3)] }); // flattened like init\n// Rebuild models at submit:\nawait form.submit((values) => send(values.users.map((u) => new ProviderUserModel(u.id))));\n```\n\nWithout `normalize`, a rejected write throws `ForgeConfigError` naming the offending path (for example `list[0]`).\n\n## Validate explicitly\n\nValidators return a flat issue list. Forge does not choose blur/change/submit policy for the application.\n\n```ts\nconst form = createForm({\n initialValues: { email: '', password: '' },\n validate: (values) => {\n const issues = [];\n if (!values.email.includes('@')) issues.push({ path: ['email'], message: 'Invalid email' });\n if (values.password.length < 12) issues.push({ path: ['password'], message: 'Use at least 12 characters' });\n return issues.length ? issues : undefined;\n },\n});\n\nconst result = await form.validate();\nif (result.status === 'invalid') console.log(result.issues);\n```\n\nA field's `error` is derived from the first issue whose path equals that field path. Use `path: []` for form-level failures.\n\n## Submit\n\n```ts\nconst result = await form.submit(async (values, signal) => {\n const response = await fetch('/profile', {\n body: JSON.stringify(values),\n method: 'POST',\n signal,\n });\n return response.json();\n});\n\nif (result.status === 'ok') console.log(result.value);\n```\n\n`submit()` validates first, passes the exact validated snapshot to the handler, prevents duplicate active submissions, and reports aborts explicitly.\n\n## Bind an element\n\n```ts\nimport { bindField } from '@vielzeug/forge/dom';\n\nconst stop = bindField(input, form.field('email'), {\n read: (element) => element.value,\n write: (element, value) => {\n element.value = value;\n },\n});\n```\n\nCall `stop()` when the element owner unmounts.\n\n## Use a Standard Schema validator\n\n```ts\nimport { schemaValidator } from '@vielzeug/forge/schema';\n\nconst form = createForm({\n initialValues: { email: '' },\n validate: schemaValidator(UserSchema),\n});\n```\n\nSpell schemas implement Standard Schema directly. Forge uses the schema result only for success and issues; transformations do not replace form values. Cancellation settles Forge promptly even when underlying validator work cannot be stopped.\n\n## Persist a draft\n\n```ts\nimport { loadForm, saveForm } from '@vielzeug/forge/persist';\n\nconst codec = {\n fromRecord: (record) => record.value,\n toRecord: (values) => ({ id: 'profile', value: values }),\n};\n\nawait saveForm(form, store, 'drafts', codec);\nawait loadForm(form, store, 'drafts', 'profile', codec, { signal });\n```\n\nPersistence remains explicit. The store owns durability and validation; the codec owns record shape. Loading returns `false` rather than overwriting edits made while storage was pending.\n\n## Serialize FormData\n\n```ts\nimport { toFormData } from '@vielzeug/forge/form-data';\n\nawait fetch('/profile', { body: toFormData(form.value), method: 'POST' });\n```\n\nObject keys containing dots and arrays containing nested objects reject instead of producing ambiguous or lossy entries.\n\n## Dispose\n\n```ts\nform.dispose();\n```\n\nDisposal settles active Forge validation and signals active submission/persistence work and clears subscribers. It does not dispose borrowed validators, stores, or DOM elements.\n\n## Framework Integration\n\nInject an owner-scoped form and subscribe to its stable `FormState` snapshot.\n\n::: code-group\n\n```tsx [React]\nimport { useSyncExternalStore } from 'react';\nimport type { Form } from '@vielzeug/forge';\n\nexport function useFormState<T extends Record<string, unknown>>(form: Form<T>) {\n return useSyncExternalStore(\n form.subscribe,\n () => form.state,\n () => form.state,\n );\n}\n```\n\nWhen the component is the form's sole owner, create it in a ref and skip explicit disposal: writes on a disposed form throw `ForgeDisposedError`, which is what a StrictMode double-mount hits when effect cleanup disposes a ref-held form that survives the remount. Garbage collection reclaims a sole-subscriber form; dispose explicitly only when external subscribers or in-flight work need teardown.\n\n```ts [Vue]\nimport { onUnmounted, shallowRef } from 'vue';\nimport type { Form } from '@vielzeug/forge';\n\nexport function useFormState<T extends Record<string, unknown>>(form: Form<T>) {\n const state = shallowRef(form.state);\n const stop = form.subscribe(\n (next) => {\n state.value = next;\n },\n { immediate: true },\n );\n onUnmounted(stop);\n return state;\n}\n```\n\n```ts [Svelte]\nimport type { Form } from '@vielzeug/forge';\n\nexport const formState = <T extends Record<string, unknown>>(form: Form<T>) => ({\n subscribe(run: (state: Form<T>['state']) => void) {\n return form.subscribe(run, { immediate: true });\n },\n});\n```\n\n:::\n\nThe owner that creates the form disposes it. Framework subscriptions own only their unsubscribe callbacks.\n\n## Working with Other Vielzeug Libraries\n\n- Pass Spell schemas to `schemaValidator()` through Standard Schema.\n- Pass Vault stores directly to `loadForm()` and `saveForm()`.\n- Bind Ore or native controls with `bindField()` and owner cleanup.\n\n## Best Practices\n\n- Keep validation timing in the UI layer.\n- Return flat issues rather than shape-coupled error trees.\n- Use field handles instead of string paths.\n- Decode persisted/network data at its boundary.\n- Dispose forms with their owner.\n",
4
+ "index": "---\ntitle: 'Forge: Immutable typed form state'\ndescription: Framework-neutral form and field state with nested handles, flat validation issues, and explicit integration helpers.\npackage: forge\ncategory: state\nkeywords: [forms, validation, fields, immutable, standard schema, formdata]\nexports: [createForm, toPlainValues]\nrelated: [spell, vault, assay]\nenvironments: [browser, node, ssr, deno]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"forge\" />\n\n## Why Forge?\n\nForge owns form state without owning rendering or validation timing. Nested field handles keep access typed, flat validation issues compose across arrays and unions, and Forge-owned validation and persistence operations settle on cancellation.\n\n## Quick Start\n\n```ts\nimport { createForm } from '@vielzeug/forge';\n\nconst form = createForm({\n initialValues: { email: '', profile: { name: '' } },\n validate: (values) => (values.email.includes('@') ? undefined : [{ path: ['email'], message: 'Invalid email' }]),\n});\n\nform.field('profile').field('name').set('Ada');\nconst result = await form.validate();\n```\n\n| Feature | Forge | Local component state |\n| ----------------------------- | -------------------------------------------- | -------------------------------------------- |\n| Bundle size | <PackageInfo package=\"forge\" type=\"size\" /> | n/a |\n| Nested typed fields | <ore-icon name=\"check\" size=\"16\"></ore-icon> | Manual |\n| Flat validation issues | <ore-icon name=\"check\" size=\"16\"></ore-icon> | Manual |\n| Abortable validation | <ore-icon name=\"check\" size=\"16\"></ore-icon> | Manual |\n| Framework-neutral | <ore-icon name=\"check\" size=\"16\"></ore-icon> | Varies |\n| Zero third-party dependencies | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n\n<div class=\"decision-callout\">\n\n**Use Forge when** several fields need coordinated validation, submission, dirty/touched state, nested updates, or explicit persistence.\n\n**Use local state when** a form has only one or two fields and no shared validation lifecycle.\n\n</div>\n\n## Installation\n\n```sh\npnpm add @vielzeug/forge\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- `createForm()`: deeply readonly form state with structural sharing and cloned dates\n- `field().field()`: typed nested field handles\n- `patch()`: shallow top-level merge without spread casts\n- `normalize` + `toPlainValues()`: hold domain-model classes in form state\n- Flat `{ path, message }` validation issues\n- Explicit `validate()` and `submit()` timing\n- `/dom`: optional element binding\n- `/schema`: validator-agnostic Standard Schema adapter\n- `/persist`: explicit key/value draft persistence\n- `/form-data`: browser submission serialization\n\n</div>\n\n## Documentation\n\n<div class=\"doc-links\">\n\n- [Usage Guide](./usage.md)\n- [API Reference](./api.md)\n- [Examples](./examples.md)\n- [Migration Guide](./migration.md)\n\n</div>\n\n## See Also\n\n- [Spell](/spell/): Standard Schema-compatible validation.\n- [Vault](/vault/): durable typed storage for drafts.\n- [Assay](/assay/): DOM test helpers for form interaction.\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
5
+ "api": "---\ntitle: 'Forge: API Reference'\ndescription: Immutable typed form state, flat validation issues, and optional integration helpers.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| --------------------------- | ------------------------------------------------ | -------------- | -------------------------------------- |\n| `createForm()` | Create immutable form and field state | Sync | Dispose with its owner |\n| `toPlainValues()` | Flatten class instances to the plain value shape | Sync | Drops circular branches |\n| `validate()` | Run the configured full-form validator | Async | Superseded work returns `aborted` |\n| `submit()` | Validate and submit one captured snapshot | Async | Concurrent submission rejects |\n| `bindField()` | Bind a field to an HTML element | Sync | Caller owns returned cleanup |\n| `schemaValidator()` | Adapt Standard Schema validation | Async | Transform output is not applied |\n| `loadForm()` / `saveForm()` | Explicit key/value draft persistence | Async | Loading will not overwrite newer edits |\n| `toFormData()` | Serialize supported values | Sync | Dotted keys and object arrays reject |\n\n## Package Entry Point\n\n| Import | Purpose |\n| --------------------------- | ---------------------------------- |\n| `@vielzeug/forge` | Form and field state |\n| `@vielzeug/forge/dom` | `bindField()` DOM binding |\n| `@vielzeug/forge/form-data` | `toFormData()` serialization |\n| `@vielzeug/forge/schema` | Standard Schema validation adapter |\n| `@vielzeug/forge/persist` | Explicit draft save/load helpers |\n\n## createForm\n\n```ts\nfunction createForm<TValues extends Record<string, unknown>>(options: FormOptions<TValues>): Form<TValues>;\n```\n\n`initialValues` is required. Validation is explicit and returns flat issues.\n\n```ts\nconst form = createForm({\n initialValues: { email: '' },\n validate: (values) => (values.email.includes('@') ? undefined : [{ path: ['email'], message: 'Invalid email' }]),\n});\n```\n\n`normalize` runs before value validation at every write boundary (`initialValues`, `set`, `patch`, `reset`, `field().set`), so a caller that normalizes once at `createForm` stays correct everywhere. Pair it with `toPlainValues()` to hold domain-model classes in form state.\n\n```ts\nimport { createForm, toPlainValues } from '@vielzeug/forge';\n\nconst form = createForm({ initialValues: { user: new UserModel() }, normalize: toPlainValues });\n\nform.reset({ user: new UserModel() }); // same normalization as init\n```\n\n## toPlainValues\n\n```ts\nfunction toPlainValues<T>(value: T): T;\n```\n\nDeeply converts a value into the plain shape Forge accepts: primitives pass through, `Date` is cloned, `File`/`Blob` keep identity, arrays map, and class instances flatten to their own enumerable entries. Unsafe keys (`__proto__`, `constructor`, `prototype`) are dropped, so the output always passes value validation. The returned type parameter is a convenience cast: the flattened shape differs from the input type whenever class instances are present.\n\nLossy conversions replace the error an un-normalized write would throw: `Map`, `Set`, and other keyless built-ins flatten to `{}`; sparse array slots are dropped, shifting later indexes; `NaN`, `Infinity`, functions, and circular branches become `undefined`. Normalize model classes, not arbitrary graphs.\n\n```ts\nimport { createForm, toPlainValues } from '@vielzeug/forge';\n\nclass UserModel {\n email = '';\n name = '';\n}\n\ntoPlainValues(new UserModel()); // { email: '', name: '' }\nconst form = createForm({ initialValues: { user: new UserModel() }, normalize: toPlainValues });\n```\n\n## Form\n\n```ts\ninterface Form<TValues extends Record<string, unknown>> {\n readonly value: ReadonlyDeep<TValues>;\n readonly state: FormState;\n readonly disposed: boolean;\n readonly disposalSignal: AbortSignal;\n field<K extends keyof TValues & string>(key: K): Field<TValues[K]>;\n set(next: TValues | ((previous: ReadonlyDeep<TValues>) => TValues)): void;\n patch(next: Partial<TValues>): void;\n patch(updater: (previous: ReadonlyDeep<TValues>) => Partial<TValues>): void;\n reset(next?: TValues): void;\n validate(signal?: AbortSignal): Promise<ValidationResult>;\n submit<TResult>(handler, signal?: AbortSignal): Promise<SubmitResult<TResult>>;\n subscribe(listener, options?: { immediate?: boolean }): () => void;\n dispose(): void;\n [Symbol.dispose](): void;\n}\n```\n\n`validate()` and `submit()` return `{ status: 'valid' }`, `{ status: 'invalid', issues }`, or `{ status: 'aborted' }`. Successful submission returns `{ status: 'ok', value }`. Submission handlers receive the exact snapshot that passed validation. `form.state` retains one stable reference until the next transition for framework external-store adapters.\n\n`patch()` shallow-merges top-level keys: `form.patch({ count: 1 })` equals `form.set((prev) => ({ ...prev, count: 1 }))` without the `as T` cast a spread requires. Nested values replace by identity; there is no deep merge.\n\n```ts\ntype FormState = Readonly<{\n formError: string | undefined;\n hasErrors: boolean;\n issues: readonly ValidationIssue[] | undefined;\n submitCount: number;\n submitting: boolean;\n touched: boolean;\n validity: 'invalid' | 'unknown' | 'valid';\n validating: boolean;\n}>;\n```\n\n## Field\n\n```ts\ninterface Field<Value> {\n readonly value: ReadonlyDeep<Value>;\n readonly state: FieldState<Value>;\n readonly dirty: boolean;\n readonly touched: boolean;\n readonly error: string | undefined;\n field(keyOrIndex): Field<unknown>;\n set(next: Value | ((previous: Value) => Value)): void;\n reset(): void;\n touch(): void;\n subscribe(listener, options?: { immediate?: boolean }): () => void;\n}\n```\n\nNested `field().field()` handles avoid string paths while preserving type inference.\n\n## Value types\n\n```ts\ntype Atomic = Date | File | Blob;\ntype ReadonlyDate = Omit<Date, Extract<keyof Date, `set${string}`>>;\ntype ReadonlyDeep<T> = T extends Date\n ? ReadonlyDate\n : T extends File | Blob\n ? T\n : T extends readonly (infer Item)[]\n ? readonly ReadonlyDeep<Item>[]\n : T extends Record<string, unknown>\n ? { readonly [K in keyof T]: ReadonlyDeep<T[K]> }\n : T;\n```\n\nForge clones valid dates, preserves binary identity, freezes plain containers, and rejects unsupported, circular, sparse, or non-finite values.\n\n## ValidationIssue\n\n```ts\ntype ValidationIssue = Readonly<{\n path: readonly (string | number)[];\n message: string;\n}>;\n```\n\n`path: []` denotes a form-level issue. A field derives its first matching error from the flat issue list.\n\n## bindField\n\n```ts\nimport { bindField } from '@vielzeug/forge/dom';\n\nconst stop = bindField(input, form.field('email'), {\n read: (element) => element.value,\n write: (element, value) => {\n element.value = value;\n },\n});\n```\n\nThe binding reads the configured event (`input` by default), marks the field touched on blur, writes external state changes, and returns cleanup.\n\n## schemaValidator\n\n```ts\nimport { schemaValidator } from '@vielzeug/forge/schema';\n\nconst form = createForm({\n initialValues: { email: '' },\n validate: schemaValidator(UserSchema),\n});\n```\n\nAccepts any Standard Schema-compatible validator. Portable issues are copied into Forge-owned immutable `{ path, message }` values. Cancellation settles promptly, although the underlying schema operation may continue. Successful transformed output is intentionally not written into the form.\n\n## Draft persistence\n\n```ts\nimport { loadForm, saveForm } from '@vielzeug/forge/persist';\n\nawait saveForm(form, store, 'profile');\nawait loadForm(form, store, 'profile', { signal });\n```\n\nThe store is a structural key/value contract: `get(key)` and `put(key, value)`, sync or async. Saved drafts are the form values themselves; `loadForm` restores only plain objects and reports anything else as missing. The optional signal and form disposal cancel pending work; a load returns `false` when values changed before the draft arrived.\n\n## FormData\n\n```ts\nimport { toFormData } from '@vielzeug/forge/form-data';\n\nconst body = toFormData(form.value);\n```\n\nFlattens nested plain objects to dotted keys and repeats scalar or binary array entries. Dots in object keys and nested objects or arrays inside arrays throw `ForgeConfigError` to prevent ambiguous or lossy output.\n\n## Errors\n\n- `ForgeError`: base package error.\n- `ForgeConfigError`: invalid value, path, issue, or serialization configuration.\n- `ForgeDisposedError`: operation attempted after disposal.\n- `ForgeSubmitError`: concurrent submission attempt.\n- `ForgeValidationError`: unexpected validator execution failure, with the original `cause`.\n",
6
+ "usage": "---\ntitle: 'Forge: Usage Guide'\ndescription: Build, validate, submit, bind, and persist typed forms with Forge.\n---\n\n[[toc]]\n\n## Basic Usage\n\n```ts\nimport { createForm } from '@vielzeug/forge';\n\nconst form = createForm({\n initialValues: {\n email: '',\n profile: { name: '' },\n },\n});\n```\n\nRead `form.value` for the current deeply readonly snapshot. Use `set()` for whole-form replacement and field handles for focused updates.\n\n```ts\nform.field('email').set('ada@example.com');\nform.field('profile').field('name').set('Ada');\n```\n\n`patch()` shallow-merges top-level keys without the cast a spread `set()` needs:\n\n```ts\nform.patch({ email: 'ada@example.com' }); // siblings keep their values\n```\n\n## Hold domain-model classes\n\nForge values must be plain JSON-safe data. When your app stores class instances (models, DTOs with behavior), pass `normalize: toPlainValues` once at `createForm`; it runs before validation at every write boundary: init, `set`, `patch`, `reset`, and nested `field().set`, so a reset with fresh models behaves like init.\n\n```ts\nimport { createForm, toPlainValues } from '@vielzeug/forge';\n\nclass ProviderUserModel {\n id: number;\n email = '';\n constructor(id: number) {\n this.id = id;\n }\n}\n\nconst form = createForm<{ users: ProviderUserModel[] }>({\n initialValues: { users: [new ProviderUserModel(1)] },\n normalize: toPlainValues,\n});\n\nform.field('users').field(0).set(new ProviderUserModel(2)); // flattened like init\nform.reset({ users: [new ProviderUserModel(3)] }); // flattened like init\n// Rebuild models at submit:\nawait form.submit((values) => send(values.users.map((u) => new ProviderUserModel(u.id))));\n```\n\nWithout `normalize`, a rejected write throws `ForgeConfigError` naming the offending path (for example `list[0]`).\n\n## Validate explicitly\n\nValidators return a flat issue list. Forge does not choose blur/change/submit policy for the application.\n\n```ts\nconst form = createForm({\n initialValues: { email: '', password: '' },\n validate: (values) => {\n const issues = [];\n if (!values.email.includes('@')) issues.push({ path: ['email'], message: 'Invalid email' });\n if (values.password.length < 12) issues.push({ path: ['password'], message: 'Use at least 12 characters' });\n return issues.length ? issues : undefined;\n },\n});\n\nconst result = await form.validate();\nif (result.status === 'invalid') console.log(result.issues);\n```\n\nA field's `error` is derived from the first issue whose path equals that field path. Use `path: []` for form-level failures.\n\n## Submit\n\n```ts\nconst result = await form.submit(async (values, signal) => {\n const response = await fetch('/profile', {\n body: JSON.stringify(values),\n method: 'POST',\n signal,\n });\n return response.json();\n});\n\nif (result.status === 'ok') console.log(result.value);\n```\n\n`submit()` validates first, passes the exact validated snapshot to the handler, prevents duplicate active submissions, and reports aborts explicitly.\n\n## Bind an element\n\n```ts\nimport { bindField } from '@vielzeug/forge/dom';\n\nconst stop = bindField(input, form.field('email'), {\n read: (element) => element.value,\n write: (element, value) => {\n element.value = value;\n },\n});\n```\n\nCall `stop()` when the element owner unmounts.\n\n## Use a Standard Schema validator\n\n```ts\nimport { schemaValidator } from '@vielzeug/forge/schema';\n\nconst form = createForm({\n initialValues: { email: '' },\n validate: schemaValidator(UserSchema),\n});\n```\n\nSpell schemas implement Standard Schema directly. Forge uses the schema result only for success and issues; transformations do not replace form values. Cancellation settles Forge promptly even when underlying validator work cannot be stopped.\n\n## Persist a draft\n\n```ts\nimport { type FormDraftStore, loadForm, saveForm } from '@vielzeug/forge/persist';\n\nconst store: FormDraftStore = {\n get: async (key) => JSON.parse((await localStorage.getItem(key)) ?? 'null'),\n put: async (key, value) => localStorage.setItem(key, JSON.stringify(value)),\n};\n\nawait saveForm(form, store, 'profile');\nawait loadForm(form, store, 'profile', { signal });\n```\n\nPersistence remains explicit. The store owns durability and serialization format; Forge owns the draft shape, which is the form values themselves. Loading returns `false` rather than overwriting edits made while storage was pending, and it never restores a draft that is not a plain object.\n\n## Serialize FormData\n\n```ts\nimport { toFormData } from '@vielzeug/forge/form-data';\n\nawait fetch('/profile', { body: toFormData(form.value), method: 'POST' });\n```\n\nObject keys containing dots and arrays containing nested objects reject instead of producing ambiguous or lossy entries.\n\n## Dispose\n\n```ts\nform.dispose();\n```\n\nDisposal settles active Forge validation and signals active submission/persistence work and clears subscribers. It does not dispose borrowed validators, stores, or DOM elements.\n\n## Framework Integration\n\nInject an owner-scoped form and subscribe to its stable `FormState` snapshot.\n\n::: code-group\n\n```tsx [React]\nimport { useSyncExternalStore } from 'react';\nimport type { Form } from '@vielzeug/forge';\n\nexport function useFormState<T extends Record<string, unknown>>(form: Form<T>) {\n return useSyncExternalStore(\n form.subscribe,\n () => form.state,\n () => form.state,\n );\n}\n```\n\nWhen the component is the form's sole owner, create it in a ref and skip explicit disposal: writes on a disposed form throw `ForgeDisposedError`, which is what a StrictMode double-mount hits when effect cleanup disposes a ref-held form that survives the remount. Garbage collection reclaims a sole-subscriber form; dispose explicitly only when external subscribers or in-flight work need teardown.\n\n```ts [Vue]\nimport { onUnmounted, shallowRef } from 'vue';\nimport type { Form } from '@vielzeug/forge';\n\nexport function useFormState<T extends Record<string, unknown>>(form: Form<T>) {\n const state = shallowRef(form.state);\n const stop = form.subscribe(\n (next) => {\n state.value = next;\n },\n { immediate: true },\n );\n onUnmounted(stop);\n return state;\n}\n```\n\n```ts [Svelte]\nimport type { Form } from '@vielzeug/forge';\n\nexport const formState = <T extends Record<string, unknown>>(form: Form<T>) => ({\n subscribe(run: (state: Form<T>['state']) => void) {\n return form.subscribe(run, { immediate: true });\n },\n});\n```\n\n:::\n\nThe owner that creates the form disposes it. Framework subscriptions own only their unsubscribe callbacks.\n\n## Working with Other Vielzeug Libraries\n\n- Pass Spell schemas to `schemaValidator()` through Standard Schema.\n- Wrap Vault stores in a small `FormDraftStore` adapter for `loadForm()` and `saveForm()`.\n- Bind Ore or native controls with `bindField()` and owner cleanup.\n\n## Best Practices\n\n- Keep validation timing in the UI layer.\n- Return flat issues rather than shape-coupled error trees.\n- Use field handles instead of string paths.\n- Decode persisted/network data at its boundary.\n- Dispose forms with their owner.\n",
7
7
  "examples": "---\ntitle: 'Forge: Examples'\ndescription: Practical immutable form recipes.\n---\n\n## Examples\n\n- [Login form](./examples/login-form.md)\n- [Conditional values](./examples/form-with-conditional-fields.md)\n- [Dynamic arrays](./examples/dynamic-form-fields.md)\n- [Contact form with file upload](./examples/contact-form-with-file-upload.md)\n- [Registration form](./examples/registration-form.md)\n- [Multi-step wizard](./examples/multi-step-wizard.md)\n- [Search form with debounce](./examples/search-form-with-debounce.md)\n"
8
8
  },
9
9
  "examples": [
@@ -2,8 +2,8 @@
2
2
  "apiSource": "export { createBus } from './bus';\nexport { BusDisposedError, HeraldError } from './errors';\nexport type {\n Bus,\n BusOptions,\n EventKey,\n EventMap,\n HeraldEvent,\n Listener,\n SubscribeOptions,\n Unsubscribe,\n WaitAnyResult,\n} from './types';\n",
3
3
  "docs": {
4
4
  "index": "---\ntitle: 'Herald: Typed event bus for TypeScript'\ndescription: Typed synchronous event delivery with wildcard subscriptions, one-shot waits, tracing, and AbortSignal lifecycle.\npackage: herald\ncategory: events\nkeywords: [event-bus, typed-events, pub-sub, async-wait, abort-signal]\nrelated: [ripple, wayfinder, familiar]\nexports: [createBus, HeraldError, BusDisposedError]\nenvironments: [browser, node, ssr, deno]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"herald\" />\n\n## Why Herald?\n\nRaw event emitters lose payload inference and leave one-shot waiting, cancellation, diagnostics, and teardown to every caller. Herald keeps events temporal: use [Ripple](/ripple/) when you need retained state.\n\n```ts\n// Before\nconst listeners = new Set<(payload: unknown) => void>();\nlisteners.add((payload) => loadProfile((payload as { id: string }).id));\n\n// After\nimport { createBus } from '@vielzeug/herald';\n\ninterface AppEvents {\n 'user:login': { id: string };\n}\n\nfunction loadProfile(id: string): void {\n console.log(id);\n}\n\nconst bus = createBus<AppEvents>();\nbus.on('user:login', ({ id }) => loadProfile(id));\n```\n\nDelivery is synchronous and temporal: events are not retained or replayed. Listener failures do not stop later listeners; `emit()` rethrows the first failure after dispatch, while `tap()` exposes every failure for diagnostics.\n\n| Feature | Herald | mitt | EventEmitter3 |\n| ------------------------ | -------------------------------------------- | ----------------------------------------------------- | ----------------------------------------------------- |\n| Bundle size | <PackageInfo package=\"herald\" type=\"size\" /> | ~200 B | ~1.5 kB |\n| Typed payloads | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"triangle-alert\" size=\"16\"></ore-icon> | <ore-icon name=\"triangle-alert\" size=\"16\"></ore-icon> |\n| One-shot async wait | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> |\n| AbortSignal lifecycle | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> |\n| Runtime activity tracing | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> |\n| Zero dependencies | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n\n<div class=\"decision-callout\">\n\n**Use Herald when** modules need typed temporal event delivery with owned lifecycle.\n\n**Consider Ripple when** consumers need current state and replayed values.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/herald\n```\n\n```sh [npm]\nnpm install @vielzeug/herald\n```\n\n```sh [yarn]\nyarn add @vielzeug/herald\n```\n\n:::\n\n## Quick Start\n\n```ts\nimport { createBus } from '@vielzeug/herald';\n\ninterface AppEvents {\n 'user:login': { id: string };\n 'user:logout': void;\n}\n\nconst bus = createBus<AppEvents>();\nconst stop = bus.on('user:login', ({ id }) => console.log(id));\n\nbus.emit('user:login', { id: '42' });\nstop();\nbus.dispose();\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- `on()` / `once()`: typed subscriptions with explicit teardown\n- `onAny()`: cross-cutting event observation\n- `tap()`: observe bus activity for logging and diagnostics\n- `wait()` / `waitAny()`: one-shot async coordination\n- `listenerCount()` / `wildcardCount()` / `eventNames()`: listener inspection\n- `error` tap events: isolate listener failures without interrupting delivery\n- `AbortSignal`: subscription, wait, tap, and disposal ownership\n- `createTestBus()`: emitted-payload recording for tests\n\n</div>\n\n## Documentation\n\n<div class=\"doc-links\">\n\n- [Usage Guide](./usage.md)\n- [API Reference](./api.md)\n- [Examples](./examples.md)\n- [Migration Guide](./migration.md)\n\n</div>\n\n## See Also\n\n<div class=\"see-also\">\n\n- [Ripple](/ripple/): retained reactive state.\n- [Wayfinder](/wayfinder/): route lifecycle events.\n- [Familiar](/familiar/): worker completion events.\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
5
- "api": "---\ntitle: 'Herald: API Reference'\ndescription: Reference for typed synchronous events, subscriptions, waits, tracing, lifecycle, and test helpers.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution | Common gotcha |\n| ---------------------- | --------------------------------- | --------- | ------------------------------------------------------------------ |\n| `createBus()` | Create a typed temporal event bus | Sync | Events are not retained or replayed |\n| `emit()` | Deliver one event | Sync | Returns `void`; rethrows the first listener failure after dispatch |\n| `on()` / `once()` | Subscribe to one event | Sync | Keep the unsubscribe function or pass a signal |\n| `onAny()` | Subscribe to every event | Sync | Payload is `unknown` |\n| `wait()` / `waitAny()` | Await future one-shot events | Async | Disposal and external abort reject the promise |\n| `tap()` | Observe bus runtime activity | Sync | Tap-handler failures are swallowed |\n| `createTestBus()` | Record emitted payloads | Sync | Import from `/testing` |\n\n## Package Entry Points\n\n| Import | Purpose |\n| -------------------------- | ----------------------------------------- |\n| `@vielzeug/herald` | Bus factory, errors, and public bus types |\n| `@vielzeug/herald/testing` | `createTestBus()` and `TestBus` |\n\n## `createBus()`\n\n```ts\nfunction createBus<T extends EventMap = Record<string, unknown>>(options?: BusOptions): Bus<T>;\n```\n\nCreates a synchronous bus for future event delivery. Construction has no external side effects.\n\n```ts\nimport { createBus } from '@vielzeug/herald';\n\ninterface Events {\n count: number;\n ready: void;\n}\n\nconst bus = createBus<Events>({ maxListeners: 20, name: 'worker' });\nbus.emit('count', 1);\nbus.emit('ready');\nbus.dispose();\n```\n\n### `BusOptions`\n\n```ts\ntype BusOptions = {\n maxListeners?: number;\n name?: string;\n};\n```\n\n| Field | Description |\n| -------------- | ---------------------------------------------------------------------------------------------------------------------------- |\n| `maxListeners` | Development warning threshold applied separately to one event's listeners and wildcard listeners. Omit to disable the check. |\n| `name` | Display name included in disposal errors and listener-threshold warnings. |\n\n## `Bus`\n\n```ts\ntype Bus<T extends EventMap> = {\n [Symbol.dispose](): void;\n readonly disposalSignal: AbortSignal;\n dispose(): void;\n readonly disposed: boolean;\n emit<K extends EventKey<T>>(event: K, ...args: T[K] extends void ? [] : [payload: T[K]]): void;\n eventNames(): EventKey<T>[];\n listenerCount(event?: EventKey<T>): number;\n on<K extends EventKey<T>>(event: K, listener: Listener<T[K]>, options?: SubscribeOptions): Unsubscribe;\n onAny(listener: (event: EventKey<T>, payload: unknown) => void, options?: SubscribeOptions): Unsubscribe;\n once<K extends EventKey<T>>(event: K, listener: Listener<T[K]>, options?: { signal?: AbortSignal }): Unsubscribe;\n tap(handler: (event: HeraldEvent<T>) => void, options?: { signal?: AbortSignal }): Unsubscribe;\n wait<K extends EventKey<T>>(event: K, options?: { signal?: AbortSignal }): Promise<T[K]>;\n waitAny<const K extends readonly EventKey<T>[]>(\n events: K,\n options?: { signal?: AbortSignal },\n ): Promise<WaitAnyResult<T, K>>;\n wildcardCount(): number;\n};\n```\n\n### `emit()`\n\nCalls a snapshot of event-specific listeners synchronously, then wildcard listeners, then emits an `emit` trace event. It always returns `void`. Synchronous listener failures produce `error` trace events without stopping delivery; after dispatch, the first failure is rethrown.\n\nAfter disposal, emission is a no-op.\n\n### `on()` and `once()`\n\n```ts\ntype Listener<T> = (payload: T) => void;\ntype SubscribeOptions = { signal?: AbortSignal };\ntype Unsubscribe = () => void;\n```\n\n`on()` returns an idempotent unsubscribe function. `once()` is the one-shot variant: it unsubscribes before invoking the listener. An already-aborted signal creates no subscription.\n\n### `onAny()`\n\nReceives `(event, payload)` after event-specific listeners and supports `signal`. Wildcard listeners are excluded from `listenerCount()` and reported by `wildcardCount()`.\n\n### `wait()`\n\nResolves with the next payload for one event. It rejects with the external signal's reason when aborted, or `BusDisposedError` when bus disposal wins. Earlier emissions are not replayed.\n\n### `waitAny()`\n\nAccepts one or more event keys. It resolves once with a typed `{ event, payload }` discriminated union and removes every losing subscription.\n\n```ts\nconst result = await bus.waitAny(['count', 'ready']);\nif (result.event === 'count') console.log(result.payload);\n```\n\n### Listener inspection\n\n- `listenerCount(event)` returns specific listeners for one key.\n- `listenerCount()` returns all specific listeners.\n- `wildcardCount()` returns `onAny()` listeners.\n- `eventNames()` returns keys with active specific listeners.\n\n### `tap()`\n\nObserves runtime activity without affecting delivery. It returns an idempotent unsubscribe function and accepts an ownership signal. Tap-handler errors are swallowed.\n\n```ts\nconst stop = bus.tap((event) => {\n if (event.type === 'error') recordListenerFailure(event.error);\n});\n```\n\n### Disposal\n\n`dispose()` is permanent and idempotent. It emits a final `dispose` trace event, aborts `disposalSignal` with `BusDisposedError`, rejects pending waits, removes subscriptions, and clears taps. `[Symbol.dispose]()` delegates to it.\n\n## Runtime Events\n\n```ts\ntype HeraldEvent<T extends EventMap = EventMap> =\n | { readonly event: EventKey<T>; readonly listeners: number; readonly payload: unknown; readonly type: 'emit' }\n | { readonly event: EventKey<T>; readonly type: 'subscribe' }\n | { readonly event: EventKey<T>; readonly type: 'unsubscribe' }\n | { readonly type: 'subscribe-any' }\n | { readonly type: 'unsubscribe-any' }\n | { readonly error: unknown; readonly event: EventKey<T>; readonly type: 'error' }\n | { readonly type: 'dispose' };\n```\n\n`listeners` on an `emit` event counts every specific and wildcard listener invoked, including listeners that threw. Runtime events intentionally contain no timestamp; observers can add one using their own clock.\n\n## Shared Types\n\n```ts\ntype EventMap = object;\ntype EventKey<T extends EventMap> = Extract<keyof T, string>;\n\ntype WaitAnyResult<T extends EventMap, K extends readonly EventKey<T>[]> = {\n [I in keyof K]: K[I] extends EventKey<T> ? { event: K[I]; payload: T[K[I]] } : never;\n}[number];\n```\n\nInterfaces and object type aliases are valid event maps. Only string keys participate in the bus API.\n\n## Testing\n\n### `createTestBus()`\n\n```ts\nimport { createTestBus } from '@vielzeug/herald/testing';\n\nfunction createTestBus<T extends EventMap = Record<string, unknown>>(options?: BusOptions): TestBus<T>;\n```\n\nCreates a regular bus that records every dispatched payload through a `tap()` observer, including dispatches whose listeners throw.\n\n### `TestBus`\n\n```ts\ntype TestBus<T extends EventMap> = Bus<T> & {\n allEmitted(): { [K in EventKey<T>]?: T[K][] };\n emitted<K extends EventKey<T>>(event: K): T[K][];\n emittedCount<K extends EventKey<T>>(event: K): number;\n reset(): void;\n};\n```\n\n`emitted()` and `allEmitted()` return array snapshots. `reset()` clears records without affecting subscriptions. Disposal clears records and the underlying bus. To prevent prototype mutation in the returned plain object, `allEmitted()` omits records named `__proto__`, `constructor`, or `prototype`; `emitted(event)` remains available for those keys.\n\n## Errors\n\n| Error | Trigger | Notable properties |\n| ------------------ | ------------------------------------------------------------------------- | ------------------------------------------ |\n| `BusDisposedError` | Bus disposal aborts `disposalSignal` or interrupts `wait()` / `waitAny()` | Configured bus name appears in the message |\n| `HeraldError` | Base class for Herald-originated errors | Use `instanceof HeraldError` |\n",
6
- "usage": "---\ntitle: 'Herald: Usage Guide'\ndescription: Define typed events, own subscriptions, await one-shot events, trace failures, and test emissions.\n---\n\n[[toc]]\n\n## Basic Usage\n\nUse an interface or object type whose string keys are event names and whose values are payloads. Use `void` or `undefined` for payloadless events.\n\n```ts\nimport { createBus } from '@vielzeug/herald';\n\ninterface AppEvents {\n 'cart:updated': { count: number };\n 'user:logout': void;\n}\n\nusing bus = createBus<AppEvents>({ name: 'app' });\nconst stop = bus.on('cart:updated', ({ count }) => console.log(count));\n\nbus.emit('cart:updated', { count: 1 });\nbus.emit('user:logout');\nstop();\n```\n\n`emit()` calls listeners synchronously and returns `void`. Event-specific listeners run before wildcard listeners. Events emitted without listeners are discarded.\n\n## Own Subscription Lifetimes\n\nKeep the returned unsubscribe function or bind a subscription to an `AbortSignal`. `once()` unsubscribes before invoking the listener.\n\n```ts\nconst controller = new AbortController();\n\nbus.on('cart:updated', renderCart, { signal: controller.signal });\nbus.once('user:logout', clearSession);\n\ncontroller.abort();\n```\n\nAn already-aborted signal creates no subscription and returns an idempotent no-op unsubscribe function.\n\n## Observe Every Event\n\nUse `onAny()` for cross-cutting application behavior. Wildcard listeners receive the event key and untyped payload after event-specific listeners.\n\n```ts\nconst stop = bus.onAny((event, payload) => {\n audit(event, payload);\n});\n\nstop();\n```\n\n`wildcardCount()` reports wildcard listeners separately from `listenerCount()`.\n\n## Await One Event\n\n`wait()` resolves on the next matching event. `waitAny()` accepts one or more keys and returns a discriminated union.\n\n```ts\nconst cart = await bus.wait('cart:updated', { signal: AbortSignal.timeout(5_000) });\nconst result = await bus.waitAny(['cart:updated', 'user:logout'], {\n signal: AbortSignal.timeout(5_000),\n});\n\nif (result.event === 'cart:updated') console.log(result.payload.count);\n```\n\nThese methods do not replay earlier events. External cancellation rejects with the signal reason. Bus disposal rejects pending waits with `BusDisposedError`.\n\n## Handle Listener Failures\n\nListener exceptions do not prevent remaining specific or wildcard listeners from running. Each failure produces a `error` tap event, then `emit()` rethrows the first error after dispatch.\n\n```ts\nconst stopTrace = bus.tap((event) => {\n if (event.type === 'error') {\n recordListenerFailure(event.error);\n }\n});\n\nstopTrace();\n```\n\nHerald captures synchronous listener throws only, and `tap()` does not suppress the error rethrown after dispatch. A listener that starts asynchronous work must handle its own rejected promises.\n\n## Trace Bus Activity\n\n`tap()` observes subscriptions, unsubscriptions, wildcard subscriptions, emissions, listener failures, and disposal without changing bus behavior. Tap-handler failures are swallowed.\n\n```ts\nconst stopTrace = bus.tap(\n (event) => {\n recordHeraldEvent(event);\n },\n { signal: owner.signal },\n);\n```\n\nAn `emit` trace includes the event key, payload, and number of specific plus wildcard listeners invoked. Trace events do not include timestamps; add them in the observer if needed.\n\n## Inspect Listeners\n\n```ts\nbus.listenerCount('cart:updated'); // specific listeners for this key\nbus.listenerCount(); // all specific listeners\nbus.wildcardCount(); // onAny listeners\nbus.eventNames(); // keys with active specific listeners\n```\n\n`eventNames()` does not include events that only have wildcard listeners.\n\n## Dispose the Bus\n\n`dispose()` is permanent and idempotent. It emits a final tap event, aborts `disposalSignal` with `BusDisposedError`, clears all listeners and taps, and rejects pending waits. Later subscriptions and emissions are no-ops.\n\n```ts\nusing scopedBus = createBus<AppEvents>({ name: 'checkout' });\nscopedBus.disposalSignal.addEventListener('abort', () => releaseOwnedWork());\n```\n\nThe configured name appears in disposal errors and listener-threshold warnings.\n\n## Test Emissions\n\nImport test helpers from the focused testing entry point.\n\n```ts\nimport { createTestBus } from '@vielzeug/herald/testing';\n\nusing testBus = createTestBus<AppEvents>();\ntestBus.emit('cart:updated', { count: 2 });\n\nexpect(testBus.emitted('cart:updated')).toEqual([{ count: 2 }]);\nexpect(testBus.emittedCount('cart:updated')).toBe(1);\nexpect(testBus.allEmitted()).toEqual({ 'cart:updated': [{ count: 2 }] });\n\ntestBus.reset();\n```\n\nReturned recordings are snapshots. `reset()` clears recording history without removing listeners; disposal clears both.\n\n## Working with Other Vielzeug Libraries\n\nUse Herald for temporal facts, Ripple for retained state, Rune for structured logging inside `tap()`, and Postmaster when work must survive reloads or retry durably.\n\n## Best Practices\n\n- Define one explicit event map per module or application boundary.\n- Emit facts, not mutable retained state.\n- Keep synchronous listeners short.\n- Handle rejected promises inside asynchronous listener work.\n- Keep unsubscribe functions or pass ownership signals.\n- Use `wait()` and `waitAny()` only for future one-shot events.\n- Install a `tap()` observer when listener failures must be visible.\n- Dispose owner-scoped buses.\n",
5
+ "api": "---\ntitle: 'Herald: API Reference'\ndescription: Reference for typed synchronous events, subscriptions, waits, tracing, lifecycle, and test helpers.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution | Common gotcha |\n| ---------------------- | --------------------------------- | --------- | ------------------------------------------------------------------ |\n| `createBus()` | Create a typed temporal event bus | Sync | Events are not retained or replayed |\n| `emit()` | Deliver one event | Sync | Returns `void`; rethrows the first listener failure after dispatch |\n| `on()` / `once()` | Subscribe to one event | Sync | Keep the unsubscribe function or pass a signal |\n| `onAny()` | Subscribe to every event | Sync | Payload is `unknown` |\n| `wait()` / `waitAny()` | Await future one-shot events | Async | Disposal and external abort reject the promise |\n| `tap()` | Observe bus runtime activity | Sync | Tap-handler failures are swallowed |\n| `createTestBus()` | Record emitted payloads | Sync | Import from `/testing` |\n\n## Package Entry Points\n\n| Import | Purpose |\n| -------------------------- | ----------------------------------------- |\n| `@vielzeug/herald` | Bus factory, errors, and public bus types |\n| `@vielzeug/herald/testing` | `createTestBus()` and `TestBus` |\n\n## `createBus()`\n\n```ts\nfunction createBus<T extends EventMap = Record<string, unknown>>(options?: BusOptions): Bus<T>;\n```\n\nCreates a synchronous bus for future event delivery. Construction has no external side effects.\n\n```ts\nimport { createBus } from '@vielzeug/herald';\n\ninterface Events {\n count: number;\n ready: void;\n}\n\nconst bus = createBus<Events>({ maxListeners: 20, name: 'worker' });\nbus.emit('count', 1);\nbus.emit('ready');\nbus.dispose();\n```\n\n### `BusOptions`\n\n```ts\ntype BusOptions = {\n maxListeners?: number;\n name?: string;\n};\n```\n\n| Field | Description |\n| -------------- | ---------------------------------------------------------------------------------------------------------------------------- |\n| `maxListeners` | Development warning threshold applied separately to one event's listeners and wildcard listeners. Omit to disable the check. |\n| `name` | Display name included in disposal errors and listener-threshold warnings. |\n\n## `Bus`\n\n```ts\ntype Bus<T extends EventMap> = {\n [Symbol.dispose](): void;\n readonly disposalSignal: AbortSignal;\n dispose(): void;\n readonly disposed: boolean;\n emit<K extends EventKey<T>>(event: K, ...args: T[K] extends void ? [] : [payload: T[K]]): void;\n eventNames(): EventKey<T>[];\n listenerCount(event?: EventKey<T>): number;\n on<K extends EventKey<T>>(event: K, listener: Listener<T[K]>, options?: SubscribeOptions): Unsubscribe;\n onAny(listener: (event: EventKey<T>, payload: unknown) => void, options?: SubscribeOptions): Unsubscribe;\n once<K extends EventKey<T>>(event: K, listener: Listener<T[K]>, options?: SubscribeOptions): Unsubscribe;\n tap(handler: (event: HeraldEvent<T>) => void, options?: SubscribeOptions): Unsubscribe;\n wait<K extends EventKey<T>>(event: K, options?: SubscribeOptions): Promise<T[K]>;\n waitAny<const K extends readonly EventKey<T>[]>(events: K, options?: SubscribeOptions): Promise<WaitAnyResult<T, K>>;\n wildcardCount(): number;\n};\n```\n\n### `emit()`\n\nCalls a snapshot of event-specific listeners synchronously, then wildcard listeners, then emits an `emit` trace event. It always returns `void`. Synchronous listener failures produce `error` trace events without stopping delivery; after dispatch, the first failure is rethrown.\n\nAfter disposal, emission is a no-op.\n\n### `on()` and `once()`\n\n```ts\ntype Listener<T> = (payload: T) => void;\ntype SubscribeOptions = { signal?: AbortSignal };\ntype Unsubscribe = () => void;\n```\n\n`SubscribeOptions` is the single options type for every subscription-shaped method: `on`, `once`, `onAny`, `tap`, `wait`, and `waitAny`. `on()` returns an idempotent unsubscribe function. `once()` is the one-shot variant: it unsubscribes before invoking the listener. An already-aborted signal creates no subscription.\n\n### `onAny()`\n\nReceives `(event, payload)` after event-specific listeners and supports `signal`. Wildcard listeners are excluded from `listenerCount()` and reported by `wildcardCount()`.\n\n### `wait()`\n\nResolves with the next payload for one event. It rejects with the external signal's reason when aborted, or `BusDisposedError` when bus disposal wins. Earlier emissions are not replayed.\n\n### `waitAny()`\n\nAccepts one or more event keys. It resolves once with a typed `{ event, payload }` discriminated union and removes every losing subscription. An empty list throws a synchronous `TypeError`.\n\n```ts\nconst result = await bus.waitAny(['count', 'ready']);\nif (result.event === 'count') console.log(result.payload);\n```\n\n### Listener inspection\n\n- `listenerCount(event)` returns specific listeners for one key.\n- `listenerCount()` returns all specific listeners.\n- `wildcardCount()` returns `onAny()` listeners.\n- `eventNames()` returns keys with active specific listeners.\n\n### `tap()`\n\nObserves runtime activity without affecting delivery. It returns an idempotent unsubscribe function and accepts an ownership signal. Tap-handler errors are swallowed.\n\n```ts\nconst stop = bus.tap((event) => {\n if (event.type === 'error') recordListenerFailure(event.error);\n});\n```\n\n### Disposal\n\n`dispose()` is permanent and idempotent. It emits a final `dispose` trace event, aborts `disposalSignal` with `BusDisposedError`, rejects pending waits, removes subscriptions, and clears taps. `[Symbol.dispose]()` delegates to it.\n\n## Runtime Events\n\n```ts\ntype HeraldEvent<T extends EventMap = EventMap> =\n | { readonly event: EventKey<T>; readonly listeners: number; readonly payload: unknown; readonly type: 'emit' }\n | { readonly event: EventKey<T>; readonly type: 'subscribe' }\n | { readonly event: EventKey<T>; readonly type: 'unsubscribe' }\n | { readonly type: 'subscribe-any' }\n | { readonly type: 'unsubscribe-any' }\n | { readonly error: unknown; readonly event: EventKey<T>; readonly type: 'error' }\n | { readonly type: 'dispose' };\n```\n\n`listeners` on an `emit` event counts every specific and wildcard listener invoked, including listeners that threw. Runtime events intentionally contain no timestamp; observers can add one using their own clock.\n\n## Shared Types\n\n```ts\ntype EventMap = object;\ntype EventKey<T extends EventMap> = Extract<keyof T, string>;\n\ntype WaitAnyResult<T extends EventMap, K extends readonly EventKey<T>[]> = {\n [I in keyof K]: K[I] extends EventKey<T> ? { event: K[I]; payload: T[K[I]] } : never;\n}[number];\n```\n\nInterfaces and object type aliases are valid event maps. Only string keys participate in the bus API.\n\n## Testing\n\n### `createTestBus()`\n\n```ts\nimport { createTestBus } from '@vielzeug/herald/testing';\n\nfunction createTestBus<T extends EventMap = Record<string, unknown>>(options?: BusOptions): TestBus<T>;\n```\n\nCreates a regular bus that records every dispatched payload through a `tap()` observer, including dispatches whose listeners throw.\n\n### `TestBus`\n\n```ts\ntype TestBus<T extends EventMap> = Bus<T> & {\n allEmitted(): { [K in EventKey<T>]?: T[K][] };\n emitted<K extends EventKey<T>>(event: K): T[K][];\n emittedCount<K extends EventKey<T>>(event: K): number;\n reset(): void;\n};\n```\n\n`emitted()` and `allEmitted()` return array snapshots. `reset()` clears records without affecting subscriptions. Disposal clears records and the underlying bus. To prevent prototype mutation in the returned plain object, `allEmitted()` omits records named `__proto__`, `constructor`, or `prototype`; `emitted(event)` remains available for those keys.\n\n## Errors\n\n| Error | Trigger | Notable properties |\n| ------------------ | ------------------------------------------------------------------------- | ------------------------------------------ |\n| `BusDisposedError` | Bus disposal aborts `disposalSignal` or interrupts `wait()` / `waitAny()` | Configured bus name appears in the message |\n| `HeraldError` | Base class for Herald-originated errors | Use `instanceof HeraldError` |\n",
6
+ "usage": "---\ntitle: 'Herald: Usage Guide'\ndescription: Define typed events, own subscriptions, await one-shot events, trace failures, and test emissions.\n---\n\n[[toc]]\n\n## Basic Usage\n\nUse an interface or object type whose string keys are event names and whose values are payloads. Use `void` or `undefined` for payloadless events.\n\n```ts\nimport { createBus } from '@vielzeug/herald';\n\ninterface AppEvents {\n 'cart:updated': { count: number };\n 'user:logout': void;\n}\n\nusing bus = createBus<AppEvents>({ name: 'app' });\nconst stop = bus.on('cart:updated', ({ count }) => console.log(count));\n\nbus.emit('cart:updated', { count: 1 });\nbus.emit('user:logout');\nstop();\n```\n\n`emit()` calls listeners synchronously and returns `void`. Event-specific listeners run before wildcard listeners. Events emitted without listeners are discarded.\n\n## Own Subscription Lifetimes\n\nKeep the returned unsubscribe function or bind a subscription to an `AbortSignal`. `once()` unsubscribes before invoking the listener.\n\n```ts\nconst controller = new AbortController();\n\nbus.on('cart:updated', renderCart, { signal: controller.signal });\nbus.once('user:logout', clearSession);\n\ncontroller.abort();\n```\n\nAn already-aborted signal creates no subscription and returns an idempotent no-op unsubscribe function.\n\n## Observe Every Event\n\nUse `onAny()` for cross-cutting application behavior. Wildcard listeners receive the event key and untyped payload after event-specific listeners.\n\n```ts\nconst stop = bus.onAny((event, payload) => {\n audit(event, payload);\n});\n\nstop();\n```\n\n`wildcardCount()` reports wildcard listeners separately from `listenerCount()`.\n\n## Await One Event\n\n`wait()` resolves on the next matching event. `waitAny()` accepts one or more keys and returns a discriminated union.\n\n```ts\nconst cart = await bus.wait('cart:updated', { signal: AbortSignal.timeout(5_000) });\nconst result = await bus.waitAny(['cart:updated', 'user:logout'], {\n signal: AbortSignal.timeout(5_000),\n});\n\nif (result.event === 'cart:updated') console.log(result.payload.count);\n```\n\nThese methods do not replay earlier events. External cancellation rejects with the signal reason. Bus disposal rejects pending waits with `BusDisposedError`. `waitAny()` with an empty event list throws a synchronous `TypeError`.\n\n## Handle Listener Failures\n\nListener exceptions do not prevent remaining specific or wildcard listeners from running. Each failure produces a `error` tap event, then `emit()` rethrows the first error after dispatch.\n\n```ts\nconst stopTrace = bus.tap((event) => {\n if (event.type === 'error') {\n recordListenerFailure(event.error);\n }\n});\n\nstopTrace();\n```\n\nHerald captures synchronous listener throws only, and `tap()` does not suppress the error rethrown after dispatch. A listener that starts asynchronous work must handle its own rejected promises.\n\n## Trace Bus Activity\n\n`tap()` observes subscriptions, unsubscriptions, wildcard subscriptions, emissions, listener failures, and disposal without changing bus behavior. Tap-handler failures are swallowed.\n\n```ts\nconst stopTrace = bus.tap(\n (event) => {\n recordHeraldEvent(event);\n },\n { signal: owner.signal },\n);\n```\n\nAn `emit` trace includes the event key, payload, and number of specific plus wildcard listeners invoked. Trace events do not include timestamps; add them in the observer if needed.\n\n## Inspect Listeners\n\n```ts\nbus.listenerCount('cart:updated'); // specific listeners for this key\nbus.listenerCount(); // all specific listeners\nbus.wildcardCount(); // onAny listeners\nbus.eventNames(); // keys with active specific listeners\n```\n\n`eventNames()` does not include events that only have wildcard listeners.\n\n## Dispose the Bus\n\n`dispose()` is permanent and idempotent. It emits a final tap event, aborts `disposalSignal` with `BusDisposedError`, clears all listeners and taps, and rejects pending waits. Later subscriptions and emissions are no-ops.\n\n```ts\nusing scopedBus = createBus<AppEvents>({ name: 'checkout' });\nscopedBus.disposalSignal.addEventListener('abort', () => releaseOwnedWork());\n```\n\nThe configured name appears in disposal errors and listener-threshold warnings.\n\n## Test Emissions\n\nImport test helpers from the focused testing entry point.\n\n```ts\nimport { createTestBus } from '@vielzeug/herald/testing';\n\nusing testBus = createTestBus<AppEvents>();\ntestBus.emit('cart:updated', { count: 2 });\n\nexpect(testBus.emitted('cart:updated')).toEqual([{ count: 2 }]);\nexpect(testBus.emittedCount('cart:updated')).toBe(1);\nexpect(testBus.allEmitted()).toEqual({ 'cart:updated': [{ count: 2 }] });\n\ntestBus.reset();\n```\n\nReturned recordings are snapshots. `reset()` clears recording history without removing listeners; disposal clears both.\n\n## Working with Other Vielzeug Libraries\n\nUse Herald for temporal facts, Ripple for retained state, Rune for structured logging inside `tap()`, and Postmaster when work must survive reloads or retry durably.\n\n## Best Practices\n\n- Define one explicit event map per module or application boundary.\n- Emit facts, not mutable retained state.\n- Keep synchronous listeners short.\n- Handle rejected promises inside asynchronous listener work.\n- Keep unsubscribe functions or pass ownership signals.\n- Use `wait()` and `waitAny()` only for future one-shot events.\n- Install a `tap()` observer when listener failures must be visible.\n- Dispose owner-scoped buses.\n",
7
7
  "examples": "---\ntitle: 'Herald: Examples'\ndescription: Recipes for typed delivery, waits, lifecycle ownership, diagnostics, bridging, and testing.\n---\n\n## Examples\n\n- [Standalone Bus](./examples/standalone-entry.md)\n- [Module-Level Bus](./examples/module-level-bus.md)\n- [Await a One-Time Event](./examples/awaiting-a-one-time-event.md)\n- [Inspect Listener Counts](./examples/inspecting-listener-counts.md)\n- [Observe Listener Failures](./examples/custom-error-boundary.md)\n- [Handle Disposal in Async Code](./examples/handling-disposal-in-async-code.md)\n- [Scope a Bus to a Request](./examples/request-scoping.md)\n- [Consume Ongoing Events](./examples/streaming-with-events.md)\n- [Bridge Buses Explicitly](./examples/bus-bridging-with-pipeevents.md)\n- [Test with `createTestBus()`](./examples/testing-with-createtestbus.md)\n"
8
8
  },
9
9
  "examples": [
@@ -4,7 +4,7 @@
4
4
  "index": "---\ntitle: 'Ledger: Reversible async history'\ndescription: Serialized reversible command history with cancellation ownership and atomic reactive snapshots.\npackage: ledger\ncategory: utilities\nkeywords: [undo, redo, history, commands, async, reactive, ripple]\nexports:\n [\n compose,\n createLedger,\n LedgerError,\n LedgerCancelledError,\n LedgerConfigError,\n LedgerDisposedError,\n LedgerExecutionError,\n LedgerRollbackError,\n ]\nrelated: [ripple, keymap, forge, vault]\nenvironments: [browser, node, ssr, deno]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"ledger\" />\n\n## Why Ledger?\n\nUndo and redo require more than array manipulation when operations are asynchronous, cancellable, and visible in a UI. Ledger serializes only reversible commands, owns queue lifecycle, and publishes one atomic framework-neutral state snapshot without a reactive runtime dependency.\n\n```ts\n// Before\nconst undo = () => changes.pop()?.revert();\n\n// After\nimport { createLedger } from '@vielzeug/ledger';\n\nconst ledger = createLedger();\nawait ledger.do({ apply: saveNext, revert: restorePrevious });\nawait ledger.undo();\n```\n\n| Feature | Roll your own | Ledger |\n| ----------------------- | ----------------------- | -------------------------------------------- |\n| Bundle size | 0 B | <PackageInfo package=\"ledger\" type=\"size\" /> |\n| Reversible history | Manual arrays | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n| Serialized async work | Manual queue | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n| Queue cancellation | Manual ownership | Abort-aware lifecycle |\n| Framework-neutral state | Manual events | Structural `Subscribable<LedgerState>` |\n| Composition | Custom transaction code | `compose()` |\n\n<div class=\"decision-callout\">\n\n**Use Ledger when** you own reversible asynchronous state transitions and need undo, redo, or history UI.\n\n**Consider direct application code when** work is irreversible, fire-and-forget, or does not need history.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/ledger\n```\n\n```sh [npm]\nnpm install @vielzeug/ledger\n```\n\n```sh [yarn]\nyarn add @vielzeug/ledger\n```\n\n:::\n\n## Quick Start\n\nSubmit a reversible command, read state, then dispose its owner.\n\n```ts\nimport { createLedger } from '@vielzeug/ledger';\n\nlet value = 'before';\nconst ledger = createLedger();\n\nawait ledger.do({\n apply: () => {\n value = 'after';\n },\n label: 'Rename value',\n revert: () => {\n value = 'before';\n },\n});\n\nawait ledger.undo();\nconsole.log(ledger.state.getSnapshot().undo.length); // 0\nledger.dispose();\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- `createLedger()`: Create serialized reversible command history\n- `state`: Read atomic queue, undo, redo, and acceptance state\n- `compose()`: Combine reversible commands into one reversible command\n- `whenIdle()`: Await queued and active operation settlement\n- `LedgerCancelledError`: Distinguish cancellation from execution failure\n- `maxHistory`: Keep a non-negative safe-integer undo depth\n- `[Symbol.dispose]()`: Seal, abort, and clear a ledger owner\n\n</div>\n\n## Documentation\n\n<div class=\"doc-links\">\n\n- [Usage Guide](./usage.md)\n- [API Reference](./api.md)\n- [Examples](./examples.md)\n- [Migration Guide](./migration.md)\n\n</div>\n\n## See Also\n\n<div class=\"see-also\">\n\n- [Ripple](/ripple/): Project Ledger's structural state readable into a signal when reactive derivations are needed.\n- [Keymap](/keymap/): Route undo and redo shortcuts to a Ledger error boundary.\n- [Forge](/forge/): Record reversible form transitions.\n- [Vault](/vault/): Persist application snapshots outside transient undo history.\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
5
5
  "api": "---\ntitle: 'Ledger: API Reference'\ndescription: Reference for serialized reversible commands, history state, composition, cancellation, disposal, and errors.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution | Common gotcha |\n| -------------------------- | --------------------------------------- | ----------------- | ------------------------------------------- |\n| `createLedger()` | Create serialized reversible history | Sync construction | Every operation method is queued |\n| `compose()` | Combine commands into one history entry | Sync construction | Child metadata is not aggregated |\n| `ledger.do()` | Apply and record a command | Async | Failed or cancelled apply is not recorded |\n| `ledger.undo()` / `redo()` | Move the latest history entry | Async | Failures leave history on its original side |\n| `ledger.clear()` | Remove history without reverting | Async | Serialized behind earlier work |\n| `ledger.whenIdle()` | Await an empty operation queue | Async | Cannot force non-cooperative work to settle |\n\n## Package Entry Point\n\n| Import | Purpose |\n| ------------------ | -------------------------------------------------------------------------------------------------------------- |\n| `@vielzeug/ledger` | Complete Ledger runtime, error hierarchy, state-readable contract, unsubscribe type, and command/history types |\n\n## `createLedger()`\n\n```ts\nfunction createLedger<TMeta = undefined>(options?: LedgerOptions): Ledger<TMeta>;\n```\n\nCreates a ledger with one submission-order operation queue and one atomic state readable.\n\n```ts\nimport { createLedger } from '@vielzeug/ledger';\n\nconst ledger = createLedger<{ field: string }>({ maxHistory: 50 });\n```\n\n### `LedgerOptions`\n\n```ts\ninterface LedgerOptions {\n maxHistory?: number;\n}\n```\n\n`maxHistory` defaults to `100`. It must be a non-negative safe integer. `0` executes commands without retaining history.\n\n## `compose()`\n\n```ts\nfunction compose<TMeta = undefined>(\n commands: readonly ReversibleCommand<TMeta>[],\n label?: string,\n): ReversibleCommand<TMeta>;\n```\n\nSnapshots child command callbacks, applies children in order, and reverts them in reverse order. The result creates one history entry with the supplied label and `meta: undefined`.\n\nIf child application fails, completed children are compensated in reverse order. Compensation attempts continue after failures. Combined apply and compensation failures are preserved in an `AggregateError`, which Ledger exposes as `LedgerExecutionError.cause`. Normal composed reversion also attempts every child and reports failures through `LedgerRollbackError.cause` as an `AggregateError`.\n\n## `Ledger`\n\n```ts\ninterface Ledger<TMeta = undefined> {\n clear(): Promise<void>;\n readonly disposalSignal: AbortSignal;\n dispose(): void;\n readonly disposed: boolean;\n do(command: ReversibleCommand<TMeta>, options?: LedgerCallOptions): Promise<void>;\n redo(options?: LedgerCallOptions): Promise<void>;\n readonly state: Subscribable<LedgerState<TMeta>>;\n undo(options?: LedgerCallOptions): Promise<void>;\n whenIdle(): Promise<void>;\n [Symbol.dispose](): void;\n}\n```\n\nAll operation methods are serialized in call order.\n\n### `do()`\n\nSnapshots the command's `apply`, `revert`, `label`, and metadata reference when submitted. On successful apply it appends one undo entry, evicts the oldest entry beyond `maxHistory`, and clears redo history. Apply failure rejects with `LedgerExecutionError` and records nothing. Ledger does not automatically revert a failed individual command.\n\n### `undo()`\n\nReverts the final undo entry. Success moves it to the end of redo history. If no undo entry exists, the queued operation resolves without changing history. Revert failure rejects with `LedgerRollbackError` and leaves the entry in undo history.\n\n### `redo()`\n\nApplies the final redo entry. Success moves it to the end of undo history. If no redo entry exists, it resolves without changing history. Apply failure rejects with `LedgerExecutionError` and leaves the entry in redo history.\n\n### `record()`\n\nAppends an already-executed command to undo history synchronously, without running it through the queue. For stores that execute their own writes: typically synchronous, embedded state stores: `undo()` calls the recorded `revert`, and `redo()` calls the recorded `apply`, so `apply` must be able to re-apply the effect. Recording shares `do()`'s bookkeeping: it clears redo history and evicts the oldest entry beyond `maxHistory`. It throws `LedgerDisposedError` on a disposed ledger.\n\n### `clear()`\n\nQueues removal of all undo and redo entries. It does not call command revert functions and does not cancel earlier work. When history is already empty it resolves without queueing; after disposal it rejects with `LedgerDisposedError`.\n\n### `whenIdle()`\n\nResolves immediately when `queued` and `running` are zero, otherwise resolves after both reach zero. Multiple waiters are supported. It rejects with `LedgerDisposedError` when the ledger is disposed, immediately or while waiting.\n\n### Disposal\n\n`dispose()` is permanent and idempotent. It clears undo and redo history, aborts active command contexts, rejects queued operations that have not started with `LedgerDisposedError`, and rejects pending `whenIdle()` waiters. Active commands must observe their signal and settle before `running` reaches zero. Read `disposed` to detect permanent disposal. `[Symbol.dispose]()` delegates to `dispose()`.\n\n## Command Types\n\n### `ReversibleCommand`\n\n```ts\ninterface ReversibleCommand<TMeta = undefined> {\n readonly apply: (context: CommandContext) => Promise<void> | void;\n readonly label?: string;\n readonly meta?: TMeta;\n readonly revert: (context: CommandContext) => Promise<void> | void;\n}\n```\n\n`apply` and `revert` may be synchronous or asynchronous. Metadata is retained by reference; Ledger does not deep-clone or deep-freeze it.\n\n### `CommandContext`\n\n```ts\ninterface CommandContext {\n readonly signal: AbortSignal;\n}\n```\n\nThe signal combines ledger disposal with the operation signal. Queued cancellation prevents user code from running. Active cancellation is cooperative. If user code ignores abort and completes, the operation still rejects with `LedgerCancelledError` and its history transition is not committed.\n\n### `LedgerCallOptions`\n\n```ts\ninterface LedgerCallOptions {\n signal?: AbortSignal;\n}\n```\n\nSupported by `do()`, `undo()`, and `redo()`. `clear()` has no call options.\n\n## State Types\n\n### `LedgerState`\n\n```ts\ninterface LedgerState<TMeta = undefined> {\n readonly queued: number;\n readonly redo: readonly HistoryEntry<TMeta>[];\n readonly running: number;\n readonly undo: readonly HistoryEntry<TMeta>[];\n}\n```\n\n| Field | Meaning |\n| --------- | ----------------------------------------------------------------------- |\n| `queued` | Submitted operations that have not started |\n| `running` | Currently executing operation; serialization keeps this at 0 or 1 |\n| `undo` | Chronological successfully applied history; final entry is next to undo |\n| `redo` | Chronological reverted history; final entry is next to redo |\n\nState objects and history arrays are frozen replacements.\n\n### `HistoryEntry`\n\n```ts\ninterface HistoryEntry<TMeta = undefined> {\n readonly label: string | undefined;\n readonly meta: TMeta | undefined;\n}\n```\n\nHistory entries are frozen and intentionally omit command callbacks.\n\n### `Subscribable` and `Unsubscribe`\n\n`Ledger.state` implements this framework-neutral structural contract, which matches `Subscribable` in `@vielzeug/arsenal`. Both names are root type exports.\n\n```ts\ntype Unsubscribe = () => void;\n\ninterface Subscribable<T> {\n getSnapshot(): T;\n subscribe(listener: () => void): Unsubscribe;\n}\n```\n\nSubscriptions are not immediate and receive no value argument. Listeners run synchronously from a snapshot after state replacement. A listener failure does not interrupt Ledger bookkeeping or later listeners; it is rethrown in a microtask.\n\n## Errors\n\n| Error | Trigger | History result |\n| ---------------------- | ------------------------------------------------------------- | ------------------------------------------ |\n| `LedgerCancelledError` | Queued signal cancellation or active cooperative cancellation | No transition committed |\n| `LedgerDisposedError` | Submission after disposal or queued work rejected by disposal | History already cleared by disposal |\n| `LedgerExecutionError` | `apply()` fails during `do()` or `redo()` | New command absent, or redo entry retained |\n| `LedgerRollbackError` | `revert()` fails during `undo()` | Undo entry retained |\n| `LedgerConfigError` | Invalid `maxHistory` | Construction fails |\n| `LedgerError` | Base class and internal history corruption | Depends on operation |\n\nWrapped operation failures preserve the original value in `.cause`. Use `instanceof LedgerError` to catch the hierarchy, then narrow to a specific subtype.\n",
6
6
  "usage": "---\ntitle: 'Ledger: Usage Guide'\ndescription: Record reversible commands, observe serialized history, handle failures, and own cancellation and disposal.\n---\n\n[[toc]]\n\n## Basic Usage\n\nCapture both sides of a reversible transition before submitting it.\n\n```ts\nimport { createLedger } from '@vielzeug/ledger';\n\nusing ledger = createLedger();\nconst item = { name: 'Old name' };\nconst previous = item.name;\nconst next = 'New name';\n\nawait ledger.do({\n apply: () => {\n item.name = next;\n },\n label: 'Rename item',\n revert: () => {\n item.name = previous;\n },\n});\n\nawait ledger.undo();\nawait ledger.redo();\n```\n\nAll `do()`, `undo()`, `redo()`, and `clear()` calls join one submission-order queue. Keep irreversible effects outside commands unless they have a real compensating operation.\n\n## Read Atomic State\n\n`state` is a framework-neutral `Subscribable`, not a Ripple signal. Read `getSnapshot()`, and subscribe to invalidation callbacks.\n\n```ts\nfunction renderHistory(): void {\n const { queued, redo, running, undo } = ledger.state.getSnapshot();\n undoButton.disabled = undo.length === 0 || ledger.disposed;\n redoButton.disabled = redo.length === 0 || ledger.disposed;\n spinner.hidden = queued + running === 0;\n}\n\nrenderHistory();\nconst stop = ledger.state.subscribe(renderHistory);\n```\n\nSubscriptions are not immediate and receive no value argument. They run synchronously from a listener snapshot after every state replacement. A failure is rethrown in a microtask without interrupting Ledger bookkeeping or later subscribers.\n\nState objects, history arrays, and history entries are frozen snapshots. `undo` and `redo` are chronological; the next command to undo or redo is the final item. Metadata values are retained by reference rather than deep-cloned.\n\n## Attach History Metadata\n\nSet `label` for presentation and use the ledger's metadata type for application context.\n\n```ts\nconst ledger = createLedger<{ field: string }>();\n\nawait ledger.do({\n apply: () => {\n form.email = next;\n },\n label: 'Edit email',\n meta: { field: 'email' },\n revert: () => {\n form.email = previous;\n },\n});\n\nconsole.log(ledger.state.getSnapshot().undo.at(-1));\n```\n\nLedger snapshots command callbacks, label, and metadata references when `do()` is submitted. Later mutation of the command object does not replace the captured callbacks.\n\n## Compose Reversible Commands\n\n`compose()` produces one command and one history entry. Children apply in order and revert in reverse order.\n\n```ts\nimport { compose } from '@vielzeug/ledger';\n\nawait ledger.do(\n compose(\n [\n {\n apply: () => {\n node.x = nextX;\n },\n revert: () => {\n node.x = previousX;\n },\n },\n {\n apply: () => {\n node.y = nextY;\n },\n revert: () => {\n node.y = previousY;\n },\n },\n ],\n 'Move node',\n ),\n);\n```\n\nIf a child apply fails, already-applied children are compensated in reverse order. Compensation continues after failures. If application and compensation both fail, `LedgerExecutionError.cause` is an `AggregateError` containing all failures. A composed command records the supplied label but does not aggregate child metadata.\n\n## Handle Operation Failures\n\n```ts\nimport { LedgerCancelledError, LedgerExecutionError, LedgerRollbackError } from '@vielzeug/ledger';\n\ntry {\n await ledger.undo();\n} catch (error) {\n if (error instanceof LedgerCancelledError) {\n // Expected cancellation.\n } else if (error instanceof LedgerRollbackError) {\n showUndoError(error.cause);\n } else if (error instanceof LedgerExecutionError) {\n showApplyError(error.cause);\n } else {\n throw error;\n }\n}\n```\n\nA failed `do()` is not recorded and is not automatically reverted. A failed `undo()` remains in undo history; a failed `redo()` remains in redo history, allowing retry after the underlying problem is corrected.\n\n## Cancel Work\n\nPass a signal per operation. Queued cancellation prevents user code from starting. Active work receives a combined signal and must stop cooperatively.\n\n```ts\nconst controller = new AbortController();\nconst operation = ledger.do(\n {\n apply: ({ signal }) => saveDraft(nextDraft, { signal }),\n revert: ({ signal }) => saveDraft(previousDraft, { signal }),\n },\n { signal: controller.signal },\n);\n\ncontroller.abort();\nawait operation.catch(handleHistoryFailure);\n```\n\nIf active user code ignores cancellation and finishes, Ledger rejects with `LedgerCancelledError` and does not record or move history. It does not compensate partial effects automatically, so command implementations must check or forward `context.signal` before committing changes.\n\n## Record Externally Executed Work\n\nWhen a synchronous store owns its writes, execute first and record the reversible entry afterwards: `undo()` calls the recorded `revert`, `redo()` calls the recorded `apply`, so `apply` must be able to re-apply the effect.\n\n```ts\nconst previous = item.name;\n\nitem.name = next; // the store's own synchronous write\nledger.record({\n apply: () => {\n item.name = next;\n },\n label: 'rename item',\n revert: () => {\n item.name = previous;\n },\n});\n```\n\nRecording is synchronous and shares `do()`'s bookkeeping: it clears redo history and evicts the oldest entry beyond `maxHistory`.\n\n## Limit and Clear History\n\n`maxHistory` defaults to `100` and accepts non-negative safe integers. Successful commands beyond the cap evict the oldest undo entries. `0` executes commands without retaining undo or redo history.\n\n```ts\nconst ledger = createLedger({ maxHistory: 30 });\nawait ledger.clear();\n```\n\n`clear()` is serialized behind earlier work and clears both history arrays without reverting commands.\n\n## Drain and Dispose\n\n`whenIdle()` resolves when both `queued` and `running` reach zero. It does not cancel work.\n\n```ts\nconst operation = ledger.do(command);\nconst idle = ledger.whenIdle();\n\nledger.dispose();\nawait operation.catch(handleHistoryFailure);\nawait idle;\n```\n\nDisposal is permanent and idempotent. It clears history, aborts active contexts, rejects queued work with `LedgerDisposedError`, and rejects pending `whenIdle()` waiters. Read `disposed` to detect it. Active operations settle cooperatively; `whenIdle()` waits for them. Work that never settles can keep `whenIdle()` pending.\n\n## Framework Integration\n\nKeep one ledger per owning scope and adapt its structural readable through the framework's subscription API.\n\n::: code-group\n\n```tsx [React]\nimport { useEffect, useMemo, useSyncExternalStore } from 'react';\nimport { createLedger } from '@vielzeug/ledger';\n\nexport function UndoStatus() {\n const ledger = useMemo(() => createLedger(), []);\n const state = useSyncExternalStore(\n (notify) => ledger.state.subscribe(notify),\n () => ledger.state.getSnapshot(),\n () => ledger.state.getSnapshot(),\n );\n\n useEffect(() => () => ledger.dispose(), [ledger]);\n return (\n <span>\n {state.undo.length} undo / {state.redo.length} redo\n </span>\n );\n}\n```\n\n```ts [Vue 3]\nimport { onUnmounted, shallowRef } from 'vue';\nimport { createLedger } from '@vielzeug/ledger';\n\nconst ledger = createLedger();\nconst state = shallowRef(ledger.state.getSnapshot());\nconst stop = ledger.state.subscribe(() => {\n state.value = ledger.state.getSnapshot();\n});\n\nonUnmounted(() => {\n stop();\n ledger.dispose();\n});\n```\n\n```ts [Ripple]\nimport { signal } from '@vielzeug/ripple';\nimport { createLedger } from '@vielzeug/ledger';\n\nconst ledger = createLedger();\nconst state = signal(ledger.state.getSnapshot());\nconst stop = ledger.state.subscribe(() => {\n state.value = ledger.state.getSnapshot();\n});\n\nfunction dispose(): void {\n stop();\n ledger.dispose();\n}\n```\n\n:::\n\n## Working with Other Vielzeug Libraries\n\nUse Keymap to route keyboard shortcuts into `undo()` and `redo()`. Project `ledger.state` into Ripple when reactive derivations are needed. Persist application snapshots with Vault; Ledger history itself is transient.\n\n## Best Practices\n\n- Capture previous and next values before submitting a command.\n- Keep irreversible effects outside Ledger commands.\n- Forward or check `context.signal` in asynchronous command work.\n- Catch every operation promise at the application boundary.\n- Read one `state` snapshot per render.\n- Keep state subscribers synchronous and handle failures through the application's global error boundary.\n- Use `whenIdle()` before releasing owners that require a drain boundary.\n- Dispose each owner-scoped ledger.\n",
7
- "examples": "---\ntitle: 'Ledger: Examples'\ndescription: Recipes for reversible editor and form history with Ledger.\n---\n\n## Examples\n\n- [Text Editor History](./examples/text-editor.md)\n- [Form History](./examples/form-history.md)\n"
7
+ "examples": "---\ntitle: 'Ledger: Examples'\ndescription: Recipes for reversible editor and form history with Ledger.\n---\n\n## Examples\n\n- [Text Editor History](./examples/text-editor.md)\n- [JSON Delta History](./examples/json-delta-history.md)\n- [Form History](./examples/form-history.md)\n"
8
8
  },
9
9
  "examples": [
10
10
  {