API Reference
Complete API reference for @hex-di/flow organized by category.
Machine Definition
defineMachine
Creates a state machine with full type inference.
function defineMachine<TStateNames, TEventNames, TContext>(
config: MachineConfig<TStateNames, TEventNames, TContext>
): Machine<TStateNames, TEventNames, TContext>;
Parameters:
config.id- Unique machine identifierconfig.initial- Initial state (optional, inferred if unambiguous)config.states- Record of state configurationsconfig.context- Initial context value
createMachineBuilder
Fluent builder API for creating machines.
function createMachineBuilder<TContext>(config: {
id: string;
context: TContext;
}): StatePhaseBuilder<TContext>;
Builder Methods:
.addState(name, config?)- Add a state.transitions()- Switch to transition phase.on(from, event, to, config?)- Define transition.build()- Create the machine
Types
State
Branded state type with optional context.
type State<TName extends string, TContext = void> = {
readonly [StateBrandSymbol]: [TName, TContext];
};
Event
Branded event type with optional payload.
type Event<TName extends string, TPayload = void> = {
readonly [EventBrandSymbol]: [TName, TPayload];
};
Machine
Complete machine type with states, events, and context.
type Machine<TStateNames, TEventNames, TContext> = {
readonly [MachineBrandSymbol]: [TStateNames, TEventNames, TContext];
readonly id: string;
readonly initial: TStateNames;
readonly states: Record<TStateNames, StateNode>;
readonly context: TContext;
};
Universal Types
StateAny- Matches any stateEventAny- Matches any eventMachineAny- Matches any machine
Effects
Effect.invoke
Invoke a port method.
Effect.invoke(
port: string,
method: string,
args?: unknown,
options?: { compensate?: EffectAny }
): InvokeEffect
Effect.spawn
Start an activity.
Effect.spawn(
activityId: string,
input: unknown,
options?: { compensate?: EffectAny }
): SpawnEffect
Effect.stop
Stop a running activity.
Effect.stop(activityId: string): StopEffect
Effect.emit
Emit an event to the machine.
Effect.emit(
event: EventAny,
options?: { delay?: number; compensate?: EffectAny }
): EmitEffect
Effect.delay
Wait for a duration.
Effect.delay(
ms: number,
options?: { compensate?: EffectAny }
): DelayEffect
Effect.parallel
Run effects concurrently.
Effect.parallel(effects: EffectAny[]): ParallelEffect
Effect.sequence
Run effects sequentially.
Effect.sequence(effects: EffectAny[]): SequenceEffect
Effect.none
No-op effect.
Effect.none(): NoneEffect
Effect.choose
Conditional effect branching.
Effect.choose(branches: Array<{
predicate: (context: any) => boolean;
effect: EffectAny;
}>): ChooseEffect
Effect.log
Log a message.
Effect.log(
message: string | ((context: any) => string)
): LogEffect
Runner
createMachineRunner
Create a machine runner instance.
function createMachineRunner<TStateNames, TEventNames, TContext>(
machine: Machine<TStateNames, TEventNames, TContext>,
options?: MachineRunnerOptions
): MachineRunner<TStateNames, TEventNames, TContext>;
Options:
executor- Effect executoractivityManager- Activity managercollector- Transition collectortracingHook- Tracing hookmaxQueueSize- Max event queue sizehistory- History configurationclock- Custom clockeventValidator- Event validation functionenforcePureGuards- Enforce guard purity
createBasicExecutor
Create a basic effect executor.
function createBasicExecutor(): EffectExecutor;
Handles: delay, none, parallel, sequence
MachineRunner
Runner instance methods:
snapshot(): MachineSnapshot- Get current snapshotstate(): TStateNames- Get current statecontext(): TContext- Get current contextstateValue(): StateValue- Get hierarchical statesend(event): boolean- Send single eventsendBatch(events): void- Send multiple eventssendAndExecute(event): Promise<Result>- Send and await effectssubscribe(fn): Unsubscribe- Subscribe to transitionsgetActivityStatus(id): ActivityInstance | undefined- Get activity statusgetTransitionHistory(): TransitionHistoryEntry[]- Get transitionsgetEffectHistory(): EffectExecutionEntry[]- Get effectsdispose(): void- Clean up resources
MachineSnapshot
Machine state snapshot:
interface MachineSnapshot<TStateNames, TContext> {
state: TStateNames;
context: TContext;
activities: Record<string, ActivityInstance>;
pendingEvents: PendingEvent[];
stateValue: StateValue;
matches(path: string): boolean;
can(event: EventAny): boolean;
}
Activities
createActivityManager
Create an activity manager.
function createActivityManager(config?: ActivityManagerConfig): ActivityManager;
Config:
maxConcurrent- Max concurrent activitiesdefaultTimeout- Default timeout
activityPort
Define an activity port.
function activityPort<TInput, TOutput>()(
name: string
): ActivityPort<TInput, TOutput>
defineEvents
Define typed event factories.
function defineEvents<T extends Record<string, EventFactory>>(events: T): T & EventTypes<T>;
Activity Interface
interface Activity<TInput, TOutput> {
execute(input: TInput, sink: EventSink, signal: AbortSignal): Promise<TOutput>;
}
Integration
createFlowAdapter
Create a DI adapter for a machine.
function createFlowAdapter<TProvides, TRequires>(
config: FlowAdapterConfig<TProvides, TRequires>
): FlowAdapter;
Config:
provides- Port this adapter providesrequires- Required dependencieslifetime- Adapter lifetimemachine- State machineactivities- Activity definitions
createDIEffectExecutor
Create a DI-aware effect executor.
function createDIEffectExecutor(config: DIEffectExecutorConfig): DIEffectExecutor;
Config:
scopeResolver- Resolve container scopeports- Port mappingsactivities- Activity port mappingsfallback- Fallback handler
Serialization
serializeMachineState
Serialize machine state.
function serializeMachineState(
runner: MachineRunnerAny,
machineId: string,
options?: SerializeOptions
): Result<SerializedMachineState, SerializationError>;
Options:
clock- Custom clock for timestampversion- Schema versionincludeHash- Include definition hash
restoreMachineState
Restore machine from serialized state.
function restoreMachineState(
serialized: SerializedMachineState,
machine: MachineAny,
options?: RestoreOptions
): Result<MachineRunnerAny, RestoreError>;
Options:
contextValidator- Validate contextmigrationRegistry- Version migrations
Tracing
FlowTransitionEvent
Transition event for tracing:
interface FlowTransitionEvent {
id: string;
machineId: string;
prevState: string;
event: EventAny;
nextState: string;
effects: EffectAny[];
timestamp: number;
duration?: number;
hash?: string;
}
FlowCollector
Collector interface:
interface FlowCollector {
collect(event: FlowTransitionEvent): void;
query(filter?: FlowTransitionFilter): FlowTransitionEvent[];
subscribe(fn: FlowSubscriber): Unsubscribe;
getStats(): FlowStats;
clear(): void;
}
FlowMemoryCollector
In-memory collector implementation:
class FlowMemoryCollector implements FlowCollector {
constructor(policy?: FlowRetentionPolicy);
}
NoOpFlowCollector
Zero-overhead no-op collector:
const noopFlowCollector: FlowCollector;
Patterns
createMachineActivity
Create an activity from a child machine.
function createMachineActivity<TInput, TOutput>(
childMachine: MachineAny,
config?: MachineActivityConfig<TInput, TOutput>
): Activity<TInput, TOutput>;
Config:
mapInput- Map input to contextmapOutput- Map context to outputdoneEventType- Completion eventerrorEventType- Error event