Skip to content

core/src

Namespaces

Classes

DomainErrorSignal

Defined in: packages/core/src/types.ts:162

Thrown internally when a handler calls ctx.error(). Caught by the router and returned as a domain error in DispatchResult.

Param

The error code string

Param

The error data payload

Extends

  • Error

Constructors

Constructor

new DomainErrorSignal(code, data): DomainErrorSignal

Defined in: packages/core/src/types.ts:163

Parameters
code

string

data

unknown

Returns

DomainErrorSignal

Overrides

Error.constructor

Properties

cause?

optional cause?: unknown

Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es2022.error.d.ts:26

Inherited from

Error.cause

code

readonly code: string

Defined in: packages/core/src/types.ts:164

data

readonly data: unknown

Defined in: packages/core/src/types.ts:165

message

message: string

Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es5.d.ts:1077

Inherited from

Error.message

name

name: string

Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es5.d.ts:1076

Inherited from

Error.name

stack?

optional stack?: string

Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es5.d.ts:1078

Inherited from

Error.stack


MigrationError

Defined in: packages/core/src/migration.ts:55

Error thrown when a migration step fails.

Extends

  • Error

Constructors

Constructor

new MigrationError(fromVersion, toVersion, cause): MigrationError

Defined in: packages/core/src/migration.ts:61

Parameters
fromVersion

number

The schema version the migration started from

toVersion

number

The schema version the migration was attempting to reach

cause

unknown

The underlying error that caused the failure

Returns

MigrationError

Overrides

Error.constructor

Properties

cause

readonly cause: unknown

Defined in: packages/core/src/migration.ts:64

The underlying error that caused the failure

Inherited from

Error.cause

fromVersion

readonly fromVersion: number

Defined in: packages/core/src/migration.ts:62

The schema version the migration started from

message

message: string

Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es5.d.ts:1077

Inherited from

Error.message

name

name: string

Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es5.d.ts:1076

Inherited from

Error.name

stack?

optional stack?: string

Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es5.d.ts:1078

Inherited from

Error.stack

toVersion

readonly toVersion: number

Defined in: packages/core/src/migration.ts:63

The schema version the migration was attempting to reach


ValidationError

Defined in: packages/core/src/types.ts:145

Thrown internally when schema validation fails during dispatch. Caught by the router and returned as a validation error in DispatchResult.

Param

Which validation stage failed

Param

Validator-agnostic issue array (Standard Schema shape)

Extends

  • Error

Constructors

Constructor

new ValidationError(source, issues): ValidationError

Defined in: packages/core/src/types.ts:146

Parameters
source

"command" | "state" | "event" | "transition" | "restore"

issues

readonly Issue[]

Returns

ValidationError

Overrides

Error.constructor

Properties

cause?

optional cause?: unknown

Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es2022.error.d.ts:26

Inherited from

Error.cause

issues

readonly issues: readonly Issue[]

Defined in: packages/core/src/types.ts:148

message

message: string

Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es5.d.ts:1077

Inherited from

Error.message

name

name: string

Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es5.d.ts:1076

Inherited from

Error.name

source

readonly source: "command" | "state" | "event" | "transition" | "restore"

Defined in: packages/core/src/types.ts:147

stack?

optional stack?: string

Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es5.d.ts:1078

Inherited from

Error.stack


WorkflowRouter

Defined in: packages/core/src/router.ts:91

Routes commands to handlers based on workflow state.

Supports global middleware, state-scoped middleware, inline middleware, wildcard handlers, and multi-state handlers.

Type Parameters

TConfig

TConfig extends WorkflowConfig

TDeps

TDeps = { }

Constructors

Constructor

new WorkflowRouter<TConfig, TDeps>(definition, deps?, options?): WorkflowRouter<TConfig, TDeps>

Defined in: packages/core/src/router.ts:107

Parameters
definition

WorkflowDefinition<TConfig>

The workflow definition describing states, commands, events, and errors

deps?

TDeps = ...

Dependencies injected into every handler context

options?

RouterOptions = {}

Router configuration options

Returns

WorkflowRouter<TConfig, TDeps>

Properties

definition

readonly definition: WorkflowDefinition<TConfig>

Defined in: packages/core/src/router.ts:108

The workflow definition describing states, commands, events, and errors

Methods

dispatch()

dispatch<C>(workflow, type, payload): Promise<DispatchResult<TConfig>>

Defined in: packages/core/src/router.ts:336

Dispatches a command to the appropriate handler and returns the result.

Type Parameters
C

C extends string

Parameters
workflow

Workflow<TConfig>

The current workflow instance to dispatch against

type

C

payload

CommandPayload<TConfig, C>

Returns

Promise<DispatchResult<TConfig>>

A DispatchResult indicating success or failure with the updated workflow and events

on()
Call Signature

on(event, callback): this

Defined in: packages/core/src/router.ts:231

Registers a lifecycle hook callback.

Parameters
event

"dispatch:start"

The lifecycle event name

callback

(workflow, command) => void | Promise<void>

The callback to invoke when the event fires

Returns

this

Call Signature

on(event, callback): this

Defined in: packages/core/src/router.ts:235

Registers a lifecycle hook callback.

Parameters
event

"dispatch:end"

The lifecycle event name

callback

