@doeixd/machine 0.0.22 → 1.0.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.
Files changed (51) hide show
  1. package/README.md +103 -65
  2. package/dist/cjs/development/core.js +19 -45
  3. package/dist/cjs/development/core.js.map +3 -3
  4. package/dist/cjs/development/index.js +51 -46
  5. package/dist/cjs/development/index.js.map +4 -4
  6. package/dist/cjs/development/react.js +1942 -0
  7. package/dist/cjs/development/react.js.map +7 -0
  8. package/dist/cjs/production/core.js +1 -1
  9. package/dist/cjs/production/index.js +3 -3
  10. package/dist/cjs/production/react.js +1 -0
  11. package/dist/esm/development/core.js +19 -45
  12. package/dist/esm/development/core.js.map +3 -3
  13. package/dist/esm/development/index.js +51 -46
  14. package/dist/esm/development/index.js.map +4 -4
  15. package/dist/esm/development/react.js +1928 -0
  16. package/dist/esm/development/react.js.map +7 -0
  17. package/dist/esm/production/core.js +1 -1
  18. package/dist/esm/production/index.js +3 -3
  19. package/dist/esm/production/react.js +1 -0
  20. package/dist/types/actor.d.ts +4 -4
  21. package/dist/types/actor.d.ts.map +1 -1
  22. package/dist/types/context-bound.d.ts +94 -0
  23. package/dist/types/context-bound.d.ts.map +1 -0
  24. package/dist/types/entry-react.d.ts +6 -0
  25. package/dist/types/entry-react.d.ts.map +1 -0
  26. package/dist/types/functional-combinators.d.ts +5 -5
  27. package/dist/types/generators.d.ts +2 -2
  28. package/dist/types/index.d.ts +14 -29
  29. package/dist/types/index.d.ts.map +1 -1
  30. package/dist/types/primitives.d.ts +25 -5
  31. package/dist/types/primitives.d.ts.map +1 -1
  32. package/dist/types/react.d.ts +133 -0
  33. package/dist/types/react.d.ts.map +1 -0
  34. package/dist/types/utils.d.ts +22 -22
  35. package/dist/types/utils.d.ts.map +1 -1
  36. package/package.json +13 -1
  37. package/src/actor.ts +1 -1
  38. package/src/context-bound.ts +147 -0
  39. package/src/entry-react.ts +9 -2
  40. package/src/functional-combinators.ts +5 -5
  41. package/src/generators.ts +2 -2
  42. package/src/higher-order.ts +2 -2
  43. package/src/index.ts +31 -68
  44. package/src/middleware/time-travel.ts +2 -2
  45. package/src/middleware.ts +2 -2
  46. package/src/multi.ts +4 -4
  47. package/src/primitives.ts +34 -14
  48. package/src/prototype_functional.ts +2 -2
  49. package/src/react.ts +1 -2
  50. package/src/test.ts +7 -7
  51. package/src/utils.ts +31 -31
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/generators.ts", "../../../src/primitives.ts", "../../../src/multi.ts", "../../../src/higher-order.ts", "../../../src/middleware/core.ts", "../../../src/middleware/history.ts", "../../../src/middleware/snapshot.ts", "../../../src/middleware/time-travel.ts", "../../../src/middleware/composition.ts", "../../../src/utils.ts", "../../../src/functional-combinators.ts", "../../../src/index.ts"],
4
- "sourcesContent": ["/**\n * @file Generator-based state machine composition utilities.\n * @description\n * This module provides a generator-based approach to composing state machine transitions.\n * Instead of chaining method calls or using composition functions, you can write\n * imperative-style code using generators that feels like sequential, synchronous code\n * while maintaining the immutability and type safety of the state machine model.\n *\n * This pattern is particularly useful for:\n * - Multi-step workflows where each step depends on the previous\n * - Complex transition logic that would be unwieldy with chaining\n * - When you want imperative control flow (if/else, loops) with immutable state\n * - Testing scenarios where you want to control the flow step-by-step\n *\n * @example\n * ```typescript\n * const result = run(function* (machine) {\n * // Each yield passes control back and receives the next state\n * let m = yield* step(machine.increment());\n * m = yield* step(m.add(5));\n * if (m.context.count > 10) {\n * m = yield* step(m.reset());\n * }\n * return m.context.count;\n * }, initialMachine);\n * ```\n */\n\n\n\n/**\n * Runs a generator-based state machine flow to completion.\n *\n * This function executes a generator that yields machine states and returns a final value.\n * Each yield passes the current machine state back to the generator, allowing you to\n * write imperative-style code while maintaining immutability.\n *\n * **How it works:**\n * 1. The generator function receives the initial machine\n * 2. Each `yield` expression produces a new machine state\n * 3. That state is sent back into the generator via `next()`\n * 4. The generator can use the received state for the next operation\n * 5. When the generator returns, that value is returned from `run()`\n *\n * **Key insight:** The generator doesn't mutate state—it yields new immutable states\n * at each step, creating a clear audit trail of state transitions.\n *\n * @template C - The context object type for the machine.\n * @template T - The return type of the generator (can be any type).\n *\n * @param flow - A generator function that receives a machine and yields machines,\n * eventually returning a value of type T.\n * @param initial - The initial machine state to start the flow.\n *\n * @returns The final value returned by the generator.\n *\n * @example Basic usage with counter\n * ```typescript\n * const counter = createMachine({ count: 0 }, {\n * increment: function() {\n * return createMachine({ count: this.count + 1 }, this);\n * },\n * add: function(n: number) {\n * return createMachine({ count: this.count + n }, this);\n * }\n * });\n *\n * const finalCount = run(function* (m) {\n * m = yield* step(m.increment()); // count: 1\n * m = yield* step(m.add(5)); // count: 6\n * m = yield* step(m.increment()); // count: 7\n * return m.context.count;\n * }, counter);\n *\n * console.log(finalCount); // 7\n * ```\n *\n * @example Conditional logic\n * ```typescript\n * const result = run(function* (m) {\n * m = yield* step(m.increment());\n *\n * if (m.context.count > 5) {\n * m = yield* step(m.reset());\n * } else {\n * m = yield* step(m.add(10));\n * }\n *\n * return m;\n * }, counter);\n * ```\n *\n * @example Loops and accumulation\n * ```typescript\n * const sum = run(function* (m) {\n * let total = 0;\n *\n * for (let i = 0; i < 5; i++) {\n * m = yield* step(m.increment());\n * total += m.context.count;\n * }\n *\n * return total;\n * }, counter);\n * ```\n *\n * @example Error handling\n * ```typescript\n * const result = run(function* (m) {\n * try {\n * m = yield* step(m.riskyOperation());\n * m = yield* step(m.processResult());\n * } catch (error) {\n * m = yield* step(m.handleError(error));\n * }\n * return m;\n * }, machine);\n * ```\n */\nexport function run<C extends any = any, M extends { context: C } & Record<string, any> = { context: C }, T = any>(\n flow: (m: M) => Generator<M, T, M>,\n initial: M\n): T {\n // Create the generator by calling the flow function with the initial machine\n const generator = flow(initial);\n\n // Track the current machine state as we iterate\n let current = initial;\n\n // Iterate the generator until completion\n while (true) {\n // Send the current machine state into the generator and get the next yielded value\n // The generator receives `current` as the result of its last yield expression\n const { value, done } = generator.next(current);\n\n // If the generator has returned (done), we have our final value\n if (done) {\n return value as T;\n }\n\n // Otherwise, the yielded value becomes our new current state\n // This state will be sent back into the generator on the next iteration\n current = value as M;\n }\n}\n\n/**\n * A helper function to yield a machine state and receive the next state back.\n *\n * This function creates a mini-generator that yields the provided machine and\n * returns whatever value the outer runner sends back. It's designed to be used\n * with `yield*` (yield delegation) inside your main generator.\n *\n * **Why use this helper?**\n * - Makes the intent clear: \"step to this state\"\n * - Provides a consistent API for state transitions\n * - Enables type inference for the received state\n * - Works seamlessly with the `run()` function\n *\n * **What `yield*` does:**\n * `yield*` delegates to another generator. When you write `yield* step(m)`,\n * control passes to the `step` generator, which yields `m`, then returns the\n * value sent back by the runner.\n *\n * @template C - The context object type for the machine.\n *\n * @param m - The machine state to yield.\n *\n * @returns A generator that yields the machine and returns the received state.\n *\n * @example Basic stepping\n * ```typescript\n * run(function* (machine) {\n * // Yield this state and receive the next one\n * const next = yield* step(machine.increment());\n * console.log(next.context.count);\n * return next;\n * }, counter);\n * ```\n *\n * @example Without step (more verbose)\n * ```typescript\n * run(function* (machine) {\n * // This is what step() does internally\n * const next = yield machine.increment();\n * return next;\n * }, counter);\n * ```\n *\n * @example Chaining with step\n * ```typescript\n * run(function* (m) {\n * m = yield* step(m.action1());\n * m = yield* step(m.action2());\n * m = yield* step(m.action3());\n * return m;\n * }, machine);\n * ```\n */\nexport function step<C extends any = any, M extends { context: C } & Record<string, any> = { context: C }>(\n m: M\n): Generator<M, M, M> {\n // Create an immediately-invoked generator that:\n // 1. Yields the provided machine\n // 2. Receives a value back (the next state)\n // 3. Returns that received value\n return (function* () {\n const received = yield m;\n return received;\n })();\n}\n\n/**\n * Alternative to `step` that doesn't require `yield*`.\n * This is semantically identical but uses direct yielding.\n *\n * Use this if you prefer the simpler syntax without delegation.\n *\n * @template C - The context object type.\n * @param m - The machine to yield.\n * @returns The same machine (passed through).\n *\n * @example\n * ```typescript\n * run(function* (m) {\n * m = yield m.increment(); // No yield* needed\n * m = yield m.add(5);\n * return m;\n * }, counter);\n * ```\n */\nexport function yieldMachine<C extends any = any, M extends { context: C } & Record<string, any> = { context: C }>(m: M): M {\n return m;\n}\n\n/**\n * Runs multiple generator flows in sequence, passing the result of each to the next.\n *\n * This is useful for composing multiple generator-based workflows into a pipeline.\n *\n * @template C - The context object type.\n * @param initial - The initial machine state.\n * @param flows - An array of generator functions to run in sequence.\n * @returns The final machine state after all flows complete.\n *\n * @example\n * ```typescript\n * const flow1 = function* (m: Machine<{ count: number }>) {\n * m = yield* step(m.increment());\n * return m;\n * };\n *\n * const flow2 = function* (m: Machine<{ count: number }>) {\n * m = yield* step(m.add(5));\n * return m;\n * };\n *\n * const result = runSequence(counter, [flow1, flow2]);\n * console.log(result.context.count); // 6\n * ```\n */\nexport function runSequence<C extends any = any, M extends { context: C } & Record<string, any> = { context: C }>(\n initial: M,\n flows: Array<(m: M) => Generator<M, M, M>>\n): M {\n return flows.reduce((machine, flow) => {\n return run(flow, machine);\n }, initial);\n}\n\n/**\n * Creates a reusable generator flow that can be composed into other flows.\n *\n * This allows you to define common state machine patterns as reusable building blocks.\n *\n * @template C - The context object type.\n * @param flow - A generator function representing a reusable flow.\n * @returns A function that can be used with `yield*` in other generators.\n *\n * @example\n * ```typescript\n * // Define a reusable flow\n * const incrementThrice = createFlow(function* (m: Machine<{ count: number }>) {\n * m = yield* step(m.increment());\n * m = yield* step(m.increment());\n * m = yield* step(m.increment());\n * return m;\n * });\n *\n * // Use it in another flow\n * const result = run(function* (m) {\n * m = yield* incrementThrice(m);\n * m = yield* step(m.add(10));\n * return m;\n * }, counter);\n * ```\n */\nexport function createFlow<C extends any = any, M extends { context: C } & Record<string, any> = { context: C }>(\n flow: (m: M) => Generator<M, M, M>\n): (m: M) => Generator<M, M, M> {\n return flow;\n}\n\n/**\n * Runs a generator flow with debugging output at each step.\n *\n * This is useful for understanding the state transitions in your flow.\n *\n * @template C - The context object type.\n * @template T - The return type.\n * @param flow - The generator function to run.\n * @param initial - The initial machine state.\n * @param logger - Optional custom logger function.\n * @returns The final value from the generator.\n *\n * @example\n * ```typescript\n * const result = runWithDebug(function* (m) {\n * m = yield* step(m.increment());\n * m = yield* step(m.add(5));\n * return m.context.count;\n * }, counter);\n *\n * // Output:\n * // Step 0: { count: 0 }\n * // Step 1: { count: 1 }\n * // Step 2: { count: 6 }\n * // Final: 6\n * ```\n */\nexport function runWithDebug<C extends any = any, M extends { context: C } & Record<string, any> = { context: C }, T = any>(\n flow: (m: M) => Generator<M, T, M>,\n initial: M,\n logger: (step: number, machine: M) => void = (step, m) => {\n console.log(`Step ${step}:`, m.context);\n }\n): T {\n const generator = flow(initial);\n let current = initial;\n let stepCount = 0;\n\n logger(stepCount, current);\n\n while (true) {\n const { value, done } = generator.next(current);\n\n if (done) {\n console.log('Final:', value);\n return value as T;\n }\n\n current = value as M;\n stepCount++;\n logger(stepCount, current);\n }\n}\n\n// =============================================================================\n// ASYNC GENERATOR SUPPORT\n// =============================================================================\n\n/**\n * Async version of `run` for async state machines.\n *\n * This allows you to use async/await inside your generator flows while maintaining\n * the same compositional benefits.\n *\n * @template C - The context object type.\n * @template T - The return type.\n * @param flow - An async generator function.\n * @param initial - The initial machine state.\n * @returns A promise that resolves to the final value.\n *\n * @example\n * ```typescript\n * const result = await runAsync(async function* (m) {\n * m = yield* stepAsync(await m.fetchData());\n * m = yield* stepAsync(await m.processData());\n * return m.context;\n * }, asyncMachine);\n * ```\n */\nexport async function runAsync<C extends any = any, M extends { context: C } & Record<string, any> = { context: C }, T = any>(\n flow: (m: M) => AsyncGenerator<M, T, M>,\n initial: M\n): Promise<T> {\n const generator = flow(initial);\n let current = initial;\n\n while (true) {\n const { value, done } = await generator.next(current);\n\n if (done) {\n return value as T;\n }\n\n current = value as M;\n }\n}\n\n/**\n * Async version of `step` for async generators.\n *\n * @template C - The context object type.\n * @param m - The machine to yield.\n * @returns An async generator.\n *\n * @example\n * ```typescript\n * await runAsync(async function* (m) {\n * m = yield* stepAsync(await m.asyncOperation());\n * return m;\n * }, machine);\n * ```\n */\nexport async function* stepAsync<C extends any = any, M extends { context: C } & Record<string, any> = { context: C }>(\n m: M\n): AsyncGenerator<M, M, M> {\n const received = yield m;\n return received;\n}\n", "/**\n * @file Type-level primitives for formal state machine verification.\n * @description\n * This file provides a Domain Specific Language (DSL) of wrapper functions.\n * These functions serve two purposes:\n * 1. At Runtime: They are identity functions (no-ops). They return your code exactly as is.\n * 2. At Design/Build Time: They \"brand\" your transition functions with rich type metadata.\n *\n * This allows a static analysis tool (like `ts-morph`) to read your source code\n * and generate a formal Statechart (JSON) that perfectly matches your implementation,\n * including resolving Class Constructors to their names.\n */\n\n// =============================================================================\n// SECTION: CORE METADATA TYPES\n// =============================================================================\n\n/**\n * Options passed to async transition functions, including cancellation support.\n */\nexport interface TransitionOptions {\n /** AbortSignal for cancelling long-running async operations. */\n signal: AbortSignal;\n}\n\n/**\n * A unique symbol used to \"brand\" a type with metadata.\n * This key allows the static analyzer to find the metadata within a complex type signature.\n */\nexport const META_KEY = Symbol(\"MachineMeta\");\n\n/**\n * Runtime metadata symbol.\n/**\n * Non-enumerable property key for storing metadata on function objects at runtime.\n * @internal\n */\nexport const RUNTIME_META = Symbol('__machine_runtime_meta__');\n\n/**\n * Local definition of Machine type to avoid circular imports.\n * @internal\n */\ntype Machine<C extends object> = {\n readonly context: C;\n} & Record<string, (...args: any[]) => Machine<any>>;\n\n/**\n * Helper type representing a Class Constructor.\n * Used to reference target states by their class definition rather than magic strings.\n */\nexport type ClassConstructor = new (...args: any[]) => any;\n\n/**\n * Metadata describing a Guard condition.\n */\nexport interface GuardMeta {\n /** The name of the guard (e.g., \"isAdmin\"). */\n name: string;\n /** Optional documentation explaining the logic. */\n description?: string;\n}\n\n/**\n * Metadata describing an Invoked Service (async operation).\n */\nexport interface InvokeMeta {\n /** The name of the service source (e.g., \"fetchUserData\"). */\n src: string;\n /** The state class to transition to on success. */\n onDone: ClassConstructor;\n /** The state class to transition to on error. */\n onError: ClassConstructor;\n /** Optional description. */\n description?: string;\n}\n\n/**\n * Metadata describing a generic Action (side effect).\n */\nexport interface ActionMeta {\n /** The name of the action (e.g., \"logAnalytics\"). */\n name: string;\n /** Optional description. */\n description?: string;\n}\n\n/**\n * The comprehensive shape of metadata that can be encoded into a transition's type.\n */\nexport interface TransitionMeta {\n /** The target state class this transition leads to. */\n target?: ClassConstructor;\n /** A human-readable description of the transition. */\n description?: string;\n /** An array of guards that must be true for this transition to be enabled. */\n guards?: GuardMeta[];\n /** A service to invoke upon taking this transition (or entering the state). */\n invoke?: InvokeMeta;\n /** Fire-and-forget side effects associated with this transition. */\n actions?: ActionMeta[];\n}\n\n/**\n * The Branded Type.\n * It takes a function type `F` and intersects it with a hidden metadata object `M`.\n * This is the mechanism that carries information from your code to the compiler API.\n */\nexport type WithMeta<\n F extends (...args: any[]) => any,\n M extends TransitionMeta\n> = F & { [META_KEY]: M };\n\n// =============================================================================\n// SECTION: RUNTIME METADATA ATTACHMENT\n// =============================================================================\n\n/**\n * Runtime metadata interface (resolved class names as strings)\n */\nexport interface RuntimeTransitionMeta {\n target?: string;\n description?: string;\n guards?: Array<{ name: string; description?: string }>;\n invoke?: {\n src: string;\n onDone: string;\n onError: string;\n description?: string;\n };\n actions?: Array<{ name: string; description?: string }>;\n}\n\n/**\n * Attaches runtime metadata to a function object.\n * Merges with existing metadata if present.\n *\n * @param fn - The function to attach metadata to\n * @param metadata - Partial metadata to merge\n * @internal\n */\nfunction attachRuntimeMeta(fn: any, metadata: Partial<RuntimeTransitionMeta>): void {\n // Read existing metadata (may be undefined)\n const existing = fn[RUNTIME_META] || {};\n\n // Shallow merge for simple properties\n const merged: any = { ...existing, ...metadata };\n\n // Deep merge for array properties\n // Prepend new items to preserve order (outer wraps first in call stack)\n if (metadata.guards && existing.guards) {\n merged.guards = [...metadata.guards, ...existing.guards];\n } else if (metadata.guards) {\n merged.guards = [...metadata.guards];\n }\n\n if (metadata.actions && existing.actions) {\n merged.actions = [...metadata.actions, ...existing.actions];\n } else if (metadata.actions) {\n merged.actions = [...metadata.actions];\n }\n\n // Replace invoke entirely (not an array, can't merge)\n // Last invoke wins (this matches XState semantics)\n\n // Define or redefine the metadata property\n Object.defineProperty(fn, RUNTIME_META, {\n value: merged,\n enumerable: false,\n writable: false,\n configurable: true // CRITICAL: Must be configurable for re-definition\n });\n}\n\n// =============================================================================\n// SECTION: ANNOTATION PRIMITIVES (THE DSL)\n// =============================================================================\n\n/**\n * Defines a transition to a target state class.\n *\n * @param target - The Class Constructor of the state being transitioned to.\n * @param implementation - The implementation function returning the new state instance.\n * @returns The implementation function, branded with target metadata.\n *\n * @example\n * login = transitionTo(LoggedInMachine, (user) => new LoggedInMachine({ user }));\n */\nexport function transitionTo<\n T extends ClassConstructor,\n F extends (...args: any[]) => any\n>(\n _target: T,\n implementation: F\n): WithMeta<F, { target: T }> {\n // Attach runtime metadata with class name\n attachRuntimeMeta(implementation, {\n target: _target.name || _target.toString()\n });\n\n return implementation as any;\n}\n\n/**\n * Annotates a transition with a description for documentation generation.\n *\n * @param text - The description text.\n * @param transition - The transition function (or wrapper) to annotate.\n * @example\n * logout = describe(\"Logs the user out\", transitionTo(LoggedOut, ...));\n */\nexport function describe<\n F extends (...args: any[]) => any,\n M extends TransitionMeta\n>(\n _text: string,\n transition: WithMeta<F, M>\n): WithMeta<F, M & { description: string }> {\n // Attach runtime metadata\n attachRuntimeMeta(transition, {\n description: _text\n });\n\n return transition as any;\n}\n\n/**\n * Annotates a transition with a Guard condition.\n * Note: This only adds metadata. You must still implement the `if` check inside your function.\n *\n * @deprecated Use the runtime `guard()` primitive instead. Its `options.description` is used for static analysis.\n * @param guard - Object containing the name and optional description of the guard.\n * @param transition - The transition function to guard.\n * @example\n * delete = guarded({ name: \"isAdmin\" }, transitionTo(Deleted, ...));\n */\nexport function guarded<\n F extends (...args: any[]) => any,\n M extends TransitionMeta\n>(\n guard: GuardMeta,\n transition: WithMeta<F, M>\n): WithMeta<F, M & { guards: [typeof guard] }> {\n // Attach runtime metadata\n // Note: guards is an array, will be merged by attachRuntimeMeta\n attachRuntimeMeta(transition, {\n guards: [guard]\n });\n\n return transition as any;\n}\n\n/**\n * Annotates a transition with an Invoked Service (asynchronous effect).\n *\n * @param service - configuration for the service (source, onDone target, onError target).\n * @param implementation - The async function implementation that receives an AbortSignal.\n * @example\n * load = invoke(\n * { src: \"fetchData\", onDone: LoadedMachine, onError: ErrorMachine },\n * async ({ signal }) => {\n * const response = await fetch('/api/data', { signal });\n * return new LoadedMachine({ data: await response.json() });\n * }\n * );\n */\nexport function invoke<\n D extends ClassConstructor,\n E extends ClassConstructor,\n F extends (options: { signal: AbortSignal }) => any\n>(\n service: { src: string; onDone: D; onError: E; description?: string },\n implementation: F\n): WithMeta<F, { invoke: typeof service }> {\n // Attach runtime metadata with class names resolved\n attachRuntimeMeta(implementation, {\n invoke: {\n src: service.src,\n onDone: service.onDone.name || service.onDone.toString(),\n onError: service.onError.name || service.onError.toString(),\n description: service.description\n }\n });\n\n return implementation as any;\n}\n\n/**\n * Annotates a transition with a side-effect Action.\n * Useful for logging, analytics, or external event firing that doesn't change state structure.\n *\n * @param action - Object containing the name and optional description.\n * @param transition - The transition function to annotate.\n * @example\n * click = action({ name: \"trackClick\" }, (ctx) => ...);\n */\nexport function action<\n F extends (...args: any[]) => any,\n M extends TransitionMeta\n>(\n action: ActionMeta,\n transition: WithMeta<F, M>\n): WithMeta<F, M & { actions: [typeof action] }> {\n // Attach runtime metadata\n // Note: actions is an array, will be merged by attachRuntimeMeta\n attachRuntimeMeta(transition, {\n actions: [action]\n });\n\n return transition as any;\n}\n\n// =============================================================================\n// SECTION: RUNTIME GUARDS\n// =============================================================================\n\n/**\n * Configuration options for guard behavior when conditions fail.\n */\nexport interface GuardOptions<C extends object = any, TFailure extends Machine<any> = Machine<C>> {\n /** What to do when guard fails */\n onFail?: 'throw' | 'ignore' | GuardFallback<C, TFailure>;\n\n /** Custom error message for 'throw' mode */\n errorMessage?: string;\n\n /** Additional metadata for statechart extraction */\n description?: string;\n}\n\n/**\n * A fallback machine or function that returns a machine when guard fails.\n */\nexport type GuardFallback<C extends object, TFailure extends Machine<any> = Machine<C>> =\n | ((this: Machine<C>, ...args: any[]) => TFailure)\n | TFailure;\n\n/**\n * A guarded transition that checks conditions at runtime before executing.\n * Can be called with either machine or context as 'this' binding.\n */\nexport type GuardedTransition<\n C extends object,\n TSuccess extends Machine<any>,\n TFailure extends Machine<any> = Machine<C>\n> = {\n (...args: any[]): TSuccess | TFailure | Promise<TSuccess | TFailure>;\n readonly __guard: true;\n readonly condition: (ctx: C, ...args: any[]) => boolean | Promise<boolean>;\n readonly transition: (...args: any[]) => TSuccess;\n};\n\n/**\n * Creates a synchronous runtime guard that checks conditions before executing transitions.\n * This provides actual runtime protection with synchronous execution - use this for the majority of cases.\n *\n * @template C - The context type\n * @template TSuccess - The transition return type when condition passes\n * @template TFailure - The fallback return type when condition fails (defaults to Machine<C>)\n * @param condition - Synchronous function that returns true if transition should proceed\n * @param transition - The transition function to execute if condition passes\n * @param options - Configuration for guard failure behavior\n * @returns A synchronous guarded transition function\n *\n * @example\n * ```typescript\n * const machine = createMachine({ balance: 100 }, {\n * withdraw: guard(\n * (ctx, amount) => ctx.balance >= amount,\n * function(amount: number) {\n * return createMachine({ balance: this.balance - amount }, this);\n * },\n * { onFail: 'throw', errorMessage: 'Insufficient funds' }\n * )\n * });\n *\n * machine.withdraw(50); // ✅ Works synchronously\n * machine.withdraw(200); // ❌ Throws \"Insufficient funds\"\n * ```\n */\nexport function guard<\n C extends object,\n TSuccess extends Machine<any>,\n TFailure extends Machine<any> = Machine<C>\n>(\n condition: (ctx: C, ...args: any[]) => boolean,\n transition: (...args: any[]) => TSuccess,\n options: GuardOptions<C, TFailure> = {}\n): (...args: any[]) => TSuccess | TFailure {\n const { onFail = 'throw', errorMessage, description } = options;\n\n // Merge defaults into options for the metadata\n const fullOptions = { ...options, onFail, errorMessage, description };\n\n // Create the guarded transition function (synchronous)\n const guardedTransition = function(this: C | Machine<C>, ...args: any[]): TSuccess | TFailure {\n // Detect if 'this' is a machine or just context\n const isMachine = typeof this === 'object' && 'context' in this;\n const ctx = isMachine ? (this as Machine<C>).context : (this as C);\n\n // Evaluate the condition (synchronously)\n const conditionResult = condition(ctx, ...args);\n\n if (conditionResult) {\n // Condition passed, execute the transition\n // Transition functions expect 'this' to be the context\n const contextForTransition = isMachine ? (this as Machine<C>).context : (this as C);\n return transition.apply(contextForTransition, args);\n } else {\n // Condition failed, handle according to options\n if (onFail === 'throw') {\n const message = errorMessage || 'Guard condition failed';\n throw new Error(message);\n } else if (onFail === 'ignore') {\n if (isMachine) {\n // Return the current machine unchanged\n return this as TSuccess | TFailure;\n } else {\n // Cannot ignore when called with context binding\n throw new Error('Cannot use \"ignore\" mode with context-only binding. Use full machine binding or provide fallback.');\n }\n } else if (typeof onFail === 'function') {\n // Custom fallback function - call with machine as 'this'\n if (isMachine) {\n return onFail.apply(this as Machine<C>, args) as TSuccess | TFailure;\n } else {\n throw new Error('Cannot use function fallback with context-only binding. Use full machine binding.');\n }\n } else {\n // Static fallback machine\n return onFail as TSuccess | TFailure;\n }\n }\n };\n\n // Attach metadata for type branding and statechart extraction\n Object.defineProperty(guardedTransition, '__guard', { value: true, enumerable: false });\n Object.defineProperty(guardedTransition, 'condition', { value: condition, enumerable: false });\n Object.defineProperty(guardedTransition, 'transition', { value: transition, enumerable: false });\n Object.defineProperty(guardedTransition, 'options', { value: fullOptions, enumerable: false });\n\n // Attach runtime metadata for statechart extraction\n attachRuntimeMeta(guardedTransition, {\n description: description || 'Synchronous guarded transition',\n guards: [{ name: 'runtime_guard', description: description || 'Synchronous condition check' }]\n });\n\n return guardedTransition;\n}\n\n/**\n * Creates a runtime guard that checks conditions before executing transitions.\n * This provides actual runtime protection, unlike the `guarded` primitive which only adds metadata.\n * Use this when your condition or transition logic is asynchronous.\n *\n * @template C - The context type\n * @template TSuccess - The transition return type when condition passes\n * @template TFailure - The fallback return type when condition fails (defaults to Machine<C>)\n * @param condition - Function that returns true if transition should proceed (can be async)\n * @param transition - The transition function to execute if condition passes\n * @param options - Configuration for guard failure behavior\n * @returns A guarded transition function that returns a Promise\n *\n * @example\n * ```typescript\n * const machine = createMachine({ balance: 100 }, {\n * withdraw: guardAsync(\n * async (ctx, amount) => {\n * // Simulate API call to check balance\n * await new Promise(resolve => setTimeout(resolve, 100));\n * return ctx.balance >= amount;\n * },\n * async function(amount: number) {\n * // Simulate API call to process withdrawal\n * await new Promise(resolve => setTimeout(resolve, 100));\n * return createMachine({ balance: this.balance - amount }, this);\n * },\n * { onFail: 'throw', errorMessage: 'Insufficient funds' }\n * )\n * });\n *\n * await machine.withdraw(50); // ✅ Works\n * await machine.withdraw(200); // ❌ Throws \"Insufficient funds\"\n * ```\n */\nexport function guardAsync<\n C extends object,\n TSuccess extends Machine<any>,\n TFailure extends Machine<any> = Machine<C>\n>(\n condition: (ctx: C, ...args: any[]) => boolean | Promise<boolean>,\n transition: (...args: any[]) => TSuccess,\n options: GuardOptions<C, TFailure> = {}\n): GuardedTransition<C, TSuccess, TFailure> {\n const { onFail = 'throw', errorMessage, description } = options;\n\n // Merge defaults into options for the metadata\n const fullOptions = { ...options, onFail, errorMessage, description };\n\n // Create the guarded transition function\n const guardedTransition = async function(this: C | Machine<C>, ...args: any[]): Promise<TSuccess | TFailure> {\n // Detect if 'this' is a machine or just context\n const isMachine = typeof this === 'object' && 'context' in this;\n const ctx = isMachine ? (this as Machine<C>).context : (this as C);\n\n // Evaluate the condition\n const conditionResult = await Promise.resolve(condition(ctx, ...args));\n\n if (conditionResult) {\n // Condition passed, execute the transition\n // Transition functions expect 'this' to be the context\n const contextForTransition = isMachine ? (this as Machine<C>).context : (this as C);\n return transition.apply(contextForTransition, args);\n } else {\n // Condition failed, handle according to options\n if (onFail === 'throw') {\n const message = errorMessage || 'Guard condition failed';\n throw new Error(message);\n } else if (onFail === 'ignore') {\n if (isMachine) {\n // Return the current machine unchanged\n return this as TSuccess | TFailure;\n } else {\n // Cannot ignore when called with context binding\n throw new Error('Cannot use \"ignore\" mode with context-only binding. Use full machine binding or provide fallback.');\n }\n } else if (typeof onFail === 'function') {\n // Custom fallback function - call with machine as 'this'\n if (isMachine) {\n return onFail.apply(this as Machine<C>, args) as TSuccess | TFailure;\n } else {\n throw new Error('Cannot use function fallback with context-only binding. Use full machine binding.');\n }\n } else {\n // Static fallback machine\n return onFail as TSuccess | TFailure;\n }\n }\n };\n\n // Attach metadata for type branding and statechart extraction\n Object.defineProperty(guardedTransition, '__guard', { value: true, enumerable: false });\n Object.defineProperty(guardedTransition, 'condition', { value: condition, enumerable: false });\n Object.defineProperty(guardedTransition, 'transition', { value: transition, enumerable: false });\n Object.defineProperty(guardedTransition, 'options', { value: fullOptions, enumerable: false });\n\n // Attach runtime metadata for statechart extraction\n attachRuntimeMeta(guardedTransition, {\n description: description || 'Runtime guarded transition',\n guards: [{ name: 'runtime_guard', description: description || 'Runtime condition check' }]\n });\n\n return guardedTransition as GuardedTransition<C, TSuccess, TFailure>;\n}\n\n/**\n * Creates a synchronous guard that checks conditions before executing transitions.\n * This is the synchronous counterpart to `guard()` - use this when your machine\n * doesn't need async transitions to avoid unnecessary Promise overhead.\n *\n * @template C - The context type\n * @template T - The transition return type\n * @param condition - Function that returns true if transition should proceed (must be synchronous)\n * @param transition - The transition function to execute if condition passes (must be synchronous)\n * @param options - Configuration for guard failure behavior\n * @returns A synchronous guarded transition function\n *\n * @example\n * ```typescript\n * const machine = createMachine({ balance: 100 }, {\n * withdraw: guardSync(\n * (ctx, amount) => ctx.balance >= amount,\n * function(amount: number) {\n * return createMachine({ balance: this.balance - amount }, this);\n * },\n * { onFail: 'throw', errorMessage: 'Insufficient funds' }\n * )\n * });\n *\n * machine.withdraw(50); // ✅ Works synchronously\n * machine.withdraw(200); // ❌ Throws \"Insufficient funds\"\n * ```\n */\nexport function guardSync<\n C extends object,\n TSuccess extends Machine<any>,\n TFailure extends Machine<any> = Machine<C>\n>(\n condition: (ctx: C, ...args: any[]) => boolean,\n transition: (...args: any[]) => TSuccess,\n options: GuardOptions<C, TFailure> = {}\n): GuardedTransition<C, TSuccess, TFailure> {\n const { onFail = 'throw', errorMessage, description } = options;\n\n // Merge defaults into options for the metadata\n const fullOptions = { ...options, onFail, errorMessage, description };\n\n // Create the guarded transition function (synchronous)\n const guardedTransition = function(this: C | Machine<C>, ...args: any[]): TSuccess | TFailure {\n // Detect if 'this' is a machine or just context\n const isMachine = typeof this === 'object' && 'context' in this;\n const ctx = isMachine ? (this as Machine<C>).context : (this as C);\n\n // Evaluate the condition (synchronously)\n const conditionResult = condition(ctx, ...args);\n\n if (conditionResult) {\n // Condition passed, execute the transition\n // Transition functions expect 'this' to be the context\n const contextForTransition = isMachine ? (this as Machine<C>).context : (this as C);\n return transition.apply(contextForTransition, args);\n } else {\n // Condition failed, handle according to options\n if (onFail === 'throw') {\n const message = errorMessage || 'Guard condition failed';\n throw new Error(message);\n } else if (onFail === 'ignore') {\n if (isMachine) {\n // Return the current machine unchanged\n return this as TSuccess | TFailure;\n } else {\n // Cannot ignore when called with context binding\n throw new Error('Cannot use \"ignore\" mode with context-only binding. Use full machine binding or provide fallback.');\n }\n } else if (typeof onFail === 'function') {\n // Custom fallback function - call with machine as 'this'\n if (isMachine) {\n return onFail.apply(this as Machine<C>, args) as TSuccess | TFailure;\n } else {\n throw new Error('Cannot use function fallback with context-only binding. Use full machine binding.');\n }\n } else {\n // Static fallback machine\n return onFail as TSuccess | TFailure;\n }\n }\n };\n\n // Attach metadata for type branding and statechart extraction\n Object.defineProperty(guardedTransition, '__guard', { value: true, enumerable: false });\n Object.defineProperty(guardedTransition, 'condition', { value: condition, enumerable: false });\n Object.defineProperty(guardedTransition, 'transition', { value: transition, enumerable: false });\n Object.defineProperty(guardedTransition, 'options', { value: fullOptions, enumerable: false });\n\n // Attach runtime metadata for statechart extraction\n attachRuntimeMeta(guardedTransition, {\n description: description || 'Synchronous guarded transition',\n guards: [{ name: 'runtime_guard_sync', description: description || 'Synchronous condition check' }]\n });\n\n return guardedTransition as GuardedTransition<C, TSuccess, TFailure>;\n}\n\n/**\n * Fluent API for creating synchronous guarded transitions.\n * Provides a more readable way to define conditional transitions with synchronous execution.\n *\n * @template C - The context type\n * @param condition - Synchronous function that returns true if transition should proceed\n * @returns A fluent interface for defining the guarded transition\n *\n * @example\n * ```typescript\n * const machine = createMachine({ isAdmin: false }, {\n * deleteUser: whenGuard((ctx) => ctx.isAdmin)\n * .do(function(userId: string) {\n * return createMachine({ ...this.context, deleted: userId }, this);\n * })\n * .else(function() {\n * return createMachine({ ...this.context, error: 'Unauthorized' }, this);\n * })\n * });\n * ```\n */\nexport function whenGuard<C extends object>(\n condition: (ctx: C, ...args: any[]) => boolean\n) {\n return {\n /**\n * Define the transition to execute when the condition passes.\n * Returns a guarded transition that can optionally have an else clause.\n */\n do<T extends Machine<any>>(transition: (...args: any[]) => T) {\n const guarded = guard(condition, transition);\n\n // Add fluent else method to the guarded transition\n (guarded as any).else = function<F extends Machine<any>>(fallback: (...args: any[]) => F) {\n return guard(condition, transition, { onFail: fallback });\n };\n\n return guarded;\n }\n };\n}\n\n/**\n * Fluent API for creating asynchronous guarded transitions.\n * Provides a more readable way to define conditional transitions with async execution.\n *\n * @template C - The context type\n * @param condition - Function that returns true if transition should proceed (can be async)\n * @returns A fluent interface for defining the guarded transition\n *\n * @example\n * ```typescript\n * const machine = createMachine({ isAdmin: false }, {\n * deleteUser: whenGuardAsync(async (ctx) => {\n * // Simulate API call\n * await checkPermissions(ctx.userId);\n * return ctx.isAdmin;\n * })\n * .do(async function(userId: string) {\n * await deleteUserFromDB(userId);\n * return createMachine({ ...this.context, deleted: userId }, this);\n * })\n * .else(function() {\n * return createMachine({ ...this.context, error: 'Unauthorized' }, this);\n * })\n * });\n * ```\n */\nexport function whenGuardAsync<C extends object>(\n condition: (ctx: C, ...args: any[]) => boolean | Promise<boolean>\n) {\n return {\n /**\n * Define the transition to execute when the condition passes.\n * Returns a guarded transition that can optionally have an else clause.\n */\n do<T extends Machine<any>>(transition: (...args: any[]) => T) {\n const guarded = guardAsync(condition, transition);\n\n // Add fluent else method to the guarded transition\n (guarded as any).else = function<F extends Machine<any>>(fallback: (...args: any[]) => F) {\n return guardAsync(condition, transition, { onFail: fallback });\n };\n\n return guarded;\n }\n };\n}\n\n/**\n * Flexible metadata wrapper for functional and type-state patterns.\n *\n * This function allows attaching metadata to values that don't use the class-based\n * MachineBase pattern. It's particularly useful for:\n * - Functional machines created with createMachine()\n * - Type-state discriminated unions\n * - Generic machine configurations\n *\n * @param meta - Partial metadata object describing states, transitions, etc.\n * @param value - The value to annotate (machine, config, factory function, etc.)\n * @returns The value unchanged (identity function at runtime)\n *\n * @example\n * // Annotate a functional machine\n * const machine = metadata(\n * {\n * target: IdleState,\n * description: \"Counter machine with increment/decrement\"\n * },\n * createMachine({ count: 0 }, { ... })\n * );\n *\n * @example\n * // Annotate a factory function\n * export const createCounter = metadata(\n * { description: \"Creates a counter starting at 0\" },\n * () => createMachine({ count: 0 }, { ... })\n * );\n */\nexport function metadata<T>(_meta: Partial<TransitionMeta>, value: T): T {\n // At runtime, this is a no-op identity function\n // At compile-time/static-analysis, the metadata can be extracted from the type signature\n return value;\n}", "/**\n * @file multi.ts - Advanced operational patterns for state machine orchestration.\n * @description\n * This module provides optional, higher-level abstractions for managing machines.\n * They solve common ergonomic and integration challenges without compromising the\n * immutable core of the library.\n *\n * It introduces three patterns:\n *\n * 1. **Runner (`createRunner`):** A stateful controller for ergonomic control\n * of a single, immutable machine. Solves state reassignment.\n *\n * 2. **Ensemble (`createEnsemble`):** A functional pattern for orchestrating logic\n * over an external, framework-agnostic state store.\n *\n * 3. **MultiMachine (`createMultiMachine`):** A class-based alternative to the\n * Ensemble for OOP-style orchestration.\n */\n\nimport {\n Machine,\n Context,\n TransitionArgs,\n TransitionNames,\n // Transitions,\n} from './index';\n\n// =============================================================================\n// SECTION 1: THE MANAGED STATE RUNNER\n// =============================================================================\n\n/**\n * A mapped type that creates a new object type with the same transition methods\n * as the machine `M`, but pre-bound to update a Runner's internal state.\n *\n * When you call a method on `BoundTransitions`, it automatically transitions the\n * runner's state and returns the new machine instance. This is the key mechanism\n * that eliminates the need for manual state reassignment in imperative code.\n *\n * @template M - The machine type, which can be a union of multiple machine states.\n *\n * @example\n * // If your machine has these transitions:\n * // increment: () => Machine\n * // add: (n: number) => Machine\n * // Then BoundTransitions<typeof machine> provides:\n * // increment: () => Machine (auto-updates runner state)\n * // add: (n: number) => Machine (auto-updates runner state)\n */\nexport type BoundTransitions<M extends Machine<any>> = {\n [K in TransitionNames<M>]: (\n ...args: TransitionArgs<M, K>\n ) => M[K] extends (...args: any[]) => infer R ? R : never;\n};\n\n/**\n * A stateful controller that wraps an immutable machine instance, providing a\n * stable API for imperative state transitions without manual reassignment.\n *\n * The Runner holds the \"current\" machine state internally and updates it whenever\n * an action is called. This solves the ergonomic problem of having to write:\n * `machine = machine.transition()` over and over. Instead, you just call\n * `runner.actions.transition()` and the runner manages the state for you.\n *\n * **Use Runner for:**\n * - Complex local component state (React, Vue, Svelte components)\n * - Scripts that need clean imperative state management\n * - Situations where you have a single, self-contained state machine\n *\n * **Don't use Runner for:**\n * - Global application state (use Ensemble instead)\n * - Multiple interconnected machines\n *\n * @template M - The machine type (can be a union of states for Type-State patterns).\n */\nexport type Runner<M extends Machine<any>> = {\n /**\n * The current, raw machine instance. This property is essential for\n * type-narrowing in Type-State Programming patterns.\n *\n * Since machines can be unions of different state types, you can narrow\n * the type by checking `runner.state.context` properties, and TypeScript\n * will automatically narrow which transitions are available.\n *\n * @example\n * if (runner.state.context.status === 'loggedIn') {\n * // runner.state is now typed as LoggedInMachine\n * console.log(runner.state.context.username);\n * runner.actions.logout(); // Only available when logged in\n * }\n */\n readonly state: M;\n\n /**\n * A direct, readonly accessor to the context of the current machine state.\n * This is a convenience property equivalent to `runner.state.context`.\n *\n * @example\n * console.log(runner.context.count); // Same as runner.state.context.count\n */\n readonly context: Context<M>;\n\n /**\n * A stable object containing all available transition methods, pre-bound to\n * update the runner's state. This is the primary way to trigger transitions.\n *\n * When you call `runner.actions.someTransition()`, the runner automatically:\n * 1. Calls the transition on the current machine\n * 2. Updates `runner.state` with the new machine instance\n * 3. Fires the `onChange` callback (if provided to createRunner)\n * 4. Returns the new machine instance\n *\n * Note: For union-type machines, you must first narrow the type of `runner.state`\n * to ensure a given action is available at compile time.\n *\n * @example\n * runner.actions.increment(); // Automatically updates runner.state\n * runner.actions.add(5); // Returns new machine instance\n */\n readonly actions: BoundTransitions<M>;\n\n /**\n * Manually sets the runner to a new machine state. Useful for resetting state\n * or synchronizing with external events.\n *\n * This method bypasses the normal transition path and directly updates the\n * runner's internal state. The `onChange` callback will be called.\n *\n * @param newState - The new machine instance to set.\n *\n * @example\n * const reset = createCounterMachine({ count: 0 });\n * runner.setState(reset); // Jump back to initial state\n */\n setState(newState: M): void;\n};\n\n/**\n * Creates a Managed State Runner by wrapping a pure, immutable machine instance\n * in a stateful controller. This eliminates the need for `machine = machine.transition()`\n * reassignment, providing a more ergonomic, imperative API for complex local state.\n *\n * **How it works:**\n * 1. The runner holds a reference to the current machine internally\n * 2. When you call `runner.actions.transition()`, it calls the transition on the\n * current machine and automatically updates the runner's internal state\n * 3. The runner exposes a stable `actions` object that always reflects what\n * transitions are available on the *current* machine (important for Type-State)\n * 4. The `onChange` callback is invoked after every state change\n *\n * **Key difference from just calling transitions directly:**\n * Instead of: `let machine = createMachine(...); machine = machine.increment();`\n * You write: `const runner = createRunner(machine); runner.actions.increment();`\n *\n * The runner *is* the state holder, so you never need to reassign variables.\n *\n * @template M - The machine type.\n * @param initialMachine - The starting machine instance.\n * @param onChange - Optional callback fired after every state transition. Receives\n * the new machine state, allowing you to react to changes (e.g., update a UI,\n * log state changes, or trigger side effects).\n * @returns A `Runner` instance with `state`, `context`, `actions`, and `setState()`.\n *\n * @example\n * // Simple counter example\n * const counterMachine = createCounterMachine({ count: 0 });\n * const runner = createRunner(counterMachine, (newState) => {\n * console.log('Count is now:', newState.context.count);\n * });\n *\n * runner.actions.increment(); // Logs: \"Count is now: 1\"\n * runner.actions.add(5); // Logs: \"Count is now: 6\"\n * console.log(runner.context.count); // 6\n *\n * @example\n * // Type-State example with conditional narrowing\n * type AuthMachine = LoggedOutState | LoggedInState;\n *\n * const runner = createRunner(createLoggedOutMachine());\n *\n * // Narrow the type to access login\n * if (runner.state.context.status === 'loggedOut') {\n * runner.actions.login('alice'); // Only works in loggedOut state\n * }\n *\n * // Now it's logged in, so we can call logout\n * if (runner.state.context.status === 'loggedIn') {\n * runner.actions.logout();\n * }\n */\nexport function createRunner<M extends Machine<any>>(\n initialMachine: M,\n onChange?: (newState: M) => void\n): Runner<M> {\n let currentMachine = initialMachine;\n\n const setState = (newState: M) => {\n currentMachine = newState;\n onChange?.(newState);\n };\n\n // Capture the original transitions from the initial machine\n const { context: _initialContext, ...originalTransitions } = initialMachine;\n\n const actions = new Proxy({} as BoundTransitions<M>, {\n get(_target, prop: string) {\n const transition = (currentMachine as any)[prop];\n if (typeof transition !== 'function') {\n // Return undefined for properties that aren't valid transitions on the current state\n return undefined;\n }\n\n return (...args: any[]) => {\n const nextState = transition.apply(currentMachine.context, args);\n // Ensure the next state has all the original transitions\n // by reconstructing it with the original transition functions\n const nextStateWithTransitions = Object.assign(\n { context: nextState.context },\n originalTransitions\n ) as M;\n setState(nextStateWithTransitions);\n return nextStateWithTransitions;\n };\n },\n });\n\n return {\n get state() {\n return currentMachine;\n },\n get context() {\n return currentMachine.context;\n },\n actions,\n setState,\n };\n}\n\n// =============================================================================\n// SECTION 2: THE ENSEMBLE (FRAMEWORK-AGNOSTIC ORCHESTRATION)\n// =============================================================================\n\n/**\n * Defines the contract for an external, user-provided state store. The Ensemble\n * uses this interface to read and write the machine's context, allowing it to\n * plug into any state management solution (React, Solid, Zustand, etc.).\n *\n * **The power of this abstraction:**\n * Your machine logic is completely decoupled from how or where the state is stored.\n * The same machine factories can work with React's `useState`, Solid's `createSignal`,\n * a plain object, or any custom store implementation.\n *\n * **Implementation examples:**\n * - React: `{ getContext: () => state, setContext: setState }`\n * - Solid: `{ getContext: () => store, setContext: (newCtx) => Object.assign(store, newCtx) }`\n * - Plain object: `{ getContext: () => context, setContext: (ctx) => Object.assign(context, ctx) }`\n *\n * @template C - The shared context object type.\n *\n * @example\n * // Implement a simple in-memory store\n * let sharedContext = { status: 'idle' };\n * const store: StateStore<typeof sharedContext> = {\n * getContext: () => sharedContext,\n * setContext: (newCtx) => { sharedContext = newCtx; }\n * };\n *\n * @example\n * // Implement a React-based store\n * function useAppStore() {\n * const [state, setState] = useState({ status: 'idle' });\n * return {\n * getContext: () => state,\n * setContext: setState\n * };\n * }\n */\nexport interface StateStore<C extends object> {\n /**\n * A function that returns the current, up-to-date context from the external store.\n * Called whenever the Ensemble needs the latest state.\n */\n getContext: () => C;\n\n /**\n * A function that takes a new context and updates the external store.\n * Called by transitions to persist state changes.\n *\n * @param newContext - The new context object to persist.\n */\n setContext: (newContext: C) => void;\n}\n\n/**\n * A mapped type that finds all unique transition names across a union of machine types.\n *\n * This type extracts the union of all methods from all possible machine states,\n * excluding the `context` property. This is used to create the `actions` object\n * on an Ensemble, which can have methods from any of the machine states.\n *\n * At runtime, the Ensemble validates that an action is valid for the current state\n * before executing it.\n *\n * @template AllMachines - A union of all possible machine types in an Ensemble.\n *\n * @example\n * type IdleState = Machine<{ status: 'idle' }> & { fetch: () => LoadingState };\n * type LoadingState = Machine<{ status: 'loading' }> & { cancel: () => IdleState };\n * type AllStates = IdleState | LoadingState;\n *\n * // AllTransitions<AllStates> = { fetch: (...) => ..., cancel: (...) => ... }\n * // (Both fetch and cancel are available, but each is only valid in its state)\n */\ntype AllTransitions<AllMachines extends Machine<any>> = Omit<\n { [K in keyof AllMachines]: AllMachines[K] }[keyof AllMachines],\n 'context'\n>;\n\n/**\n * The Ensemble object. It provides a stable, unified API for orchestrating a\n * state machine whose context is managed by an external store.\n *\n * The Ensemble acts as the \"director,\" determining which machine \"actor\" is\n * currently active based on the state of the shared context. Unlike a Runner,\n * which manages local state, an Ensemble plugs into external state management\n * (like React's useState, Solid's signal, or a global store).\n *\n * **Key characteristics:**\n * - Dynamically reconstructs the current machine based on context\n * - Validates transitions at runtime for the current state\n * - Integrates seamlessly with framework state managers\n * - Same factories can be reused across different frameworks\n *\n * **Use Ensemble for:**\n * - Global application state\n * - Framework integration (React, Solid, Vue, etc.)\n * - Complex workflows that span multiple components\n * - Decoupling business logic from UI framework\n *\n * @template AllMachines - A union type of all possible machine states.\n * @template C - The shared context type.\n */\nexport type Ensemble<AllMachines extends Machine<any>, C extends object> = {\n /**\n * A direct, readonly accessor to the context from the provided `StateStore`.\n * This is always up-to-date with the external store.\n */\n readonly context: C;\n\n /**\n * The current, fully-typed machine instance. This is dynamically created on-demand\n * based on the context state. Use this for type-narrowing with Type-State patterns.\n *\n * The machine is reconstructed on every access, so it always reflects the\n * current state of the context.\n */\n readonly state: AllMachines;\n\n /**\n * A stable object containing all possible actions from all machine states.\n * The Ensemble performs a runtime check to ensure an action is valid for the\n * current state before executing it.\n *\n * The `actions` object itself is stable (doesn't change), but the methods\n * available on it dynamically change based on the current state.\n */\n readonly actions: AllTransitions<AllMachines>;\n};\n\n/**\n * Creates an Ensemble to orchestrate a state machine over an external state store.\n * This is the primary tool for framework integration, as it decouples pure state\n * logic (defined in factories) from an application's state management solution\n * (defined in store).\n *\n * **How it works:**\n * 1. You provide a `StateStore` that can read and write your application's state\n * 2. You define factory functions that create machines for each state\n * 3. You provide a `getDiscriminant` accessor that tells the Ensemble which\n * factory to use based on the current context\n * 4. The Ensemble dynamically constructs the right machine and provides a stable\n * `actions` object to call transitions\n *\n * **Why this pattern?**\n * Your business logic (machines) is completely separated from your state management\n * (React, Solid, Zustand). You can change state managers without rewriting machines,\n * and you can test machines in isolation without framework dependencies.\n *\n * @template C - The shared context type.\n * @template F - An object of functions that create machine instances for each state.\n * Each factory receives the context and returns a Machine instance for that state.\n * @param store - The user-provided `StateStore` that reads/writes the context.\n * @param factories - An object mapping state discriminant keys to factory functions.\n * Each factory receives the context and returns a machine instance.\n * @param getDiscriminant - An accessor function that takes the context and returns\n * the key of the current state in the `factories` object. This provides full\n * refactoring safety—if you rename a property in your context, TypeScript will\n * catch it at the accessor function.\n * @returns An `Ensemble` instance with `context`, `state`, and `actions`.\n *\n * @example\n * // Using a simple in-memory store\n * let sharedContext = { status: 'idle' as const, data: null };\n * const store = {\n * getContext: () => sharedContext,\n * setContext: (newCtx) => { sharedContext = newCtx; }\n * };\n *\n * // Define factories for each state\n * const factories = {\n * idle: (ctx) => createMachine(ctx, {\n * fetch: () => store.setContext({ ...ctx, status: 'loading' })\n * }),\n * loading: (ctx) => createMachine(ctx, {\n * succeed: (data: any) => store.setContext({ status: 'success', data }),\n * fail: (error: string) => store.setContext({ status: 'error', error })\n * }),\n * success: (ctx) => createMachine(ctx, {\n * retry: () => store.setContext({ status: 'loading', data: null })\n * }),\n * error: (ctx) => createMachine(ctx, {\n * retry: () => store.setContext({ status: 'loading', data: null })\n * })\n * };\n *\n * // Create the ensemble with a discriminant accessor\n * const ensemble = createEnsemble(store, factories, (ctx) => ctx.status);\n *\n * // Use the ensemble\n * ensemble.actions.fetch();\n * console.log(ensemble.context.status); // 'loading'\n *\n * @example\n * // React integration example\n * function useAppEnsemble() {\n * const [context, setContext] = useState({ status: 'idle' as const, data: null });\n *\n * const store: StateStore<typeof context> = {\n * getContext: () => context,\n * setContext: (newCtx) => setContext(newCtx)\n * };\n *\n * const ensemble = useMemo(() =>\n * createEnsemble(store, factories, (ctx) => ctx.status),\n * [context] // Re-create ensemble if context changes\n * );\n *\n * return ensemble;\n * }\n *\n * // In your component:\n * function MyComponent() {\n * const ensemble = useAppEnsemble();\n * return (\n * <>\n * <p>Status: {ensemble.context.status}</p>\n * <button onClick={() => ensemble.actions.fetch()}>\n * Fetch Data\n * </button>\n * </>\n * );\n * }\n */\nexport function createEnsemble<\n C extends object,\n F extends Record<string, (context: C) => Machine<C>>\n>(\n store: StateStore<C>,\n factories: F,\n getDiscriminant: (context: C) => keyof F\n): Ensemble<ReturnType<F[keyof F]>, C> {\n type AllMachines = ReturnType<F[keyof F]>;\n\n const getCurrentMachine = (): AllMachines => {\n const context = store.getContext();\n const currentStateName = getDiscriminant(context);\n const factory = factories[currentStateName];\n\n if (!factory) {\n throw new Error(\n `[Ensemble] Invalid state: No factory found for state \"${String(currentStateName)}\".`\n );\n }\n return factory(context) as AllMachines;\n };\n\n const actions = new Proxy({} as AllTransitions<AllMachines>, {\n get(_target, prop: string) {\n const currentMachine = getCurrentMachine();\n const action = (currentMachine as any)[prop];\n\n if (typeof action !== 'function') {\n throw new Error(\n `[Ensemble] Transition \"${prop}\" is not valid in the current state.`\n );\n }\n\n // Return a function that, when called, executes the transition.\n // The transition itself is responsible for calling `store.setContext`.\n return (...args: any[]) => {\n return action.apply(currentMachine.context, args);\n };\n },\n });\n\n return {\n get context() {\n return store.getContext();\n },\n get state() {\n return getCurrentMachine();\n },\n actions,\n };\n}\n\n/**\n * Creates a factory for building type-safe, framework-agnostic Ensembles.\n * This is a higher-order function that captures the application's state store\n * and state-discriminant logic in a closure.\n *\n * This allows you to define your application's state \"environment\" once and then\n * easily create multiple, consistent ensembles by only providing the behavioral logic.\n *\n * @template C The shared context type for the application.\n * @param store The application's state store (e.g., from React, Zustand, etc.).\n * @param getDiscriminant An accessor function that determines the current state from the context.\n * @returns A `withFactories` function that is pre-configured for your app's environment.\n */\nexport function createEnsembleFactory<C extends object>(\n store: StateStore<C>,\n getDiscriminant: (context: C) => keyof any\n) {\n /**\n * This returned function is pre-configured with the `store` and `getDiscriminant` logic.\n * It takes the machine factories (the behavioral logic) and returns a complete Ensemble.\n *\n * @template F The type of the factories object.\n * @param factories An object where each key is a state name and each value is a\n * function that creates a machine instance for that state.\n * @returns A fully-formed, reactive, and type-safe Ensemble instance.\n */\n return function withFactories<\n F extends Record<string, (context: C) => Machine<C>>\n >(\n factories: F\n ): Ensemble<ReturnType<F[keyof F]>, C> {\n // We simply call the original createEnsemble with the captured arguments.\n return createEnsemble(store, factories, getDiscriminant as (context: C) => keyof F);\n };\n}\n\n// =============================================================================\n// SECTION 3: GENERATOR INTEGRATION\n// =============================================================================\n\n/**\n * Executes a generator-based workflow using a Managed State Runner.\n *\n * This provides the cleanest syntax for multi-step imperative workflows, as the\n * `yield` keyword is only used for control flow, not state passing. Unlike the\n * basic `run()` function from the core library, this works directly with a Runner,\n * making it perfect for complex local state orchestration.\n *\n * **Syntax benefits:**\n * - No need to manually thread state through a chain of transitions\n * - `yield` is purely for control flow, not for passing state\n * - Can use regular `if`/`for` statements without helpers\n * - Generator return value is automatically your final result\n *\n * @param flow - A generator function that receives the `Runner` instance. The\n * generator can yield values (returned by transitions) and use them for control\n * flow, or just yield for side effects.\n * @param initialMachine - The machine to start the flow with. A runner will be\n * created from this automatically.\n * @returns The final value returned by the generator (the `return` statement).\n *\n * @example\n * // Simple sequential transitions\n * const result = runWithRunner(function* (runner) {\n * yield runner.actions.increment();\n * yield runner.actions.add(10);\n * if (runner.context.count > 5) {\n * yield runner.actions.reset();\n * }\n * return runner.context;\n * }, createCounterMachine());\n * console.log(result); // { count: 0 }\n *\n * @example\n * // Complex workflow with Type-State narrowing\n * const result = runWithRunner(function* (runner) {\n * // Start logged out\n * if (runner.state.context.status === 'loggedOut') {\n * yield runner.actions.login('alice');\n * }\n *\n * // Now logged in, fetch profile\n * if (runner.state.context.status === 'loggedIn') {\n * yield runner.actions.fetchProfile();\n * }\n *\n * // Return final context\n * return runner.context;\n * }, createAuthMachine());\n */\nexport function runWithRunner<M extends Machine<any>, T>(\n flow: (runner: Runner<M>) => Generator<any, T, any>,\n initialMachine: M\n): T {\n const runner = createRunner(initialMachine);\n const generator = flow(runner);\n let result = generator.next();\n while (!result.done) {\n result = generator.next();\n }\n return result.value;\n}\n\n/**\n * Executes a generator-based workflow using an Ensemble.\n *\n * This pattern is ideal for orchestrating complex sagas or workflows that\n * interact with a global, framework-managed state. Like `runWithRunner`,\n * it provides clean imperative syntax for multi-step workflows, but operates\n * on an Ensemble's external store rather than internal state.\n *\n * **Key differences from runWithRunner:**\n * - Works with external state stores (React, Solid, etc.)\n * - Useful for global workflows and sagas\n * - State changes automatically propagate to the framework\n * - Great for testing framework-agnostic state logic\n *\n * @param flow - A generator function that receives the `Ensemble` instance.\n * The generator can read `ensemble.context` and call `ensemble.actions`.\n * @param ensemble - The `Ensemble` to run the workflow against. Its context\n * is shared across the entire workflow.\n * @returns The final value returned by the generator (the `return` statement).\n *\n * @example\n * // Multi-step workflow with an ensemble\n * const result = runWithEnsemble(function* (ensemble) {\n * // Fetch initial data\n * if (ensemble.context.status === 'idle') {\n * yield ensemble.actions.fetch();\n * }\n *\n * // Process the data\n * if (ensemble.context.status === 'success') {\n * yield ensemble.actions.process(ensemble.context.data);\n * }\n *\n * return ensemble.context;\n * }, ensemble);\n *\n * @example\n * // Testing a workflow without a UI framework\n * const store: StateStore<AppContext> = {\n * getContext: () => context,\n * setContext: (newCtx) => Object.assign(context, newCtx)\n * };\n *\n * const ensemble = createEnsemble(store, factories, (ctx) => ctx.status);\n *\n * // Run a complex workflow and assert the result\n * const result = runWithEnsemble(function* (e) {\n * yield e.actions.login('alice');\n * yield e.actions.fetchProfile();\n * yield e.actions.updateEmail('alice@example.com');\n * return e.context;\n * }, ensemble);\n *\n * expect(result.userEmail).toBe('alice@example.com');\n */\nexport function runWithEnsemble<\n AllMachines extends Machine<any>,\n C extends object,\n T\n>(\n flow: (ensemble: Ensemble<AllMachines, C>) => Generator<any, T, any>,\n ensemble: Ensemble<AllMachines, C>\n): T {\n const generator = flow(ensemble);\n let result = generator.next();\n while (!result.done) {\n result = generator.next();\n }\n return result.value;\n}\n\n// =============================================================================\n// SECTION 4: CLASS-BASED MULTI-MACHINE (OOP APPROACH)\n// =============================================================================\n\n/**\n * The base class for creating a class-based state machine (MultiMachine).\n * Extend this class to define your state machine's logic using instance methods\n * as transitions.\n *\n * This approach is ideal for developers who prefer class-based architectures\n * and want to manage a shared context directly through an external StateStore.\n * It provides a familiar OOP interface while maintaining the decoupling benefits\n * of the StateStore pattern.\n *\n * **Key features:**\n * - Extend this class and define transition methods as instance methods\n * - Protected `context` getter provides access to the current state\n * - Protected `setContext()` method updates the external store\n * - Works seamlessly with `createMultiMachine()`\n *\n * @template C - The shared context type. Should typically contain a discriminant\n * property (like `status`) that identifies the current state.\n *\n * @example\n * // Define your context type\n * type AppContext = { status: 'idle' | 'loading' | 'error'; data?: any; error?: string };\n *\n * // Extend MultiMachineBase and define transitions as methods\n * class AppMachine extends MultiMachineBase<AppContext> {\n * async fetch(url: string) {\n * // Notify subscribers we're loading\n * this.setContext({ ...this.context, status: 'loading' });\n *\n * try {\n * const data = await fetch(url).then(r => r.json());\n * // Update state when done\n * this.setContext({ ...this.context, status: 'idle', data });\n * } catch (error) {\n * // Handle errors\n * this.setContext({\n * ...this.context,\n * status: 'error',\n * error: error.message\n * });\n * }\n * }\n *\n * reset() {\n * this.setContext({ status: 'idle' });\n * }\n * }\n */\nexport abstract class MultiMachineBase<C extends object> {\n /**\n * The external state store that manages the machine's context.\n * @protected\n */\n protected store: StateStore<C>;\n\n /**\n * @param store - The StateStore that will manage this machine's context.\n */\n constructor(store: StateStore<C>) {\n this.store = store;\n }\n\n /**\n * Read-only access to the current context from the external store.\n * This getter always returns the latest context from the store.\n *\n * @protected\n *\n * @example\n * const currentStatus = this.context.status;\n * const currentData = this.context.data;\n */\n protected get context(): C {\n return this.store.getContext();\n }\n\n /**\n * Update the shared context in the external store.\n * Call this method in your transition methods to update the state.\n *\n * @protected\n * @param newContext - The new context object. Should typically be a shallow\n * copy with only the properties you're changing, merged with the current\n * context using spread operators.\n *\n * @example\n * // In a transition method:\n * this.setContext({ ...this.context, status: 'loading' });\n *\n * @example\n * // Updating nested properties:\n * this.setContext({\n * ...this.context,\n * user: { ...this.context.user, name: 'Alice' }\n * });\n */\n protected setContext(newContext: C): void {\n this.store.setContext(newContext);\n }\n}\n\n/**\n * Creates a live, type-safe instance of a class-based state machine (MultiMachine).\n *\n * This is the class-based alternative to the functional `createEnsemble` pattern,\n * designed for developers who prefer an OOP-style architecture. This function takes\n * your MultiMachine class blueprint and an external state store, and wires them\n * together. The returned object is a Proxy that dynamically exposes both context\n * properties and the available transition methods from your class.\n *\n * **Key features:**\n * - Directly access context properties as if they were on the machine object\n * - Call transition methods to update state through the store\n * - Type-safe integration with TypeScript\n * - Seamless Proxy-based API (no special method names or API quirks)\n *\n * **How it works:**\n * The returned Proxy intercepts property access. For context properties, it returns\n * values from the store. For methods, it calls them on the MultiMachine instance.\n * This creates the illusion of a single object that is both data and behavior.\n *\n * @template C - The shared context type.\n * @template T - The MultiMachine class type.\n *\n * @param MachineClass - The class you defined that extends `MultiMachineBase<C>`.\n * @param store - The `StateStore` that will manage the machine's context.\n * @returns A Proxy that merges context properties with class methods, allowing\n * direct access to both via a unified object interface.\n *\n * @example\n * // Define your context type\n * type CounterContext = { count: number };\n *\n * // Define your machine class\n * class CounterMachine extends MultiMachineBase<CounterContext> {\n * increment() {\n * this.setContext({ count: this.context.count + 1 });\n * }\n *\n * add(n: number) {\n * this.setContext({ count: this.context.count + n });\n * }\n *\n * reset() {\n * this.setContext({ count: 0 });\n * }\n * }\n *\n * // Create a store\n * let sharedContext = { count: 0 };\n * const store = {\n * getContext: () => sharedContext,\n * setContext: (ctx) => { sharedContext = ctx; }\n * };\n *\n * // Create the machine instance\n * const machine = createMultiMachine(CounterMachine, store);\n *\n * // Use it naturally - properties and methods seamlessly integrated\n * console.log(machine.count); // 0\n * machine.increment();\n * console.log(machine.count); // 1\n * machine.add(5);\n * console.log(machine.count); // 6\n * machine.reset();\n * console.log(machine.count); // 0\n *\n * @example\n * // Status-based state machine with type discrimination\n * type AppContext = {\n * status: 'idle' | 'loading' | 'success' | 'error';\n * data?: any;\n * error?: string;\n * };\n *\n * class AppMachine extends MultiMachineBase<AppContext> {\n * async fetch() {\n * this.setContext({ ...this.context, status: 'loading' });\n * try {\n * const data = await fetch('/api/data').then(r => r.json());\n * this.setContext({ status: 'success', data });\n * } catch (error) {\n * this.setContext({\n * status: 'error',\n * error: error instanceof Error ? error.message : 'Unknown error'\n * });\n * }\n * }\n *\n * reset() {\n * this.setContext({ status: 'idle' });\n * }\n * }\n *\n * // Set up\n * let context: AppContext = { status: 'idle' };\n * const store = {\n * getContext: () => context,\n * setContext: (ctx) => { context = ctx; }\n * };\n *\n * const app = createMultiMachine(AppMachine, store);\n *\n * // Use naturally with type discrimination\n * console.log(app.status); // 'idle'\n *\n * if (app.status === 'idle') {\n * app.fetch(); // Transition to loading\n * }\n *\n * // Later: app.status === 'success'\n * // console.log(app.data); // Access the data\n */\nexport function createMultiMachine<\n C extends object,\n T extends MultiMachineBase<C>\n>(\n MachineClass: new (store: StateStore<C>) => T,\n store: StateStore<C>\n): C & T {\n const instance = new MachineClass(store);\n\n return new Proxy({} as C & T, {\n get(_target, prop: string | symbol) {\n // 1. Prioritize properties from the context\n const context = store.getContext();\n if (prop in context) {\n return (context as any)[prop];\n }\n\n // 2. Then check for methods on the instance\n const method = (instance as any)[prop];\n if (typeof method === 'function') {\n return (...args: any[]) => {\n return method.apply(instance, args);\n };\n }\n\n return undefined;\n },\n\n set(_target, prop: string | symbol, value: any) {\n // Allow direct mutation of context properties\n const context = store.getContext();\n if (prop in context) {\n const newContext = { ...context, [prop]: value } as C;\n store.setContext(newContext);\n return true;\n }\n return false;\n },\n\n has(_target, prop: string | symbol) {\n // Support `in` operator checks\n const context = store.getContext();\n return prop in context || typeof (instance as any)[prop] === 'function';\n },\n\n ownKeys(_target) {\n // Support reflection APIs\n const context = store.getContext();\n const contextKeys = Object.keys(context);\n const methodKeys = Object.getOwnPropertyNames(\n Object.getPrototypeOf(instance)\n ).filter((key) => key !== 'constructor' && typeof (instance as any)[key] === 'function');\n return Array.from(new Set([...contextKeys, ...methodKeys]));\n },\n\n getOwnPropertyDescriptor(_target, prop) {\n // Support property descriptors\n const context = store.getContext();\n if (prop in context || typeof (instance as any)[prop] === 'function') {\n return {\n value: undefined,\n writable: true,\n enumerable: true,\n configurable: true,\n };\n }\n return undefined;\n },\n });\n}\n\n// =============================================================================\n// SECTION 5: THE MUTABLE MACHINE (EXPERIMENTAL)\n// =============================================================================\n\n/**\n * A mapped type that defines the shape of a Mutable Machine: an intersection\n * of the context `C` and all possible transitions.\n */\ntype MutableMachine<C extends object, AllMachines extends Machine<any>> = C &\n AllTransitions<AllMachines>;\n\n\n /**\n * Creates a Mutable Machine that uses a shared, mutable context. This primitive\n * provides a stable object reference whose properties are mutated in place,\n * offering a direct, imperative API.\n *\n * ---\n *\n * ### Key Characteristics & Trade-offs\n *\n * - **Stable Object Reference**: The machine is a single object. You can pass this\n * reference around, and it will always reflect the current state.\n * - **Direct Imperative API**: Transitions are called like methods directly on the\n * object (`machine.login('user')`), and the object's properties update immediately.\n * - **No State History**: Since the context is mutated, the history of previous\n * states is not preserved, which makes patterns like time-travel debugging impossible.\n * - **Not for Reactive UIs**: Most UI frameworks (React, Solid, Vue) rely on\n * immutable state changes to trigger updates. Mutating the context directly\n * will not cause components to re-render. Use the `Ensemble` primitive for UI integration.\n *\n * ---\n *\n * ### Best Suited For\n *\n * - **Backend Services & Game Logic**: Ideal for managing state in server-side\n * processes, game loops, or other non-UI environments where performance and a\n * stable state object are priorities.\n * - **Complex Synchronous Scripts**: Useful for orchestrating data processing\n * pipelines, command-line tools, or any script where state needs to be managed\n * imperatively without passing it through a function chain.\n *\n * @template C - The shared context type.\n * @template F - An object of functions that create machine instances for each state.\n * **Crucially, transitions inside these machines must be pure functions that\n * return the *next context object*, not a new machine instance.**\n * @param sharedContext - The initial context object. This object will be mutated.\n * @param factories - An object mapping state names to functions that create machine instances.\n * @param getDiscriminant - An accessor function that takes the context and returns the key\n * of the current state in the `factories` object. Provides refactoring safety.\n * @returns A Proxy that acts as a stable, mutable machine instance.\n *\n * @example\n * // ===== 1. Basic Authentication Example =====\n *\n * type AuthContext =\n * | { status: 'loggedOut'; error?: string }\n * | { status: 'loggedIn'; username: string };\n *\n * const authFactories = {\n * loggedOut: (ctx: AuthContext) => ({\n * context: ctx,\n * // This transition is a PURE function that returns the NEXT CONTEXT\n * login: (username: string) => ({ status: 'loggedIn', username }),\n * }),\n * loggedIn: (ctx: AuthContext) => ({\n * context: ctx,\n * logout: () => ({ status: 'loggedOut' }),\n * }),\n * };\n *\n * const authUser = createMutableMachine(\n * { status: 'loggedOut' } as AuthContext,\n * authFactories,\n * 'status'\n * );\n *\n * const userReference = authUser; // Store a reference to the object\n *\n * console.log(authUser.status); // 'loggedOut'\n *\n * authUser.login('alice'); // Mutates the object in place\n *\n * console.log(authUser.status); // 'loggedIn'\n * console.log(authUser.username); // 'alice'\n *\n * // The original reference points to the same, mutated object\n * console.log(userReference.status); // 'loggedIn'\n * console.log(userReference === authUser); // true\n *\n * // --- Type-safe transitions ---\n * // `authUser.login('bob')` would now throw a runtime error because `login`\n * // is not a valid action in the 'loggedIn' state.\n *\n * if (authUser.status === 'loggedIn') {\n * // TypeScript correctly narrows the type here, allowing a safe call.\n * authUser.logout();\n * }\n * console.log(authUser.status); // 'loggedOut'\n *\n * @example\n * // ===== 2. Game State Loop Example =====\n *\n * type PlayerContext = {\n * state: 'idle' | 'walking' | 'attacking';\n * hp: number;\n * position: { x: number; y: number };\n * };\n *\n * const playerFactories = {\n * idle: (ctx: PlayerContext) => ({\n * context: ctx,\n * walk: (dx: number, dy: number) => ({ ...ctx, state: 'walking', position: { x: ctx.position.x + dx, y: ctx.position.y + dy } }),\n * attack: () => ({ ...ctx, state: 'attacking' }),\n * }),\n * walking: (ctx: PlayerContext) => ({\n * context: ctx,\n * stop: () => ({ ...ctx, state: 'idle' }),\n * }),\n * attacking: (ctx: PlayerContext) => ({\n * context: ctx,\n * finishAttack: () => ({ ...ctx, state: 'idle' }),\n * }),\n * };\n *\n * const player = createMutableMachine(\n * { state: 'idle', hp: 100, position: { x: 0, y: 0 } },\n * playerFactories,\n * (ctx) => ctx.state\n * );\n *\n * // Simulate a game loop\n * function processInput(input: 'move_right' | 'attack') {\n * if (player.state === 'idle') {\n * if (input === 'move_right') player.walk(1, 0);\n * if (input === 'attack') player.attack();\n * }\n * console.log(`State: ${player.state}, Position: (${player.position.x}, ${player.position.y})`);\n * }\n *\n * processInput('move_right'); // State: walking, Position: (1, 0)\n * player.stop();\n * processInput('attack'); // State: attacking, Position: (1, 0)\n */\nexport function createMutableMachine<\n C extends object,\n F extends Record<string, (context: C) => Machine<C>>\n>(\n sharedContext: C,\n factories: F,\n getDiscriminant: (context: C) => keyof F\n): MutableMachine<C, ReturnType<F[keyof F]>> {\n const getCurrentMachine = (): ReturnType<F[keyof F]> => {\n const currentStateName = getDiscriminant(sharedContext);\n const factory = factories[currentStateName];\n if (!factory) {\n throw new Error(\n `[MutableMachine] Invalid state: No factory for state \"${String(currentStateName)}\".`\n );\n }\n return factory(sharedContext) as ReturnType<F[keyof F]>;\n };\n\n return new Proxy(sharedContext, {\n get(target, prop, _receiver) {\n // 1. Prioritize properties on the context object itself.\n if (prop in target) {\n return (target as any)[prop];\n }\n\n // 2. If not on context, check if it's a valid transition for the current state.\n const currentMachine = getCurrentMachine();\n const transition = (currentMachine as any)[prop];\n\n if (typeof transition === 'function') {\n return (...args: any[]) => {\n // This pattern requires transitions to be pure functions that return the next context.\n const nextContext = transition.apply(currentMachine.context, args);\n if (typeof nextContext !== 'object' || nextContext === null) {\n console.warn(`[MutableMachine] Transition \"${String(prop)}\" did not return a valid context object. State may be inconsistent.`);\n return;\n }\n // 3. Mutate the shared context with the result.\n // Clear existing keys before assigning to handle removed properties.\n Object.keys(target).forEach(key => delete (target as any)[key]);\n Object.assign(target, nextContext);\n };\n }\n\n return undefined;\n },\n set(target, prop, value, _receiver) {\n // Allow direct mutation of the context\n (target as any)[prop] = value;\n return true;\n },\n has(target, prop) {\n // Let checks like `if ('login' in machine)` work correctly.\n const currentMachine = getCurrentMachine();\n return prop in target || typeof (currentMachine as any)[prop] === 'function';\n }\n }) as MutableMachine<C, ReturnType<F[keyof F]>>;\n}", "/**\n * @file Higher-Level Abstractions for @doeixd/machine\n * @description\n * This module provides a collection of powerful, pre-built patterns and primitives\n * on top of the core `@doeixd/machine` library. These utilities are designed to\n * solve common, recurring problems in state management, such as data fetching,\n * hierarchical state, and toggling boolean context properties.\n *\n * Think of this as the \"standard library\" of common machine patterns.\n */\n\nimport {\n MachineBase,\n Machine,\n Transitions,\n // AsyncMachine,\n setContext,\n Context,\n // MaybePromise,\n} from './index'; // Assuming this is a sibling package or in the same project\n\n// =============================================================================\n// SECTION 1: CUSTOM PRIMITIVES FOR COMPOSITION\n// =============================================================================\n\n/**\n * A type utility to infer the child machine type from a parent.\n */\ntype ChildMachine<P> = P extends MachineBase<{ child: infer C }> ? C : never;\n\n/**\n * Creates a transition method that delegates a call to a child machine.\n *\n * This is a higher-order function that reduces boilerplate when implementing\n * hierarchical state machines. It generates a method for the parent machine that:\n * 1. Checks if the specified action exists on the current child state.\n * 2. If it exists, calls the action on the child.\n * 3. Reconstructs the parent machine with the new child state returned by the action.\n * 4. If the action doesn't exist on the child, it returns the parent machine unchanged.\n *\n * @template P - The parent machine type, which must have a `child` property in its context.\n * @template K - The name of the action on the child machine to delegate to.\n * @param actionName - The string name of the child's transition method.\n * @param ...args - Any arguments to pass to the child's transition method.\n * @returns The parent machine instance, with its `child` state potentially updated.\n *\n * @example\n * ```typescript\n * class Parent extends MachineBase<{ child: ChildMachine }> {\n * // Instead of writing a manual delegation method...\n * // save = () => {\n * // if ('save' in this.context.child) {\n * // const newChild = this.context.child.save();\n * // return setContext(this, { child: newChild });\n * // }\n * // return this;\n * // }\n * \n * // ...you can just use the primitive.\n * save = delegateToChild('save');\n * edit = delegateToChild('edit');\n * }\n * ```\n */\nexport function delegateToChild<\n P extends MachineBase<{ child: MachineBase<any> }>,\n K extends keyof ChildMachine<P> & string\n>(\n actionName: K\n): (\n ...args: ChildMachine<P>[K] extends (...a: infer A) => any ? A : never\n) => P {\n return function(this: P, ...args: any[]): P {\n const child = this.context.child as any;\n\n if (typeof child[actionName] === 'function') {\n const newChildState = child[actionName](...args);\n return setContext(this as any, { ...this.context, child: newChildState }) as P;\n }\n \n // If the action is not available on the current child state, do nothing.\n return this;\n };\n}\n\n/**\n * Creates a transition method that toggles a boolean property within the machine's context.\n *\n * This is a simple utility to reduce boilerplate for managing boolean flags.\n *\n * @template M - The machine type.\n * @template K - The key of the boolean property in the machine's context.\n * @param prop - The string name of the context property to toggle.\n * @returns A new machine instance with the toggled property.\n *\n * @example\n * ```typescript\n * class SettingsMachine extends MachineBase<{ notifications: boolean; darkMode: boolean }> {\n * toggleNotifications = toggle('notifications');\n * toggleDarkMode = toggle('darkMode');\n * }\n * ```\n */\nexport function toggle<\n M extends MachineBase<any>,\n K extends keyof Context<M>\n>(\n prop: K\n): (this: M) => M {\n return function(this: M): M {\n // Ensure the property is boolean-like for a sensible toggle\n if (typeof this.context[prop] !== 'boolean') {\n console.warn(`[toggle primitive] Property '${String(prop)}' is not a boolean. Toggling may have unexpected results.`);\n }\n return setContext(this as any, {\n ...this.context,\n [prop]: !this.context[prop],\n }) as M;\n };\n}\n\n\n// =============================================================================\n// SECTION 2: PRE-BUILT, CUSTOMIZABLE MACHINES\n// =============================================================================\n\n/**\n * A fully-featured, pre-built state machine for data fetching.\n * It handles loading, success, error states, cancellation, and retry logic out of the box.\n *\n * This machine is highly customizable through its configuration options.\n */\n\n// --- Types for the Fetch Machine ---\n\nexport type Fetcher<T, _E = Error> = (params: any) => Promise<T>;\nexport type OnSuccess<T> = (data: T) => void;\nexport type OnError<E> = (error: E) => void;\n\nexport interface FetchMachineConfig<T, E = Error> {\n fetcher: Fetcher<T, E>;\n initialParams?: any;\n maxRetries?: number;\n onSuccess?: OnSuccess<T>;\n onError?: OnError<E>;\n}\n\n// --- Contexts for Fetch States ---\ntype IdleContext = { status: 'idle' };\ntype LoadingContext = { status: 'loading'; abortController: AbortController; attempts: number };\ntype RetryingContext = { status: 'retrying'; error: any; attempts: number };\ntype SuccessContext<T> = { status: 'success'; data: T };\ntype ErrorContext<E> = { status: 'error'; error: E };\ntype CanceledContext = { status: 'canceled' };\n\n// --- Machine State Classes (internal) ---\n\nclass IdleMachine<T, E> extends MachineBase<IdleContext> {\n constructor(private config: FetchMachineConfig<T, E>) { super({ status: 'idle' }); }\n fetch = (params?: any) => new LoadingMachine(this.config, params ?? this.config.initialParams, 1);\n}\n\nclass LoadingMachine<T, E> extends MachineBase<LoadingContext> {\n constructor(private config: FetchMachineConfig<T, E>, private params: any, attempts: number) {\n super({ status: 'loading', abortController: new AbortController(), attempts });\n this.execute(); // Auto-execute on creation\n }\n\n private async execute() {\n // This is a \"fire-and-forget\" call that transitions the machine internally.\n // In a real implementation, this would be managed by an external runner.\n // For this example, we assume an external mechanism calls `succeed`, `fail`, etc.\n }\n \n succeed = (data: T) => {\n this.config.onSuccess?.(data);\n return new SuccessMachine<T, E>(this.config, { status: 'success', data });\n };\n\n fail = (error: E) => {\n const maxRetries = this.config.maxRetries ?? 3;\n if (this.context.attempts < maxRetries) {\n return new RetryingMachine<T, E>(this.config, this.params, error, this.context.attempts);\n }\n this.config.onError?.(error);\n return new ErrorMachine<T, E>(this.config, { status: 'error', error });\n };\n \n cancel = () => {\n this.context.abortController.abort();\n return new CanceledMachine<T, E>(this.config);\n };\n}\n\nclass RetryingMachine<T, E> extends MachineBase<RetryingContext> {\n constructor(private config: FetchMachineConfig<T, E>, private params: any, error: E, attempts: number) {\n super({ status: 'retrying', error, attempts });\n // In a real implementation, you'd have a delay here (e.g., exponential backoff)\n // before transitioning to LoadingMachine again.\n }\n \n // This would be called after a delay.\n retry = (params?: any) => new LoadingMachine<T, E>(this.config, params ?? this.params, this.context.attempts + 1);\n}\n\nclass SuccessMachine<T, E> extends MachineBase<SuccessContext<T>> {\n constructor(private config: FetchMachineConfig<T, E>, context: SuccessContext<T>) { super(context); }\n refetch = (params?: any) => new LoadingMachine(this.config, params ?? this.config.initialParams, 1);\n}\n\nclass ErrorMachine<T, E> extends MachineBase<ErrorContext<E>> {\n constructor(private config: FetchMachineConfig<T, E>, context: ErrorContext<E>) { super(context); }\n retry = (params?: any) => new LoadingMachine(this.config, params ?? this.config.initialParams, 1);\n}\n\nclass CanceledMachine<T, E> extends MachineBase<CanceledContext> {\n constructor(private config: FetchMachineConfig<T, E>) { super({ status: 'canceled' }); }\n refetch = (params?: any) => new LoadingMachine(this.config, params ?? this.config.initialParams, 1);\n}\n\nexport type FetchMachine<T, E = Error> =\n | IdleMachine<T, E>\n | LoadingMachine<T, E>\n | RetryingMachine<T, E>\n | SuccessMachine<T, E>\n | ErrorMachine<T, E>\n | CanceledMachine<T, E>;\n\n/**\n * Creates a pre-built, highly configurable async data-fetching machine.\n *\n * This factory function returns a state machine that handles the entire lifecycle\n * of a data request, including loading, success, error, cancellation, and retries.\n *\n * @template T - The type of the data to be fetched.\n * @template E - The type of the error.\n * @param config - Configuration object.\n * @param config.fetcher - An async function that takes params and returns the data.\n * @param [config.maxRetries=3] - The number of times to retry on failure.\n * @param [config.onSuccess] - Optional callback fired with the data on success.\n * @param [config.onError] - Optional callback fired with the error on final failure.\n * @returns An `IdleMachine` instance, ready to start fetching.\n *\n * @example\n * ```typescript\n * // 1. Define your data fetching logic\n * async function fetchUser(id: number): Promise<{ id: number; name: string }> {\n * const res = await fetch(`/api/users/${id}`);\n * if (!res.ok) throw new Error('User not found');\n * return res.json();\n * }\n *\n * // 2. Create the machine\n * const userMachine = createFetchMachine({\n * fetcher: fetchUser,\n * onSuccess: (user) => console.log(`Fetched: ${user.name}`),\n * });\n *\n * // 3. Use it (e.g., in a React hook)\n * // let machine = userMachine;\n * // machine = await machine.fetch(123); // Transitions to Loading, then Success/Error\n * ```\n * \n * @note This is a simplified example. For a real-world implementation, you would\n * typically use this machine with a runner (like `runMachine` or `useMachine`) to\n * manage the async transitions and state updates automatically.\n */\nexport function createFetchMachine<T, E = Error>(\n config: FetchMachineConfig<T, E>\n): FetchMachine<T, E> {\n // A more robust implementation would validate the config here.\n return new IdleMachine<T, E>(config);\n}\n\n/**\n * The core type for a Parallel Machine.\n * It combines two machines, M1 and M2, into a single, unified type.\n * @template M1 - The first machine in the parallel composition.\n * @template M2 - The second machine in the parallel composition.\n */\nexport type ParallelMachine<\n M1 extends Machine<any>,\n M2 extends Machine<any>\n> = Machine<Context<M1> & Context<M2>> & {\n // Map transitions from M1. When called, they return a new ParallelMachine\n // where M1 has transitioned but M2 remains the same.\n [K in keyof Transitions<M1>]: Transitions<M1>[K] extends (...args: infer A) => infer R\n ? R extends Machine<any>\n ? (...args: A) => ParallelMachine<R, M2>\n : never\n : never;\n} & {\n // Map transitions from M2. When called, they return a new ParallelMachine\n // where M2 has transitioned but M1 remains the same.\n [K in keyof Transitions<M2>]: Transitions<M2>[K] extends (...args: infer A) => infer R\n ? R extends Machine<any>\n ? (...args: A) => ParallelMachine<M1, R>\n : never\n : never;\n};\n\n\n/**\n * Creates a parallel machine by composing two independent machines.\n *\n * This function takes two machines and merges them into a single machine entity.\n * Transitions from either machine can be called, and they will only affect\n * their respective part of the combined state.\n *\n * NOTE: This primitive assumes that the transition names between the two\n * machines do not collide. If both machines have a transition named `next`,\n * the behavior is undefined.\n *\n * @param m1 The first machine instance.\n * @param m2 The second machine instance.\n * @returns A new ParallelMachine instance.\n */\nexport function createParallelMachine<\n M1 extends Machine<any>,\n M2 extends Machine<any>\n>(m1: M1, m2: M2): ParallelMachine<M1, M2> {\n // 1. Combine the contexts\n const combinedContext = { ...m1.context, ...m2.context };\n\n const transitions1 = { ...m1 } as Transitions<M1>;\n const transitions2 = { ...m2 } as Transitions<M2>;\n delete (transitions1 as any).context;\n delete (transitions2 as any).context;\n\n const combinedTransitions = {} as any;\n\n // 2. Re-wire transitions from the first machine\n for (const key in transitions1) {\n const transitionFn = (transitions1 as any)[key];\n combinedTransitions[key] = (...args: any[]) => {\n const nextM1 = transitionFn.apply(m1.context, args);\n // Recursively create a new parallel machine with the new M1 state\n return createParallelMachine(nextM1, m2);\n };\n }\n\n // 3. Re-wire transitions from the second machine\n for (const key in transitions2) {\n const transitionFn = (transitions2 as any)[key];\n combinedTransitions[key] = (...args: any[]) => {\n const nextM2 = transitionFn.apply(m2.context, args);\n // Recursively create a new parallel machine with the new M2 state\n return createParallelMachine(m1, nextM2);\n };\n }\n\n return {\n context: combinedContext,\n ...combinedTransitions,\n } as ParallelMachine<M1, M2>;\n}\n\n// A mapped type that transforms the return types of a machine's transitions.\n// For a transition that returns `NewMachineState`, this will transform it to return `T`.\nexport type RemapTransitions<M extends Machine<any>, T> = {\n [K in keyof Transitions<M>]: Transitions<M>[K] extends (...args: infer A) => any\n ? (...args: A) => T\n : never;\n};", "/**\n * @file Core middleware types and basic middleware creation\n */\n\nimport type { Context, BaseMachine } from '../index';\n\n// =============================================================================\n// SECTION: MIDDLEWARE TYPES\n// =============================================================================\n\n/**\n * Context object passed to middleware hooks containing transition metadata.\n * @template C - The context object type\n */\nexport interface MiddlewareContext<C extends object> {\n /** The name of the transition being called */\n transitionName: string;\n /** The current machine context before the transition */\n context: Readonly<C>;\n /** Arguments passed to the transition function */\n args: any[];\n}\n\n/**\n * Result object passed to after hooks containing transition outcome.\n * @template C - The context object type\n */\nexport interface MiddlewareResult<C extends object> {\n /** The name of the transition that was called */\n transitionName: string;\n /** The context before the transition */\n prevContext: Readonly<C>;\n /** The context after the transition */\n nextContext: Readonly<C>;\n /** Arguments that were passed to the transition */\n args: any[];\n}\n\n/**\n * Error context passed to error hooks.\n * @template C - The context object type\n */\nexport interface MiddlewareError<C extends object> {\n /** The name of the transition that failed */\n transitionName: string;\n /** The context when the error occurred */\n context: Readonly<C>;\n /** Arguments that were passed to the transition */\n args: any[];\n /** The error that was thrown */\n error: Error;\n}\n\n/**\n * Configuration object for middleware hooks.\n * All hooks are optional - provide only the ones you need.\n * @template C - The context object type\n */\nexport interface MiddlewareHooks<C extends object> {\n /**\n * Called before a transition executes.\n * Can be used for validation, logging, analytics, etc.\n *\n * @param ctx - Transition context with machine state and transition details\n * @returns void to continue, CANCEL to abort silently, or Promise for async validation\n */\n before?: (ctx: MiddlewareContext<C>) => void | typeof CANCEL | Promise<void | typeof CANCEL>;\n\n /**\n * Called after a transition successfully executes.\n * Receives both the previous and next context.\n * Cannot prevent the transition (it already happened).\n *\n * @param result - Transition result with before/after contexts and transition details\n */\n after?: (result: MiddlewareResult<C>) => void | Promise<void>;\n\n /**\n * Called when a transition throws an error.\n * Can be used for error reporting, recovery, etc.\n *\n * @param error - Error context with transition details and error information\n */\n error?: (error: MiddlewareError<C>) => void | Promise<void>;\n}\n\n/**\n * Options for configuring middleware behavior.\n */\nexport interface MiddlewareOptions {\n /** Whether to continue execution if a hook throws an error */\n continueOnError?: boolean;\n /** Whether to log errors from hooks */\n logErrors?: boolean;\n /** Custom error handler for hook errors */\n onError?: (error: Error, hookName: string, ctx: any) => void;\n}\n\n/**\n * Symbol used to cancel a transition from a before hook.\n */\nexport const CANCEL = Symbol('CANCEL');\n\n// =============================================================================\n// SECTION: CORE MIDDLEWARE FUNCTIONS\n// =============================================================================\n\n/**\n * Creates a middleware function that wraps machine transitions with hooks.\n *\n * @template M - The machine type\n * @param machine - The machine to instrument\n * @param hooks - Middleware hooks to execute\n * @param options - Middleware configuration options\n * @returns A new machine with middleware applied\n */\nexport function createMiddleware<M extends BaseMachine<any>>(\n machine: M,\n hooks: MiddlewareHooks<Context<M>>,\n options: MiddlewareOptions = {}\n): M {\n const { continueOnError = false, logErrors = true, onError } = options;\n\n // Create a wrapped machine that intercepts all transition calls\n const wrappedMachine: any = { ...machine };\n\n // Copy any extra properties from the original machine (for middleware composition)\n for (const prop in machine) {\n if (!Object.prototype.hasOwnProperty.call(machine, prop)) continue;\n if (prop !== 'context' && typeof machine[prop] !== 'function') {\n wrappedMachine[prop] = machine[prop];\n }\n }\n\n // Wrap each transition function\n for (const prop in machine) {\n if (!Object.prototype.hasOwnProperty.call(machine, prop)) continue;\n const value = machine[prop];\n if (typeof value === 'function' && prop !== 'context') {\n wrappedMachine[prop] = function (this: any, ...args: any[]) {\n const transitionName = prop;\n const context = wrappedMachine.context;\n\n // Helper function to execute the transition and after hooks\n const executeTransition = () => {\n // 2. Execute the actual transition\n let nextMachine: any;\n try {\n nextMachine = value.apply(this, args);\n } catch (error) {\n // 3. Execute error hooks if transition failed\n if (hooks.error) {\n try {\n // Error hooks are called synchronously for now\n hooks.error({\n transitionName,\n context,\n args: [...args],\n error: error as Error\n });\n } catch (hookError) {\n if (!continueOnError) throw hookError;\n if (logErrors) console.error(`Middleware error hook error for ${transitionName}:`, hookError);\n onError?.(hookError as Error, 'error', { transitionName, context, args, error });\n }\n }\n throw error; // Re-throw the original error\n }\n\n // Ensure the returned machine has the same extra properties as the wrapped machine\n const ensureMiddlewareProperties = (machine: any) => {\n if (machine && typeof machine === 'object' && machine.context) {\n // Copy extra properties from the wrapped machine to the returned machine\n for (const prop in wrappedMachine) {\n if (!Object.prototype.hasOwnProperty.call(wrappedMachine, prop)) continue;\n if (prop !== 'context' && !(prop in machine)) {\n machine[prop] = wrappedMachine[prop];\n }\n }\n\n // Also wrap the transition functions on the returned machine\n for (const prop in machine) {\n if (!Object.prototype.hasOwnProperty.call(machine, prop)) continue;\n const value = machine[prop];\n if (typeof value === 'function' && prop !== 'context' && wrappedMachine[prop]) {\n machine[prop] = wrappedMachine[prop];\n }\n }\n }\n return machine;\n };\n\n // Check if the transition is async (returns a Promise)\n if (nextMachine && typeof nextMachine.then === 'function') {\n // For async transitions, we need to handle the after hooks after the promise resolves\n const asyncResult = nextMachine.then((resolvedMachine: any) => {\n // Ensure middleware properties are attached\n ensureMiddlewareProperties(resolvedMachine);\n\n // Execute after hooks with the resolved machine\n if (hooks.after) {\n try {\n const result = hooks.after({\n transitionName,\n prevContext: context,\n nextContext: resolvedMachine.context,\n args: [...args]\n });\n\n // Handle async after hooks\n if (result && typeof result.then === 'function') {\n return result.then(() => resolvedMachine);\n }\n } catch (error) {\n if (!continueOnError) throw error;\n if (logErrors) console.error(`Middleware after hook error for ${transitionName}:`, error);\n onError?.(error as Error, 'after', {\n transitionName,\n prevContext: context,\n nextContext: resolvedMachine.context,\n args\n });\n }\n }\n return resolvedMachine;\n });\n\n return asyncResult;\n } else {\n // Ensure middleware properties are attached to synchronous transitions\n ensureMiddlewareProperties(nextMachine);\n\n // Synchronous transition\n // 4. Execute after hooks\n if (hooks.after) {\n try {\n const result = hooks.after({\n transitionName,\n prevContext: context,\n nextContext: nextMachine.context,\n args: [...args]\n });\n\n // Handle async after hooks\n if (result && typeof result === 'object' && result && 'then' in result) {\n return result.then(() => nextMachine).catch((error: Error) => {\n if (!continueOnError) throw error;\n if (logErrors) console.error(`Middleware after hook error for ${transitionName}:`, error);\n onError?.(error, 'after', {\n transitionName,\n prevContext: context,\n nextContext: nextMachine.context,\n args\n });\n return nextMachine;\n });\n }\n } catch (error) {\n if (!continueOnError) throw error;\n if (logErrors) console.error(`Middleware after hook error for ${transitionName}:`, error);\n onError?.(error as Error, 'after', {\n transitionName,\n prevContext: context,\n nextContext: nextMachine.context,\n args\n });\n }\n }\n\n // 5. Return the next machine state\n return nextMachine;\n }\n };\n\n // 1. Execute before hooks synchronously if possible\n if (hooks.before) {\n try {\n const result = hooks.before({\n transitionName,\n context,\n args: [...args]\n });\n\n // Handle async hooks\n if (result && typeof result === 'object' && result && 'then' in result) {\n // For async hooks, return a promise that executes the transition after\n return result.then((hookResult: any) => {\n if (hookResult === CANCEL) {\n return wrappedMachine;\n }\n return executeTransition();\n }).catch((error: Error) => {\n if (!continueOnError) throw error;\n if (logErrors) console.error(`Middleware before hook error for ${transitionName}:`, error);\n onError?.(error, 'before', { transitionName, context, args });\n return executeTransition();\n });\n }\n\n // Check if transition should be cancelled\n if (result === CANCEL) {\n return wrappedMachine; // Return the same machine instance\n }\n } catch (error) {\n if (!continueOnError) throw error;\n if (logErrors) console.error(`Middleware before hook error for ${transitionName}:`, error);\n onError?.(error as Error, 'before', { transitionName, context, args });\n }\n };\n\n return executeTransition();\n };\n }\n }\n\n return wrappedMachine;\n}\n\n/**\n * Creates a simple logging middleware that logs all transitions.\n *\n * @template M - The machine type\n * @param machine - The machine to add logging to\n * @param options - Logging configuration options\n * @returns A new machine with logging middleware\n */\nexport function withLogging<M extends BaseMachine<any>>(\n machine: M,\n options: {\n logger?: (message: string) => void;\n includeArgs?: boolean;\n includeContext?: boolean;\n } = {}\n): M {\n const { logger = console.log, includeArgs = false, includeContext = true } = options;\n\n return createMiddleware(machine, {\n before: ({ transitionName, args }) => {\n const message = includeArgs ? `→ ${transitionName} [${args.join(', ')}]` : `→ ${transitionName}`;\n logger(message);\n },\n after: ({ transitionName, nextContext }) => {\n const contextStr = includeContext ? ` ${JSON.stringify(nextContext)}` : '';\n logger(`✓ ${transitionName}${contextStr}`);\n },\n error: ({ transitionName, error }) => {\n console.error(`[Machine] ${transitionName} failed:`, error);\n }\n });\n}\n\n/**\n * Creates analytics tracking middleware.\n *\n * @template M - The machine type\n * @param machine - The machine to track\n * @param track - Analytics tracking function\n * @param options - Configuration options\n * @returns A new machine with analytics tracking\n */\nexport function withAnalytics<M extends BaseMachine<any>>(\n machine: M,\n track: (event: string, data?: any) => void,\n options: {\n eventPrefix?: string;\n includePrevContext?: boolean;\n includeArgs?: boolean;\n } = {}\n): M {\n const { eventPrefix = 'state_transition', includePrevContext = false, includeArgs = false } = options;\n\n return createMiddleware(machine, {\n after: ({ transitionName, prevContext, nextContext, args }) => {\n const event = `${eventPrefix}.${transitionName}`;\n const data: any = { transition: transitionName };\n if (includePrevContext) data.from = prevContext;\n data.to = nextContext;\n if (includeArgs) data.args = args;\n track(event, data);\n }\n });\n}\n\n/**\n * Creates validation middleware that runs before transitions.\n *\n * @template M - The machine type\n * @param machine - The machine to validate\n * @param validator - Validation function\n * @returns A new machine with validation\n */\nexport function withValidation<M extends BaseMachine<any>>(\n machine: M,\n validator: (ctx: MiddlewareContext<Context<M>>) => boolean | void\n): M {\n return createMiddleware(machine, {\n before: (ctx) => {\n const result = validator(ctx);\n if (result === false) {\n throw new Error(`Validation failed for transition: ${ctx.transitionName}`);\n }\n }\n });\n}\n\n/**\n * Creates permission-checking middleware.\n *\n * @template M - The machine type\n * @param machine - The machine to protect\n * @param checker - Permission checking function\n * @returns A new machine with permission checks\n */\nexport function withPermissions<M extends BaseMachine<any>>(\n machine: M,\n checker: (ctx: MiddlewareContext<Context<M>>) => boolean\n): M {\n return createMiddleware(machine, {\n before: (ctx) => {\n if (!checker(ctx)) {\n throw new Error(`Unauthorized transition: ${ctx.transitionName}`);\n }\n }\n });\n}\n\n/**\n * Creates error reporting middleware.\n *\n * @template M - The machine type\n * @param machine - The machine to monitor\n * @param reporter - Error reporting function\n * @param options - Configuration options\n * @returns A new machine with error reporting\n */\nexport function withErrorReporting<M extends BaseMachine<any>>(\n machine: M,\n reporter: (error: Error, ctx: any) => void,\n options: { includeArgs?: boolean } = {}\n): M {\n const { includeArgs = false } = options;\n\n return createMiddleware(machine, {\n error: (errorCtx) => {\n // Format the context to match test expectations\n const formattedCtx = {\n transition: errorCtx.transitionName,\n context: errorCtx.context,\n ...(includeArgs && { args: errorCtx.args })\n };\n reporter(errorCtx.error, formattedCtx);\n }\n });\n}\n\n/**\n * Creates performance monitoring middleware.\n *\n * @template M - The machine type\n * @param machine - The machine to monitor\n * @param tracker - Performance tracking function\n * @returns A new machine with performance monitoring\n */\nexport function withPerformanceMonitoring<M extends BaseMachine<any>>(\n machine: M,\n tracker: (metric: { transitionName: string; duration: number; context: Context<M> }) => void\n): M {\n const startTimes = new Map<string, number>();\n\n return createMiddleware(machine, {\n before: (ctx) => {\n startTimes.set(ctx.transitionName, Date.now());\n },\n after: (result) => {\n const startTime = startTimes.get(result.transitionName);\n if (startTime) {\n const duration = Date.now() - startTime;\n startTimes.delete(result.transitionName);\n // For test compatibility, pass a single object as expected\n const testResult = {\n transitionName: result.transitionName,\n duration,\n context: result.nextContext || result.prevContext\n };\n tracker(testResult);\n }\n }\n });\n}\n\n/**\n * Creates retry middleware for failed transitions.\n *\n * @template M - The machine type\n * @param machine - The machine to add retry logic to\n * @param options - Retry configuration\n * @returns A new machine with retry logic\n */\nexport function withRetry<M extends BaseMachine<any>>(\n machine: M,\n options: {\n maxAttempts?: number;\n maxRetries?: number; // alias for maxAttempts\n shouldRetry?: (error: Error, attempt: number) => boolean;\n backoffMs?: number | ((attempt: number) => number);\n delay?: number | ((attempt: number) => number); // alias for backoffMs\n backoffMultiplier?: number; // multiplier for exponential backoff\n onRetry?: (error: Error, attempt: number) => void;\n } = {}\n): M {\n const {\n maxAttempts = options.maxRetries ?? 3,\n shouldRetry = () => true,\n backoffMs = options.delay ?? 100,\n backoffMultiplier = 2,\n onRetry\n } = options;\n\n // Create a wrapped machine that adds retry logic\n const wrappedMachine: any = { ...machine };\n\n // Wrap each transition function with retry logic\n for (const prop in machine) {\n if (!Object.prototype.hasOwnProperty.call(machine, prop)) continue;\n const value = machine[prop];\n if (typeof value === 'function' && prop !== 'context') {\n wrappedMachine[prop] = async function (this: any, ...args: any[]) {\n let lastError: Error;\n let attempt = 0;\n\n while (attempt < maxAttempts) {\n try {\n return await value.apply(this, args);\n } catch (error) {\n lastError = error as Error;\n attempt++;\n\n if (attempt < maxAttempts && shouldRetry(lastError, attempt)) {\n onRetry?.(lastError, attempt);\n const baseDelay = typeof backoffMs === 'function' ? backoffMs(attempt) : backoffMs;\n const delay = baseDelay * Math.pow(backoffMultiplier, attempt - 1);\n await new Promise(resolve => setTimeout(resolve, delay));\n } else {\n throw lastError;\n }\n }\n }\n\n throw lastError!;\n };\n\n\n\n }\n }\n\n return wrappedMachine;\n}\n\n/**\n * Creates custom middleware from hooks.\n *\n * @template M - The machine type\n * @param hooks - Middleware hooks\n * @param options - Middleware options\n * @returns A middleware function\n */\nexport function createCustomMiddleware<M extends BaseMachine<any>>(\n hooks: MiddlewareHooks<Context<M>>,\n options?: MiddlewareOptions\n): (machine: M) => M {\n return (machine: M) => createMiddleware(machine, hooks, options);\n}", "/**\n * @file History tracking middleware\n */\n\nimport type { BaseMachine } from '../index';\nimport { createMiddleware } from './core';\n\n// =============================================================================\n// SECTION: HISTORY TYPES\n// =============================================================================\n\n/**\n * A single history entry recording a transition.\n */\nexport interface HistoryEntry {\n /** Unique ID for this history entry */\n id: string;\n /** Name of the transition that was called */\n transitionName: string;\n /** Arguments passed to the transition */\n args: any[];\n /** Timestamp when the transition occurred */\n timestamp: number;\n /** Optional serialized version of args for persistence */\n serializedArgs?: string;\n}\n\n/**\n * Serializer interface for converting context/args to/from strings.\n */\nexport interface Serializer<T = any> {\n serialize: (value: T) => string;\n deserialize: (str: string) => T;\n}\n\n// =============================================================================\n// SECTION: HISTORY MIDDLEWARE\n// =============================================================================\n\n/**\n * Creates a machine with history tracking capabilities.\n * Records all transitions that occur, allowing you to see the sequence of state changes.\n *\n * @template M - The machine type\n * @param machine - The machine to track\n * @param options - Configuration options\n * @returns A new machine with history tracking\n *\n * @example\n * ```typescript\n * const tracked = withHistory(counter, { maxSize: 50 });\n * tracked.increment();\n * console.log(tracked.history); // [{ id: \"entry-1\", transitionName: \"increment\", ... }]\n * ```\n */\nexport function withHistory<M extends BaseMachine<any>>(\n machine: M,\n options: {\n /** Maximum number of history entries to keep (default: unlimited) */\n maxSize?: number;\n /** Optional serializer for transition arguments */\n serializer?: Serializer<any[]>;\n /** Callback when a transition occurs */\n onEntry?: (entry: HistoryEntry) => void;\n } = {}\n): M & { history: HistoryEntry[]; clearHistory: () => void } {\n const { maxSize, serializer, onEntry } = options;\n const history: HistoryEntry[] = [];\n let entryId = 0;\n\n const instrumentedMachine = createMiddleware(machine, {\n before: ({ transitionName, args }) => {\n const entry: HistoryEntry = {\n id: `entry-${entryId++}`,\n transitionName,\n args: [...args],\n timestamp: Date.now()\n };\n\n if (serializer) {\n try {\n entry.serializedArgs = serializer.serialize(args);\n } catch (err) {\n console.error('Failed to serialize history args:', err);\n }\n }\n\n history.push(entry);\n\n // Enforce max size\n if (maxSize && history.length > maxSize) {\n history.shift();\n }\n\n onEntry?.(entry);\n }\n });\n\n // Attach history properties to the machine\n return Object.assign(instrumentedMachine, {\n history,\n clearHistory: () => { history.length = 0; entryId = 0; }\n });\n}", "/**\n * @file Snapshot tracking middleware for context state\n */\n\nimport type { Context, BaseMachine } from '../index';\nimport { createMiddleware } from './core';\nimport type { Serializer } from './history';\n\n// =============================================================================\n// SECTION: SNAPSHOT TYPES\n// =============================================================================\n\n/**\n * A snapshot of machine context before and after a transition.\n */\nexport interface ContextSnapshot<C extends object> {\n /** Unique ID for this snapshot */\n id: string;\n /** Name of the transition that caused this snapshot */\n transitionName: string;\n /** Context before the transition */\n before: C;\n /** Context after the transition */\n after: C;\n /** Timestamp of the snapshot */\n timestamp: number;\n /** Optional serialized versions of contexts */\n serializedBefore?: string;\n serializedAfter?: string;\n /** Optional diff information */\n diff?: any;\n}\n\n// =============================================================================\n// SECTION: SNAPSHOT MIDDLEWARE\n// =============================================================================\n\n/**\n * Creates a machine with snapshot tracking capabilities.\n * Records context state before and after each transition for debugging and inspection.\n *\n * @template M - The machine type\n * @param machine - The machine to track\n * @param options - Configuration options\n * @returns A new machine with snapshot tracking\n *\n * @example\n * ```typescript\n * const tracked = withSnapshot(counter, {\n * maxSize: 50,\n * serializer: {\n * serialize: (ctx) => JSON.stringify(ctx),\n * deserialize: (str) => JSON.parse(str)\n * }\n * });\n *\n * tracked.increment();\n * console.log(tracked.snapshots); // [{ before: { count: 0 }, after: { count: 1 }, ... }]\n * ```\n */\nexport function withSnapshot<M extends BaseMachine<any>>(\n machine: M,\n options: {\n /** Maximum number of snapshots to keep (default: unlimited) */\n maxSize?: number;\n /** Optional serializer for context */\n serializer?: Serializer<Context<M>>;\n /** Custom function to capture additional snapshot data */\n captureSnapshot?: (before: Context<M>, after: Context<M>) => any;\n /** Only capture snapshots where context actually changed */\n onlyOnChange?: boolean;\n } = {}\n): M & {\n snapshots: ContextSnapshot<Context<M>>[];\n clearSnapshots: () => void;\n restoreSnapshot: (snapshot: ContextSnapshot<Context<M>>['before']) => M;\n} {\n const {\n maxSize,\n serializer,\n captureSnapshot,\n onlyOnChange = false\n } = options;\n\n const snapshots: ContextSnapshot<Context<M>>[] = [];\n let snapshotId = 0;\n\n const instrumentedMachine = createMiddleware(machine, {\n after: ({ transitionName, prevContext, nextContext }) => {\n // Skip if only capturing on change and context didn't change\n if (onlyOnChange && JSON.stringify(prevContext) === JSON.stringify(nextContext)) {\n return;\n }\n\n const snapshot: ContextSnapshot<Context<M>> = {\n id: `snapshot-${snapshotId++}`,\n transitionName,\n before: { ...prevContext },\n after: { ...nextContext },\n timestamp: Date.now()\n };\n\n // Serialize contexts if serializer provided\n if (serializer) {\n try {\n snapshot.serializedBefore = serializer.serialize(prevContext);\n snapshot.serializedAfter = serializer.serialize(nextContext);\n } catch (err) {\n console.error('Failed to serialize snapshot:', err);\n }\n }\n\n // Capture custom snapshot data\n if (captureSnapshot) {\n try {\n snapshot.diff = captureSnapshot(prevContext, nextContext);\n } catch (err) {\n console.error('Failed to capture snapshot:', err);\n }\n }\n\n snapshots.push(snapshot);\n\n // Enforce max size\n if (maxSize && snapshots.length > maxSize) {\n snapshots.shift();\n }\n }\n });\n\n // Helper to restore machine to a previous state\n const restoreSnapshot = (context: Context<M>): M => {\n // Find the machine's transition functions (excluding context and snapshot properties)\n const transitions = Object.fromEntries(\n Object.entries(machine).filter(([key]) =>\n key !== 'context' &&\n key !== 'snapshots' &&\n key !== 'clearSnapshots' &&\n key !== 'restoreSnapshot' &&\n typeof machine[key as keyof M] === 'function'\n )\n );\n\n return Object.assign({ context }, transitions) as M;\n };\n\n // Attach snapshot properties to the machine\n return Object.assign(instrumentedMachine, {\n snapshots,\n clearSnapshots: () => { snapshots.length = 0; snapshotId = 0; },\n restoreSnapshot\n });\n}", "/**\n * @file Time travel middleware combining history, snapshots, and replay capabilities\n */\n\nimport type { Context, BaseMachine } from '../index';\nimport { createMiddleware } from './core';\nimport { type HistoryEntry, type Serializer } from './history';\nimport { type ContextSnapshot } from './snapshot';\n\n// =============================================================================\n// SECTION: TIME TRAVEL TYPES\n// =============================================================================\n\n/**\n * A machine enhanced with history tracking capabilities.\n */\nexport type WithHistory<M extends BaseMachine<any>> = M & {\n /** History of all transitions */\n history: HistoryEntry[];\n /** Clear all history */\n clearHistory: () => void;\n};\n\n/**\n * A machine enhanced with snapshot tracking capabilities.\n */\nexport type WithSnapshot<M extends BaseMachine<any>> = M & {\n /** Snapshots of context before/after each transition */\n snapshots: ContextSnapshot<Context<M>>[];\n /** Clear all snapshots */\n clearSnapshots: () => void;\n /** Restore machine to a previous context state */\n restoreSnapshot: (context: Context<M>) => M;\n};\n\n/**\n * A machine enhanced with time travel capabilities.\n */\nexport type WithTimeTravel<M extends BaseMachine<any>> = M & {\n /** History of all transitions */\n history: HistoryEntry[];\n /** Snapshots of context before/after each transition */\n snapshots: ContextSnapshot<Context<M>>[];\n /** Clear all history and snapshots */\n clearTimeTravel: () => void;\n /** Clear just the history */\n clearHistory: () => void;\n /** Clear just the snapshots */\n clearSnapshots: () => void;\n /** Restore machine to a previous context state */\n restoreSnapshot: (context: Context<M>) => M;\n /** Replay transitions from a specific point in history */\n replayFrom: (startIndex: number) => M;\n};\n\n// =============================================================================\n// SECTION: TIME TRAVEL MIDDLEWARE\n// =============================================================================\n\n/**\n * Creates a machine with full time travel debugging capabilities.\n * Combines history tracking, snapshots, and replay functionality.\n *\n * @template M - The machine type\n * @param machine - The machine to enhance\n * @param options - Configuration options\n * @returns A machine with time travel capabilities\n *\n * @example\n * ```typescript\n * const debugMachine = withTimeTravel(counter);\n *\n * // Make some transitions\n * debugMachine.increment();\n * debugMachine.increment();\n * debugMachine.decrement();\n *\n * // Time travel to previous states\n * const previousState = debugMachine.replayFrom(0); // Replay from start\n * const undoLast = debugMachine.restoreSnapshot(debugMachine.snapshots[1].before);\n *\n * // Inspect history\n * console.log(debugMachine.history);\n * console.log(debugMachine.snapshots);\n * ```\n */\nexport function withTimeTravel<M extends BaseMachine<any>>(\n machine: M,\n options: {\n /** Maximum number of history entries/snapshots to keep */\n maxSize?: number;\n /** Optional serializer for persistence */\n serializer?: Serializer;\n /** Callback when history/snapshot events occur */\n onRecord?: (type: 'history' | 'snapshot', data: any) => void;\n } = {}\n): WithTimeTravel<M> {\n const { maxSize, serializer, onRecord } = options;\n\n // Create separate history and snapshot tracking\n const history: HistoryEntry[] = [];\n const snapshots: ContextSnapshot<Context<M>>[] = [];\n let historyId = 0;\n let snapshotId = 0;\n\n // Create middleware that handles both history and snapshots\n const instrumentedMachine = createMiddleware(machine, {\n before: ({ transitionName, args }: { transitionName: string; args: any[] }) => {\n const entry: HistoryEntry = {\n id: `entry-${historyId++}`,\n transitionName,\n args: [...args],\n timestamp: Date.now()\n };\n\n if (serializer) {\n try {\n entry.serializedArgs = serializer.serialize(args);\n } catch (err) {\n console.error('Failed to serialize history args:', err);\n }\n }\n\n history.push(entry);\n\n // Enforce max size\n if (maxSize && history.length > maxSize) {\n history.shift();\n }\n\n onRecord?.('history', entry);\n },\n after: ({ transitionName, prevContext, nextContext }: { transitionName: string; prevContext: Context<M>; nextContext: Context<M> }) => {\n const snapshot: ContextSnapshot<Context<M>> = {\n id: `snapshot-${snapshotId++}`,\n transitionName,\n before: { ...prevContext },\n after: { ...nextContext },\n timestamp: Date.now()\n };\n\n // Serialize contexts if serializer provided\n if (serializer) {\n try {\n snapshot.serializedBefore = serializer.serialize(prevContext);\n snapshot.serializedAfter = serializer.serialize(nextContext);\n } catch (err) {\n console.error('Failed to serialize snapshot:', err);\n }\n }\n\n snapshots.push(snapshot);\n\n // Enforce max size\n if (maxSize && snapshots.length > maxSize) {\n snapshots.shift();\n }\n\n onRecord?.('snapshot', snapshot);\n }\n });\n\n // Helper to restore machine to a previous state\n const restoreSnapshot = (context: Context<M>): M => {\n // Find the machine's transition functions (excluding context and snapshot properties)\n const transitions = Object.fromEntries(\n Object.entries(machine).filter(([key]) =>\n key !== 'context' &&\n key !== 'history' &&\n key !== 'snapshots' &&\n key !== 'clearHistory' &&\n key !== 'clearSnapshots' &&\n key !== 'restoreSnapshot' &&\n key !== 'clearTimeTravel' &&\n key !== 'replayFrom' &&\n typeof machine[key as keyof M] === 'function'\n )\n );\n\n return Object.assign({ context }, transitions) as M;\n };\n\n // Create replay functionality\n const replayFrom = (startIndex: number): M => {\n if (startIndex < 0 || startIndex >= history.length) {\n throw new Error(`Invalid replay start index: ${startIndex}`);\n }\n\n // Start from the context at the specified history index\n let currentContext = snapshots[startIndex]?.before;\n if (!currentContext) {\n throw new Error(`No snapshot available for index ${startIndex}`);\n }\n\n // Get all transitions from start index to end\n const transitionsToReplay = history.slice(startIndex);\n\n // Create a fresh machine instance\n const freshMachine = Object.assign(\n { context: currentContext },\n Object.fromEntries(\n Object.entries(machine).filter(([key]) =>\n key !== 'context' &&\n typeof machine[key as keyof M] === 'function'\n )\n )\n ) as M;\n\n // Replay each transition\n let replayedMachine = freshMachine;\n for (const entry of transitionsToReplay) {\n const transitionFn = replayedMachine[entry.transitionName as keyof M] as Function;\n if (transitionFn) {\n replayedMachine = transitionFn.apply(replayedMachine.context, entry.args);\n }\n }\n\n return replayedMachine;\n };\n\n // Return machine with all time travel capabilities\n return Object.assign(instrumentedMachine, {\n history,\n snapshots,\n clearHistory: () => { history.length = 0; historyId = 0; },\n clearSnapshots: () => { snapshots.length = 0; snapshotId = 0; },\n clearTimeTravel: () => {\n history.length = 0;\n snapshots.length = 0;\n historyId = 0;\n snapshotId = 0;\n },\n restoreSnapshot,\n replayFrom\n }) as WithTimeTravel<M>;\n}", "/**\n * @file Middleware composition and pipeline utilities\n */\n\nimport type { BaseMachine, Context } from '../index';\nimport type {\n MiddlewareContext,\n MiddlewareResult,\n MiddlewareError,\n MiddlewareHooks,\n MiddlewareOptions\n} from './core';\nimport {\n withLogging,\n withAnalytics,\n withValidation,\n withPermissions,\n withErrorReporting,\n withPerformanceMonitoring,\n withRetry\n} from './core';\nimport { withHistory, type HistoryEntry, type Serializer } from './history';\nimport { withSnapshot } from './snapshot';\nimport { withTimeTravel, type WithTimeTravel, type WithHistory, type WithSnapshot } from './time-travel';\n\n// =============================================================================\n// SECTION: COMPOSITION TYPES\n// =============================================================================\n\n/**\n * A middleware function that transforms a machine.\n * @template M - The input machine type\n * @template R - The output machine type (usually extends M)\n */\nexport type MiddlewareFn<M extends BaseMachine<any>, R extends BaseMachine<any> = M> = (machine: M) => R;\n\n/**\n * A conditional middleware that may or may not be applied based on a predicate.\n * @template M - The machine type\n */\nexport type ConditionalMiddleware<M extends BaseMachine<any>> = {\n /** The middleware function to apply */\n middleware: MiddlewareFn<M>;\n /** Predicate function that determines if the middleware should be applied */\n when: (machine: M) => boolean;\n};\n\n/**\n * A named middleware entry for registry-based composition.\n * @template M - The machine type\n */\nexport type NamedMiddleware<M extends BaseMachine<any>> = {\n /** Unique name for the middleware */\n name: string;\n /** The middleware function */\n middleware: MiddlewareFn<M>;\n /** Optional description */\n description?: string;\n /** Optional priority for ordering (higher numbers = applied later) */\n priority?: number;\n};\n\n/**\n * Configuration for middleware pipeline execution.\n */\nexport interface PipelineConfig {\n /** Whether to continue execution if a middleware throws an error */\n continueOnError?: boolean;\n /** Whether to log errors from middlewares */\n logErrors?: boolean;\n /** Custom error handler */\n onError?: (error: Error, middlewareIndex: number, middlewareName?: string) => void;\n}\n\n/**\n * Result of pipeline execution.\n */\nexport type PipelineResult<M extends BaseMachine<any>> = M;\n\n// =============================================================================\n// SECTION: TYPE-LEVEL COMPOSITION\n// =============================================================================\n\n/**\n * Type-level utility for composing middleware return types.\n * This enables perfect TypeScript inference when chaining middlewares.\n */\nexport type ComposeResult<\n M extends BaseMachine<any>,\n Ms extends readonly MiddlewareFn<any, any>[]\n> = Ms extends readonly [infer First, ...infer Rest]\n ? First extends MiddlewareFn<any, infer R>\n ? Rest extends readonly MiddlewareFn<any, any>[]\n ? ComposeResult<R, Rest>\n : R\n : M\n : M;\n\n// =============================================================================\n// SECTION: COMPOSITION FUNCTIONS\n// =============================================================================\n\n/**\n * Compose multiple middleware functions into a single middleware stack.\n * Middleware is applied left-to-right (first middleware wraps outermost).\n *\n * @template M - The machine type\n * @param machine - The base machine\n * @param middlewares - Array of middleware functions\n * @returns A new machine with all middleware applied\n */\nexport function compose<M extends BaseMachine<any>>(\n machine: M,\n ...middlewares: Array<(m: M) => M>\n): M {\n return middlewares.reduce((acc, middleware) => middleware(acc), machine);\n}\n\n/**\n * Type-safe middleware composition with perfect inference.\n * Composes multiple middlewares into a single transformation chain.\n *\n * @template M - The input machine type\n * @template Ms - Array of middleware functions\n * @param machine - The machine to enhance\n * @param middlewares - Middleware functions to apply in order\n * @returns The machine with all middlewares applied, with precise type inference\n */\nexport function composeTyped<\n M extends BaseMachine<any>,\n Ms extends readonly MiddlewareFn<any, any>[]\n>(\n machine: M,\n ...middlewares: Ms\n): ComposeResult<M, Ms> {\n return middlewares.reduce((acc, middleware) => middleware(acc), machine) as ComposeResult<M, Ms>;\n}\n\n// =============================================================================\n// SECTION: FLUENT API\n// =============================================================================\n\n/**\n * Fluent middleware composer for building complex middleware chains.\n * Provides excellent TypeScript inference and IntelliSense.\n */\nclass MiddlewareChainBuilder<M extends BaseMachine<any>> {\n constructor(private machine: M) {}\n\n /**\n * Add a middleware to the composition chain.\n * @param middleware - The middleware function to add\n * @returns A new composer with the middleware applied\n */\n with<M2 extends MiddlewareFn<any, any>>(\n middleware: M2\n ): MiddlewareChainBuilder<ReturnType<M2> extends BaseMachine<any> ? ReturnType<M2> : M> {\n const result = middleware(this.machine);\n return new MiddlewareChainBuilder(result as any);\n }\n\n /**\n * Build the final machine with all middlewares applied.\n */\n build(): M {\n return this.machine;\n }\n}\n\n/**\n * Create a fluent middleware chain builder.\n *\n * @example\n * ```typescript\n * const enhanced = chain(counter)\n * .with(withHistory())\n * .with(withSnapshot())\n * .with(withTimeTravel())\n * .build();\n * ```\n */\nexport function chain<M extends BaseMachine<any>>(machine: M) {\n return new MiddlewareChainBuilder(machine);\n}\n\n// =============================================================================\n// SECTION: CONDITIONAL MIDDLEWARE\n// =============================================================================\n\n/**\n * Create a conditional middleware that only applies when a predicate is true.\n *\n * @template M - The machine type\n * @param middleware - The middleware to conditionally apply\n * @param predicate - Function that determines when to apply the middleware\n * @returns A conditional middleware that can be called directly or used in pipelines\n */\nexport function when<M extends BaseMachine<any>>(\n middleware: MiddlewareFn<M>,\n predicate: (machine: M) => boolean\n): ConditionalMiddleware<M> & MiddlewareFn<M> {\n const conditional: ConditionalMiddleware<M> & MiddlewareFn<M> = function(machine: M) {\n return predicate(machine) ? middleware(machine) : machine;\n };\n\n conditional.middleware = middleware;\n conditional.when = predicate;\n\n return conditional;\n}\n\n/**\n * Create a middleware that only applies in development mode.\n *\n * @template M - The machine type\n * @param middleware - The middleware to apply in development\n * @returns A conditional middleware for development mode\n */\nexport function inDevelopment<M extends BaseMachine<any>>(\n middleware: MiddlewareFn<M>\n): ConditionalMiddleware<M> & MiddlewareFn<M> {\n return when(middleware, () => {\n return typeof process !== 'undefined'\n ? process.env.NODE_ENV === 'development'\n : typeof window !== 'undefined'\n ? !window.location.hostname.includes('production')\n : false;\n });\n}\n\n/**\n * Create a middleware that only applies when a context property matches a value.\n *\n * @template M - The machine type\n * @template K - The context key\n * @param key - The context property key\n * @param value - The value to match\n * @param middleware - The middleware to apply when the condition matches\n * @returns A conditional middleware\n */\nexport function whenContext<M extends BaseMachine<any>, K extends keyof Context<M>>(\n key: K,\n value: Context<M>[K],\n middleware: MiddlewareFn<M>\n): ConditionalMiddleware<M> & MiddlewareFn<M> {\n return when(middleware, (machine) => machine.context[key] === value);\n}\n\n// =============================================================================\n// SECTION: MIDDLEWARE REGISTRY\n// =============================================================================\n\n/**\n * Create a middleware registry for managing reusable middleware configurations.\n */\nexport function createMiddlewareRegistry<M extends BaseMachine<any>>() {\n const registry = new Map<string, NamedMiddleware<M>>();\n\n return {\n /**\n * Register a middleware by name.\n */\n register(\n name: string,\n middleware: MiddlewareFn<M>,\n description?: string,\n priority?: number\n ): typeof this {\n if (registry.has(name)) {\n throw new Error(`Middleware '${name}' is already registered`);\n }\n\n registry.set(name, { name, middleware, description, priority });\n return this;\n },\n\n /**\n * Unregister a middleware by name.\n */\n unregister(name: string): boolean {\n return registry.delete(name);\n },\n\n /**\n * Check if a middleware is registered.\n */\n has(name: string): boolean {\n return registry.has(name);\n },\n\n /**\n * Get a registered middleware by name.\n */\n get(name: string): NamedMiddleware<M> | undefined {\n return registry.get(name);\n },\n\n /**\n * List all registered middlewares.\n */\n list(): NamedMiddleware<M>[] {\n return Array.from(registry.values()).sort((a, b) => (a.priority ?? 0) - (b.priority ?? 0));\n },\n\n /**\n * Apply a selection of registered middlewares to a machine.\n * Middlewares are applied in priority order (lowest to highest).\n */\n apply(machine: M, middlewareNames: string[]): M {\n const middlewares = middlewareNames\n .map(name => {\n const entry = registry.get(name);\n if (!entry) {\n throw new Error(`Middleware '${name}' is not registered`);\n }\n return entry;\n })\n .sort((a, b) => (a.priority ?? 0) - (b.priority ?? 0));\n\n return composeTyped(machine, ...middlewares.map(m => m.middleware));\n },\n\n /**\n * Apply all registered middlewares to a machine in priority order.\n */\n applyAll(machine: M): M {\n const middlewares = this.list();\n return composeTyped(machine, ...middlewares.map(m => m.middleware));\n }\n };\n}\n\n// =============================================================================\n// SECTION: PIPELINES\n// =============================================================================\n\n/**\n * Create a middleware pipeline with error handling and conditional execution.\n *\n * @template M - The machine type\n * @param config - Pipeline configuration\n * @returns A function that executes middlewares in a pipeline\n */\nexport function createPipeline<M extends BaseMachine<any>>(\n config: PipelineConfig = {}\n): {\n <Ms extends Array<MiddlewareFn<M> | ConditionalMiddleware<M>>>(\n machine: M,\n ...middlewares: Ms\n ): { machine: M; errors: Array<{ error: Error; middlewareIndex: number; middlewareName?: string }>; success: boolean };\n} {\n const {\n continueOnError = false,\n logErrors = true,\n onError\n } = config;\n\n return (machine: M, ...middlewares: Array<MiddlewareFn<M> | ConditionalMiddleware<M>>) => {\n let currentMachine = machine;\n const errors: Array<{ error: Error; middlewareIndex: number; middlewareName?: string }> = [];\n let success = true;\n\n for (let i = 0; i < middlewares.length; i++) {\n const middleware = middlewares[i];\n\n try {\n // Handle conditional middleware\n if ('middleware' in middleware && 'when' in middleware) {\n if (!middleware.when(currentMachine)) {\n continue; // Skip this middleware\n }\n currentMachine = middleware.middleware(currentMachine);\n } else {\n // Regular middleware\n currentMachine = (middleware as MiddlewareFn<M>)(currentMachine);\n }\n } catch (error) {\n success = false;\n if (!continueOnError) {\n throw error;\n }\n\n errors.push({\n error: error as Error,\n middlewareIndex: i,\n middlewareName: (middleware as any).name\n });\n\n if (logErrors) {\n console.error(`Pipeline middleware error at index ${i}:`, error);\n }\n\n onError?.(error as Error, i, (middleware as any).name);\n }\n }\n\n return { machine: currentMachine, errors, success };\n };\n}\n\n// =============================================================================\n// SECTION: UTILITY FUNCTIONS\n// =============================================================================\n\n/**\n * Combine multiple middlewares with short-circuiting.\n */\nexport function combine<M extends BaseMachine<any>>(\n ...middlewares: Array<MiddlewareFn<M>>\n): MiddlewareFn<M> {\n return (machine: M) => composeTyped(machine, ...middlewares);\n}\n\n/**\n * Create a middleware that applies different middlewares based on context.\n */\nexport function branch<M extends BaseMachine<any>>(\n branches: Array<[predicate: (machine: M) => boolean, middleware: MiddlewareFn<M>]>,\n fallback?: MiddlewareFn<M>\n): MiddlewareFn<M> {\n return (machine: M) => {\n for (const [predicate, middleware] of branches) {\n if (predicate(machine)) {\n return middleware(machine);\n }\n }\n return fallback ? fallback(machine) : machine;\n };\n}\n\n// =============================================================================\n// SECTION: ENHANCED TYPE GUARDS\n// =============================================================================\n\n/**\n * Enhanced type guard to check if a value is a middleware function with better inference.\n */\nexport function isMiddlewareFn<M extends BaseMachine<any>, R extends BaseMachine<any> = M>(\n value: any\n): value is MiddlewareFn<M, R> {\n return typeof value === 'function' && value.length === 1;\n}\n\n/**\n * Enhanced type guard to check if a value is a conditional middleware with better inference.\n */\nexport function isConditionalMiddleware<M extends BaseMachine<any>>(\n value: any\n): value is ConditionalMiddleware<M> {\n return (\n value !== null &&\n (typeof value === 'object' || typeof value === 'function') &&\n 'middleware' in value &&\n 'when' in value &&\n isMiddlewareFn(value.middleware) &&\n typeof value.when === 'function'\n );\n}\n\n/**\n * Type guard to check if a value is a middleware result with strict type checking.\n */\nexport function isMiddlewareResult<C extends object>(\n value: any,\n contextType?: C\n): value is MiddlewareResult<C> {\n return (\n value !== null &&\n typeof value === 'object' &&\n 'transitionName' in value &&\n 'prevContext' in value &&\n 'nextContext' in value &&\n 'args' in value &&\n typeof value.transitionName === 'string' &&\n Array.isArray(value.args) &&\n (!contextType || (\n isValidContext(value.prevContext, contextType) &&\n isValidContext(value.nextContext, contextType)\n ))\n );\n}\n\n/**\n * Type guard to check if a value is middleware context with strict type checking.\n */\nexport function isMiddlewareContext<C extends object>(\n value: any,\n contextType?: C\n): value is MiddlewareContext<C> {\n return (\n value !== null &&\n typeof value === 'object' &&\n 'transitionName' in value &&\n 'context' in value &&\n 'args' in value &&\n typeof value.transitionName === 'string' &&\n Array.isArray(value.args) &&\n (!contextType || isValidContext(value.context, contextType))\n );\n}\n\n/**\n * Type guard to check if a value is middleware error with strict type checking.\n */\nexport function isMiddlewareError<C extends object>(\n value: any,\n contextType?: C\n): value is MiddlewareError<C> {\n return (\n value !== null &&\n typeof value === 'object' &&\n 'transitionName' in value &&\n 'context' in value &&\n 'args' in value &&\n 'error' in value &&\n typeof value.transitionName === 'string' &&\n Array.isArray(value.args) &&\n value.error instanceof Error &&\n (!contextType || isValidContext(value.context, contextType))\n );\n}\n\n/**\n * Type guard to check if a value is middleware hooks with strict type checking.\n */\nexport function isMiddlewareHooks<C extends object>(\n value: any,\n _contextType?: C\n): value is MiddlewareHooks<C> {\n if (value === null || typeof value !== 'object') return false;\n\n const hooks = value as Partial<MiddlewareHooks<C>>;\n\n // Check before hook\n if ('before' in hooks && hooks.before !== undefined) {\n if (typeof hooks.before !== 'function') return false;\n }\n\n // Check after hook\n if ('after' in hooks && hooks.after !== undefined) {\n if (typeof hooks.after !== 'function') return false;\n }\n\n // Check error hook\n if ('error' in hooks && hooks.error !== undefined) {\n if (typeof hooks.error !== 'function') return false;\n }\n\n return true;\n}\n\n/**\n * Type guard to check if a value is middleware options with strict type checking.\n */\nexport function isMiddlewareOptions(value: any): value is MiddlewareOptions {\n return (\n value === undefined ||\n (value !== null &&\n typeof value === 'object' &&\n ('continueOnError' in value ? typeof value.continueOnError === 'boolean' : true) &&\n ('logErrors' in value ? typeof value.logErrors === 'boolean' : true) &&\n ('onError' in value ? typeof value.onError === 'function' || value.onError === undefined : true))\n );\n}\n\n/**\n * Helper function to validate context objects.\n */\nfunction isValidContext<C extends object>(value: any, _contextType: C): value is C {\n return value !== null && typeof value === 'object';\n}\n\n/**\n * Type guard to check if a value is a named middleware with strict type checking.\n */\nexport function isNamedMiddleware<M extends BaseMachine<any>>(\n value: any\n): value is NamedMiddleware<M> {\n return (\n value !== null &&\n typeof value === 'object' &&\n 'name' in value &&\n 'middleware' in value &&\n typeof value.name === 'string' &&\n isMiddlewareFn(value.middleware) &&\n ('description' in value ? typeof value.description === 'string' || value.description === undefined : true) &&\n ('priority' in value ? typeof value.priority === 'number' || value.priority === undefined : true)\n );\n}\n\n/**\n * Type guard to check if a value is pipeline config with strict type checking.\n */\nexport function isPipelineConfig(value: any): value is PipelineConfig {\n return (\n value === undefined ||\n (value !== null &&\n typeof value === 'object' &&\n ('continueOnError' in value ? typeof value.continueOnError === 'boolean' : true) &&\n ('logErrors' in value ? typeof value.logErrors === 'boolean' : true) &&\n ('onError' in value ? typeof value.onError === 'function' || value.onError === undefined : true))\n );\n}\n\n// =============================================================================\n// SECTION: GENERIC MIDDLEWARE BUILDER\n// =============================================================================\n\n/**\n * Configuration for logging middleware.\n */\nexport interface LoggingOptions {\n logger?: (message: string) => void;\n includeArgs?: boolean;\n includeContext?: boolean;\n logLevel?: 'debug' | 'info' | 'warn' | 'error';\n}\n\n/**\n * Configuration for analytics middleware.\n */\nexport interface AnalyticsOptions {\n eventPrefix?: string;\n includePrevContext?: boolean;\n includeArgs?: boolean;\n includeTiming?: boolean;\n}\n\n/**\n * Configuration for validation middleware.\n */\nexport interface ValidationOptions {\n throwOnFailure?: boolean;\n logFailures?: boolean;\n}\n\n/**\n * Configuration for error reporting middleware.\n */\nexport interface ErrorReportingOptions {\n includeArgs?: boolean;\n includeStackTrace?: boolean;\n reportTo?: string[];\n}\n\n/**\n * Configuration for performance monitoring middleware.\n */\nexport interface PerformanceOptions {\n includeArgs?: boolean;\n includeContext?: boolean;\n warnThreshold?: number;\n}\n\n/**\n * Configuration for retry middleware.\n */\nexport interface RetryOptions {\n maxAttempts?: number;\n maxRetries?: number;\n shouldRetry?: (error: Error, attempt: number) => boolean;\n backoffMs?: number | ((attempt: number) => number);\n delay?: number | ((attempt: number) => number);\n backoffMultiplier?: number;\n onRetry?: (error: Error, attempt: number) => void;\n}\n\n/**\n * Configuration for history middleware.\n */\nexport interface HistoryOptions {\n maxSize?: number;\n serializer?: Serializer<any[]>;\n onEntry?: (entry: HistoryEntry) => void;\n includeTimestamps?: boolean;\n}\n\n/**\n * Configuration for snapshot middleware.\n */\nexport interface SnapshotOptions {\n maxSize?: number;\n serializer?: Serializer<Context<any>>;\n captureSnapshot?: (before: Context<any>, after: Context<any>) => any;\n onlyOnChange?: boolean;\n includeDiff?: boolean;\n}\n\n/**\n * Configuration for time travel middleware.\n */\nexport interface TimeTravelOptions {\n maxSize?: number;\n serializer?: Serializer;\n onRecord?: (type: 'history' | 'snapshot', data: any) => void;\n enableReplay?: boolean;\n}\n\n/**\n * Generic middleware builder with perfect TypeScript inference.\n * Provides a fluent API for configuring and applying middleware.\n */\nexport class MiddlewareBuilder<M extends BaseMachine<any>> {\n private middlewares: Array<(machine: any) => any> = [];\n\n constructor(private machine: M) {}\n\n /**\n * Add logging middleware with type-safe configuration.\n */\n withLogging(options?: LoggingOptions): MiddlewareBuilder<M> {\n this.middlewares.push((machine: M) => withLogging(machine, options));\n return this;\n }\n\n /**\n * Add analytics middleware with type-safe configuration.\n */\n withAnalytics(\n track: (event: string, data?: any) => void,\n options?: AnalyticsOptions\n ): MiddlewareBuilder<M> {\n this.middlewares.push((machine: M) => withAnalytics(machine, track, options));\n return this;\n }\n\n /**\n * Add validation middleware with type-safe configuration.\n */\n withValidation(\n validator: (ctx: MiddlewareContext<Context<M>>) => boolean | void,\n _options?: ValidationOptions\n ): MiddlewareBuilder<M> {\n this.middlewares.push((machine: M) => withValidation(machine, validator));\n return this;\n }\n\n /**\n * Add permission checking middleware with type-safe configuration.\n */\n withPermissions(\n checker: (ctx: MiddlewareContext<Context<M>>) => boolean\n ): MiddlewareBuilder<M> {\n this.middlewares.push((machine: M) => withPermissions(machine, checker));\n return this;\n }\n\n /**\n * Add error reporting middleware with type-safe configuration.\n */\n withErrorReporting(\n reporter: (error: Error, ctx: MiddlewareError<Context<M>>) => void,\n options?: ErrorReportingOptions\n ): MiddlewareBuilder<M> {\n this.middlewares.push((machine: M) => withErrorReporting(machine, reporter, options));\n return this;\n }\n\n /**\n * Add performance monitoring middleware with type-safe configuration.\n */\n withPerformanceMonitoring(\n tracker: (metric: { transitionName: string; duration: number; context: Context<M> }) => void,\n _options?: PerformanceOptions\n ): MiddlewareBuilder<M> {\n this.middlewares.push((machine: M) => withPerformanceMonitoring(machine, tracker));\n return this;\n }\n\n /**\n * Add retry middleware with type-safe configuration.\n */\n withRetry(options?: RetryOptions): MiddlewareBuilder<M> {\n this.middlewares.push((machine: M) => withRetry(machine, options));\n return this;\n }\n\n /**\n * Add history tracking middleware with type-safe configuration.\n */\n withHistory(options?: HistoryOptions): MiddlewareBuilder<WithHistory<M>> {\n this.middlewares.push((machine: M) => withHistory(machine, options));\n return this as unknown as MiddlewareBuilder<WithHistory<M>>;\n }\n\n /**\n * Add snapshot tracking middleware with type-safe configuration.\n */\n withSnapshot(options?: SnapshotOptions): MiddlewareBuilder<WithSnapshot<M>> {\n this.middlewares.push((machine: M) => withSnapshot(machine, options));\n return this as unknown as MiddlewareBuilder<WithSnapshot<M>>;\n }\n\n /**\n * Add time travel middleware with type-safe configuration.\n */\n withTimeTravel(options?: TimeTravelOptions): MiddlewareBuilder<WithTimeTravel<M>> {\n this.middlewares.push((machine: M) => withTimeTravel(machine, options));\n return this as unknown as MiddlewareBuilder<WithTimeTravel<M>>;\n }\n\n /**\n * Add debugging middleware (combination of history, snapshot, and time travel).\n */\n withDebugging(): MiddlewareBuilder<WithDebugging<M>> {\n this.middlewares.push((machine: M) => withDebugging(machine));\n return this as unknown as MiddlewareBuilder<WithDebugging<M>>;\n }\n\n /**\n * Add a custom middleware function.\n */\n withCustom<R extends BaseMachine<any> = M>(\n middleware: MiddlewareFn<M, R>\n ): MiddlewareBuilder<R> {\n this.middlewares.push(middleware);\n return this as unknown as MiddlewareBuilder<R>;\n }\n\n /**\n * Add a conditional middleware.\n */\n withConditional(\n middleware: MiddlewareFn<M>,\n predicate: (machine: M) => boolean\n ): MiddlewareBuilder<M> {\n this.middlewares.push(when(middleware, predicate));\n return this;\n }\n\n /**\n * Build the final machine with all configured middleware applied.\n */\n build(): M {\n let result = this.machine;\n for (const middleware of this.middlewares) {\n result = middleware(result);\n }\n return result;\n }\n\n /**\n * Get the middleware chain without building (for inspection or further composition).\n */\n getChain(): Array<(machine: any) => any> {\n return [...this.middlewares];\n }\n\n /**\n * Clear all configured middleware.\n */\n clear(): MiddlewareBuilder<M> {\n this.middlewares = [];\n return this;\n }\n}\n\n/**\n * Create a typed middleware builder for a machine.\n * Provides perfect TypeScript inference for middleware configuration.\n *\n * @example\n * ```typescript\n * const enhancedMachine = middlewareBuilder(myMachine)\n * .withLogging({ includeArgs: true })\n * .withAnalytics(trackEvent)\n * .withHistory({ maxSize: 100 })\n * .withRetry({ maxAttempts: 3 })\n * .build();\n * ```\n */\nexport function middlewareBuilder<M extends BaseMachine<any>>(machine: M): MiddlewareBuilder<M> {\n return new MiddlewareBuilder(machine);\n}\n\n/**\n * Create a middleware factory function with pre-configured options.\n * Useful for creating reusable middleware configurations.\n */\nexport function createMiddlewareFactory<M extends BaseMachine<any>>(\n defaultOptions: {\n logging?: LoggingOptions;\n analytics?: { track: (event: string, data?: any) => void; options?: AnalyticsOptions };\n history?: HistoryOptions;\n snapshot?: SnapshotOptions;\n timeTravel?: TimeTravelOptions;\n retry?: RetryOptions;\n } = {}\n) {\n return {\n create: (machine: M) => {\n const builder = middlewareBuilder(machine);\n\n if (defaultOptions.logging) {\n builder.withLogging(defaultOptions.logging);\n }\n\n if (defaultOptions.analytics) {\n builder.withAnalytics(\n defaultOptions.analytics.track,\n defaultOptions.analytics.options\n );\n }\n\n if (defaultOptions.history) {\n builder.withHistory(defaultOptions.history);\n }\n\n if (defaultOptions.snapshot) {\n builder.withSnapshot(defaultOptions.snapshot);\n }\n\n if (defaultOptions.timeTravel) {\n builder.withTimeTravel(defaultOptions.timeTravel);\n }\n\n if (defaultOptions.retry) {\n builder.withRetry(defaultOptions.retry);\n }\n\n return builder;\n }\n };\n}\n\n// =============================================================================\n// SECTION: UTILITY FUNCTIONS\n// =============================================================================\n\n// =============================================================================\n// SECTION: COMMON COMBINATIONS\n// =============================================================================\n\n/**\n * Common middleware combination types for better DX.\n */\nexport type WithDebugging<M extends BaseMachine<any>> = WithTimeTravel<WithSnapshot<WithHistory<M>>>;\n\n/**\n * Convenience function for the most common debugging middleware stack.\n */\nexport function withDebugging<M extends BaseMachine<any>>(machine: M): WithDebugging<M> {\n return withTimeTravel(withSnapshot(withHistory(machine)));\n}", "/**\n * @file A collection of high-level, type-safe utility functions for @doeixd/machine.\n * @description These helpers provide ergonomic improvements for common patterns like\n * state checking, event creation, debugging, and composing transitions.\n */\n\nimport {\n Machine,\n AsyncMachine,\n MaybePromise,\n Context,\n Event,\n Transitions,\n TransitionArgs,\n setContext,\n createMachine,\n} from './index'; // Assuming index.ts is in the same directory\n\n// =============================================================================\n// SECTION: STATE & TYPE GUARDS\n// =============================================================================\n\n/**\n * A type representing a Class Constructor, used for type guards.\n */\ntype ClassConstructor = new (...args: any[]) => any;\n\n/**\n * A type-safe way to check if a machine is in a specific state, acting as a Type Guard.\n * This is the preferred way to do state checking when using class-based machines.\n *\n * @template T - The class constructor type to check against.\n * @param machine - The machine instance to check.\n * @param machineClass - The class constructor representing the state.\n * @returns {boolean} `true` if the machine is an instance of the class, narrowing its type.\n *\n * @example\n * declare const machine: LoggedInMachine | LoggedOutMachine;\n *\n * if (isState(machine, LoggedInMachine)) {\n * // `machine` is now correctly typed as LoggedInMachine\n * machine.logout();\n * }\n */\nexport function isState<T extends ClassConstructor>(\n machine: any,\n machineClass: T\n): machine is InstanceType<T> {\n return machine instanceof machineClass;\n}\n\n\n// =============================================================================\n// SECTION: EVENT & DISPATCH HELPERS\n// =============================================================================\n\n/**\n * A type-safe factory function for creating event objects for `runMachine`.\n * This provides full autocompletion and type checking for event names and their arguments.\n *\n * @template M - The machine type the event belongs to.\n * @template K - The specific event name (transition method name).\n * @param type - The name of the event (e.g., \"increment\").\n * @param args - The arguments for that event, correctly typed.\n * @returns A type-safe event object ready to be passed to `dispatch`.\n *\n * @example\n * // Given: type MyMachine = Machine<{...}> & { add: (n: number) => any }\n * const event = createEvent<MyMachine, 'add'>('add', 5);\n * // `event` is correctly typed as { type: \"add\"; args: [number] }\n *\n * await runner.dispatch(event);\n */\nexport function createEvent<\n M extends Machine<any>,\n K extends keyof Transitions<M> & string\n>(type: K, ...args: TransitionArgs<M, K>): Event<M> {\n return { type, args } as unknown as Event<M>;\n}\n\n\n// =============================================================================\n// SECTION: CONTEXT & STATE MANIPULATION\n// =============================================================================\n\n/**\n * Creates a new machine instance by shallowly merging a partial context into the\n * current context, preserving all original transitions.\n *\n * @template M - The machine type.\n * @param machine - The original machine instance.\n * @param partialContext - An object with a subset of context properties to update.\n * @returns A new machine instance of the same type with the merged context.\n *\n * @example\n * const user = new User({ name: 'Alex', age: 30, status: 'active' });\n * const updatedUser = mergeContext(user, { status: 'inactive' });\n * // updatedUser.context is { name: 'Alex', age: 30, status: 'inactive' }\n */\nexport function mergeContext<M extends Machine<any>>(\n machine: M,\n partialContext: Partial<Context<M>>\n): M {\n return setContext(machine, (ctx) => ({ ...ctx, ...partialContext }));\n}\n\n\n// =============================================================================\n// SECTION: COMPOSITION & DEBUGGING\n// =============================================================================\n\n/**\n * Sequentially applies a series of transitions to a machine.\n * This function correctly handles both synchronous and asynchronous transitions,\n * always returning a Promise with the final machine state.\n *\n * @template M - The machine type, must be compatible with AsyncMachine.\n * @param initialMachine - The starting machine state.\n * @param transitions - An array of functions, each taking a machine and returning the next.\n * @returns A `Promise` that resolves to the final machine state after all transitions complete.\n *\n * @example\n * const finalState = await pipeTransitions(\n * new Counter({ count: 0 }),\n * (m) => m.increment(), // sync\n * (m) => m.addAsync(5), // async\n * (m) => m.increment() // sync\n * );\n * // finalState.context.count will be 6\n */\nexport async function pipeTransitions<M extends AsyncMachine<any>>(\n initialMachine: M,\n ...transitions: ((m: M) => MaybePromise<M>)[]\n): Promise<M> {\n let current: M = initialMachine;\n for (const transitionFn of transitions) {\n current = await transitionFn(current);\n }\n return current;\n}\n\n/**\n * A \"tap\" utility for logging a machine's context without interrupting a chain of operations.\n * It prints the context to the console and returns the machine instance unchanged.\n *\n * @template M - The machine type.\n * @param machine - The machine instance to log.\n * @param label - An optional label to print before the context object.\n * @returns The original, unmodified machine instance.\n *\n * @example\n * import { logState as tap } from './utils';\n *\n * await pipeTransitions(\n * new Counter({ count: 0 }),\n * tap, // Logs: { count: 0 }\n * (m) => m.increment(),\n * (m) => tap(m, 'After increment:') // Logs: After increment: { count: 1 }\n * );\n */\nexport function logState<M extends Machine<any>>(machine: M, label?: string): M {\n if (label) {\n console.log(label, machine.context);\n } else {\n console.log(machine.context);\n }\n return machine;\n}\n\n/**\n * A generic combinator that creates transition functions from pure context transformers.\n * This enables writing transitions as simple, testable functions that only transform context,\n * while automatically handling the machine creation boilerplate.\n *\n * @template C - The context object type.\n * @template TArgs - The argument types for the transition function.\n * @param getTransitions - A function that returns the transition functions object to use for the new machine.\n * @param transformer - A pure function that transforms the context based on the current state and arguments.\n * @returns A transition function that can be used as a machine method.\n *\n * @example\n * ```typescript\n * // Define transitions object with self-reference\n * const counterTransitions = {\n * increment: createTransition(\n * () => counterTransitions,\n * (ctx) => ({ count: ctx.count + 1 })\n * ),\n * add: createTransition(\n * () => counterTransitions,\n * (ctx, n: number) => ({ count: ctx.count + n })\n * )\n * };\n *\n * // Create machine\n * const counter = createMachine({ count: 0 }, counterTransitions);\n *\n * // Use transitions\n * const incremented = counter.increment(); // { count: 1 }\n * const added = incremented.add(5); // { count: 6 }\n * ```\n *\n * @example\n * ```typescript\n * // With class-based machines\n * class Counter extends MachineBase<{ count: number }> {\n * constructor(count = 0) {\n * super({ count });\n * }\n *\n * increment = createTransition(\n * () => ({ increment: this.increment, add: this.add }),\n * (ctx) => ({ count: ctx.count + 1 })\n * );\n *\n * add = createTransition(\n * () => ({ increment: this.increment, add: this.add }),\n * (ctx, n: number) => ({ count: ctx.count + n })\n * );\n * }\n * ```\n *\n * @remarks\n * This function promotes the library's philosophy of pure, immutable transitions.\n * The transformer function should be pure and only depend on its parameters.\n * The returned transition function automatically creates a new machine instance,\n * preserving all transitions while updating only the context.\n * The getTransitions function is called lazily to avoid circular reference issues.\n */\nexport function createTransition<\n C extends object,\n TArgs extends any[]\n>(\n getTransitions: () => Record<string, (this: C, ...args: any[]) => any>,\n transformer: (ctx: C, ...args: TArgs) => C\n): (this: { context: C }, ...args: TArgs) => Machine<C> {\n return function (this: { context: C }, ...args: TArgs): Machine<C> {\n const nextContext = transformer(this.context, ...args);\n return createMachine(nextContext, getTransitions());\n };\n}\n\n// =============================================================================\n// SECTION: TRANSITION BINDING HELPERS\n// =============================================================================\n\n/**\n * Calls a transition function with an explicit `this` context.\n * Useful for invoking transition methods with proper context binding.\n *\n * @template C - The context type that the function expects as `this`.\n * @template F - The function type with a `this` parameter.\n * @template A - The argument types for the function.\n * @param fn - The transition function to call.\n * @param context - The context object to bind as `this`.\n * @param args - Arguments to pass to the function.\n * @returns The result of calling the function with the given context and arguments.\n *\n * @example\n * type MyContext = { count: number };\n * const increment = function(this: MyContext) { return this.count + 1; };\n * const result = call(increment, { count: 5 }); // Returns 6\n *\n * // Particularly useful with machine transitions:\n * import { call } from '@doeixd/machine/utils';\n * const nextMachine = yield* step(call(m.increment, m.context));\n */\nexport function call<C, F extends (this: C, ...args: any[]) => any>(\n fn: F,\n context: C,\n ...args: Parameters<F> extends [any, ...infer Rest] ? Rest : never\n): ReturnType<F> {\n return fn.apply(context, args);\n}\n\n/**\n * Binds all transition methods of a machine to its context automatically.\n * Returns a Proxy that intercepts method calls and binds them to `machine.context`.\n * This eliminates the need to use `.call(m.context, ...)` for every transition.\n *\n * Automatically recursively wraps returned machines, enabling seamless chaining\n * in generator-based flows.\n *\n * @template M - The machine type with a `context` property and transition methods.\n * @param machine - The machine instance to wrap.\n * @returns A Proxy of the machine where all callable properties (transitions) are automatically bound to the machine's context.\n *\n * @example\n * type CounterContext = { count: number };\n * const counter = bindTransitions(createMachine({ count: 0 }, {\n * increment(this: CounterContext) { return createCounter(this.count + 1); }\n * }));\n *\n * // Now you can call transitions directly without .call():\n * const next = counter.increment(); // Works! This is automatically bound.\n *\n * // Particularly useful with generators:\n * const result = run(function* (m) {\n * m = yield* step(m.increment()); // Clean syntax\n * m = yield* step(m.add(5)); // No .call() needed\n * return m;\n * }, bindTransitions(counter));\n *\n * @remarks\n * The Proxy preserves all original properties and methods. Non-callable properties\n * are accessed directly from the machine. Callable properties are wrapped to bind\n * them to `machine.context` before invocation. Returned machines are automatically\n * re-wrapped to maintain binding across transition chains.\n */\nexport function bindTransitions<M extends { context: any }>(machine: M): M {\n return new Proxy(machine, {\n get(target, prop) {\n const value = target[prop as keyof M];\n \n // If it's a callable property (transition method), bind it to context\n if (typeof value === 'function') {\n return function(...args: any[]) {\n const result = value.apply(target.context, args);\n // Recursively wrap returned machines to maintain binding\n if (result && typeof result === 'object' && 'context' in result) {\n return bindTransitions(result);\n }\n return result;\n };\n }\n \n // Otherwise, return the value as-is\n return value;\n },\n }) as M;\n}\n\n/**\n * A strongly-typed wrapper class for binding transitions to machine context.\n * Unlike the Proxy-based `bindTransitions`, this class preserves full type safety\n * and provides better IDE support through explicit property forwarding.\n *\n * @template M - The machine type with a `context` property and transition methods.\n *\n * @example\n * type CounterContext = { count: number };\n * const counter = createMachine({ count: 0 }, {\n * increment(this: CounterContext) { return createCounter(this.count + 1); }\n * });\n *\n * const bound = new BoundMachine(counter);\n *\n * // All transitions are automatically bound to context\n * const result = run(function* (m) {\n * m = yield* step(m.increment());\n * m = yield* step(m.add(5));\n * return m.context.count;\n * }, bound);\n *\n * @remarks\n * Advantages over Proxy-based `bindTransitions`:\n * - Full type safety with TypeScript's type system\n * - Returned machines are automatically re-wrapped\n * - Better IDE autocompletion and hover information\n * - No type casting needed\n *\n * Disadvantages:\n * - Requires explicit instance creation: `new BoundMachine(m)` vs `bindTransitions(m)`\n * - Not a transparent drop-in replacement for the original machine\n */\nexport class BoundMachine<M extends { context: any }> {\n private readonly wrappedMachine: M;\n [key: string | symbol]: any;\n\n constructor(machine: M) {\n this.wrappedMachine = machine;\n\n // Create a proxy to intercept property access\n return new Proxy(this, {\n get: (target, prop) => {\n // Handle direct property access to wrapped machine\n if (prop === 'wrappedMachine') {\n return Reflect.get(target, prop);\n }\n if (prop === 'context') {\n return this.wrappedMachine.context;\n }\n\n const value = this.wrappedMachine[prop as keyof M];\n\n // Bind transition methods to context\n if (typeof value === 'function') {\n return (...args: any[]) => {\n const result = value.apply(this.wrappedMachine.context, args);\n // Recursively wrap returned machines\n if (result && typeof result === 'object' && 'context' in result) {\n return new BoundMachine(result);\n }\n return result;\n };\n }\n\n // Return non-function properties directly\n return value;\n },\n }) as any;\n }\n}\n\n/**\n * Creates a sequence machine that orchestrates multi-step flows by automatically\n * advancing through a series of machines. When the current machine reaches a \"final\"\n * state (determined by the isFinal predicate), the sequence automatically transitions\n * to the next machine in the sequence.\n *\n * This implementation uses a functional approach with object delegation rather than Proxy.\n */\nfunction createSequenceMachine<\n M extends readonly [Machine<any>, ...Machine<any>[]]\n>(\n machines: M,\n isFinal: (machine: M[number]) => boolean\n): M[number] {\n if (machines.length === 0) {\n throw new Error('Sequence must contain at least one machine');\n }\n\n let currentIndex = 0;\n let currentMachine = machines[0];\n\n const createDelegationObject = (machine: M[number]) => {\n const delegationObject = Object.create(machine);\n\n // The context getter returns the machine's own context\n // (machine is the specific machine instance this delegation object represents)\n Object.defineProperty(delegationObject, 'context', {\n get: () => machine.context,\n enumerable: true,\n configurable: true\n });\n\n // Override all methods to add advancement logic\n const originalProto = Object.getPrototypeOf(machine);\n const methodNames = Object.getOwnPropertyNames(originalProto).filter(name =>\n name !== 'constructor' && name !== 'context' && typeof (machine as any)[name] === 'function'\n );\n\n for (const methodName of methodNames) {\n const methodKey = methodName as keyof any;\n\n (delegationObject as any)[methodKey] = (...args: unknown[]) => {\n const result = (currentMachine as any)[methodKey](...args);\n\n // Handle both sync and async results\n const handleResult = (resultMachine: unknown) => {\n return advanceIfNeeded(resultMachine as M[number]);\n };\n\n // If the result is a Promise, handle it asynchronously\n if (result && typeof (result as any).then === 'function') {\n return (result as Promise<unknown>).then(handleResult);\n }\n\n // Otherwise, handle synchronously\n return handleResult(result);\n };\n }\n\n return delegationObject;\n };\n\n const advanceIfNeeded = (machine: M[number]): M[number] => {\n currentMachine = machine;\n\n // Check if we should advance to the next machine\n if (isFinal(currentMachine) && currentIndex < machines.length - 1) {\n currentIndex++;\n currentMachine = machines[currentIndex];\n // Create a new delegation object for the new currentMachine\n return createDelegationObject(currentMachine);\n }\n\n return machine;\n };\n\n return createDelegationObject(currentMachine);\n}\n/**\n * Creates a sequence machine that orchestrates multi-step flows by automatically\n * advancing through a series of machines. When the current machine reaches a \"final\"\n * state (determined by the isFinal predicate), the sequence automatically transitions\n * to the next machine in the sequence.\n *\n * This is perfect for wizard-style flows, multi-step processes, or any scenario where\n * you need to chain machines together with automatic progression.\n *\n * @template M - The tuple of machine types in the sequence.\n * @param machines - The machines to sequence, in order.\n * @param isFinal - A predicate function that determines when a machine is in a final state.\n * Called after each transition to check if the sequence should advance.\n * @returns A new machine that wraps the sequence, delegating to the current machine\n * and automatically advancing when each machine reaches its final state.\n *\n * @example\n * ```typescript\n * // Define form machines with final states\n * class NameForm extends MachineBase<{ name: string; valid: boolean }> {\n * submit = (name: string) => new NameForm({ name, valid: name.length > 0 });\n * }\n *\n * class EmailForm extends MachineBase<{ email: string; valid: boolean }> {\n * submit = (email: string) => new EmailForm({ email, valid: email.includes('@') });\n * }\n *\n * class PasswordForm extends MachineBase<{ password: string; valid: boolean }> {\n * submit = (password: string) => new PasswordForm({ password, valid: password.length >= 8 });\n * }\n *\n * // Create sequence that advances when each form becomes valid\n * const wizard = sequence(\n * [new NameForm({ name: '', valid: false }),\n * new EmailForm({ email: '', valid: false }),\n * new PasswordForm({ password: '', valid: false })],\n * (machine) => machine.context.valid // Advance when valid becomes true\n * );\n *\n * // Usage - automatically advances through forms\n * let current = wizard;\n * current = current.submit('John'); // Still on NameForm (not valid yet)\n * current = current.submit('John Doe'); // Advances to EmailForm (name is valid)\n * current = current.submit('john@'); // Still on EmailForm (not valid yet)\n * current = current.submit('john@example.com'); // Advances to PasswordForm\n * current = current.submit('12345678'); // Advances to end of sequence\n * ```\n *\n * @example\n * ```typescript\n * // Async sequence with API calls\n * const authSequence = sequence(\n * [new LoginForm(), new TwoFactorForm(), new Dashboard()],\n * (machine) => machine.context.authenticated === true\n * );\n *\n * // The sequence handles async transitions automatically\n * const finalState = await authSequence.login('user@example.com', 'password');\n * ```\n *\n * @example\n * ```typescript\n * // Complex predicate - advance based on multiple conditions\n * const complexSequence = sequence(\n * [step1Machine, step2Machine, step3Machine],\n * (machine) => {\n * // Advance when all required fields are filled AND validated\n * return machine.context.requiredFields.every(f => f.filled) &&\n * machine.context.validationErrors.length === 0;\n * }\n * );\n * ```\n *\n * @remarks\n * - The sequence maintains the union type of all machines in the sequence\n * - Transitions are delegated to the current machine in the sequence\n * - When a machine reaches a final state, the sequence automatically advances\n * - If the sequence reaches the end, further transitions return the final machine\n * - The isFinal predicate is called after every transition to check advancement\n * - Works with both sync and async machines (returns MaybePromise)\n */\nexport function sequence<\n M extends readonly [Machine<any>, ...Machine<any>[]]\n>(\n machines: M,\n isFinal: (machine: M[number]) => boolean\n): M[number] {\n return createSequenceMachine(machines, isFinal);\n}\n\n/**\n * Convenience overload for sequencing exactly 2 machines.\n * Provides better type inference and IntelliSense for common 2-step flows.\n *\n * @example\n * ```typescript\n * const flow = sequence2(\n * new LoginForm(),\n * new Dashboard(),\n * (machine) => machine.context.authenticated\n * );\n * ```\n */\nexport function sequence2<\n M1 extends Machine<any>,\n M2 extends Machine<any>\n>(\n machine1: M1,\n machine2: M2,\n isFinal: (machine: M1 | M2) => boolean\n): M1 | M2 {\n return sequence([machine1, machine2], isFinal);\n}\n\n/**\n * Convenience overload for sequencing exactly 3 machines.\n * Provides better type inference and IntelliSense for common 3-step flows.\n *\n * @example\n * ```typescript\n * const wizard = sequence3(\n * new NameForm({ name: '', valid: false }),\n * new EmailForm({ email: '', valid: false }),\n * new PasswordForm({ password: '', valid: false }),\n * (machine) => machine.context.valid\n * );\n * ```\n */\nexport function sequence3<\n M1 extends Machine<any>,\n M2 extends Machine<any>,\n M3 extends Machine<any>\n>(\n machine1: M1,\n machine2: M2,\n machine3: M3,\n isFinal: (machine: M1 | M2 | M3) => boolean\n): M1 | M2 | M3 {\n return sequence([machine1, machine2, machine3], isFinal);\n}", "import { createMachine, Machine, BaseMachine, extendTransitions } from './index';\n\n/**\n * Creates a factory for building type-safe transitions for a specific machine.\n * This higher-order function captures the machine's `transitions` object in a closure,\n * enabling a clean, functional pattern for defining state changes without directly\n * manipulating the machine's context.\n *\n * This pattern promotes:\n * - Pure functions for state transformations\n * - Separation of transition logic from machine construction\n * - Reusable transition factories across similar machines\n * - Type safety through generic constraints\n *\n * @template C The context type of the machine\n * @template C The context type of the machine\n * @returns A `createTransition` function that can create transitions for machines with context type C\n *\n * @example\n * ```typescript\n * // Define your machine's transitions object\n * const counterTransitions = {\n * increment: function(amount: number) {\n * return createMachine({ count: this.count + amount }, counterTransitions);\n * }\n * };\n *\n * // Create a transition factory\n * const createCounterTransition = createTransitionFactory<{ count: number }>();\n *\n * // Use the factory to create pure, type-safe transitions\n * const incrementBy = createCounterTransition(\n * (ctx, amount: number) => ({ count: ctx.count + amount })\n * );\n *\n * const counter = createMachine({ count: 0 }, counterTransitions);\n * const newCounter = counter.increment(5); // Direct call\n * // OR\n * const incremented = incrementBy.call(counter, 5); // Using factory\n * ```\n */\nexport function createTransitionFactory<C extends object>() {\n /**\n * Takes a pure context transformer function and returns a full, type-safe\n * machine transition method that can be attached to a machine.\n *\n * The transformer function receives the current context as its first argument,\n * followed by any additional arguments passed to the transition.\n *\n * @template TArgs The argument types for the transition (excluding context)\n * @param transformer A pure function: `(context, ...args) => nextContext`\n * @returns A machine transition method that can be called on a machine instance\n *\n * @example\n * ```typescript\n * const createTodoTransition = createTransitionFactory<TodoContext>();\n *\n * const addTodo = createTodoTransition(\n * (ctx, text: string) => ({\n * ...ctx,\n * todos: [...ctx.todos, { id: Date.now(), text, completed: false }]\n * })\n * );\n *\n * const updateTodo = createTodoTransition(\n * (ctx, id: number, updates: Partial<Todo>) => ({\n * ...ctx,\n * todos: ctx.todos.map(todo =>\n * todo.id === id ? { ...todo, ...updates } : todo\n * )\n * })\n * );\n * ```\n */\n return function createTransition<TArgs extends any[]>(\n transformer: (ctx: C, ...args: TArgs) => C\n ) {\n return function (this: BaseMachine<C>, ...args: TArgs): Machine<C> {\n const nextContext = transformer(this.context, ...args);\n // Use `this` as the transitions object, which includes all current transitions\n return createMachine(nextContext, this);\n };\n };\n}\n\n/**\n * Creates a factory for adding new, type-safe transitions to an existing machine instance.\n * This enables a functional, compositional approach to building up a machine's capabilities\n * incrementally, without modifying the original machine.\n *\n * This pattern supports:\n * - Progressive enhancement of machine behavior\n * - Plugin-like extension of existing machines\n * - Immutable composition (original machine unchanged)\n * - Type-safe addition of new transitions\n *\n * @template M The machine type being extended\n * @param machine The machine instance to extend\n * @returns An `addTransition` function pre-configured for this machine\n *\n * @example\n * ```typescript\n * // Start with a basic counter machine\n * const basicCounter = createMachine({ count: 0 }, {\n * increment: function() {\n * return createMachine({ count: this.count + 1 }, this);\n * }\n * });\n *\n * // Create an extender for this machine\n * const extendCounter = createTransitionExtender(basicCounter);\n *\n * // Add new transitions functionally\n * const extendedCounter = extendCounter('decrement',\n * (ctx) => ({ count: ctx.count - 1 })\n * ).addTransition('reset',\n * (ctx) => ({ count: 0 })\n * ).addTransition('add',\n * (ctx, amount: number) => ({ count: ctx.count + amount })\n * );\n *\n * // The original machine is unchanged\n * console.log(basicCounter.count); // 0\n *\n * // The extended machine has all transitions\n * const result = extendedCounter.increment().add(10).decrement();\n * console.log(result.count); // 10\n * ```\n */\nexport function createTransitionExtender<M extends Machine<any>>(machine: M) {\n type C = M['context'];\n\n /**\n * Adds a new transition to the machine and returns a new extender for chaining.\n * The new transition is created from a pure context transformer function.\n *\n * @template TName The name of the new transition\n * @template TArgs The argument types for the new transition\n * @param name The name of the new transition method\n * @param transformer A pure function that defines how the context should change\n * @returns A new transition extender with the added transition\n *\n * @example\n * ```typescript\n * const userMachine = createMachine({ name: '', email: '' }, {});\n * const extendUser = createTransitionExtender(userMachine);\n *\n * const withValidation = extendUser.addTransition('setName',\n * (ctx, name: string) => {\n * if (name.length < 2) throw new Error('Name too short');\n * return { ...ctx, name };\n * }\n * ).addTransition('setEmail',\n * (ctx, email: string) => {\n * if (!email.includes('@')) throw new Error('Invalid email');\n * return { ...ctx, email };\n * }\n * );\n *\n * const user = withValidation.machine.setName('John').setEmail('john@example.com');\n * ```\n */\n return {\n machine,\n\n addTransition: function<\n TName extends string,\n TArgs extends any[],\n >(\n name: TName,\n transformer: (ctx: C, ...args: TArgs) => C\n ) {\n const transitionFn = function (this: Machine<C>, ...args: TArgs) {\n const nextContext = transformer(this.context, ...args);\n\n // Use `this` as the transitions object, which includes all current transitions\n return createMachine(nextContext, this);\n };\n\n // Create the extended machine\n const newMachine = extendTransitions(machine, { [name]: transitionFn } as any);\n\n // Return a new extender that includes this transition\n return createTransitionExtender(newMachine);\n }\n };\n}\n\n/**\n * A mapped type that creates the final transition method signatures based on\n * an object of pure context transformers. It infers argument types and sets\n * the correct return type.\n */\ntype MachineTransitions<\n T extends Record<string, (ctx: C, ...args: any[]) => C>,\n C extends object\n> = {\n [K in keyof T]: T[K] extends (ctx: C, ...args: infer A) => C\n ? (this: Machine<C>, ...args: A) => Machine<C>\n : never;\n};\n\n/**\n * Creates a complete, type-safe, functional state machine using a curried, two-step\n * approach that separates the initial data from the transition logic.\n *\n * This is a highly declarative and functional pattern for building single-state machines.\n *\n * @template C The context type of the machine.\n * @param initialContext The starting context (data) for the machine.\n * @returns A new function that takes an object of pure context-transformer\n * functions and returns a fully-formed machine instance.\n */\nexport function createFunctionalMachine<C extends object>(initialContext: C) {\n /**\n * This returned function is pre-configured with the `initialContext`.\n *\n * @template T The type of the transformers object.\n * @param transformers An object where each key is a transition name and each value\n * is a pure function: `(context, ...args) => nextContext`.\n * @returns A fully-formed, immutable, and type-safe machine instance.\n *\n * @example\n * ```typescript\n * const createCounter = createFunctionalMachine({ count: 0 });\n *\n * const counter = createCounter({\n * increment: (ctx) => ({ count: ctx.count + 1 }),\n * decrement: (ctx) => ({ count: ctx.count - 1 }),\n * add: (ctx, amount: number) => ({ count: ctx.count + amount }),\n * reset: (ctx) => ({ count: 0 })\n * });\n *\n * // Use the machine\n * const updated = counter.increment().add(5).decrement();\n * console.log(updated.context.count); // 5\n * ```\n */\n return function withTransitions<\n T extends Record<string, (ctx: C, ...args: any[]) => C>\n >(\n transformers: T\n ): Machine<C> & MachineTransitions<T, C> {\n // 1. Create a placeholder object for the final transitions.\n const transitions: any = {};\n\n // 2. Map the pure transformers to full machine transition methods.\n const machineTransitions = Object.fromEntries(\n Object.entries(transformers).map(([key, transformer]) => [\n key,\n function (this: { context: C }, ...args: any[]) {\n // Apply the pure data transformation.\n const nextContext = transformer(this.context, ...args);\n // Return a new machine, passing in the `transitions` object from the closure.\n // At this point, `transitions` will be fully populated.\n return createMachine(nextContext, transitions);\n },\n ])\n );\n\n // 3. Populate the placeholder with the real transitions.\n Object.assign(transitions, machineTransitions);\n\n // 4. Create and return the initial machine instance using the provided context.\n return createMachine(initialContext, transitions) as any;\n };\n}\n\n/**\n * A smart, type-safe function that creates state machines using either the traditional\n * `createMachine` pattern or the functional `createFunctionalMachine` pattern, automatically\n * detecting which approach to use based on the arguments provided.\n *\n * **Two Usage Patterns:**\n *\n * 1. **Traditional Pattern** (with transitions object):\n * ```typescript\n * const machine = state({ count: 0 }, {\n * increment() { return createMachine({ count: this.count + 1 }, this); }\n * });\n * ```\n *\n * 2. **Functional Pattern** (curried, with transformers):\n * ```typescript\n * const createCounter = state({ count: 0 });\n * const machine = createCounter({\n * increment: ctx => ({ count: ctx.count + 1 }),\n * add: (ctx, n: number) => ({ count: ctx.count + n })\n * });\n * ```\n *\n * **How it works:**\n * - When called with 2 arguments: Uses `createMachine` (traditional pattern)\n * - When called with 1 argument: Uses `createFunctionalMachine` (functional pattern)\n *\n * **Edge Cases Handled:**\n * - Empty transitions object: Falls back to functional pattern\n * - Context with function properties: Properly typed as transitions vs transformers\n * - Type inference: Maintains full type safety in both patterns\n *\n * @template C The context type\n * @template T The transitions/transformers type\n * @param context The initial context object\n * @param transitions Optional transitions object (traditional pattern)\n * @returns Either a machine (traditional) or a factory function (functional)\n *\n * @example\n * ```typescript\n * // Traditional pattern\n * const counter1 = state({ count: 0 }, {\n * increment() { return createMachine({ count: this.count + 1 }, this); },\n * decrement() { return createMachine({ count: this.count - 1 }, this); }\n * });\n *\n * // Functional pattern\n * const createCounter = state({ count: 0 });\n * const counter2 = createCounter({\n * increment: ctx => ({ count: ctx.count + 1 }),\n * decrement: ctx => ({ count: ctx.count - 1 }),\n * reset: ctx => ({ count: 0 })\n * });\n * ```\n */\nexport function state<C extends object>(context: C): ReturnType<typeof createFunctionalMachine<C>>;\nexport function state<C extends object, T extends Record<string, any>>(\n context: C,\n transitions: T\n): Machine<C> & T;\nexport function state<C extends object, T extends Record<string, any>>(\n context: C,\n transitions?: T\n): Machine<C> & T | ReturnType<typeof createFunctionalMachine<C>> {\n // If transitions is provided (2 arguments), use traditional createMachine pattern\n if (transitions !== undefined) {\n return createMachine(context, transitions);\n }\n\n // If only context is provided (1 argument), use functional createFunctionalMachine pattern\n return createFunctionalMachine(context);\n}", "/**\n * @file A tiny, immutable, and type-safe state machine library for TypeScript.\n * @author doeixd\n * @version 1.0.0\n */\n\n// =============================================================================\n// SECTION: CORE TYPES & INTERFACES\n// =============================================================================\n\n/**\n * A utility type that represents either a value of type T or a Promise that resolves to T.\n * @template T - The value type.\n */\nexport type MaybePromise<T> = T | Promise<T>;\n\n/**\n * The fundamental shape of a synchronous machine. This is a highly advanced\n * generic type that performs two critical functions at compile time:\n *\n * 1. **Extraction:** It intelligently infers the pure transitions object from\n * the flexible argument `A` (which can be a plain object, a factory\n * function, or the augmented `this` from another transition).\n *\n * 2. **Filtering:** After extracting the transitions, it filters them, keeping\n * only the functions that return a valid `Machine`.\n *\n * This makes the `Machine` type itself the single source of truth for what\n * constitutes a valid, type-safe machine, enabling a remarkably clean and\n * powerful API for `createMachine`.\n *\n * @template C The context object type.\n * @template A The raw, flexible argument for transitions (object, factory, or `this`).\n */\nexport type Machine<\n C extends object,\n T extends object = {}\n> = {\n readonly context: C;\n} & T;\n\n/**\n * The shape of an asynchronous machine, where transitions can return Promises.\n * Async transitions receive an AbortSignal as the last parameter for cancellation support.\n * @template C - The context object type.\n */\nexport type AsyncMachine<\n C extends object,\n T extends object = {}\n> = {\n readonly context: C;\n} & T;\n\n/**\n * Utility type to extract the parameters of an async transition function,\n * which includes TransitionOptions as the last parameter.\n */\nexport type AsyncTransitionArgs<M extends AsyncMachine<any, any>, K extends keyof M & string> =\n M[K] extends (...a: infer A) => any\n ? A extends [...infer Rest, TransitionOptions] ? Rest : A\n : never;\n\n/**\n * A helper type to define a distinct state in a state machine (a \"typestate\").\n * Allows defining the context and transitions in a single generic type.\n * @template C - The context specific to this state.\n * @template T - The transitions available in this state.\n */\nexport type TypeState<C extends object, T extends object = {}> = Machine<C, T>;\n\n/**\n * A helper type to define a distinct async state in a state machine.\n * @template C - The context specific to this state.\n * @template T - The transitions available in this state.\n */\nexport type AsyncTypeState<C extends object, T extends object = {}> = AsyncMachine<C, T>;\n\n\n/**\n * Options passed to async transition functions, including cancellation support.\n */\nexport interface TransitionOptions {\n /** AbortSignal for cancelling long-running async operations. */\n signal: AbortSignal;\n}\n\n\n// =============================================================================\n// SECTION: TYPE UTILITIES & INTROSPECTION\n// =============================================================================\n\n\n\n/**\n * Extracts the context type `C` from a machine type `M`.\n * @template M - The machine type.\n * @example type Ctx = Context<Machine<{ count: number }>> // { count: number }\n */\nexport type Context<M extends { context: any }> = M[\"context\"];\n\n/**\n * Extracts the transition function signatures from a machine, excluding the context property.\n * @template M - The machine type.\n */\nexport type Transitions<M extends BaseMachine<any>> = Omit<M, \"context\">;\n\n/**\n * Extracts the argument types for a specific transition function in a Machine.\n * @template M - The machine type.\n * @template K - The transition function name.\n */\nexport type TransitionArgs<M extends Machine<any>, K extends keyof M & string> =\n M[K] extends (...args: infer A) => any ? A : never;\n/**\n * Extracts the names of all transitions as a string union type.\n * @template M - The machine type.\n * @example\n * type Names = TransitionNames<Machine<{ count: number }> & { increment: () => any }>\n * // Names = \"increment\"\n */\nexport type TransitionNames<M extends BaseMachine<any>> = keyof Omit<M, \"context\"> & string;\n\n/**\n * Base machine type that both Machine and AsyncMachine extend from.\n * @template C - The context object type.\n */\nexport type BaseMachine<C extends object> = {\n /** The readonly state of the machine. */\n readonly context: C;\n};\n\n/**\n * Helper to make a type deeply readonly (freezes nested objects).\n * Useful for ensuring immutability of context at the type level.\n * @template T - The type to make readonly.\n */\nexport type DeepReadonly<T> = {\n readonly [P in keyof T]: T[P] extends object\n ? T[P] extends (...args: any[]) => any\n ? T[P]\n : DeepReadonly<T[P]>\n : T[P];\n};\n\n/**\n * Infers the machine type from a machine factory function.\n * @template F - The factory function type.\n * @example\n * const factory = () => createMachine({ count: 0 }, { ... });\n * type MyMachine = InferMachine<typeof factory>; // Extracts the return type\n */\nexport type InferMachine<F extends (...args: any[]) => any> = ReturnType<F>;\n\n\nexport type EventFromTransitions<T extends Record<string, (...args: any[]) => any>> =\n { [K in keyof T & string]: { type: K; args: T[K] extends (...a: infer A) => any ? A : never } }[keyof T & string];\n\n/**\n * A discriminated union type representing an event that can be dispatched to a machine.\n * This is automatically generated from a machine's type signature, ensuring full type safety.\n * @template M - The machine type.\n * @example\n * type CounterEvent = Event<Machine<{ count: number }>& { add: (n: number) => any }>\n * // CounterEvent = { type: \"add\"; args: [number] }\n */\nexport type Event<M extends BaseMachine<any>> = {\n [K in keyof Omit<M, \"context\"> & string]: M[K] extends (...args: infer A) => any\n ? { type: K; args: A }\n : never\n}[keyof Omit<M, \"context\"> & string];\n\n\n/**\n * A helper type for use with TypeScript's `satisfies` operator to provide\n * strong, immediate type-checking for standalone transition objects.\n *\n * This solves the \"chicken-and-egg\" problem where you need the final machine\n * type to correctly type the transitions object, but you need the transitions\n * object to create the machine. By forward-declaring the machine type and using\n * `satisfies TransitionsFor<...>`, you get full IntelliSense and error-checking\n * at the exact location of your transition definitions.\n *\n * @template C The context object type for the machine.\n * @template T The literal type of the transitions object itself (`typeof myTransitions`).\n *\n * @example\n * import { createMachine, Machine, TransitionsFor } from '@doeixd/machine';\n *\n * // 1. Define the context for your machine.\n * type CounterContext = { count: number };\n *\n * // 2. Forward-declare the final machine type. This is the key step that\n * // breaks the circular dependency for the type checker.\n * type CounterMachine = Machine<CounterContext> & typeof counterTransitions;\n *\n * // 3. Define the transitions object, using `satisfies` to apply the helper type.\n * // This provides immediate type-checking and full autocompletion for `this`.\n * const counterTransitions = {\n * increment() {\n * // `this` is now fully typed!\n * // IntelliSense knows `this.count` is a number and\n * // `this.transitions.add` is a function.\n * return createMachine({ count: this.count + 1 }, this.transitions);\n * },\n * add(n: number) {\n * return createMachine({ count: this.count + n }, this.transitions);\n * },\n * // ❌ TypeScript will immediately throw a compile error on the next line\n * // because the return type 'string' does not satisfy 'Machine<any>'.\n * invalidTransition() {\n * return \"this is not a machine\";\n * }\n * } satisfies TransitionsFor<CounterContext, typeof counterTransitions>;\n *\n * // 4. Create the machine instance. The `createMachine` call is now\n * // guaranteed to be type-safe because `counterTransitions` has already\n * // been validated.\n * export function createCounter(initialCount = 0): CounterMachine {\n * return createMachine({ count: initialCount }, counterTransitions);\n * }\n */\nexport type TransitionsFor<C extends object, T extends Record<string, any>> = {\n [K in keyof T]: (this: C & { transitions: T }, ...args: Parameters<T[K] extends (...a: infer A) => any ? (...a: A) => any : never>) => Machine<any, any>;\n};\n\n/**\n * A helper type for use with the `satisfies` operator to provide strong\n * type-checking for standalone asynchronous transition objects.\n */\nexport type AsyncTransitionsFor<C extends object, T extends Record<string, any>> = {\n [K in keyof T]: (this: C & { transitions: T }, ...args: Parameters<T[K] extends (...a: infer A) => any ? (...a: A) => any : never>) => MaybePromise<AsyncMachine<any, any>>;\n};\n\n/**\n * A mapped type that iterates over a transitions object `T` and keeps only the\n * keys whose functions return a valid `Machine`. This provides a \"self-correcting\"\n * type that prevents the definition of invalid transitions at compile time.\n *\n * It acts as a filter at the type level. When used in the return type of a\n * function like `createMachine`, it ensures that the resulting machine object\n * will not have any properties corresponding to functions that were defined\n * with an incorrect return type. This provides immediate, precise feedback to\n * the developer, making it impossible to create a machine with an invalid\n * transition shape.\n *\n * @template T The raw transitions object type provided by the user.\n *\n * @example\n * import { createMachine, Machine } from '@doeixd/machine';\n *\n * const machine = createMachine({ value: 'A' }, {\n * // This is a valid transition because it returns a `Machine`.\n * // The key 'goToB' will be PRESERVED in the final type.\n * goToB() {\n * return createMachine({ value: 'B' }, this.transitions);\n * },\n *\n * // This is an INVALID transition because it returns a string.\n * // The key 'invalid' will be OMITTED from the final type.\n * invalid() {\n * return \"This is not a Machine object\";\n * },\n *\n * // This is also invalid as it's not a function.\n * // The key 'alsoInvalid' will be OMITTED from the final type.\n * alsoInvalid: 123\n * });\n *\n * // --- USAGE ---\n *\n * // ✅ This call is valid and works as expected.\n * const nextState = machine.goToB();\n *\n * // ❌ This line will cause a COMPILE-TIME a ERROR because the `FilterValidTransitions`\n * // type has removed the 'invalid' key from the `machine`'s type signature.\n * //\n * // Error: Property 'invalid' does not exist on type\n * // 'Machine<{ value: string; }> & { goToB: () => Machine<...>; }'.\n * //\n * machine.invalid();\n */\nexport type FilterValidTransitions<T> = {\n [K in keyof T as T[K] extends (...args: any[]) => Machine<any> ? K : never]: T[K];\n};\n\n/**\n * A conditional type that intelligently extracts the pure transitions object `T`\n * from the flexible second argument of `createMachine`.\n *\n * It handles three cases:\n * 1. If the argument is the augmented `this` context (`C & { transitions: T }`), it extracts `T`.\n * 2. If the argument is a factory function `((ctx: C) => T)`, it infers and returns `T`.\n * 3. If the argument is already the pure transitions object `T`, it returns it as is.\n */\nexport type ExtractTransitions<Arg, C extends object> = Arg extends (\n ...args: any[]\n) => infer R\n ? R // Case 2: It's a factory function, extract the return type `R`.\n : Arg extends C & { transitions: infer T }\n ? T // Case 1: It's the augmented `this` context, extract `T` from `transitions`.\n : Arg; // Case 3: It's already the plain transitions object.\n\n/** Keep only keys whose value is a function that returns a Machine. */\nexport type ValidTransitions<T> = {\n [K in keyof T as T[K] extends (...a: any[]) => Machine<any, any> ? K : never]:\n T[K] extends (...a: infer A) => Machine<infer C2, infer T2> ? (...a: A) => Machine<C2, T2> : never;\n};\n\n/** Same for async transitions (functions returning MaybePromise<AsyncMachine>). */\nexport type ValidAsyncTransitions<T> = {\n [K in keyof T as T[K] extends (...a: any[]) => MaybePromise<AsyncMachine<any, any>> ? K : never]:\n T[K] extends (...a: infer A) => MaybePromise<AsyncMachine<infer C2, infer T2>> ? (...a: A) => MaybePromise<AsyncMachine<C2, T2>> : never;\n};\n\n// =============================================================================\n// SECTION: MACHINE CREATION (FUNCTIONAL & OOP)\n// =============================================================================\n\n/**\n * Creates a synchronous state machine from a context and transition functions.\n * This is the core factory for the functional approach.\n *\n * @template C - The context object type.\n * @param context - The initial state context.\n * @param fns - An object containing transition function definitions.\n * @returns A new machine instance.\n */\n/**\n * Helper to transform transition functions to be bound (no 'this' requirement).\n */\nexport type BindTransitions<T> = {\n [K in keyof T]: T[K] extends (this: any, ...args: infer A) => infer R\n ? (...args: A) => R\n : T[K];\n};\n\n/**\n * Creates a synchronous state machine from a context and a factory function.\n * This \"Functional Builder\" pattern allows for type-safe transitions without\n * manually passing `this` or `transitions`.\n *\n * @template C - The context object type.\n * @template T - The transitions object type.\n * @param context - The initial state context.\n * @param factory - A function that receives a `transition` helper and returns the transitions object.\n * @returns A new machine instance.\n */\nexport function createMachine<C extends object, T extends Record<string, (this: C, ...args: any[]) => any> = Record<string, (this: C, ...args: any[]) => any>>(\n context: C,\n factory: (transition: (newContext: C) => Machine<C, any>) => T\n): Machine<C, BindTransitions<T>>;\n\n/**\n * Creates a synchronous state machine from a context and transition functions.\n * This is the core factory for the functional approach.\n *\n * @template C - The context object type.\n * @param context - The initial state context.\n * @param fns - An object containing transition function definitions.\n * @returns A new machine instance.\n */\nexport function createMachine<C extends object, T extends Record<string, (this: { context: C } & T, ...args: any[]) => any> & { context?: any }>(\n context: C,\n fns: T\n): { context: C } & T;\n\n/**\n * Creates a synchronous state machine by copying context and transitions from an existing machine.\n * This is useful for creating a new machine with updated context but the same transitions.\n *\n * @template C - The context object type.\n * @template M - The machine type to copy transitions from.\n * @param context - The new context.\n * @param machine - The machine to copy transitions from.\n * @returns A new machine instance with the given context and copied transitions.\n */\nexport function createMachine<C extends object, M extends BaseMachine<C>>(\n context: C,\n machine: M\n): Machine<C, Transitions<M>>;\n\n/**\n * Creates a synchronous state machine from a context and transition functions that expect `this` to be the context object.\n * This is used internally by utilities that need to bind transitions to context objects.\n *\n * @template C - The context object type.\n * @param context - The initial state context.\n * @param fns - An object containing transition function definitions that expect `this` to be the context.\n * @returns A new machine instance.\n */\nexport function createMachine<C extends object, T extends Record<string, (this: C, ...args: any[]) => any>>(\n context: C,\n fns: T\n): Machine<C, T>;\n\nexport function createMachine(context: any, fnsOrFactory: any): any {\n if (typeof fnsOrFactory === 'function') {\n let transitions: any;\n const transition = (newContext: any) => {\n const machine = createMachine(newContext, transitions);\n // Re-bind transitions to the new context\n const boundTransitions = Object.fromEntries(\n Object.entries(transitions).map(([key, fn]) => [\n key,\n (fn as Function).bind(newContext)\n ])\n );\n return Object.assign(machine, boundTransitions);\n };\n transitions = fnsOrFactory(transition);\n\n // Bind transitions to initial context\n const boundTransitions = Object.fromEntries(\n Object.entries(transitions).map(([key, fn]) => [\n key,\n (fn as Function).bind(context)\n ])\n );\n\n return Object.assign({ context }, boundTransitions);\n }\n\n // If fns is a machine (has context property), extract just the transition functions\n const transitions = 'context' in fnsOrFactory ? Object.fromEntries(\n Object.entries(fnsOrFactory).filter(([key]) => key !== 'context')\n ) : fnsOrFactory;\n\n // For normal object transitions, we might also need binding if they use `this`\n // But existing code expects `this` to be the machine (context + transitions).\n // The new API expects `this` to be just context.\n\n const machine = Object.assign({ context }, transitions);\n return machine;\n}\n\n/**\n * Creates an asynchronous state machine from a context and a factory function.\n * This \"Functional Builder\" pattern allows for type-safe transitions without\n * manually passing `this` or `transitions`.\n *\n * @template C - The context object type.\n * @template T - The transitions object type.\n * @param context - The initial state context.\n * @param factory - A function that receives a `transition` helper and returns the transitions object.\n * @returns A new async machine instance.\n */\nexport function createAsyncMachine<C extends object, T extends Record<string, (this: C, ...args: any[]) => any>>(\n context: C,\n factory: (transition: (newContext: C) => AsyncMachine<C, T>) => T\n): AsyncMachine<C, BindTransitions<T>>;\n\n/**\n * Creates an asynchronous state machine by copying context and transitions from an existing machine.\n * This is useful for creating a new machine with updated context but the same transitions.\n *\n * @template C - The context object type.\n * @template M - The machine type to copy transitions from.\n * @param context - The new context.\n * @param machine - The machine to copy transitions from.\n * @returns A new async machine instance with the given context and copied transitions.\n */\nexport function createAsyncMachine<C extends object, M extends BaseMachine<C>>(\n context: C,\n machine: M\n): AsyncMachine<C, Transitions<M>>;\n\n/**\n * Creates an asynchronous state machine from a context and async transition functions.\n *\n * @template C - The context object type.\n * @param context - The initial state context.\n * @param fns - An object containing async transition function definitions.\n * @returns A new async machine instance.\n */\nexport function createAsyncMachine<C extends object, T extends Record<string, (this: C, ...args: any[]) => any>>(\n context: C,\n fns: T\n): AsyncMachine<C, T>;\n\nexport function createAsyncMachine(context: any, fnsOrFactory: any): any {\n if (typeof fnsOrFactory === 'function') {\n let transitions: any;\n const transition = (newContext: any) => {\n const machine = createAsyncMachine(newContext, transitions);\n // Re-bind transitions to the new context\n const boundTransitions = Object.fromEntries(\n Object.entries(transitions).map(([key, fn]) => [\n key,\n (fn as Function).bind(newContext)\n ])\n );\n return Object.assign(machine, boundTransitions);\n };\n transitions = fnsOrFactory(transition);\n\n // Bind transitions to initial context\n const boundTransitions = Object.fromEntries(\n Object.entries(transitions).map(([key, fn]) => [\n key,\n (fn as Function).bind(context)\n ])\n );\n\n return Object.assign({ context }, boundTransitions);\n }\n\n // If fns is a machine (has context property), extract just the transition functions\n const transitions = 'context' in fnsOrFactory ? Object.fromEntries(\n Object.entries(fnsOrFactory).filter(([key]) => key !== 'context')\n ) : fnsOrFactory;\n\n const machine = Object.assign({ context }, transitions);\n return machine;\n}\n\n/**\n * Creates a machine factory - a higher-order function that simplifies machine creation.\n * Instead of writing transition logic that creates new machines, you just write\n * pure context transformation functions.\n *\n * @template C - The context object type.\n * @returns A factory configurator function.\n *\n * @example\n * const counterFactory = createMachineFactory<{ count: number }>()({\n * increment: (ctx) => ({ count: ctx.count + 1 }),\n * add: (ctx, n: number) => ({ count: ctx.count + n })\n * });\n *\n * const counter = counterFactory({ count: 0 });\n * const next = counter.increment(); // Returns new machine with count: 1\n */\nexport function createMachineFactory<C extends object>() {\n return <T extends Record<string, (ctx: C, ...args: any[]) => C>>(\n transformers: T\n ) => {\n type MachineFns = {\n [K in keyof T]: (\n this: Machine<C>,\n ...args: T[K] extends (ctx: C, ...args: infer A) => C ? A : never\n ) => MaybePromise<Machine<C>>;\n };\n\n const fns = Object.fromEntries(\n Object.entries(transformers).map(([key, transform]) => [\n key,\n function (this: Machine<C>, ...args: any[]) {\n const newContext = (transform as any)(this.context, ...args);\n return createMachine(newContext, fns as any);\n },\n ])\n ) as MachineFns;\n\n return (initialContext: C): Machine<C> & MachineFns => {\n return createMachine(initialContext, fns);\n };\n };\n}\n\n\n// =============================================================================\n// SECTION: ADVANCED CREATION & IMMUTABLE HELPERS\n// =============================================================================\n\n/**\n * Creates a new machine instance with an updated context, preserving all original transitions.\n * This is the primary, type-safe utility for applying state changes.\n *\n * @template M - The machine type.\n * @param machine - The original machine instance.\n * @param newContextOrFn - The new context object or an updater function.\n * @returns A new machine instance of the same type with the updated context.\n */\nexport function setContext<M extends Machine<any>>(\n machine: M,\n newContextOrFn: Context<M> | ((ctx: Readonly<Context<M>>) => Context<M>)\n): M {\n const { context, ...transitions } = machine;\n const newContext =\n typeof newContextOrFn === \"function\"\n ? (newContextOrFn as (ctx: Readonly<Context<M>>) => Context<M>)(context)\n : newContextOrFn;\n\n return createMachine(newContext, transitions as any) as M;\n}\n\n/**\n * Creates a minimal machine-like object with just a context property.\n * Useful for creating test fixtures and working with pattern matching utilities.\n *\n * @template C - The context type\n * @param context - The context object\n * @returns An object with a readonly context property\n *\n * @example\n * ```typescript\n * // For testing with discriminated unions\n * type FetchContext =\n * | { status: 'idle' }\n * | { status: 'success'; data: string };\n *\n * const idleMachine = createContext<FetchContext>({ status: 'idle' });\n * const successMachine = createContext<FetchContext>({ status: 'success', data: 'result' });\n *\n * // Works with pattern matching\n * const match = createMatcher(\n * discriminantCase('idle', 'status', 'idle'),\n * discriminantCase('success', 'status', 'success')\n * );\n *\n * if (match.is.success(successMachine)) {\n * console.log(successMachine.context.data); // TypeScript knows data exists\n * }\n * ```\n */\nexport function createContext<C extends object>(\n context: C\n): { readonly context: C } {\n return { context };\n}\n\n/**\n * Creates a new machine by overriding or adding transition functions to an existing machine.\n * Ideal for mocking in tests or decorating functionality. The original machine is unchanged.\n *\n * @template M - The original machine type.\n * @template T - An object of new or overriding transition functions.\n * @param machine - The base machine instance.\n * @param overrides - An object containing the transitions to add or overwrite.\n * @returns A new machine instance with the merged transitions.\n */\nexport function overrideTransitions<\n M extends Machine<any>,\n T extends Record<string, (this: Context<M>, ...args: any[]) => any>\n>(\n machine: M,\n overrides: T\n): Machine<Context<M>> & Omit<Transitions<M>, keyof T> & T {\n const { context, ...originalTransitions } = machine;\n const newTransitions = { ...originalTransitions, ...overrides };\n return createMachine(context, newTransitions as any) as any;\n}\n\n/**\n * Creates a new machine by adding new transition functions.\n * This utility will produce a compile-time error if you attempt to add a\n * transition that already exists, preventing accidental overrides.\n *\n * @template M - The original machine type.\n * @template T - An object of new transition functions, whose keys must not exist in M.\n * @param machine - The base machine instance.\n * @param newTransitions - An object containing the new transitions to add.\n * @returns A new machine instance with the combined original and new transitions.\n */\nexport function extendTransitions<\n M extends Machine<any>,\n T extends Record<string, (this: Context<M>, ...args: any[]) => any> & {\n [K in keyof T]: K extends keyof M ? never : T[K];\n }\n>(machine: M, newTransitions: T): M & T {\n const { context, ...originalTransitions } = machine;\n const combinedTransitions = { ...originalTransitions, ...newTransitions };\n return createMachine(context, combinedTransitions as any) as M & T;\n}\n\n/**\n * Combines two machine factories into a single factory that creates machines with merged context and transitions.\n * This allows you to compose independent state machines that operate on different parts of the same context.\n *\n * The resulting factory takes the parameters of the first factory, while the second factory is called with no arguments.\n * Context properties are merged (second factory's context takes precedence on conflicts).\n * Transition names must not conflict between the two machines.\n *\n * @template F1 - The first factory function type.\n * @template F2 - The second factory function type.\n * @param factory1 - The first machine factory (provides parameters and primary context).\n * @param factory2 - The second machine factory (provides additional context and transitions).\n * @returns A new factory function that creates combined machines.\n *\n * @example\n * ```typescript\n * // Define two independent machines\n * const createCounter = (initial: number) =>\n * createMachine({ count: initial }, {\n * increment: function() { return createMachine({ count: this.count + 1 }, this); },\n * decrement: function() { return createMachine({ count: this.count - 1 }, this); }\n * });\n *\n * const createLogger = () =>\n * createMachine({ logs: [] as string[] }, {\n * log: function(message: string) {\n * return createMachine({ logs: [...this.logs, message] }, this);\n * },\n * clear: function() {\n * return createMachine({ logs: [] }, this);\n * }\n * });\n *\n * // Combine them\n * const createCounterWithLogging = combineFactories(createCounter, createLogger);\n *\n * // Use the combined factory\n * const machine = createCounterWithLogging(5); // { count: 5, logs: [] }\n * const incremented = machine.increment(); // { count: 6, logs: [] }\n * const logged = incremented.log(\"Count incremented\"); // { count: 6, logs: [\"Count incremented\"] }\n * ```\n */\nexport function combineFactories<\n F1 extends (...args: any[]) => Machine<any>,\n F2 extends () => Machine<any>\n>(\n factory1: F1,\n factory2: F2\n): (\n ...args: Parameters<F1>\n) => Machine<Context<ReturnType<F1>> & Context<ReturnType<F2>>> &\n Omit<ReturnType<F1>, 'context'> &\n Omit<ReturnType<F2>, 'context'> {\n return (...args: Parameters<F1>) => {\n // Create instances from both factories\n const machine1 = factory1(...args);\n const machine2 = factory2();\n\n // Merge contexts (machine2 takes precedence on conflicts)\n const combinedContext = { ...machine1.context, ...machine2.context };\n\n // Extract transitions from both machines\n const { context: _, ...transitions1 } = machine1;\n const { context: __, ...transitions2 } = machine2;\n\n // Combine transitions (TypeScript will catch conflicts at compile time)\n const combinedTransitions = { ...transitions1, ...transitions2 };\n\n // Create the combined machine\n return createMachine(combinedContext, combinedTransitions as any) as any;\n };\n}\n\n/**\n * Creates a builder function from a \"template\" machine instance.\n * This captures the behavior of a machine and returns a factory that can stamp out\n * new instances with different initial contexts. Excellent for class-based machines.\n *\n * @template M - The machine type.\n * @param templateMachine - An instance of a machine to use as the template.\n * @returns A function that builds new machines of type M.\n */\nexport function createMachineBuilder<M extends Machine<any>>(\n templateMachine: M\n): (context: Context<M>) => M {\n const { context, ...transitions } = templateMachine;\n return (newContext: Context<M>): M => {\n return createMachine(newContext, transitions as any) as M;\n };\n}\n\n/**\n * Pattern match on a machine's state based on a discriminant property in the context.\n * This provides type-safe exhaustive matching for state machines.\n *\n * @template M - The machine type.\n * @template K - The discriminant key in the context.\n * @template R - The return type.\n * @param machine - The machine to match against.\n * @param discriminantKey - The key in the context to use for matching (e.g., \"status\").\n * @param handlers - An object mapping each possible value to a handler function.\n * @returns The result of the matched handler.\n *\n * @example\n * const result = matchMachine(\n * machine,\n * 'status',\n * {\n * idle: (ctx) => \"Machine is idle\",\n * loading: (ctx) => \"Loading...\",\n * success: (ctx) => `Success: ${ctx.data}`,\n * error: (ctx) => `Error: ${ctx.error}`\n * }\n * );\n */\nexport function matchMachine<\n M extends Machine<any>,\n K extends keyof Context<M> & string,\n R\n>(\n machine: M,\n discriminantKey: K,\n handlers: {\n [V in Context<M>[K] & string]: (ctx: Context<M>) => R;\n }\n): R {\n const discriminant = machine.context[discriminantKey] as Context<M>[K] & string;\n const handler = handlers[discriminant];\n if (!handler) {\n throw new Error(`No handler found for state: ${String(discriminant)}`);\n }\n return handler(machine.context);\n}\n\n/**\n * Type-safe helper to assert that a machine's context has a specific discriminant value.\n * This narrows the type of the context based on the discriminant, properly handling\n * discriminated unions.\n *\n * @template M - The machine type.\n * @template K - The discriminant key.\n * @template V - The discriminant value.\n * @param machine - The machine to check.\n * @param key - The discriminant key to check.\n * @param value - The expected value.\n * @returns True if the discriminant matches, with type narrowing.\n *\n * @example\n * type Context = { status: 'idle' } | { status: 'loading' } | { status: 'success'; data: string };\n * const machine = createMachine<Context>({ status: 'success', data: 'test' }, {});\n *\n * if (hasState(machine, 'status', 'success')) {\n * // machine.context is narrowed to { status: 'success'; data: string }\n * console.log(machine.context.data); // ✓ TypeScript knows about 'data'\n * }\n */\nexport function hasState<\n M extends Machine<any>,\n K extends keyof Context<M>,\n V extends Context<M>[K]\n>(\n machine: M,\n key: K,\n value: V\n): machine is M & { context: Extract<Context<M>, { [P in K]: V }> } {\n return machine.context[key] === value;\n}\n\n\n// =============================================================================\n// SECTION: RUNTIME & EVENT DISPATCHER\n// =============================================================================\n\n/**\n * Runs an asynchronous state machine with a managed lifecycle and event dispatch capability.\n * This is the \"interpreter\" for async machines, handling state updates and side effects.\n * Provides automatic AbortController management to prevent async race conditions.\n *\n * @template M - The initial machine type.\n * @param initial - The initial machine state.\n * @param onChange - Optional callback invoked with the new machine state after every transition.\n * @returns An object with a `state` getter for the current context, an async `dispatch` function, and a `stop` method.\n */\nexport function runMachine<M extends AsyncMachine<any>>(\n initial: M,\n onChange?: (m: M) => void\n) {\n let current = initial;\n // Keep track of the controller for the currently-running async transition.\n let activeController: AbortController | null = null;\n\n async function dispatch<E extends Event<typeof current>>(event: E): Promise<M> {\n // 1. If an async transition is already in progress, cancel it.\n if (activeController) {\n activeController.abort();\n activeController = null;\n }\n\n const fn = (current as any)[event.type];\n if (typeof fn !== 'function') {\n throw new Error(`[Machine] Unknown event type '${String(event.type)}' on current state.`);\n }\n\n // 2. Create a new AbortController for this new transition.\n const controller = new AbortController();\n activeController = controller;\n\n try {\n // 3. Pass the signal to the transition function.\n const nextStatePromise = fn.apply(current.context, [...event.args, { signal: controller.signal }]);\n\n const nextState = await nextStatePromise;\n\n // 4. If this promise resolved but has since been aborted, do not update state.\n // This prevents the race condition.\n if (controller.signal.aborted) {\n // Return the *current* state, as if the transition never completed.\n return current;\n }\n\n current = nextState;\n onChange?.(current);\n return current;\n\n } finally {\n // 5. Clean up the controller once the transition is complete (resolved or rejected).\n // Only clear it if it's still the active one.\n if (activeController === controller) {\n activeController = null;\n }\n }\n }\n\n return {\n /** Gets the context of the current state of the machine. */\n get state(): Context<M> {\n return current.context;\n },\n /** Dispatches a type-safe event to the machine, triggering a transition. */\n dispatch,\n /** Stops any pending async operation and cleans up resources. */\n stop: () => {\n if (activeController) {\n activeController.abort();\n activeController = null;\n }\n },\n };\n}\n\n/**\n * An optional base class for creating machines using an Object-Oriented style.\n *\n * This class provides the fundamental structure required by the library: a `context`\n * property to hold the state. By extending `MachineBase`, you get a clear and\n * type-safe starting point for defining states and transitions as classes and methods.\n *\n * Transitions should be implemented as methods that return a new instance of a\n * state machine class (often `new MyClass(...)` or by using a `createMachineBuilder`).\n * The `context` is marked `readonly` to enforce the immutable update pattern.\n *\n * @template C - The context object type that defines the state for this machine.\n *\n * @example\n * // Define a simple counter state\n * class Counter extends MachineBase<{ readonly count: number }> {\n * constructor(count = 0) {\n * super({ count });\n * }\n *\n * increment(): Counter {\n * // Return a new instance for the next state\n * return new Counter(this.context.count + 1);\n * }\n *\n * add(n: number): Counter {\n * return new Counter(this.context.count + n);\n * }\n * }\n *\n * const machine = new Counter(5);\n * const nextState = machine.increment(); // Returns a new Counter instance\n *\n * console.log(machine.context.count); // 5 (original is unchanged)\n * console.log(nextState.context.count); // 6 (new state)\n */\nexport class MachineBase<C extends object> {\n /**\n * The immutable state of the machine.\n * To change the state, a transition method must return a new machine instance\n * with a new context object.\n */\n public readonly context: C;\n\n /**\n * Initializes a new machine instance with its starting context.\n * @param context - The initial state of the machine.\n */\n constructor(context: C) {\n this.context = context;\n // Object.freeze can provide additional runtime safety against accidental mutation,\n // though it comes with a minor performance cost. It's a good practice for ensuring purity.\n // Object.freeze(this.context);\n }\n}\n\n\n/**\n * Applies an update function to a machine's context, returning a new machine.\n * This is a simpler alternative to `setContext` when you always use an updater function.\n *\n * @template C - The context object type.\n * @param m - The machine to update.\n * @param update - A function that takes the current context and returns the new context.\n * @returns A new machine with the updated context.\n *\n * @example\n * const updated = next(counter, (ctx) => ({ count: ctx.count + 1 }));\n */\nexport function next<C extends object>(\n m: Machine<C>,\n update: (ctx: Readonly<C>) => C\n): Machine<C> {\n const { context, ...transitions } = m;\n return createMachine(update(context), transitions as any) as Machine<C>;\n}\n\n/**\n * A type representing either a synchronous Machine or a Promise that resolves to a Machine.\n * Useful for functions that can return either sync or async machines.\n *\n * @template C - The context object type.\n *\n * @example\n * function getMachine(): MachineLike<{ count: number }> {\n * if (Math.random() > 0.5) {\n * return createMachine({ count: 0 }, { ... });\n * } else {\n * return Promise.resolve(createMachine({ count: 0 }, { ... }));\n * }\n * }\n */\nexport type MachineLike<C extends object> =\n | Machine<C>\n | Promise<Machine<C>>;\n\n/**\n * A type representing the result of a machine transition.\n * Can be either:\n * - A new machine state\n * - A tuple of [machine, cleanup function] where cleanup is called when leaving the state\n *\n * This enables state machines with side effects that need cleanup (e.g., subscriptions, timers).\n *\n * @template C - The context object type.\n *\n * @example\n * function transition(): MachineResult<{ count: number }> {\n * const interval = setInterval(() => console.log(\"tick\"), 1000);\n * const machine = createMachine({ count: 0 }, { ... });\n * return [machine, () => clearInterval(interval)];\n * }\n */\nexport type MachineResult<C extends object> =\n | Machine<C>\n | [Machine<C>, () => void | Promise<void>];\n\n\n// =============================================================================\n// SECTION: GENERATOR-BASED COMPOSITION\n// =============================================================================\n\nexport {\n run,\n step,\n yieldMachine,\n runSequence,\n createFlow,\n runWithDebug,\n runAsync,\n stepAsync\n} from './generators';\n\n// =============================================================================\n// SECTION: TYPE-LEVEL METADATA PRIMITIVES\n// =============================================================================\n\nexport {\n transitionTo,\n describe,\n guarded,\n guard,\n guardAsync,\n whenGuard,\n whenGuardAsync,\n invoke,\n action,\n metadata,\n META_KEY,\n type TransitionMeta,\n type GuardMeta,\n type InvokeMeta,\n type ActionMeta,\n type ClassConstructor,\n type WithMeta,\n type GuardOptions,\n type GuardFallback,\n type GuardedTransition\n} from './primitives';\n\n// =============================================================================\n// SECTION: STATECHART EXTRACTION (Build-time only)\n// =============================================================================\n\n// Note: Extraction tools are available as dev dependencies for build-time use\n// They are not included in the runtime bundle for size optimization\n// Use: npx tsx scripts/extract-statechart.ts\n\nexport type {\n MachineConfig,\n ExtractionConfig,\n ParallelRegionConfig,\n ChildStatesConfig\n} from './extract';\n\n// Note: Extraction functions (extractMachine, extractMachines, generateChart) are NOT exported\n// to keep them out of the runtime bundle. Use the CLI tool or import directly from the source\n// file for build-time statechart generation.\n\nexport * from './multi'\n\nexport * from './higher-order'\n\n// =============================================================================\n// SECTION: MIDDLEWARE & INTERCEPTION\n// =============================================================================\n\nexport * from './middleware/index';\n\nexport * from './mixins';\n\n// =============================================================================\n// SECTION: UTILITIES & HELPERS\n// =============================================================================\n\nexport {\n isState,\n createEvent,\n createTransition,\n mergeContext,\n pipeTransitions,\n logState,\n call,\n bindTransitions,\n BoundMachine\n} from './utils';\n\n// =============================================================================\n// SECTION: FUNCTIONAL COMBINATORS\n// =============================================================================\n\nexport {\n createTransitionFactory,\n createTransitionExtender,\n createFunctionalMachine,\n state\n} from './functional-combinators';\n\n// =============================================================================\n// SECTION: PATTERN MATCHING\n// =============================================================================\n\nexport {\n createMatcher,\n classCase,\n discriminantCase,\n customCase,\n forContext,\n type MatcherCase,\n type CasesToMapping,\n type MatcherUnion,\n type CaseNames,\n type CaseHandler,\n type ExhaustivenessMarker,\n type IsExhaustive,\n type WhenBuilder,\n type Matcher\n} from './matcher';\n\n// =============================================================================\n// SECTION: ACTOR MODEL\n// =============================================================================\n\nexport {\n Actor,\n createActor,\n spawn,\n fromPromise,\n fromObservable,\n type ActorRef,\n type InspectionEvent\n} from './actor';"],
5
- "mappings": ";AAuHO,SAAS,IACd,MACA,SACG;AAEH,QAAM,YAAY,KAAK,OAAO;AAG9B,MAAI,UAAU;AAGd,SAAO,MAAM;AAGX,UAAM,EAAE,OAAO,KAAK,IAAI,UAAU,KAAK,OAAO;AAG9C,QAAI,MAAM;AACR,aAAO;AAAA,IACT;AAIA,cAAU;AAAA,EACZ;AACF;AAuDO,SAAS,KACd,GACoB;AAKpB,SAAQ,aAAa;AACnB,UAAM,WAAW,MAAM;AACvB,WAAO;AAAA,EACT,EAAG;AACL;AAqBO,SAAS,aAAmG,GAAS;AAC1H,SAAO;AACT;AA4BO,SAAS,YACd,SACA,OACG;AACH,SAAO,MAAM,OAAO,CAAC,SAAS,SAAS;AACrC,WAAO,IAAI,MAAM,OAAO;AAAA,EAC1B,GAAG,OAAO;AACZ;AA6BO,SAAS,WACd,MAC8B;AAC9B,SAAO;AACT;AA6BO,SAAS,aACd,MACA,SACA,SAA6C,CAACA,OAAM,MAAM;AACxD,UAAQ,IAAI,QAAQA,KAAI,KAAK,E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A,UACA;AACA,MAAI,UAAU;AAEd,MAAI,mBAA2C;AAE/C,iBAAe,SAA0C,OAAsB;AAE7E,QAAI,kBAAkB;AACpB,uBAAiB,MAAM;AACvB,yBAAmB;AAAA,IACrB;AAEA,UAAM,KAAM,QAAgB,MAAM,IAAI;AACtC,QAAI,OAAO,OAAO,YAAY;AAC5B,YAAM,IAAI,MAAM,iCAAiC,OAAO,MAAM,IAAI,CAAC,qBAAqB;AAAA,IAC1F;AAGA,UAAM,aAAa,IAAI,gBAAgB;AACvC,uBAAmB;AAEnB,QAAI;AAEF,YAAM,mBAAmB,GAAG,MAAM,QAAQ,SAAS,CAAC,GAAG,MAAM,MAAM,EAAE,QAAQ,WAAW,OAAO,CAAC,CAAC;AAEjG,YAAM,YAAY,MAAM;AAIxB,UAAI,WAAW,OAAO,SAAS;AAE7B,eAAO;AAAA,MACT;AAEA,gBAAU;AACV,2CAAW;AACX,aAAO;AAAA,IAET,UAAE;AAGA,UAAI,qBAAqB,YAAY;AACnC,2BAAmB;AAAA,MACrB;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AAAA;AAAA,IAEL,IAAI,QAAoB;AACtB,aAAO,QAAQ;AAAA,IACjB;AAAA;AAAA,IAEA;AAAA;AAAA,IAEA,MAAM,MAAM;AACV,UAAI,kBAAkB;AACpB,yBAAiB,MAAM;AACvB,2BAAmB;AAAA,MACrB;AAAA,IACF;AAAA,EACF;AACF;AAsCO,IAAM,cAAN,MAAoC;AAAA;AAAA;AAAA;AAAA;AAAA,EAYzC,YAAY,SAAY;AACtB,SAAK,UAAU;AAAA,EAIjB;AACF;AAeO,SAAS,KACd,GACA,QACY;AACZ,QAAM,EAAE,SAAS,GAAG,YAAY,IAAI;AACpC,SAAO,cAAc,OAAO,OAAO,GAAG,WAAkB;AAC1D;",
6
- "names": ["step", "metadata", "guard", "action", "guarded", "action", "machine", "prop", "value", "createTransition", "transitions", "machine", "boundTransitions"]
4
+ "sourcesContent": ["/**\n * @file Generator-based state machine composition utilities.\n * @description\n * This module provides a generator-based approach to composing state machine transitions.\n * Instead of chaining method calls or using composition functions, you can write\n * imperative-style code using generators that feels like sequential, synchronous code\n * while maintaining the immutability and type safety of the state machine model.\n *\n * This pattern is particularly useful for:\n * - Multi-step workflows where each step depends on the previous\n * - Complex transition logic that would be unwieldy with chaining\n * - When you want imperative control flow (if/else, loops) with immutable state\n * - Testing scenarios where you want to control the flow step-by-step\n *\n * @example\n * ```typescript\n * const result = run(function* (machine) {\n * // Each yield passes control back and receives the next state\n * let m = yield* step(machine.increment());\n * m = yield* step(m.add(5));\n * if (m.context.count > 10) {\n * m = yield* step(m.reset());\n * }\n * return m.context.count;\n * }, initialMachine);\n * ```\n */\n\n\n\n/**\n * Runs a generator-based state machine flow to completion.\n *\n * This function executes a generator that yields machine states and returns a final value.\n * Each yield passes the current machine state back to the generator, allowing you to\n * write imperative-style code while maintaining immutability.\n *\n * **How it works:**\n * 1. The generator function receives the initial machine\n * 2. Each `yield` expression produces a new machine state\n * 3. That state is sent back into the generator via `next()`\n * 4. The generator can use the received state for the next operation\n * 5. When the generator returns, that value is returned from `run()`\n *\n * **Key insight:** The generator doesn't mutate state—it yields new immutable states\n * at each step, creating a clear audit trail of state transitions.\n *\n * @template C - The context object type for the machine.\n * @template T - The return type of the generator (can be any type).\n *\n * @param flow - A generator function that receives a machine and yields machines,\n * eventually returning a value of type T.\n * @param initial - The initial machine state to start the flow.\n *\n * @returns The final value returned by the generator.\n *\n * @example Basic usage with counter\n * ```typescript\n * const counter = createMachine({ count: 0 }, {\n * increment: function() {\n * return createMachine({ count: this.context.count + 1 }, this);\n * },\n * add: function(n: number) {\n * return createMachine({ count: this.context.count + n }, this);\n * }\n * });\n *\n * const finalCount = run(function* (m) {\n * m = yield* step(m.increment()); // count: 1\n * m = yield* step(m.add(5)); // count: 6\n * m = yield* step(m.increment()); // count: 7\n * return m.context.count;\n * }, counter);\n *\n * console.log(finalCount); // 7\n * ```\n *\n * @example Conditional logic\n * ```typescript\n * const result = run(function* (m) {\n * m = yield* step(m.increment());\n *\n * if (m.context.count > 5) {\n * m = yield* step(m.reset());\n * } else {\n * m = yield* step(m.add(10));\n * }\n *\n * return m;\n * }, counter);\n * ```\n *\n * @example Loops and accumulation\n * ```typescript\n * const sum = run(function* (m) {\n * let total = 0;\n *\n * for (let i = 0; i < 5; i++) {\n * m = yield* step(m.increment());\n * total += m.context.count;\n * }\n *\n * return total;\n * }, counter);\n * ```\n *\n * @example Error handling\n * ```typescript\n * const result = run(function* (m) {\n * try {\n * m = yield* step(m.riskyOperation());\n * m = yield* step(m.processResult());\n * } catch (error) {\n * m = yield* step(m.handleError(error));\n * }\n * return m;\n * }, machine);\n * ```\n */\nexport function run<C extends any = any, M extends { context: C } & Record<string, any> = { context: C }, T = any>(\n flow: (m: M) => Generator<M, T, M>,\n initial: M\n): T {\n // Create the generator by calling the flow function with the initial machine\n const generator = flow(initial);\n\n // Track the current machine state as we iterate\n let current = initial;\n\n // Iterate the generator until completion\n while (true) {\n // Send the current machine state into the generator and get the next yielded value\n // The generator receives `current` as the result of its last yield expression\n const { value, done } = generator.next(current);\n\n // If the generator has returned (done), we have our final value\n if (done) {\n return value as T;\n }\n\n // Otherwise, the yielded value becomes our new current state\n // This state will be sent back into the generator on the next iteration\n current = value as M;\n }\n}\n\n/**\n * A helper function to yield a machine state and receive the next state back.\n *\n * This function creates a mini-generator that yields the provided machine and\n * returns whatever value the outer runner sends back. It's designed to be used\n * with `yield*` (yield delegation) inside your main generator.\n *\n * **Why use this helper?**\n * - Makes the intent clear: \"step to this state\"\n * - Provides a consistent API for state transitions\n * - Enables type inference for the received state\n * - Works seamlessly with the `run()` function\n *\n * **What `yield*` does:**\n * `yield*` delegates to another generator. When you write `yield* step(m)`,\n * control passes to the `step` generator, which yields `m`, then returns the\n * value sent back by the runner.\n *\n * @template C - The context object type for the machine.\n *\n * @param m - The machine state to yield.\n *\n * @returns A generator that yields the machine and returns the received state.\n *\n * @example Basic stepping\n * ```typescript\n * run(function* (machine) {\n * // Yield this state and receive the next one\n * const next = yield* step(machine.increment());\n * console.log(next.context.count);\n * return next;\n * }, counter);\n * ```\n *\n * @example Without step (more verbose)\n * ```typescript\n * run(function* (machine) {\n * // This is what step() does internally\n * const next = yield machine.increment();\n * return next;\n * }, counter);\n * ```\n *\n * @example Chaining with step\n * ```typescript\n * run(function* (m) {\n * m = yield* step(m.action1());\n * m = yield* step(m.action2());\n * m = yield* step(m.action3());\n * return m;\n * }, machine);\n * ```\n */\nexport function step<C extends any = any, M extends { context: C } & Record<string, any> = { context: C }>(\n m: M\n): Generator<M, M, M> {\n // Create an immediately-invoked generator that:\n // 1. Yields the provided machine\n // 2. Receives a value back (the next state)\n // 3. Returns that received value\n return (function* () {\n const received = yield m;\n return received;\n })();\n}\n\n/**\n * Alternative to `step` that doesn't require `yield*`.\n * This is semantically identical but uses direct yielding.\n *\n * Use this if you prefer the simpler syntax without delegation.\n *\n * @template C - The context object type.\n * @param m - The machine to yield.\n * @returns The same machine (passed through).\n *\n * @example\n * ```typescript\n * run(function* (m) {\n * m = yield m.increment(); // No yield* needed\n * m = yield m.add(5);\n * return m;\n * }, counter);\n * ```\n */\nexport function yieldMachine<C extends any = any, M extends { context: C } & Record<string, any> = { context: C }>(m: M): M {\n return m;\n}\n\n/**\n * Runs multiple generator flows in sequence, passing the result of each to the next.\n *\n * This is useful for composing multiple generator-based workflows into a pipeline.\n *\n * @template C - The context object type.\n * @param initial - The initial machine state.\n * @param flows - An array of generator functions to run in sequence.\n * @returns The final machine state after all flows complete.\n *\n * @example\n * ```typescript\n * const flow1 = function* (m: Machine<{ count: number }>) {\n * m = yield* step(m.increment());\n * return m;\n * };\n *\n * const flow2 = function* (m: Machine<{ count: number }>) {\n * m = yield* step(m.add(5));\n * return m;\n * };\n *\n * const result = runSequence(counter, [flow1, flow2]);\n * console.log(result.context.count); // 6\n * ```\n */\nexport function runSequence<C extends any = any, M extends { context: C } & Record<string, any> = { context: C }>(\n initial: M,\n flows: Array<(m: M) => Generator<M, M, M>>\n): M {\n return flows.reduce((machine, flow) => {\n return run(flow, machine);\n }, initial);\n}\n\n/**\n * Creates a reusable generator flow that can be composed into other flows.\n *\n * This allows you to define common state machine patterns as reusable building blocks.\n *\n * @template C - The context object type.\n * @param flow - A generator function representing a reusable flow.\n * @returns A function that can be used with `yield*` in other generators.\n *\n * @example\n * ```typescript\n * // Define a reusable flow\n * const incrementThrice = createFlow(function* (m: Machine<{ count: number }>) {\n * m = yield* step(m.increment());\n * m = yield* step(m.increment());\n * m = yield* step(m.increment());\n * return m;\n * });\n *\n * // Use it in another flow\n * const result = run(function* (m) {\n * m = yield* incrementThrice(m);\n * m = yield* step(m.add(10));\n * return m;\n * }, counter);\n * ```\n */\nexport function createFlow<C extends any = any, M extends { context: C } & Record<string, any> = { context: C }>(\n flow: (m: M) => Generator<M, M, M>\n): (m: M) => Generator<M, M, M> {\n return flow;\n}\n\n/**\n * Runs a generator flow with debugging output at each step.\n *\n * This is useful for understanding the state transitions in your flow.\n *\n * @template C - The context object type.\n * @template T - The return type.\n * @param flow - The generator function to run.\n * @param initial - The initial machine state.\n * @param logger - Optional custom logger function.\n * @returns The final value from the generator.\n *\n * @example\n * ```typescript\n * const result = runWithDebug(function* (m) {\n * m = yield* step(m.increment());\n * m = yield* step(m.add(5));\n * return m.context.count;\n * }, counter);\n *\n * // Output:\n * // Step 0: { count: 0 }\n * // Step 1: { count: 1 }\n * // Step 2: { count: 6 }\n * // Final: 6\n * ```\n */\nexport function runWithDebug<C extends any = any, M extends { context: C } & Record<string, any> = { context: C }, T = any>(\n flow: (m: M) => Generator<M, T, M>,\n initial: M,\n logger: (step: number, machine: M) => void = (step, m) => {\n console.log(`Step ${step}:`, m.context);\n }\n): T {\n const generator = flow(initial);\n let current = initial;\n let stepCount = 0;\n\n logger(stepCount, current);\n\n while (true) {\n const { value, done } = generator.next(current);\n\n if (done) {\n console.log('Final:', value);\n return value as T;\n }\n\n current = value as M;\n stepCount++;\n logger(stepCount, current);\n }\n}\n\n// =============================================================================\n// ASYNC GENERATOR SUPPORT\n// =============================================================================\n\n/**\n * Async version of `run` for async state machines.\n *\n * This allows you to use async/await inside your generator flows while maintaining\n * the same compositional benefits.\n *\n * @template C - The context object type.\n * @template T - The return type.\n * @param flow - An async generator function.\n * @param initial - The initial machine state.\n * @returns A promise that resolves to the final value.\n *\n * @example\n * ```typescript\n * const result = await runAsync(async function* (m) {\n * m = yield* stepAsync(await m.fetchData());\n * m = yield* stepAsync(await m.processData());\n * return m.context;\n * }, asyncMachine);\n * ```\n */\nexport async function runAsync<C extends any = any, M extends { context: C } & Record<string, any> = { context: C }, T = any>(\n flow: (m: M) => AsyncGenerator<M, T, M>,\n initial: M\n): Promise<T> {\n const generator = flow(initial);\n let current = initial;\n\n while (true) {\n const { value, done } = await generator.next(current);\n\n if (done) {\n return value as T;\n }\n\n current = value as M;\n }\n}\n\n/**\n * Async version of `step` for async generators.\n *\n * @template C - The context object type.\n * @param m - The machine to yield.\n * @returns An async generator.\n *\n * @example\n * ```typescript\n * await runAsync(async function* (m) {\n * m = yield* stepAsync(await m.asyncOperation());\n * return m;\n * }, machine);\n * ```\n */\nexport async function* stepAsync<C extends any = any, M extends { context: C } & Record<string, any> = { context: C }>(\n m: M\n): AsyncGenerator<M, M, M> {\n const received = yield m;\n return received;\n}\n", "/**\n * @file Type-level primitives for formal state machine verification.\n * @description\n * This file provides a Domain Specific Language (DSL) of wrapper functions.\n * These functions serve two purposes:\n * 1. At Runtime: They are identity functions (no-ops). They return your code exactly as is.\n * 2. At Design/Build Time: They \"brand\" your transition functions with rich type metadata.\n *\n * This allows a static analysis tool (like `ts-morph`) to read your source code\n * and generate a formal Statechart (JSON) that perfectly matches your implementation,\n * including resolving Class Constructors to their names.\n */\n\n// =============================================================================\n// SECTION: CORE METADATA TYPES\n// =============================================================================\n\n/**\n * Options passed to async transition functions, including cancellation support.\n */\nexport interface TransitionOptions {\n /** AbortSignal for cancelling long-running async operations. */\n signal: AbortSignal;\n}\n\n/**\n * A unique symbol used to \"brand\" a type with metadata.\n * This key allows the static analyzer to find the metadata within a complex type signature.\n */\nexport const META_KEY = Symbol(\"MachineMeta\");\n\n/**\n * Runtime metadata symbol.\n/**\n * Non-enumerable property key for storing metadata on function objects at runtime.\n * @internal\n */\nexport const RUNTIME_META = Symbol('__machine_runtime_meta__');\n\n/**\n * Local definition of Machine type to avoid circular imports.\n * @internal\n */\ntype Machine<C extends object> = {\n readonly context: C;\n} & Record<string, (...args: any[]) => Machine<any>>;\n\n/**\n * Helper type representing a Class Constructor.\n * Used to reference target states by their class definition rather than magic strings.\n */\nexport type ClassConstructor = new (...args: any[]) => any;\n\n/**\n * Metadata describing a Guard condition.\n */\nexport interface GuardMeta {\n /** The name of the guard (e.g., \"isAdmin\"). */\n name: string;\n /** Optional documentation explaining the logic. */\n description?: string;\n}\n\n/**\n * Metadata describing an Invoked Service (async operation).\n */\nexport interface InvokeMeta {\n /** The name of the service source (e.g., \"fetchUserData\"). */\n src: string;\n /** The state class to transition to on success. */\n onDone: ClassConstructor;\n /** The state class to transition to on error. */\n onError: ClassConstructor;\n /** Optional description. */\n description?: string;\n}\n\n/**\n * Metadata describing a generic Action (side effect).\n */\nexport interface ActionMeta {\n /** The name of the action (e.g., \"logAnalytics\"). */\n name: string;\n /** Optional description. */\n description?: string;\n}\n\n/**\n * The comprehensive shape of metadata that can be encoded into a transition's type.\n */\nexport interface TransitionMeta {\n /** The target state class this transition leads to. */\n target?: ClassConstructor;\n /** A human-readable description of the transition. */\n description?: string;\n /** An array of guards that must be true for this transition to be enabled. */\n guards?: GuardMeta[];\n /** A service to invoke upon taking this transition (or entering the state). */\n invoke?: InvokeMeta;\n /** Fire-and-forget side effects associated with this transition. */\n actions?: ActionMeta[];\n}\n\n/**\n * The Branded Type.\n * It takes a function type `F` and intersects it with a hidden metadata object `M`.\n * This is the mechanism that carries information from your code to the compiler API.\n */\nexport type WithMeta<\n F extends (...args: any[]) => any,\n M extends TransitionMeta\n> = F & { [META_KEY]: M };\n\n// =============================================================================\n// SECTION: RUNTIME METADATA ATTACHMENT\n// =============================================================================\n\n/**\n * Runtime metadata interface (resolved class names as strings)\n */\nexport interface RuntimeTransitionMeta {\n target?: string;\n description?: string;\n guards?: Array<{ name: string; description?: string }>;\n invoke?: {\n src: string;\n onDone: string;\n onError: string;\n description?: string;\n };\n actions?: Array<{ name: string; description?: string }>;\n}\n\n/**\n * Attaches runtime metadata to a function object.\n * Merges with existing metadata if present.\n *\n * @param fn - The function to attach metadata to\n * @param metadata - Partial metadata to merge\n * @internal\n */\nfunction attachRuntimeMeta(fn: any, metadata: Partial<RuntimeTransitionMeta>): void {\n // Read existing metadata (may be undefined)\n const existing = fn[RUNTIME_META] || {};\n\n // Shallow merge for simple properties\n const merged: any = { ...existing, ...metadata };\n\n // Deep merge for array properties\n // Prepend new items to preserve order (outer wraps first in call stack)\n if (metadata.guards && existing.guards) {\n merged.guards = [...metadata.guards, ...existing.guards];\n } else if (metadata.guards) {\n merged.guards = [...metadata.guards];\n }\n\n if (metadata.actions && existing.actions) {\n merged.actions = [...metadata.actions, ...existing.actions];\n } else if (metadata.actions) {\n merged.actions = [...metadata.actions];\n }\n\n // Replace invoke entirely (not an array, can't merge)\n // Last invoke wins (this matches XState semantics)\n\n // Define or redefine the metadata property\n Object.defineProperty(fn, RUNTIME_META, {\n value: merged,\n enumerable: false,\n writable: false,\n configurable: true // CRITICAL: Must be configurable for re-definition\n });\n}\n\n// =============================================================================\n// SECTION: ANNOTATION PRIMITIVES (THE DSL)\n// =============================================================================\n\n/**\n * Defines a transition to a target state class.\n *\n * @param target - The Class Constructor of the state being transitioned to.\n * @param implementation - The implementation function returning the new state instance.\n * @returns The implementation function, branded with target metadata.\n *\n * @example\n * login = transitionTo(LoggedInMachine, (user) => new LoggedInMachine({ user }));\n */\nexport function transitionTo<\n T extends ClassConstructor,\n F extends (...args: any[]) => any\n>(\n _target: T,\n implementation: F\n): WithMeta<F, { target: T }> {\n // Attach runtime metadata with class name\n attachRuntimeMeta(implementation, {\n target: _target.name || _target.toString()\n });\n\n return implementation as any;\n}\n\n/**\n * Annotates a transition with a description for documentation generation.\n *\n * @param text - The description text.\n * @param transition - The transition function (or wrapper) to annotate.\n * @example\n * logout = describe(\"Logs the user out\", transitionTo(LoggedOut, ...));\n */\nexport function describe<\n F extends (...args: any[]) => any,\n M extends TransitionMeta\n>(\n _text: string,\n transition: WithMeta<F, M>\n): WithMeta<F, M & { description: string }> {\n // Attach runtime metadata\n attachRuntimeMeta(transition, {\n description: _text\n });\n\n return transition as any;\n}\n\n/**\n * Annotates a transition with a Guard condition.\n * Note: This only adds metadata. You must still implement the `if` check inside your function.\n *\n * @deprecated Use the runtime `guard()` primitive instead. Its `options.description` is used for static analysis.\n * @param guard - Object containing the name and optional description of the guard.\n * @param transition - The transition function to guard.\n * @example\n * delete = guarded({ name: \"isAdmin\" }, transitionTo(Deleted, ...));\n */\nexport function guarded<\n F extends (...args: any[]) => any,\n M extends TransitionMeta\n>(\n guard: GuardMeta,\n transition: WithMeta<F, M>\n): WithMeta<F, M & { guards: [typeof guard] }> {\n // Attach runtime metadata\n // Note: guards is an array, will be merged by attachRuntimeMeta\n attachRuntimeMeta(transition, {\n guards: [guard]\n });\n\n return transition as any;\n}\n\n/**\n * Annotates a transition with an Invoked Service (asynchronous effect).\n *\n * @param service - configuration for the service (source, onDone target, onError target).\n * @param implementation - The async function implementation that receives an AbortSignal.\n * @example\n * load = invoke(\n * { src: \"fetchData\", onDone: LoadedMachine, onError: ErrorMachine },\n * async ({ signal }) => {\n * const response = await fetch('/api/data', { signal });\n * return new LoadedMachine({ data: await response.json() });\n * }\n * );\n */\nexport function invoke<\n D extends ClassConstructor,\n E extends ClassConstructor,\n F extends (options: { signal: AbortSignal }) => any\n>(\n service: { src: string; onDone: D; onError: E; description?: string },\n implementation: F\n): WithMeta<F, { invoke: typeof service }> {\n // Attach runtime metadata with class names resolved\n attachRuntimeMeta(implementation, {\n invoke: {\n src: service.src,\n onDone: service.onDone.name || service.onDone.toString(),\n onError: service.onError.name || service.onError.toString(),\n description: service.description\n }\n });\n\n return implementation as any;\n}\n\n/**\n * Annotates a transition with a side-effect Action.\n * Useful for logging, analytics, or external event firing that doesn't change state structure.\n *\n * @param action - Object containing the name and optional description.\n * @param transition - The transition function to annotate.\n * @example\n * click = action({ name: \"trackClick\" }, (ctx) => ...);\n */\nexport function action<\n F extends (...args: any[]) => any,\n M extends TransitionMeta\n>(\n action: ActionMeta,\n transition: WithMeta<F, M>\n): WithMeta<F, M & { actions: [typeof action] }> {\n // Attach runtime metadata\n // Note: actions is an array, will be merged by attachRuntimeMeta\n attachRuntimeMeta(transition, {\n actions: [action]\n });\n\n return transition as any;\n}\n\n// =============================================================================\n// SECTION: RUNTIME GUARDS\n// =============================================================================\n\n/**\n * Configuration options for guard behavior when conditions fail.\n */\nexport interface GuardOptions<C extends object = any, TFailure extends Machine<any> = Machine<C>> {\n /** What to do when guard fails */\n onFail?: 'throw' | 'ignore' | GuardFallback<C, TFailure>;\n\n /** Custom error message for 'throw' mode */\n errorMessage?: string;\n\n /** Additional metadata for statechart extraction */\n description?: string;\n}\n\n/**\n * A fallback machine or function that returns a machine when guard fails.\n */\nexport type GuardFallback<C extends object, TFailure extends Machine<any> = Machine<C>> =\n | ((this: Machine<C>, ...args: any[]) => TFailure)\n | TFailure;\n\n/**\n * A guarded transition that checks conditions at runtime before executing.\n * Can be called with either machine or context as 'this' binding.\n */\nexport type GuardedTransition<\n C extends object,\n TSuccess extends Machine<any>,\n TFailure extends Machine<any> = Machine<C>\n> = {\n (...args: any[]): TSuccess | TFailure | Promise<TSuccess | TFailure>;\n readonly __guard: true;\n readonly condition: (ctx: C, ...args: any[]) => boolean | Promise<boolean>;\n readonly transition: (...args: any[]) => TSuccess;\n};\n\n/**\n * Creates a synchronous runtime guard that checks conditions before executing transitions.\n * This provides actual runtime protection with synchronous execution - use this for the majority of cases.\n *\n * **IMPORTANT - Context-Bound Limitation:**\n * Guards accept calls with either `this === machine` or `this === context`, but when called\n * with context-only binding, the guard normalizes to `{ context }` before passing to the transition.\n * This means:\n * - ✅ Transitions can access `this.context`\n * - ❌ Transitions CANNOT call `this.otherTransition()` (no transitions property)\n * - Recommended: Use guards only with machine-bound transitions for full composition support\n *\n * @template C - The context type\n * @template TSuccess - The transition return type when condition passes\n * @template TFailure - The fallback return type when condition fails (defaults to Machine<C>)\n * @param condition - Synchronous function that returns true if transition should proceed\n * @param transition - The transition function to execute if condition passes\n * @param options - Configuration for guard failure behavior\n * @returns A synchronous guarded transition function\n *\n * @example\n * ```typescript\n * const machine = createMachine({ balance: 100 }, {\n * withdraw: guard(\n * (ctx, amount) => ctx.balance >= amount,\n * function(this: Machine<{balance: number}>, amount: number) {\n * // ✅ Can access this.context\n * return createMachine({ balance: this.context.balance - amount }, this);\n * // ❌ Cannot call this.otherTransition() if guard was called with context-only binding\n * },\n * { onFail: 'throw', errorMessage: 'Insufficient funds' }\n * )\n * });\n *\n * machine.withdraw(50); // ✅ Works synchronously\n * machine.withdraw(200); // ❌ Throws \"Insufficient funds\"\n * ```\n */\nexport function guard<\n C extends object,\n TSuccess extends Machine<any>,\n TFailure extends Machine<any> = Machine<C>\n>(\n condition: (ctx: C, ...args: any[]) => boolean,\n transition: (...args: any[]) => TSuccess,\n options: GuardOptions<C, TFailure> = {}\n): (...args: any[]) => TSuccess | TFailure {\n const { onFail = 'throw', errorMessage, description } = options;\n\n // Merge defaults into options for the metadata\n const fullOptions = { ...options, onFail, errorMessage, description };\n\n // Create the guarded transition function (synchronous)\n const guardedTransition = function(this: C | Machine<C>, ...args: any[]): TSuccess | TFailure {\n // Detect if 'this' is a machine or just context\n const isMachine = typeof this === 'object' && 'context' in this;\n const ctx = isMachine ? (this as Machine<C>).context : (this as C);\n\n // Evaluate the condition (synchronously)\n const conditionResult = condition(ctx, ...args);\n\n if (conditionResult) {\n // Condition passed, execute the transition\n // Transition functions expect 'this' to be the machine\n const machineForTransition = isMachine ? (this as Machine<C>) : { context: this as C };\n return transition.apply(machineForTransition, args);\n } else {\n // Condition failed, handle according to options\n if (onFail === 'throw') {\n const message = errorMessage || 'Guard condition failed';\n throw new Error(message);\n } else if (onFail === 'ignore') {\n if (isMachine) {\n // Return the current machine unchanged\n return this as TSuccess | TFailure;\n } else {\n // Cannot ignore when called with context binding\n throw new Error('Cannot use \"ignore\" mode with context-only binding. Use full machine binding or provide fallback.');\n }\n } else if (typeof onFail === 'function') {\n // Custom fallback function - call with machine as 'this'\n if (isMachine) {\n return onFail.apply(this as Machine<C>, args) as TSuccess | TFailure;\n } else {\n throw new Error('Cannot use function fallback with context-only binding. Use full machine binding.');\n }\n } else {\n // Static fallback machine\n return onFail as TSuccess | TFailure;\n }\n }\n };\n\n // Attach metadata for type branding and statechart extraction\n Object.defineProperty(guardedTransition, '__guard', { value: true, enumerable: false });\n Object.defineProperty(guardedTransition, 'condition', { value: condition, enumerable: false });\n Object.defineProperty(guardedTransition, 'transition', { value: transition, enumerable: false });\n Object.defineProperty(guardedTransition, 'options', { value: fullOptions, enumerable: false });\n\n // Attach runtime metadata for statechart extraction\n attachRuntimeMeta(guardedTransition, {\n description: description || 'Synchronous guarded transition',\n guards: [{ name: 'runtime_guard', description: description || 'Synchronous condition check' }]\n });\n\n return guardedTransition;\n}\n\n/**\n * Creates a runtime guard that checks conditions before executing transitions.\n * This provides actual runtime protection, unlike the `guarded` primitive which only adds metadata.\n * Use this when your condition or transition logic is asynchronous.\n *\n * **IMPORTANT - Context-Bound Limitation:**\n * Guards accept calls with either `this === machine` or `this === context`, but when called\n * with context-only binding, the guard normalizes to `{ context }` before passing to the transition.\n * This means:\n * - ✅ Transitions can access `this.context`\n * - ❌ Transitions CANNOT call `this.otherTransition()` (no transitions property)\n * - Recommended: Use guards only with machine-bound transitions for full composition support\n *\n * @template C - The context type\n * @template TSuccess - The transition return type when condition passes\n * @template TFailure - The fallback return type when condition fails (defaults to Machine<C>)\n * @param condition - Function that returns true if transition should proceed (can be async)\n * @param transition - The transition function to execute if condition passes\n * @param options - Configuration for guard failure behavior\n * @returns A guarded transition function that returns a Promise\n *\n * @example\n * ```typescript\n * const machine = createMachine({ balance: 100 }, {\n * withdraw: guardAsync(\n * async (ctx, amount) => {\n * // Simulate API call to check balance\n * await new Promise(resolve => setTimeout(resolve, 100));\n * return ctx.balance >= amount;\n * },\n * async function(this: Machine<{balance: number}>, amount: number) {\n * // Simulate API call to process withdrawal\n * await new Promise(resolve => setTimeout(resolve, 100));\n * // ✅ Can access this.context\n * return createMachine({ balance: this.context.balance - amount }, this);\n * // ❌ Cannot call this.otherTransition() if guard was called with context-only binding\n * },\n * { onFail: 'throw', errorMessage: 'Insufficient funds' }\n * )\n * });\n *\n * await machine.withdraw(50); // ✅ Works\n * await machine.withdraw(200); // ❌ Throws \"Insufficient funds\"\n * ```\n */\nexport function guardAsync<\n C extends object,\n TSuccess extends Machine<any>,\n TFailure extends Machine<any> = Machine<C>\n>(\n condition: (ctx: C, ...args: any[]) => boolean | Promise<boolean>,\n transition: (...args: any[]) => TSuccess,\n options: GuardOptions<C, TFailure> = {}\n): GuardedTransition<C, TSuccess, TFailure> {\n const { onFail = 'throw', errorMessage, description } = options;\n\n // Merge defaults into options for the metadata\n const fullOptions = { ...options, onFail, errorMessage, description };\n\n // Create the guarded transition function\n const guardedTransition = async function(this: C | Machine<C>, ...args: any[]): Promise<TSuccess | TFailure> {\n // Detect if 'this' is a machine or just context\n const isMachine = typeof this === 'object' && 'context' in this;\n const ctx = isMachine ? (this as Machine<C>).context : (this as C);\n\n // Evaluate the condition\n const conditionResult = await Promise.resolve(condition(ctx, ...args));\n\n if (conditionResult) {\n // Condition passed, execute the transition\n // Transition functions expect 'this' to be the machine\n const machineForTransition = isMachine ? (this as Machine<C>) : { context: this as C };\n return transition.apply(machineForTransition, args);\n } else {\n // Condition failed, handle according to options\n if (onFail === 'throw') {\n const message = errorMessage || 'Guard condition failed';\n throw new Error(message);\n } else if (onFail === 'ignore') {\n if (isMachine) {\n // Return the current machine unchanged\n return this as TSuccess | TFailure;\n } else {\n // Cannot ignore when called with context binding\n throw new Error('Cannot use \"ignore\" mode with context-only binding. Use full machine binding or provide fallback.');\n }\n } else if (typeof onFail === 'function') {\n // Custom fallback function - call with machine as 'this'\n if (isMachine) {\n return onFail.apply(this as Machine<C>, args) as TSuccess | TFailure;\n } else {\n throw new Error('Cannot use function fallback with context-only binding. Use full machine binding.');\n }\n } else {\n // Static fallback machine\n return onFail as TSuccess | TFailure;\n }\n }\n };\n\n // Attach metadata for type branding and statechart extraction\n Object.defineProperty(guardedTransition, '__guard', { value: true, enumerable: false });\n Object.defineProperty(guardedTransition, 'condition', { value: condition, enumerable: false });\n Object.defineProperty(guardedTransition, 'transition', { value: transition, enumerable: false });\n Object.defineProperty(guardedTransition, 'options', { value: fullOptions, enumerable: false });\n\n // Attach runtime metadata for statechart extraction\n attachRuntimeMeta(guardedTransition, {\n description: description || 'Runtime guarded transition',\n guards: [{ name: 'runtime_guard', description: description || 'Runtime condition check' }]\n });\n\n return guardedTransition as GuardedTransition<C, TSuccess, TFailure>;\n}\n\n/**\n * Creates a synchronous guard that checks conditions before executing transitions.\n * This is the synchronous counterpart to `guard()` - use this when your machine\n * doesn't need async transitions to avoid unnecessary Promise overhead.\n *\n * @template C - The context type\n * @template T - The transition return type\n * @param condition - Function that returns true if transition should proceed (must be synchronous)\n * @param transition - The transition function to execute if condition passes (must be synchronous)\n * @param options - Configuration for guard failure behavior\n * @returns A synchronous guarded transition function\n *\n * @example\n * ```typescript\n * const machine = createMachine({ balance: 100 }, {\n * withdraw: guardSync(\n * (ctx, amount) => ctx.balance >= amount,\n * function(amount: number) {\n * return createMachine({ balance: this.context.balance - amount }, this);\n * },\n * { onFail: 'throw', errorMessage: 'Insufficient funds' }\n * )\n * });\n *\n * machine.withdraw(50); // ✅ Works synchronously\n * machine.withdraw(200); // ❌ Throws \"Insufficient funds\"\n * ```\n */\nexport function guardSync<\n C extends object,\n TSuccess extends Machine<any>,\n TFailure extends Machine<any> = Machine<C>\n>(\n condition: (ctx: C, ...args: any[]) => boolean,\n transition: (...args: any[]) => TSuccess,\n options: GuardOptions<C, TFailure> = {}\n): GuardedTransition<C, TSuccess, TFailure> {\n const { onFail = 'throw', errorMessage, description } = options;\n\n // Merge defaults into options for the metadata\n const fullOptions = { ...options, onFail, errorMessage, description };\n\n // Create the guarded transition function (synchronous)\n const guardedTransition = function(this: C | Machine<C>, ...args: any[]): TSuccess | TFailure {\n // Detect if 'this' is a machine or just context\n const isMachine = typeof this === 'object' && 'context' in this;\n const ctx = isMachine ? (this as Machine<C>).context : (this as C);\n\n // Evaluate the condition (synchronously)\n const conditionResult = condition(ctx, ...args);\n\n if (conditionResult) {\n // Condition passed, execute the transition\n // Transition functions expect 'this' to be the machine\n const machineForTransition = isMachine ? (this as Machine<C>) : { context: this as C };\n return transition.apply(machineForTransition, args);\n } else {\n // Condition failed, handle according to options\n if (onFail === 'throw') {\n const message = errorMessage || 'Guard condition failed';\n throw new Error(message);\n } else if (onFail === 'ignore') {\n if (isMachine) {\n // Return the current machine unchanged\n return this as TSuccess | TFailure;\n } else {\n // Cannot ignore when called with context binding\n throw new Error('Cannot use \"ignore\" mode with context-only binding. Use full machine binding or provide fallback.');\n }\n } else if (typeof onFail === 'function') {\n // Custom fallback function - call with machine as 'this'\n if (isMachine) {\n return onFail.apply(this as Machine<C>, args) as TSuccess | TFailure;\n } else {\n throw new Error('Cannot use function fallback with context-only binding. Use full machine binding.');\n }\n } else {\n // Static fallback machine\n return onFail as TSuccess | TFailure;\n }\n }\n };\n\n // Attach metadata for type branding and statechart extraction\n Object.defineProperty(guardedTransition, '__guard', { value: true, enumerable: false });\n Object.defineProperty(guardedTransition, 'condition', { value: condition, enumerable: false });\n Object.defineProperty(guardedTransition, 'transition', { value: transition, enumerable: false });\n Object.defineProperty(guardedTransition, 'options', { value: fullOptions, enumerable: false });\n\n // Attach runtime metadata for statechart extraction\n attachRuntimeMeta(guardedTransition, {\n description: description || 'Synchronous guarded transition',\n guards: [{ name: 'runtime_guard_sync', description: description || 'Synchronous condition check' }]\n });\n\n return guardedTransition as GuardedTransition<C, TSuccess, TFailure>;\n}\n\n/**\n * Fluent API for creating synchronous guarded transitions.\n * Provides a more readable way to define conditional transitions with synchronous execution.\n *\n * @template C - The context type\n * @param condition - Synchronous function that returns true if transition should proceed\n * @returns A fluent interface for defining the guarded transition\n *\n * @example\n * ```typescript\n * const machine = createMachine({ isAdmin: false }, {\n * deleteUser: whenGuard((ctx) => ctx.isAdmin)\n * .do(function(userId: string) {\n * return createMachine({ ...this.context, deleted: userId }, this);\n * })\n * .else(function() {\n * return createMachine({ ...this.context, error: 'Unauthorized' }, this);\n * })\n * });\n * ```\n */\nexport function whenGuard<C extends object>(\n condition: (ctx: C, ...args: any[]) => boolean\n) {\n return {\n /**\n * Define the transition to execute when the condition passes.\n * Returns a guarded transition that can optionally have an else clause.\n */\n do<T extends Machine<any>>(transition: (...args: any[]) => T) {\n const guarded = guard(condition, transition);\n\n // Add fluent else method to the guarded transition\n (guarded as any).else = function<F extends Machine<any>>(fallback: (...args: any[]) => F) {\n return guard(condition, transition, { onFail: fallback });\n };\n\n return guarded;\n }\n };\n}\n\n/**\n * Fluent API for creating asynchronous guarded transitions.\n * Provides a more readable way to define conditional transitions with async execution.\n *\n * @template C - The context type\n * @param condition - Function that returns true if transition should proceed (can be async)\n * @returns A fluent interface for defining the guarded transition\n *\n * @example\n * ```typescript\n * const machine = createMachine({ isAdmin: false }, {\n * deleteUser: whenGuardAsync(async (ctx) => {\n * // Simulate API call\n * await checkPermissions(ctx.userId);\n * return ctx.isAdmin;\n * })\n * .do(async function(userId: string) {\n * await deleteUserFromDB(userId);\n * return createMachine({ ...this.context, deleted: userId }, this);\n * })\n * .else(function() {\n * return createMachine({ ...this.context, error: 'Unauthorized' }, this);\n * })\n * });\n * ```\n */\nexport function whenGuardAsync<C extends object>(\n condition: (ctx: C, ...args: any[]) => boolean | Promise<boolean>\n) {\n return {\n /**\n * Define the transition to execute when the condition passes.\n * Returns a guarded transition that can optionally have an else clause.\n */\n do<T extends Machine<any>>(transition: (...args: any[]) => T) {\n const guarded = guardAsync(condition, transition);\n\n // Add fluent else method to the guarded transition\n (guarded as any).else = function<F extends Machine<any>>(fallback: (...args: any[]) => F) {\n return guardAsync(condition, transition, { onFail: fallback });\n };\n\n return guarded;\n }\n };\n}\n\n/**\n * Flexible metadata wrapper for functional and type-state patterns.\n *\n * This function allows attaching metadata to values that don't use the class-based\n * MachineBase pattern. It's particularly useful for:\n * - Functional machines created with createMachine()\n * - Type-state discriminated unions\n * - Generic machine configurations\n *\n * @param meta - Partial metadata object describing states, transitions, etc.\n * @param value - The value to annotate (machine, config, factory function, etc.)\n * @returns The value unchanged (identity function at runtime)\n *\n * @example\n * // Annotate a functional machine\n * const machine = metadata(\n * {\n * target: IdleState,\n * description: \"Counter machine with increment/decrement\"\n * },\n * createMachine({ count: 0 }, { ... })\n * );\n *\n * @example\n * // Annotate a factory function\n * export const createCounter = metadata(\n * { description: \"Creates a counter starting at 0\" },\n * () => createMachine({ count: 0 }, { ... })\n * );\n */\nexport function metadata<T>(_meta: Partial<TransitionMeta>, value: T): T {\n // At runtime, this is a no-op identity function\n // At compile-time/static-analysis, the metadata can be extracted from the type signature\n return value;\n}", "/**\n * @file multi.ts - Advanced operational patterns for state machine orchestration.\n * @description\n * This module provides optional, higher-level abstractions for managing machines.\n * They solve common ergonomic and integration challenges without compromising the\n * immutable core of the library.\n *\n * It introduces three patterns:\n *\n * 1. **Runner (`createRunner`):** A stateful controller for ergonomic control\n * of a single, immutable machine. Solves state reassignment.\n *\n * 2. **Ensemble (`createEnsemble`):** A functional pattern for orchestrating logic\n * over an external, framework-agnostic state store.\n *\n * 3. **MultiMachine (`createMultiMachine`):** A class-based alternative to the\n * Ensemble for OOP-style orchestration.\n */\n\nimport {\n Machine,\n Context,\n TransitionArgs,\n TransitionNames,\n // Transitions,\n} from './index';\n\n// =============================================================================\n// SECTION 1: THE MANAGED STATE RUNNER\n// =============================================================================\n\n/**\n * A mapped type that creates a new object type with the same transition methods\n * as the machine `M`, but pre-bound to update a Runner's internal state.\n *\n * When you call a method on `BoundTransitions`, it automatically transitions the\n * runner's state and returns the new machine instance. This is the key mechanism\n * that eliminates the need for manual state reassignment in imperative code.\n *\n * @template M - The machine type, which can be a union of multiple machine states.\n *\n * @example\n * // If your machine has these transitions:\n * // increment: () => Machine\n * // add: (n: number) => Machine\n * // Then BoundTransitions<typeof machine> provides:\n * // increment: () => Machine (auto-updates runner state)\n * // add: (n: number) => Machine (auto-updates runner state)\n */\nexport type BoundTransitions<M extends Machine<any>> = {\n [K in TransitionNames<M>]: (\n ...args: TransitionArgs<M, K>\n ) => M[K] extends (...args: any[]) => infer R ? R : never;\n};\n\n/**\n * A stateful controller that wraps an immutable machine instance, providing a\n * stable API for imperative state transitions without manual reassignment.\n *\n * The Runner holds the \"current\" machine state internally and updates it whenever\n * an action is called. This solves the ergonomic problem of having to write:\n * `machine = machine.transition()` over and over. Instead, you just call\n * `runner.actions.transition()` and the runner manages the state for you.\n *\n * **Use Runner for:**\n * - Complex local component state (React, Vue, Svelte components)\n * - Scripts that need clean imperative state management\n * - Situations where you have a single, self-contained state machine\n *\n * **Don't use Runner for:**\n * - Global application state (use Ensemble instead)\n * - Multiple interconnected machines\n *\n * @template M - The machine type (can be a union of states for Type-State patterns).\n */\nexport type Runner<M extends Machine<any>> = {\n /**\n * The current, raw machine instance. This property is essential for\n * type-narrowing in Type-State Programming patterns.\n *\n * Since machines can be unions of different state types, you can narrow\n * the type by checking `runner.state.context` properties, and TypeScript\n * will automatically narrow which transitions are available.\n *\n * @example\n * if (runner.state.context.status === 'loggedIn') {\n * // runner.state is now typed as LoggedInMachine\n * console.log(runner.state.context.username);\n * runner.actions.logout(); // Only available when logged in\n * }\n */\n readonly state: M;\n\n /**\n * A direct, readonly accessor to the context of the current machine state.\n * This is a convenience property equivalent to `runner.state.context`.\n *\n * @example\n * console.log(runner.context.count); // Same as runner.state.context.count\n */\n readonly context: Context<M>;\n\n /**\n * A stable object containing all available transition methods, pre-bound to\n * update the runner's state. This is the primary way to trigger transitions.\n *\n * When you call `runner.actions.someTransition()`, the runner automatically:\n * 1. Calls the transition on the current machine\n * 2. Updates `runner.state` with the new machine instance\n * 3. Fires the `onChange` callback (if provided to createRunner)\n * 4. Returns the new machine instance\n *\n * Note: For union-type machines, you must first narrow the type of `runner.state`\n * to ensure a given action is available at compile time.\n *\n * @example\n * runner.actions.increment(); // Automatically updates runner.state\n * runner.actions.add(5); // Returns new machine instance\n */\n readonly actions: BoundTransitions<M>;\n\n /**\n * Manually sets the runner to a new machine state. Useful for resetting state\n * or synchronizing with external events.\n *\n * This method bypasses the normal transition path and directly updates the\n * runner's internal state. The `onChange` callback will be called.\n *\n * @param newState - The new machine instance to set.\n *\n * @example\n * const reset = createCounterMachine({ count: 0 });\n * runner.setState(reset); // Jump back to initial state\n */\n setState(newState: M): void;\n};\n\n/**\n * Creates a Managed State Runner by wrapping a pure, immutable machine instance\n * in a stateful controller. This eliminates the need for `machine = machine.transition()`\n * reassignment, providing a more ergonomic, imperative API for complex local state.\n *\n * **How it works:**\n * 1. The runner holds a reference to the current machine internally\n * 2. When you call `runner.actions.transition()`, it calls the transition on the\n * current machine and automatically updates the runner's internal state\n * 3. The runner exposes a stable `actions` object that always reflects what\n * transitions are available on the *current* machine (important for Type-State)\n * 4. The `onChange` callback is invoked after every state change\n *\n * **Key difference from just calling transitions directly:**\n * Instead of: `let machine = createMachine(...); machine = machine.increment();`\n * You write: `const runner = createRunner(machine); runner.actions.increment();`\n *\n * The runner *is* the state holder, so you never need to reassign variables.\n *\n * @template M - The machine type.\n * @param initialMachine - The starting machine instance.\n * @param onChange - Optional callback fired after every state transition. Receives\n * the new machine state, allowing you to react to changes (e.g., update a UI,\n * log state changes, or trigger side effects).\n * @returns A `Runner` instance with `state`, `context`, `actions`, and `setState()`.\n *\n * @example\n * // Simple counter example\n * const counterMachine = createCounterMachine({ count: 0 });\n * const runner = createRunner(counterMachine, (newState) => {\n * console.log('Count is now:', newState.context.count);\n * });\n *\n * runner.actions.increment(); // Logs: \"Count is now: 1\"\n * runner.actions.add(5); // Logs: \"Count is now: 6\"\n * console.log(runner.context.count); // 6\n *\n * @example\n * // Type-State example with conditional narrowing\n * type AuthMachine = LoggedOutState | LoggedInState;\n *\n * const runner = createRunner(createLoggedOutMachine());\n *\n * // Narrow the type to access login\n * if (runner.state.context.status === 'loggedOut') {\n * runner.actions.login('alice'); // Only works in loggedOut state\n * }\n *\n * // Now it's logged in, so we can call logout\n * if (runner.state.context.status === 'loggedIn') {\n * runner.actions.logout();\n * }\n */\nexport function createRunner<M extends Machine<any>>(\n initialMachine: M,\n onChange?: (newState: M) => void\n): Runner<M> {\n let currentMachine = initialMachine;\n\n const setState = (newState: M) => {\n currentMachine = newState;\n onChange?.(newState);\n };\n\n // Capture the original transitions from the initial machine\n const { context: _initialContext, ...originalTransitions } = initialMachine;\n\n const actions = new Proxy({} as BoundTransitions<M>, {\n get(_target, prop: string) {\n const transition = (currentMachine as any)[prop];\n if (typeof transition !== 'function') {\n // Return undefined for properties that aren't valid transitions on the current state\n return undefined;\n }\n\n return (...args: any[]) => {\n const nextState = transition.apply(currentMachine, args);\n // Ensure the next state has all the original transitions\n // by reconstructing it with the original transition functions\n const nextStateWithTransitions = Object.assign(\n { context: nextState.context },\n originalTransitions\n ) as M;\n setState(nextStateWithTransitions);\n return nextStateWithTransitions;\n };\n },\n });\n\n return {\n get state() {\n return currentMachine;\n },\n get context() {\n return currentMachine.context;\n },\n actions,\n setState,\n };\n}\n\n// =============================================================================\n// SECTION 2: THE ENSEMBLE (FRAMEWORK-AGNOSTIC ORCHESTRATION)\n// =============================================================================\n\n/**\n * Defines the contract for an external, user-provided state store. The Ensemble\n * uses this interface to read and write the machine's context, allowing it to\n * plug into any state management solution (React, Solid, Zustand, etc.).\n *\n * **The power of this abstraction:**\n * Your machine logic is completely decoupled from how or where the state is stored.\n * The same machine factories can work with React's `useState`, Solid's `createSignal`,\n * a plain object, or any custom store implementation.\n *\n * **Implementation examples:**\n * - React: `{ getContext: () => state, setContext: setState }`\n * - Solid: `{ getContext: () => store, setContext: (newCtx) => Object.assign(store, newCtx) }`\n * - Plain object: `{ getContext: () => context, setContext: (ctx) => Object.assign(context, ctx) }`\n *\n * @template C - The shared context object type.\n *\n * @example\n * // Implement a simple in-memory store\n * let sharedContext = { status: 'idle' };\n * const store: StateStore<typeof sharedContext> = {\n * getContext: () => sharedContext,\n * setContext: (newCtx) => { sharedContext = newCtx; }\n * };\n *\n * @example\n * // Implement a React-based store\n * function useAppStore() {\n * const [state, setState] = useState({ status: 'idle' });\n * return {\n * getContext: () => state,\n * setContext: setState\n * };\n * }\n */\nexport interface StateStore<C extends object> {\n /**\n * A function that returns the current, up-to-date context from the external store.\n * Called whenever the Ensemble needs the latest state.\n */\n getContext: () => C;\n\n /**\n * A function that takes a new context and updates the external store.\n * Called by transitions to persist state changes.\n *\n * @param newContext - The new context object to persist.\n */\n setContext: (newContext: C) => void;\n}\n\n/**\n * A mapped type that finds all unique transition names across a union of machine types.\n *\n * This type extracts the union of all methods from all possible machine states,\n * excluding the `context` property. This is used to create the `actions` object\n * on an Ensemble, which can have methods from any of the machine states.\n *\n * At runtime, the Ensemble validates that an action is valid for the current state\n * before executing it.\n *\n * @template AllMachines - A union of all possible machine types in an Ensemble.\n *\n * @example\n * type IdleState = Machine<{ status: 'idle' }> & { fetch: () => LoadingState };\n * type LoadingState = Machine<{ status: 'loading' }> & { cancel: () => IdleState };\n * type AllStates = IdleState | LoadingState;\n *\n * // AllTransitions<AllStates> = { fetch: (...) => ..., cancel: (...) => ... }\n * // (Both fetch and cancel are available, but each is only valid in its state)\n */\ntype AllTransitions<AllMachines extends Machine<any>> = Omit<\n { [K in keyof AllMachines]: AllMachines[K] }[keyof AllMachines],\n 'context'\n>;\n\n/**\n * The Ensemble object. It provides a stable, unified API for orchestrating a\n * state machine whose context is managed by an external store.\n *\n * The Ensemble acts as the \"director,\" determining which machine \"actor\" is\n * currently active based on the state of the shared context. Unlike a Runner,\n * which manages local state, an Ensemble plugs into external state management\n * (like React's useState, Solid's signal, or a global store).\n *\n * **Key characteristics:**\n * - Dynamically reconstructs the current machine based on context\n * - Validates transitions at runtime for the current state\n * - Integrates seamlessly with framework state managers\n * - Same factories can be reused across different frameworks\n *\n * **Use Ensemble for:**\n * - Global application state\n * - Framework integration (React, Solid, Vue, etc.)\n * - Complex workflows that span multiple components\n * - Decoupling business logic from UI framework\n *\n * @template AllMachines - A union type of all possible machine states.\n * @template C - The shared context type.\n */\nexport type Ensemble<AllMachines extends Machine<any>, C extends object> = {\n /**\n * A direct, readonly accessor to the context from the provided `StateStore`.\n * This is always up-to-date with the external store.\n */\n readonly context: C;\n\n /**\n * The current, fully-typed machine instance. This is dynamically created on-demand\n * based on the context state. Use this for type-narrowing with Type-State patterns.\n *\n * The machine is reconstructed on every access, so it always reflects the\n * current state of the context.\n */\n readonly state: AllMachines;\n\n /**\n * A stable object containing all possible actions from all machine states.\n * The Ensemble performs a runtime check to ensure an action is valid for the\n * current state before executing it.\n *\n * The `actions` object itself is stable (doesn't change), but the methods\n * available on it dynamically change based on the current state.\n */\n readonly actions: AllTransitions<AllMachines>;\n};\n\n/**\n * Creates an Ensemble to orchestrate a state machine over an external state store.\n * This is the primary tool for framework integration, as it decouples pure state\n * logic (defined in factories) from an application's state management solution\n * (defined in store).\n *\n * **How it works:**\n * 1. You provide a `StateStore` that can read and write your application's state\n * 2. You define factory functions that create machines for each state\n * 3. You provide a `getDiscriminant` accessor that tells the Ensemble which\n * factory to use based on the current context\n * 4. The Ensemble dynamically constructs the right machine and provides a stable\n * `actions` object to call transitions\n *\n * **Why this pattern?**\n * Your business logic (machines) is completely separated from your state management\n * (React, Solid, Zustand). You can change state managers without rewriting machines,\n * and you can test machines in isolation without framework dependencies.\n *\n * @template C - The shared context type.\n * @template F - An object of functions that create machine instances for each state.\n * Each factory receives the context and returns a Machine instance for that state.\n * @param store - The user-provided `StateStore` that reads/writes the context.\n * @param factories - An object mapping state discriminant keys to factory functions.\n * Each factory receives the context and returns a machine instance.\n * @param getDiscriminant - An accessor function that takes the context and returns\n * the key of the current state in the `factories` object. This provides full\n * refactoring safety—if you rename a property in your context, TypeScript will\n * catch it at the accessor function.\n * @returns An `Ensemble` instance with `context`, `state`, and `actions`.\n *\n * @example\n * // Using a simple in-memory store\n * let sharedContext = { status: 'idle' as const, data: null };\n * const store = {\n * getContext: () => sharedContext,\n * setContext: (newCtx) => { sharedContext = newCtx; }\n * };\n *\n * // Define factories for each state\n * const factories = {\n * idle: (ctx) => createMachine(ctx, {\n * fetch: () => store.setContext({ ...ctx, status: 'loading' })\n * }),\n * loading: (ctx) => createMachine(ctx, {\n * succeed: (data: any) => store.setContext({ status: 'success', data }),\n * fail: (error: string) => store.setContext({ status: 'error', error })\n * }),\n * success: (ctx) => createMachine(ctx, {\n * retry: () => store.setContext({ status: 'loading', data: null })\n * }),\n * error: (ctx) => createMachine(ctx, {\n * retry: () => store.setContext({ status: 'loading', data: null })\n * })\n * };\n *\n * // Create the ensemble with a discriminant accessor\n * const ensemble = createEnsemble(store, factories, (ctx) => ctx.status);\n *\n * // Use the ensemble\n * ensemble.actions.fetch();\n * console.log(ensemble.context.status); // 'loading'\n *\n * @example\n * // React integration example\n * function useAppEnsemble() {\n * const [context, setContext] = useState({ status: 'idle' as const, data: null });\n *\n * const store: StateStore<typeof context> = {\n * getContext: () => context,\n * setContext: (newCtx) => setContext(newCtx)\n * };\n *\n * const ensemble = useMemo(() =>\n * createEnsemble(store, factories, (ctx) => ctx.status),\n * [context] // Re-create ensemble if context changes\n * );\n *\n * return ensemble;\n * }\n *\n * // In your component:\n * function MyComponent() {\n * const ensemble = useAppEnsemble();\n * return (\n * <>\n * <p>Status: {ensemble.context.status}</p>\n * <button onClick={() => ensemble.actions.fetch()}>\n * Fetch Data\n * </button>\n * </>\n * );\n * }\n */\nexport function createEnsemble<\n C extends object,\n F extends Record<string, (context: C) => Machine<C>>\n>(\n store: StateStore<C>,\n factories: F,\n getDiscriminant: (context: C) => keyof F\n): Ensemble<ReturnType<F[keyof F]>, C> {\n type AllMachines = ReturnType<F[keyof F]>;\n\n const getCurrentMachine = (): AllMachines => {\n const context = store.getContext();\n const currentStateName = getDiscriminant(context);\n const factory = factories[currentStateName];\n\n if (!factory) {\n throw new Error(\n `[Ensemble] Invalid state: No factory found for state \"${String(currentStateName)}\".`\n );\n }\n return factory(context) as AllMachines;\n };\n\n const actions = new Proxy({} as AllTransitions<AllMachines>, {\n get(_target, prop: string) {\n const currentMachine = getCurrentMachine();\n const action = (currentMachine as any)[prop];\n\n if (typeof action !== 'function') {\n throw new Error(\n `[Ensemble] Transition \"${prop}\" is not valid in the current state.`\n );\n }\n\n // Return a function that, when called, executes the transition.\n // The transition itself is responsible for calling `store.setContext`.\n return (...args: any[]) => {\n return action.apply(currentMachine, args);\n };\n },\n });\n\n return {\n get context() {\n return store.getContext();\n },\n get state() {\n return getCurrentMachine();\n },\n actions,\n };\n}\n\n/**\n * Creates a factory for building type-safe, framework-agnostic Ensembles.\n * This is a higher-order function that captures the application's state store\n * and state-discriminant logic in a closure.\n *\n * This allows you to define your application's state \"environment\" once and then\n * easily create multiple, consistent ensembles by only providing the behavioral logic.\n *\n * @template C The shared context type for the application.\n * @param store The application's state store (e.g., from React, Zustand, etc.).\n * @param getDiscriminant An accessor function that determines the current state from the context.\n * @returns A `withFactories` function that is pre-configured for your app's environment.\n */\nexport function createEnsembleFactory<C extends object>(\n store: StateStore<C>,\n getDiscriminant: (context: C) => keyof any\n) {\n /**\n * This returned function is pre-configured with the `store` and `getDiscriminant` logic.\n * It takes the machine factories (the behavioral logic) and returns a complete Ensemble.\n *\n * @template F The type of the factories object.\n * @param factories An object where each key is a state name and each value is a\n * function that creates a machine instance for that state.\n * @returns A fully-formed, reactive, and type-safe Ensemble instance.\n */\n return function withFactories<\n F extends Record<string, (context: C) => Machine<C>>\n >(\n factories: F\n ): Ensemble<ReturnType<F[keyof F]>, C> {\n // We simply call the original createEnsemble with the captured arguments.\n return createEnsemble(store, factories, getDiscriminant as (context: C) => keyof F);\n };\n}\n\n// =============================================================================\n// SECTION 3: GENERATOR INTEGRATION\n// =============================================================================\n\n/**\n * Executes a generator-based workflow using a Managed State Runner.\n *\n * This provides the cleanest syntax for multi-step imperative workflows, as the\n * `yield` keyword is only used for control flow, not state passing. Unlike the\n * basic `run()` function from the core library, this works directly with a Runner,\n * making it perfect for complex local state orchestration.\n *\n * **Syntax benefits:**\n * - No need to manually thread state through a chain of transitions\n * - `yield` is purely for control flow, not for passing state\n * - Can use regular `if`/`for` statements without helpers\n * - Generator return value is automatically your final result\n *\n * @param flow - A generator function that receives the `Runner` instance. The\n * generator can yield values (returned by transitions) and use them for control\n * flow, or just yield for side effects.\n * @param initialMachine - The machine to start the flow with. A runner will be\n * created from this automatically.\n * @returns The final value returned by the generator (the `return` statement).\n *\n * @example\n * // Simple sequential transitions\n * const result = runWithRunner(function* (runner) {\n * yield runner.actions.increment();\n * yield runner.actions.add(10);\n * if (runner.context.count > 5) {\n * yield runner.actions.reset();\n * }\n * return runner.context;\n * }, createCounterMachine());\n * console.log(result); // { count: 0 }\n *\n * @example\n * // Complex workflow with Type-State narrowing\n * const result = runWithRunner(function* (runner) {\n * // Start logged out\n * if (runner.state.context.status === 'loggedOut') {\n * yield runner.actions.login('alice');\n * }\n *\n * // Now logged in, fetch profile\n * if (runner.state.context.status === 'loggedIn') {\n * yield runner.actions.fetchProfile();\n * }\n *\n * // Return final context\n * return runner.context;\n * }, createAuthMachine());\n */\nexport function runWithRunner<M extends Machine<any>, T>(\n flow: (runner: Runner<M>) => Generator<any, T, any>,\n initialMachine: M\n): T {\n const runner = createRunner(initialMachine);\n const generator = flow(runner);\n let result = generator.next();\n while (!result.done) {\n result = generator.next();\n }\n return result.value;\n}\n\n/**\n * Executes a generator-based workflow using an Ensemble.\n *\n * This pattern is ideal for orchestrating complex sagas or workflows that\n * interact with a global, framework-managed state. Like `runWithRunner`,\n * it provides clean imperative syntax for multi-step workflows, but operates\n * on an Ensemble's external store rather than internal state.\n *\n * **Key differences from runWithRunner:**\n * - Works with external state stores (React, Solid, etc.)\n * - Useful for global workflows and sagas\n * - State changes automatically propagate to the framework\n * - Great for testing framework-agnostic state logic\n *\n * @param flow - A generator function that receives the `Ensemble` instance.\n * The generator can read `ensemble.context` and call `ensemble.actions`.\n * @param ensemble - The `Ensemble` to run the workflow against. Its context\n * is shared across the entire workflow.\n * @returns The final value returned by the generator (the `return` statement).\n *\n * @example\n * // Multi-step workflow with an ensemble\n * const result = runWithEnsemble(function* (ensemble) {\n * // Fetch initial data\n * if (ensemble.context.status === 'idle') {\n * yield ensemble.actions.fetch();\n * }\n *\n * // Process the data\n * if (ensemble.context.status === 'success') {\n * yield ensemble.actions.process(ensemble.context.data);\n * }\n *\n * return ensemble.context;\n * }, ensemble);\n *\n * @example\n * // Testing a workflow without a UI framework\n * const store: StateStore<AppContext> = {\n * getContext: () => context,\n * setContext: (newCtx) => Object.assign(context, newCtx)\n * };\n *\n * const ensemble = createEnsemble(store, factories, (ctx) => ctx.status);\n *\n * // Run a complex workflow and assert the result\n * const result = runWithEnsemble(function* (e) {\n * yield e.actions.login('alice');\n * yield e.actions.fetchProfile();\n * yield e.actions.updateEmail('alice@example.com');\n * return e.context;\n * }, ensemble);\n *\n * expect(result.userEmail).toBe('alice@example.com');\n */\nexport function runWithEnsemble<\n AllMachines extends Machine<any>,\n C extends object,\n T\n>(\n flow: (ensemble: Ensemble<AllMachines, C>) => Generator<any, T, any>,\n ensemble: Ensemble<AllMachines, C>\n): T {\n const generator = flow(ensemble);\n let result = generator.next();\n while (!result.done) {\n result = generator.next();\n }\n return result.value;\n}\n\n// =============================================================================\n// SECTION 4: CLASS-BASED MULTI-MACHINE (OOP APPROACH)\n// =============================================================================\n\n/**\n * The base class for creating a class-based state machine (MultiMachine).\n * Extend this class to define your state machine's logic using instance methods\n * as transitions.\n *\n * This approach is ideal for developers who prefer class-based architectures\n * and want to manage a shared context directly through an external StateStore.\n * It provides a familiar OOP interface while maintaining the decoupling benefits\n * of the StateStore pattern.\n *\n * **Key features:**\n * - Extend this class and define transition methods as instance methods\n * - Protected `context` getter provides access to the current state\n * - Protected `setContext()` method updates the external store\n * - Works seamlessly with `createMultiMachine()`\n *\n * @template C - The shared context type. Should typically contain a discriminant\n * property (like `status`) that identifies the current state.\n *\n * @example\n * // Define your context type\n * type AppContext = { status: 'idle' | 'loading' | 'error'; data?: any; error?: string };\n *\n * // Extend MultiMachineBase and define transitions as methods\n * class AppMachine extends MultiMachineBase<AppContext> {\n * async fetch(url: string) {\n * // Notify subscribers we're loading\n * this.setContext({ ...this.context, status: 'loading' });\n *\n * try {\n * const data = await fetch(url).then(r => r.json());\n * // Update state when done\n * this.setContext({ ...this.context, status: 'idle', data });\n * } catch (error) {\n * // Handle errors\n * this.setContext({\n * ...this.context,\n * status: 'error',\n * error: error.message\n * });\n * }\n * }\n *\n * reset() {\n * this.setContext({ status: 'idle' });\n * }\n * }\n */\nexport abstract class MultiMachineBase<C extends object> {\n /**\n * The external state store that manages the machine's context.\n * @protected\n */\n protected store: StateStore<C>;\n\n /**\n * @param store - The StateStore that will manage this machine's context.\n */\n constructor(store: StateStore<C>) {\n this.store = store;\n }\n\n /**\n * Read-only access to the current context from the external store.\n * This getter always returns the latest context from the store.\n *\n * @protected\n *\n * @example\n * const currentStatus = this.context.status;\n * const currentData = this.context.data;\n */\n protected get context(): C {\n return this.store.getContext();\n }\n\n /**\n * Update the shared context in the external store.\n * Call this method in your transition methods to update the state.\n *\n * @protected\n * @param newContext - The new context object. Should typically be a shallow\n * copy with only the properties you're changing, merged with the current\n * context using spread operators.\n *\n * @example\n * // In a transition method:\n * this.setContext({ ...this.context, status: 'loading' });\n *\n * @example\n * // Updating nested properties:\n * this.setContext({\n * ...this.context,\n * user: { ...this.context.user, name: 'Alice' }\n * });\n */\n protected setContext(newContext: C): void {\n this.store.setContext(newContext);\n }\n}\n\n/**\n * Creates a live, type-safe instance of a class-based state machine (MultiMachine).\n *\n * This is the class-based alternative to the functional `createEnsemble` pattern,\n * designed for developers who prefer an OOP-style architecture. This function takes\n * your MultiMachine class blueprint and an external state store, and wires them\n * together. The returned object is a Proxy that dynamically exposes both context\n * properties and the available transition methods from your class.\n *\n * **Key features:**\n * - Directly access context properties as if they were on the machine object\n * - Call transition methods to update state through the store\n * - Type-safe integration with TypeScript\n * - Seamless Proxy-based API (no special method names or API quirks)\n *\n * **How it works:**\n * The returned Proxy intercepts property access. For context properties, it returns\n * values from the store. For methods, it calls them on the MultiMachine instance.\n * This creates the illusion of a single object that is both data and behavior.\n *\n * @template C - The shared context type.\n * @template T - The MultiMachine class type.\n *\n * @param MachineClass - The class you defined that extends `MultiMachineBase<C>`.\n * @param store - The `StateStore` that will manage the machine's context.\n * @returns A Proxy that merges context properties with class methods, allowing\n * direct access to both via a unified object interface.\n *\n * @example\n * // Define your context type\n * type CounterContext = { count: number };\n *\n * // Define your machine class\n * class CounterMachine extends MultiMachineBase<CounterContext> {\n * increment() {\n * this.setContext({ count: this.context.count + 1 });\n * }\n *\n * add(n: number) {\n * this.setContext({ count: this.context.count + n });\n * }\n *\n * reset() {\n * this.setContext({ count: 0 });\n * }\n * }\n *\n * // Create a store\n * let sharedContext = { count: 0 };\n * const store = {\n * getContext: () => sharedContext,\n * setContext: (ctx) => { sharedContext = ctx; }\n * };\n *\n * // Create the machine instance\n * const machine = createMultiMachine(CounterMachine, store);\n *\n * // Use it naturally - properties and methods seamlessly integrated\n * console.log(machine.count); // 0\n * machine.increment();\n * console.log(machine.count); // 1\n * machine.add(5);\n * console.log(machine.count); // 6\n * machine.reset();\n * console.log(machine.count); // 0\n *\n * @example\n * // Status-based state machine with type discrimination\n * type AppContext = {\n * status: 'idle' | 'loading' | 'success' | 'error';\n * data?: any;\n * error?: string;\n * };\n *\n * class AppMachine extends MultiMachineBase<AppContext> {\n * async fetch() {\n * this.setContext({ ...this.context, status: 'loading' });\n * try {\n * const data = await fetch('/api/data').then(r => r.json());\n * this.setContext({ status: 'success', data });\n * } catch (error) {\n * this.setContext({\n * status: 'error',\n * error: error instanceof Error ? error.message : 'Unknown error'\n * });\n * }\n * }\n *\n * reset() {\n * this.setContext({ status: 'idle' });\n * }\n * }\n *\n * // Set up\n * let context: AppContext = { status: 'idle' };\n * const store = {\n * getContext: () => context,\n * setContext: (ctx) => { context = ctx; }\n * };\n *\n * const app = createMultiMachine(AppMachine, store);\n *\n * // Use naturally with type discrimination\n * console.log(app.status); // 'idle'\n *\n * if (app.status === 'idle') {\n * app.fetch(); // Transition to loading\n * }\n *\n * // Later: app.status === 'success'\n * // console.log(app.data); // Access the data\n */\nexport function createMultiMachine<\n C extends object,\n T extends MultiMachineBase<C>\n>(\n MachineClass: new (store: StateStore<C>) => T,\n store: StateStore<C>\n): C & T {\n const instance = new MachineClass(store);\n\n return new Proxy({} as C & T, {\n get(_target, prop: string | symbol) {\n // 1. Prioritize properties from the context\n const context = store.getContext();\n if (prop in context) {\n return (context as any)[prop];\n }\n\n // 2. Then check for methods on the instance\n const method = (instance as any)[prop];\n if (typeof method === 'function') {\n return (...args: any[]) => {\n return method.apply(instance, args);\n };\n }\n\n return undefined;\n },\n\n set(_target, prop: string | symbol, value: any) {\n // Allow direct mutation of context properties\n const context = store.getContext();\n if (prop in context) {\n const newContext = { ...context, [prop]: value } as C;\n store.setContext(newContext);\n return true;\n }\n return false;\n },\n\n has(_target, prop: string | symbol) {\n // Support `in` operator checks\n const context = store.getContext();\n return prop in context || typeof (instance as any)[prop] === 'function';\n },\n\n ownKeys(_target) {\n // Support reflection APIs\n const context = store.getContext();\n const contextKeys = Object.keys(context);\n const methodKeys = Object.getOwnPropertyNames(\n Object.getPrototypeOf(instance)\n ).filter((key) => key !== 'constructor' && typeof (instance as any)[key] === 'function');\n return Array.from(new Set([...contextKeys, ...methodKeys]));\n },\n\n getOwnPropertyDescriptor(_target, prop) {\n // Support property descriptors\n const context = store.getContext();\n if (prop in context || typeof (instance as any)[prop] === 'function') {\n return {\n value: undefined,\n writable: true,\n enumerable: true,\n configurable: true,\n };\n }\n return undefined;\n },\n });\n}\n\n// =============================================================================\n// SECTION 5: THE MUTABLE MACHINE (EXPERIMENTAL)\n// =============================================================================\n\n/**\n * A mapped type that defines the shape of a Mutable Machine: an intersection\n * of the context `C` and all possible transitions.\n */\ntype MutableMachine<C extends object, AllMachines extends Machine<any>> = C &\n AllTransitions<AllMachines>;\n\n\n /**\n * Creates a Mutable Machine that uses a shared, mutable context. This primitive\n * provides a stable object reference whose properties are mutated in place,\n * offering a direct, imperative API.\n *\n * ---\n *\n * ### Key Characteristics & Trade-offs\n *\n * - **Stable Object Reference**: The machine is a single object. You can pass this\n * reference around, and it will always reflect the current state.\n * - **Direct Imperative API**: Transitions are called like methods directly on the\n * object (`machine.login('user')`), and the object's properties update immediately.\n * - **No State History**: Since the context is mutated, the history of previous\n * states is not preserved, which makes patterns like time-travel debugging impossible.\n * - **Not for Reactive UIs**: Most UI frameworks (React, Solid, Vue) rely on\n * immutable state changes to trigger updates. Mutating the context directly\n * will not cause components to re-render. Use the `Ensemble` primitive for UI integration.\n *\n * ---\n *\n * ### Best Suited For\n *\n * - **Backend Services & Game Logic**: Ideal for managing state in server-side\n * processes, game loops, or other non-UI environments where performance and a\n * stable state object are priorities.\n * - **Complex Synchronous Scripts**: Useful for orchestrating data processing\n * pipelines, command-line tools, or any script where state needs to be managed\n * imperatively without passing it through a function chain.\n *\n * @template C - The shared context type.\n * @template F - An object of functions that create machine instances for each state.\n * **Crucially, transitions inside these machines must be pure functions that\n * return the *next context object*, not a new machine instance.**\n * @param sharedContext - The initial context object. This object will be mutated.\n * @param factories - An object mapping state names to functions that create machine instances.\n * @param getDiscriminant - An accessor function that takes the context and returns the key\n * of the current state in the `factories` object. Provides refactoring safety.\n * @returns A Proxy that acts as a stable, mutable machine instance.\n *\n * @example\n * // ===== 1. Basic Authentication Example =====\n *\n * type AuthContext =\n * | { status: 'loggedOut'; error?: string }\n * | { status: 'loggedIn'; username: string };\n *\n * const authFactories = {\n * loggedOut: (ctx: AuthContext) => ({\n * context: ctx,\n * // This transition is a PURE function that returns the NEXT CONTEXT\n * login: (username: string) => ({ status: 'loggedIn', username }),\n * }),\n * loggedIn: (ctx: AuthContext) => ({\n * context: ctx,\n * logout: () => ({ status: 'loggedOut' }),\n * }),\n * };\n *\n * const authUser = createMutableMachine(\n * { status: 'loggedOut' } as AuthContext,\n * authFactories,\n * 'status'\n * );\n *\n * const userReference = authUser; // Store a reference to the object\n *\n * console.log(authUser.status); // 'loggedOut'\n *\n * authUser.login('alice'); // Mutates the object in place\n *\n * console.log(authUser.status); // 'loggedIn'\n * console.log(authUser.username); // 'alice'\n *\n * // The original reference points to the same, mutated object\n * console.log(userReference.status); // 'loggedIn'\n * console.log(userReference === authUser); // true\n *\n * // --- Type-safe transitions ---\n * // `authUser.login('bob')` would now throw a runtime error because `login`\n * // is not a valid action in the 'loggedIn' state.\n *\n * if (authUser.status === 'loggedIn') {\n * // TypeScript correctly narrows the type here, allowing a safe call.\n * authUser.logout();\n * }\n * console.log(authUser.status); // 'loggedOut'\n *\n * @example\n * // ===== 2. Game State Loop Example =====\n *\n * type PlayerContext = {\n * state: 'idle' | 'walking' | 'attacking';\n * hp: number;\n * position: { x: number; y: number };\n * };\n *\n * const playerFactories = {\n * idle: (ctx: PlayerContext) => ({\n * context: ctx,\n * walk: (dx: number, dy: number) => ({ ...ctx, state: 'walking', position: { x: ctx.position.x + dx, y: ctx.position.y + dy } }),\n * attack: () => ({ ...ctx, state: 'attacking' }),\n * }),\n * walking: (ctx: PlayerContext) => ({\n * context: ctx,\n * stop: () => ({ ...ctx, state: 'idle' }),\n * }),\n * attacking: (ctx: PlayerContext) => ({\n * context: ctx,\n * finishAttack: () => ({ ...ctx, state: 'idle' }),\n * }),\n * };\n *\n * const player = createMutableMachine(\n * { state: 'idle', hp: 100, position: { x: 0, y: 0 } },\n * playerFactories,\n * (ctx) => ctx.state\n * );\n *\n * // Simulate a game loop\n * function processInput(input: 'move_right' | 'attack') {\n * if (player.state === 'idle') {\n * if (input === 'move_right') player.walk(1, 0);\n * if (input === 'attack') player.attack();\n * }\n * console.log(`State: ${player.state}, Position: (${player.position.x}, ${player.position.y})`);\n * }\n *\n * processInput('move_right'); // State: walking, Position: (1, 0)\n * player.stop();\n * processInput('attack'); // State: attacking, Position: (1, 0)\n */\nexport function createMutableMachine<\n C extends object,\n F extends Record<string, (context: C) => Machine<C>>\n>(\n sharedContext: C,\n factories: F,\n getDiscriminant: (context: C) => keyof F\n): MutableMachine<C, ReturnType<F[keyof F]>> {\n const getCurrentMachine = (): ReturnType<F[keyof F]> => {\n const currentStateName = getDiscriminant(sharedContext);\n const factory = factories[currentStateName];\n if (!factory) {\n throw new Error(\n `[MutableMachine] Invalid state: No factory for state \"${String(currentStateName)}\".`\n );\n }\n return factory(sharedContext) as ReturnType<F[keyof F]>;\n };\n\n return new Proxy(sharedContext, {\n get(target, prop, _receiver) {\n // 1. Prioritize properties on the context object itself.\n if (prop in target) {\n return (target as any)[prop];\n }\n\n // 2. If not on context, check if it's a valid transition for the current state.\n const currentMachine = getCurrentMachine();\n const transition = (currentMachine as any)[prop];\n\n if (typeof transition === 'function') {\n return (...args: any[]) => {\n // This pattern requires transitions to be pure functions that return the next context.\n const nextContext = transition.apply(currentMachine, args);\n if (typeof nextContext !== 'object' || nextContext === null) {\n console.warn(`[MutableMachine] Transition \"${String(prop)}\" did not return a valid context object. State may be inconsistent.`);\n return;\n }\n // 3. Mutate the shared context with the result.\n // Clear existing keys before assigning to handle removed properties.\n Object.keys(target).forEach(key => delete (target as any)[key]);\n Object.assign(target, nextContext);\n };\n }\n\n return undefined;\n },\n set(target, prop, value, _receiver) {\n // Allow direct mutation of the context\n (target as any)[prop] = value;\n return true;\n },\n has(target, prop) {\n // Let checks like `if ('login' in machine)` work correctly.\n const currentMachine = getCurrentMachine();\n return prop in target || typeof (currentMachine as any)[prop] === 'function';\n }\n }) as MutableMachine<C, ReturnType<F[keyof F]>>;\n}\n", "/**\n * @file Higher-Level Abstractions for @doeixd/machine\n * @description\n * This module provides a collection of powerful, pre-built patterns and primitives\n * on top of the core `@doeixd/machine` library. These utilities are designed to\n * solve common, recurring problems in state management, such as data fetching,\n * hierarchical state, and toggling boolean context properties.\n *\n * Think of this as the \"standard library\" of common machine patterns.\n */\n\nimport {\n MachineBase,\n Machine,\n Transitions,\n // AsyncMachine,\n setContext,\n Context,\n // MaybePromise,\n} from './index'; // Assuming this is a sibling package or in the same project\n\n// =============================================================================\n// SECTION 1: CUSTOM PRIMITIVES FOR COMPOSITION\n// =============================================================================\n\n/**\n * A type utility to infer the child machine type from a parent.\n */\ntype ChildMachine<P> = P extends MachineBase<{ child: infer C }> ? C : never;\n\n/**\n * Creates a transition method that delegates a call to a child machine.\n *\n * This is a higher-order function that reduces boilerplate when implementing\n * hierarchical state machines. It generates a method for the parent machine that:\n * 1. Checks if the specified action exists on the current child state.\n * 2. If it exists, calls the action on the child.\n * 3. Reconstructs the parent machine with the new child state returned by the action.\n * 4. If the action doesn't exist on the child, it returns the parent machine unchanged.\n *\n * @template P - The parent machine type, which must have a `child` property in its context.\n * @template K - The name of the action on the child machine to delegate to.\n * @param actionName - The string name of the child's transition method.\n * @param ...args - Any arguments to pass to the child's transition method.\n * @returns The parent machine instance, with its `child` state potentially updated.\n *\n * @example\n * ```typescript\n * class Parent extends MachineBase<{ child: ChildMachine }> {\n * // Instead of writing a manual delegation method...\n * // save = () => {\n * // if ('save' in this.context.child) {\n * // const newChild = this.context.child.save();\n * // return setContext(this, { child: newChild });\n * // }\n * // return this;\n * // }\n * \n * // ...you can just use the primitive.\n * save = delegateToChild('save');\n * edit = delegateToChild('edit');\n * }\n * ```\n */\nexport function delegateToChild<\n P extends MachineBase<{ child: MachineBase<any> }>,\n K extends keyof ChildMachine<P> & string\n>(\n actionName: K\n): (\n ...args: ChildMachine<P>[K] extends (...a: infer A) => any ? A : never\n) => P {\n return function(this: P, ...args: any[]): P {\n const child = this.context.child as any;\n\n if (typeof child[actionName] === 'function') {\n const newChildState = child[actionName](...args);\n return setContext(this as any, { ...this.context, child: newChildState }) as P;\n }\n \n // If the action is not available on the current child state, do nothing.\n return this;\n };\n}\n\n/**\n * Creates a transition method that toggles a boolean property within the machine's context.\n *\n * This is a simple utility to reduce boilerplate for managing boolean flags.\n *\n * @template M - The machine type.\n * @template K - The key of the boolean property in the machine's context.\n * @param prop - The string name of the context property to toggle.\n * @returns A new machine instance with the toggled property.\n *\n * @example\n * ```typescript\n * class SettingsMachine extends MachineBase<{ notifications: boolean; darkMode: boolean }> {\n * toggleNotifications = toggle('notifications');\n * toggleDarkMode = toggle('darkMode');\n * }\n * ```\n */\nexport function toggle<\n M extends MachineBase<any>,\n K extends keyof Context<M>\n>(\n prop: K\n): (this: M) => M {\n return function(this: M): M {\n // Ensure the property is boolean-like for a sensible toggle\n if (typeof this.context[prop] !== 'boolean') {\n console.warn(`[toggle primitive] Property '${String(prop)}' is not a boolean. Toggling may have unexpected results.`);\n }\n return setContext(this as any, {\n ...this.context,\n [prop]: !this.context[prop],\n }) as M;\n };\n}\n\n\n// =============================================================================\n// SECTION 2: PRE-BUILT, CUSTOMIZABLE MACHINES\n// =============================================================================\n\n/**\n * A fully-featured, pre-built state machine for data fetching.\n * It handles loading, success, error states, cancellation, and retry logic out of the box.\n *\n * This machine is highly customizable through its configuration options.\n */\n\n// --- Types for the Fetch Machine ---\n\nexport type Fetcher<T, _E = Error> = (params: any) => Promise<T>;\nexport type OnSuccess<T> = (data: T) => void;\nexport type OnError<E> = (error: E) => void;\n\nexport interface FetchMachineConfig<T, E = Error> {\n fetcher: Fetcher<T, E>;\n initialParams?: any;\n maxRetries?: number;\n onSuccess?: OnSuccess<T>;\n onError?: OnError<E>;\n}\n\n// --- Contexts for Fetch States ---\ntype IdleContext = { status: 'idle' };\ntype LoadingContext = { status: 'loading'; abortController: AbortController; attempts: number };\ntype RetryingContext = { status: 'retrying'; error: any; attempts: number };\ntype SuccessContext<T> = { status: 'success'; data: T };\ntype ErrorContext<E> = { status: 'error'; error: E };\ntype CanceledContext = { status: 'canceled' };\n\n// --- Machine State Classes (internal) ---\n\nclass IdleMachine<T, E> extends MachineBase<IdleContext> {\n constructor(private config: FetchMachineConfig<T, E>) { super({ status: 'idle' }); }\n fetch = (params?: any) => new LoadingMachine(this.config, params ?? this.config.initialParams, 1);\n}\n\nclass LoadingMachine<T, E> extends MachineBase<LoadingContext> {\n constructor(private config: FetchMachineConfig<T, E>, private params: any, attempts: number) {\n super({ status: 'loading', abortController: new AbortController(), attempts });\n this.execute(); // Auto-execute on creation\n }\n\n private async execute() {\n // This is a \"fire-and-forget\" call that transitions the machine internally.\n // In a real implementation, this would be managed by an external runner.\n // For this example, we assume an external mechanism calls `succeed`, `fail`, etc.\n }\n \n succeed = (data: T) => {\n this.config.onSuccess?.(data);\n return new SuccessMachine<T, E>(this.config, { status: 'success', data });\n };\n\n fail = (error: E) => {\n const maxRetries = this.config.maxRetries ?? 3;\n if (this.context.attempts < maxRetries) {\n return new RetryingMachine<T, E>(this.config, this.params, error, this.context.attempts);\n }\n this.config.onError?.(error);\n return new ErrorMachine<T, E>(this.config, { status: 'error', error });\n };\n \n cancel = () => {\n this.context.abortController.abort();\n return new CanceledMachine<T, E>(this.config);\n };\n}\n\nclass RetryingMachine<T, E> extends MachineBase<RetryingContext> {\n constructor(private config: FetchMachineConfig<T, E>, private params: any, error: E, attempts: number) {\n super({ status: 'retrying', error, attempts });\n // In a real implementation, you'd have a delay here (e.g., exponential backoff)\n // before transitioning to LoadingMachine again.\n }\n \n // This would be called after a delay.\n retry = (params?: any) => new LoadingMachine<T, E>(this.config, params ?? this.params, this.context.attempts + 1);\n}\n\nclass SuccessMachine<T, E> extends MachineBase<SuccessContext<T>> {\n constructor(private config: FetchMachineConfig<T, E>, context: SuccessContext<T>) { super(context); }\n refetch = (params?: any) => new LoadingMachine(this.config, params ?? this.config.initialParams, 1);\n}\n\nclass ErrorMachine<T, E> extends MachineBase<ErrorContext<E>> {\n constructor(private config: FetchMachineConfig<T, E>, context: ErrorContext<E>) { super(context); }\n retry = (params?: any) => new LoadingMachine(this.config, params ?? this.config.initialParams, 1);\n}\n\nclass CanceledMachine<T, E> extends MachineBase<CanceledContext> {\n constructor(private config: FetchMachineConfig<T, E>) { super({ status: 'canceled' }); }\n refetch = (params?: any) => new LoadingMachine(this.config, params ?? this.config.initialParams, 1);\n}\n\nexport type FetchMachine<T, E = Error> =\n | IdleMachine<T, E>\n | LoadingMachine<T, E>\n | RetryingMachine<T, E>\n | SuccessMachine<T, E>\n | ErrorMachine<T, E>\n | CanceledMachine<T, E>;\n\n/**\n * Creates a pre-built, highly configurable async data-fetching machine.\n *\n * This factory function returns a state machine that handles the entire lifecycle\n * of a data request, including loading, success, error, cancellation, and retries.\n *\n * @template T - The type of the data to be fetched.\n * @template E - The type of the error.\n * @param config - Configuration object.\n * @param config.fetcher - An async function that takes params and returns the data.\n * @param [config.maxRetries=3] - The number of times to retry on failure.\n * @param [config.onSuccess] - Optional callback fired with the data on success.\n * @param [config.onError] - Optional callback fired with the error on final failure.\n * @returns An `IdleMachine` instance, ready to start fetching.\n *\n * @example\n * ```typescript\n * // 1. Define your data fetching logic\n * async function fetchUser(id: number): Promise<{ id: number; name: string }> {\n * const res = await fetch(`/api/users/${id}`);\n * if (!res.ok) throw new Error('User not found');\n * return res.json();\n * }\n *\n * // 2. Create the machine\n * const userMachine = createFetchMachine({\n * fetcher: fetchUser,\n * onSuccess: (user) => console.log(`Fetched: ${user.name}`),\n * });\n *\n * // 3. Use it (e.g., in a React hook)\n * // let machine = userMachine;\n * // machine = await machine.fetch(123); // Transitions to Loading, then Success/Error\n * ```\n * \n * @note This is a simplified example. For a real-world implementation, you would\n * typically use this machine with a runner (like `runMachine` or `useMachine`) to\n * manage the async transitions and state updates automatically.\n */\nexport function createFetchMachine<T, E = Error>(\n config: FetchMachineConfig<T, E>\n): FetchMachine<T, E> {\n // A more robust implementation would validate the config here.\n return new IdleMachine<T, E>(config);\n}\n\n/**\n * The core type for a Parallel Machine.\n * It combines two machines, M1 and M2, into a single, unified type.\n * @template M1 - The first machine in the parallel composition.\n * @template M2 - The second machine in the parallel composition.\n */\nexport type ParallelMachine<\n M1 extends Machine<any>,\n M2 extends Machine<any>\n> = Machine<Context<M1> & Context<M2>> & {\n // Map transitions from M1. When called, they return a new ParallelMachine\n // where M1 has transitioned but M2 remains the same.\n [K in keyof Transitions<M1>]: Transitions<M1>[K] extends (...args: infer A) => infer R\n ? R extends Machine<any>\n ? (...args: A) => ParallelMachine<R, M2>\n : never\n : never;\n} & {\n // Map transitions from M2. When called, they return a new ParallelMachine\n // where M2 has transitioned but M1 remains the same.\n [K in keyof Transitions<M2>]: Transitions<M2>[K] extends (...args: infer A) => infer R\n ? R extends Machine<any>\n ? (...args: A) => ParallelMachine<M1, R>\n : never\n : never;\n};\n\n\n/**\n * Creates a parallel machine by composing two independent machines.\n *\n * This function takes two machines and merges them into a single machine entity.\n * Transitions from either machine can be called, and they will only affect\n * their respective part of the combined state.\n *\n * NOTE: This primitive assumes that the transition names between the two\n * machines do not collide. If both machines have a transition named `next`,\n * the behavior is undefined.\n *\n * @param m1 The first machine instance.\n * @param m2 The second machine instance.\n * @returns A new ParallelMachine instance.\n */\nexport function createParallelMachine<\n M1 extends Machine<any>,\n M2 extends Machine<any>\n>(m1: M1, m2: M2): ParallelMachine<M1, M2> {\n // 1. Combine the contexts\n const combinedContext = { ...m1.context, ...m2.context };\n\n const transitions1 = { ...m1 } as Transitions<M1>;\n const transitions2 = { ...m2 } as Transitions<M2>;\n delete (transitions1 as any).context;\n delete (transitions2 as any).context;\n\n const combinedTransitions = {} as any;\n\n // 2. Re-wire transitions from the first machine\n for (const key in transitions1) {\n const transitionFn = (transitions1 as any)[key];\n combinedTransitions[key] = (...args: any[]) => {\n const nextM1 = transitionFn.apply(m1, args);\n // Recursively create a new parallel machine with the new M1 state\n return createParallelMachine(nextM1, m2);\n };\n }\n\n // 3. Re-wire transitions from the second machine\n for (const key in transitions2) {\n const transitionFn = (transitions2 as any)[key];\n combinedTransitions[key] = (...args: any[]) => {\n const nextM2 = transitionFn.apply(m2, args);\n // Recursively create a new parallel machine with the new M2 state\n return createParallelMachine(m1, nextM2);\n };\n }\n\n return {\n context: combinedContext,\n ...combinedTransitions,\n } as ParallelMachine<M1, M2>;\n}\n\n// A mapped type that transforms the return types of a machine's transitions.\n// For a transition that returns `NewMachineState`, this will transform it to return `T`.\nexport type RemapTransitions<M extends Machine<any>, T> = {\n [K in keyof Transitions<M>]: Transitions<M>[K] extends (...args: infer A) => any\n ? (...args: A) => T\n : never;\n};", "/**\n * @file Core middleware types and basic middleware creation\n */\n\nimport type { Context, BaseMachine } from '../index';\n\n// =============================================================================\n// SECTION: MIDDLEWARE TYPES\n// =============================================================================\n\n/**\n * Context object passed to middleware hooks containing transition metadata.\n * @template C - The context object type\n */\nexport interface MiddlewareContext<C extends object> {\n /** The name of the transition being called */\n transitionName: string;\n /** The current machine context before the transition */\n context: Readonly<C>;\n /** Arguments passed to the transition function */\n args: any[];\n}\n\n/**\n * Result object passed to after hooks containing transition outcome.\n * @template C - The context object type\n */\nexport interface MiddlewareResult<C extends object> {\n /** The name of the transition that was called */\n transitionName: string;\n /** The context before the transition */\n prevContext: Readonly<C>;\n /** The context after the transition */\n nextContext: Readonly<C>;\n /** Arguments that were passed to the transition */\n args: any[];\n}\n\n/**\n * Error context passed to error hooks.\n * @template C - The context object type\n */\nexport interface MiddlewareError<C extends object> {\n /** The name of the transition that failed */\n transitionName: string;\n /** The context when the error occurred */\n context: Readonly<C>;\n /** Arguments that were passed to the transition */\n args: any[];\n /** The error that was thrown */\n error: Error;\n}\n\n/**\n * Configuration object for middleware hooks.\n * All hooks are optional - provide only the ones you need.\n * @template C - The context object type\n */\nexport interface MiddlewareHooks<C extends object> {\n /**\n * Called before a transition executes.\n * Can be used for validation, logging, analytics, etc.\n *\n * @param ctx - Transition context with machine state and transition details\n * @returns void to continue, CANCEL to abort silently, or Promise for async validation\n */\n before?: (ctx: MiddlewareContext<C>) => void | typeof CANCEL | Promise<void | typeof CANCEL>;\n\n /**\n * Called after a transition successfully executes.\n * Receives both the previous and next context.\n * Cannot prevent the transition (it already happened).\n *\n * @param result - Transition result with before/after contexts and transition details\n */\n after?: (result: MiddlewareResult<C>) => void | Promise<void>;\n\n /**\n * Called when a transition throws an error.\n * Can be used for error reporting, recovery, etc.\n *\n * @param error - Error context with transition details and error information\n */\n error?: (error: MiddlewareError<C>) => void | Promise<void>;\n}\n\n/**\n * Options for configuring middleware behavior.\n */\nexport interface MiddlewareOptions {\n /** Whether to continue execution if a hook throws an error */\n continueOnError?: boolean;\n /** Whether to log errors from hooks */\n logErrors?: boolean;\n /** Custom error handler for hook errors */\n onError?: (error: Error, hookName: string, ctx: any) => void;\n}\n\n/**\n * Symbol used to cancel a transition from a before hook.\n */\nexport const CANCEL = Symbol('CANCEL');\n\n// =============================================================================\n// SECTION: CORE MIDDLEWARE FUNCTIONS\n// =============================================================================\n\n/**\n * Creates a middleware function that wraps machine transitions with hooks.\n *\n * @template M - The machine type\n * @param machine - The machine to instrument\n * @param hooks - Middleware hooks to execute\n * @param options - Middleware configuration options\n * @returns A new machine with middleware applied\n */\nexport function createMiddleware<M extends BaseMachine<any>>(\n machine: M,\n hooks: MiddlewareHooks<Context<M>>,\n options: MiddlewareOptions = {}\n): M {\n const { continueOnError = false, logErrors = true, onError } = options;\n\n // Create a wrapped machine that intercepts all transition calls\n const wrappedMachine: any = { ...machine };\n\n // Copy any extra properties from the original machine (for middleware composition)\n for (const prop in machine) {\n if (!Object.prototype.hasOwnProperty.call(machine, prop)) continue;\n if (prop !== 'context' && typeof machine[prop] !== 'function') {\n wrappedMachine[prop] = machine[prop];\n }\n }\n\n // Wrap each transition function\n for (const prop in machine) {\n if (!Object.prototype.hasOwnProperty.call(machine, prop)) continue;\n const value = machine[prop];\n if (typeof value === 'function' && prop !== 'context') {\n wrappedMachine[prop] = function (this: any, ...args: any[]) {\n const transitionName = prop;\n const context = wrappedMachine.context;\n\n // Helper function to execute the transition and after hooks\n const executeTransition = () => {\n // 2. Execute the actual transition\n let nextMachine: any;\n try {\n nextMachine = value.apply(this, args);\n } catch (error) {\n // 3. Execute error hooks if transition failed\n if (hooks.error) {\n try {\n // Error hooks are called synchronously for now\n hooks.error({\n transitionName,\n context,\n args: [...args],\n error: error as Error\n });\n } catch (hookError) {\n if (!continueOnError) throw hookError;\n if (logErrors) console.error(`Middleware error hook error for ${transitionName}:`, hookError);\n onError?.(hookError as Error, 'error', { transitionName, context, args, error });\n }\n }\n throw error; // Re-throw the original error\n }\n\n // Ensure the returned machine has the same extra properties as the wrapped machine\n const ensureMiddlewareProperties = (machine: any) => {\n if (machine && typeof machine === 'object' && machine.context) {\n // Copy extra properties from the wrapped machine to the returned machine\n for (const prop in wrappedMachine) {\n if (!Object.prototype.hasOwnProperty.call(wrappedMachine, prop)) continue;\n if (prop !== 'context' && !(prop in machine)) {\n machine[prop] = wrappedMachine[prop];\n }\n }\n\n // Also wrap the transition functions on the returned machine\n for (const prop in machine) {\n if (!Object.prototype.hasOwnProperty.call(machine, prop)) continue;\n const value = machine[prop];\n if (typeof value === 'function' && prop !== 'context' && wrappedMachine[prop]) {\n machine[prop] = wrappedMachine[prop];\n }\n }\n }\n return machine;\n };\n\n // Check if the transition is async (returns a Promise)\n if (nextMachine && typeof nextMachine.then === 'function') {\n // For async transitions, we need to handle the after hooks after the promise resolves\n const asyncResult = nextMachine.then((resolvedMachine: any) => {\n // Ensure middleware properties are attached\n ensureMiddlewareProperties(resolvedMachine);\n\n // Execute after hooks with the resolved machine\n if (hooks.after) {\n try {\n const result = hooks.after({\n transitionName,\n prevContext: context,\n nextContext: resolvedMachine.context,\n args: [...args]\n });\n\n // Handle async after hooks\n if (result && typeof result.then === 'function') {\n return result.then(() => resolvedMachine);\n }\n } catch (error) {\n if (!continueOnError) throw error;\n if (logErrors) console.error(`Middleware after hook error for ${transitionName}:`, error);\n onError?.(error as Error, 'after', {\n transitionName,\n prevContext: context,\n nextContext: resolvedMachine.context,\n args\n });\n }\n }\n return resolvedMachine;\n });\n\n return asyncResult;\n } else {\n // Ensure middleware properties are attached to synchronous transitions\n ensureMiddlewareProperties(nextMachine);\n\n // Synchronous transition\n // 4. Execute after hooks\n if (hooks.after) {\n try {\n const result = hooks.after({\n transitionName,\n prevContext: context,\n nextContext: nextMachine.context,\n args: [...args]\n });\n\n // Handle async after hooks\n if (result && typeof result === 'object' && result && 'then' in result) {\n return result.then(() => nextMachine).catch((error: Error) => {\n if (!continueOnError) throw error;\n if (logErrors) console.error(`Middleware after hook error for ${transitionName}:`, error);\n onError?.(error, 'after', {\n transitionName,\n prevContext: context,\n nextContext: nextMachine.context,\n args\n });\n return nextMachine;\n });\n }\n } catch (error) {\n if (!continueOnError) throw error;\n if (logErrors) console.error(`Middleware after hook error for ${transitionName}:`, error);\n onError?.(error as Error, 'after', {\n transitionName,\n prevContext: context,\n nextContext: nextMachine.context,\n args\n });\n }\n }\n\n // 5. Return the next machine state\n return nextMachine;\n }\n };\n\n // 1. Execute before hooks synchronously if possible\n if (hooks.before) {\n try {\n const result = hooks.before({\n transitionName,\n context,\n args: [...args]\n });\n\n // Handle async hooks\n if (result && typeof result === 'object' && result && 'then' in result) {\n // For async hooks, return a promise that executes the transition after\n return result.then((hookResult: any) => {\n if (hookResult === CANCEL) {\n return wrappedMachine;\n }\n return executeTransition();\n }).catch((error: Error) => {\n if (!continueOnError) throw error;\n if (logErrors) console.error(`Middleware before hook error for ${transitionName}:`, error);\n onError?.(error, 'before', { transitionName, context, args });\n return executeTransition();\n });\n }\n\n // Check if transition should be cancelled\n if (result === CANCEL) {\n return wrappedMachine; // Return the same machine instance\n }\n } catch (error) {\n if (!continueOnError) throw error;\n if (logErrors) console.error(`Middleware before hook error for ${transitionName}:`, error);\n onError?.(error as Error, 'before', { transitionName, context, args });\n }\n };\n\n return executeTransition();\n };\n }\n }\n\n return wrappedMachine;\n}\n\n/**\n * Creates a simple logging middleware that logs all transitions.\n *\n * @template M - The machine type\n * @param machine - The machine to add logging to\n * @param options - Logging configuration options\n * @returns A new machine with logging middleware\n */\nexport function withLogging<M extends BaseMachine<any>>(\n machine: M,\n options: {\n logger?: (message: string) => void;\n includeArgs?: boolean;\n includeContext?: boolean;\n } = {}\n): M {\n const { logger = console.log, includeArgs = false, includeContext = true } = options;\n\n return createMiddleware(machine, {\n before: ({ transitionName, args }) => {\n const message = includeArgs ? `→ ${transitionName} [${args.join(', ')}]` : `→ ${transitionName}`;\n logger(message);\n },\n after: ({ transitionName, nextContext }) => {\n const contextStr = includeContext ? ` ${JSON.stringify(nextContext)}` : '';\n logger(`✓ ${transitionName}${contextStr}`);\n },\n error: ({ transitionName, error }) => {\n console.error(`[Machine] ${transitionName} failed:`, error);\n }\n });\n}\n\n/**\n * Creates analytics tracking middleware.\n *\n * @template M - The machine type\n * @param machine - The machine to track\n * @param track - Analytics tracking function\n * @param options - Configuration options\n * @returns A new machine with analytics tracking\n */\nexport function withAnalytics<M extends BaseMachine<any>>(\n machine: M,\n track: (event: string, data?: any) => void,\n options: {\n eventPrefix?: string;\n includePrevContext?: boolean;\n includeArgs?: boolean;\n } = {}\n): M {\n const { eventPrefix = 'state_transition', includePrevContext = false, includeArgs = false } = options;\n\n return createMiddleware(machine, {\n after: ({ transitionName, prevContext, nextContext, args }) => {\n const event = `${eventPrefix}.${transitionName}`;\n const data: any = { transition: transitionName };\n if (includePrevContext) data.from = prevContext;\n data.to = nextContext;\n if (includeArgs) data.args = args;\n track(event, data);\n }\n });\n}\n\n/**\n * Creates validation middleware that runs before transitions.\n *\n * @template M - The machine type\n * @param machine - The machine to validate\n * @param validator - Validation function\n * @returns A new machine with validation\n */\nexport function withValidation<M extends BaseMachine<any>>(\n machine: M,\n validator: (ctx: MiddlewareContext<Context<M>>) => boolean | void\n): M {\n return createMiddleware(machine, {\n before: (ctx) => {\n const result = validator(ctx);\n if (result === false) {\n throw new Error(`Validation failed for transition: ${ctx.transitionName}`);\n }\n }\n });\n}\n\n/**\n * Creates permission-checking middleware.\n *\n * @template M - The machine type\n * @param machine - The machine to protect\n * @param checker - Permission checking function\n * @returns A new machine with permission checks\n */\nexport function withPermissions<M extends BaseMachine<any>>(\n machine: M,\n checker: (ctx: MiddlewareContext<Context<M>>) => boolean\n): M {\n return createMiddleware(machine, {\n before: (ctx) => {\n if (!checker(ctx)) {\n throw new Error(`Unauthorized transition: ${ctx.transitionName}`);\n }\n }\n });\n}\n\n/**\n * Creates error reporting middleware.\n *\n * @template M - The machine type\n * @param machine - The machine to monitor\n * @param reporter - Error reporting function\n * @param options - Configuration options\n * @returns A new machine with error reporting\n */\nexport function withErrorReporting<M extends BaseMachine<any>>(\n machine: M,\n reporter: (error: Error, ctx: any) => void,\n options: { includeArgs?: boolean } = {}\n): M {\n const { includeArgs = false } = options;\n\n return createMiddleware(machine, {\n error: (errorCtx) => {\n // Format the context to match test expectations\n const formattedCtx = {\n transition: errorCtx.transitionName,\n context: errorCtx.context,\n ...(includeArgs && { args: errorCtx.args })\n };\n reporter(errorCtx.error, formattedCtx);\n }\n });\n}\n\n/**\n * Creates performance monitoring middleware.\n *\n * @template M - The machine type\n * @param machine - The machine to monitor\n * @param tracker - Performance tracking function\n * @returns A new machine with performance monitoring\n */\nexport function withPerformanceMonitoring<M extends BaseMachine<any>>(\n machine: M,\n tracker: (metric: { transitionName: string; duration: number; context: Context<M> }) => void\n): M {\n const startTimes = new Map<string, number>();\n\n return createMiddleware(machine, {\n before: (ctx) => {\n startTimes.set(ctx.transitionName, Date.now());\n },\n after: (result) => {\n const startTime = startTimes.get(result.transitionName);\n if (startTime) {\n const duration = Date.now() - startTime;\n startTimes.delete(result.transitionName);\n // For test compatibility, pass a single object as expected\n const testResult = {\n transitionName: result.transitionName,\n duration,\n context: result.nextContext || result.prevContext\n };\n tracker(testResult);\n }\n }\n });\n}\n\n/**\n * Creates retry middleware for failed transitions.\n *\n * @template M - The machine type\n * @param machine - The machine to add retry logic to\n * @param options - Retry configuration\n * @returns A new machine with retry logic\n */\nexport function withRetry<M extends BaseMachine<any>>(\n machine: M,\n options: {\n maxAttempts?: number;\n maxRetries?: number; // alias for maxAttempts\n shouldRetry?: (error: Error, attempt: number) => boolean;\n backoffMs?: number | ((attempt: number) => number);\n delay?: number | ((attempt: number) => number); // alias for backoffMs\n backoffMultiplier?: number; // multiplier for exponential backoff\n onRetry?: (error: Error, attempt: number) => void;\n } = {}\n): M {\n const {\n maxAttempts = options.maxRetries ?? 3,\n shouldRetry = () => true,\n backoffMs = options.delay ?? 100,\n backoffMultiplier = 2,\n onRetry\n } = options;\n\n // Create a wrapped machine that adds retry logic\n const wrappedMachine: any = { ...machine };\n\n // Wrap each transition function with retry logic\n for (const prop in machine) {\n if (!Object.prototype.hasOwnProperty.call(machine, prop)) continue;\n const value = machine[prop];\n if (typeof value === 'function' && prop !== 'context') {\n wrappedMachine[prop] = async function (this: any, ...args: any[]) {\n let lastError: Error;\n let attempt = 0;\n\n while (attempt < maxAttempts) {\n try {\n return await value.apply(this, args);\n } catch (error) {\n lastError = error as Error;\n attempt++;\n\n if (attempt < maxAttempts && shouldRetry(lastError, attempt)) {\n onRetry?.(lastError, attempt);\n const baseDelay = typeof backoffMs === 'function' ? backoffMs(attempt) : backoffMs;\n const delay = baseDelay * Math.pow(backoffMultiplier, attempt - 1);\n await new Promise(resolve => setTimeout(resolve, delay));\n } else {\n throw lastError;\n }\n }\n }\n\n throw lastError!;\n };\n\n\n\n }\n }\n\n return wrappedMachine;\n}\n\n/**\n * Creates custom middleware from hooks.\n *\n * @template M - The machine type\n * @param hooks - Middleware hooks\n * @param options - Middleware options\n * @returns A middleware function\n */\nexport function createCustomMiddleware<M extends BaseMachine<any>>(\n hooks: MiddlewareHooks<Context<M>>,\n options?: MiddlewareOptions\n): (machine: M) => M {\n return (machine: M) => createMiddleware(machine, hooks, options);\n}", "/**\n * @file History tracking middleware\n */\n\nimport type { BaseMachine } from '../index';\nimport { createMiddleware } from './core';\n\n// =============================================================================\n// SECTION: HISTORY TYPES\n// =============================================================================\n\n/**\n * A single history entry recording a transition.\n */\nexport interface HistoryEntry {\n /** Unique ID for this history entry */\n id: string;\n /** Name of the transition that was called */\n transitionName: string;\n /** Arguments passed to the transition */\n args: any[];\n /** Timestamp when the transition occurred */\n timestamp: number;\n /** Optional serialized version of args for persistence */\n serializedArgs?: string;\n}\n\n/**\n * Serializer interface for converting context/args to/from strings.\n */\nexport interface Serializer<T = any> {\n serialize: (value: T) => string;\n deserialize: (str: string) => T;\n}\n\n// =============================================================================\n// SECTION: HISTORY MIDDLEWARE\n// =============================================================================\n\n/**\n * Creates a machine with history tracking capabilities.\n * Records all transitions that occur, allowing you to see the sequence of state changes.\n *\n * @template M - The machine type\n * @param machine - The machine to track\n * @param options - Configuration options\n * @returns A new machine with history tracking\n *\n * @example\n * ```typescript\n * const tracked = withHistory(counter, { maxSize: 50 });\n * tracked.increment();\n * console.log(tracked.history); // [{ id: \"entry-1\", transitionName: \"increment\", ... }]\n * ```\n */\nexport function withHistory<M extends BaseMachine<any>>(\n machine: M,\n options: {\n /** Maximum number of history entries to keep (default: unlimited) */\n maxSize?: number;\n /** Optional serializer for transition arguments */\n serializer?: Serializer<any[]>;\n /** Callback when a transition occurs */\n onEntry?: (entry: HistoryEntry) => void;\n } = {}\n): M & { history: HistoryEntry[]; clearHistory: () => void } {\n const { maxSize, serializer, onEntry } = options;\n const history: HistoryEntry[] = [];\n let entryId = 0;\n\n const instrumentedMachine = createMiddleware(machine, {\n before: ({ transitionName, args }) => {\n const entry: HistoryEntry = {\n id: `entry-${entryId++}`,\n transitionName,\n args: [...args],\n timestamp: Date.now()\n };\n\n if (serializer) {\n try {\n entry.serializedArgs = serializer.serialize(args);\n } catch (err) {\n console.error('Failed to serialize history args:', err);\n }\n }\n\n history.push(entry);\n\n // Enforce max size\n if (maxSize && history.length > maxSize) {\n history.shift();\n }\n\n onEntry?.(entry);\n }\n });\n\n // Attach history properties to the machine\n return Object.assign(instrumentedMachine, {\n history,\n clearHistory: () => { history.length = 0; entryId = 0; }\n });\n}", "/**\n * @file Snapshot tracking middleware for context state\n */\n\nimport type { Context, BaseMachine } from '../index';\nimport { createMiddleware } from './core';\nimport type { Serializer } from './history';\n\n// =============================================================================\n// SECTION: SNAPSHOT TYPES\n// =============================================================================\n\n/**\n * A snapshot of machine context before and after a transition.\n */\nexport interface ContextSnapshot<C extends object> {\n /** Unique ID for this snapshot */\n id: string;\n /** Name of the transition that caused this snapshot */\n transitionName: string;\n /** Context before the transition */\n before: C;\n /** Context after the transition */\n after: C;\n /** Timestamp of the snapshot */\n timestamp: number;\n /** Optional serialized versions of contexts */\n serializedBefore?: string;\n serializedAfter?: string;\n /** Optional diff information */\n diff?: any;\n}\n\n// =============================================================================\n// SECTION: SNAPSHOT MIDDLEWARE\n// =============================================================================\n\n/**\n * Creates a machine with snapshot tracking capabilities.\n * Records context state before and after each transition for debugging and inspection.\n *\n * @template M - The machine type\n * @param machine - The machine to track\n * @param options - Configuration options\n * @returns A new machine with snapshot tracking\n *\n * @example\n * ```typescript\n * const tracked = withSnapshot(counter, {\n * maxSize: 50,\n * serializer: {\n * serialize: (ctx) => JSON.stringify(ctx),\n * deserialize: (str) => JSON.parse(str)\n * }\n * });\n *\n * tracked.increment();\n * console.log(tracked.snapshots); // [{ before: { count: 0 }, after: { count: 1 }, ... }]\n * ```\n */\nexport function withSnapshot<M extends BaseMachine<any>>(\n machine: M,\n options: {\n /** Maximum number of snapshots to keep (default: unlimited) */\n maxSize?: number;\n /** Optional serializer for context */\n serializer?: Serializer<Context<M>>;\n /** Custom function to capture additional snapshot data */\n captureSnapshot?: (before: Context<M>, after: Context<M>) => any;\n /** Only capture snapshots where context actually changed */\n onlyOnChange?: boolean;\n } = {}\n): M & {\n snapshots: ContextSnapshot<Context<M>>[];\n clearSnapshots: () => void;\n restoreSnapshot: (snapshot: ContextSnapshot<Context<M>>['before']) => M;\n} {\n const {\n maxSize,\n serializer,\n captureSnapshot,\n onlyOnChange = false\n } = options;\n\n const snapshots: ContextSnapshot<Context<M>>[] = [];\n let snapshotId = 0;\n\n const instrumentedMachine = createMiddleware(machine, {\n after: ({ transitionName, prevContext, nextContext }) => {\n // Skip if only capturing on change and context didn't change\n if (onlyOnChange && JSON.stringify(prevContext) === JSON.stringify(nextContext)) {\n return;\n }\n\n const snapshot: ContextSnapshot<Context<M>> = {\n id: `snapshot-${snapshotId++}`,\n transitionName,\n before: { ...prevContext },\n after: { ...nextContext },\n timestamp: Date.now()\n };\n\n // Serialize contexts if serializer provided\n if (serializer) {\n try {\n snapshot.serializedBefore = serializer.serialize(prevContext);\n snapshot.serializedAfter = serializer.serialize(nextContext);\n } catch (err) {\n console.error('Failed to serialize snapshot:', err);\n }\n }\n\n // Capture custom snapshot data\n if (captureSnapshot) {\n try {\n snapshot.diff = captureSnapshot(prevContext, nextContext);\n } catch (err) {\n console.error('Failed to capture snapshot:', err);\n }\n }\n\n snapshots.push(snapshot);\n\n // Enforce max size\n if (maxSize && snapshots.length > maxSize) {\n snapshots.shift();\n }\n }\n });\n\n // Helper to restore machine to a previous state\n const restoreSnapshot = (context: Context<M>): M => {\n // Find the machine's transition functions (excluding context and snapshot properties)\n const transitions = Object.fromEntries(\n Object.entries(machine).filter(([key]) =>\n key !== 'context' &&\n key !== 'snapshots' &&\n key !== 'clearSnapshots' &&\n key !== 'restoreSnapshot' &&\n typeof machine[key as keyof M] === 'function'\n )\n );\n\n return Object.assign({ context }, transitions) as M;\n };\n\n // Attach snapshot properties to the machine\n return Object.assign(instrumentedMachine, {\n snapshots,\n clearSnapshots: () => { snapshots.length = 0; snapshotId = 0; },\n restoreSnapshot\n });\n}", "/**\n * @file Time travel middleware combining history, snapshots, and replay capabilities\n */\n\nimport type { Context, BaseMachine } from '../index';\nimport { createMiddleware } from './core';\nimport { type HistoryEntry, type Serializer } from './history';\nimport { type ContextSnapshot } from './snapshot';\n\n// =============================================================================\n// SECTION: TIME TRAVEL TYPES\n// =============================================================================\n\n/**\n * A machine enhanced with history tracking capabilities.\n */\nexport type WithHistory<M extends BaseMachine<any>> = M & {\n /** History of all transitions */\n history: HistoryEntry[];\n /** Clear all history */\n clearHistory: () => void;\n};\n\n/**\n * A machine enhanced with snapshot tracking capabilities.\n */\nexport type WithSnapshot<M extends BaseMachine<any>> = M & {\n /** Snapshots of context before/after each transition */\n snapshots: ContextSnapshot<Context<M>>[];\n /** Clear all snapshots */\n clearSnapshots: () => void;\n /** Restore machine to a previous context state */\n restoreSnapshot: (context: Context<M>) => M;\n};\n\n/**\n * A machine enhanced with time travel capabilities.\n */\nexport type WithTimeTravel<M extends BaseMachine<any>> = M & {\n /** History of all transitions */\n history: HistoryEntry[];\n /** Snapshots of context before/after each transition */\n snapshots: ContextSnapshot<Context<M>>[];\n /** Clear all history and snapshots */\n clearTimeTravel: () => void;\n /** Clear just the history */\n clearHistory: () => void;\n /** Clear just the snapshots */\n clearSnapshots: () => void;\n /** Restore machine to a previous context state */\n restoreSnapshot: (context: Context<M>) => M;\n /** Replay transitions from a specific point in history */\n replayFrom: (startIndex: number) => M;\n};\n\n// =============================================================================\n// SECTION: TIME TRAVEL MIDDLEWARE\n// =============================================================================\n\n/**\n * Creates a machine with full time travel debugging capabilities.\n * Combines history tracking, snapshots, and replay functionality.\n *\n * @template M - The machine type\n * @param machine - The machine to enhance\n * @param options - Configuration options\n * @returns A machine with time travel capabilities\n *\n * @example\n * ```typescript\n * const debugMachine = withTimeTravel(counter);\n *\n * // Make some transitions\n * debugMachine.increment();\n * debugMachine.increment();\n * debugMachine.decrement();\n *\n * // Time travel to previous states\n * const previousState = debugMachine.replayFrom(0); // Replay from start\n * const undoLast = debugMachine.restoreSnapshot(debugMachine.snapshots[1].before);\n *\n * // Inspect history\n * console.log(debugMachine.history);\n * console.log(debugMachine.snapshots);\n * ```\n */\nexport function withTimeTravel<M extends BaseMachine<any>>(\n machine: M,\n options: {\n /** Maximum number of history entries/snapshots to keep */\n maxSize?: number;\n /** Optional serializer for persistence */\n serializer?: Serializer;\n /** Callback when history/snapshot events occur */\n onRecord?: (type: 'history' | 'snapshot', data: any) => void;\n } = {}\n): WithTimeTravel<M> {\n const { maxSize, serializer, onRecord } = options;\n\n // Create separate history and snapshot tracking\n const history: HistoryEntry[] = [];\n const snapshots: ContextSnapshot<Context<M>>[] = [];\n let historyId = 0;\n let snapshotId = 0;\n\n // Create middleware that handles both history and snapshots\n const instrumentedMachine = createMiddleware(machine, {\n before: ({ transitionName, args }: { transitionName: string; args: any[] }) => {\n const entry: HistoryEntry = {\n id: `entry-${historyId++}`,\n transitionName,\n args: [...args],\n timestamp: Date.now()\n };\n\n if (serializer) {\n try {\n entry.serializedArgs = serializer.serialize(args);\n } catch (err) {\n console.error('Failed to serialize history args:', err);\n }\n }\n\n history.push(entry);\n\n // Enforce max size\n if (maxSize && history.length > maxSize) {\n history.shift();\n }\n\n onRecord?.('history', entry);\n },\n after: ({ transitionName, prevContext, nextContext }: { transitionName: string; prevContext: Context<M>; nextContext: Context<M> }) => {\n const snapshot: ContextSnapshot<Context<M>> = {\n id: `snapshot-${snapshotId++}`,\n transitionName,\n before: { ...prevContext },\n after: { ...nextContext },\n timestamp: Date.now()\n };\n\n // Serialize contexts if serializer provided\n if (serializer) {\n try {\n snapshot.serializedBefore = serializer.serialize(prevContext);\n snapshot.serializedAfter = serializer.serialize(nextContext);\n } catch (err) {\n console.error('Failed to serialize snapshot:', err);\n }\n }\n\n snapshots.push(snapshot);\n\n // Enforce max size\n if (maxSize && snapshots.length > maxSize) {\n snapshots.shift();\n }\n\n onRecord?.('snapshot', snapshot);\n }\n });\n\n // Helper to restore machine to a previous state\n const restoreSnapshot = (context: Context<M>): M => {\n // Find the machine's transition functions (excluding context and snapshot properties)\n const transitions = Object.fromEntries(\n Object.entries(machine).filter(([key]) =>\n key !== 'context' &&\n key !== 'history' &&\n key !== 'snapshots' &&\n key !== 'clearHistory' &&\n key !== 'clearSnapshots' &&\n key !== 'restoreSnapshot' &&\n key !== 'clearTimeTravel' &&\n key !== 'replayFrom' &&\n typeof machine[key as keyof M] === 'function'\n )\n );\n\n return Object.assign({ context }, transitions) as M;\n };\n\n // Create replay functionality\n const replayFrom = (startIndex: number): M => {\n if (startIndex < 0 || startIndex >= history.length) {\n throw new Error(`Invalid replay start index: ${startIndex}`);\n }\n\n // Start from the context at the specified history index\n let currentContext = snapshots[startIndex]?.before;\n if (!currentContext) {\n throw new Error(`No snapshot available for index ${startIndex}`);\n }\n\n // Get all transitions from start index to end\n const transitionsToReplay = history.slice(startIndex);\n\n // Create a fresh machine instance\n const freshMachine = Object.assign(\n { context: currentContext },\n Object.fromEntries(\n Object.entries(machine).filter(([key]) =>\n key !== 'context' &&\n typeof machine[key as keyof M] === 'function'\n )\n )\n ) as M;\n\n // Replay each transition\n let replayedMachine = freshMachine;\n for (const entry of transitionsToReplay) {\n const transitionFn = replayedMachine[entry.transitionName as keyof M] as Function;\n if (transitionFn) {\n replayedMachine = transitionFn.apply(replayedMachine, entry.args);\n }\n }\n\n return replayedMachine;\n };\n\n // Return machine with all time travel capabilities\n return Object.assign(instrumentedMachine, {\n history,\n snapshots,\n clearHistory: () => { history.length = 0; historyId = 0; },\n clearSnapshots: () => { snapshots.length = 0; snapshotId = 0; },\n clearTimeTravel: () => {\n history.length = 0;\n snapshots.length = 0;\n historyId = 0;\n snapshotId = 0;\n },\n restoreSnapshot,\n replayFrom\n }) as WithTimeTravel<M>;\n}\n", "/**\n * @file Middleware composition and pipeline utilities\n */\n\nimport type { BaseMachine, Context } from '../index';\nimport type {\n MiddlewareContext,\n MiddlewareResult,\n MiddlewareError,\n MiddlewareHooks,\n MiddlewareOptions\n} from './core';\nimport {\n withLogging,\n withAnalytics,\n withValidation,\n withPermissions,\n withErrorReporting,\n withPerformanceMonitoring,\n withRetry\n} from './core';\nimport { withHistory, type HistoryEntry, type Serializer } from './history';\nimport { withSnapshot } from './snapshot';\nimport { withTimeTravel, type WithTimeTravel, type WithHistory, type WithSnapshot } from './time-travel';\n\n// =============================================================================\n// SECTION: COMPOSITION TYPES\n// =============================================================================\n\n/**\n * A middleware function that transforms a machine.\n * @template M - The input machine type\n * @template R - The output machine type (usually extends M)\n */\nexport type MiddlewareFn<M extends BaseMachine<any>, R extends BaseMachine<any> = M> = (machine: M) => R;\n\n/**\n * A conditional middleware that may or may not be applied based on a predicate.\n * @template M - The machine type\n */\nexport type ConditionalMiddleware<M extends BaseMachine<any>> = {\n /** The middleware function to apply */\n middleware: MiddlewareFn<M>;\n /** Predicate function that determines if the middleware should be applied */\n when: (machine: M) => boolean;\n};\n\n/**\n * A named middleware entry for registry-based composition.\n * @template M - The machine type\n */\nexport type NamedMiddleware<M extends BaseMachine<any>> = {\n /** Unique name for the middleware */\n name: string;\n /** The middleware function */\n middleware: MiddlewareFn<M>;\n /** Optional description */\n description?: string;\n /** Optional priority for ordering (higher numbers = applied later) */\n priority?: number;\n};\n\n/**\n * Configuration for middleware pipeline execution.\n */\nexport interface PipelineConfig {\n /** Whether to continue execution if a middleware throws an error */\n continueOnError?: boolean;\n /** Whether to log errors from middlewares */\n logErrors?: boolean;\n /** Custom error handler */\n onError?: (error: Error, middlewareIndex: number, middlewareName?: string) => void;\n}\n\n/**\n * Result of pipeline execution.\n */\nexport type PipelineResult<M extends BaseMachine<any>> = M;\n\n// =============================================================================\n// SECTION: TYPE-LEVEL COMPOSITION\n// =============================================================================\n\n/**\n * Type-level utility for composing middleware return types.\n * This enables perfect TypeScript inference when chaining middlewares.\n */\nexport type ComposeResult<\n M extends BaseMachine<any>,\n Ms extends readonly MiddlewareFn<any, any>[]\n> = Ms extends readonly [infer First, ...infer Rest]\n ? First extends MiddlewareFn<any, infer R>\n ? Rest extends readonly MiddlewareFn<any, any>[]\n ? ComposeResult<R, Rest>\n : R\n : M\n : M;\n\n// =============================================================================\n// SECTION: COMPOSITION FUNCTIONS\n// =============================================================================\n\n/**\n * Compose multiple middleware functions into a single middleware stack.\n * Middleware is applied left-to-right (first middleware wraps outermost).\n *\n * @template M - The machine type\n * @param machine - The base machine\n * @param middlewares - Array of middleware functions\n * @returns A new machine with all middleware applied\n */\nexport function compose<M extends BaseMachine<any>>(\n machine: M,\n ...middlewares: Array<(m: M) => M>\n): M {\n return middlewares.reduce((acc, middleware) => middleware(acc), machine);\n}\n\n/**\n * Type-safe middleware composition with perfect inference.\n * Composes multiple middlewares into a single transformation chain.\n *\n * @template M - The input machine type\n * @template Ms - Array of middleware functions\n * @param machine - The machine to enhance\n * @param middlewares - Middleware functions to apply in order\n * @returns The machine with all middlewares applied, with precise type inference\n */\nexport function composeTyped<\n M extends BaseMachine<any>,\n Ms extends readonly MiddlewareFn<any, any>[]\n>(\n machine: M,\n ...middlewares: Ms\n): ComposeResult<M, Ms> {\n return middlewares.reduce((acc, middleware) => middleware(acc), machine) as ComposeResult<M, Ms>;\n}\n\n// =============================================================================\n// SECTION: FLUENT API\n// =============================================================================\n\n/**\n * Fluent middleware composer for building complex middleware chains.\n * Provides excellent TypeScript inference and IntelliSense.\n */\nclass MiddlewareChainBuilder<M extends BaseMachine<any>> {\n constructor(private machine: M) {}\n\n /**\n * Add a middleware to the composition chain.\n * @param middleware - The middleware function to add\n * @returns A new composer with the middleware applied\n */\n with<M2 extends MiddlewareFn<any, any>>(\n middleware: M2\n ): MiddlewareChainBuilder<ReturnType<M2> extends BaseMachine<any> ? ReturnType<M2> : M> {\n const result = middleware(this.machine);\n return new MiddlewareChainBuilder(result as any);\n }\n\n /**\n * Build the final machine with all middlewares applied.\n */\n build(): M {\n return this.machine;\n }\n}\n\n/**\n * Create a fluent middleware chain builder.\n *\n * @example\n * ```typescript\n * const enhanced = chain(counter)\n * .with(withHistory())\n * .with(withSnapshot())\n * .with(withTimeTravel())\n * .build();\n * ```\n */\nexport function chain<M extends BaseMachine<any>>(machine: M) {\n return new MiddlewareChainBuilder(machine);\n}\n\n// =============================================================================\n// SECTION: CONDITIONAL MIDDLEWARE\n// =============================================================================\n\n/**\n * Create a conditional middleware that only applies when a predicate is true.\n *\n * @template M - The machine type\n * @param middleware - The middleware to conditionally apply\n * @param predicate - Function that determines when to apply the middleware\n * @returns A conditional middleware that can be called directly or used in pipelines\n */\nexport function when<M extends BaseMachine<any>>(\n middleware: MiddlewareFn<M>,\n predicate: (machine: M) => boolean\n): ConditionalMiddleware<M> & MiddlewareFn<M> {\n const conditional: ConditionalMiddleware<M> & MiddlewareFn<M> = function(machine: M) {\n return predicate(machine) ? middleware(machine) : machine;\n };\n\n conditional.middleware = middleware;\n conditional.when = predicate;\n\n return conditional;\n}\n\n/**\n * Create a middleware that only applies in development mode.\n *\n * @template M - The machine type\n * @param middleware - The middleware to apply in development\n * @returns A conditional middleware for development mode\n */\nexport function inDevelopment<M extends BaseMachine<any>>(\n middleware: MiddlewareFn<M>\n): ConditionalMiddleware<M> & MiddlewareFn<M> {\n return when(middleware, () => {\n return typeof process !== 'undefined'\n ? process.env.NODE_ENV === 'development'\n : typeof window !== 'undefined'\n ? !window.location.hostname.includes('production')\n : false;\n });\n}\n\n/**\n * Create a middleware that only applies when a context property matches a value.\n *\n * @template M - The machine type\n * @template K - The context key\n * @param key - The context property key\n * @param value - The value to match\n * @param middleware - The middleware to apply when the condition matches\n * @returns A conditional middleware\n */\nexport function whenContext<M extends BaseMachine<any>, K extends keyof Context<M>>(\n key: K,\n value: Context<M>[K],\n middleware: MiddlewareFn<M>\n): ConditionalMiddleware<M> & MiddlewareFn<M> {\n return when(middleware, (machine) => machine.context[key] === value);\n}\n\n// =============================================================================\n// SECTION: MIDDLEWARE REGISTRY\n// =============================================================================\n\n/**\n * Create a middleware registry for managing reusable middleware configurations.\n */\nexport function createMiddlewareRegistry<M extends BaseMachine<any>>() {\n const registry = new Map<string, NamedMiddleware<M>>();\n\n return {\n /**\n * Register a middleware by name.\n */\n register(\n name: string,\n middleware: MiddlewareFn<M>,\n description?: string,\n priority?: number\n ): typeof this {\n if (registry.has(name)) {\n throw new Error(`Middleware '${name}' is already registered`);\n }\n\n registry.set(name, { name, middleware, description, priority });\n return this;\n },\n\n /**\n * Unregister a middleware by name.\n */\n unregister(name: string): boolean {\n return registry.delete(name);\n },\n\n /**\n * Check if a middleware is registered.\n */\n has(name: string): boolean {\n return registry.has(name);\n },\n\n /**\n * Get a registered middleware by name.\n */\n get(name: string): NamedMiddleware<M> | undefined {\n return registry.get(name);\n },\n\n /**\n * List all registered middlewares.\n */\n list(): NamedMiddleware<M>[] {\n return Array.from(registry.values()).sort((a, b) => (a.priority ?? 0) - (b.priority ?? 0));\n },\n\n /**\n * Apply a selection of registered middlewares to a machine.\n * Middlewares are applied in priority order (lowest to highest).\n */\n apply(machine: M, middlewareNames: string[]): M {\n const middlewares = middlewareNames\n .map(name => {\n const entry = registry.get(name);\n if (!entry) {\n throw new Error(`Middleware '${name}' is not registered`);\n }\n return entry;\n })\n .sort((a, b) => (a.priority ?? 0) - (b.priority ?? 0));\n\n return composeTyped(machine, ...middlewares.map(m => m.middleware));\n },\n\n /**\n * Apply all registered middlewares to a machine in priority order.\n */\n applyAll(machine: M): M {\n const middlewares = this.list();\n return composeTyped(machine, ...middlewares.map(m => m.middleware));\n }\n };\n}\n\n// =============================================================================\n// SECTION: PIPELINES\n// =============================================================================\n\n/**\n * Create a middleware pipeline with error handling and conditional execution.\n *\n * @template M - The machine type\n * @param config - Pipeline configuration\n * @returns A function that executes middlewares in a pipeline\n */\nexport function createPipeline<M extends BaseMachine<any>>(\n config: PipelineConfig = {}\n): {\n <Ms extends Array<MiddlewareFn<M> | ConditionalMiddleware<M>>>(\n machine: M,\n ...middlewares: Ms\n ): { machine: M; errors: Array<{ error: Error; middlewareIndex: number; middlewareName?: string }>; success: boolean };\n} {\n const {\n continueOnError = false,\n logErrors = true,\n onError\n } = config;\n\n return (machine: M, ...middlewares: Array<MiddlewareFn<M> | ConditionalMiddleware<M>>) => {\n let currentMachine = machine;\n const errors: Array<{ error: Error; middlewareIndex: number; middlewareName?: string }> = [];\n let success = true;\n\n for (let i = 0; i < middlewares.length; i++) {\n const middleware = middlewares[i];\n\n try {\n // Handle conditional middleware\n if ('middleware' in middleware && 'when' in middleware) {\n if (!middleware.when(currentMachine)) {\n continue; // Skip this middleware\n }\n currentMachine = middleware.middleware(currentMachine);\n } else {\n // Regular middleware\n currentMachine = (middleware as MiddlewareFn<M>)(currentMachine);\n }\n } catch (error) {\n success = false;\n if (!continueOnError) {\n throw error;\n }\n\n errors.push({\n error: error as Error,\n middlewareIndex: i,\n middlewareName: (middleware as any).name\n });\n\n if (logErrors) {\n console.error(`Pipeline middleware error at index ${i}:`, error);\n }\n\n onError?.(error as Error, i, (middleware as any).name);\n }\n }\n\n return { machine: currentMachine, errors, success };\n };\n}\n\n// =============================================================================\n// SECTION: UTILITY FUNCTIONS\n// =============================================================================\n\n/**\n * Combine multiple middlewares with short-circuiting.\n */\nexport function combine<M extends BaseMachine<any>>(\n ...middlewares: Array<MiddlewareFn<M>>\n): MiddlewareFn<M> {\n return (machine: M) => composeTyped(machine, ...middlewares);\n}\n\n/**\n * Create a middleware that applies different middlewares based on context.\n */\nexport function branch<M extends BaseMachine<any>>(\n branches: Array<[predicate: (machine: M) => boolean, middleware: MiddlewareFn<M>]>,\n fallback?: MiddlewareFn<M>\n): MiddlewareFn<M> {\n return (machine: M) => {\n for (const [predicate, middleware] of branches) {\n if (predicate(machine)) {\n return middleware(machine);\n }\n }\n return fallback ? fallback(machine) : machine;\n };\n}\n\n// =============================================================================\n// SECTION: ENHANCED TYPE GUARDS\n// =============================================================================\n\n/**\n * Enhanced type guard to check if a value is a middleware function with better inference.\n */\nexport function isMiddlewareFn<M extends BaseMachine<any>, R extends BaseMachine<any> = M>(\n value: any\n): value is MiddlewareFn<M, R> {\n return typeof value === 'function' && value.length === 1;\n}\n\n/**\n * Enhanced type guard to check if a value is a conditional middleware with better inference.\n */\nexport function isConditionalMiddleware<M extends BaseMachine<any>>(\n value: any\n): value is ConditionalMiddleware<M> {\n return (\n value !== null &&\n (typeof value === 'object' || typeof value === 'function') &&\n 'middleware' in value &&\n 'when' in value &&\n isMiddlewareFn(value.middleware) &&\n typeof value.when === 'function'\n );\n}\n\n/**\n * Type guard to check if a value is a middleware result with strict type checking.\n */\nexport function isMiddlewareResult<C extends object>(\n value: any,\n contextType?: C\n): value is MiddlewareResult<C> {\n return (\n value !== null &&\n typeof value === 'object' &&\n 'transitionName' in value &&\n 'prevContext' in value &&\n 'nextContext' in value &&\n 'args' in value &&\n typeof value.transitionName === 'string' &&\n Array.isArray(value.args) &&\n (!contextType || (\n isValidContext(value.prevContext, contextType) &&\n isValidContext(value.nextContext, contextType)\n ))\n );\n}\n\n/**\n * Type guard to check if a value is middleware context with strict type checking.\n */\nexport function isMiddlewareContext<C extends object>(\n value: any,\n contextType?: C\n): value is MiddlewareContext<C> {\n return (\n value !== null &&\n typeof value === 'object' &&\n 'transitionName' in value &&\n 'context' in value &&\n 'args' in value &&\n typeof value.transitionName === 'string' &&\n Array.isArray(value.args) &&\n (!contextType || isValidContext(value.context, contextType))\n );\n}\n\n/**\n * Type guard to check if a value is middleware error with strict type checking.\n */\nexport function isMiddlewareError<C extends object>(\n value: any,\n contextType?: C\n): value is MiddlewareError<C> {\n return (\n value !== null &&\n typeof value === 'object' &&\n 'transitionName' in value &&\n 'context' in value &&\n 'args' in value &&\n 'error' in value &&\n typeof value.transitionName === 'string' &&\n Array.isArray(value.args) &&\n value.error instanceof Error &&\n (!contextType || isValidContext(value.context, contextType))\n );\n}\n\n/**\n * Type guard to check if a value is middleware hooks with strict type checking.\n */\nexport function isMiddlewareHooks<C extends object>(\n value: any,\n _contextType?: C\n): value is MiddlewareHooks<C> {\n if (value === null || typeof value !== 'object') return false;\n\n const hooks = value as Partial<MiddlewareHooks<C>>;\n\n // Check before hook\n if ('before' in hooks && hooks.before !== undefined) {\n if (typeof hooks.before !== 'function') return false;\n }\n\n // Check after hook\n if ('after' in hooks && hooks.after !== undefined) {\n if (typeof hooks.after !== 'function') return false;\n }\n\n // Check error hook\n if ('error' in hooks && hooks.error !== undefined) {\n if (typeof hooks.error !== 'function') return false;\n }\n\n return true;\n}\n\n/**\n * Type guard to check if a value is middleware options with strict type checking.\n */\nexport function isMiddlewareOptions(value: any): value is MiddlewareOptions {\n return (\n value === undefined ||\n (value !== null &&\n typeof value === 'object' &&\n ('continueOnError' in value ? typeof value.continueOnError === 'boolean' : true) &&\n ('logErrors' in value ? typeof value.logErrors === 'boolean' : true) &&\n ('onError' in value ? typeof value.onError === 'function' || value.onError === undefined : true))\n );\n}\n\n/**\n * Helper function to validate context objects.\n */\nfunction isValidContext<C extends object>(value: any, _contextType: C): value is C {\n return value !== null && typeof value === 'object';\n}\n\n/**\n * Type guard to check if a value is a named middleware with strict type checking.\n */\nexport function isNamedMiddleware<M extends BaseMachine<any>>(\n value: any\n): value is NamedMiddleware<M> {\n return (\n value !== null &&\n typeof value === 'object' &&\n 'name' in value &&\n 'middleware' in value &&\n typeof value.name === 'string' &&\n isMiddlewareFn(value.middleware) &&\n ('description' in value ? typeof value.description === 'string' || value.description === undefined : true) &&\n ('priority' in value ? typeof value.priority === 'number' || value.priority === undefined : true)\n );\n}\n\n/**\n * Type guard to check if a value is pipeline config with strict type checking.\n */\nexport function isPipelineConfig(value: any): value is PipelineConfig {\n return (\n value === undefined ||\n (value !== null &&\n typeof value === 'object' &&\n ('continueOnError' in value ? typeof value.continueOnError === 'boolean' : true) &&\n ('logErrors' in value ? typeof value.logErrors === 'boolean' : true) &&\n ('onError' in value ? typeof value.onError === 'function' || value.onError === undefined : true))\n );\n}\n\n// =============================================================================\n// SECTION: GENERIC MIDDLEWARE BUILDER\n// =============================================================================\n\n/**\n * Configuration for logging middleware.\n */\nexport interface LoggingOptions {\n logger?: (message: string) => void;\n includeArgs?: boolean;\n includeContext?: boolean;\n logLevel?: 'debug' | 'info' | 'warn' | 'error';\n}\n\n/**\n * Configuration for analytics middleware.\n */\nexport interface AnalyticsOptions {\n eventPrefix?: string;\n includePrevContext?: boolean;\n includeArgs?: boolean;\n includeTiming?: boolean;\n}\n\n/**\n * Configuration for validation middleware.\n */\nexport interface ValidationOptions {\n throwOnFailure?: boolean;\n logFailures?: boolean;\n}\n\n/**\n * Configuration for error reporting middleware.\n */\nexport interface ErrorReportingOptions {\n includeArgs?: boolean;\n includeStackTrace?: boolean;\n reportTo?: string[];\n}\n\n/**\n * Configuration for performance monitoring middleware.\n */\nexport interface PerformanceOptions {\n includeArgs?: boolean;\n includeContext?: boolean;\n warnThreshold?: number;\n}\n\n/**\n * Configuration for retry middleware.\n */\nexport interface RetryOptions {\n maxAttempts?: number;\n maxRetries?: number;\n shouldRetry?: (error: Error, attempt: number) => boolean;\n backoffMs?: number | ((attempt: number) => number);\n delay?: number | ((attempt: number) => number);\n backoffMultiplier?: number;\n onRetry?: (error: Error, attempt: number) => void;\n}\n\n/**\n * Configuration for history middleware.\n */\nexport interface HistoryOptions {\n maxSize?: number;\n serializer?: Serializer<any[]>;\n onEntry?: (entry: HistoryEntry) => void;\n includeTimestamps?: boolean;\n}\n\n/**\n * Configuration for snapshot middleware.\n */\nexport interface SnapshotOptions {\n maxSize?: number;\n serializer?: Serializer<Context<any>>;\n captureSnapshot?: (before: Context<any>, after: Context<any>) => any;\n onlyOnChange?: boolean;\n includeDiff?: boolean;\n}\n\n/**\n * Configuration for time travel middleware.\n */\nexport interface TimeTravelOptions {\n maxSize?: number;\n serializer?: Serializer;\n onRecord?: (type: 'history' | 'snapshot', data: any) => void;\n enableReplay?: boolean;\n}\n\n/**\n * Generic middleware builder with perfect TypeScript inference.\n * Provides a fluent API for configuring and applying middleware.\n */\nexport class MiddlewareBuilder<M extends BaseMachine<any>> {\n private middlewares: Array<(machine: any) => any> = [];\n\n constructor(private machine: M) {}\n\n /**\n * Add logging middleware with type-safe configuration.\n */\n withLogging(options?: LoggingOptions): MiddlewareBuilder<M> {\n this.middlewares.push((machine: M) => withLogging(machine, options));\n return this;\n }\n\n /**\n * Add analytics middleware with type-safe configuration.\n */\n withAnalytics(\n track: (event: string, data?: any) => void,\n options?: AnalyticsOptions\n ): MiddlewareBuilder<M> {\n this.middlewares.push((machine: M) => withAnalytics(machine, track, options));\n return this;\n }\n\n /**\n * Add validation middleware with type-safe configuration.\n */\n withValidation(\n validator: (ctx: MiddlewareContext<Context<M>>) => boolean | void,\n _options?: ValidationOptions\n ): MiddlewareBuilder<M> {\n this.middlewares.push((machine: M) => withValidation(machine, validator));\n return this;\n }\n\n /**\n * Add permission checking middleware with type-safe configuration.\n */\n withPermissions(\n checker: (ctx: MiddlewareContext<Context<M>>) => boolean\n ): MiddlewareBuilder<M> {\n this.middlewares.push((machine: M) => withPermissions(machine, checker));\n return this;\n }\n\n /**\n * Add error reporting middleware with type-safe configuration.\n */\n withErrorReporting(\n reporter: (error: Error, ctx: MiddlewareError<Context<M>>) => void,\n options?: ErrorReportingOptions\n ): MiddlewareBuilder<M> {\n this.middlewares.push((machine: M) => withErrorReporting(machine, reporter, options));\n return this;\n }\n\n /**\n * Add performance monitoring middleware with type-safe configuration.\n */\n withPerformanceMonitoring(\n tracker: (metric: { transitionName: string; duration: number; context: Context<M> }) => void,\n _options?: PerformanceOptions\n ): MiddlewareBuilder<M> {\n this.middlewares.push((machine: M) => withPerformanceMonitoring(machine, tracker));\n return this;\n }\n\n /**\n * Add retry middleware with type-safe configuration.\n */\n withRetry(options?: RetryOptions): MiddlewareBuilder<M> {\n this.middlewares.push((machine: M) => withRetry(machine, options));\n return this;\n }\n\n /**\n * Add history tracking middleware with type-safe configuration.\n */\n withHistory(options?: HistoryOptions): MiddlewareBuilder<WithHistory<M>> {\n this.middlewares.push((machine: M) => withHistory(machine, options));\n return this as unknown as MiddlewareBuilder<WithHistory<M>>;\n }\n\n /**\n * Add snapshot tracking middleware with type-safe configuration.\n */\n withSnapshot(options?: SnapshotOptions): MiddlewareBuilder<WithSnapshot<M>> {\n this.middlewares.push((machine: M) => withSnapshot(machine, options));\n return this as unknown as MiddlewareBuilder<WithSnapshot<M>>;\n }\n\n /**\n * Add time travel middleware with type-safe configuration.\n */\n withTimeTravel(options?: TimeTravelOptions): MiddlewareBuilder<WithTimeTravel<M>> {\n this.middlewares.push((machine: M) => withTimeTravel(machine, options));\n return this as unknown as MiddlewareBuilder<WithTimeTravel<M>>;\n }\n\n /**\n * Add debugging middleware (combination of history, snapshot, and time travel).\n */\n withDebugging(): MiddlewareBuilder<WithDebugging<M>> {\n this.middlewares.push((machine: M) => withDebugging(machine));\n return this as unknown as MiddlewareBuilder<WithDebugging<M>>;\n }\n\n /**\n * Add a custom middleware function.\n */\n withCustom<R extends BaseMachine<any> = M>(\n middleware: MiddlewareFn<M, R>\n ): MiddlewareBuilder<R> {\n this.middlewares.push(middleware);\n return this as unknown as MiddlewareBuilder<R>;\n }\n\n /**\n * Add a conditional middleware.\n */\n withConditional(\n middleware: MiddlewareFn<M>,\n predicate: (machine: M) => boolean\n ): MiddlewareBuilder<M> {\n this.middlewares.push(when(middleware, predicate));\n return this;\n }\n\n /**\n * Build the final machine with all configured middleware applied.\n */\n build(): M {\n let result = this.machine;\n for (const middleware of this.middlewares) {\n result = middleware(result);\n }\n return result;\n }\n\n /**\n * Get the middleware chain without building (for inspection or further composition).\n */\n getChain(): Array<(machine: any) => any> {\n return [...this.middlewares];\n }\n\n /**\n * Clear all configured middleware.\n */\n clear(): MiddlewareBuilder<M> {\n this.middlewares = [];\n return this;\n }\n}\n\n/**\n * Create a typed middleware builder for a machine.\n * Provides perfect TypeScript inference for middleware configuration.\n *\n * @example\n * ```typescript\n * const enhancedMachine = middlewareBuilder(myMachine)\n * .withLogging({ includeArgs: true })\n * .withAnalytics(trackEvent)\n * .withHistory({ maxSize: 100 })\n * .withRetry({ maxAttempts: 3 })\n * .build();\n * ```\n */\nexport function middlewareBuilder<M extends BaseMachine<any>>(machine: M): MiddlewareBuilder<M> {\n return new MiddlewareBuilder(machine);\n}\n\n/**\n * Create a middleware factory function with pre-configured options.\n * Useful for creating reusable middleware configurations.\n */\nexport function createMiddlewareFactory<M extends BaseMachine<any>>(\n defaultOptions: {\n logging?: LoggingOptions;\n analytics?: { track: (event: string, data?: any) => void; options?: AnalyticsOptions };\n history?: HistoryOptions;\n snapshot?: SnapshotOptions;\n timeTravel?: TimeTravelOptions;\n retry?: RetryOptions;\n } = {}\n) {\n return {\n create: (machine: M) => {\n const builder = middlewareBuilder(machine);\n\n if (defaultOptions.logging) {\n builder.withLogging(defaultOptions.logging);\n }\n\n if (defaultOptions.analytics) {\n builder.withAnalytics(\n defaultOptions.analytics.track,\n defaultOptions.analytics.options\n );\n }\n\n if (defaultOptions.history) {\n builder.withHistory(defaultOptions.history);\n }\n\n if (defaultOptions.snapshot) {\n builder.withSnapshot(defaultOptions.snapshot);\n }\n\n if (defaultOptions.timeTravel) {\n builder.withTimeTravel(defaultOptions.timeTravel);\n }\n\n if (defaultOptions.retry) {\n builder.withRetry(defaultOptions.retry);\n }\n\n return builder;\n }\n };\n}\n\n// =============================================================================\n// SECTION: UTILITY FUNCTIONS\n// =============================================================================\n\n// =============================================================================\n// SECTION: COMMON COMBINATIONS\n// =============================================================================\n\n/**\n * Common middleware combination types for better DX.\n */\nexport type WithDebugging<M extends BaseMachine<any>> = WithTimeTravel<WithSnapshot<WithHistory<M>>>;\n\n/**\n * Convenience function for the most common debugging middleware stack.\n */\nexport function withDebugging<M extends BaseMachine<any>>(machine: M): WithDebugging<M> {\n return withTimeTravel(withSnapshot(withHistory(machine)));\n}", "/**\n * @file A collection of high-level, type-safe utility functions for @doeixd/machine.\n * @description These helpers provide ergonomic improvements for common patterns like\n * state checking, event creation, debugging, and composing transitions.\n */\n\nimport {\n Machine,\n AsyncMachine,\n MaybePromise,\n Context,\n Event,\n Transitions,\n TransitionArgs,\n setContext,\n createMachine,\n} from './index'; // Assuming index.ts is in the same directory\n\n// =============================================================================\n// SECTION: STATE & TYPE GUARDS\n// =============================================================================\n\n/**\n * A type representing a Class Constructor, used for type guards.\n */\ntype ClassConstructor = new (...args: any[]) => any;\n\n/**\n * A type-safe way to check if a machine is in a specific state, acting as a Type Guard.\n * This is the preferred way to do state checking when using class-based machines.\n *\n * @template T - The class constructor type to check against.\n * @param machine - The machine instance to check.\n * @param machineClass - The class constructor representing the state.\n * @returns {boolean} `true` if the machine is an instance of the class, narrowing its type.\n *\n * @example\n * declare const machine: LoggedInMachine | LoggedOutMachine;\n *\n * if (isState(machine, LoggedInMachine)) {\n * // `machine` is now correctly typed as LoggedInMachine\n * machine.logout();\n * }\n */\nexport function isState<T extends ClassConstructor>(\n machine: any,\n machineClass: T\n): machine is InstanceType<T> {\n return machine instanceof machineClass;\n}\n\n\n// =============================================================================\n// SECTION: EVENT & DISPATCH HELPERS\n// =============================================================================\n\n/**\n * A type-safe factory function for creating event objects for `runMachine`.\n * This provides full autocompletion and type checking for event names and their arguments.\n *\n * @template M - The machine type the event belongs to.\n * @template K - The specific event name (transition method name).\n * @param type - The name of the event (e.g., \"increment\").\n * @param args - The arguments for that event, correctly typed.\n * @returns A type-safe event object ready to be passed to `dispatch`.\n *\n * @example\n * // Given: type MyMachine = Machine<{...}> & { add: (n: number) => any }\n * const event = createEvent<MyMachine, 'add'>('add', 5);\n * // `event` is correctly typed as { type: \"add\"; args: [number] }\n *\n * await runner.dispatch(event);\n */\nexport function createEvent<\n M extends Machine<any>,\n K extends keyof Transitions<M> & string\n>(type: K, ...args: TransitionArgs<M, K>): Event<M> {\n return { type, args } as unknown as Event<M>;\n}\n\n\n// =============================================================================\n// SECTION: CONTEXT & STATE MANIPULATION\n// =============================================================================\n\n/**\n * Creates a new machine instance by shallowly merging a partial context into the\n * current context, preserving all original transitions.\n *\n * @template M - The machine type.\n * @param machine - The original machine instance.\n * @param partialContext - An object with a subset of context properties to update.\n * @returns A new machine instance of the same type with the merged context.\n *\n * @example\n * const user = new User({ name: 'Alex', age: 30, status: 'active' });\n * const updatedUser = mergeContext(user, { status: 'inactive' });\n * // updatedUser.context is { name: 'Alex', age: 30, status: 'inactive' }\n */\nexport function mergeContext<M extends Machine<any>>(\n machine: M,\n partialContext: Partial<Context<M>>\n): M {\n return setContext(machine, (ctx) => ({ ...ctx, ...partialContext }));\n}\n\n\n// =============================================================================\n// SECTION: COMPOSITION & DEBUGGING\n// =============================================================================\n\n/**\n * Sequentially applies a series of transitions to a machine.\n * This function correctly handles both synchronous and asynchronous transitions,\n * always returning a Promise with the final machine state.\n *\n * @template M - The machine type, must be compatible with AsyncMachine.\n * @param initialMachine - The starting machine state.\n * @param transitions - An array of functions, each taking a machine and returning the next.\n * @returns A `Promise` that resolves to the final machine state after all transitions complete.\n *\n * @example\n * const finalState = await pipeTransitions(\n * new Counter({ count: 0 }),\n * (m) => m.increment(), // sync\n * (m) => m.addAsync(5), // async\n * (m) => m.increment() // sync\n * );\n * // finalState.context.count will be 6\n */\nexport async function pipeTransitions<M extends AsyncMachine<any>>(\n initialMachine: M,\n ...transitions: ((m: M) => MaybePromise<M>)[]\n): Promise<M> {\n let current: M = initialMachine;\n for (const transitionFn of transitions) {\n current = await transitionFn(current);\n }\n return current;\n}\n\n/**\n * A \"tap\" utility for logging a machine's context without interrupting a chain of operations.\n * It prints the context to the console and returns the machine instance unchanged.\n *\n * @template M - The machine type.\n * @param machine - The machine instance to log.\n * @param label - An optional label to print before the context object.\n * @returns The original, unmodified machine instance.\n *\n * @example\n * import { logState as tap } from './utils';\n *\n * await pipeTransitions(\n * new Counter({ count: 0 }),\n * tap, // Logs: { count: 0 }\n * (m) => m.increment(),\n * (m) => tap(m, 'After increment:') // Logs: After increment: { count: 1 }\n * );\n */\nexport function logState<M extends Machine<any>>(machine: M, label?: string): M {\n if (label) {\n console.log(label, machine.context);\n } else {\n console.log(machine.context);\n }\n return machine;\n}\n\n/**\n * A generic combinator that creates transition functions from pure context transformers.\n * This enables writing transitions as simple, testable functions that only transform context,\n * while automatically handling the machine creation boilerplate.\n *\n * @template C - The context object type.\n * @template TArgs - The argument types for the transition function.\n * @param getTransitions - A function that returns the transition functions object to use for the new machine.\n * @param transformer - A pure function that transforms the context based on the current state and arguments.\n * @returns A transition function that can be used as a machine method.\n *\n * @example\n * ```typescript\n * // Define transitions object with self-reference\n * const counterTransitions = {\n * increment: createTransition(\n * () => counterTransitions,\n * (ctx) => ({ count: ctx.count + 1 })\n * ),\n * add: createTransition(\n * () => counterTransitions,\n * (ctx, n: number) => ({ count: ctx.count + n })\n * )\n * };\n *\n * // Create machine\n * const counter = createMachine({ count: 0 }, counterTransitions);\n *\n * // Use transitions\n * const incremented = counter.increment(); // { count: 1 }\n * const added = incremented.add(5); // { count: 6 }\n * ```\n *\n * @example\n * ```typescript\n * // With class-based machines\n * class Counter extends MachineBase<{ count: number }> {\n * constructor(count = 0) {\n * super({ count });\n * }\n *\n * increment = createTransition(\n * () => ({ increment: this.increment, add: this.add }),\n * (ctx) => ({ count: ctx.count + 1 })\n * );\n *\n * add = createTransition(\n * () => ({ increment: this.increment, add: this.add }),\n * (ctx, n: number) => ({ count: ctx.count + n })\n * );\n * }\n * ```\n *\n * @remarks\n * This function promotes the library's philosophy of pure, immutable transitions.\n * The transformer function should be pure and only depend on its parameters.\n * The returned transition function automatically creates a new machine instance,\n * preserving all transitions while updating only the context.\n * The getTransitions function is called lazily to avoid circular reference issues.\n */\nexport function createTransition<\n C extends object,\n TArgs extends any[]\n>(\n getTransitions: () => Record<string, (this: Machine<C, any>, ...args: any[]) => any>,\n transformer: (ctx: C, ...args: TArgs) => C\n): (this: { context: C }, ...args: TArgs) => Machine<C> {\n return function (this: { context: C }, ...args: TArgs): Machine<C> {\n const nextContext = transformer(this.context, ...args);\n return createMachine(nextContext, getTransitions());\n };\n}\n\n// =============================================================================\n// SECTION: TRANSITION BINDING HELPERS\n// =============================================================================\n\n/**\n * Calls a transition function with an explicit `this` binding.\n * Useful for invoking transition methods with proper machine binding.\n *\n * @template M - The machine type that the function expects as `this`.\n * @template F - The function type with a `this` parameter.\n * @template A - The argument types for the function.\n * @param fn - The transition function to call.\n * @param machine - The machine object to bind as `this`.\n * @param args - Arguments to pass to the function.\n * @returns The result of calling the function with the given machine and arguments.\n *\n * @example\n * type MyMachine = Machine<{ count: number }>;\n * const increment = function(this: MyMachine) { return createMachine({ count: this.context.count + 1 }, this); };\n * const result = call(increment, machine); // Returns new machine\n *\n * // Particularly useful with machine transitions:\n * import { call } from '@doeixd/machine/utils';\n * const nextMachine = yield* step(call(m.increment, m));\n */\nexport function call<M extends Machine<any>, F extends (this: M, ...args: any[]) => any>(\n fn: F,\n machine: M,\n ...args: Parameters<F> extends [any, ...infer Rest] ? Rest : never\n): ReturnType<F> {\n return fn.apply(machine, args);\n}\n\n/**\n * Binds all transition methods of a machine to the machine itself automatically.\n * Returns a Proxy that intercepts method calls and binds them to the full machine.\n * This eliminates the need to use `.call(m, ...)` for every transition.\n *\n * Automatically recursively wraps returned machines, enabling seamless chaining\n * in generator-based flows.\n *\n * @template M - The machine type with a `context` property and transition methods.\n * @param machine - The machine instance to wrap.\n * @returns A Proxy of the machine where all callable properties (transitions) are automatically bound to the machine.\n *\n * @example\n * type CounterMachine = Machine<{ count: number }>;\n * const counter = bindTransitions(createMachine({ count: 0 }, {\n * increment(this: CounterMachine) { return createMachine({ count: this.context.count + 1 }, this); }\n * }));\n *\n * // Now you can call transitions directly without .call():\n * const next = counter.increment(); // Works! This is automatically bound.\n *\n * // Particularly useful with generators:\n * const result = run(function* (m) {\n * m = yield* step(m.increment()); // Clean syntax\n * m = yield* step(m.add(5)); // No .call() needed\n * return m;\n * }, bindTransitions(counter));\n *\n * @remarks\n * The Proxy preserves all original properties and methods. Non-callable properties\n * are accessed directly from the machine. Callable properties are wrapped to bind\n * them to the machine before invocation. Returned machines are automatically\n * re-wrapped to maintain binding across transition chains.\n */\nexport function bindTransitions<M extends { context: any }>(machine: M): M {\n return new Proxy(machine, {\n get(target, prop) {\n const value = target[prop as keyof M];\n\n // If it's a callable property (transition method), bind it to machine\n if (typeof value === 'function') {\n return function(...args: any[]) {\n const result = value.apply(target, args);\n // Recursively wrap returned machines to maintain binding\n if (result && typeof result === 'object' && 'context' in result) {\n return bindTransitions(result);\n }\n return result;\n };\n }\n\n // Otherwise, return the value as-is\n return value;\n },\n }) as M;\n}\n\n/**\n * A strongly-typed wrapper class for binding transitions to the machine.\n * Unlike the Proxy-based `bindTransitions`, this class preserves full type safety\n * and provides better IDE support through explicit property forwarding.\n *\n * @template M - The machine type with a `context` property and transition methods.\n *\n * @example\n * type CounterMachine = Machine<{ count: number }>;\n * const counter = createMachine({ count: 0 }, {\n * increment(this: CounterMachine) { return createMachine({ count: this.context.count + 1 }, this); }\n * });\n *\n * const bound = new BoundMachine(counter);\n *\n * // All transitions are automatically bound to machine\n * const result = run(function* (m) {\n * m = yield* step(m.increment());\n * m = yield* step(m.add(5));\n * return m.context.count;\n * }, bound);\n *\n * @remarks\n * Advantages over Proxy-based `bindTransitions`:\n * - Full type safety with TypeScript's type system\n * - Returned machines are automatically re-wrapped\n * - Better IDE autocompletion and hover information\n * - No type casting needed\n *\n * Disadvantages:\n * - Requires explicit instance creation: `new BoundMachine(m)` vs `bindTransitions(m)`\n * - Not a transparent drop-in replacement for the original machine\n */\nexport class BoundMachine<M extends { context: any }> {\n private readonly wrappedMachine: M;\n [key: string | symbol]: any;\n\n constructor(machine: M) {\n this.wrappedMachine = machine;\n\n // Create a proxy to intercept property access\n return new Proxy(this, {\n get: (target, prop) => {\n // Handle direct property access to wrapped machine\n if (prop === 'wrappedMachine') {\n return Reflect.get(target, prop);\n }\n if (prop === 'context') {\n return this.wrappedMachine.context;\n }\n\n const value = this.wrappedMachine[prop as keyof M];\n\n // Bind transition methods to machine\n if (typeof value === 'function') {\n return (...args: any[]) => {\n const result = value.apply(this.wrappedMachine, args);\n // Recursively wrap returned machines\n if (result && typeof result === 'object' && 'context' in result) {\n return new BoundMachine(result);\n }\n return result;\n };\n }\n\n // Return non-function properties directly\n return value;\n },\n }) as any;\n }\n}\n\n/**\n * Creates a sequence machine that orchestrates multi-step flows by automatically\n * advancing through a series of machines. When the current machine reaches a \"final\"\n * state (determined by the isFinal predicate), the sequence automatically transitions\n * to the next machine in the sequence.\n *\n * This implementation uses a functional approach with object delegation rather than Proxy.\n */\nfunction createSequenceMachine<\n M extends readonly [Machine<any>, ...Machine<any>[]]\n>(\n machines: M,\n isFinal: (machine: M[number]) => boolean\n): M[number] {\n if (machines.length === 0) {\n throw new Error('Sequence must contain at least one machine');\n }\n\n let currentIndex = 0;\n let currentMachine = machines[0];\n\n const createDelegationObject = (machine: M[number]) => {\n const delegationObject = Object.create(machine);\n\n // The context getter returns the machine's own context\n // (machine is the specific machine instance this delegation object represents)\n Object.defineProperty(delegationObject, 'context', {\n get: () => machine.context,\n enumerable: true,\n configurable: true\n });\n\n // Override all methods to add advancement logic\n const originalProto = Object.getPrototypeOf(machine);\n const methodNames = Object.getOwnPropertyNames(originalProto).filter(name =>\n name !== 'constructor' && name !== 'context' && typeof (machine as any)[name] === 'function'\n );\n\n for (const methodName of methodNames) {\n const methodKey = methodName as keyof any;\n\n (delegationObject as any)[methodKey] = (...args: unknown[]) => {\n const result = (currentMachine as any)[methodKey](...args);\n\n // Handle both sync and async results\n const handleResult = (resultMachine: unknown) => {\n return advanceIfNeeded(resultMachine as M[number]);\n };\n\n // If the result is a Promise, handle it asynchronously\n if (result && typeof (result as any).then === 'function') {\n return (result as Promise<unknown>).then(handleResult);\n }\n\n // Otherwise, handle synchronously\n return handleResult(result);\n };\n }\n\n return delegationObject;\n };\n\n const advanceIfNeeded = (machine: M[number]): M[number] => {\n currentMachine = machine;\n\n // Check if we should advance to the next machine\n if (isFinal(currentMachine) && currentIndex < machines.length - 1) {\n currentIndex++;\n currentMachine = machines[currentIndex];\n // Create a new delegation object for the new currentMachine\n return createDelegationObject(currentMachine);\n }\n\n return machine;\n };\n\n return createDelegationObject(currentMachine);\n}\n/**\n * Creates a sequence machine that orchestrates multi-step flows by automatically\n * advancing through a series of machines. When the current machine reaches a \"final\"\n * state (determined by the isFinal predicate), the sequence automatically transitions\n * to the next machine in the sequence.\n *\n * This is perfect for wizard-style flows, multi-step processes, or any scenario where\n * you need to chain machines together with automatic progression.\n *\n * @template M - The tuple of machine types in the sequence.\n * @param machines - The machines to sequence, in order.\n * @param isFinal - A predicate function that determines when a machine is in a final state.\n * Called after each transition to check if the sequence should advance.\n * @returns A new machine that wraps the sequence, delegating to the current machine\n * and automatically advancing when each machine reaches its final state.\n *\n * @example\n * ```typescript\n * // Define form machines with final states\n * class NameForm extends MachineBase<{ name: string; valid: boolean }> {\n * submit = (name: string) => new NameForm({ name, valid: name.length > 0 });\n * }\n *\n * class EmailForm extends MachineBase<{ email: string; valid: boolean }> {\n * submit = (email: string) => new EmailForm({ email, valid: email.includes('@') });\n * }\n *\n * class PasswordForm extends MachineBase<{ password: string; valid: boolean }> {\n * submit = (password: string) => new PasswordForm({ password, valid: password.length >= 8 });\n * }\n *\n * // Create sequence that advances when each form becomes valid\n * const wizard = sequence(\n * [new NameForm({ name: '', valid: false }),\n * new EmailForm({ email: '', valid: false }),\n * new PasswordForm({ password: '', valid: false })],\n * (machine) => machine.context.valid // Advance when valid becomes true\n * );\n *\n * // Usage - automatically advances through forms\n * let current = wizard;\n * current = current.submit('John'); // Still on NameForm (not valid yet)\n * current = current.submit('John Doe'); // Advances to EmailForm (name is valid)\n * current = current.submit('john@'); // Still on EmailForm (not valid yet)\n * current = current.submit('john@example.com'); // Advances to PasswordForm\n * current = current.submit('12345678'); // Advances to end of sequence\n * ```\n *\n * @example\n * ```typescript\n * // Async sequence with API calls\n * const authSequence = sequence(\n * [new LoginForm(), new TwoFactorForm(), new Dashboard()],\n * (machine) => machine.context.authenticated === true\n * );\n *\n * // The sequence handles async transitions automatically\n * const finalState = await authSequence.login('user@example.com', 'password');\n * ```\n *\n * @example\n * ```typescript\n * // Complex predicate - advance based on multiple conditions\n * const complexSequence = sequence(\n * [step1Machine, step2Machine, step3Machine],\n * (machine) => {\n * // Advance when all required fields are filled AND validated\n * return machine.context.requiredFields.every(f => f.filled) &&\n * machine.context.validationErrors.length === 0;\n * }\n * );\n * ```\n *\n * @remarks\n * - The sequence maintains the union type of all machines in the sequence\n * - Transitions are delegated to the current machine in the sequence\n * - When a machine reaches a final state, the sequence automatically advances\n * - If the sequence reaches the end, further transitions return the final machine\n * - The isFinal predicate is called after every transition to check advancement\n * - Works with both sync and async machines (returns MaybePromise)\n */\nexport function sequence<\n M extends readonly [Machine<any>, ...Machine<any>[]]\n>(\n machines: M,\n isFinal: (machine: M[number]) => boolean\n): M[number] {\n return createSequenceMachine(machines, isFinal);\n}\n\n/**\n * Convenience overload for sequencing exactly 2 machines.\n * Provides better type inference and IntelliSense for common 2-step flows.\n *\n * @example\n * ```typescript\n * const flow = sequence2(\n * new LoginForm(),\n * new Dashboard(),\n * (machine) => machine.context.authenticated\n * );\n * ```\n */\nexport function sequence2<\n M1 extends Machine<any>,\n M2 extends Machine<any>\n>(\n machine1: M1,\n machine2: M2,\n isFinal: (machine: M1 | M2) => boolean\n): M1 | M2 {\n return sequence([machine1, machine2], isFinal);\n}\n\n/**\n * Convenience overload for sequencing exactly 3 machines.\n * Provides better type inference and IntelliSense for common 3-step flows.\n *\n * @example\n * ```typescript\n * const wizard = sequence3(\n * new NameForm({ name: '', valid: false }),\n * new EmailForm({ email: '', valid: false }),\n * new PasswordForm({ password: '', valid: false }),\n * (machine) => machine.context.valid\n * );\n * ```\n */\nexport function sequence3<\n M1 extends Machine<any>,\n M2 extends Machine<any>,\n M3 extends Machine<any>\n>(\n machine1: M1,\n machine2: M2,\n machine3: M3,\n isFinal: (machine: M1 | M2 | M3) => boolean\n): M1 | M2 | M3 {\n return sequence([machine1, machine2, machine3], isFinal);\n}\n", "import { createMachine, Machine, BaseMachine, extendTransitions } from './index';\n\n/**\n * Creates a factory for building type-safe transitions for a specific machine.\n * This higher-order function captures the machine's `transitions` object in a closure,\n * enabling a clean, functional pattern for defining state changes without directly\n * manipulating the machine's context.\n *\n * This pattern promotes:\n * - Pure functions for state transformations\n * - Separation of transition logic from machine construction\n * - Reusable transition factories across similar machines\n * - Type safety through generic constraints\n *\n * @template C The context type of the machine\n * @template C The context type of the machine\n * @returns A `createTransition` function that can create transitions for machines with context type C\n *\n * @example\n * ```typescript\n * // Define your machine's transitions object\n * const counterTransitions = {\n * increment: function(amount: number) {\n * return createMachine({ count: this.context.count + amount }, counterTransitions);\n * }\n * };\n *\n * // Create a transition factory\n * const createCounterTransition = createTransitionFactory<{ count: number }>();\n *\n * // Use the factory to create pure, type-safe transitions\n * const incrementBy = createCounterTransition(\n * (ctx, amount: number) => ({ count: ctx.count + amount })\n * );\n *\n * const counter = createMachine({ count: 0 }, counterTransitions);\n * const newCounter = counter.increment(5); // Direct call\n * // OR\n * const incremented = incrementBy.call(counter, 5); // Using factory\n * ```\n */\nexport function createTransitionFactory<C extends object>() {\n /**\n * Takes a pure context transformer function and returns a full, type-safe\n * machine transition method that can be attached to a machine.\n *\n * The transformer function receives the current context as its first argument,\n * followed by any additional arguments passed to the transition.\n *\n * @template TArgs The argument types for the transition (excluding context)\n * @param transformer A pure function: `(context, ...args) => nextContext`\n * @returns A machine transition method that can be called on a machine instance\n *\n * @example\n * ```typescript\n * const createTodoTransition = createTransitionFactory<TodoContext>();\n *\n * const addTodo = createTodoTransition(\n * (ctx, text: string) => ({\n * ...ctx,\n * todos: [...ctx.todos, { id: Date.now(), text, completed: false }]\n * })\n * );\n *\n * const updateTodo = createTodoTransition(\n * (ctx, id: number, updates: Partial<Todo>) => ({\n * ...ctx,\n * todos: ctx.todos.map(todo =>\n * todo.id === id ? { ...todo, ...updates } : todo\n * )\n * })\n * );\n * ```\n */\n return function createTransition<TArgs extends any[]>(\n transformer: (ctx: C, ...args: TArgs) => C\n ) {\n return function (this: BaseMachine<C>, ...args: TArgs): Machine<C> {\n const nextContext = transformer(this.context, ...args);\n // Use `this` as the transitions object, which includes all current transitions\n return createMachine(nextContext, this);\n };\n };\n}\n\n/**\n * Creates a factory for adding new, type-safe transitions to an existing machine instance.\n * This enables a functional, compositional approach to building up a machine's capabilities\n * incrementally, without modifying the original machine.\n *\n * This pattern supports:\n * - Progressive enhancement of machine behavior\n * - Plugin-like extension of existing machines\n * - Immutable composition (original machine unchanged)\n * - Type-safe addition of new transitions\n *\n * @template M The machine type being extended\n * @param machine The machine instance to extend\n * @returns An `addTransition` function pre-configured for this machine\n *\n * @example\n * ```typescript\n * // Start with a basic counter machine\n * const basicCounter = createMachine({ count: 0 }, {\n * increment: function() {\n * return createMachine({ count: this.context.count + 1 }, this);\n * }\n * });\n *\n * // Create an extender for this machine\n * const extendCounter = createTransitionExtender(basicCounter);\n *\n * // Add new transitions functionally\n * const extendedCounter = extendCounter('decrement',\n * (ctx) => ({ count: ctx.count - 1 })\n * ).addTransition('reset',\n * (ctx) => ({ count: 0 })\n * ).addTransition('add',\n * (ctx, amount: number) => ({ count: ctx.count + amount })\n * );\n *\n * // The original machine is unchanged\n * console.log(basicCounter.count); // 0\n *\n * // The extended machine has all transitions\n * const result = extendedCounter.increment().add(10).decrement();\n * console.log(result.count); // 10\n * ```\n */\nexport function createTransitionExtender<M extends Machine<any>>(machine: M) {\n type C = M['context'];\n\n /**\n * Adds a new transition to the machine and returns a new extender for chaining.\n * The new transition is created from a pure context transformer function.\n *\n * @template TName The name of the new transition\n * @template TArgs The argument types for the new transition\n * @param name The name of the new transition method\n * @param transformer A pure function that defines how the context should change\n * @returns A new transition extender with the added transition\n *\n * @example\n * ```typescript\n * const userMachine = createMachine({ name: '', email: '' }, {});\n * const extendUser = createTransitionExtender(userMachine);\n *\n * const withValidation = extendUser.addTransition('setName',\n * (ctx, name: string) => {\n * if (name.length < 2) throw new Error('Name too short');\n * return { ...ctx, name };\n * }\n * ).addTransition('setEmail',\n * (ctx, email: string) => {\n * if (!email.includes('@')) throw new Error('Invalid email');\n * return { ...ctx, email };\n * }\n * );\n *\n * const user = withValidation.machine.setName('John').setEmail('john@example.com');\n * ```\n */\n return {\n machine,\n\n addTransition: function<\n TName extends string,\n TArgs extends any[],\n >(\n name: TName,\n transformer: (ctx: C, ...args: TArgs) => C\n ) {\n const transitionFn = function (this: Machine<C>, ...args: TArgs) {\n const nextContext = transformer(this.context, ...args);\n\n // Use `this` as the transitions object, which includes all current transitions\n return createMachine(nextContext, this);\n };\n\n // Create the extended machine\n const newMachine = extendTransitions(machine, { [name]: transitionFn } as any);\n\n // Return a new extender that includes this transition\n return createTransitionExtender(newMachine);\n }\n };\n}\n\n/**\n * A mapped type that creates the final transition method signatures based on\n * an object of pure context transformers. It infers argument types and sets\n * the correct return type.\n */\ntype MachineTransitions<\n T extends Record<string, (ctx: C, ...args: any[]) => C>,\n C extends object\n> = {\n [K in keyof T]: T[K] extends (ctx: C, ...args: infer A) => C\n ? (this: Machine<C>, ...args: A) => Machine<C>\n : never;\n};\n\n/**\n * Creates a complete, type-safe, functional state machine using a curried, two-step\n * approach that separates the initial data from the transition logic.\n *\n * This is a highly declarative and functional pattern for building single-state machines.\n *\n * @template C The context type of the machine.\n * @param initialContext The starting context (data) for the machine.\n * @returns A new function that takes an object of pure context-transformer\n * functions and returns a fully-formed machine instance.\n */\nexport function createFunctionalMachine<C extends object>(initialContext: C) {\n /**\n * This returned function is pre-configured with the `initialContext`.\n *\n * @template T The type of the transformers object.\n * @param transformers An object where each key is a transition name and each value\n * is a pure function: `(context, ...args) => nextContext`.\n * @returns A fully-formed, immutable, and type-safe machine instance.\n *\n * @example\n * ```typescript\n * const createCounter = createFunctionalMachine({ count: 0 });\n *\n * const counter = createCounter({\n * increment: (ctx) => ({ count: ctx.count + 1 }),\n * decrement: (ctx) => ({ count: ctx.count - 1 }),\n * add: (ctx, amount: number) => ({ count: ctx.count + amount }),\n * reset: (ctx) => ({ count: 0 })\n * });\n *\n * // Use the machine\n * const updated = counter.increment().add(5).decrement();\n * console.log(updated.context.count); // 5\n * ```\n */\n return function withTransitions<\n T extends Record<string, (ctx: C, ...args: any[]) => C>\n >(\n transformers: T\n ): Machine<C> & MachineTransitions<T, C> {\n // 1. Create a placeholder object for the final transitions.\n const transitions: any = {};\n\n // 2. Map the pure transformers to full machine transition methods.\n const machineTransitions = Object.fromEntries(\n Object.entries(transformers).map(([key, transformer]) => [\n key,\n function (this: { context: C }, ...args: any[]) {\n // Apply the pure data transformation.\n const nextContext = transformer(this.context, ...args);\n // Return a new machine, passing in the `transitions` object from the closure.\n // At this point, `transitions` will be fully populated.\n return createMachine(nextContext, transitions);\n },\n ])\n );\n\n // 3. Populate the placeholder with the real transitions.\n Object.assign(transitions, machineTransitions);\n\n // 4. Create and return the initial machine instance using the provided context.\n return createMachine(initialContext, transitions) as any;\n };\n}\n\n/**\n * A smart, type-safe function that creates state machines using either the traditional\n * `createMachine` pattern or the functional `createFunctionalMachine` pattern, automatically\n * detecting which approach to use based on the arguments provided.\n *\n * **Two Usage Patterns:**\n *\n * 1. **Traditional Pattern** (with transitions object):\n * ```typescript\n * const machine = state({ count: 0 }, {\n * increment() { return createMachine({ count: this.context.count + 1 }, this); }\n * });\n * ```\n *\n * 2. **Functional Pattern** (curried, with transformers):\n * ```typescript\n * const createCounter = state({ count: 0 });\n * const machine = createCounter({\n * increment: ctx => ({ count: ctx.count + 1 }),\n * add: (ctx, n: number) => ({ count: ctx.count + n })\n * });\n * ```\n *\n * **How it works:**\n * - When called with 2 arguments: Uses `createMachine` (traditional pattern)\n * - When called with 1 argument: Uses `createFunctionalMachine` (functional pattern)\n *\n * **Edge Cases Handled:**\n * - Empty transitions object: Falls back to functional pattern\n * - Context with function properties: Properly typed as transitions vs transformers\n * - Type inference: Maintains full type safety in both patterns\n *\n * @template C The context type\n * @template T The transitions/transformers type\n * @param context The initial context object\n * @param transitions Optional transitions object (traditional pattern)\n * @returns Either a machine (traditional) or a factory function (functional)\n *\n * @example\n * ```typescript\n * // Traditional pattern\n * const counter1 = state({ count: 0 }, {\n * increment() { return createMachine({ count: this.context.count + 1 }, this); },\n * decrement() { return createMachine({ count: this.context.count - 1 }, this); }\n * });\n *\n * // Functional pattern\n * const createCounter = state({ count: 0 });\n * const counter2 = createCounter({\n * increment: ctx => ({ count: ctx.count + 1 }),\n * decrement: ctx => ({ count: ctx.count - 1 }),\n * reset: ctx => ({ count: 0 })\n * });\n * ```\n */\nexport function state<C extends object>(context: C): ReturnType<typeof createFunctionalMachine<C>>;\nexport function state<C extends object, T extends Record<string, any>>(\n context: C,\n transitions: T\n): Machine<C> & T;\nexport function state<C extends object, T extends Record<string, any>>(\n context: C,\n transitions?: T\n): Machine<C> & T | ReturnType<typeof createFunctionalMachine<C>> {\n // If transitions is provided (2 arguments), use traditional createMachine pattern\n if (transitions !== undefined) {\n return createMachine(context, transitions);\n }\n\n // If only context is provided (1 argument), use functional createFunctionalMachine pattern\n return createFunctionalMachine(context);\n}", "/**\n * @file A tiny, immutable, and type-safe state machine library for TypeScript.\n * @author doeixd\n * @version 1.0.0\n */\n\n// =============================================================================\n// SECTION: CORE TYPES & INTERFACES\n// =============================================================================\n\n/**\n * A utility type that represents either a value of type T or a Promise that resolves to T.\n * @template T - The value type.\n */\nexport type MaybePromise<T> = T | Promise<T>;\n\n/**\n * The fundamental shape of a synchronous machine. This is a highly advanced\n * generic type that performs two critical functions at compile time:\n *\n * 1. **Extraction:** It intelligently infers the pure transitions object from\n * the flexible argument `A` (which can be a plain object, a factory\n * function, or the augmented `this` from another transition).\n *\n * 2. **Filtering:** After extracting the transitions, it filters them, keeping\n * only the functions that return a valid `Machine`.\n *\n * This makes the `Machine` type itself the single source of truth for what\n * constitutes a valid, type-safe machine, enabling a remarkably clean and\n * powerful API for `createMachine`.\n *\n * @template C The context object type.\n * @template A The raw, flexible argument for transitions (object, factory, or `this`).\n */\nexport type Machine<\n C extends object,\n T extends object = {}\n> = {\n readonly context: C;\n} & T;\n\n/**\n * The shape of an asynchronous machine, where transitions can return Promises.\n * Async transitions receive an AbortSignal as the last parameter for cancellation support.\n * @template C - The context object type.\n */\nexport type AsyncMachine<\n C extends object,\n T extends object = {}\n> = {\n readonly context: C;\n} & T;\n\n/**\n * Utility type to extract the parameters of an async transition function,\n * which includes TransitionOptions as the last parameter.\n */\nexport type AsyncTransitionArgs<M extends AsyncMachine<any, any>, K extends keyof M & string> =\n M[K] extends (...a: infer A) => any\n ? A extends [...infer Rest, TransitionOptions] ? Rest : A\n : never;\n\n/**\n * A helper type to define a distinct state in a state machine (a \"typestate\").\n * Allows defining the context and transitions in a single generic type.\n * @template C - The context specific to this state.\n * @template T - The transitions available in this state.\n */\nexport type TypeState<C extends object, T extends object = {}> = Machine<C, T>;\n\n/**\n * A helper type to define a distinct async state in a state machine.\n * @template C - The context specific to this state.\n * @template T - The transitions available in this state.\n */\nexport type AsyncTypeState<C extends object, T extends object = {}> = AsyncMachine<C, T>;\n\n\n/**\n * Options passed to async transition functions, including cancellation support.\n */\nexport interface TransitionOptions {\n /** AbortSignal for cancelling long-running async operations. */\n signal: AbortSignal;\n}\n\n\n// =============================================================================\n// SECTION: TYPE UTILITIES & INTROSPECTION\n// =============================================================================\n\n\n\n/**\n * Extracts the context type `C` from a machine type `M`.\n * @template M - The machine type.\n * @example type Ctx = Context<Machine<{ count: number }>> // { count: number }\n */\nexport type Context<M extends { context: any }> = M[\"context\"];\n\n/**\n * Extracts the transition function signatures from a machine, excluding the context property.\n * @template M - The machine type.\n */\nexport type Transitions<M extends BaseMachine<any>> = Omit<M, \"context\">;\n\n/**\n * Extracts the argument types for a specific transition function in a Machine.\n * @template M - The machine type.\n * @template K - The transition function name.\n */\nexport type TransitionArgs<M extends Machine<any>, K extends keyof M & string> =\n M[K] extends (...args: infer A) => any ? A : never;\n/**\n * Extracts the names of all transitions as a string union type.\n * @template M - The machine type.\n * @example\n * type Names = TransitionNames<Machine<{ count: number }> & { increment: () => any }>\n * // Names = \"increment\"\n */\nexport type TransitionNames<M extends BaseMachine<any>> = keyof Omit<M, \"context\"> & string;\n\n/**\n * Base machine type that both Machine and AsyncMachine extend from.\n * @template C - The context object type.\n */\nexport type BaseMachine<C extends object> = {\n /** The readonly state of the machine. */\n readonly context: C;\n};\n\n/**\n * Helper to make a type deeply readonly (freezes nested objects).\n * Useful for ensuring immutability of context at the type level.\n * @template T - The type to make readonly.\n */\nexport type DeepReadonly<T> = {\n readonly [P in keyof T]: T[P] extends object\n ? T[P] extends (...args: any[]) => any\n ? T[P]\n : DeepReadonly<T[P]>\n : T[P];\n};\n\n/**\n * Infers the machine type from a machine factory function.\n * @template F - The factory function type.\n * @example\n * const factory = () => createMachine({ count: 0 }, { ... });\n * type MyMachine = InferMachine<typeof factory>; // Extracts the return type\n */\nexport type InferMachine<F extends (...args: any[]) => any> = ReturnType<F>;\n\n\nexport type EventFromTransitions<T extends Record<string, (...args: any[]) => any>> =\n { [K in keyof T & string]: { type: K; args: T[K] extends (...a: infer A) => any ? A : never } }[keyof T & string];\n\n/**\n * A discriminated union type representing an event that can be dispatched to a machine.\n * This is automatically generated from a machine's type signature, ensuring full type safety.\n * @template M - The machine type.\n * @example\n * type CounterEvent = Event<Machine<{ count: number }>& { add: (n: number) => any }>\n * // CounterEvent = { type: \"add\"; args: [number] }\n */\nexport type Event<M extends BaseMachine<any>> = {\n [K in keyof Omit<M, \"context\"> & string]: M[K] extends (...args: infer A) => any\n ? { type: K; args: A }\n : never\n}[keyof Omit<M, \"context\"> & string];\n\n\n/**\n * A helper type for use with TypeScript's `satisfies` operator to provide\n * strong, immediate type-checking for standalone transition objects.\n *\n * This solves the \"chicken-and-egg\" problem where you need the final machine\n * type to correctly type the transitions object, but you need the transitions\n * object to create the machine. By forward-declaring the machine type and using\n * `satisfies TransitionsFor<...>`, you get full IntelliSense and error-checking\n * at the exact location of your transition definitions.\n *\n * @template C The context object type for the machine.\n * @template T The literal type of the transitions object itself (`typeof myTransitions`).\n *\n * @example\n * import { createMachine, Machine, TransitionsFor } from '@doeixd/machine';\n *\n * // 1. Define the context for your machine.\n * type CounterContext = { count: number };\n *\n * // 2. Forward-declare the final machine type. This is the key step that\n * // breaks the circular dependency for the type checker.\n * type CounterMachine = Machine<CounterContext> & typeof counterTransitions;\n *\n * // 3. Define the transitions object, using `satisfies` to apply the helper type.\n * // This provides immediate type-checking and full autocompletion for `this`.\n * const counterTransitions = {\n * increment() {\n * // `this` is now fully typed!\n * // IntelliSense knows `this.context.count` is a number and\n * // `this.transitions.add` is a function.\n * return createMachine({ count: this.context.count + 1 }, this.transitions);\n * },\n * add(n: number) {\n * return createMachine({ count: this.context.count + n }, this.transitions);\n * },\n * // ❌ TypeScript will immediately throw a compile error on the next line\n * // because the return type 'string' does not satisfy 'Machine<any>'.\n * invalidTransition() {\n * return \"this is not a machine\";\n * }\n * } satisfies TransitionsFor<CounterContext, typeof counterTransitions>;\n *\n * // 4. Create the machine instance. The `createMachine` call is now\n * // guaranteed to be type-safe because `counterTransitions` has already\n * // been validated.\n * export function createCounter(initialCount = 0): CounterMachine {\n * return createMachine({ count: initialCount }, counterTransitions);\n * }\n */\nexport type TransitionsFor<C extends object, T extends Record<string, any>> = {\n [K in keyof T]: (this: Machine<C, T>, ...args: Parameters<T[K] extends (...a: infer A) => any ? (...a: A) => any : never>) => Machine<any, any>;\n};\n\n/**\n * A helper type for use with the `satisfies` operator to provide strong\n * type-checking for standalone asynchronous transition objects.\n */\nexport type AsyncTransitionsFor<C extends object, T extends Record<string, any>> = {\n [K in keyof T]: (this: Machine<C, T>, ...args: Parameters<T[K] extends (...a: infer A) => any ? (...a: A) => any : never>) => MaybePromise<AsyncMachine<any, any>>;\n};\n\n/**\n * A mapped type that iterates over a transitions object `T` and keeps only the\n * keys whose functions return a valid `Machine`. This provides a \"self-correcting\"\n * type that prevents the definition of invalid transitions at compile time.\n *\n * It acts as a filter at the type level. When used in the return type of a\n * function like `createMachine`, it ensures that the resulting machine object\n * will not have any properties corresponding to functions that were defined\n * with an incorrect return type. This provides immediate, precise feedback to\n * the developer, making it impossible to create a machine with an invalid\n * transition shape.\n *\n * @template T The raw transitions object type provided by the user.\n *\n * @example\n * import { createMachine, Machine } from '@doeixd/machine';\n *\n * const machine = createMachine({ value: 'A' }, {\n * // This is a valid transition because it returns a `Machine`.\n * // The key 'goToB' will be PRESERVED in the final type.\n * goToB() {\n * return createMachine({ value: 'B' }, this.transitions);\n * },\n *\n * // This is an INVALID transition because it returns a string.\n * // The key 'invalid' will be OMITTED from the final type.\n * invalid() {\n * return \"This is not a Machine object\";\n * },\n *\n * // This is also invalid as it's not a function.\n * // The key 'alsoInvalid' will be OMITTED from the final type.\n * alsoInvalid: 123\n * });\n *\n * // --- USAGE ---\n *\n * // ✅ This call is valid and works as expected.\n * const nextState = machine.goToB();\n *\n * // ❌ This line will cause a COMPILE-TIME a ERROR because the `FilterValidTransitions`\n * // type has removed the 'invalid' key from the `machine`'s type signature.\n * //\n * // Error: Property 'invalid' does not exist on type\n * // 'Machine<{ value: string; }> & { goToB: () => Machine<...>; }'.\n * //\n * machine.invalid();\n */\nexport type FilterValidTransitions<T> = {\n [K in keyof T as T[K] extends (...args: any[]) => Machine<any> ? K : never]: T[K];\n};\n\n/**\n * A conditional type that intelligently extracts the pure transitions object `T`\n * from the flexible second argument of `createMachine`.\n *\n * It handles three cases:\n * 1. If the argument is the augmented `this` context (`C & { transitions: T }`), it extracts `T`.\n * 2. If the argument is a factory function `((ctx: C) => T)`, it infers and returns `T`.\n * 3. If the argument is already the pure transitions object `T`, it returns it as is.\n */\nexport type ExtractTransitions<Arg, C extends object> = Arg extends (\n ...args: any[]\n) => infer R\n ? R // Case 2: It's a factory function, extract the return type `R`.\n : Arg extends C & { transitions: infer T }\n ? T // Case 1: It's the augmented `this` context, extract `T` from `transitions`.\n : Arg; // Case 3: It's already the plain transitions object.\n\n/** Keep only keys whose value is a function that returns a Machine. */\nexport type ValidTransitions<T> = {\n [K in keyof T as T[K] extends (...a: any[]) => Machine<any, any> ? K : never]:\n T[K] extends (...a: infer A) => Machine<infer C2, infer T2> ? (...a: A) => Machine<C2, T2> : never;\n};\n\n/** Same for async transitions (functions returning MaybePromise<AsyncMachine>). */\nexport type ValidAsyncTransitions<T> = {\n [K in keyof T as T[K] extends (...a: any[]) => MaybePromise<AsyncMachine<any, any>> ? K : never]:\n T[K] extends (...a: infer A) => MaybePromise<AsyncMachine<infer C2, infer T2>> ? (...a: A) => MaybePromise<AsyncMachine<C2, T2>> : never;\n};\n\n// =============================================================================\n// SECTION: MACHINE CREATION (FUNCTIONAL & OOP)\n// =============================================================================\n\n/**\n * Creates a synchronous state machine from a context and transition functions.\n * This is the core factory for the functional approach.\n *\n * @template C - The context object type.\n * @param context - The initial state context.\n * @param fns - An object containing transition function definitions.\n * @returns A new machine instance.\n */\n/**\n * Helper to transform transition functions to be bound (no 'this' requirement).\n */\nexport type BindTransitions<T> = {\n [K in keyof T]: T[K] extends (this: any, ...args: infer A) => infer R\n ? (...args: A) => R\n : T[K];\n};\n\n/**\n * Creates a synchronous state machine from a context and a factory function.\n * This \"Functional Builder\" pattern allows for type-safe transitions without\n * manually passing `this` or `transitions`.\n *\n * @template C - The context object type.\n * @template T - The transitions object type.\n * @param context - The initial state context.\n * @param factory - A function that receives a `transition` helper and returns the transitions object.\n * @returns A new machine instance.\n */\nexport function createMachine<C extends object, T extends Record<string, (this: Machine<C, any>, ...args: any[]) => any> = Record<string, (this: Machine<C, any>, ...args: any[]) => any>>(\n context: C,\n factory: (transition: (newContext: C) => Machine<C, any>) => T\n): Machine<C, T>;\n\n/**\n * Creates a synchronous state machine from a context and transition functions.\n * This is the core factory for the functional approach.\n * Transitions receive the full machine as `this`, allowing them to access\n * `this.context` and call other transitions via `this.otherTransition()`.\n *\n * @template C - The context object type.\n * @param context - The initial state context.\n * @param fns - An object containing transition function definitions.\n * @returns A new machine instance.\n */\nexport function createMachine<C extends object, T extends Record<string, (this: Machine<C, T>, ...args: any[]) => any> & { context?: any }>(\n context: C,\n fns: T\n): Machine<C, T>;\n\n/**\n * Creates a synchronous state machine by copying context and transitions from an existing machine.\n * This is useful for creating a new machine with updated context but the same transitions.\n *\n * @template C - The context object type.\n * @template M - The machine type to copy transitions from.\n * @param context - The new context.\n * @param machine - The machine to copy transitions from.\n * @returns A new machine instance with the given context and copied transitions.\n */\nexport function createMachine<C extends object, M extends BaseMachine<C>>(\n context: C,\n machine: M\n): Machine<C, Transitions<M>>;\n\nexport function createMachine(context: any, fnsOrFactory: any): any {\n if (typeof fnsOrFactory === 'function') {\n let transitions: any;\n const transition = (newContext: any) => {\n return createMachine(newContext, transitions);\n };\n transitions = fnsOrFactory(transition);\n\n return Object.assign({ context }, transitions);\n }\n\n // If fns is a machine (has context property), extract just the transition functions\n const transitions = 'context' in fnsOrFactory ? Object.fromEntries(\n Object.entries(fnsOrFactory).filter(([key]) => key !== 'context')\n ) : fnsOrFactory;\n\n const machine = Object.assign({ context }, transitions);\n return machine;\n}\n\n/**\n * Creates an asynchronous state machine from a context and a factory function.\n * This \"Functional Builder\" pattern allows for type-safe transitions without\n * manually passing `this` or `transitions`.\n *\n * @template C - The context object type.\n * @template T - The transitions object type.\n * @param context - The initial state context.\n * @param factory - A function that receives a `transition` helper and returns the transitions object.\n * @returns A new async machine instance.\n */\nexport function createAsyncMachine<C extends object, T extends Record<string, (this: C, ...args: any[]) => any>>(\n context: C,\n factory: (transition: (newContext: C) => AsyncMachine<C, T>) => T\n): AsyncMachine<C, BindTransitions<T>>;\n\n/**\n * Creates an asynchronous state machine by copying context and transitions from an existing machine.\n * This is useful for creating a new machine with updated context but the same transitions.\n *\n * @template C - The context object type.\n * @template M - The machine type to copy transitions from.\n * @param context - The new context.\n * @param machine - The machine to copy transitions from.\n * @returns A new async machine instance with the given context and copied transitions.\n */\nexport function createAsyncMachine<C extends object, M extends BaseMachine<C>>(\n context: C,\n machine: M\n): AsyncMachine<C, Transitions<M>>;\n\n/**\n * Creates an asynchronous state machine from a context and async transition functions.\n *\n * @template C - The context object type.\n * @param context - The initial state context.\n * @param fns - An object containing async transition function definitions.\n * @returns A new async machine instance.\n */\nexport function createAsyncMachine<C extends object, T extends Record<string, (this: C, ...args: any[]) => any>>(\n context: C,\n fns: T\n): AsyncMachine<C, T>;\n\nexport function createAsyncMachine(context: any, fnsOrFactory: any): any {\n if (typeof fnsOrFactory === 'function') {\n let transitions: any;\n const transition = (newContext: any) => {\n return createAsyncMachine(newContext, transitions);\n };\n transitions = fnsOrFactory(transition);\n\n return Object.assign({ context }, transitions);\n }\n\n // If fns is a machine (has context property), extract just the transition functions\n const transitions = 'context' in fnsOrFactory ? Object.fromEntries(\n Object.entries(fnsOrFactory).filter(([key]) => key !== 'context')\n ) : fnsOrFactory;\n\n const machine = Object.assign({ context }, transitions);\n return machine;\n}\n\n/**\n * Creates a machine factory - a higher-order function that simplifies machine creation.\n * Instead of writing transition logic that creates new machines, you just write\n * pure context transformation functions.\n *\n * @template C - The context object type.\n * @returns A factory configurator function.\n *\n * @example\n * const counterFactory = createMachineFactory<{ count: number }>()({\n * increment: (ctx) => ({ count: ctx.count + 1 }),\n * add: (ctx, n: number) => ({ count: ctx.count + n })\n * });\n *\n * const counter = counterFactory({ count: 0 });\n * const next = counter.increment(); // Returns new machine with count: 1\n */\nexport function createMachineFactory<C extends object>() {\n return <T extends Record<string, (ctx: C, ...args: any[]) => C>>(\n transformers: T\n ) => {\n type MachineFns = {\n [K in keyof T]: (\n this: Machine<C>,\n ...args: T[K] extends (ctx: C, ...args: infer A) => C ? A : never\n ) => MaybePromise<Machine<C>>;\n };\n\n const fns = Object.fromEntries(\n Object.entries(transformers).map(([key, transform]) => [\n key,\n function (this: Machine<C>, ...args: any[]) {\n const newContext = (transform as any)(this.context, ...args);\n return createMachine(newContext, fns as any);\n },\n ])\n ) as MachineFns;\n\n return (initialContext: C): Machine<C> & MachineFns => {\n return createMachine(initialContext, fns);\n };\n };\n}\n\n\n// =============================================================================\n// SECTION: ADVANCED CREATION & IMMUTABLE HELPERS\n// =============================================================================\n\n/**\n * Creates a new machine instance with an updated context, preserving all original transitions.\n * This is the primary, type-safe utility for applying state changes.\n *\n * @template M - The machine type.\n * @param machine - The original machine instance.\n * @param newContextOrFn - The new context object or an updater function.\n * @returns A new machine instance of the same type with the updated context.\n */\nexport function setContext<M extends Machine<any>>(\n machine: M,\n newContextOrFn: Context<M> | ((ctx: Readonly<Context<M>>) => Context<M>)\n): M {\n const { context, ...transitions } = machine;\n const newContext =\n typeof newContextOrFn === \"function\"\n ? (newContextOrFn as (ctx: Readonly<Context<M>>) => Context<M>)(context)\n : newContextOrFn;\n\n return createMachine(newContext, transitions as any) as M;\n}\n\n/**\n * Creates a minimal machine-like object with just a context property.\n * Useful for creating test fixtures and working with pattern matching utilities.\n *\n * @template C - The context type\n * @param context - The context object\n * @returns An object with a readonly context property\n *\n * @example\n * ```typescript\n * // For testing with discriminated unions\n * type FetchContext =\n * | { status: 'idle' }\n * | { status: 'success'; data: string };\n *\n * const idleMachine = createContext<FetchContext>({ status: 'idle' });\n * const successMachine = createContext<FetchContext>({ status: 'success', data: 'result' });\n *\n * // Works with pattern matching\n * const match = createMatcher(\n * discriminantCase('idle', 'status', 'idle'),\n * discriminantCase('success', 'status', 'success')\n * );\n *\n * if (match.is.success(successMachine)) {\n * console.log(successMachine.context.data); // TypeScript knows data exists\n * }\n * ```\n */\nexport function createContext<C extends object>(\n context: C\n): { readonly context: C } {\n return { context };\n}\n\n/**\n * Creates a new machine by overriding or adding transition functions to an existing machine.\n * Ideal for mocking in tests or decorating functionality. The original machine is unchanged.\n *\n * @template M - The original machine type.\n * @template T - An object of new or overriding transition functions.\n * @param machine - The base machine instance.\n * @param overrides - An object containing the transitions to add or overwrite.\n * @returns A new machine instance with the merged transitions.\n */\nexport function overrideTransitions<\n M extends Machine<any>,\n T extends Record<string, (this: Context<M>, ...args: any[]) => any>\n>(\n machine: M,\n overrides: T\n): Machine<Context<M>> & Omit<Transitions<M>, keyof T> & T {\n const { context, ...originalTransitions } = machine;\n const newTransitions = { ...originalTransitions, ...overrides };\n return createMachine(context, newTransitions as any) as any;\n}\n\n/**\n * Creates a new machine by adding new transition functions.\n * This utility will produce a compile-time error if you attempt to add a\n * transition that already exists, preventing accidental overrides.\n *\n * @template M - The original machine type.\n * @template T - An object of new transition functions, whose keys must not exist in M.\n * @param machine - The base machine instance.\n * @param newTransitions - An object containing the new transitions to add.\n * @returns A new machine instance with the combined original and new transitions.\n */\nexport function extendTransitions<\n M extends Machine<any>,\n T extends Record<string, (this: Context<M>, ...args: any[]) => any> & {\n [K in keyof T]: K extends keyof M ? never : T[K];\n }\n>(machine: M, newTransitions: T): M & T {\n const { context, ...originalTransitions } = machine;\n const combinedTransitions = { ...originalTransitions, ...newTransitions };\n return createMachine(context, combinedTransitions as any) as M & T;\n}\n\n/**\n * Combines two machine factories into a single factory that creates machines with merged context and transitions.\n * This allows you to compose independent state machines that operate on different parts of the same context.\n *\n * The resulting factory takes the parameters of the first factory, while the second factory is called with no arguments.\n * Context properties are merged (second factory's context takes precedence on conflicts).\n * Transition names must not conflict between the two machines.\n *\n * @template F1 - The first factory function type.\n * @template F2 - The second factory function type.\n * @param factory1 - The first machine factory (provides parameters and primary context).\n * @param factory2 - The second machine factory (provides additional context and transitions).\n * @returns A new factory function that creates combined machines.\n *\n * @example\n * ```typescript\n * // Define two independent machines\n * const createCounter = (initial: number) =>\n * createMachine({ count: initial }, {\n * increment: function() { return createMachine({ count: this.context.count + 1 }, this); },\n * decrement: function() { return createMachine({ count: this.context.count - 1 }, this); }\n * });\n *\n * const createLogger = () =>\n * createMachine({ logs: [] as string[] }, {\n * log: function(message: string) {\n * return createMachine({ logs: [...this.context.logs, message] }, this);\n * },\n * clear: function() {\n * return createMachine({ logs: [] }, this);\n * }\n * });\n *\n * // Combine them\n * const createCounterWithLogging = combineFactories(createCounter, createLogger);\n *\n * // Use the combined factory\n * const machine = createCounterWithLogging(5); // { count: 5, logs: [] }\n * const incremented = machine.increment(); // { count: 6, logs: [] }\n * const logged = incremented.log(\"Count incremented\"); // { count: 6, logs: [\"Count incremented\"] }\n * ```\n */\nexport function combineFactories<\n F1 extends (...args: any[]) => Machine<any>,\n F2 extends () => Machine<any>\n>(\n factory1: F1,\n factory2: F2\n): (\n ...args: Parameters<F1>\n) => Machine<Context<ReturnType<F1>> & Context<ReturnType<F2>>> &\n Omit<ReturnType<F1>, 'context'> &\n Omit<ReturnType<F2>, 'context'> {\n return (...args: Parameters<F1>) => {\n // Create instances from both factories\n const machine1 = factory1(...args);\n const machine2 = factory2();\n\n // Merge contexts (machine2 takes precedence on conflicts)\n const combinedContext = { ...machine1.context, ...machine2.context };\n\n // Extract transitions from both machines\n const { context: _, ...transitions1 } = machine1;\n const { context: __, ...transitions2 } = machine2;\n\n // Combine transitions (TypeScript will catch conflicts at compile time)\n const combinedTransitions = { ...transitions1, ...transitions2 };\n\n // Create the combined machine\n return createMachine(combinedContext, combinedTransitions as any) as any;\n };\n}\n\n/**\n * Creates a builder function from a \"template\" machine instance.\n * This captures the behavior of a machine and returns a factory that can stamp out\n * new instances with different initial contexts. Excellent for class-based machines.\n *\n * @template M - The machine type.\n * @param templateMachine - An instance of a machine to use as the template.\n * @returns A function that builds new machines of type M.\n */\nexport function createMachineBuilder<M extends Machine<any>>(\n templateMachine: M\n): (context: Context<M>) => M {\n const { context, ...transitions } = templateMachine;\n return (newContext: Context<M>): M => {\n return createMachine(newContext, transitions as any) as M;\n };\n}\n\n/**\n * Pattern match on a machine's state based on a discriminant property in the context.\n * This provides type-safe exhaustive matching for state machines.\n *\n * @template M - The machine type.\n * @template K - The discriminant key in the context.\n * @template R - The return type.\n * @param machine - The machine to match against.\n * @param discriminantKey - The key in the context to use for matching (e.g., \"status\").\n * @param handlers - An object mapping each possible value to a handler function.\n * @returns The result of the matched handler.\n *\n * @example\n * const result = matchMachine(\n * machine,\n * 'status',\n * {\n * idle: (ctx) => \"Machine is idle\",\n * loading: (ctx) => \"Loading...\",\n * success: (ctx) => `Success: ${ctx.data}`,\n * error: (ctx) => `Error: ${ctx.error}`\n * }\n * );\n */\nexport function matchMachine<\n M extends Machine<any>,\n K extends keyof Context<M> & string,\n R\n>(\n machine: M,\n discriminantKey: K,\n handlers: {\n [V in Context<M>[K] & string]: (ctx: Context<M>) => R;\n }\n): R {\n const discriminant = machine.context[discriminantKey] as Context<M>[K] & string;\n const handler = handlers[discriminant];\n if (!handler) {\n throw new Error(`No handler found for state: ${String(discriminant)}`);\n }\n return handler(machine.context);\n}\n\n/**\n * Type-safe helper to assert that a machine's context has a specific discriminant value.\n * This narrows the type of the context based on the discriminant, properly handling\n * discriminated unions.\n *\n * @template M - The machine type.\n * @template K - The discriminant key.\n * @template V - The discriminant value.\n * @param machine - The machine to check.\n * @param key - The discriminant key to check.\n * @param value - The expected value.\n * @returns True if the discriminant matches, with type narrowing.\n *\n * @example\n * type Context = { status: 'idle' } | { status: 'loading' } | { status: 'success'; data: string };\n * const machine = createMachine<Context>({ status: 'success', data: 'test' }, {});\n *\n * if (hasState(machine, 'status', 'success')) {\n * // machine.context is narrowed to { status: 'success'; data: string }\n * console.log(machine.context.data); // ✓ TypeScript knows about 'data'\n * }\n */\nexport function hasState<\n M extends Machine<any>,\n K extends keyof Context<M>,\n V extends Context<M>[K]\n>(\n machine: M,\n key: K,\n value: V\n): machine is M & { context: Extract<Context<M>, { [P in K]: V }> } {\n return machine.context[key] === value;\n}\n\n\n// =============================================================================\n// SECTION: RUNTIME & EVENT DISPATCHER\n// =============================================================================\n\n/**\n * Runs an asynchronous state machine with a managed lifecycle and event dispatch capability.\n * This is the \"interpreter\" for async machines, handling state updates and side effects.\n * Provides automatic AbortController management to prevent async race conditions.\n *\n * @template M - The initial machine type.\n * @param initial - The initial machine state.\n * @param onChange - Optional callback invoked with the new machine state after every transition.\n * @returns An object with a `state` getter for the current context, an async `dispatch` function, and a `stop` method.\n */\nexport function runMachine<M extends AsyncMachine<any>>(\n initial: M,\n onChange?: (m: M) => void\n) {\n let current = initial;\n // Keep track of the controller for the currently-running async transition.\n let activeController: AbortController | null = null;\n\n async function dispatch<E extends Event<typeof current>>(event: E): Promise<M> {\n // 1. If an async transition is already in progress, cancel it.\n if (activeController) {\n activeController.abort();\n activeController = null;\n }\n\n const fn = (current as any)[event.type];\n if (typeof fn !== 'function') {\n throw new Error(`[Machine] Unknown event type '${String(event.type)}' on current state.`);\n }\n\n // 2. Create a new AbortController for this new transition.\n const controller = new AbortController();\n activeController = controller;\n\n try {\n // 3. Pass the signal to the transition function.\n const nextStatePromise = fn.apply(current, [...event.args, { signal: controller.signal }]);\n\n const nextState = await nextStatePromise;\n\n // 4. If this promise resolved but has since been aborted, do not update state.\n // This prevents the race condition.\n if (controller.signal.aborted) {\n // Return the *current* state, as if the transition never completed.\n return current;\n }\n\n current = nextState;\n onChange?.(current);\n return current;\n\n } finally {\n // 5. Clean up the controller once the transition is complete (resolved or rejected).\n // Only clear it if it's still the active one.\n if (activeController === controller) {\n activeController = null;\n }\n }\n }\n\n return {\n /** Gets the context of the current state of the machine. */\n get state(): Context<M> {\n return current.context;\n },\n /** Dispatches a type-safe event to the machine, triggering a transition. */\n dispatch,\n /** Stops any pending async operation and cleans up resources. */\n stop: () => {\n if (activeController) {\n activeController.abort();\n activeController = null;\n }\n },\n };\n}\n\n/**\n * An optional base class for creating machines using an Object-Oriented style.\n *\n * This class provides the fundamental structure required by the library: a `context`\n * property to hold the state. By extending `MachineBase`, you get a clear and\n * type-safe starting point for defining states and transitions as classes and methods.\n *\n * Transitions should be implemented as methods that return a new instance of a\n * state machine class (often `new MyClass(...)` or by using a `createMachineBuilder`).\n * The `context` is marked `readonly` to enforce the immutable update pattern.\n *\n * @template C - The context object type that defines the state for this machine.\n *\n * @example\n * // Define a simple counter state\n * class Counter extends MachineBase<{ readonly count: number }> {\n * constructor(count = 0) {\n * super({ count });\n * }\n *\n * increment(): Counter {\n * // Return a new instance for the next state\n * return new Counter(this.context.count + 1);\n * }\n *\n * add(n: number): Counter {\n * return new Counter(this.context.count + n);\n * }\n * }\n *\n * const machine = new Counter(5);\n * const nextState = machine.increment(); // Returns a new Counter instance\n *\n * console.log(machine.context.count); // 5 (original is unchanged)\n * console.log(nextState.context.count); // 6 (new state)\n */\nexport class MachineBase<C extends object> {\n /**\n * The immutable state of the machine.\n * To change the state, a transition method must return a new machine instance\n * with a new context object.\n */\n public readonly context: C;\n\n /**\n * Initializes a new machine instance with its starting context.\n * @param context - The initial state of the machine.\n */\n constructor(context: C) {\n this.context = context;\n // Object.freeze can provide additional runtime safety against accidental mutation,\n // though it comes with a minor performance cost. It's a good practice for ensuring purity.\n // Object.freeze(this.context);\n }\n}\n\n\n/**\n * Applies an update function to a machine's context, returning a new machine.\n * This is a simpler alternative to `setContext` when you always use an updater function.\n *\n * @template C - The context object type.\n * @param m - The machine to update.\n * @param update - A function that takes the current context and returns the new context.\n * @returns A new machine with the updated context.\n *\n * @example\n * const updated = next(counter, (ctx) => ({ count: ctx.count + 1 }));\n */\nexport function next<C extends object>(\n m: Machine<C>,\n update: (ctx: Readonly<C>) => C\n): Machine<C> {\n const { context, ...transitions } = m;\n return createMachine(update(context), transitions as any) as Machine<C>;\n}\n\n/**\n * A type representing either a synchronous Machine or a Promise that resolves to a Machine.\n * Useful for functions that can return either sync or async machines.\n *\n * @template C - The context object type.\n *\n * @example\n * function getMachine(): MachineLike<{ count: number }> {\n * if (Math.random() > 0.5) {\n * return createMachine({ count: 0 }, { ... });\n * } else {\n * return Promise.resolve(createMachine({ count: 0 }, { ... }));\n * }\n * }\n */\nexport type MachineLike<C extends object> =\n | Machine<C>\n | Promise<Machine<C>>;\n\n/**\n * A type representing the result of a machine transition.\n * Can be either:\n * - A new machine state\n * - A tuple of [machine, cleanup function] where cleanup is called when leaving the state\n *\n * This enables state machines with side effects that need cleanup (e.g., subscriptions, timers).\n *\n * @template C - The context object type.\n *\n * @example\n * function transition(): MachineResult<{ count: number }> {\n * const interval = setInterval(() => console.log(\"tick\"), 1000);\n * const machine = createMachine({ count: 0 }, { ... });\n * return [machine, () => clearInterval(interval)];\n * }\n */\nexport type MachineResult<C extends object> =\n | Machine<C>\n | [Machine<C>, () => void | Promise<void>];\n\n\n// =============================================================================\n// SECTION: GENERATOR-BASED COMPOSITION\n// =============================================================================\n\nexport {\n run,\n step,\n yieldMachine,\n runSequence,\n createFlow,\n runWithDebug,\n runAsync,\n stepAsync\n} from './generators';\n\n// =============================================================================\n// SECTION: TYPE-LEVEL METADATA PRIMITIVES\n// =============================================================================\n\nexport {\n transitionTo,\n describe,\n guarded,\n guard,\n guardAsync,\n whenGuard,\n whenGuardAsync,\n invoke,\n action,\n metadata,\n META_KEY,\n type TransitionMeta,\n type GuardMeta,\n type InvokeMeta,\n type ActionMeta,\n type ClassConstructor,\n type WithMeta,\n type GuardOptions,\n type GuardFallback,\n type GuardedTransition\n} from './primitives';\n\n// =============================================================================\n// SECTION: STATECHART EXTRACTION (Build-time only)\n// =============================================================================\n\n// Note: Extraction tools are available as dev dependencies for build-time use\n// They are not included in the runtime bundle for size optimization\n// Use: npx tsx scripts/extract-statechart.ts\n\nexport type {\n MachineConfig,\n ExtractionConfig,\n ParallelRegionConfig,\n ChildStatesConfig\n} from './extract';\n\n// Note: Extraction functions (extractMachine, extractMachines, generateChart) are NOT exported\n// to keep them out of the runtime bundle. Use the CLI tool or import directly from the source\n// file for build-time statechart generation.\n\nexport * from './multi'\n\nexport * from './higher-order'\n\n// =============================================================================\n// SECTION: MIDDLEWARE & INTERCEPTION\n// =============================================================================\n\nexport * from './middleware/index';\n\nexport * from './mixins';\n\n// =============================================================================\n// SECTION: UTILITIES & HELPERS\n// =============================================================================\n\nexport {\n isState,\n createEvent,\n createTransition,\n mergeContext,\n pipeTransitions,\n logState,\n call,\n bindTransitions,\n BoundMachine\n} from './utils';\n\n// =============================================================================\n// SECTION: FUNCTIONAL COMBINATORS\n// =============================================================================\n\nexport {\n createTransitionFactory,\n createTransitionExtender,\n createFunctionalMachine,\n state\n} from './functional-combinators';\n\n// =============================================================================\n// SECTION: PATTERN MATCHING\n// =============================================================================\n\nexport {\n createMatcher,\n classCase,\n discriminantCase,\n customCase,\n forContext,\n type MatcherCase,\n type CasesToMapping,\n type MatcherUnion,\n type CaseNames,\n type CaseHandler,\n type ExhaustivenessMarker,\n type IsExhaustive,\n type WhenBuilder,\n type Matcher\n} from './matcher';\n\n// =============================================================================\n// SECTION: ACTOR MODEL\n// =============================================================================\n\nexport {\n Actor,\n createActor,\n spawn,\n fromPromise,\n fromObservable,\n type ActorRef,\n type InspectionEvent\n} from './actor';\n\n// =============================================================================\n// SECTION: CONTEXT-BOUND UTILITIES\n// =============================================================================\n\nexport {\n createContextBoundMachine,\n callWithContext,\n isContextBound,\n type ContextBoundMachine\n} from './context-bound';"],
5
+ "mappings": ";AAuHO,SAAS,IACd,MACA,SACG;AAEH,QAAM,YAAY,KAAK,OAAO;AAG9B,MAAI,UAAU;AAGd,SAAO,MAAM;AAGX,UAAM,EAAE,OAAO,KAAK,IAAI,UAAU,KAAK,OAAO;AAG9C,QAAI,MAAM;AACR,aAAO;AAAA,IACT;AAIA,cAAU;AAAA,EACZ;AACF;AAuDO,SAAS,KACd,GACoB;AAKpB,SAAQ,aAAa;AACnB,UAAM,WAAW,MAAM;AACvB,WAAO;AAAA,EACT,EAAG;AACL;AAqBO,SAAS,aAAmG,GAAS;AAC1H,SAAO;AACT;AA4BO,SAAS,YACd,SACA,OACG;AACH,SAAO,MAAM,OAAO,CAAC,SAAS,SAAS;AACrC,WAAO,IAAI,MAAM,OAAO;AAAA,EAC1B,GAAG,OAAO;AACZ;AA6BO,SAAS,WACd,MAC8B;AAC9B,SAAO;AACT;AA6BO,SAAS,aACd,MACA,SACA,SAA6C,CAACA,OAAM,MAAM;AACxD,UAAQ,IAAI,QAAQA,KAAI,KAAK,EAAE,OAAO;AACxC,GACG;AACH,QAAM,YAAY,KAAK,OAAO;AAC9B,MAAI,UAAU;AACd,MAAI,YAAY;AAEhB,SAAO,WAAW,OAAO;AAEzB,SAAO,MAAM;AACX,UAAM,EAAE,OAAO,KAAK,IAAI,UAAU,KAAK,OAAO;AAE9C,QAAI,MAAM;AACR,cAAQ,IAAI,UAAU,KAAK;AAC3B,aAAO;AAAA,IACT;AAEA,cAAU;AACV;AACA,WAAO,WAAW,OAAO;AAAA,EAC3B;AACF;AA2BA,eAAsB,SACpB,MACA,SACY;AACZ,QAAM,YAAY,KAAK,OAAO;AAC9B,MAAI,UAAU;AAEd,SAAO,MAAM;AACX,UAAM,EAAE,OAAO,KAAK,IAAI,MAAM,UAA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AEd,MAAI,mBAA2C;AAE/C,iBAAe,SAA0C,OAAsB;AAE7E,QAAI,kBAAkB;AACpB,uBAAiB,MAAM;AACvB,yBAAmB;AAAA,IACrB;AAEA,UAAM,KAAM,QAAgB,MAAM,IAAI;AACtC,QAAI,OAAO,OAAO,YAAY;AAC5B,YAAM,IAAI,MAAM,iCAAiC,OAAO,MAAM,IAAI,CAAC,qBAAqB;AAAA,IAC1F;AAGA,UAAM,aAAa,IAAI,gBAAgB;AACvC,uBAAmB;AAEnB,QAAI;AAEF,YAAM,mBAAmB,GAAG,MAAM,SAAS,CAAC,GAAG,MAAM,MAAM,EAAE,QAAQ,WAAW,OAAO,CAAC,CAAC;AAEzF,YAAM,YAAY,MAAM;AAIxB,UAAI,WAAW,OAAO,SAAS;AAE7B,eAAO;AAAA,MACT;AAEA,gBAAU;AACV,2CAAW;AACX,aAAO;AAAA,IAET,UAAE;AAGA,UAAI,qBAAqB,YAAY;AACnC,2BAAmB;AAAA,MACrB;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AAAA;AAAA,IAEL,IAAI,QAAoB;AACtB,aAAO,QAAQ;AAAA,IACjB;AAAA;AAAA,IAEA;AAAA;AAAA,IAEA,MAAM,MAAM;AACV,UAAI,kBAAkB;AACpB,yBAAiB,MAAM;AACvB,2BAAmB;AAAA,MACrB;AAAA,IACF;AAAA,EACF;AACF;AAsCO,IAAM,cAAN,MAAoC;AAAA;AAAA;AAAA;AAAA;AAAA,EAYzC,YAAY,SAAY;AACtB,SAAK,UAAU;AAAA,EAIjB;AACF;AAeO,SAAS,KACd,GACA,QACY;AACZ,QAAM,EAAE,SAAS,GAAG,YAAY,IAAI;AACpC,SAAO,cAAc,OAAO,OAAO,GAAG,WAAkB;AAC1D;",
6
+ "names": ["step", "metadata", "guard", "action", "guarded", "action", "machine", "prop", "value", "createTransition", "transitions"]
7
7
  }