@statewalker/fsm 0.37.0 → 0.38.1

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/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/utils/printer.ts","../src/utils/tracer.ts"],"sourcesContent":["import type { FsmProcess } from \"../core/fsm-process.ts\";\nexport type Printer = (...args: unknown[]) => void;\nexport type PrinterConfig = {\n prefix?: string;\n print?: (...args: unknown[]) => void;\n lineNumbers?: boolean;\n};\n\nconst printerStore = new WeakMap<object, Printer>();\n\nexport function preparePrinter(\n process: FsmProcess,\n { prefix = \"\", print = console.log, lineNumbers = false }: PrinterConfig,\n): Printer {\n let lineCounter = 0;\n const shift = () => {\n let prefix = \"\";\n for (let s = process.state?.parent; s; s = s.parent) {\n prefix += \" \";\n }\n return prefix;\n };\n const getPrefix = lineNumbers ? () => `[${++lineCounter}]${shift()}` : shift;\n const printer = (...args: unknown[]) => print(prefix, getPrefix(), ...args);\n return printer;\n}\n\nexport function setProcessPrinter(\n process: FsmProcess,\n config: PrinterConfig = {},\n) {\n const printer = preparePrinter(process, config);\n printerStore.set(process, printer);\n}\n\nexport function getProcessPrinter(process: FsmProcess): Printer {\n return printerStore.get(process) || console.log;\n}\n\nexport function getPrinter(state: { process: FsmProcess }): Printer {\n return printerStore.get(state) || getProcessPrinter(state.process);\n}\n","import type { FsmProcess } from \"../core/fsm-process.ts\";\nimport type { FsmState } from \"../core/fsm-state.ts\";\nimport { getPrinter, type Printer } from \"./printer.ts\";\n\nexport function setProcessTracer(process: FsmProcess, print?: Printer) {\n return process.onStateCreate((state: FsmState) => {\n setStateTracer(state, print);\n });\n}\n\nexport function setStateTracer(state: FsmState, print?: Printer) {\n state.onEnter(() => {\n const printLine = print || getPrinter(state);\n printLine(`<${state?.key} event=\"${state.process.event}\">`);\n });\n state.onExit(async () => {\n await Promise.resolve().then(async () => {\n const printLine = print || getPrinter(state);\n printLine(`</${state.key}> <!-- event=\"${state.process.event}\" -->`);\n });\n });\n}\n"],"mappings":";;AAQA,MAAM,+BAAe,IAAI,SAA0B;AAEnD,SAAgB,eACd,SACA,EAAE,SAAS,IAAI,QAAQ,QAAQ,KAAK,cAAc,SACzC;CACT,IAAI,cAAc;CAClB,MAAM,cAAc;EAClB,IAAI,SAAS;AACb,OAAK,IAAI,IAAI,QAAQ,OAAO,QAAQ,GAAG,IAAI,EAAE,OAC3C,WAAU;AAEZ,SAAO;;CAET,MAAM,YAAY,oBAAoB,IAAI,EAAE,YAAY,GAAG,OAAO,KAAK;CACvE,MAAM,WAAW,GAAG,SAAoB,MAAM,QAAQ,WAAW,EAAE,GAAG,KAAK;AAC3E,QAAO;;AAGT,SAAgB,kBACd,SACA,SAAwB,EAAE,EAC1B;CACA,MAAM,UAAU,eAAe,SAAS,OAAO;AAC/C,cAAa,IAAI,SAAS,QAAQ;;AAGpC,SAAgB,kBAAkB,SAA8B;AAC9D,QAAO,aAAa,IAAI,QAAQ,IAAI,QAAQ;;AAG9C,SAAgB,WAAW,OAAyC;AAClE,QAAO,aAAa,IAAI,MAAM,IAAI,kBAAkB,MAAM,QAAQ;;;;ACpCpE,SAAgB,iBAAiB,SAAqB,OAAiB;AACrE,QAAO,QAAQ,eAAe,UAAoB;AAChD,iBAAe,OAAO,MAAM;GAC5B;;AAGJ,SAAgB,eAAe,OAAiB,OAAiB;AAC/D,OAAM,cAAc;AAElB,GADkB,SAAS,WAAW,MAAM,EAClC,IAAI,OAAO,IAAI,UAAU,MAAM,QAAQ,MAAM,IAAI;GAC3D;AACF,OAAM,OAAO,YAAY;AACvB,QAAM,QAAQ,SAAS,CAAC,KAAK,YAAY;AAEvC,IADkB,SAAS,WAAW,MAAM,EAClC,KAAK,MAAM,IAAI,gBAAgB,MAAM,QAAQ,MAAM,OAAO;IACpE;GACF"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/core/fsm-base-class.ts","../src/core/fsm-state.ts","../src/core/fsm-state-config.ts","../src/core/fsm-state-descriptor.ts","../src/core/fsm-process.ts","../src/core/fsm-transitions.ts","../src/start-process.ts","../src/trace/printer.ts","../src/trace/tracer.ts"],"sourcesContent":["type Handler<P extends unknown[] = unknown[], R = unknown> = (...args: P) => R;\n\n/**\n * Shared handler-registry substrate under both `FsmProcess` and `FsmState`.\n *\n * Both the process and every state need the same primitive: keep named lists of\n * callbacks (`onEnter`, `onExit`, `dump`, …) and run them with consistent ordering\n * and error routing. Centralising it here keeps the two subclasses thin and their\n * hook methods one-liners. `handlers` maps a hook name to its ordered callback list;\n * the protected `_addHandler` / `_removeHandler` / `_runHandler` manage and invoke\n * them. Handlers run **sequentially** (awaited in turn); a throwing handler is routed\n * to `_handleError` rather than aborting the batch. Subclasses expose typed sugar\n * (e.g. `state.onEnter(fn)` calls `_addHandler(\"onEnter\", fn)`) and override\n * `_handleError` to forward errors.\n */\nexport class FsmBaseClass {\n handlers: Record<string, Handler[]> = {};\n\n // ----------------------------------------------\n // internal methods\n\n /**\n * Register `handler` under `type`; returns a disposer that removes it.\n * `direct=false` prepends instead of appends — used so `onExit` handlers run in\n * reverse (inner-to-outer) unwinding order.\n */\n protected _addHandler<T>(type: string, handler: T, direct: boolean = true) {\n let list = this.handlers[type];\n if (!list) {\n list = this.handlers[type] = [];\n }\n const h = handler as Handler;\n direct ? list.push(h) : list.unshift(h);\n return () => this._removeHandler(type, h);\n }\n\n protected _removeHandler<T>(type: string, handler: T) {\n let list = this.handlers[type];\n if (!list) return;\n list = list.filter((h) => h !== handler);\n if (list.length > 0) {\n this.handlers[type] = list;\n } else {\n delete this.handlers[type];\n }\n }\n\n /** Run every handler of `type` in order, awaiting each; route throws to `_handleError`. */\n async _runHandler(type: string, ...args: unknown[]) {\n const list = this.handlers[type] || [];\n for (const handler of list) {\n try {\n await handler(...args);\n } catch (error) {\n await this._handleError(error);\n }\n }\n }\n\n /** Default error sink — logs. `FsmState`/`FsmProcess` override it to fire `onStateError`. */\n async _handleError(error: Error | unknown) {\n console.error(error);\n }\n}\n\n/**\n * Bind the named methods of `obj` to `obj` in place, so they can be passed as bare\n * callbacks (e.g. `ctx[KEY_DISPATCH] = process.dispatch`) without losing `this`.\n */\nexport function bindMethods<T>(obj: T, ...methods: (string | symbol)[]) {\n const o = obj as Record<string | symbol, unknown>;\n for (const methodName of methods) {\n const method = o[methodName];\n if (typeof method !== \"function\") continue;\n o[methodName] = method.bind(o);\n }\n return obj;\n}\n","import { bindMethods, FsmBaseClass } from \"./fsm-base-class.ts\";\nimport type { FsmProcess } from \"./fsm-process.ts\";\nimport type { FsmStateDescriptor } from \"./fsm-state-descriptor.ts\";\n\n/** Serialized form of a single state: its `key` plus the `data` bag its `dump` hooks filled. */\nexport type FsmStateDump = Record<string, unknown> & {\n key: string;\n data: Record<string, unknown>;\n};\n/** An `onEnter` / `onExit` callback; receives the state it fired on. */\nexport type FsmStateHandler = (\n state: FsmState,\n ...args: unknown[]\n) => void | Promise<void>;\n\n/** A `dump` / `restore` callback; reads or fills the mutable per-state `data` bag. */\nexport type FsmStateDumpHandler = (\n state: FsmState,\n dump: FsmStateDump,\n) => void | Promise<void>;\n\n/** An `onStateError` callback; receives the error thrown by another handler on this state. */\nexport type FsmStateErrorHandler = (\n state: FsmState,\n error: unknown,\n) => void | Promise<void>;\n\n/**\n * One live node in a running machine's active-state stack.\n *\n * A state needs a place to attach behaviour and record data while it is active.\n * `FsmState` is that handle — created by the engine each time a state is entered,\n * discarded when it exits — so handlers can capture per-activation closures instead\n * of sharing mutable machine-wide state. It offers lifecycle hooks `onEnter` /\n * `onExit` / `onStateError`, serialization hooks `dump` / `restore`, and the tree\n * links `key` / `parent` / `descriptor`; every hook method returns a disposer.\n * Attach hooks from within `FsmProcess.onStateCreate((state) => …)`, or let\n * `startProcess` install them for you from a `load` callback.\n */\nexport class FsmState extends FsmBaseClass {\n process: FsmProcess;\n key: string;\n parent?: FsmState;\n descriptor?: FsmStateDescriptor;\n\n constructor(\n process: FsmProcess,\n parent: FsmState | undefined,\n key: string,\n descriptor?: FsmStateDescriptor,\n ) {\n super();\n this.process = process;\n this.key = key;\n this.parent = parent;\n this.descriptor = descriptor;\n bindMethods(this, \"onEnter\", \"onExit\", \"dump\", \"restore\", \"onStateError\");\n }\n\n /** Run when this state is entered. */\n onEnter(handler: FsmStateHandler) {\n return this._addHandler(\"onEnter\", handler, true);\n }\n /** Run when this state exits — registered inner-first so unwinding is inner-to-outer. */\n onExit(handler: FsmStateHandler) {\n return this._addHandler(\"onExit\", handler, false);\n }\n /** Handle an error thrown by another handler on this state (also bubbles to the process). */\n onStateError(handler: FsmStateErrorHandler) {\n return this._addHandler(\"onStateError\", handler);\n }\n /** Contribute to this state's snapshot: fill `dump.data` when the process is dumped. */\n dump(handler: FsmStateDumpHandler) {\n return this._addHandler(\"dump\", handler, true);\n }\n /** Rehydrate from this state's snapshot: read `dump.data` when the process is restored. */\n restore(handler: FsmStateDumpHandler) {\n return this._addHandler(\"restore\", handler, true);\n }\n\n async _handleError(error: Error | unknown) {\n // Run the state's own error handlers directly — NOT via `_runHandler`, whose\n // catch re-routes to `_handleError`, which would re-enter `onStateError`\n // forever. A throw from an error handler terminates at `console.error`.\n for (const handler of this.handlers.onStateError ?? []) {\n try {\n await handler(this, error);\n } catch (e) {\n console.error(e);\n }\n }\n await this.process._handleStateError(this, error);\n }\n}\n","// Sentinel keys used inside `FsmStateConfig.transitions` tuples. The raw `\"\"` and\n// `\"*\"` literals are ambiguous at the call site — `[\"\", \"start\", \"Active\"]` does not\n// visibly say \"from the *initial* state\" — so these named constants document intent\n// while keeping the runtime value (a shared empty string / asterisk) identical, which\n// keeps configs plain-serializable.\n\n/** Wildcard `from`-state: a transition that applies in *any* state. */\nexport const STATE_ANY = \"*\";\n/** Empty `from`-state: the *initial* pseudo-state a parent enters into. */\nexport const STATE_INITIAL = \"\";\n/** Empty `to`-state: the *final* pseudo-state; entering it exits the parent. */\nexport const STATE_FINAL = \"\";\n/** Wildcard `event`: a transition triggered by *any* event. */\nexport const EVENT_ANY = \"*\";\n/** Empty event: the eventless/automatic transition (fires with no named event). */\nexport const EVENT_EMPTY = \"\";\n\nexport type FsmStateKey = string;\nexport type FsmEventKey = string;\n\n/**\n * Declarative definition of a (possibly nested) state machine.\n *\n * One plain-object shape describes an entire HFSM, so machines stay serializable,\n * diffable, and inspectable by tooling — the config is data, not code. A config has:\n * - `key` — the state's name (unique among its siblings);\n * - `transitions` — `[from, event, to]` tuples, where `from`/`to` name sibling\n * states, `\"\"` is the initial (`from`) or final (`to`) pseudo-state, and `\"*\"` is a\n * wildcard (see the constants above);\n * - `states` — nested child configs; entering this state descends into its initial\n * child. The index signature lets consumers attach arbitrary metadata.\n *\n * Pass a config to `new FsmProcess(config)` or `startProcess(ctx, config, …)`; it is\n * compiled once into an `FsmStateDescriptor` for fast lookup at runtime.\n */\nexport type FsmStateConfig = {\n key: FsmStateKey;\n transitions?: [from: FsmStateKey, event: FsmEventKey, to: FsmStateKey][];\n states?: FsmStateConfig[];\n} & Record<string, unknown>;\n","import {\n EVENT_ANY,\n type FsmStateConfig,\n STATE_ANY,\n STATE_FINAL,\n} from \"./fsm-state-config.ts\";\n\n/**\n * The *compiled* form of an `FsmStateConfig` subtree.\n *\n * Resolving a transition happens on every event, so the flat `[from, event, to]`\n * tuple list is pre-indexed once into nested maps for O(1) lookup, and the\n * wildcard-fallback order is applied here rather than re-derived on each dispatch.\n * The shape is `transitions[from][event] = to` plus a `states` map of child\n * descriptors. `FsmProcess` builds one from your config in its constructor; you\n * rarely construct a descriptor directly.\n */\nexport class FsmStateDescriptor {\n transitions: Record<string, Record<string, string>> = {};\n states: Record<string, FsmStateDescriptor> = {};\n\n /**\n * Recursively compile a config (and its nested `states`) into descriptors,\n * turning the tuple list into the indexed `transitions` map.\n */\n static build(config: FsmStateConfig) {\n const descriptor = new FsmStateDescriptor();\n for (const [from, event, to] of config.transitions || []) {\n let index = descriptor.transitions[from];\n if (!index) {\n index = descriptor.transitions[from] = {};\n }\n index[event] = to;\n }\n if (config.states) {\n for (const substateConfig of config.states) {\n descriptor.states[substateConfig.key] =\n FsmStateDescriptor.build(substateConfig);\n }\n }\n return descriptor;\n }\n\n /**\n * Resolve the target state for a `(stateKey, eventKey)` pair. Tries the most\n * specific match first, then falls back through the wildcards —\n * `(state, event)` → `(*, event)` → `(state, *)` → `(*, *)` — and returns\n * `STATE_FINAL` if nothing matches, so an unmatched event exits the state rather\n * than silently doing nothing.\n */\n getTargetStateKey(stateKey: string, eventKey: string) {\n const pairs = [\n [stateKey, eventKey],\n [STATE_ANY, eventKey],\n [stateKey, EVENT_ANY],\n [STATE_ANY, EVENT_ANY],\n ];\n let targetKey: string | undefined;\n for (\n let i = 0, len = pairs.length;\n targetKey === undefined && i < len;\n i++\n ) {\n const [stateKey, eventKey] = pairs[i];\n const stateTransitions = this.transitions[stateKey];\n if (!stateTransitions) continue;\n targetKey = stateTransitions[eventKey];\n }\n return targetKey !== undefined ? targetKey : STATE_FINAL;\n }\n}\n","import { bindMethods, FsmBaseClass } from \"./fsm-base-class.ts\";\nimport {\n FsmState,\n type FsmStateDump,\n type FsmStateHandler,\n} from \"./fsm-state.ts\";\nimport {\n EVENT_EMPTY,\n type FsmStateConfig,\n STATE_FINAL,\n STATE_INITIAL,\n} from \"./fsm-state-config.ts\";\nimport { FsmStateDescriptor } from \"./fsm-state-descriptor.ts\";\n\n// Status bitmask: where the process is in the enter/exit cycle of `dispatch`.\n// Why a bitmask (rather than an enum): the loop tests *phases* with cheap bitwise\n// masks — `status & STATUS_ENTER`, `status & this.mask` — and composite masks\n// (ENTER / EXIT) are just OR-combinations of the primitive bits.\n/** Not started / no current transition. */\nexport const STATUS_NONE = 0;\n/** Entering: descended into a parent's first (initial) child. */\nexport const STATUS_FIRST = 1;\n/** Entering: advanced to a resolved target (sibling) state. */\nexport const STATUS_NEXT = 2;\n/** Rested on a leaf — dispatch returns control here (the default `mask`). */\nexport const STATUS_LEAF = 4;\n/** Exiting: popped back up to the parent state. */\nexport const STATUS_LAST = 8;\n/** Terminated: the machine has exited its root and cannot advance further. */\nexport const STATUS_FINISHED = 16;\n\n//\n/** Composite: any \"entering\" phase. */\nexport const STATUS_ENTER = STATUS_FIRST | STATUS_NEXT;\n/** Composite: any \"exiting\" phase. */\nexport const STATUS_EXIT = STATUS_LEAF | STATUS_LAST;\n\n/** A process-level handler (`onStateCreate` / `onStateError`). */\nexport type FsmProcessHandler = (\n process: FsmProcess,\n ...args: unknown[]\n) => void | Promise<void>;\n\n/** Serialized form of the whole machine: status, last event, and the root→leaf state stack. */\nexport type FsmProcessDump = Record<string, unknown> & {\n status: number;\n event?: string;\n stack: FsmStateDump[];\n};\n\nexport type FsmProcessDumpHandler = (\n process: FsmProcess,\n dump: FsmProcessDump,\n) => void | Promise<void>;\n\n/**\n * The running state machine — owner of the active-state stack and the traversal.\n *\n * This is the engine: given a compiled config it drives the enter/exit walk in\n * response to events, so callers reason in terms of states and events, not manual\n * stack bookkeeping. `dispatch(event)` advances the machine to the next resting leaf;\n * `shutdown(event?)` unwinds every active state; `state` is the current leaf;\n * `onStateCreate(handler)` is the primary extension point (fires once per created\n * state — attach that state's hooks there); and `dump()` / `restore(dump)` snapshot\n * and rehydrate the whole stack. Typical use: `new FsmProcess(config)`, register\n * `onStateCreate`, then `dispatch(\"\")` to enter the initial state and\n * `dispatch(event)` for each subsequent event.\n */\nexport class FsmProcess extends FsmBaseClass {\n state?: FsmState;\n event?: string;\n nextEvents: string[] = [];\n running: boolean = false;\n mask: number = STATUS_LEAF;\n status: number = 0;\n config: FsmStateConfig;\n rootDescriptor: FsmStateDescriptor;\n\n constructor(config: FsmStateConfig) {\n super();\n this.rootDescriptor = FsmStateDescriptor.build(config);\n this.config = config;\n bindMethods(this, \"dispatch\", \"dump\", \"restore\");\n }\n\n /** Force-exit the whole stack (root last), running each state's `onExit`; ends the machine. */\n async shutdown(event?: string) {\n while (this.state) {\n this.event = event;\n this.status = STATUS_FINISHED;\n await this.state?._runHandler(\"onExit\", this.state);\n this.state = this.state.parent;\n }\n }\n\n /**\n * Feed an event to the machine and run the enter/exit cycle until it rests on a\n * leaf (`status & mask`) or finishes.\n *\n * If a dispatch is already running (e.g. an `onEnter` handler dispatches\n * synchronously), the event is appended to the `nextEvents` FIFO queue and applied\n * — in order, none dropped — when the current run settles; runs never nest. Returns\n * `false` once the machine has finished, `true` otherwise.\n */\n async dispatch(event: string): Promise<boolean> {\n // Queue the event. Re-entrant dispatches (from handlers running mid-settle)\n // append here and are drained in order — so no earlier event is overwritten.\n this.nextEvents.push(event);\n if (!this.running && !(this.status & STATUS_FINISHED)) {\n this.running = true;\n try {\n while (this.nextEvents.length > 0) {\n this.event = this.nextEvents.shift();\n while (true) {\n // ---\n if (this.status & STATUS_EXIT) {\n await this.state?._runHandler(\"onExit\", this.state);\n }\n if (!(await this._update())) break;\n if (this.status & STATUS_ENTER) {\n await this.state?._runHandler(\"onEnter\", this.state);\n }\n if (this.status & this.mask) break;\n // ---\n }\n if (this.status & STATUS_FINISHED) break;\n }\n } finally {\n this.running = false;\n }\n }\n return !(this.status & STATUS_FINISHED);\n }\n\n /**\n * Snapshot the machine to a plain object: `{ status, event, stack }` where the\n * stack is root→leaf, each entry carrying whatever its `dump` hooks recorded.\n */\n async dump(...args: unknown[]): Promise<FsmProcessDump> {\n const dumpState = async (state: FsmState) => {\n const stateDump: FsmStateDump = {\n key: state.key,\n data: {},\n };\n await state._runHandler(\"dump\", state, stateDump.data, ...args);\n return stateDump;\n };\n const dumpStates = async (\n state: FsmState | undefined,\n stack: FsmStateDump[] = [],\n ) => {\n if (!state) return stack;\n state.parent && (await dumpStates(state.parent, stack));\n stack.push(await dumpState(state));\n return stack;\n };\n const dump: FsmProcessDump = {\n status: this.status,\n event: this.event,\n stack: await dumpStates(this.state),\n };\n return dump;\n }\n\n /**\n * Rebuild the machine from a `dump`: recreate each state in the stack (firing\n * `onStateCreate`) and replay its `restore` hooks, leaving the process resumable\n * from where it was snapshotted.\n */\n async restore(dump: FsmProcessDump, ...args: unknown[]) {\n this.status = dump.status || 0;\n this.event = dump.event;\n this.state = undefined;\n for (let i = 0; i < dump.stack.length; i++) {\n const stateDump = dump.stack[i];\n this.state = this.state\n ? await this._newSubstate(this.state, stateDump.key)\n : await this._newState(undefined, stateDump.key, this.rootDescriptor);\n await this.state._runHandler(\n \"restore\",\n this.state,\n stateDump.data,\n ...args,\n );\n }\n return this;\n }\n\n /** Primary extension point: fires once for every state the machine creates. */\n onStateCreate(handler: FsmStateHandler) {\n return this._addHandler(\"onStateCreate\", handler, true);\n }\n\n onStateError(\n handler: (state: FsmState, error: unknown) => void | Promise<void>,\n ) {\n return this._addHandler(\"onStateError\", handler);\n }\n\n async _handleStateError(state: FsmState, error: Error | unknown) {\n await this._runHandler(\"onStateError\", state, error);\n this._handleError(error);\n }\n\n async _newState(\n parent: FsmState | undefined,\n key: string,\n descriptor: FsmStateDescriptor | undefined,\n ) {\n const state = new FsmState(this, parent, key, descriptor);\n await this._runHandler(\"onStateCreate\", state);\n return state;\n }\n\n async _getSubstate(\n parent: FsmState | undefined,\n prevStateKey: string | undefined,\n ) {\n if (!parent) return;\n const toState =\n parent.descriptor?.getTargetStateKey(\n prevStateKey || STATE_INITIAL,\n this.event || EVENT_EMPTY,\n ) || STATE_FINAL;\n if (!toState) return;\n return this._newSubstate(parent, toState);\n }\n\n async _newSubstate(parent: FsmState | undefined, toState: string) {\n let descriptor: FsmStateDescriptor | undefined;\n for (\n let state: FsmState | undefined = parent;\n !descriptor && state;\n state = state.parent\n ) {\n descriptor = state.descriptor?.states[toState];\n }\n return this._newState(parent, toState, descriptor);\n }\n\n /**\n * One step of the traversal: compute the next state and update `status`.\n *\n * Either descends to a child / advances to a resolved target (setting an ENTER\n * status), or — when no target resolves — settles on the current leaf\n * (`STATUS_LEAF`) or pops to the parent (`STATUS_LAST`), reaching `STATUS_FINISHED`\n * once the root is exited. Returns `false` when finished.\n */\n async _update() {\n if (this.status & STATUS_FINISHED) return false;\n const nextState =\n this.status !== STATUS_NONE\n ? this.status & STATUS_ENTER\n ? await this._getSubstate(this.state, STATE_INITIAL)\n : await this._getSubstate(this.state?.parent, this.state?.key)\n : await this._newState(undefined, this.config.key, this.rootDescriptor);\n if (nextState !== undefined) {\n this.state = nextState;\n this.status = this.status & STATUS_EXIT ? STATUS_NEXT : STATUS_FIRST;\n } else {\n if (this.status & STATUS_EXIT) {\n this.state = this.state?.parent;\n this.status = STATUS_LAST;\n } else {\n this.status = STATUS_LEAF;\n }\n if (!this.state) this.status = STATUS_FINISHED;\n }\n return !(this.status & STATUS_FINISHED);\n }\n}\n","import type { FsmProcess } from \"./fsm-process.ts\";\nimport type { FsmState } from \"./fsm-state.ts\";\nimport { EVENT_ANY } from \"./fsm-state-config.ts\";\nimport type { FsmStateDescriptor } from \"./fsm-state-descriptor.ts\";\n\n// ---------------------------------------------------------------------------\n// Transition introspection — read-only queries over the state/transition graph\n// ---------------------------------------------------------------------------\n\n/**\n * List the transitions currently reachable from `state` — for a UI or viewer that\n * needs to know which events can fire right now (e.g. to render only the enabled\n * buttons). Collects `[from, event, to]` tuples by walking up the parent chain; the\n * nearest state's rule for an event wins, so an outer fallback is masked by an inner\n * override. The returned tuples are ordered outer→inner (root first).\n */\nexport function getStateTransitions(\n state?: FsmState,\n): [from: string, event: string, to: string][] {\n const result: [from: string, event: string, to: string][] = [];\n const index: Record<string, boolean> = {};\n if (state) {\n let prevStateKey = state.key;\n for (let parent = state.parent; parent; parent = parent.parent) {\n if (!parent.descriptor) continue;\n result.push(\n ...getTransitionsFromDescriptor(parent.descriptor, prevStateKey, index),\n );\n prevStateKey = parent.key;\n }\n }\n return result.reverse();\n}\n\nfunction getTransitionsFromDescriptor(\n descriptor: FsmStateDescriptor,\n prevStateKey: string,\n index: Record<string, boolean>,\n): [from: string, event: string, to: string][] {\n const result: [from: string, event: string, to: string][] = [];\n const prevStateKeys = [prevStateKey, \"*\"];\n for (const prevKey of prevStateKeys) {\n const targets = descriptor.transitions[prevKey];\n if (targets) {\n for (const [event, target] of Object.entries(targets)) {\n if (index[event]) continue;\n // Mark the event seen regardless of target — an inner exit-to-final\n // (`to === \"\"`, a falsy target) must still mask an outer rule for the\n // same event, matching what `dispatch` actually resolves.\n index[event] = true;\n result.push([prevStateKey, event, target]);\n }\n }\n }\n return result;\n}\n\n/**\n * Guard: would `event` trigger any transition in the process's current state? Used\n * to avoid dispatching dead events — the runner calls it before `dispatch`, and\n * consumers use it to enable/disable controls. Returns `true` iff `event` appears\n * among `getStateTransitions(process.state)`.\n */\nexport function isStateTransitionEnabled(\n process: FsmProcess,\n event: string,\n): boolean {\n const transitions = getStateTransitions(process.state);\n for (const [, ev] of transitions) {\n // A wildcard-event rule (`ev === EVENT_ANY`) matches any concrete event, just\n // as the engine's `getTargetStateKey` falls back to `(state, *)` / `(*, *)`.\n if (ev === event || ev === EVENT_ANY) return true;\n }\n return false;\n}\n","import { FsmProcess, type FsmProcessDump } from \"./core/fsm-process.ts\";\nimport type { FsmState } from \"./core/fsm-state.ts\";\nimport type { FsmStateConfig } from \"./core/fsm-state-config.ts\";\nimport { isStateTransitionEnabled } from \"./core/fsm-transitions.ts\";\n\n/**\n * Per-state behaviour contract used by `startProcess`. One function shape expresses\n * what to do while in a state, and its *return value* wires up the rest, so a state's\n * setup and teardown live together. The handler runs on entry with the shared\n * `context` and may return:\n * - nothing — no teardown;\n * - a cleanup `function` — registered as this state's `onExit`;\n * - an async/sync generator — run concurrently, each yielded string dispatched back\n * into the machine (self-driving/reactive states), auto-`return()`ed on exit.\n */\nexport type StageHandler<C = Record<string, unknown>> = (\n context: C,\n) =>\n | void\n | (() => void | Promise<void>)\n | Promise<void | (() => void | Promise<void>)>\n | AsyncGenerator<string, void, unknown>\n | Generator<string, void, unknown>;\n\n/**\n * The caller's remote control returned by `startProcess`: stop the machine and\n * snapshot/rehydrate it without holding a reference to the underlying `FsmProcess`.\n */\nexport interface ProcessHandle {\n shutdown(): Promise<void>;\n dump(...args: unknown[]): Promise<FsmProcessDump>;\n restore(dump: FsmProcessDump, ...args: unknown[]): Promise<void>;\n}\n\n// Context keys under which `startProcess` binds the machine into the shared context\n// object. Why via context (not closures): handlers reach the running machine\n// uniformly — `(ctx[KEY_DISPATCH])(event)` — regardless of where they are defined.\n/** Context key: `(event) => Promise<void>` that dispatches an event (guarded). */\nexport const KEY_DISPATCH = \"fsm:dispatch\";\n/** Context key: `() => Promise<void>` that shuts the machine down. */\nexport const KEY_TERMINATE = \"fsm:terminate\";\n/** Context key: the current state-key stack (root→leaf), refreshed on every transition. */\nexport const KEY_STATES = \"fsm:states\";\n/** Context key: the last dispatched event. */\nexport const KEY_EVENT = \"fsm:event\";\n\n// ---------------------------------------------------------------------------\n// Generator detection\n// ---------------------------------------------------------------------------\n\nfunction isGenerator(\n value: unknown,\n): value is\n | Generator<string, void, unknown>\n | AsyncGenerator<string, void, unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"next\" in value &&\n typeof (value as { next: unknown }).next === \"function\"\n );\n}\n\n// ---------------------------------------------------------------------------\n// startProcess (also exported as startFsmProcess for backward compat)\n// ---------------------------------------------------------------------------\n\n/**\n * Ergonomic runner: build a machine, attach behaviour via one `load` callback, and\n * bind the machine into `context`.\n *\n * Doing this by hand (`new FsmProcess` + `onStateCreate` + `onEnter` + a loader +\n * context wiring) is boilerplate every consumer repeats, so `startProcess` does it\n * once — most callers use this instead of the raw engine. It creates the process; on\n * each state entry calls `load(stateKey, event)` and installs the returned\n * `StageHandler`s (their return values become `onExit` cleanups or event-yielding\n * generators — see `StageHandler`); binds `KEY_DISPATCH` / `KEY_TERMINATE` /\n * `KEY_STATES` / `KEY_EVENT` into `context`; dispatches `startEvent` to enter the\n * initial state; and returns a `ProcessHandle`.\n *\n * @param context shared object handlers read/write and the machine is bound into\n * @param config the declarative machine definition\n * @param load returns the handler(s) to run for a given `(stateKey, event)`\n * @param startEvent initial event (default `\"\"`, the eventless start)\n */\nexport async function startProcess<C = unknown>(\n context: C,\n config: FsmStateConfig,\n load: (\n state: string,\n event: string | undefined,\n ) => StageHandler<C>[] | Promise<StageHandler<C>[]>,\n startEvent = \"\",\n): Promise<ProcessHandle> {\n let terminated = false;\n const ctx = context as Record<string, unknown>;\n const process = new FsmProcess(config);\n const statesStack: string[] = [];\n\n process.onStateCreate((state: FsmState) => {\n state.onEnter(async () => {\n statesStack.push(state.key);\n ctx[KEY_STATES] = [...statesStack];\n ctx[KEY_EVENT] = process.event;\n\n const modules = (await load(state.key, process.event)) ?? [];\n for (const module of Array.isArray(modules) ? modules : [modules]) {\n const result = await module?.(context);\n if (isGenerator(result)) {\n let stateExited = false;\n state.onExit(() => {\n stateExited = true;\n result.return?.(undefined as never);\n });\n (async () => {\n try {\n for await (const event of result) {\n if (stateExited || terminated) break;\n await dispatch(event);\n if (stateExited || terminated) break;\n }\n } catch (error) {\n // A generator `return()` during state exit / termination throws an\n // abort we intentionally swallow; a genuine error thrown by the\n // generator body must surface through the state's error handling\n // rather than vanish.\n if (!stateExited && !terminated) await state._handleError(error);\n }\n })();\n } else if (typeof result === \"function\") {\n state.onExit(result as () => void | Promise<void>);\n }\n }\n });\n state.onExit(() => {\n statesStack.pop();\n ctx[KEY_STATES] = [...statesStack];\n ctx[KEY_EVENT] = process.event;\n });\n });\n\n async function dispatch(event: string): Promise<void> {\n if (event !== undefined && isStateTransitionEnabled(process, event)) {\n await process.dispatch(event);\n }\n }\n async function terminate(): Promise<void> {\n terminated = true;\n await process.shutdown();\n }\n\n async function dumpProcess(...args: unknown[]): Promise<FsmProcessDump> {\n return process.dump(...args);\n }\n\n async function restoreProcess(\n dumpData: FsmProcessDump,\n ...args: unknown[]\n ): Promise<void> {\n statesStack.length = 0;\n terminated = false;\n await process.restore(dumpData, ...args);\n for (\n let state: FsmState | undefined = process.state;\n state;\n state = state.parent\n ) {\n statesStack.unshift(state.key);\n }\n ctx[KEY_STATES] = [...statesStack];\n ctx[KEY_EVENT] = process.event;\n }\n\n ctx[KEY_DISPATCH] = dispatch;\n ctx[KEY_TERMINATE] = terminate;\n await process.dispatch(startEvent);\n return {\n shutdown: terminate,\n dump: dumpProcess,\n restore: restoreProcess,\n };\n}\n\n/** Permanent equal alias of {@link startProcess} — the name existing consumers import. */\nexport const startFsmProcess = startProcess;\n","import type { FsmProcess } from \"../core/fsm-process.ts\";\n\n/** A sink for trace output — anything shaped like `console.log`. */\nexport type Printer = (...args: unknown[]) => void;\n/**\n * Tuning for a `Printer`.\n * - `prefix` — string prepended to every line (e.g. a process tag).\n * - `print` — the underlying sink (defaults to `console.log`).\n * - `lineNumbers` — prepend an incrementing `[n]` counter.\n */\nexport type PrinterConfig = {\n prefix?: string;\n print?: (...args: unknown[]) => void;\n lineNumbers?: boolean;\n};\n\nconst printerStore = new WeakMap<object, Printer>();\n\n/**\n * Build a `Printer` bound to `process` that indents each line by the current state\n * nesting depth (two spaces per level), so log output visually mirrors the state\n * tree — hierarchical indentation makes enter/exit traces readable at a glance.\n */\nexport function preparePrinter(\n process: FsmProcess,\n { prefix = \"\", print = console.log, lineNumbers = false }: PrinterConfig,\n): Printer {\n let lineCounter = 0;\n const shift = () => {\n let prefix = \"\";\n for (let s = process.state?.parent; s; s = s.parent) {\n prefix += \" \";\n }\n return prefix;\n };\n const getPrefix = lineNumbers ? () => `[${++lineCounter}]${shift()}` : shift;\n const printer = (...args: unknown[]) => print(prefix, getPrefix(), ...args);\n return printer;\n}\n\n/**\n * Attach a printer to `process` (stored in a weak map so it is GC'd with the\n * process). Handlers/tracers then reach it via {@link getProcessPrinter} /\n * {@link getPrinter} rather than threading a logger through every call.\n */\nexport function setProcessPrinter(\n process: FsmProcess,\n config: PrinterConfig = {},\n) {\n const printer = preparePrinter(process, config);\n printerStore.set(process, printer);\n}\n\n/** The printer attached to `process`, or `console.log` if none was set. */\nexport function getProcessPrinter(process: FsmProcess): Printer {\n return printerStore.get(process) || console.log;\n}\n\n/** The printer for a state — its own if set, else its process's (see {@link getProcessPrinter}). */\nexport function getPrinter(state: { process: FsmProcess }): Printer {\n return printerStore.get(state) || getProcessPrinter(state.process);\n}\n","import type { FsmProcess } from \"../core/fsm-process.ts\";\nimport type { FsmState } from \"../core/fsm-state.ts\";\nimport { getPrinter, type Printer } from \"./printer.ts\";\n\n/**\n * Trace every state of `process`: as each state is created, attach a state tracer —\n * so you can watch the machine move as a readable stream of enter/exit markers\n * without editing any handler. Hooks `onStateCreate` and delegates to\n * {@link setStateTracer}; pass a `print` sink to override the process printer.\n */\nexport function setProcessTracer(process: FsmProcess, print?: Printer) {\n return process.onStateCreate((state: FsmState) => {\n setStateTracer(state, print);\n });\n}\n\n/**\n * Trace one state's lifecycle: emit `<key event=\"…\">` on enter and `</key>` on exit\n * (XML-like, so nested states read as nested tags). Falls back to the state's\n * printer ({@link getPrinter}) when no `print` sink is given.\n */\nexport function setStateTracer(state: FsmState, print?: Printer) {\n state.onEnter(() => {\n const printLine = print || getPrinter(state);\n printLine(`<${state?.key} event=\"${state.process.event}\">`);\n });\n state.onExit(async () => {\n await Promise.resolve().then(async () => {\n const printLine = print || getPrinter(state);\n printLine(`</${state.key}> <!-- event=\"${state.process.event}\" -->`);\n });\n });\n}\n"],"mappings":";;;;;;;;;;;;;;AAeA,IAAa,eAAb,MAA0B;;kBACc,EAAE;;;;;;;CAUxC,YAAyB,MAAc,SAAY,SAAkB,MAAM;EACzE,IAAI,OAAO,KAAK,SAAS;AACzB,MAAI,CAAC,KACH,QAAO,KAAK,SAAS,QAAQ,EAAE;EAEjC,MAAM,IAAI;AACV,WAAS,KAAK,KAAK,EAAE,GAAG,KAAK,QAAQ,EAAE;AACvC,eAAa,KAAK,eAAe,MAAM,EAAE;;CAG3C,eAA4B,MAAc,SAAY;EACpD,IAAI,OAAO,KAAK,SAAS;AACzB,MAAI,CAAC,KAAM;AACX,SAAO,KAAK,QAAQ,MAAM,MAAM,QAAQ;AACxC,MAAI,KAAK,SAAS,EAChB,MAAK,SAAS,QAAQ;MAEtB,QAAO,KAAK,SAAS;;;CAKzB,MAAM,YAAY,MAAc,GAAG,MAAiB;EA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,aAAa,IAAI,QAAQ,IAAI,QAAQ;;;AAI9C,SAAgB,WAAW,OAAyC;AAClE,QAAO,aAAa,IAAI,MAAM,IAAI,kBAAkB,MAAM,QAAQ;;;;;;;;;;AClDpE,SAAgB,iBAAiB,SAAqB,OAAiB;AACrE,QAAO,QAAQ,eAAe,UAAoB;AAChD,iBAAe,OAAO,MAAM;GAC5B;;;;;;;AAQJ,SAAgB,eAAe,OAAiB,OAAiB;AAC/D,OAAM,cAAc;AAElB,GADkB,SAAS,WAAW,MAAM,EAClC,IAAI,OAAO,IAAI,UAAU,MAAM,QAAQ,MAAM,IAAI;GAC3D;AACF,OAAM,OAAO,YAAY;AACvB,QAAM,QAAQ,SAAS,CAAC,KAAK,YAAY;AAEvC,IADkB,SAAS,WAAW,MAAM,EAClC,KAAK,MAAM,IAAI,gBAAgB,MAAM,QAAQ,MAAM,OAAO;IACpE;GACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@statewalker/fsm",
3
- "version": "0.37.0",
3
+ "version": "0.38.1",
4
4
  "description": "HFSM Implementation",
5
5
  "keywords": [],
6
6
  "homepage": "https://github.com/statewalker/statewalker-fsm",
@@ -10,11 +10,7 @@
10
10
  },