(workflow, command, result) => void | Promise<void>

The callback to invoke when the event fires

Returns

this

Call Signature

on(event, callback): this

Defined in: packages/core/src/router.ts:243

Registers a lifecycle hook callback.

Parameters
event

"pipeline:start"

The lifecycle event name

callback

(ctx) => void | Promise<void>

The callback to invoke when the event fires

Returns

this

Call Signature

on(event, callback): this

Defined in: packages/core/src/router.ts:247

Registers a lifecycle hook callback.

Parameters
event

"pipeline:end"

The lifecycle event name

callback

(ctx, result) => void | Promise<void>

The callback to invoke when the event fires

Returns

this

Call Signature

on(event, callback): this

Defined in: packages/core/src/router.ts:254

Registers a lifecycle hook callback.

Parameters
event

"transition"

The lifecycle event name

callback

(from, to, workflow) => void | Promise<void>

The callback to invoke when the event fires

Returns

this

Call Signature

on(event, callback): this

Defined in: packages/core/src/router.ts:262

Registers a lifecycle hook callback.

Parameters
event

"error"

The lifecycle event name

callback

(error, ctx) => void | Promise<void>

The callback to invoke when the event fires

Returns

this

Call Signature

on(event, callback): this

Defined in: packages/core/src/router.ts:269

Registers a lifecycle hook callback.

Parameters
event

"event"

The lifecycle event name

callback

(event, workflow) => void | Promise<void>

The callback to invoke when the event fires

Returns

this

Call Signature

on<C>(state, command, handler): this

Defined in: packages/core/src/router.ts:282

Registers a wildcard handler that matches any state.

Type Parameters
C

C extends string

Parameters
state

"*"

Must be "*" to match all states

command

C

The command name to handle

handler

(ctx) => void | Promise<void>

The terminal handler

Returns

this

Call Signature

on<C>(state, command, ...fns): this

Defined in: packages/core/src/router.ts:293

Registers a wildcard handler that matches any state, with inline middleware.

Type Parameters
C

C extends string

Parameters
state

"*"

Must be "*" to match all states

command

C

The command name to handle

fns

...[...AnyMiddleware[], (ctx) => void | Promise<void>]

Inline middleware followed by the terminal handler

Returns

this

state()
Call Signature

state<S>(name, setup): this

Defined in: packages/core/src/router.ts:191

Registers handlers for a single state.

Type Parameters
S

S extends string

Parameters
name

S

State name to register handlers for

setup

(state) => void

Callback that receives a state builder to register commands and middleware

Returns

this

Call Signature

state<S>(names, setup): this

Defined in: packages/core/src/router.ts:200

Registers handlers for multiple states.

Type Parameters
S

S extends string

Parameters
names

readonly S[]

Array of state names to register handlers for

setup

(state) => void

Callback that receives a state builder to register commands and middleware

Returns

this

use()

use(arg): this

Defined in: packages/core/src/router.ts:120

Adds global middleware, merges another router, or applies a plugin.

Parameters
arg

WorkflowRouter<TConfig, TDeps> | Plugin<TConfig, TDeps> | GenericPlugin | ((ctx, next) => Promise<void>)

A middleware function, another WorkflowRouter to merge, or a Plugin

Returns

this

Interfaces

ClientWorkflowDefinition

Defined in: packages/core/src/definition.ts:115

A client-safe projection of a workflow definition. Server-declared fields are stripped by serializeForClient(); this projection deserialises snapshots without re-validation (snapshots come from a trusted server and should not be mutated in transit). Consumers wanting defence-in-depth should validate manually before calling deserialize.

Type Parameters

TConfig

TConfig extends WorkflowConfig = WorkflowConfig

Properties

config

readonly config: TConfig

Defined in: packages/core/src/definition.ts:117

The raw schema configuration.

name

readonly name: string

Defined in: packages/core/src/definition.ts:118

Methods

deserialize()

deserialize(snapshot): { ok: true; workflow: ClientWorkflow<TConfig>; } | { error: ValidationError; ok: false; }

Defined in: packages/core/src/definition.ts:120

Parameters
snapshot

WorkflowSnapshot<TConfig>

Returns

{ ok: true; workflow: ClientWorkflow<TConfig>; } | { error: ValidationError; ok: false; }

hasState()

hasState(stateName): boolean

Defined in: packages/core/src/definition.ts:119

Parameters
stateName

string

Returns

boolean


ClientWorkflowOf

Defined in: packages/core/src/types.ts:52

Client-side workflow narrowed to a specific known state.

Type Parameters

TConfig

TConfig extends WorkflowConfig

S

S extends StateNames<TConfig>

Properties

createdAt

readonly createdAt: Date

Defined in: packages/core/src/types.ts:57

data

readonly data: ClientStateData<TConfig, S>

Defined in: packages/core/src/types.ts:56

definitionName

readonly definitionName: string

Defined in: packages/core/src/types.ts:54

id

readonly id: string

Defined in: packages/core/src/types.ts:53

state

readonly state: S

Defined in: packages/core/src/types.ts:55

updatedAt

readonly updatedAt: Date

Defined in: packages/core/src/types.ts:58


Context

Defined in: packages/core/src/context.ts:21

