@vielzeug/codex 2.1.4 → 2.2.0

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 (48) hide show
  1. package/dist/errors.js +0 -3
  2. package/dist/errors.js.map +1 -1
  3. package/dist/snapshot.js.map +1 -1
  4. package/dist/tools/packages.js +2 -3
  5. package/dist/tools/packages.js.map +1 -1
  6. package/dist/tools/refine.js +2 -2
  7. package/dist/tools/refine.js.map +1 -1
  8. package/dist/tools/schema.js +2 -0
  9. package/dist/tools/schema.js.map +1 -1
  10. package/package.json +6 -1
  11. package/data/catalog.json +0 -1689
  12. package/data/llms-full.txt +0 -25771
  13. package/data/llms.txt +0 -40
  14. package/data/manifest.json +0 -8
  15. package/data/packages/arsenal.json +0 -210
  16. package/data/packages/assay.json +0 -40
  17. package/data/packages/clockwork.json +0 -67
  18. package/data/packages/codex.json +0 -43
  19. package/data/packages/coins.json +0 -103
  20. package/data/packages/conduit.json +0 -60
  21. package/data/packages/courier.json +0 -58
  22. package/data/packages/dnd.json +0 -77
  23. package/data/packages/familiar.json +0 -40
  24. package/data/packages/flux.json +0 -93
  25. package/data/packages/forge.json +0 -84
  26. package/data/packages/herald.json +0 -108
  27. package/data/packages/keymap.json +0 -59
  28. package/data/packages/ledger.json +0 -57
  29. package/data/packages/lingua.json +0 -68
  30. package/data/packages/necromancer.json +0 -50
  31. package/data/packages/orbit.json +0 -107
  32. package/data/packages/ore.json +0 -73
  33. package/data/packages/prism.json +0 -67
  34. package/data/packages/pulse.json +0 -60
  35. package/data/packages/refine.json +0 -12
  36. package/data/packages/ripple.json +0 -83
  37. package/data/packages/rune.json +0 -80
  38. package/data/packages/sandbox.json +0 -40
  39. package/data/packages/scout.json +0 -60
  40. package/data/packages/scroll.json +0 -114
  41. package/data/packages/sourcerer.json +0 -74
  42. package/data/packages/spell.json +0 -134
  43. package/data/packages/tempo.json +0 -81
  44. package/data/packages/vault.json +0 -87
  45. package/data/packages/ward.json +0 -113
  46. package/data/packages/wayfinder.json +0 -113
  47. package/data/refine.json +0 -11926
  48. package/data/search.json +0 -1436
