@vielzeug/codex 26.11.12 → 26.11.13

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 (63) hide show
  1. package/data/catalog.json +181 -61
  2. package/data/llms-full.txt +1546 -918
  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/lingua.json +37 -42
  15. package/data/packages/patchwork.json +45 -0
  16. package/data/packages/postmaster.json +8 -8
  17. package/data/packages/refine.json +2 -2
  18. package/data/packages/scribe.json +57 -0
  19. package/data/packages/sentinel.json +1 -1
  20. package/data/packages/sourcerer.json +2 -2
  21. package/data/packages/tabula.json +40 -0
  22. package/data/packages/tavern.json +20 -18
  23. package/data/packages/tempo.json +48 -63
  24. package/data/packages/vault.json +29 -31
  25. package/data/packages/wayfinder.json +3 -6
  26. package/data/refine.json +76 -0
  27. package/dist/catalog.d.ts +13 -1
  28. package/dist/catalog.js +80 -53
  29. package/dist/catalog.js.map +1 -1
  30. package/dist/cli.js +5 -5
  31. package/dist/cli.js.map +1 -1
  32. package/dist/errors.js +0 -1
  33. package/dist/errors.js.map +1 -1
  34. package/dist/http.d.ts +0 -1
  35. package/dist/http.js +0 -5
  36. package/dist/http.js.map +1 -1
  37. package/dist/index.d.ts +5 -5
  38. package/dist/index.js +3 -3
  39. package/dist/index.js.map +1 -1
  40. package/dist/port.js +2 -2
  41. package/dist/port.js.map +1 -1
  42. package/dist/server.d.ts +5 -3
  43. package/dist/server.js +10 -6
  44. package/dist/server.js.map +1 -1
  45. package/dist/snapshot.d.ts +11 -8
  46. package/dist/snapshot.js +24 -128
  47. package/dist/snapshot.js.map +1 -1
  48. package/dist/tools/index.d.ts +0 -2
  49. package/dist/tools/index.js +0 -2
  50. package/dist/tools/index.js.map +1 -1
  51. package/dist/tools/refine.d.ts +2 -2
  52. package/dist/tools/refine.js.map +1 -1
  53. package/dist/types.d.ts +2 -30
  54. package/dist/types.js +1 -1
  55. package/package.json +2 -13
  56. package/skills/vielzeug/SKILL.md +3 -0
  57. package/data/search.json +0 -1688
  58. package/dist/refine-catalog.d.ts +0 -15
  59. package/dist/refine-catalog.js +0 -27
  60. package/dist/refine-catalog.js.map +0 -1
  61. package/dist/refine.d.ts +0 -7
  62. package/dist/refine.js +0 -9
  63. package/dist/refine.js.map +0 -1
package/data/llms.txt CHANGED
@@ -1,6 +1,6 @@
1
1
  # Vielzeug
2
2
 
3
- > 43 focused TypeScript packages. Version: 26.11.11
3
+ > 46 focused TypeScript packages. Version: 26.11.12
4
4
 
5
5
  Install any package independently: `pnpm add @vielzeug/<name>`
6
6
 
@@ -30,6 +30,7 @@ Install any package independently: `pnpm add @vielzeug/<name>`
30
30
  - [@vielzeug/necromancer](/necromancer/): Lifecycle-owned Web Animations API primitives for native playback, groups, and additive FLIP transitions.
31
31
  - [@vielzeug/orbit](/orbit/): Floating positioning with lifecycle-owned geometry and middleware.
32
32
  - [@vielzeug/ore](/ore/): Functional custom-element authoring with typed props, reactive templates, lifecycle helpers, and testing utilities.
33
+ - [@vielzeug/patchwork](/patchwork/): RFC 6902 JSON Patch: structural diff, immutable apply, and guarded tryApply for sync protocols.
33
34
  - [@vielzeug/postmaster](/postmaster/): Typed durable job outbox with leased processing, retries, and dead-letter recovery for browser applications.
34
35
  - [@vielzeug/prism](/prism/): Responsive SVG charts with explicit updates: line, bar, area, scatter, pie, radar, heatmap, sparkline
35
36
  - [@vielzeug/pulse](/pulse/): Explicitly connected, typed WebSocket sessions with scoped channels, ref-counted rooms with reactive presence, reconnect restoration, and heartbeat.
@@ -38,11 +39,13 @@ Install any package independently: `pnpm add @vielzeug/<name>`
38
39
  - [@vielzeug/rune](/rune/): Browser/Node logger with levels, namespaces, pluggable transports, lazy bindings, and timing helpers.
39
40
  - [@vielzeug/sandbox](/sandbox/): Isolated iframe runtime with a typed state bridge and explicit message trust boundary for safe execution of untrusted HTML: component previews, playgrounds, plugin sandboxes, and more.
40
41
  - [@vielzeug/scout](/scout/): Trigram-indexed fuzzy search with per-field weights, match highlighting, and an optional reactive layer.
42
+ - [@vielzeug/scribe](/scribe/): Safe Markdown prose: deterministic parser, XSS-safe DOM and HTML renderers, outline and plain-text extraction
41
43
  - [@vielzeug/scroll](/scroll/): Lightweight, dependency-free virtual list engine with variable heights, sticky headers, grids, and external-store integration.
42
44
  - [@vielzeug/sentinel](/sentinel/): Subscribable browser and DOM snapshots for viewport, network, media query, element size, intersection state, and screen wake lock.
43
45
  - [@vielzeug/sigil](/sigil/): QR code generation and scanning: pure matrix encoder, SVG and canvas renderers, native BarcodeDetector scanning
44
46
  - [@vielzeug/sourcerer](/sourcerer/): Framework-agnostic collection pagination and observable single-value resources.
45
47
  - [@vielzeug/spell](/spell/): Zero-dependency schema validation with explicit async checks, Standard Schema interoperability, and JSON Schema export.
48
+ - [@vielzeug/tabula](/tabula/): Typed CSV and TSV: RFC 4180 parser with schema-validated rows, streaming reader, and safe serializer.
46
49
  - [@vielzeug/tandem](/tandem/): Offline-first sync engine with rev baselines, tombstoned deletions, and idle-batched pushes for browser applications.
47
50
  - [@vielzeug/tavern](/tavern/): Table sessions over mesh: host-owned state replication with guest command forwarding
48
51
  - [@vielzeug/tempo](/tempo/): Explicit Temporal parsing, timezone-safe arithmetic, and localized date/time formatting for TypeScript.
@@ -1,8 +1,4 @@
1
1
  {
2
- "catalog": "catalog.json",
3
- "contentDirectory": "packages",
4
- "refine": "refine.json",
5
- "schemaVersion": 1,
6
- "search": "search.json",
7
- "version": "26.11.11"
2
+ "schemaVersion": 2,
3
+ "version": "26.11.12"
8
4
  }
@@ -68,7 +68,7 @@
68
68
  "ArchiveSort": "export type ArchiveSort = 'liked' | 'recent';",
69
69
  "archiveSortSchema": "export const archiveSortSchema: Schema<ArchiveSort> = s.enum(['liked', 'recent'] as const);",
70
70
  "ArchivePage": "export interface ArchivePage<T> {\n /** Cursor for the next page; null after the last. */\n cursor: string | null;\n entries: readonly T[];\n}",
71
- "ArchiveError": "export class ArchiveError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}",
71
+ "ArchiveError": "export class ArchiveError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n }\n}",
72
72
  "ArchiveDefinitionError": "export class ArchiveDefinitionError extends ArchiveError {}",
73
73
  "ArchiveDerivationStage": "export type ArchiveDerivationStage = 'canonicalize' | 'hash' | 'index' | 'schema';",
74
74
  "ArchiveDerivationError": "export class ArchiveDerivationError extends ArchiveError {\n readonly stage: ArchiveDerivationStage;\n\n constructor(stage: ArchiveDerivationStage, message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.stage = stage;\n }\n}"