Mutable context flowing through the middleware pipeline during dispatch.

Type Parameters

TConfig

TConfig extends WorkflowConfig

TDeps

TDeps

TState

TState extends StateNames<TConfig> = StateNames<TConfig>

TCommand

TCommand extends CommandNames<TConfig> = CommandNames<TConfig>

Properties

command

readonly command: object

Defined in: packages/core/src/context.ts:28

The command being dispatched, with type and validated payload.

payload

readonly payload: CommandPayload<TConfig, TCommand>

type

readonly type: TCommand

data

readonly data: StateData<TConfig, TState>

Defined in: packages/core/src/context.ts:41

Current state data (reflects mutations from update).

deps

readonly deps: TDeps

Defined in: packages/core/src/context.ts:35

Dependencies injected via the router constructor.

events

readonly events: readonly object[]

Defined in: packages/core/src/context.ts:68

Accumulated events emitted during this dispatch.

payload

readonly payload: CommandPayload<TConfig, TCommand>

Defined in: packages/core/src/context.ts:38

Validated command payload (shorthand for command.payload).

state

readonly state: TState

Defined in: packages/core/src/context.ts:59

Current state name (reflects mutations from transition).

workflow

readonly workflow: WorkflowOf<TConfig, TState>

Defined in: packages/core/src/context.ts:33

The original workflow before any mutations.

Methods

emit()

emit<E>(type, data): void

Defined in: packages/core/src/context.ts:66

Emits a domain event. Validates event data against the event's Zod schema.

Type Parameters
E

E extends string

Parameters
type

E

Event type name

data

EventData<TConfig, E>

Event data matching the event's schema

Returns

void

error()

error<C>(code, data): never

Defined in: packages/core/src/context.ts:75

Signals a domain error. Validates error data and throws internally (caught by the router).

Type Parameters
C

C extends string

Parameters
code

C

Error code

data

ErrorData<TConfig, C>

Error data matching the error code's schema

Returns

never

get()

get<T>(key): T

Defined in: packages/core/src/context.ts:112

Retrieves a value from context-scoped middleware state. Throws if not set.

Type Parameters
T

T

Parameters
key

ContextKey<T>

A ContextKey created via createKey

Returns

T

getOrNull()

getOrNull<T>(key): T | undefined

Defined in: packages/core/src/context.ts:117

Retrieves a value from context-scoped middleware state, or undefined if not set.

Type Parameters
T

T

Parameters
key

ContextKey<T>

A ContextKey created via createKey

Returns

T | undefined

getWorkflowSnapshot()

getWorkflowSnapshot(): Workflow<TConfig>

Defined in: packages/core/src/context.ts:120

Internal

— not part of the handler API

Returns

Workflow<TConfig>

match()
Call Signature

match<R>(matchers): R

Defined in: packages/core/src/context.ts:81

Pattern-matches on the current state, calling the matching callback with narrowed data. All states must be handled (exhaustive).

Type Parameters
R

R

Parameters
matchers

{ [S in string]: (data: StateData<TConfig, S>, workflow: WorkflowOf<TConfig, S>) => R }

Returns

R

Call Signature

match<R>(matchers, fallback): R

Defined in: packages/core/src/context.ts:92

Pattern-matches on the current state with a fallback for unhandled states.

Type Parameters
R

R

Parameters
matchers

Partial<{ [S in StateNames<TConfig>]: (data: StateData<TConfig, S>, workflow: WorkflowOf<TConfig, S>) => R }>

fallback

() => R

Returns

R

set()

set<T>(key, value): void

Defined in: packages/core/src/context.ts:107

Stores a value in context-scoped middleware state.

Type Parameters
T

T

Parameters
key

ContextKey<T>

A ContextKey created via createKey

value

T

The value to store

Returns

void

transition()

transition<Target>(target, data): void

Defined in: packages/core/src/context.ts:53

Transitions the workflow to a new state with new data. Validates against the target state's Zod schema.

Type Parameters
Target

Target extends string

Parameters
target

Target

Target state name

data

StateData<TConfig, Target>

Data for the target state

Returns

void

update()

update(data): void

Defined in: packages/core/src/context.ts:46

Merges partial data into the current state. Validates against the state's Zod schema.

Parameters
data

Partial<StateData<TConfig, TState>>

Partial state data to merge

Returns

void


ContextKey

Defined in: packages/core/src/key.ts:2

A phantom-typed key for type-safe middleware state storage via Context.set and Context.get.

Type Parameters

T

T

Properties

_phantom

readonly _phantom: T

Defined in: packages/core/src/key.ts:4

Internal

Phantom type brand — not used at runtime.

id

readonly id: symbol

Defined in: packages/core/src/key.ts:6

Internal symbol providing uniqueness.


MigrateOptions

Defined in: packages/core/src/migration.ts:33

Options for migrate.

Properties

onError?

optional onError?: (error) => void

Defined in: packages/core/src/migration.ts:51

Called when a migration step fails.

Parameters
error

MigrationError

The MigrationError describing the failure

Returns

void

onStep?

optional onStep?: (fromVersion, toVersion, snapshot, description?) => void

Defined in: packages/core/src/migration.ts:41

Called after each successful migration step.

Parameters
fromVersion

number

The version before this step