11
11
  "license": "MIT",
12
12
  "type": "module",
13
- "bin": {
14
- "fsm": "./bin/cli.js"
15
- },
16
13
  "files": [
17
- "bin",
18
14
  "dist",
19
15
  "src"
20
16
  ],
@@ -28,19 +24,13 @@
28
24
  "types": "./dist/index.d.ts",
29
25
  "import": "./dist/index.js",
30
26
  "default": "./dist/index.js"
31
- },
32
- "./*": {
33
- "source": "./src/*.ts",
34
- "types": "./dist/*.d.ts",
35
- "import": "./dist/*.js",
36
- "default": "./dist/*.js"
37
27
  }
38
28
  },
39
29
  "devDependencies": {
40
- "@biomejs/biome": "^2.3.0",
41
- "tsdown": "^0.12.4",
42
- "typescript": "^5.9.2",
43
- "vitest": "^3.2.4"
30
+ "@biomejs/biome": "catalog:",
31
+ "tsdown": "catalog:",
32
+ "typescript": "^6.0.3",
33
+ "vitest": "catalog:"
44
34
  },
45
35
  "repository": {
46
36
  "type": "git",
@@ -1,10 +1,29 @@
1
1
  type Handler<P extends unknown[] = unknown[], R = unknown> = (...args: P) => R;
2
2
 
3
+ /**
4
+ * Shared handler-registry substrate under both `FsmProcess` and `FsmState`.
5
+ *
6
+ * Both the process and every state need the same primitive: keep named lists of
7
+ * callbacks (`onEnter`, `onExit`, `dump`, …) and run them with consistent ordering
8
+ * and error routing. Centralising it here keeps the two subclasses thin and their
9
+ * hook methods one-liners. `handlers` maps a hook name to its ordered callback list;
10
+ * the protected `_addHandler` / `_removeHandler` / `_runHandler` manage and invoke
11
+ * them. Handlers run **sequentially** (awaited in turn); a throwing handler is routed
12
+ * to `_handleError` rather than aborting the batch. Subclasses expose typed sugar
13
+ * (e.g. `state.onEnter(fn)` calls `_addHandler("onEnter", fn)`) and override
14
+ * `_handleError` to forward errors.
15
+ */
3
16
  export class FsmBaseClass {
4
17
  handlers: Record<string, Handler[]> = {};
5
18
 
6
19
  // ----------------------------------------------
7
20
  // internal methods
21
+
22
+ /**
23
+ * Register `handler` under `type`; returns a disposer that removes it.
24
+ * `direct=false` prepends instead of appends — used so `onExit` handlers run in
25
+ * reverse (inner-to-outer) unwinding order.
26
+ */
8
27
  protected _addHandler<T>(type: string, handler: T, direct: boolean = true) {
9
28
  let list = this.handlers[type];
10
29
  if (!list) {
@@ -26,6 +45,7 @@ export class FsmBaseClass {
26
45
  }
27
46
  }
28
47
 
48
+ /** Run every handler of `type` in order, awaiting each; route throws to `_handleError`. */
29
49
  async _runHandler(type: string, ...args: unknown[]) {
30
50
  const list = this.handlers[type] || [];
31
51
  for (const handler of list) {
@@ -37,11 +57,16 @@ export class FsmBaseClass {
37
57
  }
38
58
  }
39
59
 
60
+ /** Default error sink — logs. `FsmState`/`FsmProcess` override it to fire `onStateError`. */
40
61
  async _handleError(error: Error | unknown) {
41
62
  console.error(error);
42
63
  }
43
64
  }
44
65
 
66
+ /**
67
+ * Bind the named methods of `obj` to `obj` in place, so they can be passed as bare
68
+ * callbacks (e.g. `ctx[KEY_DISPATCH] = process.dispatch`) without losing `this`.
69
+ */
45
70
  export function bindMethods<T>(obj: T, ...methods: (string | symbol)[]) {
46
71
  const o = obj as Record<string | symbol, unknown>;
47
72
  for (const methodName of methods) {
@@ -12,22 +12,36 @@ import {
12
12
  } from "./fsm-state-config.ts";
13
13
  import { FsmStateDescriptor } from "./fsm-state-descriptor.ts";
14
14
 
15
+ // Status bitmask: where the process is in the enter/exit cycle of `dispatch`.
16
+ // Why a bitmask (rather than an enum): the loop tests *phases* with cheap bitwise
17
+ // masks — `status & STATUS_ENTER`, `status & this.mask` — and composite masks
18
+ // (ENTER / EXIT) are just OR-combinations of the primitive bits.
19
+ /** Not started / no current transition. */
15
20
  export const STATUS_NONE = 0;
21
+ /** Entering: descended into a parent's first (initial) child. */
16
22
  export const STATUS_FIRST = 1;
23
+ /** Entering: advanced to a resolved target (sibling) state. */
17
24
  export const STATUS_NEXT = 2;
25
+ /** Rested on a leaf — dispatch returns control here (the default `mask`). */
18
26
  export const STATUS_LEAF = 4;
27
+ /** Exiting: popped back up to the parent state. */
19
28
  export const STATUS_LAST = 8;
29
+ /** Terminated: the machine has exited its root and cannot advance further. */
20
30
  export const STATUS_FINISHED = 16;
21
31
 
22
32
  //
33
+ /** Composite: any "entering" phase. */
23
34
  export const STATUS_ENTER = STATUS_FIRST | STATUS_NEXT;
35
+ /** Composite: any "exiting" phase. */
24
36
  export const STATUS_EXIT = STATUS_LEAF | STATUS_LAST;
25
37
 
38
+ /** A process-level handler (`onStateCreate` / `onStateError`). */
26
39
  export type FsmProcessHandler = (
27
40
  process: FsmProcess,
28
41
  ...args: unknown[]
29
42
  ) => void | Promise<void>;
30
43
 
44
+ /** Serialized form of the whole machine: status, last event, and the root→leaf state stack. */
31
45
  export type FsmProcessDump = Record<string, unknown> & {
32
46
  status: number;
33
47
  event?: string;
@@ -39,10 +53,23 @@ export type FsmProcessDumpHandler = (
39
53
  dump: FsmProcessDump,
40
54
  ) => void | Promise<void>;
41
55
 
56
+ /**
57
+ * The running state machine — owner of the active-state stack and the traversal.
58
+ *
59
+ * This is the engine: given a compiled config it drives the enter/exit walk in
60
+ * response to events, so callers reason in terms of states and events, not manual
61
+ * stack bookkeeping. `dispatch(event)` advances the machine to the next resting leaf;
62
+ * `shutdown(event?)` unwinds every active state; `state` is the current leaf;
63
+ * `onStateCreate(handler)` is the primary extension point (fires once per created
64
+ * state — attach that state's hooks there); and `dump()` / `restore(dump)` snapshot
65
+ * and rehydrate the whole stack. Typical use: `new FsmProcess(config)`, register
66
+ * `onStateCreate`, then `dispatch("")` to enter the initial state and
67
+ * `dispatch(event)` for each subsequent event.
68
+ */
42
69
  export class FsmProcess extends FsmBaseClass {
43
70
  state?: FsmState;
44
71
  event?: string;
45
- nextEvent?: string;
72
+ nextEvents: string[] = [];
46
73
  running: boolean = false;
47
74
  mask: number = STATUS_LEAF;
48
75
  status: number = 0;
@@ -56,6 +83,7 @@ export class FsmProcess extends FsmBaseClass {
56
83
  bindMethods(this, "dispatch", "dump", "restore");
57
84
  }
58
85
 
86
+ /** Force-exit the whole stack (root last), running each state's `onExit`; ends the machine. */
59
87
  async shutdown(event?: string) {
60
88
  while (this.state) {
61
89
  this.event = event;
@@ -65,36 +93,49 @@ export class FsmProcess extends FsmBaseClass {
65
93
  }
66
94
  }
67
95
 
96
+ /**
97
+ * Feed an event to the machine and run the enter/exit cycle until it rests on a
98
+ * leaf (`status & mask`) or finishes.
99
+ *
100
+ * If a dispatch is already running (e.g. an `onEnter` handler dispatches
101
+ * synchronously), the event is appended to the `nextEvents` FIFO queue and applied
102
+ * — in order, none dropped — when the current run settles; runs never nest. Returns
103
+ * `false` once the machine has finished, `true` otherwise.
104
+ */
68
105
  async dispatch(event: string): Promise<boolean> {
69
- this.nextEvent = event;
106
+ // Queue the event. Re-entrant dispatches (from handlers running mid-settle)
107
+ // append here and are drained in order — so no earlier event is overwritten.
108
+ this.nextEvents.push(event);
70
109
  if (!this.running && !(this.status & STATUS_FINISHED)) {
71
110
  this.running = true;
72
111
  try {
73
- this.event = this.nextEvent;
74
- this.nextEvent = undefined;
75
- while (true) {
76
- // ---
77
- if (this.status & STATUS_EXIT) {
78
- await this.state?._runHandler("onExit", this.state);
112
+ while (this.nextEvents.length > 0) {
113
+ this.event = this.nextEvents.shift();
114
+ while (true) {
115
+ // ---
116
+ if (this.status & STATUS_EXIT) {
117
+ await this.state?._runHandler("onExit", this.state);
118
+ }
119
+ if (!(await this._update())) break;
120
+ if (this.status & STATUS_ENTER) {
121
+ await this.state?._runHandler("onEnter", this.state);
122
+ }
123
+ if (this.status & this.mask) break;
124
+ // ---
79
125
  }
80
- if (!(await this._update())) break;
81
- if (this.status & STATUS_ENTER) {
82
- await this.state?._runHandler("onEnter", this.state);
83
- }
84
- if (this.status & this.mask) break;
85
- // ---
126
+ if (this.status & STATUS_FINISHED) break;
86
127
  }
87
128
  } finally {
88
129
  this.running = false;
89
130
  }
90
- const nextEvent = this.nextEvent;
91
- if (nextEvent !== undefined) {
92
- return Promise.resolve().then(() => this.dispatch(nextEvent));
93
- }
94
131
  }
95
132
  return !(this.status & STATUS_FINISHED);
96
133
  }
97
134
 
135
+ /**
136
+ * Snapshot the machine to a plain object: `{ status, event, stack }` where the
137
+ * stack is root→leaf, each entry carrying whatever its `dump` hooks recorded.
138
+ */
98
139
  async dump(...args: unknown[]): Promise<FsmProcessDump> {
99
140
  const dumpState = async (state: FsmState) => {
100
141
  const stateDump: FsmStateDump = {
@@ -121,6 +162,11 @@ export class FsmProcess extends FsmBaseClass {
121
162
  return dump;
122
163
  }
123
164
 
165
+ /**
166
+ * Rebuild the machine from a `dump`: recreate each state in the stack (firing
167
+ * `onStateCreate`) and replay its `restore` hooks, leaving the process resumable
168
+ * from where it was snapshotted.
169
+ */
124
170
  async restore(dump: FsmProcessDump, ...args: unknown[]) {
125
171
  this.status = dump.status || 0;
126
172
  this.event = dump.event;
@@ -140,6 +186,7 @@ export class FsmProcess extends FsmBaseClass {
140
186
  return this;
141
187
  }
142
188
 
189
+ /** Primary extension point: fires once for every state the machine creates. */
143
190
  onStateCreate(handler: FsmStateHandler) {
144
191
  return this._addHandler("onStateCreate", handler, true);
145
192
  }
@@ -191,6 +238,14 @@ export class FsmProcess extends FsmBaseClass {
191
238
  return this._newState(parent, toState, descriptor);
192
239
  }
193
240
 
241
+ /**
242
+ * One step of the traversal: compute the next state and update `status`.
243
+ *
244
+ * Either descends to a child / advances to a resolved target (setting an ENTER
245
+ * status), or — when no target resolves — settles on the current leaf
246
+ * (`STATUS_LEAF`) or pops to the parent (`STATUS_LAST`), reaching `STATUS_FINISHED`
247
+ * once the root is exited. Returns `false` when finished.
248
+ */
194
249
  async _update() {
195
250
  if (this.status & STATUS_FINISHED) return false;
196
251
  const nextState =
@@ -1,11 +1,38 @@
1
+ // Sentinel keys used inside `FsmStateConfig.transitions` tuples. The raw `""` and
2
+ // `"*"` literals are ambiguous at the call site — `["", "start", "Active"]` does not
3
+ // visibly say "from the *initial* state" — so these named constants document intent
4
+ // while keeping the runtime value (a shared empty string / asterisk) identical, which
5
+ // keeps configs plain-serializable.
6
+
7
+ /** Wildcard `from`-state: a transition that applies in *any* state. */
1
8
  export const STATE_ANY = "*";
9
+ /** Empty `from`-state: the *initial* pseudo-state a parent enters into. */
2
10
  export const STATE_INITIAL = "";
11
+ /** Empty `to`-state: the *final* pseudo-state; entering it exits the parent. */
3
12
  export const STATE_FINAL = "";
13
+ /** Wildcard `event`: a transition triggered by *any* event. */
4
14
  export const EVENT_ANY = "*";
15
+ /** Empty event: the eventless/automatic transition (fires with no named event). */
5
16
  export const EVENT_EMPTY = "";
6
17
 
7
18
  export type FsmStateKey = string;
8
19
  export type FsmEventKey = string;
20
+
21
+ /**
22
+ * Declarative definition of a (possibly nested) state machine.
23
+ *
24
+ * One plain-object shape describes an entire HFSM, so machines stay serializable,
25
+ * diffable, and inspectable by tooling — the config is data, not code. A config has:
26
+ * - `key` — the state's name (unique among its siblings);
27
+ * - `transitions` — `[from, event, to]` tuples, where `from`/`to` name sibling
28
+ * states, `""` is the initial (`from`) or final (`to`) pseudo-state, and `"*"` is a
29
+ * wildcard (see the constants above);
30
+ * - `states` — nested child configs; entering this state descends into its initial
31
+ * child. The index signature lets consumers attach arbitrary metadata.
32
+ *
33
+ * Pass a config to `new FsmProcess(config)` or `startProcess(ctx, config, …)`; it is
34
+ * compiled once into an `FsmStateDescriptor` for fast lookup at runtime.
35
+ */
9
36
  export type FsmStateConfig = {
10
37
  key: FsmStateKey;
11
38
  transitions?: [from: FsmStateKey, event: FsmEventKey, to: FsmStateKey][];
@@ -5,10 +5,24 @@ import {
5
5
  STATE_FINAL,
6
6
  } from "./fsm-state-config.ts";
7
7
 
8
+ /**
9
+ * The *compiled* form of an `FsmStateConfig` subtree.
10
+ *
11
+ * Resolving a transition happens on every event, so the flat `[from, event, to]`
12
+ * tuple list is pre-indexed once into nested maps for O(1) lookup, and the
13
+ * wildcard-fallback order is applied here rather than re-derived on each dispatch.
14
+ * The shape is `transitions[from][event] = to` plus a `states` map of child
15
+ * descriptors. `FsmProcess` builds one from your config in its constructor; you
16
+ * rarely construct a descriptor directly.
17
+ */
8
18
  export class FsmStateDescriptor {
9
19
  transitions: Record<string, Record<string, string>> = {};
10
20
  states: Record<string, FsmStateDescriptor> = {};
11
21
 
22
+ /**
23
+ * Recursively compile a config (and its nested `states`) into descriptors,
24
+ * turning the tuple list into the indexed `transitions` map.
25
+ */
12
26
  static build(config: FsmStateConfig) {
13
27
  const descriptor = new FsmStateDescriptor();
14
28
  for (const [from, event, to] of config.transitions || []) {
@@ -27,6 +41,13 @@ export class FsmStateDescriptor {
27
41
  return descriptor;
28
42
  }
29
43
 
44
+ /**
45
+ * Resolve the target state for a `(stateKey, eventKey)` pair. Tries the most
46
+ * specific match first, then falls back through the wildcards —
47
+ * `(state, event)` → `(*, event)` → `(state, *)` → `(*, *)` — and returns
48
+ * `STATE_FINAL` if nothing matches, so an unmatched event exits the state rather
49
+ * than silently doing nothing.
50
+ */
30
51
  getTargetStateKey(stateKey: string, eventKey: string) {
31
52
  const pairs = [
32
53
  [stateKey, eventKey],
@@ -2,25 +2,41 @@ import { bindMethods, FsmBaseClass } from "./fsm-base-class.ts";
2
2
  import type { FsmProcess } from "./fsm-process.ts";
3
3
  import type { FsmStateDescriptor } from "./fsm-state-descriptor.ts";
4
4
 
5
+ /** Serialized form of a single state: its `key` plus the `data` bag its `dump` hooks filled. */
5
6
  export type FsmStateDump = Record<string, unknown> & {
6
7
  key: string;
7
8
  data: Record<string, unknown>;
8
9
  };
10
+ /** An `onEnter` / `onExit` callback; receives the state it fired on. */
9
11
  export type FsmStateHandler = (
10
12
  state: FsmState,
11
13
  ...args: unknown[]
12
14
  ) => void | Promise<void>;
13
15
 
16
+ /** A `dump` / `restore` callback; reads or fills the mutable per-state `data` bag. */
14
17
  export type FsmStateDumpHandler = (
15
18
  state: FsmState,
16
19
  dump: FsmStateDump,
17
20
  ) => void | Promise<void>;
18
21
 
22
+ /** An `onStateError` callback; receives the error thrown by another handler on this state. */
19
23
  export type FsmStateErrorHandler = (
20
24
  state: FsmState,
21
25
  error: unknown,
22
26
  ) => void | Promise<void>;
23
27
 
28
+ /**
29
+ * One live node in a running machine's active-state stack.
30
+ *
31
+ * A state needs a place to attach behaviour and record data while it is active.
32
+ * `FsmState` is that handle — created by the engine each time a state is entered,
33
+ * discarded when it exits — so handlers can capture per-activation closures instead
34
+ * of sharing mutable machine-wide state. It offers lifecycle hooks `onEnter` /
35
+ * `onExit` / `onStateError`, serialization hooks `dump` / `restore`, and the tree
36
+ * links `key` / `parent` / `descriptor`; every hook method returns a disposer.
37
+ * Attach hooks from within `FsmProcess.onStateCreate((state) => …)`, or let
38
+ * `startProcess` install them for you from a `load` callback.
39
+ */
24
40
  export class FsmState extends FsmBaseClass {
25
41
  process: FsmProcess;
26
42
  key: string;
@@ -41,24 +57,38 @@ export class FsmState extends FsmBaseClass {
41
57
  bindMethods(this, "onEnter", "onExit", "dump", "restore", "onStateError");
42
58
  }
43
59
 
60
+ /** Run when this state is entered. */
44
61
  onEnter(handler: FsmStateHandler) {
45
62
  return this._addHandler("onEnter", handler, true);
46
63
  }
64
+ /** Run when this state exits — registered inner-first so unwinding is inner-to-outer. */
47
65
  onExit(handler: FsmStateHandler) {
48
66
  return this._addHandler("onExit", handler, false);
49
67
  }
68
+ /** Handle an error thrown by another handler on this state (also bubbles to the process). */
50
69
  onStateError(handler: FsmStateErrorHandler) {
51
70
  return this._addHandler("onStateError", handler);
52
71
  }
72
+ /** Contribute to this state's snapshot: fill `dump.data` when the process is dumped. */
53
73
  dump(handler: FsmStateDumpHandler) {
54
74
  return this._addHandler("dump", handler, true);
55
75
  }
76
+ /** Rehydrate from this state's snapshot: read `dump.data` when the process is restored. */
56
77
  restore(handler: FsmStateDumpHandler) {
57
78
  return this._addHandler("restore", handler, true);
58
79
  }
59
80
 
60
81
  async _handleError(error: Error | unknown) {
61
- await this._runHandler("onStateError", this, error);
82
+ // Run the state's own error handlers directly — NOT via `_runHandler`, whose
83
+ // catch re-routes to `_handleError`, which would re-enter `onStateError`
84
+ // forever. A throw from an error handler terminates at `console.error`.
85
+ for (const handler of this.handlers.onStateError ?? []) {
86
+ try {
87
+ await handler(this, error);
88
+ } catch (e) {
89
+ console.error(e);
90
+ }
91
+ }
62
92
  await this.process._handleStateError(this, error);
63
93
  }
64
94
  }
@@ -0,0 +1,75 @@
1
+ import type { FsmProcess } from "./fsm-process.ts";
2
+ import type { FsmState } from "./fsm-state.ts";
3
+ import { EVENT_ANY } from "./fsm-state-config.ts";
4
+ import type { FsmStateDescriptor } from "./fsm-state-descriptor.ts";
5
+
6
+ // ---------------------------------------------------------------------------
7
+ // Transition introspection — read-only queries over the state/transition graph
8
+ // ---------------------------------------------------------------------------
9
+
10
+ /**
11
+ * List the transitions currently reachable from `state` — for a UI or viewer that
12
+ * needs to know which events can fire right now (e.g. to render only the enabled
13
+ * buttons). Collects `[from, event, to]` tuples by walking up the parent chain; the
14
+ * nearest state's rule for an event wins, so an outer fallback is masked by an inner
15
+ * override. The returned tuples are ordered outer→inner (root first).
16
+ */
17
+ export function getStateTransitions(
18
+ state?: FsmState,
19
+ ): [from: string, event: string, to: string][] {
20
+ const result: [from: string, event: string, to: string][] = [];
21
+ const index: Record<string, boolean> = {};
22
+ if (state) {
23
+ let prevStateKey = state.key;
24
+ for (let parent = state.parent; parent; parent = parent.parent) {
25
+ if (!parent.descriptor) continue;
26
+ result.push(
27
+ ...getTransitionsFromDescriptor(parent.descriptor, prevStateKey, index),
28
+ );
29
+ prevStateKey = parent.key;
30
+ }
31
+ }
32
+ return result.reverse();
33
+ }
34
+
35
+ function getTransitionsFromDescriptor(
36
+ descriptor: FsmStateDescriptor,
37
+ prevStateKey: string,
38
+ index: Record<string, boolean>,
39
+ ): [from: string, event: string, to: string][] {
40
+ const result: [from: string, event: string, to: string][] = [];
41
+ const prevStateKeys = [prevStateKey, "*"];
42
+ for (const prevKey of prevStateKeys) {
43
+ const targets = descriptor.transitions[prevKey];
44
+ if (targets) {
45
+ for (const [event, target] of Object.entries(targets)) {
46
+ if (index[event]) continue;
47
+ // Mark the event seen regardless of target — an inner exit-to-final
48
+ // (`to === ""`, a falsy target) must still mask an outer rule for the
49
+ // same event, matching what `dispatch` actually resolves.
50
+ index[event] = true;
51
+ result.push([prevStateKey, event, target]);
52
+ }
53
+ }
54
+ }
55
+ return result;
56
+ }
57
+
58
+ /**
59
+ * Guard: would `event` trigger any transition in the process's current state? Used
60
+ * to avoid dispatching dead events — the runner calls it before `dispatch`, and
61
+ * consumers use it to enable/disable controls. Returns `true` iff `event` appears
62
+ * among `getStateTransitions(process.state)`.
63
+ */
64
+ export function isStateTransitionEnabled(
65
+ process: FsmProcess,
66
+ event: string,
67
+ ): boolean {
68
+ const transitions = getStateTransitions(process.state);
69
+ for (const [, ev] of transitions) {
70
+ // A wildcard-event rule (`ev === EVENT_ANY`) matches any concrete event, just
71
+ // as the engine's `getTargetStateKey` falls back to `(state, *)` / `(*, *)`.
72
+ if (ev === event || ev === EVENT_ANY) return true;
73
+ }
74
+ return false;
75
+ }
package/src/core/index.ts CHANGED
@@ -3,3 +3,4 @@ export * from "./fsm-process.ts";
3
3
  export * from "./fsm-state.ts";
4
4
  export * from "./fsm-state-config.ts";
5
5
  export * from "./fsm-state-descriptor.ts";
6
+ export * from "./fsm-transitions.ts";
package/src/index.ts CHANGED
@@ -1,3 +1,3 @@
1
1
  export * from "./core/index.ts";
2
- export * from "./orchestrator/index.ts";
3
- export * from "./utils/index.ts";
2
+ export * from "./start-process.ts";
3
+ export * from "./trace/index.ts";