Skip to main content

makeHsm

makeHsm<Context, Protocol>(topState, ctx, initialize?, traceLevel?, traceWriter?, dispatchErrorCallback?): Hsm<Context, Protocol>

Creates and optionally initializes a hierarchical state machine actor bound to ctx.

The returned Hsm is the single runtime object: external clients call post / call / sync; the active state is the instance prototype chain updated by State.transition.

Type Parameters

Context

Context

Domain context type (inferred from ctx when passed inline)

Protocol

Protocol extends { } | undefined

Event/service vocabulary (inferred from topState when it implements Protocol)

Parameters

topState

StateClass<Context, Protocol>

Root state class constructor (must extend TopState)

ctx

Context

Mutable domain object shared by all states; stored on the instance as Hsm.ctx

initialize?

boolean = defaultInitialize

When true (default), enqueue the initial walk: descend @InitialState chains from topState and run StateEvents.onEntry on each entered state until the initial leaf is active. When false, prototype starts at topState with no entry hooks

traceLevel?

TraceLevel = defaultTraceLevel

Initial TraceLevel (default TraceLevel.DEBUG)

traceWriter?

TraceWriter = defaultTraceWriter

TraceWriter implementation (default: prefixes strings with state name and logs to console)

dispatchErrorCallback?

DispatchErrorCallback<Context, Protocol> = defaultDispatchErrorCallback

Last-resort error hook (default: trace + rethrow)

Returns

Hsm<Context, Protocol>

Client handle implementing Hsm for the same Context and Protocol

Remarks

  • Await Hsm.sync after creation when initialize: true before asserting initial state
  • Zero runtime npm dependencies; safe to embed in browsers when state names are registered
  • Transition LCA paths are cached per machine instance for the lifetime of the actor

Examples

const door = makeHsm(DoorTop, { openCount: 0 });
await door.sync();
door.post('open');
await door.sync();
const writer = { write: (_hsm, msg) => logs.push(msg) };
const sm = makeHsm(Top, ctx, true, TraceLevel.VERBOSE_DEBUG, writer);
await sm.sync();