toVersion

number

The version after this step

snapshot

WorkflowSnapshot

The snapshot after this step

description?

string

Optional description from the migration entry

Returns

void


MigrationPipeline

Defined in: packages/core/src/migration.ts:18

A validated migration pipeline ready to transform snapshots.

Type Parameters

TConfig

TConfig extends WorkflowConfig = WorkflowConfig

Properties

definition

readonly definition: WorkflowDefinition<TConfig>

Defined in: packages/core/src/migration.ts:20

The workflow definition this pipeline belongs to.

migrations

readonly migrations: ReadonlyMap<number, NormalizedMigration>

Defined in: packages/core/src/migration.ts:24

Map of version number to normalized migration step.

targetVersion

readonly targetVersion: number

Defined in: packages/core/src/migration.ts:22

The target schema version to migrate snapshots to.


RouterOptions

Defined in: packages/core/src/router.ts:35

Options for the WorkflowRouter constructor.

Properties

onHookError?

optional onHookError?: (error) => void

Defined in: packages/core/src/router.ts:37

Callback invoked when a lifecycle hook throws. Defaults to console.error.

Parameters
error

unknown

Returns

void

wrapDeps?

optional wrapDeps?: boolean

Defined in: packages/core/src/router.ts:39

Wrap deps in a Proxy to catch dependency errors. Defaults to true.


StandardSchemaV1

Defined in: packages/core/src/standard.ts:6