@@ -1,8 +1,8 @@
1
1
  {
2
- "apiSource": "export * from './array/chunk';\nexport * from './array/filterMap';\nexport * from './array/groupBy';\nexport * from './array/indexBy';\nexport * from './array/paginate';\nexport * from './array/partition';\nexport * from './array/sort';\nexport * from './array/uniq';\nexport * from './async/abortable';\nexport * from './async/abortError';\nexport * from './async/attempt';\nexport * from './async/backoff';\nexport * from './async/parallel';\nexport * from './async/retry';\nexport * from './async/sleep';\nexport * from './async/taskPool';\nexport * from './async/waitFor';\nexport * from './cache/cache';\nexport * from './cache/memo';\nexport * from './encoding/base64url';\nexport * from './encoding/compression';\nexport * from './encoding/share-code';\nexport * from './errors';\nexport * from './function/debounce';\nexport * from './function/once';\nexport * from './function/pipe';\nexport * from './function/tapper';\nexport * from './function/throttle';\nexport * from './guards/combinators';\nexport * from './guards/isDefined';\nexport * from './guards/isEqual';\nexport * from './guards/isNil';\nexport * from './guards/isPlainObject';\nexport * from './math/allocate';\nexport * from './math/clamp';\nexport * from './math/range';\nexport * from './object/getPath';\nexport * from './object/hash';\nexport * from './object/omit';\nexport * from './object/pick';\nexport * from './random/random';\nexport * from './random/source';\nexport * from './string/camelCase';\nexport * from './types';\n",
2
+ "apiSource": "export * from './array/chunk';\nexport * from './array/filterMap';\nexport * from './array/groupBy';\nexport * from './array/indexBy';\nexport * from './array/paginate';\nexport * from './array/partition';\nexport * from './array/sort';\nexport * from './array/uniq';\nexport * from './async/abortable';\nexport * from './async/abortError';\nexport * from './async/attempt';\nexport * from './async/backoff';\nexport * from './async/parallel';\nexport * from './async/retry';\nexport * from './async/sleep';\nexport * from './async/taskPool';\nexport * from './async/timer';\nexport * from './async/waitFor';\nexport * from './cache/cache';\nexport * from './cache/memo';\nexport * from './encoding/base64url';\nexport * from './encoding/compression';\nexport * from './encoding/share-code';\nexport * from './errors';\nexport * from './function/debounce';\nexport * from './function/once';\nexport * from './function/pipe';\nexport * from './function/tapper';\nexport * from './function/throttle';\nexport * from './guards/combinators';\nexport * from './guards/isDefined';\nexport * from './guards/isEqual';\nexport * from './guards/isNil';\nexport * from './guards/isPlainObject';\nexport * from './math/allocate';\nexport * from './math/clamp';\nexport * from './math/range';\nexport * from './object/getPath';\nexport * from './object/hash';\nexport * from './object/omit';\nexport * from './object/pick';\nexport * from './random/random';\nexport * from './random/source';\nexport * from './string/camelCase';\nexport * from './types';\n",
3
3
  "docs": {
4
4
  "index": "---\ntitle: 'Arsenal: Utility library for TypeScript'\ndescription: Tree-shakeable TypeScript utilities with focused category entry points for arrays, async work, caching, objects, strings, math, and guards.\npackage: arsenal\ncategory: utilities\nkeywords: [utility, array, pagination, sorting, string, object, math, async, cache]\nexports: [paginate, sort, retry, taskPool, cache]\nrelated: [tempo, sourcerer, spell, coins]\nenvironments: [browser, node, ssr, deno]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"arsenal\" />\n\n## Why Arsenal?\n\nArsenal provides typed, zero-dependency utilities that reduce repeated application code: collection transforms, numeric operations, retry and cancellation, caching, safe-path traversal, and deterministic serialization. The root stays curated while category entry points expose the broader toolkit. Exact platform aliases remain excluded.\n\n```ts\n// Before\nconst users = JSON.parse(raw).filter((user) => user.name.includes(query));\n\n// After\nimport { fuzzyFilter } from '@vielzeug/arsenal/array';\nimport { tryParseJson } from '@vielzeug/arsenal/object';\n\nconst parsed = tryParseJson(raw);\nconst users = parsed.ok ? fuzzyFilter(parsed.value as User[], query, { select: (user) => user.name }) : [];\n```\n\n| Feature | Arsenal | lodash-es | Remeda |\n| ------------------------- | --------------------------------------------- | -------------------------------------------- | -------------------------------------------- |\n| Bundle size | <PackageInfo package=\"arsenal\" type=\"size\" /> | ~72 kB | ~18 kB |\n| Typed root utilities | <ore-icon name=\"check\" size=\"16\"></ore-icon> | Partial | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n| Category entry points | <ore-icon name=\"check\" size=\"16\"></ore-icon> | Partial | Partial |\n| Async task pool and cache | <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 Arsenal when** you need one typed utility dependency with focused subpaths for specialized behavior.\n\n**Consider narrower alternatives when** you need only platform APIs or a small functional subset.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/arsenal\n```\n\n```sh [npm]\nnpm install @vielzeug/arsenal\n```\n\n```sh [yarn]\nyarn add @vielzeug/arsenal\n```\n\n:::\n\n## Quick Start\n\n```ts\nimport { groupBy, retry } from '@vielzeug/arsenal';\nimport { cache } from '@vielzeug/arsenal/cache';\nimport { taskPool } from '@vielzeug/arsenal/async';\n\nconst byRole = groupBy([{ role: 'admin' }, { role: 'user' }], (user) => user.role);\n\nconst pool = taskPool({ concurrency: 2 });\nconst health = await pool.run((signal) =>\n retry(() => fetch('/health', { signal }).then((response) => response.json())),\n);\n\nconst responses = cache<string, unknown>({ ttlMs: 60_000 });\nconst profile = await responses.getOrLoad('/profile', () => fetch('/profile').then((response) => response.json()));\n\npool.dispose();\nconsole.log(byRole, health, profile);\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- **`retry`**: retry async work with cancellation support from package root\n- **`taskPool`**: bounded, disposable concurrent work from `/async`\n- **`cache`**: identity-keyed TTL cache with async load deduplication from `/cache`\n- **`fuzzyFilter`**: explicit-field fuzzy filtering from `/array`\n- **`tryParseJson`**: preserve JSON syntax failures from `/object`\n- **`allocate`**: lossless proportional distribution from `/math`\n- **`chunk`, `zip`, `compact`**: typed collection transforms from `/array`\n- **`paginate`**: one page plus its totals from an in-memory list, in a one- or zero-based page base\n- **`sort`**: selector, `{ key: direction }`, or ordered grid criteria from one entry point\n- **`range`, `average`, `median`**: common numeric operations from `/math`\n- **`assert`, `tap`**: typed control-flow helpers from `/function`\n- **`isEqual`**: structural equality from package root\n- **`hash`**: deterministic serialization for stable cache keys from `/object`\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- [Spell](/spell/): validate `unknown` JSON data after `tryParseJson`.\n- [Vault](/vault/): persistent storage; Arsenal cache is in-memory only.\n- [Tempo](/tempo/): date/time utilities kept outside Arsenal.\n- [Coins](/coins/): money formatting and currency conversion.\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
5
- "api": "---\ntitle: 'Arsenal: API Reference'\ndescription: Reference for Arsenal root utilities and category entry points.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution | Common gotcha |\n| ----------------------------------- | ---------------------------------------------------------- | --------- | --------------------------------------------------------------------------- |\n| `groupBy` | Group values by key (prototype-pollution guarded) | Sync | Root export |\n| `chunk` / `zip` / `compact` | Typed collection transforms | Sync | Available from `/array` |\n| `paginate` | Cut one page and its totals out of a list | Sync | Pages past the last return empty `items`, unclamped |\n| `sort` | Sort by a selector, keyed fields, or ordered path criteria | Sync | Criteria paths are resolved safely; mixed value types throw |\n| `range` / `average` / `median` | Numeric generation and aggregation | Sync | Available from `/math` |\n| `assert` | Assert and narrow a condition | Sync | Available from `/function` |\n| `retry` | Retry async work | Async | Rethrows final error |\n| `taskPool` | Bound concurrent tasks | Async | Available from `/async` |\n| `cache` | In-memory identity-keyed cache | Async | Available from `/cache` |\n| `fuzzyFilter` | Filter string or selected object fields | Sync | Object collections require `select` |\n| `fuzzyScore` | Rank string or selected object fields | Sync | Object collections require `select` |\n| `tryParseJson` | Preserve JSON syntax result | Sync | Returns `unknown` on success |\n| `getPath` | Optional object lookup (safe-path guarded) | Sync | Available from `/object` |\n| `allocate` | Lossless proportional distribution | Sync | Available from `/math` |\n| `isEqual` | Structural equality | Sync | Root export |\n| `hash` | Deterministic serialization for cache keys | Sync | Available from `/object` |\n| `compressBytes` / `decompressBytes` | Native byte compression with bounded decompression | Async | Requires native compression streams; decoding requires an output limit |\n| `pack` / `unpack` | Versioned, compressed, URL-safe payload envelope | Async | Both sides bound the payload with `maxBytes`; compression falls back to raw |\n\n## Package Entry Points\n\n| Import | Purpose |\n| ---------------------------- | ----------------------------------------------------------------------- |\n| `@vielzeug/arsenal` | Curated common utilities |\n| `@vielzeug/arsenal/array` | Immutable transforms, pagination, set operations, sorting, fuzzy search |\n| `@vielzeug/arsenal/async` | Retry, cancellation, task pool, timing |\n| `@vielzeug/arsenal/cache` | In-memory cache and memoization |\n| `@vielzeug/arsenal/encoding` | Base64url and native byte compression |\n| `@vielzeug/arsenal/function` | Assertions, composition, timing, teardown |\n| `@vielzeug/arsenal/guards` | Type guards, predicate combinators, equality guards |\n| `@vielzeug/arsenal/math` | Ranges, aggregation, statistics, interpolation, exact allocation |\n| `@vielzeug/arsenal/object` | Paths, transforms, hash, JSON parse result |\n| `@vielzeug/arsenal/random` | Cryptographic-entropy selection and shuffle |\n| `@vielzeug/arsenal/string` | Unicode-aware case transforms and similarity |\n\n## Array\n\n### Typed transforms\n\n```ts\nchunk<T>(input: readonly T[], size?: number): T[][]\ncompact<T>(array: readonly T[]): Array<Exclude<T, false | '' | 0 | 0n | null | undefined>>\nfirst<T>(array: readonly T[], fallback?: T): T | undefined\nlast<T>(array: readonly T[], fallback?: T): T | undefined\nreplace<T>(array: readonly T[], predicate: (value: T) => boolean, value: T): T[]\nrotate<T>(array: readonly T[], positions: number, options?: { wrap?: boolean }): T[]\nzip(...arrays): Array<tuple>\nunzip(rows): tupleOfArrays\n```\n\n`take`, `takeLast`, `drop`, and `dropLast` return new arrays and normalize negative counts to zero. Set operations accept optional selectors for object identity.\n\n### paginate\n\n```ts\npaginate<T>(items: readonly T[], options?: PaginateOptions): PageEnvelope<T>\n```\n\nCuts one page out of an in-memory list and returns the items with the arithmetic that produced them. `pageOffset` selects the caller's page base: `1` (default) for one-based paging, `0` for zero-based servers such as Spring. The default `page` is the first page in that base, and the default `pageSize` is `20`. `totalPages` is at least 1, even for an empty list, so `page < totalPages` never underflows. Pages past the last yield empty `items` and echo the requested page rather than clamping it. Throws `TypeError` for a non-array and `RangeError` when `page` is not an integer in the selected base or `pageSize` is not a positive integer.\n\n| Option | Type | Default | Description |\n| ------------ | -------- | --------------------------------- | ------------------------------------------------------------------------ |\n| `page` | `number` | First page in `pageOffset`'s base | Requested page; must be an integer greater than or equal to `pageOffset` |\n| `pageSize` | `number` | `20` | Number of items per page; must be a positive integer |\n| `pageOffset` | `0 \\| 1` | `1` | Page-number base: `0` for zero-based callers, `1` for one-based callers |\n\n```ts\nimport { paginate } from '@vielzeug/arsenal/array';\n\npaginate([1, 2, 3, 4, 5], { page: 2, pageSize: 2 });\n// { items: [3, 4], page: 2, pageSize: 2, totalItems: 5, totalPages: 3 }\n\nconst springPage = 0;\npaginate([1, 2, 3, 4, 5], { page: springPage, pageOffset: 0 });\n// { items: [1, 2, 3, 4, 5], page: 0, pageSize: 20, totalItems: 5, totalPages: 1 }\n```\n\nThe envelope is server-neutral: it models no HTTP dialect, so adapters map their response onto it and map it back out.\n\n### sort\n\n```ts\nsort<T>(array: readonly T[], selector: (item: T) => unknown, direction?: SortDirection): T[];\nsort<T>(array: readonly T[], selectors: SortSelectors<T>): T[];\nsort<T>(array: readonly T[], criteria: ReadonlyArray<SortCriterion<T>>): T[];\n```\n\nThree forms, one entry point. The selector form sorts by one extracted value; the selectors form accepts an object mapping property keys to directions; the criteria form sorts by an ordered list of paths, which is the shape a data grid hands over when its sortable columns are runtime strings.\n\n```ts\nimport { sort } from '@vielzeug/arsenal/array';\n\nconst users = [\n { name: 'Ada', age: 41 },\n { name: 'Grace', age: 30 },\n];\nsort(users, (user) => user.name);\nsort(users, { name: 'asc', age: 'desc' });\n\nconst rows = [\n { address: { city: 'Berlin' }, age: 41 },\n { address: { city: 'Aachen' }, age: 30 },\n];\nsort(rows, [{ key: 'address.city' }, { key: 'age', direction: 'desc' }]);\n```\n\nCriteria paths are resolved with `getPath`, so dotted and bracketed paths (`'address.city'`, `'tags[0]'`) work and prototype-access segments are refused. The first criterion that differs wins and earlier ties keep their input order. Ordering is delegated to `compare`, so a column that mixes value types (a number beside a string) throws a `TypeError` instead of guessing an order.\n\n### fuzzyFilter / fuzzyScore\n\n```ts\nfuzzyFilter(strings: readonly string[], query: string, options?: FuzzyOptions): string[]\nfuzzyFilter<T>(items: readonly T[], query: string, options: FuzzySelection<T>): T[]\nfuzzyScore(strings: readonly string[], query: string, options?: FuzzyOptions): ScoredResult<string>[]\nfuzzyScore<T>(items: readonly T[], query: string, options: FuzzySelection<T>): ScoredResult<T>[]\n```\n\n`fuzzyFilter` preserves input order. `fuzzyScore` orders results by descending score.\n\n```ts\nimport { fuzzyFilter } from '@vielzeug/arsenal/array';\n\nconst users = [{ email: 'alice@example.com', name: 'Alice' }];\nconst matches = fuzzyFilter(users, 'alice', { select: (user) => [user.name, user.email] });\n```\n\n---\n\n## Async\n\n### taskPool\n\n```ts\ninterface TaskPool {\n run<T>(task: (signal: AbortSignal) => Promise<T>): Promise<T>;\n idle(): Promise<void>;\n dispose(reason?: unknown): void;\n readonly active: number;\n readonly pending: number;\n readonly disposed: boolean;\n readonly disposalSignal: AbortSignal;\n}\n\ntaskPool(options?: { concurrency?: number }): TaskPool\n```\n\n`dispose()` aborts running cooperative tasks and rejects pending tasks.\n\n```ts\nimport { taskPool } from '@vielzeug/arsenal/async';\n\nconst pool = taskPool({ concurrency: 2 });\nconst user = await pool.run((signal) => fetch('/user', { signal }).then((response) => response.json()));\npool.dispose();\n```\n\n---\n\n## Cache\n\n### cache\n\n```ts\ninterface Cache<K, T> {\n entries(): ReadonlyArray<readonly [K, T]>;\n get(key: K): T | undefined;\n set(key: K, value: T, options?: { ttlMs?: number }): void;\n getOrLoad(key: K, load: () => Promise<T>): Promise<T>;\n delete(key: K): boolean;\n clear(): void;\n readonly size: number;\n}\n\ncache<K, T>(options?: CacheOptions): Cache<K, T>\n```\n\nKeys use native `Map` identity. Expiry is lazy, evaluated by `get`, `getOrLoad`, `set`, and `entries`. `entries()` trims expired values and returns a new insertion-ordered snapshot without exposing internal storage. The `size` getter does not evict expired entries.\n\n```ts\nimport { cache } from '@vielzeug/arsenal/cache';\n\nconst profiles = cache<string, Profile>({ ttlMs: 60_000 });\nconst profile = await profiles.getOrLoad('me', loadProfile);\n```\n\n---\n\n## Encoding\n\nURL-safe base64 (`base64url`) codecs without `btoa`/`Buffer`, so the same code runs in browsers, workers, and Node.\n\n```ts\nimport { base64UrlToBytes, base64UrlToText, bytesToBase64Url, textToBase64Url, utf8Bytes } from '@vielzeug/arsenal';\n\ntextToBase64Url('{\"build\":\"hero\"}'); // never contains '+', '/', or '='\nbase64UrlToText(textToBase64Url('League of Legends')); // round-trips any UTF-8 text\nbytesToBase64Url(Uint8Array.from([0, 1, 250])); // byte-level codec for binary payloads\nbase64UrlToBytes(code); // throws on characters outside the alphabet\nutf8Bytes('Hunter äöü'); // 11: byte length of a UTF-8 string\n```\n\n### compressBytes\n\n```ts\ncompressBytes(bytes: Uint8Array, options?: CompressionOptions): Promise<Uint8Array>\n```\n\nCompresses bytes using the native `CompressionStream` API without modifying the input.\n\n| Option | Type | Default | Meaning |\n| -------- | ------------------- | --------------- | --------------------------------------------------------- |\n| `format` | `CompressionFormat` | `'deflate-raw'` | Compression format; the receiver must use the same format |\n\n**Returns:** Compressed bytes. Rejects with `ArsenalSerializationError` when the format or capability is unavailable, or stream processing fails. Does not fall back to another format.\n\n**Example:** Encode compressed bytes for a URL.\n\n```ts\nimport { bytesToBase64Url, compressBytes } from '@vielzeug/arsenal';\n\nconst bytes = new TextEncoder().encode(JSON.stringify({ name: 'Hunters' }));\nconst code = bytesToBase64Url(await compressBytes(bytes));\n```\n\n---\n\n### decompressBytes\n\n```ts\ndecompressBytes(bytes: Uint8Array, options: DecompressionOptions): Promise<Uint8Array>\n```\n\nDecompresses bytes using the native `DecompressionStream` API, enforcing the output limit while reading chunks.\n\n| Option | Type | Default | Meaning |\n| ---------------- | ------------------- | --------------- | ------------------------------------------------------ |\n| `format` | `CompressionFormat` | `'deflate-raw'` | Format used by the sender |\n| `maxOutputBytes` | `number` | Required | Non-negative safe integer; maximum decoded byte length |\n\n**Returns:** Decompressed bytes. Rejects with `ArsenalSerializationError` for invalid limits, corrupt or truncated data, unavailable formats/capabilities, or output exceeding the limit. A failed stream is canceled and its reader lock released. Bound encoded input separately before calling this function.\n\n**Example:** Decode text within an application-defined byte limit.\n\n```ts\nimport { compressBytes, decompressBytes } from '@vielzeug/arsenal';\n\nconst compressed = await compressBytes(new TextEncoder().encode('Hunters'));\nconst bytes = await decompressBytes(compressed, { maxOutputBytes: 8192 });\nconst text = new TextDecoder('utf-8', { fatal: true }).decode(bytes);\n```\n\n---\n\n### pack\n\n```ts\npack(payload: unknown, options: ShareCodeOptions): Promise<string>\n```\n\nSerializes `payload` as JSON and encodes it into a compact share code: `prefix` + mode marker + base64url bytes, compressed with raw DEFLATE when the compressed form is shorter and the runtime supports the streams.\n\n| Option | Type | Meaning |\n| ---------- | -------- | ------------------------------------------------------------------- |\n| `maxBytes` | `number` | Positive safe integer; maximum serialized payload size |\n| `prefix` | `string` | 1–8 alphanumeric characters identifying the code family and version |\n\n**Returns:** The shorter of the raw (`prefix` + `r`) and compressed (`prefix` + `d`) representations. Throws `ShareCodeError` (`too-large`, `invalid`) for oversized payloads and misconfigured options.\n\n**Example:** Encode a shareable build as a code small enough for a URL.\n\n```ts\nimport { pack } from '@vielzeug/arsenal';\n\nconst code = await pack({ cards: ['slash', 'guard'] }, { maxBytes: 8192, prefix: 'ab1' });\n```\n\n---\n\n### unpack\n\n```ts\nunpack(code: string, options: ShareCodeOptions): Promise<unknown>\n```\n\nDecodes a share code produced by `pack` with the same options. Both sides are bounded: input longer than `maxBytes` could carry is refused up front, streamed decompression stops at `maxBytes`, and non-canonical base64url is rejected by round-trip.\n\n**Returns:** The parsed JSON payload. Throws `ShareCodeError` (`invalid` for foreign or malformed codes, `too-large` for budget overruns, `compression-unavailable` when a compressed code arrives on a runtime without `DecompressionStream`). Underlying compression failures surface as `ArsenalSerializationError`.\n\n**Example:** Decode untrusted input within the byte budget.\n\n```ts\nimport { unpack } from '@vielzeug/arsenal';\n\nconst payload = await unpack(code, { maxBytes: 8192, prefix: 'ab1' });\n```\n\n## Object\n\n### tryParseJson\n\n```ts\ntype JsonParseResult = { ok: true; value: unknown } | { error: SyntaxError; ok: false };\n\ntryParseJson(text: string): JsonParseResult\n```\n\nUse a schema validator after success to refine `unknown` data.\n\n```ts\nimport { tryParseJson } from '@vielzeug/arsenal/object';\n\nconst result = tryParseJson(raw);\nif (!result.ok) throw result.error;\n```\n\n### getPath\n\n```ts\ngetPath<T extends Record<string, unknown>, P extends string>(item: T, path: P): PathValue<T, P> | undefined\ngetPathOr<T extends Record<string, unknown>, P extends string, F>(item: T, path: P, fallback: F): PathValue<T, P> | F\nrequirePath<T extends Record<string, unknown>, P extends string>(item: T, path: P): Exclude<PathValue<T, P>, undefined>\n```\n\n### hash\n\n```ts\nhash(value: unknown, options?: HashOptions): string\n```\n\nProduces a deterministic, order-independent serialization. Handles `Date`, `RegExp`, `Set`, `Map`, and `bigint`. Circular references produce a sentinel. Useful for stable cache keys.\n\n---\n\n## Math\n\n### Numeric toolkit\n\n```ts\nrange(stop: number): number[]\nrange(start: number, stop: number, step?: number): number[]\nclamp(value: number, min?: number, max?: number): number\nsum<T>(values: readonly T[], select?: (value: T) => number): number\naverage<T>(values: readonly T[], select?: (value: T) => number): number | undefined\nmedian<T>(values: readonly T[], select?: (value: T) => number): number | undefined\nvariance<T>(values: readonly T[], select?: (value: T) => number): number\nstandardDeviation<T>(values: readonly T[], select?: (value: T) => number): number\n```\n\n`sum` and `average` reject non-finite values. `gcd` and `lcm` require safe integers. `linspace` requires finite bounds and a positive integer point count. `variance` and `standardDeviation` compute population statistics.\n\n### allocate\n\n```ts\nallocate(amount: number, ratios: number[] | number): number[]\nallocate(amount: bigint, ratios: number[] | number): bigint[]\n```\n\nDistributes an amount proportionally across ratios. The indivisible remainder is applied to the last bucket so the sum equals the original amount exactly: critical for financial operations.\n\n## Types\n\n```ts\ntype FuzzyOptions = {\n normalize?: boolean;\n threshold?: number;\n};\n\ntype FuzzySelection<T> = FuzzyOptions & {\n select: (item: T) => string | readonly string[];\n};\n\ntype ScoredResult<T> = { item: T; score: number };\n\ntype PageEnvelope<T> = Readonly<{\n items: readonly T[];\n page: number;\n pageSize: number;\n totalItems: number;\n totalPages: number;\n}>;\n\ntype PaginateOptions = Readonly<{\n page?: number;\n pageSize?: number;\n pageOffset?: 0 | 1;\n}>;\n\ntype SortDirection = 'asc' | 'desc';\n\ntype SortSelectors<T> = Partial<Record<keyof T, SortDirection>>;\n\ntype SortCriterion<T> = Readonly<{\n key: keyof T | (string & {});\n direction?: SortDirection;\n}>;\n\ntype CacheOptions = {\n capacity?: number;\n now?: () => number;\n ttlMs?: number;\n};\n\ninterface CompressionOptions {\n format?: CompressionFormat;\n}\n\ninterface DecompressionOptions extends CompressionOptions {\n maxOutputBytes: number;\n}\n```\n\n## Errors\n\n- `RangeError`: invalid numeric bounds, capacity, concurrency, or retry count.\n- `TypeError`: invalid value types, unsupported comparison, or required path missing.\n- `ArsenalSerializationError`: memo or hash cannot serialize supplied input; compression fails, is unavailable, receives an invalid output limit, or exceeds that limit. Stream failures retain the original error as `cause`.\n- `ShareCodeError`: a share code cannot be encoded or decoded; the `reason` field is `invalid`, `too-large`, or `compression-unavailable`.\n",
5
+ "api": "---\ntitle: 'Arsenal: API Reference'\ndescription: Reference for Arsenal root utilities and category entry points.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution | Common gotcha |\n| ----------------------------------- | ---------------------------------------------------------- | --------- | --------------------------------------------------------------------------- |\n| `groupBy` | Group values by key (prototype-pollution guarded) | Sync | Root export |\n| `chunk` / `zip` / `compact` | Typed collection transforms | Sync | Available from `/array` |\n| `paginate` | Cut one page and its totals out of a list | Sync | Pages past the last return empty `items`, unclamped |\n| `sort` | Sort by a selector, keyed fields, or ordered path criteria | Sync | Criteria paths are resolved safely; mixed value types throw |\n| `range` / `average` / `median` | Numeric generation and aggregation | Sync | Available from `/math` |\n| `assert` | Assert and narrow a condition | Sync | Available from `/function` |\n| `retry` | Retry async work | Async | Rethrows final error |\n| `taskPool` | Bound concurrent tasks | Async | Available from `/async` |\n| `timer` | Re-armable single-slot timeout | Async | Available from `/async` |\n| `cache` | In-memory identity-keyed cache | Async | Available from `/cache` |\n| `fuzzyFilter` | Filter string or selected object fields | Sync | Object collections require `select` |\n| `fuzzyScore` | Rank string or selected object fields | Sync | Object collections require `select` |\n| `tryParseJson` | Preserve JSON syntax result | Sync | Returns `unknown` on success |\n| `getPath` | Optional object lookup (safe-path guarded) | Sync | Available from `/object` |\n| `allocate` | Lossless proportional distribution | Sync | Available from `/math` |\n| `isEqual` | Structural equality | Sync | Root export |\n| `hash` | Deterministic serialization for cache keys | Sync | Available from `/object` |\n| `compressBytes` / `decompressBytes` | Native byte compression with bounded decompression | Async | Requires native compression streams; decoding requires an output limit |\n| `pack` / `unpack` | Versioned, compressed, URL-safe payload envelope | Async | Both sides bound the payload with `maxBytes`; compression falls back to raw |\n\n## Package Entry Points\n\n| Import | Purpose |\n| ---------------------------- | ----------------------------------------------------------------------- |\n| `@vielzeug/arsenal` | Curated common utilities |\n| `@vielzeug/arsenal/array` | Immutable transforms, pagination, set operations, sorting, fuzzy search |\n| `@vielzeug/arsenal/async` | Retry, cancellation, task pool, timing |\n| `@vielzeug/arsenal/cache` | In-memory cache and memoization |\n| `@vielzeug/arsenal/encoding` | Base64url and native byte compression |\n| `@vielzeug/arsenal/function` | Assertions, composition, timing, teardown |\n| `@vielzeug/arsenal/guards` | Type guards, predicate combinators, equality guards |\n| `@vielzeug/arsenal/math` | Ranges, aggregation, statistics, interpolation, exact allocation |\n| `@vielzeug/arsenal/object` | Paths, transforms, hash, JSON parse result |\n| `@vielzeug/arsenal/random` | Cryptographic-entropy selection and shuffle |\n| `@vielzeug/arsenal/string` | Unicode-aware case transforms and similarity |\n\n## Array\n\n### Typed transforms\n\n```ts\nchunk<T>(input: readonly T[], size?: number): T[][]\ncompact<T>(array: readonly T[]): Array<Exclude<T, false | '' | 0 | 0n | null | undefined>>\nfirst<T>(array: readonly T[], fallback?: T): T | undefined\nlast<T>(array: readonly T[], fallback?: T): T | undefined\nreplace<T>(array: readonly T[], predicate: (value: T) => boolean, value: T): T[]\nrotate<T>(array: readonly T[], positions: number, options?: { wrap?: boolean }): T[]\nzip(...arrays): Array<tuple>\nunzip(rows): tupleOfArrays\n```\n\n`take`, `takeLast`, `drop`, and `dropLast` return new arrays and normalize negative counts to zero. Set operations accept optional selectors for object identity.\n\n### paginate\n\n```ts\npaginate<T>(items: readonly T[], options?: PaginateOptions): PageEnvelope<T>\n```\n\nCuts one page out of an in-memory list and returns the items with the arithmetic that produced them. `pageOffset` selects the caller's page base: `1` (default) for one-based paging, `0` for zero-based servers such as Spring. The default `page` is the first page in that base, and the default `pageSize` is `20`. `totalPages` is at least 1, even for an empty list, so `page < totalPages` never underflows. Pages past the last yield empty `items` and echo the requested page rather than clamping it. Throws `TypeError` for a non-array and `RangeError` when `page` is not an integer in the selected base or `pageSize` is not a positive integer.\n\n| Option | Type | Default | Description |\n| ------------ | -------- | --------------------------------- | ------------------------------------------------------------------------ |\n| `page` | `number` | First page in `pageOffset`'s base | Requested page; must be an integer greater than or equal to `pageOffset` |\n| `pageSize` | `number` | `20` | Number of items per page; must be a positive integer |\n| `pageOffset` | `0 \\| 1` | `1` | Page-number base: `0` for zero-based callers, `1` for one-based callers |\n\n```ts\nimport { paginate } from '@vielzeug/arsenal/array';\n\npaginate([1, 2, 3, 4, 5], { page: 2, pageSize: 2 });\n// { items: [3, 4], page: 2, pageSize: 2, totalItems: 5, totalPages: 3 }\n\nconst springPage = 0;\npaginate([1, 2, 3, 4, 5], { page: springPage, pageOffset: 0 });\n// { items: [1, 2, 3, 4, 5], page: 0, pageSize: 20, totalItems: 5, totalPages: 1 }\n```\n\nThe envelope is server-neutral: it models no HTTP dialect, so adapters map their response onto it and map it back out.\n\n### sort\n\n```ts\nsort<T>(array: readonly T[], selector: (item: T) => unknown, direction?: SortDirection): T[];\nsort<T>(array: readonly T[], selectors: SortSelectors<T>): T[];\nsort<T>(array: readonly T[], criteria: ReadonlyArray<SortCriterion<T>>): T[];\n```\n\nThree forms, one entry point. The selector form sorts by one extracted value; the selectors form accepts an object mapping property keys to directions; the criteria form sorts by an ordered list of paths, which is the shape a data grid hands over when its sortable columns are runtime strings.\n\n```ts\nimport { sort } from '@vielzeug/arsenal/array';\n\nconst users = [\n { name: 'Ada', age: 41 },\n { name: 'Grace', age: 30 },\n];\nsort(users, (user) => user.name);\nsort(users, { name: 'asc', age: 'desc' });\n\nconst rows = [\n { address: { city: 'Berlin' }, age: 41 },\n { address: { city: 'Aachen' }, age: 30 },\n];\nsort(rows, [{ key: 'address.city' }, { key: 'age', direction: 'desc' }]);\n```\n\nCriteria paths are resolved with `getPath`, so dotted and bracketed paths (`'address.city'`, `'tags[0]'`) work and prototype-access segments are refused. The first criterion that differs wins and earlier ties keep their input order. Ordering is delegated to `compare`, so a column that mixes value types (a number beside a string) throws a `TypeError` instead of guessing an order.\n\n### fuzzyFilter / fuzzyScore\n\n```ts\nfuzzyFilter(strings: readonly string[], query: string, options?: FuzzyOptions): string[]\nfuzzyFilter<T>(items: readonly T[], query: string, options: FuzzySelection<T>): T[]\nfuzzyScore(strings: readonly string[], query: string, options?: FuzzyOptions): ScoredResult<string>[]\nfuzzyScore<T>(items: readonly T[], query: string, options: FuzzySelection<T>): ScoredResult<T>[]\n```\n\n`fuzzyFilter` preserves input order. `fuzzyScore` orders results by descending score.\n\n```ts\nimport { fuzzyFilter } from '@vielzeug/arsenal/array';\n\nconst users = [{ email: 'alice@example.com', name: 'Alice' }];\nconst matches = fuzzyFilter(users, 'alice', { select: (user) => [user.name, user.email] });\n```\n\n---\n\n## Async\n\n### taskPool\n\n```ts\ninterface TaskPool {\n run<T>(task: (signal: AbortSignal) => Promise<T>): Promise<T>;\n idle(): Promise<void>;\n dispose(reason?: unknown): void;\n readonly active: number;\n readonly pending: number;\n readonly disposed: boolean;\n readonly disposalSignal: AbortSignal;\n}\n\ntaskPool(options?: { concurrency?: number }): TaskPool\n```\n\n`dispose()` aborts running cooperative tasks and rejects pending tasks.\n\n```ts\nimport { taskPool } from '@vielzeug/arsenal/async';\n\nconst pool = taskPool({ concurrency: 2 });\nconst user = await pool.run((signal) => fetch('/user', { signal }).then((response) => response.json()));\npool.dispose();\n```\n\n### timer\n\n```ts\ninterface Timer {\n arm(ms: number): void;\n cancel(): void;\n readonly pending: boolean;\n}\n\ntimer(fn: () => void): Timer\n```\n\nA single-slot, re-armable timeout. `arm()` cancels any pending run first, so at most one run is ever scheduled. `pending` is already `false` inside the callback, which may re-arm the timer.\n\n```ts\nimport { timer } from '@vielzeug/arsenal/async';\n\nconst idleFlush = timer(() => flush());\nidleFlush.arm(500); // debounced: re-arming restarts the delay\nidleFlush.cancel();\n```\n\n---\n\n## Cache\n\n### cache\n\n```ts\ninterface Cache<K, T> {\n entries(): ReadonlyArray<readonly [K, T]>;\n get(key: K): T | undefined;\n set(key: K, value: T, options?: { ttlMs?: number }): void;\n getOrLoad(key: K, load: () => Promise<T>): Promise<T>;\n delete(key: K): boolean;\n clear(): void;\n readonly size: number;\n}\n\ncache<K, T>(options?: CacheOptions): Cache<K, T>\n```\n\nKeys use native `Map` identity. Expiry is lazy, evaluated by `get`, `getOrLoad`, `set`, and `entries`. `entries()` trims expired values and returns a new insertion-ordered snapshot without exposing internal storage. The `size` getter does not evict expired entries.\n\n```ts\nimport { cache } from '@vielzeug/arsenal/cache';\n\nconst profiles = cache<string, Profile>({ ttlMs: 60_000 });\nconst profile = await profiles.getOrLoad('me', loadProfile);\n```\n\n---\n\n## Encoding\n\nURL-safe base64 (`base64url`) codecs without `btoa`/`Buffer`, so the same code runs in browsers, workers, and Node.\n\n```ts\nimport { base64UrlToBytes, base64UrlToText, bytesToBase64Url, textToBase64Url, utf8Bytes } from '@vielzeug/arsenal';\n\ntextToBase64Url('{\"build\":\"hero\"}'); // never contains '+', '/', or '='\nbase64UrlToText(textToBase64Url('League of Legends')); // round-trips any UTF-8 text\nbytesToBase64Url(Uint8Array.from([0, 1, 250])); // byte-level codec for binary payloads\nbase64UrlToBytes(code); // throws on characters outside the alphabet\nutf8Bytes('Hunter äöü'); // 11: byte length of a UTF-8 string\n```\n\n### compressBytes\n\n```ts\ncompressBytes(bytes: Uint8Array, options?: CompressionOptions): Promise<Uint8Array>\n```\n\nCompresses bytes using the native `CompressionStream` API without modifying the input.\n\n| Option | Type | Default | Meaning |\n| -------- | ------------------- | --------------- | --------------------------------------------------------- |\n| `format` | `CompressionFormat` | `'deflate-raw'` | Compression format; the receiver must use the same format |\n\n**Returns:** Compressed bytes. Rejects with `ArsenalSerializationError` when the format or capability is unavailable, or stream processing fails. Does not fall back to another format.\n\n**Example:** Encode compressed bytes for a URL.\n\n```ts\nimport { bytesToBase64Url, compressBytes } from '@vielzeug/arsenal';\n\nconst bytes = new TextEncoder().encode(JSON.stringify({ name: 'Hunters' }));\nconst code = bytesToBase64Url(await compressBytes(bytes));\n```\n\n---\n\n### decompressBytes\n\n```ts\ndecompressBytes(bytes: Uint8Array, options: DecompressionOptions): Promise<Uint8Array>\n```\n\nDecompresses bytes using the native `DecompressionStream` API, enforcing the output limit while reading chunks.\n\n| Option | Type | Default | Meaning |\n| ---------------- | ------------------- | --------------- | ------------------------------------------------------ |\n| `format` | `CompressionFormat` | `'deflate-raw'` | Format used by the sender |\n| `maxOutputBytes` | `number` | Required | Non-negative safe integer; maximum decoded byte length |\n\n**Returns:** Decompressed bytes. Rejects with `ArsenalSerializationError` for invalid limits, corrupt or truncated data, unavailable formats/capabilities, or output exceeding the limit. A failed stream is canceled and its reader lock released. Bound encoded input separately before calling this function.\n\n**Example:** Decode text within an application-defined byte limit.\n\n```ts\nimport { compressBytes, decompressBytes } from '@vielzeug/arsenal';\n\nconst compressed = await compressBytes(new TextEncoder().encode('Hunters'));\nconst bytes = await decompressBytes(compressed, { maxOutputBytes: 8192 });\nconst text = new TextDecoder('utf-8', { fatal: true }).decode(bytes);\n```\n\n---\n\n### pack\n\n```ts\npack(payload: unknown, options: ShareCodeOptions): Promise<string>\n```\n\nSerializes `payload` as JSON and encodes it into a compact share code: `prefix` + mode marker + base64url bytes, compressed with raw DEFLATE when the compressed form is shorter and the runtime supports the streams.\n\n| Option | Type | Meaning |\n| ---------- | -------- | ------------------------------------------------------------------- |\n| `maxBytes` | `number` | Positive safe integer; maximum serialized payload size |\n| `prefix` | `string` | 1–8 alphanumeric characters identifying the code family and version |\n\n**Returns:** The shorter of the raw (`prefix` + `r`) and compressed (`prefix` + `d`) representations. Throws `ShareCodeError` (`too-large`, `invalid`) for oversized payloads and misconfigured options.\n\n**Example:** Encode a shareable build as a code small enough for a URL.\n\n```ts\nimport { pack } from '@vielzeug/arsenal';\n\nconst code = await pack({ cards: ['slash', 'guard'] }, { maxBytes: 8192, prefix: 'ab1' });\n```\n\n---\n\n### unpack\n\n```ts\nunpack(code: string, options: ShareCodeOptions): Promise<unknown>\n```\n\nDecodes a share code produced by `pack` with the same options. Both sides are bounded: input longer than `maxBytes` could carry is refused up front, streamed decompression stops at `maxBytes`, and non-canonical base64url is rejected by round-trip.\n\n**Returns:** The parsed JSON payload. Throws `ShareCodeError` (`invalid` for foreign or malformed codes, `too-large` for budget overruns, `compression-unavailable` when a compressed code arrives on a runtime without `DecompressionStream`). Underlying compression failures surface as `ArsenalSerializationError`.\n\n**Example:** Decode untrusted input within the byte budget.\n\n```ts\nimport { unpack } from '@vielzeug/arsenal';\n\nconst payload = await unpack(code, { maxBytes: 8192, prefix: 'ab1' });\n```\n\n## Object\n\n### tryParseJson\n\n```ts\ntype JsonParseResult = { ok: true; value: unknown } | { error: SyntaxError; ok: false };\n\ntryParseJson(text: string): JsonParseResult\n```\n\nUse a schema validator after success to refine `unknown` data.\n\n```ts\nimport { tryParseJson } from '@vielzeug/arsenal/object';\n\nconst result = tryParseJson(raw);\nif (!result.ok) throw result.error;\n```\n\n### getPath\n\n```ts\ngetPath<T extends Record<string, unknown>, P extends string>(item: T, path: P): PathValue<T, P> | undefined\ngetPathOr<T extends Record<string, unknown>, P extends string, F>(item: T, path: P, fallback: F): PathValue<T, P> | F\nrequirePath<T extends Record<string, unknown>, P extends string>(item: T, path: P): Exclude<PathValue<T, P>, undefined>\n```\n\n### hash\n\n```ts\nhash(value: unknown, options?: HashOptions): string\n```\n\nProduces a deterministic, order-independent serialization. Handles `Date`, `RegExp`, `Set`, `Map`, and `bigint`. Circular references produce a sentinel. Useful for stable cache keys.\n\n---\n\n## Math\n\n### Numeric toolkit\n\n```ts\nrange(stop: number): number[]\nrange(start: number, stop: number, step?: number): number[]\nclamp(value: number, min?: number, max?: number): number\nsum<T>(values: readonly T[], select?: (value: T) => number): number\naverage<T>(values: readonly T[], select?: (value: T) => number): number | undefined\nmedian<T>(values: readonly T[], select?: (value: T) => number): number | undefined\nvariance<T>(values: readonly T[], select?: (value: T) => number): number\nstandardDeviation<T>(values: readonly T[], select?: (value: T) => number): number\n```\n\n`sum` and `average` reject non-finite values. `gcd` and `lcm` require safe integers. `linspace` requires finite bounds and a positive integer point count. `variance` and `standardDeviation` compute population statistics.\n\n### allocate\n\n```ts\nallocate(amount: number, ratios: number[] | number): number[]\nallocate(amount: bigint, ratios: number[] | number): bigint[]\n```\n\nDistributes an amount proportionally across ratios. The indivisible remainder is applied to the last bucket so the sum equals the original amount exactly: critical for financial operations.\n\n## Types\n\n```ts\ntype FuzzyOptions = {\n normalize?: boolean;\n threshold?: number;\n};\n\ntype FuzzySelection<T> = FuzzyOptions & {\n select: (item: T) => string | readonly string[];\n};\n\ntype ScoredResult<T> = { item: T; score: number };\n\ntype PageEnvelope<T> = Readonly<{\n items: readonly T[];\n page: number;\n pageSize: number;\n totalItems: number;\n totalPages: number;\n}>;\n\ntype PaginateOptions = Readonly<{\n page?: number;\n pageSize?: number;\n pageOffset?: 0 | 1;\n}>;\n\ntype SortDirection = 'asc' | 'desc';\n\ntype SortSelectors<T> = Partial<Record<keyof T, SortDirection>>;\n\ntype SortCriterion<T> = Readonly<{\n key: keyof T | (string & {});\n direction?: SortDirection;\n}>;\n\ntype CacheOptions = {\n capacity?: number;\n now?: () => number;\n ttlMs?: number;\n};\n\ninterface CompressionOptions {\n format?: CompressionFormat;\n}\n\ninterface DecompressionOptions extends CompressionOptions {\n maxOutputBytes: number;\n}\n```\n\n## Errors\n\n- `RangeError`: invalid numeric bounds, capacity, concurrency, or retry count.\n- `TypeError`: invalid value types, unsupported comparison, or required path missing.\n- `ArsenalSerializationError`: memo or hash cannot serialize supplied input; compression fails, is unavailable, receives an invalid output limit, or exceeds that limit. Stream failures retain the original error as `cause`.\n- `ShareCodeError`: a share code cannot be encoded or decoded; the `reason` field is `invalid`, `too-large`, or `compression-unavailable`.\n",
6
6
  "usage": "---\ntitle: 'Arsenal: Usage Guide'\ndescription: Use Arsenal root utilities for common work and category entry points for specialized collection, async, cache, object, and string behavior.\n---\n\n[[toc]]\n\n## Basic Usage\n\nStart at package root for common utilities. Move to a category entry point for the broader typed toolkit. Arsenal keeps helpers that improve readability, narrowing, immutable updates, or edge-case consistency; exact platform aliases stay out.\n\n```ts\nimport { groupBy, retry } from '@vielzeug/arsenal';\n\nconst users = [\n { id: 'a1', role: 'admin' },\n { id: 'u1', role: 'user' },\n { id: 'u2', role: 'user' },\n];\n\nconst byRole = groupBy(users, (user) => user.role);\nconst health = await retry(() => fetch('/health').then((response) => response.json()));\n\nconsole.log(byRole, health);\n```\n\nUse category imports for APIs absent from root:\n\n```ts\nimport { fuzzyFilter } from '@vielzeug/arsenal/array';\nimport { taskPool } from '@vielzeug/arsenal/async';\nimport { cache } from '@vielzeug/arsenal/cache';\nimport { tryParseJson } from '@vielzeug/arsenal/object';\n```\n\n## Transform Collections\n\nUse `/array` for transforms that preserve input immutability. `filterMap` combines mapping and omission; `indexBy` and `groupBy` build lookup structures without mutation.\n\n```ts\nimport { filterMap, indexBy, sort } from '@vielzeug/arsenal/array';\n\nconst products = [\n { id: 'p1', price: 20, published: true },\n { id: 'p2', price: 10, published: false },\n { id: 'p3', price: 15, published: true },\n];\n\nconst publishedLabels = filterMap(products, (product) =>\n product.published ? `${product.id}: ${product.price}` : undefined,\n);\nconst byId = indexBy(products, (product) => product.id);\nconst byPrice = sort(products, (product) => product.price);\n\nconsole.log(publishedLabels, byId, byPrice);\n```\n\n## Page an In-Memory List\n\nUse `paginate` when the whole list is local and a view needs one page plus its totals.\n\n```ts\nimport { paginate } from '@vielzeug/arsenal/array';\n\nconst rows = Array.from({ length: 45 }, (_, index) => ({ id: index + 1 }));\n\nconst first = paginate(rows, { pageSize: 10 });\nconst past = paginate(rows, { page: 9, pageSize: 10 });\n\nconsole.log(first.totalPages, past.items); // 5 []\n```\n\n`page` is echoed rather than clamped, so a stale page number reads as an empty page instead of\nsilently jumping elsewhere. Pass `{ pageOffset: 0 }` for a zero-based caller and the envelope comes\nback in that same base.\n\n## Sort by Grid Criteria\n\n`sort` accepts the ordering a data grid already holds: an ordered list of column paths, each with a direction.\n\n```ts\nimport { sort } from '@vielzeug/arsenal/array';\n\nconst rows = [\n { address: { city: 'Berlin' }, age: 41 },\n { address: { city: 'Aachen' }, age: 30 },\n { address: { city: 'Berlin' }, age: 27 },\n];\n\nconst ordered = sort(rows, [{ key: 'address.city' }, { key: 'age', direction: 'desc' }]);\n```\n\nPaths are resolved safely, so nested and indexed columns work and prototype access is refused. The\nfirst criterion that differs decides the order and ties keep their input order. Keep each column\ntyped: a column mixing numbers and strings throws a `TypeError` rather than guessing an order.\n\n## Search Explicit Fields\n\nSearch string arrays directly. Object collections require `select`, so callers define exactly what can match.\n\n```ts\nimport { fuzzyFilter, fuzzyScore } from '@vielzeug/arsenal/array';\n\nconst users = [\n { email: 'alice@example.com', name: 'Alice' },\n { email: 'bob@example.com', name: 'Bob' },\n];\n\nconst matches = fuzzyFilter(users, 'alice', { select: (user) => [user.name, user.email] });\nconst ranked = fuzzyScore(users, 'ali', { select: (user) => user.name });\n```\n\n## Work with Object Data\n\nUse `/object` for paths, key selection, stable cache keys, and object transforms.\n\n```ts\nimport { getPathOr, hash, omit, pick } from '@vielzeug/arsenal/object';\n\nconst config = { api: { host: 'localhost', port: 3000 }, debug: true };\nconst port = getPathOr(config, 'api.port', 8080);\nconst publicConfig = pick(config, ['api']);\nconst productionConfig = omit(config, ['debug']);\nconst key = hash({ port, productionConfig });\n\nconsole.log(publicConfig, key);\n```\n\n## Parse and Validate JSON\n\n`tryParseJson` distinguishes syntax failure from schema failure. Treat successful values as `unknown`, then validate with Spell or application code.\n\n```ts\nimport { tryParseJson } from '@vielzeug/arsenal/object';\nimport { s } from '@vielzeug/spell';\n\nconst User = s.object({ id: s.string(), name: s.string() });\nconst parsed = tryParseJson(raw);\n\nif (!parsed.ok) throw parsed.error;\n\nconst user = User.parse(parsed.value);\n```\n\n## Bound Concurrent Work\n\nUse `parallel` for one finite collection. Use `taskPool` when tasks arrive over time or need disposal.\n\n```ts\nimport { parallel, taskPool } from '@vielzeug/arsenal/async';\n\nconst metadata = await parallel(urls, (url) => fetch(url).then((response) => response.json()), { limit: 4 });\n\nconst pool = taskPool({ concurrency: 2 });\nconst profile = await pool.run((signal) => fetch('/profile', { signal }).then((response) => response.json()));\n\nawait pool.idle();\npool.dispose();\n\nconsole.log(metadata, profile);\n```\n\n## Cache Loaded Values\n\nUse `cache` for process-local values. Keys retain native `Map` identity. `getOrLoad` deduplicates concurrent loads for one key.\n\n```ts\nimport { cache } from '@vielzeug/arsenal/cache';\n\ntype Profile = { id: string; name: string };\n\nconst profiles = cache<string, Profile>({ capacity: 100, ttlMs: 60_000 });\nconst profile = await profiles.getOrLoad('me', () => fetch('/profile').then((response) => response.json()));\n\nconsole.log(profiles.entries());\nprofiles.delete('me');\nconst freshProfile = await profiles.getOrLoad('me', () => fetch('/profile').then((response) => response.json()));\n\nconsole.log(profile, freshProfile);\n```\n\n## Test Deterministic Randomness\n\nRandom helpers use cryptographic entropy by default. Pass `RandomSource` in tests when output must be deterministic.\n\n```ts\nimport { random, randomFloat, type RandomSource } from '@vielzeug/arsenal/random';\n\nconst source: RandomSource = { next: () => 0.5 };\n\nrandomFloat(source); // 0.5\nrandom(1, 4, source); // 3\n```\n\n## Encode Text for URLs and QR Codes\n\nShare codes ride in URLs and QR payloads, where `+`, `/`, and padding `=` break consumers. The base64url codecs are environment-independent: no `btoa`, no `Buffer`, so the same encode/decode pair works in the browser, in workers, and in Node.\n\n```ts\nimport { base64UrlToText, textToBase64Url } from '@vielzeug/arsenal';\n\nconst code = textToBase64Url(JSON.stringify({ seat: 4, version: 2 }));\n// eyJzZWF0Ijo0LCJ2ZXJzaW9uIjoyfQ: safe in a query string or QR\n\nconst payload = JSON.parse(base64UrlToText(code));\n```\n\nDecoding throws on characters outside the base64url alphabet, so corrupted input fails loudly instead of decoding to garbage.\n\n## Compress Share Payloads\n\nCompress UTF-8 bytes before Base64url encoding. Set a decoded-byte limit before accepting compressed input from another device.\n\n```ts\nimport { base64UrlToBytes, bytesToBase64Url, compressBytes, decompressBytes } from '@vielzeug/arsenal';\n\nconst payload = JSON.stringify({ name: 'Hunters', notes: 'An expedition through Alborea. '.repeat(20) });\nconst compressed = await compressBytes(new TextEncoder().encode(payload));\nconst code = bytesToBase64Url(compressed);\nconst bytes = await decompressBytes(base64UrlToBytes(code), { maxOutputBytes: 8192 });\nconst restored = new TextDecoder('utf-8', { fatal: true }).decode(bytes);\nconsole.log(restored === payload);\n```\n\nBoth helpers default to `deflate-raw`. You can explicitly select `gzip` or `deflate`; use the same format at both ends. The helpers reject when native streams do not support the selected format. They do not choose a fallback or define a wire protocol.\n\nFor a complete versioned envelope over these primitives — prefix, compression mode marker, byte budgets on both sides — see [`pack` / `unpack`](./api.md#pack).\n\nCompression can enlarge small inputs. Compare the final encoded strings, including any format marker, before choosing a representation. Bound input size before decoding Base64url and validate decompressed JSON against your schema. The decompression limit bounds retained output, not native stream working memory.\n\n## Working with Other Vielzeug Libraries\n\nUse Spell after `tryParseJson` for typed external data. Use Vault instead of `cache` when data must survive reloads or process restart.\n\n```ts\nimport { tryParseJson } from '@vielzeug/arsenal/object';\nimport { s } from '@vielzeug/spell';\n\nconst Settings = s.object({ theme: s.string() });\nconst parsed = tryParseJson(rawSettings);\nconst settings = parsed.ok ? Settings.parse(parsed.value) : { theme: 'system' };\n```\n\n## Best Practices\n\n- Import common utilities from package root.\n- Import the broader toolkit from category entry points.\n- Prefer Arsenal when a helper improves typing, intent, immutable updates, or edge-case behavior.\n- Use the platform directly for exact aliases such as `crypto.randomUUID()` and `Array.prototype.flat()`.\n- Pass `select` for every fuzzy search over objects.\n- Validate parsed JSON before using it as application data.\n- Use `parallel` for finite batches and `taskPool` for ongoing work.\n- Dispose task pools when their owner ends.\n- Use `cache` only for in-memory data.\n- Inject `RandomSource` in deterministic tests.\n",
7
7
  "examples": "---\ntitle: 'Arsenal: Examples'\ndescription: Practical examples and recipes for arsenal.\n---\n\n## Examples\n\n- [Array utilities](./examples/array.md)\n- [Async utilities](./examples/async.md)\n- [Cache utilities](./examples/cache.md)\n- [Encoding utilities](./examples/encoding.md)\n- [Function utilities](./examples/function.md)\n- [Guards / Typed predicates](./examples/typed.md)\n- [Math utilities](./examples/math.md)\n- [Object utilities](./examples/object.md): includes `getPath`, `tryParseJson`, `hash`, `diff`, `deepMerge`\n- [Random utilities](./examples/random.md)\n- [String utilities](./examples/string.md)\n"
8
8
  },
@@ -200,6 +200,8 @@
200
200
  "sleep": "export async function sleep(timeout: number, signal?: AbortSignal): Promise<void> {\n if (!signal) {\n return new Promise((resolve) => setTimeout(resolve, timeout));\n }\n\n if (signal.aborted) {\n return Promise.reject(abortError(signal));\n }\n\n return new Promise<void>((resolve, reject) => {\n const id = setTimeout(() => {\n signal.removeEventListener('abort', onAbort);\n resolve();\n }, timeout);\n\n const onAbort = () => {\n clearTimeout(id);\n signal.removeEventListener('abort', onAbort);\n reject(abortError(signal));\n };\n\n signal.addEventListener('abort', onAbort);\n });\n}",
201
201
  "TaskPool": "export interface TaskPool {\n readonly active: number;\n readonly disposalSignal: AbortSignal;\n dispose(reason?: unknown): void;\n readonly disposed: boolean;\n idle(): Promise<void>;\n readonly pending: number;\n run<T>(task: (signal: AbortSignal) => Promise<T>): Promise<T>;\n [Symbol.dispose](): void;\n}",
202
202
  "taskPool": "export function taskPool({ concurrency = 1 }: { concurrency?: number } = {}): TaskPool {\n if (!Number.isInteger(concurrency) || concurrency < 1) {\n throw new RangeError('taskPool: concurrency must be a positive integer');\n }\n\n const controller = new AbortController();\n const pending: PendingTask[] = [];\n let active = 0;\n let disposed = false;\n let idleDeferred: ReturnType<typeof Promise.withResolvers<void>> | undefined;\n\n const resolveIdle = (): void => {\n if (active === 0 && pending.length === 0) {\n idleDeferred?.resolve();\n idleDeferred = undefined;\n }\n };\n\n const start = (): void => {\n while (active < concurrency && pending.length > 0) {\n const next = pending.shift()!;\n\n active++;\n void Promise.resolve()\n .then(() => next.run(controller.signal))\n .then(next.resolve, next.reject)\n .finally(() => {\n active--;\n start();\n resolveIdle();\n });\n }\n };\n\n return {\n get active(): number {\n return active;\n },\n get disposalSignal(): AbortSignal {\n return controller.signal;\n },\n dispose: (reason: unknown = new DOMException('Task pool disposed', 'AbortError')): void => {\n if (disposed) return;\n\n disposed = true;\n controller.abort(reason);\n\n for (const task of pending.splice(0)) task.reject(reason);\n\n resolveIdle();\n },\n get disposed(): boolean {\n return disposed;\n },\n idle: (): Promise<void> => {\n if (active === 0 && pending.length === 0) return Promise.resolve();\n\n idleDeferred ??= Promise.withResolvers<void>();\n\n return idleDeferred.promise;\n },\n get pending(): number {\n return pending.length;\n },\n run: <T>(task: (signal: AbortSignal) => Promise<T>): Promise<T> => {\n const deferred = Promise.withResolvers<T>();\n\n if (disposed) {\n deferred.reject(controller.signal.reason);\n\n return deferred.promise;\n }\n\n pending.push({\n reject: deferred.reject,\n resolve: deferred.resolve as (value: unknown) => void,\n run: task as (signal: AbortSignal) => Promise<unknown>,\n });\n start();\n\n return deferred.promise;\n },\n [Symbol.dispose](): void {\n this.dispose();\n },\n };\n}",
203
+ "Timer": "export type Timer = {\n /** (Re)starts the timer: any pending run is cancelled first, so at most one run is ever scheduled. */\n arm(ms: number): void;\n /** Cancels the pending run, if any. Safe to call repeatedly. */\n cancel(): void;\n /** `true` while a run is scheduled and has not fired yet. */\n readonly pending: boolean;\n};",
204
+ "timer": "export function timer(fn: () => void): Timer {\n let id: ReturnType<typeof setTimeout> | undefined;\n\n const cancel = (): void => {\n if (id === undefined) return;\n\n clearTimeout(id);\n id = undefined;\n };\n\n return {\n arm(ms) {\n cancel();\n id = setTimeout(() => {\n id = undefined;\n fn();\n }, ms);\n },\n cancel,\n get pending() {\n return id !== undefined;\n },\n };\n}",
203
205
  "WaitForOptions": "export type WaitForOptions = {\n interval?: number;\n signal?: AbortSignal;\n timeout?: number;\n};",
204
206
  "waitFor": "export async function waitFor(\n condition: (signal: AbortSignal) => boolean | Promise<boolean>,\n { interval = 100, signal, timeout: ms = 5000 }: WaitForOptions = {},\n): Promise<void> {\n const deadline = AbortSignal.timeout(ms);\n const merged = signal ? AbortSignal.any([signal, deadline]) : deadline;\n\n merged.throwIfAborted();\n\n while (true) {\n merged.throwIfAborted();\n\n if (await condition(merged)) return;\n\n await sleep(interval, merged);\n }\n}",
205
207
  "CacheOptions": "export type CacheOptions = {\n capacity?: number;\n now?: () => number;\n ttlMs?: number;\n};",
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "apiSource": "export {\n ClockworkDefinitionError,\n ClockworkError,\n ClockworkSnapshotError,\n ClockworkTransitionLimitError,\n} from './errors.js';\nexport { defineMachine } from './interpret.js';\nexport type {\n Actor,\n ActorErrorContext,\n ActorOptions,\n ActorTapEvent,\n After,\n Effect,\n EffectArgs,\n EventByType,\n EventType,\n Guard,\n Invoke,\n InvokeArgs,\n Machine,\n MachineConfig,\n MachineEvent,\n MachineSnapshot,\n Reducer,\n StateNode,\n Transition,\n TransitionInput,\n TransitionResult,\n} from './types.js';\n",
3
3
  "docs": {
4
- "index": "---\ntitle: 'Clockwork: Typed finite state machines for TypeScript'\ndescription: Framework-neutral typed state machines with pure transitions, actor-owned runtime work, timers, invokes, and explicit effects.\npackage: clockwork\ncategory: state\nkeywords: [state-machine, finite-state, typed, actor, async-tasks]\nrelated: [herald, ripple, ward]\nexports: [defineMachine, ClockworkError, Machine, Actor, MachineConfig, MachineSnapshot]\nenvironments: [browser, node, ssr, deno]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"clockwork\" />\n\n## Why Clockwork?\n\nApplication workflows often mix state changes with timers, requests, rendering, and cleanup. Clockwork keeps transition logic pure while each disposable actor owns runtime work. You can test state decisions without starting effects or invokes.\n\n```ts\nimport { defineMachine } from '@vielzeug/clockwork';\n\n// Before\nif (status === 'idle') status = 'loading';\nfetchItems().then((items) => {\n status = 'ready';\n data = items;\n});\n\n// After\ntype Event = { type: 'FETCH' } | { items: string[]; type: 'DONE' };\nconst machine = defineMachine<{ items: string[] }, Event>()({\n context: { items: [] },\n initial: 'idle',\n states: {\n idle: { on: { FETCH: { target: 'loading' } } },\n loading: {\n invoke: [\n {\n src: ({ signal }) => fetch('/api/items', { signal }).then((response) => response.json() as Promise<string[]>),\n onDone: ({ result }) => ({ items: result, type: 'DONE' }),\n },\n ],\n on: { DONE: { reduce: ({ event }) => ({ items: event.items }), target: 'ready' } },\n },\n ready: {},\n },\n});\n```\n\n| Feature | Clockwork | XState | Zustand |\n| ------------------- | ----------------------------------------------------------- | ------------------------------------------------------------------------ | ------------------------------------------------- |\n| Bundle size | <PackageInfo package=\"clockwork\" type=\"size\" /> | Larger actor/statechart runtime | Smaller store runtime |\n| Zero dependencies | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n| Pure transition API | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"triangle-alert\" size=\"16\"></ore-icon> Statechart-focused | <ore-icon name=\"x\" size=\"16\"></ore-icon> |\n| Owned cancellation | <ore-icon name=\"check\" size=\"16\"></ore-icon> Actor disposal | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> |\n| Framework coupling | <ore-icon name=\"check\" size=\"16\"></ore-icon> None | <ore-icon name=\"check\" size=\"16\"></ore-icon> None | <ore-icon name=\"check\" size=\"16\"></ore-icon> None |\n\n<div class=\"decision-callout\">\n\n**Use Clockwork when** your feature has explicit workflow states, cancellable work, or effects that must run after a state commit.\n\n**Consider XState when** you need statecharts, visual tooling, or its broader actor ecosystem.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/clockwork\n```\n\n```sh [npm]\nnpm install @vielzeug/clockwork\n```\n\n```sh [yarn]\nyarn add @vielzeug/clockwork\n```\n\n:::\n\n## Quick Start\n\nDefine the context and event union, create an actor, observe its snapshot, then dispose it when its owner ends.\n\n```ts\nimport { defineMachine } from '@vielzeug/clockwork';\n\ntype Event = { type: 'DEC' } | { type: 'INC' };\n\nconst counter = defineMachine<{ count: number }, Event>()({\n context: { count: 0 },\n initial: 'idle',\n states: {\n idle: {\n on: {\n DEC: { reduce: ({ context }) => ({ count: context.count - 1 }), target: 'idle' },\n INC: { reduce: ({ context }) => ({ count: context.count + 1 }), target: 'idle' },\n },\n },\n },\n});\n\nusing actor = counter.createActor();\nactor.subscribe((snapshot) => console.log(snapshot));\nactor.send({ type: 'INC' });\n// { context: { count: 1 }, state: 'idle' }\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- **`defineMachine()`**: defines one flat, typed machine and rejects the footguns types cannot express.\n- **`machine.transition()`**: evaluates a transition without actor runtime work.\n- **`machine.createActor()`**: creates isolated, disposable runtime ownership.\n- **`reduce`**: returns a replacement context from a transition.\n- **`effects`**: run after commit and stable subscriber notification.\n- **`invoke`**: runs cancellable asynchronous work on state entry.\n- **`after`**: schedules cancellable delayed transitions.\n- **`actor.snapshot`**: exposes the current shallow-frozen state/context value.\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- [Herald](/herald/): publish events between independent actors without coupling machine definitions.\n- [Ripple](/ripple/): bridge actor snapshots into a reactive graph when you need fine-grained rendering.\n- [Ward](/ward/): call authorization predicates from transition guards.\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
5
- "api": "---\ntitle: 'Clockwork: API Reference'\ndescription: Reference for Clockwork machine definitions, actors, and types.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| ----------------------- | ---------------------------------------------------------- | -------------- | ----------------------------------------------------------- |\n| `defineMachine()` | Define a typed flat machine | Sync | Call the generic factory before supplying the definition |\n| `Machine.transition()` | Resolve a pure next snapshot | Sync | Does not run effects, invokes, or timers |\n| `Machine.createActor()` | Create a runtime owner | Sync | Fresh and restored actors have different entry behavior |\n| `Actor.send()` | Dispatch an event | Sync | Returns `void`; re-entrant events queue internally |\n| `Actor.subscribe()` | Observe committed snapshots | Sync | Observes only; it does not trace sends or errors |\n| `Actor.tap()` | Observe transitions, ignores, errors, disposal | Sync | Handler errors are swallowed; it cannot control disposition |\n| `ClockworkError` | Report definition, snapshot, and transition-limit failures | Sync | Narrow with the error subtypes, not message text |\n\n## Package Entry Points\n\n| Import | Purpose |\n| --------------------- | ------------------------------------------------- |\n| `@vielzeug/clockwork` | Machine factory, actor runtime, errors, and types |\n\n## Exported Surface\n\nCallback parameter types are inferred for inline definitions. Clockwork also exports reusable callback, transition, state-node, actor-option, result, and error-context types for shared helpers.\n\n| Primary export | Kind |\n| ------------------------------- | -------- |\n| `defineMachine` | Function |\n| `Machine` | Type |\n| `Actor` | Type |\n| `MachineSnapshot` | Type |\n| `MachineConfig` | Type |\n| `ClockworkError` | Class |\n| `ClockworkDefinitionError` | Class |\n| `ClockworkSnapshotError` | Class |\n| `ClockworkTransitionLimitError` | Class |\n\nAdditional exported types: `ActorErrorContext`, `ActorOptions`, `ActorTapEvent`, `After`, `Effect`, `EffectArgs`, `EventByType`, `EventType`, `Guard`, `Invoke`, `InvokeArgs`, `MachineEvent`, `Reducer`, `StateNode`, `Transition`, `TransitionInput`, and `TransitionResult`.\n\n## Core Functions\n\n### `defineMachine()`\n\n```ts\nfunction defineMachine<\n Context extends Record<string, unknown> = Record<string, never>,\n Event extends MachineEvent = MachineEvent,\n>(): <State extends string>(definition: MachineConfig<State, Context, Event>) => Machine<State, Context, Event>;\n```\n\nReturns a factory that accepts a typed flat machine definition. The definition is trusted as typed: targets, callback shapes, and state keys are compiler-checked. `defineMachine()` rejects only what types cannot express: timer delays outside `0..2,147,483,647` ms, empty transition arrays, and a context that is not a plain record (arrays, `null`, and class instances fail). Omit `context` only when the context type has no keys.\n\nThe curried signature is required so TypeScript can infer `State` from the `states` object while you explicitly provide `Context` and `Event`. TypeScript does not support partial type argument inference, so the state-key union cannot be inferred in a single non-curried call when the context and event generics are explicit.\n\n**Returns:** A definition function that returns `Machine`.\n\n**Example:**\n\n```ts\nimport { defineMachine } from '@vielzeug/clockwork';\n\ntype Event = { type: 'START' };\n\nconst machine = defineMachine<Record<string, never>, Event>()({\n initial: 'idle',\n states: { idle: { on: { START: { target: 'running' } } }, running: {} },\n});\n```\n\nThrows `ClockworkDefinitionError` when a definition carries a timer delay outside the platform range, an empty transition array, or a context that is not a plain record.\n\n---\n\n### `Actor.subscribe()`\n\n```ts\nsubscribe(listener: (snapshot: MachineSnapshot<State, Context>) => void): () => void;\n```\n\nSubscribes to future committed actor snapshots. It does not run immediately; read `actor.snapshot` for the initial value. Returns an unsubscribe function. Subscriber failures are reported through `tap()` as `error` events with `phase: 'subscriber'` without stopping remaining subscribers, declared effects, or the actor.\n\n**Example:**\n\n```ts\nimport { defineMachine } from '@vielzeug/clockwork';\n\nconst machine = defineMachine<Record<string, never>, { type: 'NEXT' }>()({\n initial: 'idle',\n states: { idle: { on: { NEXT: { target: 'idle' } } } },\n});\n\nconst actor = machine.createActor();\nconst stop = actor.subscribe((snapshot) => console.debug(snapshot));\nactor.send({ type: 'NEXT' });\nstop();\nactor.dispose();\n```\n\n## Machine Methods\n\n### `machine.transition()`\n\n```ts\ntransition(\n snapshot: MachineSnapshot<State, Context>,\n event: Event,\n): TransitionResult<State, Context>;\n```\n\nResolves a snapshot for one user event without actor runtime work.\n\n| Parameter | Type | Description |\n| ---------- | --------------------------------- | ----------------------- |\n| `snapshot` | `MachineSnapshot<State, Context>` | Input state and context |\n| `event` | `Event` | User event to evaluate |\n\n**Returns:** A `TransitionResult` with `transition` or `ignored` type.\n\n**Example:**\n\n```ts\nconst result = machine.transition(machine.initialSnapshot, { type: 'START' });\n```\n\n---\n\n### `machine.can()`\n\n```ts\ncan(snapshot: MachineSnapshot<State, Context>, event: Event): boolean;\n```\n\nReturns whether a transition exists and its guard passes.\n\n**Returns:** `true` when the supplied snapshot accepts the event.\n\n---\n\n### `machine.createActor()`\n\n```ts\ncreateActor(options?: ActorOptions<State, Context>): Actor<State, Context, Event>;\n```\n\nCreates an independent actor for event dispatch, timers, invokes, effects, subscriptions, and disposal. A fresh actor starts the initial state's entry effects and resources. An actor restored with `options.snapshot` starts only the restored state's resources: invokes and timers, not entry effects.\n\n| Parameter | Type | Description |\n| ------------------ | --------------------------------- | -------------------------------- |\n| `options.snapshot` | `MachineSnapshot<State, Context>` | Optional restored actor snapshot |\n\n**Returns:** Disposable `Actor`.\n\n**Example:**\n\n```ts\nconst actor = machine.createActor({ snapshot: { context: {}, state: 'idle' } });\n```\n\n## Actor Methods\n\n### `actor.send()`\n\n```ts\nsend(event: Event): void;\n```\n\nDispatches a user event to the current actor state. Events sent while the actor is processing queue and flush synchronously; sends to a disposed actor are ignored. For active actors, malformed events without a string `type` log a development warning and are ignored. Valid but unhandled event types are ignored without a warning. Use `actor.snapshot` after sending to read the current snapshot.\n\n**Returns:** Nothing.\n\n---\n\n### `actor.can()`\n\n```ts\ncan(event: Event): boolean;\n```\n\nReturns whether the current actor snapshot accepts an event. A guard failure is reported as a fatal transition error, disposes the actor, and returns `false`. Returns `false` after disposal.\n\n**Returns:** Boolean transition availability.\n\n---\n\n### `actor.subscribe()`\n\n```ts\nsubscribe(listener: (snapshot: MachineSnapshot<State, Context>) => void): () => void;\n```\n\nRegisters a listener for committed snapshots. The listener does not run immediately.\n\n**Returns:** An unsubscribe function.\n\n---\n\n### `actor.dispose()`\n\n```ts\ndispose(): void;\n[Symbol.dispose](): void;\n```\n\nCancels timers and invokes, clears queued events, tappers and listeners, emits a final `dispose` tap event, and aborts `disposalSignal`.\n\n**Returns:** Nothing. Idempotent.\n\n### `actor.tap()`\n\n```ts\ntap(\n handler: (event: ActorTapEvent<State, Context, Event>) => void,\n options?: { signal?: AbortSignal },\n): () => void;\n```\n\nObserves actor lifecycle without affecting machine behavior: `{ type: 'transition' | 'ignored' }` carries the event and resulting snapshot, `{ type: 'error' }` carries the error with its `phase`/`state`/`event` context, and `{ type: 'dispose' }` is the final event before tappers are cleared. Handler errors are swallowed. Returns an unsubscribe function.\n\n```ts\nactor.tap((event) => {\n if (event.type === 'error') console.error(event.phase, event.state, event.error);\n});\n```\n\n## Error Handling Policy\n\nMachine-execution failures are fail-stop: guard, reducer, effect, invoke, timer, and queued-transition-limit failures dispose the actor. The queued-transition limit is a fixed internal guard against runaway loops, not a configurable option. Subscriber failures are observational: Clockwork reports them through `tap()`, continues the stable subscriber snapshot and declared effects, and keeps the actor active. Tap handlers cannot control disposition.\n\nSubscriber iteration uses a stable snapshot: listeners added during notification begin with the next transition.\n\n## Types\n\n### `MachineSnapshot<State, Context>`\n\n```ts\ntype MachineSnapshot<State extends string, Context extends Record<string, unknown>> = {\n readonly context: Readonly<Context>;\n readonly state: State;\n};\n```\n\nClockwork shallow-clones and freezes each snapshot and its context record. Nested context values remain caller-owned and are not deep-frozen.\n\n### `MachineConfig<State, Context, Event>`\n\n```ts\ntype MachineConfig<\n State extends string,\n Context extends Record<string, unknown>,\n Event extends MachineEvent,\n> = (keyof Context extends never ? { readonly context?: Context } : { readonly context: Context }) & {\n readonly initial: State;\n readonly states: Record<State, StateNode<State, Context, Event>>;\n};\n```\n\nA flat machine definition. State nodes cannot contain child states. The `StateNode`, `Transition`, `After`, `Invoke`, `Effect`, `Guard`, and `Reducer` shapes are inferred inline and exported for reusable helpers. `After.delay` must be finite and between 0 and 2,147,483,647 milliseconds; delayed guards and reducers receive `event: undefined`.\n\n### `Actor<State, Context, Event>`\n\n```ts\ntype Actor<State extends string, Context extends Record<string, unknown>, Event extends MachineEvent> = {\n [Symbol.dispose](): void;\n can(event: Event): boolean;\n readonly disposalSignal: AbortSignal;\n dispose(): void;\n readonly disposed: boolean;\n send(event: Event): void;\n readonly snapshot: MachineSnapshot<State, Context>;\n subscribe(listener: (snapshot: MachineSnapshot<State, Context>) => void): () => void;\n tap(\n handler: (event: ActorTapEvent<State, Context, Event>) => void,\n options?: { readonly signal?: AbortSignal },\n ): () => void;\n};\n```\n\nAn actor's `snapshot` is the current plain readonly snapshot.\n\n### `ActorTapEvent<State, Context, Event>`\n\n```ts\ntype ActorTapEvent<State, Context, Event> =\n | (ActorErrorContext<State, Event> & { readonly error: unknown; readonly type: 'error' })\n | {\n readonly event: Event | undefined;\n readonly snapshot: MachineSnapshot<State, Context>;\n readonly type: 'transition' | 'ignored';\n }\n | { readonly type: 'dispose' };\n\ntype ActorErrorContext<State, Event> = {\n readonly event?: Event;\n readonly phase: 'effect' | 'invoke' | 'subscriber' | 'transition';\n readonly state: State;\n};\n```\n\n### `Machine<State, Context, Event>`\n\n```ts\ntype Machine<State extends string, Context extends Record<string, unknown>, Event extends MachineEvent> = {\n can(snapshot: MachineSnapshot<State, Context>, event: Event): boolean;\n createActor(options?: ActorOptions<State, Context>): Actor<State, Context, Event>;\n readonly initialSnapshot: MachineSnapshot<State, Context>;\n transition(snapshot: MachineSnapshot<State, Context>, event: Event): TransitionResult<State, Context>;\n};\n```\n\nA reusable machine. Its state and event lookups are own-property guarded, so unknown or prototype-colliding names such as `__proto__` or `constructor` are safely ignored when no transition exists.\n\n## Errors\n\n### `ClockworkError`\n\n`ClockworkError` is the base class for every Clockwork failure, with `details` and standard `Error` fields. Use `instanceof ClockworkError` to narrow an unknown error. Three subtypes carry the failure category:\n\n| Subtype | Raised when |\n| ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |\n| `ClockworkDefinitionError` | `defineMachine()` rejects a definition footgun types cannot express: a timer delay outside `0..2,147,483,647` ms, an empty transition array, or a context that is not a plain record |\n| `ClockworkSnapshotError` | A snapshot, its context, or a reducer result is not a plain object record, or names an undeclared state |\n| `ClockworkTransitionLimitError` | An actor exceeds the fixed queued-transition limit and disposes itself |\n\n```ts\nif (error instanceof ClockworkDefinitionError) {\n console.error(error.message, error.details);\n}\n```\n",
6
- "usage": "---\ntitle: 'Clockwork: Usage Guide'\ndescription: Build deterministic state machines with pure transitions and actor-owned runtime work.\n---\n\n[[toc]]\n\n## Basic Usage\n\nCall `defineMachine<Context, Event>()` first to bind context and event types; the returned definition function infers state labels from `states`. Context is optional only when its type has no keys. Create one actor for each independently owned workflow.\n\n```ts\nimport { defineMachine } from '@vielzeug/clockwork';\n\ntype Event = { type: 'TOGGLE' };\n\nconst machine = defineMachine<Record<string, never>, Event>()({\n initial: 'on',\n states: {\n off: { on: { TOGGLE: { target: 'on' } } },\n on: { on: { TOGGLE: { target: 'off' } } },\n },\n});\n\nconst actor = machine.createActor();\nactor.send({ type: 'TOGGLE' });\nconsole.log(actor.snapshot.state); // 'off'\nactor.dispose();\n```\n\nDispose actors when a feature, request, or test ends. You can use `using` when the surrounding runtime supports `Symbol.dispose`.\n\n```ts\nusing actor = machine.createActor();\nactor.send({ type: 'TOGGLE' });\n```\n\n## Context reducers\n\nA reducer receives readonly context and returns the next context. Clockwork shallow-clones and freezes each snapshot and context record; nested values are not deep-cloned, so make explicit nested replacements.\n\n```ts\ntype Event = { type: 'DEC' } | { type: 'INC' } | { type: 'RESET' };\n\nconst counter = defineMachine<{ count: number }, Event>()({\n context: { count: 0 },\n initial: 'idle',\n states: {\n idle: {\n on: {\n DEC: { reduce: ({ context }) => ({ count: context.count - 1 }), target: 'idle' },\n INC: { reduce: ({ context }) => ({ count: context.count + 1 }), target: 'idle' },\n RESET: { reduce: () => ({ count: 0 }), target: 'idle' },\n },\n },\n },\n});\n```\n\nKeep reducers pure. Make nested copies yourself when nested data changes.\n\n```ts\nSAVE: {\n reduce: ({ context, event }) => ({\n ...context,\n profile: { ...context.profile, name: event.name },\n }),\n target: 'editing',\n}\n```\n\n## Guards\n\nGuards decide whether a transition can run. They receive readonly context and the matching event. For several choices, use an ordered array; the first passing guard wins.\n\n```ts\nPAY: [\n {\n guard: ({ context }) => context.balance >= context.total,\n reduce: ({ context }) => ({ ...context, balance: context.balance - context.total }),\n target: 'success',\n },\n { target: 'insufficientFunds' },\n];\n```\n\nCall `actor.can(event)` for the current actor snapshot or `machine.can(snapshot, event)` for an arbitrary snapshot.\n\n## Pure transitions\n\n`machine.transition()` enables isolated unit tests and decision UIs. It returns the unchanged snapshot with `type: 'ignored'` when no transition matches; it does not expose or run effects.\n\n```ts\nconst result = counter.transition({ context: { count: 3 }, state: 'idle' }, { type: 'INC' });\n\nif (result.type === 'transition') {\n console.log(result.snapshot.context.count); // 4\n}\n```\n\n## Effects\n\nEntry, exit, and transition effects run only through an actor. The actor commits, establishes target-state timers and invokes, notifies a stable subscriber snapshot, then runs exit, transition, and entry effects. Subscriber failures are reported but cannot skip declared effects. Effects cannot change context; send a regular event for another state change.\n\n```ts\ntype WorkflowEvent = { type: 'SUBMIT' };\nconst workflow = defineMachine<{ orderId: string }, WorkflowEvent>()({\n context: { orderId: '' },\n initial: 'draft',\n states: {\n draft: {\n on: {\n SUBMIT: {\n effects: [({ context }) => console.debug('submitted', context)],\n target: 'submitted',\n },\n },\n },\n submitted: { entry: [({ context }) => console.log(`Submitted ${context.orderId}`)] },\n },\n});\n```\n\nEffects receive `context`, the triggering `event` (or `undefined` for initial entry), actor `send`, and the actor lifetime `signal`.\n\n## Async invokes\n\nInvokes start on state entry. `src` gets readonly entry context, the triggering event or `undefined`, and an `AbortSignal`. `onDone` or `onError` map settlement to ordinary events. All invokes are cancelled when the actor exits the state or disposes.\n\n```ts\ntype LoadEvent =\n | { type: 'FETCH' }\n | { items: string[]; type: 'SUCCESS' }\n | { message: string; type: 'FAILURE' }\n | { type: 'RETRY' };\n\nconst loader = defineMachine<{ error: string; items: string[] }, LoadEvent>()({\n context: { error: '', items: [] },\n initial: 'idle',\n states: {\n idle: { on: { FETCH: { target: 'loading' } } },\n loading: {\n invoke: [\n {\n src: async ({ signal }) => {\n const response = await fetch('/api/items', { signal });\n if (!response.ok) throw new Error(`HTTP ${response.status}`);\n return response.json() as Promise<string[]>;\n },\n onDone: ({ result }) => ({ items: result, type: 'SUCCESS' }),\n onError: ({ error }) => ({ message: String(error), type: 'FAILURE' }),\n },\n ],\n on: {\n FAILURE: { reduce: ({ event }) => ({ error: event.message, items: [] }), target: 'error' },\n SUCCESS: { reduce: ({ event }) => ({ error: '', items: event.items }), target: 'ready' },\n },\n },\n ready: {},\n error: { on: { RETRY: { target: 'loading' } } },\n },\n});\n```\n\n## Delayed transitions\n\n`after` starts timers on state entry and cancels them on exit or disposal. Delay must be finite and between 0 and 2,147,483,647 milliseconds. Guards and reducers receive `event: undefined`; a user event with `type: '$after'` remains a normal user event.\n\n```ts\ntype NotificationEvent = { type: 'DISMISS' } | { message: string; type: 'SHOW' };\nconst notification = defineMachine<{ message: string }, NotificationEvent>()({\n context: { message: '' },\n initial: 'hidden',\n states: {\n hidden: { on: { SHOW: { reduce: ({ event }) => ({ message: event.message }), target: 'visible' } } },\n visible: {\n after: [{ delay: 5_000, target: 'hidden' }],\n on: { DISMISS: { target: 'hidden' } },\n },\n },\n});\n```\n\n## Snapshot observation and persistence\n\n`actor.snapshot` is the current shallow-frozen `MachineSnapshot`; read it directly rather than calling a snapshot method. Use `subscribe()` to integrate a state library or persist future committed snapshots. Fresh actors run their initial entry effects and resources; restored actors start only the restored state's invokes and timers, not its entry effects.\n\n```ts\nconst stored = sessionStorage.getItem('wizard');\nconst actor = machine.createActor({\n snapshot: stored ? JSON.parse(stored) : undefined,\n});\n\nconst stopSaving = actor.subscribe((snapshot) => {\n sessionStorage.setItem('wizard', JSON.stringify(snapshot));\n});\n\nconsole.log(actor.snapshot);\nstopSaving();\nactor.dispose();\n```\n\nValidate untrusted persisted data before passing it to `createActor()`. Clockwork validates the restored state name but cannot validate application-specific context fields.\n\n## Error handling\n\nGuard, reducer, effect, invoke, timer, and transition-limit failures dispose the actor. The transition limit is a fixed internal guard against runaway loops. Subscriber failures are reported but do not dispose the actor or interrupt remaining subscribers and declared effects.\n\nUse `tap()` to observe either class without controlling disposition. The `error` event carries the error and its `phase` and `state`; handler failures are swallowed so observation cannot alter actor behavior.\n\n```ts\nconst actor = machine.createActor();\nactor.tap((event) => {\n if (event.type === 'error')\n console.error({ error: event.error, event: event.event, phase: event.phase, state: event.state });\n});\n```\n\nFor fatal machine failures, the `error` event is emitted before disposal. Without a tap handler, fatal failures dispose silently.\n\n## Debugging\n\nUse `actor.subscribe()` to observe committed snapshots during development. It observes snapshots only; it does not trace dispatched events or runtime errors.\n\n```ts\nconst actor = machine.createActor();\nconst stop = actor.subscribe((snapshot) => console.debug(snapshot));\nactor.send({ type: 'NEXT' });\nstop();\nactor.dispose();\n```\n\nFor richer inspection, route snapshots to application devtools. Clockwork intentionally has no internal trace buffer.\n\n## Flat state maps\n\nClockwork has flat state IDs. Prefer explicit states such as `editingDraft` and `editingSaving`, or compose several actors when domains have independent lifecycles.\n\n## SSR\n\nReuse one machine definition, but create and dispose an actor per request. Never share an actor across concurrent requests.\n\n## Testing\n\nTest deterministic state behavior through `machine.transition()`. Create actors only for timers, invokes, effects, queueing, subscriptions, or disposal behavior.\n\n```ts\nimport { expect, test } from 'vitest';\n\ntest('increments without an actor', () => {\n const result = counter.transition({ context: { count: 2 }, state: 'idle' }, { type: 'INC' });\n\n expect(result).toMatchObject({\n snapshot: { context: { count: 3 }, state: 'idle' },\n type: 'transition',\n });\n});\n```\n\n## Framework Integration\n\nBridge the current actor snapshot into renderer state through one subscription. Dispose that subscription with component lifecycle.\n\n::: code-group\n\n```ts [React]\nimport { useSyncExternalStore } from 'react';\n\nfunction useActor<Value>(actor: {\n readonly snapshot: Value;\n subscribe(listener: (snapshot: Value) => void): () => void;\n}) {\n return useSyncExternalStore(\n (notify) => actor.subscribe(() => notify()),\n () => actor.snapshot,\n () => actor.snapshot,\n );\n}\n```\n\n```ts [Vue 3]\nimport { onUnmounted, shallowRef } from 'vue';\n\nconst snapshot = shallowRef(actor.snapshot);\nconst stop = actor.subscribe((next) => (snapshot.value = next));\nonUnmounted(stop);\n```\n\n```ts [Svelte]\nimport { onDestroy } from 'svelte';\n\nlet snapshot = actor.snapshot;\nconst stop = actor.subscribe((next) => (snapshot = next));\nonDestroy(stop);\n```\n\n:::\n\n## Working with Other Vielzeug Libraries\n\nUse Herald when separate actors exchange application events. Bridge Clockwork snapshots into Ripple only at a UI or application boundary.\n\n```ts\nimport { createBus } from '@vielzeug/herald';\n\nconst bus = createBus<{ REFRESH: void }>();\nbus.on('REFRESH', () => actor.send({ type: 'FETCH' }));\n```\n\n## Best Practices\n\n- Define context and event unions with `defineMachine<Context, Event>()`.\n- Return replacement context from reducers; do not rely on runtime copying or freezing.\n- Keep guards and reducers pure.\n- Use actors for effects, timers, invokes, subscriptions, and cancellation.\n- Read the current snapshot from `actor.snapshot`, not a wrapper value.\n- Validate persisted context before restoring a snapshot.\n- Dispose every actor at its ownership boundary.\n- Route runtime failures through the `tap()` observer for logging and diagnostics.\n",
4
+ "index": "---\ntitle: 'Clockwork: Typed finite state machines for TypeScript'\ndescription: Framework-neutral typed state machines with pure transitions, actor-owned runtime work, timers, invokes, and explicit effects.\npackage: clockwork\ncategory: state\nkeywords: [state-machine, finite-state, typed, actor, async-tasks]\nrelated: [herald, ripple, ward]\nexports: [defineMachine, ClockworkError, Machine, Actor, MachineConfig, MachineSnapshot]\nenvironments: [browser, node, ssr, deno]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"clockwork\" />\n\n## Why Clockwork?\n\nApplication workflows often mix state changes with timers, requests, rendering, and cleanup. Clockwork keeps transition logic pure while each disposable actor owns runtime work. You can test state decisions without starting effects or invokes.\n\n```ts\nimport { defineMachine } from '@vielzeug/clockwork';\n\n// Before\nif (status === 'idle') status = 'loading';\nfetchItems().then((items) => {\n status = 'ready';\n data = items;\n});\n\n// After\ntype Event = { type: 'FETCH' } | { items: string[]; type: 'DONE' };\nconst machine = defineMachine<{ items: string[] }, Event>()({\n context: { items: [] },\n initial: 'idle',\n states: {\n idle: { on: { FETCH: { target: 'loading' } } },\n loading: {\n invoke: [\n {\n src: ({ signal }) => fetch('/api/items', { signal }).then((response) => response.json() as Promise<string[]>),\n onDone: ({ result }) => ({ items: result as string[], type: 'DONE' }),\n },\n ],\n on: { DONE: { reduce: ({ event }) => ({ items: event.items }), target: 'ready' } },\n },\n ready: {},\n },\n});\n```\n\n| Feature | Clockwork | XState | Zustand |\n| ------------------- | ----------------------------------------------------------- | ------------------------------------------------------------------------ | ------------------------------------------------- |\n| Bundle size | <PackageInfo package=\"clockwork\" type=\"size\" /> | Larger actor/statechart runtime | Smaller store runtime |\n| Zero dependencies | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n| Pure transition API | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"triangle-alert\" size=\"16\"></ore-icon> Statechart-focused | <ore-icon name=\"x\" size=\"16\"></ore-icon> |\n| Owned cancellation | <ore-icon name=\"check\" size=\"16\"></ore-icon> Actor disposal | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> |\n| Framework coupling | <ore-icon name=\"check\" size=\"16\"></ore-icon> None | <ore-icon name=\"check\" size=\"16\"></ore-icon> None | <ore-icon name=\"check\" size=\"16\"></ore-icon> None |\n\n<div class=\"decision-callout\">\n\n**Use Clockwork when** your feature has explicit workflow states, cancellable work, or effects that must run after a state commit.\n\n**Consider XState when** you need statecharts, visual tooling, or its broader actor ecosystem.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/clockwork\n```\n\n```sh [npm]\nnpm install @vielzeug/clockwork\n```\n\n```sh [yarn]\nyarn add @vielzeug/clockwork\n```\n\n:::\n\n## Quick Start\n\nDefine the context and event union, create an actor, observe its snapshot, then dispose it when its owner ends.\n\n```ts\nimport { defineMachine } from '@vielzeug/clockwork';\n\ntype Event = { type: 'DEC' } | { type: 'INC' };\n\nconst counter = defineMachine<{ count: number }, Event>()({\n context: { count: 0 },\n initial: 'idle',\n states: {\n idle: {\n on: {\n DEC: { reduce: ({ context }) => ({ count: context.count - 1 }), target: 'idle' },\n INC: { reduce: ({ context }) => ({ count: context.count + 1 }), target: 'idle' },\n },\n },\n },\n});\n\nusing actor = counter.createActor();\nactor.subscribe((snapshot) => console.log(snapshot));\nactor.send({ type: 'INC' });\n// { context: { count: 1 }, state: 'idle' }\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- **`defineMachine()`**: defines one flat, typed machine and rejects the footguns types cannot express.\n- **`machine.transition()`**: evaluates a transition without actor runtime work.\n- **`machine.createActor()`**: creates isolated, disposable runtime ownership.\n- **`reduce`**: returns a replacement context from a transition.\n- **`effects`**: run after commit and stable subscriber notification.\n- **`invoke`**: runs cancellable asynchronous work on state entry.\n- **`after`**: schedules cancellable delayed transitions.\n- **`actor.snapshot`**: exposes the current shallow-frozen state/context value.\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- [Herald](/herald/): publish events between independent actors without coupling machine definitions.\n- [Ripple](/ripple/): bridge actor snapshots into a reactive graph when you need fine-grained rendering.\n- [Ward](/ward/): call authorization predicates from transition guards.\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
5
+ "api": "---\ntitle: 'Clockwork: API Reference'\ndescription: Reference for Clockwork machine definitions, actors, and types.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| ----------------------- | ---------------------------------------------------------- | -------------- | ----------------------------------------------------------- |\n| `defineMachine()` | Define a typed flat machine | Sync | Call the generic factory before supplying the definition |\n| `Machine.transition()` | Resolve a pure next snapshot | Sync | Does not run effects, invokes, or timers |\n| `Machine.createActor()` | Create a runtime owner | Sync | Fresh and restored actors have different entry behavior |\n| `Actor.send()` | Dispatch an event | Sync | Returns `void`; re-entrant events queue internally |\n| `Actor.subscribe()` | Observe committed snapshots | Sync | Observes only; it does not trace sends or errors |\n| `Actor.tap()` | Observe transitions, ignores, errors, disposal | Sync | Handler errors are swallowed; it cannot control disposition |\n| `ClockworkError` | Report definition, snapshot, and transition-limit failures | Sync | Narrow with the error subtypes, not message text |\n\n## Package Entry Points\n\n| Import | Purpose |\n| --------------------- | ------------------------------------------------- |\n| `@vielzeug/clockwork` | Machine factory, actor runtime, errors, and types |\n\n## Exported Surface\n\nCallback parameter types are inferred for inline definitions. Clockwork also exports reusable callback, transition, state-node, actor-option, result, and error-context types for shared helpers.\n\n| Primary export | Kind |\n| ------------------------------- | -------- |\n| `defineMachine` | Function |\n| `Machine` | Type |\n| `Actor` | Type |\n| `MachineSnapshot` | Type |\n| `MachineConfig` | Type |\n| `ClockworkError` | Class |\n| `ClockworkDefinitionError` | Class |\n| `ClockworkSnapshotError` | Class |\n| `ClockworkTransitionLimitError` | Class |\n\nAdditional exported types: `ActorErrorContext`, `ActorOptions`, `ActorTapEvent`, `After`, `Effect`, `EffectArgs`, `EventByType`, `EventType`, `Guard`, `Invoke`, `InvokeArgs`, `MachineEvent`, `Reducer`, `StateNode`, `Transition`, `TransitionInput`, and `TransitionResult`.\n\n## Core Functions\n\n### `defineMachine()`\n\n```ts\nfunction defineMachine<\n Context extends Record<string, unknown> = Record<string, never>,\n Event extends MachineEvent = MachineEvent,\n>(): <State extends string>(definition: MachineConfig<State, Context, Event>) => Machine<State, Context, Event>;\n```\n\nReturns a factory that accepts a typed flat machine definition. The definition is trusted as typed: targets, callback shapes, and state keys are compiler-checked. `defineMachine()` rejects only what types cannot express: timer delays outside `0..2,147,483,647` ms, empty transition arrays, and a context that is not a plain record (arrays, `null`, and class instances fail). Omit `context` only when the context type has no keys.\n\nThe curried signature is required so TypeScript can infer `State` from the `states` object while you explicitly provide `Context` and `Event`. TypeScript does not support partial type argument inference, so the state-key union cannot be inferred in a single non-curried call when the context and event generics are explicit.\n\n**Returns:** A definition function that returns `Machine`.\n\n**Example:**\n\n```ts\nimport { defineMachine } from '@vielzeug/clockwork';\n\ntype Event = { type: 'START' };\n\nconst machine = defineMachine<Record<string, never>, Event>()({\n initial: 'idle',\n states: { idle: { on: { START: { target: 'running' } } }, running: {} },\n});\n```\n\nThrows `ClockworkDefinitionError` when a definition carries a timer delay outside the platform range, an empty transition array, or a context that is not a plain record.\n\n---\n\n### `Actor.subscribe()`\n\n```ts\nsubscribe(\n listener: (snapshot: MachineSnapshot<State, Context>) => void,\n options?: { readonly signal?: AbortSignal },\n): () => void;\n```\n\nSubscribes to future committed actor snapshots. It does not run immediately; read `actor.snapshot` for the initial value. `options.signal` auto-unsubscribes when the signal aborts; an already-aborted signal creates no subscription. Returns an unsubscribe function. Subscriber failures are reported through `tap()` as `error` events with `phase: 'subscriber'` without stopping remaining subscribers, declared effects, or the actor.\n\n**Example:**\n\n```ts\nimport { defineMachine } from '@vielzeug/clockwork';\n\nconst machine = defineMachine<Record<string, never>, { type: 'NEXT' }>()({\n initial: 'idle',\n states: { idle: { on: { NEXT: { target: 'idle' } } } },\n});\n\nconst actor = machine.createActor();\nconst stop = actor.subscribe((snapshot) => console.debug(snapshot));\nactor.send({ type: 'NEXT' });\nstop();\nactor.dispose();\n```\n\n## Machine Methods\n\n### `machine.transition()`\n\n```ts\ntransition(\n snapshot: MachineSnapshot<State, Context>,\n event: Event,\n): TransitionResult<State, Context>;\n```\n\nResolves a snapshot for one user event without actor runtime work.\n\n| Parameter | Type | Description |\n| ---------- | --------------------------------- | ----------------------- |\n| `snapshot` | `MachineSnapshot<State, Context>` | Input state and context |\n| `event` | `Event` | User event to evaluate |\n\n**Returns:** A `TransitionResult` with `transition` or `ignored` type.\n\n**Example:**\n\n```ts\nconst result = machine.transition(machine.initialSnapshot, { type: 'START' });\n```\n\n---\n\n### `machine.can()`\n\n```ts\ncan(snapshot: MachineSnapshot<State, Context>, event: Event): boolean;\n```\n\nReturns whether a transition exists and its guard passes.\n\n**Returns:** `true` when the supplied snapshot accepts the event.\n\n---\n\n### `machine.createActor()`\n\n```ts\ncreateActor(options?: ActorOptions<State, Context>): Actor<State, Context, Event>;\n```\n\nCreates an independent actor for event dispatch, timers, invokes, effects, subscriptions, and disposal. A fresh actor starts the initial state's entry effects and resources. An actor restored with `options.snapshot` starts only the restored state's resources: invokes and timers, not entry effects.\n\n| Parameter | Type | Description |\n| ------------------ | --------------------------------- | -------------------------------- |\n| `options.snapshot` | `MachineSnapshot<State, Context>` | Optional restored actor snapshot |\n\n**Returns:** Disposable `Actor`.\n\n**Example:**\n\n```ts\nconst actor = machine.createActor({ snapshot: { context: {}, state: 'idle' } });\n```\n\n## Actor Methods\n\n### `actor.send()`\n\n```ts\nsend(event: Event): void;\n```\n\nDispatches a user event to the current actor state. Events sent while the actor is processing queue and flush synchronously; sends to a disposed actor are ignored. For active actors, malformed events without a string `type` log a development warning and are ignored. Valid but unhandled event types are ignored without a warning. Use `actor.snapshot` after sending to read the current snapshot.\n\n**Returns:** Nothing.\n\n---\n\n### `actor.can()`\n\n```ts\ncan(event: Event): boolean;\n```\n\nReturns whether the current actor snapshot accepts an event. A guard failure is reported as a fatal transition error, disposes the actor, and returns `false`. Returns `false` after disposal.\n\n**Returns:** Boolean transition availability.\n\n---\n\n### `actor.subscribe()`\n\n```ts\nsubscribe(\n listener: (snapshot: MachineSnapshot<State, Context>) => void,\n options?: { readonly signal?: AbortSignal },\n): () => void;\n```\n\nRegisters a listener for committed snapshots. The listener does not run immediately. `options.signal` auto-unsubscribes on abort; an already-aborted signal creates no subscription.\n\n**Returns:** An unsubscribe function.\n\n---\n\n### `actor.dispose()`\n\n```ts\ndispose(): void;\n[Symbol.dispose](): void;\n```\n\nCancels timers and invokes, clears queued events, tappers and listeners, emits a final `dispose` tap event, and aborts `disposalSignal`.\n\n**Returns:** Nothing. Idempotent.\n\n### `actor.tap()`\n\n```ts\ntap(\n handler: (event: ActorTapEvent<State, Context, Event>) => void,\n options?: { signal?: AbortSignal },\n): () => void;\n```\n\nObserves actor lifecycle without affecting machine behavior: `{ type: 'transition' | 'ignored' }` carries the event and resulting snapshot, `{ type: 'error' }` carries the error with its `phase`/`state`/`event` context, and `{ type: 'dispose' }` is the final event before tappers are cleared. Handler errors are swallowed. Returns an unsubscribe function.\n\n```ts\nactor.tap((event) => {\n if (event.type === 'error') console.error(event.phase, event.state, event.error);\n});\n```\n\n## Error Handling Policy\n\nMachine-execution failures are fail-stop: guard, reducer, effect, invoke, timer, and queued-transition-limit failures dispose the actor. The queued-transition limit is a fixed internal guard against runaway loops, not a configurable option. Subscriber failures are observational: Clockwork reports them through `tap()`, continues the stable subscriber snapshot and declared effects, and keeps the actor active. Tap handlers cannot control disposition.\n\nSubscriber iteration uses a stable snapshot: listeners added during notification begin with the next transition.\n\n## Types\n\n### `MachineSnapshot<State, Context>`\n\n```ts\ntype MachineSnapshot<State extends string, Context extends Record<string, unknown>> = {\n readonly context: Readonly<Context>;\n readonly state: State;\n};\n```\n\nClockwork shallow-clones and freezes each snapshot and its context record. Nested context values remain caller-owned and are not deep-frozen.\n\n### `MachineConfig<State, Context, Event>`\n\n```ts\ntype MachineConfig<\n State extends string,\n Context extends Record<string, unknown>,\n Event extends MachineEvent,\n> = (keyof Context extends never ? { readonly context?: Context } : { readonly context: Context }) & {\n readonly initial: State;\n readonly states: Record<State, StateNode<State, Context, Event>>;\n};\n```\n\nA flat machine definition. State nodes cannot contain child states. The `StateNode`, `Transition`, `After`, `Invoke`, `Effect`, `Guard`, and `Reducer` shapes are inferred inline and exported for reusable helpers. `After.delay` must be finite and between 0 and 2,147,483,647 milliseconds; delayed guards and reducers receive `event: undefined`. `Invoke` inside a state node fixes its `Result` to `unknown`, so `onDone` receives `result: unknown`; narrow or cast where the result enters your mapped event.\n\n### `Actor<State, Context, Event>`\n\n```ts\ntype Actor<State extends string, Context extends Record<string, unknown>, Event extends MachineEvent> = {\n [Symbol.dispose](): void;\n can(event: Event): boolean;\n readonly disposalSignal: AbortSignal;\n dispose(): void;\n readonly disposed: boolean;\n send(event: Event): void;\n readonly snapshot: MachineSnapshot<State, Context>;\n subscribe(listener: (snapshot: MachineSnapshot<State, Context>) => void): () => void;\n tap(\n handler: (event: ActorTapEvent<State, Context, Event>) => void,\n options?: { readonly signal?: AbortSignal },\n ): () => void;\n};\n```\n\nAn actor's `snapshot` is the current plain readonly snapshot.\n\n### `ActorTapEvent<State, Context, Event>`\n\n```ts\ntype ActorTapEvent<State, Context, Event> =\n | (ActorErrorContext<State, Event> & { readonly error: unknown; readonly type: 'error' })\n | {\n readonly event: Event | undefined;\n readonly snapshot: MachineSnapshot<State, Context>;\n readonly type: 'transition' | 'ignored';\n }\n | { readonly type: 'dispose' };\n\ntype ActorErrorContext<State, Event> = {\n readonly event?: Event;\n readonly phase: 'effect' | 'invoke' | 'subscriber' | 'transition';\n readonly state: State;\n};\n```\n\n### `Machine<State, Context, Event>`\n\n```ts\ntype Machine<State extends string, Context extends Record<string, unknown>, Event extends MachineEvent> = {\n can(snapshot: MachineSnapshot<State, Context>, event: Event): boolean;\n createActor(options?: ActorOptions<State, Context>): Actor<State, Context, Event>;\n readonly initialSnapshot: MachineSnapshot<State, Context>;\n transition(snapshot: MachineSnapshot<State, Context>, event: Event): TransitionResult<State, Context>;\n};\n```\n\nA reusable machine. Its state and event lookups are own-property guarded, so unknown or prototype-colliding names such as `__proto__` or `constructor` are safely ignored when no transition exists.\n\n## Errors\n\n### `ClockworkError`\n\n`ClockworkError` is the base class for every Clockwork failure, with `details` and standard `Error` fields. Use `instanceof ClockworkError` to narrow an unknown error. Three subtypes carry the failure category:\n\n| Subtype | Raised when |\n| ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |\n| `ClockworkDefinitionError` | `defineMachine()` rejects a definition footgun types cannot express: a timer delay outside `0..2,147,483,647` ms, an empty transition array, or a context that is not a plain record |\n| `ClockworkSnapshotError` | A snapshot, its context, or a reducer result is not a plain object record, or names an undeclared state |\n| `ClockworkTransitionLimitError` | An actor exceeds the fixed queued-transition limit and disposes itself |\n\n```ts\nif (error instanceof ClockworkDefinitionError) {\n console.error(error.message, error.details);\n}\n```\n",
6
+ "usage": "---\ntitle: 'Clockwork: Usage Guide'\ndescription: Build deterministic state machines with pure transitions and actor-owned runtime work.\n---\n\n[[toc]]\n\n## Basic Usage\n\nCall `defineMachine<Context, Event>()` first to bind context and event types; the returned definition function infers state labels from `states`. Context is optional only when its type has no keys. Create one actor for each independently owned workflow.\n\n```ts\nimport { defineMachine } from '@vielzeug/clockwork';\n\ntype Event = { type: 'TOGGLE' };\n\nconst machine = defineMachine<Record<string, never>, Event>()({\n initial: 'on',\n states: {\n off: { on: { TOGGLE: { target: 'on' } } },\n on: { on: { TOGGLE: { target: 'off' } } },\n },\n});\n\nconst actor = machine.createActor();\nactor.send({ type: 'TOGGLE' });\nconsole.log(actor.snapshot.state); // 'off'\nactor.dispose();\n```\n\nDispose actors when a feature, request, or test ends. You can use `using` when the surrounding runtime supports `Symbol.dispose`.\n\n```ts\nusing actor = machine.createActor();\nactor.send({ type: 'TOGGLE' });\n```\n\n## Context reducers\n\nA reducer receives readonly context and returns the next context. Clockwork shallow-clones and freezes each snapshot and context record; nested values are not deep-cloned, so make explicit nested replacements.\n\n```ts\ntype Event = { type: 'DEC' } | { type: 'INC' } | { type: 'RESET' };\n\nconst counter = defineMachine<{ count: number }, Event>()({\n context: { count: 0 },\n initial: 'idle',\n states: {\n idle: {\n on: {\n DEC: { reduce: ({ context }) => ({ count: context.count - 1 }), target: 'idle' },\n INC: { reduce: ({ context }) => ({ count: context.count + 1 }), target: 'idle' },\n RESET: { reduce: () => ({ count: 0 }), target: 'idle' },\n },\n },\n },\n});\n```\n\nKeep reducers pure. Make nested copies yourself when nested data changes.\n\n```ts\nSAVE: {\n reduce: ({ context, event }) => ({\n ...context,\n profile: { ...context.profile, name: event.name },\n }),\n target: 'editing',\n}\n```\n\n## Guards\n\nGuards decide whether a transition can run. They receive readonly context and the matching event. For several choices, use an ordered array; the first passing guard wins.\n\n```ts\nPAY: [\n {\n guard: ({ context }) => context.balance >= context.total,\n reduce: ({ context }) => ({ ...context, balance: context.balance - context.total }),\n target: 'success',\n },\n { target: 'insufficientFunds' },\n];\n```\n\nCall `actor.can(event)` for the current actor snapshot or `machine.can(snapshot, event)` for an arbitrary snapshot.\n\n## Pure transitions\n\n`machine.transition()` enables isolated unit tests and decision UIs. It returns the unchanged snapshot with `type: 'ignored'` when no transition matches; it does not expose or run effects.\n\n```ts\nconst result = counter.transition({ context: { count: 3 }, state: 'idle' }, { type: 'INC' });\n\nif (result.type === 'transition') {\n console.log(result.snapshot.context.count); // 4\n}\n```\n\n## Effects\n\nEntry, exit, and transition effects run only through an actor. The actor commits, establishes target-state timers and invokes, notifies a stable subscriber snapshot, then runs exit, transition, and entry effects. Subscriber failures are reported but cannot skip declared effects. Effects cannot change context; send a regular event for another state change.\n\n```ts\ntype WorkflowEvent = { type: 'SUBMIT' };\nconst workflow = defineMachine<{ orderId: string }, WorkflowEvent>()({\n context: { orderId: '' },\n initial: 'draft',\n states: {\n draft: {\n on: {\n SUBMIT: {\n effects: [({ context }) => console.debug('submitted', context)],\n target: 'submitted',\n },\n },\n },\n submitted: { entry: [({ context }) => console.log(`Submitted ${context.orderId}`)] },\n },\n});\n```\n\nEffects receive `context`, the triggering `event` (or `undefined` for initial entry), actor `send`, and the actor lifetime `signal`.\n\n## Async invokes\n\nInvokes start on state entry. `src` gets readonly entry context, the triggering event or `undefined`, and an `AbortSignal`. `onDone` or `onError` map settlement to ordinary events. All invokes are cancelled when the actor exits the state or disposes.\n\n`onDone` receives `result: unknown`: without a schema system the machine cannot tie one callback's parameter to each `src`'s concrete return type, so narrow or cast explicitly where the result enters your event.\n\n```ts\ntype LoadEvent =\n | { type: 'FETCH' }\n | { items: string[]; type: 'SUCCESS' }\n | { message: string; type: 'FAILURE' }\n | { type: 'RETRY' };\n\nconst loader = defineMachine<{ error: string; items: string[] }, LoadEvent>()({\n context: { error: '', items: [] },\n initial: 'idle',\n states: {\n idle: { on: { FETCH: { target: 'loading' } } },\n loading: {\n invoke: [\n {\n src: async ({ signal }) => {\n const response = await fetch('/api/items', { signal });\n if (!response.ok) throw new Error(`HTTP ${response.status}`);\n return response.json() as Promise<string[]>;\n },\n onDone: ({ result }) => ({ items: result as string[], type: 'SUCCESS' }),\n onError: ({ error }) => ({ message: String(error), type: 'FAILURE' }),\n },\n ],\n on: {\n FAILURE: { reduce: ({ event }) => ({ error: event.message, items: [] }), target: 'error' },\n SUCCESS: { reduce: ({ event }) => ({ error: '', items: event.items }), target: 'ready' },\n },\n },\n ready: {},\n error: { on: { RETRY: { target: 'loading' } } },\n },\n});\n```\n\n## Delayed transitions\n\n`after` starts timers on state entry and cancels them on exit or disposal. Delay must be finite and between 0 and 2,147,483,647 milliseconds. Guards and reducers receive `event: undefined`; a user event with `type: '$after'` remains a normal user event.\n\n```ts\ntype NotificationEvent = { type: 'DISMISS' } | { message: string; type: 'SHOW' };\nconst notification = defineMachine<{ message: string }, NotificationEvent>()({\n context: { message: '' },\n initial: 'hidden',\n states: {\n hidden: { on: { SHOW: { reduce: ({ event }) => ({ message: event.message }), target: 'visible' } } },\n visible: {\n after: [{ delay: 5_000, target: 'hidden' }],\n on: { DISMISS: { target: 'hidden' } },\n },\n },\n});\n```\n\n## Snapshot observation and persistence\n\n`actor.snapshot` is the current shallow-frozen `MachineSnapshot`; read it directly rather than calling a snapshot method. Use `subscribe()` to integrate a state library or persist future committed snapshots; pass `{ signal }` to auto-unsubscribe when an owner's lifetime ends. Fresh actors run their initial entry effects and resources; restored actors start only the restored state's invokes and timers, not its entry effects.\n\n```ts\nconst stored = sessionStorage.getItem('wizard');\nconst actor = machine.createActor({\n snapshot: stored ? JSON.parse(stored) : undefined,\n});\n\nconst stopSaving = actor.subscribe((snapshot) => {\n sessionStorage.setItem('wizard', JSON.stringify(snapshot));\n});\n\nconsole.log(actor.snapshot);\nstopSaving();\nactor.dispose();\n```\n\nValidate untrusted persisted data before passing it to `createActor()`. Clockwork validates the restored state name but cannot validate application-specific context fields.\n\n## Error handling\n\nGuard, reducer, effect, invoke, timer, and transition-limit failures dispose the actor. The transition limit is a fixed internal guard against runaway loops. Subscriber failures are reported but do not dispose the actor or interrupt remaining subscribers and declared effects.\n\nUse `tap()` to observe either class without controlling disposition. The `error` event carries the error and its `phase` and `state`; handler failures are swallowed so observation cannot alter actor behavior.\n\n```ts\nconst actor = machine.createActor();\nactor.tap((event) => {\n if (event.type === 'error')\n console.error({ error: event.error, event: event.event, phase: event.phase, state: event.state });\n});\n```\n\nFor fatal machine failures, the `error` event is emitted before disposal. Without a tap handler, fatal failures dispose silently.\n\n## Debugging\n\nUse `actor.subscribe()` to observe committed snapshots during development. It observes snapshots only; it does not trace dispatched events or runtime errors.\n\n```ts\nconst actor = machine.createActor();\nconst stop = actor.subscribe((snapshot) => console.debug(snapshot));\nactor.send({ type: 'NEXT' });\nstop();\nactor.dispose();\n```\n\nFor richer inspection, route snapshots to application devtools. Clockwork intentionally has no internal trace buffer.\n\n## Flat state maps\n\nClockwork has flat state IDs. Prefer explicit states such as `editingDraft` and `editingSaving`, or compose several actors when domains have independent lifecycles.\n\n## SSR\n\nReuse one machine definition, but create and dispose an actor per request. Never share an actor across concurrent requests.\n\n## Testing\n\nTest deterministic state behavior through `machine.transition()`. Create actors only for timers, invokes, effects, queueing, subscriptions, or disposal behavior.\n\n```ts\nimport { expect, test } from 'vitest';\n\ntest('increments without an actor', () => {\n const result = counter.transition({ context: { count: 2 }, state: 'idle' }, { type: 'INC' });\n\n expect(result).toMatchObject({\n snapshot: { context: { count: 3 }, state: 'idle' },\n type: 'transition',\n });\n});\n```\n\n## Framework Integration\n\nBridge the current actor snapshot into renderer state through one subscription. Dispose that subscription with component lifecycle.\n\n::: code-group\n\n```ts [React]\nimport { useSyncExternalStore } from 'react';\n\nfunction useActor<Value>(actor: {\n readonly snapshot: Value;\n subscribe(listener: (snapshot: Value) => void): () => void;\n}) {\n return useSyncExternalStore(\n (notify) => actor.subscribe(() => notify()),\n () => actor.snapshot,\n () => actor.snapshot,\n );\n}\n```\n\n```ts [Vue 3]\nimport { onUnmounted, shallowRef } from 'vue';\n\nconst snapshot = shallowRef(actor.snapshot);\nconst stop = actor.subscribe((next) => (snapshot.value = next));\nonUnmounted(stop);\n```\n\n```ts [Svelte]\nimport { onDestroy } from 'svelte';\n\nlet snapshot = actor.snapshot;\nconst stop = actor.subscribe((next) => (snapshot = next));\nonDestroy(stop);\n```\n\n:::\n\n## Working with Other Vielzeug Libraries\n\nUse Herald when separate actors exchange application events. Bridge Clockwork snapshots into Ripple only at a UI or application boundary.\n\n```ts\nimport { createBus } from '@vielzeug/herald';\n\nconst bus = createBus<{ REFRESH: void }>();\nbus.on('REFRESH', () => actor.send({ type: 'FETCH' }));\n```\n\n## Best Practices\n\n- Define context and event unions with `defineMachine<Context, Event>()`.\n- Return replacement context from reducers; do not rely on runtime copying or freezing.\n- Keep guards and reducers pure.\n- Use actors for effects, timers, invokes, subscriptions, and cancellation.\n- Read the current snapshot from `actor.snapshot`, not a wrapper value.\n- Validate persisted context before restoring a snapshot.\n- Dispose every actor at its ownership boundary.\n- Route runtime failures through the `tap()` observer for logging and diagnostics.\n",
7
7
  "examples": "---\ntitle: 'Clockwork: Examples'\ndescription: Practical state machine patterns with pure transitions and actors.\n---\n\n- [Counter with Reset](./examples/counter-with-reset.md)\n- [Form Validation](./examples/form-validation.md)\n- [Auto-Dismiss Notification](./examples/auto-dismiss-notification.md)\n- [Model Nested Workflows with Flat States](./examples/hierarchical-states.md)\n- [Pure Transition Testing](./examples/unit-testing.md)\n- [Auth Flow with Guards](./examples/auth-flow.md)\n- [Data Fetching with Error Recovery](./examples/data-fetching.md)\n- [Fetch with Retry](./examples/fetch-retry.md)\n- [Paginated Data Loading](./examples/paginated-data-loading.md)\n- [Media Player](./examples/media-player.md)\n- [Persisted Wizard](./examples/persisted-wizard.md)\n- [Multi-Step Wizard with Routing](./examples/wizard-with-routing.md)\n- [Shopping Cart Checkout](./examples/checkout.md)\n- [Permission-Based Access Control](./examples/permission-based-access.md)\n- [Event Boundaries](./examples/middleware-pipeline.md)\n- [Multi-Machine Coordination](./examples/multi-machine-coordination.md)\n- [Debugging Transitions](./examples/debugging-transitions.md)\n"
8
8
  },
9
9
  "examples": [
@@ -1,9 +1,9 @@
1
1
  {
2
- "apiSource": "/**\n * `@vielzeug/codex`: supported public contract.\n *\n * Exposes the generic catalog, snapshot loader, errors, and server hosts.\n * Refine catalog types and tools live behind `@vielzeug/codex/refine`.\n */\nexport { StdioServerTransport } from '@modelcontextprotocol/server/stdio';\nexport { type Catalog, CatalogError, type SearchHit, SnapshotCatalog } from './catalog.js';\nexport { CodexError } from './errors.js';\nexport { type HttpHost, type HttpHostOptions, startHttpHost } from './http.js';\nexport { createMcpServer } from './server.js';\nexport { type LoadedSnapshot, loadSnapshot } from './snapshot.js';\nexport type {\n DocPage,\n Example,\n PackageMeta,\n SnapshotManifest,\n} from './types.js';\n",
2
+ "apiSource": "/**\n * `@vielzeug/codex`: supported public contract.\n *\n * Exposes the catalog (package docs plus bundled Refine component metadata), the snapshot\n * loader, errors, the MCP server factory, and the loopback HTTP host.\n */\n\nexport { StdioServerTransport } from '@modelcontextprotocol/server/stdio';\nexport { type Catalog, CatalogError, type SearchHit, SnapshotCatalog } from './catalog.js';\nexport { CodexError } from './errors.js';\nexport { type HttpHost, type HttpHostOptions, startHttpHost } from './http.js';\nexport { createMcpServer, type McpServerOptions } from './server.js';\nexport { type LoadedSnapshot, loadSnapshot, validateSnapshot } from './snapshot.js';\nexport type {\n CemAttribute,\n CemCssPart,\n CemCssProperty,\n CemDeclaration,\n CemEvent,\n CemMember,\n CemSlot,\n DocPage,\n Example,\n PackageMeta,\n SnapshotManifest,\n} from './types.js';\n",
3
3
  "docs": {
4
- "index": "---\ntitle: Codex\ndescription: Local MCP access to Vielzeug documentation and package metadata.\npackage: codex\ncategory: AI\nkeywords: [mcp, docs, ai]\nrelated: [refine]\nexports:\n [\n loadSnapshot,\n SnapshotCatalog,\n createMcpServer,\n createMcpServerWithRefine,\n startHttpHost,\n StdioServerTransport,\n CatalogError,\n CodexError,\n ]\nenvironments: [node]\n---\n\n<PackageHero package=\"codex\" />\n\n## Why Codex?\n\nCodex exposes current Vielzeug catalog data through MCP without scanning source at request time.\n\n## Installation\n\n```sh\npnpm add @vielzeug/codex\n```\n\n## Quick Start\n\n```sh\nnpx -y @vielzeug/codex\n```\n\n## Features\n\n- `loadSnapshot` validates chunked snapshot metadata.\n- `SnapshotCatalog` loads package content only when requested.\n- `createMcpServer` registers generic package tools; `/refine` adds component tools explicitly.\n- Root and `/refine` entry points publish TypeScript declarations.\n- `startHttpHost` enforces loopback binding plus localhost Host and Origin validation.\n\n## Documentation\n\n- [Usage](./usage.md)\n- [API](./api.md)\n- [Examples](./examples.md)\n- [Migration Guide](./migration.md)\n\n## See Also\n\n- [Refine](../refine/) provides component metadata bundled by Codex.\n",
5
- "api": "---\ntitle: Codex API\ndescription: Snapshot, catalog, MCP server, and local HTTP host APIs.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| --------------------------- | -------------------------------------------------- | -------------- | ------------------------------------ |\n| `loadSnapshot` | Read validated snapshot metadata | Sync | Content chunks load lazily |\n| `SnapshotCatalog` | Query package corpus | Sync | Construct from loaded snapshot |\n| `createMcpServer` | MCP adapter factory (generic tools) | Sync | Requires catalog and version |\n| `createMcpServerWithRefine` | MCP adapter factory (all package and Refine tools) | Sync | Import from `@vielzeug/codex/refine` |\n| `startHttpHost` | Loopback Streamable HTTP host | Async | HTTP remains local-only |\n\n## Package Entry Points\n\n| Import | Purpose |\n| ------------------------ | ----------------------------------------------------------------------- |\n| `@vielzeug/codex` | `Catalog`, `SnapshotCatalog`, `loadSnapshot`, MCP server, and HTTP host |\n| `@vielzeug/codex/refine` | Refine catalog and MCP server with component tools |\n\n## Snapshot\n\n### `loadSnapshot`\n\n```ts\nloadSnapshot(snapshotRoot?: string, options?: { validateContents?: boolean }): LoadedSnapshot;\n```\n\nLoads catalog/search metadata and Refine metadata. `snapshotRoot` defaults to bundled `data/`. Package content chunks stay lazy unless `validateContents: true`, which validates every package content chunk during loading.\n\n### `SnapshotCatalog`\n\n```ts\nnew SnapshotCatalog(snapshot: LoadedSnapshot)\n```\n\nProvides generic package lookup, docs/source/example/signature access, and deterministic search. Use `SnapshotRefineCatalog` from `/refine` when component methods are needed.\n\n---\n\n## MCP\n\n### `createMcpServer`\n\n```ts\ncreateMcpServer(catalog: Catalog, options: { version: string; debug?: boolean }): Server;\n```\n\nRegisters generic package tools over `Catalog`. Refine tools are opt-in through `/refine`. The root also re-exports `StdioServerTransport` for connecting the server without a second package import.\n\n## Refine tools (`@vielzeug/codex/refine`)\n\n### `createMcpServerWithRefine`\n\n```ts\ncreateMcpServerWithRefine(catalog: RefineCatalog, options: { version: string; debug?: boolean }): Server;\n```\n\nCreates a server with the general Vielzeug package catalog tools and the additional `refine-*` component tools.\n\n### `SnapshotRefineCatalog`\n\n```ts\nnew SnapshotRefineCatalog(snapshot: LoadedSnapshot)\n```\n\nExtends `SnapshotCatalog` with `getComponent()` and `listComponents()`.\n\nComponent declarations and their nested data use readonly TypeScript types.\n\n## HTTP\n\n### `startHttpHost`\n\n```ts\nstartHttpHost(options: HttpHostOptions): Promise<HttpHost>;\n```\n\nStarts Streamable HTTP on `127.0.0.1` by default. Runtime validation accepts only `127.0.0.1` or `::1`; every request must also pass localhost Host and Origin checks. `createServer` must return a fresh, unconnected server with its request handlers registered.\n\n## Types\n\n```ts\ninterface SnapshotPointer {\n readonly directory: string;\n}\n\ninterface SnapshotManifest {\n readonly catalog: 'catalog.json';\n readonly contentDirectory: 'packages';\n readonly refine: 'refine.json' | null;\n readonly schemaVersion: typeof SNAPSHOT_SCHEMA_VERSION;\n readonly search: 'search.json';\n readonly version: string;\n}\n```\n\nDev snapshots use `SnapshotPointer` (via `current.json`); published snapshots are static directories.\n\n```ts\ninterface LoadedSnapshot {\n readonly catalog: CatalogFile;\n readonly contentDirectory: string;\n readonly manifest: SnapshotManifest;\n readonly refineComponents: readonly CemDeclaration[];\n readonly search: readonly SearchRecord[];\n}\n```\n\n```ts\ninterface CatalogFile {\n readonly packages: readonly PackageMeta[];\n readonly version: string;\n}\n\ninterface SearchRecord {\n readonly category: string;\n readonly description: string;\n readonly docs: Readonly<Partial<Record<DocPage, string>>>;\n readonly examples: readonly { readonly id: string; readonly text: string }[];\n readonly exports: string;\n readonly keywords: string;\n readonly name: string;\n readonly related: string;\n readonly slug: string;\n readonly source: string | null;\n}\n\ninterface PackageMeta {\n readonly availableDocPages: readonly DocPage[];\n readonly category: string;\n readonly description: string;\n readonly exampleIds: readonly string[];\n readonly exports: readonly string[];\n readonly hasSource: boolean;\n readonly keywords: readonly string[];\n readonly name: string;\n readonly related: readonly string[];\n readonly slug: string;\n readonly version: string;\n}\n\ninterface Example {\n readonly code: string;\n readonly id: string;\n readonly name: string;\n}\n```\n\n```ts\ninterface Catalog {\n getDocs(slug: string, page: DocPage): string;\n getExample(slug: string, exampleId: string): Example;\n getPackage(slug: string): PackageMeta;\n getSource(slug: string): string;\n getTypeSignature(slug: string, symbol: string): string;\n listExamples(slug: string): readonly Pick<Example, 'id' | 'name'>[];\n listPackages(): readonly PackageMeta[];\n search(query: string): readonly SearchHit[];\n}\n\ninterface RefineCatalog extends Catalog {\n getComponent(tagName: string): CemDeclaration;\n listComponents(): readonly CemDeclaration[];\n}\n\ninterface SearchHit {\n readonly matchedExamples?: readonly string[];\n readonly matchedIn: readonly ('docs' | 'examples' | 'exports' | 'keywords' | 'metadata' | 'related' | 'source')[];\n readonly matchedPages?: readonly DocPage[];\n readonly name: string;\n readonly slug: string;\n}\n```\n\nCatalog exposes semantic reads. It does not expose its cached content chunks.\n\n```ts\ninterface HttpHost {\n readonly disposalSignal: AbortSignal;\n dispose(): Promise<void>;\n readonly disposed: boolean;\n readonly host: string;\n readonly port: number;\n [Symbol.asyncDispose](): Promise<void>;\n}\n\ninterface HttpHostOptions {\n createServer: () => Server;\n host?: '127.0.0.1' | '::1';\n port: number;\n version: string;\n}\n```\n\n```ts\nconst DOC_PAGES = ['index', 'api', 'usage', 'examples'] as const;\ntype DocPage = (typeof DOC_PAGES)[number];\n\nconst SNAPSHOT_SCHEMA_VERSION = 1 as const;\n```\n\nCEM types and `RefineCatalog` are exported from `/refine`.\n\n```ts\ninterface CemDeclaration {\n readonly attributes?: readonly CemAttribute[];\n readonly cssParts?: readonly CemCssPart[];\n readonly cssProperties?: readonly CemCssProperty[];\n readonly description?: string;\n readonly events?: readonly CemEvent[];\n readonly members?: readonly CemMember[];\n readonly name?: string;\n readonly slots?: readonly CemSlot[];\n readonly superclass?: { readonly name: string; readonly package?: string };\n readonly tagName?: string;\n readonly [key: string]: unknown;\n}\n\ninterface CemAttribute {\n readonly default?: string;\n readonly description?: string;\n readonly fieldName?: string;\n readonly name: string;\n readonly type?: { readonly text: string };\n}\n\ninterface CemCssPart {\n readonly description?: string;\n readonly name: string;\n}\n\ninterface CemCssProperty {\n readonly default?: string;\n readonly description?: string;\n readonly name: string;\n}\n\ninterface CemEvent {\n readonly description?: string;\n readonly name: string;\n readonly type?: { readonly text: string };\n}\n\ninterface CemMember {\n readonly description?: string;\n readonly kind?: 'field' | 'method';\n readonly name: string;\n readonly type?: { readonly text: string };\n}\n\ninterface CemSlot {\n readonly description?: string;\n readonly name: string;\n}\n```\n\n## Errors\n\n`CodexError` signals malformed snapshots or host failures. `CatalogError` adds `INVALID_ARG`, `NOT_FOUND`, or `UNAVAILABLE` for expected tool failures.\n",
6
- "usage": "---\ntitle: 'Codex: Usage Guide'\ndescription: Install, connect, develop, and debug the Vielzeug MCP server.\n---\n\n[[toc]]\n\n## Basic Usage\n\nRun local stdio server:\n\n```sh\nnpx -y @vielzeug/codex\n```\n\nUse shipped `mcp-setup.json` for machine-readable generic configuration. Client-specific configuration must use its documented MCP format.\n\n## HTTP Mode\n\nHTTP uses Streamable HTTP and binds loopback only:\n\n```sh\nnpx -y @vielzeug/codex --port=3100\ncurl http://127.0.0.1:3100/health\n```\n\nResponse includes snapshot version. Runtime bind validation and Host/Origin allowlists restrict access to localhost; no remote host mode exists. Programmatic HTTP hosting takes a `createServer` factory that returns a fresh, unconnected server with its request handlers registered. Dispose the host asynchronously and observe `disposed` or `disposalSignal` when coordinating shutdown.\n\n## Agent Skill\n\nCodex ships a `vielzeug` agent skill: a `SKILL.md` that tells an AI agent working in _your_ project to discover packages through the MCP tools instead of guessing, to use the owning `@vielzeug/*` package instead of hand-rolling, and to build UI from Refine components, tokens, and theme whenever `@vielzeug/refine` is installed. Install it into the project:\n\n```sh\nnpx -y @vielzeug/codex skills install\nnpx -y @vielzeug/codex skills install --target=.claude/skills\nnpx -y @vielzeug/codex skills install --force # overwrite an existing copy\n```\n\nWithout `--target`, the first existing directory among `.agents/skills`, `.github/skills`, and `.claude/skills` is used; when none exists, `.agents/skills` is created. The command refuses to overwrite an installed skill unless `--force` is passed. Rerun after upgrading codex to pick up the current package list, which is generated from the published manifests. The skill pairs with the MCP server: its lookups (`get-docs`, `refine-get-component`, `refine-validate-usage`, …) assume codex is connected, and it documents `node_modules` fallbacks for when it is not.\n\n## Local Development\n\nRequires Node 22+ and root setup:\n\n```sh\nbun install\ncd packages/codex\nbun run test:unit\nbun run test:integration\nbun run dev\n```\n\n`test:unit` uses fixtures only. `test:integration` regenerates a current snapshot then checks real monorepo inputs.\n\n`bun run dev` watches documentation and package inputs, atomically publishes snapshots, then restarts server when snapshot changes.\n\n## Debugging\n\n```sh\nbun run dev\nnode src/cli.ts --port=3100 --debug\ncurl http://127.0.0.1:3100/health\n```\n\n`--debug` logs tool durations and expected catalog errors to stderr. Build `@vielzeug/refine` before generating snapshot when component metadata changes.\n\n## Programmatic Usage\n\n```ts\nimport { SnapshotCatalog, StdioServerTransport, createMcpServer, loadSnapshot } from '@vielzeug/codex';\n\nconst snapshot = loadSnapshot();\nconst catalog = new SnapshotCatalog(snapshot);\nawait createMcpServer(catalog, { version: snapshot.manifest.version }).connect(new StdioServerTransport());\n```\n\nTo include Refine component tools, create a server with the `@vielzeug/codex/refine` subpath:\n\n```ts\nimport { StdioServerTransport, loadSnapshot } from '@vielzeug/codex';\nimport { createMcpServerWithRefine, SnapshotRefineCatalog } from '@vielzeug/codex/refine';\n\nconst snapshot = loadSnapshot();\nconst catalog = new SnapshotRefineCatalog(snapshot);\nconst server = createMcpServerWithRefine(catalog, { version: snapshot.manifest.version });\nawait server.connect(new StdioServerTransport());\n```\n\n## Best Practices\n\n- Use `search-packages` for capability discovery before loading broad source.\n- Use `get-type-signature` before loading full source.\n- Published package snapshots are static directories; local dev snapshots are immutable generations selected by `.dev/current.json`.\n- Pass `validateContents: true` to `loadSnapshot()` for artifact verification; normal startup keeps package chunks lazy.\n- Return a fresh configured server from `startHttpHost`'s `createServer` factory.\n- Keep HTTP local. Use stdio for normal client integration.\n- Run `bun run test:unit` before `bun run test:integration`.\n",
4
+ "index": "---\ntitle: Codex\ndescription: Local MCP access to Vielzeug documentation and package metadata.\npackage: codex\ncategory: AI\nkeywords: [mcp, docs, ai]\nrelated: [refine]\nexports: [loadSnapshot, SnapshotCatalog, createMcpServer, startHttpHost, StdioServerTransport, CatalogError, CodexError]\nenvironments: [node]\n---\n\n<PackageHero package=\"codex\" />\n\n## Why Codex?\n\nCodex exposes current Vielzeug catalog data through MCP without scanning source at request time.\n\n## Installation\n\n```sh\npnpm add @vielzeug/codex\n```\n\n## Quick Start\n\n```sh\nnpx -y @vielzeug/codex\n```\n\n## Features\n\n- `loadSnapshot` validates chunked snapshot metadata.\n- `SnapshotCatalog` loads package content only when requested.\n- `createMcpServer` registers package tools, plus Refine component tools whenever the snapshot carries them.\n- The single entry point publishes TypeScript declarations.\n- `startHttpHost` enforces loopback binding plus localhost Host and Origin validation.\n\n## Documentation\n\n- [Usage](./usage.md)\n- [API](./api.md)\n- [Examples](./examples.md)\n- [Migration Guide](./migration.md)\n\n## See Also\n\n- [Refine](../refine/) provides component metadata bundled by Codex.\n",
5
+ "api": "---\ntitle: Codex API\ndescription: Snapshot, catalog, MCP server, and local HTTP host APIs.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| ------------------ | ------------------------------------------ | -------------- | ------------------------------------- |\n| `loadSnapshot` | Read validated snapshot metadata | Sync | Content chunks load lazily |\n| `validateSnapshot` | Full artifact verification (all chunks) | Sync | Generation/CI use, not normal startup |\n| `SnapshotCatalog` | Query package corpus and Refine components | Sync | Construct from loaded snapshot |\n| `createMcpServer` | MCP adapter factory | Sync | Requires catalog and version |\n| `startHttpHost` | Loopback Streamable HTTP host | Async | HTTP remains local-only |\n\n## Package Entry Point\n\n`@vielzeug/codex` is the single entry point: catalog (package docs plus bundled Refine component\nmetadata), snapshot loader, errors, the MCP server factory, the loopback HTTP host, and a\nre-export of `StdioServerTransport`. There is one `Catalog` surface and one server factory.\n\n## Snapshot\n\n### `loadSnapshot`\n\n```ts\nloadSnapshot(directory?: string, options?: { validateContents?: boolean }): LoadedSnapshot;\n```\n\nLoads one snapshot directory: `manifest.json` plus `catalog.json` (eager metadata), an optional\n`refine.json`, and lazily read `packages/<slug>.json` content chunks. `directory` defaults to the\nbundled `data/`. The snapshot layout is fixed by code; the manifest carries `{ schemaVersion, version }`\nonly. `validateContents: true` turns the lazy chunks into an eager cross-checked read.\n\n### `validateSnapshot`\n\n```ts\nvalidateSnapshot(snapshotRoot?: string): void;\n```\n\nRuns `loadSnapshot` with `validateContents: true`. Used by snapshot generation, integration tests,\nand artifact verification; normal startup keeps package chunks lazy.\n\n### `SnapshotCatalog`\n\n```ts\nnew SnapshotCatalog(snapshot: LoadedSnapshot)\n```\n\nProvides package lookup, docs/source/example/signature access, deterministic search, and the\nRefine component lookup (`listComponents()`, `getComponent(tagName)`). Component methods return an\nempty list (and `NOT_FOUND` per tag) when the snapshot carries no Refine metadata. `search()`\nreads content chunks through the same lazy cache as the content getters; there is no separate\nsearch index.\n\n---\n\n## MCP\n\n### `createMcpServer`\n\n```ts\ncreateMcpServer(catalog: Catalog, options: { version: string; debug?: boolean }): Server;\n```\n\nRegisters the generic package tools over `Catalog`, plus the `refine-*` component tools when the\ncatalog actually carries Refine metadata; tools that could only answer \"unavailable\" are never\noffered. The root also re-exports `StdioServerTransport` for connecting the server without a\nsecond package import.\n\n## HTTP\n\n### `startHttpHost`\n\n```ts\nstartHttpHost(options: HttpHostOptions): Promise<HttpHost>;\n```\n\nStarts Streamable HTTP on `127.0.0.1` by default. Runtime validation accepts only `127.0.0.1` or\n`::1`; every request must also pass localhost Host and Origin checks. `createServer` must return a\nfresh, unconnected server with its request handlers registered.\n\n## Types\n\n```ts\ninterface SnapshotManifest {\n readonly schemaVersion: typeof SNAPSHOT_SCHEMA_VERSION;\n readonly version: string;\n}\n\ninterface LoadedSnapshot {\n readonly catalog: CatalogFile;\n readonly contentDirectory: string;\n readonly manifest: SnapshotManifest;\n readonly refineComponents: readonly CemDeclaration[];\n}\n```\n\n```ts\ninterface CatalogFile {\n readonly packages: readonly PackageMeta[];\n readonly version: string;\n}\n\ninterface PackageMeta {\n readonly availableDocPages: readonly DocPage[];\n readonly category: string;\n readonly description: string;\n readonly exampleIds: readonly string[];\n readonly exports: readonly string[];\n readonly hasSource: boolean;\n readonly keywords: readonly string[];\n readonly name: string;\n readonly related: readonly string[];\n readonly slug: string;\n readonly version: string;\n}\n\ninterface Example {\n readonly code: string;\n readonly id: string;\n readonly name: string;\n}\n```\n\n```ts\ninterface Catalog {\n getComponent(tagName: string): CemDeclaration;\n getDocs(slug: string, page: DocPage): string;\n getExample(slug: string, exampleId: string): Example;\n getPackage(slug: string): PackageMeta;\n getSource(slug: string): string;\n getTypeSignature(slug: string, symbol: string): string;\n listComponents(): readonly CemDeclaration[];\n listExamples(slug: string): readonly Pick<Example, 'id' | 'name'>[];\n listPackages(): readonly PackageMeta[];\n search(query: string): readonly SearchHit[];\n}\n\ninterface SearchHit {\n readonly matchedExamples?: readonly string[];\n readonly matchedIn: readonly ('docs' | 'examples' | 'exports' | 'keywords' | 'metadata' | 'related' | 'source')[];\n readonly matchedPages?: readonly DocPage[];\n readonly name: string;\n readonly slug: string;\n}\n```\n\nCatalog exposes semantic reads. It does not expose its cached content chunks.\n\n```ts\ninterface HttpHost {\n dispose(): Promise<void>;\n readonly disposed: boolean;\n readonly host: string;\n readonly port: number;\n [Symbol.asyncDispose](): Promise<void>;\n}\n\ninterface HttpHostOptions {\n createServer: () => Server;\n host?: '127.0.0.1' | '::1';\n port: number;\n version: string;\n}\n```\n\n```ts\nconst DOC_PAGES = ['index', 'api', 'usage', 'examples'] as const;\ntype DocPage = (typeof DOC_PAGES)[number];\n\nconst SNAPSHOT_SCHEMA_VERSION = 2 as const;\n```\n\n```ts\ninterface CemDeclaration {\n readonly attributes?: readonly CemAttribute[];\n readonly cssParts?: readonly CemCssPart[];\n readonly cssProperties?: readonly CemCssProperty[];\n readonly description?: string;\n readonly events?: readonly CemEvent[];\n readonly members?: readonly CemMember[];\n readonly name?: string;\n readonly slots?: readonly CemSlot[];\n readonly superclass?: { readonly name: string; readonly package?: string };\n readonly tagName?: string;\n readonly [key: string]: unknown;\n}\n\ninterface CemAttribute {\n readonly default?: string;\n readonly description?: string;\n readonly fieldName?: string;\n readonly name: string;\n readonly type?: { readonly text: string };\n}\n\ninterface CemCssPart {\n readonly description?: string;\n readonly name: string;\n}\n\ninterface CemCssProperty {\n readonly default?: string;\n readonly description?: string;\n readonly name: string;\n}\n\ninterface CemEvent {\n readonly description?: string;\n readonly name: string;\n readonly type?: { readonly text: string };\n}\n\ninterface CemMember {\n readonly description?: string;\n readonly kind?: 'field' | 'method';\n readonly name: string;\n readonly type?: { readonly text: string };\n}\n\ninterface CemSlot {\n readonly description?: string;\n readonly name: string;\n}\n```\n\nComponent declarations and their nested data use readonly TypeScript types. The loader pins only\nthe contract its consumers depend on: declarations form an array with valid, unique custom-element\n`tagName`s.\n\n## Errors\n\n`CodexError` signals malformed snapshots or host failures. `CatalogError` adds `INVALID_ARG`,\n`NOT_FOUND`, or `UNAVAILABLE` for expected tool failures.\n",
6
+ "usage": "---\ntitle: 'Codex: Usage Guide'\ndescription: Install, connect, develop, and debug the Vielzeug MCP server.\n---\n\n[[toc]]\n\n## Basic Usage\n\nRun local stdio server:\n\n```sh\nnpx -y @vielzeug/codex\n```\n\nUse shipped `mcp-setup.json` for machine-readable generic configuration. Client-specific configuration must use its documented MCP format.\n\n## HTTP Mode\n\nHTTP uses Streamable HTTP and binds loopback only:\n\n```sh\nnpx -y @vielzeug/codex --port=3100\ncurl http://127.0.0.1:3100/health\n```\n\nResponse includes snapshot version. Runtime bind validation and Host/Origin allowlists restrict access to localhost; no remote host mode exists. Programmatic HTTP hosting takes a `createServer` factory that returns a fresh, unconnected server with its request handlers registered. Dispose the host asynchronously and observe `disposed` when coordinating shutdown.\n\n## Agent Skill\n\nCodex ships a `vielzeug` agent skill: a `SKILL.md` that tells an AI agent working in _your_ project to discover packages through the MCP tools instead of guessing, to use the owning `@vielzeug/*` package instead of hand-rolling, and to build UI from Refine components, tokens, and theme whenever `@vielzeug/refine` is installed. Install it into the project:\n\n```sh\nnpx -y @vielzeug/codex skills install\nnpx -y @vielzeug/codex skills install --target=.claude/skills\nnpx -y @vielzeug/codex skills install --force # overwrite an existing copy\n```\n\nWithout `--target`, the first existing directory among `.agents/skills`, `.github/skills`, and `.claude/skills` is used; when none exists, `.agents/skills` is created. The command refuses to overwrite an installed skill unless `--force` is passed. Rerun after upgrading codex to pick up the current package list, which is generated from the published manifests. The skill pairs with the MCP server: its lookups (`get-docs`, `refine-get-component`, `refine-validate-usage`, …) assume codex is connected, and it documents `node_modules` fallbacks for when it is not.\n\n## Local Development\n\nRequires Node 22+ and root setup:\n\n```sh\nbun install\ncd packages/codex\nbun run test:unit\nbun run test:integration\nbun run dev\n```\n\n`test:unit` uses fixtures only. `test:integration` regenerates a current snapshot then checks real monorepo inputs.\n\n`bun run dev` watches documentation and package inputs, regenerates `.dev/` through a staging swap, and restarts the server against it.\n\n## Debugging\n\n```sh\nbun run dev\nnode src/cli.ts --port=3100 --debug\ncurl http://127.0.0.1:3100/health\n```\n\n`--debug` logs tool durations and expected catalog errors to stderr. Build `@vielzeug/refine` before generating snapshot when component metadata changes.\n\n## Programmatic Usage\n\n```ts\nimport { SnapshotCatalog, StdioServerTransport, createMcpServer, loadSnapshot } from '@vielzeug/codex';\n\nconst snapshot = loadSnapshot();\nconst catalog = new SnapshotCatalog(snapshot);\nawait createMcpServer(catalog, { version: snapshot.manifest.version }).connect(new StdioServerTransport());\n```\n\n`createMcpServer` also registers the `refine-*` component tools whenever the loaded snapshot carries Refine metadata; there is nothing to opt into.\n\n## Best Practices\n\n- Use `search-packages` for capability discovery before loading broad source.\n- Use `get-type-signature` before loading full source.\n- Every snapshot is one flat directory (manifest, catalog, content chunks, optional Refine metadata); `--snapshot` points at it directly.\n- Pass `validateContents: true` to `loadSnapshot()` for artifact verification; normal startup keeps package chunks lazy.\n- Return a fresh configured server from `startHttpHost`'s `createServer` factory.\n- Keep HTTP local. Use stdio for normal client integration.\n- Run `bun run test:unit` before `bun run test:integration`.\n",
7
7
  "examples": "---\ntitle: 'Codex: Examples'\ndescription: Practical MCP tool-call examples for package discovery, docs lookup, and Refine component queries.\n---\n\n## Examples\n\n- [Listing Packages](./examples/listing-packages.md)\n- [Searching Packages](./examples/searching-packages.md)\n- [Package Metadata](./examples/package-metadata.md)\n- [Reading Docs](./examples/reading-docs.md)\n- [Running REPL Examples](./examples/running-repl-examples.md)\n- [Looking Up Components](./examples/looking-up-components.md)\n- [Inspector](./examples/inspector.md)\n"
8
8
  },
9
9
  "examples": [],
@@ -17,12 +17,21 @@
17
17
  "HttpHost": "export { type HttpHost, type HttpHostOptions, startHttpHost } from './http.js';",
18
18
  "HttpHostOptions": "export { type HttpHost, type HttpHostOptions, startHttpHost } from './http.js';",
19
19
  "startHttpHost": "export { type HttpHost, type HttpHostOptions, startHttpHost } from './http.js';",
20
- "createMcpServer": "export { createMcpServer } from './server.js';",
21
- "LoadedSnapshot": "export { type LoadedSnapshot, loadSnapshot } from './snapshot.js';",
22
- "loadSnapshot": "export { type LoadedSnapshot, loadSnapshot } from './snapshot.js';",
23
- "DocPage": "export type {\n DocPage,\n Example,\n PackageMeta,\n SnapshotManifest,\n} from './types.js';",
24
- "Example": "export type {\n DocPage,\n Example,\n PackageMeta,\n SnapshotManifest,\n} from './types.js';",
25
- "PackageMeta": "export type {\n DocPage,\n Example,\n PackageMeta,\n SnapshotManifest,\n} from './types.js';",
26
- "SnapshotManifest": "export type {\n DocPage,\n Example,\n PackageMeta,\n SnapshotManifest,\n} from './types.js';"
20
+ "createMcpServer": "export { createMcpServer, type McpServerOptions } from './server.js';",
21
+ "McpServerOptions": "export { createMcpServer, type McpServerOptions } from './server.js';",
22
+ "LoadedSnapshot": "export { type LoadedSnapshot, loadSnapshot, validateSnapshot } from './snapshot.js';",
23
+ "loadSnapshot": "export { type LoadedSnapshot, loadSnapshot, validateSnapshot } from './snapshot.js';",
24
+ "validateSnapshot": "export { type LoadedSnapshot, loadSnapshot, validateSnapshot } from './snapshot.js';",
25
+ "CemAttribute": "export type {\n CemAttribute,\n CemCssPart,\n CemCssProperty,\n CemDeclaration,\n CemEvent,\n CemMember,\n CemSlot,\n DocPage,\n Example,\n PackageMeta,\n SnapshotManifest,\n} from './types.js';",
26
+ "CemCssPart": "export type {\n CemAttribute,\n CemCssPart,\n CemCssProperty,\n CemDeclaration,\n CemEvent,\n CemMember,\n CemSlot,\n DocPage,\n Example,\n PackageMeta,\n SnapshotManifest,\n} from './types.js';",
27
+ "CemCssProperty": "export type {\n CemAttribute,\n CemCssPart,\n CemCssProperty,\n CemDeclaration,\n CemEvent,\n CemMember,\n CemSlot,\n DocPage,\n Example,\n PackageMeta,\n SnapshotManifest,\n} from './types.js';",
28
+ "CemDeclaration": "export type {\n CemAttribute,\n CemCssPart,\n CemCssProperty,\n CemDeclaration,\n CemEvent,\n CemMember,\n CemSlot,\n DocPage,\n Example,\n PackageMeta,\n SnapshotManifest,\n} from './types.js';",
29
+ "CemEvent": "export type {\n CemAttribute,\n CemCssPart,\n CemCssProperty,\n CemDeclaration,\n CemEvent,\n CemMember,\n CemSlot,\n DocPage,\n Example,\n PackageMeta,\n SnapshotManifest,\n} from './types.js';",
30
+ "CemMember": "export type {\n CemAttribute,\n CemCssPart,\n CemCssProperty,\n CemDeclaration,\n CemEvent,\n CemMember,\n CemSlot,\n DocPage,\n Example,\n PackageMeta,\n SnapshotManifest,\n} from './types.js';",
31
+ "CemSlot": "export type {\n CemAttribute,\n CemCssPart,\n CemCssProperty,\n CemDeclaration,\n CemEvent,\n CemMember,\n CemSlot,\n DocPage,\n Example,\n PackageMeta,\n SnapshotManifest,\n} from './types.js';",
32
+ "DocPage": "export type {\n CemAttribute,\n CemCssPart,\n CemCssProperty,\n CemDeclaration,\n CemEvent,\n CemMember,\n CemSlot,\n DocPage,\n Example,\n PackageMeta,\n SnapshotManifest,\n} from './types.js';",
33
+ "Example": "export type {\n CemAttribute,\n CemCssPart,\n CemCssProperty,\n CemDeclaration,\n CemEvent,\n CemMember,\n CemSlot,\n DocPage,\n Example,\n PackageMeta,\n SnapshotManifest,\n} from './types.js';",
34
+ "PackageMeta": "export type {\n CemAttribute,\n CemCssPart,\n CemCssProperty,\n CemDeclaration,\n CemEvent,\n CemMember,\n CemSlot,\n DocPage,\n Example,\n PackageMeta,\n SnapshotManifest,\n} from './types.js';",
35
+ "SnapshotManifest": "export type {\n CemAttribute,\n CemCssPart,\n CemCssProperty,\n CemDeclaration,\n CemEvent,\n CemMember,\n CemSlot,\n DocPage,\n Example,\n PackageMeta,\n SnapshotManifest,\n} from './types.js';"
27
36
  }
28
37
  }