xstate 6.0.0-beta.0 → 6.0.0-beta.2

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 (81) hide show
  1. package/bin/xstate.js +10 -4
  2. package/dist/{createActor-551369be.development.esm.js → createActor-0250284a.development.esm.js} +244 -41
  3. package/dist/{createActor-cbe3abac.esm.js → createActor-20a97166.esm.js} +243 -40
  4. package/dist/{createActor-a49ae0ce.development.cjs.js → createActor-c029d29f.development.cjs.js} +245 -40
  5. package/dist/{createActor-25900f76.cjs.js → createActor-c91c9ffe.cjs.js} +244 -39
  6. package/dist/declarations/src/createActor.d.ts +3 -1
  7. package/dist/declarations/src/createMachine.d.ts +6 -3
  8. package/dist/declarations/src/durable/index.d.ts +43 -8
  9. package/dist/declarations/src/effectDescriptor.d.ts +2 -2
  10. package/dist/declarations/src/machineVersion.types.d.ts +2 -2
  11. package/dist/declarations/src/setup.d.ts +5 -5
  12. package/dist/declarations/src/systemTransition.d.ts +1 -1
  13. package/dist/declarations/src/types.d.ts +11 -3
  14. package/dist/declarations/src/types.v6.d.ts +37 -2
  15. package/dist/{effectDescriptor-f73da4ec.development.cjs.js → effectDescriptor-3fff5c51.development.cjs.js} +5 -5
  16. package/dist/{effectDescriptor-2fa27c54.cjs.js → effectDescriptor-47f73e7e.cjs.js} +5 -5
  17. package/dist/{effectDescriptor-321a8ce9.development.esm.js → effectDescriptor-5ac7dccb.development.esm.js} +5 -5
  18. package/dist/{effectDescriptor-d8b0f749.esm.js → effectDescriptor-e93df910.esm.js} +5 -5
  19. package/dist/{machineSchemas-88d01821.cjs.js → legacySnapshot-8d595687.cjs.js} +117 -1
  20. package/dist/{machineSchemas-45c21bc2.esm.js → legacySnapshot-9e06feb4.esm.js} +116 -2
  21. package/dist/{machineSchemas-b5736804.development.esm.js → legacySnapshot-ae6594a7.development.esm.js} +117 -3
  22. package/dist/{machineSchemas-6d96bef4.development.cjs.js → legacySnapshot-ebf0b2b8.development.cjs.js} +118 -2
  23. package/dist/xstate-actors.cjs.js +1 -1
  24. package/dist/xstate-actors.development.cjs.js +1 -1
  25. package/dist/xstate-actors.development.esm.js +2 -2
  26. package/dist/xstate-actors.esm.js +2 -2
  27. package/dist/xstate-actors.umd.min.js +1 -1
  28. package/dist/xstate-actors.umd.min.js.map +1 -1
  29. package/dist/xstate-durable.cjs.js +120 -10
  30. package/dist/xstate-durable.development.cjs.js +120 -10
  31. package/dist/xstate-durable.development.esm.js +120 -10
  32. package/dist/xstate-durable.esm.js +120 -10
  33. package/dist/xstate-durable.umd.min.js +1 -1
  34. package/dist/xstate-durable.umd.min.js.map +1 -1
  35. package/dist/xstate-fsm.cjs.js +4 -4
  36. package/dist/xstate-fsm.development.cjs.js +4 -4
  37. package/dist/xstate-fsm.development.esm.js +4 -4
  38. package/dist/xstate-fsm.esm.js +4 -4
  39. package/dist/xstate-fsm.umd.min.js +1 -1
  40. package/dist/xstate-fsm.umd.min.js.map +1 -1
  41. package/dist/xstate-graph.cjs.js +1 -1
  42. package/dist/xstate-graph.development.cjs.js +1 -1
  43. package/dist/xstate-graph.development.esm.js +2 -2
  44. package/dist/xstate-graph.esm.js +2 -2
  45. package/dist/xstate-graph.umd.min.js +1 -1
  46. package/dist/xstate-graph.umd.min.js.map +1 -1
  47. package/dist/xstate-persist.cjs.js +23 -12
  48. package/dist/xstate-persist.development.cjs.js +23 -12
  49. package/dist/xstate-persist.development.esm.js +17 -6
  50. package/dist/xstate-persist.esm.js +17 -6
  51. package/dist/xstate-persist.umd.min.js +1 -1
  52. package/dist/xstate-persist.umd.min.js.map +1 -1
  53. package/dist/xstate-validation.cjs.js +1 -1
  54. package/dist/xstate-validation.development.cjs.js +1 -1
  55. package/dist/xstate-validation.development.esm.js +1 -1
  56. package/dist/xstate-validation.esm.js +1 -1
  57. package/dist/xstate.cjs.js +63 -51
  58. package/dist/xstate.development.cjs.js +63 -51
  59. package/dist/xstate.development.esm.js +53 -41
  60. package/dist/xstate.esm.js +53 -41
  61. package/dist/xstate.umd.min.js +1 -1
  62. package/dist/xstate.umd.min.js.map +1 -1
  63. package/docs/agents.md +9 -0
  64. package/docs/api-stability.json +273 -249
  65. package/docs/backend-workflows.md +3 -3
  66. package/docs/durable-execution.md +72 -48
  67. package/docs/errors.md +2 -2
  68. package/docs/examples.md +34 -34
  69. package/docs/fsm.md +2 -1
  70. package/docs/guards.md +1 -1
  71. package/docs/index.md +1 -1
  72. package/docs/invoke.md +34 -2
  73. package/docs/persistence.md +16 -10
  74. package/docs/serialization.md +1 -1
  75. package/docs/setup-and-provide.md +3 -3
  76. package/docs/spawn.md +1 -1
  77. package/docs/system-transitions.md +6 -6
  78. package/docs/tutorial.md +5 -5
  79. package/docs/typescript.md +9 -0
  80. package/docs/xstate-v5-to-v6.md +176 -19
  81. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"xstate-graph.umd.min.js","sources":["../src/xstateError.ts","../src/devDiagnostics.ts","../src/constants.ts","../src/remoteActorRef.ts","../src/runtimeHelpers.ts","../src/Mailbox.ts","../src/eventUtils.ts","../src/reportUnhandledError.ts","../src/symbolObservable.ts","../src/transitionSelection.ts","../src/timerKey.ts","../src/transitionActions.ts","../src/actions.ts","../src/snapshotActorRef.ts","../src/State.ts","../src/utils.ts","../src/system.ts","../src/createActor.ts","../src/validation.ts","../src/actors/logic.ts","../src/actors/index.ts","../src/graph/actorScope.ts","../src/graph/graph.ts","../src/graph/traversalError.ts","../src/graph/adjacency.ts","../src/graph/alterPath.ts","../src/graph/pathFromEvents.ts","../src/graph/shortestPaths.ts","../src/graph/simplePaths.ts"],"sourcesContent":["/**\n * Builds the production message for an XState error: the stable code, the\n * dynamic values, and a link to its entry in docs/errors.md. Development\n * builds use the full message instead, so call sites read `isDevelopment ?\n * fullMessage : xstateError(code, ...values)` and the full text tree-shakes\n * out of production bundles.\n */\nexport function xstateError(code: number, ...values: unknown[]): string {\n return `XState error E${code}${\n values.length\n ? ` (${values\n .map((value) =>\n typeof value === 'string' ? JSON.stringify(value) : String(value)\n )\n .join(', ')})`\n : ''\n }. See https://github.com/statelyai/xstate/blob/next/docs/errors.md#e${code}`;\n}\n","import isDevelopment from '#is-development';\nimport { xstateError } from './xstateError.ts';\n\n/**\n * Checks for leftover v5 configuration on hand-written machine configs, setup\n * configs and actor options. Keys that v6 would silently ignore throw in every\n * build; harmless leftovers only warn in development. Production builds throw\n * coded messages (see docs/errors.md), so the message tables below are\n * referenced from development branches only.\n */\n\nconst INLINE_TRANSITION =\n 'Use an inline transition function instead: return { target } when the condition passes, or undefined to reject the event (before any enq call, which would select the transition). Named guards are available as `guards.name(...)` in its arguments.';\n\nconst INLINE_ACTION =\n 'Use a single inline function `(args, enq) => { ... }`; call named actions with `enq(actions.name, params)`.';\n\n// Keys that v6 would ignore or misread; each throws E1 in production.\nconst REMOVED_ROOT_KEY_NAMES = [\n 'types',\n 'tsTypes',\n 'schema',\n 'internalEvents',\n 'services',\n 'devTools'\n];\n\nconst REMOVED_ROOT_KEYS: Record<string, string> = {\n types:\n '\"types\" was replaced by \"schemas\". Declare contracts under `schemas` (or `setup({ schemas })`), or use `types<T>()` inside `schemas` for type-only contracts.',\n tsTypes:\n '\"tsTypes\" (typegen) was removed. Declare contracts under `schemas` (or `setup({ schemas })`).',\n schema:\n '\"schema\" was replaced by \"schemas\". Declare contracts under `schemas` (or `setup({ schemas })`).',\n internalEvents:\n 'The top-level \"internalEvents\" list was removed. Declare private events under `schemas.internalEvents` instead, e.g. `schemas: { internalEvents: { tick: types<{}>() } }`.',\n services:\n '\"services\" was renamed. Provide actor logic under \"actors\" (or `setup({ actors })`).',\n devTools:\n '\"devTools\" was removed. Pass the \"inspect\" option to `createActor(...)` instead.'\n};\n\nconst SETUP_INTERNAL_EVENTS =\n 'setup() has no \"internalEvents\" option. Declare private events under `schemas.internalEvents` instead, e.g. `setup({ schemas: { internalEvents: { tick: types<{}>() } } })`.';\n\nconst ACTIVITIES =\n 'uses \"activities\", which was removed. Invoke an actor with \"invoke\" instead.';\n\n// Leftovers that change nothing in v6; reported in development only.\nconst HARMLESS_ROOT_KEYS: Record<string, string> = {\n predictableActionArguments:\n 'was removed with no replacement; v6 always runs effects in order.',\n preserveActionOrder:\n 'was removed with no replacement; v6 always runs effects in order.',\n strict: 'was removed with no replacement.'\n};\n\nconst TRANSITION_KEYS = ['onDone', 'onError', 'onTimeout', 'always'] as const;\nconst INVOKE_TRANSITION_KEYS = [\n 'onDone',\n 'onError',\n 'onSnapshot',\n 'onTimeout'\n] as const;\n\nconst SUFFIXED_LIFECYCLE =\n /^xstate\\.(done\\.actor|error\\.actor|snapshot|done\\.state|after)\\.(.+)$/;\n\nfunction checkLifecycleEventKey(eventType: string, stateId: string): void {\n const match = SUFFIXED_LIFECYCLE.exec(eventType);\n // `xstate.done.actor.*` is a wildcard over the category type and still matches.\n // `xstate.snapshot.actor` is the v6 category type itself, and\n // `xstate.snapshot.actor.*` is a wildcard over it.\n if (\n !match ||\n match[2] === '*' ||\n (match[1] === 'snapshot' &&\n (match[2] === 'actor' || match[2] === 'actor.*'))\n )\n return;\n if (!isDevelopment) {\n throw new Error(xstateError(3, eventType, stateId));\n }\n const [, category, suffix] = match;\n const where = `Transition \"${eventType}\" in ${describeState(stateId)}`;\n const replacement =\n category === 'after'\n ? `Use \\`after: { <delay>: ... }\\` on the state, or key on 'xstate.after' and select \\`matches: { stateId, delay }\\``\n : category === 'done.state'\n ? `Use \"onDone\" on the state, or key on 'xstate.done.state' with \\`matches: { stateId: '${suffix}' }\\``\n : `Key on '${category === 'snapshot' ? 'xstate.snapshot.actor' : `xstate.${category}`}' with \\`matches: { actorId: '${suffix}' }\\`, or use the invoke's ${category === 'done.actor' ? '\"onDone\"' : category === 'error.actor' ? '\"onError\"' : '\"onSnapshot\"'}`;\n throw new Error(\n `${where} never fires: v6 lifecycle event types carry the id in a payload field instead of the type. ${replacement}.`\n );\n}\n\nfunction checkTransitions(\n transitions: unknown,\n name: string,\n stateId: string\n): void {\n if (!transitions) return;\n for (const t of Array.isArray(transitions) ? transitions : [transitions]) {\n if (!t || typeof t !== 'object') continue;\n if ((t as any).cond !== undefined) {\n throw new Error(\n isDevelopment\n ? `Transition \"${name}\" in ${describeState(stateId)} uses \"cond\", which was removed. ${INLINE_TRANSITION}`\n : xstateError(4, name, stateId, 'cond')\n );\n }\n if ((t as any).guard !== undefined) {\n throw new Error(\n isDevelopment\n ? `Transition \"${name}\" in ${describeState(stateId)} uses an object-form \"guard\", which was removed. ${INLINE_TRANSITION}`\n : xstateError(4, name, stateId, 'guard')\n );\n }\n if ((t as any).actions !== undefined) {\n throw new Error(\n isDevelopment\n ? `Transition \"${name}\" in ${describeState(stateId)} uses \"actions\", which was removed. Use an inline transition function \\`(args, enq) => { ... }\\` and queue effects on \"enq\"; call named actions with \\`enq(actions.name, params)\\`.`\n : xstateError(4, name, stateId, 'actions')\n );\n }\n }\n}\n\n// The root of a machine without an id has the empty id.\nfunction describeState(stateId: string): string {\n return stateId ? `state \"${stateId}\"` : 'the root state';\n}\n\nfunction describeShape(value: unknown): string {\n return Array.isArray(value)\n ? 'an array'\n : typeof value === 'string'\n ? `a string (\"${value}\")`\n : `a ${typeof value}`;\n}\n\nfunction capitalize(text: string): string {\n return text.charAt(0).toUpperCase() + text.slice(1);\n}\n\nconst UNGUARDED_INITIAL =\n 'Initial transitions cannot be guarded; use an \"always\" transition on the target state to redirect conditionally.';\n\nfunction checkInitialTransition(initial: any, stateId: string): void {\n if (!initial || typeof initial !== 'object') return;\n if (initial.cond !== undefined) {\n throw new Error(\n isDevelopment\n ? `Initial transition of ${describeState(stateId)} uses \"cond\", which was removed. ${UNGUARDED_INITIAL}`\n : xstateError(5, stateId, 'cond')\n );\n }\n if (initial.guard !== undefined) {\n throw new Error(\n isDevelopment\n ? `Initial transition of ${describeState(stateId)} uses an object-form \"guard\", which was removed. ${UNGUARDED_INITIAL}`\n : xstateError(5, stateId, 'guard')\n );\n }\n if (initial.actions !== undefined) {\n throw new Error(\n isDevelopment\n ? `Initial transition of ${describeState(stateId)} uses \"actions\", which was removed. Use a \\`to: (args, enq) => { ... }\\` function on the initial transition and queue effects on \"enq\", or an \"entry\" function on the target state.`\n : xstateError(5, stateId, 'actions')\n );\n }\n}\n\nfunction checkStateNode(node: any, stateId: string): void {\n checkInitialTransition(node.initial, stateId);\n if (node.activities !== undefined) {\n throw new Error(\n isDevelopment\n ? `${capitalize(describeState(stateId))} ${ACTIVITIES}`\n : xstateError(6, stateId)\n );\n }\n for (const key of ['entry', 'exit'] as const) {\n const action = node[key];\n if (action !== undefined && typeof action !== 'function') {\n throw new Error(\n isDevelopment\n ? `${capitalize(describeState(stateId))} has ${describeShape(action)} as \"${key}\", which is not supported. ${INLINE_ACTION}`\n : xstateError(7, stateId, key)\n );\n }\n }\n if (node.on) {\n for (const eventType of Object.keys(node.on)) {\n checkLifecycleEventKey(eventType, stateId);\n checkTransitions(node.on[eventType], eventType, stateId);\n }\n }\n if (node.after) {\n for (const delay of Object.keys(node.after)) {\n checkTransitions(node.after[delay], `after.${delay}`, stateId);\n }\n }\n for (const key of TRANSITION_KEYS) {\n checkTransitions(node[key], key, stateId);\n }\n if (node.invoke) {\n for (const invoke of Array.isArray(node.invoke)\n ? node.invoke\n : [node.invoke]) {\n if (!invoke || typeof invoke !== 'object') continue;\n for (const key of INVOKE_TRANSITION_KEYS) {\n checkTransitions(invoke[key], `invoke.${key}`, stateId);\n }\n }\n }\n if (node.states) {\n for (const key of Object.keys(node.states)) {\n const child = node.states[key];\n if (child && typeof child === 'object') {\n checkStateNode(\n child,\n child.id ?? (stateId ? `${stateId}.${key}` : key)\n );\n }\n }\n }\n}\n\n/**\n * Throws (or warns, for harmless leftovers) when a hand-written machine config\n * contains v5 keys that v6 would otherwise ignore or misread.\n */\nexport function diagnoseAuthorConfig(config: any): void {\n if (!config || typeof config !== 'object') return;\n for (const key of REMOVED_ROOT_KEY_NAMES) {\n if (config[key] !== undefined) {\n throw new Error(\n isDevelopment ? REMOVED_ROOT_KEYS[key] : xstateError(1, key)\n );\n }\n }\n if (isDevelopment) {\n for (const key of Object.keys(HARMLESS_ROOT_KEYS)) {\n if (config[key] !== undefined) {\n console.warn(`Machine config \"${key}\" ${HARMLESS_ROOT_KEYS[key]}`);\n }\n }\n }\n checkStateNode(config, config.id ?? '');\n}\n\n/**\n * Throws when a `setup(...)` config contains a key that belongs elsewhere and\n * would otherwise be ignored.\n */\nexport function diagnoseSetupConfig(config: any): void {\n if (!config || typeof config !== 'object') return;\n if (config.internalEvents !== undefined) {\n throw new Error(isDevelopment ? SETUP_INTERNAL_EVENTS : xstateError(2));\n }\n}\n\nconst REMOVED_ACTOR_OPTIONS: Record<string, string> = {\n parent:\n 'The \"parent\" actor option was removed. Create child actors through invoke, spawn, or enq.spawn instead.',\n systemId:\n 'The \"systemId\" actor option was renamed. Use \"registryKey\": createActor(logic, { registryKey }), and look the actor up with system.get(registryKey).',\n state:\n 'The \"state\" actor option was removed. Restore persisted snapshots with restoreActor(logic, snapshot) from \"xstate/persist\".',\n snapshot:\n 'The \"snapshot\" actor option was removed. Restore persisted snapshots with restoreActor(logic, snapshot) from \"xstate/persist\".',\n devTools:\n 'The \"devTools\" actor option was removed. Pass the \"inspect\" option instead: createActor(logic, { inspect }).',\n deferEvents:\n 'The \"deferEvents\" actor option was removed. Events sent before start() are always queued until the actor starts.',\n execute:\n 'The \"execute\" actor option was removed. Effects always run when the actor processes an event; use transition() for pure, effect-free steps.'\n};\n\nconst ACTOR_OPTIONS = new Set([\n 'clock',\n 'logger',\n 'syncSnapshot',\n 'id',\n 'registryKey',\n 'input',\n 'src',\n 'inspect',\n 'onRejectedEvent',\n 'onUnhandledEvent',\n '_systemRef',\n '_sessionId',\n '_inert',\n '_restore'\n]);\n\n/**\n * Throws when `createActor(...)` options contain a key that v6 does not read,\n * so a misspelled or v5-era option fails instead of being ignored.\n */\nexport function diagnoseActorOptions(options: any): void {\n if (!options || typeof options !== 'object') return;\n for (const key of Object.keys(options)) {\n if (ACTOR_OPTIONS.has(key)) continue;\n throw new Error(\n isDevelopment\n ? (REMOVED_ACTOR_OPTIONS[key] ??\n `Unknown actor option \"${key}\". Supported options: ${[\n ...ACTOR_OPTIONS\n ]\n .filter((name) => !name.startsWith('_'))\n .join(', ')}.`)\n : xstateError(8, key)\n );\n }\n}\n","export const STATE_DELIMITER = '.';\nexport const TARGETLESS_KEY = '';\nexport const NULL_EVENT = '';\nexport const STATE_IDENTIFIER = '#';\nexport const WILDCARD = '*';\nexport const XSTATE_INIT = 'xstate.init';\nexport const XSTATE_START = '@xstate.start';\nexport const XSTATE_SPAWN = '@xstate.spawn';\n/** The event an actor receives when it is stopped. */\nexport const XSTATE_STOP = 'xstate.stop';\n/** The effect that stops a child actor. */\nexport const XSTATE_STOP_EFFECT = '@xstate.stop';\nexport const XSTATE_TERMINATE = '@xstate.terminate';\nexport const XSTATE_TIMER = 'xstate.timer';\n\nexport const XSTATE_LOGIC_EFFECT_RESOLVE = 'xstate.logic.effect.resolve';\nexport const XSTATE_LOGIC_EFFECT_REJECT = 'xstate.logic.effect.reject';\nexport const XSTATE_LOGIC_EFFECT_START = 'xstate.logic.effect.start';\n","import isDevelopment from '#is-development';\nimport { xstateError } from './xstateError.ts';\nimport type { AnyActorSystem } from './system.ts';\nimport type {\n AnyActor,\n AnyEventObject,\n SerializedActorRef,\n Snapshot,\n Subscription\n} from './types.ts';\n\nconst emptySubscription: Subscription = { unsubscribe() {} };\n\nconst restoreHint =\n 'or restore this snapshot with embedded children on the runtime that owns them.';\n\n/** @internal */\nexport function isRemoteActorRef(actorRef: AnyActor): boolean {\n return (actorRef as { _remote?: boolean })._remote === true;\n}\n\n/**\n * @internal Whether a send target is an actor reference that went through\n * JSON (`actor.toJSON()`): plain data carrying an address, not an actor.\n */\nexport function isSerializedActorRef(\n target: unknown\n): target is SerializedActorRef {\n if (\n typeof target !== 'object' ||\n target === null ||\n Array.isArray(target) ||\n typeof (target as SerializedActorRef).$actor !== 'string'\n ) {\n return false;\n }\n for (const key in target) {\n if (key !== '$actor' && key !== 'incarnation') {\n return false;\n }\n }\n const incarnation = (target as SerializedActorRef).incarnation;\n return incarnation === undefined || typeof incarnation === 'string';\n}\n\n/** @internal The actor id that the last segment of an address encodes. */\nexport function getAddressId(address: string): string {\n const segment = address.slice(address.lastIndexOf('/') + 1);\n return segment.includes('%')\n ? segment.replaceAll('%2F', '/').replaceAll('%25', '%')\n : segment;\n}\n\n/** @internal The error reported when no live actor has a serialized address. */\nexport function createMissingAddressError(target: SerializedActorRef): Error {\n return new Error(\n !isDevelopment\n ? xstateError(\n 50,\n ...(target.incarnation === undefined\n ? [target.$actor]\n : [target.$actor, target.incarnation])\n )\n : target.incarnation === undefined\n ? `Unable to send event to actor '${target.$actor}': no live actor has that address`\n : `Unable to send event to actor '${target.$actor}' (incarnation '${target.incarnation}'): no live actor has that address and incarnation`\n );\n}\n\n/**\n * @internal The live actor a serialized ref names: the actor at its address,\n * and, when the ref carries an `incarnation`, only that incarnation. A ref\n * without one follows whichever actor is live at the address.\n */\nexport function resolveSerializedActorRef(\n system: { _getByAddress?: (address: string) => AnyActor | undefined },\n target: SerializedActorRef\n): AnyActor | undefined {\n const live = system._getByAddress?.(target.$actor);\n return live &&\n (target.incarnation === undefined || live.sessionId === target.incarnation)\n ? live\n : undefined;\n}\n\n/**\n * The lifecycle-only snapshot a remote handle exposes. `active` is accurate\n * by construction: a completion removes the child from its parent's\n * `children`, so a handle only exists while the child is presumed active,\n * and the terminal result arrives as a completion event instead of a\n * snapshot. Full snapshots are a co-location capability.\n */\nconst remoteSnapshot: Snapshot<undefined> = Object.freeze({\n status: 'active' as const,\n output: undefined,\n error: undefined\n});\n\n/**\n * Creates the inert ref `enq.spawn(...)` returns while a transition is only\n * evaluated (for example by `snapshot.can(...)`, or to resolve conflicting\n * transitions) and no actor is created. It carries the identity the spawn\n * would get, accepts and drops events, exposes the same lifecycle-only\n * snapshot as a remote handle, and serializes like any actor ref. Its address\n * is unknown when the evaluating scope is detached from the parent actor.\n *\n * @internal\n */\nexport function createInertActorRef(options: {\n id: string;\n address: string | undefined;\n src: string | undefined;\n}): AnyActor {\n const { id, address } = options;\n const handle = {\n ref: undefined as unknown as AnyActor,\n id,\n address,\n src: options.src,\n sessionId: undefined,\n send() {},\n getSnapshot(): Snapshot<undefined> {\n return remoteSnapshot;\n },\n subscribe(): Subscription {\n return emptySubscription;\n },\n on(): Subscription {\n return emptySubscription;\n },\n toJSON(): SerializedActorRef {\n if (address === undefined) {\n throw new Error(\n isDevelopment\n ? `Cannot serialize actor ref '${id}': it was returned by a spawn during speculative transition evaluation, which creates no actor and has no parent address.`\n : xstateError(51, id)\n );\n }\n return { $actor: address };\n }\n };\n const ref = handle as unknown as AnyActor;\n handle.ref = ref;\n return ref;\n}\n\n/**\n * Creates a location-transparent handle to an actor whose state lives with\n * another runtime. The handle is constructed from identity alone — no lookup\n * — and every send routes through the system's runtime; its state is not\n * synchronously readable.\n *\n * The surface is deliberately minimal: it covers every member the runtime\n * reaches for a restored child (send/_send, lifecycle via start/_stop and\n * system.stopActor, persistence, subscribe/on as inert subscriptions).\n * Members that only make sense for a co-located actor (public stop(),\n * select(), trigger) throw a descriptive error rather than being absent, so\n * calling one reports what went wrong instead of a bare TypeError. Observable\n * interop and _processingStatus are omitted entirely.\n *\n * @internal\n */\nexport function createRemoteActorRef(\n system: AnyActorSystem,\n options: {\n id: string;\n address: string;\n src: string;\n parent: AnyActor | undefined;\n registryKey?: string;\n syncSnapshot?: boolean;\n incarnation?: string;\n }\n): AnyActor {\n const handle = {\n _remote: true as const,\n // Self-reference so context persistence recognizes the handle as an\n // actor reference instead of recursing into it.\n ref: undefined as unknown as AnyActor,\n id: options.id,\n address: options.address,\n src: options.src,\n registryKey: options.registryKey,\n // The host-supplied incarnation token, when present: the owner's\n // sessionId for this child, letting this side drop stale completions and\n // journaled sends name the intended incarnation. Without one the handle\n // does not know the child's incarnation and the owning runtime is the\n // authority on staleness.\n sessionId: options.incarnation as string,\n system,\n _parent: options.parent,\n // Round-trips through persistence verbatim (undefined stays undefined,\n // so re-persisting is byte-stable); a remote handle cannot act on it\n // locally.\n _syncSnapshot: options.syncSnapshot,\n send(event: AnyEventObject) {\n void system.sendEvent(undefined, ref, event);\n },\n _send(event: AnyEventObject) {\n throw new Error(\n isDevelopment\n ? `Remote actor '${options.address}' has no local mailbox to receive \"${event.type}\". Its state lives with another runtime; install a runtime that can reach it (via \\`createDurable\\`'s adapter runtime operations, or \\`system.runtime\\`) before sending, ${restoreHint}`\n : xstateError(52, options.address, event.type)\n );\n },\n getSnapshot(): Snapshot<undefined> {\n return remoteSnapshot;\n },\n getPersistedSnapshot(): never {\n throw new Error(\n isDevelopment\n ? `Cannot persist remote actor '${options.address}' from here: its state lives with the runtime that owns it. Persist it there, ${restoreHint}`\n : xstateError(53, options.address)\n );\n },\n start() {},\n _stop() {},\n stop() {\n throw new Error(\n isDevelopment\n ? `Cannot stop remote actor '${options.address}' directly: stopping is a co-located operation. Stop it through the system runtime that owns it (\\`system.stopActor(ref)\\`), ${restoreHint}`\n : xstateError(54, options.address)\n );\n },\n select() {\n throw new Error(\n isDevelopment\n ? `Cannot select from remote actor '${options.address}': its snapshot is not synchronously readable because its state lives with another runtime. Read it on the runtime that owns it, ${restoreHint}`\n : xstateError(55, options.address)\n );\n },\n get trigger(): never {\n throw new Error(\n isDevelopment\n ? `Remote actor '${options.address}' has no \\`trigger\\` shorthand: it requires a co-located actor. Use \\`send(...)\\`, which routes through the system runtime.`\n : xstateError(56, options.address)\n );\n },\n // Observation is a co-location capability: a remote handle never emits,\n // so subscriptions are inert rather than errors — generic observers may\n // attach to any ref.\n subscribe(): Subscription {\n return emptySubscription;\n },\n on(): Subscription {\n return emptySubscription;\n },\n _isRunning() {\n return false;\n },\n // The same shape Actor.toJSON produces, so serialized snapshots carry\n // one actor-reference shape whether a child is co-located or remote.\n toJSON(): SerializedActorRef {\n return { $actor: options.address };\n }\n };\n const ref = handle as unknown as AnyActor;\n handle.ref = ref;\n return ref;\n}\n","import isDevelopment from '#is-development';\nimport { xstateError } from './xstateError.ts';\nimport {\n XSTATE_LOGIC_EFFECT_REJECT,\n XSTATE_LOGIC_EFFECT_RESOLVE,\n XSTATE_LOGIC_EFFECT_START\n} from './constants.ts';\nimport {\n createMissingAddressError,\n getAddressId,\n isSerializedActorRef,\n resolveSerializedActorRef\n} from './remoteActorRef.ts';\nimport type { ActorSystemRuntime } from './system.ts';\nimport type {\n EventObject,\n ActorTermination,\n AnyActor,\n AnyEventObject,\n Subscription\n} from './types.ts';\n\n/** @internal */\nexport function publishEmittedEvent(\n source: AnyActor,\n event: EventObject,\n runtime: Partial<ActorSystemRuntime>\n): void | PromiseLike<void> {\n source.system._notifyEmitted(source, event);\n return runtime.emitEvent!(source, event);\n}\n\ntype StepEffects = Record<\n string,\n | { status: 'active' }\n | { status: 'done'; output: unknown }\n | { status: 'error'; error: unknown }\n>;\n\nfunction getStepEffect(actor: AnyActor, key: string) {\n const effects = (actor.getSnapshot() as { effects?: StepEffects }).effects;\n return effects && Object.prototype.hasOwnProperty.call(effects, key)\n ? effects[key]\n : undefined;\n}\n\n// Live promises belong to an actor incarnation, unlike its persisted journal.\n// A restored active record has no promise here and must be retried locally.\nconst pendingSteps = new WeakMap<AnyActor, Map<string, Promise<unknown>>>();\n\n/**\n * Runs one keyed step of an async actor with the built-in journal: the\n * result is memoized in the actor's own snapshot (`effects[key]`), so a\n * restored actor skips completed steps when its logic function re-runs.\n * Custom runtimes that implement `runStep` use this for the default local\n * behavior, the same way `deliverEvent` exposes local delivery.\n *\n * @experimental\n */\nexport async function runStep<TStepOutput>(\n actor: AnyActor,\n key: string,\n exec: () => TStepOutput | PromiseLike<TStepOutput>,\n sendSelf: (event: AnyEventObject) => void = (event) =>\n void actor.system.sendEvent(actor, actor, event)\n): Promise<TStepOutput> {\n const effect = getStepEffect(actor, key);\n if (effect?.status === 'done') {\n return effect.output as TStepOutput;\n }\n if (effect?.status === 'error') {\n throw effect.error;\n }\n const running = pendingSteps.get(actor)?.get(key);\n if (running) {\n return running as Promise<TStepOutput>;\n }\n if (actor.getSnapshot().status !== 'active') {\n throw new Error(\n isDevelopment\n ? `Actor terminated before step \"${key}\" completed`\n : xstateError(72, key)\n );\n }\n\n let resolve!: (value: TStepOutput | PromiseLike<TStepOutput>) => void;\n let reject!: (reason: unknown) => void;\n const promise = new Promise<TStepOutput>((resolvePromise, rejectPromise) => {\n resolve = resolvePromise;\n reject = rejectPromise;\n });\n let steps = pendingSteps.get(actor);\n if (!steps) {\n steps = new Map();\n pendingSteps.set(actor, steps);\n }\n steps.set(key, promise);\n // oxlint-disable-next-line prefer-const\n let subscription: Subscription | undefined;\n const cleanup = () => {\n subscription?.unsubscribe();\n steps.delete(key);\n if (!steps.size) {\n pendingSteps.delete(actor);\n }\n };\n void promise.then(cleanup, cleanup);\n subscription = actor.subscribe({\n error: reject,\n complete: () =>\n reject(\n new Error(\n isDevelopment\n ? `Actor terminated before step \"${key}\" completed`\n : xstateError(72, key)\n )\n )\n });\n void (async () => {\n try {\n sendSelf({ type: XSTATE_LOGIC_EFFECT_START, key });\n const output = await exec();\n if (actor.getSnapshot().status === 'active') {\n sendSelf({ type: XSTATE_LOGIC_EFFECT_RESOLVE, key, output });\n resolve(output);\n }\n } catch (error) {\n if (actor.getSnapshot().status === 'active') {\n sendSelf({ type: XSTATE_LOGIC_EFFECT_REJECT, key, error });\n }\n reject(error);\n }\n })().catch(reject);\n return promise;\n}\n\n/**\n * Delivers an event directly to a target actor, bypassing any installed host\n * runtime. Custom runtimes use this for the default local delivery behavior\n * inside their own `sendEvent` implementations.\n *\n * @experimental\n */\nexport function deliverEvent(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n): void {\n if (isSerializedActorRef(target)) {\n const serialized = target;\n const system = source?.system;\n const live = system && resolveSerializedActorRef(system, serialized);\n if (!live) {\n const error = createMissingAddressError(serialized);\n if (!system) {\n throw error;\n }\n void system.deadLetter(source, undefined, event, 'missingTarget', {\n targetId: getAddressId(serialized.$actor),\n error\n });\n return;\n }\n target = live;\n }\n if (rejectUndeliverableEvent(source, target, event)) {\n return;\n }\n const runtimeTarget = target as AnyActor & {\n _send(event: AnyEventObject, sourceRef?: AnyActor): void;\n };\n\n runtimeTarget._send(event, source);\n}\n\n/**\n * Returns the boundary error preventing this delivery, if any: an internal\n * event type cannot cross an actor boundary from an external sender.\n */\nfunction getEventBoundaryError(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n): Error | undefined {\n const runtimeTarget = target as AnyActor & {\n logic?: { isInternalEventType?: (eventType: string) => boolean };\n };\n\n if (\n source !== target &&\n runtimeTarget.logic?.isInternalEventType?.(event.type)\n ) {\n return new Error(\n isDevelopment\n ? `Internal event \"${event.type}\" cannot be sent to actor \"${target.id}\" from outside.`\n : xstateError(73, event.type, target.id)\n );\n }\n return undefined;\n}\n\n/**\n * Rejects an event that must not cross the delivery boundary — an internal\n * event type sent from outside its owning actor — by reporting it as a dead\n * letter. Returns `true` when the event was rejected and must not be\n * delivered. Host runtimes must call this before taking ownership of\n * delivery.\n */\nexport function rejectUndeliverableEvent(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n): boolean {\n const error = getEventBoundaryError(source, target, event);\n if (error) {\n void target.system.deadLetter(source, target, event, 'internalEvent', {\n error\n });\n return true;\n }\n return false;\n}\n\n/**\n * Publishes an actor's terminal result, notifying its parent and observers.\n * Custom runtimes use this for the default local behavior inside their own\n * `terminateActor` implementations.\n *\n * @experimental\n */\nexport function terminateActor(\n actor: AnyActor,\n termination: ActorTermination\n): void {\n (\n actor as AnyActor & { _terminate(termination: ActorTermination): void }\n )._terminate(termination);\n}\n\n/**\n * Stops an actor without producing a completion result. Custom runtimes use\n * this for the default local behavior inside their own `stopActor`\n * implementations.\n *\n * @experimental\n */\nexport function stopActor(actor: AnyActor): void {\n (actor as AnyActor & { _stop(): void })._stop();\n}\n","interface MailboxItem<T> {\n value: T;\n next: MailboxItem<T> | null;\n}\n\nexport class Mailbox<T> {\n private _active: boolean = false;\n private _current: MailboxItem<T> | null = null;\n private _last: MailboxItem<T> | null = null;\n\n constructor(private _process: (ev: T) => void) {}\n\n public start() {\n this._active = true;\n this.flush();\n }\n\n public clear(): void {\n // we can't set _current to null because we might be currently processing\n // and enqueue following clear shouldn't start processing the enqueued item immediately\n if (this._current) {\n this._current.next = null;\n this._last = this._current;\n }\n }\n\n public enqueue(event: T): void {\n const enqueued = {\n value: event,\n next: null\n };\n\n if (this._current) {\n this._last!.next = enqueued;\n this._last = enqueued;\n return;\n }\n\n this._current = enqueued;\n this._last = enqueued;\n\n if (this._active) {\n this.flush();\n }\n }\n\n private flush() {\n while (this._current) {\n // atm the given _process is responsible for implementing proper try/catch handling\n // we assume here that this won't throw in a way that can affect this mailbox\n const consumed = this._current;\n this._process(consumed.value);\n this._current = consumed.next;\n }\n this._last = null;\n }\n}\n","import { XSTATE_INIT } from './constants.ts';\nimport {\n ActorTimeoutEvent,\n AfterEvent,\n DoneActorEvent,\n DoneStateEvent,\n ErrorActorEvent,\n ErrorPlatformEvent,\n TimeoutEvent\n} from './types.ts';\n\n/**\n * Returns an event that represents an implicit event that is sent after the\n * specified `delay`.\n *\n * @param delayRef The delay in milliseconds\n * @param id The state node ID where this event is handled\n */\nexport function createAfterEvent(\n delayRef: number | string,\n id: string\n): AfterEvent {\n return { type: 'xstate.after', delay: delayRef, stateId: id };\n}\n\n/**\n * Returns an event that represents an implicit state-level timeout. Fired when\n * a state's `timeout` duration elapses without the state being exited.\n *\n * @param id The state node ID where this timeout is configured\n */\nexport function createTimeoutEvent(id: string): TimeoutEvent {\n return { type: 'xstate.timeout.state', stateId: id };\n}\n\n/**\n * Returns an event that represents an implicit invoke-level timeout. Fired when\n * an invoked actor has not completed within its `timeout` duration.\n *\n * @param invokeId The invoked actor's ID\n */\nexport function createInvokeTimeoutEvent(\n invokeId: string,\n sessionId?: string\n): ActorTimeoutEvent {\n return {\n type: 'xstate.timeout.actor',\n actorId: invokeId,\n sessionId\n };\n}\n\n/**\n * Returns an event that represents that a final state node has been reached in\n * the parent state node.\n *\n * @param id The final state node's parent state node `id`\n * @param output The data to pass into the event\n */\nexport function createDoneStateEvent(\n id: string,\n output?: unknown\n): DoneStateEvent {\n return {\n type: 'xstate.done.state',\n stateId: id,\n output\n };\n}\n\n/**\n * Returns an event that represents that an invoked service has terminated.\n *\n * An invoked service is terminated when it has reached a top-level final state\n * node, but not when it is canceled.\n *\n * @param invokeId The invoked service ID\n * @param output The data to pass into the event\n * @param sessionId The unique session ID of the completed actor\n */\nexport function createDoneActorEvent(\n invokeId: string,\n output: unknown,\n sessionId: string\n): DoneActorEvent {\n return {\n type: 'xstate.done.actor',\n output,\n actorId: invokeId,\n sessionId\n };\n}\n\nexport function createErrorActorEvent(\n id: string,\n error: unknown,\n sessionId: string\n): ErrorActorEvent {\n return {\n type: 'xstate.error.actor',\n error,\n actorId: id,\n sessionId\n };\n}\n\nexport function createErrorPlatformEvent(\n kind: string,\n error?: unknown\n): ErrorPlatformEvent {\n return { type: `xstate.error.${kind}`, error };\n}\n\nexport function createInitEvent(input: unknown) {\n return { type: XSTATE_INIT, input } as const;\n}\n","/**\n * This function makes sure that unhandled errors are thrown in a separate\n * macrotask. It allows those errors to be detected by global error handlers and\n * reported to bug tracking services without interrupting our own stack of\n * execution.\n *\n * @param err Error to be thrown\n */\nexport function reportUnhandledError(err: unknown) {\n setTimeout(() => {\n throw err;\n });\n}\n","export const symbolObservable: typeof Symbol.observable = (() =>\n (typeof Symbol === 'function' && Symbol.observable) ||\n '@@observable')() as any;\n","import type { AnyActor } from './types.ts';\n\ntype TransitionSelectionFrame = {\n mode: 'abort' | 'suppress';\n parent: AnyActor | undefined;\n requiresReevaluation: boolean;\n};\n\nconst selectionFrames: TransitionSelectionFrame[] = [];\n\nexport const transitionEffectSignal = new Error('Transition effect');\n\nexport function protectSelectionRelay(target: AnyActor): boolean {\n let matched = false;\n let abort = false;\n for (const frame of selectionFrames) {\n if (frame.parent === target) {\n frame.requiresReevaluation = true;\n matched = true;\n abort ||= frame.mode === 'abort';\n }\n }\n if (abort) {\n throw transitionEffectSignal;\n }\n return matched;\n}\n\nexport function beginTransitionSelection(\n parent: AnyActor | undefined,\n mode: TransitionSelectionFrame['mode'] = 'abort'\n) {\n const frame: TransitionSelectionFrame = {\n mode,\n parent,\n requiresReevaluation: false\n };\n selectionFrames.push(frame);\n return {\n frame,\n close() {\n selectionFrames.pop();\n }\n };\n}\n","import type { AnyActor, EventObject, TimerKey } from './types.ts';\n\ntype TimerIdentity = { id?: string; seq?: number; event: EventObject };\n\n/**\n * @internal The identity fields of a built-in timer event (`after`, state and\n * invoke `timeout`), or `undefined` for any other event.\n */\nexport function getBuiltInTimerIdentity(\n event: EventObject\n): EventObject | undefined {\n const { stateId, delay, actorId } = event as {\n stateId?: unknown;\n delay?: unknown;\n actorId?: unknown;\n };\n switch (event.type) {\n case 'xstate.after':\n // Same field order as the event, so persisted events serialize alike.\n return { type: event.type, delay, stateId } as EventObject;\n case 'xstate.timeout.state':\n return { type: event.type, stateId } as EventObject;\n case 'xstate.timeout.actor':\n return { type: event.type, actorId } as EventObject;\n }\n return undefined;\n}\n\n/** @internal The key of a logical timer, effect or cancellation. */\nexport function getTimerKey(timer: TimerIdentity): TimerKey {\n if (timer.id !== undefined) {\n return { id: timer.id };\n }\n if (timer.seq !== undefined) {\n return { seq: timer.seq };\n }\n return { event: getBuiltInTimerIdentity(timer.event) ?? timer.event };\n}\n\n/**\n * @internal Reads the timer key carried by a firing input or cancellation\n * (`{ id }`, `{ seq }` or `{ event }` fields).\n */\nexport function readTimerKey(input: object): TimerKey | undefined {\n const value = input as { id?: unknown; seq?: unknown; event?: unknown };\n if (typeof value.id === 'string') {\n return { id: value.id };\n }\n if (typeof value.seq === 'number') {\n return { seq: value.seq };\n }\n if (\n value.event &&\n typeof value.event === 'object' &&\n typeof (value.event as EventObject).type === 'string'\n ) {\n return { event: value.event as EventObject };\n }\n return undefined;\n}\n\n/** @internal Whether a logical timer has the given key. */\nexport function matchesTimerKey(timer: TimerIdentity, key: TimerKey): boolean {\n if ('id' in key) {\n return timer.id === key.id;\n }\n if (timer.id !== undefined) {\n return false;\n }\n if ('seq' in key) {\n return timer.seq === key.seq;\n }\n if (timer.seq !== undefined) {\n return false;\n }\n const event = timer.event as unknown as Record<string, unknown>;\n const pattern = key.event as unknown as Record<string, unknown>;\n for (const field in pattern) {\n if (event[field] !== pattern[field]) {\n return false;\n }\n }\n return true;\n}\n\n/** @internal A private string form of a timer key, for in-memory maps. */\nexport function serializeTimerKey(key: TimerKey): string {\n if ('id' in key) {\n return JSON.stringify(['id', key.id]);\n }\n if ('seq' in key) {\n return JSON.stringify(['seq', key.seq]);\n }\n return JSON.stringify([\n 'event',\n getBuiltInTimerIdentity(key.event) ?? key.event\n ]);\n}\n\n/** @internal The private local-scheduler key of an actor's logical timer. */\nexport function getScheduledTimerKey(actor: AnyActor, key: TimerKey): string {\n return `${actor.sessionId}|${serializeTimerKey(key)}`;\n}\n","import isDevelopment from '#is-development';\nimport { xstateError } from './xstateError.ts';\nimport { publishEmittedEvent } from './runtimeHelpers.ts';\nimport { assertSendToEvent, builtInActions } from './actions.ts';\nimport { resolveRegisteredActorSource } from './actorSource.ts';\nimport { listenerLogic, type ListenerInput } from './actors/listener.ts';\nimport {\n subscriptionLogic,\n type SubscriptionInput,\n type SubscriptionMappers\n} from './actors/subscription.ts';\nimport { XSTATE_SPAWN, XSTATE_START, XSTATE_TERMINATE } from './constants.ts';\nimport {\n getBuiltInTimerIdentity,\n getTimerKey,\n matchesTimerKey,\n readTimerKey\n} from './timerKey.ts';\nimport { createInertActorRef } from './remoteActorRef.ts';\nimport {\n encodeAddressSegment,\n getActorIdPrefix,\n parseGeneratedActorId,\n type ActorSystemRuntime,\n type DeadLetterDetail,\n type EventRejectionReason\n} from './system.ts';\nimport type {\n ActorTermination,\n AnyAction,\n AnyActor,\n AnyActorLogic,\n AnyActorScope,\n AnyEventObject,\n AnyMachineSnapshot,\n CancelExecutableEffect,\n CustomExecutableEffect,\n EmitExecutableEffect,\n EnqueueObject,\n EventObject,\n ExecutableEffect,\n MachineContext,\n LogicalTimer,\n RaiseExecutableEffect,\n DeadLetterExecutableEffect,\n SendToExecutableEffect,\n Snapshot,\n SpecialExecutableEffect,\n SpawnExecutableEffect,\n StartExecutableEffect,\n StopExecutableEffect,\n TerminateExecutableEffect,\n TimerKey\n} from './types.ts';\n\ntype TransitionActionRecord = {\n action: (...args: any[]) => any;\n args: any[];\n childUpdate?:\n | {\n type: 'add';\n actor: AnyActor;\n id: string;\n counters?: Record<string, number>;\n }\n | { type: 'remove'; actor: AnyActor };\n};\n\ntype EffectRuntime = Partial<ActorSystemRuntime>;\n\nfunction execCustomEffect(\n this: CustomExecutableEffect\n): void | PromiseLike<void> | undefined {\n const result = this.action?.(...this.args);\n if (isDevelopment) {\n warnOnIgnoredEffectResult(this, result);\n }\n return result;\n}\n\nconst warnedEffectResults = new WeakSet<object>();\n\n/**\n * A function passed to `enq(...)` runs as an effect after the transition is\n * computed, so a `{ context }` or `{ children }` it returns is never applied.\n * Development builds say so, once per function.\n */\nfunction warnOnIgnoredEffectResult(\n effect: CustomExecutableEffect,\n result: unknown\n): void {\n if (\n !effect.action ||\n result === null ||\n typeof result !== 'object' ||\n warnedEffectResults.has(effect.action)\n ) {\n return;\n }\n const prototype = Object.getPrototypeOf(result);\n if (prototype !== Object.prototype && prototype !== null) {\n return;\n }\n const keys = ['context', 'children'].filter((key) => key in result);\n if (!keys.length) {\n return;\n }\n warnedEffectResults.add(effect.action);\n console.warn(\n `Action \"${effect.type || '(anonymous)'}\" returned { ${keys.join(', ')} }, which is ignored: functions passed to enq(...) run as effects after the transition. Return the patch from the transition, entry or exit function instead; a named action can be called there directly and its result returned.`\n );\n}\n\nfunction execEmitEffect(\n this: EmitExecutableEffect,\n runtime: EffectRuntime = this.source.system\n): void | PromiseLike<void> {\n return publishEmittedEvent(this.source, this.event, runtime);\n}\n\n/** @internal Creates an emitted-event effect. */\nexport function createEmitEffect(\n actorScope: AnyActorScope,\n event: EventObject\n): EmitExecutableEffect {\n return {\n kind: 'emit',\n exec: execEmitEffect,\n type: event.type,\n source: actorScope.self,\n event,\n params: undefined,\n args: []\n };\n}\n\nfunction execDeadLetterEffect(\n this: DeadLetterExecutableEffect,\n runtime: EffectRuntime = (this.target ?? this.source)!.system\n): void | PromiseLike<void> {\n return runtime.deadLetter!(\n this.source,\n this.target,\n this.event,\n this.reason,\n this.detail\n );\n}\n\n/** @internal Creates a dead-letter effect for a boundary-rejected event. */\nexport function createDeadLetterEffect(\n actorScope: AnyActorScope,\n source: AnyActor | undefined,\n event: AnyEventObject,\n reason: EventRejectionReason,\n detail?: DeadLetterDetail\n): DeadLetterExecutableEffect {\n return {\n kind: 'builtin',\n type: '@xstate.deadLetter',\n exec: execDeadLetterEffect,\n source,\n target: actorScope.self,\n event,\n reason,\n detail,\n params: undefined,\n args: []\n };\n}\n\n/**\n * @internal Creates a dead-letter effect for an `enq.sendTo` whose target is\n * an undefined ref, an unknown child id, or the parent of a root actor.\n */\nfunction createMissingTargetEffect(\n actorScope: AnyActorScope,\n event: AnyEventObject,\n targetId: string | undefined\n): DeadLetterExecutableEffect {\n return {\n kind: 'builtin',\n type: '@xstate.deadLetter',\n exec: execDeadLetterEffect,\n source: actorScope.self,\n target: undefined,\n event,\n reason: 'missingTarget',\n detail: {\n targetId,\n error: new Error(\n !isDevelopment\n ? xstateError(65, targetId)\n : targetId !== undefined\n ? `Unable to send event to unknown child '${targetId}'`\n : 'Unable to send event to an undefined actor'\n )\n },\n params: undefined,\n args: []\n };\n}\n\n/** @internal Creates a directly executable user effect. */\nexport function createCustomEffect(\n type: string,\n action: (runtime?: EffectRuntime) => void | PromiseLike<void> | undefined,\n params?: unknown\n): CustomExecutableEffect {\n return {\n kind: 'action',\n exec: action,\n type,\n action: action as () => void | PromiseLike<void>,\n params,\n args: []\n };\n}\n\nfunction execSpawnEffect(\n this: SpawnExecutableEffect,\n runtime: EffectRuntime = this.actor.system\n): void | PromiseLike<void> {\n return runtime.spawnActor!(this.source, this.actor);\n}\n\nfunction execStartEffect(\n this: StartExecutableEffect,\n runtime: EffectRuntime = this.actor.system\n): void | PromiseLike<void> {\n // A child stopped before its deferred start (spawned and stopped in the\n // same transition) stays stopped; actors cannot be restarted.\n if (\n (this.actor as { _processingStatus?: number })._processingStatus ===\n 2 /* ProcessingStatus.Stopped */\n ) {\n return;\n }\n return runtime.startActor!(this.actor);\n}\n\nfunction execStopEffect(\n this: StopExecutableEffect,\n runtime: EffectRuntime = this.source.system\n): void | PromiseLike<void> {\n return runtime.stopActor!(this.actor);\n}\n\nfunction execTerminateEffect(\n this: TerminateExecutableEffect,\n runtime: EffectRuntime = this.actor.system\n): void | PromiseLike<void> {\n const termination: ActorTermination =\n this.status === 'done'\n ? { status: 'done', output: this.output, error: undefined }\n : { status: 'error', output: undefined, error: this.error };\n return runtime.terminateActor!(this.actor, termination);\n}\n\nfunction execRaiseEffect(\n this: RaiseExecutableEffect,\n runtime: EffectRuntime = this.source.system\n): void | PromiseLike<void> {\n return runtime.scheduleTimer!(\n this.source,\n getTimerKey(this),\n this.delay ?? 0\n );\n}\n\nfunction execSendToEffect(\n this: SendToExecutableEffect,\n runtime: EffectRuntime = this.source.system\n): void | PromiseLike<void> {\n assertSendToEvent(this.event);\n if (this.delay !== undefined) {\n return runtime.scheduleTimer!(this.source, getTimerKey(this), this.delay);\n }\n return runtime.sendEvent!(this.source, this.target, this.event);\n}\n\nfunction execCancelEffect(\n this: CancelExecutableEffect,\n runtime: EffectRuntime = this.source.system\n): void | PromiseLike<void> {\n return runtime.cancelTimer!(this.source, readTimerKey(this)!);\n}\n\nfunction updateLogicalTimers(\n snapshot: AnyMachineSnapshot,\n effect: ExecutableEffect,\n actorScope: AnyActorScope\n): AnyMachineSnapshot {\n if (!isBuiltInExecutableEffect(effect)) {\n return snapshot;\n }\n\n if (effect.type === '@xstate.cancel') {\n const key = readTimerKey(effect)!;\n if (!snapshot.timers?.some((timer) => matchesTimerKey(timer, key))) {\n return snapshot;\n }\n return {\n ...snapshot,\n timers: snapshot.timers.filter((timer) => !matchesTimerKey(timer, key))\n };\n }\n\n if (\n (effect.type !== '@xstate.raise' && effect.type !== '@xstate.sendTo') ||\n effect.delay === undefined\n ) {\n return snapshot;\n }\n\n // A delayed raise or send without an `id` is numbered by the actor's\n // timer sequence. Built-in timers (`after`, `timeout`) have neither; their\n // event identifies them.\n let nextTimerId = snapshot._nextTimerId ?? 0;\n if (effect.id === undefined && !getBuiltInTimerIdentity(effect.event)) {\n effect.seq = nextTimerId++;\n const args = effect.args as unknown[];\n args[args.length - 1] = {\n ...(args[args.length - 1] as object),\n seq: effect.seq\n };\n }\n const target =\n effect.type === '@xstate.raise' || effect.target === actorScope.self\n ? 'self'\n : effect.target;\n const timer: LogicalTimer = {\n ...(effect.id !== undefined && { id: effect.id }),\n ...(effect.seq !== undefined && { seq: effect.seq }),\n delay: effect.delay,\n type: effect.type,\n event: effect.event,\n target\n };\n // Scheduling a timer that is already pending replaces it in place.\n const key = getTimerKey(timer);\n const timers = snapshot.timers ?? [];\n const index = timers.findIndex((pending) => matchesTimerKey(pending, key));\n\n return {\n ...snapshot,\n timers:\n index === -1\n ? [...timers, timer]\n : timers.map((pending, i) => (i === index ? timer : pending)),\n _nextTimerId: nextTimerId\n };\n}\n\nexport function mergeContextPatch(\n context: MachineContext,\n patch: MachineContext\n): MachineContext {\n return { ...context, ...patch };\n}\n\nfunction pushBuiltInAction(actions: any[], action: any, ...args: any[]) {\n const actionRecord: TransitionActionRecord = { action, args };\n actions.push(actionRecord as AnyAction);\n return actionRecord;\n}\n\n/** @internal Max-merges generated-id counter records, copy-on-write. */\nexport function mergeActorIdCounters(\n current: Record<string, number> | undefined,\n update: Record<string, number>\n): Record<string, number> {\n const merged = { ...current };\n for (const key of Object.keys(update)) {\n merged[key] = Math.max(merged[key] ?? 0, update[key]);\n }\n return merged;\n}\n\nfunction applyChildUpdate(\n snapshot: AnyMachineSnapshot,\n update: NonNullable<TransitionActionRecord['childUpdate']>,\n actorScope: AnyActorScope\n): AnyMachineSnapshot {\n if (update.type === 'add') {\n return {\n ...snapshot,\n children: { ...snapshot.children, [update.id]: update.actor },\n ...(update.counters && {\n _nextActorIds: mergeActorIdCounters(\n snapshot._nextActorIds,\n update.counters\n )\n })\n };\n }\n\n const children = { ...snapshot.children };\n let owned = update.actor._parent === actorScope.self;\n for (const key of Object.keys(children)) {\n if (children[key] === update.actor) {\n owned = true;\n delete children[key];\n }\n }\n if (!owned) {\n throw new Error(\n isDevelopment\n ? `Cannot stop child actor ${update.actor.id} of ${actorScope.self.id} because it is not a child`\n : xstateError(47, update.actor.id, actorScope.self.id)\n );\n }\n actorScope.system._unregister(update.actor);\n return { ...snapshot, children };\n}\n\nfunction getTransitionActionRecord(\n action: AnyAction\n): TransitionActionRecord | undefined {\n if (\n typeof action === 'object' &&\n action !== null &&\n 'action' in action &&\n typeof action.action === 'function'\n ) {\n return action as TransitionActionRecord;\n }\n return undefined;\n}\n\nfunction pushSpawnedChild(\n actions: any[],\n actor: AnyActor,\n id: string,\n counters?: Record<string, number>\n) {\n const action = pushBuiltInAction(\n actions,\n builtInActions['@xstate.spawn'],\n actor\n );\n action.childUpdate = { type: 'add', actor, id, counters };\n}\n\n/**\n * Spawn-allocation state shared by every enqueue object of one transition, so\n * generated ids stay unique and resolvable across action functions and\n * microsteps of the same event.\n */\ninterface SpawnAllocation {\n counters: Map<string, number>;\n /** Explicit child ids claimed by spawns/invokes of this transition. */\n explicitIds: Set<string>;\n /** Ids of children stopped by this transition, freeing them for reuse. */\n stoppedIds: Set<string>;\n}\n\nconst spawnAllocations = new WeakMap<object, SpawnAllocation>();\n\nconst createSpawnAllocation = (): SpawnAllocation => ({\n counters: new Map(),\n explicitIds: new Set(),\n stoppedIds: new Set()\n});\n\n/**\n * Starts a fresh spawn-allocation transaction for one logical transition.\n * Called at every transition boundary so pure replays from the same snapshot\n * allocate identical ids.\n *\n * @internal\n */\nexport function beginSpawnAllocation(actorScope: AnyActorScope): void {\n spawnAllocations.set(actorScope, createSpawnAllocation());\n}\n\n// Read the raw snapshot: getSnapshot() throws while the actor initializes,\n// and entry actions run before any snapshot exists.\nfunction getWorkingSnapshotOf(actorScope: AnyActorScope):\n | {\n _nextActorIds?: Record<string, number>;\n children?: Record<string, AnyActor | undefined>;\n }\n | undefined {\n return (\n actorScope.self as {\n _snapshot?: {\n _nextActorIds?: Record<string, number>;\n children?: Record<string, AnyActor | undefined>;\n };\n }\n )._snapshot;\n}\n\nfunction getRegisteredActors(\n actorScope: AnyActorScope\n): Record<string, AnyActorLogic> | undefined {\n return (\n actorScope.self as {\n logic?: { sources?: { actors?: Record<string, AnyActorLogic> } };\n }\n ).logic?.sources?.actors;\n}\n\nfunction resolveTransitionSpawnSource(\n actorScope: AnyActorScope,\n source: string | AnyActorLogic\n): { logic: AnyActorLogic; src: string | undefined } {\n const registeredActors = getRegisteredActors(actorScope);\n if (typeof source === 'string') {\n const logic = registeredActors?.[source];\n if (!logic) {\n throw new Error(\n isDevelopment\n ? `Actor source '${source}' is not provided`\n : xstateError(66, source)\n );\n }\n return { logic, src: source };\n }\n if (!registeredActors) {\n return { logic: source, src: undefined };\n }\n return {\n logic: source,\n src: resolveRegisteredActorSource(registeredActors, source)\n };\n}\n\n/**\n * Internal helper actors (listeners, subscriptions) number their ids from\n * system-level counters under `@xstate.`-prefixed names; snapshot-owned\n * children number from per-snapshot counters. The two spaces only stay\n * collision-free because their prefixes are disjoint, so user sources must\n * not enter the reserved `xstate.` / `@xstate.` namespaces.\n */\nfunction assertUnreservedPrefix(prefix: string): void {\n if (\n isDevelopment &&\n (prefix.startsWith('xstate.') || prefix.startsWith('@xstate.'))\n ) {\n throw new Error(\n `Child actor ids with the \"xstate.\" or \"@xstate.\" prefix are reserved for internal actors; rename the \"${prefix}\" source or logic id.`\n );\n }\n}\n\n/**\n * The next free index for a prefix. The parent snapshot's persisted counter\n * is always a floor, so a freed id is never handed out again — not even when\n * an explicit id reserved a lower one earlier in the transition.\n */\nfunction nextChildIndex(\n actorScope: AnyActorScope,\n allocation: SpawnAllocation,\n prefix: string\n): number {\n return Math.max(\n allocation.counters.get(prefix) ?? 0,\n getWorkingSnapshotOf(actorScope)?._nextActorIds?.[prefix] ?? 0\n );\n}\n\n/**\n * The next generated index for a prefix that is not claimed in this\n * transition or held by a live child, such as an implicit invoke id\n * (`worker:0` for an invoke in state `worker`). Does not allocate.\n */\nfunction nextFreeChildIndex(\n actorScope: AnyActorScope,\n allocation: SpawnAllocation,\n prefix: string\n): number {\n let next = nextChildIndex(actorScope, allocation, prefix);\n const children = getWorkingSnapshotOf(actorScope)?.children;\n while (\n allocation.explicitIds.has(`${prefix}:${next}`) ||\n children?.[`${prefix}:${next}`]\n ) {\n next++;\n }\n return next;\n}\n\n/**\n * Allocates the next generated child id for the transition's allocation\n * transaction, seeded from the parent snapshot's own persisted counters. This\n * is the single allocator for snapshot-owned children (`enq.spawn` and\n * context-factory spawns); a correct allocation cannot collide.\n *\n * @internal\n */\nexport function allocateChildId(\n actorScope: AnyActorScope,\n src: string | AnyActorLogic,\n localAllocation?: SpawnAllocation\n): { id: string; counters: Record<string, number> } {\n if (isDevelopment && !spawnAllocations.get(actorScope)) {\n console.warn(\n 'A child id was generated outside a spawn-allocation transaction; ids may repeat across enqueue objects. Transition entry points must call beginSpawnAllocation().'\n );\n }\n const allocation =\n spawnAllocations.get(actorScope) ??\n localAllocation ??\n createSpawnAllocation();\n const prefix = getActorIdPrefix(src);\n assertUnreservedPrefix(prefix);\n const next = nextFreeChildIndex(actorScope, allocation, prefix);\n allocation.counters.set(prefix, next + 1);\n return { id: `${prefix}:${next}`, counters: { [prefix]: next + 1 } };\n}\n\n/**\n * Requires an explicit child id to be unoccupied before a spawn or invoke\n * claims it: an address must name at most one live actor. An id is occupied\n * when a child of this parent already holds it and this transition has not\n * stopped that child, or when an earlier spawn of this transition claimed it.\n *\n * @internal\n */\nexport function assertChildIdFree(\n actorScope: AnyActorScope,\n id: string,\n localAllocation?: SpawnAllocation\n): void {\n const allocation =\n spawnAllocations.get(actorScope) ??\n localAllocation ??\n createSpawnAllocation();\n const existing = getWorkingSnapshotOf(actorScope)?.children?.[id] as\n | AnyActor\n | undefined;\n // A terminated child no longer occupies its id: it relayed its completion\n // and is removed from `children` right after the transition handling it,\n // so the supervisor pattern — respawn under the same name while handling\n // the child's done/error event — must not conflict with the outgoing\n // entry. Remote handles never expose a terminal status locally; the\n // completion event that removes one is the owning runtime's business.\n const occupied =\n existing !== undefined &&\n !allocation.stoppedIds.has(id) &&\n existing.getSnapshot().status === 'active';\n if (allocation.explicitIds.has(id) || occupied) {\n throw new Error(\n isDevelopment\n ? `Cannot spawn child actor with id '${id}': the id is already in use by another child of '${actorScope.self.id}'. Stop the existing child before reusing its id.`\n : xstateError(67, id, actorScope.self.id)\n );\n }\n allocation.explicitIds.add(id);\n}\n\n/**\n * Records that this transition stopped a child, freeing its id for a later\n * spawn or invoke of the same transition (the invoke restart pattern).\n *\n * @internal\n */\nfunction recordStoppedChild(actorScope: AnyActorScope, actor: AnyActor): void {\n const allocation = spawnAllocations.get(actorScope);\n if (allocation) {\n allocation.stoppedIds.add(actor.id);\n allocation.explicitIds.delete(actor.id);\n }\n}\n\n/**\n * Reserves an explicit generated-shaped id (`worker:5`) in the transaction\n * and the parent snapshot, so live runs and pure replays allocate the same\n * later ids even after this child is removed.\n *\n * @internal\n */\nexport function reserveChildId(\n actorScope: AnyActorScope,\n id: string,\n localAllocation?: SpawnAllocation\n): Record<string, number> | undefined {\n const generated = parseGeneratedActorId(id);\n if (!generated) {\n return undefined;\n }\n assertUnreservedPrefix(generated.prefix);\n const allocation =\n spawnAllocations.get(actorScope) ??\n localAllocation ??\n createSpawnAllocation();\n // The requested id is used as asked, but numbering continues from the\n // highest reservation: an explicit low id never rewinds the counter.\n const next = Math.max(\n nextChildIndex(actorScope, allocation, generated.prefix),\n generated.index + 1\n );\n allocation.counters.set(generated.prefix, next);\n return { [generated.prefix]: next };\n}\n\n/**\n * The counters allocated so far in the transition's transaction, for\n * committing into a snapshot built outside `applyChildUpdate` (the\n * pre-initial snapshot with context-factory spawns).\n *\n * @internal\n */\nexport function takeSpawnAllocationCounters(\n actorScope: AnyActorScope\n): Record<string, number> | undefined {\n const counters = spawnAllocations.get(actorScope)?.counters;\n if (!counters?.size) {\n return undefined;\n }\n return Object.fromEntries(counters);\n}\n\n/**\n * Scopes whose `self` is not the evaluated snapshot's actor (the shared\n * `snapshot.can(...)` scope), so spawned inert refs have no address.\n *\n * @internal\n */\nexport const detachedScopes = new WeakSet<AnyActorScope>();\n\nexport function assertRaiseEvent(event: unknown): void {\n if (typeof event === 'string') {\n throw new Error(\n isDevelopment\n ? `Only event objects may be used with raise; use raise({ type: \"${event}\" }) instead`\n : xstateError(68, event)\n );\n }\n}\n\nexport function createTransitionEnqueue(\n actorScope: AnyActorScope,\n actions: any[],\n internalEvents: EventObject[],\n actorSubscriptions = false,\n createActors = true\n) {\n // Paths that never begin a transaction keep a per-enqueue scope.\n const localAllocation =\n spawnAllocations.get(actorScope) ?? createSpawnAllocation();\n const props: Partial<EnqueueObject<any, any>> = {\n cancel: (id: string | TimerKey) => {\n pushBuiltInAction(\n actions,\n builtInActions['@xstate.cancel'],\n actorScope,\n typeof id === 'string' ? { id } : id\n );\n },\n emit: (emittedEvent) => {\n actions.push(emittedEvent);\n },\n log: (...args) => {\n pushBuiltInAction(actions, actorScope.logger, ...args);\n },\n raise: (raisedEvent, options) => {\n assertRaiseEvent(raisedEvent);\n if (options?.delay !== undefined) {\n pushBuiltInAction(\n actions,\n builtInActions['@xstate.raise'],\n actorScope,\n raisedEvent,\n options\n );\n } else {\n internalEvents.push(raisedEvent);\n }\n },\n spawn: (source: string | AnyActorLogic, options?: any) => {\n const { logic, src } = resolveTransitionSpawnSource(actorScope, source);\n if (!createActors) {\n // Speculative evaluation creates no actor and allocates no id: return\n // an inert ref with the id this spawn would get.\n const prefix = getActorIdPrefix(src ?? logic);\n const id =\n options?.id ??\n `${prefix}:${nextFreeChildIndex(actorScope, spawnAllocations.get(actorScope) ?? localAllocation, prefix)}`;\n return createInertActorRef({\n id,\n address: detachedScopes.has(actorScope)\n ? undefined\n : `${actorScope.self.address}/${encodeAddressSegment(id)}`,\n src\n });\n }\n // Generated ids allocate from the parent snapshot's own counters\n // through the transition's allocation transaction; explicit\n // generated-shaped ids reserve their numbering the same way.\n let id = options?.id;\n let counters: Record<string, number> | undefined;\n if (id === undefined) {\n ({ id, counters } = allocateChildId(\n actorScope,\n src ?? logic,\n localAllocation\n ));\n } else {\n assertChildIdFree(actorScope, id, localAllocation);\n counters = reserveChildId(actorScope, id, localAllocation);\n }\n const actor = actorScope.system.createActorRef(logic, {\n ...options,\n ...(src !== undefined && { src }),\n id,\n parent: actorScope.self\n });\n pushSpawnedChild(actions, actor, id, counters);\n return actor;\n },\n sendTo: (actor, event, options) => {\n // A missing target (undefined ref, unknown child id, or `parent` of a\n // root actor) resolves to a dead letter in `resolveActionsWithContext`.\n pushBuiltInAction(\n actions,\n builtInActions['@xstate.sendTo'],\n actorScope,\n actor,\n event,\n options\n );\n },\n stop: (actor) => {\n if (actor) {\n // enq.stop accepts the consumer ActorRef contract; refs handed to\n // machine code are always full actor instances at runtime.\n const actorInstance = actor as AnyActor;\n const action = pushBuiltInAction(\n actions,\n builtInActions['@xstate.stop'],\n actorScope,\n actorInstance\n );\n action.childUpdate = { type: 'remove', actor: actorInstance };\n recordStoppedChild(actorScope, actorInstance);\n }\n }\n };\n\n if (actorSubscriptions) {\n Object.assign(props, {\n listen: (actor: any, eventType: string, mapper: any) => {\n if (!createActors) {\n return { id: undefined } as unknown as AnyActor;\n }\n const input: ListenerInput<any, any> = {\n actor,\n eventType,\n mapper\n };\n const listenerActor = actorScope.system.createActorRef(listenerLogic, {\n input,\n parent: actorScope.self\n });\n pushBuiltInAction(\n actions,\n builtInActions['@xstate.spawn'],\n listenerActor\n );\n return listenerActor;\n },\n subscribeTo: (actor: any, mappers: any) => {\n if (!createActors) {\n return { id: undefined } as unknown as AnyActor;\n }\n const normalizedMappers: SubscriptionMappers<any, any, any> =\n typeof mappers === 'function' ? { snapshot: mappers } : mappers;\n\n const input: SubscriptionInput<any, any, any, any> = {\n actor,\n mappers: normalizedMappers\n };\n const subscriptionActor = actorScope.system.createActorRef(\n subscriptionLogic,\n {\n input,\n parent: actorScope.self\n }\n );\n pushBuiltInAction(\n actions,\n builtInActions['@xstate.spawn'],\n subscriptionActor\n );\n return subscriptionActor;\n }\n });\n }\n\n // The handle is only valid while its function runs; `closeTransitionEnqueue`\n // invalidates it once the function returns.\n let closed = false;\n const guard =\n <T extends (...args: any[]) => any>(fn: T) =>\n (...args: Parameters<T>) =>\n closed ? lateEnqueueCall() : fn(...args);\n for (const key of Object.keys(props) as (keyof typeof props)[]) {\n (props as any)[key] = guard((props as any)[key]);\n }\n const enqueue = createEnqueueObject(\n props,\n guard((action, ...args) => {\n // A named action is `undefined` when it has no implementation. Skip it:\n // an `{ action, args }` record without a function would be emitted as\n // an event. Speculative passes (`can()`, conflict resolution) run with\n // `createActors: false`; warn only when the transition really runs.\n if (typeof action !== 'function') {\n if (isDevelopment && createActors) {\n warnNotAFunction(action);\n }\n return;\n }\n pushBuiltInAction(actions, action, ...args);\n })\n );\n enqueueClosers.set(enqueue, () => {\n closed = true;\n });\n return enqueue;\n}\n\nconst enqueueClosers = new WeakMap<object, () => void>();\n\n/**\n * @internal Invalidates an enqueue handle after the function it was passed\n * to returned. Later `enq.*` calls throw in development and no-op in\n * production.\n */\nexport function closeTransitionEnqueue(enqueue: object): void {\n enqueueClosers.get(enqueue)?.();\n}\n\n/** @internal Handles an `enq.*` call made after its function returned. */\nexport function lateEnqueueCall(): any {\n if (isDevelopment) {\n throw new Error('enq.* called after the transition function returned');\n }\n return undefined;\n}\n\nfunction warnNotAFunction(value: unknown): void {\n const received =\n typeof value === 'string'\n ? `the string \"${value}\"`\n : value !== null && typeof value === 'object'\n ? 'an object'\n : String(value);\n console.warn(\n `enq(...) received ${received} instead of a function, so nothing was enqueued. A named action is undefined when it has no implementation: implement it in setup({ actions }) or the machine config, or pass it to machine.provide({ actions }).`\n );\n}\n\nfunction getBuiltInActionFields(\n action: (...args: any[]) => void,\n args: unknown[]\n): Partial<SpecialExecutableEffect> | undefined {\n switch (action) {\n case builtInActions['@xstate.spawn']: {\n const [actor] = args as Parameters<\n (typeof builtInActions)['@xstate.spawn']\n >;\n return {\n type: '@xstate.spawn',\n kind: 'builtin',\n exec: execSpawnEffect,\n source: actor._parent,\n actor,\n id: actor.id,\n logic: (actor as any).logic,\n src: actor.src,\n input: (actor as any).options?.input\n };\n }\n case builtInActions['@xstate.raise']: {\n const [, event, options] = args as Parameters<\n (typeof builtInActions)['@xstate.raise']\n >;\n return {\n type: '@xstate.raise',\n kind: 'builtin',\n exec: execRaiseEffect,\n source: (\n args as Parameters<(typeof builtInActions)['@xstate.raise']>\n )[0].self,\n event,\n id: options?.id,\n delay: options?.delay\n };\n }\n case builtInActions['@xstate.sendTo']: {\n const [, target, event, options] = args as Parameters<\n (typeof builtInActions)['@xstate.sendTo']\n >;\n return {\n type: '@xstate.sendTo',\n kind: 'builtin',\n exec: execSendToEffect,\n source: (\n args as Parameters<(typeof builtInActions)['@xstate.sendTo']>\n )[0].self,\n target,\n event,\n id: options?.id,\n delay: options?.delay\n };\n }\n case builtInActions['@xstate.cancel']: {\n const [, key] = args as Parameters<\n (typeof builtInActions)['@xstate.cancel']\n >;\n return {\n type: '@xstate.cancel',\n kind: 'builtin',\n exec: execCancelEffect,\n source: (\n args as Parameters<(typeof builtInActions)['@xstate.cancel']>\n )[0].self,\n ...key\n };\n }\n case builtInActions['@xstate.stop']: {\n const [, actor] = args as Parameters<\n (typeof builtInActions)['@xstate.stop']\n >;\n return {\n type: '@xstate.stop',\n kind: 'builtin',\n exec: execStopEffect,\n source: (args as Parameters<(typeof builtInActions)['@xstate.stop']>)[0]\n .self,\n actor,\n id: actor.id\n };\n }\n default:\n return undefined;\n }\n}\n\n/** @internal Creates an actor-start effect, including for restored children. */\nexport function createStartEffect(actor: AnyActor): StartExecutableEffect {\n const args: Parameters<(typeof builtInActions)['@xstate.start']> = [actor];\n return {\n kind: 'builtin',\n exec: execStartEffect,\n type: XSTATE_START,\n source: actor._parent,\n params: undefined,\n args,\n actor,\n id: actor.id\n };\n}\n\n/** @internal Recreates a pending logical timer without re-entering its state. */\nexport function createTimerEffect(\n actorScope: AnyActorScope,\n timer: LogicalTimer,\n delay: number\n): RaiseExecutableEffect | SendToExecutableEffect {\n const source = actorScope.self;\n const options = { id: timer.id, seq: timer.seq, delay };\n if (timer.type === '@xstate.raise') {\n return {\n kind: 'builtin',\n type: timer.type,\n source,\n event: timer.event,\n id: timer.id,\n ...(timer.seq !== undefined && { seq: timer.seq }),\n delay,\n params: undefined,\n args: [actorScope, timer.event, options],\n exec: execRaiseEffect\n };\n }\n const target = timer.target === 'self' ? source : timer.target;\n return {\n kind: 'builtin',\n type: timer.type,\n source,\n target,\n event: timer.event,\n id: timer.id,\n ...(timer.seq !== undefined && { seq: timer.seq }),\n delay,\n params: undefined,\n args: [actorScope, target, timer.event, options],\n exec: execSendToEffect\n };\n}\n\nexport function createSpawnEffect(actor: AnyActor): SpawnExecutableEffect {\n const args: Parameters<(typeof builtInActions)['@xstate.spawn']> = [actor];\n return {\n kind: 'builtin',\n exec: execSpawnEffect,\n type: XSTATE_SPAWN,\n source: actor._parent,\n params: undefined,\n args,\n actor,\n id: actor.id,\n logic: (actor as any).logic,\n src: actor.src,\n input: (actor as any).options?.input\n };\n}\n\n/** @internal Creates an immediate actor-to-actor delivery effect. */\nexport function createSendToEffect(\n actorScope: AnyActorScope,\n target: AnyActor,\n event: EventObject\n): SendToExecutableEffect {\n const args: Parameters<(typeof builtInActions)['@xstate.sendTo']> = [\n actorScope,\n target,\n event,\n {}\n ];\n return {\n kind: 'builtin',\n exec: execSendToEffect,\n type: '@xstate.sendTo',\n source: actorScope.self,\n target,\n event,\n id: undefined,\n delay: undefined,\n params: undefined,\n args\n };\n}\n\n/** @internal Creates the terminal lifecycle effect for an actor. */\nexport function createTerminationEffect(\n actorScope: AnyActorScope,\n snapshot: Snapshot<unknown>\n): TerminateExecutableEffect {\n if (snapshot.status !== 'done' && snapshot.status !== 'error') {\n throw new Error(\n isDevelopment\n ? 'Cannot terminate an active or stopped actor'\n : xstateError(69, actorScope.self.id, snapshot.status)\n );\n }\n const termination: ActorTermination =\n snapshot.status === 'done'\n ? { status: 'done', output: snapshot.output, error: undefined }\n : { status: 'error', output: undefined, error: snapshot.error };\n const args: Parameters<(typeof builtInActions)['@xstate.terminate']> = [\n actorScope.self,\n termination\n ];\n return {\n kind: 'builtin',\n exec: execTerminateEffect,\n type: XSTATE_TERMINATE,\n source: actorScope.self,\n actor: actorScope.self,\n id: actorScope.self.id,\n ...termination,\n params: undefined,\n args\n };\n}\n\n/**\n * Ensures that a newly terminal snapshot has exactly one ordered actor\n * termination effect.\n *\n * @internal\n */\nexport function finalizeTransitionResult<\n TSnapshot extends Snapshot<unknown>,\n TEffect\n>(\n actorScope: AnyActorScope,\n previousSnapshot: TSnapshot | undefined,\n [nextSnapshot, effects]: [TSnapshot, TEffect[]]\n): [TSnapshot, Array<TEffect | TerminateExecutableEffect>] {\n const becameTerminal =\n nextSnapshot.status === 'done' || nextSnapshot.status === 'error';\n const wasTerminal =\n previousSnapshot?.status === 'done' || previousSnapshot?.status === 'error';\n const hasTerminationEffect = effects.some(\n (effect) =>\n typeof effect === 'object' &&\n effect !== null &&\n 'type' in effect &&\n effect.type === XSTATE_TERMINATE\n );\n\n return becameTerminal && !wasTerminal && !hasTerminationEffect\n ? [\n nextSnapshot,\n [...effects, createTerminationEffect(actorScope, nextSnapshot)]\n ]\n : [nextSnapshot, effects];\n}\n\n/**\n * Attached (listener/subscription) starts are ordered before child starts so\n * that a listener/subscription captures events emitted synchronously as its\n * target actor starts.\n */\nexport function deriveDeferredStarts(\n effects: ReadonlyArray<ExecutableEffect>\n): StartExecutableEffect[] {\n const attachedStarts: StartExecutableEffect[] = [];\n const childStarts: StartExecutableEffect[] = [];\n\n for (const effect of effects) {\n if (!isBuiltInExecutableEffect(effect) || effect.type !== XSTATE_SPAWN) {\n continue;\n }\n const { actor, logic } = effect;\n const start = createStartEffect(actor);\n if (logic === listenerLogic || logic === subscriptionLogic) {\n attachedStarts.push(start);\n } else {\n childStarts.push(start);\n }\n }\n\n return [...attachedStarts, ...childStarts];\n}\n\n/** @public */\nexport function isBuiltInExecutableEffect(\n action: ExecutableEffect\n): action is SpecialExecutableEffect {\n return action.kind === 'builtin';\n}\n\n/**\n * Executes transition effects sequentially, awaiting each runtime operation.\n *\n * @public\n */\nexport async function executeEffects(\n effects: readonly ExecutableEffect[],\n runtime?: Partial<ActorSystemRuntime>\n): Promise<void> {\n for (const effect of effects) {\n await effect.exec(runtime);\n }\n}\n\nexport function resolveActionsWithContext(\n currentSnapshot: AnyMachineSnapshot,\n _event: AnyEventObject,\n actorScope: AnyActorScope,\n actions: AnyAction[]\n): [AnyMachineSnapshot, ExecutableEffect[]] {\n let intermediateSnapshot = currentSnapshot;\n const executableActions: ExecutableEffect[] = [];\n\n for (const action of actions) {\n const isInline = typeof action === 'function';\n const actionRecord = getTransitionActionRecord(action);\n let resolvedActionArgs = actionRecord?.args;\n\n if (\n actionRecord?.action === builtInActions['@xstate.sendTo'] &&\n (actionRecord.args[1] === undefined ||\n typeof actionRecord.args[1] === 'string')\n ) {\n const childId: string | undefined = actionRecord.args[1];\n const target =\n childId !== undefined &&\n Object.hasOwn(intermediateSnapshot.children, childId)\n ? intermediateSnapshot.children[childId]\n : undefined;\n if (!target) {\n // Boundary fault: the event is dead-lettered and the sender keeps\n // running; a missing target is never an actor error.\n executableActions.push(\n createMissingTargetEffect(actorScope, actionRecord.args[2], childId)\n );\n continue;\n }\n resolvedActionArgs = [\n actionRecord.args[0],\n target,\n ...actionRecord.args.slice(2)\n ];\n }\n // A ref that went through JSON stays address-backed through effects and\n // timers: delivery resolves it to whichever actor is live at the address\n // then, routes it through a host runtime, or reports a dead letter.\n\n const resolvedAction = isInline\n ? action\n : actionRecord\n ? actionRecord.action.bind(null, ...resolvedActionArgs!)\n : false;\n\n let actionParams = undefined;\n\n if (typeof action === 'object' && action !== null) {\n const {\n type: _,\n childUpdate: _childUpdate,\n ...emittedEventParams\n } = action as any;\n actionParams = emittedEventParams;\n }\n\n if (actionRecord?.childUpdate) {\n intermediateSnapshot = applyChildUpdate(\n intermediateSnapshot,\n actionRecord.childUpdate,\n actorScope\n );\n }\n\n if (!resolvedAction || !('resolve' in resolvedAction)) {\n const builtInFields =\n typeof action === 'object' &&\n action !== null &&\n 'action' in action &&\n typeof action.action === 'function'\n ? getBuiltInActionFields(action.action, resolvedActionArgs!)\n : undefined;\n const isEmittedEvent =\n typeof action === 'object' && action !== null && !actionRecord;\n\n const executableAction = {\n kind: builtInFields\n ? ('builtin' as const)\n : isEmittedEvent\n ? ('emit' as const)\n : ('action' as const),\n type:\n typeof action === 'object'\n ? 'action' in action && typeof action.action === 'function'\n ? (action.action.name ?? '(anonymous)')\n : (action as AnyEventObject).type\n : action.name || '(anonymous)',\n params: builtInFields ? undefined : actionParams,\n args:\n typeof action === 'object' && 'action' in action\n ? resolvedActionArgs!\n : [],\n ...(builtInFields\n ? {}\n : isEmittedEvent\n ? { source: actorScope.self, event: action }\n : {\n action: actionRecord?.action ?? (isInline ? action : undefined)\n }),\n ...(!builtInFields\n ? { exec: isEmittedEvent ? execEmitEffect : execCustomEffect }\n : {}),\n ...builtInFields\n };\n\n const typedExecutableEffect = executableAction as ExecutableEffect;\n intermediateSnapshot = updateLogicalTimers(\n intermediateSnapshot,\n typedExecutableEffect,\n actorScope\n );\n executableActions.push(typedExecutableEffect);\n continue;\n }\n }\n\n return [intermediateSnapshot, executableActions];\n}\n\nexport function createEnqueueObject(\n props: Partial<EnqueueObject<any, any>>,\n action: <T extends (...args: any[]) => any>(\n fn: T,\n ...args: Parameters<T>\n ) => void\n): EnqueueObject<any, any> {\n const enqueueFn = (\n fn: (...args: any[]) => any,\n ...args: Parameters<typeof fn>\n ) => {\n action(fn, ...args);\n };\n\n Object.assign(enqueueFn, {\n cancel: noop,\n emit: noop,\n log: noop,\n raise: noop,\n spawn: emptyActor,\n sendTo: noop,\n stop: noop,\n listen: emptyActor,\n subscribeTo: emptyActor,\n ...props\n });\n\n return enqueueFn as any;\n}\n\nconst noop = () => {};\nconst emptyActor = () => ({}) as any;\n","import isDevelopment from '#is-development';\nimport { xstateError } from './xstateError.ts';\nimport { getTimerKey } from './timerKey.ts';\nimport {\n type ActorTermination,\n AnyActor,\n AnyActorScope,\n EventObject,\n TimerKey\n} from './types';\n\nexport function assertSendToEvent(event: EventObject): void {\n if (typeof event === 'string') {\n throw new Error(\n isDevelopment\n ? // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `Only event objects may be used with sendTo; use sendTo({ type: \"${event}\" }) instead`\n : xstateError(70, event)\n );\n }\n}\n\nexport const builtInActions = {\n // Actor refs are created while resolving the next snapshot. Starting is a\n // separate deferred effect so the returned list remains execution-complete.\n ['@xstate.spawn']: (actor: AnyActor) => {\n return actor.system.spawnActor(actor._parent, actor);\n },\n ['@xstate.start']: (actor: AnyActor) => {\n return actor.system.startActor(actor);\n },\n ['@xstate.raise']: (\n actorScope: AnyActorScope,\n event: EventObject,\n options: { id?: string; seq?: number; delay?: number }\n ) => {\n return actorScope.system.scheduleTimer(\n actorScope.self,\n getTimerKey({ id: options.id, seq: options.seq, event }),\n options?.delay ?? 0\n );\n },\n ['@xstate.sendTo']: (\n actorScope: AnyActorScope,\n actor: AnyActor,\n event: EventObject,\n options: { id?: string; seq?: number; delay?: number }\n ) => {\n assertSendToEvent(event);\n if (options?.delay !== undefined) {\n return actorScope.system.scheduleTimer(\n actorScope.self,\n getTimerKey({ id: options.id, seq: options.seq, event }),\n options?.delay ?? 0\n );\n } else {\n return actorScope.system._relay(actorScope.self, actor, event);\n }\n },\n ['@xstate.cancel']: (actorScope: AnyActorScope, key: TimerKey) => {\n return actorScope.system.cancelTimer(actorScope.self, key);\n },\n ['@xstate.stop']: (actorScope: AnyActorScope, actor: AnyActor) => {\n return actorScope.system.stopActor(actor);\n },\n ['@xstate.terminate']: (actor: AnyActor, termination: ActorTermination) => {\n return actor.system.terminateActor(actor, termination);\n }\n};\n","import isDevelopment from '#is-development';\nimport { hasAmbientInspector } from './inspectionAmbient.ts';\nimport { xstateError } from './xstateError.ts';\nimport type { AnyActor, Snapshot } from './types.ts';\n\n/** Snapshot-scoped actor identity and system view. @internal */\nexport interface SnapshotActorRef {\n actor: AnyActor;\n systemState: SnapshotSystemState;\n}\n\ninterface SnapshotSystemState {\n root?: AnyActor;\n children?: Map<string, AnyActor>;\n keyedActors: Map<PropertyKey, AnyActor | undefined>;\n snapshot: AnyActor['system']['_snapshot'];\n sourceSystem: AnyActor['system'];\n sourceVersion: number;\n}\n\nconst snapshotActorRefs = new WeakMap<object, SnapshotActorRef>();\nconst lazySnapshotActorRefs = new WeakMap<object, () => SnapshotActorRef>();\nconst emptyKeyedActors = new Map<PropertyKey, AnyActor | undefined>();\n\nfunction copyRegisteredActors(\n system: AnyActor['system'],\n state?: SnapshotSystemState\n): Map<string, AnyActor> {\n if (state) {\n const children = new Map<string, AnyActor>(state.children);\n if (state.root?.sessionId) {\n children.set(state.root.sessionId, state.root);\n }\n return children;\n }\n return new Map(system.children);\n}\n\nfunction captureRegisteredActors(system: AnyActor['system']): {\n root?: AnyActor;\n children?: Map<string, AnyActor>;\n} {\n const root = system._getRootActor?.();\n const peekedChildren = system._peekChildren?.();\n if (!root && !peekedChildren) {\n if (system._getRootActor && system._peekChildren) {\n return {};\n }\n const children = new Map<string, AnyActor>(system.children);\n return children.size ? { children } : {};\n }\n if (!peekedChildren?.size) {\n return root ? { root } : {};\n }\n return { children: new Map<string, AnyActor>(system.children) };\n}\n\nfunction getKeyedActors(\n system: AnyActor['system']\n): Map<PropertyKey, AnyActor | undefined> {\n const peek = system._peekKeyedActors;\n if (peek) {\n return peek.call(system) ?? emptyKeyedActors;\n }\n return system.keyedActors;\n}\n\n/** Marks topology or persisted runtime state as changed. @internal */\nexport function markSystemSnapshotDirty(system: AnyActor['system']): void {\n system._snapshotVersion++;\n}\n\nfunction getSystemSnapshotVersion(system: AnyActor['system']): number {\n return system._snapshotVersion;\n}\n\nfunction getSnapshotChildren(\n snapshot: Snapshot<unknown>\n): Record<string, AnyActor | undefined> {\n return 'children' in snapshot && snapshot.children\n ? (snapshot.children as Record<string, AnyActor | undefined>)\n : {};\n}\n\n/**\n * Creates the isolated receptionist/id view used by a pure branch. Scheduling,\n * relaying and clocks remain delegated to the snapshot's execution system.\n *\n * @internal\n */\nexport function createSnapshotSystem(\n baseSystem: AnyActor['system'],\n children: Record<string, AnyActor | undefined>,\n baseState?: SnapshotSystemState\n): AnyActor['system'] {\n const forwardInspection = hasAmbientInspector();\n const registeredActors = copyRegisteredActors(baseSystem, baseState);\n const keyedActors = new Map<PropertyKey, AnyActor | undefined>(\n baseState?.keyedActors ?? getKeyedActors(baseSystem)\n );\n const reverseKeyedActors = new WeakMap<AnyActor, PropertyKey>();\n const system: AnyActor['system'] = Object.assign(Object.create(baseSystem), {\n children: registeredActors,\n keyedActors,\n reverseKeyedActors,\n _snapshot: { ...(baseState?.snapshot ?? baseSystem._snapshot) },\n _snapshotVersion: baseState?.sourceVersion ?? baseSystem._snapshotVersion,\n _register: (sessionId: string, actor: AnyActor) => {\n registeredActors.set(sessionId, actor);\n markSystemSnapshotDirty(system);\n return sessionId;\n },\n _unregister: (actor: AnyActor) => {\n if (actor.sessionId) {\n registeredActors.delete(actor.sessionId);\n }\n const registryKey = reverseKeyedActors.get(actor);\n if (registryKey !== undefined && keyedActors.get(registryKey) === actor) {\n keyedActors.delete(registryKey);\n }\n reverseKeyedActors.delete(actor);\n markSystemSnapshotDirty(system);\n },\n _set: (registryKey: PropertyKey, actor: AnyActor) => {\n const existing = keyedActors.get(registryKey);\n if (existing && existing !== actor) {\n throw new Error(\n isDevelopment\n ? `Actor with registry key '${String(registryKey)}' already exists.`\n : xstateError(45, String(registryKey))\n );\n }\n keyedActors.set(registryKey, actor);\n reverseKeyedActors.set(actor, registryKey);\n markSystemSnapshotDirty(system);\n },\n get: (registryKey: PropertyKey) => keyedActors.get(registryKey),\n getAll: () => Object.fromEntries(keyedActors),\n onEmitted: (listener: Parameters<AnyActor['system']['onEmitted']>[0]) =>\n baseSystem.onEmitted(listener),\n _notifyEmitted: (\n actorRef: AnyActor,\n event: Parameters<AnyActor['system']['_notifyEmitted']>[1]\n ) => baseSystem._notifyEmitted(actorRef, event),\n // Pure transition resolution must not leak topology inspection events\n // into a live runtime system — planning branches stay silent. The one\n // exception is a durable execution's own transitions (marked by the\n // ambient inspector at creation time): there the pure path IS the\n // execution, so inspection forwards to the base system's observers.\n _hasInspectionObservers: forwardInspection\n ? () => baseSystem._hasInspectionObservers?.() ?? false\n : () => false,\n _sendInspectionEvent: forwardInspection\n ? (event: Parameters<AnyActor['system']['_sendInspectionEvent']>[0]) =>\n baseSystem._sendInspectionEvent(event)\n : () => {}\n });\n\n for (const [registryKey, actor] of keyedActors) {\n if (!actor) {\n continue;\n }\n reverseKeyedActors.set(actor, registryKey);\n }\n for (const actor of Object.values(children)) {\n if (!actor) {\n continue;\n }\n if (actor.sessionId) {\n registeredActors.set(actor.sessionId, actor);\n }\n const registryKey = actor.registryKey;\n if (registryKey) {\n keyedActors.set(registryKey, actor);\n reverseKeyedActors.set(actor, registryKey);\n }\n }\n\n return system;\n}\n\n/** Returns the actor identity associated with a transition snapshot. @internal */\nexport function getSnapshotActorRef(\n snapshot: Snapshot<unknown>\n): SnapshotActorRef | undefined {\n const existing = snapshotActorRefs.get(snapshot);\n if (existing) {\n return existing;\n }\n const create = lazySnapshotActorRefs.get(snapshot);\n if (!create) {\n return undefined;\n }\n const created = create();\n snapshotActorRefs.set(snapshot, created);\n lazySnapshotActorRefs.delete(snapshot);\n return created;\n}\n\n/** Reads an already materialized snapshot association without creating one. @internal */\nexport function peekSnapshotActorRef(\n snapshot: Snapshot<unknown>\n): SnapshotActorRef | undefined {\n return snapshotActorRefs.get(snapshot);\n}\n\n/** Returns the existing identity provider without resolving it. @internal */\nexport function getSnapshotActorRefProvider(\n snapshot: Snapshot<unknown>\n): (() => SnapshotActorRef) | undefined {\n const existing = snapshotActorRefs.get(snapshot);\n return existing ? () => existing : lazySnapshotActorRefs.get(snapshot);\n}\n\n/** Defers actor/system identity allocation until a snapshot capability is used. @internal */\nexport function setLazySnapshotActorRef(\n snapshot: Snapshot<unknown>,\n create: () => SnapshotActorRef\n): void {\n snapshotActorRefs.delete(snapshot);\n lazySnapshotActorRefs.set(snapshot, create);\n}\n\n/**\n * Copies an internal actor association without rebuilding its system view.\n *\n * @internal\n */\nexport function copySnapshotActorRef(\n source: Snapshot<unknown>,\n target: Snapshot<unknown>\n): boolean {\n const ref = snapshotActorRefs.get(source);\n if (ref) {\n snapshotActorRefs.set(target, ref);\n return true;\n }\n const create = lazySnapshotActorRefs.get(source);\n if (create) {\n lazySnapshotActorRefs.set(target, create);\n return true;\n }\n return false;\n}\n\n/** Refreshes the only topology change made by an otherwise idle root start. */\nexport function refreshSnapshotActorRefRoot(\n snapshot: Snapshot<unknown>,\n actor: AnyActor,\n system: AnyActor['system']\n): boolean {\n const ref = snapshotActorRefs.get(snapshot);\n const sourceVersion = getSystemSnapshotVersion(system);\n if (\n ref?.actor !== actor ||\n ref.systemState.sourceSystem !== system ||\n ref.systemState.sourceVersion + 1 !== sourceVersion ||\n system._getRootActor?.() !== actor ||\n system._peekChildren?.()\n ) {\n return false;\n }\n ref.systemState.root = actor;\n ref.systemState.sourceVersion = sourceVersion;\n return true;\n}\n\n/**\n * Associates a transition snapshot with an actor and an immutable system view.\n * The internal association is excluded from enumeration and persistence.\n *\n * @internal\n */\nexport function setSnapshotActorRef(\n snapshot: Snapshot<unknown>,\n actor: AnyActor,\n baseSystem: AnyActor['system'] = actor.system,\n previousSnapshot?: Snapshot<unknown>\n): void {\n lazySnapshotActorRefs.delete(snapshot);\n const sourceVersion = getSystemSnapshotVersion(baseSystem);\n const previousRef = previousSnapshot\n ? getSnapshotActorRef(previousSnapshot)\n : undefined;\n const reusableRef =\n previousRef?.actor === actor ? previousRef : getSnapshotActorRef(snapshot);\n\n if (\n reusableRef?.actor === actor &&\n reusableRef.systemState.sourceSystem === baseSystem &&\n reusableRef.systemState.sourceVersion === sourceVersion\n ) {\n snapshotActorRefs.set(snapshot, reusableRef);\n return;\n }\n\n const capturedActors = captureRegisteredActors(baseSystem);\n let children = capturedActors.children;\n const baseKeyedActors = getKeyedActors(baseSystem);\n let keyedActors = baseKeyedActors.size\n ? new Map(baseKeyedActors)\n : emptyKeyedActors;\n for (const child of Object.values(getSnapshotChildren(snapshot))) {\n if (!child) {\n continue;\n }\n if (child.sessionId) {\n (children ??= new Map()).set(child.sessionId, child);\n }\n const registryKey = child.registryKey;\n if (registryKey) {\n if (keyedActors === emptyKeyedActors) {\n keyedActors = new Map();\n }\n keyedActors.set(registryKey, child);\n }\n }\n snapshotActorRefs.set(snapshot, {\n actor,\n systemState: {\n ...capturedActors,\n children,\n keyedActors,\n snapshot: { ...baseSystem._snapshot },\n sourceSystem: baseSystem,\n sourceVersion\n }\n } satisfies SnapshotActorRef);\n}\n","import { getTimerStart } from './timerClock.ts';\nimport { getScheduledTimerKey, getTimerKey } from './timerKey.ts';\nimport isDevelopment from '#is-development';\nimport { xstateError } from './xstateError.ts';\nimport { getStateValue, isStateId } from './stateUtils.ts';\nimport type {\n AnyMachineSnapshot,\n AnyStateMachine,\n AnyActor,\n EventObject,\n HistoryValue,\n MachineContext,\n StateConfig,\n StateValue,\n StateValueMap,\n AnyActorRef,\n Snapshot,\n MetaObject,\n StateSchema,\n StateId,\n StateIdInputs,\n StateContextFromStateValue,\n StateIdReference,\n SnapshotStatus,\n PersistedHistoryValue,\n AnyStateNode,\n LogicalTimer,\n SerializedActorRef\n} from './types.ts';\nimport { describeMachine, isActorRefLike, matchesState } from './utils.ts';\nimport {\n copySnapshotActorRef,\n getSnapshotActorRef,\n setSnapshotActorRef\n} from './snapshotActorRef.ts';\nimport { isRemoteActorRef, isSerializedActorRef } from './remoteActorRef.ts';\nimport { findNonJsonPath } from './persistedSnapshotFormat.ts';\n\nconst emptySnapshotRecord = Object.freeze({});\nconst emptyTimers: readonly LogicalTimer[] = Object.freeze([]);\n\nfunction compactTimers(\n timers: readonly LogicalTimer[] | undefined\n): readonly LogicalTimer[] {\n return timers?.length ? timers : emptyTimers;\n}\n\n/**\n * Deep-freezes the plain objects and arrays in machine context so accidental\n * in-place mutation throws instead of silently corrupting state. Actor refs,\n * class instances, Map/Set, Date, etc. are left untouched. Callers guard with\n * `isDevelopment` so production builds pay nothing.\n *\n * @internal\n */\nconst deepFrozenContext = new WeakSet<object>();\n\nexport function freezeContext(value: any, visiting = new Set<object>()): void {\n if (\n !value ||\n typeof value !== 'object' ||\n deepFrozenContext.has(value) ||\n visiting.has(value)\n ) {\n return;\n }\n if (!Array.isArray(value)) {\n const proto = Object.getPrototypeOf(value);\n if (\n (proto !== Object.prototype && proto !== null) ||\n isActorRefLike(value)\n ) {\n return;\n }\n }\n visiting.add(value);\n try {\n Object.freeze(value);\n } catch {\n // Some proxies (e.g. framework reactive state) refuse to be frozen.\n return;\n }\n // Descend even if the object was already frozen elsewhere: its children\n // may still be mutable.\n for (const key of Object.keys(value)) {\n freezeContext(value[key], visiting);\n }\n deepFrozenContext.add(value);\n}\n\nfunction compactSnapshotRecord<T extends object>(value: T | undefined): T {\n if (value === emptySnapshotRecord) {\n return value;\n }\n return value && Object.keys(value).length\n ? value\n : (emptySnapshotRecord as T);\n}\n\n/** @public */\nexport function isMachineSnapshot(value: unknown): value is AnyMachineSnapshot {\n return (\n !!value &&\n typeof value === 'object' &&\n 'machine' in value &&\n 'value' in value\n );\n}\n\ntype Values<T> = T[keyof T];\n\ntype MatchingObjectStateValue<\n TStateValue extends Record<string, unknown>,\n TTestStateValue extends Record<string, unknown>\n> =\n false extends Values<{\n [K in keyof TTestStateValue]: K extends keyof TStateValue\n ? NonNullable<TStateValue[K]> extends StateValue\n ? NonNullable<TTestStateValue[K]> extends StateValue\n ? [\n MatchingStateValue<\n NonNullable<TStateValue[K]>,\n NonNullable<TTestStateValue[K]>\n >\n ] extends [never]\n ? false\n : true\n : false\n : false\n : false;\n }>\n ? never\n : {\n [K in keyof TStateValue]: K extends keyof TTestStateValue\n ? MatchingStateValue<\n NonNullable<TStateValue[K]>,\n NonNullable<TTestStateValue[K]>\n >\n : TStateValue[K];\n };\n\ntype MatchingStateValue<\n TStateValue extends StateValue,\n TTestStateValue extends StateValue\n> = StateValue extends TTestStateValue\n ? TStateValue\n : string extends TTestStateValue\n ? TStateValue\n : TStateValue extends unknown\n ? TTestStateValue extends string\n ? TStateValue extends string\n ? TTestStateValue extends TStateValue\n ? TTestStateValue\n : Extract<TStateValue, TTestStateValue>\n : TStateValue extends Record<string, unknown>\n ? TStateValue & Record<TTestStateValue, StateValue | undefined>\n : never\n : TTestStateValue extends Record<string, unknown>\n ? TStateValue extends Record<string, unknown>\n ? MatchingObjectStateValue<TStateValue, TTestStateValue>\n : never\n : never\n : never;\n\ntype StateValuePath<TStateValue extends StateValue> =\n TStateValue extends StateValueMap\n ? {\n [K in keyof TStateValue & string]:\n | K\n | (NonNullable<TStateValue[K]> extends infer TChild extends StateValue\n ? `${K}.${StateValuePath<TChild>}`\n : never);\n }[keyof TStateValue & string]\n : TStateValue;\n\n/**\n * The values that `snapshot.matches(...)` accepts for a state value: a state\n * key, a dot-delimited path to a descendant state, or a partial state value.\n * Non-literal state values accept any value.\n */\nexport type ToTestStateValue<TStateValue extends StateValue> =\n StateValue extends TStateValue\n ? StateValue\n : TStateValue extends string\n ? TStateValue\n : TStateValue extends StateValueMap\n ? string extends keyof TStateValue\n ? StateValue\n :\n | StateValuePath<TStateValue>\n | {\n [K in keyof TStateValue]?: NonNullable<\n TStateValue[K]\n > extends infer TChild extends StateValue\n ? ToTestStateValue<TChild>\n : never;\n }\n : never;\n\n/**\n * `true` if `TTestStateValue` can match `TStateValue`, checked per position:\n * each literal key names a state at its level and each literal child matches\n * that state. A non-literal value (`string`, or a map with `string` keys)\n * passes at its own position only, so `{ checkout: string }` is accepted and\n * `{ nope: 'payment', checkout: string }` is not.\n */\ntype IsTestStateValueValid<\n TStateValue extends StateValue,\n TTestStateValue\n> = StateValue extends TStateValue\n ? true\n : string extends TTestStateValue\n ? true\n : TTestStateValue extends string\n ? [TTestStateValue] extends [StateValuePath<TStateValue>]\n ? true\n : false\n : TTestStateValue extends StateValueMap\n ? string extends keyof TTestStateValue\n ? true\n : true extends (\n TStateValue extends StateValueMap\n ? IsTestStateValueMapValid<TStateValue, TTestStateValue>\n : never\n )\n ? true\n : false\n : false;\n\ntype IsTestStateValueMapValid<\n TStateValueMap extends StateValueMap,\n TTestStateValue extends StateValueMap\n> = [Exclude<keyof TTestStateValue, keyof TStateValueMap>] extends [never]\n ? false extends {\n [K in keyof TTestStateValue]-?: IsTestStateValueValid<\n NonNullable<TStateValueMap[K & keyof TStateValueMap]>,\n NonNullable<TTestStateValue[K]>\n >;\n }[keyof TTestStateValue]\n ? false\n : true\n : false;\n\n/**\n * `unknown` if `matches(...)` accepts `TTestStateValue` for `TStateValue`,\n * otherwise `never`. Literal values must name states; a non-literal value\n * (such as a `string` leaf) is accepted at its own position.\n */\nexport type TestStateValueCheck<\n TStateValue extends StateValue,\n TTestStateValue extends StateValue\n> = [TTestStateValue] extends [ToTestStateValue<TStateValue>]\n ? unknown\n : false extends IsTestStateValueValid<TStateValue, TTestStateValue>\n ? never\n : unknown;\n\n/**\n * The `#id` references a snapshot (or union of snapshots) accepts, read from\n * its `getMeta()` keys so the overload does not depend on the state schema.\n */\ntype SnapshotStateIdReference<TSnapshot> = TSnapshot extends {\n getMeta: () => Record<infer TStateId, any>;\n}\n ? string extends TStateId\n ? `#${string}`\n : `#${Exclude<TStateId, ''> & string}`\n : `#${string}`;\n\ninterface MachineSnapshotBase<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TStateValue extends StateValue,\n TTag extends string,\n _TOutput,\n TMeta extends MetaObject,\n TStateSchema extends StateSchema = StateSchema\n> {\n /** The state machine that produced this state snapshot. */\n machine: AnyStateMachine;\n /** The tags of the active state nodes that represent the current state value. */\n tags: Set<string>;\n /**\n * The current state value.\n *\n * This represents the active state nodes in the state machine.\n *\n * - For atomic state nodes, it is a string.\n * - For compound parent state nodes, it is an object where:\n *\n * - The key is the parent state node's key\n * - The value is the current state value of the active child state node(s)\n *\n * @example\n *\n * ```ts\n * // single-level state node\n * snapshot.value; // => 'yellow'\n *\n * // nested state nodes\n * snapshot.value; // => { red: 'wait' }\n * ```\n */\n value: TStateValue;\n /** The current status of this snapshot. */\n status: SnapshotStatus;\n error: unknown;\n context: TContext;\n\n historyValue: Readonly<HistoryValue>;\n /** The enabled state nodes representative of the state value. */\n nodes: Array<AnyStateNode>;\n /** An object mapping actor names to spawned/invoked actors. */\n children: TChildren;\n /** Pending logical timers owned by this machine snapshot. */\n timers: readonly LogicalTimer[];\n /** @internal */\n _stateInputs: Record<string, Record<string, unknown>>;\n /** @internal */\n _nextTimerId: number;\n /** @internal */\n _nextActorIds?: Record<string, number>;\n /**\n * Whether the current state value is a subset of the given partial state\n * value, or, for a `'#id'` reference, whether the state node with that `id`\n * is active.\n *\n * @param partialStateValue\n */\n matches<const TTestStateId extends StateIdReference<TStateSchema>>(\n stateId: TTestStateId\n ): boolean;\n matches<\n const TTestStateValue extends Extract<ToTestStateValue<TStateValue>, string>\n >(\n partialStateValue: TTestStateValue,\n ...args: string extends TTestStateValue ? [never] : []\n ): this is MachineSnapshot<\n StateContextFromStateValue<TStateSchema, TContext, TTestStateValue>,\n TEvent,\n TChildren,\n MatchingStateValue<TStateValue, TTestStateValue>,\n TTag,\n _TOutput,\n TMeta,\n TStateSchema\n >;\n matches<\n const TTestStateValue extends Extract<\n ToTestStateValue<TStateValue>,\n StateValueMap\n >\n >(\n partialStateValue: TTestStateValue,\n ...args: string extends keyof TTestStateValue ? [never] : []\n ): this is MachineSnapshot<\n StateContextFromStateValue<TStateSchema, TContext, TTestStateValue>,\n TEvent,\n TChildren,\n MatchingStateValue<TStateValue, TTestStateValue>,\n TTag,\n _TOutput,\n TMeta,\n TStateSchema\n >;\n // Unions of snapshots (whose overloads above differ)\n matches<TSnapshot extends { value: StateValue }>(\n this: TSnapshot,\n stateId: NoInfer<SnapshotStateIdReference<TSnapshot>>\n ): boolean;\n // Non-literal values, and unions of snapshots\n matches<\n TSnapshot extends { value: StateValue },\n const TTestStateValue extends StateValue\n >(\n this: TSnapshot,\n partialStateValue: TTestStateValue &\n NoInfer<TestStateValueCheck<TSnapshot['value'], TTestStateValue>>\n ): boolean;\n\n /**\n * Whether the current state nodes has a state node with the specified `tag`.\n *\n * @param tag\n */\n hasTag: (tag: TTag) => boolean;\n\n /**\n * Determines whether sending the `event` will cause a non-forbidden\n * transition to be selected, even if the transitions have no actions nor\n * change the state value.\n *\n * Returns false for terminal snapshots. Throws if transition evaluation\n * throws; this dry run does not run onError recovery.\n *\n * @param event The event to test\n * @returns Whether the event will cause a transition\n */\n can: (event: TEvent) => boolean;\n\n getMeta: () => Record<\n StateId<TStateSchema> & string,\n TMeta | undefined // States might not have meta defined\n >;\n\n /**\n * Returns the inputs for the current active state nodes, keyed by state node\n * id.\n */\n getInputs: () => StateIdInputs<TStateSchema>;\n\n toJSON: () => unknown;\n}\n\ninterface ActiveMachineSnapshot<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TStateValue extends StateValue,\n TTag extends string,\n TOutput,\n TMeta extends MetaObject,\n TStateSchema extends StateSchema\n> extends MachineSnapshotBase<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TStateSchema\n> {\n status: 'active';\n output: undefined;\n error: undefined;\n}\n\ninterface DoneMachineSnapshot<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TStateValue extends StateValue,\n TTag extends string,\n TOutput,\n TMeta extends MetaObject,\n TStateSchema extends StateSchema\n> extends MachineSnapshotBase<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TStateSchema\n> {\n status: 'done';\n output: TOutput;\n error: undefined;\n}\n\ninterface ErrorMachineSnapshot<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TStateValue extends StateValue,\n TTag extends string,\n TOutput,\n TMeta extends MetaObject,\n TStateSchema extends StateSchema\n> extends MachineSnapshotBase<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TStateSchema\n> {\n status: 'error';\n output: undefined;\n error: unknown;\n}\n\ninterface StoppedMachineSnapshot<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TStateValue extends StateValue,\n TTag extends string,\n TOutput,\n TMeta extends MetaObject,\n TStateSchema extends StateSchema\n> extends MachineSnapshotBase<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TStateSchema\n> {\n status: 'stopped';\n output: undefined;\n error: undefined;\n}\n\n/** @public */\nexport type MachineSnapshot<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TStateValue extends StateValue,\n TTag extends string,\n TOutput,\n TMeta extends MetaObject,\n TStateSchema extends StateSchema\n> =\n | ActiveMachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TStateSchema\n >\n | DoneMachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TStateSchema\n >\n | ErrorMachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TStateSchema\n >\n | StoppedMachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TStateSchema\n >;\n\nconst machineSnapshotMatches = function matches(\n this: AnyMachineSnapshot,\n testValue: StateValue\n) {\n if (typeof testValue === 'string' && isStateId(testValue)) {\n const stateNode = this.machine.getStateNodeById(testValue);\n return this.nodes.includes(stateNode);\n }\n return matchesState(testValue, this.value);\n};\n\nconst machineSnapshotHasTag = function hasTag(\n this: AnyMachineSnapshot,\n tag: string\n) {\n return this.tags.has(tag);\n};\n\nconst machineSnapshotCan = function can(\n this: AnyMachineSnapshot,\n event: EventObject\n) {\n if (isDevelopment && !this.machine) {\n console.warn(\n `state.can(...) used outside of a machine-created State object; this will always return false.`\n );\n }\n\n // The dry-run logic lives on the machine so that non-machine bundles\n // (e.g. `createFSM`) don't pay for the transition-resolution machinery.\n return this.machine?._canTransition(this, event) ?? false;\n};\n\nconst machineSnapshotToJSON = function toJSON(this: AnyMachineSnapshot) {\n const {\n nodes,\n _stateInputs,\n tags,\n machine,\n getMeta,\n getInputs,\n toJSON,\n can,\n hasTag,\n matches,\n ...jsonValues\n } = this;\n return { ...jsonValues, tags: Array.from(tags) };\n};\n\nconst machineSnapshotGetMeta = function getMeta(this: AnyMachineSnapshot) {\n const meta: Record<string, any> = {};\n for (const stateNode of this.nodes) {\n if (stateNode.meta !== undefined) {\n meta[stateNode.id] = stateNode.meta;\n }\n }\n return meta;\n};\n\nconst machineSnapshotGetInputs = function getInputs<\n TStateSchema extends StateSchema\n>(\n this: AnyMachineSnapshot & {\n _stateInputs: StateIdInputs<TStateSchema>;\n }\n): StateIdInputs<TStateSchema> {\n return this._stateInputs;\n};\n\nfunction collectTags(stateNodes: Array<AnyStateNode>): Set<string> {\n const tags = new Set<string>();\n for (const stateNode of stateNodes) {\n for (const tag of stateNode.tags) {\n tags.add(tag);\n }\n }\n return tags;\n}\n\nexport function createMachineSnapshot<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TStateValue extends StateValue,\n TTag extends string,\n TMeta extends MetaObject,\n TStateSchema extends StateSchema\n>(\n config: StateConfig<TContext, TEvent>,\n machine: AnyStateMachine,\n actorRef?: AnyActor\n): MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n undefined,\n TMeta,\n TStateSchema\n> {\n const snapshot = {\n status: config.status as never,\n output: config.output,\n error: config.error,\n machine,\n context: config.context,\n nodes: config._nodes,\n value: (config.value ??\n getStateValue(machine.root, config._nodes)) as never,\n tags: collectTags(config._nodes),\n children: compactSnapshotRecord(config.children) as TChildren,\n timers: compactTimers(config.timers),\n historyValue: compactSnapshotRecord(config.historyValue),\n _stateInputs: compactSnapshotRecord(config._stateInputs),\n _nextTimerId: config._nextTimerId ?? 0,\n _nextActorIds: config._nextActorIds,\n matches: machineSnapshotMatches as never,\n hasTag: machineSnapshotHasTag,\n can: machineSnapshotCan,\n getMeta: machineSnapshotGetMeta,\n getInputs: machineSnapshotGetInputs,\n toJSON: machineSnapshotToJSON\n };\n if (isDevelopment) {\n freezeContext(snapshot.context);\n }\n if (actorRef) {\n setSnapshotActorRef(snapshot, actorRef);\n }\n return snapshot;\n}\n\nexport function cloneMachineSnapshot<TState extends AnyMachineSnapshot>(\n snapshot: TState,\n config: Partial<StateConfig<any, any>> = {}\n): TState {\n const configWithSnapshot = {\n ...snapshot,\n ...config\n } as StateConfig<any, any>;\n\n if ((config._nodes ?? snapshot.nodes) === snapshot.nodes) {\n const clonedSnapshot = {\n status: configWithSnapshot.status as never,\n output: configWithSnapshot.output,\n error: configWithSnapshot.error,\n machine: snapshot.machine,\n context: configWithSnapshot.context,\n nodes: snapshot.nodes,\n value: snapshot.value,\n tags: snapshot.tags,\n children: compactSnapshotRecord(configWithSnapshot.children),\n timers: compactTimers(configWithSnapshot.timers),\n historyValue: compactSnapshotRecord(configWithSnapshot.historyValue),\n _stateInputs: compactSnapshotRecord(configWithSnapshot._stateInputs),\n _nextTimerId: configWithSnapshot._nextTimerId ?? 0,\n _nextActorIds: configWithSnapshot._nextActorIds,\n matches: machineSnapshotMatches as never,\n hasTag: machineSnapshotHasTag,\n can: machineSnapshotCan,\n getMeta: machineSnapshotGetMeta,\n getInputs: machineSnapshotGetInputs,\n toJSON: machineSnapshotToJSON\n } as unknown as TState;\n if (isDevelopment) {\n freezeContext(clonedSnapshot.context);\n }\n copySnapshotActorRef(snapshot, clonedSnapshot);\n return clonedSnapshot;\n }\n\n const clonedSnapshot = createMachineSnapshot(\n {\n ...configWithSnapshot,\n value: undefined\n },\n snapshot.machine\n ) as unknown as TState;\n copySnapshotActorRef(snapshot, clonedSnapshot);\n return clonedSnapshot;\n}\n\nfunction serializeHistoryValue(\n historyValue: HistoryValue\n): PersistedHistoryValue {\n const result: PersistedHistoryValue = {};\n\n for (const key in historyValue) {\n const value = historyValue[key];\n if (Array.isArray(value)) {\n result[key] = value.map((item) => ({ id: item.id }));\n }\n }\n\n return result;\n}\n\nexport function getPersistedSnapshot<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TStateValue extends StateValue,\n TTag extends string,\n TOutput,\n TMeta extends MetaObject\n>(\n snapshot: MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n any // state schema\n >,\n options?: unknown\n): Snapshot<unknown> {\n const {\n nodes,\n _stateInputs,\n tags,\n machine,\n children,\n timers,\n context,\n can,\n hasTag,\n matches,\n getMeta,\n getInputs,\n toJSON,\n ...jsonValues\n } = snapshot;\n\n if (isDevelopment) {\n // Before persistContext, which rejects cycles with an error.\n warnOnNonJsonPayload(\n {\n context,\n output: jsonValues.output,\n error: jsonValues.error,\n stateInputs: _stateInputs\n },\n machine.id\n );\n }\n\n const childrenJson: Record<string, unknown> = {};\n const timersJson: unknown[] = [];\n\n const embedChildren =\n (options as { embedChildren?: boolean } | undefined)?.embedChildren !==\n false;\n for (const id in children) {\n const child = children[id] as any;\n const sourceKey = typeof child.src === 'string' ? child.src : undefined;\n // An inline invoke has no source key; it restores through the invoke\n // definition with its id among the active states.\n const invoked =\n sourceKey === undefined &&\n child._invoked === true &&\n nodes.some((node) => node.invoke.some((def) => def.id === id));\n if (\n sourceKey === undefined &&\n !invoked &&\n (!options || !('__unsafeAllowInlineActors' in (options as object)))\n ) {\n throw new Error(\n isDevelopment\n ? 'An inline child actor cannot be persisted.'\n : xstateError(41, id)\n );\n }\n // Children are referenced by their logical address. Embedding the child\n // state is the co-locating runtime's whole-tree checkpoint capability;\n // remote handles never embed — their state lives with another runtime.\n const embed = embedChildren && !isRemoteActorRef(child);\n if (!embed && sourceKey === undefined) {\n // Fail where it is actionable: a by-address reference without a\n // registered source key could be persisted but never restored.\n throw new Error(\n isDevelopment\n ? `Unable to persist child '${id}' by address: it requires a registered source key.`\n : xstateError(42, id)\n );\n }\n childrenJson[id as keyof typeof childrenJson] = {\n address: child.address,\n // The explicit marker disambiguates a by-address reference from a child\n // whose own persisted snapshot happens to be undefined.\n ...(embed\n ? { snapshot: child.getPersistedSnapshot(options) }\n : {\n remote: true,\n // A remote handle's sessionId IS the host-supplied incarnation\n // token, round-tripped verbatim. A local child persisted by\n // address never stamps its own sessionId: that value is this\n // incarnation's, not a durable identity, and it would make\n // persisted snapshots nondeterministic across replays.\n incarnation: isRemoteActorRef(child) ? child.sessionId : undefined\n }),\n ...(invoked ? {} : { src: child.src }),\n registryKey: child.registryKey,\n syncSnapshot: child._syncSnapshot\n };\n }\n\n const snapshotActor = getSnapshotActorRef(snapshot)?.actor;\n // Only the wall clock is stamped into persisted timers: a custom clock's\n // readings (a simulated clock, a monotonic counter) are meaningless in any\n // other process, and restoring them under the wall clock would fire every\n // pending delay instantly. Pure-transition snapshots have no local\n // schedule; durable executions record an accepted start separately.\n const scheduledTimers = snapshotActor?.system?._clock?.now\n ? undefined\n : snapshotActor?.system?._snapshot?._scheduledTimers;\n for (const timer of timers) {\n let event = timer.event;\n if (event.type === 'xstate.timeout.actor') {\n event = { ...event };\n delete (event as EventObject & { sessionId?: string }).sessionId;\n }\n let target: string | { type: 'parent' } | SerializedActorRef;\n if (timer.target === 'self') {\n target = 'self';\n } else if (isSerializedActorRef(timer.target)) {\n // An address-backed target resolves when the timer fires.\n target = { ...timer.target };\n } else {\n const childId = Object.entries(children).find(\n ([, child]) => child === timer.target\n )?.[0];\n if (childId) {\n target = childId;\n } else if (\n timer.target === getSnapshotActorRef(snapshot)?.actor._parent\n ) {\n target = { type: 'parent' };\n } else {\n throw new Error(\n isDevelopment\n ? `Unable to persist timer ${timer.id !== undefined ? `'${timer.id}'` : `for event '${timer.event.type}'`}: target actor '${timer.target.id}' is no longer addressable from this snapshot.`\n : xstateError(43, timer.target.id)\n );\n }\n }\n // A live runtime knows when the timer is due; persist the wall-clock\n // start (dueAt - declared delay) so restore can honor the absolute\n // deadline. Derived from dueAt, not the scheduling moment, so repeated\n // persist/restore cycles keep the same deadline. Without a live schedule\n // (a restored-but-never-started actor, a pure-transition snapshot) the\n // timer's accepted durable start or carried-in start passes through,\n // so re-persisting cannot push the deadline back.\n const scheduled =\n scheduledTimers?.[\n getScheduledTimerKey(snapshotActor!, getTimerKey(timer))\n ];\n const scheduledAt = scheduled\n ? scheduled.dueAt - timer.delay\n : getTimerStart(timer);\n timersJson.push({\n ...(timer.id !== undefined && { id: timer.id }),\n ...(timer.seq !== undefined && { seq: timer.seq }),\n delay: timer.delay,\n type: timer.type,\n event,\n target,\n ...(scheduledAt !== undefined && { scheduledAt })\n });\n }\n\n const persisted: Record<string, unknown> = {\n ...jsonValues,\n context: persistContext(\n context,\n () => getSnapshotActorRef(snapshot)?.actor.id ?? machine.id\n ) as any,\n children: childrenJson,\n timers: timersJson,\n historyValue: serializeHistoryValue(jsonValues.historyValue)\n };\n\n if (_stateInputs && Object.keys(_stateInputs).length > 0) {\n persisted.stateInputs = _stateInputs;\n }\n\n if (machine.version !== undefined) {\n persisted.machine = {\n id: machine.id,\n version: machine.version\n };\n }\n\n return persisted as Snapshot<unknown>;\n}\n\nfunction warnOnNonJsonPayload(\n persisted: Record<string, unknown>,\n machineId: string\n) {\n for (const key of ['context', 'output', 'error', 'stateInputs']) {\n const found = findNonJsonPath(persisted[key], key);\n if (found) {\n console.warn(\n `Persisted snapshot of ${describeMachine(machineId)} contains a non-JSON value (${found.kind}) at '${found.path}'. Persisted snapshots must be JSON-serializable; this value will be lost or throw in JSON.stringify.`\n );\n return;\n }\n }\n}\n\nfunction persistContext(\n contextPart: Record<string, unknown>,\n getActorId: () => string,\n path = 'context',\n ancestors: object[] = []\n) {\n // `ancestors` is the current descent path: a shared, non-circular object\n // reached twice is fine; one that contains itself is not JSON.\n ancestors.push(contextPart);\n let copy: typeof contextPart | undefined;\n for (const key in contextPart) {\n const value = contextPart[key];\n if (value && typeof value === 'object') {\n if (isActorRefLike(value)) {\n copy ??= Array.isArray(contextPart)\n ? (contextPart.slice() as typeof contextPart)\n : { ...contextPart };\n // The address lets refs to non-children still route after restore.\n copy[key] = { $actor: (value as any as AnyActor).address };\n } else {\n const valuePath = Array.isArray(contextPart)\n ? `${path}[${key}]`\n : `${path}.${key}`;\n if (ancestors.includes(value)) {\n throw new Error(\n isDevelopment\n ? `Cannot persist actor \"${getActorId()}\": circular reference at ${valuePath}`\n : xstateError(44, getActorId(), valuePath)\n );\n }\n const result = persistContext(\n value as typeof contextPart,\n getActorId,\n valuePath,\n ancestors\n );\n if (result !== value) {\n copy ??= Array.isArray(contextPart)\n ? (contextPart.slice() as typeof contextPart)\n : { ...contextPart };\n copy[key] = result;\n }\n }\n }\n }\n ancestors.pop();\n return copy ?? contextPart;\n}\n","import isDevelopment from '#is-development';\nimport { xstateError } from './xstateError.ts';\nimport { isMachineSnapshot } from './State.ts';\nimport type { StateNode } from './StateNode.ts';\nimport { TARGETLESS_KEY, WILDCARD } from './constants.ts';\nimport type {\n AnyActor,\n AnyActorLogic,\n AnyEventObject,\n AnyInvokeDefinition,\n AnyMachineSnapshot,\n AnyStateMachine,\n AnyStateNode,\n AnyTransitionConfig,\n AnyTransitionConfigFunction,\n ErrorEvent,\n EventObject,\n MachineContext,\n Mapper,\n Observer,\n OutputArg,\n StateLike,\n StateValue\n} from './types.ts';\nimport type { NonReducibleUnknown, SingleOrArray } from './typeUtils.ts';\n\n/** @public */\nexport function matchesState(\n parentStateId: StateValue,\n childStateId: StateValue\n): boolean {\n const parentStateValue = toStateValue(parentStateId);\n const childStateValue = toStateValue(childStateId);\n\n if (typeof childStateValue === 'string') {\n if (typeof parentStateValue === 'string') {\n return childStateValue === parentStateValue;\n }\n\n // Parent more specific than child\n return false;\n }\n\n if (typeof parentStateValue === 'string') {\n return parentStateValue in childStateValue;\n }\n\n return Object.keys(parentStateValue).every((key) => {\n if (!(key in childStateValue)) {\n return false;\n }\n\n return matchesState(parentStateValue[key]!, childStateValue[key]!);\n });\n}\n\n/**\n * @internal Throws when a user source name (action, guard, actor or delay)\n * enters the `xstate.` / `@xstate.` namespaces, which are reserved for\n * built-in events, effects and source keys.\n */\nexport function assertUnreservedSourceName(kind: string, name: string): void {\n if (name.startsWith('xstate.') || name.startsWith('@xstate.')) {\n throw new Error(\n isDevelopment\n ? `Invalid ${kind} name '${name}': the 'xstate.' and '@xstate.' prefixes are reserved for built-in names.`\n : xstateError(37, kind, name)\n );\n }\n}\n\n/** Whether a state key contains a `.` that is not escaped as `\\\\.`. */\nexport function hasUnescapedDot(key: string): boolean {\n for (let i = 0; i < key.length; i++) {\n if (key[i] === '\\\\') {\n i++;\n } else if (key[i] === '.') {\n return true;\n }\n }\n return false;\n}\n\nexport function toStatePath(stateId: string | string[]): string[] {\n if (isArray(stateId)) {\n return stateId;\n }\n\n const result: string[] = [];\n let segment = '';\n\n for (let i = 0; i < stateId.length; i++) {\n const char = stateId.charCodeAt(i);\n switch (char) {\n // \\\n case 92:\n // An escaped `.` stays escaped: `foo\\\\.bar` is one path segment, the\n // literal state key `'foo\\\\.bar'`. Other escapes consume the next\n // character.\n segment += stateId[i + 1] === '.' ? '\\\\.' : stateId[i + 1];\n // and skip over it\n i++;\n continue;\n // .\n case 46:\n result.push(segment);\n segment = '';\n continue;\n }\n segment += stateId[i];\n }\n\n result.push(segment);\n\n return result;\n}\n\nfunction toStateValue(stateValue: StateLike<any> | StateValue): StateValue {\n if (isMachineSnapshot(stateValue)) {\n return stateValue.value;\n }\n\n if (typeof stateValue !== 'string') {\n return stateValue as StateValue;\n }\n\n const statePath = toStatePath(stateValue);\n\n return pathToStateValue(statePath);\n}\n\n/** @internal */\nfunction pathToStateValue(statePath: string[]): StateValue {\n if (statePath.length === 1) {\n return statePath[0];\n }\n\n const value: StateValue = {};\n let marker = value;\n\n for (let i = 0; i < statePath.length - 1; i++) {\n if (i === statePath.length - 2) {\n marker[statePath[i]] = statePath[i + 1];\n } else {\n const previous = marker;\n marker = {};\n previous[statePath[i]] = marker;\n }\n }\n\n return value;\n}\n\nexport function mapValues<P, O extends Record<string, unknown>>(\n collection: O,\n iteratee: (item: O[keyof O], key: keyof O, collection: O, i: number) => P\n): { [key in keyof O]: P };\nexport function mapValues(\n collection: Record<string, unknown>,\n iteratee: (\n item: unknown,\n key: string,\n collection: Record<string, unknown>,\n i: number\n ) => unknown\n) {\n const result: Record<string, unknown> = {};\n\n const collectionKeys = Object.keys(collection);\n for (let i = 0; i < collectionKeys.length; i++) {\n const key = collectionKeys[i];\n const value = iteratee(collection[key], key, collection, i);\n if (key === '__proto__') {\n Object.defineProperty(result, key, {\n value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n result[key] = value;\n }\n }\n\n return result;\n}\n\nfunction toArrayStrict<T>(value: readonly T[] | T): readonly T[] {\n if (isArray(value)) {\n return value;\n }\n return [value];\n}\n\nexport function toArray<T>(value: readonly T[] | T | undefined): readonly T[] {\n if (value === undefined) {\n return [];\n }\n return toArrayStrict(value);\n}\n\nexport function resolveOutput<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject\n>(\n mapper:\n | Mapper<TContext, TExpressionEvent, unknown, EventObject>\n | NonReducibleUnknown,\n context: TContext,\n event: TExpressionEvent,\n self: AnyActor,\n input?: Record<string, unknown>\n): unknown {\n if (typeof mapper === 'function') {\n const outputMapper = mapper as Mapper<\n TContext,\n TExpressionEvent,\n unknown,\n EventObject\n >;\n const args = {\n context,\n event,\n output: getEventOutput(event),\n self,\n input\n } as unknown as Parameters<typeof outputMapper>[0];\n\n return outputMapper(args);\n }\n\n if (\n isDevelopment &&\n !!mapper &&\n typeof mapper === 'object' &&\n Object.values(mapper).some((val) => typeof val === 'function')\n ) {\n console.warn(\n `Dynamically mapping values to individual properties is deprecated. Use a single function that returns the mapped object instead.\\nFound object containing properties whose values are possibly mapping functions: ${Object.entries(\n mapper\n )\n .filter(([, value]) => typeof value === 'function')\n .map(\n ([key, value]) =>\n `\\n - ${key}: ${(value as () => any)\n .toString()\n .replace(/\\n\\s*/g, '')}`\n )\n .join('')}`\n );\n }\n\n return mapper;\n}\n\nexport function getEventOutput<TEvent extends EventObject>(\n event: TEvent\n): OutputArg<TEvent>['output'] {\n if (isDoneEvent(event)) {\n const doneEvent = event as unknown as EventObject & { output: unknown };\n return doneEvent.output as OutputArg<TEvent>['output'];\n }\n\n return undefined as OutputArg<TEvent>['output'];\n}\n\nfunction isDoneEvent(event: EventObject): boolean {\n return (\n event.type === 'xstate.done.actor' || event.type === 'xstate.done.state'\n );\n}\n\nfunction isArray(value: any): value is readonly any[] {\n return Array.isArray(value);\n}\n\nexport function isErrorEvent(event: AnyEventObject): event is ErrorEvent {\n return event.type.startsWith('xstate.error.');\n}\n\n/**\n * Normalizes authored transitions to config objects. A bare string target is\n * rejected (the types and `machineFromJSON` reject it too): `name` and\n * `stateId` locate it in the error.\n */\nexport function toTransitionConfigArray(\n configLike: SingleOrArray<AnyTransitionConfig | AnyTransitionConfigFunction>,\n name: string,\n stateId: string\n): Array<AnyTransitionConfig> {\n return toArrayStrict(configLike).map((transitionLike) => {\n // Untyped (JS or JSON-parsed) configs can still contain a string.\n const value: unknown = transitionLike;\n if (typeof value === 'string') {\n throw new Error(\n isDevelopment\n ? `Transition for \"${name}\" in ${stateId ? `state \"${stateId}\"` : 'the root state'} is the string \"${value}\". Use { target: '${value}' }. The @xstate/codemod string-targets transform rewrites these.`\n : xstateError(38, name, stateId, value)\n );\n }\n if (typeof transitionLike === 'undefined') {\n return { target: undefined };\n }\n\n if (typeof transitionLike === 'function') {\n return { to: transitionLike };\n }\n\n return transitionLike;\n });\n}\n\nexport function normalizeTarget<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n target: SingleOrArray<string | StateNode<TContext, TEvent>> | undefined\n): ReadonlyArray<string | StateNode<TContext, TEvent>> | undefined {\n if (target === undefined || target === TARGETLESS_KEY) {\n return undefined;\n }\n return toArray(target);\n}\n\n/** @experimental Used by framework integrations; not part of the stable API. */\nexport function toObserver<T>(\n nextHandler?: Observer<T> | ((value: T) => void),\n errorHandler?: (error: any) => void,\n completionHandler?: () => void\n): Observer<T> {\n const isObserver = typeof nextHandler === 'object';\n const self = isObserver ? nextHandler : undefined;\n\n return {\n next: (isObserver ? nextHandler.next : nextHandler)?.bind(self),\n error: (isObserver ? nextHandler.error : errorHandler)?.bind(self),\n complete: (isObserver ? nextHandler.complete : completionHandler)?.bind(\n self\n ),\n ...(isObserver && nextHandler.passive ? { passive: true } : {})\n };\n}\n\n/**\n * Names a machine in messages: `machine 'shop'`, or `the machine` when it\n * has no id.\n */\nexport function describeMachine(id: string): string {\n return id ? `machine '${id}'` : 'the machine';\n}\n\n/** The implicit id of an invoke: `<stateId>:<index>`, e.g. `loading:0`. */\nexport function createInvokeId(stateNodeId: string, index: number): string {\n return `${stateNodeId}:${index}`;\n}\n\n/** Whether `value` looks like an actor ref (as persisted context detects them). */\nexport function isActorRefLike(value: object): boolean {\n return 'sessionId' in value && 'send' in value && 'ref' in value;\n}\n\n/**\n * Resolves the logic of a persisted child that has no source key: an inline\n * invoke, identified by its id among the invoke definitions of the active\n * state nodes.\n */\nexport function resolveInvokedActorLogic(\n machine: AnyStateMachine,\n nodes: Iterable<AnyStateNode>,\n childId: string\n): AnyActorLogic {\n const definitions: AnyInvokeDefinition[] = [];\n for (const node of nodes) {\n for (const definition of node.invoke) {\n if (definition.id === childId) {\n definitions.push(definition);\n }\n }\n }\n if (definitions.length !== 1) {\n throw new Error(\n isDevelopment\n ? `Unable to restore child actor '${childId}': it has no source key, and ${definitions.length ? 'several active states' : 'no active state'} of ${describeMachine(machine.id)} ${definitions.length ? 'invoke' : 'invokes'} it.`\n : xstateError(39, childId)\n );\n }\n const logic = definitions[0].logic;\n if (typeof logic === 'string') {\n const registered = machine.sources.actors[logic];\n if (!registered) {\n throw new Error(\n isDevelopment\n ? `Unable to restore child actor '${childId}': child source '${logic}' is not provided in ${describeMachine(machine.id)}.`\n : xstateError(29, childId, logic)\n );\n }\n return registered;\n }\n if (typeof logic === 'function') {\n throw new Error(\n isDevelopment\n ? `Unable to restore child actor '${childId}': its invoke resolves \\`src\\` with a function that returned inline logic. Register the logic in \\`actors\\` and return its key so the child persists by source key.`\n : xstateError(40, childId)\n );\n }\n return logic;\n}\n\n/**\n * Returns one event per transition of the active state nodes of `snapshot`,\n * including the internal events for invoked actors (`xstate.done.actor`,\n * `xstate.error.actor`) and delayed transitions (`xstate.after`). Graph\n * traversal sends these when the `events` option is not given.\n *\n * @public\n */\nexport function getAllOwnEvents(snapshot: AnyMachineSnapshot) {\n const events = snapshot.nodes.flatMap((stateNode) =>\n [...stateNode.transitions.values()].flatMap((transitions) =>\n transitions.map((transition) => {\n const event: AnyEventObject = {\n type: transition.eventType,\n ...transition.matches\n };\n if (\n 'actorId' in event &&\n (event.type === 'xstate.done.actor' ||\n event.type === 'xstate.error.actor' ||\n event.type === 'xstate.snapshot.actor' ||\n event.type === 'xstate.timeout.actor')\n ) {\n event.sessionId = snapshot.children[event.actorId]?.sessionId;\n }\n return event;\n })\n )\n );\n return events.filter(\n (event, index) =>\n events.findIndex((candidate) => {\n const keys = Object.keys(event);\n return (\n keys.length === Object.keys(candidate).length &&\n keys.every((key) => Object.is(event[key], candidate[key]))\n );\n }) === index\n );\n}\n\nexport function matchesEvent(\n event: EventObject,\n pattern: Record<string, unknown>\n): boolean {\n return Object.entries(pattern).every(([key, value]) =>\n Object.is((event as AnyEventObject)[key], value)\n );\n}\n\n/**\n * Checks if an event type matches an event descriptor, supporting wildcards.\n * Event descriptors can be:\n *\n * - Exact matches: \"event.type\"\n * - Wildcard: \"*\"\n * - Partial matches: \"event.*\"\n *\n * @param eventType - The actual event type string\n * @param descriptor - The event descriptor to match against\n * @returns True if the event type matches the descriptor\n */\nexport function matchesEventDescriptor(\n eventType: string,\n descriptor: string\n): boolean {\n if (descriptor === eventType) {\n return true;\n }\n\n if (descriptor === WILDCARD) {\n return true;\n }\n\n if (!descriptor.endsWith('.*')) {\n return false;\n }\n\n if (isDevelopment && /.*\\*.+/.test(descriptor)) {\n console.warn(\n `Wildcards can only be the last token of an event descriptor (e.g., \"event.*\") or the entire event descriptor (\"*\"). Check the \"${descriptor}\" event.`\n );\n }\n\n const partialEventTokens = descriptor.split('.');\n const eventTokens = eventType.split('.');\n\n for (\n let tokenIndex = 0;\n tokenIndex < partialEventTokens.length;\n tokenIndex++\n ) {\n const partialEventToken = partialEventTokens[tokenIndex];\n const eventToken = eventTokens[tokenIndex];\n\n if (partialEventToken === '*') {\n const isLastToken = tokenIndex === partialEventTokens.length - 1;\n\n if (isDevelopment && !isLastToken) {\n console.warn(\n `Infix wildcards in transition events are not allowed. Check the \"${descriptor}\" transition.`\n );\n }\n\n return isLastToken;\n }\n\n if (partialEventToken !== eventToken) {\n return false;\n }\n }\n\n return true;\n}\n","import isDevelopment from '#is-development';\nimport { xstateError } from './xstateError.ts';\nimport { protectSelectionRelay } from './transitionSelection.ts';\nimport type { InspectionEvent, SentRecord } from './inspection.ts';\nimport type { StandardSchemaV1 } from './schema.types.ts';\nimport type { InternalActorOptions } from './createActor.ts';\nimport {\n AnyEventObject,\n ActorTermination,\n ActorSystemInfo,\n AnyActor,\n Observer,\n EventObject,\n Subscription,\n AnyActorLogic,\n LogicalTimer,\n TimerKey\n} from './types.ts';\nimport type { HomomorphicOmit } from './typeUtils.ts';\nimport { XSTATE_TIMER } from './constants.ts';\nimport { getScheduledTimerKey, matchesTimerKey } from './timerKey.ts';\nimport { toObserver } from './utils.ts';\nimport { reportUnhandledError } from './reportUnhandledError.ts';\nimport { getAmbientInspector } from './inspectionAmbient.ts';\nimport { markSystemSnapshotDirty } from './snapshotActorRef.ts';\nimport {\n createMissingAddressError,\n isSerializedActorRef,\n resolveSerializedActorRef,\n getAddressId\n} from './remoteActorRef.ts';\nimport {\n rejectUndeliverableEvent,\n deliverEvent,\n stopActor as stopActorLocally,\n terminateActor as terminateActorLocally,\n runStep\n} from './runtimeHelpers.ts';\n\ninterface ScheduledTimer {\n key: TimerKey;\n scheduledAt: number;\n dueAt: number;\n delay: number;\n source: AnyActor;\n}\n\nexport interface Clock {\n /** Returns the clock's current time in milliseconds. */\n now?(): number;\n setTimeout(fn: (...args: any[]) => void, timeout: number): any;\n clearTimeout(id: any): void;\n}\n\ninterface Scheduler {\n schedule(source: AnyActor, key: TimerKey, delay: number): void;\n cancel(source: AnyActor, key: TimerKey): void;\n cancelAll(actor: AnyActor): void;\n}\n\nlet executionIdPrefix: string | undefined;\nlet nextExecutionId = 0;\n\nfunction createExecutionIdPrefix(): string {\n let crypto: Crypto | undefined;\n try {\n crypto = globalThis.crypto;\n } catch {\n // Use the process-local fallback below.\n }\n\n if (crypto?.getRandomValues) {\n try {\n const values = new Uint32Array(4);\n crypto.getRandomValues(values);\n return Array.from(values, (value) =>\n value.toString(36).padStart(7, '0')\n ).join('');\n } catch {\n // Try randomUUID next.\n }\n }\n\n if (crypto?.randomUUID) {\n try {\n return crypto.randomUUID().replaceAll('-', '');\n } catch {\n // Use the process-local fallback below.\n }\n }\n\n return `xstate-${Date.now().toString(36)}-${Math.random()\n .toString(36)\n .slice(2)}`;\n}\n\nfunction createExecutionId(): string {\n executionIdPrefix ??= createExecutionIdPrefix();\n return `${executionIdPrefix}:${(nextExecutionId++).toString(36)}`;\n}\n\n/**\n * The identity a durable execution pins on every system its transitions\n * create. Shared across all transitions (and replays) of one execution, so\n * session ids become a deterministic function of actor-creation order:\n * `<executionId>:0`, `<executionId>:1`, … A replayed execution re-creates\n * the same session ids, so journaled completion events (which carry the\n * producing incarnation's `sessionId`) still match the children the replay\n * re-creates.\n */\nexport interface ExecutionIdentity {\n executionId: string;\n nextSessionId: number;\n}\n\nlet ambientExecutionIdentity: ExecutionIdentity | undefined;\n\n/** @internal Runs `fn` with systems it creates pinned to `identity`. */\nexport function withExecutionIdentity<T>(\n identity: ExecutionIdentity | undefined,\n fn: () => T\n): T {\n if (!identity) {\n return fn();\n }\n const previous = ambientExecutionIdentity;\n ambientExecutionIdentity = identity;\n try {\n return fn();\n } finally {\n ambientExecutionIdentity = previous;\n }\n}\n\n/** @internal */\nexport {\n hasAmbientInspector,\n withSystemInspector\n} from './inspectionAmbient.ts';\n\n/**\n * Derives the deterministic id prefix for a generated actor id from its actor\n * source: the registered source key when the source is a string, the logic's\n * own `id` otherwise, with `x` as the last-resort prefix.\n *\n * @internal\n */\nexport function getActorIdPrefix(\n src: string | AnyActorLogic | undefined\n): string {\n if (typeof src === 'string') {\n return src;\n }\n const logicId = (src as { id?: unknown } | undefined)?.id;\n // Only named logic earns a named id prefix; machines without an id have\n // the empty id.\n return typeof logicId === 'string' && logicId.length ? logicId : 'x';\n}\n\n/**\n * Encodes one actor id as an address segment. `/` separates segments, so it\n * is percent-encoded, and the escape character `%` is escaped first so the\n * encoding stays injective: the ids 'a/b' and 'a%2Fb' must not produce the\n * same address.\n *\n * @internal\n */\nexport function encodeAddressSegment(id: string): string {\n return id.includes('/') || id.includes('%')\n ? id.replaceAll('%', '%25').replaceAll('/', '%2F')\n : id;\n}\n\n/**\n * Parses a generated-shaped actor id (`prefix:<n>`). This single definition is\n * the determinism contract for id reservation: live allocation, replay, and\n * restore must all agree on what counts as generated-shaped. Deliberately\n * broader than ids a generated allocation could produce — over-reserving\n * skips numbers, which is harmless, while under-reserving could collide.\n *\n * @internal\n */\nexport function parseGeneratedActorId(\n id: string\n): { prefix: string; index: number } | undefined {\n const separator = id.lastIndexOf(':');\n if (separator <= 0 || separator === id.length - 1) {\n return undefined;\n }\n const index = Number(id.slice(separator + 1));\n return Number.isSafeInteger(index) && index >= 0\n ? { prefix: id.slice(0, separator), index }\n : undefined;\n}\n\n/**\n * The id (and address root segment) of the first parentless actor of a logic:\n * the logic's own name, or `x:0` for anonymous logic.\n *\n * @internal\n */\nexport function getRootActorId(\n src: string | AnyActorLogic | undefined\n): string {\n const prefix = getActorIdPrefix(src);\n return prefix === 'x' ? 'x:0' : prefix;\n}\n\nfunction getActorIdCounterKey(\n parent: AnyActor | undefined,\n prefix: string\n): string {\n return `${parent ? parent.address : ''}|${prefix}`;\n}\n\nfunction bumpActorIdCounter(\n system: AnyActorSystem,\n counterKey: string,\n next: number\n): void {\n const counters = system._snapshot._nextActorIds;\n if ((counters[counterKey] ?? 0) >= next) {\n return;\n }\n // Copy-on-write: snapshot systems share this record by shallow `_snapshot`\n // copies, so branches must not observe each other's allocations.\n system._snapshot._nextActorIds = { ...counters, [counterKey]: next };\n markSystemSnapshotDirty(system);\n}\n\n/** @internal */\nexport function resolveActorId(\n system: AnyActorSystem,\n requestedId: string | undefined,\n options?: {\n parent?: AnyActor;\n src?: string | AnyActorLogic;\n }\n): string {\n if (requestedId !== undefined) {\n const generated = parseGeneratedActorId(requestedId);\n if (generated) {\n bumpActorIdCounter(\n system,\n getActorIdCounterKey(options?.parent, generated.prefix),\n generated.index + 1\n );\n } else if (!options?.parent) {\n // Reserve a restored root's bare name so a later parentless actor of\n // the same logic in this system numbers past it.\n bumpActorIdCounter(\n system,\n getActorIdCounterKey(undefined, requestedId),\n 1\n );\n }\n return requestedId;\n }\n\n const prefix = getActorIdPrefix(options?.src);\n const counterKey = getActorIdCounterKey(options?.parent, prefix);\n const counter = system._snapshot._nextActorIds[counterKey] ?? 0;\n bumpActorIdCounter(system, counterKey, counter + 1);\n // The first parentless actor of a logic gets the logic's own name; later\n // parentless actors of the same logic in a shared system get numbered so\n // addresses stay unique.\n return !options?.parent && prefix !== 'x' && counter === 0\n ? prefix\n : `${prefix}:${counter}`;\n}\n\n/** @internal */\nexport function bookSessionId(system: AnyActorSystem): string {\n return `${system._identity.executionId}:${system._identity.nextSessionId++}`;\n}\n\n/**\n * Runtime operations used to execute effects.\n *\n * XState calculates pure transitions; a runtime executes their effects. The\n * built-in local runtime is one implementation at the same level as any\n * other: install a different one via `system.runtime` (for durable hosts,\n * through `createDurable`'s adapter runtime operations).\n */\n/**\n * Why an event was not delivered: `'invalidEvent'` (payload failed its\n * declared schema), `'internalEvent'` (an internal event type sent from\n * outside its owning actor), `'stopped'` (the target actor already stopped)\n * or `'missingTarget'` (`enq.sendTo` received an undefined ref, an unknown\n * child id, or the `parent` of a root actor). Hosts may report additional\n * reasons.\n *\n * @public\n */\nexport type EventRejectionReason =\n | 'invalidEvent'\n | 'internalEvent'\n | 'stopped'\n | 'missingTarget'\n | (string & {});\n\n/**\n * Extra detail attached to a dead letter.\n *\n * @public\n */\nexport interface DeadLetterDetail {\n /** Standard Schema issues for `invalidEvent` rejections. */\n issues?: readonly StandardSchemaV1.Issue[];\n /** The underlying error describing the rejection. */\n error?: Error;\n /**\n * The unresolved target id for `missingTarget` rejections (the child id\n * passed to `enq.sendTo`), when one was given.\n */\n targetId?: string | undefined;\n}\n\n/**\n * Describes an event that was rejected at the delivery boundary instead of\n * being delivered to its target actor (a dead letter).\n *\n * @public\n */\nexport interface EventRejection extends DeadLetterDetail {\n /** The event that was rejected. */\n event: AnyEventObject;\n /** The actor the event was addressed to. */\n targetRef: AnyActor | undefined;\n /** The `id` of the target actor. */\n targetId: string | undefined;\n /** The actor that sent the event, or `undefined` for an external send. */\n sourceRef: AnyActor | undefined;\n /** Whether the event came from outside the system or from another actor. */\n eventOrigin: 'external' | 'actor';\n reason: EventRejectionReason;\n}\n\n/** @public */\nexport interface ActorEmission {\n actorRef: AnyActor;\n event: AnyEventObject;\n}\n\n/** @experimental */\nexport interface ActorSystemRuntime {\n /** Publishes a newly created actor to the runtime. */\n spawnActor(\n source: AnyActor | undefined,\n actor: AnyActor\n ): void | PromiseLike<void>;\n /** Starts an actor. */\n startActor(actor: AnyActor): void | PromiseLike<void>;\n /** Stops an actor without producing a completion result. */\n stopActor(actor: AnyActor): void | PromiseLike<void>;\n /** Completes or errors an actor and publishes its terminal result. */\n terminateActor(\n actor: AnyActor,\n termination: ActorTermination\n ): void | PromiseLike<void>;\n /** Delivers an event between actors. */\n sendEvent(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n ): void | PromiseLike<void>;\n /** Delivers an emitted event, after system emission observers have run. */\n emitEvent(source: AnyActor, event: EventObject): void | PromiseLike<void>;\n /**\n * Schedules a logical timer. `source.address` and `timer` identify it; when\n * it fires, deliver `{ type: 'xstate.timer', ...timer }` to `source`.\n */\n scheduleTimer(\n source: AnyActor,\n timer: TimerKey,\n delay: number\n ): void | PromiseLike<void>;\n /** Cancels one logical timer. */\n cancelTimer(source: AnyActor, timer: TimerKey): void | PromiseLike<void>;\n /**\n * Runs an async actor's entire body as one durable unit. The actor is the\n * natural journal entry: its identity — `address`, string `src` key and\n * serializable `input` — crosses any boundary, so a host can wrap `exec`\n * in its own step primitive, or ignore `exec` entirely and re-run the\n * registered logic on a remote executor from `(src, input)` alone. The\n * default runs the body in this process, unjournaled.\n *\n * Like `runStep`, this is an orchestration frame: it may span external\n * events and must never be serialized behind other runtime operations.\n */\n runLogic(\n actor: AnyActor,\n exec: () => PromiseLike<unknown>\n ): PromiseLike<unknown>;\n /**\n * Runs one keyed step of an async actor (`enq.step`). The default journals\n * the result in the actor's own snapshot; a durable host implements this\n * to journal steps in its own journal instead — memoized results replay\n * without re-running `exec`.\n *\n * Unlike other runtime operations, a step is an orchestration frame that\n * may itself await runtime operations, so implementations must not\n * serialize it behind them.\n */\n runStep(\n actor: AnyActor,\n key: string,\n exec: () => unknown | PromiseLike<unknown>\n ): unknown | PromiseLike<unknown>;\n /**\n * Reports an undeliverable event. Delivery stays at-most-once — this is\n * observability, not retry. The system always calls its\n * `onRejectedEvent` listeners first; the default then logs in development.\n * `detail` carries validation issues and the underlying error for events\n * rejected at the delivery boundary.\n */\n deadLetter(\n source: AnyActor | undefined,\n target: AnyActor | undefined,\n event: AnyEventObject,\n reason: EventRejectionReason,\n detail?: DeadLetterDetail\n ): void | PromiseLike<void>;\n /** Cancels all logical timers owned by an actor. */\n cancelAllTimers(source: AnyActor): void | PromiseLike<void>;\n}\n\n/** @internal Every operation of `ActorSystemRuntime`, for runtime wrappers. */\nexport const RUNTIME_OPERATIONS = [\n 'spawnActor',\n 'startActor',\n 'stopActor',\n 'terminateActor',\n 'emitEvent',\n 'scheduleTimer',\n 'cancelTimer',\n 'cancelAllTimers',\n 'deadLetter'\n // `runLogic`, `runStep` and `sendEvent` are deliberately absent: durable\n // executions wire them separately, since logic bodies and steps await\n // other runtime operations and root-addressed sends are captured per\n // batch.\n] as const satisfies readonly (keyof ActorSystemRuntime)[];\n\ntype ScheduledTimerId = string & { __scheduledTimerId: never };\n\nconst emptyScheduledTimers = Object.freeze(\n {}\n) as ActorSystem<any>['_snapshot']['_scheduledTimers'];\n\nfunction createScheduledTimerId(\n actor: AnyActor,\n key: TimerKey\n): ScheduledTimerId {\n return getScheduledTimerKey(actor, key) as ScheduledTimerId;\n}\n\nfunction findLogicalTimer(\n source: AnyActor,\n key: TimerKey\n): LogicalTimer | undefined {\n return (\n source.getSnapshot()?.timers as readonly LogicalTimer[] | undefined\n )?.find((timer) => matchesTimerKey(timer, key));\n}\n\n/** @public */\nexport interface ActorSystem<\n T extends ActorSystemInfo\n> extends ActorSystemRuntime {\n /** @internal Allocates an actor reference during snapshot calculation. */\n createActorRef(\n logic: AnyActorLogic,\n options: InternalActorOptions<AnyActorLogic>\n ): AnyActor;\n /** @internal */\n children: Map<string, AnyActor>;\n /** @internal Avoids materializing the registered-actor map. */\n _getRootActor?: () => AnyActor | undefined;\n /** @internal Avoids materializing the registered-actor map. */\n _peekChildren?: () => Map<string, AnyActor> | undefined;\n /** @internal */\n reverseKeyedActors: WeakMap<AnyActor, keyof T['actors']>;\n /** @internal */\n keyedActors: Map<keyof T['actors'], AnyActor | undefined>;\n /** @internal */\n _peekKeyedActors?: () =>\n | Map<keyof T['actors'], AnyActor | undefined>\n | undefined;\n /**\n * @internal Returns the live actor at a logical address, if any. Resolves\n * serialized actor refs used as send targets.\n */\n _getByAddress?: (address: string) => AnyActor | undefined;\n /** @internal */\n _register: (sessionId: string, actor: AnyActor) => string;\n /** @internal */\n _unregister: (actor: AnyActor) => void;\n /** @internal */\n _set: <K extends keyof T['actors']>(key: K, actor: AnyActor) => void;\n get: <K extends keyof T['actors']>(key: K) => T['actors'][K] | undefined;\n getAll: () => Partial<T['actors']>;\n\n inspect: (\n observer:\n | Observer<InspectionEvent>\n | ((inspectionEvent: InspectionEvent) => void)\n ) => Subscription;\n /**\n * Subscribes to events the system could not deliver (dead letters): sends\n * to a stopped actor, events rejected at the delivery boundary\n * and internal events sent from outside their owner. Listeners run in\n * registration order; a listener that throws does not prevent the others.\n * The `onRejectedEvent` option on `createActor` registers a listener the\n * same way.\n *\n * @public\n */\n onRejectedEvent: (\n listener: (rejection: EventRejection) => void\n ) => Subscription;\n /**\n * Observes emitted events from every actor in this system, before runtime\n * delivery. Listeners run in registration order; errors do not prevent\n * other listeners or delivery. Unsubscribe to stop observing.\n *\n * @public\n */\n onEmitted: (listener: (emission: ActorEmission) => void) => Subscription;\n /** @internal */\n _notifyEmitted: (actorRef: AnyActor, event: AnyEventObject) => void;\n /** @internal Avoids collecting inspection-only transition metadata. */\n _hasInspectionObservers?: () => boolean;\n /** @internal */\n _sendInspectionEvent: (\n event: HomomorphicOmit<InspectionEvent, 'rootId'>\n ) => void;\n /** @internal */\n _relay: (\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n ) => void | PromiseLike<void>;\n scheduler: Scheduler;\n getSnapshot: () => {\n _scheduledTimers: Record<string, ScheduledTimer>;\n };\n /**\n * Runtime identity shared by every snapshot view of this actor system.\n *\n * @internal\n */\n _identity: {\n executionId: string;\n nextSessionId: number;\n };\n /** @internal */\n _snapshot: {\n _scheduledTimers: Record<ScheduledTimerId, ScheduledTimer>;\n /** Deterministic generated-id counters keyed by `${parentAddress}|${srcPrefix}`. */\n _nextActorIds: Record<string, number>;\n };\n /** @internal */\n _snapshotVersion: number;\n start: () => void;\n _clock: Clock;\n _logger: (...args: any[]) => void;\n /**\n * The runtime executing this system's effects. When unset, the built-in\n * local in-memory runtime runs them; `createActor(machine).start()` is just\n * that built-in runtime. A host runtime installed here applies to every\n * actor in the system — snapshot-scoped views and children created later\n * included — and may implement any subset of operations, with the rest\n * keeping the built-in behavior.\n *\n * An operation that returns a promise owns its own failure handling: the\n * paths that hand work to a runtime do not await it. `createDurable`\n * tracks its adapter's operations and fails `executeEffects` when one\n * rejects.\n *\n * Durable hosts should provide this through `createDurable`'s\n * adapter runtime operations rather than assigning it directly.\n */\n runtime?: Partial<ActorSystemRuntime>;\n}\n\n/** @public */\nexport type AnyActorSystem = ActorSystem<any>;\n\n// These optional lazy fields intentionally have no emitted initializers.\n// oxlint-disable-next-line typescript/no-unsafe-declaration-merging\ninterface RuntimeSystem<T extends ActorSystemInfo> {\n runtime?: Partial<ActorSystemRuntime>;\n _children?: Map<string, AnyActor>;\n _keyedActors?: Map<keyof T['actors'], AnyActor | undefined>;\n _reverseKeyedActors?: WeakMap<AnyActor, keyof T['actors']>;\n _inspectionObservers?: Set<Observer<InspectionEvent>>;\n _timerMap?: { [id: ScheduledTimerId]: number };\n _rejectionListeners?: Set<(rejection: EventRejection) => void>;\n _emissionListeners?: Set<(emission: ActorEmission) => void>;\n}\n\nclass RuntimeSystem<T extends ActorSystemInfo> implements ActorSystem<T> {\n public _identity = ambientExecutionIdentity ?? {\n executionId: createExecutionId(),\n nextSessionId: 0\n };\n public _snapshot: ActorSystem<T>['_snapshot'];\n public _snapshotVersion = 0;\n public scheduler: Scheduler = this;\n public _clock: Clock;\n public _logger: (...args: any[]) => void;\n public createActorRef: ActorSystem<T>['createActorRef'];\n\n public get children(): Map<string, AnyActor> {\n const children = (this._children ??= new Map());\n if (this._getRootActor()) {\n children.set(this._rootActor.sessionId, this._rootActor);\n }\n return children;\n }\n\n public set children(children: Map<string, AnyActor>) {\n this._children = children;\n }\n\n public _getRootActor(): AnyActor | undefined {\n return this._rootActor._isRunning() ? this._rootActor : undefined;\n }\n\n public _peekChildren(): Map<string, AnyActor> | undefined {\n return this._children;\n }\n\n public get keyedActors(): Map<keyof T['actors'], AnyActor | undefined> {\n return (this._keyedActors ??= new Map());\n }\n\n public set keyedActors(actors: Map<keyof T['actors'], AnyActor | undefined>) {\n this._keyedActors = actors;\n }\n\n public get reverseKeyedActors(): WeakMap<AnyActor, keyof T['actors']> {\n return (this._reverseKeyedActors ??= new WeakMap());\n }\n\n public set reverseKeyedActors(actors: WeakMap<AnyActor, keyof T['actors']>) {\n this._reverseKeyedActors = actors;\n }\n\n /** @internal Avoids materializing the receptionist for empty systems. */\n public _peekKeyedActors():\n | Map<keyof T['actors'], AnyActor | undefined>\n | undefined {\n return this._keyedActors;\n }\n\n constructor(\n private _rootActor: AnyActor,\n options: {\n clock: Clock;\n logger: (...args: any[]) => void;\n createActorRef: ActorSystem<T>['createActorRef'];\n }\n ) {\n this._clock = options.clock;\n this._logger = options.logger;\n this.createActorRef = options.createActorRef;\n const ambientInspector = getAmbientInspector();\n if (ambientInspector) {\n this.inspect(ambientInspector);\n }\n this._snapshot = {\n _scheduledTimers: emptyScheduledTimers,\n // System-level counters are process-local backstops; per-actor\n // counters persist on each machine snapshot, and restored explicit ids\n // reserve their numbering here via `resolveActorId`.\n _nextActorIds: {}\n };\n }\n\n // Records a send on the *sender's* transition for the `sent[]` inspection\n // facet. Captures the send when it is initiated (including delayed sends that\n // may never deliver), keyed to the source actor's in-flight transition.\n private _recordSent(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject,\n delay?: number,\n id?: string\n ): void {\n if (!this._inspectionObservers?.size || !source) {\n return;\n }\n const inspectionSource = source as AnyActor & {\n _collectedSent?: SentRecord[];\n };\n const collected = (inspectionSource._collectedSent ??= []);\n collected.push({\n targetRef: target,\n targetId: target.id,\n event,\n delay,\n id\n });\n }\n\n public schedule(source: AnyActor, key: TimerKey, delay: number): void {\n const scheduledTimerId = createScheduledTimerId(source, key);\n if (this._timerMap?.[scheduledTimerId] !== undefined) {\n this.cancel(source, key);\n }\n\n const timer = findLogicalTimer(source, key);\n if (timer) {\n const target = timer.target === 'self' ? source : timer.target;\n this._recordSent(source, target, timer.event, delay, timer.id);\n }\n\n const scheduledAt = this._clock.now?.() ?? Date.now();\n const scheduledTimer: ScheduledTimer = {\n source,\n delay,\n key,\n scheduledAt,\n dueAt: scheduledAt + delay\n };\n if (this._snapshot._scheduledTimers === emptyScheduledTimers) {\n this._snapshot._scheduledTimers = {};\n }\n this._snapshot._scheduledTimers[scheduledTimerId] = scheduledTimer;\n markSystemSnapshotDirty(this);\n\n const timeout = this._clock.setTimeout(() => {\n if (this._timerMap) {\n delete this._timerMap[scheduledTimerId];\n }\n delete this._snapshot._scheduledTimers[scheduledTimerId];\n markSystemSnapshotDirty(this);\n\n this._deliver(source, source, { type: XSTATE_TIMER, ...key });\n }, delay);\n\n (this._timerMap ??= {})[scheduledTimerId] = timeout;\n }\n\n public cancel(source: AnyActor, key: TimerKey): void {\n const scheduledTimerId = createScheduledTimerId(source, key);\n const timeout = this._timerMap?.[scheduledTimerId];\n\n if (this._timerMap) {\n delete this._timerMap[scheduledTimerId];\n }\n if (this._snapshot._scheduledTimers !== emptyScheduledTimers) {\n delete this._snapshot._scheduledTimers[scheduledTimerId];\n }\n markSystemSnapshotDirty(this);\n\n if (timeout !== undefined) {\n this._clock.clearTimeout(timeout);\n }\n }\n\n public cancelAll(actor: AnyActor): void {\n for (const scheduledTimerId in this._snapshot._scheduledTimers) {\n const scheduledTimer =\n this._snapshot._scheduledTimers[scheduledTimerId as ScheduledTimerId];\n if (scheduledTimer.source === actor) {\n this.cancel(actor, scheduledTimer.key);\n }\n }\n }\n\n // Delivers an event to the target actor. Used by both `_relay` (which also\n // records the send) and the scheduler's timer (which already recorded it).\n private _deliver(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n ): void {\n deliverEvent(source, target, event);\n }\n\n public _register(sessionId: string, actor: AnyActor): string {\n if (actor === this._rootActor) {\n this._children?.set(sessionId, actor);\n } else {\n (this._children ??= new Map()).set(sessionId, actor);\n }\n markSystemSnapshotDirty(this);\n return sessionId;\n }\n\n public _getByAddress(address: string): AnyActor | undefined {\n const root = this._getRootActor();\n if (root?.address === address) {\n return root;\n }\n for (const actor of this._children?.values() ?? []) {\n if (actor.address === address && actor._isRunning()) {\n return actor;\n }\n }\n return undefined;\n }\n\n public _unregister(actor: AnyActor): void {\n let changed: boolean;\n // Remote handles have no sessionId and are never in the session map;\n // their registry cleanup happens through the keyed-actor path below.\n if (actor === this._rootActor) {\n changed = this._getRootActor() !== undefined;\n changed =\n (actor.sessionId !== undefined &&\n (this._children?.delete(actor.sessionId) ?? false)) ||\n changed;\n } else {\n changed =\n actor.sessionId !== undefined &&\n (this._children?.delete(actor.sessionId) ?? false);\n }\n const registryKey = this._reverseKeyedActors?.get(actor);\n\n if (registryKey !== undefined) {\n if (this._keyedActors?.get(registryKey) === actor) {\n this._keyedActors.delete(registryKey);\n changed = true;\n }\n this._reverseKeyedActors?.delete(actor);\n }\n if (changed) {\n markSystemSnapshotDirty(this);\n }\n }\n\n public get<K extends keyof T['actors']>(\n registryKey: K\n ): T['actors'][K] | undefined {\n return this._keyedActors?.get(registryKey) as T['actors'][K] | undefined;\n }\n\n public getAll(): Partial<T['actors']> {\n return Object.fromEntries(this._keyedActors?.entries() ?? []) as Partial<\n T['actors']\n >;\n }\n\n public _set<K extends keyof T['actors']>(\n registryKey: K,\n actor: AnyActor\n ): void {\n const existing = this._keyedActors?.get(registryKey);\n if (existing && existing !== actor) {\n throw new Error(\n isDevelopment\n ? `Actor with registry key '${registryKey as string}' already exists.`\n : xstateError(45, String(registryKey))\n );\n }\n\n (this._keyedActors ??= new Map()).set(registryKey, actor);\n (this._reverseKeyedActors ??= new WeakMap()).set(actor, registryKey);\n if (existing !== actor) {\n markSystemSnapshotDirty(this);\n }\n }\n\n public inspect(\n observerOrFn:\n | Observer<InspectionEvent>\n | ((inspectionEvent: InspectionEvent) => void)\n ): Subscription {\n const observer = toObserver(observerOrFn);\n (this._inspectionObservers ??= new Set()).add(observer);\n\n return {\n unsubscribe: () => {\n this._inspectionObservers?.delete(observer);\n }\n };\n }\n\n public onRejectedEvent(\n listener: (rejection: EventRejection) => void\n ): Subscription {\n // Wrap so the same function registered twice gets two subscriptions.\n const entry = (rejection: EventRejection) => listener(rejection);\n (this._rejectionListeners ??= new Set()).add(entry);\n return {\n unsubscribe: () => {\n this._rejectionListeners?.delete(entry);\n }\n };\n }\n\n public onEmitted(listener: (emission: ActorEmission) => void): Subscription {\n const entry = (emission: ActorEmission) => listener(emission);\n (this._emissionListeners ??= new Set()).add(entry);\n return {\n unsubscribe: () => {\n this._emissionListeners?.delete(entry);\n }\n };\n }\n\n public _notifyEmitted(actorRef: AnyActor, event: AnyEventObject): void {\n const listeners = this._emissionListeners;\n if (!listeners?.size) {\n return;\n }\n const emission: ActorEmission = { actorRef, event };\n for (const listener of Array.from(listeners)) {\n try {\n listener(emission);\n } catch (err) {\n reportUnhandledError(err);\n }\n }\n }\n\n public _hasInspectionObservers(): boolean {\n return !!this._inspectionObservers?.size;\n }\n\n public _sendInspectionEvent(\n event: HomomorphicOmit<InspectionEvent, 'rootId'>\n ): void {\n if (!this._inspectionObservers?.size) {\n return;\n }\n const resolvedInspectionEvent: InspectionEvent = {\n ...event,\n rootId: this._rootActor.sessionId!\n };\n this._inspectionObservers.forEach((observer) => {\n try {\n observer.next?.(resolvedInspectionEvent);\n } catch (err) {\n reportUnhandledError(err);\n }\n });\n }\n\n // Unlike the other operations, spawn has no local work: local actors\n // register with the system when they are constructed, so this only\n // notifies a host runtime.\n public spawnActor(\n source: AnyActor | undefined,\n actor: AnyActor\n ): void | PromiseLike<void> {\n return this.runtime?.spawnActor?.(source, actor);\n }\n\n public startActor(actor: AnyActor): void | PromiseLike<void> {\n const override = this.runtime?.startActor;\n if (override) {\n return override(actor);\n }\n actor.start();\n }\n\n public stopActor(actor: AnyActor): void | PromiseLike<void> {\n const override = this.runtime?.stopActor;\n if (override) {\n return override(actor);\n }\n stopActorLocally(actor);\n }\n\n public terminateActor(\n actor: AnyActor,\n termination: ActorTermination\n ): void | PromiseLike<void> {\n const override = this.runtime?.terminateActor;\n if (override) {\n return override(actor, termination);\n }\n terminateActorLocally(actor, termination);\n }\n\n public sendEvent(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n ): void | PromiseLike<void> {\n if (isSerializedActorRef(target)) {\n // A ref that went through JSON resolves by address to the live actor.\n // A host runtime may own actors this system cannot see, so an\n // unresolved address is its to route; locally it is a dead letter.\n const live = resolveSerializedActorRef(this, target);\n if (live) {\n target = live;\n } else if (\n // A live actor of another incarnation is stale locally; an\n // address this system cannot see may belong to a host runtime.\n this._getByAddress(target.$actor) ||\n !this.runtime?.sendEvent\n ) {\n return this.deadLetter(source, undefined, event, 'missingTarget', {\n targetId: getAddressId(target.$actor),\n error: createMissingAddressError(target)\n });\n }\n }\n if (rejectUndeliverableEvent(source, target, event)) {\n return;\n }\n // Record for the inspection `sent[]` facet regardless of which runtime\n // delivers, so host runtimes keep inspection parity.\n this._recordSent(source, target, event);\n const override = this.runtime?.sendEvent;\n if (override) {\n return override(source, target, event);\n }\n this._deliver(source, target, event);\n }\n\n public emitEvent(\n source: AnyActor,\n event: EventObject\n ): void | PromiseLike<void> {\n const override = this.runtime?.emitEvent;\n if (override) {\n return override(source, event);\n }\n (source as AnyActor & { _emit(value: EventObject): void })._emit(event);\n }\n\n public deadLetter(\n source: AnyActor | undefined,\n target: AnyActor | undefined,\n event: AnyEventObject,\n reason: EventRejectionReason,\n detail?: DeadLetterDetail\n ): void | PromiseLike<void> {\n const listeners = this._rejectionListeners;\n if (listeners?.size) {\n const rejection: EventRejection = {\n event,\n targetRef: target,\n targetId: target?.id ?? detail?.targetId,\n sourceRef: source,\n eventOrigin: source ? 'actor' : 'external',\n reason,\n issues: detail?.issues,\n error: detail?.error\n };\n // Snapshot so listeners added or removed during delivery do not affect\n // this rejection.\n for (const listener of [...listeners]) {\n try {\n listener(rejection);\n } catch (err) {\n reportUnhandledError(err);\n }\n }\n }\n const override = this.runtime?.deadLetter;\n if (override) {\n return override(source, target, event, reason, detail);\n }\n if (isDevelopment) {\n console.warn(\n target\n ? `Event \"${event.type}\" to actor \"${target.id}\" was not delivered (${reason}).`\n : `Actor \"${source?.id}\" sent event \"${event.type}\" to missing target ${\n detail?.targetId !== undefined\n ? `\"${detail.targetId}\"`\n : 'undefined'\n }; the event was not delivered (${reason}).`\n );\n }\n }\n\n public runStep(\n actor: AnyActor,\n key: string,\n exec: () => unknown | PromiseLike<unknown>\n ): unknown | PromiseLike<unknown> {\n const override = this.runtime?.runStep;\n if (override) {\n return override(actor, key, exec);\n }\n return runStep(actor, key, exec);\n }\n\n public runLogic(\n actor: AnyActor,\n exec: () => PromiseLike<unknown>\n ): PromiseLike<unknown> {\n const override = this.runtime?.runLogic;\n if (override) {\n return override(actor, exec);\n }\n return exec();\n }\n\n public scheduleTimer(\n source: AnyActor,\n key: TimerKey,\n delay: number\n ): void | PromiseLike<void> {\n const override = this.runtime?.scheduleTimer;\n if (override) {\n // The local scheduler records delayed sends for inspection inside\n // `schedule`; keep that parity for host runtimes.\n const timer = findLogicalTimer(source, key);\n if (timer) {\n const target = timer.target === 'self' ? source : timer.target;\n this._recordSent(source, target, timer.event, delay, timer.id);\n }\n return override(source, key, delay);\n }\n this.schedule(source, key, delay);\n }\n\n public cancelTimer(\n source: AnyActor,\n key: TimerKey\n ): void | PromiseLike<void> {\n const override = this.runtime?.cancelTimer;\n if (override) {\n return override(source, key);\n }\n this.cancel(source, key);\n }\n\n public cancelAllTimers(source: AnyActor): void | PromiseLike<void> {\n const override = this.runtime?.cancelAllTimers;\n if (override) {\n return override(source);\n }\n this.cancelAll(source);\n }\n\n public _relay(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n ): void | PromiseLike<void> {\n if (protectSelectionRelay(target)) {\n return;\n }\n // Returned so callers that can observe a host runtime's asynchronous\n // delivery do; the built-in runtime delivers synchronously.\n return this.sendEvent(source, target, event);\n }\n\n public getSnapshot(): {\n _scheduledTimers: Record<string, ScheduledTimer>;\n } {\n return {\n _scheduledTimers: { ...this._snapshot._scheduledTimers }\n };\n }\n\n public start(): void {\n const scheduledTimers = this._snapshot._scheduledTimers;\n let resetScheduledTimers = true;\n for (const scheduledId in scheduledTimers) {\n if (resetScheduledTimers) {\n this._snapshot._scheduledTimers = {};\n resetScheduledTimers = false;\n }\n const { source, dueAt, key } =\n scheduledTimers[scheduledId as ScheduledTimerId];\n this.scheduleTimer(\n source,\n key,\n Math.max(0, dueAt - (this._clock.now?.() ?? Date.now()))\n );\n }\n }\n}\n\n/** @internal */\nexport function createRuntimeSystem<T extends ActorSystemInfo>(\n rootActor: AnyActor,\n options: {\n clock: Clock;\n logger: (...args: any[]) => void;\n createActorRef: ActorSystem<T>['createActorRef'];\n }\n): ActorSystem<T> {\n return new RuntimeSystem(rootActor, options);\n}\n","import isDevelopment from '#is-development';\nimport { xstateError } from './xstateError.ts';\nimport { diagnoseActorOptions } from './devDiagnostics.ts';\nimport { publishEmittedEvent } from './runtimeHelpers.ts';\nimport type { ActionRecord, SentRecord } from './inspection.ts';\nimport { Mailbox } from './Mailbox.ts';\nimport { XSTATE_STOP, XSTATE_TIMER } from './constants.ts';\nimport {\n createDoneActorEvent,\n createErrorActorEvent,\n createInitEvent\n} from './eventUtils.ts';\nimport { reportUnhandledError } from './reportUnhandledError.ts';\nimport { symbolObservable } from './symbolObservable.ts';\nimport {\n encodeAddressSegment,\n AnyActorSystem,\n bookSessionId,\n Clock,\n createRuntimeSystem,\n resolveActorId\n} from './system.ts';\n\n// those are needed to make JSDoc `@link` work properly\n// oxlint-disable no-unused-vars\nimport type {\n createObservableLogic,\n createEventObservableLogic\n} from './actors/observable.ts';\nimport type { createCallbackLogic } from './actors/callback.ts';\nimport type { createStepLogic } from './actors/logic.ts';\nimport type { createAsyncLogic } from './actors/promise.ts';\nimport type { createMachine } from './createMachine.ts';\n// oxlint-enable no-unused-vars\n\nlet executingCustomAction: boolean = false;\n\nimport type {\n ActorTermination,\n ActorScope,\n ActorTrigger,\n AnyActor,\n AnyActorLogic,\n EmittedFrom,\n EventFromLogic,\n SendableEventFromLogic,\n InputFrom,\n PersistedSnapshotOf,\n Snapshot,\n SnapshotFrom,\n AnyTransitionDefinition,\n ExecutableEffect,\n Readable,\n ActorLogicTransitionResult,\n LogicalTimer,\n ReservedMachineEvent,\n SerializedActorRef\n} from './types.ts';\nimport { getTimerKey } from './timerKey.ts';\nimport {\n ActorOptions,\n ActorInstance,\n ActorRef,\n EventObject,\n InteropSubscribable,\n Observer,\n Subscription\n} from './types.ts';\nimport { toObserver } from './utils.ts';\nimport { finalizeTransitionResult } from './transitionActions.ts';\nimport {\n refreshSnapshotActorRefRoot,\n setSnapshotActorRef\n} from './snapshotActorRef.ts';\n\ninterface ActorMailboxEvent<TEvent> {\n event: TEvent;\n sourceRef: AnyActor | undefined;\n}\n\nconst emptyInspectionRecords = Object.freeze([]) as unknown as never[];\n\nconst reservedMachineEventTypes = {\n 'xstate.done.actor': true,\n 'xstate.error.actor': true,\n 'xstate.error.execution': true,\n 'xstate.snapshot.actor': true,\n 'xstate.done.state': true,\n 'xstate.after': true,\n 'xstate.timeout.state': true,\n 'xstate.timeout.actor': true,\n [XSTATE_TIMER]: true\n} satisfies Record<ReservedMachineEvent['type'] | typeof XSTATE_TIMER, true>;\n\n// those values are currently used by @xstate/react directly so it's important to keep the assigned values in sync\nexport enum ProcessingStatus {\n NotStarted = 0,\n Running = 1,\n Stopped = 2\n}\n\nconst defaultOptions = Object.freeze({\n clock: {\n setTimeout: (fn, ms) => {\n return setTimeout(fn, ms);\n },\n clearTimeout: (id) => {\n return clearTimeout(id);\n }\n } as Clock,\n logger: console.log.bind(console)\n});\n\nfunction safeCall<T>(fn: ((arg: T) => void) | undefined, arg?: T) {\n try {\n fn?.(arg as T);\n } catch (err) {\n reportUnhandledError(err);\n }\n}\n\nfunction executeExecutableEffects(\n effects: readonly ExecutableEffect[] | undefined,\n actorScope: ActorScope<any, any, any, any>\n): void {\n if (!effects?.length) {\n return;\n }\n\n for (const effect of effects) {\n actorScope.actionExecutor(effect);\n }\n}\n\n/**\n * Options core passes when it creates actors: the public {@link ActorOptions}\n * plus the parent of a child actor. Not exported from the package entry.\n */\nexport interface InternalActorOptions<\n TLogic extends AnyActorLogic\n> extends ActorOptions<TLogic> {\n parent?: AnyActor;\n}\n\nfunction createActorRef(\n logic: AnyActorLogic,\n options: InternalActorOptions<AnyActorLogic>\n): AnyActor {\n return new Actor(logic, options);\n}\n\n/**\n * An Actor is a running process that can receive events, send events and change\n * its behavior based on the events it receives, which can cause effects outside\n * of the actor. When you run a state machine, it becomes an actor.\n *\n * An `Actor` is the concrete runtime instance with lifecycle methods and\n * system-owned internals. It also satisfies the narrower `ActorRef` contract,\n * so consumer APIs should accept `ActorRef` when they only need to send events\n * or read snapshots.\n *\n * @public\n */\nexport class Actor<TLogic extends AnyActorLogic> implements ActorInstance<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>,\n EmittedFrom<TLogic>,\n SendableEventFromLogic<TLogic>\n> {\n /** The current internal state of the actor. */\n private _snapshot!: SnapshotFrom<TLogic>;\n /**\n * The clock that is responsible for setting and clearing timeouts, such as\n * delayed events and transitions.\n */\n public clock: Clock;\n public options: Readonly<ActorOptions<TLogic>>;\n\n /** The unique identifier for this actor relative to its parent. */\n public id: string;\n\n private _boundProcess?: (\n item: ActorMailboxEvent<EventFromLogic<TLogic>>\n ) => void;\n private mailbox?: Mailbox<ActorMailboxEvent<EventFromLogic<TLogic>>>;\n private _mailboxStarted = false;\n\n private observers?: Set<Observer<SnapshotFrom<TLogic>>>;\n /** Whether a consumer subscribed to this actor's error after it errored. */\n private _errorObserved = false;\n private eventListeners:\n | Map<string, Set<(emittedEvent: EmittedFrom<TLogic>) => void>>\n | undefined;\n private logger: (...args: any[]) => void;\n\n /** @internal */\n public _processingStatus: ProcessingStatus = ProcessingStatus.NotStarted;\n private _forceDeferredActions = false;\n\n // Actor Ref\n public _parent?: AnyActor;\n /** @internal */\n public _syncSnapshot?: boolean;\n public ref: ActorRef<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>,\n EmittedFrom<TLogic>,\n SendableEventFromLogic<TLogic>\n >;\n // TODO: add typings for system\n private _actorScope: ActorScope<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>,\n AnyActorSystem,\n EmittedFrom<TLogic>,\n SendableEventFromLogic<TLogic>\n >;\n\n /** @internal */\n public _lastSourceRef?: AnyActor;\n /** @internal */\n public _collectedMicrosteps: AnyTransitionDefinition[] | undefined;\n /** @internal Actions executed during the in-flight transition. */\n public _collectedActions: ActionRecord[] | undefined;\n /** @internal Events relayed to other actors during the in-flight transition. */\n public _collectedSent: SentRecord[] | undefined;\n private _initialEffects: ExecutableEffect[] | undefined;\n public registryKey: string | undefined;\n\n /** The globally unique process ID for this invocation. */\n public sessionId: string;\n\n private _address?: string;\n /**\n * The deterministic logical address of this actor within its system: the\n * `/`-joined path of actor ids from the root. Stable across persistence and\n * restore, unlike `sessionId`, which identifies one incarnation.\n *\n * `/` separates segments, so an id containing one (a state name with a\n * slash reaches its invoked child's id) is percent-encoded to keep the\n * path unambiguous.\n */\n public get address(): string {\n // `id` and `_parent` never change after construction, so the whole chain\n // memoizes to O(1) amortized.\n return (this._address ??= this._parent\n ? `${this._parent.address}/${encodeAddressSegment(this.id)}`\n : encodeAddressSegment(this.id));\n }\n\n /** The system to which this actor belongs. */\n public system: AnyActorSystem;\n\n private _trigger?: ActorTrigger<SendableEventFromLogic<TLogic>>;\n\n public get trigger(): ActorTrigger<SendableEventFromLogic<TLogic>> {\n return (this._trigger ??= new Proxy({} as Actor<TLogic>['trigger'], {\n get: (_, eventType: string) => {\n return (payload?: Record<PropertyKey, unknown>) => {\n this.send({\n ...payload,\n type: eventType\n } as SendableEventFromLogic<TLogic>);\n };\n }\n }) as ActorTrigger<SendableEventFromLogic<TLogic>>);\n }\n\n private _boundSend?: ActorRef<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>,\n EmittedFrom<TLogic>,\n SendableEventFromLogic<TLogic>\n >['send'];\n\n public get send(): ActorRef<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>,\n EmittedFrom<TLogic>,\n SendableEventFromLogic<TLogic>\n >['send'] {\n return (this._boundSend ??= this._sendPublic.bind(this));\n }\n\n public src: string | AnyActorLogic;\n\n /**\n * Creates a new actor instance for the given logic with the provided options,\n * if any.\n *\n * @param logic The logic to create an actor from\n * @param options Actor options\n */\n constructor(\n public logic: TLogic,\n options?: ActorOptions<TLogic>\n ) {\n const resolvedOptions = (\n options ? { ...defaultOptions, ...options } : defaultOptions\n ) as InternalActorOptions<TLogic> & typeof defaultOptions;\n\n const { clock, logger, parent, syncSnapshot, id, registryKey, inspect } =\n resolvedOptions;\n\n this.system = parent\n ? parent.system\n : (resolvedOptions._systemRef?.current ??\n createRuntimeSystem(this, {\n clock,\n logger,\n createActorRef\n }));\n\n if (\n !parent &&\n resolvedOptions._systemRef &&\n !resolvedOptions._systemRef.current\n ) {\n resolvedOptions._systemRef.current = this.system;\n resolvedOptions._systemRef.initialize?.();\n }\n\n if (inspect && !parent) {\n // Always inspect at the system-level\n this.system.inspect(toObserver(inspect));\n }\n\n if (resolvedOptions.onRejectedEvent && !parent) {\n this.system.onRejectedEvent(resolvedOptions.onRejectedEvent);\n }\n\n this.sessionId = resolvedOptions._sessionId ?? bookSessionId(this.system);\n this.id = resolveActorId(this.system, id, {\n parent,\n src: resolvedOptions.src ?? logic\n });\n this.logger = options?.logger ?? this.system._logger;\n this.clock = options?.clock ?? this.system._clock;\n this._parent = parent;\n this._syncSnapshot = syncSnapshot;\n this.options = resolvedOptions as ActorOptions<TLogic> &\n typeof defaultOptions;\n this.src = resolvedOptions.src ?? logic;\n this.ref = this;\n this._actorScope = this as unknown as typeof this._actorScope;\n\n if (registryKey) {\n this.registryKey = registryKey;\n this.system._set(registryKey, this);\n }\n\n // prepare to collect initial microsteps during initialTransition\n this._collectedMicrosteps = undefined;\n const restore = resolvedOptions._restore;\n this._restored = restore !== undefined;\n try {\n if (restore) {\n this._setSnapshot(restore.restore(this._actorScope));\n } else if (options?._inert) {\n // Inert actors (createInertActorScope) only anchor a scope for pure\n // transition functions; computing an initial snapshot here would run\n // init-time side effects (context factories, entry) a second time.\n } else {\n const [snapshot, effects] = finalizeTransitionResult(\n this._actorScope,\n undefined,\n this.logic.initialTransition(this.options?.input, this._actorScope)\n );\n this._setSnapshot(snapshot);\n this._initialEffects = effects.length ? effects : undefined;\n }\n } catch (err) {\n // Restored logic may keep its snapshot shape on restore failures (e.g.\n // machines). Otherwise we can't get the true\n // `TSnapshot & { status: 'error'; }`, so this is a lie of sorts.\n this._setSnapshot(\n restore?.error?.(err) ??\n ({\n status: 'error',\n output: undefined,\n error: err\n } as SnapshotFrom<TLogic>)\n );\n // discard any functions deferred during the failed initial snapshot\n // computation so they can't run against an inconsistent actor\n if (this._deferred) {\n this._deferred.length = 0;\n }\n }\n\n if (\n registryKey &&\n (this._snapshot as Snapshot<unknown>).status !== 'active'\n ) {\n this.system._unregister(this);\n }\n\n // Announce actor topology: emitted once for every actor (root and every\n // spawned/invoked child) so the actor graph can be drawn before any\n // transitions occur. This is the only place actor identity is announced.\n if (this.system._hasInspectionObservers?.() ?? true) {\n this.system._sendInspectionEvent({\n type: '@xstate.actor',\n actorRef: this,\n parentRef: this._parent,\n id: this.id,\n src: this.src,\n snapshot: this._snapshot\n });\n }\n }\n\n // array of functions to defer\n private _deferred: Array<() => void> | undefined;\n\n private _restored = false;\n\n /** @internal */\n public _getLogger(): ActorScope<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>\n >['logger'] {\n return this.logger;\n }\n\n private get self(): Actor<TLogic> {\n return this;\n }\n\n private get defer(): (fn: () => void) => void {\n const defer = (fn: () => void) => this._defer(fn);\n Object.defineProperty(this, 'defer', { value: defer });\n return defer;\n }\n\n private get stopChild(): (child: AnyActor) => void {\n const stopChild = (child: AnyActor) => this._stopChild(child);\n Object.defineProperty(this, 'stopChild', { value: stopChild });\n return stopChild;\n }\n\n private get emit(): (event: EmittedFrom<TLogic>) => void | PromiseLike<void> {\n const emit = (event: EmittedFrom<TLogic>) =>\n publishEmittedEvent(this, event, this.system);\n Object.defineProperty(this, 'emit', { value: emit });\n return emit;\n }\n\n private get actionExecutor(): (action: ExecutableEffect) => void {\n const actionExecutor = (action: ExecutableEffect) =>\n this._executeAction(action);\n Object.defineProperty(this, 'actionExecutor', { value: actionExecutor });\n return actionExecutor;\n }\n\n /** @internal */\n public _isRunning(): boolean {\n return this._processingStatus === ProcessingStatus.Running;\n }\n\n /** @internal */\n public _defer(fn: () => void): void {\n (this._deferred ??= []).push(fn);\n }\n\n /** @internal */\n public _stopChild(child: AnyActor): void {\n if (child._parent !== this) {\n throw new Error(\n isDevelopment\n ? `Cannot stop child actor ${child.id} of ${this.id} because it is not a child`\n : xstateError(47, child.id, this.id)\n );\n }\n (child as Actor<AnyActorLogic>)._stop();\n }\n\n /** @internal */\n public _executeAction(action: ExecutableEffect): void {\n const exec = () => {\n // Record every executed action for the '@xstate.transition' inspection\n // event's `actions[]` facet (replaces the v5 '@xstate.action' event).\n if (this.system._hasInspectionObservers?.() ?? true) {\n (this._collectedActions ??= []).push({\n type: action.type,\n params: action.params\n });\n }\n const saveExecutingCustomAction = executingCustomAction;\n try {\n executingCustomAction = true;\n const result = action.exec();\n if (\n result &&\n typeof (result as PromiseLike<unknown>).then === 'function'\n ) {\n void Promise.resolve(result).catch((err) => {\n if (this._processingStatus === ProcessingStatus.Stopped) {\n return;\n }\n this._recoverOrError(err);\n });\n }\n } finally {\n executingCustomAction = saveExecutingCustomAction;\n }\n };\n if (\n this._processingStatus === ProcessingStatus.Running &&\n !this._forceDeferredActions\n ) {\n exec();\n } else {\n (this._deferred ??= []).push(exec);\n }\n }\n\n /** Associates each live snapshot with this actor for later pure transitions. */\n private _setSnapshot(snapshot: SnapshotFrom<TLogic>): void {\n const previousSnapshot = this._snapshot;\n this._snapshot = snapshot;\n setSnapshotActorRef(snapshot, this, this.system, previousSnapshot);\n }\n\n private _setErrorSnapshot(\n err: unknown,\n snapshot: SnapshotFrom<TLogic> = this._snapshot\n ) {\n this._setSnapshot({\n ...(snapshot as Snapshot<unknown>),\n status: 'error',\n error: err\n } as SnapshotFrom<TLogic>);\n }\n\n /** Recover via the logic's error event if possible; otherwise error out. */\n private _recoverOrError(\n err: unknown,\n snapshot?: SnapshotFrom<TLogic>,\n previousSnapshot?: SnapshotFrom<TLogic>\n ): boolean {\n if (this._tryHandleExecutionError(err, snapshot)) {\n return true;\n }\n this._setErrorSnapshot(err);\n this._error(err, previousSnapshot);\n return false;\n }\n\n private _tryHandleExecutionError(\n err: unknown,\n snapshot: SnapshotFrom<TLogic> = this._snapshot\n ): boolean {\n // Machine logic can recover from execution errors via `onError`\n // transitions; the logic decides (so the actor stays logic-agnostic).\n const errorEvent = this.logic.getExecutionErrorEvent?.(snapshot, err) as\n | EventFromLogic<TLogic>\n | undefined;\n if (!errorEvent) {\n return false;\n }\n\n try {\n const [nextSnapshot, effects] = finalizeTransitionResult(\n this._actorScope,\n snapshot,\n this.logic.transition(snapshot, errorEvent, this._actorScope)\n );\n this._setSnapshot(nextSnapshot);\n executeExecutableEffects(effects, this._actorScope);\n this.update(nextSnapshot, errorEvent);\n return true;\n } catch {\n return false;\n }\n }\n\n private _next(snapshot: SnapshotFrom<TLogic>) {\n for (const observer of this.observers ?? emptyInspectionRecords) {\n safeCall(observer.next, snapshot);\n }\n }\n\n private update(snapshot: SnapshotFrom<TLogic>, event: EventObject): void {\n // Update state\n this._setSnapshot(snapshot);\n\n // Execute deferred effects\n const deferred = this._deferred;\n for (let i = 0; i < (deferred?.length ?? 0); i++) {\n const deferredFn = deferred![i];\n try {\n deferredFn();\n } catch (err) {\n // this error can only be caught when executing *initial* actions\n // it's the only time when we call actions provided by the user through those deferreds\n // when the actor is already running we always execute them synchronously while transitioning\n // no \"builtin deferred\" should actually throw an error since they are either safe\n // or the control flow is passed through the mailbox and errors should be caught by the `_process` used by the mailbox\n deferred!.length = 0;\n if (this._tryHandleExecutionError(err, snapshot)) {\n return;\n }\n this._setErrorSnapshot(err, snapshot);\n this._error(err);\n break;\n }\n }\n if (deferred) {\n deferred.length = 0;\n }\n\n switch ((this._snapshot as Snapshot<unknown>).status) {\n case 'active':\n this._next(snapshot);\n break;\n case 'done':\n case 'error':\n // Terminal lifecycle is represented by the ordered\n // `@xstate.terminate` effect returned by the actor logic.\n break;\n }\n this._inspectTransition(this._snapshot, event);\n }\n\n /** @internal Emits the transition inspection event; used by the pure\n * `transition()` path for snapshots driven outside a live actor. */\n public _inspectTransition(\n snapshot: SnapshotFrom<TLogic>,\n event: EventObject\n ): void {\n if (this.system._hasInspectionObservers?.() ?? true) {\n this.system._sendInspectionEvent({\n type: '@xstate.transition',\n actorRef: this,\n event,\n sourceRef: this._lastSourceRef,\n targetRef: this,\n snapshot,\n microsteps: this._collectedMicrosteps ?? emptyInspectionRecords,\n actions: this._collectedActions ?? emptyInspectionRecords,\n sent: this._collectedSent ?? emptyInspectionRecords,\n eventType: event.type\n });\n }\n this._collectedMicrosteps = undefined;\n this._collectedActions = undefined;\n this._collectedSent = undefined;\n }\n\n private _flushInitialEffects(): boolean {\n if (!this._initialEffects?.length) {\n return true;\n }\n this._forceDeferredActions = true;\n try {\n executeExecutableEffects(this._initialEffects, this._actorScope);\n this._initialEffects = undefined;\n return true;\n } catch (err) {\n this._initialEffects = undefined;\n if (this._deferred) {\n this._deferred.length = 0;\n }\n this._recoverOrError(err);\n return (this._snapshot as Snapshot<unknown>).status === 'active';\n } finally {\n this._forceDeferredActions = false;\n }\n }\n\n /**\n * Subscribe an observer to an actor’s snapshot values.\n *\n * @remarks\n * The observer will receive the actor’s snapshot value when it is emitted.\n * The observer can be:\n *\n * - A plain function that receives the latest snapshot, or\n * - An observer object whose `.next(snapshot)` method receives the latest\n * snapshot\n *\n * @example\n *\n * ```ts\n * // Observer as a plain function\n * const subscription = actor.subscribe((snapshot) => {\n * console.log(snapshot);\n * });\n * ```\n *\n * @example\n *\n * ```ts\n * // Observer as an object\n * const subscription = actor.subscribe({\n * next(snapshot) {\n * console.log(snapshot);\n * },\n * error(err) {\n * // ...\n * },\n * complete() {\n * // ...\n * }\n * });\n * ```\n *\n * The return value of `actor.subscribe(observer)` is a subscription object\n * that has an `.unsubscribe()` method. You can call\n * `subscription.unsubscribe()` to unsubscribe the observer:\n *\n * @example\n *\n * ```ts\n * const subscription = actor.subscribe((snapshot) => {\n * // ...\n * });\n *\n * // Unsubscribe the observer\n * subscription.unsubscribe();\n * ```\n *\n * When the actor is stopped, all of its observers will automatically be\n * unsubscribed.\n *\n * @param observer - Either a plain function that receives the latest\n * snapshot, or an observer object whose `.next(snapshot)` method receives\n * the latest snapshot\n */\n public subscribe(observer: Observer<SnapshotFrom<TLogic>>): Subscription;\n public subscribe(\n nextListener?: (snapshot: SnapshotFrom<TLogic>) => void,\n errorListener?: (error: any) => void,\n completeListener?: () => void\n ): Subscription;\n public subscribe(\n nextListenerOrObserver?:\n | ((snapshot: SnapshotFrom<TLogic>) => void)\n | Observer<SnapshotFrom<TLogic>>,\n errorListener?: (error: any) => void,\n completeListener?: () => void\n ): Subscription {\n const observer = toObserver(\n nextListenerOrObserver,\n errorListener,\n completeListener\n );\n\n if (this._processingStatus !== ProcessingStatus.Stopped) {\n (this.observers ??= new Set()).add(observer);\n } else {\n switch ((this._snapshot as Snapshot<unknown>).status) {\n case 'done':\n safeCall(observer.complete);\n break;\n case 'error': {\n const err = (this._snapshot as Snapshot<unknown>).error;\n if (!observer.error) {\n reportUnhandledError(err);\n } else {\n if (!observer.passive) {\n this._errorObserved = true;\n }\n safeCall(observer.error, err);\n }\n break;\n }\n }\n }\n\n return {\n unsubscribe: () => {\n this.observers?.delete(observer);\n }\n };\n }\n\n public on<TType extends EmittedFrom<TLogic>['type'] | '*'>(\n type: TType,\n handler: (\n emitted: EmittedFrom<TLogic> &\n (TType extends '*' ? unknown : { type: TType })\n ) => void\n ): Subscription {\n let listeners = this.eventListeners?.get(type);\n if (!listeners) {\n listeners = new Set();\n (this.eventListeners ??= new Map()).set(type, listeners);\n }\n listeners.add(handler as (emittedEvent: EmittedFrom<TLogic>) => void);\n\n return {\n unsubscribe: () => {\n listeners.delete(\n handler as (emittedEvent: EmittedFrom<TLogic>) => void\n );\n }\n };\n }\n\n public select<TSelected>(\n selector: (snapshot: SnapshotFrom<TLogic>) => TSelected,\n equalityFn: (a: TSelected, b: TSelected) => boolean = Object.is\n ): Readable<TSelected> {\n return {\n subscribe: (\n observerOrFn:\n | Observer<TSelected>\n | ((value: TSelected) => void)\n | undefined,\n errorListener?: (error: any) => void,\n completeListener?: () => void\n ) => {\n const observer = toObserver(\n observerOrFn,\n errorListener,\n completeListener\n );\n let selected = selector(this.getSnapshot());\n return this.subscribe({\n next: (snapshot) => {\n const next = selector(snapshot);\n if (!equalityFn(selected, next)) {\n selected = next;\n observer.next?.(next);\n }\n },\n error: observer.error,\n complete: observer.complete\n });\n },\n get: () => selector(this.getSnapshot())\n };\n }\n\n /** Starts the Actor from the initial state */\n public start(): this {\n if (this._processingStatus === ProcessingStatus.Running) {\n // Do not restart the service if it is already started\n return this;\n }\n\n if (this._processingStatus === ProcessingStatus.Stopped) {\n const status = (this._snapshot as Snapshot<unknown>).status;\n if (status === 'done' || status === 'error') {\n // A terminated actor has nothing left to start.\n return this;\n }\n // Actors are single-use: a stopped actor cannot be restarted.\n throw new Error(\n isDevelopment\n ? `Actor ${this.id} was stopped and cannot be restarted. Create a new actor with createActor().`\n : xstateError(48, this.id)\n );\n }\n\n if (this._syncSnapshot) {\n this.subscribe({\n next: (snapshot: Snapshot<unknown>) => {\n if (snapshot.status === 'active') {\n this.system._relay(this, this._parent!, {\n type: 'xstate.snapshot.actor',\n actorId: this.id,\n sessionId: this.sessionId,\n snapshot\n });\n }\n },\n error: () => {}\n });\n }\n\n this.system._register(this.sessionId, this);\n if (this.registryKey) {\n this.system._set(this.registryKey, this);\n }\n this._processingStatus = ProcessingStatus.Running;\n\n this._lastSourceRef = this._parent;\n\n const status = (this._snapshot as Snapshot<unknown>).status;\n\n switch (status) {\n case 'done':\n // a state machine can be \"done\" upon initialization (it could reach a final state using initial microsteps)\n // we still need to complete observers, flush deferreds etc\n if (this._restored) {\n // Restoration does not replay the transition that originally\n // terminated the actor, and must not notify the parent again.\n this._next(this._snapshot);\n this._stopProcedure();\n this._complete();\n return this;\n }\n if (!this._flushInitialEffects()) {\n return this;\n }\n this.update(\n this._snapshot,\n createInitEvent(\n this.options.input\n ) as unknown as EventFromLogic<TLogic>\n );\n // TODO: rethink cleanup of observers, mailbox, etc\n return this;\n case 'error':\n this._error((this._snapshot as Snapshot<unknown>).error);\n return this;\n case 'stopped':\n // A restored stopped snapshot is terminal: the actor does not process\n // events or run transitions.\n this._stopProcedure();\n this._complete();\n return this;\n }\n\n if (!this._parent) {\n this.system.start();\n }\n\n if (!this._flushInitialEffects()) {\n return this;\n }\n\n if (this.logic.start) {\n try {\n this.logic.start(this._snapshot, this._actorScope, {\n restored: this._restored\n });\n } catch (err) {\n this._setErrorSnapshot(err);\n this._error(err);\n return this;\n }\n }\n\n if (\n !this._restored &&\n !this._deferred?.length &&\n !this.observers?.size &&\n !(this.system._hasInspectionObservers?.() ?? true)\n ) {\n // Starting changes the registered system view associated with the\n // snapshot, even when there is nothing to publish or execute.\n if (!refreshSnapshotActorRefRoot(this._snapshot, this, this.system)) {\n this._setSnapshot(this._snapshot);\n }\n this._collectedMicrosteps = undefined;\n this._collectedActions = undefined;\n this._collectedSent = undefined;\n } else {\n this.update(\n this._snapshot,\n createInitEvent(this.options.input) as unknown as EventFromLogic<TLogic>\n );\n }\n\n if (this._restored) {\n const timers =\n (\n this._snapshot as unknown as {\n timers?: readonly LogicalTimer[];\n }\n ).timers ?? [];\n // scheduledAt is only persisted from — and only meaningful under — the\n // wall clock; a custom clock (a simulated clock, a monotonic counter)\n // restores every timer with its declared delay. The clamp bounds\n // remaining time by the declared delay in case the wall clock moved\n // backwards between persist and restore.\n const wallClock = !this.system._clock.now;\n const now = Date.now();\n for (const timer of timers) {\n // A timer persisted from a live runtime carries its wall-clock start;\n // honor the absolute deadline instead of restarting the full delay.\n // Without a start (a pure-transition snapshot, or an older snapshot)\n // the declared delay is all there is.\n const delay =\n wallClock && timer.scheduledAt !== undefined\n ? Math.min(\n timer.delay,\n Math.max(0, timer.scheduledAt + timer.delay - now)\n )\n : timer.delay;\n this.system.scheduleTimer(this, getTimerKey(timer), delay);\n }\n this._restored = false;\n }\n\n this._mailboxStarted = true;\n this.mailbox?.start();\n\n return this;\n }\n\n private _process({\n event,\n sourceRef\n }: ActorMailboxEvent<EventFromLogic<TLogic>>) {\n this._lastSourceRef = sourceRef;\n const previousSnapshot = this._snapshot;\n let nextState: ActorLogicTransitionResult<SnapshotFrom<TLogic>> | undefined;\n let caughtError;\n try {\n nextState = finalizeTransitionResult(\n this._actorScope,\n this._snapshot,\n this.logic.transition(this._snapshot, event, this._actorScope)\n );\n } catch (err) {\n // we wrap it in a box so we can rethrow it later even if falsy value gets caught here\n caughtError = { err };\n }\n\n if (caughtError) {\n this._collectedMicrosteps = undefined;\n this._collectedActions = undefined;\n this._collectedSent = undefined;\n if (!this._recoverOrError(caughtError.err)) {\n this._inspectTransition(this._snapshot, event);\n }\n return;\n }\n if (!nextState) {\n return;\n }\n\n let snapshot = this._snapshot;\n try {\n const [nextSnapshot, effects] = nextState;\n if (\n nextSnapshot === previousSnapshot &&\n !effects.length &&\n // State machine snapshots only; other logic may ignore events freely.\n 'machine' in (previousSnapshot as object) &&\n event.type !== XSTATE_STOP &&\n (!sourceRef || !Object.hasOwn(reservedMachineEventTypes, event.type))\n ) {\n this._reportUnhandledEvent(event);\n }\n snapshot = nextSnapshot;\n this._setSnapshot(snapshot);\n executeExecutableEffects(effects, this._actorScope);\n this.update(snapshot, event);\n } catch (err) {\n if (!this._recoverOrError(err, snapshot, previousSnapshot)) {\n this._inspectTransition(this._snapshot, event);\n }\n return;\n }\n\n if (event.type === XSTATE_STOP) {\n this._stopProcedure();\n this._complete();\n }\n }\n\n private _warnedUnhandledTypes?: Set<string>;\n\n private _reportUnhandledEvent(event: EventFromLogic<TLogic>): void {\n safeCall(() => this.options.onUnhandledEvent?.(event, this._snapshot));\n if (isDevelopment) {\n const to =\n event.type === 'xstate.route'\n ? ` to ${JSON.stringify((event as { to?: unknown }).to)}`\n : '';\n const warned = (this._warnedUnhandledTypes ??= new Set());\n if (!warned.has(event.type + to)) {\n warned.add(event.type + to);\n console.warn(\n `Actor ${this.id} received event \"${event.type}\"${to} in state ${JSON.stringify(\n (this._snapshot as { value?: unknown }).value\n )} with no matching transition`\n );\n }\n }\n }\n\n /** @internal */\n public _emit(event: EmittedFrom<TLogic>): void {\n for (const listeners of [\n this.eventListeners?.get(event.type),\n this.eventListeners?.get('*')\n ]) {\n if (listeners) {\n for (const handler of listeners) {\n safeCall(handler, event);\n }\n }\n }\n }\n\n /** @internal */\n public _terminate(termination: ActorTermination): void {\n if (termination.status === 'done') {\n // The terminal snapshot is published before observer completion and the\n // parent notification, matching actor lifecycle order.\n this._next(this._snapshot);\n this._stopProcedure();\n this._complete();\n if (this._parent) {\n this.system._relay(\n this,\n this._parent,\n createDoneActorEvent(this.id, termination.output, this.sessionId)\n );\n }\n return;\n }\n if (termination.status === 'error') {\n this._error(termination.error);\n }\n }\n\n /** @internal */\n public _stop(): this {\n if (this._processingStatus === ProcessingStatus.Stopped) {\n return this;\n }\n this.mailbox?.clear();\n if (this._processingStatus === ProcessingStatus.NotStarted) {\n this._processingStatus = ProcessingStatus.Stopped;\n this.system._unregister(this);\n return this;\n }\n this._send({ type: XSTATE_STOP } as EventFromLogic<TLogic>);\n this.system._unregister(this);\n\n return this;\n }\n\n /** Stops the Actor and unsubscribe all listeners. */\n public stop(): this {\n if (this._parent) {\n throw new Error(\n isDevelopment\n ? 'A non-root actor cannot be stopped directly.'\n : xstateError(49, this.id)\n );\n }\n return this._stop();\n }\n private _complete(): void {\n for (const observer of this.observers ?? emptyInspectionRecords) {\n safeCall(observer.complete);\n }\n this.observers?.clear();\n this.eventListeners?.clear();\n }\n\n /**\n * Reports an unhandled error unless a consumer observes it before the\n * report runs. An actor can error before its creator has a chance to\n * subscribe, so the check waits one macrotask for a subscriber with an\n * `error` callback.\n */\n private _reportUnlessObserved(err: unknown): void {\n setTimeout(() => {\n if (!this._errorObserved) {\n reportUnhandledError(err);\n }\n });\n }\n\n private _error(err: unknown, previousSnapshot?: SnapshotFrom<TLogic>): void {\n this._stopProcedure();\n // Transition calculation or effect execution may fail before child stop\n // effects run. Keep the previous snapshot's children when calculation has\n // already removed them, and include children owned by non-machine logic\n // from the runtime registry.\n const children = new Set<AnyActor>();\n for (const snapshot of [this._snapshot, previousSnapshot]) {\n const snapshotChildren = (\n snapshot as\n | {\n children?: Record<string, AnyActor | undefined>;\n }\n | undefined\n )?.children;\n for (const child of Object.values(snapshotChildren ?? {})) {\n if (\n child?._parent === this &&\n typeof child.getSnapshot === 'function'\n ) {\n children.add(child);\n }\n }\n }\n for (const child of this.system._peekChildren?.()?.values() ?? []) {\n if (child._parent === this) {\n children.add(child);\n }\n }\n for (const child of children) {\n try {\n if (child.getSnapshot().status !== 'active') {\n continue;\n }\n const result = this.system.stopActor(child);\n if (result) {\n void Promise.resolve(result).catch(reportUnhandledError);\n }\n } catch (error) {\n reportUnhandledError(error);\n }\n }\n if (!this.observers?.size) {\n if (!this._parent) {\n this._reportUnlessObserved(err);\n }\n } else {\n let reportError = false;\n let handled = false;\n\n for (const observer of this.observers) {\n const errorListener = observer.error;\n if (!observer.passive) {\n reportError ||= !errorListener;\n handled ||= !!errorListener;\n }\n safeCall(errorListener, err);\n }\n reportError ||= !handled;\n this.observers.clear();\n if (reportError) {\n this._reportUnlessObserved(err);\n }\n }\n this.eventListeners?.clear();\n\n if (this._parent) {\n this.system._relay(\n this,\n this._parent,\n createErrorActorEvent(this.id, err, this.sessionId)\n );\n }\n }\n private _stopProcedure(): void {\n if (this._processingStatus !== ProcessingStatus.Running) {\n // Actor already stopped; do nothing\n return;\n }\n\n // Cancel all delayed events\n this.system.cancelAllTimers(this);\n\n // TODO: mailbox.reset\n this.mailbox?.clear();\n this.mailbox = undefined;\n this._boundProcess = undefined;\n this._mailboxStarted = false;\n\n this._processingStatus = ProcessingStatus.Stopped;\n this.system._unregister(this);\n }\n\n /** @internal */\n public _send(event: EventFromLogic<TLogic>, sourceRef?: AnyActor) {\n if (this._processingStatus === ProcessingStatus.Stopped) {\n this.system.deadLetter(sourceRef, this as AnyActor, event, 'stopped');\n return;\n }\n\n let mailbox = this.mailbox;\n if (!mailbox) {\n this._boundProcess ??= this._process.bind(this);\n mailbox = this.mailbox = new Mailbox(this._boundProcess);\n if (this._mailboxStarted) {\n mailbox.start();\n }\n }\n mailbox.enqueue({ event, sourceRef });\n }\n\n /**\n * Sends an event to the running Actor to trigger a transition.\n *\n * @param event The event to send\n */\n private _sendPublic(event: SendableEventFromLogic<TLogic>) {\n if (isDevelopment && typeof event === 'string') {\n throw new Error(\n `Only event objects may be sent to actors; use .send({ type: \"${event}\" }) instead`\n );\n }\n this.system._relay(undefined, this, event);\n }\n\n /**\n * Returns the actor's serializable logical identity: `{ $actor: address }`.\n * The result can be used as an `enq.sendTo(...)` target.\n */\n public toJSON(): SerializedActorRef {\n return { $actor: this.address };\n }\n\n /**\n * Obtain the internal state of the actor, which can be persisted.\n *\n * @remarks\n * The internal state can be persisted from any actor, not only machines.\n *\n * Note that the persisted state is not the same as the snapshot from\n * {@link Actor.getSnapshot}. Persisted state represents the internal state of\n * the actor, while snapshots represent the actor's last emitted value.\n *\n * Can be restored with {@link ActorOptions.snapshot}\n * @see https://stately.ai/docs/persistence\n */\n public getPersistedSnapshot(options?: {\n /**\n * Whether persisted machine children embed their own persisted state\n * (the co-locating runtime's whole-tree checkpoint) or are referenced by\n * logical address only, leaving each child's state with the runtime that\n * owns it. Defaults to `true`.\n */\n embedChildren?: boolean;\n }): PersistedSnapshotOf<TLogic>;\n public getPersistedSnapshot(options?: unknown): PersistedSnapshotOf<TLogic> {\n return this.logic.getPersistedSnapshot(\n this._snapshot,\n options\n ) as PersistedSnapshotOf<TLogic>;\n }\n\n public [symbolObservable](): InteropSubscribable<SnapshotFrom<TLogic>> {\n return this;\n }\n\n /**\n * Read an actor’s snapshot synchronously.\n *\n * @remarks\n * The snapshot is the last value the actor published, not a query of its\n * private state: the actor emits a snapshot when it transitions, and this\n * returns that cached last emission. The read is coherent within one\n * synchronous transition turn because event processing runs to completion;\n * across asynchronous boundaries it may be stale, like any observed value.\n *\n * Only co-located actors publish full snapshots. A location-transparent\n * remote handle exposes lifecycle only ({ status, output?, error? }): while\n * the handle exists among its parent's children the child is presumed\n * `active`, and its terminal result arrives as a completion event.\n *\n * Note that some actors, such as callback actors generated with\n * `createCallbackLogic`, will not emit snapshots.\n * @see {@link Actor.subscribe} to subscribe to an actor’s snapshot values.\n * @see {@link Actor.getPersistedSnapshot} to persist the internal state of an actor (which is more than just a snapshot).\n */\n public getSnapshot(): SnapshotFrom<TLogic> {\n if (isDevelopment && !this._snapshot) {\n throw new Error(\n `Snapshot can't be read while the actor initializes itself`\n );\n }\n return this._snapshot;\n }\n}\n\n/**\n * `'input'` when creating an actor from `TLogic` requires input (its input type\n * does not accept `undefined`), otherwise `never`.\n *\n * @public\n */\nexport type RequiredActorOptionsKeys<TLogic extends AnyActorLogic> =\n undefined extends InputFrom<TLogic> ? never : 'input';\n\n/**\n * The options `createActor` (and framework hooks) require for `TLogic`:\n * `{ input }` when the logic requires input, otherwise nothing.\n *\n * @public\n */\nexport type RequiredActorOptionsFor<TLogic extends AnyActorLogic> = [\n RequiredActorOptionsKeys<TLogic>\n] extends [never]\n ? {}\n : { [K in RequiredActorOptionsKeys<TLogic>]: unknown };\n\n/** Options accepted by {@link createActor}. */\ntype CreateActorOptionsArgs<TLogic extends AnyActorLogic> = [\n RequiredActorOptionsKeys<TLogic>\n] extends [never]\n ? [options?: ActorOptions<TLogic>]\n : [options: ActorOptions<TLogic> & RequiredActorOptionsFor<TLogic>];\n\n/**\n * Creates a new actor instance for the given actor logic with the provided\n * options, if any.\n *\n * @remarks\n * When you create an actor from actor logic via `createActor(logic)`, you\n * implicitly create an actor system where the created actor is the root actor.\n * Any actors spawned from this root actor and its descendants are part of that\n * actor system.\n * @example\n *\n * ```ts\n * import { createActor } from 'xstate';\n * import { someActorLogic } from './someActorLogic.ts';\n *\n * // Creating the actor, which implicitly creates an actor system with itself as the root actor\n * const actor = createActor(someActorLogic);\n *\n * actor.subscribe((snapshot) => {\n * console.log(snapshot);\n * });\n *\n * // Actors must be started by calling `actor.start()`, which will also start the actor system.\n * actor.start();\n *\n * // Actors can receive events\n * actor.send({ type: 'someEvent' });\n *\n * // You can stop root actors by calling `actor.stop()`, which will also stop the actor system and all actors in that system.\n * actor.stop();\n * ```\n *\n * @param logic - The actor logic to create an actor from. For a state machine\n * actor logic creator, see {@link createMachine}. Other actor logic creators\n * include {@link createCallbackLogic}, {@link createEventObservableLogic},\n * {@link createObservableLogic}, {@link createStepLogic}, and\n * {@link createAsyncLogic}.\n * @param options - Actor options\n * @public\n */\nexport function createActor<TLogic extends AnyActorLogic>(\n logic: TLogic,\n ...[options]: CreateActorOptionsArgs<TLogic>\n): Actor<TLogic> {\n diagnoseActorOptions(options);\n return new Actor(logic, options);\n}\n","import type {\n ActorLogicValidator,\n ActorValidationRequest\n} from './validation.types.ts';\n\nexport function assertValid(\n validator: ActorLogicValidator,\n request: ActorValidationRequest\n): void {\n const error = validator.check(request);\n if (error) {\n throw error;\n }\n}\n","import {\n XSTATE_LOGIC_EFFECT_REJECT,\n XSTATE_LOGIC_EFFECT_RESOLVE,\n XSTATE_LOGIC_EFFECT_START,\n XSTATE_INIT,\n XSTATE_STOP\n} from '../constants.ts';\nimport { createInitEvent } from '../eventUtils.ts';\nimport { StandardSchemaV1 } from '../schema.types.ts';\nimport {\n ActorSystemRuntime,\n AnyActorSystem,\n type DeadLetterDetail\n} from '../system.ts';\nimport { assertValid } from '../validation.ts';\nimport type { ActorLogicValidator } from '../validation.types.ts';\nimport {\n finalizeTransitionResult,\n createCustomEffect,\n createDeadLetterEffect,\n createEmitEffect,\n createSendToEffect\n} from '../transitionActions.ts';\nimport {\n ActorLogic,\n ActorRefFrom,\n ActorScope,\n AnyActorRef,\n EventObject,\n ExecutableEffect,\n Snapshot\n} from '../types.ts';\nimport type { NonReducibleUnknown } from '../typeUtils.ts';\n\n/** @public */\nexport type StepSnapshot<TContext, TOutput, TInput> = Snapshot<TOutput> & {\n context: TContext;\n input: TInput | undefined;\n effects?: Record<string, StepEffectState>;\n};\n\n/** @public */\nexport type StepEffectState =\n | { status: 'active' }\n | { status: 'done'; output?: unknown }\n | { status: 'error'; error: unknown };\n\n/** @public */\nexport interface StepLogicArgs<TContext, TEvent extends EventObject, TInput> {\n context: TContext;\n event: TEvent;\n input: TInput;\n system: AnyActorSystem;\n self: StepActorRef<TContext, unknown, TEvent, TInput>;\n}\n\n/** @public */\nexport interface StepLogicEnqueue<\n TEvent extends EventObject,\n TEmitted extends EventObject\n> {\n emit: (emitted: TEmitted) => void;\n sendBack: (event: EventObject) => void;\n raise: (event: TEvent) => void;\n effect: {\n (\n exec: (runtime?: Partial<ActorSystemRuntime>) => void | (() => void)\n ): void;\n (\n key: string,\n exec: (runtime?: Partial<ActorSystemRuntime>) => void | (() => void)\n ): void;\n };\n}\n\n/** @public */\nexport type StepPatch<TContext, TOutput, TInput> = Partial<{\n context: TContext;\n input: TInput | undefined;\n status: StepSnapshot<TContext, TOutput, TInput>['status'];\n output: TOutput;\n error: unknown;\n effects: Record<string, StepEffectState>;\n}>;\n\n/** @public */\nexport type StepLogicFunction<\n TContext,\n TOutput,\n TEvent extends EventObject,\n TInput,\n TEmitted extends EventObject\n> = (\n args: StepLogicArgs<TContext, TEvent, TInput>,\n enq: StepLogicEnqueue<TEvent, TEmitted>\n) => void | StepPatch<TContext, TOutput, TInput>;\n\n/** @public */\nexport interface StepLogicConfig<\n TContext,\n TOutput,\n TEvent extends EventObject,\n TInput,\n TEmitted extends EventObject,\n TInputSchema extends StandardSchemaV1 = StandardSchemaV1,\n TOutputSchema extends StandardSchemaV1 = StandardSchemaV1\n> {\n id?: string;\n validator?: ActorLogicValidator;\n schemas?: {\n input?: TInputSchema;\n output?: TOutputSchema;\n };\n context: TContext | ((args: { input: TInput }) => TContext);\n run: StepLogicFunction<TContext, TOutput, TEvent, TInput, TEmitted>;\n}\n\ninterface StepTransition<\n TContext,\n TOutput,\n TEvent extends EventObject,\n TInput,\n TEmitted extends EventObject\n> {\n (\n snapshot: StepSnapshot<TContext, TOutput, TInput>,\n event: TEvent,\n actorScope: ActorScope<\n StepSnapshot<TContext, TOutput, TInput>,\n TEvent,\n AnyActorSystem,\n TEmitted\n >\n ): [StepSnapshot<TContext, TOutput, TInput>, ExecutableEffect[]];\n (\n snapshot: StepSnapshot<TContext, TOutput, TInput>,\n event: TEvent,\n actorScope: ActorScope<\n StepSnapshot<TContext, TOutput, TInput>,\n TEvent,\n AnyActorSystem,\n TEmitted\n >\n ): StepSnapshot<TContext, TOutput, TInput>;\n}\n\n/** @public */\nexport type StepActorLogic<\n TContext,\n TOutput,\n TEvent extends EventObject = EventObject,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n> = Omit<\n ActorLogic<\n StepSnapshot<TContext, TOutput, TInput>,\n TEvent,\n TInput,\n AnyActorSystem,\n TEmitted\n >,\n 'transition'\n> & {\n id?: string;\n transition: StepTransition<TContext, TOutput, TEvent, TInput, TEmitted>;\n};\n\n/** @public */\nexport type StepActorRef<\n TContext,\n TOutput,\n TEvent extends EventObject,\n TInput\n> = ActorRefFrom<StepActorLogic<TContext, TOutput, TEvent, TInput>>;\n\nconst effectStates = new WeakMap<\n AnyActorRef,\n Map<PropertyKey, { cleanup?: () => void }>\n>();\n\nfunction getEffectState(self: AnyActorRef) {\n let state = effectStates.get(self);\n if (!state) {\n state = new Map();\n effectStates.set(self, state);\n }\n return state;\n}\n\nfunction executeLogicEffect(\n self: AnyActorRef,\n key: string | undefined,\n effect: () => void | (() => void)\n): void {\n const state = getEffectState(self);\n if (key !== undefined && state.has(key)) {\n return;\n }\n const cleanup = effect();\n state.set(key ?? Symbol(), {\n cleanup: typeof cleanup === 'function' ? cleanup : undefined\n });\n}\n\nfunction cleanupLogicEffects(self: AnyActorRef): void {\n const state = effectStates.get(self);\n if (!state) {\n return;\n }\n effectStates.delete(self);\n let failure: { error: unknown } | undefined;\n for (const { cleanup } of state.values()) {\n try {\n cleanup?.();\n } catch (error) {\n failure ??= { error };\n }\n }\n if (failure) throw failure.error;\n}\n\nfunction resolveContext<TContext, TInput>(\n context: TContext | ((args: { input: TInput }) => TContext),\n input: TInput\n) {\n return typeof context === 'function'\n ? (context as (args: { input: TInput }) => TContext)({ input })\n : context;\n}\n\n/** @public */\nexport function createStepLogic<\n TContext,\n const TInputSchema extends StandardSchemaV1,\n const TOutputSchema extends StandardSchemaV1,\n TEvent extends EventObject = EventObject,\n TEmitted extends EventObject = EventObject\n>(\n config: StepLogicConfig<\n TContext,\n StandardSchemaV1.InferOutput<TOutputSchema>,\n TEvent,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted,\n TInputSchema,\n TOutputSchema\n > & {\n schemas: { input: TInputSchema; output: TOutputSchema };\n }\n): StepActorLogic<\n TContext,\n StandardSchemaV1.InferOutput<TOutputSchema>,\n TEvent,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted\n>;\nexport function createStepLogic<\n TContext,\n TOutput,\n const TInputSchema extends StandardSchemaV1,\n TEvent extends EventObject = EventObject,\n TEmitted extends EventObject = EventObject\n>(\n config: StepLogicConfig<\n TContext,\n TOutput,\n TEvent,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted,\n TInputSchema\n > & {\n schemas: { input: TInputSchema; output?: undefined };\n }\n): StepActorLogic<\n TContext,\n TOutput,\n TEvent,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted\n>;\nexport function createStepLogic<\n TContext,\n const TOutputSchema extends StandardSchemaV1,\n TEvent extends EventObject = EventObject,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n config: StepLogicConfig<\n TContext,\n StandardSchemaV1.InferOutput<TOutputSchema>,\n TEvent,\n TInput,\n TEmitted,\n StandardSchemaV1,\n TOutputSchema\n > & {\n schemas: { input?: undefined; output: TOutputSchema };\n }\n): StepActorLogic<\n TContext,\n StandardSchemaV1.InferOutput<TOutputSchema>,\n TEvent,\n TInput,\n TEmitted\n>;\nexport function createStepLogic<\n TContext,\n TOutput = unknown,\n TEvent extends EventObject = EventObject,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n config: StepLogicConfig<TContext, TOutput, TEvent, TInput, TEmitted>\n): StepActorLogic<TContext, TOutput, TEvent, TInput, TEmitted>;\nexport function createStepLogic<\n TContext,\n TOutput = unknown,\n TEvent extends EventObject = EventObject,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n config: StepLogicConfig<TContext, TOutput, TEvent, TInput, TEmitted>\n): StepActorLogic<TContext, TOutput, TEvent, TInput, TEmitted> {\n const calculateTransition = ((snapshot, event, actorScope) => {\n if (snapshot.status !== 'active') {\n return [snapshot, []];\n }\n\n if (event.type === XSTATE_STOP) {\n return [\n {\n ...snapshot,\n status: 'stopped',\n input: undefined\n },\n [\n createCustomEffect('@xstate.cleanup', () =>\n cleanupLogicEffects(actorScope.self)\n )\n ]\n ];\n }\n\n if (event.type === XSTATE_LOGIC_EFFECT_START) {\n return [\n {\n ...snapshot,\n effects: {\n ...snapshot.effects,\n [(event as any).key]: { status: 'active' }\n }\n },\n []\n ];\n }\n\n if (event.type === XSTATE_LOGIC_EFFECT_RESOLVE) {\n return [\n {\n ...snapshot,\n effects: {\n ...snapshot.effects,\n [(event as any).key]: {\n status: 'done',\n output: (event as any).output\n }\n }\n },\n []\n ];\n }\n\n if (event.type === XSTATE_LOGIC_EFFECT_REJECT) {\n return [\n {\n ...snapshot,\n effects: {\n ...snapshot.effects,\n [(event as any).key]: {\n status: 'error',\n error: (event as any).error\n }\n }\n },\n []\n ];\n }\n\n const effects: ExecutableEffect[] = [];\n const trackedEffects: Record<string, StepEffectState> = Object.create(null);\n const enqueueEffect = (\n key: string,\n exec: (runtime?: Partial<ActorSystemRuntime>) => void | (() => void)\n ) => {\n const recorded =\n snapshot.effects &&\n Object.prototype.hasOwnProperty.call(snapshot.effects, key)\n ? snapshot.effects[key]\n : undefined;\n // Active process-local attachments must be recreated on restore. A\n // completed effect remains memoized; ordinary events never reattach.\n if (\n recorded &&\n !(event.type === XSTATE_INIT && recorded.status === 'active')\n ) {\n return;\n }\n effects.push(\n createCustomEffect(\n '@xstate.effect',\n (runtime = actorScope.self.system) =>\n executeLogicEffect(actorScope.self, key, () => exec(runtime)),\n { key }\n )\n );\n trackedEffects[key] = { status: 'active' };\n };\n const enq: StepLogicEnqueue<TEvent, TEmitted> = {\n emit: (emitted) => {\n effects.push(createEmitEffect(actorScope, emitted));\n },\n sendBack: (sentEvent) => {\n const parent = actorScope.self._parent;\n if (parent) {\n effects.push(createSendToEffect(actorScope, parent, sentEvent));\n }\n },\n raise: (raisedEvent) => {\n effects.push(\n createSendToEffect(actorScope, actorScope.self, raisedEvent)\n );\n },\n effect: ((keyOrExec, maybeExec) => {\n if (typeof keyOrExec === 'string') {\n enqueueEffect(keyOrExec, maybeExec);\n return;\n }\n const exec = keyOrExec as (\n runtime?: Partial<ActorSystemRuntime>\n ) => void | (() => void);\n effects.push(\n createCustomEffect(\n '@xstate.effect',\n (runtime = actorScope.self.system) =>\n executeLogicEffect(actorScope.self, undefined, () =>\n exec(runtime)\n )\n )\n );\n }) as StepLogicEnqueue<TEvent, TEmitted>['effect']\n };\n\n const patch = config.run(\n {\n context: snapshot.context,\n event,\n input: snapshot.input!,\n system: actorScope.system,\n self: actorScope.self as any,\n emit: actorScope.emit\n } as StepLogicArgs<TContext, TEvent, TInput>,\n enq\n );\n\n const nextSnapshot = {\n ...snapshot,\n ...(patch || {})\n } as StepSnapshot<TContext, TOutput, TInput>;\n\n if ('context' in snapshot || patch?.context !== undefined) {\n (nextSnapshot as any).context = patch?.context ?? snapshot.context;\n }\n if (patch?.effects || Object.keys(trackedEffects).length) {\n (nextSnapshot as any).effects = {\n ...snapshot.effects,\n ...patch?.effects,\n ...trackedEffects\n };\n }\n\n return finalizeTransitionResult(actorScope, snapshot, [\n nextSnapshot,\n effects\n ]);\n }) as StepTransition<TContext, TOutput, TEvent, TInput, TEmitted>;\n\n const transition = ((snapshot, event, actorScope) => {\n if (config.validator) {\n const sourceRef = (actorScope.self as any)._lastSourceRef;\n const eventOrigin = sourceRef ? 'actor' : 'external';\n const error = config.validator.check({\n kind: 'event',\n logic,\n event,\n eventOrigin\n });\n if (error) {\n // Boundary fault: rejected (never delivered), not an actor error.\n return [\n snapshot,\n [\n createDeadLetterEffect(\n actorScope,\n sourceRef,\n event,\n 'invalidEvent',\n {\n issues: (error as { issues?: DeadLetterDetail['issues'] })\n .issues,\n error\n }\n )\n ]\n ];\n }\n }\n const result = calculateTransition(snapshot, event, actorScope);\n if (config.validator) {\n assertValid(config.validator, {\n kind: 'result',\n logic,\n snapshot: result[0],\n effects: result[1]\n });\n }\n return result;\n }) as StepTransition<TContext, TOutput, TEvent, TInput, TEmitted>;\n\n const logic: StepActorLogic<TContext, TOutput, TEvent, TInput, TEmitted> = {\n id: config.id,\n config,\n validator: config.validator,\n transition,\n start: (snapshot, actorScope, options) => {\n if (!options?.restored) {\n return;\n }\n const [nextSnapshot, effects] = transition(\n snapshot,\n createInitEvent(snapshot.input) as unknown as TEvent,\n actorScope\n );\n Object.assign(snapshot, nextSnapshot);\n for (const effect of effects) {\n actorScope.actionExecutor(effect);\n }\n },\n initialTransition: (input, actorScope) => {\n if (config.validator) {\n assertValid(config.validator, {\n kind: 'input',\n logic,\n input\n });\n }\n const context = resolveContext(config.context, input);\n const snapshot = {\n status: 'active' as const,\n output: undefined,\n error: undefined,\n input\n };\n\n if (context !== undefined) {\n (snapshot as any).context = context;\n }\n\n return transition(\n { ...snapshot } as StepSnapshot<TContext, TOutput, TInput>,\n createInitEvent(input) as unknown as TEvent,\n actorScope\n );\n },\n getInitialSnapshot: (actorScope, input) =>\n logic.initialTransition(input, actorScope)[0],\n getPersistedSnapshot: (snapshot) => snapshot,\n restoreSnapshot: (snapshot: any) => snapshot\n };\n\n return logic;\n}\n","import { createActor } from '../createActor.ts';\nimport type { ActorFromLogic } from '../types.ts';\nimport { createStepLogic } from './logic.ts';\nexport {\n createCallbackLogic,\n type CallbackActorLogic,\n type CallbackActorRef,\n type CallbackLogicConfig,\n type CallbackSnapshot,\n type CallbackLogicFunction\n} from './callback.ts';\nexport {\n createObservableLogic,\n createEventObservableLogic,\n type EventObservableLogicConfig,\n type EventObservableLogicFunction,\n type ObservableActorLogic,\n type ObservableActorRef,\n type ObservableLogicConfig,\n type ObservableLogicFunction,\n type ObservableSnapshot\n} from './observable.ts';\nexport {\n createStepLogic,\n type StepActorLogic,\n type StepActorRef,\n type StepLogicArgs,\n type StepLogicConfig,\n type StepEffectState,\n type StepLogicEnqueue,\n type StepLogicFunction,\n type StepPatch,\n type StepSnapshot\n} from './logic.ts';\nexport {\n createAsyncLogic,\n type AsyncActorLogic,\n type AsyncActorRef,\n type AsyncSnapshot,\n type AsyncLogicArgs,\n type AsyncLogicConfig,\n type AsyncLogicEnqueue,\n type AsyncLogicFunction,\n TimeoutError\n} from './promise.ts';\nexport {\n createListenerLogic,\n type ListenerActorLogic,\n type ListenerActorRef,\n type ListenerSnapshot,\n type ListenerInput\n} from './listener.ts';\nexport {\n createSubscriptionLogic,\n type SubscriptionActorLogic,\n type SubscriptionActorRef,\n type SubscriptionSnapshot,\n type SubscriptionInput,\n type SubscriptionMappers\n} from './subscription.ts';\n\nconst emptyLogic = /* #__PURE__ */ createStepLogic<undefined, undefined>({\n context: undefined,\n run: () => undefined\n});\n\n/** @public */\nexport function createEmptyActor(): ActorFromLogic<typeof emptyLogic> {\n return createActor(emptyLogic);\n}\n","import { AnyActorScope, createEmptyActor } from '../index.ts';\n\nexport function createMockActorScope(): AnyActorScope {\n const emptyActor = createEmptyActor();\n return {\n self: emptyActor,\n logger: console.log,\n id: '',\n sessionId: Math.random().toString(32).slice(2),\n defer: () => {},\n system: emptyActor.system, // TODO: mock system?\n stopChild: () => {},\n emit: () => {},\n actionExecutor: () => {}\n };\n}\n","import {\n EventObject,\n AnyStateMachine,\n StateNode,\n AnyActorLogic,\n EventFromLogic,\n Snapshot,\n InputFrom,\n SnapshotFrom,\n isMachineSnapshot\n} from '../index.ts';\nimport type {\n SerializedEvent,\n SerializedSnapshot,\n StatePath,\n DirectedGraphEdge,\n DirectedGraphNode,\n DirectedGraphDiagnostic,\n TraversalOptions,\n AnyStateNode,\n TraversalConfig\n} from './types.ts';\nimport { createMockActorScope } from './actorScope.ts';\nimport {\n getAllOwnEvents,\n matchesEvent,\n matchesEventDescriptor\n} from '../utils.ts';\n\n/**\n * Returns all state nodes of the given `node`.\n *\n * @public\n * @param stateNode State node to recursively get child state nodes from\n * @public\n */\nexport function getDescendantStateNodes(stateNode: {\n states: Record<string, AnyStateNode | StateNode<never, EventObject>>;\n}): AnyStateNode[] {\n const { states } = stateNode;\n const nodes = Object.keys(states).reduce((accNodes, stateKey) => {\n const childStateNode = states[stateKey] as AnyStateNode;\n const childStateNodes = getDescendantStateNodes(childStateNode);\n\n accNodes.push(childStateNode, ...childStateNodes);\n return accNodes;\n }, [] as AnyStateNode[]);\n\n return nodes;\n}\n\nfunction getChildren(stateNode: AnyStateNode): AnyStateNode[] {\n if (!stateNode.states) {\n return [];\n }\n\n const children = Object.keys(stateNode.states).map((key) => {\n return stateNode.states[key];\n });\n\n return children;\n}\n\n/** @public */\nexport function serializeSnapshot(snapshot: Snapshot<any>): SerializedSnapshot {\n const { value, context } = snapshot as any;\n const machineSnapshot = isMachineSnapshot(snapshot) ? snapshot : undefined;\n const inputs = machineSnapshot?.getInputs();\n const history = machineSnapshot?.historyValue;\n return JSON.stringify({\n value,\n context: Object.keys(context ?? {}).length ? context : undefined,\n // Equal values and root contexts can still make different decisions when\n // their state inputs or remembered history differ. Empty records remain\n // omitted to preserve the keys of machines that do not use these features.\n stateInputs: inputs && Object.keys(inputs).length ? inputs : undefined,\n historyValue:\n history && Object.keys(history).length\n ? Object.fromEntries(\n Object.entries(history).map(([id, nodes]) => [\n id,\n nodes.map((node) => node.id)\n ])\n )\n : undefined\n }) as SerializedSnapshot;\n}\n\nfunction serializeEvent<TEvent extends EventObject>(\n event: TEvent\n): SerializedEvent {\n return JSON.stringify(event) as SerializedEvent;\n}\n\nfunction resolveEventCases<TSnapshot>(\n cases: object,\n state: TSnapshot,\n defaults?: EventObject[]\n): EventObject[] {\n const events: EventObject[] = [];\n const sources = cases as Record<\n string,\n readonly object[] | ((state: TSnapshot) => readonly object[])\n >;\n const entries = Object.entries(sources).filter(\n ([, source]) => source !== undefined\n );\n const applicable = (type: string) =>\n !defaults ||\n defaults.some((event) => matchesEventDescriptor(type, event.type));\n for (const [type, source] of entries) {\n if (!applicable(type)) {\n continue;\n }\n const samples = typeof source === 'function' ? source(state) : source;\n if (!Array.isArray(samples) || !samples.length) {\n throw new Error(`Event cases for \"${type}\" must be a non-empty array`);\n }\n for (const payload of samples) {\n const event = { ...payload, type };\n if (\n !defaults ||\n defaults.some(\n ({ type: descriptor, ...pattern }) =>\n matchesEventDescriptor(type, descriptor) &&\n matchesEvent(event, pattern)\n )\n ) {\n events.push(event);\n }\n }\n }\n return [\n ...events,\n ...(defaults?.filter(\n (event) => !entries.some(([type]) => type === event.type)\n ) ?? [])\n ];\n}\n\nfunction createDefaultMachineOptions<TMachine extends AnyStateMachine>(\n machine: TMachine,\n options?: TraversalOptions<\n SnapshotFrom<TMachine>,\n EventFromLogic<TMachine>,\n InputFrom<TMachine>\n >\n): TraversalOptions<\n SnapshotFrom<TMachine>,\n EventFromLogic<TMachine>,\n InputFrom<TMachine>\n> {\n const traversalOptions: TraversalOptions<\n SnapshotFrom<TMachine>,\n EventFromLogic<TMachine>,\n InputFrom<TMachine>\n > = {\n serializeState: serializeSnapshot,\n serializeEvent,\n ...options,\n events: (state) => getAllOwnEvents(state) as EventFromLogic<TMachine>[],\n fromState:\n options?.fromState ??\n (machine.getInitialSnapshot(\n createMockActorScope(),\n options?.input\n ) as SnapshotFrom<TMachine>)\n };\n\n return traversalOptions;\n}\n\n/** @public */\nexport function toDirectedGraph(\n stateMachine: AnyStateNode | AnyStateMachine\n): DirectedGraphNode {\n const stateNode = (\n isMachineLogic(stateMachine) ? stateMachine.root : stateMachine\n ) as AnyStateNode; // TODO: accept only machines\n\n const diagnostics: DirectedGraphDiagnostic[] = [];\n const transitions = [\n ...[...stateNode.transitions.values()].flat(),\n ...(stateNode.always ?? [])\n ];\n const edges: DirectedGraphEdge[] = transitions.flatMap(\n (t, transitionIndex) => {\n if (t.to) {\n diagnostics.push({\n code: 'dynamic-target',\n stateId: stateNode.id,\n eventType: t.eventType,\n transitionId: `${stateNode.id}:${transitionIndex}`,\n message:\n 'Transition function destinations require execution or source analysis.'\n });\n }\n // A transition function computes its target when it runs, so there is\n // no static edge to draw; a targetless transition stays in its state.\n const targets = t.target ?? (t.to ? [] : [stateNode]);\n\n return targets.map((target, targetIndex) => {\n const edge: DirectedGraphEdge = {\n id: `${stateNode.id}:${transitionIndex}:${targetIndex}`,\n source: stateNode,\n target: target as AnyStateNode,\n transition: t,\n label: {\n text: t.eventType,\n toJSON: () => ({ text: t.eventType })\n },\n toJSON: () => {\n const { label } = edge;\n\n return { source: stateNode.id, target: target.id, label };\n }\n };\n\n return edge;\n });\n }\n );\n\n const children = getChildren(stateNode).map(toDirectedGraph);\n diagnostics.push(...children.flatMap((child) => child.analysis.diagnostics));\n const graph = {\n id: stateNode.id,\n stateNode: stateNode,\n children,\n edges,\n analysis: {\n transitionTargetsComplete: diagnostics.length === 0,\n diagnostics\n },\n toJSON: () => {\n const { id, children, edges: graphEdges } = graph;\n return { id, children, edges: graphEdges, analysis: graph.analysis };\n }\n };\n\n return graph;\n}\n\nfunction isMachineLogic(logic: unknown): logic is AnyStateMachine {\n if (!logic || typeof logic !== 'object') {\n return false;\n }\n\n const machine = logic as Partial<AnyStateMachine>;\n const root = machine.root as Partial<AnyStateNode> | undefined;\n\n return (\n !!root &&\n typeof root === 'object' &&\n typeof root.id === 'string' &&\n typeof root.states === 'object' &&\n typeof root.transitions?.values === 'function' &&\n typeof machine.getStateNodeById === 'function' &&\n typeof machine.resolveState === 'function' &&\n typeof machine.getTransitionData === 'function'\n );\n}\n\nexport function resolveTraversalOptions<TLogic extends AnyActorLogic>(\n logic: TLogic,\n traversalOptions?: TraversalOptions<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>,\n InputFrom<TLogic>\n >,\n defaultOptions?: TraversalOptions<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>,\n InputFrom<TLogic>\n >\n): TraversalConfig<SnapshotFrom<TLogic>, EventFromLogic<TLogic>> {\n const resolvedDefaultOptions =\n defaultOptions ??\n (isMachineLogic(logic)\n ? (createDefaultMachineOptions(\n logic,\n traversalOptions as any\n ) as TraversalOptions<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>,\n InputFrom<TLogic>\n >)\n : undefined);\n const serializeState =\n traversalOptions?.serializeState ??\n resolvedDefaultOptions?.serializeState ??\n ((state) => JSON.stringify(state));\n const eventSource =\n traversalOptions?.events ?? resolvedDefaultOptions?.events ?? [];\n const traversalConfig: TraversalConfig<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>\n > = {\n serializeState,\n serializeEvent,\n filterEvents: undefined,\n limit: Infinity,\n toState: undefined,\n // Traversal should not continue past the `toState` predicate\n // since the target state has already been reached at that point\n stopWhen: traversalOptions?.toState,\n ...resolvedDefaultOptions,\n ...traversalOptions,\n // Synthetic completion/delay events are supported by the machine runtime.\n events: (typeof eventSource === 'function' || Array.isArray(eventSource)\n ? eventSource\n : (state: SnapshotFrom<TLogic>) =>\n resolveEventCases(\n eventSource,\n state,\n isMachineSnapshot(state) ? getAllOwnEvents(state) : undefined\n )) as TraversalConfig<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>\n >['events'],\n fromState: traversalOptions?.fromState ?? resolvedDefaultOptions?.fromState\n };\n\n return traversalConfig;\n}\n\n/** @public */\nexport function joinPaths<\n TSnapshot extends Snapshot<unknown>,\n TEvent extends EventObject\n>(\n headPath: StatePath<TSnapshot, TEvent>,\n tailPath: StatePath<TSnapshot, TEvent>\n): StatePath<TSnapshot, TEvent> {\n const secondPathSource = tailPath.steps[0].state;\n\n if (secondPathSource !== headPath.state) {\n throw new Error(`Paths cannot be joined`);\n }\n\n return {\n state: tailPath.state,\n // e.g. [A, B, C] + [C, D, E] = [A, B, C, D, E]\n steps: headPath.steps.concat(tailPath.steps.slice(1)),\n weight: headPath.weight + tailPath.weight\n };\n}\n","export function createTraversalError(\n state: string,\n event: string,\n cause: unknown\n): Error {\n return new Error(\n `Unable to evaluate graph transition from state ${state} with event ${event}. If the transition needs event payloads, provide representative events using the \"events\" option.`,\n { cause }\n );\n}\n","import {\n ActorScope,\n ActorLogic,\n ActorSystem,\n EventObject,\n Snapshot,\n AnyActorLogic,\n SnapshotFrom,\n EventFromLogic\n} from '../index.ts';\nimport {\n SerializedEvent,\n SerializedSnapshot,\n TraversalOptions,\n AdjacencyMap,\n AdjacencyValue,\n EventCaseOptionsArgs,\n EventListOptions,\n TraversalEvent\n} from './types';\nimport { resolveTraversalOptions } from './graph.ts';\nimport { createMockActorScope } from './actorScope.ts';\nimport { createTraversalError } from './traversalError.ts';\n\nfunction resolveTransitionSnapshot<TSnapshot>(\n result: TSnapshot | [TSnapshot, unknown[]]\n): TSnapshot {\n return Array.isArray(result) ? result[0] : result;\n}\n\n/** @public */\nexport function getAdjacencyMap<TLogic extends AnyActorLogic>(\n logic: TLogic,\n ...[options]: EventCaseOptionsArgs<NoInfer<TLogic>>\n): AdjacencyMap<SnapshotFrom<TLogic>, EventFromLogic<TLogic>>;\nexport function getAdjacencyMap<\n TLogic extends AnyActorLogic,\n const TEvents extends readonly TraversalEvent<\n SnapshotFrom<NoInfer<TLogic>>,\n EventFromLogic<NoInfer<TLogic>>\n >[]\n>(\n logic: TLogic,\n options: EventListOptions<NoInfer<TLogic>, TEvents>\n): AdjacencyMap<SnapshotFrom<TLogic>, EventFromLogic<TLogic>>;\nexport function getAdjacencyMap<\n TSnapshot extends Snapshot<unknown>,\n TEvent extends EventObject,\n TInput,\n TSystem extends ActorSystem<any> = ActorSystem<any>\n>(\n logic: ActorLogic<TSnapshot, TEvent, TInput, TSystem>,\n options?: TraversalOptions<TSnapshot, TEvent, TInput>\n): AdjacencyMap<TSnapshot, TEvent> {\n 'use strict';\n const { transition } = logic;\n const {\n serializeEvent,\n serializeState,\n events: getEvents,\n filterEvents,\n limit,\n fromState: customFromState,\n stopWhen\n } = resolveTraversalOptions(logic, options);\n const actorScope = createMockActorScope() as ActorScope<\n TSnapshot,\n TEvent,\n TSystem\n >;\n const fromState =\n customFromState ??\n logic.getInitialSnapshot(\n actorScope,\n // TODO: fix this\n options?.input as TInput\n );\n\n const adj: AdjacencyMap<TSnapshot, TEvent> = Object.create(null);\n\n let iterations = 0;\n const queue: Array<{\n nextState: TSnapshot;\n event: TEvent | undefined;\n prevState: TSnapshot | undefined;\n }> = [{ nextState: fromState, event: undefined, prevState: undefined }];\n\n for (let head = 0; head < queue.length; head++) {\n const { nextState: state, event, prevState } = queue[head];\n // Release processed entries without shifting the remaining frontier.\n if (head > 4096 && head * 2 > queue.length) {\n queue.splice(0, head + 1);\n head = -1;\n }\n\n if (iterations++ > limit) {\n throw new Error('Traversal limit exceeded');\n }\n\n const serializedState = serializeState(\n state,\n event,\n prevState\n ) as SerializedSnapshot;\n if (adj[serializedState]) {\n continue;\n }\n\n adj[serializedState] = {\n state,\n transitions: Object.create(null)\n };\n\n if (stopWhen && stopWhen(state)) {\n continue;\n }\n\n const events =\n typeof getEvents === 'function' ? getEvents(state) : getEvents;\n\n for (const nextEvent of events) {\n if (filterEvents && !filterEvents(state, nextEvent)) {\n continue;\n }\n\n const serializedEvent = serializeEvent(nextEvent) as SerializedEvent;\n let nextSnapshot: TSnapshot;\n try {\n nextSnapshot = resolveTransitionSnapshot(\n transition(state, nextEvent, actorScope)\n );\n } catch (cause) {\n throw createTraversalError(serializedState, serializedEvent, cause);\n }\n\n adj[serializedState].transitions[serializedEvent] = {\n event: nextEvent,\n state: nextSnapshot\n };\n queue.push({\n nextState: nextSnapshot,\n event: nextEvent,\n prevState: state\n });\n }\n }\n\n return adj;\n}\n\n/** @public */\nexport function adjacencyMapToArray<TSnapshot, TEvent>(\n adjMap: AdjacencyMap<TSnapshot, TEvent>\n): Array<{\n state: TSnapshot;\n event: TEvent;\n nextState: TSnapshot;\n}> {\n const adjList: Array<{\n state: TSnapshot;\n event: TEvent;\n nextState: TSnapshot;\n }> = [];\n\n for (const adjValue of Object.values(adjMap)) {\n for (const transition of Object.values(\n (adjValue as AdjacencyValue<TSnapshot, TEvent>).transitions\n )) {\n adjList.push({\n state: (adjValue as AdjacencyValue<TSnapshot, TEvent>).state,\n event: transition.event,\n nextState: transition.state\n });\n }\n }\n\n return adjList;\n}\n","import { XSTATE_INIT } from '../constants.ts';\nimport { StatePath } from './types.ts';\n\n// TODO: rewrite parts of the algorithm leading to this to make this function obsolete\nexport function alterPath<T extends StatePath<any, any>>(path: T): T {\n let steps: T['steps'] = [];\n\n if (!path.steps.length) {\n steps = [\n {\n state: path.state,\n event: { type: XSTATE_INIT }\n }\n ];\n } else {\n for (let i = 0; i < path.steps.length; i++) {\n const step = path.steps[i];\n\n steps.push({\n state: step.state,\n event: i === 0 ? { type: XSTATE_INIT } : path.steps[i - 1].event\n });\n }\n steps.push({\n state: path.state,\n event: path.steps[path.steps.length - 1].event\n });\n }\n return {\n ...path,\n steps\n };\n}\n","import {\n ActorScope,\n ActorLogic,\n ActorSystem,\n EventObject,\n Snapshot\n} from '../index.ts';\nimport { StatePath, Steps, TraversalOptions, TraversalEvent } from './types.ts';\nimport { resolveTraversalOptions } from './graph.ts';\nimport { alterPath } from './alterPath.ts';\nimport { createMockActorScope } from './actorScope.ts';\nimport { createTraversalError } from './traversalError.ts';\n\n/** @public */\nexport function getPathsFromEvents<\n TSnapshot extends Snapshot<unknown>,\n TEvent extends EventObject,\n TInput,\n TSystem extends ActorSystem<any> = ActorSystem<any>\n>(\n logic: ActorLogic<TSnapshot, TEvent, TInput, TSystem>,\n events: TEvent[],\n options?: Omit<TraversalOptions<TSnapshot, TEvent, TInput>, 'events'> & {\n events?:\n | readonly TraversalEvent<TSnapshot, TEvent>[]\n | ((state: TSnapshot) => readonly TraversalEvent<TSnapshot, TEvent>[]);\n }\n): Array<StatePath<TSnapshot, TEvent>> {\n const resolvedOptions = resolveTraversalOptions(logic, {\n events,\n ...options\n });\n const actorScope = createMockActorScope() as ActorScope<\n TSnapshot,\n TEvent,\n TSystem\n >;\n const fromState =\n resolvedOptions.fromState ??\n logic.getInitialSnapshot(\n actorScope,\n // TODO: fix this\n options?.input as TInput\n );\n\n const { serializeState, serializeEvent, filterEvents, stopWhen, limit } =\n resolvedOptions;\n const steps: Steps<TSnapshot, TEvent> = [];\n let state = fromState;\n let stateSerial = serializeState(state, undefined, undefined);\n for (const event of events) {\n if (steps.length >= limit) {\n throw new Error('Traversal limit exceeded');\n }\n const eventSerial = serializeEvent(event);\n let nextEvent: TEvent | undefined = event;\n if (options?.events !== undefined) {\n const candidates =\n typeof options.events === 'function'\n ? options.events(state)\n : options.events;\n nextEvent = undefined;\n for (let index = candidates.length - 1; index >= 0; index--) {\n const candidate = candidates[index] as TEvent;\n if (\n (!filterEvents || filterEvents(state, candidate)) &&\n serializeEvent(candidate) === eventSerial\n ) {\n nextEvent = candidate;\n break;\n }\n }\n } else if (filterEvents && !filterEvents(state, event)) {\n nextEvent = undefined;\n }\n if (!nextEvent || stopWhen?.(state)) {\n throw new Error(\n `Invalid transition from ${stateSerial} with ${eventSerial}`\n );\n }\n steps.push({ state, event });\n let result: ReturnType<typeof logic.transition>;\n try {\n result = logic.transition(state, nextEvent, actorScope);\n } catch (cause) {\n throw createTraversalError(stateSerial, eventSerial, cause);\n }\n const nextState = Array.isArray(result) ? result[0] : result;\n stateSerial = serializeState(nextState, event, state);\n state = nextState;\n }\n\n // If it is expected to reach a specific state (`toState`) and that state\n // isn't reached, there are no paths\n if (resolvedOptions.toState && !resolvedOptions.toState(state)) {\n return [];\n }\n\n return [\n alterPath({\n state,\n steps,\n weight: steps.length\n })\n ];\n}\n","import {\n AnyActorLogic,\n EventFromLogic,\n InputFrom,\n SnapshotFrom\n} from '../index.ts';\nimport { getAdjacencyMap } from './adjacency.ts';\nimport { alterPath } from './alterPath.ts';\nimport { resolveTraversalOptions } from './graph.ts';\nimport {\n SerializedEvent,\n SerializedSnapshot,\n StatePath,\n StatePlanMap,\n EventCaseOptionsArgs,\n EventListOptions,\n TraversalEvent,\n TraversalOptions\n} from './types.ts';\nimport { createMockActorScope } from './actorScope.ts';\n\n/** @public */\nexport function getShortestPaths<TLogic extends AnyActorLogic>(\n logic: TLogic,\n ...[options]: EventCaseOptionsArgs<NoInfer<TLogic>>\n): Array<StatePath<SnapshotFrom<TLogic>, EventFromLogic<TLogic>>>;\nexport function getShortestPaths<\n TLogic extends AnyActorLogic,\n const TEvents extends readonly TraversalEvent<\n SnapshotFrom<NoInfer<TLogic>>,\n EventFromLogic<NoInfer<TLogic>>\n >[]\n>(\n logic: TLogic,\n options: EventListOptions<NoInfer<TLogic>, TEvents>\n): Array<StatePath<SnapshotFrom<TLogic>, EventFromLogic<TLogic>>>;\nexport function getShortestPaths<TLogic extends AnyActorLogic>(\n logic: TLogic,\n options?: TraversalOptions<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>,\n InputFrom<TLogic>\n >\n): Array<StatePath<SnapshotFrom<TLogic>, EventFromLogic<TLogic>>> {\n type TInternalState = SnapshotFrom<TLogic>;\n type TEvent = EventFromLogic<TLogic>;\n\n const resolvedOptions = resolveTraversalOptions(logic, options);\n const serializeState = resolvedOptions.serializeState as (\n ...args: Parameters<typeof resolvedOptions.serializeState>\n ) => SerializedSnapshot;\n const fromState =\n resolvedOptions.fromState ??\n logic.getInitialSnapshot(createMockActorScope(), options?.input);\n const adjacency = getAdjacencyMap(logic, { ...resolvedOptions, fromState });\n\n // weight, state, event\n const weightMap = new Map<\n SerializedSnapshot,\n {\n weight: number;\n state: SerializedSnapshot | undefined;\n event: TEvent | undefined;\n }\n >();\n const stateMap = new Map<SerializedSnapshot, TInternalState>();\n const serializedFromState = serializeState(fromState, undefined, undefined);\n stateMap.set(serializedFromState, fromState);\n\n weightMap.set(serializedFromState, {\n weight: 0,\n state: undefined,\n event: undefined\n });\n const unvisited = new Set<SerializedSnapshot>();\n const visited = new Set<SerializedSnapshot>();\n\n unvisited.add(serializedFromState);\n for (const serializedState of unvisited) {\n const prevState = stateMap.get(serializedState);\n const { weight } = weightMap.get(serializedState)!;\n for (const event of Object.keys(\n adjacency[serializedState].transitions\n ) as SerializedEvent[]) {\n const { state: nextState, event: eventObject } =\n adjacency[serializedState].transitions[event];\n const nextSerializedState = serializeState(\n nextState,\n eventObject,\n prevState\n );\n stateMap.set(nextSerializedState, nextState);\n if (!weightMap.has(nextSerializedState)) {\n weightMap.set(nextSerializedState, {\n weight: weight + 1,\n state: serializedState,\n event: eventObject\n });\n } else {\n const { weight: nextWeight } = weightMap.get(nextSerializedState)!;\n if (nextWeight > weight + 1) {\n weightMap.set(nextSerializedState, {\n weight: weight + 1,\n state: serializedState,\n event: eventObject\n });\n }\n }\n if (!visited.has(nextSerializedState)) {\n unvisited.add(nextSerializedState);\n }\n }\n visited.add(serializedState);\n unvisited.delete(serializedState);\n }\n\n const statePlanMap: StatePlanMap<TInternalState, TEvent> =\n Object.create(null);\n const paths: Array<StatePath<TInternalState, TEvent>> = [];\n\n weightMap.forEach(\n ({ weight, state: fromState, event: fromEvent }, stateSerial) => {\n const state = stateMap.get(stateSerial)!;\n const steps =\n fromState === undefined\n ? []\n : statePlanMap[fromState].paths[0].steps.concat({\n state: stateMap.get(fromState)!,\n event: fromEvent!\n });\n\n paths.push({\n state,\n steps,\n weight\n });\n statePlanMap[stateSerial] = {\n state,\n paths: [\n {\n state,\n steps,\n weight\n }\n ]\n };\n }\n );\n\n if (resolvedOptions.toState) {\n return paths\n .filter((path) => resolvedOptions.toState!(path.state))\n .map(alterPath);\n }\n\n return paths.map(alterPath);\n}\n","import {\n AnyActorLogic,\n EventFromLogic,\n InputFrom,\n SnapshotFrom\n} from '../index.ts';\nimport {\n SerializedEvent,\n SerializedSnapshot,\n StatePath,\n Steps,\n EventCaseOptionsArgs,\n EventListOptions,\n TraversalEvent,\n TraversalOptions,\n VisitedContext\n} from './types.ts';\nimport { resolveTraversalOptions } from './graph.ts';\nimport { getAdjacencyMap } from './adjacency.ts';\nimport { alterPath } from './alterPath.ts';\nimport { createMockActorScope } from './actorScope.ts';\n\n/** @public */\nexport function getSimplePaths<TLogic extends AnyActorLogic>(\n logic: TLogic,\n ...[options]: EventCaseOptionsArgs<NoInfer<TLogic>>\n): Array<StatePath<SnapshotFrom<TLogic>, EventFromLogic<TLogic>>>;\nexport function getSimplePaths<\n TLogic extends AnyActorLogic,\n const TEvents extends readonly TraversalEvent<\n SnapshotFrom<NoInfer<TLogic>>,\n EventFromLogic<NoInfer<TLogic>>\n >[]\n>(\n logic: TLogic,\n options: EventListOptions<NoInfer<TLogic>, TEvents>\n): Array<StatePath<SnapshotFrom<TLogic>, EventFromLogic<TLogic>>>;\nexport function getSimplePaths<TLogic extends AnyActorLogic>(\n logic: TLogic,\n options?: TraversalOptions<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>,\n InputFrom<TLogic>\n >\n): Array<StatePath<SnapshotFrom<TLogic>, EventFromLogic<TLogic>>> {\n type TState = SnapshotFrom<TLogic>;\n type TEvent = EventFromLogic<TLogic>;\n\n const resolvedOptions = resolveTraversalOptions(logic, options);\n const actorScope = createMockActorScope();\n const fromState =\n resolvedOptions.fromState ??\n logic.getInitialSnapshot(actorScope, options?.input);\n const serializeState = resolvedOptions.serializeState as (\n ...args: Parameters<typeof resolvedOptions.serializeState>\n ) => SerializedSnapshot;\n const adjacency = getAdjacencyMap(logic, { ...resolvedOptions, fromState });\n const stateMap = new Map<SerializedSnapshot, TState>();\n const visitCtx: VisitedContext<TState, TEvent> = {\n vertices: new Set(),\n edges: new Set()\n };\n const steps: Steps<TState, TEvent> = [];\n const pathMap: Record<\n SerializedSnapshot,\n { state: TState; paths: Array<StatePath<TState, TEvent>> }\n > = Object.create(null);\n\n function util(\n fromStateSerial: SerializedSnapshot,\n toStateSerial: SerializedSnapshot\n ) {\n const fromState = stateMap.get(fromStateSerial)!;\n visitCtx.vertices.add(fromStateSerial);\n\n if (fromStateSerial === toStateSerial) {\n if (!pathMap[toStateSerial]) {\n pathMap[toStateSerial] = {\n state: stateMap.get(toStateSerial)!,\n paths: []\n };\n }\n\n const toStatePlan = pathMap[toStateSerial];\n\n const path2: StatePath<TState, TEvent> = {\n state: fromState,\n weight: steps.length,\n steps: [...steps]\n };\n\n toStatePlan.paths.push(path2);\n } else {\n if (!adjacency[fromStateSerial]) {\n return;\n }\n for (const serializedEvent of Object.keys(\n adjacency[fromStateSerial].transitions\n ) as SerializedEvent[]) {\n const { state: nextState, event: subEvent } =\n adjacency[fromStateSerial].transitions[serializedEvent];\n\n if (!(serializedEvent in adjacency[fromStateSerial].transitions)) {\n continue;\n }\n const prevState = stateMap.get(fromStateSerial);\n\n const nextStateSerial = serializeState(nextState, subEvent, prevState);\n stateMap.set(nextStateSerial, nextState);\n\n if (!visitCtx.vertices.has(nextStateSerial)) {\n visitCtx.edges.add(serializedEvent);\n steps.push({\n state: stateMap.get(fromStateSerial)!,\n event: subEvent\n });\n util(nextStateSerial, toStateSerial);\n }\n }\n }\n\n steps.pop();\n visitCtx.vertices.delete(fromStateSerial);\n }\n\n const fromStateSerial = serializeState(fromState, undefined);\n stateMap.set(fromStateSerial, fromState);\n\n for (const nextStateSerial of Object.keys(\n adjacency\n ) as SerializedSnapshot[]) {\n util(fromStateSerial, nextStateSerial);\n }\n\n const simplePaths = Object.values(pathMap).flatMap((p) => p.paths);\n\n if (resolvedOptions.toState) {\n return simplePaths\n .filter((path) => resolvedOptions.toState!(path.state))\n .map(alterPath);\n }\n\n return simplePaths.map(alterPath);\n}\n"],"names":["xstateError","code","values","length","map","value","JSON","stringify","String","join","ACTOR_OPTIONS","Set","XSTATE_INIT","XSTATE_STOP","XSTATE_TERMINATE","XSTATE_TIMER","XSTATE_LOGIC_EFFECT_RESOLVE","XSTATE_LOGIC_EFFECT_REJECT","XSTATE_LOGIC_EFFECT_START","isSerializedActorRef","target","Array","isArray","$actor","key","incarnation","undefined","getAddressId","address","segment","slice","lastIndexOf","includes","replaceAll","createMissingAddressError","Error","resolveSerializedActorRef","system","live","_getByAddress","sessionId","publishEmittedEvent","source","event","runtime","_notifyEmitted","emitEvent","Object","freeze","status","output","error","pendingSteps","WeakMap","async","runStep","actor","exec","sendSelf","sendEvent","effect","effects","getSnapshot","prototype","hasOwnProperty","call","getStepEffect","running","get","resolve","reject","promise","Promise","resolvePromise","rejectPromise","subscription","steps","Map","set","cleanup","unsubscribe","delete","size","then","subscribe","complete","type","catch","rejectUndeliverableEvent","runtimeTarget","logic","isInternalEventType","id","getEventBoundaryError","deadLetter","Mailbox","constructor","_process","this","_active","_current","_last","start","flush","clear","next","enqueue","enqueued","consumed","createInitEvent","input","reportUnhandledError","err","setTimeout","symbolObservable","Symbol","observable","selectionFrames","transitionEffectSignal","getBuiltInTimerIdentity","stateId","delay","actorId","getTimerKey","timer","seq","getScheduledTimerKey","serializeTimerKey","execEmitEffect","execDeadLetterEffect","reason","detail","createDeadLetterEffect","actorScope","kind","self","params","args","createCustomEffect","action","execTerminateEffect","termination","terminateActor","execSendToEffect","assertSendToEvent","scheduleTimer","createSendToEffect","createTerminationEffect","snapshot","finalizeTransitionResult","previousSnapshot","nextSnapshot","becameTerminal","wasTerminal","hasTerminationEffect","some","snapshotActorRefs","lazySnapshotActorRefs","emptyKeyedActors","markSystemSnapshotDirty","_snapshotVersion","getSystemSnapshotVersion","getSnapshotActorRef","existing","create","created","setSnapshotActorRef","baseSystem","sourceVersion","previousRef","reusableRef","systemState","sourceSystem","capturedActors","root","_getRootActor","peekedChildren","_peekChildren","children","captureRegisteredActors","baseKeyedActors","peek","_peekKeyedActors","keyedActors","getKeyedActors","child","getSnapshotChildren","registryKey","_snapshot","isMachineSnapshot","toObserver","nextHandler","errorHandler","completionHandler","isObserver","bind","passive","getAllOwnEvents","events","nodes","flatMap","stateNode","transitions","transition","eventType","matches","filter","index","findIndex","candidate","keys","every","is","matchesEvent","pattern","entries","matchesEventDescriptor","descriptor","endsWith","partialEventTokens","split","eventTokens","tokenIndex","partialEventToken","eventToken","executionIdPrefix","nextExecutionId","createExecutionId","crypto","globalThis","getRandomValues","Uint32Array","from","toString","padStart","randomUUID","Date","now","Math","random","createExecutionIdPrefix","encodeAddressSegment","getActorIdCounterKey","parent","prefix","bumpActorIdCounter","counterKey","counters","_nextActorIds","resolveActorId","requestedId","options","generated","separator","Number","isSafeInteger","parseGeneratedActorId","src","logicId","getActorIdPrefix","counter","emptyScheduledTimers","createScheduledTimerId","findLogicalTimer","timers","find","field","matchesTimerKey","RuntimeSystem","_children","_rootActor","_isRunning","_keyedActors","actors","reverseKeyedActors","_reverseKeyedActors","_identity","executionId","nextSessionId","scheduler","_clock","_logger","createActorRef","clock","logger","ambientInspector","getAmbientInspector","_scheduledTimers","_recordSent","_inspectionObservers","inspectionSource","_collectedSent","push","targetRef","targetId","schedule","scheduledTimerId","_timerMap","cancel","scheduledAt","scheduledTimer","dueAt","timeout","_deliver","clearTimeout","cancelAll","serialized","_send","deliverEvent","_register","_unregister","changed","getAll","fromEntries","_set","inspect","observerOrFn","observer","add","onRejectedEvent","listener","entry","rejection","_rejectionListeners","onEmitted","emission","_emissionListeners","actorRef","listeners","_hasInspectionObservers","_sendInspectionEvent","resolvedInspectionEvent","rootId","forEach","spawnActor","startActor","override","stopActor","_stop","stopActorLocally","_terminate","terminateActorLocally","_emit","sourceRef","eventOrigin","issues","runLogic","cancelTimer","cancelAllTimers","_relay","matched","abort","frame","requiresReevaluation","mode","protectSelectionRelay","scheduledTimers","resetScheduledTimers","scheduledId","max","executingCustomAction","emptyInspectionRecords","reservedMachineEventTypes","ProcessingStatus","defaultOptions","fn","ms","console","log","safeCall","arg","executeExecutableEffects","actionExecutor","Actor","_address","_parent","trigger","_trigger","Proxy","_","payload","send","_boundSend","_sendPublic","_boundProcess","mailbox","_mailboxStarted","observers","_errorObserved","eventListeners","_processingStatus","NotStarted","_forceDeferredActions","_syncSnapshot","ref","_actorScope","_lastSourceRef","_collectedMicrosteps","_collectedActions","_initialEffects","_deferred","_restored","_warnedUnhandledTypes","resolvedOptions","syncSnapshot","_systemRef","current","rootActor","createRuntimeSystem","initialize","_sessionId","restore","_restore","_setSnapshot","_inert","initialTransition","parentRef","_getLogger","defer","_defer","defineProperty","stopChild","_stopChild","emit","_executeAction","Running","saveExecutingCustomAction","result","Stopped","_recoverOrError","_setErrorSnapshot","_tryHandleExecutionError","_error","errorEvent","getExecutionErrorEvent","update","_next","deferred","i","deferredFn","_inspectTransition","microsteps","actions","sent","_flushInitialEffects","nextListenerOrObserver","errorListener","completeListener","on","handler","select","selector","equalityFn","selected","_stopProcedure","_complete","restored","refreshSnapshotActorRefRoot","wallClock","min","nextState","caughtError","hasOwn","_reportUnhandledEvent","onUnhandledEvent","invokeId","stop","_reportUnlessObserved","snapshotChildren","reportError","handled","toJSON","getPersistedSnapshot","createActor","has","diagnoseActorOptions","assertValid","validator","request","check","effectStates","executeLogicEffect","state","getEffectState","createStepLogic","config","calculateTransition","failure","cleanupLogicEffects","trackedEffects","enq","emitted","createEmitEffect","sendBack","sentEvent","raise","raisedEvent","keyOrExec","maybeExec","enqueueEffect","recorded","patch","run","context","assign","resolveContext","getInitialSnapshot","restoreSnapshot","emptyLogic","createMockActorScope","emptyActor","serializeSnapshot","machineSnapshot","inputs","getInputs","history","historyValue","stateInputs","node","serializeEvent","isMachineLogic","machine","states","getStateNodeById","resolveState","getTransitionData","resolveTraversalOptions","traversalOptions","resolvedDefaultOptions","serializeState","fromState","eventSource","filterEvents","limit","Infinity","toState","stopWhen","cases","defaults","sources","applicable","samples","resolveEventCases","createTraversalError","cause","resolveTransitionSnapshot","getAdjacencyMap","getEvents","customFromState","adj","iterations","queue","prevState","head","splice","serializedState","nextEvent","serializedEvent","alterPath","path","step","adjMap","adjList","adjValue","getDescendantStateNodes","reduce","accNodes","stateKey","childStateNode","childStateNodes","stateSerial","eventSerial","candidates","weight","adjacency","weightMap","stateMap","serializedFromState","unvisited","visited","eventObject","nextSerializedState","nextWeight","statePlanMap","paths","fromEvent","concat","visitCtx","vertices","edges","pathMap","util","fromStateSerial","toStateSerial","toStatePlan","path2","subEvent","nextStateSerial","pop","simplePaths","p","headPath","tailPath","toDirectedGraph","stateMachine","diagnostics","flat","always","t","transitionIndex","to","transitionId","message","targetIndex","edge","label","text","getChildren","analysis","graph","transitionTargetsComplete","graphEdges"],"mappings":"kPAOO,SAASA,EAAYC,KAAiBC,GAC3C,MAAO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ts","../src/devDiagnostics.ts","../src/constants.ts","../src/remoteActorRef.ts","../src/runtimeHelpers.ts","../src/Mailbox.ts","../src/eventUtils.ts","../src/reportUnhandledError.ts","../src/symbolObservable.ts","../src/transitionSelection.ts","../src/timerKey.ts","../src/transitionActions.ts","../src/actions.ts","../src/snapshotActorRef.ts","../src/State.ts","../src/utils.ts","../src/system.ts","../src/createActor.ts","../src/validation.ts","../src/actors/logic.ts","../src/actors/index.ts","../src/graph/actorScope.ts","../src/graph/graph.ts","../src/graph/traversalError.ts","../src/graph/adjacency.ts","../src/graph/alterPath.ts","../src/graph/pathFromEvents.ts","../src/graph/shortestPaths.ts","../src/graph/simplePaths.ts"],"sourcesContent":["/**\n * Builds the production message for an XState error: the stable code, the\n * dynamic values, and a link to its entry in docs/errors.md. Development\n * builds use the full message instead, so call sites read `isDevelopment ?\n * fullMessage : xstateError(code, ...values)` and the full text tree-shakes\n * out of production bundles.\n */\nexport function xstateError(code: number, ...values: unknown[]): string {\n return `XState error E${code}${\n values.length\n ? ` (${values\n .map((value) =>\n typeof value === 'string' ? JSON.stringify(value) : String(value)\n )\n .join(', ')})`\n : ''\n }. See https://github.com/statelyai/xstate/blob/next/docs/errors.md#e${code}`;\n}\n","import isDevelopment from '#is-development';\nimport { xstateError } from './xstateError.ts';\n\n/**\n * Checks for leftover v5 configuration on hand-written machine configs, setup\n * configs and actor options. Keys that v6 would silently ignore throw in every\n * build; harmless leftovers only warn in development. Production builds throw\n * coded messages (see docs/errors.md), so the message tables below are\n * referenced from development branches only.\n */\n\nconst INLINE_TRANSITION =\n 'Use an inline transition function instead: return { target } when the condition passes, or undefined to reject the event (before any enq call, which would select the transition). Named guards are available as `guards.name(...)` in its arguments.';\n\nconst INLINE_ACTION =\n 'Use a single inline function `(args, enq) => { ... }`; call named actions with `enq(actions.name, params)`.';\n\n// Keys that v6 would ignore or misread; each throws E1 in production.\nconst REMOVED_ROOT_KEY_NAMES = [\n 'types',\n 'tsTypes',\n 'schema',\n 'internalEvents',\n 'services',\n 'devTools'\n];\n\nconst REMOVED_ROOT_KEYS: Record<string, string> = {\n types:\n '\"types\" was replaced by \"schemas\". Declare contracts under `schemas` (or `setup({ schemas })`), or use `types<T>()` inside `schemas` for type-only contracts.',\n tsTypes:\n '\"tsTypes\" (typegen) was removed. Declare contracts under `schemas` (or `setup({ schemas })`).',\n schema:\n '\"schema\" was replaced by \"schemas\". Declare contracts under `schemas` (or `setup({ schemas })`).',\n internalEvents:\n 'The top-level \"internalEvents\" list was removed. Declare private events under `schemas.internalEvents` instead, e.g. `schemas: { internalEvents: { tick: types<{}>() } }`.',\n services:\n '\"services\" was renamed. Provide actor logic under \"actors\" (or `setup({ actors })`).',\n devTools:\n '\"devTools\" was removed. Pass the \"inspect\" option to `createActor(...)` instead.'\n};\n\nconst SETUP_INTERNAL_EVENTS =\n 'setup() has no \"internalEvents\" option. Declare private events under `schemas.internalEvents` instead, e.g. `setup({ schemas: { internalEvents: { tick: types<{}>() } } })`.';\n\nconst ACTIVITIES =\n 'uses \"activities\", which was removed. Invoke an actor with \"invoke\" instead.';\n\n// Leftovers that change nothing in v6; reported in development only.\nconst HARMLESS_ROOT_KEYS: Record<string, string> = {\n predictableActionArguments:\n 'was removed with no replacement; v6 always runs effects in order.',\n preserveActionOrder:\n 'was removed with no replacement; v6 always runs effects in order.',\n strict: 'was removed with no replacement.'\n};\n\nconst TRANSITION_KEYS = ['onDone', 'onError', 'onTimeout', 'always'] as const;\nconst INVOKE_TRANSITION_KEYS = [\n 'onDone',\n 'onError',\n 'onSnapshot',\n 'onTimeout'\n] as const;\n\nconst SUFFIXED_LIFECYCLE =\n /^xstate\\.(done\\.actor|error\\.actor|snapshot|done\\.state|after)\\.(.+)$/;\n\nfunction checkLifecycleEventKey(eventType: string, stateId: string): void {\n const match = SUFFIXED_LIFECYCLE.exec(eventType);\n // `xstate.done.actor.*` is a wildcard over the category type and still matches.\n // `xstate.snapshot.actor` is the v6 category type itself, and\n // `xstate.snapshot.actor.*` is a wildcard over it.\n if (\n !match ||\n match[2] === '*' ||\n (match[1] === 'snapshot' &&\n (match[2] === 'actor' || match[2] === 'actor.*'))\n )\n return;\n if (!isDevelopment) {\n throw new Error(xstateError(3, eventType, stateId));\n }\n const [, category, suffix] = match;\n const where = `Transition \"${eventType}\" in ${describeState(stateId)}`;\n const replacement =\n category === 'after'\n ? `Use \\`after: { <delay>: ... }\\` on the state, or key on 'xstate.after' and select \\`matches: { stateId, delay }\\``\n : category === 'done.state'\n ? `Use \"onDone\" on the state, or key on 'xstate.done.state' with \\`matches: { stateId: '${suffix}' }\\``\n : `Key on '${category === 'snapshot' ? 'xstate.snapshot.actor' : `xstate.${category}`}' with \\`matches: { actorId: '${suffix}' }\\`, or use the invoke's ${category === 'done.actor' ? '\"onDone\"' : category === 'error.actor' ? '\"onError\"' : '\"onSnapshot\"'}`;\n throw new Error(\n `${where} never fires: v6 lifecycle event types carry the id in a payload field instead of the type. ${replacement}.`\n );\n}\n\nfunction checkTransitions(\n transitions: unknown,\n name: string,\n stateId: string\n): void {\n if (!transitions) return;\n for (const t of Array.isArray(transitions) ? transitions : [transitions]) {\n if (!t || typeof t !== 'object') continue;\n if ((t as any).cond !== undefined) {\n throw new Error(\n isDevelopment\n ? `Transition \"${name}\" in ${describeState(stateId)} uses \"cond\", which was removed. ${INLINE_TRANSITION}`\n : xstateError(4, name, stateId, 'cond')\n );\n }\n if ((t as any).guard !== undefined) {\n throw new Error(\n isDevelopment\n ? `Transition \"${name}\" in ${describeState(stateId)} uses an object-form \"guard\", which was removed. ${INLINE_TRANSITION}`\n : xstateError(4, name, stateId, 'guard')\n );\n }\n if ((t as any).actions !== undefined) {\n throw new Error(\n isDevelopment\n ? `Transition \"${name}\" in ${describeState(stateId)} uses \"actions\", which was removed. Use an inline transition function \\`(args, enq) => { ... }\\` and queue effects on \"enq\"; call named actions with \\`enq(actions.name, params)\\`.`\n : xstateError(4, name, stateId, 'actions')\n );\n }\n }\n}\n\n// The root of a machine without an id has the empty id.\nfunction describeState(stateId: string): string {\n return stateId ? `state \"${stateId}\"` : 'the root state';\n}\n\nfunction describeShape(value: unknown): string {\n return Array.isArray(value)\n ? 'an array'\n : typeof value === 'string'\n ? `a string (\"${value}\")`\n : `a ${typeof value}`;\n}\n\nfunction capitalize(text: string): string {\n return text.charAt(0).toUpperCase() + text.slice(1);\n}\n\nconst UNGUARDED_INITIAL =\n 'Initial transitions cannot be guarded; use an \"always\" transition on the target state to redirect conditionally.';\n\nfunction checkInitialTransition(initial: any, stateId: string): void {\n if (!initial || typeof initial !== 'object') return;\n if (initial.cond !== undefined) {\n throw new Error(\n isDevelopment\n ? `Initial transition of ${describeState(stateId)} uses \"cond\", which was removed. ${UNGUARDED_INITIAL}`\n : xstateError(5, stateId, 'cond')\n );\n }\n if (initial.guard !== undefined) {\n throw new Error(\n isDevelopment\n ? `Initial transition of ${describeState(stateId)} uses an object-form \"guard\", which was removed. ${UNGUARDED_INITIAL}`\n : xstateError(5, stateId, 'guard')\n );\n }\n if (initial.actions !== undefined) {\n throw new Error(\n isDevelopment\n ? `Initial transition of ${describeState(stateId)} uses \"actions\", which was removed. Use a \\`to: (args, enq) => { ... }\\` function on the initial transition and queue effects on \"enq\", or an \"entry\" function on the target state.`\n : xstateError(5, stateId, 'actions')\n );\n }\n}\n\nfunction checkStateNode(node: any, stateId: string): void {\n checkInitialTransition(node.initial, stateId);\n if (node.activities !== undefined) {\n throw new Error(\n isDevelopment\n ? `${capitalize(describeState(stateId))} ${ACTIVITIES}`\n : xstateError(6, stateId)\n );\n }\n for (const key of ['entry', 'exit'] as const) {\n const action = node[key];\n if (action !== undefined && typeof action !== 'function') {\n throw new Error(\n isDevelopment\n ? `${capitalize(describeState(stateId))} has ${describeShape(action)} as \"${key}\", which is not supported. ${INLINE_ACTION}`\n : xstateError(7, stateId, key)\n );\n }\n }\n if (node.on) {\n for (const eventType of Object.keys(node.on)) {\n checkLifecycleEventKey(eventType, stateId);\n checkTransitions(node.on[eventType], eventType, stateId);\n }\n }\n if (node.after) {\n for (const delay of Object.keys(node.after)) {\n checkTransitions(node.after[delay], `after.${delay}`, stateId);\n }\n }\n for (const key of TRANSITION_KEYS) {\n checkTransitions(node[key], key, stateId);\n }\n if (node.invoke) {\n for (const invoke of Array.isArray(node.invoke)\n ? node.invoke\n : [node.invoke]) {\n if (!invoke || typeof invoke !== 'object') continue;\n for (const key of INVOKE_TRANSITION_KEYS) {\n checkTransitions(invoke[key], `invoke.${key}`, stateId);\n }\n }\n }\n if (node.states) {\n for (const key of Object.keys(node.states)) {\n const child = node.states[key];\n if (child && typeof child === 'object') {\n checkStateNode(\n child,\n child.id ?? (stateId ? `${stateId}.${key}` : key)\n );\n }\n }\n }\n}\n\n/**\n * Throws (or warns, for harmless leftovers) when a hand-written machine config\n * contains v5 keys that v6 would otherwise ignore or misread.\n */\nexport function diagnoseAuthorConfig(config: any): void {\n if (!config || typeof config !== 'object') return;\n for (const key of REMOVED_ROOT_KEY_NAMES) {\n if (config[key] !== undefined) {\n throw new Error(\n isDevelopment ? REMOVED_ROOT_KEYS[key] : xstateError(1, key)\n );\n }\n }\n if (isDevelopment) {\n for (const key of Object.keys(HARMLESS_ROOT_KEYS)) {\n if (config[key] !== undefined) {\n console.warn(`Machine config \"${key}\" ${HARMLESS_ROOT_KEYS[key]}`);\n }\n }\n }\n checkStateNode(config, config.id ?? '');\n}\n\n/**\n * Throws when a `setup(...)` config contains a key that belongs elsewhere and\n * would otherwise be ignored.\n */\nexport function diagnoseSetupConfig(config: any): void {\n if (!config || typeof config !== 'object') return;\n if (config.internalEvents !== undefined) {\n throw new Error(isDevelopment ? SETUP_INTERNAL_EVENTS : xstateError(2));\n }\n}\n\nconst REMOVED_ACTOR_OPTIONS: Record<string, string> = {\n parent:\n 'The \"parent\" actor option was removed. Create child actors through invoke, spawn, or enq.spawn instead.',\n systemId:\n 'The \"systemId\" actor option was renamed. Use \"registryKey\": createActor(logic, { registryKey }), and look the actor up with system.get(registryKey).',\n state:\n 'The \"state\" actor option was removed. Restore persisted snapshots with restoreActor(logic, snapshot) from \"xstate/persist\".',\n snapshot:\n 'The \"snapshot\" actor option was removed. Restore persisted snapshots with restoreActor(logic, snapshot) from \"xstate/persist\".',\n devTools:\n 'The \"devTools\" actor option was removed. Pass the \"inspect\" option instead: createActor(logic, { inspect }).',\n deferEvents:\n 'The \"deferEvents\" actor option was removed. Events sent before start() are always queued until the actor starts.',\n execute:\n 'The \"execute\" actor option was removed. Effects always run when the actor processes an event; use transition() for pure, effect-free steps.'\n};\n\nconst ACTOR_OPTIONS = new Set([\n 'clock',\n 'logger',\n 'syncSnapshot',\n 'id',\n 'registryKey',\n 'input',\n 'src',\n 'inspect',\n 'onRejectedEvent',\n 'onUnhandledEvent',\n '_systemRef',\n '_sessionId',\n '_inert',\n '_restore'\n]);\n\n/**\n * Throws when `createActor(...)` options contain a key that v6 does not read,\n * so a misspelled or v5-era option fails instead of being ignored.\n */\nexport function diagnoseActorOptions(options: any): void {\n if (!options || typeof options !== 'object') return;\n for (const key of Object.keys(options)) {\n if (ACTOR_OPTIONS.has(key)) continue;\n throw new Error(\n isDevelopment\n ? (REMOVED_ACTOR_OPTIONS[key] ??\n `Unknown actor option \"${key}\". Supported options: ${[\n ...ACTOR_OPTIONS\n ]\n .filter((name) => !name.startsWith('_'))\n .join(', ')}.`)\n : xstateError(8, key)\n );\n }\n}\n","export const STATE_DELIMITER = '.';\nexport const TARGETLESS_KEY = '';\nexport const NULL_EVENT = '';\nexport const STATE_IDENTIFIER = '#';\nexport const WILDCARD = '*';\nexport const XSTATE_INIT = 'xstate.init';\nexport const XSTATE_START = '@xstate.start';\nexport const XSTATE_SPAWN = '@xstate.spawn';\n/** The event an actor receives when it is stopped. */\nexport const XSTATE_STOP = 'xstate.stop';\n/** The effect that stops a child actor. */\nexport const XSTATE_STOP_EFFECT = '@xstate.stop';\nexport const XSTATE_TERMINATE = '@xstate.terminate';\nexport const XSTATE_TIMER = 'xstate.timer';\n\nexport const XSTATE_LOGIC_EFFECT_RESOLVE = 'xstate.logic.effect.resolve';\nexport const XSTATE_LOGIC_EFFECT_REJECT = 'xstate.logic.effect.reject';\nexport const XSTATE_LOGIC_EFFECT_START = 'xstate.logic.effect.start';\n","import isDevelopment from '#is-development';\nimport { xstateError } from './xstateError.ts';\nimport type { AnyActorSystem } from './system.ts';\nimport type {\n AnyActor,\n AnyEventObject,\n SerializedActorRef,\n Snapshot,\n Subscription\n} from './types.ts';\n\nconst emptySubscription: Subscription = { unsubscribe() {} };\n\nconst restoreHint =\n 'or restore this snapshot with embedded children on the runtime that owns them.';\n\n/** @internal */\nexport function isRemoteActorRef(actorRef: AnyActor): boolean {\n return (actorRef as { _remote?: boolean })._remote === true;\n}\n\n/**\n * @internal Whether a send target is an actor reference that went through\n * JSON (`actor.toJSON()`): plain data carrying an address, not an actor.\n */\nexport function isSerializedActorRef(\n target: unknown\n): target is SerializedActorRef {\n if (\n typeof target !== 'object' ||\n target === null ||\n Array.isArray(target) ||\n typeof (target as SerializedActorRef)['@actor'] !== 'string'\n ) {\n return false;\n }\n for (const key in target) {\n if (key !== '@actor' && key !== 'incarnation') {\n return false;\n }\n }\n const incarnation = (target as SerializedActorRef).incarnation;\n return incarnation === undefined || typeof incarnation === 'string';\n}\n\n/** @internal The actor id that the last segment of an address encodes. */\nexport function getAddressId(address: string): string {\n const segment = address.slice(address.lastIndexOf('/') + 1);\n return segment.includes('%')\n ? segment.replaceAll('%2F', '/').replaceAll('%25', '%')\n : segment;\n}\n\n/** @internal The error reported when no live actor has a serialized address. */\nexport function createMissingAddressError(target: SerializedActorRef): Error {\n return new Error(\n !isDevelopment\n ? xstateError(\n 50,\n ...(target.incarnation === undefined\n ? [target['@actor']]\n : [target['@actor'], target.incarnation])\n )\n : target.incarnation === undefined\n ? `Unable to send event to actor '${target['@actor']}': no live actor has that address`\n : `Unable to send event to actor '${target['@actor']}' (incarnation '${target.incarnation}'): no live actor has that address and incarnation`\n );\n}\n\n/**\n * @internal The live actor a serialized ref names: the actor at its address,\n * and, when the ref carries an `incarnation`, only that incarnation. A ref\n * without one follows whichever actor is live at the address.\n */\nexport function resolveSerializedActorRef(\n system: { _getByAddress?: (address: string) => AnyActor | undefined },\n target: SerializedActorRef\n): AnyActor | undefined {\n const live = system._getByAddress?.(target['@actor']);\n return live &&\n (target.incarnation === undefined || live.sessionId === target.incarnation)\n ? live\n : undefined;\n}\n\n/**\n * The lifecycle-only snapshot a remote handle exposes. `active` is accurate\n * by construction: a completion removes the child from its parent's\n * `children`, so a handle only exists while the child is presumed active,\n * and the terminal result arrives as a completion event instead of a\n * snapshot. Full snapshots are a co-location capability.\n */\nconst remoteSnapshot: Snapshot<undefined> = Object.freeze({\n status: 'active' as const,\n output: undefined,\n error: undefined\n});\n\n/**\n * Creates the inert ref `enq.spawn(...)` returns while a transition is only\n * evaluated (for example by `snapshot.can(...)`, or to resolve conflicting\n * transitions) and no actor is created. It carries the identity the spawn\n * would get, accepts and drops events, exposes the same lifecycle-only\n * snapshot as a remote handle, and serializes like any actor ref. Its address\n * is unknown when the evaluating scope is detached from the parent actor.\n *\n * @internal\n */\nexport function createInertActorRef(options: {\n id: string;\n address: string | undefined;\n src: string | undefined;\n}): AnyActor {\n const { id, address } = options;\n const handle = {\n ref: undefined as unknown as AnyActor,\n id,\n address,\n src: options.src,\n sessionId: undefined,\n send() {},\n getSnapshot(): Snapshot<undefined> {\n return remoteSnapshot;\n },\n subscribe(): Subscription {\n return emptySubscription;\n },\n on(): Subscription {\n return emptySubscription;\n },\n toJSON(): SerializedActorRef {\n if (address === undefined) {\n throw new Error(\n isDevelopment\n ? `Cannot serialize actor ref '${id}': it was returned by a spawn during speculative transition evaluation, which creates no actor and has no parent address.`\n : xstateError(51, id)\n );\n }\n return { '@actor': address };\n }\n };\n const ref = handle as unknown as AnyActor;\n handle.ref = ref;\n return ref;\n}\n\n/**\n * Creates a location-transparent handle to an actor whose state lives with\n * another runtime. The handle is constructed from identity alone — no lookup\n * — and every send routes through the system's runtime; its state is not\n * synchronously readable.\n *\n * The surface is deliberately minimal: it covers every member the runtime\n * reaches for a restored child (send/_send, lifecycle via start/_stop and\n * system.stopActor, persistence, subscribe/on as inert subscriptions).\n * Members that only make sense for a co-located actor (public stop(),\n * select(), trigger) throw a descriptive error rather than being absent, so\n * calling one reports what went wrong instead of a bare TypeError. Observable\n * interop and _processingStatus are omitted entirely.\n *\n * @internal\n */\nexport function createRemoteActorRef(\n system: AnyActorSystem,\n options: {\n id: string;\n address: string;\n src: string;\n parent: AnyActor | undefined;\n registryKey?: string;\n syncSnapshot?: boolean;\n incarnation?: string;\n }\n): AnyActor {\n const handle = {\n _remote: true as const,\n // Self-reference so context persistence recognizes the handle as an\n // actor reference instead of recursing into it.\n ref: undefined as unknown as AnyActor,\n id: options.id,\n address: options.address,\n src: options.src,\n registryKey: options.registryKey,\n // The host-supplied incarnation token, when present: the owner's\n // sessionId for this child, letting this side drop stale completions and\n // journaled sends name the intended incarnation. Without one the handle\n // does not know the child's incarnation and the owning runtime is the\n // authority on staleness.\n sessionId: options.incarnation as string,\n system,\n _parent: options.parent,\n // Round-trips through persistence verbatim (undefined stays undefined,\n // so re-persisting is byte-stable); a remote handle cannot act on it\n // locally.\n _syncSnapshot: options.syncSnapshot,\n send(event: AnyEventObject) {\n void system.sendEvent(undefined, ref, event);\n },\n _send(event: AnyEventObject) {\n throw new Error(\n isDevelopment\n ? `Remote actor '${options.address}' has no local mailbox to receive \"${event.type}\". Its state lives with another runtime; install a runtime that can reach it (via \\`createDurable\\`'s adapter runtime operations, or \\`system.runtime\\`) before sending, ${restoreHint}`\n : xstateError(52, options.address, event.type)\n );\n },\n getSnapshot(): Snapshot<undefined> {\n return remoteSnapshot;\n },\n getPersistedSnapshot(): never {\n throw new Error(\n isDevelopment\n ? `Cannot persist remote actor '${options.address}' from here: its state lives with the runtime that owns it. Persist it there, ${restoreHint}`\n : xstateError(53, options.address)\n );\n },\n start() {},\n _stop() {},\n stop() {\n throw new Error(\n isDevelopment\n ? `Cannot stop remote actor '${options.address}' directly: stopping is a co-located operation. Stop it through the system runtime that owns it (\\`system.stopActor(ref)\\`), ${restoreHint}`\n : xstateError(54, options.address)\n );\n },\n select() {\n throw new Error(\n isDevelopment\n ? `Cannot select from remote actor '${options.address}': its snapshot is not synchronously readable because its state lives with another runtime. Read it on the runtime that owns it, ${restoreHint}`\n : xstateError(55, options.address)\n );\n },\n get trigger(): never {\n throw new Error(\n isDevelopment\n ? `Remote actor '${options.address}' has no \\`trigger\\` shorthand: it requires a co-located actor. Use \\`send(...)\\`, which routes through the system runtime.`\n : xstateError(56, options.address)\n );\n },\n // Observation is a co-location capability: a remote handle never emits,\n // so subscriptions are inert rather than errors — generic observers may\n // attach to any ref.\n subscribe(): Subscription {\n return emptySubscription;\n },\n on(): Subscription {\n return emptySubscription;\n },\n _isRunning() {\n return false;\n },\n // The same shape Actor.toJSON produces, so serialized snapshots carry\n // one actor-reference shape whether a child is co-located or remote.\n toJSON(): SerializedActorRef {\n return { '@actor': options.address };\n }\n };\n const ref = handle as unknown as AnyActor;\n handle.ref = ref;\n return ref;\n}\n","import isDevelopment from '#is-development';\nimport { xstateError } from './xstateError.ts';\nimport {\n XSTATE_LOGIC_EFFECT_REJECT,\n XSTATE_LOGIC_EFFECT_RESOLVE,\n XSTATE_LOGIC_EFFECT_START\n} from './constants.ts';\nimport {\n createMissingAddressError,\n getAddressId,\n isSerializedActorRef,\n resolveSerializedActorRef\n} from './remoteActorRef.ts';\nimport type { ActorSystemRuntime } from './system.ts';\nimport type {\n EventObject,\n ActorTermination,\n AnyActor,\n AnyEventObject,\n Subscription\n} from './types.ts';\n\n/** @internal */\nexport function publishEmittedEvent(\n source: AnyActor,\n event: EventObject,\n runtime: Partial<ActorSystemRuntime>\n): void | PromiseLike<void> {\n source.system._notifyEmitted(source, event);\n return runtime.emitEvent!(source, event);\n}\n\ntype StepEffects = Record<\n string,\n | { status: 'active' }\n | { status: 'done'; output: unknown }\n | { status: 'error'; error: unknown }\n>;\n\nfunction getStepEffect(actor: AnyActor, key: string) {\n const effects = (actor.getSnapshot() as { effects?: StepEffects }).effects;\n return effects && Object.prototype.hasOwnProperty.call(effects, key)\n ? effects[key]\n : undefined;\n}\n\n// Live promises belong to an actor incarnation, unlike its persisted journal.\n// A restored active record has no promise here and must be retried locally.\nconst pendingSteps = new WeakMap<AnyActor, Map<string, Promise<unknown>>>();\n\n/**\n * Runs one keyed step of an async actor with the built-in journal: the\n * result is memoized in the actor's own snapshot (`effects[key]`), so a\n * restored actor skips completed steps when its logic function re-runs.\n * Custom runtimes that implement `runStep` use this for the default local\n * behavior, the same way `deliverEvent` exposes local delivery.\n *\n * @experimental\n */\nexport async function runStep<TStepOutput>(\n actor: AnyActor,\n key: string,\n exec: () => TStepOutput | PromiseLike<TStepOutput>,\n sendSelf: (event: AnyEventObject) => void = (event) =>\n void actor.system.sendEvent(actor, actor, event)\n): Promise<TStepOutput> {\n const effect = getStepEffect(actor, key);\n if (effect?.status === 'done') {\n return effect.output as TStepOutput;\n }\n if (effect?.status === 'error') {\n throw effect.error;\n }\n const running = pendingSteps.get(actor)?.get(key);\n if (running) {\n return running as Promise<TStepOutput>;\n }\n if (actor.getSnapshot().status !== 'active') {\n throw new Error(\n isDevelopment\n ? `Actor terminated before step \"${key}\" completed`\n : xstateError(72, key)\n );\n }\n\n let resolve!: (value: TStepOutput | PromiseLike<TStepOutput>) => void;\n let reject!: (reason: unknown) => void;\n const promise = new Promise<TStepOutput>((resolvePromise, rejectPromise) => {\n resolve = resolvePromise;\n reject = rejectPromise;\n });\n let steps = pendingSteps.get(actor);\n if (!steps) {\n steps = new Map();\n pendingSteps.set(actor, steps);\n }\n steps.set(key, promise);\n // oxlint-disable-next-line prefer-const\n let subscription: Subscription | undefined;\n const cleanup = () => {\n subscription?.unsubscribe();\n steps.delete(key);\n if (!steps.size) {\n pendingSteps.delete(actor);\n }\n };\n void promise.then(cleanup, cleanup);\n subscription = actor.subscribe({\n error: reject,\n complete: () =>\n reject(\n new Error(\n isDevelopment\n ? `Actor terminated before step \"${key}\" completed`\n : xstateError(72, key)\n )\n )\n });\n void (async () => {\n try {\n sendSelf({ type: XSTATE_LOGIC_EFFECT_START, key });\n const output = await exec();\n if (actor.getSnapshot().status === 'active') {\n sendSelf({ type: XSTATE_LOGIC_EFFECT_RESOLVE, key, output });\n resolve(output);\n }\n } catch (error) {\n if (actor.getSnapshot().status === 'active') {\n sendSelf({ type: XSTATE_LOGIC_EFFECT_REJECT, key, error });\n }\n reject(error);\n }\n })().catch(reject);\n return promise;\n}\n\n/**\n * Delivers an event directly to a target actor, bypassing any installed host\n * runtime. Custom runtimes use this for the default local delivery behavior\n * inside their own `sendEvent` implementations.\n *\n * @experimental\n */\nexport function deliverEvent(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n): void {\n if (isSerializedActorRef(target)) {\n const serialized = target;\n const system = source?.system;\n const live = system && resolveSerializedActorRef(system, serialized);\n if (!live) {\n const error = createMissingAddressError(serialized);\n if (!system) {\n throw error;\n }\n void system.deadLetter(source, undefined, event, 'missingTarget', {\n targetId: getAddressId(serialized['@actor']),\n error\n });\n return;\n }\n target = live;\n }\n if (rejectUndeliverableEvent(source, target, event)) {\n return;\n }\n const runtimeTarget = target as AnyActor & {\n _send(event: AnyEventObject, sourceRef?: AnyActor): void;\n };\n\n runtimeTarget._send(event, source);\n}\n\n/**\n * Returns the boundary error preventing this delivery, if any: an internal\n * event type cannot cross an actor boundary from an external sender.\n */\nfunction getEventBoundaryError(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n): Error | undefined {\n const runtimeTarget = target as AnyActor & {\n logic?: { isInternalEventType?: (eventType: string) => boolean };\n };\n\n if (\n source !== target &&\n runtimeTarget.logic?.isInternalEventType?.(event.type)\n ) {\n return new Error(\n isDevelopment\n ? `Internal event \"${event.type}\" cannot be sent to actor \"${target.id}\" from outside.`\n : xstateError(73, event.type, target.id)\n );\n }\n return undefined;\n}\n\n/**\n * Rejects an event that must not cross the delivery boundary — an internal\n * event type sent from outside its owning actor — by reporting it as a dead\n * letter. Returns `true` when the event was rejected and must not be\n * delivered. Host runtimes must call this before taking ownership of\n * delivery.\n */\nexport function rejectUndeliverableEvent(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n): boolean {\n const error = getEventBoundaryError(source, target, event);\n if (error) {\n void target.system.deadLetter(source, target, event, 'internalEvent', {\n error\n });\n return true;\n }\n return false;\n}\n\n/**\n * Publishes an actor's terminal result, notifying its parent and observers.\n * Custom runtimes use this for the default local behavior inside their own\n * `terminateActor` implementations.\n *\n * @experimental\n */\nexport function terminateActor(\n actor: AnyActor,\n termination: ActorTermination\n): void {\n (\n actor as AnyActor & { _terminate(termination: ActorTermination): void }\n )._terminate(termination);\n}\n\n/**\n * Stops an actor without producing a completion result. Custom runtimes use\n * this for the default local behavior inside their own `stopActor`\n * implementations.\n *\n * @experimental\n */\nexport function stopActor(actor: AnyActor): void {\n (actor as AnyActor & { _stop(): void })._stop();\n}\n","interface MailboxItem<T> {\n value: T;\n next: MailboxItem<T> | null;\n}\n\nexport class Mailbox<T> {\n private _active: boolean = false;\n private _current: MailboxItem<T> | null = null;\n private _last: MailboxItem<T> | null = null;\n\n constructor(private _process: (ev: T) => void) {}\n\n public start() {\n this._active = true;\n this.flush();\n }\n\n public clear(): void {\n // we can't set _current to null because we might be currently processing\n // and enqueue following clear shouldn't start processing the enqueued item immediately\n if (this._current) {\n this._current.next = null;\n this._last = this._current;\n }\n }\n\n public enqueue(event: T): void {\n const enqueued = {\n value: event,\n next: null\n };\n\n if (this._current) {\n this._last!.next = enqueued;\n this._last = enqueued;\n return;\n }\n\n this._current = enqueued;\n this._last = enqueued;\n\n if (this._active) {\n this.flush();\n }\n }\n\n private flush() {\n while (this._current) {\n // atm the given _process is responsible for implementing proper try/catch handling\n // we assume here that this won't throw in a way that can affect this mailbox\n const consumed = this._current;\n this._process(consumed.value);\n this._current = consumed.next;\n }\n this._last = null;\n }\n}\n","import { XSTATE_INIT } from './constants.ts';\nimport {\n ActorTimeoutEvent,\n AfterEvent,\n DoneActorEvent,\n DoneStateEvent,\n ErrorActorEvent,\n ErrorPlatformEvent,\n TimeoutEvent\n} from './types.ts';\n\n/**\n * Returns an event that represents an implicit event that is sent after the\n * specified `delay`.\n *\n * @param delayRef The delay in milliseconds\n * @param id The state node ID where this event is handled\n */\nexport function createAfterEvent(\n delayRef: number | string,\n id: string\n): AfterEvent {\n return { type: 'xstate.after', delay: delayRef, stateId: id };\n}\n\n/**\n * Returns an event that represents an implicit state-level timeout. Fired when\n * a state's `timeout` duration elapses without the state being exited.\n *\n * @param id The state node ID where this timeout is configured\n */\nexport function createTimeoutEvent(id: string): TimeoutEvent {\n return { type: 'xstate.timeout.state', stateId: id };\n}\n\n/**\n * Returns an event that represents an implicit invoke-level timeout. Fired when\n * an invoked actor has not completed within its `timeout` duration.\n *\n * @param invokeId The invoked actor's ID\n */\nexport function createInvokeTimeoutEvent(\n invokeId: string,\n sessionId?: string\n): ActorTimeoutEvent {\n return {\n type: 'xstate.timeout.actor',\n actorId: invokeId,\n sessionId\n };\n}\n\n/**\n * Returns an event that represents that a final state node has been reached in\n * the parent state node.\n *\n * @param id The final state node's parent state node `id`\n * @param output The data to pass into the event\n */\nexport function createDoneStateEvent(\n id: string,\n output?: unknown\n): DoneStateEvent {\n return {\n type: 'xstate.done.state',\n stateId: id,\n output\n };\n}\n\n/**\n * Returns an event that represents that an invoked service has terminated.\n *\n * An invoked service is terminated when it has reached a top-level final state\n * node, but not when it is canceled.\n *\n * @param invokeId The invoked service ID\n * @param output The data to pass into the event\n * @param sessionId The unique session ID of the completed actor\n */\nexport function createDoneActorEvent(\n invokeId: string,\n output: unknown,\n sessionId: string\n): DoneActorEvent {\n return {\n type: 'xstate.done.actor',\n output,\n actorId: invokeId,\n sessionId\n };\n}\n\nexport function createErrorActorEvent(\n id: string,\n error: unknown,\n sessionId: string\n): ErrorActorEvent {\n return {\n type: 'xstate.error.actor',\n error,\n actorId: id,\n sessionId\n };\n}\n\nexport function createErrorPlatformEvent(\n kind: string,\n error?: unknown\n): ErrorPlatformEvent {\n return { type: `xstate.error.${kind}`, error };\n}\n\nexport function createInitEvent(input: unknown) {\n return { type: XSTATE_INIT, input } as const;\n}\n","/**\n * This function makes sure that unhandled errors are thrown in a separate\n * macrotask. It allows those errors to be detected by global error handlers and\n * reported to bug tracking services without interrupting our own stack of\n * execution.\n *\n * @param err Error to be thrown\n */\nexport function reportUnhandledError(err: unknown) {\n setTimeout(() => {\n throw err;\n });\n}\n","export const symbolObservable: typeof Symbol.observable = (() =>\n (typeof Symbol === 'function' && Symbol.observable) ||\n '@@observable')() as any;\n","import type { AnyActor } from './types.ts';\n\ntype TransitionSelectionFrame = {\n mode: 'abort' | 'suppress';\n parent: AnyActor | undefined;\n requiresReevaluation: boolean;\n};\n\nconst selectionFrames: TransitionSelectionFrame[] = [];\n\nexport const transitionEffectSignal = new Error('Transition effect');\n\nexport function protectSelectionRelay(target: AnyActor): boolean {\n let matched = false;\n let abort = false;\n for (const frame of selectionFrames) {\n if (frame.parent === target) {\n frame.requiresReevaluation = true;\n matched = true;\n abort ||= frame.mode === 'abort';\n }\n }\n if (abort) {\n throw transitionEffectSignal;\n }\n return matched;\n}\n\nexport function beginTransitionSelection(\n parent: AnyActor | undefined,\n mode: TransitionSelectionFrame['mode'] = 'abort'\n) {\n const frame: TransitionSelectionFrame = {\n mode,\n parent,\n requiresReevaluation: false\n };\n selectionFrames.push(frame);\n return {\n frame,\n close() {\n selectionFrames.pop();\n }\n };\n}\n","import type { AnyActor, EventObject, TimerKey } from './types.ts';\n\ntype TimerIdentity = { id?: string; seq?: number; event: EventObject };\n\n/**\n * @internal The identity fields of a built-in timer event (`after`, state and\n * invoke `timeout`), or `undefined` for any other event.\n */\nexport function getBuiltInTimerIdentity(\n event: EventObject\n): EventObject | undefined {\n const { stateId, delay, actorId } = event as {\n stateId?: unknown;\n delay?: unknown;\n actorId?: unknown;\n };\n switch (event.type) {\n case 'xstate.after':\n // Same field order as the event, so persisted events serialize alike.\n return { type: event.type, delay, stateId } as EventObject;\n case 'xstate.timeout.state':\n return { type: event.type, stateId } as EventObject;\n case 'xstate.timeout.actor':\n return { type: event.type, actorId } as EventObject;\n }\n return undefined;\n}\n\n/** @internal The key of a logical timer, effect or cancellation. */\nexport function getTimerKey(timer: TimerIdentity): TimerKey {\n if (timer.id !== undefined) {\n return { id: timer.id };\n }\n if (timer.seq !== undefined) {\n return { seq: timer.seq };\n }\n return { event: getBuiltInTimerIdentity(timer.event) ?? timer.event };\n}\n\n/**\n * @internal Reads the timer key carried by a firing input or cancellation\n * (`{ id }`, `{ seq }` or `{ event }` fields).\n */\nexport function readTimerKey(input: object): TimerKey | undefined {\n const value = input as { id?: unknown; seq?: unknown; event?: unknown };\n if (typeof value.id === 'string') {\n return { id: value.id };\n }\n if (typeof value.seq === 'number') {\n return { seq: value.seq };\n }\n if (\n value.event &&\n typeof value.event === 'object' &&\n typeof (value.event as EventObject).type === 'string'\n ) {\n return { event: value.event as EventObject };\n }\n return undefined;\n}\n\n/** @internal Whether a logical timer has the given key. */\nexport function matchesTimerKey(timer: TimerIdentity, key: TimerKey): boolean {\n if ('id' in key) {\n return timer.id === key.id;\n }\n if (timer.id !== undefined) {\n return false;\n }\n if ('seq' in key) {\n return timer.seq === key.seq;\n }\n if (timer.seq !== undefined) {\n return false;\n }\n const event = timer.event as unknown as Record<string, unknown>;\n const pattern = key.event as unknown as Record<string, unknown>;\n for (const field in pattern) {\n if (event[field] !== pattern[field]) {\n return false;\n }\n }\n return true;\n}\n\n/** @internal A private string form of a timer key, for in-memory maps. */\nexport function serializeTimerKey(key: TimerKey): string {\n if ('id' in key) {\n return JSON.stringify(['id', key.id]);\n }\n if ('seq' in key) {\n return JSON.stringify(['seq', key.seq]);\n }\n return JSON.stringify([\n 'event',\n getBuiltInTimerIdentity(key.event) ?? key.event\n ]);\n}\n\n/** @internal The private local-scheduler key of an actor's logical timer. */\nexport function getScheduledTimerKey(actor: AnyActor, key: TimerKey): string {\n return `${actor.sessionId}|${serializeTimerKey(key)}`;\n}\n","import isDevelopment from '#is-development';\nimport { xstateError } from './xstateError.ts';\nimport { publishEmittedEvent } from './runtimeHelpers.ts';\nimport { assertSendToEvent, builtInActions } from './actions.ts';\nimport { resolveRegisteredActorSource } from './actorSource.ts';\nimport { listenerLogic, type ListenerInput } from './actors/listener.ts';\nimport {\n subscriptionLogic,\n type SubscriptionInput,\n type SubscriptionMappers\n} from './actors/subscription.ts';\nimport { XSTATE_SPAWN, XSTATE_START, XSTATE_TERMINATE } from './constants.ts';\nimport {\n getBuiltInTimerIdentity,\n getTimerKey,\n matchesTimerKey,\n readTimerKey\n} from './timerKey.ts';\nimport { createInertActorRef } from './remoteActorRef.ts';\nimport {\n encodeAddressSegment,\n getActorIdPrefix,\n parseGeneratedActorId,\n type ActorSystemRuntime,\n type DeadLetterDetail,\n type EventRejectionReason\n} from './system.ts';\nimport type {\n ActorTermination,\n AnyAction,\n AnyActor,\n AnyActorLogic,\n AnyActorScope,\n AnyEventObject,\n AnyMachineSnapshot,\n CancelExecutableEffect,\n CustomExecutableEffect,\n EmitExecutableEffect,\n EnqueueObject,\n EventObject,\n ExecutableEffect,\n MachineContext,\n LogicalTimer,\n RaiseExecutableEffect,\n DeadLetterExecutableEffect,\n SendToExecutableEffect,\n Snapshot,\n SpecialExecutableEffect,\n SpawnExecutableEffect,\n StartExecutableEffect,\n StopExecutableEffect,\n TerminateExecutableEffect,\n TimerKey\n} from './types.ts';\n\ntype TransitionActionRecord = {\n action: (...args: any[]) => any;\n args: any[];\n childUpdate?:\n | {\n type: 'add';\n actor: AnyActor;\n id: string;\n counters?: Record<string, number>;\n }\n | { type: 'remove'; actor: AnyActor };\n};\n\ntype EffectRuntime = Partial<ActorSystemRuntime>;\n\nfunction execCustomEffect(\n this: CustomExecutableEffect\n): void | PromiseLike<void> | undefined {\n const result = this.action?.(...this.args);\n if (isDevelopment) {\n warnOnIgnoredEffectResult(this, result);\n }\n return result;\n}\n\nconst warnedEffectResults = new WeakSet<object>();\n\n/**\n * A function passed to `enq(...)` runs as an effect after the transition is\n * computed, so a `{ context }` or `{ children }` it returns is never applied.\n * Development builds say so, once per function.\n */\nfunction warnOnIgnoredEffectResult(\n effect: CustomExecutableEffect,\n result: unknown\n): void {\n if (\n !effect.action ||\n result === null ||\n typeof result !== 'object' ||\n warnedEffectResults.has(effect.action)\n ) {\n return;\n }\n const prototype = Object.getPrototypeOf(result);\n if (prototype !== Object.prototype && prototype !== null) {\n return;\n }\n const keys = ['context', 'children'].filter((key) => key in result);\n if (!keys.length) {\n return;\n }\n warnedEffectResults.add(effect.action);\n console.warn(\n `Action \"${effect.type || '(anonymous)'}\" returned { ${keys.join(', ')} }, which is ignored: functions passed to enq(...) run as effects after the transition. Return the patch from the transition, entry or exit function instead; a named action can be called there directly and its result returned.`\n );\n}\n\nfunction execEmitEffect(\n this: EmitExecutableEffect,\n runtime: EffectRuntime = this.source.system\n): void | PromiseLike<void> {\n return publishEmittedEvent(this.source, this.event, runtime);\n}\n\n/** @internal Creates an emitted-event effect. */\nexport function createEmitEffect(\n actorScope: AnyActorScope,\n event: EventObject\n): EmitExecutableEffect {\n return {\n kind: 'emit',\n exec: execEmitEffect,\n type: event.type,\n source: actorScope.self,\n event,\n params: undefined,\n args: []\n };\n}\n\nfunction execDeadLetterEffect(\n this: DeadLetterExecutableEffect,\n runtime: EffectRuntime = (this.target ?? this.source)!.system\n): void | PromiseLike<void> {\n return runtime.deadLetter!(\n this.source,\n this.target,\n this.event,\n this.reason,\n this.detail\n );\n}\n\n/** @internal Creates a dead-letter effect for a boundary-rejected event. */\nexport function createDeadLetterEffect(\n actorScope: AnyActorScope,\n source: AnyActor | undefined,\n event: AnyEventObject,\n reason: EventRejectionReason,\n detail?: DeadLetterDetail\n): DeadLetterExecutableEffect {\n return {\n kind: 'builtin',\n type: '@xstate.deadLetter',\n exec: execDeadLetterEffect,\n source,\n target: actorScope.self,\n event,\n reason,\n detail,\n params: undefined,\n args: []\n };\n}\n\n/**\n * @internal Creates a dead-letter effect for an `enq.sendTo` whose target is\n * an undefined ref, an unknown child id, or the parent of a root actor.\n */\nfunction createMissingTargetEffect(\n actorScope: AnyActorScope,\n event: AnyEventObject,\n targetId: string | undefined\n): DeadLetterExecutableEffect {\n return {\n kind: 'builtin',\n type: '@xstate.deadLetter',\n exec: execDeadLetterEffect,\n source: actorScope.self,\n target: undefined,\n event,\n reason: 'missingTarget',\n detail: {\n targetId,\n error: new Error(\n !isDevelopment\n ? xstateError(65, targetId)\n : targetId !== undefined\n ? `Unable to send event to unknown child '${targetId}'`\n : 'Unable to send event to an undefined actor'\n )\n },\n params: undefined,\n args: []\n };\n}\n\n/** @internal Creates a directly executable user effect. */\nexport function createCustomEffect(\n type: string,\n action: (runtime?: EffectRuntime) => void | PromiseLike<void> | undefined,\n params?: unknown\n): CustomExecutableEffect {\n return {\n kind: 'action',\n exec: action,\n type,\n action: action as () => void | PromiseLike<void>,\n params,\n args: []\n };\n}\n\nfunction execSpawnEffect(\n this: SpawnExecutableEffect,\n runtime: EffectRuntime = this.actor.system\n): void | PromiseLike<void> {\n return runtime.spawnActor!(this.source, this.actor);\n}\n\nfunction execStartEffect(\n this: StartExecutableEffect,\n runtime: EffectRuntime = this.actor.system\n): void | PromiseLike<void> {\n // A child stopped before its deferred start (spawned and stopped in the\n // same transition) stays stopped; actors cannot be restarted.\n if (\n (this.actor as { _processingStatus?: number })._processingStatus ===\n 2 /* ProcessingStatus.Stopped */\n ) {\n return;\n }\n return runtime.startActor!(this.actor);\n}\n\nfunction execStopEffect(\n this: StopExecutableEffect,\n runtime: EffectRuntime = this.source.system\n): void | PromiseLike<void> {\n return runtime.stopActor!(this.actor);\n}\n\nfunction execTerminateEffect(\n this: TerminateExecutableEffect,\n runtime: EffectRuntime = this.actor.system\n): void | PromiseLike<void> {\n const termination: ActorTermination =\n this.status === 'done'\n ? { status: 'done', output: this.output, error: undefined }\n : { status: 'error', output: undefined, error: this.error };\n return runtime.terminateActor!(this.actor, termination);\n}\n\nfunction execRaiseEffect(\n this: RaiseExecutableEffect,\n runtime: EffectRuntime = this.source.system\n): void | PromiseLike<void> {\n return runtime.scheduleTimer!(\n this.source,\n getTimerKey(this),\n this.delay ?? 0\n );\n}\n\nfunction execSendToEffect(\n this: SendToExecutableEffect,\n runtime: EffectRuntime = this.source.system\n): void | PromiseLike<void> {\n assertSendToEvent(this.event);\n if (this.delay !== undefined) {\n return runtime.scheduleTimer!(this.source, getTimerKey(this), this.delay);\n }\n return runtime.sendEvent!(this.source, this.target, this.event);\n}\n\nfunction execCancelEffect(\n this: CancelExecutableEffect,\n runtime: EffectRuntime = this.source.system\n): void | PromiseLike<void> {\n return runtime.cancelTimer!(this.source, readTimerKey(this)!);\n}\n\nfunction updateLogicalTimers(\n snapshot: AnyMachineSnapshot,\n effect: ExecutableEffect,\n actorScope: AnyActorScope\n): AnyMachineSnapshot {\n if (!isBuiltInExecutableEffect(effect)) {\n return snapshot;\n }\n\n if (effect.type === '@xstate.cancel') {\n const key = readTimerKey(effect)!;\n if (!snapshot.timers?.some((timer) => matchesTimerKey(timer, key))) {\n return snapshot;\n }\n return {\n ...snapshot,\n timers: snapshot.timers.filter((timer) => !matchesTimerKey(timer, key))\n };\n }\n\n if (\n (effect.type !== '@xstate.raise' && effect.type !== '@xstate.sendTo') ||\n effect.delay === undefined\n ) {\n return snapshot;\n }\n\n // A delayed raise or send without an `id` is numbered by the actor's\n // timer sequence. Built-in timers (`after`, `timeout`) have neither; their\n // event identifies them.\n let nextTimerId = snapshot._nextTimerId ?? 0;\n if (effect.id === undefined && !getBuiltInTimerIdentity(effect.event)) {\n effect.seq = nextTimerId++;\n const args = effect.args as unknown[];\n args[args.length - 1] = {\n ...(args[args.length - 1] as object),\n seq: effect.seq\n };\n }\n const target =\n effect.type === '@xstate.raise' || effect.target === actorScope.self\n ? 'self'\n : effect.target;\n const timer: LogicalTimer = {\n ...(effect.id !== undefined && { id: effect.id }),\n ...(effect.seq !== undefined && { seq: effect.seq }),\n delay: effect.delay,\n type: effect.type,\n event: effect.event,\n target\n };\n // Scheduling a timer that is already pending replaces it in place.\n const key = getTimerKey(timer);\n const timers = snapshot.timers ?? [];\n const index = timers.findIndex((pending) => matchesTimerKey(pending, key));\n\n return {\n ...snapshot,\n timers:\n index === -1\n ? [...timers, timer]\n : timers.map((pending, i) => (i === index ? timer : pending)),\n _nextTimerId: nextTimerId\n };\n}\n\nexport function mergeContextPatch(\n context: MachineContext,\n patch: MachineContext\n): MachineContext {\n return { ...context, ...patch };\n}\n\nfunction pushBuiltInAction(actions: any[], action: any, ...args: any[]) {\n const actionRecord: TransitionActionRecord = { action, args };\n actions.push(actionRecord as AnyAction);\n return actionRecord;\n}\n\n/** @internal Max-merges generated-id counter records, copy-on-write. */\nexport function mergeActorIdCounters(\n current: Record<string, number> | undefined,\n update: Record<string, number>\n): Record<string, number> {\n const merged = { ...current };\n for (const key of Object.keys(update)) {\n merged[key] = Math.max(merged[key] ?? 0, update[key]);\n }\n return merged;\n}\n\nfunction applyChildUpdate(\n snapshot: AnyMachineSnapshot,\n update: NonNullable<TransitionActionRecord['childUpdate']>,\n actorScope: AnyActorScope\n): AnyMachineSnapshot {\n if (update.type === 'add') {\n return {\n ...snapshot,\n children: { ...snapshot.children, [update.id]: update.actor },\n ...(update.counters && {\n _nextActorIds: mergeActorIdCounters(\n snapshot._nextActorIds,\n update.counters\n )\n })\n };\n }\n\n const children = { ...snapshot.children };\n let owned = update.actor._parent === actorScope.self;\n for (const key of Object.keys(children)) {\n if (children[key] === update.actor) {\n owned = true;\n delete children[key];\n }\n }\n if (!owned) {\n throw new Error(\n isDevelopment\n ? `Cannot stop child actor ${update.actor.id} of ${actorScope.self.id} because it is not a child`\n : xstateError(47, update.actor.id, actorScope.self.id)\n );\n }\n actorScope.system._unregister(update.actor);\n return { ...snapshot, children };\n}\n\nfunction getTransitionActionRecord(\n action: AnyAction\n): TransitionActionRecord | undefined {\n if (\n typeof action === 'object' &&\n action !== null &&\n 'action' in action &&\n typeof action.action === 'function'\n ) {\n return action as TransitionActionRecord;\n }\n return undefined;\n}\n\nfunction pushSpawnedChild(\n actions: any[],\n actor: AnyActor,\n id: string,\n counters?: Record<string, number>\n) {\n const action = pushBuiltInAction(\n actions,\n builtInActions['@xstate.spawn'],\n actor\n );\n action.childUpdate = { type: 'add', actor, id, counters };\n}\n\n/**\n * Spawn-allocation state shared by every enqueue object of one transition, so\n * generated ids stay unique and resolvable across action functions and\n * microsteps of the same event.\n */\ninterface SpawnAllocation {\n counters: Map<string, number>;\n /** Explicit child ids claimed by spawns/invokes of this transition. */\n explicitIds: Set<string>;\n /** Ids of children stopped by this transition, freeing them for reuse. */\n stoppedIds: Set<string>;\n}\n\nconst spawnAllocations = new WeakMap<object, SpawnAllocation>();\n\nconst createSpawnAllocation = (): SpawnAllocation => ({\n counters: new Map(),\n explicitIds: new Set(),\n stoppedIds: new Set()\n});\n\n/**\n * Starts a fresh spawn-allocation transaction for one logical transition.\n * Called at every transition boundary so pure replays from the same snapshot\n * allocate identical ids.\n *\n * @internal\n */\nexport function beginSpawnAllocation(actorScope: AnyActorScope): void {\n spawnAllocations.set(actorScope, createSpawnAllocation());\n}\n\n// Read the raw snapshot: getSnapshot() throws while the actor initializes,\n// and entry actions run before any snapshot exists.\nfunction getWorkingSnapshotOf(actorScope: AnyActorScope):\n | {\n _nextActorIds?: Record<string, number>;\n children?: Record<string, AnyActor | undefined>;\n }\n | undefined {\n return (\n actorScope.self as {\n _snapshot?: {\n _nextActorIds?: Record<string, number>;\n children?: Record<string, AnyActor | undefined>;\n };\n }\n )._snapshot;\n}\n\nfunction getRegisteredActors(\n actorScope: AnyActorScope\n): Record<string, AnyActorLogic> | undefined {\n return (\n actorScope.self as {\n logic?: { sources?: { actors?: Record<string, AnyActorLogic> } };\n }\n ).logic?.sources?.actors;\n}\n\nfunction resolveTransitionSpawnSource(\n actorScope: AnyActorScope,\n source: string | AnyActorLogic\n): { logic: AnyActorLogic; src: string | undefined } {\n const registeredActors = getRegisteredActors(actorScope);\n if (typeof source === 'string') {\n const logic = registeredActors?.[source];\n if (!logic) {\n throw new Error(\n isDevelopment\n ? `Actor source '${source}' is not provided`\n : xstateError(66, source)\n );\n }\n return { logic, src: source };\n }\n if (!registeredActors) {\n return { logic: source, src: undefined };\n }\n return {\n logic: source,\n src: resolveRegisteredActorSource(registeredActors, source)\n };\n}\n\n/**\n * Internal helper actors (listeners, subscriptions) number their ids from\n * system-level counters under `@xstate.`-prefixed names; snapshot-owned\n * children number from per-snapshot counters. The two spaces only stay\n * collision-free because their prefixes are disjoint, so user sources must\n * not enter the reserved `xstate.` / `@xstate.` namespaces.\n */\nfunction assertUnreservedPrefix(prefix: string): void {\n if (\n isDevelopment &&\n (prefix.startsWith('xstate.') || prefix.startsWith('@xstate.'))\n ) {\n throw new Error(\n `Child actor ids with the \"xstate.\" or \"@xstate.\" prefix are reserved for internal actors; rename the \"${prefix}\" source or logic id.`\n );\n }\n}\n\n/**\n * The next free index for a prefix. The parent snapshot's persisted counter\n * is always a floor, so a freed id is never handed out again — not even when\n * an explicit id reserved a lower one earlier in the transition.\n */\nfunction nextChildIndex(\n actorScope: AnyActorScope,\n allocation: SpawnAllocation,\n prefix: string\n): number {\n return Math.max(\n allocation.counters.get(prefix) ?? 0,\n getWorkingSnapshotOf(actorScope)?._nextActorIds?.[prefix] ?? 0\n );\n}\n\n/**\n * The next generated index for a prefix that is not claimed in this\n * transition or held by a live child, such as an implicit invoke id\n * (`worker:0` for an invoke in state `worker`). Does not allocate.\n */\nfunction nextFreeChildIndex(\n actorScope: AnyActorScope,\n allocation: SpawnAllocation,\n prefix: string\n): number {\n let next = nextChildIndex(actorScope, allocation, prefix);\n const children = getWorkingSnapshotOf(actorScope)?.children;\n while (\n allocation.explicitIds.has(`${prefix}:${next}`) ||\n children?.[`${prefix}:${next}`]\n ) {\n next++;\n }\n return next;\n}\n\n/**\n * Allocates the next generated child id for the transition's allocation\n * transaction, seeded from the parent snapshot's own persisted counters. This\n * is the single allocator for snapshot-owned children (`enq.spawn` and\n * context-factory spawns); a correct allocation cannot collide.\n *\n * @internal\n */\nexport function allocateChildId(\n actorScope: AnyActorScope,\n src: string | AnyActorLogic,\n localAllocation?: SpawnAllocation\n): { id: string; counters: Record<string, number> } {\n if (isDevelopment && !spawnAllocations.get(actorScope)) {\n console.warn(\n 'A child id was generated outside a spawn-allocation transaction; ids may repeat across enqueue objects. Transition entry points must call beginSpawnAllocation().'\n );\n }\n const allocation =\n spawnAllocations.get(actorScope) ??\n localAllocation ??\n createSpawnAllocation();\n const prefix = getActorIdPrefix(src);\n assertUnreservedPrefix(prefix);\n const next = nextFreeChildIndex(actorScope, allocation, prefix);\n allocation.counters.set(prefix, next + 1);\n return { id: `${prefix}:${next}`, counters: { [prefix]: next + 1 } };\n}\n\n/**\n * Requires an explicit child id to be unoccupied before a spawn or invoke\n * claims it: an address must name at most one live actor. An id is occupied\n * when a child of this parent already holds it and this transition has not\n * stopped that child, or when an earlier spawn of this transition claimed it.\n *\n * @internal\n */\nexport function assertChildIdFree(\n actorScope: AnyActorScope,\n id: string,\n localAllocation?: SpawnAllocation\n): void {\n const allocation =\n spawnAllocations.get(actorScope) ??\n localAllocation ??\n createSpawnAllocation();\n const existing = getWorkingSnapshotOf(actorScope)?.children?.[id] as\n | AnyActor\n | undefined;\n // A terminated child no longer occupies its id: it relayed its completion\n // and is removed from `children` right after the transition handling it,\n // so the supervisor pattern — respawn under the same name while handling\n // the child's done/error event — must not conflict with the outgoing\n // entry. Remote handles never expose a terminal status locally; the\n // completion event that removes one is the owning runtime's business.\n const occupied =\n existing !== undefined &&\n !allocation.stoppedIds.has(id) &&\n existing.getSnapshot().status === 'active';\n if (allocation.explicitIds.has(id) || occupied) {\n throw new Error(\n isDevelopment\n ? `Cannot spawn child actor with id '${id}': the id is already in use by another child of '${actorScope.self.id}'. Stop the existing child before reusing its id.`\n : xstateError(67, id, actorScope.self.id)\n );\n }\n allocation.explicitIds.add(id);\n}\n\n/**\n * Records that this transition stopped a child, freeing its id for a later\n * spawn or invoke of the same transition (the invoke restart pattern).\n *\n * @internal\n */\nfunction recordStoppedChild(actorScope: AnyActorScope, actor: AnyActor): void {\n const allocation = spawnAllocations.get(actorScope);\n if (allocation) {\n allocation.stoppedIds.add(actor.id);\n allocation.explicitIds.delete(actor.id);\n }\n}\n\n/**\n * Reserves an explicit generated-shaped id (`worker:5`) in the transaction\n * and the parent snapshot, so live runs and pure replays allocate the same\n * later ids even after this child is removed.\n *\n * @internal\n */\nexport function reserveChildId(\n actorScope: AnyActorScope,\n id: string,\n localAllocation?: SpawnAllocation\n): Record<string, number> | undefined {\n const generated = parseGeneratedActorId(id);\n if (!generated) {\n return undefined;\n }\n assertUnreservedPrefix(generated.prefix);\n const allocation =\n spawnAllocations.get(actorScope) ??\n localAllocation ??\n createSpawnAllocation();\n // The requested id is used as asked, but numbering continues from the\n // highest reservation: an explicit low id never rewinds the counter.\n const next = Math.max(\n nextChildIndex(actorScope, allocation, generated.prefix),\n generated.index + 1\n );\n allocation.counters.set(generated.prefix, next);\n return { [generated.prefix]: next };\n}\n\n/**\n * The counters allocated so far in the transition's transaction, for\n * committing into a snapshot built outside `applyChildUpdate` (the\n * pre-initial snapshot with context-factory spawns).\n *\n * @internal\n */\nexport function takeSpawnAllocationCounters(\n actorScope: AnyActorScope\n): Record<string, number> | undefined {\n const counters = spawnAllocations.get(actorScope)?.counters;\n if (!counters?.size) {\n return undefined;\n }\n return Object.fromEntries(counters);\n}\n\n/**\n * Scopes whose `self` is not the evaluated snapshot's actor (the shared\n * `snapshot.can(...)` scope), so spawned inert refs have no address.\n *\n * @internal\n */\nexport const detachedScopes = new WeakSet<AnyActorScope>();\n\nexport function assertRaiseEvent(event: unknown): void {\n if (typeof event === 'string') {\n throw new Error(\n isDevelopment\n ? `Only event objects may be used with raise; use raise({ type: \"${event}\" }) instead`\n : xstateError(68, event)\n );\n }\n}\n\nexport function createTransitionEnqueue(\n actorScope: AnyActorScope,\n actions: any[],\n internalEvents: EventObject[],\n actorSubscriptions = false,\n createActors = true\n) {\n // Paths that never begin a transaction keep a per-enqueue scope.\n const localAllocation =\n spawnAllocations.get(actorScope) ?? createSpawnAllocation();\n const props: Partial<EnqueueObject<any, any>> = {\n cancel: (id: string | TimerKey) => {\n pushBuiltInAction(\n actions,\n builtInActions['@xstate.cancel'],\n actorScope,\n typeof id === 'string' ? { id } : id\n );\n },\n emit: (emittedEvent) => {\n actions.push(emittedEvent);\n },\n log: (...args) => {\n pushBuiltInAction(actions, actorScope.logger, ...args);\n },\n raise: (raisedEvent, options) => {\n assertRaiseEvent(raisedEvent);\n if (options?.delay !== undefined) {\n pushBuiltInAction(\n actions,\n builtInActions['@xstate.raise'],\n actorScope,\n raisedEvent,\n options\n );\n } else {\n internalEvents.push(raisedEvent);\n }\n },\n spawn: (source: string | AnyActorLogic, options?: any) => {\n const { logic, src } = resolveTransitionSpawnSource(actorScope, source);\n if (!createActors) {\n // Speculative evaluation creates no actor and allocates no id: return\n // an inert ref with the id this spawn would get.\n const prefix = getActorIdPrefix(src ?? logic);\n const id =\n options?.id ??\n `${prefix}:${nextFreeChildIndex(actorScope, spawnAllocations.get(actorScope) ?? localAllocation, prefix)}`;\n return createInertActorRef({\n id,\n address: detachedScopes.has(actorScope)\n ? undefined\n : `${actorScope.self.address}/${encodeAddressSegment(id)}`,\n src\n });\n }\n // Generated ids allocate from the parent snapshot's own counters\n // through the transition's allocation transaction; explicit\n // generated-shaped ids reserve their numbering the same way.\n let id = options?.id;\n let counters: Record<string, number> | undefined;\n if (id === undefined) {\n ({ id, counters } = allocateChildId(\n actorScope,\n src ?? logic,\n localAllocation\n ));\n } else {\n assertChildIdFree(actorScope, id, localAllocation);\n counters = reserveChildId(actorScope, id, localAllocation);\n }\n const actor = actorScope.system.createActorRef(logic, {\n ...options,\n ...(src !== undefined && { src }),\n id,\n parent: actorScope.self\n });\n pushSpawnedChild(actions, actor, id, counters);\n return actor;\n },\n sendTo: (actor, event, options) => {\n // A missing target (undefined ref, unknown child id, or `parent` of a\n // root actor) resolves to a dead letter in `resolveActionsWithContext`.\n pushBuiltInAction(\n actions,\n builtInActions['@xstate.sendTo'],\n actorScope,\n actor,\n event,\n options\n );\n },\n stop: (actor) => {\n if (actor) {\n // enq.stop accepts the consumer ActorRef contract; refs handed to\n // machine code are always full actor instances at runtime.\n const actorInstance = actor as AnyActor;\n const action = pushBuiltInAction(\n actions,\n builtInActions['@xstate.stop'],\n actorScope,\n actorInstance\n );\n action.childUpdate = { type: 'remove', actor: actorInstance };\n recordStoppedChild(actorScope, actorInstance);\n }\n }\n };\n\n if (actorSubscriptions) {\n Object.assign(props, {\n listen: (actor: any, eventType: string, mapper: any) => {\n if (!createActors) {\n return { id: undefined } as unknown as AnyActor;\n }\n const input: ListenerInput<any, any> = {\n actor,\n eventType,\n mapper\n };\n const listenerActor = actorScope.system.createActorRef(listenerLogic, {\n input,\n parent: actorScope.self\n });\n pushBuiltInAction(\n actions,\n builtInActions['@xstate.spawn'],\n listenerActor\n );\n return listenerActor;\n },\n subscribeTo: (actor: any, mappers: any) => {\n if (!createActors) {\n return { id: undefined } as unknown as AnyActor;\n }\n const normalizedMappers: SubscriptionMappers<any, any, any> =\n typeof mappers === 'function' ? { snapshot: mappers } : mappers;\n\n const input: SubscriptionInput<any, any, any, any> = {\n actor,\n mappers: normalizedMappers\n };\n const subscriptionActor = actorScope.system.createActorRef(\n subscriptionLogic,\n {\n input,\n parent: actorScope.self\n }\n );\n pushBuiltInAction(\n actions,\n builtInActions['@xstate.spawn'],\n subscriptionActor\n );\n return subscriptionActor;\n }\n });\n }\n\n // The handle is only valid while its function runs; `closeTransitionEnqueue`\n // invalidates it once the function returns.\n let closed = false;\n const guard =\n <T extends (...args: any[]) => any>(fn: T) =>\n (...args: Parameters<T>) =>\n closed ? lateEnqueueCall() : fn(...args);\n for (const key of Object.keys(props) as (keyof typeof props)[]) {\n (props as any)[key] = guard((props as any)[key]);\n }\n const enqueue = createEnqueueObject(\n props,\n guard((action, ...args) => {\n // A named action is `undefined` when it has no implementation. Skip it:\n // an `{ action, args }` record without a function would be emitted as\n // an event. Speculative passes (`can()`, conflict resolution) run with\n // `createActors: false`; warn only when the transition really runs.\n if (typeof action !== 'function') {\n if (isDevelopment && createActors) {\n warnNotAFunction(action);\n }\n return;\n }\n pushBuiltInAction(actions, action, ...args);\n })\n );\n enqueueClosers.set(enqueue, () => {\n closed = true;\n });\n return enqueue;\n}\n\nconst enqueueClosers = new WeakMap<object, () => void>();\n\n/**\n * @internal Invalidates an enqueue handle after the function it was passed\n * to returned. Later `enq.*` calls throw in development and no-op in\n * production.\n */\nexport function closeTransitionEnqueue(enqueue: object): void {\n enqueueClosers.get(enqueue)?.();\n}\n\n/** @internal Handles an `enq.*` call made after its function returned. */\nexport function lateEnqueueCall(): any {\n if (isDevelopment) {\n throw new Error('enq.* called after the transition function returned');\n }\n return undefined;\n}\n\nfunction warnNotAFunction(value: unknown): void {\n const received =\n typeof value === 'string'\n ? `the string \"${value}\"`\n : value !== null && typeof value === 'object'\n ? 'an object'\n : String(value);\n console.warn(\n `enq(...) received ${received} instead of a function, so nothing was enqueued. A named action is undefined when it has no implementation: implement it in setup({ actions }) or the machine config, or pass it to machine.provide({ actions }).`\n );\n}\n\nfunction getBuiltInActionFields(\n action: (...args: any[]) => void,\n args: unknown[]\n): Partial<SpecialExecutableEffect> | undefined {\n switch (action) {\n case builtInActions['@xstate.spawn']: {\n const [actor] = args as Parameters<\n (typeof builtInActions)['@xstate.spawn']\n >;\n return {\n type: '@xstate.spawn',\n kind: 'builtin',\n exec: execSpawnEffect,\n source: actor._parent,\n actor,\n id: actor.id,\n logic: (actor as any).logic,\n src: actor.src,\n input: (actor as any).options?.input\n };\n }\n case builtInActions['@xstate.raise']: {\n const [, event, options] = args as Parameters<\n (typeof builtInActions)['@xstate.raise']\n >;\n return {\n type: '@xstate.raise',\n kind: 'builtin',\n exec: execRaiseEffect,\n source: (\n args as Parameters<(typeof builtInActions)['@xstate.raise']>\n )[0].self,\n event,\n id: options?.id,\n delay: options?.delay\n };\n }\n case builtInActions['@xstate.sendTo']: {\n const [, target, event, options] = args as Parameters<\n (typeof builtInActions)['@xstate.sendTo']\n >;\n return {\n type: '@xstate.sendTo',\n kind: 'builtin',\n exec: execSendToEffect,\n source: (\n args as Parameters<(typeof builtInActions)['@xstate.sendTo']>\n )[0].self,\n target,\n event,\n id: options?.id,\n delay: options?.delay\n };\n }\n case builtInActions['@xstate.cancel']: {\n const [, key] = args as Parameters<\n (typeof builtInActions)['@xstate.cancel']\n >;\n return {\n type: '@xstate.cancel',\n kind: 'builtin',\n exec: execCancelEffect,\n source: (\n args as Parameters<(typeof builtInActions)['@xstate.cancel']>\n )[0].self,\n ...key\n };\n }\n case builtInActions['@xstate.stop']: {\n const [, actor] = args as Parameters<\n (typeof builtInActions)['@xstate.stop']\n >;\n return {\n type: '@xstate.stop',\n kind: 'builtin',\n exec: execStopEffect,\n source: (args as Parameters<(typeof builtInActions)['@xstate.stop']>)[0]\n .self,\n actor,\n id: actor.id\n };\n }\n default:\n return undefined;\n }\n}\n\n/** @internal Creates an actor-start effect, including for restored children. */\nexport function createStartEffect(actor: AnyActor): StartExecutableEffect {\n const args: Parameters<(typeof builtInActions)['@xstate.start']> = [actor];\n return {\n kind: 'builtin',\n exec: execStartEffect,\n type: XSTATE_START,\n source: actor._parent,\n params: undefined,\n args,\n actor,\n id: actor.id\n };\n}\n\n/** @internal Recreates a pending logical timer without re-entering its state. */\nexport function createTimerEffect(\n actorScope: AnyActorScope,\n timer: LogicalTimer,\n delay: number\n): RaiseExecutableEffect | SendToExecutableEffect {\n const source = actorScope.self;\n const options = { id: timer.id, seq: timer.seq, delay };\n if (timer.type === '@xstate.raise') {\n return {\n kind: 'builtin',\n type: timer.type,\n source,\n event: timer.event,\n id: timer.id,\n ...(timer.seq !== undefined && { seq: timer.seq }),\n delay,\n params: undefined,\n args: [actorScope, timer.event, options],\n exec: execRaiseEffect\n };\n }\n const target = timer.target === 'self' ? source : timer.target;\n return {\n kind: 'builtin',\n type: timer.type,\n source,\n target,\n event: timer.event,\n id: timer.id,\n ...(timer.seq !== undefined && { seq: timer.seq }),\n delay,\n params: undefined,\n args: [actorScope, target, timer.event, options],\n exec: execSendToEffect\n };\n}\n\nexport function createSpawnEffect(actor: AnyActor): SpawnExecutableEffect {\n const args: Parameters<(typeof builtInActions)['@xstate.spawn']> = [actor];\n return {\n kind: 'builtin',\n exec: execSpawnEffect,\n type: XSTATE_SPAWN,\n source: actor._parent,\n params: undefined,\n args,\n actor,\n id: actor.id,\n logic: (actor as any).logic,\n src: actor.src,\n input: (actor as any).options?.input\n };\n}\n\n/** @internal Creates an immediate actor-to-actor delivery effect. */\nexport function createSendToEffect(\n actorScope: AnyActorScope,\n target: AnyActor,\n event: EventObject\n): SendToExecutableEffect {\n const args: Parameters<(typeof builtInActions)['@xstate.sendTo']> = [\n actorScope,\n target,\n event,\n {}\n ];\n return {\n kind: 'builtin',\n exec: execSendToEffect,\n type: '@xstate.sendTo',\n source: actorScope.self,\n target,\n event,\n id: undefined,\n delay: undefined,\n params: undefined,\n args\n };\n}\n\n/** @internal Creates the terminal lifecycle effect for an actor. */\nexport function createTerminationEffect(\n actorScope: AnyActorScope,\n snapshot: Snapshot<unknown>\n): TerminateExecutableEffect {\n if (snapshot.status !== 'done' && snapshot.status !== 'error') {\n throw new Error(\n isDevelopment\n ? 'Cannot terminate an active or stopped actor'\n : xstateError(69, actorScope.self.id, snapshot.status)\n );\n }\n const termination: ActorTermination =\n snapshot.status === 'done'\n ? { status: 'done', output: snapshot.output, error: undefined }\n : { status: 'error', output: undefined, error: snapshot.error };\n const args: Parameters<(typeof builtInActions)['@xstate.terminate']> = [\n actorScope.self,\n termination\n ];\n return {\n kind: 'builtin',\n exec: execTerminateEffect,\n type: XSTATE_TERMINATE,\n source: actorScope.self,\n actor: actorScope.self,\n id: actorScope.self.id,\n ...termination,\n params: undefined,\n args\n };\n}\n\n/**\n * Ensures that a newly terminal snapshot has exactly one ordered actor\n * termination effect.\n *\n * @internal\n */\nexport function finalizeTransitionResult<\n TSnapshot extends Snapshot<unknown>,\n TEffect\n>(\n actorScope: AnyActorScope,\n previousSnapshot: TSnapshot | undefined,\n [nextSnapshot, effects]: [TSnapshot, TEffect[]]\n): [TSnapshot, Array<TEffect | TerminateExecutableEffect>] {\n const becameTerminal =\n nextSnapshot.status === 'done' || nextSnapshot.status === 'error';\n const wasTerminal =\n previousSnapshot?.status === 'done' || previousSnapshot?.status === 'error';\n const hasTerminationEffect = effects.some(\n (effect) =>\n typeof effect === 'object' &&\n effect !== null &&\n 'type' in effect &&\n effect.type === XSTATE_TERMINATE\n );\n\n return becameTerminal && !wasTerminal && !hasTerminationEffect\n ? [\n nextSnapshot,\n [...effects, createTerminationEffect(actorScope, nextSnapshot)]\n ]\n : [nextSnapshot, effects];\n}\n\n/**\n * Attached (listener/subscription) starts are ordered before child starts so\n * that a listener/subscription captures events emitted synchronously as its\n * target actor starts.\n */\nexport function deriveDeferredStarts(\n effects: ReadonlyArray<ExecutableEffect>\n): StartExecutableEffect[] {\n const attachedStarts: StartExecutableEffect[] = [];\n const childStarts: StartExecutableEffect[] = [];\n\n for (const effect of effects) {\n if (!isBuiltInExecutableEffect(effect) || effect.type !== XSTATE_SPAWN) {\n continue;\n }\n const { actor, logic } = effect;\n const start = createStartEffect(actor);\n if (logic === listenerLogic || logic === subscriptionLogic) {\n attachedStarts.push(start);\n } else {\n childStarts.push(start);\n }\n }\n\n return [...attachedStarts, ...childStarts];\n}\n\n/** @public */\nexport function isBuiltInExecutableEffect(\n action: ExecutableEffect\n): action is SpecialExecutableEffect {\n return action.kind === 'builtin';\n}\n\n/**\n * Executes transition effects sequentially, awaiting each runtime operation.\n *\n * @public\n */\nexport async function executeEffects(\n effects: readonly ExecutableEffect[],\n runtime?: Partial<ActorSystemRuntime>\n): Promise<void> {\n for (const effect of effects) {\n await effect.exec(runtime);\n }\n}\n\nexport function resolveActionsWithContext(\n currentSnapshot: AnyMachineSnapshot,\n _event: AnyEventObject,\n actorScope: AnyActorScope,\n actions: AnyAction[]\n): [AnyMachineSnapshot, ExecutableEffect[]] {\n let intermediateSnapshot = currentSnapshot;\n const executableActions: ExecutableEffect[] = [];\n\n for (const action of actions) {\n const isInline = typeof action === 'function';\n const actionRecord = getTransitionActionRecord(action);\n let resolvedActionArgs = actionRecord?.args;\n\n if (\n actionRecord?.action === builtInActions['@xstate.sendTo'] &&\n (actionRecord.args[1] === undefined ||\n typeof actionRecord.args[1] === 'string')\n ) {\n const childId: string | undefined = actionRecord.args[1];\n const target =\n childId !== undefined &&\n Object.hasOwn(intermediateSnapshot.children, childId)\n ? intermediateSnapshot.children[childId]\n : undefined;\n if (!target) {\n // Boundary fault: the event is dead-lettered and the sender keeps\n // running; a missing target is never an actor error.\n executableActions.push(\n createMissingTargetEffect(actorScope, actionRecord.args[2], childId)\n );\n continue;\n }\n resolvedActionArgs = [\n actionRecord.args[0],\n target,\n ...actionRecord.args.slice(2)\n ];\n }\n // A ref that went through JSON stays address-backed through effects and\n // timers: delivery resolves it to whichever actor is live at the address\n // then, routes it through a host runtime, or reports a dead letter.\n\n const resolvedAction = isInline\n ? action\n : actionRecord\n ? actionRecord.action.bind(null, ...resolvedActionArgs!)\n : false;\n\n let actionParams = undefined;\n\n if (typeof action === 'object' && action !== null) {\n const {\n type: _,\n childUpdate: _childUpdate,\n ...emittedEventParams\n } = action as any;\n actionParams = emittedEventParams;\n }\n\n if (actionRecord?.childUpdate) {\n intermediateSnapshot = applyChildUpdate(\n intermediateSnapshot,\n actionRecord.childUpdate,\n actorScope\n );\n }\n\n if (!resolvedAction || !('resolve' in resolvedAction)) {\n const builtInFields =\n typeof action === 'object' &&\n action !== null &&\n 'action' in action &&\n typeof action.action === 'function'\n ? getBuiltInActionFields(action.action, resolvedActionArgs!)\n : undefined;\n const isEmittedEvent =\n typeof action === 'object' && action !== null && !actionRecord;\n\n const executableAction = {\n kind: builtInFields\n ? ('builtin' as const)\n : isEmittedEvent\n ? ('emit' as const)\n : ('action' as const),\n type:\n typeof action === 'object'\n ? 'action' in action && typeof action.action === 'function'\n ? (action.action.name ?? '(anonymous)')\n : (action as AnyEventObject).type\n : action.name || '(anonymous)',\n params: builtInFields ? undefined : actionParams,\n args:\n typeof action === 'object' && 'action' in action\n ? resolvedActionArgs!\n : [],\n ...(builtInFields\n ? {}\n : isEmittedEvent\n ? { source: actorScope.self, event: action }\n : {\n action: actionRecord?.action ?? (isInline ? action : undefined)\n }),\n ...(!builtInFields\n ? { exec: isEmittedEvent ? execEmitEffect : execCustomEffect }\n : {}),\n ...builtInFields\n };\n\n const typedExecutableEffect = executableAction as ExecutableEffect;\n intermediateSnapshot = updateLogicalTimers(\n intermediateSnapshot,\n typedExecutableEffect,\n actorScope\n );\n executableActions.push(typedExecutableEffect);\n continue;\n }\n }\n\n return [intermediateSnapshot, executableActions];\n}\n\nexport function createEnqueueObject(\n props: Partial<EnqueueObject<any, any>>,\n action: <T extends (...args: any[]) => any>(\n fn: T,\n ...args: Parameters<T>\n ) => void\n): EnqueueObject<any, any> {\n const enqueueFn = (\n fn: (...args: any[]) => any,\n ...args: Parameters<typeof fn>\n ) => {\n action(fn, ...args);\n };\n\n Object.assign(enqueueFn, {\n cancel: noop,\n emit: noop,\n log: noop,\n raise: noop,\n spawn: emptyActor,\n sendTo: noop,\n stop: noop,\n listen: emptyActor,\n subscribeTo: emptyActor,\n ...props\n });\n\n return enqueueFn as any;\n}\n\nconst noop = () => {};\nconst emptyActor = () => ({}) as any;\n","import isDevelopment from '#is-development';\nimport { xstateError } from './xstateError.ts';\nimport { getTimerKey } from './timerKey.ts';\nimport {\n type ActorTermination,\n AnyActor,\n AnyActorScope,\n EventObject,\n TimerKey\n} from './types';\n\nexport function assertSendToEvent(event: EventObject): void {\n if (typeof event === 'string') {\n throw new Error(\n isDevelopment\n ? // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `Only event objects may be used with sendTo; use sendTo({ type: \"${event}\" }) instead`\n : xstateError(70, event)\n );\n }\n}\n\nexport const builtInActions = {\n // Actor refs are created while resolving the next snapshot. Starting is a\n // separate deferred effect so the returned list remains execution-complete.\n ['@xstate.spawn']: (actor: AnyActor) => {\n return actor.system.spawnActor(actor._parent, actor);\n },\n ['@xstate.start']: (actor: AnyActor) => {\n return actor.system.startActor(actor);\n },\n ['@xstate.raise']: (\n actorScope: AnyActorScope,\n event: EventObject,\n options: { id?: string; seq?: number; delay?: number }\n ) => {\n return actorScope.system.scheduleTimer(\n actorScope.self,\n getTimerKey({ id: options.id, seq: options.seq, event }),\n options?.delay ?? 0\n );\n },\n ['@xstate.sendTo']: (\n actorScope: AnyActorScope,\n actor: AnyActor,\n event: EventObject,\n options: { id?: string; seq?: number; delay?: number }\n ) => {\n assertSendToEvent(event);\n if (options?.delay !== undefined) {\n return actorScope.system.scheduleTimer(\n actorScope.self,\n getTimerKey({ id: options.id, seq: options.seq, event }),\n options?.delay ?? 0\n );\n } else {\n return actorScope.system._relay(actorScope.self, actor, event);\n }\n },\n ['@xstate.cancel']: (actorScope: AnyActorScope, key: TimerKey) => {\n return actorScope.system.cancelTimer(actorScope.self, key);\n },\n ['@xstate.stop']: (actorScope: AnyActorScope, actor: AnyActor) => {\n return actorScope.system.stopActor(actor);\n },\n ['@xstate.terminate']: (actor: AnyActor, termination: ActorTermination) => {\n return actor.system.terminateActor(actor, termination);\n }\n};\n","import isDevelopment from '#is-development';\nimport { hasAmbientInspector } from './inspectionAmbient.ts';\nimport { xstateError } from './xstateError.ts';\nimport type { ActorSystemRuntime } from './system.ts';\nimport type { InspectionEvent } from './inspection.ts';\nimport type { AnyActor, Snapshot } from './types.ts';\n\n/** Snapshot-scoped actor identity and system view. @internal */\nexport interface SnapshotActorRef {\n actor: AnyActor;\n systemState: SnapshotSystemState;\n}\n\ninterface SnapshotSystemState {\n root?: AnyActor;\n children?: Map<string, AnyActor>;\n keyedActors: Map<PropertyKey, AnyActor | undefined>;\n snapshot: AnyActor['system']['_snapshot'];\n sourceSystem: AnyActor['system'];\n sourceVersion: number;\n}\n\n// Each view's execution system and whether it forwards inspection. Views\n// never chain: they all inherit from the execution system directly.\nconst snapshotSystemViews = new WeakMap<\n AnyActor['system'],\n {\n executionSystem: AnyActor['system'];\n rootSystem: AnyActor['system'];\n forwardInspection: boolean;\n }\n>();\n// Facilities owned by the execution rather than by one snapshot's view. A view\n// reads and writes them on the execution system, so timers, listeners and the\n// runtime installed through any snapshot are visible through every other.\nconst executionFacilities = [\n 'runtime',\n '_timerMap',\n '_rejectionListeners',\n '_inspectionObservers',\n '_emissionListeners'\n] as const;\n// The durable execution that owns each execution system.\n/** A durable execution, as the owner of the views its transitions create. @internal */\nexport interface ExecutionOwner {\n runtime: Partial<ActorSystemRuntime> | undefined;\n inspect: ((inspectionEvent: InspectionEvent) => void) | undefined;\n}\nconst executionOwners = new WeakMap<AnyActor['system'], ExecutionOwner>();\nlet ambientExecutionOwner: ExecutionOwner | undefined;\nconst snapshotActorRefs = new WeakMap<object, SnapshotActorRef>();\nconst lazySnapshotActorRefs = new WeakMap<object, () => SnapshotActorRef>();\nconst emptyKeyedActors = new Map<PropertyKey, AnyActor | undefined>();\n\nfunction copyRegisteredActors(\n system: AnyActor['system'],\n state?: SnapshotSystemState\n): Map<string, AnyActor> {\n if (state) {\n const children = new Map<string, AnyActor>(state.children);\n if (state.root?.sessionId) {\n children.set(state.root.sessionId, state.root);\n }\n return children;\n }\n return new Map(system.children);\n}\n\nfunction captureRegisteredActors(system: AnyActor['system']): {\n root?: AnyActor;\n children?: Map<string, AnyActor>;\n} {\n const root = system._getRootActor?.();\n const peekedChildren = system._peekChildren?.();\n if (!root && !peekedChildren) {\n if (system._getRootActor && system._peekChildren) {\n return {};\n }\n const children = new Map<string, AnyActor>(system.children);\n return children.size ? { children } : {};\n }\n if (!peekedChildren?.size) {\n return root ? { root } : {};\n }\n return { children: new Map<string, AnyActor>(system.children) };\n}\n\nfunction getKeyedActors(\n system: AnyActor['system']\n): Map<PropertyKey, AnyActor | undefined> {\n const peek = system._peekKeyedActors;\n if (peek) {\n return peek.call(system) ?? emptyKeyedActors;\n }\n return system.keyedActors;\n}\n\n/** Marks topology or persisted runtime state as changed. @internal */\nexport function markSystemSnapshotDirty(system: AnyActor['system']): void {\n system._snapshotVersion++;\n}\n\nfunction getSystemSnapshotVersion(system: AnyActor['system']): number {\n return system._snapshotVersion;\n}\n\nfunction getSnapshotChildren(\n snapshot: Snapshot<unknown>\n): Record<string, AnyActor | undefined> {\n return 'children' in snapshot && snapshot.children\n ? (snapshot.children as Record<string, AnyActor | undefined>)\n : {};\n}\n\n/**\n * Creates the isolated receptionist/id view used by a pure branch. Scheduling,\n * relaying and clocks remain delegated to the snapshot's execution system.\n *\n * @internal\n */\nexport function createSnapshotSystem(\n baseSystem: AnyActor['system'],\n children: Record<string, AnyActor | undefined>,\n baseState?: SnapshotSystemState,\n owner?: ExecutionOwner\n): AnyActor['system'] {\n const baseView = snapshotSystemViews.get(baseSystem);\n const baseExecutionSystem = baseView?.executionSystem ?? baseSystem;\n // The runtime system under every view. A view runs its methods against the\n // execution system's facilities.\n const rootSystem = baseView?.rootSystem ?? baseSystem;\n const forks =\n owner !== undefined && executionOwners.get(baseExecutionSystem) !== owner;\n // A view an execution owns reports to that execution's inspector.\n const forwardInspection = owner\n ? !!owner.inspect\n : hasAmbientInspector() && (baseView?.forwardInspection ?? true);\n const registeredActors = copyRegisteredActors(baseSystem, baseState);\n const keyedActors = new Map<PropertyKey, AnyActor | undefined>(\n baseState?.keyedActors ?? getKeyedActors(baseSystem)\n );\n const reverseKeyedActors = new WeakMap<AnyActor, PropertyKey>();\n // The view's execution system; adoption can make the view its own.\n const execution = () => snapshotSystemViews.get(system)!.executionSystem;\n const forwards = () => snapshotSystemViews.get(system)!.forwardInspection;\n const system: AnyActor['system'] = Object.assign(\n Object.create(baseExecutionSystem),\n {\n children: registeredActors,\n keyedActors,\n reverseKeyedActors,\n _snapshot: { ...(baseState?.snapshot ?? baseSystem._snapshot) },\n _snapshotVersion: baseState?.sourceVersion ?? baseSystem._snapshotVersion,\n _register: (sessionId: string, actor: AnyActor) => {\n registeredActors.set(sessionId, actor);\n markSystemSnapshotDirty(system);\n return sessionId;\n },\n _unregister: (actor: AnyActor) => {\n if (actor.sessionId) {\n registeredActors.delete(actor.sessionId);\n }\n const registryKey = reverseKeyedActors.get(actor);\n if (\n registryKey !== undefined &&\n keyedActors.get(registryKey) === actor\n ) {\n keyedActors.delete(registryKey);\n }\n reverseKeyedActors.delete(actor);\n markSystemSnapshotDirty(system);\n },\n _set: (registryKey: PropertyKey, actor: AnyActor) => {\n const existing = keyedActors.get(registryKey);\n if (existing && existing !== actor) {\n throw new Error(\n isDevelopment\n ? `Actor with registry key '${String(registryKey)}' already exists.`\n : xstateError(45, String(registryKey))\n );\n }\n keyedActors.set(registryKey, actor);\n reverseKeyedActors.set(actor, registryKey);\n markSystemSnapshotDirty(system);\n },\n get: (registryKey: PropertyKey) => keyedActors.get(registryKey),\n getAll: () => Object.fromEntries(keyedActors),\n onEmitted: (listener: Parameters<AnyActor['system']['onEmitted']>[0]) =>\n rootSystem.onEmitted.call(execution(), listener),\n _notifyEmitted: (\n actorRef: AnyActor,\n event: Parameters<AnyActor['system']['_notifyEmitted']>[1]\n ) => rootSystem._notifyEmitted.call(execution(), actorRef, event),\n // Pure transition resolution must not leak topology inspection events\n // into a live runtime system — planning branches stay silent. The one\n // exception is a durable execution's own transitions (marked by the\n // ambient inspector at creation time): there the pure path IS the\n // execution, so inspection forwards to the execution system's observers.\n _hasInspectionObservers: () =>\n forwards() &&\n (rootSystem._hasInspectionObservers?.call(execution()) ?? false),\n _sendInspectionEvent: (\n event: Parameters<AnyActor['system']['_sendInspectionEvent']>[0]\n ) => {\n if (forwards()) {\n rootSystem._sendInspectionEvent.call(execution(), event);\n }\n }\n }\n );\n\n const executionSystem = forks ? system : baseExecutionSystem;\n if (forks) {\n forkFacilities(system, baseExecutionSystem, owner!);\n } else {\n for (const key of executionFacilities) {\n Object.defineProperty(system, key, {\n configurable: true,\n get: () => (execution() as any)[key],\n set: (value) => {\n (execution() as any)[key] = value;\n }\n });\n }\n }\n snapshotSystemViews.set(system, {\n executionSystem,\n rootSystem,\n forwardInspection\n });\n\n for (const [registryKey, actor] of keyedActors) {\n if (!actor) {\n continue;\n }\n reverseKeyedActors.set(actor, registryKey);\n }\n for (const actor of Object.values(children)) {\n if (!actor) {\n continue;\n }\n if (actor.sessionId) {\n registeredActors.set(actor.sessionId, actor);\n }\n const registryKey = actor.registryKey;\n if (registryKey) {\n keyedActors.set(registryKey, actor);\n reverseKeyedActors.set(actor, registryKey);\n }\n }\n\n return system;\n}\n\n/**\n * Makes `system` the execution system of `owner`, a new incarnation: it gets\n * the owner's runtime and the pending timers it saw, and starts with no\n * listeners or inspectors, so nothing registered on another execution\n * observes it.\n */\nfunction forkFacilities(\n system: AnyActor['system'],\n from: AnyActor['system'],\n owner: ExecutionOwner\n): void {\n const timers = (from as any)._timerMap;\n for (const key of executionFacilities) {\n Object.defineProperty(system, key, {\n configurable: true,\n writable: true,\n value:\n key === 'runtime'\n ? owner.runtime\n : key === '_timerMap' && timers\n ? { ...timers }\n : undefined\n });\n }\n executionOwners.set(system, owner);\n if (owner.inspect) {\n system.inspect(owner.inspect);\n }\n}\n\n/**\n * Makes `owner` own `system` before it installs its runtime there, and\n * returns whether it does. An unowned view forks in place, so the install\n * never reaches the system it was derived from. A system another execution\n * owns is left alone.\n *\n * @internal\n */\nexport function adoptSystem(\n system: AnyActor['system'],\n owner: ExecutionOwner\n): boolean {\n const view = snapshotSystemViews.get(system);\n const current = executionOwners.get(view?.executionSystem ?? system);\n if (current === owner) {\n if (view) {\n view.forwardInspection = !!owner.inspect;\n }\n return true;\n }\n // A system another execution owns stays with it.\n if (current) {\n return false;\n }\n if (!view) {\n executionOwners.set(system, owner);\n return true;\n }\n forkFacilities(system, view.executionSystem, owner);\n view.executionSystem = system;\n view.forwardInspection = !!owner.inspect;\n return true;\n}\n\n/**\n * Runs `fn` as a transition of `owner`. A view it derives from a system the\n * owner does not own forks into the owner's own execution system.\n *\n * @internal\n */\nexport function withExecutionOwner<T>(owner: ExecutionOwner, fn: () => T): T {\n const previous = ambientExecutionOwner;\n ambientExecutionOwner = owner;\n try {\n return fn();\n } finally {\n ambientExecutionOwner = previous;\n }\n}\n\n/** Hands the ambient owner to the first scope that asks for it. @internal */\nexport function takeExecutionOwner(): ExecutionOwner | undefined {\n const owner = ambientExecutionOwner;\n ambientExecutionOwner = undefined;\n return owner;\n}\n\n/** Returns the actor identity associated with a transition snapshot. @internal */\nexport function getSnapshotActorRef(\n snapshot: Snapshot<unknown>\n): SnapshotActorRef | undefined {\n const existing = snapshotActorRefs.get(snapshot);\n if (existing) {\n return existing;\n }\n const create = lazySnapshotActorRefs.get(snapshot);\n if (!create) {\n return undefined;\n }\n const created = create();\n snapshotActorRefs.set(snapshot, created);\n lazySnapshotActorRefs.delete(snapshot);\n return created;\n}\n\n/** Reads an already materialized snapshot association without creating one. @internal */\nexport function peekSnapshotActorRef(\n snapshot: Snapshot<unknown>\n): SnapshotActorRef | undefined {\n return snapshotActorRefs.get(snapshot);\n}\n\n/** Returns the existing identity provider without resolving it. @internal */\nexport function getSnapshotActorRefProvider(\n snapshot: Snapshot<unknown>\n): (() => SnapshotActorRef) | undefined {\n const existing = snapshotActorRefs.get(snapshot);\n return existing ? () => existing : lazySnapshotActorRefs.get(snapshot);\n}\n\n/** Defers actor/system identity allocation until a snapshot capability is used. @internal */\nexport function setLazySnapshotActorRef(\n snapshot: Snapshot<unknown>,\n create: () => SnapshotActorRef\n): void {\n snapshotActorRefs.delete(snapshot);\n lazySnapshotActorRefs.set(snapshot, create);\n}\n\n/**\n * Copies an internal actor association without rebuilding its system view.\n *\n * @internal\n */\nexport function copySnapshotActorRef(\n source: Snapshot<unknown>,\n target: Snapshot<unknown>\n): boolean {\n const ref = snapshotActorRefs.get(source);\n if (ref) {\n snapshotActorRefs.set(target, ref);\n return true;\n }\n const create = lazySnapshotActorRefs.get(source);\n if (create) {\n lazySnapshotActorRefs.set(target, create);\n return true;\n }\n return false;\n}\n\n/** Refreshes the only topology change made by an otherwise idle root start. */\nexport function refreshSnapshotActorRefRoot(\n snapshot: Snapshot<unknown>,\n actor: AnyActor,\n system: AnyActor['system']\n): boolean {\n const ref = snapshotActorRefs.get(snapshot);\n const sourceVersion = getSystemSnapshotVersion(system);\n if (\n ref?.actor !== actor ||\n ref.systemState.sourceSystem !== system ||\n ref.systemState.sourceVersion + 1 !== sourceVersion ||\n system._getRootActor?.() !== actor ||\n system._peekChildren?.()\n ) {\n return false;\n }\n ref.systemState.root = actor;\n ref.systemState.sourceVersion = sourceVersion;\n return true;\n}\n\n/**\n * Associates a transition snapshot with an actor and an immutable system view.\n * The internal association is excluded from enumeration and persistence.\n *\n * @internal\n */\nexport function setSnapshotActorRef(\n snapshot: Snapshot<unknown>,\n actor: AnyActor,\n baseSystem: AnyActor['system'] = actor.system,\n previousSnapshot?: Snapshot<unknown>\n): void {\n lazySnapshotActorRefs.delete(snapshot);\n const sourceVersion = getSystemSnapshotVersion(baseSystem);\n const previousRef = previousSnapshot\n ? getSnapshotActorRef(previousSnapshot)\n : undefined;\n const reusableRef =\n previousRef?.actor === actor ? previousRef : getSnapshotActorRef(snapshot);\n\n if (\n reusableRef?.actor === actor &&\n reusableRef.systemState.sourceSystem === baseSystem &&\n reusableRef.systemState.sourceVersion === sourceVersion\n ) {\n snapshotActorRefs.set(snapshot, reusableRef);\n return;\n }\n\n const capturedActors = captureRegisteredActors(baseSystem);\n let children = capturedActors.children;\n const baseKeyedActors = getKeyedActors(baseSystem);\n let keyedActors = baseKeyedActors.size\n ? new Map(baseKeyedActors)\n : emptyKeyedActors;\n for (const child of Object.values(getSnapshotChildren(snapshot))) {\n if (!child) {\n continue;\n }\n if (child.sessionId) {\n (children ??= new Map()).set(child.sessionId, child);\n }\n const registryKey = child.registryKey;\n if (registryKey) {\n if (keyedActors === emptyKeyedActors) {\n keyedActors = new Map();\n }\n keyedActors.set(registryKey, child);\n }\n }\n snapshotActorRefs.set(snapshot, {\n actor,\n systemState: {\n ...capturedActors,\n children,\n keyedActors,\n snapshot: { ...baseSystem._snapshot },\n sourceSystem: baseSystem,\n sourceVersion\n }\n } satisfies SnapshotActorRef);\n}\n","import { getTimerStart } from './timerClock.ts';\nimport { getScheduledTimerKey, getTimerKey } from './timerKey.ts';\nimport isDevelopment from '#is-development';\nimport { xstateError } from './xstateError.ts';\nimport { getStateValue, isStateId } from './stateUtils.ts';\nimport type {\n AnyMachineSnapshot,\n AnyStateMachine,\n AnyActor,\n EventObject,\n HistoryValue,\n MachineContext,\n StateConfig,\n StateValue,\n StateValueMap,\n AnyActorRef,\n Snapshot,\n MetaObject,\n StateSchema,\n StateId,\n StateIdInputs,\n StateContextFromStateValue,\n StateIdReference,\n SnapshotStatus,\n PersistedHistoryValue,\n AnyStateNode,\n LogicalTimer,\n SerializedActorRef\n} from './types.ts';\nimport { describeMachine, isActorRefLike, matchesState } from './utils.ts';\nimport {\n copySnapshotActorRef,\n getSnapshotActorRef,\n setSnapshotActorRef\n} from './snapshotActorRef.ts';\nimport { isRemoteActorRef, isSerializedActorRef } from './remoteActorRef.ts';\nimport { findNonJsonPath } from './persistedSnapshotFormat.ts';\n\nconst emptySnapshotRecord = Object.freeze({});\nconst emptyTimers: readonly LogicalTimer[] = Object.freeze([]);\n\nfunction compactTimers(\n timers: readonly LogicalTimer[] | undefined\n): readonly LogicalTimer[] {\n return timers?.length ? timers : emptyTimers;\n}\n\n/**\n * Deep-freezes the plain objects and arrays in machine context so accidental\n * in-place mutation throws instead of silently corrupting state. Actor refs,\n * class instances, Map/Set, Date, etc. are left untouched. Callers guard with\n * `isDevelopment` so production builds pay nothing.\n *\n * @internal\n */\nconst deepFrozenContext = new WeakSet<object>();\n\nexport function freezeContext(value: any, visiting = new Set<object>()): void {\n if (\n !value ||\n typeof value !== 'object' ||\n deepFrozenContext.has(value) ||\n visiting.has(value)\n ) {\n return;\n }\n if (!Array.isArray(value)) {\n const proto = Object.getPrototypeOf(value);\n if (\n (proto !== Object.prototype && proto !== null) ||\n isActorRefLike(value)\n ) {\n return;\n }\n }\n visiting.add(value);\n try {\n Object.freeze(value);\n } catch {\n // Some proxies (e.g. framework reactive state) refuse to be frozen.\n return;\n }\n // Descend even if the object was already frozen elsewhere: its children\n // may still be mutable.\n for (const key of Object.keys(value)) {\n freezeContext(value[key], visiting);\n }\n deepFrozenContext.add(value);\n}\n\nfunction compactSnapshotRecord<T extends object>(value: T | undefined): T {\n if (value === emptySnapshotRecord) {\n return value;\n }\n return value && Object.keys(value).length\n ? value\n : (emptySnapshotRecord as T);\n}\n\n/** @public */\nexport function isMachineSnapshot(value: unknown): value is AnyMachineSnapshot {\n return (\n !!value &&\n typeof value === 'object' &&\n 'machine' in value &&\n 'value' in value\n );\n}\n\ntype Values<T> = T[keyof T];\n\ntype MatchingObjectStateValue<\n TStateValue extends Record<string, unknown>,\n TTestStateValue extends Record<string, unknown>\n> =\n false extends Values<{\n [K in keyof TTestStateValue]: K extends keyof TStateValue\n ? NonNullable<TStateValue[K]> extends StateValue\n ? NonNullable<TTestStateValue[K]> extends StateValue\n ? [\n MatchingStateValue<\n NonNullable<TStateValue[K]>,\n NonNullable<TTestStateValue[K]>\n >\n ] extends [never]\n ? false\n : true\n : false\n : false\n : false;\n }>\n ? never\n : {\n [K in keyof TStateValue]: K extends keyof TTestStateValue\n ? MatchingStateValue<\n NonNullable<TStateValue[K]>,\n NonNullable<TTestStateValue[K]>\n >\n : TStateValue[K];\n };\n\ntype MatchingStateValue<\n TStateValue extends StateValue,\n TTestStateValue extends StateValue\n> = StateValue extends TTestStateValue\n ? TStateValue\n : string extends TTestStateValue\n ? TStateValue\n : TStateValue extends unknown\n ? TTestStateValue extends string\n ? TStateValue extends string\n ? TTestStateValue extends TStateValue\n ? TTestStateValue\n : Extract<TStateValue, TTestStateValue>\n : TStateValue extends Record<string, unknown>\n ? TStateValue & Record<TTestStateValue, StateValue | undefined>\n : never\n : TTestStateValue extends Record<string, unknown>\n ? TStateValue extends Record<string, unknown>\n ? MatchingObjectStateValue<TStateValue, TTestStateValue>\n : never\n : never\n : never;\n\ntype StateValuePath<TStateValue extends StateValue> =\n TStateValue extends StateValueMap\n ? {\n [K in keyof TStateValue & string]:\n | K\n | (NonNullable<TStateValue[K]> extends infer TChild extends StateValue\n ? `${K}.${StateValuePath<TChild>}`\n : never);\n }[keyof TStateValue & string]\n : TStateValue;\n\n/**\n * The values that `snapshot.matches(...)` accepts for a state value: a state\n * key, a dot-delimited path to a descendant state, or a partial state value.\n * Non-literal state values accept any value.\n */\nexport type ToTestStateValue<TStateValue extends StateValue> =\n StateValue extends TStateValue\n ? StateValue\n : TStateValue extends string\n ? TStateValue\n : TStateValue extends StateValueMap\n ? string extends keyof TStateValue\n ? StateValue\n :\n | StateValuePath<TStateValue>\n | {\n [K in keyof TStateValue]?: NonNullable<\n TStateValue[K]\n > extends infer TChild extends StateValue\n ? ToTestStateValue<TChild>\n : never;\n }\n : never;\n\n/**\n * `true` if `TTestStateValue` can match `TStateValue`, checked per position:\n * each literal key names a state at its level and each literal child matches\n * that state. A non-literal value (`string`, or a map with `string` keys)\n * passes at its own position only, so `{ checkout: string }` is accepted and\n * `{ nope: 'payment', checkout: string }` is not.\n */\ntype IsTestStateValueValid<\n TStateValue extends StateValue,\n TTestStateValue\n> = StateValue extends TStateValue\n ? true\n : string extends TTestStateValue\n ? true\n : TTestStateValue extends string\n ? [TTestStateValue] extends [StateValuePath<TStateValue>]\n ? true\n : false\n : TTestStateValue extends StateValueMap\n ? string extends keyof TTestStateValue\n ? true\n : true extends (\n TStateValue extends StateValueMap\n ? IsTestStateValueMapValid<TStateValue, TTestStateValue>\n : never\n )\n ? true\n : false\n : false;\n\ntype IsTestStateValueMapValid<\n TStateValueMap extends StateValueMap,\n TTestStateValue extends StateValueMap\n> = [Exclude<keyof TTestStateValue, keyof TStateValueMap>] extends [never]\n ? false extends {\n [K in keyof TTestStateValue]-?: IsTestStateValueValid<\n NonNullable<TStateValueMap[K & keyof TStateValueMap]>,\n NonNullable<TTestStateValue[K]>\n >;\n }[keyof TTestStateValue]\n ? false\n : true\n : false;\n\n/**\n * `unknown` if `matches(...)` accepts `TTestStateValue` for `TStateValue`,\n * otherwise `never`. Literal values must name states; a non-literal value\n * (such as a `string` leaf) is accepted at its own position.\n */\nexport type TestStateValueCheck<\n TStateValue extends StateValue,\n TTestStateValue extends StateValue\n> = [TTestStateValue] extends [ToTestStateValue<TStateValue>]\n ? unknown\n : false extends IsTestStateValueValid<TStateValue, TTestStateValue>\n ? never\n : unknown;\n\n/**\n * The `#id` references a snapshot (or union of snapshots) accepts, read from\n * its `getMeta()` keys so the overload does not depend on the state schema.\n */\ntype SnapshotStateIdReference<TSnapshot> = TSnapshot extends {\n getMeta: () => Record<infer TStateId, any>;\n}\n ? string extends TStateId\n ? `#${string}`\n : `#${Exclude<TStateId, ''> & string}`\n : `#${string}`;\n\ninterface MachineSnapshotBase<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TStateValue extends StateValue,\n TTag extends string,\n _TOutput,\n TMeta extends MetaObject,\n TStateSchema extends StateSchema = StateSchema\n> {\n /** The state machine that produced this state snapshot. */\n machine: AnyStateMachine;\n /** The tags of the active state nodes that represent the current state value. */\n tags: Set<string>;\n /**\n * The current state value.\n *\n * This represents the active state nodes in the state machine.\n *\n * - For atomic state nodes, it is a string.\n * - For compound parent state nodes, it is an object where:\n *\n * - The key is the parent state node's key\n * - The value is the current state value of the active child state node(s)\n *\n * @example\n *\n * ```ts\n * // single-level state node\n * snapshot.value; // => 'yellow'\n *\n * // nested state nodes\n * snapshot.value; // => { red: 'wait' }\n * ```\n */\n value: TStateValue;\n /** The current status of this snapshot. */\n status: SnapshotStatus;\n error: unknown;\n context: TContext;\n\n historyValue: Readonly<HistoryValue>;\n /** The enabled state nodes representative of the state value. */\n nodes: Array<AnyStateNode>;\n /** An object mapping actor names to spawned/invoked actors. */\n children: TChildren;\n /** Pending logical timers owned by this machine snapshot. */\n timers: readonly LogicalTimer[];\n /** @internal */\n _stateInputs: Record<string, Record<string, unknown>>;\n /** @internal */\n _nextTimerId: number;\n /** @internal */\n _nextActorIds?: Record<string, number>;\n /**\n * Whether the current state value is a subset of the given partial state\n * value, or, for a `'#id'` reference, whether the state node with that `id`\n * is active.\n *\n * @param partialStateValue\n */\n matches<const TTestStateId extends StateIdReference<TStateSchema>>(\n stateId: TTestStateId\n ): boolean;\n matches<\n const TTestStateValue extends Extract<ToTestStateValue<TStateValue>, string>\n >(\n partialStateValue: TTestStateValue,\n ...args: string extends TTestStateValue ? [never] : []\n ): this is MachineSnapshot<\n StateContextFromStateValue<TStateSchema, TContext, TTestStateValue>,\n TEvent,\n TChildren,\n MatchingStateValue<TStateValue, TTestStateValue>,\n TTag,\n _TOutput,\n TMeta,\n TStateSchema\n >;\n matches<\n const TTestStateValue extends Extract<\n ToTestStateValue<TStateValue>,\n StateValueMap\n >\n >(\n partialStateValue: TTestStateValue,\n ...args: string extends keyof TTestStateValue ? [never] : []\n ): this is MachineSnapshot<\n StateContextFromStateValue<TStateSchema, TContext, TTestStateValue>,\n TEvent,\n TChildren,\n MatchingStateValue<TStateValue, TTestStateValue>,\n TTag,\n _TOutput,\n TMeta,\n TStateSchema\n >;\n // Unions of snapshots (whose overloads above differ)\n matches<TSnapshot extends { value: StateValue }>(\n this: TSnapshot,\n stateId: NoInfer<SnapshotStateIdReference<TSnapshot>>\n ): boolean;\n // Non-literal values, and unions of snapshots\n matches<\n TSnapshot extends { value: StateValue },\n const TTestStateValue extends StateValue\n >(\n this: TSnapshot,\n partialStateValue: TTestStateValue &\n NoInfer<TestStateValueCheck<TSnapshot['value'], TTestStateValue>>\n ): boolean;\n\n /**\n * Whether the current state nodes has a state node with the specified `tag`.\n *\n * @param tag\n */\n hasTag: (tag: TTag) => boolean;\n\n /**\n * Determines whether sending the `event` will cause a non-forbidden\n * transition to be selected, even if the transitions have no actions nor\n * change the state value.\n *\n * Returns false for terminal snapshots. Throws if transition evaluation\n * throws; this dry run does not run onError recovery.\n *\n * @param event The event to test\n * @returns Whether the event will cause a transition\n */\n can: (event: TEvent) => boolean;\n\n getMeta: () => Record<\n StateId<TStateSchema> & string,\n TMeta | undefined // States might not have meta defined\n >;\n\n /**\n * Returns the inputs for the current active state nodes, keyed by state node\n * id.\n */\n getInputs: () => StateIdInputs<TStateSchema>;\n\n toJSON: () => unknown;\n}\n\ninterface ActiveMachineSnapshot<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TStateValue extends StateValue,\n TTag extends string,\n TOutput,\n TMeta extends MetaObject,\n TStateSchema extends StateSchema\n> extends MachineSnapshotBase<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TStateSchema\n> {\n status: 'active';\n output: undefined;\n error: undefined;\n}\n\ninterface DoneMachineSnapshot<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TStateValue extends StateValue,\n TTag extends string,\n TOutput,\n TMeta extends MetaObject,\n TStateSchema extends StateSchema\n> extends MachineSnapshotBase<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TStateSchema\n> {\n status: 'done';\n output: TOutput;\n error: undefined;\n}\n\ninterface ErrorMachineSnapshot<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TStateValue extends StateValue,\n TTag extends string,\n TOutput,\n TMeta extends MetaObject,\n TStateSchema extends StateSchema\n> extends MachineSnapshotBase<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TStateSchema\n> {\n status: 'error';\n output: undefined;\n error: unknown;\n}\n\ninterface StoppedMachineSnapshot<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TStateValue extends StateValue,\n TTag extends string,\n TOutput,\n TMeta extends MetaObject,\n TStateSchema extends StateSchema\n> extends MachineSnapshotBase<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TStateSchema\n> {\n status: 'stopped';\n output: undefined;\n error: undefined;\n}\n\n/** @public */\nexport type MachineSnapshot<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TStateValue extends StateValue,\n TTag extends string,\n TOutput,\n TMeta extends MetaObject,\n TStateSchema extends StateSchema\n> =\n | ActiveMachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TStateSchema\n >\n | DoneMachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TStateSchema\n >\n | ErrorMachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TStateSchema\n >\n | StoppedMachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TStateSchema\n >;\n\nconst machineSnapshotMatches = function matches(\n this: AnyMachineSnapshot,\n testValue: StateValue\n) {\n if (typeof testValue === 'string' && isStateId(testValue)) {\n const stateNode = this.machine.getStateNodeById(testValue);\n return this.nodes.includes(stateNode);\n }\n return matchesState(testValue, this.value);\n};\n\nconst machineSnapshotHasTag = function hasTag(\n this: AnyMachineSnapshot,\n tag: string\n) {\n return this.tags.has(tag);\n};\n\nconst machineSnapshotCan = function can(\n this: AnyMachineSnapshot,\n event: EventObject\n) {\n if (isDevelopment && !this.machine) {\n console.warn(\n `state.can(...) used outside of a machine-created State object; this will always return false.`\n );\n }\n\n // The dry-run logic lives on the machine so that non-machine bundles\n // (e.g. `createFSM`) don't pay for the transition-resolution machinery.\n return this.machine?._canTransition(this, event) ?? false;\n};\n\nconst machineSnapshotToJSON = function toJSON(this: AnyMachineSnapshot) {\n const {\n nodes,\n _stateInputs,\n _nextTimerId,\n _nextActorIds,\n tags,\n machine,\n getMeta,\n getInputs,\n toJSON,\n can,\n hasTag,\n matches,\n ...jsonValues\n } = this;\n return { ...jsonValues, tags: Array.from(tags) };\n};\n\nconst machineSnapshotGetMeta = function getMeta(this: AnyMachineSnapshot) {\n const meta: Record<string, any> = {};\n for (const stateNode of this.nodes) {\n if (stateNode.meta !== undefined) {\n meta[stateNode.id] = stateNode.meta;\n }\n }\n return meta;\n};\n\nconst machineSnapshotGetInputs = function getInputs<\n TStateSchema extends StateSchema\n>(\n this: AnyMachineSnapshot & {\n _stateInputs: StateIdInputs<TStateSchema>;\n }\n): StateIdInputs<TStateSchema> {\n return this._stateInputs;\n};\n\nfunction collectTags(stateNodes: Array<AnyStateNode>): Set<string> {\n const tags = new Set<string>();\n for (const stateNode of stateNodes) {\n for (const tag of stateNode.tags) {\n tags.add(tag);\n }\n }\n return tags;\n}\n\nexport function createMachineSnapshot<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TStateValue extends StateValue,\n TTag extends string,\n TMeta extends MetaObject,\n TStateSchema extends StateSchema\n>(\n config: StateConfig<TContext, TEvent>,\n machine: AnyStateMachine,\n actorRef?: AnyActor\n): MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n undefined,\n TMeta,\n TStateSchema\n> {\n const snapshot = {\n status: config.status as never,\n output: config.output,\n error: config.error,\n machine,\n context: config.context,\n nodes: config._nodes,\n value: (config.value ??\n getStateValue(machine.root, config._nodes)) as never,\n tags: collectTags(config._nodes),\n children: compactSnapshotRecord(config.children) as TChildren,\n timers: compactTimers(config.timers),\n historyValue: compactSnapshotRecord(config.historyValue),\n _stateInputs: compactSnapshotRecord(config._stateInputs),\n _nextTimerId: config._nextTimerId ?? 0,\n _nextActorIds: config._nextActorIds,\n matches: machineSnapshotMatches as never,\n hasTag: machineSnapshotHasTag,\n can: machineSnapshotCan,\n getMeta: machineSnapshotGetMeta,\n getInputs: machineSnapshotGetInputs,\n toJSON: machineSnapshotToJSON\n };\n if (isDevelopment) {\n freezeContext(snapshot.context);\n }\n if (actorRef) {\n setSnapshotActorRef(snapshot, actorRef);\n }\n return snapshot;\n}\n\nexport function cloneMachineSnapshot<TState extends AnyMachineSnapshot>(\n snapshot: TState,\n config: Partial<StateConfig<any, any>> = {}\n): TState {\n const configWithSnapshot = {\n ...snapshot,\n ...config\n } as StateConfig<any, any>;\n\n if ((config._nodes ?? snapshot.nodes) === snapshot.nodes) {\n const clonedSnapshot = {\n status: configWithSnapshot.status as never,\n output: configWithSnapshot.output,\n error: configWithSnapshot.error,\n machine: snapshot.machine,\n context: configWithSnapshot.context,\n nodes: snapshot.nodes,\n value: snapshot.value,\n tags: snapshot.tags,\n children: compactSnapshotRecord(configWithSnapshot.children),\n timers: compactTimers(configWithSnapshot.timers),\n historyValue: compactSnapshotRecord(configWithSnapshot.historyValue),\n _stateInputs: compactSnapshotRecord(configWithSnapshot._stateInputs),\n _nextTimerId: configWithSnapshot._nextTimerId ?? 0,\n _nextActorIds: configWithSnapshot._nextActorIds,\n matches: machineSnapshotMatches as never,\n hasTag: machineSnapshotHasTag,\n can: machineSnapshotCan,\n getMeta: machineSnapshotGetMeta,\n getInputs: machineSnapshotGetInputs,\n toJSON: machineSnapshotToJSON\n } as unknown as TState;\n if (isDevelopment) {\n freezeContext(clonedSnapshot.context);\n }\n copySnapshotActorRef(snapshot, clonedSnapshot);\n return clonedSnapshot;\n }\n\n const clonedSnapshot = createMachineSnapshot(\n {\n ...configWithSnapshot,\n value: undefined\n },\n snapshot.machine\n ) as unknown as TState;\n copySnapshotActorRef(snapshot, clonedSnapshot);\n return clonedSnapshot;\n}\n\nfunction serializeHistoryValue(\n historyValue: HistoryValue\n): PersistedHistoryValue {\n const result: PersistedHistoryValue = {};\n\n for (const key in historyValue) {\n const value = historyValue[key];\n if (Array.isArray(value)) {\n result[key] = value.map((item) => ({ id: item.id }));\n }\n }\n\n return result;\n}\n\nexport function getPersistedSnapshot<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TStateValue extends StateValue,\n TTag extends string,\n TOutput,\n TMeta extends MetaObject\n>(\n snapshot: MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n any // state schema\n >,\n options?: unknown\n): Snapshot<unknown> {\n const {\n nodes,\n _stateInputs,\n _nextTimerId,\n _nextActorIds,\n tags,\n machine,\n children,\n timers,\n context,\n can,\n hasTag,\n matches,\n getMeta,\n getInputs,\n toJSON,\n ...jsonValues\n } = snapshot;\n\n if (isDevelopment) {\n // Before persistContext, which rejects cycles with an error.\n warnOnNonJsonPayload(\n {\n context,\n output: jsonValues.output,\n error: jsonValues.error,\n stateInputs: _stateInputs\n },\n machine.id\n );\n }\n\n const childrenJson: Record<string, unknown> = {};\n const timersJson: unknown[] = [];\n\n const embedChildren =\n (options as { embedChildren?: boolean } | undefined)?.embedChildren !==\n false;\n for (const id in children) {\n const child = children[id] as any;\n const sourceKey = typeof child.src === 'string' ? child.src : undefined;\n // An inline invoke has no source key; it restores through the invoke\n // definition with its id among the active states.\n const invoked =\n sourceKey === undefined &&\n child._invoked === true &&\n nodes.some((node) => node.invoke.some((def) => def.id === id));\n if (\n sourceKey === undefined &&\n !invoked &&\n (!options || !('__unsafeAllowInlineActors' in (options as object)))\n ) {\n throw new Error(\n isDevelopment\n ? 'An inline child actor cannot be persisted.'\n : xstateError(41, id)\n );\n }\n // Children are referenced by their logical address. Embedding the child\n // state is the co-locating runtime's whole-tree checkpoint capability;\n // remote handles never embed — their state lives with another runtime.\n const embed = embedChildren && !isRemoteActorRef(child);\n if (!embed && sourceKey === undefined) {\n // Fail where it is actionable: a by-address reference without a\n // registered source key could be persisted but never restored.\n throw new Error(\n isDevelopment\n ? `Unable to persist child '${id}' by address: it requires a registered source key.`\n : xstateError(42, id)\n );\n }\n childrenJson[id as keyof typeof childrenJson] = {\n address: child.address,\n // The explicit marker disambiguates a by-address reference from a child\n // whose own persisted snapshot happens to be undefined.\n ...(embed\n ? { snapshot: child.getPersistedSnapshot(options) }\n : {\n remote: true,\n // A remote handle's sessionId IS the host-supplied incarnation\n // token, round-tripped verbatim. A local child persisted by\n // address never stamps its own sessionId: that value is this\n // incarnation's, not a durable identity, and it would make\n // persisted snapshots nondeterministic across replays.\n incarnation: isRemoteActorRef(child) ? child.sessionId : undefined\n }),\n ...(invoked ? {} : { src: child.src }),\n registryKey: child.registryKey,\n syncSnapshot: child._syncSnapshot\n };\n }\n\n const snapshotActor = getSnapshotActorRef(snapshot)?.actor;\n // Only the wall clock is stamped into persisted timers: a custom clock's\n // readings (a simulated clock, a monotonic counter) are meaningless in any\n // other process, and restoring them under the wall clock would fire every\n // pending delay instantly. Pure-transition snapshots have no local\n // schedule; durable executions record an accepted start separately.\n const scheduledTimers = snapshotActor?.system?._clock?.now\n ? undefined\n : snapshotActor?.system?._snapshot?._scheduledTimers;\n for (const timer of timers) {\n let event = timer.event;\n if (event.type === 'xstate.timeout.actor') {\n event = { ...event };\n delete (event as EventObject & { sessionId?: string }).sessionId;\n }\n let target: string | { type: 'parent' } | SerializedActorRef;\n if (timer.target === 'self') {\n target = 'self';\n } else if (isSerializedActorRef(timer.target)) {\n // An address-backed target resolves when the timer fires.\n target = { ...timer.target };\n } else {\n const childId = Object.entries(children).find(\n ([, child]) => child === timer.target\n )?.[0];\n if (childId) {\n target = childId;\n } else if (\n timer.target === getSnapshotActorRef(snapshot)?.actor._parent\n ) {\n target = { type: 'parent' };\n } else {\n throw new Error(\n isDevelopment\n ? `Unable to persist timer ${timer.id !== undefined ? `'${timer.id}'` : `for event '${timer.event.type}'`}: target actor '${timer.target.id}' is no longer addressable from this snapshot.`\n : xstateError(43, timer.target.id)\n );\n }\n }\n // A live runtime knows when the timer is due; persist the wall-clock\n // start (dueAt - declared delay) so restore can honor the absolute\n // deadline. Derived from dueAt, not the scheduling moment, so repeated\n // persist/restore cycles keep the same deadline. Without a live schedule\n // (a restored-but-never-started actor, a pure-transition snapshot) the\n // timer's accepted durable start or carried-in start passes through,\n // so re-persisting cannot push the deadline back.\n const scheduled =\n scheduledTimers?.[\n getScheduledTimerKey(snapshotActor!, getTimerKey(timer))\n ];\n const scheduledAt = scheduled\n ? scheduled.dueAt - timer.delay\n : getTimerStart(timer);\n timersJson.push({\n ...(timer.id !== undefined && { id: timer.id }),\n ...(timer.seq !== undefined && { seq: timer.seq }),\n delay: timer.delay,\n type: timer.type,\n event,\n target,\n ...(scheduledAt !== undefined && { scheduledAt })\n });\n }\n\n const persisted: Record<string, unknown> = {\n ...jsonValues,\n context: persistContext(\n context,\n () => getSnapshotActorRef(snapshot)?.actor.id ?? machine.id\n ) as any,\n children: childrenJson,\n timers: timersJson,\n historyValue: serializeHistoryValue(jsonValues.historyValue)\n };\n\n if (_stateInputs && Object.keys(_stateInputs).length > 0) {\n persisted.stateInputs = _stateInputs;\n }\n // Stores such as Convex reject `_`-prefixed field names.\n persisted.nextTimerId = _nextTimerId;\n if (_nextActorIds && Object.keys(_nextActorIds).length > 0) {\n persisted.nextActorIds = _nextActorIds;\n }\n\n if (machine.version !== undefined) {\n persisted.machine = {\n id: machine.id,\n version: machine.version\n };\n }\n\n return persisted as Snapshot<unknown>;\n}\n\nfunction warnOnNonJsonPayload(\n persisted: Record<string, unknown>,\n machineId: string\n) {\n for (const key of ['context', 'output', 'error', 'stateInputs']) {\n const found = findNonJsonPath(persisted[key], key);\n if (found) {\n console.warn(\n `Persisted snapshot of ${describeMachine(machineId)} contains a non-JSON value (${found.kind}) at '${found.path}'. Persisted snapshots must be JSON-serializable; this value will be lost or throw in JSON.stringify.`\n );\n return;\n }\n }\n}\n\nfunction persistContext(\n contextPart: Record<string, unknown>,\n getActorId: () => string,\n path = 'context',\n ancestors: object[] = []\n) {\n // `ancestors` is the current descent path: a shared, non-circular object\n // reached twice is fine; one that contains itself is not JSON.\n ancestors.push(contextPart);\n let copy: typeof contextPart | undefined;\n for (const key in contextPart) {\n const value = contextPart[key];\n if (value && typeof value === 'object') {\n if (isActorRefLike(value)) {\n copy ??= Array.isArray(contextPart)\n ? (contextPart.slice() as typeof contextPart)\n : { ...contextPart };\n // The address lets refs to non-children still route after restore.\n copy[key] = { '@actor': (value as any as AnyActor).address };\n } else {\n const valuePath = Array.isArray(contextPart)\n ? `${path}[${key}]`\n : `${path}.${key}`;\n if (ancestors.includes(value)) {\n throw new Error(\n isDevelopment\n ? `Cannot persist actor \"${getActorId()}\": circular reference at ${valuePath}`\n : xstateError(44, getActorId(), valuePath)\n );\n }\n const result = persistContext(\n value as typeof contextPart,\n getActorId,\n valuePath,\n ancestors\n );\n if (result !== value) {\n copy ??= Array.isArray(contextPart)\n ? (contextPart.slice() as typeof contextPart)\n : { ...contextPart };\n copy[key] = result;\n }\n }\n }\n }\n ancestors.pop();\n return copy ?? contextPart;\n}\n","import isDevelopment from '#is-development';\nimport { xstateError } from './xstateError.ts';\nimport { isMachineSnapshot } from './State.ts';\nimport type { StateNode } from './StateNode.ts';\nimport { TARGETLESS_KEY, WILDCARD } from './constants.ts';\nimport type {\n AnyActor,\n AnyActorLogic,\n AnyEventObject,\n AnyInvokeDefinition,\n AnyMachineSnapshot,\n AnyStateMachine,\n AnyStateNode,\n AnyTransitionConfig,\n AnyTransitionConfigFunction,\n ErrorEvent,\n EventObject,\n MachineContext,\n Mapper,\n Observer,\n OutputArg,\n StateLike,\n StateValue\n} from './types.ts';\nimport type { NonReducibleUnknown, SingleOrArray } from './typeUtils.ts';\n\n/** @public */\nexport function matchesState(\n parentStateId: StateValue,\n childStateId: StateValue\n): boolean {\n const parentStateValue = toStateValue(parentStateId);\n const childStateValue = toStateValue(childStateId);\n\n if (typeof childStateValue === 'string') {\n if (typeof parentStateValue === 'string') {\n return childStateValue === parentStateValue;\n }\n\n // Parent more specific than child\n return false;\n }\n\n if (typeof parentStateValue === 'string') {\n return parentStateValue in childStateValue;\n }\n\n return Object.keys(parentStateValue).every((key) => {\n if (!(key in childStateValue)) {\n return false;\n }\n\n return matchesState(parentStateValue[key]!, childStateValue[key]!);\n });\n}\n\n/**\n * @internal Throws when a user source name (action, guard, actor or delay)\n * enters the `xstate.` / `@xstate.` namespaces, which are reserved for\n * built-in events, effects and source keys.\n */\nexport function assertUnreservedSourceName(kind: string, name: string): void {\n if (name.startsWith('xstate.') || name.startsWith('@xstate.')) {\n throw new Error(\n isDevelopment\n ? `Invalid ${kind} name '${name}': the 'xstate.' and '@xstate.' prefixes are reserved for built-in names.`\n : xstateError(37, kind, name)\n );\n }\n}\n\n/** Whether a state key contains a `.` that is not escaped as `\\\\.`. */\nexport function hasUnescapedDot(key: string): boolean {\n for (let i = 0; i < key.length; i++) {\n if (key[i] === '\\\\') {\n i++;\n } else if (key[i] === '.') {\n return true;\n }\n }\n return false;\n}\n\nexport function toStatePath(stateId: string | string[]): string[] {\n if (isArray(stateId)) {\n return stateId;\n }\n\n const result: string[] = [];\n let segment = '';\n\n for (let i = 0; i < stateId.length; i++) {\n const char = stateId.charCodeAt(i);\n switch (char) {\n // \\\n case 92:\n // An escaped `.` stays escaped: `foo\\\\.bar` is one path segment, the\n // literal state key `'foo\\\\.bar'`. Other escapes consume the next\n // character.\n segment += stateId[i + 1] === '.' ? '\\\\.' : stateId[i + 1];\n // and skip over it\n i++;\n continue;\n // .\n case 46:\n result.push(segment);\n segment = '';\n continue;\n }\n segment += stateId[i];\n }\n\n result.push(segment);\n\n return result;\n}\n\nfunction toStateValue(stateValue: StateLike<any> | StateValue): StateValue {\n if (isMachineSnapshot(stateValue)) {\n return stateValue.value;\n }\n\n if (typeof stateValue !== 'string') {\n return stateValue as StateValue;\n }\n\n const statePath = toStatePath(stateValue);\n\n return pathToStateValue(statePath);\n}\n\n/** @internal */\nfunction pathToStateValue(statePath: string[]): StateValue {\n if (statePath.length === 1) {\n return statePath[0];\n }\n\n const value: StateValue = {};\n let marker = value;\n\n for (let i = 0; i < statePath.length - 1; i++) {\n if (i === statePath.length - 2) {\n marker[statePath[i]] = statePath[i + 1];\n } else {\n const previous = marker;\n marker = {};\n previous[statePath[i]] = marker;\n }\n }\n\n return value;\n}\n\nexport function mapValues<P, O extends Record<string, unknown>>(\n collection: O,\n iteratee: (item: O[keyof O], key: keyof O, collection: O, i: number) => P\n): { [key in keyof O]: P };\nexport function mapValues(\n collection: Record<string, unknown>,\n iteratee: (\n item: unknown,\n key: string,\n collection: Record<string, unknown>,\n i: number\n ) => unknown\n) {\n const result: Record<string, unknown> = {};\n\n const collectionKeys = Object.keys(collection);\n for (let i = 0; i < collectionKeys.length; i++) {\n const key = collectionKeys[i];\n const value = iteratee(collection[key], key, collection, i);\n if (key === '__proto__') {\n Object.defineProperty(result, key, {\n value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n result[key] = value;\n }\n }\n\n return result;\n}\n\nfunction toArrayStrict<T>(value: readonly T[] | T): readonly T[] {\n if (isArray(value)) {\n return value;\n }\n return [value];\n}\n\nexport function toArray<T>(value: readonly T[] | T | undefined): readonly T[] {\n if (value === undefined) {\n return [];\n }\n return toArrayStrict(value);\n}\n\nexport function resolveOutput<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject\n>(\n mapper:\n | Mapper<TContext, TExpressionEvent, unknown, EventObject>\n | NonReducibleUnknown,\n context: TContext,\n event: TExpressionEvent,\n self: AnyActor,\n input?: Record<string, unknown>\n): unknown {\n if (typeof mapper === 'function') {\n const outputMapper = mapper as Mapper<\n TContext,\n TExpressionEvent,\n unknown,\n EventObject\n >;\n const args = {\n context,\n event,\n output: getEventOutput(event),\n self,\n input\n } as unknown as Parameters<typeof outputMapper>[0];\n\n return outputMapper(args);\n }\n\n if (\n isDevelopment &&\n !!mapper &&\n typeof mapper === 'object' &&\n Object.values(mapper).some((val) => typeof val === 'function')\n ) {\n console.warn(\n `Dynamically mapping values to individual properties is deprecated. Use a single function that returns the mapped object instead.\\nFound object containing properties whose values are possibly mapping functions: ${Object.entries(\n mapper\n )\n .filter(([, value]) => typeof value === 'function')\n .map(\n ([key, value]) =>\n `\\n - ${key}: ${(value as () => any)\n .toString()\n .replace(/\\n\\s*/g, '')}`\n )\n .join('')}`\n );\n }\n\n return mapper;\n}\n\nexport function getEventOutput<TEvent extends EventObject>(\n event: TEvent\n): OutputArg<TEvent>['output'] {\n if (isDoneEvent(event)) {\n const doneEvent = event as unknown as EventObject & { output: unknown };\n return doneEvent.output as OutputArg<TEvent>['output'];\n }\n\n return undefined as OutputArg<TEvent>['output'];\n}\n\nfunction isDoneEvent(event: EventObject): boolean {\n return (\n event.type === 'xstate.done.actor' || event.type === 'xstate.done.state'\n );\n}\n\nfunction isArray(value: any): value is readonly any[] {\n return Array.isArray(value);\n}\n\nexport function isErrorEvent(event: AnyEventObject): event is ErrorEvent {\n return event.type.startsWith('xstate.error.');\n}\n\n/**\n * Normalizes authored transitions to config objects. A bare string target is\n * rejected (the types and `machineFromJSON` reject it too): `name` and\n * `stateId` locate it in the error.\n */\nexport function toTransitionConfigArray(\n configLike: SingleOrArray<AnyTransitionConfig | AnyTransitionConfigFunction>,\n name: string,\n stateId: string\n): Array<AnyTransitionConfig> {\n return toArrayStrict(configLike).map((transitionLike) => {\n // Untyped (JS or JSON-parsed) configs can still contain a string.\n const value: unknown = transitionLike;\n if (typeof value === 'string') {\n throw new Error(\n isDevelopment\n ? `Transition for \"${name}\" in ${stateId ? `state \"${stateId}\"` : 'the root state'} is the string \"${value}\". Use { target: '${value}' }. The @xstate/codemod string-targets transform rewrites these.`\n : xstateError(38, name, stateId, value)\n );\n }\n if (typeof transitionLike === 'undefined') {\n return { target: undefined };\n }\n\n if (typeof transitionLike === 'function') {\n return { to: transitionLike };\n }\n\n return transitionLike;\n });\n}\n\nexport function normalizeTarget<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n target: SingleOrArray<string | StateNode<TContext, TEvent>> | undefined\n): ReadonlyArray<string | StateNode<TContext, TEvent>> | undefined {\n if (target === undefined || target === TARGETLESS_KEY) {\n return undefined;\n }\n return toArray(target);\n}\n\n/** @experimental Used by framework integrations; not part of the stable API. */\nexport function toObserver<T>(\n nextHandler?: Observer<T> | ((value: T) => void),\n errorHandler?: (error: any) => void,\n completionHandler?: () => void\n): Observer<T> {\n const isObserver = typeof nextHandler === 'object';\n const self = isObserver ? nextHandler : undefined;\n\n return {\n next: (isObserver ? nextHandler.next : nextHandler)?.bind(self),\n error: (isObserver ? nextHandler.error : errorHandler)?.bind(self),\n complete: (isObserver ? nextHandler.complete : completionHandler)?.bind(\n self\n ),\n ...(isObserver && nextHandler.passive ? { passive: true } : {})\n };\n}\n\n/**\n * Names a machine in messages: `machine 'shop'`, or `the machine` when it\n * has no id.\n */\nexport function describeMachine(id: string): string {\n return id ? `machine '${id}'` : 'the machine';\n}\n\n/** The implicit id of an invoke: `<stateId>:<index>`, e.g. `loading:0`. */\nexport function createInvokeId(stateNodeId: string, index: number): string {\n return `${stateNodeId}:${index}`;\n}\n\n/** Whether `value` looks like an actor ref (as persisted context detects them). */\nexport function isActorRefLike(value: object): boolean {\n return 'sessionId' in value && 'send' in value && 'ref' in value;\n}\n\n/**\n * Resolves the logic of a persisted child that has no source key: an inline\n * invoke, identified by its id among the invoke definitions of the active\n * state nodes.\n */\nexport function resolveInvokedActorLogic(\n machine: AnyStateMachine,\n nodes: Iterable<AnyStateNode>,\n childId: string\n): AnyActorLogic {\n const definitions: AnyInvokeDefinition[] = [];\n for (const node of nodes) {\n for (const definition of node.invoke) {\n if (definition.id === childId) {\n definitions.push(definition);\n }\n }\n }\n if (definitions.length !== 1) {\n throw new Error(\n isDevelopment\n ? `Unable to restore child actor '${childId}': it has no source key, and ${definitions.length ? 'several active states' : 'no active state'} of ${describeMachine(machine.id)} ${definitions.length ? 'invoke' : 'invokes'} it.`\n : xstateError(39, childId)\n );\n }\n const logic = definitions[0].logic;\n if (typeof logic === 'string') {\n const registered = machine.sources.actors[logic];\n if (!registered) {\n throw new Error(\n isDevelopment\n ? `Unable to restore child actor '${childId}': child source '${logic}' is not provided in ${describeMachine(machine.id)}.`\n : xstateError(29, childId, logic)\n );\n }\n return registered;\n }\n if (typeof logic === 'function') {\n throw new Error(\n isDevelopment\n ? `Unable to restore child actor '${childId}': its invoke resolves \\`src\\` with a function that returned inline logic. Register the logic in \\`actors\\` and return its key so the child persists by source key.`\n : xstateError(40, childId)\n );\n }\n return logic;\n}\n\n/**\n * Returns one event per transition of the active state nodes of `snapshot`,\n * including the internal events for invoked actors (`xstate.done.actor`,\n * `xstate.error.actor`) and delayed transitions (`xstate.after`). Graph\n * traversal sends these when the `events` option is not given.\n *\n * @public\n */\nexport function getAllOwnEvents(snapshot: AnyMachineSnapshot) {\n const events = snapshot.nodes.flatMap((stateNode) =>\n [...stateNode.transitions.values()].flatMap((transitions) =>\n transitions.map((transition) => {\n const event: AnyEventObject = {\n type: transition.eventType,\n ...transition.matches\n };\n if (\n 'actorId' in event &&\n (event.type === 'xstate.done.actor' ||\n event.type === 'xstate.error.actor' ||\n event.type === 'xstate.snapshot.actor' ||\n event.type === 'xstate.timeout.actor')\n ) {\n event.sessionId = snapshot.children[event.actorId]?.sessionId;\n }\n return event;\n })\n )\n );\n return events.filter(\n (event, index) =>\n events.findIndex((candidate) => {\n const keys = Object.keys(event);\n return (\n keys.length === Object.keys(candidate).length &&\n keys.every((key) => Object.is(event[key], candidate[key]))\n );\n }) === index\n );\n}\n\nexport function matchesEvent(\n event: EventObject,\n pattern: Record<string, unknown>\n): boolean {\n return Object.entries(pattern).every(([key, value]) =>\n Object.is((event as AnyEventObject)[key], value)\n );\n}\n\n/**\n * Checks if an event type matches an event descriptor, supporting wildcards.\n * Event descriptors can be:\n *\n * - Exact matches: \"event.type\"\n * - Wildcard: \"*\"\n * - Partial matches: \"event.*\"\n *\n * @param eventType - The actual event type string\n * @param descriptor - The event descriptor to match against\n * @returns True if the event type matches the descriptor\n */\nexport function matchesEventDescriptor(\n eventType: string,\n descriptor: string\n): boolean {\n if (descriptor === eventType) {\n return true;\n }\n\n if (descriptor === WILDCARD) {\n return true;\n }\n\n if (!descriptor.endsWith('.*')) {\n return false;\n }\n\n if (isDevelopment && /.*\\*.+/.test(descriptor)) {\n console.warn(\n `Wildcards can only be the last token of an event descriptor (e.g., \"event.*\") or the entire event descriptor (\"*\"). Check the \"${descriptor}\" event.`\n );\n }\n\n const partialEventTokens = descriptor.split('.');\n const eventTokens = eventType.split('.');\n\n for (\n let tokenIndex = 0;\n tokenIndex < partialEventTokens.length;\n tokenIndex++\n ) {\n const partialEventToken = partialEventTokens[tokenIndex];\n const eventToken = eventTokens[tokenIndex];\n\n if (partialEventToken === '*') {\n const isLastToken = tokenIndex === partialEventTokens.length - 1;\n\n if (isDevelopment && !isLastToken) {\n console.warn(\n `Infix wildcards in transition events are not allowed. Check the \"${descriptor}\" transition.`\n );\n }\n\n return isLastToken;\n }\n\n if (partialEventToken !== eventToken) {\n return false;\n }\n }\n\n return true;\n}\n","import isDevelopment from '#is-development';\nimport { xstateError } from './xstateError.ts';\nimport { protectSelectionRelay } from './transitionSelection.ts';\nimport type { InspectionEvent, SentRecord } from './inspection.ts';\nimport type { StandardSchemaV1 } from './schema.types.ts';\nimport type { InternalActorOptions } from './createActor.ts';\nimport {\n AnyEventObject,\n ActorTermination,\n ActorSystemInfo,\n AnyActor,\n Observer,\n EventObject,\n Subscription,\n AnyActorLogic,\n LogicalTimer,\n TimerKey\n} from './types.ts';\nimport type { HomomorphicOmit } from './typeUtils.ts';\nimport { XSTATE_TIMER } from './constants.ts';\nimport { getScheduledTimerKey, matchesTimerKey } from './timerKey.ts';\nimport { toObserver } from './utils.ts';\nimport { reportUnhandledError } from './reportUnhandledError.ts';\nimport { getAmbientInspector } from './inspectionAmbient.ts';\nimport { markSystemSnapshotDirty } from './snapshotActorRef.ts';\nimport {\n createMissingAddressError,\n isSerializedActorRef,\n resolveSerializedActorRef,\n getAddressId\n} from './remoteActorRef.ts';\nimport {\n rejectUndeliverableEvent,\n deliverEvent,\n stopActor as stopActorLocally,\n terminateActor as terminateActorLocally,\n runStep\n} from './runtimeHelpers.ts';\n\ninterface ScheduledTimer {\n key: TimerKey;\n scheduledAt: number;\n dueAt: number;\n delay: number;\n source: AnyActor;\n}\n\nexport interface Clock {\n /** Returns the clock's current time in milliseconds. */\n now?(): number;\n setTimeout(fn: (...args: any[]) => void, timeout: number): any;\n clearTimeout(id: any): void;\n}\n\ninterface Scheduler {\n schedule(source: AnyActor, key: TimerKey, delay: number): void;\n cancel(source: AnyActor, key: TimerKey): void;\n cancelAll(actor: AnyActor): void;\n}\n\nlet executionIdPrefix: string | undefined;\nlet nextExecutionId = 0;\n\nfunction createExecutionIdPrefix(): string {\n let crypto: Crypto | undefined;\n try {\n crypto = globalThis.crypto;\n } catch {\n // Use the process-local fallback below.\n }\n\n if (crypto?.getRandomValues) {\n try {\n const values = new Uint32Array(4);\n crypto.getRandomValues(values);\n return Array.from(values, (value) =>\n value.toString(36).padStart(7, '0')\n ).join('');\n } catch {\n // Try randomUUID next.\n }\n }\n\n if (crypto?.randomUUID) {\n try {\n return crypto.randomUUID().replaceAll('-', '');\n } catch {\n // Use the process-local fallback below.\n }\n }\n\n return `xstate-${Date.now().toString(36)}-${Math.random()\n .toString(36)\n .slice(2)}`;\n}\n\nfunction createExecutionId(): string {\n executionIdPrefix ??= createExecutionIdPrefix();\n return `${executionIdPrefix}:${(nextExecutionId++).toString(36)}`;\n}\n\n/**\n * The identity a durable execution pins on every system its transitions\n * create. Shared across all transitions (and replays) of one execution, so\n * session ids become a deterministic function of actor-creation order:\n * `<executionId>:0`, `<executionId>:1`, … A replayed execution re-creates\n * the same session ids, so journaled completion events (which carry the\n * producing incarnation's `sessionId`) still match the children the replay\n * re-creates.\n */\nexport interface ExecutionIdentity {\n executionId: string;\n nextSessionId: number;\n}\n\nlet ambientExecutionIdentity: ExecutionIdentity | undefined;\n\n/** @internal Runs `fn` with systems it creates pinned to `identity`. */\nexport function withExecutionIdentity<T>(\n identity: ExecutionIdentity | undefined,\n fn: () => T\n): T {\n if (!identity) {\n return fn();\n }\n const previous = ambientExecutionIdentity;\n ambientExecutionIdentity = identity;\n try {\n return fn();\n } finally {\n ambientExecutionIdentity = previous;\n }\n}\n\n/** @internal */\nexport {\n hasAmbientInspector,\n withSystemInspector\n} from './inspectionAmbient.ts';\n\n/**\n * Derives the deterministic id prefix for a generated actor id from its actor\n * source: the registered source key when the source is a string, the logic's\n * own `id` otherwise, with `x` as the last-resort prefix.\n *\n * @internal\n */\nexport function getActorIdPrefix(\n src: string | AnyActorLogic | undefined\n): string {\n if (typeof src === 'string') {\n return src;\n }\n const logicId = (src as { id?: unknown } | undefined)?.id;\n // Only named logic earns a named id prefix; machines without an id have\n // the empty id.\n return typeof logicId === 'string' && logicId.length ? logicId : 'x';\n}\n\n/**\n * Encodes one actor id as an address segment. `/` separates segments, so it\n * is percent-encoded, and the escape character `%` is escaped first so the\n * encoding stays injective: the ids 'a/b' and 'a%2Fb' must not produce the\n * same address.\n *\n * @internal\n */\nexport function encodeAddressSegment(id: string): string {\n return id.includes('/') || id.includes('%')\n ? id.replaceAll('%', '%25').replaceAll('/', '%2F')\n : id;\n}\n\n/**\n * Parses a generated-shaped actor id (`prefix:<n>`). This single definition is\n * the determinism contract for id reservation: live allocation, replay, and\n * restore must all agree on what counts as generated-shaped. Deliberately\n * broader than ids a generated allocation could produce — over-reserving\n * skips numbers, which is harmless, while under-reserving could collide.\n *\n * @internal\n */\nexport function parseGeneratedActorId(\n id: string\n): { prefix: string; index: number } | undefined {\n const separator = id.lastIndexOf(':');\n if (separator <= 0 || separator === id.length - 1) {\n return undefined;\n }\n const index = Number(id.slice(separator + 1));\n return Number.isSafeInteger(index) && index >= 0\n ? { prefix: id.slice(0, separator), index }\n : undefined;\n}\n\n/**\n * The id (and address root segment) of the first parentless actor of a logic:\n * the logic's own name, or `x:0` for anonymous logic.\n *\n * @internal\n */\nexport function getRootActorId(\n src: string | AnyActorLogic | undefined\n): string {\n const prefix = getActorIdPrefix(src);\n return prefix === 'x' ? 'x:0' : prefix;\n}\n\nfunction getActorIdCounterKey(\n parent: AnyActor | undefined,\n prefix: string\n): string {\n return `${parent ? parent.address : ''}|${prefix}`;\n}\n\nfunction bumpActorIdCounter(\n system: AnyActorSystem,\n counterKey: string,\n next: number\n): void {\n const counters = system._snapshot._nextActorIds;\n if ((counters[counterKey] ?? 0) >= next) {\n return;\n }\n // Copy-on-write: snapshot systems share this record by shallow `_snapshot`\n // copies, so branches must not observe each other's allocations.\n system._snapshot._nextActorIds = { ...counters, [counterKey]: next };\n markSystemSnapshotDirty(system);\n}\n\n/** @internal */\nexport function resolveActorId(\n system: AnyActorSystem,\n requestedId: string | undefined,\n options?: {\n parent?: AnyActor;\n src?: string | AnyActorLogic;\n }\n): string {\n if (requestedId !== undefined) {\n const generated = parseGeneratedActorId(requestedId);\n if (generated) {\n bumpActorIdCounter(\n system,\n getActorIdCounterKey(options?.parent, generated.prefix),\n generated.index + 1\n );\n } else if (!options?.parent) {\n // Reserve a restored root's bare name so a later parentless actor of\n // the same logic in this system numbers past it.\n bumpActorIdCounter(\n system,\n getActorIdCounterKey(undefined, requestedId),\n 1\n );\n }\n return requestedId;\n }\n\n const prefix = getActorIdPrefix(options?.src);\n const counterKey = getActorIdCounterKey(options?.parent, prefix);\n const counter = system._snapshot._nextActorIds[counterKey] ?? 0;\n bumpActorIdCounter(system, counterKey, counter + 1);\n // The first parentless actor of a logic gets the logic's own name; later\n // parentless actors of the same logic in a shared system get numbered so\n // addresses stay unique.\n return !options?.parent && prefix !== 'x' && counter === 0\n ? prefix\n : `${prefix}:${counter}`;\n}\n\n/** @internal */\nexport function bookSessionId(system: AnyActorSystem): string {\n return `${system._identity.executionId}:${system._identity.nextSessionId++}`;\n}\n\n/**\n * Runtime operations used to execute effects.\n *\n * XState calculates pure transitions; a runtime executes their effects. The\n * built-in local runtime is one implementation at the same level as any\n * other: install a different one via `system.runtime` (for durable hosts,\n * through `createDurable`'s adapter runtime operations).\n */\n/**\n * Why an event was not delivered: `'invalidEvent'` (payload failed its\n * declared schema), `'internalEvent'` (an internal event type sent from\n * outside its owning actor), `'stopped'` (the target actor already stopped)\n * or `'missingTarget'` (`enq.sendTo` received an undefined ref, an unknown\n * child id, or the `parent` of a root actor). Hosts may report additional\n * reasons.\n *\n * @public\n */\nexport type EventRejectionReason =\n | 'invalidEvent'\n | 'internalEvent'\n | 'stopped'\n | 'missingTarget'\n | (string & {});\n\n/**\n * Extra detail attached to a dead letter.\n *\n * @public\n */\nexport interface DeadLetterDetail {\n /** Standard Schema issues for `invalidEvent` rejections. */\n issues?: readonly StandardSchemaV1.Issue[];\n /** The underlying error describing the rejection. */\n error?: Error;\n /**\n * The unresolved target id for `missingTarget` rejections (the child id\n * passed to `enq.sendTo`), when one was given.\n */\n targetId?: string | undefined;\n}\n\n/**\n * Describes an event that was rejected at the delivery boundary instead of\n * being delivered to its target actor (a dead letter).\n *\n * @public\n */\nexport interface EventRejection extends DeadLetterDetail {\n /** The event that was rejected. */\n event: AnyEventObject;\n /** The actor the event was addressed to. */\n targetRef: AnyActor | undefined;\n /** The `id` of the target actor. */\n targetId: string | undefined;\n /** The actor that sent the event, or `undefined` for an external send. */\n sourceRef: AnyActor | undefined;\n /** Whether the event came from outside the system or from another actor. */\n eventOrigin: 'external' | 'actor';\n reason: EventRejectionReason;\n}\n\n/** @public */\nexport interface ActorEmission {\n actorRef: AnyActor;\n event: AnyEventObject;\n}\n\n/** @experimental */\nexport interface ActorSystemRuntime {\n /** Publishes a newly created actor to the runtime. */\n spawnActor(\n source: AnyActor | undefined,\n actor: AnyActor\n ): void | PromiseLike<void>;\n /** Starts an actor. */\n startActor(actor: AnyActor): void | PromiseLike<void>;\n /** Stops an actor without producing a completion result. */\n stopActor(actor: AnyActor): void | PromiseLike<void>;\n /** Completes or errors an actor and publishes its terminal result. */\n terminateActor(\n actor: AnyActor,\n termination: ActorTermination\n ): void | PromiseLike<void>;\n /** Delivers an event between actors. */\n sendEvent(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n ): void | PromiseLike<void>;\n /** Delivers an emitted event, after system emission observers have run. */\n emitEvent(source: AnyActor, event: EventObject): void | PromiseLike<void>;\n /**\n * Schedules a logical timer. `source.address` and `timer` identify it; when\n * it fires, deliver `{ type: 'xstate.timer', ...timer }` to `source`.\n */\n scheduleTimer(\n source: AnyActor,\n timer: TimerKey,\n delay: number\n ): void | PromiseLike<void>;\n /** Cancels one logical timer. */\n cancelTimer(source: AnyActor, timer: TimerKey): void | PromiseLike<void>;\n /**\n * Runs an async actor's entire body as one durable unit. The actor is the\n * natural journal entry: its identity — `address`, string `src` key and\n * serializable `input` — crosses any boundary, so a host can wrap `exec`\n * in its own step primitive, or ignore `exec` entirely and re-run the\n * registered logic on a remote executor from `(src, input)` alone. The\n * default runs the body in this process, unjournaled.\n *\n * Like `runStep`, this is an orchestration frame: it may span external\n * events and must never be serialized behind other runtime operations.\n */\n runLogic(\n actor: AnyActor,\n exec: () => PromiseLike<unknown>\n ): PromiseLike<unknown>;\n /**\n * Runs one keyed step of an async actor (`enq.step`). The default journals\n * the result in the actor's own snapshot; a durable host implements this\n * to journal steps in its own journal instead — memoized results replay\n * without re-running `exec`.\n *\n * Unlike other runtime operations, a step is an orchestration frame that\n * may itself await runtime operations, so implementations must not\n * serialize it behind them.\n */\n runStep(\n actor: AnyActor,\n key: string,\n exec: () => unknown | PromiseLike<unknown>\n ): unknown | PromiseLike<unknown>;\n /**\n * Reports an undeliverable event. Delivery stays at-most-once — this is\n * observability, not retry. The system always calls its\n * `onRejectedEvent` listeners first; the default then logs in development.\n * `detail` carries validation issues and the underlying error for events\n * rejected at the delivery boundary.\n */\n deadLetter(\n source: AnyActor | undefined,\n target: AnyActor | undefined,\n event: AnyEventObject,\n reason: EventRejectionReason,\n detail?: DeadLetterDetail\n ): void | PromiseLike<void>;\n /** Cancels all logical timers owned by an actor. */\n cancelAllTimers(source: AnyActor): void | PromiseLike<void>;\n}\n\n/** @internal Every operation of `ActorSystemRuntime`, for runtime wrappers. */\nexport const RUNTIME_OPERATIONS = [\n 'spawnActor',\n 'startActor',\n 'stopActor',\n 'terminateActor',\n 'emitEvent',\n 'scheduleTimer',\n 'cancelTimer',\n 'cancelAllTimers',\n 'deadLetter'\n // `runLogic`, `runStep` and `sendEvent` are deliberately absent: durable\n // executions wire them separately, since logic bodies and steps await\n // other runtime operations and root-addressed sends are captured per\n // batch.\n] as const satisfies readonly (keyof ActorSystemRuntime)[];\n\ntype ScheduledTimerId = string & { __scheduledTimerId: never };\n\nconst emptyScheduledTimers = Object.freeze(\n {}\n) as ActorSystem<any>['_snapshot']['_scheduledTimers'];\n\nfunction createScheduledTimerId(\n actor: AnyActor,\n key: TimerKey\n): ScheduledTimerId {\n return getScheduledTimerKey(actor, key) as ScheduledTimerId;\n}\n\nfunction findLogicalTimer(\n source: AnyActor,\n key: TimerKey\n): LogicalTimer | undefined {\n return (\n source.getSnapshot()?.timers as readonly LogicalTimer[] | undefined\n )?.find((timer) => matchesTimerKey(timer, key));\n}\n\n/** @public */\nexport interface ActorSystem<\n T extends ActorSystemInfo\n> extends ActorSystemRuntime {\n /** @internal Allocates an actor reference during snapshot calculation. */\n createActorRef(\n logic: AnyActorLogic,\n options: InternalActorOptions<AnyActorLogic>\n ): AnyActor;\n /** @internal */\n children: Map<string, AnyActor>;\n /** @internal Avoids materializing the registered-actor map. */\n _getRootActor?: () => AnyActor | undefined;\n /** @internal Avoids materializing the registered-actor map. */\n _peekChildren?: () => Map<string, AnyActor> | undefined;\n /** @internal */\n reverseKeyedActors: WeakMap<AnyActor, keyof T['actors']>;\n /** @internal */\n keyedActors: Map<keyof T['actors'], AnyActor | undefined>;\n /** @internal */\n _peekKeyedActors?: () =>\n | Map<keyof T['actors'], AnyActor | undefined>\n | undefined;\n /**\n * @internal Returns the live actor at a logical address, if any. Resolves\n * serialized actor refs used as send targets.\n */\n _getByAddress?: (address: string) => AnyActor | undefined;\n /** @internal */\n _register: (sessionId: string, actor: AnyActor) => string;\n /** @internal */\n _unregister: (actor: AnyActor) => void;\n /** @internal */\n _set: <K extends keyof T['actors']>(key: K, actor: AnyActor) => void;\n get: <K extends keyof T['actors']>(key: K) => T['actors'][K] | undefined;\n getAll: () => Partial<T['actors']>;\n\n inspect: (\n observer:\n | Observer<InspectionEvent>\n | ((inspectionEvent: InspectionEvent) => void)\n ) => Subscription;\n /**\n * Subscribes to events the system could not deliver (dead letters): sends\n * to a stopped actor, events rejected at the delivery boundary\n * and internal events sent from outside their owner. Listeners run in\n * registration order; a listener that throws does not prevent the others.\n * The `onRejectedEvent` option on `createActor` registers a listener the\n * same way.\n *\n * @public\n */\n onRejectedEvent: (\n listener: (rejection: EventRejection) => void\n ) => Subscription;\n /**\n * Observes emitted events from every actor in this system, before runtime\n * delivery. Listeners run in registration order; errors do not prevent\n * other listeners or delivery. Unsubscribe to stop observing.\n *\n * @public\n */\n onEmitted: (listener: (emission: ActorEmission) => void) => Subscription;\n /** @internal */\n _notifyEmitted: (actorRef: AnyActor, event: AnyEventObject) => void;\n /** @internal Avoids collecting inspection-only transition metadata. */\n _hasInspectionObservers?: () => boolean;\n /** @internal */\n _sendInspectionEvent: (\n event: HomomorphicOmit<InspectionEvent, 'rootId'>\n ) => void;\n /** @internal */\n _relay: (\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n ) => void | PromiseLike<void>;\n scheduler: Scheduler;\n getSnapshot: () => {\n _scheduledTimers: Record<string, ScheduledTimer>;\n };\n /**\n * Runtime identity shared by every snapshot view of this actor system.\n *\n * @internal\n */\n _identity: {\n executionId: string;\n nextSessionId: number;\n };\n /** @internal */\n _snapshot: {\n _scheduledTimers: Record<ScheduledTimerId, ScheduledTimer>;\n /** Deterministic generated-id counters keyed by `${parentAddress}|${srcPrefix}`. */\n _nextActorIds: Record<string, number>;\n };\n /** @internal */\n _snapshotVersion: number;\n start: () => void;\n _clock: Clock;\n _logger: (...args: any[]) => void;\n /**\n * The runtime executing this system's effects. When unset, the built-in\n * local in-memory runtime runs them; `createActor(machine).start()` is just\n * that built-in runtime. A host runtime installed here applies to every\n * actor in the system — snapshot-scoped views and children created later\n * included — and may implement any subset of operations, with the rest\n * keeping the built-in behavior.\n *\n * An operation that returns a promise owns its own failure handling: the\n * paths that hand work to a runtime do not await it. `createDurable`\n * tracks its adapter's operations and fails `executeEffects` when one\n * rejects.\n *\n * Durable hosts should provide this through `createDurable`'s\n * adapter runtime operations rather than assigning it directly.\n */\n runtime?: Partial<ActorSystemRuntime>;\n}\n\n/** @public */\nexport type AnyActorSystem = ActorSystem<any>;\n\n// These optional lazy fields intentionally have no emitted initializers.\n// oxlint-disable-next-line typescript/no-unsafe-declaration-merging\ninterface RuntimeSystem<T extends ActorSystemInfo> {\n runtime?: Partial<ActorSystemRuntime>;\n _children?: Map<string, AnyActor>;\n _keyedActors?: Map<keyof T['actors'], AnyActor | undefined>;\n _reverseKeyedActors?: WeakMap<AnyActor, keyof T['actors']>;\n _inspectionObservers?: Set<Observer<InspectionEvent>>;\n _timerMap?: { [id: ScheduledTimerId]: number };\n _rejectionListeners?: Set<(rejection: EventRejection) => void>;\n _emissionListeners?: Set<(emission: ActorEmission) => void>;\n}\n\nclass RuntimeSystem<T extends ActorSystemInfo> implements ActorSystem<T> {\n public _identity = ambientExecutionIdentity ?? {\n executionId: createExecutionId(),\n nextSessionId: 0\n };\n public _snapshot: ActorSystem<T>['_snapshot'];\n public _snapshotVersion = 0;\n public scheduler: Scheduler = this;\n public _clock: Clock;\n public _logger: (...args: any[]) => void;\n public createActorRef: ActorSystem<T>['createActorRef'];\n\n public get children(): Map<string, AnyActor> {\n const children = (this._children ??= new Map());\n if (this._getRootActor()) {\n children.set(this._rootActor.sessionId, this._rootActor);\n }\n return children;\n }\n\n public set children(children: Map<string, AnyActor>) {\n this._children = children;\n }\n\n public _getRootActor(): AnyActor | undefined {\n return this._rootActor._isRunning() ? this._rootActor : undefined;\n }\n\n public _peekChildren(): Map<string, AnyActor> | undefined {\n return this._children;\n }\n\n public get keyedActors(): Map<keyof T['actors'], AnyActor | undefined> {\n return (this._keyedActors ??= new Map());\n }\n\n public set keyedActors(actors: Map<keyof T['actors'], AnyActor | undefined>) {\n this._keyedActors = actors;\n }\n\n public get reverseKeyedActors(): WeakMap<AnyActor, keyof T['actors']> {\n return (this._reverseKeyedActors ??= new WeakMap());\n }\n\n public set reverseKeyedActors(actors: WeakMap<AnyActor, keyof T['actors']>) {\n this._reverseKeyedActors = actors;\n }\n\n /** @internal Avoids materializing the receptionist for empty systems. */\n public _peekKeyedActors():\n | Map<keyof T['actors'], AnyActor | undefined>\n | undefined {\n return this._keyedActors;\n }\n\n constructor(\n private _rootActor: AnyActor,\n options: {\n clock: Clock;\n logger: (...args: any[]) => void;\n createActorRef: ActorSystem<T>['createActorRef'];\n }\n ) {\n this._clock = options.clock;\n this._logger = options.logger;\n this.createActorRef = options.createActorRef;\n const ambientInspector = getAmbientInspector();\n if (ambientInspector) {\n this.inspect(ambientInspector);\n }\n this._snapshot = {\n _scheduledTimers: emptyScheduledTimers,\n // System-level counters are process-local backstops; per-actor\n // counters persist on each machine snapshot, and restored explicit ids\n // reserve their numbering here via `resolveActorId`.\n _nextActorIds: {}\n };\n }\n\n // Records a send on the *sender's* transition for the `sent[]` inspection\n // facet. Captures the send when it is initiated (including delayed sends that\n // may never deliver), keyed to the source actor's in-flight transition.\n // A send made with no transition in flight (a callback's `sendBack`, a value\n // an observable relays to its parent) is not recorded: no transition reports\n // it, so it would be held until the source's next transition, or for as long\n // as the source lives if it never makes one.\n private _recordSent(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject,\n delay?: number,\n id?: string\n ): void {\n if (!this._inspectionObservers?.size || !source) {\n return;\n }\n const inspectionSource = source as AnyActor & {\n _collectedSent?: SentRecord[];\n _inTransition?: boolean;\n };\n if (!inspectionSource._inTransition) {\n return;\n }\n const collected = (inspectionSource._collectedSent ??= []);\n collected.push({\n targetRef: target,\n targetId: target.id,\n event,\n delay,\n id\n });\n }\n\n public schedule(source: AnyActor, key: TimerKey, delay: number): void {\n const scheduledTimerId = createScheduledTimerId(source, key);\n if (this._timerMap?.[scheduledTimerId] !== undefined) {\n this.cancel(source, key);\n }\n\n const timer = findLogicalTimer(source, key);\n if (timer) {\n const target = timer.target === 'self' ? source : timer.target;\n this._recordSent(source, target, timer.event, delay, timer.id);\n }\n\n const scheduledAt = this._clock.now?.() ?? Date.now();\n const scheduledTimer: ScheduledTimer = {\n source,\n delay,\n key,\n scheduledAt,\n dueAt: scheduledAt + delay\n };\n if (this._snapshot._scheduledTimers === emptyScheduledTimers) {\n this._snapshot._scheduledTimers = {};\n }\n this._snapshot._scheduledTimers[scheduledTimerId] = scheduledTimer;\n markSystemSnapshotDirty(this);\n\n const timeout = this._clock.setTimeout(() => {\n if (this._timerMap) {\n delete this._timerMap[scheduledTimerId];\n }\n delete this._snapshot._scheduledTimers[scheduledTimerId];\n markSystemSnapshotDirty(this);\n\n this._deliver(source, source, { type: XSTATE_TIMER, ...key });\n }, delay);\n\n (this._timerMap ??= {})[scheduledTimerId] = timeout;\n }\n\n public cancel(source: AnyActor, key: TimerKey): void {\n const scheduledTimerId = createScheduledTimerId(source, key);\n const timeout = this._timerMap?.[scheduledTimerId];\n\n if (this._timerMap) {\n delete this._timerMap[scheduledTimerId];\n }\n if (this._snapshot._scheduledTimers !== emptyScheduledTimers) {\n delete this._snapshot._scheduledTimers[scheduledTimerId];\n }\n markSystemSnapshotDirty(this);\n\n if (timeout !== undefined) {\n this._clock.clearTimeout(timeout);\n }\n }\n\n public cancelAll(actor: AnyActor): void {\n for (const scheduledTimerId in this._snapshot._scheduledTimers) {\n const scheduledTimer =\n this._snapshot._scheduledTimers[scheduledTimerId as ScheduledTimerId];\n if (scheduledTimer.source === actor) {\n this.cancel(actor, scheduledTimer.key);\n }\n }\n }\n\n // Delivers an event to the target actor. Used by both `_relay` (which also\n // records the send) and the scheduler's timer (which already recorded it).\n private _deliver(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n ): void {\n deliverEvent(source, target, event);\n }\n\n public _register(sessionId: string, actor: AnyActor): string {\n if (actor === this._rootActor) {\n this._children?.set(sessionId, actor);\n } else {\n (this._children ??= new Map()).set(sessionId, actor);\n }\n markSystemSnapshotDirty(this);\n return sessionId;\n }\n\n public _getByAddress(address: string): AnyActor | undefined {\n const root = this._getRootActor();\n if (root?.address === address) {\n return root;\n }\n for (const actor of this._children?.values() ?? []) {\n if (actor.address === address && actor._isRunning()) {\n return actor;\n }\n }\n return undefined;\n }\n\n public _unregister(actor: AnyActor): void {\n let changed: boolean;\n // Remote handles have no sessionId and are never in the session map;\n // their registry cleanup happens through the keyed-actor path below.\n if (actor === this._rootActor) {\n changed = this._getRootActor() !== undefined;\n changed =\n (actor.sessionId !== undefined &&\n (this._children?.delete(actor.sessionId) ?? false)) ||\n changed;\n } else {\n changed =\n actor.sessionId !== undefined &&\n (this._children?.delete(actor.sessionId) ?? false);\n }\n const registryKey = this._reverseKeyedActors?.get(actor);\n\n if (registryKey !== undefined) {\n if (this._keyedActors?.get(registryKey) === actor) {\n this._keyedActors.delete(registryKey);\n changed = true;\n }\n this._reverseKeyedActors?.delete(actor);\n }\n if (changed) {\n markSystemSnapshotDirty(this);\n }\n }\n\n public get<K extends keyof T['actors']>(\n registryKey: K\n ): T['actors'][K] | undefined {\n return this._keyedActors?.get(registryKey) as T['actors'][K] | undefined;\n }\n\n public getAll(): Partial<T['actors']> {\n return Object.fromEntries(this._keyedActors?.entries() ?? []) as Partial<\n T['actors']\n >;\n }\n\n public _set<K extends keyof T['actors']>(\n registryKey: K,\n actor: AnyActor\n ): void {\n const existing = this._keyedActors?.get(registryKey);\n if (existing && existing !== actor) {\n throw new Error(\n isDevelopment\n ? `Actor with registry key '${registryKey as string}' already exists.`\n : xstateError(45, String(registryKey))\n );\n }\n\n (this._keyedActors ??= new Map()).set(registryKey, actor);\n (this._reverseKeyedActors ??= new WeakMap()).set(actor, registryKey);\n if (existing !== actor) {\n markSystemSnapshotDirty(this);\n }\n }\n\n public inspect(\n observerOrFn:\n | Observer<InspectionEvent>\n | ((inspectionEvent: InspectionEvent) => void)\n ): Subscription {\n const observer = toObserver(observerOrFn);\n (this._inspectionObservers ??= new Set()).add(observer);\n\n return {\n unsubscribe: () => {\n this._inspectionObservers?.delete(observer);\n }\n };\n }\n\n public onRejectedEvent(\n listener: (rejection: EventRejection) => void\n ): Subscription {\n // Wrap so the same function registered twice gets two subscriptions.\n const entry = (rejection: EventRejection) => listener(rejection);\n (this._rejectionListeners ??= new Set()).add(entry);\n return {\n unsubscribe: () => {\n this._rejectionListeners?.delete(entry);\n }\n };\n }\n\n public onEmitted(listener: (emission: ActorEmission) => void): Subscription {\n const entry = (emission: ActorEmission) => listener(emission);\n (this._emissionListeners ??= new Set()).add(entry);\n return {\n unsubscribe: () => {\n this._emissionListeners?.delete(entry);\n }\n };\n }\n\n public _notifyEmitted(actorRef: AnyActor, event: AnyEventObject): void {\n const listeners = this._emissionListeners;\n if (!listeners?.size) {\n return;\n }\n const emission: ActorEmission = { actorRef, event };\n for (const listener of Array.from(listeners)) {\n try {\n listener(emission);\n } catch (err) {\n reportUnhandledError(err);\n }\n }\n }\n\n public _hasInspectionObservers(): boolean {\n return !!this._inspectionObservers?.size;\n }\n\n public _sendInspectionEvent(\n event: HomomorphicOmit<InspectionEvent, 'rootId'>\n ): void {\n if (!this._inspectionObservers?.size) {\n return;\n }\n const resolvedInspectionEvent: InspectionEvent = {\n ...event,\n rootId: this._rootActor.sessionId!\n };\n this._inspectionObservers.forEach((observer) => {\n try {\n observer.next?.(resolvedInspectionEvent);\n } catch (err) {\n reportUnhandledError(err);\n }\n });\n }\n\n // Unlike the other operations, spawn has no local work: local actors\n // register with the system when they are constructed, so this only\n // notifies a host runtime.\n public spawnActor(\n source: AnyActor | undefined,\n actor: AnyActor\n ): void | PromiseLike<void> {\n return this.runtime?.spawnActor?.(source, actor);\n }\n\n public startActor(actor: AnyActor): void | PromiseLike<void> {\n const override = this.runtime?.startActor;\n if (override) {\n return override(actor);\n }\n actor.start();\n }\n\n public stopActor(actor: AnyActor): void | PromiseLike<void> {\n const override = this.runtime?.stopActor;\n if (override) {\n return override(actor);\n }\n stopActorLocally(actor);\n }\n\n public terminateActor(\n actor: AnyActor,\n termination: ActorTermination\n ): void | PromiseLike<void> {\n const override = this.runtime?.terminateActor;\n if (override) {\n return override(actor, termination);\n }\n terminateActorLocally(actor, termination);\n }\n\n public sendEvent(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n ): void | PromiseLike<void> {\n if (isSerializedActorRef(target)) {\n // A ref that went through JSON resolves by address to the live actor.\n // A host runtime may own actors this system cannot see, so an\n // unresolved address is its to route; locally it is a dead letter.\n const live = resolveSerializedActorRef(this, target);\n if (live) {\n target = live;\n } else if (\n // A live actor of another incarnation is stale locally; an\n // address this system cannot see may belong to a host runtime.\n this._getByAddress(target['@actor']) ||\n !this.runtime?.sendEvent\n ) {\n return this.deadLetter(source, undefined, event, 'missingTarget', {\n targetId: getAddressId(target['@actor']),\n error: createMissingAddressError(target)\n });\n }\n }\n if (rejectUndeliverableEvent(source, target, event)) {\n return;\n }\n // Record for the inspection `sent[]` facet regardless of which runtime\n // delivers, so host runtimes keep inspection parity.\n this._recordSent(source, target, event);\n const override = this.runtime?.sendEvent;\n if (override) {\n return override(source, target, event);\n }\n this._deliver(source, target, event);\n }\n\n public emitEvent(\n source: AnyActor,\n event: EventObject\n ): void | PromiseLike<void> {\n const override = this.runtime?.emitEvent;\n if (override) {\n return override(source, event);\n }\n (source as AnyActor & { _emit(value: EventObject): void })._emit(event);\n }\n\n public deadLetter(\n source: AnyActor | undefined,\n target: AnyActor | undefined,\n event: AnyEventObject,\n reason: EventRejectionReason,\n detail?: DeadLetterDetail\n ): void | PromiseLike<void> {\n const listeners = this._rejectionListeners;\n if (listeners?.size) {\n const rejection: EventRejection = {\n event,\n targetRef: target,\n targetId: target?.id ?? detail?.targetId,\n sourceRef: source,\n eventOrigin: source ? 'actor' : 'external',\n reason,\n issues: detail?.issues,\n error: detail?.error\n };\n // Snapshot so listeners added or removed during delivery do not affect\n // this rejection.\n for (const listener of [...listeners]) {\n try {\n listener(rejection);\n } catch (err) {\n reportUnhandledError(err);\n }\n }\n }\n const override = this.runtime?.deadLetter;\n if (override) {\n return override(source, target, event, reason, detail);\n }\n if (isDevelopment) {\n console.warn(\n target\n ? `Event \"${event.type}\" to actor \"${target.id}\" was not delivered (${reason}).`\n : `Actor \"${source?.id}\" sent event \"${event.type}\" to missing target ${\n detail?.targetId !== undefined\n ? `\"${detail.targetId}\"`\n : 'undefined'\n }; the event was not delivered (${reason}).`\n );\n }\n }\n\n public runStep(\n actor: AnyActor,\n key: string,\n exec: () => unknown | PromiseLike<unknown>\n ): unknown | PromiseLike<unknown> {\n const override = this.runtime?.runStep;\n if (override) {\n return override(actor, key, exec);\n }\n return runStep(actor, key, exec);\n }\n\n public runLogic(\n actor: AnyActor,\n exec: () => PromiseLike<unknown>\n ): PromiseLike<unknown> {\n const override = this.runtime?.runLogic;\n if (override) {\n return override(actor, exec);\n }\n return exec();\n }\n\n public scheduleTimer(\n source: AnyActor,\n key: TimerKey,\n delay: number\n ): void | PromiseLike<void> {\n const override = this.runtime?.scheduleTimer;\n if (override) {\n // The local scheduler records delayed sends for inspection inside\n // `schedule`; keep that parity for host runtimes.\n const timer = findLogicalTimer(source, key);\n if (timer) {\n const target = timer.target === 'self' ? source : timer.target;\n this._recordSent(source, target, timer.event, delay, timer.id);\n }\n return override(source, key, delay);\n }\n this.schedule(source, key, delay);\n }\n\n public cancelTimer(\n source: AnyActor,\n key: TimerKey\n ): void | PromiseLike<void> {\n const override = this.runtime?.cancelTimer;\n if (override) {\n return override(source, key);\n }\n this.cancel(source, key);\n }\n\n public cancelAllTimers(source: AnyActor): void | PromiseLike<void> {\n const override = this.runtime?.cancelAllTimers;\n if (override) {\n return override(source);\n }\n this.cancelAll(source);\n }\n\n public _relay(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n ): void | PromiseLike<void> {\n if (protectSelectionRelay(target)) {\n return;\n }\n // Returned so callers that can observe a host runtime's asynchronous\n // delivery do; the built-in runtime delivers synchronously.\n return this.sendEvent(source, target, event);\n }\n\n public getSnapshot(): {\n _scheduledTimers: Record<string, ScheduledTimer>;\n } {\n return {\n _scheduledTimers: { ...this._snapshot._scheduledTimers }\n };\n }\n\n public start(): void {\n const scheduledTimers = this._snapshot._scheduledTimers;\n let resetScheduledTimers = true;\n for (const scheduledId in scheduledTimers) {\n if (resetScheduledTimers) {\n this._snapshot._scheduledTimers = {};\n resetScheduledTimers = false;\n }\n const { source, dueAt, key } =\n scheduledTimers[scheduledId as ScheduledTimerId];\n this.scheduleTimer(\n source,\n key,\n Math.max(0, dueAt - (this._clock.now?.() ?? Date.now()))\n );\n }\n }\n}\n\n/** @internal */\nexport function createRuntimeSystem<T extends ActorSystemInfo>(\n rootActor: AnyActor,\n options: {\n clock: Clock;\n logger: (...args: any[]) => void;\n createActorRef: ActorSystem<T>['createActorRef'];\n }\n): ActorSystem<T> {\n return new RuntimeSystem(rootActor, options);\n}\n","import isDevelopment from '#is-development';\nimport { xstateError } from './xstateError.ts';\nimport { diagnoseActorOptions } from './devDiagnostics.ts';\nimport { publishEmittedEvent } from './runtimeHelpers.ts';\nimport type { ActionRecord, SentRecord } from './inspection.ts';\nimport { Mailbox } from './Mailbox.ts';\nimport { XSTATE_STOP, XSTATE_TIMER } from './constants.ts';\nimport {\n createDoneActorEvent,\n createErrorActorEvent,\n createInitEvent\n} from './eventUtils.ts';\nimport { reportUnhandledError } from './reportUnhandledError.ts';\nimport { symbolObservable } from './symbolObservable.ts';\nimport {\n encodeAddressSegment,\n AnyActorSystem,\n bookSessionId,\n Clock,\n createRuntimeSystem,\n resolveActorId\n} from './system.ts';\n\n// those are needed to make JSDoc `@link` work properly\n// oxlint-disable no-unused-vars\nimport type {\n createObservableLogic,\n createEventObservableLogic\n} from './actors/observable.ts';\nimport type { createCallbackLogic } from './actors/callback.ts';\nimport type { createStepLogic } from './actors/logic.ts';\nimport type { createAsyncLogic } from './actors/promise.ts';\nimport type { createMachine } from './createMachine.ts';\n// oxlint-enable no-unused-vars\n\nlet executingCustomAction: boolean = false;\n\nimport type {\n ActorTermination,\n ActorScope,\n ActorTrigger,\n AnyActor,\n AnyActorLogic,\n EmittedFrom,\n EventFromLogic,\n SendableEventFromLogic,\n InputFrom,\n PersistedSnapshotOf,\n Snapshot,\n SnapshotFrom,\n AnyTransitionDefinition,\n ExecutableEffect,\n Readable,\n ActorLogicTransitionResult,\n LogicalTimer,\n ReservedMachineEvent,\n SerializedActorRef\n} from './types.ts';\nimport { getTimerKey } from './timerKey.ts';\nimport {\n ActorOptions,\n ActorInstance,\n ActorRef,\n EventObject,\n InteropSubscribable,\n Observer,\n Subscription\n} from './types.ts';\nimport { toObserver } from './utils.ts';\nimport { finalizeTransitionResult } from './transitionActions.ts';\nimport {\n refreshSnapshotActorRefRoot,\n setSnapshotActorRef\n} from './snapshotActorRef.ts';\n\ninterface ActorMailboxEvent<TEvent> {\n event: TEvent;\n sourceRef: AnyActor | undefined;\n}\n\nconst emptyInspectionRecords = Object.freeze([]) as unknown as never[];\n\nconst reservedMachineEventTypes = {\n 'xstate.done.actor': true,\n 'xstate.error.actor': true,\n 'xstate.error.execution': true,\n 'xstate.snapshot.actor': true,\n 'xstate.done.state': true,\n 'xstate.after': true,\n 'xstate.timeout.state': true,\n 'xstate.timeout.actor': true,\n [XSTATE_TIMER]: true\n} satisfies Record<ReservedMachineEvent['type'] | typeof XSTATE_TIMER, true>;\n\n// those values are currently used by @xstate/react directly so it's important to keep the assigned values in sync\nexport enum ProcessingStatus {\n NotStarted = 0,\n Running = 1,\n Stopped = 2\n}\n\nconst defaultOptions = Object.freeze({\n clock: {\n setTimeout: (fn, ms) => {\n return setTimeout(fn, ms);\n },\n clearTimeout: (id) => {\n return clearTimeout(id);\n }\n } as Clock,\n logger: console.log.bind(console)\n});\n\nfunction safeCall<T>(fn: ((arg: T) => void) | undefined, arg?: T) {\n try {\n fn?.(arg as T);\n } catch (err) {\n reportUnhandledError(err);\n }\n}\n\nfunction executeExecutableEffects(\n effects: readonly ExecutableEffect[] | undefined,\n actorScope: ActorScope<any, any, any, any>\n): void {\n if (!effects?.length) {\n return;\n }\n\n for (const effect of effects) {\n actorScope.actionExecutor(effect);\n }\n}\n\n/**\n * Options core passes when it creates actors: the public {@link ActorOptions}\n * plus the parent of a child actor. Not exported from the package entry.\n */\nexport interface InternalActorOptions<\n TLogic extends AnyActorLogic\n> extends ActorOptions<TLogic> {\n parent?: AnyActor;\n}\n\nfunction createActorRef(\n logic: AnyActorLogic,\n options: InternalActorOptions<AnyActorLogic>\n): AnyActor {\n return new Actor(logic, options);\n}\n\n/**\n * An Actor is a running process that can receive events, send events and change\n * its behavior based on the events it receives, which can cause effects outside\n * of the actor. When you run a state machine, it becomes an actor.\n *\n * An `Actor` is the concrete runtime instance with lifecycle methods and\n * system-owned internals. It also satisfies the narrower `ActorRef` contract,\n * so consumer APIs should accept `ActorRef` when they only need to send events\n * or read snapshots.\n *\n * @public\n */\nexport class Actor<TLogic extends AnyActorLogic> implements ActorInstance<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>,\n EmittedFrom<TLogic>,\n SendableEventFromLogic<TLogic>\n> {\n /** The current internal state of the actor. */\n private _snapshot!: SnapshotFrom<TLogic>;\n /**\n * The clock that is responsible for setting and clearing timeouts, such as\n * delayed events and transitions.\n */\n public clock: Clock;\n public options: Readonly<ActorOptions<TLogic>>;\n\n /** The unique identifier for this actor relative to its parent. */\n public id: string;\n\n private _boundProcess?: (\n item: ActorMailboxEvent<EventFromLogic<TLogic>>\n ) => void;\n private mailbox?: Mailbox<ActorMailboxEvent<EventFromLogic<TLogic>>>;\n private _mailboxStarted = false;\n\n private observers?: Set<Observer<SnapshotFrom<TLogic>>>;\n /** Whether a consumer subscribed to this actor's error after it errored. */\n private _errorObserved = false;\n private eventListeners:\n | Map<string, Set<(emittedEvent: EmittedFrom<TLogic>) => void>>\n | undefined;\n private logger: (...args: any[]) => void;\n\n /** @internal */\n public _processingStatus: ProcessingStatus = ProcessingStatus.NotStarted;\n private _forceDeferredActions = false;\n\n // Actor Ref\n public _parent?: AnyActor;\n /** @internal */\n public _syncSnapshot?: boolean;\n public ref: ActorRef<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>,\n EmittedFrom<TLogic>,\n SendableEventFromLogic<TLogic>\n >;\n // TODO: add typings for system\n private _actorScope: ActorScope<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>,\n AnyActorSystem,\n EmittedFrom<TLogic>,\n SendableEventFromLogic<TLogic>\n >;\n\n /** @internal */\n public _lastSourceRef?: AnyActor;\n /** @internal */\n public _collectedMicrosteps: AnyTransitionDefinition[] | undefined;\n /** @internal Actions executed during the in-flight transition. */\n public _collectedActions: ActionRecord[] | undefined;\n /** @internal Events relayed to other actors during the in-flight transition. */\n public _collectedSent: SentRecord[] | undefined;\n /**\n * @internal Whether a transition is in flight: while the actor starts,\n * processes an event, or recovers from an execution error. Sends are recorded\n * for `sent[]` only then.\n */\n public _inTransition = false;\n private _initialEffects: ExecutableEffect[] | undefined;\n public registryKey: string | undefined;\n\n /** The globally unique process ID for this invocation. */\n public sessionId: string;\n\n private _address?: string;\n /**\n * The deterministic logical address of this actor within its system: the\n * `/`-joined path of actor ids from the root. Stable across persistence and\n * restore, unlike `sessionId`, which identifies one incarnation.\n *\n * `/` separates segments, so an id containing one (a state name with a\n * slash reaches its invoked child's id) is percent-encoded to keep the\n * path unambiguous.\n */\n public get address(): string {\n // `id` and `_parent` never change after construction, so the whole chain\n // memoizes to O(1) amortized.\n return (this._address ??= this._parent\n ? `${this._parent.address}/${encodeAddressSegment(this.id)}`\n : encodeAddressSegment(this.id));\n }\n\n /** The system to which this actor belongs. */\n public system: AnyActorSystem;\n\n private _trigger?: ActorTrigger<SendableEventFromLogic<TLogic>>;\n\n public get trigger(): ActorTrigger<SendableEventFromLogic<TLogic>> {\n return (this._trigger ??= new Proxy({} as Actor<TLogic>['trigger'], {\n get: (_, eventType: string) => {\n return (payload?: Record<PropertyKey, unknown>) => {\n this.send({\n ...payload,\n type: eventType\n } as SendableEventFromLogic<TLogic>);\n };\n }\n }) as ActorTrigger<SendableEventFromLogic<TLogic>>);\n }\n\n private _boundSend?: ActorRef<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>,\n EmittedFrom<TLogic>,\n SendableEventFromLogic<TLogic>\n >['send'];\n\n public get send(): ActorRef<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>,\n EmittedFrom<TLogic>,\n SendableEventFromLogic<TLogic>\n >['send'] {\n return (this._boundSend ??= this._sendPublic.bind(this));\n }\n\n public src: string | AnyActorLogic;\n\n /**\n * Creates a new actor instance for the given logic with the provided options,\n * if any.\n *\n * @param logic The logic to create an actor from\n * @param options Actor options\n */\n constructor(\n public logic: TLogic,\n options?: ActorOptions<TLogic>\n ) {\n const resolvedOptions = (\n options ? { ...defaultOptions, ...options } : defaultOptions\n ) as InternalActorOptions<TLogic> & typeof defaultOptions;\n\n const { clock, logger, parent, syncSnapshot, id, registryKey, inspect } =\n resolvedOptions;\n\n this.system = parent\n ? parent.system\n : (resolvedOptions._systemRef?.current ??\n createRuntimeSystem(this, {\n clock,\n logger,\n createActorRef\n }));\n\n if (\n !parent &&\n resolvedOptions._systemRef &&\n !resolvedOptions._systemRef.current\n ) {\n resolvedOptions._systemRef.current = this.system;\n resolvedOptions._systemRef.initialize?.();\n }\n\n if (inspect && !parent) {\n // Always inspect at the system-level\n this.system.inspect(toObserver(inspect));\n }\n\n if (resolvedOptions.onRejectedEvent && !parent) {\n this.system.onRejectedEvent(resolvedOptions.onRejectedEvent);\n }\n\n this.sessionId = resolvedOptions._sessionId ?? bookSessionId(this.system);\n this.id = resolveActorId(this.system, id, {\n parent,\n src: resolvedOptions.src ?? logic\n });\n this.logger = options?.logger ?? this.system._logger;\n this.clock = options?.clock ?? this.system._clock;\n this._parent = parent;\n this._syncSnapshot = syncSnapshot;\n this.options = resolvedOptions as ActorOptions<TLogic> &\n typeof defaultOptions;\n this.src = resolvedOptions.src ?? logic;\n this.ref = this;\n this._actorScope = this as unknown as typeof this._actorScope;\n\n if (registryKey) {\n this.registryKey = registryKey;\n this.system._set(registryKey, this);\n }\n\n // prepare to collect initial microsteps during initialTransition\n this._collectedMicrosteps = undefined;\n const restore = resolvedOptions._restore;\n this._restored = restore !== undefined;\n try {\n if (restore) {\n this._setSnapshot(restore.restore(this._actorScope));\n } else if (options?._inert) {\n // Inert actors (createInertActorScope) only anchor a scope for pure\n // transition functions; computing an initial snapshot here would run\n // init-time side effects (context factories, entry) a second time.\n } else {\n this._inTransition = true;\n try {\n const [snapshot, effects] = finalizeTransitionResult(\n this._actorScope,\n undefined,\n this.logic.initialTransition(this.options?.input, this._actorScope)\n );\n this._setSnapshot(snapshot);\n this._initialEffects = effects.length ? effects : undefined;\n } finally {\n this._inTransition = false;\n }\n }\n } catch (err) {\n // Restored logic may keep its snapshot shape on restore failures (e.g.\n // machines). Otherwise we can't get the true\n // `TSnapshot & { status: 'error'; }`, so this is a lie of sorts.\n this._setSnapshot(\n restore?.error?.(err) ??\n ({\n status: 'error',\n output: undefined,\n error: err\n } as SnapshotFrom<TLogic>)\n );\n // discard any functions deferred during the failed initial snapshot\n // computation so they can't run against an inconsistent actor\n if (this._deferred) {\n this._deferred.length = 0;\n }\n }\n\n if (\n registryKey &&\n (this._snapshot as Snapshot<unknown>).status !== 'active'\n ) {\n this.system._unregister(this);\n }\n\n // Announce actor topology: emitted once for every actor (root and every\n // spawned/invoked child) so the actor graph can be drawn before any\n // transitions occur. This is the only place actor identity is announced.\n if (this.system._hasInspectionObservers?.() ?? true) {\n this.system._sendInspectionEvent({\n type: '@xstate.actor',\n actorRef: this,\n parentRef: this._parent,\n id: this.id,\n src: this.src,\n snapshot: this._snapshot\n });\n }\n }\n\n // array of functions to defer\n private _deferred: Array<() => void> | undefined;\n\n private _restored = false;\n\n /** @internal */\n public _getLogger(): ActorScope<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>\n >['logger'] {\n return this.logger;\n }\n\n private get self(): Actor<TLogic> {\n return this;\n }\n\n private get defer(): (fn: () => void) => void {\n const defer = (fn: () => void) => this._defer(fn);\n Object.defineProperty(this, 'defer', { value: defer });\n return defer;\n }\n\n private get stopChild(): (child: AnyActor) => void {\n const stopChild = (child: AnyActor) => this._stopChild(child);\n Object.defineProperty(this, 'stopChild', { value: stopChild });\n return stopChild;\n }\n\n private get emit(): (event: EmittedFrom<TLogic>) => void | PromiseLike<void> {\n const emit = (event: EmittedFrom<TLogic>) =>\n publishEmittedEvent(this, event, this.system);\n Object.defineProperty(this, 'emit', { value: emit });\n return emit;\n }\n\n private get actionExecutor(): (action: ExecutableEffect) => void {\n const actionExecutor = (action: ExecutableEffect) =>\n this._executeAction(action);\n Object.defineProperty(this, 'actionExecutor', { value: actionExecutor });\n return actionExecutor;\n }\n\n /** @internal */\n public _isRunning(): boolean {\n return this._processingStatus === ProcessingStatus.Running;\n }\n\n /** @internal */\n public _defer(fn: () => void): void {\n (this._deferred ??= []).push(fn);\n }\n\n /** @internal */\n public _stopChild(child: AnyActor): void {\n if (child._parent !== this) {\n throw new Error(\n isDevelopment\n ? `Cannot stop child actor ${child.id} of ${this.id} because it is not a child`\n : xstateError(47, child.id, this.id)\n );\n }\n (child as Actor<AnyActorLogic>)._stop();\n }\n\n /** @internal */\n public _executeAction(action: ExecutableEffect): void {\n const exec = () => {\n // Record every executed action for the '@xstate.transition' inspection\n // event's `actions[]` facet (replaces the v5 '@xstate.action' event).\n if (this.system._hasInspectionObservers?.() ?? true) {\n (this._collectedActions ??= []).push({\n type: action.type,\n params: action.params\n });\n }\n const saveExecutingCustomAction = executingCustomAction;\n try {\n executingCustomAction = true;\n const result = action.exec();\n if (\n result &&\n typeof (result as PromiseLike<unknown>).then === 'function'\n ) {\n void Promise.resolve(result).catch((err) => {\n if (this._processingStatus === ProcessingStatus.Stopped) {\n return;\n }\n this._recoverOrError(err);\n });\n }\n } finally {\n executingCustomAction = saveExecutingCustomAction;\n }\n };\n if (\n this._processingStatus === ProcessingStatus.Running &&\n !this._forceDeferredActions\n ) {\n exec();\n } else {\n (this._deferred ??= []).push(exec);\n }\n }\n\n /** Associates each live snapshot with this actor for later pure transitions. */\n private _setSnapshot(snapshot: SnapshotFrom<TLogic>): void {\n const previousSnapshot = this._snapshot;\n this._snapshot = snapshot;\n setSnapshotActorRef(snapshot, this, this.system, previousSnapshot);\n }\n\n private _setErrorSnapshot(\n err: unknown,\n snapshot: SnapshotFrom<TLogic> = this._snapshot\n ) {\n this._setSnapshot({\n ...(snapshot as Snapshot<unknown>),\n status: 'error',\n error: err\n } as SnapshotFrom<TLogic>);\n }\n\n /** Recover via the logic's error event if possible; otherwise error out. */\n private _recoverOrError(\n err: unknown,\n snapshot?: SnapshotFrom<TLogic>,\n previousSnapshot?: SnapshotFrom<TLogic>\n ): boolean {\n if (this._tryHandleExecutionError(err, snapshot)) {\n return true;\n }\n this._setErrorSnapshot(err);\n this._error(err, previousSnapshot);\n return false;\n }\n\n private _tryHandleExecutionError(\n err: unknown,\n snapshot: SnapshotFrom<TLogic> = this._snapshot\n ): boolean {\n // Machine logic can recover from execution errors via `onError`\n // transitions; the logic decides (so the actor stays logic-agnostic).\n const errorEvent = this.logic.getExecutionErrorEvent?.(snapshot, err) as\n | EventFromLogic<TLogic>\n | undefined;\n if (!errorEvent) {\n return false;\n }\n\n const inTransition = this._inTransition;\n this._inTransition = true;\n try {\n const [nextSnapshot, effects] = finalizeTransitionResult(\n this._actorScope,\n snapshot,\n this.logic.transition(snapshot, errorEvent, this._actorScope)\n );\n this._setSnapshot(nextSnapshot);\n executeExecutableEffects(effects, this._actorScope);\n this.update(nextSnapshot, errorEvent);\n return true;\n } catch {\n return false;\n } finally {\n this._inTransition = inTransition;\n }\n }\n\n private _next(snapshot: SnapshotFrom<TLogic>) {\n for (const observer of this.observers ?? emptyInspectionRecords) {\n safeCall(observer.next, snapshot);\n }\n }\n\n private update(snapshot: SnapshotFrom<TLogic>, event: EventObject): void {\n // Update state\n this._setSnapshot(snapshot);\n\n // Execute deferred effects\n const deferred = this._deferred;\n for (let i = 0; i < (deferred?.length ?? 0); i++) {\n const deferredFn = deferred![i];\n try {\n deferredFn();\n } catch (err) {\n // this error can only be caught when executing *initial* actions\n // it's the only time when we call actions provided by the user through those deferreds\n // when the actor is already running we always execute them synchronously while transitioning\n // no \"builtin deferred\" should actually throw an error since they are either safe\n // or the control flow is passed through the mailbox and errors should be caught by the `_process` used by the mailbox\n deferred!.length = 0;\n if (this._tryHandleExecutionError(err, snapshot)) {\n return;\n }\n this._setErrorSnapshot(err, snapshot);\n this._error(err);\n break;\n }\n }\n if (deferred) {\n deferred.length = 0;\n }\n\n switch ((this._snapshot as Snapshot<unknown>).status) {\n case 'active':\n this._next(snapshot);\n break;\n case 'done':\n case 'error':\n // Terminal lifecycle is represented by the ordered\n // `@xstate.terminate` effect returned by the actor logic.\n break;\n }\n this._inspectTransition(this._snapshot, event);\n }\n\n /** @internal Emits the transition inspection event; used by the pure\n * `transition()` path for snapshots driven outside a live actor. */\n public _inspectTransition(\n snapshot: SnapshotFrom<TLogic>,\n event: EventObject\n ): void {\n if (this.system._hasInspectionObservers?.() ?? true) {\n this.system._sendInspectionEvent({\n type: '@xstate.transition',\n actorRef: this,\n event,\n sourceRef: this._lastSourceRef,\n targetRef: this,\n snapshot,\n microsteps: this._collectedMicrosteps ?? emptyInspectionRecords,\n actions: this._collectedActions ?? emptyInspectionRecords,\n sent: this._collectedSent ?? emptyInspectionRecords,\n eventType: event.type\n });\n }\n this._collectedMicrosteps = undefined;\n this._collectedActions = undefined;\n this._collectedSent = undefined;\n }\n\n private _flushInitialEffects(): boolean {\n if (!this._initialEffects?.length) {\n return true;\n }\n this._forceDeferredActions = true;\n try {\n executeExecutableEffects(this._initialEffects, this._actorScope);\n this._initialEffects = undefined;\n return true;\n } catch (err) {\n this._initialEffects = undefined;\n if (this._deferred) {\n this._deferred.length = 0;\n }\n this._recoverOrError(err);\n return (this._snapshot as Snapshot<unknown>).status === 'active';\n } finally {\n this._forceDeferredActions = false;\n }\n }\n\n /**\n * Subscribe an observer to an actor’s snapshot values.\n *\n * @remarks\n * The observer will receive the actor’s snapshot value when it is emitted.\n * The observer can be:\n *\n * - A plain function that receives the latest snapshot, or\n * - An observer object whose `.next(snapshot)` method receives the latest\n * snapshot\n *\n * @example\n *\n * ```ts\n * // Observer as a plain function\n * const subscription = actor.subscribe((snapshot) => {\n * console.log(snapshot);\n * });\n * ```\n *\n * @example\n *\n * ```ts\n * // Observer as an object\n * const subscription = actor.subscribe({\n * next(snapshot) {\n * console.log(snapshot);\n * },\n * error(err) {\n * // ...\n * },\n * complete() {\n * // ...\n * }\n * });\n * ```\n *\n * The return value of `actor.subscribe(observer)` is a subscription object\n * that has an `.unsubscribe()` method. You can call\n * `subscription.unsubscribe()` to unsubscribe the observer:\n *\n * @example\n *\n * ```ts\n * const subscription = actor.subscribe((snapshot) => {\n * // ...\n * });\n *\n * // Unsubscribe the observer\n * subscription.unsubscribe();\n * ```\n *\n * When the actor is stopped, all of its observers will automatically be\n * unsubscribed.\n *\n * @param observer - Either a plain function that receives the latest\n * snapshot, or an observer object whose `.next(snapshot)` method receives\n * the latest snapshot\n */\n public subscribe(observer: Observer<SnapshotFrom<TLogic>>): Subscription;\n public subscribe(\n nextListener?: (snapshot: SnapshotFrom<TLogic>) => void,\n errorListener?: (error: any) => void,\n completeListener?: () => void\n ): Subscription;\n public subscribe(\n nextListenerOrObserver?:\n | ((snapshot: SnapshotFrom<TLogic>) => void)\n | Observer<SnapshotFrom<TLogic>>,\n errorListener?: (error: any) => void,\n completeListener?: () => void\n ): Subscription {\n const observer = toObserver(\n nextListenerOrObserver,\n errorListener,\n completeListener\n );\n\n if (this._processingStatus !== ProcessingStatus.Stopped) {\n (this.observers ??= new Set()).add(observer);\n } else {\n switch ((this._snapshot as Snapshot<unknown>).status) {\n case 'done':\n safeCall(observer.complete);\n break;\n case 'error': {\n const err = (this._snapshot as Snapshot<unknown>).error;\n if (!observer.error) {\n reportUnhandledError(err);\n } else {\n if (!observer.passive) {\n this._errorObserved = true;\n }\n safeCall(observer.error, err);\n }\n break;\n }\n }\n }\n\n return {\n unsubscribe: () => {\n this.observers?.delete(observer);\n }\n };\n }\n\n public on<TType extends EmittedFrom<TLogic>['type'] | '*'>(\n type: TType,\n handler: (\n emitted: EmittedFrom<TLogic> &\n (TType extends '*' ? unknown : { type: TType })\n ) => void\n ): Subscription {\n let listeners = this.eventListeners?.get(type);\n if (!listeners) {\n listeners = new Set();\n (this.eventListeners ??= new Map()).set(type, listeners);\n }\n listeners.add(handler as (emittedEvent: EmittedFrom<TLogic>) => void);\n\n return {\n unsubscribe: () => {\n listeners.delete(\n handler as (emittedEvent: EmittedFrom<TLogic>) => void\n );\n }\n };\n }\n\n public select<TSelected>(\n selector: (snapshot: SnapshotFrom<TLogic>) => TSelected,\n equalityFn: (a: TSelected, b: TSelected) => boolean = Object.is\n ): Readable<TSelected> {\n return {\n subscribe: (\n observerOrFn:\n | Observer<TSelected>\n | ((value: TSelected) => void)\n | undefined,\n errorListener?: (error: any) => void,\n completeListener?: () => void\n ) => {\n const observer = toObserver(\n observerOrFn,\n errorListener,\n completeListener\n );\n let selected = selector(this.getSnapshot());\n return this.subscribe({\n next: (snapshot) => {\n const next = selector(snapshot);\n if (!equalityFn(selected, next)) {\n selected = next;\n observer.next?.(next);\n }\n },\n error: observer.error,\n complete: observer.complete\n });\n },\n get: () => selector(this.getSnapshot())\n };\n }\n\n /** Starts the Actor from the initial state */\n public start(): this {\n const inTransition = this._inTransition;\n this._inTransition = true;\n try {\n return this._start();\n } finally {\n this._inTransition = inTransition;\n }\n }\n\n private _start(): this {\n if (this._processingStatus === ProcessingStatus.Running) {\n // Do not restart the service if it is already started\n return this;\n }\n\n if (this._processingStatus === ProcessingStatus.Stopped) {\n const status = (this._snapshot as Snapshot<unknown>).status;\n if (status === 'done' || status === 'error') {\n // A terminated actor has nothing left to start.\n return this;\n }\n // Actors are single-use: a stopped actor cannot be restarted.\n throw new Error(\n isDevelopment\n ? `Actor ${this.id} was stopped and cannot be restarted. Create a new actor with createActor().`\n : xstateError(48, this.id)\n );\n }\n\n if (this._syncSnapshot) {\n this.subscribe({\n next: (snapshot: Snapshot<unknown>) => {\n if (snapshot.status === 'active') {\n this.system._relay(this, this._parent!, {\n type: 'xstate.snapshot.actor',\n actorId: this.id,\n sessionId: this.sessionId,\n snapshot\n });\n }\n },\n error: () => {}\n });\n }\n\n this.system._register(this.sessionId, this);\n if (this.registryKey) {\n this.system._set(this.registryKey, this);\n }\n this._processingStatus = ProcessingStatus.Running;\n\n this._lastSourceRef = this._parent;\n\n const status = (this._snapshot as Snapshot<unknown>).status;\n\n switch (status) {\n case 'done':\n // a state machine can be \"done\" upon initialization (it could reach a final state using initial microsteps)\n // we still need to complete observers, flush deferreds etc\n if (this._restored) {\n // Restoration does not replay the transition that originally\n // terminated the actor, and must not notify the parent again.\n this._next(this._snapshot);\n this._stopProcedure();\n this._complete();\n return this;\n }\n if (!this._flushInitialEffects()) {\n return this;\n }\n this.update(\n this._snapshot,\n createInitEvent(\n this.options.input\n ) as unknown as EventFromLogic<TLogic>\n );\n // TODO: rethink cleanup of observers, mailbox, etc\n return this;\n case 'error':\n this._error((this._snapshot as Snapshot<unknown>).error);\n return this;\n case 'stopped':\n // A restored stopped snapshot is terminal: the actor does not process\n // events or run transitions.\n this._stopProcedure();\n this._complete();\n return this;\n }\n\n if (!this._parent) {\n this.system.start();\n }\n\n if (!this._flushInitialEffects()) {\n return this;\n }\n\n if (this.logic.start) {\n try {\n this.logic.start(this._snapshot, this._actorScope, {\n restored: this._restored\n });\n } catch (err) {\n this._setErrorSnapshot(err);\n this._error(err);\n return this;\n }\n }\n\n if (\n !this._restored &&\n !this._deferred?.length &&\n !this.observers?.size &&\n !(this.system._hasInspectionObservers?.() ?? true)\n ) {\n // Starting changes the registered system view associated with the\n // snapshot, even when there is nothing to publish or execute.\n if (!refreshSnapshotActorRefRoot(this._snapshot, this, this.system)) {\n this._setSnapshot(this._snapshot);\n }\n this._collectedMicrosteps = undefined;\n this._collectedActions = undefined;\n this._collectedSent = undefined;\n } else {\n this.update(\n this._snapshot,\n createInitEvent(this.options.input) as unknown as EventFromLogic<TLogic>\n );\n }\n\n if (this._restored) {\n const timers =\n (\n this._snapshot as unknown as {\n timers?: readonly LogicalTimer[];\n }\n ).timers ?? [];\n // scheduledAt is only persisted from — and only meaningful under — the\n // wall clock; a custom clock (a simulated clock, a monotonic counter)\n // restores every timer with its declared delay. The clamp bounds\n // remaining time by the declared delay in case the wall clock moved\n // backwards between persist and restore.\n const wallClock = !this.system._clock.now;\n const now = Date.now();\n for (const timer of timers) {\n // A timer persisted from a live runtime carries its wall-clock start;\n // honor the absolute deadline instead of restarting the full delay.\n // Without a start (a pure-transition snapshot, or an older snapshot)\n // the declared delay is all there is.\n const delay =\n wallClock && timer.scheduledAt !== undefined\n ? Math.min(\n timer.delay,\n Math.max(0, timer.scheduledAt + timer.delay - now)\n )\n : timer.delay;\n this.system.scheduleTimer(this, getTimerKey(timer), delay);\n }\n this._restored = false;\n }\n\n this._mailboxStarted = true;\n this.mailbox?.start();\n\n return this;\n }\n\n private _process(item: ActorMailboxEvent<EventFromLogic<TLogic>>) {\n const inTransition = this._inTransition;\n this._inTransition = true;\n try {\n this._processEvent(item);\n } finally {\n this._inTransition = inTransition;\n }\n }\n\n private _processEvent({\n event,\n sourceRef\n }: ActorMailboxEvent<EventFromLogic<TLogic>>) {\n this._lastSourceRef = sourceRef;\n const previousSnapshot = this._snapshot;\n let nextState: ActorLogicTransitionResult<SnapshotFrom<TLogic>> | undefined;\n let caughtError;\n try {\n nextState = finalizeTransitionResult(\n this._actorScope,\n this._snapshot,\n this.logic.transition(this._snapshot, event, this._actorScope)\n );\n } catch (err) {\n // we wrap it in a box so we can rethrow it later even if falsy value gets caught here\n caughtError = { err };\n }\n\n if (caughtError) {\n this._collectedMicrosteps = undefined;\n this._collectedActions = undefined;\n this._collectedSent = undefined;\n if (!this._recoverOrError(caughtError.err)) {\n this._inspectTransition(this._snapshot, event);\n }\n return;\n }\n if (!nextState) {\n return;\n }\n\n let snapshot = this._snapshot;\n try {\n const [nextSnapshot, effects] = nextState;\n if (\n nextSnapshot === previousSnapshot &&\n !effects.length &&\n // State machine snapshots only; other logic may ignore events freely.\n 'machine' in (previousSnapshot as object) &&\n event.type !== XSTATE_STOP &&\n (!sourceRef || !Object.hasOwn(reservedMachineEventTypes, event.type))\n ) {\n this._reportUnhandledEvent(event);\n }\n snapshot = nextSnapshot;\n this._setSnapshot(snapshot);\n executeExecutableEffects(effects, this._actorScope);\n this.update(snapshot, event);\n } catch (err) {\n if (!this._recoverOrError(err, snapshot, previousSnapshot)) {\n this._inspectTransition(this._snapshot, event);\n }\n return;\n }\n\n if (event.type === XSTATE_STOP) {\n this._stopProcedure();\n this._complete();\n }\n }\n\n private _warnedUnhandledTypes?: Set<string>;\n\n private _reportUnhandledEvent(event: EventFromLogic<TLogic>): void {\n safeCall(() => this.options.onUnhandledEvent?.(event, this._snapshot));\n if (isDevelopment) {\n const to =\n event.type === 'xstate.route'\n ? ` to ${JSON.stringify((event as { to?: unknown }).to)}`\n : '';\n const warned = (this._warnedUnhandledTypes ??= new Set());\n if (!warned.has(event.type + to)) {\n warned.add(event.type + to);\n console.warn(\n `Actor ${this.id} received event \"${event.type}\"${to} in state ${JSON.stringify(\n (this._snapshot as { value?: unknown }).value\n )} with no matching transition`\n );\n }\n }\n }\n\n /** @internal */\n public _emit(event: EmittedFrom<TLogic>): void {\n for (const listeners of [\n this.eventListeners?.get(event.type),\n this.eventListeners?.get('*')\n ]) {\n if (listeners) {\n for (const handler of listeners) {\n safeCall(handler, event);\n }\n }\n }\n }\n\n /** @internal */\n public _terminate(termination: ActorTermination): void {\n if (termination.status === 'done') {\n // The terminal snapshot is published before observer completion and the\n // parent notification, matching actor lifecycle order.\n this._next(this._snapshot);\n this._stopProcedure();\n this._complete();\n if (this._parent) {\n this.system._relay(\n this,\n this._parent,\n createDoneActorEvent(this.id, termination.output, this.sessionId)\n );\n }\n return;\n }\n if (termination.status === 'error') {\n this._error(termination.error);\n }\n }\n\n /** @internal */\n public _stop(): this {\n if (this._processingStatus === ProcessingStatus.Stopped) {\n return this;\n }\n this.mailbox?.clear();\n if (this._processingStatus === ProcessingStatus.NotStarted) {\n this._processingStatus = ProcessingStatus.Stopped;\n this.system._unregister(this);\n return this;\n }\n this._send({ type: XSTATE_STOP } as EventFromLogic<TLogic>);\n this.system._unregister(this);\n\n return this;\n }\n\n /** Stops the Actor and unsubscribe all listeners. */\n public stop(): this {\n if (this._parent) {\n throw new Error(\n isDevelopment\n ? 'A non-root actor cannot be stopped directly.'\n : xstateError(49, this.id)\n );\n }\n return this._stop();\n }\n private _complete(): void {\n for (const observer of this.observers ?? emptyInspectionRecords) {\n safeCall(observer.complete);\n }\n this.observers?.clear();\n this.eventListeners?.clear();\n }\n\n /**\n * Reports an unhandled error unless a consumer observes it before the\n * report runs. An actor can error before its creator has a chance to\n * subscribe, so the check waits one macrotask for a subscriber with an\n * `error` callback.\n */\n private _reportUnlessObserved(err: unknown): void {\n setTimeout(() => {\n if (!this._errorObserved) {\n reportUnhandledError(err);\n }\n });\n }\n\n private _error(err: unknown, previousSnapshot?: SnapshotFrom<TLogic>): void {\n this._stopProcedure();\n // Transition calculation or effect execution may fail before child stop\n // effects run. Keep the previous snapshot's children when calculation has\n // already removed them, and include children owned by non-machine logic\n // from the runtime registry.\n const children = new Set<AnyActor>();\n for (const snapshot of [this._snapshot, previousSnapshot]) {\n const snapshotChildren = (\n snapshot as\n | {\n children?: Record<string, AnyActor | undefined>;\n }\n | undefined\n )?.children;\n for (const child of Object.values(snapshotChildren ?? {})) {\n if (\n child?._parent === this &&\n typeof child.getSnapshot === 'function'\n ) {\n children.add(child);\n }\n }\n }\n for (const child of this.system._peekChildren?.()?.values() ?? []) {\n if (child._parent === this) {\n children.add(child);\n }\n }\n for (const child of children) {\n try {\n if (child.getSnapshot().status !== 'active') {\n continue;\n }\n const result = this.system.stopActor(child);\n if (result) {\n void Promise.resolve(result).catch(reportUnhandledError);\n }\n } catch (error) {\n reportUnhandledError(error);\n }\n }\n if (!this.observers?.size) {\n if (!this._parent) {\n this._reportUnlessObserved(err);\n }\n } else {\n let reportError = false;\n let handled = false;\n\n for (const observer of this.observers) {\n const errorListener = observer.error;\n if (!observer.passive) {\n reportError ||= !errorListener;\n handled ||= !!errorListener;\n }\n safeCall(errorListener, err);\n }\n reportError ||= !handled;\n this.observers.clear();\n if (reportError) {\n this._reportUnlessObserved(err);\n }\n }\n this.eventListeners?.clear();\n\n if (this._parent) {\n this.system._relay(\n this,\n this._parent,\n createErrorActorEvent(this.id, err, this.sessionId)\n );\n }\n }\n private _stopProcedure(): void {\n if (this._processingStatus !== ProcessingStatus.Running) {\n // Actor already stopped; do nothing\n return;\n }\n\n // Cancel all delayed events\n this.system.cancelAllTimers(this);\n\n // TODO: mailbox.reset\n this.mailbox?.clear();\n this.mailbox = undefined;\n this._boundProcess = undefined;\n this._mailboxStarted = false;\n\n this._processingStatus = ProcessingStatus.Stopped;\n this.system._unregister(this);\n }\n\n /** @internal */\n public _send(event: EventFromLogic<TLogic>, sourceRef?: AnyActor) {\n if (this._processingStatus === ProcessingStatus.Stopped) {\n this.system.deadLetter(sourceRef, this as AnyActor, event, 'stopped');\n return;\n }\n\n let mailbox = this.mailbox;\n if (!mailbox) {\n this._boundProcess ??= this._process.bind(this);\n mailbox = this.mailbox = new Mailbox(this._boundProcess);\n if (this._mailboxStarted) {\n mailbox.start();\n }\n }\n mailbox.enqueue({ event, sourceRef });\n }\n\n /**\n * Sends an event to the running Actor to trigger a transition.\n *\n * @param event The event to send\n */\n private _sendPublic(event: SendableEventFromLogic<TLogic>) {\n if (isDevelopment && typeof event === 'string') {\n throw new Error(\n `Only event objects may be sent to actors; use .send({ type: \"${event}\" }) instead`\n );\n }\n this.system._relay(undefined, this, event);\n }\n\n /**\n * Returns the actor's serializable logical identity: `{ \"@actor\": address }`.\n * The result can be used as an `enq.sendTo(...)` target.\n */\n public toJSON(): SerializedActorRef {\n return { '@actor': this.address };\n }\n\n /**\n * Obtain the internal state of the actor, which can be persisted.\n *\n * @remarks\n * The internal state can be persisted from any actor, not only machines.\n *\n * Note that the persisted state is not the same as the snapshot from\n * {@link Actor.getSnapshot}. Persisted state represents the internal state of\n * the actor, while snapshots represent the actor's last emitted value.\n *\n * Can be restored with {@link ActorOptions.snapshot}\n * @see https://stately.ai/docs/persistence\n */\n public getPersistedSnapshot(options?: {\n /**\n * Whether persisted machine children embed their own persisted state\n * (the co-locating runtime's whole-tree checkpoint) or are referenced by\n * logical address only, leaving each child's state with the runtime that\n * owns it. Defaults to `true`.\n */\n embedChildren?: boolean;\n }): PersistedSnapshotOf<TLogic>;\n public getPersistedSnapshot(options?: unknown): PersistedSnapshotOf<TLogic> {\n return this.logic.getPersistedSnapshot(\n this._snapshot,\n options\n ) as PersistedSnapshotOf<TLogic>;\n }\n\n public [symbolObservable](): InteropSubscribable<SnapshotFrom<TLogic>> {\n return this;\n }\n\n /**\n * Read an actor’s snapshot synchronously.\n *\n * @remarks\n * The snapshot is the last value the actor published, not a query of its\n * private state: the actor emits a snapshot when it transitions, and this\n * returns that cached last emission. The read is coherent within one\n * synchronous transition turn because event processing runs to completion;\n * across asynchronous boundaries it may be stale, like any observed value.\n *\n * Only co-located actors publish full snapshots. A location-transparent\n * remote handle exposes lifecycle only ({ status, output?, error? }): while\n * the handle exists among its parent's children the child is presumed\n * `active`, and its terminal result arrives as a completion event.\n *\n * Note that some actors, such as callback actors generated with\n * `createCallbackLogic`, will not emit snapshots.\n * @see {@link Actor.subscribe} to subscribe to an actor’s snapshot values.\n * @see {@link Actor.getPersistedSnapshot} to persist the internal state of an actor (which is more than just a snapshot).\n */\n public getSnapshot(): SnapshotFrom<TLogic> {\n if (isDevelopment && !this._snapshot) {\n throw new Error(\n `Snapshot can't be read while the actor initializes itself`\n );\n }\n return this._snapshot;\n }\n}\n\n/**\n * `'input'` when creating an actor from `TLogic` requires input (its input type\n * does not accept `undefined`), otherwise `never`.\n *\n * @public\n */\nexport type RequiredActorOptionsKeys<TLogic extends AnyActorLogic> =\n undefined extends InputFrom<TLogic> ? never : 'input';\n\n/**\n * The options `createActor` (and framework hooks) require for `TLogic`:\n * `{ input }` when the logic requires input, otherwise nothing.\n *\n * @public\n */\nexport type RequiredActorOptionsFor<TLogic extends AnyActorLogic> = [\n RequiredActorOptionsKeys<TLogic>\n] extends [never]\n ? {}\n : { [K in RequiredActorOptionsKeys<TLogic>]: unknown };\n\n/** Options accepted by {@link createActor}. */\ntype CreateActorOptionsArgs<TLogic extends AnyActorLogic> = [\n RequiredActorOptionsKeys<TLogic>\n] extends [never]\n ? [options?: ActorOptions<TLogic>]\n : [options: ActorOptions<TLogic> & RequiredActorOptionsFor<TLogic>];\n\n/**\n * Creates a new actor instance for the given actor logic with the provided\n * options, if any.\n *\n * @remarks\n * When you create an actor from actor logic via `createActor(logic)`, you\n * implicitly create an actor system where the created actor is the root actor.\n * Any actors spawned from this root actor and its descendants are part of that\n * actor system.\n * @example\n *\n * ```ts\n * import { createActor } from 'xstate';\n * import { someActorLogic } from './someActorLogic.ts';\n *\n * // Creating the actor, which implicitly creates an actor system with itself as the root actor\n * const actor = createActor(someActorLogic);\n *\n * actor.subscribe((snapshot) => {\n * console.log(snapshot);\n * });\n *\n * // Actors must be started by calling `actor.start()`, which will also start the actor system.\n * actor.start();\n *\n * // Actors can receive events\n * actor.send({ type: 'someEvent' });\n *\n * // You can stop root actors by calling `actor.stop()`, which will also stop the actor system and all actors in that system.\n * actor.stop();\n * ```\n *\n * @param logic - The actor logic to create an actor from. For a state machine\n * actor logic creator, see {@link createMachine}. Other actor logic creators\n * include {@link createCallbackLogic}, {@link createEventObservableLogic},\n * {@link createObservableLogic}, {@link createStepLogic}, and\n * {@link createAsyncLogic}.\n * @param options - Actor options\n * @public\n */\nexport function createActor<TLogic extends AnyActorLogic>(\n logic: TLogic,\n ...[options]: CreateActorOptionsArgs<TLogic>\n): Actor<TLogic> {\n diagnoseActorOptions(options);\n return new Actor(logic, options);\n}\n","import type {\n ActorLogicValidator,\n ActorValidationRequest\n} from './validation.types.ts';\n\nexport function assertValid(\n validator: ActorLogicValidator,\n request: ActorValidationRequest\n): void {\n const error = validator.check(request);\n if (error) {\n throw error;\n }\n}\n","import {\n XSTATE_LOGIC_EFFECT_REJECT,\n XSTATE_LOGIC_EFFECT_RESOLVE,\n XSTATE_LOGIC_EFFECT_START,\n XSTATE_INIT,\n XSTATE_STOP\n} from '../constants.ts';\nimport { createInitEvent } from '../eventUtils.ts';\nimport { StandardSchemaV1 } from '../schema.types.ts';\nimport {\n ActorSystemRuntime,\n AnyActorSystem,\n type DeadLetterDetail\n} from '../system.ts';\nimport { assertValid } from '../validation.ts';\nimport type { ActorLogicValidator } from '../validation.types.ts';\nimport {\n finalizeTransitionResult,\n createCustomEffect,\n createDeadLetterEffect,\n createEmitEffect,\n createSendToEffect\n} from '../transitionActions.ts';\nimport {\n ActorLogic,\n ActorRefFrom,\n ActorScope,\n AnyActorRef,\n EventObject,\n ExecutableEffect,\n Snapshot\n} from '../types.ts';\nimport type { NonReducibleUnknown } from '../typeUtils.ts';\n\n/** @public */\nexport type StepSnapshot<TContext, TOutput, TInput> = Snapshot<TOutput> & {\n context: TContext;\n input: TInput | undefined;\n effects?: Record<string, StepEffectState>;\n};\n\n/** @public */\nexport type StepEffectState =\n | { status: 'active' }\n | { status: 'done'; output?: unknown }\n | { status: 'error'; error: unknown };\n\n/** @public */\nexport interface StepLogicArgs<TContext, TEvent extends EventObject, TInput> {\n context: TContext;\n event: TEvent;\n input: TInput;\n system: AnyActorSystem;\n self: StepActorRef<TContext, unknown, TEvent, TInput>;\n}\n\n/** @public */\nexport interface StepLogicEnqueue<\n TEvent extends EventObject,\n TEmitted extends EventObject\n> {\n emit: (emitted: TEmitted) => void;\n sendBack: (event: EventObject) => void;\n raise: (event: TEvent) => void;\n effect: {\n (\n exec: (runtime?: Partial<ActorSystemRuntime>) => void | (() => void)\n ): void;\n (\n key: string,\n exec: (runtime?: Partial<ActorSystemRuntime>) => void | (() => void)\n ): void;\n };\n}\n\n/** @public */\nexport type StepPatch<TContext, TOutput, TInput> = Partial<{\n context: TContext;\n input: TInput | undefined;\n status: StepSnapshot<TContext, TOutput, TInput>['status'];\n output: TOutput;\n error: unknown;\n effects: Record<string, StepEffectState>;\n}>;\n\n/** @public */\nexport type StepLogicFunction<\n TContext,\n TOutput,\n TEvent extends EventObject,\n TInput,\n TEmitted extends EventObject\n> = (\n args: StepLogicArgs<TContext, TEvent, TInput>,\n enq: StepLogicEnqueue<TEvent, TEmitted>\n) => void | StepPatch<TContext, TOutput, TInput>;\n\n/** @public */\nexport interface StepLogicConfig<\n TContext,\n TOutput,\n TEvent extends EventObject,\n TInput,\n TEmitted extends EventObject,\n TInputSchema extends StandardSchemaV1 = StandardSchemaV1,\n TOutputSchema extends StandardSchemaV1 = StandardSchemaV1\n> {\n id?: string;\n validator?: ActorLogicValidator;\n schemas?: {\n input?: TInputSchema;\n output?: TOutputSchema;\n };\n context: TContext | ((args: { input: TInput }) => TContext);\n run: StepLogicFunction<TContext, TOutput, TEvent, TInput, TEmitted>;\n}\n\ninterface StepTransition<\n TContext,\n TOutput,\n TEvent extends EventObject,\n TInput,\n TEmitted extends EventObject\n> {\n (\n snapshot: StepSnapshot<TContext, TOutput, TInput>,\n event: TEvent,\n actorScope: ActorScope<\n StepSnapshot<TContext, TOutput, TInput>,\n TEvent,\n AnyActorSystem,\n TEmitted\n >\n ): [StepSnapshot<TContext, TOutput, TInput>, ExecutableEffect[]];\n (\n snapshot: StepSnapshot<TContext, TOutput, TInput>,\n event: TEvent,\n actorScope: ActorScope<\n StepSnapshot<TContext, TOutput, TInput>,\n TEvent,\n AnyActorSystem,\n TEmitted\n >\n ): StepSnapshot<TContext, TOutput, TInput>;\n}\n\n/** @public */\nexport type StepActorLogic<\n TContext,\n TOutput,\n TEvent extends EventObject = EventObject,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n> = Omit<\n ActorLogic<\n StepSnapshot<TContext, TOutput, TInput>,\n TEvent,\n TInput,\n AnyActorSystem,\n TEmitted\n >,\n 'transition'\n> & {\n id?: string;\n transition: StepTransition<TContext, TOutput, TEvent, TInput, TEmitted>;\n};\n\n/** @public */\nexport type StepActorRef<\n TContext,\n TOutput,\n TEvent extends EventObject,\n TInput\n> = ActorRefFrom<StepActorLogic<TContext, TOutput, TEvent, TInput>>;\n\nconst effectStates = new WeakMap<\n AnyActorRef,\n Map<PropertyKey, { cleanup?: () => void }>\n>();\n\nfunction getEffectState(self: AnyActorRef) {\n let state = effectStates.get(self);\n if (!state) {\n state = new Map();\n effectStates.set(self, state);\n }\n return state;\n}\n\nfunction executeLogicEffect(\n self: AnyActorRef,\n key: string | undefined,\n effect: () => void | (() => void)\n): void {\n const state = getEffectState(self);\n if (key !== undefined && state.has(key)) {\n return;\n }\n const cleanup = effect();\n state.set(key ?? Symbol(), {\n cleanup: typeof cleanup === 'function' ? cleanup : undefined\n });\n}\n\nfunction cleanupLogicEffects(self: AnyActorRef): void {\n const state = effectStates.get(self);\n if (!state) {\n return;\n }\n effectStates.delete(self);\n let failure: { error: unknown } | undefined;\n for (const { cleanup } of state.values()) {\n try {\n cleanup?.();\n } catch (error) {\n failure ??= { error };\n }\n }\n if (failure) throw failure.error;\n}\n\nfunction resolveContext<TContext, TInput>(\n context: TContext | ((args: { input: TInput }) => TContext),\n input: TInput\n) {\n return typeof context === 'function'\n ? (context as (args: { input: TInput }) => TContext)({ input })\n : context;\n}\n\n/** @public */\nexport function createStepLogic<\n TContext,\n const TInputSchema extends StandardSchemaV1,\n const TOutputSchema extends StandardSchemaV1,\n TEvent extends EventObject = EventObject,\n TEmitted extends EventObject = EventObject\n>(\n config: StepLogicConfig<\n TContext,\n StandardSchemaV1.InferOutput<TOutputSchema>,\n TEvent,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted,\n TInputSchema,\n TOutputSchema\n > & {\n schemas: { input: TInputSchema; output: TOutputSchema };\n }\n): StepActorLogic<\n TContext,\n StandardSchemaV1.InferOutput<TOutputSchema>,\n TEvent,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted\n>;\nexport function createStepLogic<\n TContext,\n TOutput,\n const TInputSchema extends StandardSchemaV1,\n TEvent extends EventObject = EventObject,\n TEmitted extends EventObject = EventObject\n>(\n config: StepLogicConfig<\n TContext,\n TOutput,\n TEvent,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted,\n TInputSchema\n > & {\n schemas: { input: TInputSchema; output?: undefined };\n }\n): StepActorLogic<\n TContext,\n TOutput,\n TEvent,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted\n>;\nexport function createStepLogic<\n TContext,\n const TOutputSchema extends StandardSchemaV1,\n TEvent extends EventObject = EventObject,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n config: StepLogicConfig<\n TContext,\n StandardSchemaV1.InferOutput<TOutputSchema>,\n TEvent,\n TInput,\n TEmitted,\n StandardSchemaV1,\n TOutputSchema\n > & {\n schemas: { input?: undefined; output: TOutputSchema };\n }\n): StepActorLogic<\n TContext,\n StandardSchemaV1.InferOutput<TOutputSchema>,\n TEvent,\n TInput,\n TEmitted\n>;\nexport function createStepLogic<\n TContext,\n TOutput = unknown,\n TEvent extends EventObject = EventObject,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n config: StepLogicConfig<TContext, TOutput, TEvent, TInput, TEmitted>\n): StepActorLogic<TContext, TOutput, TEvent, TInput, TEmitted>;\nexport function createStepLogic<\n TContext,\n TOutput = unknown,\n TEvent extends EventObject = EventObject,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n config: StepLogicConfig<TContext, TOutput, TEvent, TInput, TEmitted>\n): StepActorLogic<TContext, TOutput, TEvent, TInput, TEmitted> {\n const calculateTransition = ((snapshot, event, actorScope) => {\n if (snapshot.status !== 'active') {\n return [snapshot, []];\n }\n\n if (event.type === XSTATE_STOP) {\n return [\n {\n ...snapshot,\n status: 'stopped',\n input: undefined\n },\n [\n createCustomEffect('@xstate.cleanup', () =>\n cleanupLogicEffects(actorScope.self)\n )\n ]\n ];\n }\n\n if (event.type === XSTATE_LOGIC_EFFECT_START) {\n return [\n {\n ...snapshot,\n effects: {\n ...snapshot.effects,\n [(event as any).key]: { status: 'active' }\n }\n },\n []\n ];\n }\n\n if (event.type === XSTATE_LOGIC_EFFECT_RESOLVE) {\n return [\n {\n ...snapshot,\n effects: {\n ...snapshot.effects,\n [(event as any).key]: {\n status: 'done',\n output: (event as any).output\n }\n }\n },\n []\n ];\n }\n\n if (event.type === XSTATE_LOGIC_EFFECT_REJECT) {\n return [\n {\n ...snapshot,\n effects: {\n ...snapshot.effects,\n [(event as any).key]: {\n status: 'error',\n error: (event as any).error\n }\n }\n },\n []\n ];\n }\n\n const effects: ExecutableEffect[] = [];\n const trackedEffects: Record<string, StepEffectState> = Object.create(null);\n const enqueueEffect = (\n key: string,\n exec: (runtime?: Partial<ActorSystemRuntime>) => void | (() => void)\n ) => {\n const recorded =\n snapshot.effects &&\n Object.prototype.hasOwnProperty.call(snapshot.effects, key)\n ? snapshot.effects[key]\n : undefined;\n // Active process-local attachments must be recreated on restore. A\n // completed effect remains memoized; ordinary events never reattach.\n if (\n recorded &&\n !(event.type === XSTATE_INIT && recorded.status === 'active')\n ) {\n return;\n }\n effects.push(\n createCustomEffect(\n '@xstate.effect',\n (runtime = actorScope.self.system) =>\n executeLogicEffect(actorScope.self, key, () => exec(runtime)),\n { key }\n )\n );\n trackedEffects[key] = { status: 'active' };\n };\n const enq: StepLogicEnqueue<TEvent, TEmitted> = {\n emit: (emitted) => {\n effects.push(createEmitEffect(actorScope, emitted));\n },\n sendBack: (sentEvent) => {\n const parent = actorScope.self._parent;\n if (parent) {\n effects.push(createSendToEffect(actorScope, parent, sentEvent));\n }\n },\n raise: (raisedEvent) => {\n effects.push(\n createSendToEffect(actorScope, actorScope.self, raisedEvent)\n );\n },\n effect: ((keyOrExec, maybeExec) => {\n if (typeof keyOrExec === 'string') {\n enqueueEffect(keyOrExec, maybeExec);\n return;\n }\n const exec = keyOrExec as (\n runtime?: Partial<ActorSystemRuntime>\n ) => void | (() => void);\n effects.push(\n createCustomEffect(\n '@xstate.effect',\n (runtime = actorScope.self.system) =>\n executeLogicEffect(actorScope.self, undefined, () =>\n exec(runtime)\n )\n )\n );\n }) as StepLogicEnqueue<TEvent, TEmitted>['effect']\n };\n\n const patch = config.run(\n {\n context: snapshot.context,\n event,\n input: snapshot.input!,\n system: actorScope.system,\n self: actorScope.self as any,\n emit: actorScope.emit\n } as StepLogicArgs<TContext, TEvent, TInput>,\n enq\n );\n\n const nextSnapshot = {\n ...snapshot,\n ...(patch || {})\n } as StepSnapshot<TContext, TOutput, TInput>;\n\n if ('context' in snapshot || patch?.context !== undefined) {\n (nextSnapshot as any).context = patch?.context ?? snapshot.context;\n }\n if (patch?.effects || Object.keys(trackedEffects).length) {\n (nextSnapshot as any).effects = {\n ...snapshot.effects,\n ...patch?.effects,\n ...trackedEffects\n };\n }\n\n return finalizeTransitionResult(actorScope, snapshot, [\n nextSnapshot,\n effects\n ]);\n }) as StepTransition<TContext, TOutput, TEvent, TInput, TEmitted>;\n\n const transition = ((snapshot, event, actorScope) => {\n if (config.validator) {\n const sourceRef = (actorScope.self as any)._lastSourceRef;\n const eventOrigin = sourceRef ? 'actor' : 'external';\n const error = config.validator.check({\n kind: 'event',\n logic,\n event,\n eventOrigin\n });\n if (error) {\n // Boundary fault: rejected (never delivered), not an actor error.\n return [\n snapshot,\n [\n createDeadLetterEffect(\n actorScope,\n sourceRef,\n event,\n 'invalidEvent',\n {\n issues: (error as { issues?: DeadLetterDetail['issues'] })\n .issues,\n error\n }\n )\n ]\n ];\n }\n }\n const result = calculateTransition(snapshot, event, actorScope);\n if (config.validator) {\n assertValid(config.validator, {\n kind: 'result',\n logic,\n snapshot: result[0],\n effects: result[1]\n });\n }\n return result;\n }) as StepTransition<TContext, TOutput, TEvent, TInput, TEmitted>;\n\n const logic: StepActorLogic<TContext, TOutput, TEvent, TInput, TEmitted> = {\n id: config.id,\n config,\n validator: config.validator,\n transition,\n start: (snapshot, actorScope, options) => {\n if (!options?.restored) {\n return;\n }\n const [nextSnapshot, effects] = transition(\n snapshot,\n createInitEvent(snapshot.input) as unknown as TEvent,\n actorScope\n );\n Object.assign(snapshot, nextSnapshot);\n for (const effect of effects) {\n actorScope.actionExecutor(effect);\n }\n },\n initialTransition: (input, actorScope) => {\n if (config.validator) {\n assertValid(config.validator, {\n kind: 'input',\n logic,\n input\n });\n }\n const context = resolveContext(config.context, input);\n const snapshot = {\n status: 'active' as const,\n output: undefined,\n error: undefined,\n input\n };\n\n if (context !== undefined) {\n (snapshot as any).context = context;\n }\n\n return transition(\n { ...snapshot } as StepSnapshot<TContext, TOutput, TInput>,\n createInitEvent(input) as unknown as TEvent,\n actorScope\n );\n },\n getInitialSnapshot: (actorScope, input) =>\n logic.initialTransition(input, actorScope)[0],\n getPersistedSnapshot: (snapshot) => snapshot,\n restoreSnapshot: (snapshot: any) => snapshot\n };\n\n return logic;\n}\n","import { createActor } from '../createActor.ts';\nimport type { ActorFromLogic } from '../types.ts';\nimport { createStepLogic } from './logic.ts';\nexport {\n createCallbackLogic,\n type CallbackActorLogic,\n type CallbackActorRef,\n type CallbackLogicConfig,\n type CallbackSnapshot,\n type CallbackLogicFunction\n} from './callback.ts';\nexport {\n createObservableLogic,\n createEventObservableLogic,\n type EventObservableLogicConfig,\n type EventObservableLogicFunction,\n type ObservableActorLogic,\n type ObservableActorRef,\n type ObservableLogicConfig,\n type ObservableLogicFunction,\n type ObservableSnapshot\n} from './observable.ts';\nexport {\n createStepLogic,\n type StepActorLogic,\n type StepActorRef,\n type StepLogicArgs,\n type StepLogicConfig,\n type StepEffectState,\n type StepLogicEnqueue,\n type StepLogicFunction,\n type StepPatch,\n type StepSnapshot\n} from './logic.ts';\nexport {\n createAsyncLogic,\n type AsyncActorLogic,\n type AsyncActorRef,\n type AsyncSnapshot,\n type AsyncLogicArgs,\n type AsyncLogicConfig,\n type AsyncLogicEnqueue,\n type AsyncLogicFunction,\n TimeoutError\n} from './promise.ts';\nexport {\n createListenerLogic,\n type ListenerActorLogic,\n type ListenerActorRef,\n type ListenerSnapshot,\n type ListenerInput\n} from './listener.ts';\nexport {\n createSubscriptionLogic,\n type SubscriptionActorLogic,\n type SubscriptionActorRef,\n type SubscriptionSnapshot,\n type SubscriptionInput,\n type SubscriptionMappers\n} from './subscription.ts';\n\nconst emptyLogic = /* #__PURE__ */ createStepLogic<undefined, undefined>({\n context: undefined,\n run: () => undefined\n});\n\n/** @public */\nexport function createEmptyActor(): ActorFromLogic<typeof emptyLogic> {\n return createActor(emptyLogic);\n}\n","import { AnyActorScope, createEmptyActor } from '../index.ts';\n\nexport function createMockActorScope(): AnyActorScope {\n const emptyActor = createEmptyActor();\n return {\n self: emptyActor,\n logger: console.log,\n id: '',\n sessionId: Math.random().toString(32).slice(2),\n defer: () => {},\n system: emptyActor.system, // TODO: mock system?\n stopChild: () => {},\n emit: () => {},\n actionExecutor: () => {}\n };\n}\n","import {\n EventObject,\n AnyStateMachine,\n StateNode,\n AnyActorLogic,\n EventFromLogic,\n Snapshot,\n InputFrom,\n SnapshotFrom,\n isMachineSnapshot\n} from '../index.ts';\nimport type {\n SerializedEvent,\n SerializedSnapshot,\n StatePath,\n DirectedGraphEdge,\n DirectedGraphNode,\n DirectedGraphDiagnostic,\n TraversalOptions,\n AnyStateNode,\n TraversalConfig\n} from './types.ts';\nimport { createMockActorScope } from './actorScope.ts';\nimport {\n getAllOwnEvents,\n matchesEvent,\n matchesEventDescriptor\n} from '../utils.ts';\n\n/**\n * Returns all state nodes of the given `node`.\n *\n * @public\n * @param stateNode State node to recursively get child state nodes from\n * @public\n */\nexport function getDescendantStateNodes(stateNode: {\n states: Record<string, AnyStateNode | StateNode<never, EventObject>>;\n}): AnyStateNode[] {\n const { states } = stateNode;\n const nodes = Object.keys(states).reduce((accNodes, stateKey) => {\n const childStateNode = states[stateKey] as AnyStateNode;\n const childStateNodes = getDescendantStateNodes(childStateNode);\n\n accNodes.push(childStateNode, ...childStateNodes);\n return accNodes;\n }, [] as AnyStateNode[]);\n\n return nodes;\n}\n\nfunction getChildren(stateNode: AnyStateNode): AnyStateNode[] {\n if (!stateNode.states) {\n return [];\n }\n\n const children = Object.keys(stateNode.states).map((key) => {\n return stateNode.states[key];\n });\n\n return children;\n}\n\n/** @public */\nexport function serializeSnapshot(snapshot: Snapshot<any>): SerializedSnapshot {\n const { value, context } = snapshot as any;\n const machineSnapshot = isMachineSnapshot(snapshot) ? snapshot : undefined;\n const inputs = machineSnapshot?.getInputs();\n const history = machineSnapshot?.historyValue;\n return JSON.stringify({\n value,\n context: Object.keys(context ?? {}).length ? context : undefined,\n // Equal values and root contexts can still make different decisions when\n // their state inputs or remembered history differ. Empty records remain\n // omitted to preserve the keys of machines that do not use these features.\n stateInputs: inputs && Object.keys(inputs).length ? inputs : undefined,\n historyValue:\n history && Object.keys(history).length\n ? Object.fromEntries(\n Object.entries(history).map(([id, nodes]) => [\n id,\n nodes.map((node) => node.id)\n ])\n )\n : undefined\n }) as SerializedSnapshot;\n}\n\nfunction serializeEvent<TEvent extends EventObject>(\n event: TEvent\n): SerializedEvent {\n return JSON.stringify(event) as SerializedEvent;\n}\n\nfunction resolveEventCases<TSnapshot>(\n cases: object,\n state: TSnapshot,\n defaults?: EventObject[]\n): EventObject[] {\n const events: EventObject[] = [];\n const sources = cases as Record<\n string,\n readonly object[] | ((state: TSnapshot) => readonly object[])\n >;\n const entries = Object.entries(sources).filter(\n ([, source]) => source !== undefined\n );\n const applicable = (type: string) =>\n !defaults ||\n defaults.some((event) => matchesEventDescriptor(type, event.type));\n for (const [type, source] of entries) {\n if (!applicable(type)) {\n continue;\n }\n const samples = typeof source === 'function' ? source(state) : source;\n if (!Array.isArray(samples) || !samples.length) {\n throw new Error(`Event cases for \"${type}\" must be a non-empty array`);\n }\n for (const payload of samples) {\n const event = { ...payload, type };\n if (\n !defaults ||\n defaults.some(\n ({ type: descriptor, ...pattern }) =>\n matchesEventDescriptor(type, descriptor) &&\n matchesEvent(event, pattern)\n )\n ) {\n events.push(event);\n }\n }\n }\n return [\n ...events,\n ...(defaults?.filter(\n (event) => !entries.some(([type]) => type === event.type)\n ) ?? [])\n ];\n}\n\nfunction createDefaultMachineOptions<TMachine extends AnyStateMachine>(\n machine: TMachine,\n options?: TraversalOptions<\n SnapshotFrom<TMachine>,\n EventFromLogic<TMachine>,\n InputFrom<TMachine>\n >\n): TraversalOptions<\n SnapshotFrom<TMachine>,\n EventFromLogic<TMachine>,\n InputFrom<TMachine>\n> {\n const traversalOptions: TraversalOptions<\n SnapshotFrom<TMachine>,\n EventFromLogic<TMachine>,\n InputFrom<TMachine>\n > = {\n serializeState: serializeSnapshot,\n serializeEvent,\n ...options,\n events: (state) => getAllOwnEvents(state) as EventFromLogic<TMachine>[],\n fromState:\n options?.fromState ??\n (machine.getInitialSnapshot(\n createMockActorScope(),\n options?.input\n ) as SnapshotFrom<TMachine>)\n };\n\n return traversalOptions;\n}\n\n/** @public */\nexport function toDirectedGraph(\n stateMachine: AnyStateNode | AnyStateMachine\n): DirectedGraphNode {\n const stateNode = (\n isMachineLogic(stateMachine) ? stateMachine.root : stateMachine\n ) as AnyStateNode; // TODO: accept only machines\n\n const diagnostics: DirectedGraphDiagnostic[] = [];\n const transitions = [\n ...[...stateNode.transitions.values()].flat(),\n ...(stateNode.always ?? [])\n ];\n const edges: DirectedGraphEdge[] = transitions.flatMap(\n (t, transitionIndex) => {\n if (t.to) {\n diagnostics.push({\n code: 'dynamic-target',\n stateId: stateNode.id,\n eventType: t.eventType,\n transitionId: `${stateNode.id}:${transitionIndex}`,\n message:\n 'Transition function destinations require execution or source analysis.'\n });\n }\n // A transition function computes its target when it runs, so there is\n // no static edge to draw; a targetless transition stays in its state.\n const targets = t.target ?? (t.to ? [] : [stateNode]);\n\n return targets.map((target, targetIndex) => {\n const edge: DirectedGraphEdge = {\n id: `${stateNode.id}:${transitionIndex}:${targetIndex}`,\n source: stateNode,\n target: target as AnyStateNode,\n transition: t,\n label: {\n text: t.eventType,\n toJSON: () => ({ text: t.eventType })\n },\n toJSON: () => {\n const { label } = edge;\n\n return { source: stateNode.id, target: target.id, label };\n }\n };\n\n return edge;\n });\n }\n );\n\n const children = getChildren(stateNode).map(toDirectedGraph);\n diagnostics.push(...children.flatMap((child) => child.analysis.diagnostics));\n const graph = {\n id: stateNode.id,\n stateNode: stateNode,\n children,\n edges,\n analysis: {\n transitionTargetsComplete: diagnostics.length === 0,\n diagnostics\n },\n toJSON: () => {\n const { id, children, edges: graphEdges } = graph;\n return { id, children, edges: graphEdges, analysis: graph.analysis };\n }\n };\n\n return graph;\n}\n\nfunction isMachineLogic(logic: unknown): logic is AnyStateMachine {\n if (!logic || typeof logic !== 'object') {\n return false;\n }\n\n const machine = logic as Partial<AnyStateMachine>;\n const root = machine.root as Partial<AnyStateNode> | undefined;\n\n return (\n !!root &&\n typeof root === 'object' &&\n typeof root.id === 'string' &&\n typeof root.states === 'object' &&\n typeof root.transitions?.values === 'function' &&\n typeof machine.getStateNodeById === 'function' &&\n typeof machine.resolveState === 'function' &&\n typeof machine.getTransitionData === 'function'\n );\n}\n\nexport function resolveTraversalOptions<TLogic extends AnyActorLogic>(\n logic: TLogic,\n traversalOptions?: TraversalOptions<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>,\n InputFrom<TLogic>\n >,\n defaultOptions?: TraversalOptions<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>,\n InputFrom<TLogic>\n >\n): TraversalConfig<SnapshotFrom<TLogic>, EventFromLogic<TLogic>> {\n const resolvedDefaultOptions =\n defaultOptions ??\n (isMachineLogic(logic)\n ? (createDefaultMachineOptions(\n logic,\n traversalOptions as any\n ) as TraversalOptions<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>,\n InputFrom<TLogic>\n >)\n : undefined);\n const serializeState =\n traversalOptions?.serializeState ??\n resolvedDefaultOptions?.serializeState ??\n ((state) => JSON.stringify(state));\n const eventSource =\n traversalOptions?.events ?? resolvedDefaultOptions?.events ?? [];\n const traversalConfig: TraversalConfig<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>\n > = {\n serializeState,\n serializeEvent,\n filterEvents: undefined,\n limit: Infinity,\n toState: undefined,\n // Traversal should not continue past the `toState` predicate\n // since the target state has already been reached at that point\n stopWhen: traversalOptions?.toState,\n ...resolvedDefaultOptions,\n ...traversalOptions,\n // Synthetic completion/delay events are supported by the machine runtime.\n events: (typeof eventSource === 'function' || Array.isArray(eventSource)\n ? eventSource\n : (state: SnapshotFrom<TLogic>) =>\n resolveEventCases(\n eventSource,\n state,\n isMachineSnapshot(state) ? getAllOwnEvents(state) : undefined\n )) as TraversalConfig<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>\n >['events'],\n fromState: traversalOptions?.fromState ?? resolvedDefaultOptions?.fromState\n };\n\n return traversalConfig;\n}\n\n/** @public */\nexport function joinPaths<\n TSnapshot extends Snapshot<unknown>,\n TEvent extends EventObject\n>(\n headPath: StatePath<TSnapshot, TEvent>,\n tailPath: StatePath<TSnapshot, TEvent>\n): StatePath<TSnapshot, TEvent> {\n const secondPathSource = tailPath.steps[0].state;\n\n if (secondPathSource !== headPath.state) {\n throw new Error(`Paths cannot be joined`);\n }\n\n return {\n state: tailPath.state,\n // e.g. [A, B, C] + [C, D, E] = [A, B, C, D, E]\n steps: headPath.steps.concat(tailPath.steps.slice(1)),\n weight: headPath.weight + tailPath.weight\n };\n}\n","export function createTraversalError(\n state: string,\n event: string,\n cause: unknown\n): Error {\n return new Error(\n `Unable to evaluate graph transition from state ${state} with event ${event}. If the transition needs event payloads, provide representative events using the \"events\" option.`,\n { cause }\n );\n}\n","import {\n ActorScope,\n ActorLogic,\n ActorSystem,\n EventObject,\n Snapshot,\n AnyActorLogic,\n SnapshotFrom,\n EventFromLogic\n} from '../index.ts';\nimport {\n SerializedEvent,\n SerializedSnapshot,\n TraversalOptions,\n AdjacencyMap,\n AdjacencyValue,\n EventCaseOptionsArgs,\n EventListOptions,\n TraversalEvent\n} from './types';\nimport { resolveTraversalOptions } from './graph.ts';\nimport { createMockActorScope } from './actorScope.ts';\nimport { createTraversalError } from './traversalError.ts';\n\nfunction resolveTransitionSnapshot<TSnapshot>(\n result: TSnapshot | [TSnapshot, unknown[]]\n): TSnapshot {\n return Array.isArray(result) ? result[0] : result;\n}\n\n/** @public */\nexport function getAdjacencyMap<TLogic extends AnyActorLogic>(\n logic: TLogic,\n ...[options]: EventCaseOptionsArgs<NoInfer<TLogic>>\n): AdjacencyMap<SnapshotFrom<TLogic>, EventFromLogic<TLogic>>;\nexport function getAdjacencyMap<\n TLogic extends AnyActorLogic,\n const TEvents extends readonly TraversalEvent<\n SnapshotFrom<NoInfer<TLogic>>,\n EventFromLogic<NoInfer<TLogic>>\n >[]\n>(\n logic: TLogic,\n options: EventListOptions<NoInfer<TLogic>, TEvents>\n): AdjacencyMap<SnapshotFrom<TLogic>, EventFromLogic<TLogic>>;\nexport function getAdjacencyMap<\n TSnapshot extends Snapshot<unknown>,\n TEvent extends EventObject,\n TInput,\n TSystem extends ActorSystem<any> = ActorSystem<any>\n>(\n logic: ActorLogic<TSnapshot, TEvent, TInput, TSystem>,\n options?: TraversalOptions<TSnapshot, TEvent, TInput>\n): AdjacencyMap<TSnapshot, TEvent> {\n 'use strict';\n const { transition } = logic;\n const {\n serializeEvent,\n serializeState,\n events: getEvents,\n filterEvents,\n limit,\n fromState: customFromState,\n stopWhen\n } = resolveTraversalOptions(logic, options);\n const actorScope = createMockActorScope() as ActorScope<\n TSnapshot,\n TEvent,\n TSystem\n >;\n const fromState =\n customFromState ??\n logic.getInitialSnapshot(\n actorScope,\n // TODO: fix this\n options?.input as TInput\n );\n\n const adj: AdjacencyMap<TSnapshot, TEvent> = Object.create(null);\n\n let iterations = 0;\n const queue: Array<{\n nextState: TSnapshot;\n event: TEvent | undefined;\n prevState: TSnapshot | undefined;\n }> = [{ nextState: fromState, event: undefined, prevState: undefined }];\n\n for (let head = 0; head < queue.length; head++) {\n const { nextState: state, event, prevState } = queue[head];\n // Release processed entries without shifting the remaining frontier.\n if (head > 4096 && head * 2 > queue.length) {\n queue.splice(0, head + 1);\n head = -1;\n }\n\n if (iterations++ > limit) {\n throw new Error('Traversal limit exceeded');\n }\n\n const serializedState = serializeState(\n state,\n event,\n prevState\n ) as SerializedSnapshot;\n if (adj[serializedState]) {\n continue;\n }\n\n adj[serializedState] = {\n state,\n transitions: Object.create(null)\n };\n\n if (stopWhen && stopWhen(state)) {\n continue;\n }\n\n const events =\n typeof getEvents === 'function' ? getEvents(state) : getEvents;\n\n for (const nextEvent of events) {\n if (filterEvents && !filterEvents(state, nextEvent)) {\n continue;\n }\n\n const serializedEvent = serializeEvent(nextEvent) as SerializedEvent;\n let nextSnapshot: TSnapshot;\n try {\n nextSnapshot = resolveTransitionSnapshot(\n transition(state, nextEvent, actorScope)\n );\n } catch (cause) {\n throw createTraversalError(serializedState, serializedEvent, cause);\n }\n\n adj[serializedState].transitions[serializedEvent] = {\n event: nextEvent,\n state: nextSnapshot\n };\n queue.push({\n nextState: nextSnapshot,\n event: nextEvent,\n prevState: state\n });\n }\n }\n\n return adj;\n}\n\n/** @public */\nexport function adjacencyMapToArray<TSnapshot, TEvent>(\n adjMap: AdjacencyMap<TSnapshot, TEvent>\n): Array<{\n state: TSnapshot;\n event: TEvent;\n nextState: TSnapshot;\n}> {\n const adjList: Array<{\n state: TSnapshot;\n event: TEvent;\n nextState: TSnapshot;\n }> = [];\n\n for (const adjValue of Object.values(adjMap)) {\n for (const transition of Object.values(\n (adjValue as AdjacencyValue<TSnapshot, TEvent>).transitions\n )) {\n adjList.push({\n state: (adjValue as AdjacencyValue<TSnapshot, TEvent>).state,\n event: transition.event,\n nextState: transition.state\n });\n }\n }\n\n return adjList;\n}\n","import { XSTATE_INIT } from '../constants.ts';\nimport { StatePath } from './types.ts';\n\n// TODO: rewrite parts of the algorithm leading to this to make this function obsolete\nexport function alterPath<T extends StatePath<any, any>>(path: T): T {\n let steps: T['steps'] = [];\n\n if (!path.steps.length) {\n steps = [\n {\n state: path.state,\n event: { type: XSTATE_INIT }\n }\n ];\n } else {\n for (let i = 0; i < path.steps.length; i++) {\n const step = path.steps[i];\n\n steps.push({\n state: step.state,\n event: i === 0 ? { type: XSTATE_INIT } : path.steps[i - 1].event\n });\n }\n steps.push({\n state: path.state,\n event: path.steps[path.steps.length - 1].event\n });\n }\n return {\n ...path,\n steps\n };\n}\n","import {\n ActorScope,\n ActorLogic,\n ActorSystem,\n EventObject,\n Snapshot\n} from '../index.ts';\nimport { StatePath, Steps, TraversalOptions, TraversalEvent } from './types.ts';\nimport { resolveTraversalOptions } from './graph.ts';\nimport { alterPath } from './alterPath.ts';\nimport { createMockActorScope } from './actorScope.ts';\nimport { createTraversalError } from './traversalError.ts';\n\n/** @public */\nexport function getPathsFromEvents<\n TSnapshot extends Snapshot<unknown>,\n TEvent extends EventObject,\n TInput,\n TSystem extends ActorSystem<any> = ActorSystem<any>\n>(\n logic: ActorLogic<TSnapshot, TEvent, TInput, TSystem>,\n events: TEvent[],\n options?: Omit<TraversalOptions<TSnapshot, TEvent, TInput>, 'events'> & {\n events?:\n | readonly TraversalEvent<TSnapshot, TEvent>[]\n | ((state: TSnapshot) => readonly TraversalEvent<TSnapshot, TEvent>[]);\n }\n): Array<StatePath<TSnapshot, TEvent>> {\n const resolvedOptions = resolveTraversalOptions(logic, {\n events,\n ...options\n });\n const actorScope = createMockActorScope() as ActorScope<\n TSnapshot,\n TEvent,\n TSystem\n >;\n const fromState =\n resolvedOptions.fromState ??\n logic.getInitialSnapshot(\n actorScope,\n // TODO: fix this\n options?.input as TInput\n );\n\n const { serializeState, serializeEvent, filterEvents, stopWhen, limit } =\n resolvedOptions;\n const steps: Steps<TSnapshot, TEvent> = [];\n let state = fromState;\n let stateSerial = serializeState(state, undefined, undefined);\n for (const event of events) {\n if (steps.length >= limit) {\n throw new Error('Traversal limit exceeded');\n }\n const eventSerial = serializeEvent(event);\n let nextEvent: TEvent | undefined = event;\n if (options?.events !== undefined) {\n const candidates =\n typeof options.events === 'function'\n ? options.events(state)\n : options.events;\n nextEvent = undefined;\n for (let index = candidates.length - 1; index >= 0; index--) {\n const candidate = candidates[index] as TEvent;\n if (\n (!filterEvents || filterEvents(state, candidate)) &&\n serializeEvent(candidate) === eventSerial\n ) {\n nextEvent = candidate;\n break;\n }\n }\n } else if (filterEvents && !filterEvents(state, event)) {\n nextEvent = undefined;\n }\n if (!nextEvent || stopWhen?.(state)) {\n throw new Error(\n `Invalid transition from ${stateSerial} with ${eventSerial}`\n );\n }\n steps.push({ state, event });\n let result: ReturnType<typeof logic.transition>;\n try {\n result = logic.transition(state, nextEvent, actorScope);\n } catch (cause) {\n throw createTraversalError(stateSerial, eventSerial, cause);\n }\n const nextState = Array.isArray(result) ? result[0] : result;\n stateSerial = serializeState(nextState, event, state);\n state = nextState;\n }\n\n // If it is expected to reach a specific state (`toState`) and that state\n // isn't reached, there are no paths\n if (resolvedOptions.toState && !resolvedOptions.toState(state)) {\n return [];\n }\n\n return [\n alterPath({\n state,\n steps,\n weight: steps.length\n })\n ];\n}\n","import {\n AnyActorLogic,\n EventFromLogic,\n InputFrom,\n SnapshotFrom\n} from '../index.ts';\nimport { getAdjacencyMap } from './adjacency.ts';\nimport { alterPath } from './alterPath.ts';\nimport { resolveTraversalOptions } from './graph.ts';\nimport {\n SerializedEvent,\n SerializedSnapshot,\n StatePath,\n StatePlanMap,\n EventCaseOptionsArgs,\n EventListOptions,\n TraversalEvent,\n TraversalOptions\n} from './types.ts';\nimport { createMockActorScope } from './actorScope.ts';\n\n/** @public */\nexport function getShortestPaths<TLogic extends AnyActorLogic>(\n logic: TLogic,\n ...[options]: EventCaseOptionsArgs<NoInfer<TLogic>>\n): Array<StatePath<SnapshotFrom<TLogic>, EventFromLogic<TLogic>>>;\nexport function getShortestPaths<\n TLogic extends AnyActorLogic,\n const TEvents extends readonly TraversalEvent<\n SnapshotFrom<NoInfer<TLogic>>,\n EventFromLogic<NoInfer<TLogic>>\n >[]\n>(\n logic: TLogic,\n options: EventListOptions<NoInfer<TLogic>, TEvents>\n): Array<StatePath<SnapshotFrom<TLogic>, EventFromLogic<TLogic>>>;\nexport function getShortestPaths<TLogic extends AnyActorLogic>(\n logic: TLogic,\n options?: TraversalOptions<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>,\n InputFrom<TLogic>\n >\n): Array<StatePath<SnapshotFrom<TLogic>, EventFromLogic<TLogic>>> {\n type TInternalState = SnapshotFrom<TLogic>;\n type TEvent = EventFromLogic<TLogic>;\n\n const resolvedOptions = resolveTraversalOptions(logic, options);\n const serializeState = resolvedOptions.serializeState as (\n ...args: Parameters<typeof resolvedOptions.serializeState>\n ) => SerializedSnapshot;\n const fromState =\n resolvedOptions.fromState ??\n logic.getInitialSnapshot(createMockActorScope(), options?.input);\n const adjacency = getAdjacencyMap(logic, { ...resolvedOptions, fromState });\n\n // weight, state, event\n const weightMap = new Map<\n SerializedSnapshot,\n {\n weight: number;\n state: SerializedSnapshot | undefined;\n event: TEvent | undefined;\n }\n >();\n const stateMap = new Map<SerializedSnapshot, TInternalState>();\n const serializedFromState = serializeState(fromState, undefined, undefined);\n stateMap.set(serializedFromState, fromState);\n\n weightMap.set(serializedFromState, {\n weight: 0,\n state: undefined,\n event: undefined\n });\n const unvisited = new Set<SerializedSnapshot>();\n const visited = new Set<SerializedSnapshot>();\n\n unvisited.add(serializedFromState);\n for (const serializedState of unvisited) {\n const prevState = stateMap.get(serializedState);\n const { weight } = weightMap.get(serializedState)!;\n for (const event of Object.keys(\n adjacency[serializedState].transitions\n ) as SerializedEvent[]) {\n const { state: nextState, event: eventObject } =\n adjacency[serializedState].transitions[event];\n const nextSerializedState = serializeState(\n nextState,\n eventObject,\n prevState\n );\n stateMap.set(nextSerializedState, nextState);\n if (!weightMap.has(nextSerializedState)) {\n weightMap.set(nextSerializedState, {\n weight: weight + 1,\n state: serializedState,\n event: eventObject\n });\n } else {\n const { weight: nextWeight } = weightMap.get(nextSerializedState)!;\n if (nextWeight > weight + 1) {\n weightMap.set(nextSerializedState, {\n weight: weight + 1,\n state: serializedState,\n event: eventObject\n });\n }\n }\n if (!visited.has(nextSerializedState)) {\n unvisited.add(nextSerializedState);\n }\n }\n visited.add(serializedState);\n unvisited.delete(serializedState);\n }\n\n const statePlanMap: StatePlanMap<TInternalState, TEvent> =\n Object.create(null);\n const paths: Array<StatePath<TInternalState, TEvent>> = [];\n\n weightMap.forEach(\n ({ weight, state: fromState, event: fromEvent }, stateSerial) => {\n const state = stateMap.get(stateSerial)!;\n const steps =\n fromState === undefined\n ? []\n : statePlanMap[fromState].paths[0].steps.concat({\n state: stateMap.get(fromState)!,\n event: fromEvent!\n });\n\n paths.push({\n state,\n steps,\n weight\n });\n statePlanMap[stateSerial] = {\n state,\n paths: [\n {\n state,\n steps,\n weight\n }\n ]\n };\n }\n );\n\n if (resolvedOptions.toState) {\n return paths\n .filter((path) => resolvedOptions.toState!(path.state))\n .map(alterPath);\n }\n\n return paths.map(alterPath);\n}\n","import {\n AnyActorLogic,\n EventFromLogic,\n InputFrom,\n SnapshotFrom\n} from '../index.ts';\nimport {\n SerializedEvent,\n SerializedSnapshot,\n StatePath,\n Steps,\n EventCaseOptionsArgs,\n EventListOptions,\n TraversalEvent,\n TraversalOptions,\n VisitedContext\n} from './types.ts';\nimport { resolveTraversalOptions } from './graph.ts';\nimport { getAdjacencyMap } from './adjacency.ts';\nimport { alterPath } from './alterPath.ts';\nimport { createMockActorScope } from './actorScope.ts';\n\n/** @public */\nexport function getSimplePaths<TLogic extends AnyActorLogic>(\n logic: TLogic,\n ...[options]: EventCaseOptionsArgs<NoInfer<TLogic>>\n): Array<StatePath<SnapshotFrom<TLogic>, EventFromLogic<TLogic>>>;\nexport function getSimplePaths<\n TLogic extends AnyActorLogic,\n const TEvents extends readonly TraversalEvent<\n SnapshotFrom<NoInfer<TLogic>>,\n EventFromLogic<NoInfer<TLogic>>\n >[]\n>(\n logic: TLogic,\n options: EventListOptions<NoInfer<TLogic>, TEvents>\n): Array<StatePath<SnapshotFrom<TLogic>, EventFromLogic<TLogic>>>;\nexport function getSimplePaths<TLogic extends AnyActorLogic>(\n logic: TLogic,\n options?: TraversalOptions<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>,\n InputFrom<TLogic>\n >\n): Array<StatePath<SnapshotFrom<TLogic>, EventFromLogic<TLogic>>> {\n type TState = SnapshotFrom<TLogic>;\n type TEvent = EventFromLogic<TLogic>;\n\n const resolvedOptions = resolveTraversalOptions(logic, options);\n const actorScope = createMockActorScope();\n const fromState =\n resolvedOptions.fromState ??\n logic.getInitialSnapshot(actorScope, options?.input);\n const serializeState = resolvedOptions.serializeState as (\n ...args: Parameters<typeof resolvedOptions.serializeState>\n ) => SerializedSnapshot;\n const adjacency = getAdjacencyMap(logic, { ...resolvedOptions, fromState });\n const stateMap = new Map<SerializedSnapshot, TState>();\n const visitCtx: VisitedContext<TState, TEvent> = {\n vertices: new Set(),\n edges: new Set()\n };\n const steps: Steps<TState, TEvent> = [];\n const pathMap: Record<\n SerializedSnapshot,\n { state: TState; paths: Array<StatePath<TState, TEvent>> }\n > = Object.create(null);\n\n function util(\n fromStateSerial: SerializedSnapshot,\n toStateSerial: SerializedSnapshot\n ) {\n const fromState = stateMap.get(fromStateSerial)!;\n visitCtx.vertices.add(fromStateSerial);\n\n if (fromStateSerial === toStateSerial) {\n if (!pathMap[toStateSerial]) {\n pathMap[toStateSerial] = {\n state: stateMap.get(toStateSerial)!,\n paths: []\n };\n }\n\n const toStatePlan = pathMap[toStateSerial];\n\n const path2: StatePath<TState, TEvent> = {\n state: fromState,\n weight: steps.length,\n steps: [...steps]\n };\n\n toStatePlan.paths.push(path2);\n } else {\n if (!adjacency[fromStateSerial]) {\n return;\n }\n for (const serializedEvent of Object.keys(\n adjacency[fromStateSerial].transitions\n ) as SerializedEvent[]) {\n const { state: nextState, event: subEvent } =\n adjacency[fromStateSerial].transitions[serializedEvent];\n\n if (!(serializedEvent in adjacency[fromStateSerial].transitions)) {\n continue;\n }\n const prevState = stateMap.get(fromStateSerial);\n\n const nextStateSerial = serializeState(nextState, subEvent, prevState);\n stateMap.set(nextStateSerial, nextState);\n\n if (!visitCtx.vertices.has(nextStateSerial)) {\n visitCtx.edges.add(serializedEvent);\n steps.push({\n state: stateMap.get(fromStateSerial)!,\n event: subEvent\n });\n util(nextStateSerial, toStateSerial);\n }\n }\n }\n\n steps.pop();\n visitCtx.vertices.delete(fromStateSerial);\n }\n\n const fromStateSerial = serializeState(fromState, undefined);\n stateMap.set(fromStateSerial, fromState);\n\n for (const nextStateSerial of Object.keys(\n adjacency\n ) as SerializedSnapshot[]) {\n util(fromStateSerial, nextStateSerial);\n }\n\n const simplePaths = Object.values(pathMap).flatMap((p) => p.paths);\n\n if (resolvedOptions.toState) {\n return simplePaths\n .filter((path) => resolvedOptions.toState!(path.state))\n .map(alterPath);\n }\n\n return simplePaths.map(alterPath);\n}\n"],"names":["xstateError","code","values","length","map","value","JSON","stringify","String","join","ACTOR_OPTIONS","Set","XSTATE_INIT","XSTATE_STOP","XSTATE_TERMINATE","XSTATE_TIMER","XSTATE_LOGIC_EFFECT_RESOLVE","XSTATE_LOGIC_EFFECT_REJECT","XSTATE_LOGIC_EFFECT_START","isSerializedActorRef","target","Array","isArray","key","incarnation","undefined","getAddressId","address","segment","slice","lastIndexOf","includes","replaceAll","createMissingAddressError","Error","resolveSerializedActorRef","system","live","_getByAddress","sessionId","publishEmittedEvent","source","event","runtime","_notifyEmitted","emitEvent","Object","freeze","status","output","error","pendingSteps","WeakMap","async","runStep","actor","exec","sendSelf","sendEvent","effect","effects","getSnapshot","prototype","hasOwnProperty","call","getStepEffect","running","get","resolve","reject","promise","Promise","resolvePromise","rejectPromise","subscription","steps","Map","set","cleanup","unsubscribe","delete","size","then","subscribe","complete","type","catch","rejectUndeliverableEvent","runtimeTarget","logic","isInternalEventType","id","getEventBoundaryError","deadLetter","Mailbox","constructor","_process","this","_active","_current","_last","start","flush","clear","next","enqueue","enqueued","consumed","createInitEvent","input","reportUnhandledError","err","setTimeout","symbolObservable","Symbol","observable","selectionFrames","transitionEffectSignal","getBuiltInTimerIdentity","stateId","delay","actorId","getTimerKey","timer","seq","getScheduledTimerKey","serializeTimerKey","execEmitEffect","execDeadLetterEffect","reason","detail","createDeadLetterEffect","actorScope","kind","self","params","args","createCustomEffect","action","execTerminateEffect","termination","terminateActor","execSendToEffect","assertSendToEvent","scheduleTimer","createSendToEffect","createTerminationEffect","snapshot","finalizeTransitionResult","previousSnapshot","nextSnapshot","becameTerminal","wasTerminal","hasTerminationEffect","some","snapshotActorRefs","lazySnapshotActorRefs","emptyKeyedActors","markSystemSnapshotDirty","_snapshotVersion","getSystemSnapshotVersion","getSnapshotActorRef","existing","create","created","setSnapshotActorRef","baseSystem","sourceVersion","previousRef","reusableRef","systemState","sourceSystem","capturedActors","root","_getRootActor","peekedChildren","_peekChildren","children","captureRegisteredActors","baseKeyedActors","peek","_peekKeyedActors","keyedActors","getKeyedActors","child","getSnapshotChildren","registryKey","_snapshot","isMachineSnapshot","toObserver","nextHandler","errorHandler","completionHandler","isObserver","bind","passive","getAllOwnEvents","events","nodes","flatMap","stateNode","transitions","transition","eventType","matches","filter","index","findIndex","candidate","keys","every","is","matchesEvent","pattern","entries","matchesEventDescriptor","descriptor","endsWith","partialEventTokens","split","eventTokens","tokenIndex","partialEventToken","eventToken","executionIdPrefix","nextExecutionId","createExecutionId","crypto","globalThis","getRandomValues","Uint32Array","from","toString","padStart","randomUUID","Date","now","Math","random","createExecutionIdPrefix","encodeAddressSegment","getActorIdCounterKey","parent","prefix","bumpActorIdCounter","counterKey","counters","_nextActorIds","resolveActorId","requestedId","options","generated","separator","Number","isSafeInteger","parseGeneratedActorId","src","logicId","getActorIdPrefix","counter","emptyScheduledTimers","createScheduledTimerId","findLogicalTimer","timers","find","field","matchesTimerKey","RuntimeSystem","_children","_rootActor","_isRunning","_keyedActors","actors","reverseKeyedActors","_reverseKeyedActors","_identity","executionId","nextSessionId","scheduler","_clock","_logger","createActorRef","clock","logger","ambientInspector","getAmbientInspector","_scheduledTimers","_recordSent","_inspectionObservers","inspectionSource","_inTransition","_collectedSent","push","targetRef","targetId","schedule","scheduledTimerId","_timerMap","cancel","scheduledAt","scheduledTimer","dueAt","timeout","_deliver","clearTimeout","cancelAll","serialized","_send","deliverEvent","_register","_unregister","changed","getAll","fromEntries","_set","inspect","observerOrFn","observer","add","onRejectedEvent","listener","entry","rejection","_rejectionListeners","onEmitted","emission","_emissionListeners","actorRef","listeners","_hasInspectionObservers","_sendInspectionEvent","resolvedInspectionEvent","rootId","forEach","spawnActor","startActor","override","stopActor","_stop","stopActorLocally","_terminate","terminateActorLocally","_emit","sourceRef","eventOrigin","issues","runLogic","cancelTimer","cancelAllTimers","_relay","matched","abort","frame","requiresReevaluation","mode","protectSelectionRelay","scheduledTimers","resetScheduledTimers","scheduledId","max","executingCustomAction","emptyInspectionRecords","reservedMachineEventTypes","ProcessingStatus","defaultOptions","fn","ms","console","log","safeCall","arg","executeExecutableEffects","actionExecutor","Actor","_address","_parent","trigger","_trigger","Proxy","_","payload","send","_boundSend","_sendPublic","_boundProcess","mailbox","_mailboxStarted","observers","_errorObserved","eventListeners","_processingStatus","NotStarted","_forceDeferredActions","_syncSnapshot","ref","_actorScope","_lastSourceRef","_collectedMicrosteps","_collectedActions","_initialEffects","_deferred","_restored","_warnedUnhandledTypes","resolvedOptions","syncSnapshot","_systemRef","current","rootActor","createRuntimeSystem","initialize","_sessionId","restore","_restore","_setSnapshot","_inert","initialTransition","parentRef","_getLogger","defer","_defer","defineProperty","stopChild","_stopChild","emit","_executeAction","Running","saveExecutingCustomAction","result","Stopped","_recoverOrError","_setErrorSnapshot","_tryHandleExecutionError","_error","errorEvent","getExecutionErrorEvent","inTransition","update","_next","deferred","i","deferredFn","_inspectTransition","microsteps","actions","sent","_flushInitialEffects","nextListenerOrObserver","errorListener","completeListener","on","handler","select","selector","equalityFn","selected","_start","_stopProcedure","_complete","restored","refreshSnapshotActorRefRoot","wallClock","min","item","_processEvent","nextState","caughtError","hasOwn","_reportUnhandledEvent","onUnhandledEvent","invokeId","stop","_reportUnlessObserved","snapshotChildren","reportError","handled","toJSON","getPersistedSnapshot","createActor","has","diagnoseActorOptions","assertValid","validator","request","check","effectStates","executeLogicEffect","state","getEffectState","createStepLogic","config","calculateTransition","failure","cleanupLogicEffects","trackedEffects","enq","emitted","createEmitEffect","sendBack","sentEvent","raise","raisedEvent","keyOrExec","maybeExec","enqueueEffect","recorded","patch","run","context","assign","resolveContext","getInitialSnapshot","restoreSnapshot","emptyLogic","createMockActorScope","emptyActor","serializeSnapshot","machineSnapshot","inputs","getInputs","history","historyValue","stateInputs","node","serializeEvent","isMachineLogic","machine","states","getStateNodeById","resolveState","getTransitionData","resolveTraversalOptions","traversalOptions","resolvedDefaultOptions","serializeState","fromState","eventSource","filterEvents","limit","Infinity","toState","stopWhen","cases","defaults","sources","applicable","samples","resolveEventCases","createTraversalError","cause","resolveTransitionSnapshot","getAdjacencyMap","getEvents","customFromState","adj","iterations","queue","prevState","head","splice","serializedState","nextEvent","serializedEvent","alterPath","path","step","adjMap","adjList","adjValue","getDescendantStateNodes","reduce","accNodes","stateKey","childStateNode","childStateNodes","stateSerial","eventSerial","candidates","weight","adjacency","weightMap","stateMap","serializedFromState","unvisited","visited","eventObject","nextSerializedState","nextWeight","statePlanMap","paths","fromEvent","concat","visitCtx","vertices","edges","pathMap","util","fromStateSerial","toStateSerial","toStatePlan","path2","subEvent","nextStateSerial","pop","simplePaths","p","headPath","tailPath","toDirectedGraph","stateMachine","diagnostics","flat","always","t","transitionIndex","to","transitionId","message","targetIndex","edge","label","text","getChildren","analysis","graph","transitionTargetsComplete","graphEdges"],"mappings":"kPAOO,SAASA,EAAYC,KAAiBC,GAC3C,MAAO,iBAAiBD,IACtBC,EAAOC,OACH,KAAKD,EACFE,IAAKC,GACa,iBAAVA,EAAqBC,KAAKC,UAAUF,GAASG,OAAOH,IAE5DI,KAAK,SACR,yEACiER,GACzE,CCuQA,MAAMS,EAAgB,IAAIC,IAAI,CAC5B,QACA,SACA,eACA,KACA,cACA,QACA,MACA,UACA,kBACA,mBACA,aACA,aACA,SACA,aClSK,MACMC,EAAc,cAIdC,EAAc,cAGdC,EAAmB,oBACnBC,EAAe,eAEfC,EAA8B,8BAC9BC,EAA6B,6BAC7BC,EAA4B,4BCQlC,SAASC,EACdC,GAEA,GACoB,iBAAXA,GACI,OAAXA,GACAC,MAAMC,QAAQF,IACsC,iBAA5CA,EAA8B,UAEtC,OAAO,EAET,IAAK,MAAMG,KAAOH,EAChB,GAAY,WAARG,GAA4B,gBAARA,EACtB,OAAO,EAGX,MAAMC,EAAeJ,EAA8BI,YACnD,YAAuBC,IAAhBD,GAAoD,iBAAhBA,CAC7C,CAGO,SAASE,EAAaC,GAC3B,MAAMC,EAAUD,EAAQE,MAAMF,EAAQG,YAAY,KAAO,GACzD,OAAOF,EAAQG,SAAS,KACpBH,EAAQI,WAAW,MAAO,KAAKA,WAAW,MAAO,KACjDJ,CACN,CAGO,SAASK,EAA0Bb,GACxC,OAAO,IAAIc,MAELlC,EACE,WAC2ByB,IAAvBL,EAAOI,YACP,CAACJ,EAAO,WACR,CAACA,EAAO,UAAWA,EAAOI,cAMxC,CAOO,SAASW,EACdC,EACAhB,GAEA,MAAMiB,EAAOD,EAAOE,gBAAgBlB,EAAO,WAC3C,OAAOiB,QACmBZ,IAAvBL,EAAOI,aAA6Ba,EAAKE,YAAcnB,EAAOI,iBAE7DC,EADAY,CAEN,CC5DO,SAAS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