Inlined Standard Schema V1 spec (https://github.com/standard-schema/standard-schema). Kept internal to rytejs — we do not re-export from index.ts, since consumers interact with their schemas directly (Zod, Valibot, ArkType, etc.).

Type Parameters

Input

Input = unknown

Output

Output = Input

Properties

~standard

readonly ~standard: Props<Input, Output>

Defined in: packages/core/src/standard.ts:7


StateConfig

Defined in: packages/core/src/state.ts:15

State configuration — a server-side schema plus an optional client-side schema.

When clientSchema is provided, serializeForClient() runs data through it and returns the validator's stripped result (Zod / Valibot default-strip; ArkType users should use loose type({...})). ClientStateData<TConfig, S> is typed as the clientSchema's inferred output — fields absent from clientSchema are not visible to client TypeScript code.

If clientSchema is omitted, server and client share the same shape and no stripping happens at serialization time.

Type Parameters

TSchema

TSchema extends StandardSchemaV1 = StandardSchemaV1

TClientSchema

TClientSchema extends StandardSchemaV1 = TSchema

Properties

clientSchema?

readonly optional clientSchema?: TClientSchema

Defined in: packages/core/src/state.ts:20

schema

readonly schema: TSchema

Defined in: packages/core/src/state.ts:19


WorkflowConfig

Defined in: packages/core/src/types.ts:23

Flattened workflow configuration — carries only already-resolved output shapes. No validator library types are threaded through router/context generics.

Properties

clientStates

clientStates: Record<string, unknown>

Defined in: packages/core/src/types.ts:29

commands

commands: Record<string, unknown>

Defined in: packages/core/src/types.ts:26

errors

errors: Record<string, unknown>

Defined in: packages/core/src/types.ts:28

events

events: Record<string, unknown>

Defined in: packages/core/src/types.ts:27

modelVersion?

optional modelVersion?: number

Defined in: packages/core/src/types.ts:24

states

states: Record<string, unknown>

Defined in: packages/core/src/types.ts:25


WorkflowDefinition

Defined in: packages/core/src/definition.ts:20

The result of defineWorkflow — holds schemas and creates workflow instances.

Type Parameters

TConfig

TConfig extends WorkflowConfig = WorkflowConfig

Properties

config

readonly config: TConfig

Defined in: packages/core/src/definition.ts:22

The raw Zod schema configuration.

name

readonly name: string

Defined in: packages/core/src/definition.ts:24

The workflow definition name.

Methods

createWorkflow()

createWorkflow<S>(id, config): WorkflowOf<TConfig, S>

Defined in: packages/core/src/definition.ts:32

Creates a new workflow instance in a given initial state.

Type Parameters
S

S extends string

Parameters
id

string

Unique identifier for this workflow instance

config

Object containing initialState and the corresponding data

data

StateData<TConfig, S>

initialState

S

Returns

WorkflowOf<TConfig, S>

A WorkflowOf narrowed to the initial state

deserialize()

deserialize(snapshot): { ok: true; workflow: Workflow<TConfig>; } | { error: ValidationError; ok: false; }

Defined in: packages/core/src/definition.ts:91

Deserializes a workflow instance from a plain snapshot, validating the state data.

Parameters
snapshot

WorkflowSnapshot<TConfig>

The snapshot to deserialize from

Returns

{ ok: true; workflow: Workflow<TConfig>; } | { error: ValidationError; ok: false; }

A result object: { ok: true, workflow } or { ok: false, error }

forClient()

forClient(): ClientWorkflowDefinition<TConfig>

Defined in: packages/core/src/definition.ts:105

Returns a client-safe projection of this definition. Memoized — returns the same instance on repeated calls.

Returns

ClientWorkflowDefinition<TConfig>

getCommandSchema()

getCommandSchema(commandName): StandardSchemaV1

Defined in: packages/core/src/definition.ts:49

Returns the schema for a given command name.

Parameters
commandName

string

The command name to look up

Returns

StandardSchemaV1

Throws

If the command name is not found in the config

getErrorSchema()

getErrorSchema(errorCode): StandardSchemaV1

Defined in: packages/core/src/definition.ts:63

Returns the schema for a given error code.

Parameters
errorCode

string

The error code to look up

Returns

StandardSchemaV1

Throws

If the error code is not found in the config

getEventSchema()

getEventSchema(eventName): StandardSchemaV1

Defined in: packages/core/src/definition.ts:56

Returns the schema for a given event name.

Parameters
eventName

string

The event name to look up

Returns

StandardSchemaV1

Throws

If the event name is not found in the config

getStateSchema()

getStateSchema(stateName): StandardSchemaV1

Defined in: packages/core/src/definition.ts:42

Returns the Zod schema for a given state name.

Parameters
stateName

string

The state name to look up

Returns

StandardSchemaV1

Throws

If the state name is not found in the config

hasCommand()

hasCommand(commandName): boolean

Defined in: packages/core/src/definition.ts:73

Returns true if the given command name exists in the config.

Parameters
commandName

string

Returns

boolean

hasEvent()

hasEvent(eventName): boolean

Defined in: packages/core/src/definition.ts:77

Returns true if the given event name exists in the config.

Parameters
eventName

string

Returns

boolean

hasState()

hasState(stateName): boolean

Defined in: packages/core/src/definition.ts:69

Returns true if the given state name exists in the config.

Parameters
stateName

string

The state name to check

Returns

boolean

serialize()

serialize(workflow): WorkflowSnapshot<TConfig>

Defined in: packages/core/src/definition.ts:84

Serializes a workflow instance into a plain, JSON-safe snapshot.

Parameters
workflow

Workflow<TConfig>

The workflow instance to serialize

Returns

WorkflowSnapshot<TConfig>

A WorkflowSnapshot representing the current state

serializeForClient()

serializeForClient(workflow): WorkflowSnapshot<TConfig>

Defined in: packages/core/src/definition.ts:100

Serializes a workflow into a client-safe snapshot with server-only fields stripped.

Parameters
workflow

Workflow<TConfig>

The workflow instance to serialize

Returns

WorkflowSnapshot<TConfig>

A WorkflowSnapshot with server-only fields removed from data


WorkflowOf

Defined in: packages/core/src/types.ts:76

Workflow narrowed to a specific known state.

Type Parameters

TConfig

TConfig extends WorkflowConfig

S

S extends StateNames<TConfig>

Properties

createdAt

readonly createdAt: Date

Defined in: packages/core/src/types.ts:86

Timestamp of workflow creation.

data

readonly data: StateData<TConfig, S>

Defined in: packages/core/src/types.ts:84

State data, typed according to the state's Zod schema.

definitionName

readonly definitionName: string

Defined in: packages/core/src/types.ts:80

Name of the workflow definition this instance belongs to.

id

readonly id: string

Defined in: packages/core/src/types.ts:78

Unique workflow instance identifier.

state

readonly state: S

Defined in: packages/core/src/types.ts:82

Current state name.

updatedAt

readonly updatedAt: Date

Defined in: packages/core/src/types.ts:88

Timestamp of last state change.


WorkflowSnapshot

Defined in: packages/core/src/snapshot.ts:4

A plain, JSON-safe representation of a workflow's state for serialization and storage.

Type Parameters

TConfig

TConfig extends WorkflowConfig = WorkflowConfig

Properties

createdAt

readonly createdAt: string

Defined in: packages/core/src/snapshot.ts:14

ISO 8601 timestamp of workflow creation.

data

readonly data: unknown

Defined in: packages/core/src/snapshot.ts:12

State data (untyped — validated on WorkflowDefinition.deserialize).

definitionName

readonly definitionName: string

Defined in: packages/core/src/snapshot.ts:8

Name of the workflow definition.

id

readonly id: string

Defined in: packages/core/src/snapshot.ts:6

Unique workflow instance identifier.

modelVersion

readonly modelVersion: number

Defined in: packages/core/src/snapshot.ts:18

Schema version number for migration support.

state

readonly state: StateNames<TConfig>

Defined in: packages/core/src/snapshot.ts:10

Current state name.

updatedAt

readonly updatedAt: string

Defined in: packages/core/src/snapshot.ts:16

ISO 8601 timestamp of last state change.

version

readonly version: number

Defined in: packages/core/src/snapshot.ts:20

Optimistic concurrency version. Starts at 1, increments on each successful save.

Type Aliases

ClientStateData

ClientStateData<T, S> = T["clientStates"][S]

Defined in: packages/core/src/types.ts:46

Resolves the client-safe data type for a given state (server fields stripped).

Type Parameters

T

T extends WorkflowConfig

S

S extends StateNames<T>


ClientWorkflow

ClientWorkflow<TConfig> = { [S in StateNames<TConfig>]: ClientWorkflowOf<TConfig, S> }[StateNames<TConfig>]

Defined in: packages/core/src/types.ts:62

Discriminated union of all possible client-side workflow states.

Type Parameters

TConfig

TConfig extends WorkflowConfig = WorkflowConfig


Command

Command<T> = { [C in CommandNames<T>]: { payload: CommandPayload<T, C>; type: C } }[CommandNames<T>]

Defined in: packages/core/src/types.ts:38

Discriminated union of all commands with typed payloads — narrows payload when checking type.

Type Parameters

T

T extends WorkflowConfig


CommandNames

CommandNames<T> = keyof T["commands"] & string

Defined in: packages/core/src/types.ts:33

Type Parameters

T

T extends WorkflowConfig


CommandPayload

CommandPayload<T, C> = T["commands"][C]

Defined in: packages/core/src/types.ts:67

Resolves the payload type for a given command from pre-computed types.

Type Parameters

T

T extends WorkflowConfig

C

C extends CommandNames<T>


ConfigOf

ConfigOf<R> = R extends object ? C : never

Defined in: packages/core/src/types.ts:180

Extracts the WorkflowConfig type from a WorkflowRouter instance.

Type Parameters

R

R


DispatchResult

DispatchResult<TConfig> = { events: object[]; ok: true; workflow: Workflow<TConfig>; } | { error: PipelineError<TConfig>; ok: false; }

Defined in: packages/core/src/types.ts:127

Return type of WorkflowRouter.dispatch. Discriminated union on ok.

Type Parameters

TConfig

TConfig extends WorkflowConfig = WorkflowConfig


ErrorCodes

ErrorCodes<T> = keyof T["errors"] & string

Defined in: packages/core/src/types.ts:35

Type Parameters

T

T extends WorkflowConfig


ErrorData

ErrorData<T, C> = T["errors"][C]

Defined in: packages/core/src/types.ts:73

Resolves the data type for a given error code from pre-computed types.

Type Parameters

T

T extends WorkflowConfig

C

C extends ErrorCodes<T>


EventData

EventData<T, E> = T["events"][E]

Defined in: packages/core/src/types.ts:70

Resolves the data type for a given event from pre-computed types.

Type Parameters

T

T extends WorkflowConfig

E

E extends EventNames<T>


EventNames

EventNames<T> = keyof T["events"] & string

Defined in: packages/core/src/types.ts:34

Type Parameters

T

T extends WorkflowConfig


GenericPlugin

GenericPlugin = Plugin<any, any>

Defined in: packages/core/src/plugin.ts:33

A plugin that works with any router, regardless of config or deps.


Handler

Handler<TConfig, TDeps, TState, TCommand> = (ctx) => void | Promise<void>

Defined in: packages/core/src/handler.ts:5

Terminal handler function — receives fully typed context with state and command narrowing.

Type Parameters

TConfig

TConfig extends WorkflowConfig

TDeps

TDeps

TState

TState extends StateNames<TConfig>

TCommand

TCommand extends CommandNames<TConfig>

Parameters

ctx

Context<TConfig, TDeps, TState, TCommand>

Returns

void | Promise<void>


HookEvent

HookEvent = "dispatch:start" | "dispatch:end" | "pipeline:start" | "pipeline:end" | "transition" | "error" | "event"

Defined in: packages/core/src/hooks.ts:2

The lifecycle hook event names.


Middleware

Middleware<TConfig, TDeps, TState, TCommand> = (ctx, next) => Promise<void>

Defined in: packages/core/src/middleware.ts:11

Koa-style middleware function with full context narrowing via defaults.

  • Global middleware: Middleware<TConfig, TDeps> — union of all states/commands
  • State-scoped: Middleware<TConfig, TDeps, "draft"> — narrowed to state
  • Inline: Middleware<TConfig, TDeps, "draft", "publish"> — fully narrowed

Type Parameters

TConfig

TConfig extends WorkflowConfig

TDeps

TDeps

TState

TState extends StateNames<TConfig> = StateNames<TConfig>

TCommand

TCommand extends CommandNames<TConfig> = CommandNames<TConfig>

Parameters

ctx

Context<TConfig, TDeps, TState, TCommand>

next

() => Promise<void>

Returns

Promise<void>


MigrateResult

MigrateResult = { ok: true; snapshot: WorkflowSnapshot; } | { error: MigrationError; ok: false; }

Defined in: packages/core/src/migration.ts:28

Result of migrate.


MigrationEntry

MigrationEntry = MigrationFn | { description: string; up: MigrationFn; }

Defined in: packages/core/src/migration.ts:9

A migration entry — either a bare MigrationFn or an object with a description.


MigrationFn

MigrationFn = (snapshot) => WorkflowSnapshot

Defined in: packages/core/src/migration.ts:6

A function that transforms a snapshot's data from one version to the next.

Parameters

snapshot

WorkflowSnapshot

Returns

WorkflowSnapshot


PipelineError

PipelineError<TConfig> = { category: "validation"; issues: readonly Issue[]; message: string; source: "command" | "state" | "event" | "transition" | "restore"; } | { category: "domain"; code: ErrorCodes<TConfig>; data: ErrorData<TConfig, ErrorCodes<TConfig>>; } | { category: "router"; code: "NO_HANDLER" | "UNKNOWN_STATE"; message: string; } | { category: "unexpected"; error: unknown; message: string; } | { category: "dependency"; error: unknown; message: string; name: string; }

Defined in: packages/core/src/types.ts:97

Discriminated union of all pipeline error types on category.

Type Parameters

TConfig

TConfig extends WorkflowConfig = WorkflowConfig


Plugin

Plugin<TConfig, TDeps> = (router) => void & object

Defined in: packages/core/src/plugin.ts:7

A branded plugin function that can be passed to WorkflowRouter.use.

Type Declaration

[PLUGIN_SYMBOL]

readonly [PLUGIN_SYMBOL]: true

Type Parameters

TConfig

TConfig extends WorkflowConfig

TDeps

TDeps


ReadonlyContext

ReadonlyContext<TConfig, TDeps, TState, TCommand> = Omit<Context<TConfig, TDeps, TState, TCommand>, "update" | "transition" | "emit" | "error" | "getWorkflowSnapshot">

Defined in: packages/core/src/readonly-context.ts:8

Read-only subset of Context for hook callbacks. Includes context-key access (set/get) but excludes dispatch mutation methods.

Type Parameters

TConfig

TConfig extends WorkflowConfig

TDeps

TDeps

TState

TState extends StateNames<TConfig> = StateNames<TConfig>

TCommand

TCommand extends CommandNames<TConfig> = CommandNames<TConfig>


StateData

StateData<T, S> = T["states"][S]

Defined in: packages/core/src/types.ts:43

Resolves the data type for a given state from pre-computed types.

Type Parameters

T

T extends WorkflowConfig

S

S extends StateNames<T>


StateGroup

StateGroup<TName, TChildren> = object & { readonly [K in keyof TChildren]: `${TName}.${K & string}` }

Defined in: packages/core/src/group.ts:21

A group of related sub-states sharing a common namespace prefix.

Returned by defineGroup. Exposes three things:

  1. states — spread into defineWorkflow's states config
  2. names — array of fully-qualified names, pass to router.state([...]) for group-wide handlers
  3. Dynamic accessors (one per child) — string literals like group.Pending === "Payment.Pending"

Children can be plain schemas or state({ schema, clientSchema }) configs. Any shared base fields are expressed in validator-native style at the call site (e.g. { ...baseShape, ...childShape } in Zod, or v.object({...}) spread in Valibot) — the group itself does no schema merging.

Type Declaration

name

readonly name: TName

names

readonly names: ReadonlyArray<`${TName}.${keyof TChildren & string}`>

states

readonly states: { readonly [K in keyof TChildren as `${TName}.${K & string}`]: TChildren[K] }

Type Parameters

TName

TName extends string

The group name prefix (e.g. "Payment")

TChildren

TChildren extends Record<string, StandardSchemaV1 | StateConfig>

Map of child names to their state entries


StateNames

StateNames<T> = keyof T["states"] & string

Defined in: packages/core/src/types.ts:32

Type Parameters

T

T extends WorkflowConfig


Workflow

Workflow<TConfig> = { [S in StateNames<TConfig>]: WorkflowOf<TConfig, S> }[StateNames<TConfig>]

Defined in: packages/core/src/types.ts:92

Discriminated union of all possible workflow states — checking .state narrows .data.

Type Parameters

TConfig

TConfig extends WorkflowConfig = WorkflowConfig

Functions

createKey()

createKey<T>(name): ContextKey<T>

Defined in: packages/core/src/key.ts:15

Creates a unique typed key for storing and retrieving values in context.

Type Parameters

T

T

Parameters

name

string

Debug label (uniqueness comes from an internal Symbol)

Returns

ContextKey<T>

A ContextKey for use with ctx.set(), ctx.get(), and ctx.getOrNull()


defineGenericPlugin()

defineGenericPlugin(fn): GenericPlugin

Defined in: packages/core/src/plugin.ts:43

Creates a plugin that works with any router without requiring explicit type parameters. Use this for cross-cutting concerns (logging, tracing, delay) that don't reference specific states, commands, or events.

Parameters

fn

(router) => void

A function that configures a router (adds hooks, middleware)

Returns

GenericPlugin

A branded GenericPlugin function


defineGroup()

defineGroup<TName, TChildren>(name, children): StateGroup<TName, TChildren>

Defined in: packages/core/src/group.ts:79

Defines a namespaced group of sub-states.

Sub-states are addressed by dot-separated names (e.g. "Payment.Pending"). Shared base fields are the consumer's concern — spread a common shape object into each child schema directly. Keeping the group validator-agnostic means it works identically with Zod, Valibot, and ArkType.

Type Parameters

TName

TName extends string

TChildren

TChildren extends Record<string, StandardSchemaV1<unknown, unknown> | StateConfig<StandardSchemaV1<unknown, unknown>, StandardSchemaV1<unknown, unknown>>>

Parameters

name

TName

Group name prefix (used as the first segment of each state name)

children

TChildren

Map of child names to their schemas or state() configs

Returns

StateGroup<TName, TChildren>

Example

ts
// Zod
const basePayment = { amount: z.number() };
const Payment = defineGroup("Payment", {
  Pending: z.object({ ...basePayment, attempt: z.number() }),
  Failed: z.object({ ...basePayment, reason: z.string() }),
});

// Valibot — same pattern
const baseV = { amount: v.number() };
const PaymentV = defineGroup("Payment", {
  Pending: v.object({ ...baseV, attempt: v.number() }),
  Failed: v.object({ ...baseV, reason: v.string() }),
});

const def = defineWorkflow("order", {
  states: { Draft: z.object({ items: z.array(z.string()) }), ...Payment.states },
  commands: { Retry: z.object({}), Cancel: z.object({}) },
  events: {},
  errors: {},
});

// Group-wide handler — fires for any Payment.* state
router.state(Payment.names, ({ on }) => {
  on("Cancel", ({ transition }) => transition("Draft", { items: [] }));
});

// Sub-state-specific handler
router.state(Payment.Pending, ({ on }) => {
  on("Retry", ({ data, transition }) => { ... });
});

defineMigrations()

defineMigrations<TConfig>(definition, migrationMap): MigrationPipeline<TConfig>

Defined in: packages/core/src/migration.ts:82

Creates a validated migration pipeline from a definition and version-keyed transform functions. Each key is the target version — the function transforms from (key - 1) to key.

Type Parameters

TConfig

TConfig extends WorkflowConfig

Parameters

definition

WorkflowDefinition<TConfig>

The workflow definition the migrations belong to

migrationMap

Record<number, MigrationEntry>

A record mapping target version numbers to MigrationEntry values

Returns

MigrationPipeline<TConfig>

A validated MigrationPipeline ready for use with migrate

Throws

If migration keys are not sequential from 2 to the definition's modelVersion, or if the highest key does not match modelVersion


definePlugin()

definePlugin<TConfig, TDeps>(fn): Plugin<TConfig, TDeps>

Defined in: packages/core/src/plugin.ts:17

Brands a function as a Ryte plugin for use with WorkflowRouter.use.

Type Parameters

TConfig

TConfig extends WorkflowConfig

TDeps

TDeps

Parameters

fn

(router) => void

A function that configures a router (adds handlers, middleware, hooks)

Returns

Plugin<TConfig, TDeps>

A branded Plugin function


defineWorkflow()

defineWorkflow<TConfig>(name, config): WorkflowDefinition<{ clientStates: { [K in string | number | symbol]: InferOut<StateClientSchema<TConfig["states"][K]>> }; commands: { [K in string | number | symbol]: InferOut<TConfig["commands"][K]> }; errors: { [K in string | number | symbol]: InferOut<TConfig["errors"][K]> }; events: { [K in string | number | symbol]: InferOut<TConfig["events"][K]> }; modelVersion: TConfig["modelVersion"] extends number ? any[any] : 1; states: { [K in string | number | symbol]: InferOut<StateSchema<TConfig["states"][K]>> }; }>

Defined in: packages/core/src/definition.ts:148

Type Parameters

TConfig

TConfig extends WorkflowConfigInput

Parameters

name

string

config

TConfig

Returns

WorkflowDefinition<{ clientStates: { [K in string | number | symbol]: InferOut<StateClientSchema<TConfig["states"][K]>> }; commands: { [K in string | number | symbol]: InferOut<TConfig["commands"][K]> }; errors: { [K in string | number | symbol]: InferOut<TConfig["errors"][K]> }; events: { [K in string | number | symbol]: InferOut<TConfig["events"][K]> }; modelVersion: TConfig["modelVersion"] extends number ? any[any] : 1; states: { [K in string | number | symbol]: InferOut<StateSchema<TConfig["states"][K]>> }; }>


isPlugin()

isPlugin(value): value is Plugin<WorkflowConfig, unknown>

Defined in: packages/core/src/plugin.ts:56

Checks whether a value is a branded Ryte plugin.

Parameters

value

unknown

The value to check

Returns

value is Plugin<WorkflowConfig, unknown>

true if the value is a Plugin


migrate()

migrate<TConfig>(pipeline, snapshot, options?): MigrateResult

Defined in: packages/core/src/migration.ts:135

Runs the migration chain from the snapshot's modelVersion to the pipeline's targetVersion. Returns a Result. Auto-stamps modelVersion after each step.

Type Parameters

TConfig

TConfig extends WorkflowConfig

Parameters

pipeline

MigrationPipeline<TConfig>

The MigrationPipeline created by defineMigrations

snapshot

WorkflowSnapshot

The workflow snapshot to migrate

options?

MigrateOptions

Optional callbacks for step progress and error reporting

Returns

MigrateResult

A MigrateResult with the migrated snapshot on success, or a MigrationError on failure


state()

state<TSchema, TClientSchema>(config): StateConfig<TSchema, TClientSchema>

Defined in: packages/core/src/state.ts:34

Declares a state with a primary (server-side) schema and an optional client-side schema. Keeping schemas as the unit of declaration makes the API validator-agnostic — we never inspect schema shape.

Type Parameters

TSchema

TSchema extends StandardSchemaV1<unknown, unknown>

TClientSchema

TClientSchema extends StandardSchemaV1<unknown, unknown> = TSchema

Parameters

config
clientSchema?

TClientSchema

schema

TSchema

Returns

StateConfig<TSchema, TClientSchema>

Example

ts
state({
    schema: z.object({ applicantName: z.string(), ssn: z.string() }),
    clientSchema: z.object({ applicantName: z.string() }),
})