@rytejs/core 0.8.0 → 0.9.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.
- package/dist/executor/index.cjs +5 -1
- package/dist/executor/index.cjs.map +1 -1
- package/dist/executor/index.d.cts +1 -1
- package/dist/executor/index.d.ts +1 -1
- package/dist/executor/index.js +5 -1
- package/dist/executor/index.js.map +1 -1
- package/dist/index.cjs +28 -13
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +28 -13
- package/dist/index.js.map +1 -1
- package/dist/{plugin-CIVHyBaZ.d.ts → plugin-ByX9Eoe-.d.ts} +22 -14
- package/dist/{plugin-CQUbAdxj.d.cts → plugin-CGikcWDu.d.cts} +22 -14
- package/dist/reactor/index.d.cts +1 -1
- package/dist/reactor/index.d.ts +1 -1
- package/package.json +1 -1
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/server.ts","../src/types.ts","../src/definition.ts","../src/key.ts","../src/migration.ts","../src/plugin.ts","../src/compose.ts","../src/wrap-deps.ts","../src/context.ts","../src/hooks.ts","../src/router.ts"],"sourcesContent":["export type { Context } from \"./context.js\";\nexport type { ClientWorkflowDefinition, WorkflowDefinition } from \"./definition.js\";\nexport { defineWorkflow } from \"./definition.js\";\nexport type { Handler } from \"./handler.js\";\nexport type { HookEvent } from \"./hooks.js\";\nexport type { ContextKey } from \"./key.js\";\nexport { createKey } from \"./key.js\";\nexport type { Middleware } from \"./middleware.js\";\nexport type {\n\tMigrateOptions,\n\tMigrateResult,\n\tMigrationEntry,\n\tMigrationFn,\n\tMigrationPipeline,\n} from \"./migration.js\";\nexport { defineMigrations, MigrationError, migrate } from \"./migration.js\";\nexport type { GenericPlugin, Plugin } from \"./plugin.js\";\nexport { defineGenericPlugin, definePlugin, isPlugin } from \"./plugin.js\";\nexport type { ReadonlyContext } from \"./readonly-context.js\";\nexport type { RouterOptions } from \"./router.js\";\nexport { WorkflowRouter } from \"./router.js\";\nexport type { Server } from \"./server.js\";\nexport { isServerField, server } from \"./server.js\";\nexport type { WorkflowSnapshot } from \"./snapshot.js\";\nexport type {\n\tClientStateData,\n\tClientWorkflow,\n\tClientWorkflowOf,\n\tCommand,\n\tCommandNames,\n\tCommandPayload,\n\tConfigOf,\n\tDispatchResult,\n\tErrorCodes,\n\tErrorData,\n\tEventData,\n\tEventNames,\n\tPipelineError,\n\tStateData,\n\tStateNames,\n\tWorkflow,\n\tWorkflowConfig,\n\tWorkflowOf,\n} from \"./types.js\";\nexport { DomainErrorSignal, ValidationError } from \"./types.js\";\n","import type { ZodType } from \"zod\";\nimport { z } from \"zod\";\n\nconst SERVER_BRAND: unique symbol = Symbol(\"ryte.server\");\n\n/** Brands a Zod schema type as server-only at the TypeScript level. */\nexport type Server<T extends ZodType> = T & { readonly [SERVER_BRAND]: true };\n\n/**\n * Marks a Zod schema as server-only. Fields wrapped in `server()` are stripped\n * from client snapshots and excluded from client TypeScript types.\n *\n * Returns a new schema reference — the original is not mutated, so shared\n * schemas can safely be used in both server and non-server positions.\n */\nexport function server<T extends ZodType>(schema: T): Server<T> {\n\t// biome-ignore lint/suspicious/noExplicitAny: creating a branded proxy that inherits all Zod behavior via prototype\n\tconst branded = Object.create(schema) as any;\n\tbranded[SERVER_BRAND] = true;\n\treturn branded as Server<T>;\n}\n\n/** Returns `true` if the schema was wrapped with `server()`. */\nexport function isServerField(schema: ZodType): boolean {\n\t// biome-ignore lint/suspicious/noExplicitAny: reading runtime brand from Zod schema\n\treturn (schema as any)[SERVER_BRAND] === true;\n}\n\ntype ServerBranded = { readonly [SERVER_BRAND]: true };\n\n/** Computes the client-safe inferred type from a Zod schema by filtering out server-branded fields. */\nexport type ClientInfer<T extends ZodType> = T extends {\n\tshape: infer Shape extends Record<string, ZodType>;\n}\n\t? {\n\t\t\t[K in keyof Shape as Shape[K] extends ServerBranded ? never : K]: Shape[K] extends {\n\t\t\t\tshape: Record<string, ZodType>;\n\t\t\t}\n\t\t\t\t? ClientInfer<Shape[K]>\n\t\t\t\t: z.infer<Shape[K]>;\n\t\t}\n\t: z.infer<T>;\n\n/**\n * Strips server-only fields from workflow data based on the state's Zod schema.\n * Recursively processes nested z.object() schemas.\n */\nexport function stripServerData(\n\tschema: ZodType,\n\tdata: Record<string, unknown>,\n): Record<string, unknown> {\n\t// biome-ignore lint/suspicious/noExplicitAny: accessing Zod v4 internal _zod.def.shape for schema introspection\n\tconst def = (schema as any)._zod?.def;\n\tif (def?.type !== \"object\" || !def.shape) return data;\n\n\tconst result: Record<string, unknown> = {};\n\tfor (const key of Object.keys(data)) {\n\t\tconst fieldSchema = def.shape[key] as ZodType | undefined;\n\t\tif (fieldSchema && isServerField(fieldSchema)) continue;\n\n\t\tif (\n\t\t\tfieldSchema &&\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: checking Zod v4 internal def.type for nested object detection\n\t\t\t(fieldSchema as any)._zod?.def?.type === \"object\" &&\n\t\t\tdata[key] !== null &&\n\t\t\ttypeof data[key] === \"object\"\n\t\t) {\n\t\t\tresult[key] = stripServerData(fieldSchema, data[key] as Record<string, unknown>);\n\t\t} else {\n\t\t\tresult[key] = data[key];\n\t\t}\n\t}\n\treturn result;\n}\n\n/**\n * Derives a client-safe Zod schema by removing server-only fields.\n * Recursively processes nested z.object() schemas.\n * Returns the original schema unchanged for non-object schemas.\n */\nexport function deriveClientSchema(schema: ZodType): ZodType {\n\t// biome-ignore lint/suspicious/noExplicitAny: accessing Zod v4 internal _zod.def.shape for schema introspection\n\tconst def = (schema as any)._zod?.def;\n\tif (def?.type !== \"object\" || !def.shape) return schema;\n\n\tconst clientShape: Record<string, ZodType> = {};\n\tfor (const [key, fieldSchema] of Object.entries(def.shape as Record<string, ZodType>)) {\n\t\tif (isServerField(fieldSchema)) continue;\n\n\t\t// biome-ignore lint/suspicious/noExplicitAny: checking Zod v4 internal def.type for nested object detection\n\t\tif ((fieldSchema as any)._zod?.def?.type === \"object\") {\n\t\t\tclientShape[key] = deriveClientSchema(fieldSchema);\n\t\t} else {\n\t\t\tclientShape[key] = fieldSchema;\n\t\t}\n\t}\n\treturn z.object(clientShape).strict();\n}\n","import type { ZodType, z } from \"zod\";\n\n/**\n * Shape of the configuration object passed to {@link defineWorkflow}.\n * Exported for internal package use only — not re-exported from index.ts.\n */\nexport interface WorkflowConfigInput {\n\t/** Optional version number for schema migrations. Defaults to 1. */\n\tmodelVersion?: number;\n\t/** Record of state names to Zod schemas defining their data shape. */\n\tstates: Record<string, ZodType>;\n\t/** Record of command names to Zod schemas defining their payload shape. */\n\tcommands: Record<string, ZodType>;\n\t/** Record of event names to Zod schemas defining their data shape. */\n\tevents: Record<string, ZodType>;\n\t/** Record of error codes to Zod schemas defining their data shape. */\n\terrors: Record<string, ZodType>;\n}\n\n/**\n * Workflow configuration with pre-resolved types for IDE completion.\n *\n * Extends {@link WorkflowConfigInput} with a `_resolved` phantom type that\n * caches `z.infer` results. This exists because Zod v4's `z.infer` uses\n * conditional types that TypeScript defers in deep generic chains, breaking\n * IDE autocomplete. The `_resolved` property is never set at runtime — it is\n * populated at the type level by {@link defineWorkflow}'s return type.\n */\nexport interface WorkflowConfig extends WorkflowConfigInput {\n\t_resolved: {\n\t\tstates: Record<string, unknown>;\n\t\tcommands: Record<string, unknown>;\n\t\tevents: Record<string, unknown>;\n\t\terrors: Record<string, unknown>;\n\t};\n\t_clientResolved: {\n\t\tstates: Record<string, unknown>;\n\t};\n}\n\nexport type StateNames<T extends WorkflowConfig> = keyof T[\"states\"] & string;\nexport type CommandNames<T extends WorkflowConfig> = keyof T[\"commands\"] & string;\nexport type EventNames<T extends WorkflowConfig> = keyof T[\"events\"] & string;\nexport type ErrorCodes<T extends WorkflowConfig> = keyof T[\"errors\"] & string;\n\n/** Forces TypeScript to flatten a type for better IDE autocomplete. */\ntype Prettify<T> = { [K in keyof T]: T[K] } & {};\n\n/** Discriminated union of all commands with typed payloads — narrows payload when checking type. */\nexport type Command<T extends WorkflowConfig> = {\n\t[C in CommandNames<T>]: { type: C; payload: CommandPayload<T, C> };\n}[CommandNames<T>];\n\n/** Resolves the data type for a given state from pre-computed types. */\nexport type StateData<T extends WorkflowConfig, S extends StateNames<T>> = Prettify<\n\tT[\"_resolved\"][\"states\"][S]\n>;\n\n/** Resolves the client-safe data type for a given state (server fields stripped). */\nexport type ClientStateData<T extends WorkflowConfig, S extends StateNames<T>> = Prettify<\n\tT[\"_clientResolved\"][\"states\"][S]\n>;\n\n/** Client-side workflow narrowed to a specific known state. */\nexport interface ClientWorkflowOf<TConfig extends WorkflowConfig, S extends StateNames<TConfig>> {\n\treadonly id: string;\n\treadonly definitionName: string;\n\treadonly state: S;\n\treadonly data: ClientStateData<TConfig, S>;\n\treadonly createdAt: Date;\n\treadonly updatedAt: Date;\n}\n\n/** Discriminated union of all possible client-side workflow states. */\nexport type ClientWorkflow<TConfig extends WorkflowConfig = WorkflowConfig> = {\n\t[S in StateNames<TConfig>]: ClientWorkflowOf<TConfig, S>;\n}[StateNames<TConfig>];\n\n/** Resolves the payload type for a given command from pre-computed types. */\nexport type CommandPayload<T extends WorkflowConfig, C extends CommandNames<T>> = Prettify<\n\tT[\"_resolved\"][\"commands\"][C]\n>;\n\n/** Resolves the data type for a given event from pre-computed types. */\nexport type EventData<T extends WorkflowConfig, E extends EventNames<T>> = Prettify<\n\tT[\"_resolved\"][\"events\"][E]\n>;\n\n/** Resolves the data type for a given error code from pre-computed types. */\nexport type ErrorData<T extends WorkflowConfig, C extends ErrorCodes<T>> = Prettify<\n\tT[\"_resolved\"][\"errors\"][C]\n>;\n\n/** Workflow narrowed to a specific known state. */\nexport interface WorkflowOf<TConfig extends WorkflowConfig, S extends StateNames<TConfig>> {\n\t/** Unique workflow instance identifier. */\n\treadonly id: string;\n\t/** Name of the workflow definition this instance belongs to. */\n\treadonly definitionName: string;\n\t/** Current state name. */\n\treadonly state: S;\n\t/** State data, typed according to the state's Zod schema. */\n\treadonly data: StateData<TConfig, S>;\n\t/** Timestamp of workflow creation. */\n\treadonly createdAt: Date;\n\t/** Timestamp of last state change. */\n\treadonly updatedAt: Date;\n}\n\n/** Discriminated union of all possible workflow states — checking .state narrows .data. */\nexport type Workflow<TConfig extends WorkflowConfig = WorkflowConfig> = {\n\t[S in StateNames<TConfig>]: WorkflowOf<TConfig, S>;\n}[StateNames<TConfig>];\n\n/** Discriminated union of all pipeline error types on `category`. */\nexport type PipelineError<TConfig extends WorkflowConfig = WorkflowConfig> =\n\t| {\n\t\t\tcategory: \"validation\";\n\t\t\tsource: \"command\" | \"state\" | \"event\" | \"transition\" | \"restore\";\n\t\t\tissues: z.core.$ZodIssue[];\n\t\t\tmessage: string;\n\t }\n\t| {\n\t\t\tcategory: \"domain\";\n\t\t\tcode: ErrorCodes<TConfig>;\n\t\t\tdata: ErrorData<TConfig, ErrorCodes<TConfig>>;\n\t }\n\t| {\n\t\t\tcategory: \"router\";\n\t\t\tcode: \"NO_HANDLER\" | \"UNKNOWN_STATE\";\n\t\t\tmessage: string;\n\t }\n\t| {\n\t\t\tcategory: \"unexpected\";\n\t\t\terror: unknown;\n\t\t\tmessage: string;\n\t }\n\t| {\n\t\t\tcategory: \"dependency\";\n\t\t\tname: string;\n\t\t\terror: unknown;\n\t\t\tmessage: string;\n\t };\n\n/** Return type of {@link WorkflowRouter.dispatch}. Discriminated union on `ok`. */\nexport type DispatchResult<TConfig extends WorkflowConfig = WorkflowConfig> =\n\t| {\n\t\t\tok: true;\n\t\t\tworkflow: Workflow<TConfig>;\n\t\t\tevents: Array<{ type: EventNames<TConfig>; data: unknown }>;\n\t }\n\t| {\n\t\t\tok: false;\n\t\t\terror: PipelineError<TConfig>;\n\t };\n\n/**\n * Thrown internally when Zod validation fails during dispatch.\n * Caught by the router and returned as a validation error in {@link DispatchResult}.\n *\n * @param source - Which validation stage failed\n * @param issues - Array of Zod validation issues\n */\nexport class ValidationError extends Error {\n\tconstructor(\n\t\tpublic readonly source: \"command\" | \"state\" | \"event\" | \"transition\" | \"restore\",\n\t\tpublic readonly issues: z.core.$ZodIssue[],\n\t) {\n\t\tsuper(`Validation failed (${source}): ${issues.map((i) => i.message).join(\", \")}`);\n\t\tthis.name = \"ValidationError\";\n\t}\n}\n\n/**\n * Thrown internally when a handler calls `ctx.error()`.\n * Caught by the router and returned as a domain error in {@link DispatchResult}.\n *\n * @param code - The error code string\n * @param data - The error data payload\n */\nexport class DomainErrorSignal extends Error {\n\tconstructor(\n\t\tpublic readonly code: string,\n\t\tpublic readonly data: unknown,\n\t) {\n\t\tsuper(`Domain error: ${code}`);\n\t\tthis.name = \"DomainErrorSignal\";\n\t}\n}\n\n/**\n * Thrown internally when a proxied dependency call fails.\n * Caught by the router and returned as a dependency error in {@link DispatchResult}.\n *\n * @param depName - The top-level dependency key (e.g. \"db\", \"stripe\")\n * @param error - The original error thrown by the dependency\n */\n/** Extracts the WorkflowConfig type from a WorkflowRouter instance. */\nexport type ConfigOf<R> = R extends { definition: { config: infer C } } ? C : never;\n\nexport class DependencyErrorSignal extends Error {\n\tconstructor(\n\t\tpublic readonly depName: string,\n\t\tpublic readonly error: unknown,\n\t) {\n\t\tconst original = error instanceof Error ? error.message : String(error);\n\t\tsuper(`Dependency \"${depName}\" failed: ${original}`);\n\t\tthis.name = \"DependencyErrorSignal\";\n\t}\n}\n","import type { ZodType, z } from \"zod\";\nimport type { ClientInfer } from \"./server.js\";\nimport { deriveClientSchema, stripServerData } from \"./server.js\";\nimport type { WorkflowSnapshot } from \"./snapshot.js\";\nimport type {\n\tClientWorkflow,\n\tStateData,\n\tStateNames,\n\tWorkflow,\n\tWorkflowConfig,\n\tWorkflowConfigInput,\n\tWorkflowOf,\n} from \"./types.js\";\nimport { ValidationError } from \"./types.js\";\n\n/**\n * The result of {@link defineWorkflow} — holds schemas and creates workflow instances.\n */\nexport interface WorkflowDefinition<TConfig extends WorkflowConfig = WorkflowConfig> {\n\t/** The raw Zod schema configuration. */\n\treadonly config: TConfig;\n\t/** The workflow definition name. */\n\treadonly name: string;\n\t/**\n\t * Creates a new workflow instance in a given initial state.\n\t *\n\t * @param id - Unique identifier for this workflow instance\n\t * @param config - Object containing `initialState` and the corresponding `data`\n\t * @returns A {@link WorkflowOf} narrowed to the initial state\n\t */\n\tcreateWorkflow<S extends StateNames<TConfig>>(\n\t\tid: string,\n\t\tconfig: { initialState: S; data: StateData<TConfig, S> },\n\t): WorkflowOf<TConfig, S>;\n\t/**\n\t * Returns the Zod schema for a given state name.\n\t *\n\t * @param stateName - The state name to look up\n\t * @throws If the state name is not found in the config\n\t */\n\tgetStateSchema(stateName: string): ZodType;\n\t/**\n\t * Returns the Zod schema for a given command name.\n\t *\n\t * @param commandName - The command name to look up\n\t * @throws If the command name is not found in the config\n\t */\n\tgetCommandSchema(commandName: string): ZodType;\n\t/**\n\t * Returns the Zod schema for a given event name.\n\t *\n\t * @param eventName - The event name to look up\n\t * @throws If the event name is not found in the config\n\t */\n\tgetEventSchema(eventName: string): ZodType;\n\t/**\n\t * Returns the Zod schema for a given error code.\n\t *\n\t * @param errorCode - The error code to look up\n\t * @throws If the error code is not found in the config\n\t */\n\tgetErrorSchema(errorCode: string): ZodType;\n\t/**\n\t * Returns `true` if the given state name exists in the config.\n\t *\n\t * @param stateName - The state name to check\n\t */\n\thasState(stateName: string): boolean;\n\t/**\n\t * Returns `true` if the given command name exists in the config.\n\t */\n\thasCommand(commandName: string): boolean;\n\t/**\n\t * Returns `true` if the given event name exists in the config.\n\t */\n\thasEvent(eventName: string): boolean;\n\t/**\n\t * Serializes a workflow instance into a plain, JSON-safe snapshot.\n\t *\n\t * @param workflow - The workflow instance to serialize\n\t * @returns A {@link WorkflowSnapshot} representing the current state\n\t */\n\tserialize(workflow: Workflow<TConfig>): WorkflowSnapshot<TConfig>;\n\t/**\n\t * Deserializes a workflow instance from a plain snapshot, validating the state data.\n\t *\n\t * @param snapshot - The snapshot to deserialize from\n\t * @returns A result object: `{ ok: true, workflow }` or `{ ok: false, error }`\n\t */\n\tdeserialize(\n\t\tsnapshot: WorkflowSnapshot<TConfig>,\n\t): { ok: true; workflow: Workflow<TConfig> } | { ok: false; error: ValidationError };\n\t/**\n\t * Serializes a workflow into a client-safe snapshot with server-only fields stripped.\n\t *\n\t * @param workflow - The workflow instance to serialize\n\t * @returns A {@link WorkflowSnapshot} with server-only fields removed from `data`\n\t */\n\tserializeForClient(workflow: Workflow<TConfig>): WorkflowSnapshot<TConfig>;\n\t/**\n\t * Returns a client-safe projection of this definition.\n\t * Memoized — returns the same instance on repeated calls.\n\t */\n\tforClient(): ClientWorkflowDefinition<TConfig>;\n}\n\n/**\n * A client-safe projection of a workflow definition.\n * State schemas have server-only fields removed. Returned by {@link WorkflowDefinition.forClient}.\n */\nexport interface ClientWorkflowDefinition<TConfig extends WorkflowConfig = WorkflowConfig> {\n\t/** The raw Zod schema configuration. */\n\treadonly config: TConfig;\n\treadonly name: string;\n\tgetStateSchema(stateName: string): ZodType;\n\thasState(stateName: string): boolean;\n\tdeserialize(\n\t\tsnapshot: WorkflowSnapshot<TConfig>,\n\t): { ok: true; workflow: ClientWorkflow<TConfig> } | { ok: false; error: ValidationError };\n}\n\n/**\n * Creates a workflow definition from a name and Zod schema configuration.\n *\n * @param name - Unique name for this workflow type\n * @param config - Object with `states`, `commands`, `events`, `errors` — each a record of Zod schemas\n * @returns A {@link WorkflowDefinition} with methods for creating instances and accessing schemas\n */\n// Zod v4 uses conditional types for z.infer which TypeScript defers in deep\n// generic chains, breaking IDE completion. We pre-compute all inferred types\n// at this call site (where TConfig is concrete) and attach them as _resolved,\n// so downstream utility types can use direct indexed access instead.\nexport function defineWorkflow<const TConfig extends WorkflowConfigInput>(\n\tname: string,\n\tconfig: TConfig,\n): WorkflowDefinition<\n\tTConfig & {\n\t\t_resolved: {\n\t\t\tstates: { [K in keyof TConfig[\"states\"]]: z.infer<TConfig[\"states\"][K]> };\n\t\t\tcommands: { [K in keyof TConfig[\"commands\"]]: z.infer<TConfig[\"commands\"][K]> };\n\t\t\tevents: { [K in keyof TConfig[\"events\"]]: z.infer<TConfig[\"events\"][K]> };\n\t\t\terrors: { [K in keyof TConfig[\"errors\"]]: z.infer<TConfig[\"errors\"][K]> };\n\t\t};\n\t\t_clientResolved: {\n\t\t\tstates: { [K in keyof TConfig[\"states\"]]: ClientInfer<TConfig[\"states\"][K]> };\n\t\t};\n\t}\n>;\n// biome-ignore lint/suspicious/noExplicitAny: implementation overload — public signature above provides consumer-facing type safety; internally TConfig extends WorkflowConfigInput which lacks _resolved\nexport function defineWorkflow(name: string, config: WorkflowConfigInput): WorkflowDefinition<any> {\n\t// biome-ignore lint/suspicious/noExplicitAny: memoized client definition — typed via public interface ClientWorkflowDefinition\n\tlet cachedClientDef: any = null;\n\n\treturn {\n\t\tconfig,\n\t\tname,\n\n\t\tcreateWorkflow(id: string, wfConfig: { initialState: string; data: unknown }) {\n\t\t\tconst schema = config.states[wfConfig.initialState];\n\t\t\tif (!schema) throw new Error(`Unknown state: ${wfConfig.initialState}`);\n\t\t\tconst result = schema.safeParse(wfConfig.data);\n\t\t\tif (!result.success) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Invalid initial data for state '${wfConfig.initialState}': ${result.error.issues.map((i) => i.message).join(\", \")}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst now = new Date();\n\t\t\treturn {\n\t\t\t\tid,\n\t\t\t\tdefinitionName: name,\n\t\t\t\tstate: wfConfig.initialState,\n\t\t\t\tdata: result.data,\n\t\t\t\tcreatedAt: now,\n\t\t\t\tupdatedAt: now,\n\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: narrowed by the public overload's generic S parameter\n\t\t\t} as any;\n\t\t},\n\n\t\tgetStateSchema(stateName: string): ZodType {\n\t\t\tconst schema = config.states[stateName];\n\t\t\tif (!schema) throw new Error(`Unknown state: ${stateName}`);\n\t\t\treturn schema;\n\t\t},\n\n\t\tgetCommandSchema(commandName: string): ZodType {\n\t\t\tconst schema = config.commands[commandName];\n\t\t\tif (!schema) throw new Error(`Unknown command: ${commandName}`);\n\t\t\treturn schema;\n\t\t},\n\n\t\tgetEventSchema(eventName: string): ZodType {\n\t\t\tconst schema = config.events[eventName];\n\t\t\tif (!schema) throw new Error(`Unknown event: ${eventName}`);\n\t\t\treturn schema;\n\t\t},\n\n\t\tgetErrorSchema(errorCode: string): ZodType {\n\t\t\tconst schema = config.errors[errorCode];\n\t\t\tif (!schema) throw new Error(`Unknown error: ${errorCode}`);\n\t\t\treturn schema;\n\t\t},\n\n\t\thasState(stateName: string): boolean {\n\t\t\treturn stateName in config.states;\n\t\t},\n\n\t\thasCommand(commandName: string): boolean {\n\t\t\treturn commandName in config.commands;\n\t\t},\n\n\t\thasEvent(eventName: string): boolean {\n\t\t\treturn eventName in config.events;\n\t\t},\n\n\t\tserialize(workflow: {\n\t\t\tid: string;\n\t\t\tstate: string;\n\t\t\tdata: unknown;\n\t\t\tcreatedAt: Date;\n\t\t\tupdatedAt: Date;\n\t\t\tversion?: number;\n\t\t}) {\n\t\t\treturn {\n\t\t\t\tid: workflow.id,\n\t\t\t\tdefinitionName: name,\n\t\t\t\tstate: workflow.state,\n\t\t\t\tdata: workflow.data,\n\t\t\t\tcreatedAt: workflow.createdAt.toISOString(),\n\t\t\t\tupdatedAt: workflow.updatedAt.toISOString(),\n\t\t\t\tmodelVersion: config.modelVersion ?? 1,\n\t\t\t\tversion: workflow.version ?? 1,\n\t\t\t};\n\t\t},\n\n\t\tdeserialize(snap: {\n\t\t\tid: string;\n\t\t\tdefinitionName: string;\n\t\t\tstate: string;\n\t\t\tdata: unknown;\n\t\t\tcreatedAt: string;\n\t\t\tupdatedAt: string;\n\t\t}) {\n\t\t\tconst stateSchema = config.states[snap.state];\n\t\t\tif (!stateSchema) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: new ValidationError(\"restore\", [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcode: \"custom\",\n\t\t\t\t\t\t\tmessage: `Unknown state: ${snap.state}`,\n\t\t\t\t\t\t\tinput: snap.state,\n\t\t\t\t\t\t\tpath: [\"state\"],\n\t\t\t\t\t\t},\n\t\t\t\t\t]),\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst result = stateSchema.safeParse(snap.data);\n\t\t\tif (!result.success) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: new ValidationError(\"restore\", result.error.issues),\n\t\t\t\t};\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tok: true,\n\t\t\t\tworkflow: {\n\t\t\t\t\tid: snap.id,\n\t\t\t\t\tdefinitionName: snap.definitionName,\n\t\t\t\t\tstate: snap.state,\n\t\t\t\t\tdata: result.data,\n\t\t\t\t\tcreatedAt: new Date(snap.createdAt),\n\t\t\t\t\tupdatedAt: new Date(snap.updatedAt),\n\t\t\t\t},\n\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Prettify<any> produces { [x: string]: any } instead of any, making unknown data incompatible\n\t\t\t} as any;\n\t\t},\n\n\t\tserializeForClient(workflow: {\n\t\t\tid: string;\n\t\t\tstate: string;\n\t\t\tdata: unknown;\n\t\t\tcreatedAt: Date;\n\t\t\tupdatedAt: Date;\n\t\t\tversion?: number;\n\t\t}) {\n\t\t\tconst stateSchema = config.states[workflow.state];\n\t\t\tconst strippedData = stateSchema\n\t\t\t\t? stripServerData(stateSchema, workflow.data as Record<string, unknown>)\n\t\t\t\t: workflow.data;\n\n\t\t\treturn {\n\t\t\t\tid: workflow.id,\n\t\t\t\tdefinitionName: name,\n\t\t\t\tstate: workflow.state,\n\t\t\t\tdata: strippedData,\n\t\t\t\tcreatedAt: workflow.createdAt.toISOString(),\n\t\t\t\tupdatedAt: workflow.updatedAt.toISOString(),\n\t\t\t\tmodelVersion: config.modelVersion ?? 1,\n\t\t\t\tversion: workflow.version ?? 1,\n\t\t\t};\n\t\t},\n\n\t\tforClient() {\n\t\t\tif (cachedClientDef) return cachedClientDef;\n\n\t\t\tconst clientSchemas: Record<string, ZodType> = {};\n\t\t\tfor (const [stateName, schema] of Object.entries(config.states)) {\n\t\t\t\tclientSchemas[stateName] = deriveClientSchema(schema);\n\t\t\t}\n\n\t\t\tcachedClientDef = {\n\t\t\t\tconfig,\n\t\t\t\tname,\n\n\t\t\t\tgetStateSchema(stateName: string): ZodType {\n\t\t\t\t\tconst schema = clientSchemas[stateName];\n\t\t\t\t\tif (!schema) throw new Error(`Unknown state: ${stateName}`);\n\t\t\t\t\treturn schema;\n\t\t\t\t},\n\n\t\t\t\thasState(stateName: string): boolean {\n\t\t\t\t\treturn stateName in clientSchemas;\n\t\t\t\t},\n\n\t\t\t\tdeserialize(snap: {\n\t\t\t\t\tid: string;\n\t\t\t\t\tdefinitionName: string;\n\t\t\t\t\tstate: string;\n\t\t\t\t\tdata: unknown;\n\t\t\t\t\tcreatedAt: string;\n\t\t\t\t\tupdatedAt: string;\n\t\t\t\t}) {\n\t\t\t\t\tconst stateSchema = clientSchemas[snap.state];\n\t\t\t\t\tif (!stateSchema) {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tok: false,\n\t\t\t\t\t\t\terror: new ValidationError(\"restore\", [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tcode: \"custom\",\n\t\t\t\t\t\t\t\t\tmessage: `Unknown state: ${snap.state}`,\n\t\t\t\t\t\t\t\t\tinput: snap.state,\n\t\t\t\t\t\t\t\t\tpath: [\"state\"],\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t]),\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\n\t\t\t\t\tconst result = stateSchema.safeParse(snap.data);\n\t\t\t\t\tif (!result.success) {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tok: false,\n\t\t\t\t\t\t\terror: new ValidationError(\"restore\", result.error.issues),\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tok: true,\n\t\t\t\t\t\tworkflow: {\n\t\t\t\t\t\t\tid: snap.id,\n\t\t\t\t\t\t\tdefinitionName: snap.definitionName,\n\t\t\t\t\t\t\tstate: snap.state,\n\t\t\t\t\t\t\tdata: result.data,\n\t\t\t\t\t\t\tcreatedAt: new Date(snap.createdAt),\n\t\t\t\t\t\t\tupdatedAt: new Date(snap.updatedAt),\n\t\t\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Prettify<any> produces { [x: string]: any } instead of any, making unknown data incompatible\n\t\t\t\t\t\t} as any,\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t};\n\n\t\t\treturn cachedClientDef;\n\t\t},\n\t};\n}\n","/** A phantom-typed key for type-safe middleware state storage via {@link Context.set} and {@link Context.get}. */\nexport interface ContextKey<T> {\n\t/** @internal Phantom type brand — not used at runtime. */\n\treadonly _phantom: T;\n\t/** Internal symbol providing uniqueness. */\n\treadonly id: symbol;\n}\n\n/**\n * Creates a unique typed key for storing and retrieving values in context.\n *\n * @param name - Debug label (uniqueness comes from an internal `Symbol`)\n * @returns A {@link ContextKey} for use with `ctx.set()`, `ctx.get()`, and `ctx.getOrNull()`\n */\nexport function createKey<T>(name: string): ContextKey<T> {\n\treturn { id: Symbol(name) } as ContextKey<T>;\n}\n","import type { WorkflowDefinition } from \"./definition.js\";\nimport type { WorkflowSnapshot } from \"./snapshot.js\";\nimport type { WorkflowConfig } from \"./types.js\";\n\n/** A function that transforms a snapshot's data from one version to the next. */\nexport type MigrationFn = (snapshot: WorkflowSnapshot) => WorkflowSnapshot;\n\n/** A migration entry — either a bare {@link MigrationFn} or an object with a description. */\nexport type MigrationEntry = MigrationFn | { description: string; up: MigrationFn };\n\n/** Internal normalized migration step with optional description. */\ninterface NormalizedMigration {\n\tfn: MigrationFn;\n\tdescription?: string;\n}\n\n/** A validated migration pipeline ready to transform snapshots. */\nexport interface MigrationPipeline<TConfig extends WorkflowConfig = WorkflowConfig> {\n\t/** The workflow definition this pipeline belongs to. */\n\treadonly definition: WorkflowDefinition<TConfig>;\n\t/** The target schema version to migrate snapshots to. */\n\treadonly targetVersion: number;\n\t/** Map of version number to normalized migration step. */\n\treadonly migrations: ReadonlyMap<number, NormalizedMigration>;\n}\n\n/** Result of {@link migrate}. */\nexport type MigrateResult =\n\t| { ok: true; snapshot: WorkflowSnapshot }\n\t| { ok: false; error: MigrationError };\n\n/** Options for {@link migrate}. */\nexport interface MigrateOptions {\n\t/**\n\t * Called after each successful migration step.\n\t * @param fromVersion - The version before this step\n\t * @param toVersion - The version after this step\n\t * @param snapshot - The snapshot after this step\n\t * @param description - Optional description from the migration entry\n\t */\n\tonStep?: (\n\t\tfromVersion: number,\n\t\ttoVersion: number,\n\t\tsnapshot: WorkflowSnapshot,\n\t\tdescription?: string,\n\t) => void;\n\t/**\n\t * Called when a migration step fails.\n\t * @param error - The {@link MigrationError} describing the failure\n\t */\n\tonError?: (error: MigrationError) => void;\n}\n\n/** Error thrown when a migration step fails. */\nexport class MigrationError extends Error {\n\t/**\n\t * @param fromVersion - The schema version the migration started from\n\t * @param toVersion - The schema version the migration was attempting to reach\n\t * @param cause - The underlying error that caused the failure\n\t */\n\tconstructor(\n\t\tpublic readonly fromVersion: number,\n\t\tpublic readonly toVersion: number,\n\t\tpublic readonly cause: unknown,\n\t) {\n\t\tsuper(\n\t\t\t`Migration ${fromVersion} → ${toVersion} failed: ${cause instanceof Error ? cause.message : String(cause)}`,\n\t\t);\n\t\tthis.name = \"MigrationError\";\n\t}\n}\n\n/**\n * Creates a validated migration pipeline from a definition and version-keyed transform functions.\n * Each key is the target version — the function transforms from (key - 1) to key.\n *\n * @param definition - The workflow definition the migrations belong to\n * @param migrationMap - A record mapping target version numbers to {@link MigrationEntry} values\n * @returns A validated {@link MigrationPipeline} ready for use with {@link migrate}\n * @throws If migration keys are not sequential from 2 to the definition's `modelVersion`, or if the highest key does not match `modelVersion`\n */\nexport function defineMigrations<TConfig extends WorkflowConfig>(\n\tdefinition: WorkflowDefinition<TConfig>,\n\tmigrationMap: Record<number, MigrationEntry>,\n): MigrationPipeline<TConfig> {\n\tconst targetVersion = definition.config.modelVersion ?? 1;\n\tconst entries = Object.entries(migrationMap).map(([k, v]) => {\n\t\tconst normalized: NormalizedMigration =\n\t\t\ttypeof v === \"function\" ? { fn: v } : { fn: v.up, description: v.description };\n\t\treturn [Number(k), normalized] as const;\n\t});\n\n\tfor (const [version] of entries) {\n\t\tif (version <= 1) {\n\t\t\tthrow new Error(`Migration keys must be > 1 (version 1 is the baseline). Got: ${version}`);\n\t\t}\n\t}\n\n\tentries.sort((a, b) => a[0] - b[0]);\n\n\tif (entries.length > 0) {\n\t\tconst highest = entries[entries.length - 1];\n\t\tif (!highest || highest[0] !== targetVersion) {\n\t\t\tthrow new Error(\n\t\t\t\t`Highest migration key (${highest?.[0]}) does not match definition modelVersion (${targetVersion})`,\n\t\t\t);\n\t\t}\n\t\tfor (let i = 0; i < entries.length; i++) {\n\t\t\tconst entry = entries[i];\n\t\t\tconst expected = targetVersion - entries.length + 1 + i;\n\t\t\tif (!entry || entry[0] !== expected) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Migration version gap: expected ${expected} but found ${entry?.[0]}. Migrations must be sequential from 2 to ${targetVersion}.`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn {\n\t\tdefinition,\n\t\ttargetVersion,\n\t\tmigrations: new Map(entries),\n\t};\n}\n\n/**\n * Runs the migration chain from the snapshot's modelVersion to the pipeline's targetVersion.\n * Returns a Result. Auto-stamps modelVersion after each step.\n *\n * @param pipeline - The {@link MigrationPipeline} created by {@link defineMigrations}\n * @param snapshot - The workflow snapshot to migrate\n * @param options - Optional callbacks for step progress and error reporting\n * @returns A {@link MigrateResult} with the migrated snapshot on success, or a {@link MigrationError} on failure\n */\nexport function migrate<TConfig extends WorkflowConfig>(\n\tpipeline: MigrationPipeline<TConfig>,\n\tsnapshot: WorkflowSnapshot,\n\toptions?: MigrateOptions,\n): MigrateResult {\n\tif (!Number.isInteger(snapshot.modelVersion) || snapshot.modelVersion < 1) {\n\t\tconst error = new MigrationError(\n\t\t\tsnapshot.modelVersion,\n\t\t\tpipeline.targetVersion,\n\t\t\tnew Error(\n\t\t\t\t`Invalid snapshot modelVersion: ${snapshot.modelVersion}. Must be a positive integer.`,\n\t\t\t),\n\t\t);\n\t\toptions?.onError?.(error);\n\t\treturn { ok: false, error };\n\t}\n\n\tif (snapshot.definitionName !== pipeline.definition.name) {\n\t\tconst error = new MigrationError(\n\t\t\tsnapshot.modelVersion,\n\t\t\tpipeline.targetVersion,\n\t\t\tnew Error(\n\t\t\t\t`Snapshot definition '${snapshot.definitionName}' does not match pipeline definition '${pipeline.definition.name}'`,\n\t\t\t),\n\t\t);\n\t\toptions?.onError?.(error);\n\t\treturn { ok: false, error };\n\t}\n\n\tif (snapshot.modelVersion > pipeline.targetVersion) {\n\t\tconst error = new MigrationError(\n\t\t\tsnapshot.modelVersion,\n\t\t\tpipeline.targetVersion,\n\t\t\tnew Error(\n\t\t\t\t`Snapshot modelVersion (${snapshot.modelVersion}) is higher than target (${pipeline.targetVersion}). Cannot downgrade.`,\n\t\t\t),\n\t\t);\n\t\toptions?.onError?.(error);\n\t\treturn { ok: false, error };\n\t}\n\n\tif (snapshot.modelVersion === pipeline.targetVersion) {\n\t\treturn { ok: true, snapshot };\n\t}\n\n\tlet current = { ...snapshot };\n\tfor (let version = current.modelVersion + 1; version <= pipeline.targetVersion; version++) {\n\t\tconst migration = pipeline.migrations.get(version);\n\t\tif (!migration) {\n\t\t\tconst error = new MigrationError(\n\t\t\t\tversion - 1,\n\t\t\t\tversion,\n\t\t\t\tnew Error(`No migration function found for version ${version}`),\n\t\t\t);\n\t\t\toptions?.onError?.(error);\n\t\t\treturn { ok: false, error };\n\t\t}\n\n\t\tconst fromVersion = version - 1;\n\t\ttry {\n\t\t\tcurrent = { ...migration.fn(current), modelVersion: version };\n\t\t} catch (cause) {\n\t\t\tconst error = new MigrationError(fromVersion, version, cause);\n\t\t\toptions?.onError?.(error);\n\t\t\treturn { ok: false, error };\n\t\t}\n\n\t\toptions?.onStep?.(fromVersion, version, current, migration.description);\n\t}\n\n\treturn { ok: true, snapshot: current };\n}\n","import type { WorkflowRouter } from \"./router.js\";\nimport type { WorkflowConfig } from \"./types.js\";\n\nconst PLUGIN_SYMBOL: unique symbol = Symbol.for(\"ryte:plugin\");\n\n/** A branded plugin function that can be passed to {@link WorkflowRouter.use}. */\nexport type Plugin<TConfig extends WorkflowConfig, TDeps> = ((\n\trouter: WorkflowRouter<TConfig, TDeps>,\n) => void) & { readonly [PLUGIN_SYMBOL]: true };\n\n/**\n * Brands a function as a Ryte plugin for use with {@link WorkflowRouter.use}.\n *\n * @param fn - A function that configures a router (adds handlers, middleware, hooks)\n * @returns A branded {@link Plugin} function\n */\nexport function definePlugin<TConfig extends WorkflowConfig, TDeps>(\n\tfn: (router: WorkflowRouter<TConfig, TDeps>) => void,\n): Plugin<TConfig, TDeps> {\n\tconst plugin = fn as Plugin<TConfig, TDeps>;\n\tObject.defineProperty(plugin, PLUGIN_SYMBOL, { value: true, writable: false });\n\treturn plugin;\n}\n\n/**\n * Checks whether a value is a branded Ryte plugin.\n *\n * @param value - The value to check\n * @returns `true` if the value is a {@link Plugin}\n */\n/** A plugin that works with any router, regardless of config or deps. */\n// biome-ignore lint/suspicious/noExplicitAny: intentional — GenericPlugin opts out of config-specific types\nexport type GenericPlugin = Plugin<any, any>;\n\n/**\n * Creates a plugin that works with any router without requiring explicit type parameters.\n * Use this for cross-cutting concerns (logging, tracing, delay) that don't reference\n * specific states, commands, or events.\n *\n * @param fn - A function that configures a router (adds hooks, middleware)\n * @returns A branded {@link GenericPlugin} function\n */\nexport function defineGenericPlugin(\n\t// biome-ignore lint/suspicious/noExplicitAny: intentional — generic plugins receive untyped router\n\tfn: (router: WorkflowRouter<any, any>) => void,\n): GenericPlugin {\n\treturn definePlugin(fn);\n}\n\n/**\n * Checks whether a value is a branded Ryte plugin.\n *\n * @param value - The value to check\n * @returns `true` if the value is a {@link Plugin}\n */\nexport function isPlugin(value: unknown): value is Plugin<WorkflowConfig, unknown> {\n\treturn typeof value === \"function\" && PLUGIN_SYMBOL in value;\n}\n","type Middleware<TCtx> = (ctx: TCtx, next: () => Promise<void>) => Promise<void>;\n\n/** Composes an array of middleware into a single function (Koa-style onion model). */\nexport function compose<TCtx>(middleware: Middleware<TCtx>[]): (ctx: TCtx) => Promise<void> {\n\treturn async (ctx: TCtx) => {\n\t\tlet index = -1;\n\t\tasync function dispatch(i: number): Promise<void> {\n\t\t\tif (i <= index) throw new Error(\"next() called multiple times\");\n\t\t\tindex = i;\n\t\t\tconst fn = middleware[i];\n\t\t\tif (!fn) return;\n\t\t\tawait fn(ctx, () => dispatch(i + 1));\n\t\t}\n\t\tawait dispatch(0);\n\t};\n}\n","import { DependencyErrorSignal } from \"./types.js\";\n\nfunction createDepProxy<T extends object>(obj: T, depName: string): T {\n\treturn new Proxy(obj, {\n\t\tget(target, prop, receiver) {\n\t\t\tif (typeof prop === \"symbol\") {\n\t\t\t\treturn Reflect.get(target, prop, receiver);\n\t\t\t}\n\n\t\t\tconst value = Reflect.get(target, prop, receiver);\n\n\t\t\tif (value === null || value === undefined) {\n\t\t\t\treturn value;\n\t\t\t}\n\n\t\t\tif (typeof value === \"function\") {\n\t\t\t\treturn (...args: unknown[]) => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst result = value.apply(target, args);\n\t\t\t\t\t\tif (result != null && typeof result === \"object\" && typeof result.then === \"function\") {\n\t\t\t\t\t\t\treturn result.catch((err: unknown) => {\n\t\t\t\t\t\t\t\tthrow new DependencyErrorSignal(depName, err);\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn result;\n\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\tthrow new DependencyErrorSignal(depName, err);\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (typeof value === \"object\") {\n\t\t\t\treturn createDepProxy(value as object, depName);\n\t\t\t}\n\n\t\t\treturn value;\n\t\t},\n\t});\n}\n\n/** Wraps a deps object in a recursive Proxy that catches dependency errors. */\nexport function wrapDeps<T extends object>(deps: T): T {\n\treturn new Proxy(deps, {\n\t\tget(target, prop, receiver) {\n\t\t\tif (typeof prop === \"symbol\") {\n\t\t\t\treturn Reflect.get(target, prop, receiver);\n\t\t\t}\n\n\t\t\tconst value = Reflect.get(target, prop, receiver);\n\n\t\t\tif (value === null || value === undefined) {\n\t\t\t\treturn value;\n\t\t\t}\n\n\t\t\tconst depName = String(prop);\n\n\t\t\tif (typeof value === \"function\") {\n\t\t\t\treturn (...args: unknown[]) => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst result = value.apply(target, args);\n\t\t\t\t\t\tif (result != null && typeof result === \"object\" && typeof result.then === \"function\") {\n\t\t\t\t\t\t\treturn result.catch((err: unknown) => {\n\t\t\t\t\t\t\t\tthrow new DependencyErrorSignal(depName, err);\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn result;\n\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\tthrow new DependencyErrorSignal(depName, err);\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (typeof value === \"object\") {\n\t\t\t\treturn createDepProxy(value as object, depName);\n\t\t\t}\n\n\t\t\treturn value;\n\t\t},\n\t});\n}\n","import type { WorkflowDefinition } from \"./definition.js\";\nimport type { ContextKey } from \"./key.js\";\nimport type {\n\tCommandNames,\n\tCommandPayload,\n\tErrorCodes,\n\tErrorData,\n\tEventData,\n\tEventNames,\n\tStateData,\n\tStateNames,\n\tWorkflow,\n\tWorkflowConfig,\n\tWorkflowOf,\n} from \"./types.js\";\nimport { DomainErrorSignal, ValidationError } from \"./types.js\";\nimport { wrapDeps as wrapDepsProxy } from \"./wrap-deps.js\";\n\n/** Mutable context flowing through the middleware pipeline during dispatch. */\nexport interface Context<\n\tTConfig extends WorkflowConfig,\n\tTDeps,\n\tTState extends StateNames<TConfig> = StateNames<TConfig>,\n\tTCommand extends CommandNames<TConfig> = CommandNames<TConfig>,\n> {\n\t/** The command being dispatched, with type and validated payload. */\n\treadonly command: {\n\t\treadonly type: TCommand;\n\t\treadonly payload: CommandPayload<TConfig, TCommand>;\n\t};\n\t/** The original workflow before any mutations. */\n\treadonly workflow: WorkflowOf<TConfig, TState>;\n\t/** Dependencies injected via the router constructor. */\n\treadonly deps: TDeps;\n\n\t/** Current state data (reflects mutations from {@link update}). */\n\treadonly data: StateData<TConfig, TState>;\n\t/**\n\t * Merges partial data into the current state. Validates against the state's Zod schema.\n\t * @param data - Partial state data to merge\n\t */\n\tupdate(data: Partial<StateData<TConfig, TState>>): void;\n\n\t/**\n\t * Transitions the workflow to a new state with new data. Validates against the target state's Zod schema.\n\t * @param target - Target state name\n\t * @param data - Data for the target state\n\t */\n\ttransition<Target extends StateNames<TConfig>>(\n\t\ttarget: Target,\n\t\tdata: StateData<TConfig, Target>,\n\t): void;\n\n\t/**\n\t * Emits a domain event. Validates event data against the event's Zod schema.\n\t * @param event - Event with type and data\n\t */\n\temit<E extends EventNames<TConfig>>(event: { type: E; data: EventData<TConfig, E> }): void;\n\t/** Accumulated events emitted during this dispatch. */\n\treadonly events: ReadonlyArray<{ type: EventNames<TConfig>; data: unknown }>;\n\n\t/**\n\t * Signals a domain error. Validates error data and throws internally (caught by the router).\n\t * @param err - Error with code and data\n\t */\n\terror<C extends ErrorCodes<TConfig>>(err: { code: C; data: ErrorData<TConfig, C> }): never;\n\n\t/**\n\t * Stores a value in context-scoped middleware state.\n\t * @param key - A {@link ContextKey} created via {@link createKey}\n\t * @param value - The value to store\n\t */\n\tset<T>(key: ContextKey<T>, value: T): void;\n\t/**\n\t * Retrieves a value from context-scoped middleware state. Throws if not set.\n\t * @param key - A {@link ContextKey} created via {@link createKey}\n\t */\n\tget<T>(key: ContextKey<T>): T;\n\t/**\n\t * Retrieves a value from context-scoped middleware state, or `undefined` if not set.\n\t * @param key - A {@link ContextKey} created via {@link createKey}\n\t */\n\tgetOrNull<T>(key: ContextKey<T>): T | undefined;\n\n\t/** @internal — not part of the handler API */\n\tgetWorkflowSnapshot(): Workflow<TConfig>;\n}\n\ninterface DomainEvent {\n\ttype: string;\n\tdata: unknown;\n}\n\n/** @internal Creates a context for dispatch. Not part of public API. */\nexport function createContext<TConfig extends WorkflowConfig, TDeps>(\n\tdefinition: WorkflowDefinition<TConfig>,\n\toriginalWorkflow: Workflow<TConfig>,\n\tcommand: { type: string; payload: unknown },\n\tdeps: TDeps,\n\toptions?: { wrapDeps?: boolean },\n): Context<TConfig, TDeps> {\n\tlet mutableState = originalWorkflow.state;\n\tlet mutableData: Record<string, unknown> = {\n\t\t...(originalWorkflow.data as Record<string, unknown>),\n\t};\n\n\tconst accumulatedEvents: DomainEvent[] = [];\n\tconst middlewareState = new Map<symbol, unknown>();\n\n\tconst ctx = {\n\t\tcommand,\n\t\tworkflow: originalWorkflow,\n\t\tdeps:\n\t\t\toptions?.wrapDeps !== false && deps != null && typeof deps === \"object\"\n\t\t\t\t? (wrapDepsProxy(deps as object) as TDeps)\n\t\t\t\t: deps,\n\n\t\tget data() {\n\t\t\treturn { ...mutableData } as StateData<TConfig, StateNames<TConfig>>;\n\t\t},\n\n\t\tupdate(data: Record<string, unknown>) {\n\t\t\tconst merged = { ...mutableData, ...data };\n\t\t\tconst schema = definition.getStateSchema(mutableState);\n\t\t\tconst result = schema.safeParse(merged);\n\t\t\tif (!result.success) {\n\t\t\t\tthrow new ValidationError(\"state\", result.error.issues);\n\t\t\t}\n\t\t\tmutableData = result.data as Record<string, unknown>;\n\t\t},\n\n\t\ttransition(target: string, data: unknown) {\n\t\t\tif (!definition.hasState(target)) {\n\t\t\t\tthrow new Error(`Unknown state: ${target}`);\n\t\t\t}\n\t\t\tconst schema = definition.getStateSchema(target);\n\t\t\tconst result = schema.safeParse(data);\n\t\t\tif (!result.success) {\n\t\t\t\tthrow new ValidationError(\"transition\", result.error.issues);\n\t\t\t}\n\t\t\tmutableState = target;\n\t\t\tmutableData = result.data as Record<string, unknown>;\n\t\t},\n\n\t\temit(event: { type: string; data: unknown }) {\n\t\t\tconst schema = definition.getEventSchema(event.type);\n\t\t\tconst result = schema.safeParse(event.data);\n\t\t\tif (!result.success) {\n\t\t\t\tthrow new ValidationError(\"event\", result.error.issues);\n\t\t\t}\n\t\t\taccumulatedEvents.push({ type: event.type, data: result.data });\n\t\t},\n\n\t\tget events() {\n\t\t\treturn [...accumulatedEvents];\n\t\t},\n\n\t\terror(err: { code: string; data: unknown }) {\n\t\t\tconst schema = definition.getErrorSchema(err.code);\n\t\t\tconst result = schema.safeParse(err.data);\n\t\t\tif (!result.success) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Invalid error data for '${err.code}': ${result.error.issues.map((i) => i.message).join(\", \")}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow new DomainErrorSignal(err.code, result.data);\n\t\t},\n\n\t\tset<T>(key: ContextKey<T>, value: T) {\n\t\t\tmiddlewareState.set(key.id, value);\n\t\t},\n\n\t\tget<T>(key: ContextKey<T>): T {\n\t\t\tif (!middlewareState.has(key.id)) {\n\t\t\t\tthrow new Error(`Context key not set: ${key.id.toString()}`);\n\t\t\t}\n\t\t\treturn middlewareState.get(key.id) as T;\n\t\t},\n\n\t\tgetOrNull<T>(key: ContextKey<T>): T | undefined {\n\t\t\treturn middlewareState.get(key.id) as T | undefined;\n\t\t},\n\n\t\tgetWorkflowSnapshot(): Workflow<TConfig> {\n\t\t\treturn {\n\t\t\t\tid: originalWorkflow.id,\n\t\t\t\tdefinitionName: originalWorkflow.definitionName,\n\t\t\t\tstate: mutableState,\n\t\t\t\tdata: { ...mutableData },\n\t\t\t\tcreatedAt: originalWorkflow.createdAt,\n\t\t\t\tupdatedAt: new Date(),\n\t\t\t} as Workflow<TConfig>;\n\t\t},\n\t};\n\n\treturn ctx as unknown as Context<TConfig, TDeps>;\n}\n","/** The lifecycle hook event names. */\nexport type HookEvent =\n\t| \"dispatch:start\"\n\t| \"dispatch:end\"\n\t| \"pipeline:start\"\n\t| \"pipeline:end\"\n\t| \"transition\"\n\t| \"error\"\n\t| \"event\";\n\nexport const HOOK_EVENTS: ReadonlySet<string> = new Set<HookEvent>([\n\t\"dispatch:start\",\n\t\"dispatch:end\",\n\t\"pipeline:start\",\n\t\"pipeline:end\",\n\t\"transition\",\n\t\"error\",\n\t\"event\",\n]);\n\n/**\n * Internal registry for lifecycle hook callbacks.\n * Hooks are observers — errors are caught and forwarded, never affecting dispatch.\n */\nexport class HookRegistry {\n\t// biome-ignore lint/complexity/noBannedTypes: callbacks have varying signatures per hook event\n\tprivate hooks = new Map<string, Function[]>();\n\n\t/** Register a callback for a hook event. */\n\t// biome-ignore lint/complexity/noBannedTypes: callbacks have varying signatures per hook event\n\tadd(event: string, callback: Function): void {\n\t\tconst existing = this.hooks.get(event) ?? [];\n\t\texisting.push(callback);\n\t\tthis.hooks.set(event, existing);\n\t}\n\n\t/** Emit a hook event, calling all registered callbacks. Errors are caught and forwarded. */\n\tasync emit(event: string, onError: (err: unknown) => void, ...args: unknown[]): Promise<void> {\n\t\tconst callbacks = this.hooks.get(event);\n\t\tif (!callbacks) return;\n\t\tfor (const cb of callbacks) {\n\t\t\ttry {\n\t\t\t\tawait cb(...args);\n\t\t\t} catch (err) {\n\t\t\t\tonError(err);\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Merge another registry's hooks into this one (used by composable routers). */\n\tmerge(other: HookRegistry): void {\n\t\tfor (const [event, callbacks] of other.hooks) {\n\t\t\tconst existing = this.hooks.get(event) ?? [];\n\t\t\texisting.push(...callbacks);\n\t\t\tthis.hooks.set(event, existing);\n\t\t}\n\t}\n}\n","import { compose } from \"./compose.js\";\nimport { type Context, createContext } from \"./context.js\";\nimport type { WorkflowDefinition } from \"./definition.js\";\nimport { HOOK_EVENTS, HookRegistry } from \"./hooks.js\";\nimport type { GenericPlugin, Plugin } from \"./plugin.js\";\nimport { isPlugin } from \"./plugin.js\";\nimport type { ReadonlyContext } from \"./readonly-context.js\";\nimport type {\n\tCommand,\n\tCommandNames,\n\tCommandPayload,\n\tDispatchResult,\n\tErrorCodes,\n\tErrorData,\n\tEventNames,\n\tPipelineError,\n\tStateNames,\n\tWorkflow,\n\tWorkflowConfig,\n} from \"./types.js\";\nimport { DependencyErrorSignal, DomainErrorSignal, ValidationError } from \"./types.js\";\n\n// biome-ignore lint/suspicious/noExplicitAny: internal type erasure for heterogeneous middleware storage\ntype AnyMiddleware = (ctx: any, next: () => Promise<void>) => Promise<void>;\n// biome-ignore lint/suspicious/noExplicitAny: internal type erasure for heterogeneous handler storage\ntype AnyHandler = (ctx: any) => void | Promise<void>;\n\ntype HandlerEntry = {\n\tinlineMiddleware: AnyMiddleware[];\n\thandler: AnyMiddleware;\n};\n\n/** Options for the {@link WorkflowRouter} constructor. */\nexport interface RouterOptions {\n\t/** Callback invoked when a lifecycle hook throws. Defaults to `console.error`. */\n\tonHookError?: (error: unknown) => void;\n\t/** Wrap deps in a Proxy to catch dependency errors. Defaults to `true`. */\n\twrapDeps?: boolean;\n}\n\nclass StateBuilder<TConfig extends WorkflowConfig, TDeps, TState extends StateNames<TConfig>> {\n\t/** @internal */ readonly middleware: AnyMiddleware[] = [];\n\t/** @internal */ readonly handlers = new Map<string, HandlerEntry>();\n\n\tconstructor() {\n\t\tthis.on = this.on.bind(this);\n\t\tthis.use = this.use.bind(this);\n\t}\n\n\t// Overload 1: handler only (no middleware) — covers 90% of usage\n\ton<C extends CommandNames<TConfig>>(\n\t\tcommand: C,\n\t\thandler: (ctx: Context<TConfig, TDeps, TState, C>) => void | Promise<void>,\n\t): this;\n\t// Overload 2: middleware + handler (variadic)\n\ton<C extends CommandNames<TConfig>>(\n\t\tcommand: C,\n\t\t...fns: [...AnyMiddleware[], (ctx: Context<TConfig, TDeps, TState, C>) => void | Promise<void>]\n\t): this;\n\t// Implementation\n\ton<C extends CommandNames<TConfig>>(\n\t\tcommand: C,\n\t\t...fns: [...AnyMiddleware[], (ctx: Context<TConfig, TDeps, TState, C>) => void | Promise<void>]\n\t): this {\n\t\tif (fns.length === 0) throw new Error(\"on() requires at least a handler\");\n\t\tconst handler = fns.pop() as AnyHandler;\n\t\tconst inlineMiddleware = fns as AnyMiddleware[];\n\t\tconst wrappedHandler: AnyMiddleware = async (ctx, _next) => {\n\t\t\tawait handler(ctx);\n\t\t};\n\t\tthis.handlers.set(command as string, { inlineMiddleware, handler: wrappedHandler });\n\t\treturn this;\n\t}\n\n\tuse(\n\t\tmiddleware: (ctx: Context<TConfig, TDeps, TState>, next: () => Promise<void>) => Promise<void>,\n\t): this {\n\t\tthis.middleware.push(middleware as AnyMiddleware);\n\t\treturn this;\n\t}\n}\n\n/**\n * Routes commands to handlers based on workflow state.\n *\n * Supports global middleware, state-scoped middleware, inline middleware,\n * wildcard handlers, and multi-state handlers.\n */\n// biome-ignore lint/complexity/noBannedTypes: {} is correct here — TDeps defaults to \"no deps\", inferred away when deps are provided\nexport class WorkflowRouter<TConfig extends WorkflowConfig, TDeps = {}> {\n\tprivate globalMiddleware: AnyMiddleware[] = [];\n\t// biome-ignore lint/suspicious/noExplicitAny: type erasure — builders store handlers for different state types\n\tprivate singleStateBuilders = new Map<string, StateBuilder<TConfig, TDeps, any>>();\n\t// biome-ignore lint/suspicious/noExplicitAny: type erasure — builders store handlers for different state types\n\tprivate multiStateBuilders = new Map<string, StateBuilder<TConfig, TDeps, any>>();\n\tprivate wildcardHandlers = new Map<string, HandlerEntry>();\n\tprivate hookRegistry = new HookRegistry();\n\tprivate readonly onHookError: (error: unknown) => void;\n\tprivate readonly wrapDeps: boolean;\n\n\t/**\n\t * @param definition - The workflow definition describing states, commands, events, and errors\n\t * @param deps - Dependencies injected into every handler context\n\t * @param options - Router configuration options\n\t */\n\tconstructor(\n\t\tpublic readonly definition: WorkflowDefinition<TConfig>,\n\t\tprivate readonly deps: TDeps = {} as TDeps,\n\t\toptions: RouterOptions = {},\n\t) {\n\t\tthis.onHookError = options.onHookError ?? console.error;\n\t\tthis.wrapDeps = options.wrapDeps !== false;\n\t}\n\n\t/**\n\t * Adds global middleware, merges another router, or applies a plugin.\n\t * @param arg - A middleware function, another {@link WorkflowRouter} to merge, or a {@link Plugin}\n\t */\n\tuse(\n\t\targ:\n\t\t\t| ((ctx: Context<TConfig, TDeps>, next: () => Promise<void>) => Promise<void>)\n\t\t\t| WorkflowRouter<TConfig, TDeps>\n\t\t\t| Plugin<TConfig, TDeps>\n\t\t\t| GenericPlugin,\n\t): this {\n\t\tif (arg instanceof WorkflowRouter) {\n\t\t\tthis.merge(arg);\n\t\t} else if (isPlugin(arg)) {\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: plugin may be GenericPlugin (Plugin<any,any>) or Plugin<TConfig,TDeps> — both are called with this router at runtime\n\t\t\t(arg as any)(this);\n\t\t} else {\n\t\t\tthis.globalMiddleware.push(arg as AnyMiddleware);\n\t\t}\n\t\treturn this;\n\t}\n\n\tprivate merge(child: WorkflowRouter<TConfig, TDeps>): void {\n\t\tif (child.definition !== this.definition) {\n\t\t\tthrow new Error(\n\t\t\t\t`Cannot merge router for '${child.definition.name}' into router for '${this.definition.name}': definition mismatch`,\n\t\t\t);\n\t\t}\n\n\t\tthis.globalMiddleware.push(...child.globalMiddleware);\n\t\tthis.mergeStateBuilders(this.singleStateBuilders, child.singleStateBuilders);\n\t\tthis.mergeStateBuilders(this.multiStateBuilders, child.multiStateBuilders);\n\n\t\tfor (const [command, entry] of child.wildcardHandlers) {\n\t\t\tif (!this.wildcardHandlers.has(command)) {\n\t\t\t\tthis.wildcardHandlers.set(command, {\n\t\t\t\t\tinlineMiddleware: [...entry.inlineMiddleware],\n\t\t\t\t\thandler: entry.handler,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\tthis.hookRegistry.merge(child.hookRegistry);\n\t}\n\n\tprivate mergeStateBuilders(\n\t\t// biome-ignore lint/suspicious/noExplicitAny: type erasure — builders store handlers for different state types\n\t\ttarget: Map<string, StateBuilder<TConfig, TDeps, any>>,\n\t\t// biome-ignore lint/suspicious/noExplicitAny: type erasure — builders store handlers for different state types\n\t\tsource: Map<string, StateBuilder<TConfig, TDeps, any>>,\n\t): void {\n\t\tfor (const [stateName, childBuilder] of source) {\n\t\t\tlet parentBuilder = target.get(stateName);\n\t\t\tif (!parentBuilder) {\n\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: type erasure — state name is dynamic at runtime\n\t\t\t\tparentBuilder = new StateBuilder<TConfig, TDeps, any>();\n\t\t\t\ttarget.set(stateName, parentBuilder);\n\t\t\t}\n\t\t\tfor (const [command, entry] of childBuilder.handlers) {\n\t\t\t\tif (!parentBuilder.handlers.has(command)) {\n\t\t\t\t\tparentBuilder.handlers.set(command, {\n\t\t\t\t\t\tinlineMiddleware: [...entry.inlineMiddleware],\n\t\t\t\t\t\thandler: entry.handler,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\tparentBuilder.middleware.push(...childBuilder.middleware);\n\t\t}\n\t}\n\n\t/**\n\t * Registers handlers for one or more states.\n\t * @param name - A state name or array of state names to register handlers for\n\t * @param setup - Callback that receives a state builder to register commands and middleware\n\t */\n\tstate<P extends StateNames<TConfig> | readonly StateNames<TConfig>[]>(\n\t\tname: P,\n\t\tsetup: (\n\t\t\tstate: StateBuilder<\n\t\t\t\tTConfig,\n\t\t\t\tTDeps,\n\t\t\t\tP extends readonly (infer S)[] ? S & StateNames<TConfig> : P & StateNames<TConfig>\n\t\t\t>,\n\t\t) => void,\n\t): this {\n\t\tconst names = Array.isArray(name) ? name : [name];\n\t\tconst isMulti = Array.isArray(name);\n\t\tconst routerMap = isMulti ? this.multiStateBuilders : this.singleStateBuilders;\n\n\t\tfor (const n of names as string[]) {\n\t\t\tlet router = routerMap.get(n);\n\t\t\tif (!router) {\n\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: type erasure — state name is dynamic at runtime\n\t\t\t\trouter = new StateBuilder<TConfig, TDeps, any>();\n\t\t\t\trouterMap.set(n, router);\n\t\t\t}\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: type erasure — setup callback expects a specific state type\n\t\t\tsetup(router as any);\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Registers a lifecycle hook callback.\n\t * @param event - The lifecycle event name\n\t * @param callback - The callback to invoke when the event fires\n\t */\n\ton(\n\t\tevent: \"dispatch:start\",\n\t\tcallback: (workflow: Workflow<TConfig>, command: Command<TConfig>) => void | Promise<void>,\n\t): this;\n\ton(\n\t\tevent: \"dispatch:end\",\n\t\tcallback: (\n\t\t\tworkflow: Workflow<TConfig>,\n\t\t\tcommand: Command<TConfig>,\n\t\t\tresult: DispatchResult<TConfig>,\n\t\t) => void | Promise<void>,\n\t): this;\n\ton(\n\t\tevent: \"pipeline:start\",\n\t\tcallback: (ctx: ReadonlyContext<TConfig, TDeps>) => void | Promise<void>,\n\t): this;\n\ton(\n\t\tevent: \"pipeline:end\",\n\t\tcallback: (\n\t\t\tctx: ReadonlyContext<TConfig, TDeps>,\n\t\t\tresult: DispatchResult<TConfig>,\n\t\t) => void | Promise<void>,\n\t): this;\n\ton(\n\t\tevent: \"transition\",\n\t\tcallback: (\n\t\t\tfrom: StateNames<TConfig>,\n\t\t\tto: StateNames<TConfig>,\n\t\t\tworkflow: Workflow<TConfig>,\n\t\t) => void | Promise<void>,\n\t): this;\n\ton(\n\t\tevent: \"error\",\n\t\tcallback: (\n\t\t\terror: PipelineError<TConfig>,\n\t\t\tctx: ReadonlyContext<TConfig, TDeps>,\n\t\t) => void | Promise<void>,\n\t): this;\n\ton(\n\t\tevent: \"event\",\n\t\tcallback: (\n\t\t\tevent: { type: EventNames<TConfig>; data: unknown },\n\t\t\tworkflow: Workflow<TConfig>,\n\t\t) => void | Promise<void>,\n\t): this;\n\t/**\n\t * Registers a wildcard handler that matches any state.\n\t * @param state - Must be `\"*\"` to match all states\n\t * @param command - The command name to handle\n\t * @param handler - The terminal handler\n\t */\n\ton<C extends CommandNames<TConfig>>(\n\t\tstate: \"*\",\n\t\tcommand: C,\n\t\thandler: (ctx: Context<TConfig, TDeps, StateNames<TConfig>, C>) => void | Promise<void>,\n\t): this;\n\t/**\n\t * Registers a wildcard handler that matches any state, with inline middleware.\n\t * @param state - Must be `\"*\"` to match all states\n\t * @param command - The command name to handle\n\t * @param fns - Inline middleware followed by the terminal handler\n\t */\n\ton<C extends CommandNames<TConfig>>(\n\t\tstate: \"*\",\n\t\tcommand: C,\n\t\t...fns: [\n\t\t\t...AnyMiddleware[],\n\t\t\t(ctx: Context<TConfig, TDeps, StateNames<TConfig>, C>) => void | Promise<void>,\n\t\t]\n\t): this;\n\t// biome-ignore lint/suspicious/noExplicitAny: implementation signature must be loose to handle all overloads\n\ton(...args: any[]): this {\n\t\tconst first = args[0] as string;\n\n\t\tif (HOOK_EVENTS.has(first)) {\n\t\t\t// biome-ignore lint/complexity/noBannedTypes: callbacks have varying signatures per hook event\n\t\t\tthis.hookRegistry.add(first, args[1] as Function);\n\t\t\treturn this;\n\t\t}\n\n\t\tif (first === \"*\") {\n\t\t\tconst command = args[1] as string;\n\t\t\tconst fns = args.slice(2) as unknown[];\n\t\t\tif (fns.length === 0) throw new Error(\"on() requires at least a handler\");\n\t\t\tconst handler = fns.pop() as AnyHandler;\n\t\t\tconst inlineMiddleware = fns as AnyMiddleware[];\n\t\t\tconst wrappedHandler: AnyMiddleware = async (ctx, _next) => {\n\t\t\t\tawait handler(ctx);\n\t\t\t};\n\t\t\tthis.wildcardHandlers.set(command, {\n\t\t\t\tinlineMiddleware,\n\t\t\t\thandler: wrappedHandler,\n\t\t\t});\n\t\t\treturn this;\n\t\t}\n\n\t\tthrow new Error(`Unknown event or state: ${first}`);\n\t}\n\n\t/**\n\t * Dispatches a command to the appropriate handler and returns the result.\n\t * @param workflow - The current workflow instance to dispatch against\n\t * @param command - The command with its type and payload\n\t * @returns A {@link DispatchResult} indicating success or failure with the updated workflow and events\n\t */\n\tasync dispatch<C extends CommandNames<TConfig>>(\n\t\tworkflow: Workflow<TConfig>,\n\t\tcommand: { type: C; payload: CommandPayload<TConfig, C> },\n\t): Promise<DispatchResult<TConfig>> {\n\t\t// Hook: dispatch:start (fires before any validation)\n\t\tawait this.hookRegistry.emit(\"dispatch:start\", this.onHookError, workflow, command);\n\n\t\tlet result: DispatchResult<TConfig>;\n\t\ttry {\n\t\t\tresult = await this.executePipeline(workflow, command);\n\t\t} catch (err) {\n\t\t\tresult = {\n\t\t\t\tok: false as const,\n\t\t\t\terror: {\n\t\t\t\t\tcategory: \"unexpected\" as const,\n\t\t\t\t\terror: err,\n\t\t\t\t\tmessage: err instanceof Error ? err.message : String(err),\n\t\t\t\t},\n\t\t\t};\n\t\t} finally {\n\t\t\t// Hook: dispatch:end (guaranteed to fire if dispatch:start fired)\n\t\t\t// biome-ignore lint/style/noNonNullAssertion: result is always assigned — either by try or catch\n\t\t\tawait this.hookRegistry.emit(\"dispatch:end\", this.onHookError, workflow, command, result!);\n\t\t}\n\t\treturn result;\n\t}\n\n\tprivate async executePipeline(\n\t\tworkflow: Workflow<TConfig>,\n\t\tcommand: { type: CommandNames<TConfig>; payload: unknown },\n\t): Promise<DispatchResult<TConfig>> {\n\t\tif (!this.definition.hasState(workflow.state)) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\terror: {\n\t\t\t\t\tcategory: \"router\",\n\t\t\t\t\tcode: \"UNKNOWN_STATE\",\n\t\t\t\t\tmessage: `Unknown state: ${workflow.state}`,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\tconst commandSchema = this.definition.getCommandSchema(command.type);\n\t\tconst payloadResult = commandSchema.safeParse(command.payload);\n\t\tif (!payloadResult.success) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\terror: {\n\t\t\t\t\tcategory: \"validation\",\n\t\t\t\t\tsource: \"command\",\n\t\t\t\t\tissues: payloadResult.error.issues,\n\t\t\t\t\tmessage: `Invalid command payload: ${payloadResult.error.issues.map((i) => i.message).join(\", \")}`,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\tconst validatedCommand = { type: command.type, payload: payloadResult.data };\n\n\t\tconst stateName = workflow.state;\n\t\tconst singleRouter = this.singleStateBuilders.get(stateName);\n\t\tconst multiRouter = this.multiStateBuilders.get(stateName);\n\t\tconst singleHandler = singleRouter?.handlers.get(command.type);\n\t\tconst multiHandler = multiRouter?.handlers.get(command.type);\n\t\tconst wildcardHandler = this.wildcardHandlers.get(command.type);\n\n\t\tlet routeEntry: HandlerEntry | undefined;\n\t\t// biome-ignore lint/suspicious/noExplicitAny: type erasure — matched router's state type is dynamic\n\t\tlet matchedRouter: StateBuilder<TConfig, TDeps, any> | undefined;\n\n\t\tif (singleHandler) {\n\t\t\trouteEntry = singleHandler;\n\t\t\tmatchedRouter = singleRouter;\n\t\t} else if (multiHandler) {\n\t\t\trouteEntry = multiHandler;\n\t\t\tmatchedRouter = multiRouter;\n\t\t} else if (wildcardHandler) {\n\t\t\trouteEntry = wildcardHandler;\n\t\t\tmatchedRouter = undefined;\n\t\t}\n\n\t\tif (!routeEntry) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\terror: {\n\t\t\t\t\tcategory: \"router\",\n\t\t\t\t\tcode: \"NO_HANDLER\",\n\t\t\t\t\tmessage: `No handler for command '${command.type}' in state '${stateName}'`,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\tconst stateMiddleware: AnyMiddleware[] = [];\n\t\tif (matchedRouter) {\n\t\t\tif (singleRouter) stateMiddleware.push(...singleRouter.middleware);\n\t\t\tif (multiRouter && multiRouter !== singleRouter)\n\t\t\t\tstateMiddleware.push(...multiRouter.middleware);\n\t\t}\n\n\t\tconst chain: AnyMiddleware[] = [\n\t\t\t...this.globalMiddleware,\n\t\t\t...stateMiddleware,\n\t\t\t...routeEntry.inlineMiddleware,\n\t\t\trouteEntry.handler,\n\t\t];\n\n\t\tconst ctx = createContext<TConfig, TDeps>(\n\t\t\tthis.definition,\n\t\t\tworkflow,\n\t\t\tvalidatedCommand,\n\t\t\tthis.deps,\n\t\t\t{ wrapDeps: this.wrapDeps },\n\t\t);\n\n\t\t// Hook: pipeline:start\n\t\tawait this.hookRegistry.emit(\"pipeline:start\", this.onHookError, ctx);\n\n\t\ttry {\n\t\t\tconst composed = compose(chain);\n\t\t\tawait composed(ctx);\n\t\t\tconst result: DispatchResult<TConfig> = {\n\t\t\t\tok: true as const,\n\t\t\t\tworkflow: ctx.getWorkflowSnapshot(),\n\t\t\t\tevents: [...ctx.events],\n\t\t\t};\n\n\t\t\t// Hook: transition (if state changed)\n\t\t\tif (result.ok && result.workflow.state !== workflow.state) {\n\t\t\t\tawait this.hookRegistry.emit(\n\t\t\t\t\t\"transition\",\n\t\t\t\t\tthis.onHookError,\n\t\t\t\t\tworkflow.state,\n\t\t\t\t\tresult.workflow.state,\n\t\t\t\t\tresult.workflow,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Hook: event (for each emitted event)\n\t\t\tif (result.ok) {\n\t\t\t\tfor (const event of result.events) {\n\t\t\t\t\tawait this.hookRegistry.emit(\"event\", this.onHookError, event, result.workflow);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Hook: pipeline:end\n\t\t\tawait this.hookRegistry.emit(\"pipeline:end\", this.onHookError, ctx, result);\n\n\t\t\treturn result;\n\t\t} catch (err) {\n\t\t\tlet result: DispatchResult<TConfig>;\n\t\t\tif (err instanceof DomainErrorSignal) {\n\t\t\t\tresult = {\n\t\t\t\t\tok: false as const,\n\t\t\t\t\terror: {\n\t\t\t\t\t\tcategory: \"domain\" as const,\n\t\t\t\t\t\tcode: err.code as ErrorCodes<TConfig>,\n\t\t\t\t\t\tdata: err.data as ErrorData<TConfig, ErrorCodes<TConfig>>,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t} else if (err instanceof ValidationError) {\n\t\t\t\tresult = {\n\t\t\t\t\tok: false as const,\n\t\t\t\t\terror: {\n\t\t\t\t\t\tcategory: \"validation\" as const,\n\t\t\t\t\t\tsource: err.source,\n\t\t\t\t\t\tissues: err.issues,\n\t\t\t\t\t\tmessage: err.message,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t} else if (err instanceof DependencyErrorSignal) {\n\t\t\t\tresult = {\n\t\t\t\t\tok: false as const,\n\t\t\t\t\terror: {\n\t\t\t\t\t\tcategory: \"dependency\" as const,\n\t\t\t\t\t\tname: err.depName,\n\t\t\t\t\t\terror: err.error,\n\t\t\t\t\t\tmessage: err.message,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t} else {\n\t\t\t\tresult = {\n\t\t\t\t\tok: false as const,\n\t\t\t\t\terror: {\n\t\t\t\t\t\tcategory: \"unexpected\" as const,\n\t\t\t\t\t\terror: err,\n\t\t\t\t\t\tmessage: err instanceof Error ? err.message : String(err),\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Hook: error\n\t\t\tawait this.hookRegistry.emit(\"error\", this.onHookError, result.error, ctx);\n\n\t\t\t// Hook: pipeline:end\n\t\t\tawait this.hookRegistry.emit(\"pipeline:end\", this.onHookError, ctx, result);\n\n\t\t\treturn result;\n\t\t}\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCA,iBAAkB;AAElB,IAAM,eAA8B,uBAAO,aAAa;AAYjD,SAAS,OAA0B,QAAsB;AAE/D,QAAM,UAAU,OAAO,OAAO,MAAM;AACpC,UAAQ,YAAY,IAAI;AACxB,SAAO;AACR;AAGO,SAAS,cAAc,QAA0B;AAEvD,SAAQ,OAAe,YAAY,MAAM;AAC1C;AAqBO,SAAS,gBACf,QACA,MAC0B;AAE1B,QAAM,MAAO,OAAe,MAAM;AAClC,MAAI,KAAK,SAAS,YAAY,CAAC,IAAI,MAAO,QAAO;AAEjD,QAAM,SAAkC,CAAC;AACzC,aAAW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QACD;AAAA,MACD,OAAO;AACN,iBAAS;AAAA,UACR,IAAI;AAAA,UACJ,OAAO;AAAA,YACN,UAAU;AAAA,YACV,OAAO;AAAA,YACP,SAAS,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAAA,UACzD;AAAA,QACD;AAAA,MACD;AAGA,YAAM,KAAK,aAAa,KAAK,SAAS,KAAK,aAAa,OAAO,OAAO,GAAG;AAGzE,YAAM,KAAK,aAAa,KAAK,gBAAgB,KAAK,aAAa,KAAK,MAAM;AAE1E,aAAO;AAAA,IACR;AAAA,EACD;AACD;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/server.ts","../src/types.ts","../src/definition.ts","../src/key.ts","../src/migration.ts","../src/plugin.ts","../src/compose.ts","../src/wrap-deps.ts","../src/context.ts","../src/hooks.ts","../src/router.ts"],"sourcesContent":["export type { Context } from \"./context.js\";\nexport type { ClientWorkflowDefinition, WorkflowDefinition } from \"./definition.js\";\nexport { defineWorkflow } from \"./definition.js\";\nexport type { Handler } from \"./handler.js\";\nexport type { HookEvent } from \"./hooks.js\";\nexport type { ContextKey } from \"./key.js\";\nexport { createKey } from \"./key.js\";\nexport type { Middleware } from \"./middleware.js\";\nexport type {\n\tMigrateOptions,\n\tMigrateResult,\n\tMigrationEntry,\n\tMigrationFn,\n\tMigrationPipeline,\n} from \"./migration.js\";\nexport { defineMigrations, MigrationError, migrate } from \"./migration.js\";\nexport type { GenericPlugin, Plugin } from \"./plugin.js\";\nexport { defineGenericPlugin, definePlugin, isPlugin } from \"./plugin.js\";\nexport type { ReadonlyContext } from \"./readonly-context.js\";\nexport type { RouterOptions } from \"./router.js\";\nexport { WorkflowRouter } from \"./router.js\";\nexport type { Server } from \"./server.js\";\nexport { isServerField, server } from \"./server.js\";\nexport type { WorkflowSnapshot } from \"./snapshot.js\";\nexport type {\n\tClientStateData,\n\tClientWorkflow,\n\tClientWorkflowOf,\n\tCommand,\n\tCommandNames,\n\tCommandPayload,\n\tConfigOf,\n\tDispatchResult,\n\tErrorCodes,\n\tErrorData,\n\tEventData,\n\tEventNames,\n\tPipelineError,\n\tStateData,\n\tStateNames,\n\tWorkflow,\n\tWorkflowConfig,\n\tWorkflowOf,\n} from \"./types.js\";\nexport { DomainErrorSignal, ValidationError } from \"./types.js\";\n","import type { ZodType } from \"zod\";\nimport { z } from \"zod\";\n\nconst SERVER_BRAND: unique symbol = Symbol(\"ryte.server\");\n\n/** Brands a Zod schema type as server-only at the TypeScript level. */\nexport type Server<T extends ZodType> = T & { readonly [SERVER_BRAND]: true };\n\n/**\n * Marks a Zod schema as server-only. Fields wrapped in `server()` are stripped\n * from client snapshots and excluded from client TypeScript types.\n *\n * Returns a new schema reference — the original is not mutated, so shared\n * schemas can safely be used in both server and non-server positions.\n */\nexport function server<T extends ZodType>(schema: T): Server<T> {\n\t// biome-ignore lint/suspicious/noExplicitAny: creating a branded proxy that inherits all Zod behavior via prototype\n\tconst branded = Object.create(schema) as any;\n\tbranded[SERVER_BRAND] = true;\n\treturn branded as Server<T>;\n}\n\n/** Returns `true` if the schema was wrapped with `server()`. */\nexport function isServerField(schema: ZodType): boolean {\n\t// biome-ignore lint/suspicious/noExplicitAny: reading runtime brand from Zod schema\n\treturn (schema as any)[SERVER_BRAND] === true;\n}\n\ntype ServerBranded = { readonly [SERVER_BRAND]: true };\n\n/** Computes the client-safe inferred type from a Zod schema by filtering out server-branded fields. */\nexport type ClientInfer<T extends ZodType> = T extends {\n\tshape: infer Shape extends Record<string, ZodType>;\n}\n\t? {\n\t\t\t[K in keyof Shape as Shape[K] extends ServerBranded ? never : K]: Shape[K] extends {\n\t\t\t\tshape: Record<string, ZodType>;\n\t\t\t}\n\t\t\t\t? ClientInfer<Shape[K]>\n\t\t\t\t: z.infer<Shape[K]>;\n\t\t}\n\t: z.infer<T>;\n\n/**\n * Strips server-only fields from workflow data based on the state's Zod schema.\n * Recursively processes nested z.object() schemas.\n */\nexport function stripServerData(\n\tschema: ZodType,\n\tdata: Record<string, unknown>,\n): Record<string, unknown> {\n\t// biome-ignore lint/suspicious/noExplicitAny: accessing Zod v4 internal _zod.def.shape for schema introspection\n\tconst def = (schema as any)._zod?.def;\n\tif (def?.type !== \"object\" || !def.shape) return data;\n\n\tconst result: Record<string, unknown> = {};\n\tfor (const key of Object.keys(data)) {\n\t\tconst fieldSchema = def.shape[key] as ZodType | undefined;\n\t\tif (fieldSchema && isServerField(fieldSchema)) continue;\n\n\t\tif (\n\t\t\tfieldSchema &&\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: checking Zod v4 internal def.type for nested object detection\n\t\t\t(fieldSchema as any)._zod?.def?.type === \"object\" &&\n\t\t\tdata[key] !== null &&\n\t\t\ttypeof data[key] === \"object\"\n\t\t) {\n\t\t\tresult[key] = stripServerData(fieldSchema, data[key] as Record<string, unknown>);\n\t\t} else {\n\t\t\tresult[key] = data[key];\n\t\t}\n\t}\n\treturn result;\n}\n\n/**\n * Derives a client-safe Zod schema by removing server-only fields.\n * Recursively processes nested z.object() schemas.\n * Returns the original schema unchanged for non-object schemas.\n */\nexport function deriveClientSchema(schema: ZodType): ZodType {\n\t// biome-ignore lint/suspicious/noExplicitAny: accessing Zod v4 internal _zod.def.shape for schema introspection\n\tconst def = (schema as any)._zod?.def;\n\tif (def?.type !== \"object\" || !def.shape) return schema;\n\n\tconst clientShape: Record<string, ZodType> = {};\n\tfor (const [key, fieldSchema] of Object.entries(def.shape as Record<string, ZodType>)) {\n\t\tif (isServerField(fieldSchema)) continue;\n\n\t\t// biome-ignore lint/suspicious/noExplicitAny: checking Zod v4 internal def.type for nested object detection\n\t\tif ((fieldSchema as any)._zod?.def?.type === \"object\") {\n\t\t\tclientShape[key] = deriveClientSchema(fieldSchema);\n\t\t} else {\n\t\t\tclientShape[key] = fieldSchema;\n\t\t}\n\t}\n\treturn z.object(clientShape).strict();\n}\n","import type { ZodType, z } from \"zod\";\n\n/**\n * Shape of the configuration object passed to {@link defineWorkflow}.\n * Exported for internal package use only — not re-exported from index.ts.\n */\nexport interface WorkflowConfigInput {\n\t/** Optional version number for schema migrations. Defaults to 1. */\n\tmodelVersion?: number;\n\t/** Record of state names to Zod schemas defining their data shape. */\n\tstates: Record<string, ZodType>;\n\t/** Record of command names to Zod schemas defining their payload shape. */\n\tcommands: Record<string, ZodType>;\n\t/** Record of event names to Zod schemas defining their data shape. */\n\tevents: Record<string, ZodType>;\n\t/** Record of error codes to Zod schemas defining their data shape. */\n\terrors: Record<string, ZodType>;\n}\n\n/**\n * Workflow configuration with pre-resolved types for IDE completion.\n *\n * Extends {@link WorkflowConfigInput} with a `_resolved` phantom type that\n * caches `z.infer` results. This exists because Zod v4's `z.infer` uses\n * conditional types that TypeScript defers in deep generic chains, breaking\n * IDE autocomplete. The `_resolved` property is never set at runtime — it is\n * populated at the type level by {@link defineWorkflow}'s return type.\n */\nexport interface WorkflowConfig extends WorkflowConfigInput {\n\t_resolved: {\n\t\tstates: Record<string, unknown>;\n\t\tcommands: Record<string, unknown>;\n\t\tevents: Record<string, unknown>;\n\t\terrors: Record<string, unknown>;\n\t};\n\t_clientResolved: {\n\t\tstates: Record<string, unknown>;\n\t};\n}\n\nexport type StateNames<T extends WorkflowConfig> = keyof T[\"states\"] & string;\nexport type CommandNames<T extends WorkflowConfig> = keyof T[\"commands\"] & string;\nexport type EventNames<T extends WorkflowConfig> = keyof T[\"events\"] & string;\nexport type ErrorCodes<T extends WorkflowConfig> = keyof T[\"errors\"] & string;\n\n/** Forces TypeScript to flatten a type for better IDE autocomplete. */\ntype Prettify<T> = { [K in keyof T]: T[K] } & {};\n\n/** Discriminated union of all commands with typed payloads — narrows payload when checking type. */\nexport type Command<T extends WorkflowConfig> = {\n\t[C in CommandNames<T>]: { type: C; payload: CommandPayload<T, C> };\n}[CommandNames<T>];\n\n/** Resolves the data type for a given state from pre-computed types. */\nexport type StateData<T extends WorkflowConfig, S extends StateNames<T>> = Prettify<\n\tT[\"_resolved\"][\"states\"][S]\n>;\n\n/** Resolves the client-safe data type for a given state (server fields stripped). */\nexport type ClientStateData<T extends WorkflowConfig, S extends StateNames<T>> = Prettify<\n\tT[\"_clientResolved\"][\"states\"][S]\n>;\n\n/** Client-side workflow narrowed to a specific known state. */\nexport interface ClientWorkflowOf<TConfig extends WorkflowConfig, S extends StateNames<TConfig>> {\n\treadonly id: string;\n\treadonly definitionName: string;\n\treadonly state: S;\n\treadonly data: ClientStateData<TConfig, S>;\n\treadonly createdAt: Date;\n\treadonly updatedAt: Date;\n}\n\n/** Discriminated union of all possible client-side workflow states. */\nexport type ClientWorkflow<TConfig extends WorkflowConfig = WorkflowConfig> = {\n\t[S in StateNames<TConfig>]: ClientWorkflowOf<TConfig, S>;\n}[StateNames<TConfig>];\n\n/** Resolves the payload type for a given command from pre-computed types. */\nexport type CommandPayload<T extends WorkflowConfig, C extends CommandNames<T>> = Prettify<\n\tT[\"_resolved\"][\"commands\"][C]\n>;\n\n/** Resolves the data type for a given event from pre-computed types. */\nexport type EventData<T extends WorkflowConfig, E extends EventNames<T>> = Prettify<\n\tT[\"_resolved\"][\"events\"][E]\n>;\n\n/** Resolves the data type for a given error code from pre-computed types. */\nexport type ErrorData<T extends WorkflowConfig, C extends ErrorCodes<T>> = Prettify<\n\tT[\"_resolved\"][\"errors\"][C]\n>;\n\n/** Workflow narrowed to a specific known state. */\nexport interface WorkflowOf<TConfig extends WorkflowConfig, S extends StateNames<TConfig>> {\n\t/** Unique workflow instance identifier. */\n\treadonly id: string;\n\t/** Name of the workflow definition this instance belongs to. */\n\treadonly definitionName: string;\n\t/** Current state name. */\n\treadonly state: S;\n\t/** State data, typed according to the state's Zod schema. */\n\treadonly data: StateData<TConfig, S>;\n\t/** Timestamp of workflow creation. */\n\treadonly createdAt: Date;\n\t/** Timestamp of last state change. */\n\treadonly updatedAt: Date;\n}\n\n/** Discriminated union of all possible workflow states — checking .state narrows .data. */\nexport type Workflow<TConfig extends WorkflowConfig = WorkflowConfig> = {\n\t[S in StateNames<TConfig>]: WorkflowOf<TConfig, S>;\n}[StateNames<TConfig>];\n\n/** Discriminated union of all pipeline error types on `category`. */\nexport type PipelineError<TConfig extends WorkflowConfig = WorkflowConfig> =\n\t| {\n\t\t\tcategory: \"validation\";\n\t\t\tsource: \"command\" | \"state\" | \"event\" | \"transition\" | \"restore\";\n\t\t\tissues: z.core.$ZodIssue[];\n\t\t\tmessage: string;\n\t }\n\t| {\n\t\t\tcategory: \"domain\";\n\t\t\tcode: ErrorCodes<TConfig>;\n\t\t\tdata: ErrorData<TConfig, ErrorCodes<TConfig>>;\n\t }\n\t| {\n\t\t\tcategory: \"router\";\n\t\t\tcode: \"NO_HANDLER\" | \"UNKNOWN_STATE\";\n\t\t\tmessage: string;\n\t }\n\t| {\n\t\t\tcategory: \"unexpected\";\n\t\t\terror: unknown;\n\t\t\tmessage: string;\n\t }\n\t| {\n\t\t\tcategory: \"dependency\";\n\t\t\tname: string;\n\t\t\terror: unknown;\n\t\t\tmessage: string;\n\t };\n\n/** Return type of {@link WorkflowRouter.dispatch}. Discriminated union on `ok`. */\nexport type DispatchResult<TConfig extends WorkflowConfig = WorkflowConfig> =\n\t| {\n\t\t\tok: true;\n\t\t\tworkflow: Workflow<TConfig>;\n\t\t\tevents: Array<{ type: EventNames<TConfig>; data: unknown }>;\n\t }\n\t| {\n\t\t\tok: false;\n\t\t\terror: PipelineError<TConfig>;\n\t };\n\n/**\n * Thrown internally when Zod validation fails during dispatch.\n * Caught by the router and returned as a validation error in {@link DispatchResult}.\n *\n * @param source - Which validation stage failed\n * @param issues - Array of Zod validation issues\n */\nexport class ValidationError extends Error {\n\tconstructor(\n\t\tpublic readonly source: \"command\" | \"state\" | \"event\" | \"transition\" | \"restore\",\n\t\tpublic readonly issues: z.core.$ZodIssue[],\n\t) {\n\t\tsuper(`Validation failed (${source}): ${issues.map((i) => i.message).join(\", \")}`);\n\t\tthis.name = \"ValidationError\";\n\t}\n}\n\n/**\n * Thrown internally when a handler calls `ctx.error()`.\n * Caught by the router and returned as a domain error in {@link DispatchResult}.\n *\n * @param code - The error code string\n * @param data - The error data payload\n */\nexport class DomainErrorSignal extends Error {\n\tconstructor(\n\t\tpublic readonly code: string,\n\t\tpublic readonly data: unknown,\n\t) {\n\t\tsuper(`Domain error: ${code}`);\n\t\tthis.name = \"DomainErrorSignal\";\n\t}\n}\n\n/**\n * Thrown internally when a proxied dependency call fails.\n * Caught by the router and returned as a dependency error in {@link DispatchResult}.\n *\n * @param depName - The top-level dependency key (e.g. \"db\", \"stripe\")\n * @param error - The original error thrown by the dependency\n */\n/** Extracts the WorkflowConfig type from a WorkflowRouter instance. */\nexport type ConfigOf<R> = R extends { definition: { config: infer C } } ? C : never;\n\nexport class DependencyErrorSignal extends Error {\n\tconstructor(\n\t\tpublic readonly depName: string,\n\t\tpublic readonly error: unknown,\n\t) {\n\t\tconst original = error instanceof Error ? error.message : String(error);\n\t\tsuper(`Dependency \"${depName}\" failed: ${original}`);\n\t\tthis.name = \"DependencyErrorSignal\";\n\t}\n}\n","import type { ZodType, z } from \"zod\";\nimport type { ClientInfer } from \"./server.js\";\nimport { deriveClientSchema, stripServerData } from \"./server.js\";\nimport type { WorkflowSnapshot } from \"./snapshot.js\";\nimport type {\n\tClientWorkflow,\n\tStateData,\n\tStateNames,\n\tWorkflow,\n\tWorkflowConfig,\n\tWorkflowConfigInput,\n\tWorkflowOf,\n} from \"./types.js\";\nimport { ValidationError } from \"./types.js\";\n\n/**\n * The result of {@link defineWorkflow} — holds schemas and creates workflow instances.\n */\nexport interface WorkflowDefinition<TConfig extends WorkflowConfig = WorkflowConfig> {\n\t/** The raw Zod schema configuration. */\n\treadonly config: TConfig;\n\t/** The workflow definition name. */\n\treadonly name: string;\n\t/**\n\t * Creates a new workflow instance in a given initial state.\n\t *\n\t * @param id - Unique identifier for this workflow instance\n\t * @param config - Object containing `initialState` and the corresponding `data`\n\t * @returns A {@link WorkflowOf} narrowed to the initial state\n\t */\n\tcreateWorkflow<S extends StateNames<TConfig>>(\n\t\tid: string,\n\t\tconfig: { initialState: S; data: StateData<TConfig, S> },\n\t): WorkflowOf<TConfig, S>;\n\t/**\n\t * Returns the Zod schema for a given state name.\n\t *\n\t * @param stateName - The state name to look up\n\t * @throws If the state name is not found in the config\n\t */\n\tgetStateSchema(stateName: string): ZodType;\n\t/**\n\t * Returns the Zod schema for a given command name.\n\t *\n\t * @param commandName - The command name to look up\n\t * @throws If the command name is not found in the config\n\t */\n\tgetCommandSchema(commandName: string): ZodType;\n\t/**\n\t * Returns the Zod schema for a given event name.\n\t *\n\t * @param eventName - The event name to look up\n\t * @throws If the event name is not found in the config\n\t */\n\tgetEventSchema(eventName: string): ZodType;\n\t/**\n\t * Returns the Zod schema for a given error code.\n\t *\n\t * @param errorCode - The error code to look up\n\t * @throws If the error code is not found in the config\n\t */\n\tgetErrorSchema(errorCode: string): ZodType;\n\t/**\n\t * Returns `true` if the given state name exists in the config.\n\t *\n\t * @param stateName - The state name to check\n\t */\n\thasState(stateName: string): boolean;\n\t/**\n\t * Returns `true` if the given command name exists in the config.\n\t */\n\thasCommand(commandName: string): boolean;\n\t/**\n\t * Returns `true` if the given event name exists in the config.\n\t */\n\thasEvent(eventName: string): boolean;\n\t/**\n\t * Serializes a workflow instance into a plain, JSON-safe snapshot.\n\t *\n\t * @param workflow - The workflow instance to serialize\n\t * @returns A {@link WorkflowSnapshot} representing the current state\n\t */\n\tserialize(workflow: Workflow<TConfig>): WorkflowSnapshot<TConfig>;\n\t/**\n\t * Deserializes a workflow instance from a plain snapshot, validating the state data.\n\t *\n\t * @param snapshot - The snapshot to deserialize from\n\t * @returns A result object: `{ ok: true, workflow }` or `{ ok: false, error }`\n\t */\n\tdeserialize(\n\t\tsnapshot: WorkflowSnapshot<TConfig>,\n\t): { ok: true; workflow: Workflow<TConfig> } | { ok: false; error: ValidationError };\n\t/**\n\t * Serializes a workflow into a client-safe snapshot with server-only fields stripped.\n\t *\n\t * @param workflow - The workflow instance to serialize\n\t * @returns A {@link WorkflowSnapshot} with server-only fields removed from `data`\n\t */\n\tserializeForClient(workflow: Workflow<TConfig>): WorkflowSnapshot<TConfig>;\n\t/**\n\t * Returns a client-safe projection of this definition.\n\t * Memoized — returns the same instance on repeated calls.\n\t */\n\tforClient(): ClientWorkflowDefinition<TConfig>;\n}\n\n/**\n * A client-safe projection of a workflow definition.\n * State schemas have server-only fields removed. Returned by {@link WorkflowDefinition.forClient}.\n */\nexport interface ClientWorkflowDefinition<TConfig extends WorkflowConfig = WorkflowConfig> {\n\t/** The raw Zod schema configuration. */\n\treadonly config: TConfig;\n\treadonly name: string;\n\tgetStateSchema(stateName: string): ZodType;\n\thasState(stateName: string): boolean;\n\tdeserialize(\n\t\tsnapshot: WorkflowSnapshot<TConfig>,\n\t): { ok: true; workflow: ClientWorkflow<TConfig> } | { ok: false; error: ValidationError };\n}\n\n/**\n * Creates a workflow definition from a name and Zod schema configuration.\n *\n * @param name - Unique name for this workflow type\n * @param config - Object with `states`, `commands`, `events`, `errors` — each a record of Zod schemas\n * @returns A {@link WorkflowDefinition} with methods for creating instances and accessing schemas\n */\n// Zod v4 uses conditional types for z.infer which TypeScript defers in deep\n// generic chains, breaking IDE completion. We pre-compute all inferred types\n// at this call site (where TConfig is concrete) and attach them as _resolved,\n// so downstream utility types can use direct indexed access instead.\nexport function defineWorkflow<const TConfig extends WorkflowConfigInput>(\n\tname: string,\n\tconfig: TConfig,\n): WorkflowDefinition<\n\tTConfig & {\n\t\t_resolved: {\n\t\t\tstates: { [K in keyof TConfig[\"states\"]]: z.infer<TConfig[\"states\"][K]> };\n\t\t\tcommands: { [K in keyof TConfig[\"commands\"]]: z.infer<TConfig[\"commands\"][K]> };\n\t\t\tevents: { [K in keyof TConfig[\"events\"]]: z.infer<TConfig[\"events\"][K]> };\n\t\t\terrors: { [K in keyof TConfig[\"errors\"]]: z.infer<TConfig[\"errors\"][K]> };\n\t\t};\n\t\t_clientResolved: {\n\t\t\tstates: { [K in keyof TConfig[\"states\"]]: ClientInfer<TConfig[\"states\"][K]> };\n\t\t};\n\t}\n>;\n// biome-ignore lint/suspicious/noExplicitAny: implementation overload — public signature above provides consumer-facing type safety; internally TConfig extends WorkflowConfigInput which lacks _resolved\nexport function defineWorkflow(name: string, config: WorkflowConfigInput): WorkflowDefinition<any> {\n\t// biome-ignore lint/suspicious/noExplicitAny: memoized client definition — typed via public interface ClientWorkflowDefinition\n\tlet cachedClientDef: any = null;\n\n\treturn {\n\t\tconfig,\n\t\tname,\n\n\t\tcreateWorkflow(id: string, wfConfig: { initialState: string; data: unknown }) {\n\t\t\tconst schema = config.states[wfConfig.initialState];\n\t\t\tif (!schema) throw new Error(`Unknown state: ${wfConfig.initialState}`);\n\t\t\tconst result = schema.safeParse(wfConfig.data);\n\t\t\tif (!result.success) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Invalid initial data for state '${wfConfig.initialState}': ${result.error.issues.map((i) => i.message).join(\", \")}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst now = new Date();\n\t\t\treturn {\n\t\t\t\tid,\n\t\t\t\tdefinitionName: name,\n\t\t\t\tstate: wfConfig.initialState,\n\t\t\t\tdata: result.data,\n\t\t\t\tcreatedAt: now,\n\t\t\t\tupdatedAt: now,\n\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: narrowed by the public overload's generic S parameter\n\t\t\t} as any;\n\t\t},\n\n\t\tgetStateSchema(stateName: string): ZodType {\n\t\t\tconst schema = config.states[stateName];\n\t\t\tif (!schema) throw new Error(`Unknown state: ${stateName}`);\n\t\t\treturn schema;\n\t\t},\n\n\t\tgetCommandSchema(commandName: string): ZodType {\n\t\t\tconst schema = config.commands[commandName];\n\t\t\tif (!schema) throw new Error(`Unknown command: ${commandName}`);\n\t\t\treturn schema;\n\t\t},\n\n\t\tgetEventSchema(eventName: string): ZodType {\n\t\t\tconst schema = config.events[eventName];\n\t\t\tif (!schema) throw new Error(`Unknown event: ${eventName}`);\n\t\t\treturn schema;\n\t\t},\n\n\t\tgetErrorSchema(errorCode: string): ZodType {\n\t\t\tconst schema = config.errors[errorCode];\n\t\t\tif (!schema) throw new Error(`Unknown error: ${errorCode}`);\n\t\t\treturn schema;\n\t\t},\n\n\t\thasState(stateName: string): boolean {\n\t\t\treturn stateName in config.states;\n\t\t},\n\n\t\thasCommand(commandName: string): boolean {\n\t\t\treturn commandName in config.commands;\n\t\t},\n\n\t\thasEvent(eventName: string): boolean {\n\t\t\treturn eventName in config.events;\n\t\t},\n\n\t\tserialize(workflow: {\n\t\t\tid: string;\n\t\t\tstate: string;\n\t\t\tdata: unknown;\n\t\t\tcreatedAt: Date;\n\t\t\tupdatedAt: Date;\n\t\t\tversion?: number;\n\t\t}) {\n\t\t\treturn {\n\t\t\t\tid: workflow.id,\n\t\t\t\tdefinitionName: name,\n\t\t\t\tstate: workflow.state,\n\t\t\t\tdata: workflow.data,\n\t\t\t\tcreatedAt: workflow.createdAt.toISOString(),\n\t\t\t\tupdatedAt: workflow.updatedAt.toISOString(),\n\t\t\t\tmodelVersion: config.modelVersion ?? 1,\n\t\t\t\tversion: workflow.version ?? 1,\n\t\t\t};\n\t\t},\n\n\t\tdeserialize(snap: {\n\t\t\tid: string;\n\t\t\tdefinitionName: string;\n\t\t\tstate: string;\n\t\t\tdata: unknown;\n\t\t\tcreatedAt: string;\n\t\t\tupdatedAt: string;\n\t\t}) {\n\t\t\tconst stateSchema = config.states[snap.state];\n\t\t\tif (!stateSchema) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: new ValidationError(\"restore\", [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcode: \"custom\",\n\t\t\t\t\t\t\tmessage: `Unknown state: ${snap.state}`,\n\t\t\t\t\t\t\tinput: snap.state,\n\t\t\t\t\t\t\tpath: [\"state\"],\n\t\t\t\t\t\t},\n\t\t\t\t\t]),\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst result = stateSchema.safeParse(snap.data);\n\t\t\tif (!result.success) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: new ValidationError(\"restore\", result.error.issues),\n\t\t\t\t};\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tok: true,\n\t\t\t\tworkflow: {\n\t\t\t\t\tid: snap.id,\n\t\t\t\t\tdefinitionName: snap.definitionName,\n\t\t\t\t\tstate: snap.state,\n\t\t\t\t\tdata: result.data,\n\t\t\t\t\tcreatedAt: new Date(snap.createdAt),\n\t\t\t\t\tupdatedAt: new Date(snap.updatedAt),\n\t\t\t\t},\n\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Prettify<any> produces { [x: string]: any } instead of any, making unknown data incompatible\n\t\t\t} as any;\n\t\t},\n\n\t\tserializeForClient(workflow: {\n\t\t\tid: string;\n\t\t\tstate: string;\n\t\t\tdata: unknown;\n\t\t\tcreatedAt: Date;\n\t\t\tupdatedAt: Date;\n\t\t\tversion?: number;\n\t\t}) {\n\t\t\tconst stateSchema = config.states[workflow.state];\n\t\t\tconst strippedData = stateSchema\n\t\t\t\t? stripServerData(stateSchema, workflow.data as Record<string, unknown>)\n\t\t\t\t: workflow.data;\n\n\t\t\treturn {\n\t\t\t\tid: workflow.id,\n\t\t\t\tdefinitionName: name,\n\t\t\t\tstate: workflow.state,\n\t\t\t\tdata: strippedData,\n\t\t\t\tcreatedAt: workflow.createdAt.toISOString(),\n\t\t\t\tupdatedAt: workflow.updatedAt.toISOString(),\n\t\t\t\tmodelVersion: config.modelVersion ?? 1,\n\t\t\t\tversion: workflow.version ?? 1,\n\t\t\t};\n\t\t},\n\n\t\tforClient() {\n\t\t\tif (cachedClientDef) return cachedClientDef;\n\n\t\t\tconst clientSchemas: Record<string, ZodType> = {};\n\t\t\tfor (const [stateName, schema] of Object.entries(config.states)) {\n\t\t\t\tclientSchemas[stateName] = deriveClientSchema(schema);\n\t\t\t}\n\n\t\t\tcachedClientDef = {\n\t\t\t\tconfig,\n\t\t\t\tname,\n\n\t\t\t\tgetStateSchema(stateName: string): ZodType {\n\t\t\t\t\tconst schema = clientSchemas[stateName];\n\t\t\t\t\tif (!schema) throw new Error(`Unknown state: ${stateName}`);\n\t\t\t\t\treturn schema;\n\t\t\t\t},\n\n\t\t\t\thasState(stateName: string): boolean {\n\t\t\t\t\treturn stateName in clientSchemas;\n\t\t\t\t},\n\n\t\t\t\tdeserialize(snap: {\n\t\t\t\t\tid: string;\n\t\t\t\t\tdefinitionName: string;\n\t\t\t\t\tstate: string;\n\t\t\t\t\tdata: unknown;\n\t\t\t\t\tcreatedAt: string;\n\t\t\t\t\tupdatedAt: string;\n\t\t\t\t}) {\n\t\t\t\t\tconst stateSchema = clientSchemas[snap.state];\n\t\t\t\t\tif (!stateSchema) {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tok: false,\n\t\t\t\t\t\t\terror: new ValidationError(\"restore\", [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tcode: \"custom\",\n\t\t\t\t\t\t\t\t\tmessage: `Unknown state: ${snap.state}`,\n\t\t\t\t\t\t\t\t\tinput: snap.state,\n\t\t\t\t\t\t\t\t\tpath: [\"state\"],\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t]),\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\n\t\t\t\t\tconst result = stateSchema.safeParse(snap.data);\n\t\t\t\t\tif (!result.success) {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tok: false,\n\t\t\t\t\t\t\terror: new ValidationError(\"restore\", result.error.issues),\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tok: true,\n\t\t\t\t\t\tworkflow: {\n\t\t\t\t\t\t\tid: snap.id,\n\t\t\t\t\t\t\tdefinitionName: snap.definitionName,\n\t\t\t\t\t\t\tstate: snap.state,\n\t\t\t\t\t\t\tdata: result.data,\n\t\t\t\t\t\t\tcreatedAt: new Date(snap.createdAt),\n\t\t\t\t\t\t\tupdatedAt: new Date(snap.updatedAt),\n\t\t\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Prettify<any> produces { [x: string]: any } instead of any, making unknown data incompatible\n\t\t\t\t\t\t} as any,\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t};\n\n\t\t\treturn cachedClientDef;\n\t\t},\n\t};\n}\n","/** A phantom-typed key for type-safe middleware state storage via {@link Context.set} and {@link Context.get}. */\nexport interface ContextKey<T> {\n\t/** @internal Phantom type brand — not used at runtime. */\n\treadonly _phantom: T;\n\t/** Internal symbol providing uniqueness. */\n\treadonly id: symbol;\n}\n\n/**\n * Creates a unique typed key for storing and retrieving values in context.\n *\n * @param name - Debug label (uniqueness comes from an internal `Symbol`)\n * @returns A {@link ContextKey} for use with `ctx.set()`, `ctx.get()`, and `ctx.getOrNull()`\n */\nexport function createKey<T>(name: string): ContextKey<T> {\n\treturn { id: Symbol(name) } as ContextKey<T>;\n}\n","import type { WorkflowDefinition } from \"./definition.js\";\nimport type { WorkflowSnapshot } from \"./snapshot.js\";\nimport type { WorkflowConfig } from \"./types.js\";\n\n/** A function that transforms a snapshot's data from one version to the next. */\nexport type MigrationFn = (snapshot: WorkflowSnapshot) => WorkflowSnapshot;\n\n/** A migration entry — either a bare {@link MigrationFn} or an object with a description. */\nexport type MigrationEntry = MigrationFn | { description: string; up: MigrationFn };\n\n/** Internal normalized migration step with optional description. */\ninterface NormalizedMigration {\n\tfn: MigrationFn;\n\tdescription?: string;\n}\n\n/** A validated migration pipeline ready to transform snapshots. */\nexport interface MigrationPipeline<TConfig extends WorkflowConfig = WorkflowConfig> {\n\t/** The workflow definition this pipeline belongs to. */\n\treadonly definition: WorkflowDefinition<TConfig>;\n\t/** The target schema version to migrate snapshots to. */\n\treadonly targetVersion: number;\n\t/** Map of version number to normalized migration step. */\n\treadonly migrations: ReadonlyMap<number, NormalizedMigration>;\n}\n\n/** Result of {@link migrate}. */\nexport type MigrateResult =\n\t| { ok: true; snapshot: WorkflowSnapshot }\n\t| { ok: false; error: MigrationError };\n\n/** Options for {@link migrate}. */\nexport interface MigrateOptions {\n\t/**\n\t * Called after each successful migration step.\n\t * @param fromVersion - The version before this step\n\t * @param toVersion - The version after this step\n\t * @param snapshot - The snapshot after this step\n\t * @param description - Optional description from the migration entry\n\t */\n\tonStep?: (\n\t\tfromVersion: number,\n\t\ttoVersion: number,\n\t\tsnapshot: WorkflowSnapshot,\n\t\tdescription?: string,\n\t) => void;\n\t/**\n\t * Called when a migration step fails.\n\t * @param error - The {@link MigrationError} describing the failure\n\t */\n\tonError?: (error: MigrationError) => void;\n}\n\n/** Error thrown when a migration step fails. */\nexport class MigrationError extends Error {\n\t/**\n\t * @param fromVersion - The schema version the migration started from\n\t * @param toVersion - The schema version the migration was attempting to reach\n\t * @param cause - The underlying error that caused the failure\n\t */\n\tconstructor(\n\t\tpublic readonly fromVersion: number,\n\t\tpublic readonly toVersion: number,\n\t\tpublic readonly cause: unknown,\n\t) {\n\t\tsuper(\n\t\t\t`Migration ${fromVersion} → ${toVersion} failed: ${cause instanceof Error ? cause.message : String(cause)}`,\n\t\t);\n\t\tthis.name = \"MigrationError\";\n\t}\n}\n\n/**\n * Creates a validated migration pipeline from a definition and version-keyed transform functions.\n * Each key is the target version — the function transforms from (key - 1) to key.\n *\n * @param definition - The workflow definition the migrations belong to\n * @param migrationMap - A record mapping target version numbers to {@link MigrationEntry} values\n * @returns A validated {@link MigrationPipeline} ready for use with {@link migrate}\n * @throws If migration keys are not sequential from 2 to the definition's `modelVersion`, or if the highest key does not match `modelVersion`\n */\nexport function defineMigrations<TConfig extends WorkflowConfig>(\n\tdefinition: WorkflowDefinition<TConfig>,\n\tmigrationMap: Record<number, MigrationEntry>,\n): MigrationPipeline<TConfig> {\n\tconst targetVersion = definition.config.modelVersion ?? 1;\n\tconst entries = Object.entries(migrationMap).map(([k, v]) => {\n\t\tconst normalized: NormalizedMigration =\n\t\t\ttypeof v === \"function\" ? { fn: v } : { fn: v.up, description: v.description };\n\t\treturn [Number(k), normalized] as const;\n\t});\n\n\tfor (const [version] of entries) {\n\t\tif (version <= 1) {\n\t\t\tthrow new Error(`Migration keys must be > 1 (version 1 is the baseline). Got: ${version}`);\n\t\t}\n\t}\n\n\tentries.sort((a, b) => a[0] - b[0]);\n\n\tif (entries.length > 0) {\n\t\tconst highest = entries[entries.length - 1];\n\t\tif (!highest || highest[0] !== targetVersion) {\n\t\t\tthrow new Error(\n\t\t\t\t`Highest migration key (${highest?.[0]}) does not match definition modelVersion (${targetVersion})`,\n\t\t\t);\n\t\t}\n\t\tfor (let i = 0; i < entries.length; i++) {\n\t\t\tconst entry = entries[i];\n\t\t\tconst expected = targetVersion - entries.length + 1 + i;\n\t\t\tif (!entry || entry[0] !== expected) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Migration version gap: expected ${expected} but found ${entry?.[0]}. Migrations must be sequential from 2 to ${targetVersion}.`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn {\n\t\tdefinition,\n\t\ttargetVersion,\n\t\tmigrations: new Map(entries),\n\t};\n}\n\n/**\n * Runs the migration chain from the snapshot's modelVersion to the pipeline's targetVersion.\n * Returns a Result. Auto-stamps modelVersion after each step.\n *\n * @param pipeline - The {@link MigrationPipeline} created by {@link defineMigrations}\n * @param snapshot - The workflow snapshot to migrate\n * @param options - Optional callbacks for step progress and error reporting\n * @returns A {@link MigrateResult} with the migrated snapshot on success, or a {@link MigrationError} on failure\n */\nexport function migrate<TConfig extends WorkflowConfig>(\n\tpipeline: MigrationPipeline<TConfig>,\n\tsnapshot: WorkflowSnapshot,\n\toptions?: MigrateOptions,\n): MigrateResult {\n\tif (!Number.isInteger(snapshot.modelVersion) || snapshot.modelVersion < 1) {\n\t\tconst error = new MigrationError(\n\t\t\tsnapshot.modelVersion,\n\t\t\tpipeline.targetVersion,\n\t\t\tnew Error(\n\t\t\t\t`Invalid snapshot modelVersion: ${snapshot.modelVersion}. Must be a positive integer.`,\n\t\t\t),\n\t\t);\n\t\toptions?.onError?.(error);\n\t\treturn { ok: false, error };\n\t}\n\n\tif (snapshot.definitionName !== pipeline.definition.name) {\n\t\tconst error = new MigrationError(\n\t\t\tsnapshot.modelVersion,\n\t\t\tpipeline.targetVersion,\n\t\t\tnew Error(\n\t\t\t\t`Snapshot definition '${snapshot.definitionName}' does not match pipeline definition '${pipeline.definition.name}'`,\n\t\t\t),\n\t\t);\n\t\toptions?.onError?.(error);\n\t\treturn { ok: false, error };\n\t}\n\n\tif (snapshot.modelVersion > pipeline.targetVersion) {\n\t\tconst error = new MigrationError(\n\t\t\tsnapshot.modelVersion,\n\t\t\tpipeline.targetVersion,\n\t\t\tnew Error(\n\t\t\t\t`Snapshot modelVersion (${snapshot.modelVersion}) is higher than target (${pipeline.targetVersion}). Cannot downgrade.`,\n\t\t\t),\n\t\t);\n\t\toptions?.onError?.(error);\n\t\treturn { ok: false, error };\n\t}\n\n\tif (snapshot.modelVersion === pipeline.targetVersion) {\n\t\treturn { ok: true, snapshot };\n\t}\n\n\tlet current = { ...snapshot };\n\tfor (let version = current.modelVersion + 1; version <= pipeline.targetVersion; version++) {\n\t\tconst migration = pipeline.migrations.get(version);\n\t\tif (!migration) {\n\t\t\tconst error = new MigrationError(\n\t\t\t\tversion - 1,\n\t\t\t\tversion,\n\t\t\t\tnew Error(`No migration function found for version ${version}`),\n\t\t\t);\n\t\t\toptions?.onError?.(error);\n\t\t\treturn { ok: false, error };\n\t\t}\n\n\t\tconst fromVersion = version - 1;\n\t\ttry {\n\t\t\tcurrent = { ...migration.fn(current), modelVersion: version };\n\t\t} catch (cause) {\n\t\t\tconst error = new MigrationError(fromVersion, version, cause);\n\t\t\toptions?.onError?.(error);\n\t\t\treturn { ok: false, error };\n\t\t}\n\n\t\toptions?.onStep?.(fromVersion, version, current, migration.description);\n\t}\n\n\treturn { ok: true, snapshot: current };\n}\n","import type { WorkflowRouter } from \"./router.js\";\nimport type { WorkflowConfig } from \"./types.js\";\n\nconst PLUGIN_SYMBOL: unique symbol = Symbol.for(\"ryte:plugin\");\n\n/** A branded plugin function that can be passed to {@link WorkflowRouter.use}. */\nexport type Plugin<TConfig extends WorkflowConfig, TDeps> = ((\n\trouter: WorkflowRouter<TConfig, TDeps>,\n) => void) & { readonly [PLUGIN_SYMBOL]: true };\n\n/**\n * Brands a function as a Ryte plugin for use with {@link WorkflowRouter.use}.\n *\n * @param fn - A function that configures a router (adds handlers, middleware, hooks)\n * @returns A branded {@link Plugin} function\n */\nexport function definePlugin<TConfig extends WorkflowConfig, TDeps>(\n\tfn: (router: WorkflowRouter<TConfig, TDeps>) => void,\n): Plugin<TConfig, TDeps> {\n\tconst plugin = fn as Plugin<TConfig, TDeps>;\n\tObject.defineProperty(plugin, PLUGIN_SYMBOL, { value: true, writable: false });\n\treturn plugin;\n}\n\n/**\n * Checks whether a value is a branded Ryte plugin.\n *\n * @param value - The value to check\n * @returns `true` if the value is a {@link Plugin}\n */\n/** A plugin that works with any router, regardless of config or deps. */\n// biome-ignore lint/suspicious/noExplicitAny: intentional — GenericPlugin opts out of config-specific types\nexport type GenericPlugin = Plugin<any, any>;\n\n/**\n * Creates a plugin that works with any router without requiring explicit type parameters.\n * Use this for cross-cutting concerns (logging, tracing, delay) that don't reference\n * specific states, commands, or events.\n *\n * @param fn - A function that configures a router (adds hooks, middleware)\n * @returns A branded {@link GenericPlugin} function\n */\nexport function defineGenericPlugin(\n\t// biome-ignore lint/suspicious/noExplicitAny: intentional — generic plugins receive untyped router\n\tfn: (router: WorkflowRouter<any, any>) => void,\n): GenericPlugin {\n\treturn definePlugin(fn);\n}\n\n/**\n * Checks whether a value is a branded Ryte plugin.\n *\n * @param value - The value to check\n * @returns `true` if the value is a {@link Plugin}\n */\nexport function isPlugin(value: unknown): value is Plugin<WorkflowConfig, unknown> {\n\treturn typeof value === \"function\" && PLUGIN_SYMBOL in value;\n}\n","type Middleware<TCtx> = (ctx: TCtx, next: () => Promise<void>) => Promise<void>;\n\n/** Composes an array of middleware into a single function (Koa-style onion model). */\nexport function compose<TCtx>(middleware: Middleware<TCtx>[]): (ctx: TCtx) => Promise<void> {\n\treturn async (ctx: TCtx) => {\n\t\tlet index = -1;\n\t\tasync function dispatch(i: number): Promise<void> {\n\t\t\tif (i <= index) throw new Error(\"next() called multiple times\");\n\t\t\tindex = i;\n\t\t\tconst fn = middleware[i];\n\t\t\tif (!fn) return;\n\t\t\tawait fn(ctx, () => dispatch(i + 1));\n\t\t}\n\t\tawait dispatch(0);\n\t};\n}\n","import { DependencyErrorSignal } from \"./types.js\";\n\nfunction createDepProxy<T extends object>(obj: T, depName: string): T {\n\treturn new Proxy(obj, {\n\t\tget(target, prop, receiver) {\n\t\t\tif (typeof prop === \"symbol\") {\n\t\t\t\treturn Reflect.get(target, prop, receiver);\n\t\t\t}\n\n\t\t\tconst value = Reflect.get(target, prop, receiver);\n\n\t\t\tif (value === null || value === undefined) {\n\t\t\t\treturn value;\n\t\t\t}\n\n\t\t\tif (typeof value === \"function\") {\n\t\t\t\treturn (...args: unknown[]) => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst result = value.apply(target, args);\n\t\t\t\t\t\tif (result != null && typeof result === \"object\" && typeof result.then === \"function\") {\n\t\t\t\t\t\t\treturn result.catch((err: unknown) => {\n\t\t\t\t\t\t\t\tthrow new DependencyErrorSignal(depName, err);\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn result;\n\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\tthrow new DependencyErrorSignal(depName, err);\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (typeof value === \"object\") {\n\t\t\t\treturn createDepProxy(value as object, depName);\n\t\t\t}\n\n\t\t\treturn value;\n\t\t},\n\t});\n}\n\n/** Wraps a deps object in a recursive Proxy that catches dependency errors. */\nexport function wrapDeps<T extends object>(deps: T): T {\n\treturn new Proxy(deps, {\n\t\tget(target, prop, receiver) {\n\t\t\tif (typeof prop === \"symbol\") {\n\t\t\t\treturn Reflect.get(target, prop, receiver);\n\t\t\t}\n\n\t\t\tconst value = Reflect.get(target, prop, receiver);\n\n\t\t\tif (value === null || value === undefined) {\n\t\t\t\treturn value;\n\t\t\t}\n\n\t\t\tconst depName = String(prop);\n\n\t\t\tif (typeof value === \"function\") {\n\t\t\t\treturn (...args: unknown[]) => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst result = value.apply(target, args);\n\t\t\t\t\t\tif (result != null && typeof result === \"object\" && typeof result.then === \"function\") {\n\t\t\t\t\t\t\treturn result.catch((err: unknown) => {\n\t\t\t\t\t\t\t\tthrow new DependencyErrorSignal(depName, err);\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn result;\n\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\tthrow new DependencyErrorSignal(depName, err);\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (typeof value === \"object\") {\n\t\t\t\treturn createDepProxy(value as object, depName);\n\t\t\t}\n\n\t\t\treturn value;\n\t\t},\n\t});\n}\n","import type { WorkflowDefinition } from \"./definition.js\";\nimport type { ContextKey } from \"./key.js\";\nimport type {\n\tCommandNames,\n\tCommandPayload,\n\tErrorCodes,\n\tErrorData,\n\tEventData,\n\tEventNames,\n\tStateData,\n\tStateNames,\n\tWorkflow,\n\tWorkflowConfig,\n\tWorkflowOf,\n} from \"./types.js\";\nimport { DomainErrorSignal, ValidationError } from \"./types.js\";\nimport { wrapDeps as wrapDepsProxy } from \"./wrap-deps.js\";\n\n/** Mutable context flowing through the middleware pipeline during dispatch. */\nexport interface Context<\n\tTConfig extends WorkflowConfig,\n\tTDeps,\n\tTState extends StateNames<TConfig> = StateNames<TConfig>,\n\tTCommand extends CommandNames<TConfig> = CommandNames<TConfig>,\n> {\n\t/** The command being dispatched, with type and validated payload. */\n\treadonly command: {\n\t\treadonly type: TCommand;\n\t\treadonly payload: CommandPayload<TConfig, TCommand>;\n\t};\n\t/** The original workflow before any mutations. */\n\treadonly workflow: WorkflowOf<TConfig, TState>;\n\t/** Dependencies injected via the router constructor. */\n\treadonly deps: TDeps;\n\n\t/** Current state data (reflects mutations from {@link update}). */\n\treadonly data: StateData<TConfig, TState>;\n\t/**\n\t * Merges partial data into the current state. Validates against the state's Zod schema.\n\t * @param data - Partial state data to merge\n\t */\n\tupdate(data: Partial<StateData<TConfig, TState>>): void;\n\n\t/**\n\t * Transitions the workflow to a new state with new data. Validates against the target state's Zod schema.\n\t * @param target - Target state name\n\t * @param data - Data for the target state\n\t */\n\ttransition<Target extends StateNames<TConfig>>(\n\t\ttarget: Target,\n\t\tdata: StateData<TConfig, Target>,\n\t): void;\n\n\t/** Current state name (reflects mutations from {@link transition}). */\n\treadonly state: TState;\n\n\t/**\n\t * Emits a domain event. Validates event data against the event's Zod schema.\n\t * @param type - Event type name\n\t * @param data - Event data matching the event's schema\n\t */\n\temit<E extends EventNames<TConfig>>(type: E, data: EventData<TConfig, E>): void;\n\t/** Accumulated events emitted during this dispatch. */\n\treadonly events: ReadonlyArray<{ type: EventNames<TConfig>; data: unknown }>;\n\n\t/**\n\t * Signals a domain error. Validates error data and throws internally (caught by the router).\n\t * @param code - Error code\n\t * @param data - Error data matching the error code's schema\n\t */\n\terror<C extends ErrorCodes<TConfig>>(code: C, data: ErrorData<TConfig, C>): never;\n\n\t/**\n\t * Pattern-matches on the current state, calling the matching callback with narrowed data.\n\t * All states must be handled (exhaustive).\n\t */\n\tmatch<R>(\n\t\tmatchers: {\n\t\t\t[S in StateNames<TConfig>]: (\n\t\t\t\tdata: StateData<TConfig, S>,\n\t\t\t\tworkflow: WorkflowOf<TConfig, S>,\n\t\t\t) => R;\n\t\t},\n\t): R;\n\t/**\n\t * Pattern-matches on the current state with a fallback for unhandled states.\n\t */\n\tmatch<R>(\n\t\tmatchers: Partial<{\n\t\t\t[S in StateNames<TConfig>]: (\n\t\t\t\tdata: StateData<TConfig, S>,\n\t\t\t\tworkflow: WorkflowOf<TConfig, S>,\n\t\t\t) => R;\n\t\t}>,\n\t\tfallback: () => R,\n\t): R;\n\n\t/**\n\t * Stores a value in context-scoped middleware state.\n\t * @param key - A {@link ContextKey} created via {@link createKey}\n\t * @param value - The value to store\n\t */\n\tset<T>(key: ContextKey<T>, value: T): void;\n\t/**\n\t * Retrieves a value from context-scoped middleware state. Throws if not set.\n\t * @param key - A {@link ContextKey} created via {@link createKey}\n\t */\n\tget<T>(key: ContextKey<T>): T;\n\t/**\n\t * Retrieves a value from context-scoped middleware state, or `undefined` if not set.\n\t * @param key - A {@link ContextKey} created via {@link createKey}\n\t */\n\tgetOrNull<T>(key: ContextKey<T>): T | undefined;\n\n\t/** @internal — not part of the handler API */\n\tgetWorkflowSnapshot(): Workflow<TConfig>;\n}\n\ninterface DomainEvent {\n\ttype: string;\n\tdata: unknown;\n}\n\n/** @internal Creates a context for dispatch. Not part of public API. */\nexport function createContext<TConfig extends WorkflowConfig, TDeps>(\n\tdefinition: WorkflowDefinition<TConfig>,\n\toriginalWorkflow: Workflow<TConfig>,\n\tcommand: { type: string; payload: unknown },\n\tdeps: TDeps,\n\toptions?: { wrapDeps?: boolean },\n): Context<TConfig, TDeps> {\n\tlet mutableState = originalWorkflow.state;\n\tlet mutableData: Record<string, unknown> = {\n\t\t...(originalWorkflow.data as Record<string, unknown>),\n\t};\n\n\tconst accumulatedEvents: DomainEvent[] = [];\n\tconst middlewareState = new Map<symbol, unknown>();\n\n\tconst ctx = {\n\t\tcommand,\n\t\tworkflow: originalWorkflow,\n\t\tdeps:\n\t\t\toptions?.wrapDeps !== false && deps != null && typeof deps === \"object\"\n\t\t\t\t? (wrapDepsProxy(deps as object) as TDeps)\n\t\t\t\t: deps,\n\n\t\tget state() {\n\t\t\treturn mutableState;\n\t\t},\n\n\t\tget data() {\n\t\t\treturn { ...mutableData } as StateData<TConfig, StateNames<TConfig>>;\n\t\t},\n\n\t\tupdate(data: Record<string, unknown>) {\n\t\t\tconst merged = { ...mutableData, ...data };\n\t\t\tconst schema = definition.getStateSchema(mutableState);\n\t\t\tconst result = schema.safeParse(merged);\n\t\t\tif (!result.success) {\n\t\t\t\tthrow new ValidationError(\"state\", result.error.issues);\n\t\t\t}\n\t\t\tmutableData = result.data as Record<string, unknown>;\n\t\t},\n\n\t\ttransition(target: string, data: unknown) {\n\t\t\tif (!definition.hasState(target)) {\n\t\t\t\tthrow new ValidationError(\"transition\", [\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: \"custom\",\n\t\t\t\t\t\tmessage: `Unknown state: ${target}`,\n\t\t\t\t\t\tinput: target,\n\t\t\t\t\t\tpath: [\"state\"],\n\t\t\t\t\t},\n\t\t\t\t]);\n\t\t\t}\n\t\t\tconst schema = definition.getStateSchema(target);\n\t\t\tconst result = schema.safeParse(data);\n\t\t\tif (!result.success) {\n\t\t\t\tthrow new ValidationError(\"transition\", result.error.issues);\n\t\t\t}\n\t\t\tmutableState = target;\n\t\t\tmutableData = result.data as Record<string, unknown>;\n\t\t},\n\n\t\temit(type: string, data: unknown) {\n\t\t\tconst schema = definition.getEventSchema(type);\n\t\t\tconst result = schema.safeParse(data);\n\t\t\tif (!result.success) {\n\t\t\t\tthrow new ValidationError(\"event\", result.error.issues);\n\t\t\t}\n\t\t\taccumulatedEvents.push({ type, data: result.data });\n\t\t},\n\n\t\tget events() {\n\t\t\treturn [...accumulatedEvents];\n\t\t},\n\n\t\terror(code: string, data: unknown) {\n\t\t\tconst schema = definition.getErrorSchema(code);\n\t\t\tconst result = schema.safeParse(data);\n\t\t\tif (!result.success) {\n\t\t\t\tthrow new ValidationError(\"state\", result.error.issues);\n\t\t\t}\n\t\t\tthrow new DomainErrorSignal(code, result.data);\n\t\t},\n\n\t\tmatch(\n\t\t\tmatchers: Record<string, (data: unknown, workflow: unknown) => unknown>,\n\t\t\tfallback?: () => unknown,\n\t\t) {\n\t\t\tconst matcher = matchers[originalWorkflow.state];\n\t\t\tif (matcher) return matcher(ctx.data, originalWorkflow);\n\t\t\tif (fallback) return fallback();\n\t\t\tthrow new Error(`No matcher for state: ${originalWorkflow.state}`);\n\t\t},\n\n\t\tset<T>(key: ContextKey<T>, value: T) {\n\t\t\tmiddlewareState.set(key.id, value);\n\t\t},\n\n\t\tget<T>(key: ContextKey<T>): T {\n\t\t\tif (!middlewareState.has(key.id)) {\n\t\t\t\tthrow new Error(`Context key not set: ${key.id.toString()}`);\n\t\t\t}\n\t\t\treturn middlewareState.get(key.id) as T;\n\t\t},\n\n\t\tgetOrNull<T>(key: ContextKey<T>): T | undefined {\n\t\t\treturn middlewareState.get(key.id) as T | undefined;\n\t\t},\n\n\t\tgetWorkflowSnapshot(): Workflow<TConfig> {\n\t\t\treturn {\n\t\t\t\tid: originalWorkflow.id,\n\t\t\t\tdefinitionName: originalWorkflow.definitionName,\n\t\t\t\tstate: mutableState,\n\t\t\t\tdata: { ...mutableData },\n\t\t\t\tcreatedAt: originalWorkflow.createdAt,\n\t\t\t\tupdatedAt: new Date(),\n\t\t\t} as Workflow<TConfig>;\n\t\t},\n\t};\n\n\treturn ctx as unknown as Context<TConfig, TDeps>;\n}\n","/** The lifecycle hook event names. */\nexport type HookEvent =\n\t| \"dispatch:start\"\n\t| \"dispatch:end\"\n\t| \"pipeline:start\"\n\t| \"pipeline:end\"\n\t| \"transition\"\n\t| \"error\"\n\t| \"event\";\n\nexport const HOOK_EVENTS: ReadonlySet<string> = new Set<HookEvent>([\n\t\"dispatch:start\",\n\t\"dispatch:end\",\n\t\"pipeline:start\",\n\t\"pipeline:end\",\n\t\"transition\",\n\t\"error\",\n\t\"event\",\n]);\n\n/**\n * Internal registry for lifecycle hook callbacks.\n * Hooks are observers — errors are caught and forwarded, never affecting dispatch.\n */\nexport class HookRegistry {\n\t// biome-ignore lint/complexity/noBannedTypes: callbacks have varying signatures per hook event\n\tprivate hooks = new Map<string, Function[]>();\n\n\t/** Register a callback for a hook event. */\n\t// biome-ignore lint/complexity/noBannedTypes: callbacks have varying signatures per hook event\n\tadd(event: string, callback: Function): void {\n\t\tconst existing = this.hooks.get(event) ?? [];\n\t\texisting.push(callback);\n\t\tthis.hooks.set(event, existing);\n\t}\n\n\t/** Emit a hook event, calling all registered callbacks. Errors are caught and forwarded. */\n\tasync emit(event: string, onError: (err: unknown) => void, ...args: unknown[]): Promise<void> {\n\t\tconst callbacks = this.hooks.get(event);\n\t\tif (!callbacks) return;\n\t\tfor (const cb of callbacks) {\n\t\t\ttry {\n\t\t\t\tawait cb(...args);\n\t\t\t} catch (err) {\n\t\t\t\tonError(err);\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Merge another registry's hooks into this one (used by composable routers). */\n\tmerge(other: HookRegistry): void {\n\t\tfor (const [event, callbacks] of other.hooks) {\n\t\t\tconst existing = this.hooks.get(event) ?? [];\n\t\t\texisting.push(...callbacks);\n\t\t\tthis.hooks.set(event, existing);\n\t\t}\n\t}\n}\n","import { compose } from \"./compose.js\";\nimport { type Context, createContext } from \"./context.js\";\nimport type { WorkflowDefinition } from \"./definition.js\";\nimport { HOOK_EVENTS, HookRegistry } from \"./hooks.js\";\nimport type { GenericPlugin, Plugin } from \"./plugin.js\";\nimport { isPlugin } from \"./plugin.js\";\nimport type { ReadonlyContext } from \"./readonly-context.js\";\nimport type {\n\tCommand,\n\tCommandNames,\n\tCommandPayload,\n\tDispatchResult,\n\tErrorCodes,\n\tErrorData,\n\tEventNames,\n\tPipelineError,\n\tStateNames,\n\tWorkflow,\n\tWorkflowConfig,\n} from \"./types.js\";\nimport { DependencyErrorSignal, DomainErrorSignal, ValidationError } from \"./types.js\";\n\n// biome-ignore lint/suspicious/noExplicitAny: internal type erasure for heterogeneous middleware storage\ntype AnyMiddleware = (ctx: any, next: () => Promise<void>) => Promise<void>;\n// biome-ignore lint/suspicious/noExplicitAny: internal type erasure for heterogeneous handler storage\ntype AnyHandler = (ctx: any) => void | Promise<void>;\n\ntype HandlerEntry = {\n\tinlineMiddleware: AnyMiddleware[];\n\thandler: AnyMiddleware;\n};\n\n/** Options for the {@link WorkflowRouter} constructor. */\nexport interface RouterOptions {\n\t/** Callback invoked when a lifecycle hook throws. Defaults to `console.error`. */\n\tonHookError?: (error: unknown) => void;\n\t/** Wrap deps in a Proxy to catch dependency errors. Defaults to `true`. */\n\twrapDeps?: boolean;\n}\n\nclass StateBuilder<TConfig extends WorkflowConfig, TDeps, TState extends StateNames<TConfig>> {\n\t/** @internal */ readonly middleware: AnyMiddleware[] = [];\n\t/** @internal */ readonly handlers = new Map<string, HandlerEntry>();\n\n\tconstructor() {\n\t\tthis.on = this.on.bind(this);\n\t\tthis.use = this.use.bind(this);\n\t}\n\n\t// Overload 1: handler only (no middleware) — covers 90% of usage\n\ton<C extends CommandNames<TConfig>>(\n\t\tcommand: C,\n\t\thandler: (ctx: Context<TConfig, TDeps, TState, C>) => void | Promise<void>,\n\t): this;\n\t// Overload 2: middleware + handler (variadic)\n\ton<C extends CommandNames<TConfig>>(\n\t\tcommand: C,\n\t\t...fns: [...AnyMiddleware[], (ctx: Context<TConfig, TDeps, TState, C>) => void | Promise<void>]\n\t): this;\n\t// Implementation\n\ton<C extends CommandNames<TConfig>>(\n\t\tcommand: C,\n\t\t...fns: [...AnyMiddleware[], (ctx: Context<TConfig, TDeps, TState, C>) => void | Promise<void>]\n\t): this {\n\t\tif (fns.length === 0) throw new Error(\"on() requires at least a handler\");\n\t\tconst handler = fns.pop() as AnyHandler;\n\t\tconst inlineMiddleware = fns as AnyMiddleware[];\n\t\tconst wrappedHandler: AnyMiddleware = async (ctx, _next) => {\n\t\t\tawait handler(ctx);\n\t\t};\n\t\tthis.handlers.set(command as string, { inlineMiddleware, handler: wrappedHandler });\n\t\treturn this;\n\t}\n\n\tuse(\n\t\tmiddleware: (ctx: Context<TConfig, TDeps, TState>, next: () => Promise<void>) => Promise<void>,\n\t): this {\n\t\tthis.middleware.push(middleware as AnyMiddleware);\n\t\treturn this;\n\t}\n}\n\n/**\n * Routes commands to handlers based on workflow state.\n *\n * Supports global middleware, state-scoped middleware, inline middleware,\n * wildcard handlers, and multi-state handlers.\n */\n// biome-ignore lint/complexity/noBannedTypes: {} is correct here — TDeps defaults to \"no deps\", inferred away when deps are provided\nexport class WorkflowRouter<TConfig extends WorkflowConfig, TDeps = {}> {\n\tprivate globalMiddleware: AnyMiddleware[] = [];\n\t// biome-ignore lint/suspicious/noExplicitAny: type erasure — builders store handlers for different state types\n\tprivate singleStateBuilders = new Map<string, StateBuilder<TConfig, TDeps, any>>();\n\t// biome-ignore lint/suspicious/noExplicitAny: type erasure — builders store handlers for different state types\n\tprivate multiStateBuilders = new Map<string, StateBuilder<TConfig, TDeps, any>>();\n\tprivate wildcardHandlers = new Map<string, HandlerEntry>();\n\tprivate hookRegistry = new HookRegistry();\n\tprivate readonly onHookError: (error: unknown) => void;\n\tprivate readonly wrapDeps: boolean;\n\n\t/**\n\t * @param definition - The workflow definition describing states, commands, events, and errors\n\t * @param deps - Dependencies injected into every handler context\n\t * @param options - Router configuration options\n\t */\n\tconstructor(\n\t\tpublic readonly definition: WorkflowDefinition<TConfig>,\n\t\tprivate readonly deps: TDeps = {} as TDeps,\n\t\toptions: RouterOptions = {},\n\t) {\n\t\tthis.onHookError = options.onHookError ?? console.error;\n\t\tthis.wrapDeps = options.wrapDeps !== false;\n\t}\n\n\t/**\n\t * Adds global middleware, merges another router, or applies a plugin.\n\t * @param arg - A middleware function, another {@link WorkflowRouter} to merge, or a {@link Plugin}\n\t */\n\tuse(\n\t\targ:\n\t\t\t| ((ctx: Context<TConfig, TDeps>, next: () => Promise<void>) => Promise<void>)\n\t\t\t| WorkflowRouter<TConfig, TDeps>\n\t\t\t| Plugin<TConfig, TDeps>\n\t\t\t| GenericPlugin,\n\t): this {\n\t\tif (arg instanceof WorkflowRouter) {\n\t\t\tthis.merge(arg);\n\t\t} else if (isPlugin(arg)) {\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: plugin may be GenericPlugin (Plugin<any,any>) or Plugin<TConfig,TDeps> — both are called with this router at runtime\n\t\t\t(arg as any)(this);\n\t\t} else {\n\t\t\tthis.globalMiddleware.push(arg as AnyMiddleware);\n\t\t}\n\t\treturn this;\n\t}\n\n\tprivate merge(child: WorkflowRouter<TConfig, TDeps>): void {\n\t\tif (child.definition !== this.definition) {\n\t\t\tthrow new Error(\n\t\t\t\t`Cannot merge router for '${child.definition.name}' into router for '${this.definition.name}': definition mismatch`,\n\t\t\t);\n\t\t}\n\n\t\tthis.globalMiddleware.push(...child.globalMiddleware);\n\t\tthis.mergeStateBuilders(this.singleStateBuilders, child.singleStateBuilders);\n\t\tthis.mergeStateBuilders(this.multiStateBuilders, child.multiStateBuilders);\n\n\t\tfor (const [command, entry] of child.wildcardHandlers) {\n\t\t\tif (!this.wildcardHandlers.has(command)) {\n\t\t\t\tthis.wildcardHandlers.set(command, {\n\t\t\t\t\tinlineMiddleware: [...entry.inlineMiddleware],\n\t\t\t\t\thandler: entry.handler,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\tthis.hookRegistry.merge(child.hookRegistry);\n\t}\n\n\tprivate mergeStateBuilders(\n\t\t// biome-ignore lint/suspicious/noExplicitAny: type erasure — builders store handlers for different state types\n\t\ttarget: Map<string, StateBuilder<TConfig, TDeps, any>>,\n\t\t// biome-ignore lint/suspicious/noExplicitAny: type erasure — builders store handlers for different state types\n\t\tsource: Map<string, StateBuilder<TConfig, TDeps, any>>,\n\t): void {\n\t\tfor (const [stateName, childBuilder] of source) {\n\t\t\tlet parentBuilder = target.get(stateName);\n\t\t\tif (!parentBuilder) {\n\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: type erasure — state name is dynamic at runtime\n\t\t\t\tparentBuilder = new StateBuilder<TConfig, TDeps, any>();\n\t\t\t\ttarget.set(stateName, parentBuilder);\n\t\t\t}\n\t\t\tfor (const [command, entry] of childBuilder.handlers) {\n\t\t\t\tif (!parentBuilder.handlers.has(command)) {\n\t\t\t\t\tparentBuilder.handlers.set(command, {\n\t\t\t\t\t\tinlineMiddleware: [...entry.inlineMiddleware],\n\t\t\t\t\t\thandler: entry.handler,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\tparentBuilder.middleware.push(...childBuilder.middleware);\n\t\t}\n\t}\n\n\t/**\n\t * Registers handlers for one or more states.\n\t * @param name - A state name or array of state names to register handlers for\n\t * @param setup - Callback that receives a state builder to register commands and middleware\n\t */\n\tstate<P extends StateNames<TConfig> | readonly StateNames<TConfig>[]>(\n\t\tname: P,\n\t\tsetup: (\n\t\t\tstate: StateBuilder<\n\t\t\t\tTConfig,\n\t\t\t\tTDeps,\n\t\t\t\tP extends readonly (infer S)[] ? S & StateNames<TConfig> : P & StateNames<TConfig>\n\t\t\t>,\n\t\t) => void,\n\t): this {\n\t\tconst names = Array.isArray(name) ? name : [name];\n\t\tconst isMulti = Array.isArray(name);\n\t\tconst routerMap = isMulti ? this.multiStateBuilders : this.singleStateBuilders;\n\n\t\tfor (const n of names as string[]) {\n\t\t\tlet router = routerMap.get(n);\n\t\t\tif (!router) {\n\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: type erasure — state name is dynamic at runtime\n\t\t\t\trouter = new StateBuilder<TConfig, TDeps, any>();\n\t\t\t\trouterMap.set(n, router);\n\t\t\t}\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: type erasure — setup callback expects a specific state type\n\t\t\tsetup(router as any);\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Registers a lifecycle hook callback.\n\t * @param event - The lifecycle event name\n\t * @param callback - The callback to invoke when the event fires\n\t */\n\ton(\n\t\tevent: \"dispatch:start\",\n\t\tcallback: (workflow: Workflow<TConfig>, command: Command<TConfig>) => void | Promise<void>,\n\t): this;\n\ton(\n\t\tevent: \"dispatch:end\",\n\t\tcallback: (\n\t\t\tworkflow: Workflow<TConfig>,\n\t\t\tcommand: Command<TConfig>,\n\t\t\tresult: DispatchResult<TConfig>,\n\t\t) => void | Promise<void>,\n\t): this;\n\ton(\n\t\tevent: \"pipeline:start\",\n\t\tcallback: (ctx: ReadonlyContext<TConfig, TDeps>) => void | Promise<void>,\n\t): this;\n\ton(\n\t\tevent: \"pipeline:end\",\n\t\tcallback: (\n\t\t\tctx: ReadonlyContext<TConfig, TDeps>,\n\t\t\tresult: DispatchResult<TConfig>,\n\t\t) => void | Promise<void>,\n\t): this;\n\ton(\n\t\tevent: \"transition\",\n\t\tcallback: (\n\t\t\tfrom: StateNames<TConfig>,\n\t\t\tto: StateNames<TConfig>,\n\t\t\tworkflow: Workflow<TConfig>,\n\t\t) => void | Promise<void>,\n\t): this;\n\ton(\n\t\tevent: \"error\",\n\t\tcallback: (\n\t\t\terror: PipelineError<TConfig>,\n\t\t\tctx: ReadonlyContext<TConfig, TDeps>,\n\t\t) => void | Promise<void>,\n\t): this;\n\ton(\n\t\tevent: \"event\",\n\t\tcallback: (\n\t\t\tevent: { type: EventNames<TConfig>; data: unknown },\n\t\t\tworkflow: Workflow<TConfig>,\n\t\t) => void | Promise<void>,\n\t): this;\n\t/**\n\t * Registers a wildcard handler that matches any state.\n\t * @param state - Must be `\"*\"` to match all states\n\t * @param command - The command name to handle\n\t * @param handler - The terminal handler\n\t */\n\ton<C extends CommandNames<TConfig>>(\n\t\tstate: \"*\",\n\t\tcommand: C,\n\t\thandler: (ctx: Context<TConfig, TDeps, StateNames<TConfig>, C>) => void | Promise<void>,\n\t): this;\n\t/**\n\t * Registers a wildcard handler that matches any state, with inline middleware.\n\t * @param state - Must be `\"*\"` to match all states\n\t * @param command - The command name to handle\n\t * @param fns - Inline middleware followed by the terminal handler\n\t */\n\ton<C extends CommandNames<TConfig>>(\n\t\tstate: \"*\",\n\t\tcommand: C,\n\t\t...fns: [\n\t\t\t...AnyMiddleware[],\n\t\t\t(ctx: Context<TConfig, TDeps, StateNames<TConfig>, C>) => void | Promise<void>,\n\t\t]\n\t): this;\n\t// biome-ignore lint/suspicious/noExplicitAny: implementation signature must be loose to handle all overloads\n\ton(...args: any[]): this {\n\t\tconst first = args[0] as string;\n\n\t\tif (HOOK_EVENTS.has(first)) {\n\t\t\t// biome-ignore lint/complexity/noBannedTypes: callbacks have varying signatures per hook event\n\t\t\tthis.hookRegistry.add(first, args[1] as Function);\n\t\t\treturn this;\n\t\t}\n\n\t\tif (first === \"*\") {\n\t\t\tconst command = args[1] as string;\n\t\t\tconst fns = args.slice(2) as unknown[];\n\t\t\tif (fns.length === 0) throw new Error(\"on() requires at least a handler\");\n\t\t\tconst handler = fns.pop() as AnyHandler;\n\t\t\tconst inlineMiddleware = fns as AnyMiddleware[];\n\t\t\tconst wrappedHandler: AnyMiddleware = async (ctx, _next) => {\n\t\t\t\tawait handler(ctx);\n\t\t\t};\n\t\t\tthis.wildcardHandlers.set(command, {\n\t\t\t\tinlineMiddleware,\n\t\t\t\thandler: wrappedHandler,\n\t\t\t});\n\t\t\treturn this;\n\t\t}\n\n\t\tthrow new Error(`Unknown event or state: ${first}`);\n\t}\n\n\t/**\n\t * Dispatches a command to the appropriate handler and returns the result.\n\t * @param workflow - The current workflow instance to dispatch against\n\t * @param command - The command with its type and payload\n\t * @returns A {@link DispatchResult} indicating success or failure with the updated workflow and events\n\t */\n\tasync dispatch<C extends CommandNames<TConfig>>(\n\t\tworkflow: Workflow<TConfig>,\n\t\ttype: C,\n\t\tpayload: CommandPayload<TConfig, C>,\n\t): Promise<DispatchResult<TConfig>> {\n\t\tconst command = { type, payload };\n\t\t// Hook: dispatch:start (fires before any validation)\n\t\tawait this.hookRegistry.emit(\"dispatch:start\", this.onHookError, workflow, command);\n\n\t\tlet result: DispatchResult<TConfig>;\n\t\ttry {\n\t\t\tresult = await this.executePipeline(workflow, command);\n\t\t} catch (err) {\n\t\t\tresult = {\n\t\t\t\tok: false as const,\n\t\t\t\terror: {\n\t\t\t\t\tcategory: \"unexpected\" as const,\n\t\t\t\t\terror: err,\n\t\t\t\t\tmessage: err instanceof Error ? err.message : String(err),\n\t\t\t\t},\n\t\t\t};\n\t\t} finally {\n\t\t\t// Hook: dispatch:end (guaranteed to fire if dispatch:start fired)\n\t\t\t// biome-ignore lint/style/noNonNullAssertion: result is always assigned — either by try or catch\n\t\t\tawait this.hookRegistry.emit(\"dispatch:end\", this.onHookError, workflow, command, result!);\n\t\t}\n\t\treturn result;\n\t}\n\n\tprivate async executePipeline(\n\t\tworkflow: Workflow<TConfig>,\n\t\tcommand: { type: CommandNames<TConfig>; payload: unknown },\n\t): Promise<DispatchResult<TConfig>> {\n\t\tif (!this.definition.hasState(workflow.state)) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\terror: {\n\t\t\t\t\tcategory: \"router\",\n\t\t\t\t\tcode: \"UNKNOWN_STATE\",\n\t\t\t\t\tmessage: `Unknown state: ${workflow.state}`,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\tconst commandSchema = this.definition.getCommandSchema(command.type);\n\t\tconst payloadResult = commandSchema.safeParse(command.payload);\n\t\tif (!payloadResult.success) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\terror: {\n\t\t\t\t\tcategory: \"validation\",\n\t\t\t\t\tsource: \"command\",\n\t\t\t\t\tissues: payloadResult.error.issues,\n\t\t\t\t\tmessage: `Invalid command payload: ${payloadResult.error.issues.map((i) => i.message).join(\", \")}`,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\tconst validatedCommand = { type: command.type, payload: payloadResult.data };\n\n\t\tconst stateName = workflow.state;\n\t\tconst singleRouter = this.singleStateBuilders.get(stateName);\n\t\tconst multiRouter = this.multiStateBuilders.get(stateName);\n\t\tconst singleHandler = singleRouter?.handlers.get(command.type);\n\t\tconst multiHandler = multiRouter?.handlers.get(command.type);\n\t\tconst wildcardHandler = this.wildcardHandlers.get(command.type);\n\n\t\tlet routeEntry: HandlerEntry | undefined;\n\t\t// biome-ignore lint/suspicious/noExplicitAny: type erasure — matched router's state type is dynamic\n\t\tlet matchedRouter: StateBuilder<TConfig, TDeps, any> | undefined;\n\n\t\tif (singleHandler) {\n\t\t\trouteEntry = singleHandler;\n\t\t\tmatchedRouter = singleRouter;\n\t\t} else if (multiHandler) {\n\t\t\trouteEntry = multiHandler;\n\t\t\tmatchedRouter = multiRouter;\n\t\t} else if (wildcardHandler) {\n\t\t\trouteEntry = wildcardHandler;\n\t\t\tmatchedRouter = undefined;\n\t\t}\n\n\t\tif (!routeEntry) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\terror: {\n\t\t\t\t\tcategory: \"router\",\n\t\t\t\t\tcode: \"NO_HANDLER\",\n\t\t\t\t\tmessage: `No handler for command '${command.type}' in state '${stateName}'`,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\tconst stateMiddleware: AnyMiddleware[] = [];\n\t\tif (matchedRouter) {\n\t\t\tif (singleRouter) stateMiddleware.push(...singleRouter.middleware);\n\t\t\tif (multiRouter && multiRouter !== singleRouter)\n\t\t\t\tstateMiddleware.push(...multiRouter.middleware);\n\t\t}\n\n\t\tconst chain: AnyMiddleware[] = [\n\t\t\t...this.globalMiddleware,\n\t\t\t...stateMiddleware,\n\t\t\t...routeEntry.inlineMiddleware,\n\t\t\trouteEntry.handler,\n\t\t];\n\n\t\tconst ctx = createContext<TConfig, TDeps>(\n\t\t\tthis.definition,\n\t\t\tworkflow,\n\t\t\tvalidatedCommand,\n\t\t\tthis.deps,\n\t\t\t{ wrapDeps: this.wrapDeps },\n\t\t);\n\n\t\t// Hook: pipeline:start\n\t\tawait this.hookRegistry.emit(\"pipeline:start\", this.onHookError, ctx);\n\n\t\ttry {\n\t\t\tconst composed = compose(chain);\n\t\t\tawait composed(ctx);\n\t\t\tconst result: DispatchResult<TConfig> = {\n\t\t\t\tok: true as const,\n\t\t\t\tworkflow: ctx.getWorkflowSnapshot(),\n\t\t\t\tevents: [...ctx.events],\n\t\t\t};\n\n\t\t\t// Hook: transition (if state changed)\n\t\t\tif (result.ok && result.workflow.state !== workflow.state) {\n\t\t\t\tawait this.hookRegistry.emit(\n\t\t\t\t\t\"transition\",\n\t\t\t\t\tthis.onHookError,\n\t\t\t\t\tworkflow.state,\n\t\t\t\t\tresult.workflow.state,\n\t\t\t\t\tresult.workflow,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Hook: event (for each emitted event)\n\t\t\tif (result.ok) {\n\t\t\t\tfor (const event of result.events) {\n\t\t\t\t\tawait this.hookRegistry.emit(\"event\", this.onHookError, event, result.workflow);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Hook: pipeline:end\n\t\t\tawait this.hookRegistry.emit(\"pipeline:end\", this.onHookError, ctx, result);\n\n\t\t\treturn result;\n\t\t} catch (err) {\n\t\t\tlet result: DispatchResult<TConfig>;\n\t\t\tif (err instanceof DomainErrorSignal) {\n\t\t\t\tresult = {\n\t\t\t\t\tok: false as const,\n\t\t\t\t\terror: {\n\t\t\t\t\t\tcategory: \"domain\" as const,\n\t\t\t\t\t\tcode: err.code as ErrorCodes<TConfig>,\n\t\t\t\t\t\tdata: err.data as ErrorData<TConfig, ErrorCodes<TConfig>>,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t} else if (err instanceof ValidationError) {\n\t\t\t\tresult = {\n\t\t\t\t\tok: false as const,\n\t\t\t\t\terror: {\n\t\t\t\t\t\tcategory: \"validation\" as const,\n\t\t\t\t\t\tsource: err.source,\n\t\t\t\t\t\tissues: err.issues,\n\t\t\t\t\t\tmessage: err.message,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t} else if (err instanceof DependencyErrorSignal) {\n\t\t\t\tresult = {\n\t\t\t\t\tok: false as const,\n\t\t\t\t\terror: {\n\t\t\t\t\t\tcategory: \"dependency\" as const,\n\t\t\t\t\t\tname: err.depName,\n\t\t\t\t\t\terror: err.error,\n\t\t\t\t\t\tmessage: err.message,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t} else {\n\t\t\t\tresult = {\n\t\t\t\t\tok: false as const,\n\t\t\t\t\terror: {\n\t\t\t\t\t\tcategory: \"unexpected\" as const,\n\t\t\t\t\t\terror: err,\n\t\t\t\t\t\tmessage: err instanceof Error ? err.message : String(err),\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Hook: error\n\t\t\tawait this.hookRegistry.emit(\"error\", this.onHookError, result.error, ctx);\n\n\t\t\t// Hook: pipeline:end\n\t\t\tawait this.hookRegistry.emit(\"pipeline:end\", this.onHookError, ctx, result);\n\n\t\t\treturn result;\n\t\t}\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCA,iBAAkB;AAElB,IAAM,eAA8B,uBAAO,aAAa;AAYjD,SAAS,OAA0B,QAAsB;AAE/D,QAAM,UAAU,OAAO,OAAO,MAAM;AACpC,UAAQ,YAAY,IAAI;AACxB,SAAO;AACR;AAGO,SAAS,cAAc,QAA0B;AAEvD,SAAQ,OAAe,YAAY,MAAM;AAC1C;AAqBO,SAAS,gBACf,QACA,MAC0B;AAE1B,QAAM,MAAO,OAAe,MAAM;AAClC,MAAI,KAAK,SAAS,YAAY,CAAC,IAAI,MAAO,QAAO;AAEjD,QAAM,SAAkC,CAAC;AACzC,aAAW,OAAO,OAAO,KAAK,IAAI,GAAG;AACpC,UAAM,cAAc,IAAI,MAAM,GAAG;AACjC,QAAI,eAAe,cAAc,WAAW,EAAG;AAE/C,QACC;AAAA,IAEC,YAAoB,MAAM,KAAK,SAAS,YACzC,KAAK,GAAG,MAAM,QACd,OAAO,KAAK,GAAG,MAAM,UACpB;AACD,aAAO,GAAG,IAAI,gBAAgB,aAAa,KAAK,GAAG,CAA4B;AAAA,IAChF,OAAO;AACN,aAAO,GAAG,IAAI,KAAK,GAAG;AAAA,IACvB;AAAA,EACD;AACA,SAAO;AACR;AAOO,SAAS,mBAAmB,QAA0B;AAE5D,QAAM,MAAO,OAAe,MAAM;AAClC,MAAI,KAAK,SAAS,YAAY,CAAC,IAAI,MAAO,QAAO;AAEjD,QAAM,cAAuC,CAAC;AAC9C,aAAW,CAAC,KAAK,WAAW,KAAK,OAAO,QAAQ,IAAI,KAA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GzE,YAAM,KAAK,aAAa,KAAK,gBAAgB,KAAK,aAAa,KAAK,MAAM;AAE1E,aAAO;AAAA,IACR;AAAA,EACD;AACD;","names":[]}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { C as Context, W as WorkflowDefinition } from './plugin-
|
|
2
|
-
export { a as ClientWorkflowDefinition, b as ContextKey, G as GenericPlugin, P as Plugin, R as ReadonlyContext, c as RouterOptions, S as Server, d as WorkflowRouter, e as createKey, f as defineGenericPlugin, g as definePlugin, h as defineWorkflow, i as isPlugin, j as isServerField, s as server } from './plugin-
|
|
1
|
+
import { C as Context, W as WorkflowDefinition } from './plugin-CGikcWDu.cjs';
|
|
2
|
+
export { a as ClientWorkflowDefinition, b as ContextKey, G as GenericPlugin, P as Plugin, R as ReadonlyContext, c as RouterOptions, S as Server, d as WorkflowRouter, e as createKey, f as defineGenericPlugin, g as definePlugin, h as defineWorkflow, i as isPlugin, j as isServerField, s as server } from './plugin-CGikcWDu.cjs';
|
|
3
3
|
import { W as WorkflowConfig, S as StateNames, C as CommandNames, a as WorkflowSnapshot } from './snapshot-6pxxtOjB.cjs';
|
|
4
4
|
export { b as ClientStateData, c as ClientWorkflow, d as ClientWorkflowOf, e as Command, f as CommandPayload, g as ConfigOf, D as DispatchResult, h as DomainErrorSignal, E as ErrorCodes, i as ErrorData, j as EventData, k as EventNames, P as PipelineError, l as StateData, V as ValidationError, m as Workflow, n as WorkflowOf } from './snapshot-6pxxtOjB.cjs';
|
|
5
5
|
import 'zod';
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { C as Context, W as WorkflowDefinition } from './plugin-
|
|
2
|
-
export { a as ClientWorkflowDefinition, b as ContextKey, G as GenericPlugin, P as Plugin, R as ReadonlyContext, c as RouterOptions, S as Server, d as WorkflowRouter, e as createKey, f as defineGenericPlugin, g as definePlugin, h as defineWorkflow, i as isPlugin, j as isServerField, s as server } from './plugin-
|
|
1
|
+
import { C as Context, W as WorkflowDefinition } from './plugin-ByX9Eoe-.js';
|
|
2
|
+
export { a as ClientWorkflowDefinition, b as ContextKey, G as GenericPlugin, P as Plugin, R as ReadonlyContext, c as RouterOptions, S as Server, d as WorkflowRouter, e as createKey, f as defineGenericPlugin, g as definePlugin, h as defineWorkflow, i as isPlugin, j as isServerField, s as server } from './plugin-ByX9Eoe-.js';
|
|
3
3
|
import { W as WorkflowConfig, S as StateNames, C as CommandNames, a as WorkflowSnapshot } from './snapshot-6pxxtOjB.js';
|
|
4
4
|
export { b as ClientStateData, c as ClientWorkflow, d as ClientWorkflowOf, e as Command, f as CommandPayload, g as ConfigOf, D as DispatchResult, h as DomainErrorSignal, E as ErrorCodes, i as ErrorData, j as EventData, k as EventNames, P as PipelineError, l as StateData, V as ValidationError, m as Workflow, n as WorkflowOf } from './snapshot-6pxxtOjB.js';
|
|
5
5
|
import 'zod';
|
package/dist/index.js
CHANGED
|
@@ -457,6 +457,9 @@ function createContext(definition, originalWorkflow, command, deps, options) {
|
|
|
457
457
|
command,
|
|
458
458
|
workflow: originalWorkflow,
|
|
459
459
|
deps: options?.wrapDeps !== false && deps != null && typeof deps === "object" ? wrapDeps(deps) : deps,
|
|
460
|
+
get state() {
|
|
461
|
+
return mutableState;
|
|
462
|
+
},
|
|
460
463
|
get data() {
|
|
461
464
|
return { ...mutableData };
|
|
462
465
|
},
|
|
@@ -471,7 +474,14 @@ function createContext(definition, originalWorkflow, command, deps, options) {
|
|
|
471
474
|
},
|
|
472
475
|
transition(target, data) {
|
|
473
476
|
if (!definition.hasState(target)) {
|
|
474
|
-
throw new
|
|
477
|
+
throw new ValidationError("transition", [
|
|
478
|
+
{
|
|
479
|
+
code: "custom",
|
|
480
|
+
message: `Unknown state: ${target}`,
|
|
481
|
+
input: target,
|
|
482
|
+
path: ["state"]
|
|
483
|
+
}
|
|
484
|
+
]);
|
|
475
485
|
}
|
|
476
486
|
const schema = definition.getStateSchema(target);
|
|
477
487
|
const result = schema.safeParse(data);
|
|
@@ -481,26 +491,30 @@ function createContext(definition, originalWorkflow, command, deps, options) {
|
|
|
481
491
|
mutableState = target;
|
|
482
492
|
mutableData = result.data;
|
|
483
493
|
},
|
|
484
|
-
emit(
|
|
485
|
-
const schema = definition.getEventSchema(
|
|
486
|
-
const result = schema.safeParse(
|
|
494
|
+
emit(type, data) {
|
|
495
|
+
const schema = definition.getEventSchema(type);
|
|
496
|
+
const result = schema.safeParse(data);
|
|
487
497
|
if (!result.success) {
|
|
488
498
|
throw new ValidationError("event", result.error.issues);
|
|
489
499
|
}
|
|
490
|
-
accumulatedEvents.push({ type
|
|
500
|
+
accumulatedEvents.push({ type, data: result.data });
|
|
491
501
|
},
|
|
492
502
|
get events() {
|
|
493
503
|
return [...accumulatedEvents];
|
|
494
504
|
},
|
|
495
|
-
error(
|
|
496
|
-
const schema = definition.getErrorSchema(
|
|
497
|
-
const result = schema.safeParse(
|
|
505
|
+
error(code, data) {
|
|
506
|
+
const schema = definition.getErrorSchema(code);
|
|
507
|
+
const result = schema.safeParse(data);
|
|
498
508
|
if (!result.success) {
|
|
499
|
-
throw new
|
|
500
|
-
`Invalid error data for '${err.code}': ${result.error.issues.map((i) => i.message).join(", ")}`
|
|
501
|
-
);
|
|
509
|
+
throw new ValidationError("state", result.error.issues);
|
|
502
510
|
}
|
|
503
|
-
throw new DomainErrorSignal(
|
|
511
|
+
throw new DomainErrorSignal(code, result.data);
|
|
512
|
+
},
|
|
513
|
+
match(matchers, fallback) {
|
|
514
|
+
const matcher = matchers[originalWorkflow.state];
|
|
515
|
+
if (matcher) return matcher(ctx.data, originalWorkflow);
|
|
516
|
+
if (fallback) return fallback();
|
|
517
|
+
throw new Error(`No matcher for state: ${originalWorkflow.state}`);
|
|
504
518
|
},
|
|
505
519
|
set(key, value) {
|
|
506
520
|
middlewareState.set(key.id, value);
|
|
@@ -717,7 +731,8 @@ var WorkflowRouter = class _WorkflowRouter {
|
|
|
717
731
|
* @param command - The command with its type and payload
|
|
718
732
|
* @returns A {@link DispatchResult} indicating success or failure with the updated workflow and events
|
|
719
733
|
*/
|
|
720
|
-
async dispatch(workflow,
|
|
734
|
+
async dispatch(workflow, type, payload) {
|
|
735
|
+
const command = { type, payload };
|
|
721
736
|
await this.hookRegistry.emit("dispatch:start", this.onHookError, workflow, command);
|
|
722
737
|
let result;
|
|
723
738
|
try {
|