@@ -1,67 +0,0 @@
1
- {
2
- "apiSource": "export type { ClockworkErrorCode } from './errors.js';\nexport { ClockworkError } from './errors.js';\nexport { defineMachine } from './interpret.js';\nexport type {\n Actor,\n ActorErrorContext,\n ActorErrorDisposition,\n ActorOptions,\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
- "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, TransitionResult]\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 src: ({ signal }) => fetch('/api/items', { signal }).then((response) => response.json() as Promise<string[]>),\n onDone: ({ result }) => ({ items: result, type: 'DONE' }),\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()`** — validates and compiles one flat machine definition.\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 only after the actor commits and notifies subscribers.\n- **`invoke`** — runs cancellable asynchronous work on state entry.\n- **`after`** — schedules cancellable delayed transitions.\n- **`actor.snapshot`** — exposes the current readonly 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, devtools, and types.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| --- | --- | --- | --- |\n| `defineMachine()` | Compile a typed flat machine definition | 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| `debugActor()` | Observe committed snapshots | Sync | Observes only; it does not trace sends or errors |\n| `ClockworkError` | Report definition and snapshot validation failures | Sync | Use `code`, not message text |\n\n## Package Entry Points\n\n| Import | Purpose |\n| --- | --- |\n| `@vielzeug/clockwork` | Machine compiler, actor runtime, errors, and types |\n| `@vielzeug/clockwork/devtools` | Opt-in snapshot observation through `debugActor()` |\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 validates and compiles a typed flat machine definition. Context must be a non-array record. Omit `context` only when the context type has no keys.\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 `ClockworkError` when a definition has an invalid context, initial state, target, transition, effect, invoke, or timer delay.\n\n---\n\n### `debugActor()`\n\n```ts\nfunction debugActor<State extends string, Context extends Record<string, unknown>, Event extends MachineEvent>(\n actor: Actor<State, Context, Event>,\n options?: DebugActorOptions<State, Context>,\n): () => void;\n```\n\nSubscribes to committed actor snapshots and logs each one with `console.debug` by default. It does not modify actor behavior and does not observe dispatched events or runtime errors.\n\n**Returns:** An unsubscribe cleanup function.\n\n**Example:**\n\n```ts\nimport { defineMachine } from '@vielzeug/clockwork';\nimport { debugActor } from '@vielzeug/clockwork/devtools';\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 stopDebugging = debugActor(actor);\nactor.send({ type: 'NEXT' });\nstopDebugging();\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, Event>): 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| `options.maxTransitions` | `number` | Positive queued-transition limit for one synchronous flush |\n| `options.onError` | `(error, context) => 'continue' \\| 'dispose'` | Explicit disposition for runtime failures |\n\n**Returns:** Disposable `Actor`.\n\n**Example:**\n\n```ts\nconst actor = machine.createActor({\n onError(error, { phase, state }) {\n console.error(phase, state, error);\n return 'continue';\n },\n snapshot: { context: {}, state: 'idle' },\n});\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. 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. 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 and listeners, and aborts `disposalSignal`.\n\n**Returns:** Nothing. Idempotent.\n\n## Types\n\n### `MachineEvent`\n\n```ts\ntype MachineEvent = { readonly type: string };\n```\n\nBase constraint for event unions.\n\n### `EventType<Event>` and `EventByType<Event, Type>`\n\n```ts\ntype EventType<Event extends MachineEvent> = Event['type'] & string;\n\ntype EventByType<Event extends MachineEvent, Type extends EventType<Event>> =\n Extract<Event, { type: Type }>;\n```\n\nExtract event type names and a matching event from an event union.\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\nThe plain readonly snapshot value used by machines and actors. Readonly is a TypeScript contract; Clockwork does not copy or freeze snapshots at runtime.\n\n### `Guard<Context, Event>` and `Reducer<Context, Event>`\n\n```ts\ntype Guard<Context extends Record<string, unknown>, Event> = (args: {\n readonly context: Readonly<Context>;\n readonly event: Event;\n}) => boolean;\n\ntype Reducer<Context extends Record<string, unknown>, Event> = (args: {\n readonly context: Readonly<Context>;\n readonly event: Event;\n}) => Context;\n```\n\nA guard selects a transition. A reducer returns replacement context, which must be a non-array record.\n\n### `EffectArgs<Context, Event>` and `Effect<Context, Event>`\n\n```ts\ntype EffectArgs<Context extends Record<string, unknown>, Event extends MachineEvent> = {\n readonly context: Readonly<Context>;\n readonly event: Event | undefined;\n readonly send: (event: Event) => void;\n readonly signal: AbortSignal;\n};\n\ntype Effect<Context extends Record<string, unknown>, Event extends MachineEvent> =\n (args: EffectArgs<Context, Event>) => void;\n```\n\nPost-commit effects receive `undefined` for initial entry and actor timer transitions. They cannot update machine context directly.\n\n### `Transition<State, Context, Event, Type>` and `TransitionInput`\n\n```ts\ntype Transition<\n State extends string,\n Context extends Record<string, unknown>,\n Event extends MachineEvent,\n Type extends EventType<Event> = EventType<Event>,\n> = {\n readonly effects?: readonly Effect<Context, Event>[];\n readonly guard?: Guard<Context, EventByType<Event, Type>>;\n readonly reduce?: Reducer<Context, EventByType<Event, Type>>;\n readonly target: State;\n};\n\ntype TransitionInput<\n State extends string,\n Context extends Record<string, unknown>,\n Event extends MachineEvent,\n Type extends EventType<Event> = EventType<Event>,\n> = Transition<State, Context, Event, Type> | readonly Transition<State, Context, Event, Type>[];\n```\n\nAn ordered transition array selects the first guard that passes.\n\n### `After<State, Context, Event>`\n\n```ts\ntype After<State extends string, Context extends Record<string, unknown>, Event extends MachineEvent> = {\n readonly delay: number;\n readonly effects?: readonly Effect<Context, Event>[];\n readonly guard?: Guard<Context, Event | undefined>;\n readonly reduce?: Reducer<Context, Event | undefined>;\n readonly target: State;\n};\n```\n\nA delayed state transition. Its guard and reducer receive `event: undefined`.\n\n### `InvokeArgs<Context, Event>` and `Invoke<Context, Event, Result>`\n\n```ts\ntype InvokeArgs<Context extends Record<string, unknown>, Event extends MachineEvent> = {\n readonly context: Readonly<Context>;\n readonly event: Event | undefined;\n readonly signal: AbortSignal;\n};\n\ntype Invoke<Context extends Record<string, unknown>, Event extends MachineEvent, Result = unknown> = {\n readonly onDone?: (args: { readonly context: Readonly<Context>; readonly result: Result }) => Event;\n readonly onError?: (args: { readonly context: Readonly<Context>; readonly error: unknown }) => Event;\n readonly src: (args: InvokeArgs<Context, Event>) => Promise<Result> | Result;\n};\n```\n\nAn actor-owned task started on state entry. `event` is the triggering event or `undefined` for initial or restored resources.\n\n### `StateNode<State, Context, Event>` and `MachineConfig<State, Context, Event>`\n\n```ts\ntype StateNode<State extends string, Context extends Record<string, unknown>, Event extends MachineEvent> = {\n readonly after?: readonly After<State, Context, Event>[];\n readonly entry?: readonly Effect<Context, Event>[];\n readonly exit?: readonly Effect<Context, Event>[];\n readonly invoke?: readonly Invoke<Context, Event>[];\n readonly on?: Partial<{ [Type in EventType<Event>]: TransitionInput<State, Context, Event, Type> }>;\n};\n\ntype MachineConfig<State extends string, Context extends Record<string, unknown>, 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.\n\n### `TransitionResult<State, Context>`\n\n```ts\ntype TransitionResult<State extends string, Context extends Record<string, unknown>> = {\n readonly snapshot: MachineSnapshot<State, Context>;\n readonly type: 'ignored' | 'transition';\n};\n```\n\nResult of a pure user-event transition. It contains no effect plan.\n\n### `ActorErrorContext<State, Event>`, `ActorErrorDisposition`, and `ActorOptions<State, Context, Event>`\n\n```ts\ntype ActorErrorContext<State extends string, Event extends MachineEvent> = {\n readonly event?: Event;\n readonly phase: 'effect' | 'invoke' | 'subscriber' | 'transition';\n readonly state: State;\n};\n\ntype ActorErrorDisposition = 'continue' | 'dispose';\n\ntype ActorOptions<State extends string, Context extends Record<string, unknown>, Event extends MachineEvent> = {\n readonly maxTransitions?: number;\n readonly onError?: (error: unknown, context: ActorErrorContext<State, Event>) => ActorErrorDisposition;\n readonly snapshot?: MachineSnapshot<State, Context>;\n};\n```\n\n`onError` must explicitly return `'continue'` to keep the actor alive or `'dispose'` to end it. Without an error handler, Clockwork disposes the actor silently.\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};\n```\n\nAn actor's `snapshot` is the current plain readonly snapshot.\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, Event>): 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 compiled, reusable machine. Its transition lookup is map-based, so unknown or poison event names such as `__proto__` are safely ignored when no transition exists.\n\n### `DebugActorOptions<State, Context>`\n\n```ts\ntype DebugActorOptions<State extends string, Context extends Record<string, unknown>> = {\n readonly logger?: (snapshot: MachineSnapshot<State, Context>) => void;\n};\n```\n\nOptional logger for `debugActor()`. Logger failures are ignored so observation cannot affect the actor's error policy.\n\n## Errors\n\n### `ClockworkError`\n\n`ClockworkError` reports invalid definitions, contexts, snapshots, and actor transition limits. It has `code`, `details`, and standard `Error` fields. Use `ClockworkError.is(error)` to narrow an unknown error.\n\n```ts\nif (ClockworkError.is(error)) {\n console.error(error.code, 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\nDefine a non-array record context and an event union before supplying the flat definition. 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 does not copy or freeze context at runtime, so do not mutate data that other code may retain.\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(\n { context: { count: 3 }, state: 'idle' },\n { type: 'INC' },\n);\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 the new state's timers and invokes, notifies subscribers, then runs exit, transition, and entry 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 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 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. Its guard and reducer 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 plain readonly snapshot; 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\nUse `onError` to choose what happens after failures from transitions, effects, invokes, or subscribers. The context identifies the runtime phase and state; an event is present when one triggered the failure. Return `'continue'` to keep the actor alive or `'dispose'` to end it.\n\n```ts\nconst actor = machine.createActor({\n onError(error, { event, phase, state }) {\n console.error({ error, event, phase, state });\n return 'continue';\n },\n});\n```\n\nWithout `onError`, an actor disposes silently. Return `'dispose'` explicitly when an error handler logs an unrecoverable failure.\n\n## Debugging\n\nUse opt-in snapshot logging during development. `debugActor()` observes committed snapshots only; it does not trace dispatched events or runtime errors.\n\n```ts\nimport { debugActor } from '@vielzeug/clockwork/devtools';\n\nconst actor = machine.createActor();\nconst stopDebugging = debugActor(actor);\nactor.send({ type: 'NEXT' });\nstopDebugging();\nactor.dispose();\n```\n\nFor richer inspection, subscribe to snapshots and record them in 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 a compiled 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(\n { context: { count: 2 }, state: 'idle' },\n { type: 'INC' },\n );\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<Snapshot>(actor: { readonly snapshot: Snapshot; subscribe(listener: (snapshot: Snapshot) => void): () => void }) {\n return useSyncExternalStore(\n (notify) => actor.subscribe(() => notify()),\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 `onError` when the owner can recover.\n",
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
- },
9
- "examples": [
10
- {
11
- "id": "after-transitions",
12
- "code": "import { defineMachine } from '@vielzeug/clockwork'\n\n// Timers begin on entry and cancel automatically on exit or disposal.\nconst machine = defineMachine()({\n context: { message: '' },\n initial: 'hidden',\n states: {\n hidden: {\n on: {\n SHOW: {\n reduce: ({ event }) => ({ message: event.message }),\n target: 'visible',\n },\n },\n },\n visible: {\n after: [{ delay: 500, target: 'hidden' }],\n on: { DISMISS: { target: 'hidden' } },\n },\n },\n})\n\nconst actor = machine.createActor()\nactor.send({ type: 'SHOW', message: 'Saved' })\nconsole.log('Visible:', actor.snapshot)\nsetTimeout(() => console.log('After timer:', actor.snapshot), 700)",
13
- "name": "Delayed Transitions"
14
- },
15
- {
16
- "id": "async-invokes",
17
- "code": "import { defineMachine } from '@vielzeug/clockwork'\n\n// Invokes get an AbortSignal and send regular events when settled.\nconst machine = defineMachine()({\n context: { error: '', user: null },\n initial: 'idle',\n states: {\n idle: { on: { FETCH: { target: 'loading' } } },\n loading: {\n invoke: [{\n src: async ({ signal }) => {\n await new Promise((resolve, reject) => {\n const timer = setTimeout(resolve, 250)\n signal.addEventListener('abort', () => { clearTimeout(timer); reject(new Error('aborted')) })\n })\n return { name: 'Alice' }\n },\n onDone: ({ result }) => ({ type: 'DONE', user: result }),\n onError: ({ error }) => ({ type: 'FAILED', message: String(error) }),\n }],\n on: {\n DONE: { reduce: ({ event }) => ({ error: '', user: event.user }), target: 'ready' },\n FAILED: { reduce: ({ event }) => ({ error: event.message, user: null }), target: 'error' },\n },\n },\n ready: {},\n error: {},\n },\n})\n\nconst actor = machine.createActor()\nactor.send({ type: 'FETCH' })\nconsole.log('Loading:', actor.snapshot)\nsetTimeout(() => console.log('Resolved:', actor.snapshot), 400)",
18
- "name": "Async Invokes"
19
- },
20
- {
21
- "id": "basic-machine",
22
- "code": "import { defineMachine } from '@vielzeug/clockwork'\n\n// Compile one machine, then create an independent actor.\nconst machine = defineMachine()({\n context: { cycles: 0 },\n initial: 'red',\n states: {\n red: { on: { NEXT: { target: 'green' } } },\n green: { on: { NEXT: { target: 'yellow' } } },\n yellow: {\n on: {\n NEXT: {\n reduce: ({ context }) => ({ cycles: context.cycles + 1 }),\n target: 'red',\n },\n },\n },\n },\n})\n\nconst actor = machine.createActor()\nconsole.log('Initial:', actor.snapshot)\nactor.send({ type: 'NEXT' })\nactor.send({ type: 'NEXT' })\nactor.send({ type: 'NEXT' })\nconsole.log('After cycle:', actor.snapshot)\nconsole.log('Can continue?', actor.can({ type: 'NEXT' }))",
23
- "name": "Basic State Machine"
24
- },
25
- {
26
- "id": "entry-exit-actions",
27
- "code": "import { defineMachine } from '@vielzeug/clockwork'\n\nconst log = (message) => console.log(message)\n\n// Effects run after the actor commits and notifies subscribers.\nconst machine = defineMachine()({\n context: { reconnects: 0 },\n initial: 'disconnected',\n states: {\n disconnected: {\n entry: [() => log('[disconnected] socket closed')],\n on: { CONNECT: { target: 'connected' } },\n },\n connected: {\n entry: [({ context }) => log('[connected] reconnects: ' + context.reconnects)],\n exit: [() => log('[connected] socket closing')],\n on: {\n DISCONNECT: { target: 'disconnected' },\n ERROR: {\n reduce: ({ context }) => ({ reconnects: context.reconnects + 1 }),\n target: 'disconnected',\n },\n },\n },\n },\n})\n\nconst actor = machine.createActor()\nactor.subscribe((snapshot) => console.log('Committed:', snapshot))\nactor.send({ type: 'CONNECT' })\nactor.send({ type: 'ERROR' })",
28
- "name": "Post-commit Effects"
29
- },
30
- {
31
- "id": "guards-and-reducers",
32
- "code": "import { defineMachine } from '@vielzeug/clockwork'\n\nconst SECRET_KEY = 'vielzeug'\n\n// Guards select a transition. Reducers return replacement context.\nconst machine = defineMachine()({\n context: { accessAttempts: 0 },\n initial: 'locked',\n states: {\n locked: {\n on: {\n UNLOCK: [\n {\n guard: ({ event }) => event.key === SECRET_KEY,\n reduce: () => ({ accessAttempts: 0 }),\n target: 'unlocked',\n },\n {\n reduce: ({ context }) => ({ accessAttempts: context.accessAttempts + 1 }),\n target: 'locked',\n },\n ],\n },\n },\n unlocked: { on: { LOCK: { target: 'locked' } } },\n },\n})\n\nconst actor = machine.createActor()\nactor.send({ type: 'UNLOCK', key: 'wrong' })\nconsole.log('Wrong key:', actor.snapshot)\nactor.send({ type: 'UNLOCK', key: SECRET_KEY })\nconsole.log('Correct key:', actor.snapshot)",
33
- "name": "Guards & Reducers"
34
- },
35
- {
36
- "id": "pure-transitions-and-errors",
37
- "code": "import { ClockworkError, defineMachine } from '@vielzeug/clockwork'\n\nconst machine = defineMachine()({\n context: { role: 'guest' },\n initial: 'locked',\n states: {\n locked: {\n on: {\n UNLOCK: {\n guard: ({ context }) => context.role === 'admin',\n target: 'unlocked',\n },\n },\n },\n unlocked: { on: { LOCK: { target: 'locked' } } },\n },\n})\n\n// Pure transition: no actor, effects, or mutation.\nconst result = machine.transition(\n { context: { role: 'guest' }, state: 'locked' },\n { type: 'UNLOCK' },\n)\nconsole.log('Guest result:', result.type)\n\nfor (const definition of [\n { initial: 'missing', states: { idle: {} } },\n { context: [], initial: 'idle', states: { idle: {} } },\n]) {\n try {\n defineMachine()(definition)\n } catch (error) {\n if (ClockworkError.is(error)) {\n console.log('Validation code:', error.code)\n console.log('Details:', error.details)\n }\n }\n}",
38
- "name": "Pure Transitions & Errors"
39
- }
40
- ],
41
- "typeSignatures": {
42
- "ClockworkErrorCode": "export type { ClockworkErrorCode } from './errors.js';",
43
- "ClockworkError": "export { ClockworkError } from './errors.js';",
44
- "defineMachine": "export { defineMachine } from './interpret.js';",
45
- "Actor": "export type {\n Actor,\n ActorErrorContext,\n ActorErrorDisposition,\n ActorOptions,\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';",
46
- "ActorErrorContext": "export type {\n Actor,\n ActorErrorContext,\n ActorErrorDisposition,\n ActorOptions,\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';",
47
- "ActorErrorDisposition": "export type {\n Actor,\n ActorErrorContext,\n ActorErrorDisposition,\n ActorOptions,\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';",
48
- "ActorOptions": "export type {\n Actor,\n ActorErrorContext,\n ActorErrorDisposition,\n ActorOptions,\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';",
49
- "After": "export type {\n Actor,\n ActorErrorContext,\n ActorErrorDisposition,\n ActorOptions,\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';",
50
- "Effect": "export type {\n Actor,\n ActorErrorContext,\n ActorErrorDisposition,\n ActorOptions,\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';",
51
- "EffectArgs": "export type {\n Actor,\n ActorErrorContext,\n ActorErrorDisposition,\n ActorOptions,\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';",
52
- "EventByType": "export type {\n Actor,\n ActorErrorContext,\n ActorErrorDisposition,\n ActorOptions,\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';",
53
- "EventType": "export type {\n Actor,\n ActorErrorContext,\n ActorErrorDisposition,\n ActorOptions,\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';",
54
- "Guard": "export type {\n Actor,\n ActorErrorContext,\n ActorErrorDisposition,\n ActorOptions,\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';",
55
- "Invoke": "export type {\n Actor,\n ActorErrorContext,\n ActorErrorDisposition,\n ActorOptions,\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';",
56
- "InvokeArgs": "export type {\n Actor,\n ActorErrorContext,\n ActorErrorDisposition,\n ActorOptions,\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';",
57
- "Machine": "export type {\n Actor,\n ActorErrorContext,\n ActorErrorDisposition,\n ActorOptions,\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';",
58
- "MachineConfig": "export type {\n Actor,\n ActorErrorContext,\n ActorErrorDisposition,\n ActorOptions,\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';",
59
- "MachineEvent": "export type {\n Actor,\n ActorErrorContext,\n ActorErrorDisposition,\n ActorOptions,\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';",
60
- "MachineSnapshot": "export type {\n Actor,\n ActorErrorContext,\n ActorErrorDisposition,\n ActorOptions,\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';",
61
- "Reducer": "export type {\n Actor,\n ActorErrorContext,\n ActorErrorDisposition,\n ActorOptions,\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';",
62
- "StateNode": "export type {\n Actor,\n ActorErrorContext,\n ActorErrorDisposition,\n ActorOptions,\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';",
63
- "Transition": "export type {\n Actor,\n ActorErrorContext,\n ActorErrorDisposition,\n ActorOptions,\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';",
64
- "TransitionInput": "export type {\n Actor,\n ActorErrorContext,\n ActorErrorDisposition,\n ActorOptions,\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';",
65
- "TransitionResult": "export type {\n Actor,\n ActorErrorContext,\n ActorErrorDisposition,\n ActorOptions,\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';"
66
- }
67
- }
@@ -1,43 +0,0 @@
1
- {
2
- "apiSource": "export { 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 {\n loadSnapshot,\n parseCatalog,\n parseContent,\n parseManifest,\n parsePointer,\n parseSearch,\n validateSnapshot,\n} from './snapshot.js';\nexport {\n type CemAttribute,\n type CemCssPart,\n type CemCssProperty,\n type CemDeclaration,\n type CemEvent,\n type CemMember,\n type CemSlot,\n DOC_PAGES,\n type DocPage,\n type Example,\n type PackageContent,\n type PackageMeta,\n SNAPSHOT_SCHEMA_VERSION,\n type SnapshotManifest,\n type SnapshotPointer,\n} from './types.js';\n",
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: [loadSnapshot, SnapshotCatalog, createMcpServer, startHttpHost]\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` adapts catalog operations to MCP.\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 | Sync | Requires catalog and version |\n| `startHttpHost` | Loopback Streamable HTTP host | Async | HTTP remains local-only |\n\n## Package Entry Point\n\n| Import | Purpose |\n| --- | --- |\n| `@vielzeug/codex` | Snapshot, catalog, MCP, and HTTP APIs |\n\n## Snapshot\n\n### `loadSnapshot`\n\n```ts\nloadSnapshot(snapshotDirectory?: string): LoadedSnapshot;\n```\n\nLoads catalog/search metadata only. Use `validateSnapshot()` during generation, integration tests, or explicit artifact verification; package chunks stay lazy at runtime.\n\n### `SnapshotCatalog`\n\n```ts\nnew SnapshotCatalog(snapshot: LoadedSnapshot)\n```\n\nProvides package lookup, docs/source/example/signature access, deterministic search, and Refine component lookup.\n\n## MCP\n\n### `createMcpServer`\n\n```ts\ncreateMcpServer(catalog: Catalog, options: { version: string; debug?: boolean }): Server;\n```\n\nRegisters MCP tools as an adapter over `Catalog`.\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. Host accepts only loopback addresses.\n\n## Types\n\n```ts\ninterface SnapshotPointer {\n directory: 'snapshots/<immutable-id>';\n}\n\n// Dev snapshots use SnapshotPointer; published snapshots are static directories.\ninterface SnapshotManifest {\n schemaVersion: 1;\n catalog: 'catalog.json';\n search: 'search.json';\n contentDirectory: 'packages';\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. No legacy SSE endpoint, CORS wildcard, or remote host mode exists.\n\n## Local Development\n\nRequires Node 22+ and root setup:\n\n```sh\npnpm setup\ncd packages/codex\npnpm test:unit\npnpm test:integration\npnpm dev\n```\n\n`test:unit` uses fixtures only. `test:integration` regenerates a current snapshot then checks real monorepo inputs.\n\n`pnpm dev` watches documentation and package inputs, atomically publishes snapshots, then restarts server when snapshot changes.\n\n## Debugging\n\n```sh\npnpm 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, createMcpServer, loadSnapshot } from '@vielzeug/codex';\nimport { StdioServerTransport } from '@modelcontextprotocol/server/stdio';\n\nconst snapshot = loadSnapshot();\nconst catalog = new SnapshotCatalog(snapshot);\nawait createMcpServer(catalog, { version: snapshot.manifest.version }).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- Run `validateSnapshot()` in artifact verification paths, not normal server startup.\n- Keep HTTP local. Use stdio for normal client integration.\n- Run `pnpm test:unit` before `pnpm test:integration`.\n",
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
- },
9
- "examples": [],
10
- "typeSignatures": {
11
- "Catalog": "export { type Catalog, CatalogError, type SearchHit, SnapshotCatalog } from './catalog.js';",
12
- "CatalogError": "export { type Catalog, CatalogError, type SearchHit, SnapshotCatalog } from './catalog.js';",
13
- "SearchHit": "export { type Catalog, CatalogError, type SearchHit, SnapshotCatalog } from './catalog.js';",
14
- "SnapshotCatalog": "export { type Catalog, CatalogError, type SearchHit, SnapshotCatalog } from './catalog.js';",
15
- "CodexError": "export { CodexError } from './errors.js';",
16
- "HttpHost": "export { type HttpHost, type HttpHostOptions, startHttpHost } from './http.js';",
17
- "HttpHostOptions": "export { type HttpHost, type HttpHostOptions, startHttpHost } from './http.js';",
18
- "startHttpHost": "export { type HttpHost, type HttpHostOptions, startHttpHost } from './http.js';",
19
- "createMcpServer": "export { createMcpServer } from './server.js';",
20
- "loadSnapshot": "export {\n loadSnapshot,\n parseCatalog,\n parseContent,\n parseManifest,\n parsePointer,\n parseSearch,\n validateSnapshot,\n} from './snapshot.js';",
21
- "parseCatalog": "export {\n loadSnapshot,\n parseCatalog,\n parseContent,\n parseManifest,\n parsePointer,\n parseSearch,\n validateSnapshot,\n} from './snapshot.js';",
22
- "parseContent": "export {\n loadSnapshot,\n parseCatalog,\n parseContent,\n parseManifest,\n parsePointer,\n parseSearch,\n validateSnapshot,\n} from './snapshot.js';",
23
- "parseManifest": "export {\n loadSnapshot,\n parseCatalog,\n parseContent,\n parseManifest,\n parsePointer,\n parseSearch,\n validateSnapshot,\n} from './snapshot.js';",
24
- "parsePointer": "export {\n loadSnapshot,\n parseCatalog,\n parseContent,\n parseManifest,\n parsePointer,\n parseSearch,\n validateSnapshot,\n} from './snapshot.js';",
25
- "parseSearch": "export {\n loadSnapshot,\n parseCatalog,\n parseContent,\n parseManifest,\n parsePointer,\n parseSearch,\n validateSnapshot,\n} from './snapshot.js';",
26
- "validateSnapshot": "export {\n loadSnapshot,\n parseCatalog,\n parseContent,\n parseManifest,\n parsePointer,\n parseSearch,\n validateSnapshot,\n} from './snapshot.js';",
27
- "CemAttribute": "export {\n type CemAttribute,\n type CemCssPart,\n type CemCssProperty,\n type CemDeclaration,\n type CemEvent,\n type CemMember,\n type CemSlot,\n DOC_PAGES,\n type DocPage,\n type Example,\n type PackageContent,\n type PackageMeta,\n SNAPSHOT_SCHEMA_VERSION,\n type SnapshotManifest,\n type SnapshotPointer,\n} from './types.js';",
28
- "CemCssPart": "export {\n type CemAttribute,\n type CemCssPart,\n type CemCssProperty,\n type CemDeclaration,\n type CemEvent,\n type CemMember,\n type CemSlot,\n DOC_PAGES,\n type DocPage,\n type Example,\n type PackageContent,\n type PackageMeta,\n SNAPSHOT_SCHEMA_VERSION,\n type SnapshotManifest,\n type SnapshotPointer,\n} from './types.js';",
29
- "CemCssProperty": "export {\n type CemAttribute,\n type CemCssPart,\n type CemCssProperty,\n type CemDeclaration,\n type CemEvent,\n type CemMember,\n type CemSlot,\n DOC_PAGES,\n type DocPage,\n type Example,\n type PackageContent,\n type PackageMeta,\n SNAPSHOT_SCHEMA_VERSION,\n type SnapshotManifest,\n type SnapshotPointer,\n} from './types.js';",
30
- "CemDeclaration": "export {\n type CemAttribute,\n type CemCssPart,\n type CemCssProperty,\n type CemDeclaration,\n type CemEvent,\n type CemMember,\n type CemSlot,\n DOC_PAGES,\n type DocPage,\n type Example,\n type PackageContent,\n type PackageMeta,\n SNAPSHOT_SCHEMA_VERSION,\n type SnapshotManifest,\n type SnapshotPointer,\n} from './types.js';",
31
- "CemEvent": "export {\n type CemAttribute,\n type CemCssPart,\n type CemCssProperty,\n type CemDeclaration,\n type CemEvent,\n type CemMember,\n type CemSlot,\n DOC_PAGES,\n type DocPage,\n type Example,\n type PackageContent,\n type PackageMeta,\n SNAPSHOT_SCHEMA_VERSION,\n type SnapshotManifest,\n type SnapshotPointer,\n} from './types.js';",
32
- "CemMember": "export {\n type CemAttribute,\n type CemCssPart,\n type CemCssProperty,\n type CemDeclaration,\n type CemEvent,\n type CemMember,\n type CemSlot,\n DOC_PAGES,\n type DocPage,\n type Example,\n type PackageContent,\n type PackageMeta,\n SNAPSHOT_SCHEMA_VERSION,\n type SnapshotManifest,\n type SnapshotPointer,\n} from './types.js';",
33
- "CemSlot": "export {\n type CemAttribute,\n type CemCssPart,\n type CemCssProperty,\n type CemDeclaration,\n type CemEvent,\n type CemMember,\n type CemSlot,\n DOC_PAGES,\n type DocPage,\n type Example,\n type PackageContent,\n type PackageMeta,\n SNAPSHOT_SCHEMA_VERSION,\n type SnapshotManifest,\n type SnapshotPointer,\n} from './types.js';",
34
- "DOC_PAGES": "export {\n type CemAttribute,\n type CemCssPart,\n type CemCssProperty,\n type CemDeclaration,\n type CemEvent,\n type CemMember,\n type CemSlot,\n DOC_PAGES,\n type DocPage,\n type Example,\n type PackageContent,\n type PackageMeta,\n SNAPSHOT_SCHEMA_VERSION,\n type SnapshotManifest,\n type SnapshotPointer,\n} from './types.js';",
35
- "DocPage": "export {\n type CemAttribute,\n type CemCssPart,\n type CemCssProperty,\n type CemDeclaration,\n type CemEvent,\n type CemMember,\n type CemSlot,\n DOC_PAGES,\n type DocPage,\n type Example,\n type PackageContent,\n type PackageMeta,\n SNAPSHOT_SCHEMA_VERSION,\n type SnapshotManifest,\n type SnapshotPointer,\n} from './types.js';",
36
- "Example": "export {\n type CemAttribute,\n type CemCssPart,\n type CemCssProperty,\n type CemDeclaration,\n type CemEvent,\n type CemMember,\n type CemSlot,\n DOC_PAGES,\n type DocPage,\n type Example,\n type PackageContent,\n type PackageMeta,\n SNAPSHOT_SCHEMA_VERSION,\n type SnapshotManifest,\n type SnapshotPointer,\n} from './types.js';",
37
- "PackageContent": "export {\n type CemAttribute,\n type CemCssPart,\n type CemCssProperty,\n type CemDeclaration,\n type CemEvent,\n type CemMember,\n type CemSlot,\n DOC_PAGES,\n type DocPage,\n type Example,\n type PackageContent,\n type PackageMeta,\n SNAPSHOT_SCHEMA_VERSION,\n type SnapshotManifest,\n type SnapshotPointer,\n} from './types.js';",
38
- "PackageMeta": "export {\n type CemAttribute,\n type CemCssPart,\n type CemCssProperty,\n type CemDeclaration,\n type CemEvent,\n type CemMember,\n type CemSlot,\n DOC_PAGES,\n type DocPage,\n type Example,\n type PackageContent,\n type PackageMeta,\n SNAPSHOT_SCHEMA_VERSION,\n type SnapshotManifest,\n type SnapshotPointer,\n} from './types.js';",
39
- "SNAPSHOT_SCHEMA_VERSION": "export {\n type CemAttribute,\n type CemCssPart,\n type CemCssProperty,\n type CemDeclaration,\n type CemEvent,\n type CemMember,\n type CemSlot,\n DOC_PAGES,\n type DocPage,\n type Example,\n type PackageContent,\n type PackageMeta,\n SNAPSHOT_SCHEMA_VERSION,\n type SnapshotManifest,\n type SnapshotPointer,\n} from './types.js';",
40
- "SnapshotManifest": "export {\n type CemAttribute,\n type CemCssPart,\n type CemCssProperty,\n type CemDeclaration,\n type CemEvent,\n type CemMember,\n type CemSlot,\n DOC_PAGES,\n type DocPage,\n type Example,\n type PackageContent,\n type PackageMeta,\n SNAPSHOT_SCHEMA_VERSION,\n type SnapshotManifest,\n type SnapshotPointer,\n} from './types.js';",
41
- "SnapshotPointer": "export {\n type CemAttribute,\n type CemCssPart,\n type CemCssProperty,\n type CemDeclaration,\n type CemEvent,\n type CemMember,\n type CemSlot,\n DOC_PAGES,\n type DocPage,\n type Example,\n type PackageContent,\n type PackageMeta,\n SNAPSHOT_SCHEMA_VERSION,\n type SnapshotManifest,\n type SnapshotPointer,\n} from './types.js';"
42
- }
43
- }
@@ -1,103 +0,0 @@
1
- {
2
- "apiSource": "export { allocate, clamp, sum } from './aggregate';\nexport { BHD, currency, defineCurrency, EUR, GBP, isCurrency, JPY, KRW, KWD, USD } from './currency';\nexport { decimal } from './decimal';\nexport type { CoinsErrorCode } from './errors';\nexport { CoinsError, CurrencyMismatchError, InvalidCurrencyError } from './errors';\nexport { exchange, exchangeRate } from './exchange';\nexport { format, formatParts } from './format';\nexport {\n abs,\n add,\n compare,\n divide,\n isMoney,\n money,\n multiply,\n negate,\n parseMoney,\n round,\n subtract,\n toDecimal,\n} from './money';\nexport { parseMoneyJSON, toJSON } from './serialization';\nexport type {\n Currency,\n CurrencyCode,\n Decimal,\n ExchangeRate,\n FormatOptions,\n Money,\n MoneyFormatPart,\n MoneyJSON,\n RoundingMode,\n} from './types';\n",
3
- "docs": {
4
- "index": "---\ntitle: Coins — Exact Money for TypeScript\ndescription: Exact bigint monetary arithmetic with explicit currency definitions, decimal strings, allocation, exchange, formatting, and JSON boundaries.\npackage: coins\ncategory: finance\nkeywords: [money, currency, bigint, decimal, exchange, formatting]\nexports: [money, currency, add, allocate, exchange, format]\nrelated: [vault, courier, spell]\nenvironments: [browser, node, ssr, deno]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"coins\" />\n\n## Why Coins?\n\nCoins keeps monetary values in bigint minor units, but makes units explicit at construction. Currency scale comes from deterministic definitions; `Intl` formats a known value without deciding its arithmetic representation.\n\n```ts\n// Before\nconst total = (19.99 + 7.25) * 1.08;\n\n// After\nimport { USD, add, money, multiply } from '@vielzeug/coins';\n\nconst total = multiply(add(money('19.99', USD), money('7.25', USD)), '1.08');\n```\n\n| Feature | Coins | decimal.js | Dinero.js |\n| --- | --- | --- | --- |\n| Bundle size | <PackageInfo package=\"coins\" type=\"size\" /> | External dependency | External dependency |\n| Bigint minor units | <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| Explicit currency scale | <ore-icon name=\"check\" size=\"16\"></ore-icon> | App-defined | Partial |\n| Exact allocation | <ore-icon name=\"check\" size=\"16\"></ore-icon> | Manual | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n| Zero dependencies | <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\n<div class=\"decision-callout\">\n\n**Use Coins when** application values represent real money and every rounding boundary must be visible.\n\n**Consider native numbers when** values are estimates, analytics, or display-only approximations.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/coins\n```\n\n```sh [npm]\nnpm install @vielzeug/coins\n```\n\n```sh [yarn]\nyarn add @vielzeug/coins\n```\n\n:::\n\n## Quick Start\n\n```ts\nimport { USD, add, format, money, multiply } from '@vielzeug/coins';\n\nconst subtotal = add(money('12.50', USD), money('7.25', USD));\nconst total = multiply(subtotal, '1.08', { rounding: 'halfEven' });\n\nconsole.log(format(total));\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- **`money`**: one constructor for decimal and explicit minor-unit values\n- **`currency`**: deterministic built-in currency definitions\n- **`add`**: exact same-currency arithmetic\n- **`allocate`**: split every minor unit without loss\n- **`exchange`**: typed source and target currency conversion\n- **`format`**: locale presentation for bigint values\n- **`parseMoneyJSON`**: validate persisted money values\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- [Vault](/vault/) — persist validated money JSON.\n- [Courier](/courier/) — retrieve exchange-rate data.\n- [Spell](/spell/) — validate external monetary payloads.\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
5
- "api": "---\ntitle: Coins — API Reference\ndescription: Exact money, currency definitions, exchange, formatting, serialization, and errors.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution | Common gotcha |\n| --- | --- | --- | --- |\n| `money` | Construct validated money | Sync | Bigint requires `{ unit: 'minor' }` |\n| `currency` | Resolve supported definition | Sync | Unknown codes throw |\n| `defineCurrency` | Define an explicit scale | Sync | Code must be three uppercase letters |\n| `add` / `subtract` | Combine matching currencies | Sync | Mismatches throw |\n| `multiply` / `divide` | Exact decimal scaling | Sync | Use decimal strings |\n| `sum` | Aggregate with identity currency | Sync | Pass `{ currency }` |\n| `allocate` | Split without losing minor units | Sync | Weights must be non-negative |\n| `exchange` | Convert through an exact rate | Sync | Rate source must match value currency |\n| `format` | Present money with `Intl` | Sync | Formatting does not define currency scale |\n| `toJSON` / `parseMoneyJSON` | Cross JSON boundary | Sync | Persisted amount uses minor units |\n\n## Package Entry Point\n\n| Import | Purpose |\n| --- | --- |\n| `@vielzeug/coins` | Complete public Coins API |\n\n## Construction\n\n### currency / defineCurrency\n\n```ts\ncurrency(code: string): Currency\ndefineCurrency({ code, minorUnit }): Currency\n```\n\nBuilt-ins: `USD`, `EUR`, `GBP`, `JPY`, `KRW`, `BHD`, `KWD`.\n\n### money\n\n```ts\nmoney(amount: string, currency: Currency): Money\nmoney(amount: string, currency: Currency, options: { rounding: RoundingMode }): Money\nmoney(amount: bigint, currency: Currency, options: { unit: 'minor' }): Money\n```\n\n```ts\nmoney('19.99', USD);\nmoney(1999n, USD, { unit: 'minor' });\n```\n\n### decimal\n\n```ts\ndecimal(value: string): Decimal\n```\n\nCreates an exact rational value for multiplication, division, or exchange rates.\n\n## Arithmetic\n\n```ts\nadd(left, right)\nsubtract(left, right)\nmultiply(value, factor, { rounding? })\ndivide(value, divisor, { rounding? })\ncompare(left, right)\nabs(value)\nnegate(value)\nround(value, { fractionDigits, rounding? })\n```\n\n`factor` and `divisor` are decimal strings. Matching currency is required for binary money operations.\n\n## Aggregation\n\n```ts\nsum(values, { currency })\nallocate(value, count)\nallocate(value, weights)\nclamp(value, { min, max })\n```\n\n`sum([], { currency: USD })` returns zero USD. `allocate` returns values whose minor-unit total exactly equals input.\n\n## Exchange\n\n```ts\nexchangeRate({ from, to, value }): ExchangeRate\nexchange(value, rate, { rounding? }): Money\n```\n\n```ts\nconst rate = exchangeRate({ from: USD, to: EUR, value: '0.9234' });\nexchange(money('100.00', USD), rate);\n```\n\n## Formatting\n\n```ts\nformat(value, options?): string\nformatParts(value, options?): MoneyFormatPart[]\n```\n\n`FormatOptions` uses `locale`, `style`, `minimumFractionDigits`, and `maximumFractionDigits`.\n\n## Serialization\n\n```ts\ntoDecimal(value): string\ntoJSON(value): MoneyJSON\nparseMoneyJSON(value: unknown, options?: { currency?: (code: string) => Currency }): Money\nparseMoney(value: unknown): Money\nisMoney(value: unknown): value is Money\n```\n\n## Types\n\n```ts\ntype Currency = { code: CurrencyCode; minorUnit: number };\ntype Money = { amount: bigint; currency: Currency };\ntype Decimal = { numerator: bigint; denominator: bigint };\ntype ExchangeRate = { from: Currency; to: Currency; value: Decimal };\ntype MoneyJSON = { amount: string; currency: string; unit: 'minor' };\ntype RoundingMode = 'awayFromZero' | 'ceil' | 'floor' | 'halfAwayFromZero' | 'halfEven' | 'towardZero';\n```\n\n## Errors\n\nEvery Coins failure extends `CoinsError` and exposes `code`.\n\n- `INVALID_CURRENCY`\n- `INVALID_DECIMAL`\n- `INVALID_MONEY`\n- `INVALID_ALLOCATION`\n- `INVALID_ROUNDING`\n- `DIVISION_BY_ZERO`\n- `CURRENCY_MISMATCH`\n\n`CurrencyMismatchError` and `InvalidCurrencyError` are specialized `CoinsError` subclasses.\n",
6
- "usage": "---\ntitle: Coins — Usage Guide\ndescription: Construct exact money, aggregate values, convert currencies, and format results with Coins.\n---\n\n[[toc]]\n\n## Basic Usage\n\nConstruct decimal values with a currency definition. Coins stores minor units internally and never accepts implicit floating-point input.\n\n```ts\nimport { USD, add, money, toDecimal } from '@vielzeug/coins';\n\nconst subtotal = add(money('12.50', USD), money('7.25', USD));\n\nconsole.log(toDecimal(subtotal)); // '19.75'\n```\n\nUse bigint only when data is already in minor units:\n\n```ts\nimport { USD, money } from '@vielzeug/coins';\n\nconst cents = money(1999n, USD, { unit: 'minor' });\n```\n\n## Define Currencies\n\nUse built-in currency definitions for supported ISO currencies. Define a currency explicitly when your domain has a distinct scale.\n\n```ts\nimport { EUR, USD, defineCurrency, money } from '@vielzeug/coins';\n\nconst rewards = defineCurrency({ code: 'PTS', minorUnit: 0 });\n\nmoney('10.00', USD);\nmoney('10.00', EUR);\nmoney('500', rewards);\n```\n\n## Apply Exact Arithmetic\n\nPass decimal strings to scaling operations. Use named rounding whenever an operation can produce fractional minor units.\n\n```ts\nimport { USD, divide, money, multiply, round, toDecimal } from '@vielzeug/coins';\n\nconst subtotal = money('19.99', USD);\nconst taxed = multiply(subtotal, '1.08', { rounding: 'halfEven' });\n\n// Extra currency precision must name its rounding policy.\nconst roundedInput = money('19.999', USD, { rounding: 'halfAwayFromZero' });\nconst split = divide(taxed, '3', { rounding: 'floor' });\nconst displayed = round(taxed, { fractionDigits: 0, rounding: 'halfAwayFromZero' });\n\nconsole.log(toDecimal(split), toDecimal(displayed));\n```\n\n## Aggregate and Allocate\n\n`sum` receives currency context, so empty collections produce a useful zero. `allocate` preserves every minor unit.\n\n```ts\nimport { USD, allocate, money, sum, toDecimal } from '@vielzeug/coins';\n\nconst total = sum([], { currency: USD });\nconst weighted = allocate(money('10.00', USD), ['1', '2', '1']);\nconst even = allocate(money(5n, USD, { unit: 'minor' }), 2);\n\nconsole.log(toDecimal(total));\nconsole.log(weighted.map(toDecimal));\nconsole.log(even.map((value) => value.amount)); // [3n, 2n]\n```\n\n## Convert Currency\n\nCreate a typed rate from currency definitions and an exact decimal string.\n\n```ts\nimport { EUR, USD, exchange, exchangeRate, format, money } from '@vielzeug/coins';\n\nconst usdToEur = exchangeRate({ from: USD, to: EUR, value: '0.9234' });\nconst euros = exchange(money('100.00', USD), usdToEur, { rounding: 'halfEven' });\n\nconsole.log(format(euros, { locale: 'de-DE' }));\n```\n\n## Serialize Money\n\nUse JSON helpers at storage and transport boundaries. Parsing validates the shape, unit, and currency code.\n\n```ts\nimport { USD, money, parseMoneyJSON, toJSON } from '@vielzeug/coins';\n\nconst encoded = toJSON(money('19.99', USD));\nconst restored = parseMoneyJSON(encoded);\n\n// Custom currencies require an explicit resolver at restore time.\nconst custom = parseMoneyJSON(customEncoded, { currency: resolveAppCurrency });\n```\n\n## Handle Errors\n\nUse `CoinsError.code` for stable recovery branches.\n\n```ts\nimport { CoinsError, USD, money } from '@vielzeug/coins';\n\ntry {\n money(1999n, USD);\n} catch (error) {\n if (error instanceof CoinsError && error.code === 'INVALID_MONEY') {\n console.log('Use { unit: \\'minor\\' } for bigint amounts.');\n }\n}\n```\n\n## Best Practices\n\n- Use decimal strings for exact external inputs.\n- Use bigint only with `{ unit: 'minor' }`.\n- Pass named rounding options for division, scaling, and exchange.\n- Keep currency definitions at application boundaries.\n- Use `sum(values, { currency })` for possibly empty collections.\n- Serialize with `toJSON` and validate with `parseMoneyJSON`.\n- Format only at presentation boundaries.\n",
7
- "examples": "---\ntitle: Coins — Examples\ndescription: Practical examples and recipes for @vielzeug/coins.\n---\n\n## Examples\n\n- [Formatting](./examples/formatting.md)\n- [Exchange Rate Conversion](./examples/exchange.md)\n- [Allocation](./examples/allocation.md)\n"
8
- },
9
- "examples": [
10
- {
11
- "id": "allocation-basic",
12
- "code": "import { USD, allocate, money, sum, toDecimal } from '@vielzeug/coins'\n\nconst weighted = allocate(money('10.00', USD), ['1', '2', '1'])\nconst even = allocate(money(5n, USD, { unit: 'minor' }), 2)\n\nconsole.log(weighted.map(toDecimal))\nconsole.log(toDecimal(sum(weighted, { currency: USD })))\nconsole.log(even.map(value => value.amount))",
13
- "name": "allocate - Preserve every minor unit"
14
- },
15
- {
16
- "id": "arithmetic-basic",
17
- "code": "import { USD, add, divide, money, multiply, subtract, toDecimal } from '@vielzeug/coins'\n\nconst subtotal = add(money('12.50', USD), money('7.25', USD))\nconst taxed = multiply(subtotal, '1.08', { rounding: 'halfEven' })\nconst split = divide(taxed, '3', { rounding: 'floor' })\n\nconsole.log(toDecimal(subtract(subtotal, money('1.00', USD))) )\nconsole.log(toDecimal(taxed))\nconsole.log(toDecimal(split))",
18
- "name": "Arithmetic - Exact decimal scaling"
19
- },
20
- {
21
- "id": "errors-basic",
22
- "code": "import { CoinsError, USD, money } from '@vielzeug/coins'\n\ntry {\n money(1999n, USD)\n} catch (error) {\n if (error instanceof CoinsError) {\n console.log(error.code)\n console.log(error.message)\n }\n}",
23
- "name": "Errors - Stable codes"
24
- },
25
- {
26
- "id": "exchange-basic",
27
- "code": "import { EUR, USD, exchange, exchangeRate, format, money } from '@vielzeug/coins'\n\nconst usdToEur = exchangeRate({ from: USD, to: EUR, value: '0.9234' })\nconst euros = exchange(money('100.00', USD), usdToEur, { rounding: 'halfEven' })\n\nconsole.log(format(euros, { locale: 'de-DE' }))",
28
- "name": "exchange - Exact currency conversion"
29
- },
30
- {
31
- "id": "format-basic",
32
- "code": "import { EUR, USD, format, formatParts, money } from '@vielzeug/coins'\n\nconst value = money('1234.56', USD)\n\nconsole.log(format(value))\nconsole.log(format(money('1234.56', EUR), { locale: 'de-DE' }))\nconsole.log(formatParts(value))",
33
- "name": "format - Locale presentation"
34
- },
35
- {
36
- "id": "money-basic",
37
- "code": "import { USD, money, toDecimal, toJSON } from '@vielzeug/coins'\n\nconst price = money('19.99', USD)\nconst stored = money(1999n, USD, { unit: 'minor' })\n\nconsole.log(toDecimal(price))\nconsole.log(stored.amount)\nconsole.log(toJSON(price))",
38
- "name": "money - Decimal and minor-unit construction"
39
- },
40
- {
41
- "id": "rounding-basic",
42
- "code": "import { USD, money, round, toDecimal } from '@vielzeug/coins'\n\nconst value = money('1.55', USD)\n\nconsole.log(toDecimal(round(value, { fractionDigits: 1, rounding: 'halfEven' })))\nconsole.log(toDecimal(round(value, { fractionDigits: 1, rounding: 'towardZero' })))",
43
- "name": "round - Explicit rounding policy"
44
- },
45
- {
46
- "id": "serialization-basic",
47
- "code": "import { USD, money, parseMoneyJSON, toJSON } from '@vielzeug/coins'\n\nconst encoded = toJSON(money('19.99', USD))\nconst restored = parseMoneyJSON(encoded)\n\nconsole.log(encoded)\nconsole.log(restored.amount, restored.currency.code)",
48
- "name": "Serialization - Validate JSON boundaries"
49
- },
50
- {
51
- "id": "utilities-basic",
52
- "code": "import { currency, defineCurrency, isCurrency, isMoney, money } from '@vielzeug/coins'\n\nconst points = defineCurrency({ code: 'PTS', minorUnit: 0 })\nconst balance = money('250', points)\n\nconsole.log(currency('USD').minorUnit)\nconsole.log(isCurrency(points))\nconsole.log(isMoney(balance))",
53
- "name": "Currency definitions and validation"
54
- }
55
- ],
56
- "typeSignatures": {
57
- "allocate": "export { allocate, clamp, sum } from './aggregate';",
58
- "clamp": "export { allocate, clamp, sum } from './aggregate';",
59
- "sum": "export { allocate, clamp, sum } from './aggregate';",
60
- "BHD": "export { BHD, currency, defineCurrency, EUR, GBP, isCurrency, JPY, KRW, KWD, USD } from './currency';",
61
- "currency": "export { BHD, currency, defineCurrency, EUR, GBP, isCurrency, JPY, KRW, KWD, USD } from './currency';",
62
- "defineCurrency": "export { BHD, currency, defineCurrency, EUR, GBP, isCurrency, JPY, KRW, KWD, USD } from './currency';",
63
- "EUR": "export { BHD, currency, defineCurrency, EUR, GBP, isCurrency, JPY, KRW, KWD, USD } from './currency';",
64
- "GBP": "export { BHD, currency, defineCurrency, EUR, GBP, isCurrency, JPY, KRW, KWD, USD } from './currency';",
65
- "isCurrency": "export { BHD, currency, defineCurrency, EUR, GBP, isCurrency, JPY, KRW, KWD, USD } from './currency';",
66
- "JPY": "export { BHD, currency, defineCurrency, EUR, GBP, isCurrency, JPY, KRW, KWD, USD } from './currency';",
67
- "KRW": "export { BHD, currency, defineCurrency, EUR, GBP, isCurrency, JPY, KRW, KWD, USD } from './currency';",
68
- "KWD": "export { BHD, currency, defineCurrency, EUR, GBP, isCurrency, JPY, KRW, KWD, USD } from './currency';",
69
- "USD": "export { BHD, currency, defineCurrency, EUR, GBP, isCurrency, JPY, KRW, KWD, USD } from './currency';",
70
- "decimal": "export { decimal } from './decimal';",
71
- "CoinsErrorCode": "export type { CoinsErrorCode } from './errors';",
72
- "CoinsError": "export { CoinsError, CurrencyMismatchError, InvalidCurrencyError } from './errors';",
73
- "CurrencyMismatchError": "export { CoinsError, CurrencyMismatchError, InvalidCurrencyError } from './errors';",
74
- "InvalidCurrencyError": "export { CoinsError, CurrencyMismatchError, InvalidCurrencyError } from './errors';",
75
- "exchange": "export { exchange, exchangeRate } from './exchange';",
76
- "exchangeRate": "export { exchange, exchangeRate } from './exchange';",
77
- "format": "export { format, formatParts } from './format';",
78
- "formatParts": "export { format, formatParts } from './format';",
79
- "abs": "export {\n abs,\n add,\n compare,\n divide,\n isMoney,\n money,\n multiply,\n negate,\n parseMoney,\n round,\n subtract,\n toDecimal,\n} from './money';",
80
- "add": "export {\n abs,\n add,\n compare,\n divide,\n isMoney,\n money,\n multiply,\n negate,\n parseMoney,\n round,\n subtract,\n toDecimal,\n} from './money';",
81
- "compare": "export {\n abs,\n add,\n compare,\n divide,\n isMoney,\n money,\n multiply,\n negate,\n parseMoney,\n round,\n subtract,\n toDecimal,\n} from './money';",
82
- "divide": "export {\n abs,\n add,\n compare,\n divide,\n isMoney,\n money,\n multiply,\n negate,\n parseMoney,\n round,\n subtract,\n toDecimal,\n} from './money';",
83
- "isMoney": "export {\n abs,\n add,\n compare,\n divide,\n isMoney,\n money,\n multiply,\n negate,\n parseMoney,\n round,\n subtract,\n toDecimal,\n} from './money';",
84
- "money": "export {\n abs,\n add,\n compare,\n divide,\n isMoney,\n money,\n multiply,\n negate,\n parseMoney,\n round,\n subtract,\n toDecimal,\n} from './money';",
85
- "multiply": "export {\n abs,\n add,\n compare,\n divide,\n isMoney,\n money,\n multiply,\n negate,\n parseMoney,\n round,\n subtract,\n toDecimal,\n} from './money';",
86
- "negate": "export {\n abs,\n add,\n compare,\n divide,\n isMoney,\n money,\n multiply,\n negate,\n parseMoney,\n round,\n subtract,\n toDecimal,\n} from './money';",
87
- "parseMoney": "export {\n abs,\n add,\n compare,\n divide,\n isMoney,\n money,\n multiply,\n negate,\n parseMoney,\n round,\n subtract,\n toDecimal,\n} from './money';",
88
- "round": "export {\n abs,\n add,\n compare,\n divide,\n isMoney,\n money,\n multiply,\n negate,\n parseMoney,\n round,\n subtract,\n toDecimal,\n} from './money';",
89
- "subtract": "export {\n abs,\n add,\n compare,\n divide,\n isMoney,\n money,\n multiply,\n negate,\n parseMoney,\n round,\n subtract,\n toDecimal,\n} from './money';",
90
- "toDecimal": "export {\n abs,\n add,\n compare,\n divide,\n isMoney,\n money,\n multiply,\n negate,\n parseMoney,\n round,\n subtract,\n toDecimal,\n} from './money';",
91
- "parseMoneyJSON": "export { parseMoneyJSON, toJSON } from './serialization';",
92
- "toJSON": "export { parseMoneyJSON, toJSON } from './serialization';",
93
- "Currency": "export type {\n Currency,\n CurrencyCode,\n Decimal,\n ExchangeRate,\n FormatOptions,\n Money,\n MoneyFormatPart,\n MoneyJSON,\n RoundingMode,\n} from './types';",
94
- "CurrencyCode": "export type {\n Currency,\n CurrencyCode,\n Decimal,\n ExchangeRate,\n FormatOptions,\n Money,\n MoneyFormatPart,\n MoneyJSON,\n RoundingMode,\n} from './types';",
95
- "Decimal": "export type {\n Currency,\n CurrencyCode,\n Decimal,\n ExchangeRate,\n FormatOptions,\n Money,\n MoneyFormatPart,\n MoneyJSON,\n RoundingMode,\n} from './types';",
96
- "ExchangeRate": "export type {\n Currency,\n CurrencyCode,\n Decimal,\n ExchangeRate,\n FormatOptions,\n Money,\n MoneyFormatPart,\n MoneyJSON,\n RoundingMode,\n} from './types';",
97
- "FormatOptions": "export type {\n Currency,\n CurrencyCode,\n Decimal,\n ExchangeRate,\n FormatOptions,\n Money,\n MoneyFormatPart,\n MoneyJSON,\n RoundingMode,\n} from './types';",
98
- "Money": "export type {\n Currency,\n CurrencyCode,\n Decimal,\n ExchangeRate,\n FormatOptions,\n Money,\n MoneyFormatPart,\n MoneyJSON,\n RoundingMode,\n} from './types';",
99
- "MoneyFormatPart": "export type {\n Currency,\n CurrencyCode,\n Decimal,\n ExchangeRate,\n FormatOptions,\n Money,\n MoneyFormatPart,\n MoneyJSON,\n RoundingMode,\n} from './types';",
100
- "MoneyJSON": "export type {\n Currency,\n CurrencyCode,\n Decimal,\n ExchangeRate,\n FormatOptions,\n Money,\n MoneyFormatPart,\n MoneyJSON,\n RoundingMode,\n} from './types';",
101
- "RoundingMode": "export type {\n Currency,\n CurrencyCode,\n Decimal,\n ExchangeRate,\n FormatOptions,\n Money,\n MoneyFormatPart,\n MoneyJSON,\n RoundingMode,\n} from './types';"
102
- }
103
- }
@@ -1,60 +0,0 @@
1
- {
2
- "apiSource": "export { createContainer } from './container';\nexport {\n ConduitCircularDependencyError,\n ConduitDisposedError,\n ConduitDisposeError,\n ConduitDuplicateRegistrationError,\n ConduitError,\n ConduitProviderNotFoundError,\n ConduitScopedResolutionError,\n} from './errors';\nexport type { Container, FactoryOptions, InferTokens, Lifetime, ScopeToken, Token, ValueOptions } from './types';\nexport { scope, token } from './types';\n",
3
- "docs": {
4
- "index": "---\ntitle: Conduit — Dependency Injection for TypeScript\ndescription: Dependency-first asynchronous dependency injection with typed tokens, lifecycle scopes, startup validation, and deterministic disposal.\npackage: conduit\ncategory: infrastructure\nkeywords: [dependency injection, container, token, lifecycle, scope]\nexports: [createContainer, token, scope]\nrelated: [courier, vault, rune]\nenvironments: [browser, node, ssr, deno]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"conduit\" />\n\n## Why Conduit?\n\nConduit makes service wiring explicit. Factory dependency tuples are source of truth for creation, startup validation, and disposal order.\n\n```ts\n// Before\nconst service = createService(createApi(config), logger);\n\n// After\ncontainer.factory(Service, [Api, Logger], (api, logger) => createService(api, logger));\n```\n\n| Feature | Conduit | Inversify | tsyringe |\n| --- | --- | --- | --- |\n| Dependencies | Explicit token tuples | Decorators/runtime metadata | Decorators/runtime metadata |\n| Async factories | <ore-icon name=\"check\" size=\"16\"></ore-icon> | Partial | Partial |\n| Lifecycle scopes | <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| Runtime dependencies | 0 | <ore-icon name=\"x\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> |\n\n<div class=\"decision-callout\">\n\n**Use Conduit when** application services need explicit wiring and owned lifecycle cleanup.\n\n**Consider direct imports when** dependencies are static, small, and need no replacement or disposal boundary.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/conduit\n```\n\n```sh [npm]\nnpm install @vielzeug/conduit\n```\n\n```sh [yarn]\nyarn add @vielzeug/conduit\n```\n\n:::\n\n## Quick Start\n\n```ts\nimport { createContainer, token } from '@vielzeug/conduit';\n\nconst Config = token<{ baseUrl: string }>('Config');\nconst Client = token<{ url: string }>('Client');\nconst container = createContainer();\n\ncontainer.value(Config, { baseUrl: '/api' });\ncontainer.factory(Client, [Config], (config) => ({ url: `${config.baseUrl}/users` }));\n\nconsole.log(await container.resolve(Client));\nawait container.dispose();\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- **`token`**: typed dependency identity\n- **`factory`**: static dependency-first creation\n- **`validate`**: startup graph validation\n- **`scope`**: explicit request and job ownership\n- **`dispose`**: in-flight-safe resource cleanup\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- [Courier](/courier/) — inject HTTP clients into application services.\n- [Vault](/vault/) — inject persistence adapters with scoped ownership.\n- [Rune](/rune/) — provide application logging services.\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
5
- "api": "---\ntitle: Conduit — API Reference\ndescription: Reference for Conduit tokens, dependency-first factories, scopes, validation, and lifecycle disposal.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Mode | Common gotcha |\n| --- | --- | --- | --- |\n| `token` | Create typed dependency identity | Sync | Same description does not mean same token |\n| `scope` | Create named lifecycle identity | Sync | Must match factory lifetime |\n| `createContainer` | Create root registry | Sync | Dispose when application ends |\n| `value` | Register an existing value | Sync | One registration per token/container |\n| `factory` | Register static dependency factory | Sync | Tuple is copied and authoritative |\n| `has` | Check registration visibility | Sync | Walks parent containers |\n| `resolve` | Resolve one dependency | Async | Missing provider throws |\n| `validate` | Validate static graph | Sync | Run after registration |\n| `createScope` | Create child owner | Sync | Named scope required for scoped factories |\n| `dispose` | Release owned resources | Async | May throw `ConduitDisposeError` after cleanup attempts |\n\n## Package Entry Point\n\n| Import | Purpose |\n| --- | --- |\n| `@vielzeug/conduit` | Complete Conduit API |\n\n## Tokens and Scopes\n\n```ts\ntoken<T>(description: string): Token<T>\nscope(name: string): ScopeToken\n```\n\nTokens and scopes are unique symbols. Descriptions exist only for diagnostics.\n\n## Container\n\n```ts\ncreateContainer(options?: { name?: string }): Container\n```\n\n### value\n\n```ts\ncontainer.value(token, value, options?)\n```\n\n`options.dispose` runs during container disposal.\n\n### has\n\n```ts\ncontainer.has(token): boolean\n```\n\nChecks local and parent registrations without creating a factory result.\n\n### factory\n\n```ts\ncontainer.factory(token, dependencies, create, options?)\n```\n\n```ts\ncontainer.factory(Service, [Api, Logger], (api, logger) => createService(api, logger));\n```\n\n`dependencies` is copied at registration and drives creation, validation, cycle detection, and teardown order. Factories may return a value or promise.\n\n`options.lifetime` accepts `'singleton'`, `'transient'`, or `ScopeToken`. A singleton cannot depend on a scoped resource.\n\n```ts\ntype FactoryOptions<T> = {\n dispose?: (value: T) => void | Promise<void>;\n lifetime?: 'singleton' | 'transient' | ScopeToken;\n};\n```\n\n### resolve\n\n```ts\ncontainer.resolve(token): Promise<T>\n```\n\nSingleton resolutions deduplicate concurrent callers.\n\n### validate\n\n```ts\ncontainer.validate(): Container\n```\n\nThrows for missing dependencies and circular factory tuples.\n\n### createScope\n\n```ts\ncontainer.createScope(scope?: ScopeToken, options?: { name?: string }): Container\n```\n\nA matching scope owns resources registered with its `ScopeToken` lifetime. Disposing a parent also disposes its active child scopes.\n\n### dispose\n\n```ts\ncontainer.dispose(): Promise<void>\ncontainer.disposalSignal: AbortSignal\ncontainer.disposed: boolean\n```\n\nDisposal blocks new work, aborts `disposalSignal`, disposes active child scopes, waits for in-flight creation, then disposes owned resources in reverse creation order. Cleanup failures are aggregated in `ConduitDisposeError.errors`.\n\n## Types\n\n```ts\ntype Token<T> = symbol;\ntype ScopeToken = symbol;\ntype Lifetime = 'singleton' | 'transient' | ScopeToken;\ntype InferTokens<Tokens> = { [K in keyof Tokens]: Tokens[K] extends Token<infer T> ? T : never };\n```\n\n## Errors\n\n- `ConduitError` — base class; `ConduitError.is(error)` narrows package errors.\n- `ConduitProviderNotFoundError` — dependency has no registration.\n- `ConduitCircularDependencyError` — static factory tuple graph contains a cycle.\n- `ConduitDuplicateRegistrationError` — token registered twice in one container.\n- `ConduitScopedResolutionError` — scoped factory resolved without matching scope.\n- `ConduitDisposedError` — operation attempted after disposal began.\n- `ConduitDisposeError` — one or more cleanup hooks failed.\n",
6
- "usage": "---\ntitle: Conduit — Usage Guide\ndescription: Register static dependency tuples, resolve services asynchronously, create scopes, validate startup wiring, and dispose owned resources.\n---\n\n[[toc]]\n\n## Basic Usage\n\nCreate tokens once, register values and factories, then resolve through one async API.\n\n```ts\nimport { createContainer, token } from '@vielzeug/conduit';\n\nconst Config = token<{ baseUrl: string }>('Config');\nconst Client = token<{ url: string }>('Client');\n\nconst container = createContainer();\ncontainer.value(Config, { baseUrl: '/api' });\ncontainer.factory(Client, [Config], (config) => ({ url: `${config.baseUrl}/users` }));\n\nconsole.log(await container.resolve(Client));\nawait container.dispose();\n```\n\n## Define Dependencies\n\nFactory token tuples are authoritative. Conduit resolves tuple values in order, validates every edge, and disposes created services in reverse dependency order.\n\n```ts\nconst Logger = token<{ info(message: string): void }>('Logger');\nconst Api = token<{ get(path: string): Promise<unknown> }>('Api');\nconst Service = token<{ load(): Promise<unknown> }>('Service');\n\ncontainer.factory(Service, [Api, Logger], (api, logger) => ({\n async load() {\n logger.info('Loading data');\n return api.get('/data');\n },\n}));\n```\n\n## Choose Lifetimes\n\nFactories are singletons by default. Use transient lifetime for a new value on every resolution. Conduit retains a transient only when its factory has a `dispose` hook.\n\n```ts\nconst RequestId = token<{ id: string }>('RequestId');\n\ncontainer.factory(RequestId, [], () => ({ id: crypto.randomUUID() }), {\n lifetime: 'transient',\n});\n```\n\nConcurrent singleton resolutions share one in-flight factory result. A singleton cannot depend on a scoped resource; give dependent factory equal-or-shorter lifetime instead. Factory dependency tuples are copied at registration, so later caller mutation cannot change Conduit's graph.\n\n## Create Named Scopes\n\nUse a scope token when a resource belongs to a request, job, or test lifecycle.\n\n```ts\nimport { createContainer, scope, token } from '@vielzeug/conduit';\n\nconst Request = scope('request');\nconst Session = token<{ id: string }>('Session');\nconst root = createContainer();\n\nroot.factory(Session, [], () => ({ id: crypto.randomUUID() }), { lifetime: Request });\n\nconst request = root.createScope(Request);\nconst session = await request.resolve(Session);\nawait request.dispose();\nawait root.dispose();\n```\n\n## Validate Startup Wiring\n\nCall `validate()` after registration. It detects missing dependencies and cycles before service resolution. Parent singleton factories validate dependencies from their registration owner; child overrides do not satisfy them.\n\n```ts\ncontainer.validate();\n```\n\n## Dispose Resources\n\n`dispose()` rejects new work, aborts `disposalSignal`, disposes child scopes, waits for in-flight creation, then releases services in reverse creation order. A factory that finishes after disposal starts is immediately cleaned up and its resolver receives `ConduitDisposedError`.\n\n```ts\nawait container.dispose();\n```\n\n`ConduitDisposeError.errors` contains every cleanup failure after Conduit attempts all hooks, including cleanup from in-flight factories and child scopes.\n\n## Testing\n\nCreate a container per test and register explicit values for external dependencies.\n\n```ts\nconst Clock = token<{ now(): number }>('Clock');\nconst Service = token<{ timestamp: number }>('Service');\nconst container = createContainer();\n\ncontainer.value(Clock, { now: () => 123 });\ncontainer.factory(Service, [Clock], (clock) => ({ timestamp: clock.now() }));\n\nexpect(await container.resolve(Service)).toEqual({ timestamp: 123 });\nawait container.dispose();\n```\n\n## Best Practices\n\n- Create tokens at module scope.\n- Declare every factory dependency in its tuple.\n- Keep factories focused on one service.\n- Use scopes for request/job-owned resources.\n- Call `validate()` during startup.\n- Dispose every scope and root container.\n- Keep optional application fallback policy outside Conduit.\n- Use `await using container = createContainer()` when lexical async disposal fits application lifetime.\n",
7
- "examples": "---\ntitle: Conduit — Examples\ndescription: Dependency-first container recipes.\n---\n\n## Examples\n\n- [Basic setup](./examples/basic-setup.md)\n- [Static async providers](./examples/async-providers.md)\n- [Lifetimes](./examples/lifetimes.md)\n- [Named scopes](./examples/named-scopes.md)\n- [Disposal lifecycle](./examples/dispose-lifecycle.md)\n- [Startup validation](./examples/startup-hardening.md)\n"
8
- },
9
- "examples": [
10
- {
11
- "id": "basic-container",
12
- "code": "import { createContainer, token } from '@vielzeug/conduit'\n\nconst Config = token<{ baseUrl: string }>('Config')\nconst Client = token<{ url: string }>('Client')\n\nconst container = createContainer()\ncontainer.value(Config, { baseUrl: '/api' })\ncontainer.factory(Client, [Config], config => ({ url: config.baseUrl + '/users' }))\n\nconsole.log(await container.resolve(Client))\nawait container.dispose()",
13
- "name": "Dependency-first factory"
14
- },
15
- {
16
- "id": "dispose-lifecycle",
17
- "code": "import { createContainer, token } from '@vielzeug/conduit'\n\nconst Database = token('Database')\nconst Service = token('Service')\nconst order = []\nconst container = createContainer()\n\ncontainer.factory(Database, [], () => ({ close() {} }), { dispose: () => { order.push('database') } })\ncontainer.factory(Service, [Database], database => ({ database }), { dispose: () => { order.push('service') } })\n\nawait container.resolve(Service)\nawait container.dispose()\nconsole.log(order)",
18
- "name": "Reverse dependency disposal"
19
- },
20
- {
21
- "id": "lifetimes",
22
- "code": "import { createContainer, token } from '@vielzeug/conduit'\n\nconst Singleton = token('Singleton')\nconst Transient = token('Transient')\nconst container = createContainer()\n\ncontainer.factory(Singleton, [], () => ({ id: crypto.randomUUID() }))\ncontainer.factory(Transient, [], () => ({ id: crypto.randomUUID() }), { lifetime: 'transient' })\n\nconsole.log((await container.resolve(Singleton)) === (await container.resolve(Singleton)))\nconsole.log((await container.resolve(Transient)) === (await container.resolve(Transient)))\nawait container.dispose()",
23
- "name": "Singleton and transient lifetimes"
24
- },
25
- {
26
- "id": "scoped-execution",
27
- "code": "import { createContainer, scope, token } from '@vielzeug/conduit'\n\nconst Request = scope('request')\nconst Session = token('Session')\nconst root = createContainer()\n\nroot.factory(Session, [], () => ({ id: crypto.randomUUID() }), { lifetime: Request })\n\nconst request = root.createScope(Request)\nconsole.log(await request.resolve(Session))\nawait request.dispose()\nawait root.dispose()",
28
- "name": "Named scope ownership"
29
- },
30
- {
31
- "id": "testing",
32
- "code": "import { createContainer, token } from '@vielzeug/conduit'\n\nconst Clock = token<{ now(): number }>('Clock')\nconst Service = token<{ timestamp: number }>('Service')\nconst container = createContainer()\n\ncontainer.value(Clock, { now: () => 123 })\ncontainer.factory(Service, [Clock], clock => ({ timestamp: clock.now() }))\n\nconsole.log(await container.resolve(Service))\nawait container.dispose()",
33
- "name": "Replace dependencies in tests"
34
- },
35
- {
36
- "id": "validate",
37
- "code": "import { createContainer, token } from '@vielzeug/conduit'\n\nconst Api = token('Api')\nconst Service = token('Service')\nconst container = createContainer()\n\ncontainer.factory(Service, [Api], api => ({ api }))\n\ntry {\n container.validate()\n} catch (error) {\n console.log(error.message)\n}\n\nawait container.dispose()",
38
- "name": "Validate static dependencies"
39
- }
40
- ],
41
- "typeSignatures": {
42
- "createContainer": "export { createContainer } from './container';",
43
- "ConduitCircularDependencyError": "export {\n ConduitCircularDependencyError,\n ConduitDisposedError,\n ConduitDisposeError,\n ConduitDuplicateRegistrationError,\n ConduitError,\n ConduitProviderNotFoundError,\n ConduitScopedResolutionError,\n} from './errors';",
44
- "ConduitDisposedError": "export {\n ConduitCircularDependencyError,\n ConduitDisposedError,\n ConduitDisposeError,\n ConduitDuplicateRegistrationError,\n ConduitError,\n ConduitProviderNotFoundError,\n ConduitScopedResolutionError,\n} from './errors';",
45
- "ConduitDisposeError": "export {\n ConduitCircularDependencyError,\n ConduitDisposedError,\n ConduitDisposeError,\n ConduitDuplicateRegistrationError,\n ConduitError,\n ConduitProviderNotFoundError,\n ConduitScopedResolutionError,\n} from './errors';",
46
- "ConduitDuplicateRegistrationError": "export {\n ConduitCircularDependencyError,\n ConduitDisposedError,\n ConduitDisposeError,\n ConduitDuplicateRegistrationError,\n ConduitError,\n ConduitProviderNotFoundError,\n ConduitScopedResolutionError,\n} from './errors';",
47
- "ConduitError": "export {\n ConduitCircularDependencyError,\n ConduitDisposedError,\n ConduitDisposeError,\n ConduitDuplicateRegistrationError,\n ConduitError,\n ConduitProviderNotFoundError,\n ConduitScopedResolutionError,\n} from './errors';",
48
- "ConduitProviderNotFoundError": "export {\n ConduitCircularDependencyError,\n ConduitDisposedError,\n ConduitDisposeError,\n ConduitDuplicateRegistrationError,\n ConduitError,\n ConduitProviderNotFoundError,\n ConduitScopedResolutionError,\n} from './errors';",
49
- "ConduitScopedResolutionError": "export {\n ConduitCircularDependencyError,\n ConduitDisposedError,\n ConduitDisposeError,\n ConduitDuplicateRegistrationError,\n ConduitError,\n ConduitProviderNotFoundError,\n ConduitScopedResolutionError,\n} from './errors';",
50
- "Container": "export type { Container, FactoryOptions, InferTokens, Lifetime, ScopeToken, Token, ValueOptions } from './types';",
51
- "FactoryOptions": "export type { Container, FactoryOptions, InferTokens, Lifetime, ScopeToken, Token, ValueOptions } from './types';",
52
- "InferTokens": "export type { Container, FactoryOptions, InferTokens, Lifetime, ScopeToken, Token, ValueOptions } from './types';",
53
- "Lifetime": "export type { Container, FactoryOptions, InferTokens, Lifetime, ScopeToken, Token, ValueOptions } from './types';",
54
- "ScopeToken": "export type { Container, FactoryOptions, InferTokens, Lifetime, ScopeToken, Token, ValueOptions } from './types';",
55
- "Token": "export type { Container, FactoryOptions, InferTokens, Lifetime, ScopeToken, Token, ValueOptions } from './types';",
56
- "ValueOptions": "export type { Container, FactoryOptions, InferTokens, Lifetime, ScopeToken, Token, ValueOptions } from './types';",
57
- "scope": "export { scope, token } from './types';",
58
- "token": "export { scope, token } from './types';"
59
- }
60
- }