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-persist.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/timerClock.ts","../src/actions.ts","../src/actorSource.ts","../src/systemLogicMetadata.ts","../src/actors/attached.ts","../src/actors/listener.ts","../src/actors/subscription.ts","../src/transitionActions.ts","../src/snapshotActorRef.ts","../src/actorScope.ts","../src/inertActorScope.ts","../src/stateUtils.ts","../src/delay.ts","../src/utils.ts","../src/State.ts","../src/system.ts","../src/createActor.ts","../src/persistedSnapshotValidation.ts","../src/memo.ts","../src/StateNode.ts","../src/validation.ts","../src/StateMachine.ts","../src/spawn.ts","../src/machineSchemas.ts","../src/persist/index.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 type { LogicalTimer } from './types.ts';\n\n// Runtime metadata stays outside pure snapshots. Timer objects survive unrelated\n// transitions; a cancelled/replaced timer gets a new object and a new deadline.\nconst starts = new WeakMap<LogicalTimer, number>();\n\n/** @internal */\nexport function getTimerStart(timer: LogicalTimer): number | undefined {\n return starts.get(timer) ?? timer.scheduledAt;\n}\n\n/** @internal */\nexport function recordTimerStart(\n timer: LogicalTimer,\n scheduledAt: number\n): void {\n starts.set(timer, scheduledAt);\n}\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 type { AnyActorLogic } from './types.ts';\n\nconst sourceKeyCaches = new WeakMap<object, Map<AnyActorLogic, string>>();\n\n/** @internal */\nexport function resolveRegisteredActorSource(\n actors: Record<string, AnyActorLogic>,\n logic: AnyActorLogic\n): string | undefined {\n let cache = sourceKeyCaches.get(actors);\n if (!cache) {\n cache = new Map();\n for (const key of Object.keys(actors)) {\n const registeredLogic = actors[key];\n // Several source keys may intentionally share one implementation. The\n // first key is its canonical persistence identity when spawning by the\n // raw logic value, which cannot retain which alias was used to access it.\n if (!cache.has(registeredLogic)) {\n cache.set(registeredLogic, key);\n }\n }\n sourceKeyCaches.set(actors, cache);\n }\n\n return cache.get(logic);\n}\n","/** Static scheduling metadata on actor definitions, never on live actors. @internal */\nexport const systemLogicMetadata = Symbol('xstate.systemLogicMetadata');\n","import { XSTATE_STOP } from '../constants.ts';\nimport { systemLogicMetadata } from '../systemLogicMetadata.ts';\nimport type { AnyActorSystem } from '../system.ts';\nimport type {\n AnyActor,\n EventObject,\n Snapshot,\n Subscription\n} from '../types.ts';\n\nconst subscriptions = /* #__PURE__ */ new WeakMap<AnyActor, Subscription>();\n\n/**\n * Internal factory for actor logic that attaches to another actor on start\n * (`enq.listen()` / `enq.subscribeTo()`) and detaches when stopped.\n */\nexport function createAttachedLogic(\n attach: (\n input: any,\n scope: { self: AnyActor; system: AnyActorSystem }\n ) => Subscription | undefined,\n /**\n * Names the logic so its generated actor ids get their own prefix, out of\n * the id space that user sources allocate from.\n */\n id?: string\n): any {\n const initialTransition = (input: unknown, _: unknown) =>\n [\n {\n status: 'active',\n output: undefined,\n error: undefined,\n input\n },\n []\n ] as const;\n\n const logic = {\n id,\n start: (state: any, { self, system }: any) => {\n // Don't attach if the target doesn't exist or is stopped.\n const target = state.input.actor;\n if (!target || target.getSnapshot().status === 'stopped') {\n return;\n }\n const subscription = attach(state.input, { self, system });\n if (!subscription) {\n return;\n }\n\n // Attached actors are not registered as children (their `input` holds\n // non-serializable function mappers), so a parent stop does not cascade\n // to them. Subscribe to the parent and tear down when it stops/errors,\n // so the subscription never relays to a stopped parent or leaks the\n // source subscription.\n let parentSubscription: Subscription | undefined;\n let torndown = false;\n const teardown = () => {\n if (torndown) {\n return;\n }\n torndown = true;\n subscription.unsubscribe();\n parentSubscription?.unsubscribe();\n };\n\n const parent: AnyActor | undefined = self._parent;\n if (parent) {\n parentSubscription = parent.subscribe({\n complete: teardown,\n error: teardown\n });\n }\n\n subscriptions.set(self, { unsubscribe: teardown });\n },\n transition: (state: any, event: EventObject, { self }: any) => {\n if (event.type === XSTATE_STOP) {\n subscriptions.get(self)?.unsubscribe();\n subscriptions.delete(self);\n return [\n {\n ...state,\n status: 'stopped',\n error: undefined\n },\n []\n ];\n }\n return [state, []];\n },\n initialTransition,\n getInitialSnapshot: (actorScope: unknown, input: unknown) =>\n initialTransition(input, actorScope)[0],\n getPersistedSnapshot: (snapshot: Snapshot<unknown>) => snapshot,\n restoreSnapshot: (snapshot: Snapshot<unknown>) => snapshot\n };\n Object.defineProperty(logic, systemLogicMetadata, { value: { kind: id } });\n return logic;\n}\n\n/**\n * Relays a mapped event to the attached actor's parent, unless the attached\n * actor has been stopped (the mapper is not called in that case).\n */\nexport function relayMappedToParent(\n self: AnyActor,\n system: AnyActorSystem,\n getEvent: () => EventObject\n): void {\n if (self.getSnapshot().status === 'stopped' || !self._parent) {\n return;\n }\n system._relay(self, self._parent, getEvent());\n}\n","import { AnyActorSystem } from '../system.ts';\nimport { matchesEventDescriptor } from '../utils.ts';\nimport {\n ActorLogic,\n ActorRefFrom,\n AnyActor,\n EventObject,\n Snapshot\n} from '../types';\nimport { createAttachedLogic, relayMappedToParent } from './attached.ts';\n\n/** @public */\nexport type ListenerSnapshot = Snapshot<undefined> & {\n input: ListenerInput<any, any>;\n};\n\n/** @public */\nexport interface ListenerInput<\n TEmitted extends EventObject,\n TMappedEvent extends EventObject\n> {\n actor: AnyActor;\n eventType: string;\n mapper: (event: TEmitted) => TMappedEvent;\n}\n\n/** @public */\nexport type ListenerActorLogic<\n TEmitted extends EventObject = EventObject,\n TMappedEvent extends EventObject = EventObject\n> = ActorLogic<\n ListenerSnapshot,\n EventObject,\n ListenerInput<TEmitted, TMappedEvent>,\n AnyActorSystem,\n EventObject\n>;\n\n/** @public */\nexport type ListenerActorRef<\n TEmitted extends EventObject = EventObject,\n TMappedEvent extends EventObject = EventObject\n> = ActorRefFrom<ListenerActorLogic<TEmitted, TMappedEvent>>;\n\n/**\n * Creates actor logic for listening to emitted events from another actor. Used\n * internally by `enq.listen()`.\n *\n * @public\n */\nexport function createListenerLogic<\n TEmitted extends EventObject = EventObject,\n TMappedEvent extends EventObject = EventObject\n>(): ListenerActorLogic<TEmitted, TMappedEvent> {\n return createAttachedLogic(\n (\n { actor, eventType, mapper }: ListenerInput<TEmitted, TMappedEvent>,\n { self, system }\n ) => {\n // Determine the subscription type:\n // - For exact matches or '*', subscribe directly\n // - For partial wildcards ('data.*'), subscribe to '*' and filter\n const isPartialWildcard = eventType !== '*' && eventType.endsWith('.*');\n\n return actor.on(isPartialWildcard ? '*' : eventType, (emittedEvent) => {\n if (\n isPartialWildcard &&\n !matchesEventDescriptor(emittedEvent.type, eventType)\n ) {\n return;\n }\n relayMappedToParent(self, system, () =>\n mapper(emittedEvent as TEmitted)\n );\n });\n },\n '@xstate.listener'\n );\n}\n\n/** @internal The logic of helper actors created by `enq.listen()`. */\nexport const listenerLogic = /* #__PURE__ */ createListenerLogic();\n","import { AnyActorSystem } from '../system.ts';\nimport {\n ActorLogic,\n ActorRefFrom,\n AnyActorRef,\n EventObject,\n Snapshot\n} from '../types';\nimport { createAttachedLogic, relayMappedToParent } from './attached.ts';\n\n/** @public */\nexport type SubscriptionSnapshot = Snapshot<undefined> & {\n input: SubscriptionInput<any, any, any, any>;\n};\n\n/** @public */\nexport interface SubscriptionMappers<\n TSnapshot extends Snapshot<unknown>,\n TOutput,\n TMappedEvent extends EventObject\n> {\n snapshot?: (snapshot: TSnapshot) => TMappedEvent;\n done?: (output: TOutput) => TMappedEvent;\n error?: (error: unknown) => TMappedEvent;\n}\n\n/** @public */\nexport interface SubscriptionInput<\n TSnapshot extends Snapshot<unknown>,\n TOutput,\n TMappedEvent extends EventObject,\n TMappers extends SubscriptionMappers<TSnapshot, TOutput, TMappedEvent>\n> {\n actor: AnyActorRef;\n mappers: TMappers;\n}\n\n/** @public */\nexport type SubscriptionActorLogic<\n TSnapshot extends Snapshot<unknown> = Snapshot<unknown>,\n TOutput = unknown,\n TMappedEvent extends EventObject = EventObject\n> = ActorLogic<\n SubscriptionSnapshot,\n EventObject,\n SubscriptionInput<\n TSnapshot,\n TOutput,\n TMappedEvent,\n SubscriptionMappers<TSnapshot, TOutput, TMappedEvent>\n >,\n AnyActorSystem,\n EventObject\n>;\n\n/** @public */\nexport type SubscriptionActorRef<\n TSnapshot extends Snapshot<unknown> = Snapshot<unknown>,\n TOutput = unknown,\n TMappedEvent extends EventObject = EventObject\n> = ActorRefFrom<SubscriptionActorLogic<TSnapshot, TOutput, TMappedEvent>>;\n\n/**\n * Creates actor logic for subscribing to lifecycle events (done/error/snapshot)\n * from another actor. Used internally by `enq.subscribeTo()`.\n *\n * @public\n */\nexport function createSubscriptionLogic<\n TSnapshot extends Snapshot<unknown> = Snapshot<unknown>,\n TOutput = unknown,\n TMappedEvent extends EventObject = EventObject\n>(): SubscriptionActorLogic<TSnapshot, TOutput, TMappedEvent> {\n return createAttachedLogic(({ actor, mappers }, { self, system }) => {\n const { done, error, snapshot: onSnapshot } = mappers;\n\n return actor.subscribe({\n next: (snapshot: TSnapshot) => {\n if (snapshot.status === 'done' && done) {\n relayMappedToParent(self, system, () =>\n done(snapshot.output as TOutput)\n );\n } else if (snapshot.status === 'error' && error) {\n relayMappedToParent(self, system, () => error(snapshot.error));\n } else if (snapshot.status === 'active' && onSnapshot) {\n relayMappedToParent(self, system, () => onSnapshot(snapshot));\n }\n },\n error: (err: unknown) => {\n if (error) {\n relayMappedToParent(self, system, () => error(err));\n }\n },\n complete: () => {\n // Actor completed without output (stopped); no action needed\n }\n });\n }, '@xstate.subscription');\n}\n\n/** @internal The logic of helper actors created by `enq.subscribeTo()`. */\nexport const subscriptionLogic = /* #__PURE__ */ createSubscriptionLogic();\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 { 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 type { AnyActor, AnyActorScope } from './types.ts';\n\n/** Marks the internal lazy scope without imposing structure on custom runtimes. @internal */\nexport const lazyActorScope = Symbol();\n\ntype InternalActorScope = AnyActorScope & {\n _parent?: AnyActor;\n [lazyActorScope]?: true;\n};\n\n/** Whether actor capabilities are represented by a lazy pure-transition scope. @internal */\nexport function isLazyActorScope(actorScope: AnyActorScope): boolean {\n return !!(actorScope as InternalActorScope)[lazyActorScope];\n}\n\n/** Reads parent metadata without otherwise touching actor capabilities. @internal */\nexport function getActorScopeParent(\n actorScope: AnyActorScope\n): AnyActor | undefined {\n return isLazyActorScope(actorScope)\n ? (actorScope as InternalActorScope)._parent\n : actorScope.self._parent;\n}\n\n/** Adds only `self`, preserving callback surfaces that expose no other capabilities. @internal */\nexport function withActorSelf<T extends object>(\n args: T,\n actorScope: AnyActorScope\n): T & Pick<AnyActorScope, 'self'> {\n if (!isLazyActorScope(actorScope)) {\n return Object.assign(args, { self: actorScope.self });\n }\n Object.defineProperty(args, 'self', {\n enumerable: true,\n get: () => actorScope.self\n });\n return args as T & Pick<AnyActorScope, 'self'>;\n}\n\n/** Adds the actor reference and parent without exposing the system. @internal */\nexport function withActorSelfAndParent<T extends object>(\n args: T,\n actorScope: AnyActorScope\n): T & Pick<AnyActorScope, 'self'> & { parent: AnyActor | undefined } {\n if (!isLazyActorScope(actorScope)) {\n const self = actorScope.self;\n return Object.assign(args, { self, parent: self._parent });\n }\n Object.defineProperties(args, {\n self: { enumerable: true, get: () => actorScope.self },\n parent: { enumerable: true, get: () => getActorScopeParent(actorScope) }\n });\n return args as T &\n Pick<AnyActorScope, 'self'> & { parent: AnyActor | undefined };\n}\n\n/** Adds actor capabilities without reading them until the callback does. @internal */\nexport function withActorScope<T extends object>(\n args: T,\n actorScope: AnyActorScope\n): T &\n Pick<AnyActorScope, 'self' | 'system'> & {\n parent: AnyActor | undefined;\n } {\n if (!isLazyActorScope(actorScope)) {\n const actorArgs = args as T &\n Pick<AnyActorScope, 'self' | 'system'> & {\n parent: AnyActor | undefined;\n };\n const self = actorScope.self;\n actorArgs.self = self;\n actorArgs.system = actorScope.system;\n actorArgs.parent = self._parent;\n return actorArgs;\n }\n Object.defineProperties(args, {\n self: { enumerable: true, get: () => actorScope.self },\n system: { enumerable: true, get: () => actorScope.system },\n parent: { enumerable: true, get: () => getActorScopeParent(actorScope) }\n });\n return args as T &\n Pick<AnyActorScope, 'self' | 'system'> & {\n parent: AnyActor | undefined;\n };\n}\n","import { createActor } from './createActor.ts';\nimport { isMachineSnapshot } from './State.ts';\nimport {\n createSnapshotSystem,\n getSnapshotActorRef,\n getSnapshotActorRefProvider,\n peekSnapshotActorRef,\n setLazySnapshotActorRef,\n setSnapshotActorRef,\n type SnapshotActorRef\n} from './snapshotActorRef.ts';\nimport {\n ActorScope,\n AnyActor,\n AnyActorLogic,\n AnyActorScope,\n EmittedFrom,\n EventFromLogic,\n Snapshot,\n SnapshotFrom\n} from './types.ts';\nimport { lazyActorScope } from './actorScope.ts';\n\n/** @internal */\nexport function setInertActorScopeSnapshot<T>(\n actorScope: AnyActorScope,\n snapshot: T,\n attachActorRef = true\n): T {\n const lazyState = getLazyInertActorState(actorScope);\n if (lazyState) {\n lazyState.snapshot = snapshot;\n if (lazyState.materialized) {\n (lazyState.materialized.self as any)._snapshot = snapshot;\n }\n } else {\n (actorScope.self as any)._snapshot = snapshot;\n }\n if (attachActorRef && snapshot && typeof snapshot === 'object') {\n setSnapshotActorRef(snapshot as any, actorScope.self);\n }\n return snapshot;\n}\n\n/** @internal */\nexport function isInertActorScope(actorScope: AnyActorScope): boolean {\n return (\n !!getLazyInertActorState(actorScope) ||\n !!(actorScope.self as any).options?._inert\n );\n}\n\n/** @internal */\nexport function attachSnapshotActorRef<TSnapshot>(\n actorScope: AnyActorScope,\n snapshot: TSnapshot\n): TSnapshot {\n setInertActorScopeSnapshot(actorScope, snapshot, false);\n const lazyState = getLazyInertActorState(actorScope);\n snapshotActorScopes.set(snapshot as object, actorScope);\n const create = () => {\n setSnapshotActorRef(\n snapshot as Snapshot<unknown>,\n actorScope.self,\n actorScope.system\n );\n return getSnapshotActorRef(snapshot as Snapshot<unknown>)!;\n };\n if (lazyState) {\n if (lazyState.materialized) {\n lazyState.identityProvider = create;\n } else {\n lazyState.identityProvider ??= create;\n }\n }\n setLazySnapshotActorRef(snapshot as Snapshot<unknown>, create);\n return snapshot;\n}\n\ntype LazyInertActorState = {\n snapshot: unknown;\n materialized?: AnyActorScope;\n sourceRef?: () => SnapshotActorRef;\n sourceChildren: Record<string, AnyActor | undefined>;\n identityProvider?: () => SnapshotActorRef;\n parent?: AnyActor;\n parentKnown: boolean;\n materialize: () => AnyActorScope;\n};\n\nconst lazyInertActorState = Symbol();\ntype LazyInertActorScope = AnyActorScope & {\n [lazyInertActorState]?: LazyInertActorState;\n};\nconst snapshotActorScopes = new WeakMap<object, AnyActorScope>();\nlet inertActorMaterializationObserver: (() => void) | undefined;\n\nfunction getLazyInertActorState(\n actorScope: AnyActorScope\n): LazyInertActorState | undefined {\n return (actorScope as LazyInertActorScope)[lazyInertActorState];\n}\n\nfunction materializeInertActorScope(actorScope: AnyActorScope): AnyActorScope {\n return getLazyInertActorState(actorScope)!.materialize();\n}\n\nconst lazyInertActorScopePrototype = {\n [lazyActorScope]: true,\n get _parent() {\n const actorScope = this as AnyActorScope;\n const state = getLazyInertActorState(actorScope)!;\n return state.parentKnown\n ? state.parent\n : materializeInertActorScope(actorScope).self._parent;\n },\n get self() {\n return materializeInertActorScope(this as AnyActorScope).self;\n },\n get defer() {\n return materializeInertActorScope(this as AnyActorScope).defer;\n },\n get id() {\n return materializeInertActorScope(this as AnyActorScope).id;\n },\n get logger() {\n return materializeInertActorScope(this as AnyActorScope).logger;\n },\n get sessionId() {\n return materializeInertActorScope(this as AnyActorScope).sessionId;\n },\n get stopChild() {\n return materializeInertActorScope(this as AnyActorScope).stopChild;\n },\n get system() {\n return materializeInertActorScope(this as AnyActorScope).system;\n },\n get emit() {\n return materializeInertActorScope(this as AnyActorScope).emit;\n },\n get actionExecutor() {\n return materializeInertActorScope(this as AnyActorScope).actionExecutor;\n }\n};\n\n/** Test-only allocation instrumentation. @internal */\nexport function setInertActorMaterializationObserver(\n observer: (() => void) | undefined\n): void {\n inertActorMaterializationObserver = observer;\n}\n\nfunction createMaterializedInertActorScope<T extends AnyActorLogic>(\n actorLogic: T,\n sourceRef: (() => SnapshotActorRef) | undefined,\n sourceChildren: Record<string, AnyActor | undefined>,\n currentSnapshot: SnapshotFrom<T> | undefined,\n sourceSelf?: AnyActor\n): AnyActorScope {\n inertActorMaterializationObserver?.();\n const snapshotRef = sourceRef?.();\n const previousSelf = sourceSelf ?? snapshotRef?.actor;\n const baseSystem = previousSelf?.system;\n const system =\n previousSelf && baseSystem\n ? createSnapshotSystem(\n baseSystem,\n sourceChildren,\n sourceSelf ? undefined : snapshotRef?.systemState\n )\n : undefined;\n const self = createActor(\n actorLogic as AnyActorLogic,\n {\n _inert: true,\n ...(previousSelf\n ? {\n id: previousSelf.id,\n _sessionId: previousSelf.sessionId\n }\n : {}),\n ...(system ? { _systemRef: { current: system } } : {})\n } as any\n );\n if (previousSelf?._parent) {\n self._parent = previousSelf._parent;\n // `address` memoizes on first read assuming `_parent` is final; nothing\n // reads it between construction and this assignment, but drop any memo so\n // a future construction-time read cannot pin a root-shaped address.\n (self as unknown as { _address?: string })._address = undefined;\n }\n if (currentSnapshot) {\n (self as any)._snapshot = currentSnapshot;\n }\n\n // Reuse the branch actor's scope while keeping planning transactional.\n return Object.create((self as any)._actorScope, {\n defer: { value: () => {} },\n stopChild: { value: (child: AnyActor) => (child as any)._stop() },\n actionExecutor: { value: () => {} }\n });\n}\n\n/** @internal */\nexport function createInertActorScope<T extends AnyActorLogic>(\n actorLogic: T,\n snapshot?: SnapshotFrom<T>,\n sourceSelf?: AnyActor,\n sourceActorScope?: AnyActorScope\n): AnyActorScope {\n const sourceScope =\n sourceActorScope ??\n (snapshot && typeof snapshot === 'object'\n ? snapshotActorScopes.get(snapshot as object)\n : undefined);\n const sourceState = sourceScope\n ? getLazyInertActorState(sourceScope)\n : undefined;\n const eagerSourceRef =\n snapshot && typeof snapshot === 'object'\n ? peekSnapshotActorRef(snapshot as Snapshot<unknown>)\n : undefined;\n const sourceRef =\n sourceState?.identityProvider ??\n (snapshot && typeof snapshot === 'object'\n ? getSnapshotActorRefProvider(snapshot as Snapshot<unknown>)\n : undefined);\n const state = {\n snapshot,\n sourceRef,\n sourceChildren: isMachineSnapshot(snapshot)\n ? (snapshot as any).children\n : {},\n identityProvider: sourceState?.identityProvider ?? sourceRef,\n parent:\n sourceSelf?._parent ??\n sourceState?.parent ??\n eagerSourceRef?.actor._parent,\n parentKnown:\n !!sourceSelf ||\n !!sourceState?.parentKnown ||\n !!eagerSourceRef ||\n !snapshot\n } as LazyInertActorState;\n state.materialize = () =>\n (state.materialized ??= createMaterializedInertActorScope(\n actorLogic,\n state.sourceRef,\n state.sourceChildren,\n state.snapshot as SnapshotFrom<T>,\n sourceSelf\n ));\n if (!state.identityProvider && !snapshot) {\n const identitySnapshot = {} as Snapshot<unknown>;\n const identitySourceRef = state.sourceRef;\n const identitySourceChildren = state.sourceChildren;\n let identityScope: AnyActorScope | undefined;\n let identityRef: SnapshotActorRef | undefined;\n const getIdentityScope = () =>\n (identityScope ??= createMaterializedInertActorScope(\n actorLogic,\n identitySourceRef,\n identitySourceChildren,\n undefined,\n sourceSelf\n ));\n state.materialize = () => {\n const scope = getIdentityScope();\n if (state.snapshot !== undefined) {\n (scope.self as any)._snapshot = state.snapshot;\n }\n return (state.materialized = scope);\n };\n state.identityProvider = () => {\n if (identityRef) {\n return identityRef;\n }\n const scope = getIdentityScope();\n setSnapshotActorRef(identitySnapshot, scope.self, scope.system);\n return (identityRef = getSnapshotActorRef(identitySnapshot)!);\n };\n }\n const actorScope = Object.create(lazyInertActorScopePrototype) as ActorScope<\n SnapshotFrom<T>,\n EventFromLogic<T>,\n any,\n EmittedFrom<T>\n >;\n (actorScope as LazyInertActorScope)[lazyInertActorState] = state;\n return actorScope;\n}\n","import isDevelopment from '#is-development';\nimport { xstateError } from './xstateError.ts';\nimport { MachineSnapshot, cloneMachineSnapshot } from './State.ts';\nimport type { StateNode } from './StateNode.ts';\nimport {\n createAfterEvent,\n createDoneStateEvent,\n createInvokeTimeoutEvent,\n createTimeoutEvent\n} from './eventUtils.ts';\nimport {\n getBuiltInTimerIdentity,\n getTimerKey,\n matchesTimerKey,\n readTimerKey\n} from './timerKey.ts';\nimport {\n XSTATE_INIT,\n STATE_DELIMITER,\n STATE_IDENTIFIER,\n XSTATE_STOP,\n XSTATE_TIMER\n} from './constants.ts';\nimport {\n describeMachine,\n getEventOutput,\n isErrorEvent,\n matchesEvent,\n matchesEventDescriptor\n} from './utils.ts';\nimport {\n AnyEventObject,\n AnyMachineSnapshot,\n AnyStateNode,\n AnyTransitionDefinition,\n DelayedTransitionDefinition,\n EventObject,\n ExecutableEffect,\n HistoryValue,\n MachineContext,\n StateValue,\n TransitionDefinition,\n TimerKey,\n AnyAction,\n AnyTransitionConfig,\n AnyActor,\n AnyActorScope,\n DoneStateEvent,\n EnqueueObject\n} from './types.ts';\nimport {\n resolveOutput,\n normalizeTarget,\n toArray,\n toStatePath,\n toTransitionConfigArray\n} from './utils.ts';\nimport { builtInActions } from './actions.ts';\nimport {\n assertChildIdFree,\n assertRaiseEvent,\n createEnqueueObject,\n lateEnqueueCall,\n createTerminationEffect,\n closeTransitionEnqueue,\n createTransitionEnqueue,\n createSendToEffect,\n deriveDeferredStarts,\n mergeContextPatch,\n resolveActionsWithContext\n} from './transitionActions.ts';\nimport { parseDurationToMilliseconds } from './delay.ts';\nimport {\n beginTransitionSelection,\n transitionEffectSignal\n} from './transitionSelection.ts';\nimport { isInertActorScope } from './inertActorScope.ts';\nimport {\n getActorScopeParent,\n isLazyActorScope,\n withActorSelfAndParent,\n withActorScope\n} from './actorScope.ts';\n\ntype AnyStateNodeIterable = Iterable<AnyStateNode>;\n\nfunction getConfiguredDelayValue(\n delay: number | string,\n delaySource: Record<string, any>\n) {\n if (typeof delay !== 'string') {\n return delay;\n }\n\n const referencedDelay = delaySource[delay];\n if (referencedDelay !== undefined) {\n return referencedDelay;\n }\n\n const parsedDelay = parseDurationToMilliseconds(delay);\n if (parsedDelay === undefined) {\n throw new Error(\n isDevelopment\n ? `Invalid delay \"${delay}\": not a configured delay name or a valid duration string (e.g. \"500ms\", \"1.5s\", \"PT1M30S\").`\n : xstateError(9, delay)\n );\n }\n return parsedDelay;\n}\n\nfunction resolveDelay(\n delay: number | string | ((args: any) => number),\n delaySource: Record<string, any>,\n args: {\n context: MachineContext;\n event: EventObject;\n stateNode: AnyStateNode;\n input?: Record<string, unknown>;\n }\n) {\n if (typeof delay === 'function') {\n return delay(args);\n }\n\n const configuredDelay = getConfiguredDelayValue(delay, delaySource);\n if (typeof configuredDelay === 'function') {\n return configuredDelay(args);\n }\n\n return configuredDelay;\n}\n\nfunction getStateInput(snapshot: AnyMachineSnapshot, stateNodeId: string) {\n return snapshot._stateInputs?.[stateNodeId];\n}\n\nexport function isAtomicStateNode(stateNode: AnyStateNode) {\n return (\n stateNode.type === 'atomic' ||\n stateNode.type === 'final' ||\n stateNode.type === 'choice'\n );\n}\n\nfunction getChildren(stateNode: AnyStateNode): Array<AnyStateNode> {\n return Object.values(stateNode.states).filter((sn) => sn.type !== 'history');\n}\n\nexport function getProperAncestors(\n stateNode: AnyStateNode,\n toStateNode: AnyStateNode | undefined\n): Array<typeof stateNode> {\n const ancestors: Array<typeof stateNode> = [];\n\n if (toStateNode === stateNode) {\n return ancestors;\n }\n\n // add all ancestors\n let m = stateNode.parent;\n while (m && m !== toStateNode) {\n ancestors.push(m);\n m = m.parent;\n }\n\n return ancestors;\n}\n\nexport function getAllStateNodes(\n stateNodes: Iterable<AnyStateNode>\n): Set<AnyStateNode> {\n const nodeSet = new Set(stateNodes);\n const activeParentSet = new Set<AnyStateNode>();\n for (const stateNode of nodeSet) {\n if (stateNode.parent) {\n activeParentSet.add(stateNode.parent);\n }\n }\n\n // add descendants\n for (const s of nodeSet) {\n // if previously active, add existing child nodes\n if (s.type === 'compound' && !activeParentSet.has(s)) {\n for (const sn of getInitialStateNodes(s)) {\n nodeSet.add(sn);\n }\n continue;\n }\n\n if (s.type === 'parallel') {\n for (const child of getChildren(s)) {\n if (!nodeSet.has(child)) {\n const initialStates = getInitialStateNodes(child);\n for (const initialStateNode of initialStates) {\n nodeSet.add(initialStateNode);\n }\n }\n }\n }\n }\n\n // add all ancestors\n // Stop walking up as soon as we hit a node already in the set: its own\n // ancestor chain is guaranteed to be added when it is visited by this loop\n // (Set iteration visits elements added during iteration), so shared ancestor\n // chains are never re-walked once per descendant.\n for (const s of nodeSet) {\n let m = s.parent;\n\n while (m && !nodeSet.has(m)) {\n nodeSet.add(m);\n m = m.parent;\n }\n }\n\n return nodeSet;\n}\n\nexport function getStateValue(\n rootNode: AnyStateNode,\n stateNodes: AnyStateNodeIterable\n): StateValue {\n const config = getAllStateNodes(stateNodes);\n const adjList = new Map<AnyStateNode, Array<AnyStateNode>>();\n\n for (const s of config) {\n if (!adjList.has(s)) {\n adjList.set(s, []);\n }\n\n if (!s.parent) {\n continue;\n }\n\n if (!adjList.has(s.parent)) {\n adjList.set(s.parent, []);\n }\n\n adjList.get(s.parent)!.push(s);\n }\n\n const getValueFromAdj = (baseNode: AnyStateNode): StateValue => {\n const childStateNodes = adjList.get(baseNode);\n\n if (!childStateNodes) {\n return {}; // todo: fix?\n }\n\n if (baseNode.type === 'compound') {\n const childStateNode = childStateNodes[0];\n if (!childStateNode) {\n return {};\n }\n if (isAtomicStateNode(childStateNode)) {\n return childStateNode.key;\n }\n }\n\n const stateValue: StateValue = {};\n for (const childStateNode of childStateNodes) {\n stateValue[childStateNode.key] = getValueFromAdj(childStateNode);\n }\n\n return stateValue;\n };\n\n return getValueFromAdj(rootNode);\n}\n\nexport function isInFinalState(\n stateNodeSet: Set<AnyStateNode>,\n stateNode: AnyStateNode\n): boolean {\n if (stateNode.type === 'compound') {\n return getChildren(stateNode).some(\n (s) => s.type === 'final' && stateNodeSet.has(s)\n );\n }\n if (stateNode.type === 'parallel') {\n return getChildren(stateNode).every((sn) =>\n isInFinalState(stateNodeSet, sn)\n );\n }\n\n return stateNode.type === 'final';\n}\n\nexport const isStateId = (str: string) => str[0] === STATE_IDENTIFIER;\n\nexport function matchesActorSession(\n event: EventObject,\n snapshot: AnyMachineSnapshot,\n actorId: string\n): boolean {\n const child = snapshot.children[actorId];\n if (!child || !('sessionId' in event)) {\n return true;\n }\n // One rule: a ref that knows its incarnation compares it; a remote handle\n // without a host-supplied token (sessionId undefined) defers to the\n // runtime that owns the child.\n return (\n child.sessionId === undefined ||\n child.sessionId === (event as { sessionId?: string }).sessionId\n );\n}\n\nexport function getCandidates<TEvent extends EventObject>(\n stateNode: StateNode<any, TEvent>,\n event: TEvent\n): Array<TransitionDefinition<any, TEvent>> {\n const exactMatches = stateNode.transitions.get(event.type) ?? [];\n const wildcardCandidates = [...stateNode.transitions.keys()]\n .filter(\n (eventDescriptor) =>\n eventDescriptor !== event.type &&\n matchesEventDescriptor(event.type, eventDescriptor)\n )\n .sort((a, b) => b.length - a.length)\n .flatMap((key) => stateNode.transitions.get(key)!);\n\n return exactMatches.length\n ? [...exactMatches, ...wildcardCandidates]\n : wildcardCandidates;\n}\n\nfunction scheduleDelayedEvent(\n stateNode: AnyStateNode,\n timerEvent: AnyEventObject,\n resolveEvent: (args: any) => AnyEventObject,\n resolveScheduledDelay: (x: {\n context: MachineContext;\n event: EventObject;\n delays: Record<string, any>;\n input?: Record<string, unknown>;\n }) => any\n) {\n const oldEntry = stateNode.entry;\n stateNode.entry = (x: any, enq: any) => {\n const result =\n typeof oldEntry === 'function' ? oldEntry(x, enq) : undefined;\n // The entry context patch is applied by the caller after this wrapper returns.\n const context =\n result?.context !== undefined\n ? mergeContextPatch(x.context, result.context)\n : x.context;\n // Built-in timers have no id: the event identifies them.\n enq.raise(resolveEvent(x) as any, {\n delay: resolveScheduledDelay({\n context,\n event: x.event,\n delays: x.delays,\n input: x.input\n })\n });\n return result;\n };\n const oldExit = stateNode.exit;\n stateNode.exit = (_: any, enq: any) => {\n enq.cancel({ event: getBuiltInTimerIdentity(timerEvent)! });\n return typeof oldExit === 'function' ? oldExit(_, enq) : undefined;\n };\n}\n\n/** All delayed transitions from the config. */\nexport function getDelayedTransitions(\n stateNode: AnyStateNode\n): Array<DelayedTransitionDefinition<MachineContext, EventObject>> {\n const afterConfig = stateNode.config.after;\n const timeoutConfig = (stateNode.config as any).timeout;\n const onTimeoutConfig = (stateNode.config as any).onTimeout;\n const invokeDefs = stateNode.invoke.filter(\n (invokeDef) => invokeDef.timeout !== undefined\n );\n\n if (!afterConfig && timeoutConfig === undefined && invokeDefs.length === 0) {\n return [];\n }\n\n if (isDevelopment && timeoutConfig !== undefined && !onTimeoutConfig) {\n throw new Error(\n `State \"${stateNode.id}\" has \\`timeout\\` but no \\`onTimeout\\` transition.`\n );\n }\n\n if (isDevelopment) {\n for (const invokeDef of invokeDefs) {\n if (!invokeDef.onTimeout) {\n throw new Error(\n `Invoke on state \"${stateNode.id}\" has \\`timeout\\` but no \\`onTimeout\\` transition.`\n );\n }\n }\n }\n\n // Every delayed transition — `after`, state-level `timeout`/`onTimeout`, and\n // invoke-level `timeout`/`onTimeout` — has the same shape: an event raised on\n // entry (and cancelled on exit) plus a transition that catches it. They\n // differ only in the event raised, the transition(s) caught, and whether the\n // delay resolves against the machine's `delays` map (invoke timeouts do not).\n //\n // `xstate.timeout.state` is a dedicated event category so a state-level `timeout`\n // cannot collide with an explicit `after` entry on the same state. Invoke\n // timeouts are scheduled on the enclosing state; completion transitions\n // cancel the timer separately, so it clears even when the parent stays active.\n const sources: Array<{\n event: AnyEventObject;\n resolveEvent?: (args: any) => AnyEventObject;\n eventMatcher?: (\n event: EventObject,\n snapshot: AnyMachineSnapshot\n ) => boolean;\n delay: any;\n transitions: unknown;\n fromDelaysMap: boolean;\n /** Where the transitions are authored, for error messages. */\n name: string;\n }> = [];\n\n if (afterConfig) {\n for (const key of Object.keys(afterConfig)) {\n const delay = Number.isNaN(+key) ? key : +key;\n sources.push({\n event: createAfterEvent(delay, stateNode.id),\n delay,\n transitions: afterConfig[key],\n fromDelaysMap: true,\n name: `after.${key}`\n });\n }\n }\n\n if (timeoutConfig !== undefined && onTimeoutConfig) {\n sources.push({\n event: createTimeoutEvent(stateNode.id),\n delay: timeoutConfig,\n transitions: onTimeoutConfig,\n fromDelaysMap: true,\n name: 'onTimeout'\n });\n }\n\n for (const invokeDef of invokeDefs) {\n sources.push({\n event: createInvokeTimeoutEvent(invokeDef.id),\n resolveEvent: ({ children }: any) =>\n createInvokeTimeoutEvent(\n invokeDef.id,\n children[invokeDef.id]?.sessionId\n ),\n eventMatcher: (event, snapshot) =>\n matchesActorSession(event, snapshot, invokeDef.id),\n delay: invokeDef.timeout!,\n transitions: invokeDef.onTimeout,\n fromDelaysMap: false,\n name: 'invoke.onTimeout'\n });\n }\n\n // `delay` here is the raw config value, retained only as metadata on the\n // transition definition — the live delay is resolved at runtime in the\n // scheduled entry action, so no eager resolution is needed.\n const delayedTransitions: Array<\n AnyTransitionConfig & {\n event: string;\n delay: any;\n _eventMatcher?: (\n event: EventObject,\n snapshot: AnyMachineSnapshot\n ) => boolean;\n }\n > = [];\n\n for (const {\n event,\n resolveEvent,\n eventMatcher,\n delay,\n transitions,\n fromDelaysMap,\n name\n } of sources) {\n scheduleDelayedEvent(stateNode, event, resolveEvent ?? (() => event), (x) =>\n resolveDelay(delay, fromDelaysMap ? x.delays : {}, {\n context: x.context,\n event: x.event,\n stateNode,\n input: x.input\n })\n );\n const { type: eventType, ...eventPattern } = event;\n for (const transition of toTransitionConfigArray(\n transitions as any,\n name,\n stateNode.id\n )) {\n delayedTransitions.push({\n ...transition,\n matches: {\n ...transition.matches,\n ...Object.fromEntries(\n Object.entries(eventPattern).filter(\n ([, value]) => value !== undefined\n )\n )\n },\n event: eventType,\n delay,\n _eventMatcher: eventMatcher\n });\n }\n }\n\n return delayedTransitions.map((delayedTransition) => ({\n ...formatTransition(\n stateNode,\n delayedTransition.event,\n delayedTransition as AnyTransitionConfig\n ),\n delay: delayedTransition.delay\n }));\n}\n\nexport function formatTransition(\n stateNode: AnyStateNode,\n descriptor: string,\n transitionConfig: AnyTransitionConfig\n): AnyTransitionDefinition {\n const removedKey = getRemovedTransitionKey(transitionConfig);\n if (removedKey) {\n throw new Error(\n isDevelopment\n ? `Transition \"${descriptor || 'always'}\" in state \"${stateNode.id}\" uses ${removedKey}, which was removed in v6. Use a transition function.`\n : xstateError(10, descriptor || 'always', stateNode.id, removedKey)\n );\n }\n const normalizedTarget = normalizeTarget(transitionConfig.target);\n const reenter = transitionConfig.reenter ?? false;\n const target = resolveTarget(stateNode, normalizedTarget);\n assertLegalTargetSet(stateNode, target);\n\n const transition = {\n ...transitionConfig,\n target,\n source: stateNode,\n reenter,\n eventType: descriptor,\n toJSON: () => transitionDefinitionToJSON(transition)\n };\n\n return transition;\n}\n\nfunction transitionDefinitionToJSON(\n transition: AnyTransitionDefinition\n): Record<string, unknown> {\n const { definition: _, ...serializableTransition } = transition;\n return {\n ...serializableTransition,\n source: `#${transition.source.id}`,\n target: transition.target?.map((target) => `#${target.id}`)\n };\n}\n\n/**\n * Returns the v5 key of a transition object that v6 would misread, in every\n * build: `cond` is never read, so the transition would always be taken,\n * transition `actions` would not run as written, and only a function `guard`\n * can be called. Development builds explain each key earlier, in\n * `diagnoseAuthorConfig`. Compiled configs (JSON, SCXML) never set them.\n */\nfunction getRemovedTransitionKey(\n transitionConfig: AnyTransitionConfig\n): string | undefined {\n const { cond, actions, guard } = transitionConfig as {\n cond?: unknown;\n actions?: unknown;\n guard?: unknown;\n };\n if (cond !== undefined) {\n return '\"cond\"';\n }\n if (actions !== undefined) {\n return '\"actions\"';\n }\n if (guard !== undefined && typeof guard !== 'function') {\n return 'an object-form \"guard\"';\n }\n return undefined;\n}\n\nfunction isStateNodeDescendantOf(\n stateNode: AnyStateNode,\n ancestor: AnyStateNode\n): boolean {\n for (let current = stateNode.parent; current; current = current.parent) {\n if (current === ancestor) {\n return true;\n }\n }\n return false;\n}\n\nfunction getLeastCommonStateNodeAncestor(\n left: AnyStateNode,\n right: AnyStateNode\n): AnyStateNode | undefined {\n const leftAncestors = new Set<AnyStateNode>();\n for (\n let current: AnyStateNode | undefined = left;\n current;\n current = current.parent\n ) {\n leftAncestors.add(current);\n }\n for (\n let current: AnyStateNode | undefined = right;\n current;\n current = current.parent\n ) {\n if (leftAncestors.has(current)) {\n return current;\n }\n }\n return undefined;\n}\n\nfunction assertLegalTargetSet(\n source: AnyStateNode,\n targets: readonly AnyStateNode[] | undefined\n): void {\n if (!targets || targets.length < 2) {\n return;\n }\n for (let leftIndex = 0; leftIndex < targets.length; leftIndex++) {\n for (\n let rightIndex = leftIndex + 1;\n rightIndex < targets.length;\n rightIndex++\n ) {\n const left = targets[leftIndex];\n const right = targets[rightIndex];\n const commonAncestor = getLeastCommonStateNodeAncestor(left, right);\n if (\n left === right ||\n isStateNodeDescendantOf(left, right) ||\n isStateNodeDescendantOf(right, left) ||\n commonAncestor?.type !== 'parallel'\n ) {\n throw new Error(\n isDevelopment\n ? `Invalid transition definition for state node '${source.id}': target set is not a legal SCXML configuration.`\n : xstateError(11, source.id)\n );\n }\n }\n }\n}\n\n/**\n * Collects route transitions from all descendants with explicit IDs. Called\n * once on the root node to avoid O(N²) repeated traversals.\n */\nexport function formatRouteTransitions(rootStateNode: AnyStateNode): void {\n const routeTransitions: AnyTransitionDefinition[] = [];\n const collectRoutes = (states: Record<string, AnyStateNode>) => {\n Object.values(states).forEach((sn) => {\n if (sn.config.route && sn.config.id) {\n const routeId = sn.config.id;\n const routeConfig = sn.config.route;\n const routeMatches = ({ event }: { event: any }) =>\n event.to === `#${routeId}`;\n\n if (typeof routeConfig === 'function') {\n // Transition-style route: the function is the guard and resolver.\n // Returning undefined/false blocks the route; returning true or a\n // config object allows it.\n routeTransitions.push(\n formatTransition(rootStateNode, 'xstate.route', {\n guard: routeMatches,\n to: (args: any) => {\n const result = routeConfig(args);\n if (!result) {\n return undefined;\n }\n return {\n ...(result === true ? {} : result),\n target: `#${routeId}`\n };\n }\n } as AnyTransitionConfig)\n );\n if (sn.states) {\n collectRoutes(sn.states);\n }\n return;\n }\n\n const { guard: _guard, ...routeOptions } = routeConfig as any;\n const transition: AnyTransitionConfig = {\n ...routeOptions,\n guard: routeMatches,\n target: `#${routeId}`\n };\n\n routeTransitions.push(\n formatTransition(rootStateNode, 'xstate.route', transition)\n );\n }\n if (sn.states) {\n collectRoutes(sn.states);\n }\n });\n };\n collectRoutes(rootStateNode.states);\n if (routeTransitions.length > 0) {\n rootStateNode.transitions.set('xstate.route', routeTransitions as any);\n }\n}\n\nfunction resolveTarget(\n stateNode: AnyStateNode,\n targets: ReadonlyArray<string | AnyStateNode> | undefined\n): ReadonlyArray<AnyStateNode> | undefined {\n if (targets === undefined) {\n // an undefined target signals that the state node should not transition from that state when receiving that event\n return undefined;\n }\n return targets.map((target) => {\n if (typeof target !== 'string') {\n return target;\n }\n if (isStateId(target)) {\n return stateNode.machine.getStateNodeById(target);\n }\n\n const isInternalTarget = target[0] === STATE_DELIMITER;\n // If internal target is defined on machine,\n // do not include machine key on target\n if (isInternalTarget && !stateNode.parent) {\n return getStateNodeByPath(stateNode, target.slice(1));\n }\n const resolvedTarget = isInternalTarget ? stateNode.key + target : target;\n if (stateNode.parent) {\n try {\n const targetStateNode = getStateNodeByPath(\n stateNode.parent,\n resolvedTarget\n );\n return targetStateNode;\n } catch (err: any) {\n throw new Error(\n isDevelopment\n ? `Invalid transition definition for state node '${stateNode.id}':\\n${err.message}`\n : xstateError(12, stateNode.id, err.message)\n );\n }\n } else {\n throw new Error(\n isDevelopment\n ? `Invalid target: \"${target}\" is not a valid target from the root node. Did you mean \".${target}\"?`\n : xstateError(13, target)\n );\n }\n });\n}\n\nfunction resolveHistoryDefaultTransition(\n stateNode: AnyStateNode & { type: 'history' }\n): AnyTransitionDefinition {\n const normalizedTarget = normalizeTarget(stateNode.config.target);\n if (!normalizedTarget) {\n if (stateNode.parent!.type === 'parallel') {\n return {\n target: [stateNode.parent!],\n source: stateNode,\n reenter: false,\n eventType: '' as any\n };\n }\n return stateNode.parent!.initial as AnyTransitionDefinition;\n }\n const target = normalizedTarget.map((t) =>\n typeof t === 'string' ? getStateNodeByPath(stateNode.parent!, t) : t\n );\n assertLegalTargetSet(stateNode, target);\n return {\n target,\n source: stateNode,\n reenter: false,\n eventType: '' as any,\n to: (stateNode.config as any)._historyDefaultTransition\n };\n}\n\nfunction isHistoryNode(\n stateNode: AnyStateNode\n): stateNode is AnyStateNode & { type: 'history' } {\n return stateNode.type === 'history';\n}\n\nfunction getInitialStateNodes(stateNode: AnyStateNode) {\n const set = new Set<AnyStateNode>();\n\n function iter(descStateNode: AnyStateNode): void {\n if (set.has(descStateNode)) {\n return;\n }\n set.add(descStateNode);\n if (descStateNode.type === 'compound') {\n for (const target of descStateNode.initial.target ?? []) {\n iter(target);\n }\n } else if (descStateNode.type === 'parallel') {\n for (const child of getChildren(descStateNode)) {\n iter(child);\n }\n }\n }\n\n iter(stateNode);\n for (const initialState of set) {\n for (const ancestor of getProperAncestors(initialState, stateNode)) {\n set.add(ancestor);\n }\n }\n\n return set;\n}\n\n/** Returns the child state node from its relative `stateKey`, or throws. */\nfunction getStateNode(stateNode: AnyStateNode, stateKey: string): AnyStateNode {\n const result = stateNode.states?.[stateKey];\n if (!result) {\n throw new Error(\n isDevelopment\n ? stateNode.states\n ? `Child state '${stateKey}' does not exist on '${stateNode.id}'`\n : `Unable to retrieve child state '${stateKey}' from '${stateNode.id}'; no child states exist.`\n : xstateError(14, stateKey, stateNode.id)\n );\n }\n return result;\n}\n\n/**\n * Returns the relative state node from the given `statePath`, or throws.\n *\n * @param statePath The string or string array relative path to the state node.\n */\nfunction getStateNodeByPath(\n stateNode: AnyStateNode,\n statePath: string | string[]\n): AnyStateNode {\n // `#id` is an exact id lookup, never an id followed by a path.\n if (typeof statePath === 'string' && isStateId(statePath)) {\n return stateNode.machine.getStateNodeById(statePath);\n }\n const arrayStatePath = toStatePath(statePath).slice();\n let currentStateNode: AnyStateNode = stateNode;\n while (arrayStatePath.length) {\n const key = arrayStatePath.shift()!;\n if (!key.length) {\n break;\n }\n currentStateNode = getStateNode(currentStateNode, key);\n }\n return currentStateNode;\n}\n\n/**\n * Returns the state nodes represented by the current state value.\n *\n * @param stateValue The state value or State instance\n * @public\n */\nexport function getStateNodes(\n stateNode: AnyStateNode,\n stateValue: StateValue\n): Array<AnyStateNode> {\n if (typeof stateValue === 'string') {\n const childStateNode = stateNode.states[stateValue];\n if (!childStateNode) {\n throw new Error(\n isDevelopment\n ? `State '${stateValue}' does not exist on '${stateNode.id}'`\n : xstateError(14, stateValue, stateNode.id)\n );\n }\n return [stateNode, childStateNode];\n }\n\n const childStateKeys = Object.keys(stateValue);\n const childStateNodes = new Array<AnyStateNode>(childStateKeys.length);\n const allStateNodes: Array<AnyStateNode> = [\n stateNode.machine.root,\n stateNode\n ];\n\n for (let i = 0; i < childStateKeys.length; i++) {\n const subStateNode = getStateNode(stateNode, childStateKeys[i]);\n childStateNodes[i] = subStateNode;\n allStateNodes.push(subStateNode);\n }\n\n for (let i = 0; i < childStateKeys.length; i++) {\n allStateNodes.push(\n ...getStateNodes(childStateNodes[i], stateValue[childStateKeys[i]]!)\n );\n }\n\n return allStateNodes;\n}\n\nexport type TransitionSelectionResult =\n | {\n enabled: boolean;\n result: unknown;\n reusable: true;\n operations: ReturnType<typeof createTransitionSelection>['operations'];\n }\n | { enabled: true; result: undefined; reusable: false };\n\nexport type TransitionSelectionResults = Map<\n AnyTransitionDefinition,\n TransitionSelectionResult\n>;\n\nexport function transitionNode<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n stateNode: AnyStateNode,\n stateValue: StateValue,\n snapshot: MachineSnapshot<\n TContext,\n TEvent,\n any,\n any,\n any,\n any,\n any,\n any // TStateSchema\n >,\n event: TEvent,\n actorScope: AnyActorScope,\n selectionResults?: TransitionSelectionResults\n): Array<TransitionDefinition<TContext, TEvent>> | undefined {\n // leaf node\n if (typeof stateValue === 'string') {\n const childStateNode = getStateNode(stateNode, stateValue);\n const next = childStateNode.next(\n snapshot,\n event,\n actorScope,\n selectionResults\n );\n\n if (!next || !next.length) {\n return stateNode.next(snapshot, event, actorScope, selectionResults);\n }\n\n return next;\n }\n\n const subStateKeys = Object.keys(stateValue);\n const subStateKey = subStateKeys[0];\n\n if (subStateKeys.length === 1) {\n const childStateNode = getStateNode(stateNode, subStateKey);\n const next = transitionNode(\n childStateNode,\n stateValue[subStateKey]!,\n snapshot,\n event,\n actorScope,\n selectionResults\n );\n\n if (!next || !next.length) {\n return stateNode.next(snapshot, event, actorScope, selectionResults);\n }\n\n return next;\n }\n\n const allInnerTransitions: Array<TransitionDefinition<TContext, TEvent>> = [];\n\n for (const subStateKey of subStateKeys) {\n const subStateValue = stateValue[subStateKey];\n\n if (!subStateValue) {\n continue;\n }\n\n const subStateNode = getStateNode(stateNode, subStateKey);\n const innerTransitions = transitionNode(\n subStateNode,\n subStateValue,\n snapshot,\n event,\n actorScope,\n selectionResults\n );\n if (innerTransitions) {\n allInnerTransitions.push(...innerTransitions);\n }\n }\n\n if (!allInnerTransitions.length) {\n return stateNode.next(snapshot, event, actorScope, selectionResults);\n }\n\n return allInnerTransitions;\n}\n\nfunction isDescendant(\n childStateNode: AnyStateNode,\n parentStateNode: AnyStateNode\n): boolean {\n let marker = childStateNode;\n while (marker.parent && marker.parent !== parentStateNode) {\n marker = marker.parent;\n }\n\n return marker.parent === parentStateNode;\n}\n\nfunction hasDescendantState(\n stateNodes: Set<AnyStateNode>,\n parentStateNode: AnyStateNode\n): boolean {\n for (const stateNode of stateNodes) {\n if (isDescendant(stateNode, parentStateNode)) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction hasIntersection<T>(s1: Iterable<T>, s2: Iterable<T>): boolean {\n const s1Size =\n s1 instanceof Set ? s1.size : Array.isArray(s1) ? s1.length : undefined;\n const s2Size =\n s2 instanceof Set ? s2.size : Array.isArray(s2) ? s2.length : undefined;\n\n if (s1Size !== undefined && s2Size !== undefined && s2Size < s1Size) {\n [s1, s2] = [s2, s1];\n }\n\n const set1 = s1 instanceof Set ? s1 : new Set(s1);\n for (const item of s2) {\n if (set1.has(item)) {\n return true;\n }\n }\n return false;\n}\n\nfunction removeConflictingTransitions(\n enabledTransitions: Array<AnyTransitionDefinition>,\n stateNodeSet: Set<AnyStateNode>,\n snapshot: AnyMachineSnapshot,\n resolveTransition: TransitionResultResolver\n): Array<AnyTransitionDefinition> {\n const filteredTransitions = new Set<AnyTransitionDefinition>();\n const exitSets = new Map<AnyTransitionDefinition, Array<AnyStateNode>>();\n\n const getExitSet = (transition: AnyTransitionDefinition) => {\n let exitSet = exitSets.get(transition);\n if (!exitSet) {\n exitSet = computeExitSet(\n [transition],\n stateNodeSet,\n snapshot,\n resolveTransition\n );\n exitSets.set(transition, exitSet);\n }\n\n return exitSet;\n };\n\n for (const t1 of enabledTransitions) {\n let t1Preempted = false;\n const transitionsToRemove = new Set<AnyTransitionDefinition>();\n for (const t2 of filteredTransitions) {\n if (hasIntersection(getExitSet(t1), getExitSet(t2))) {\n if (isDescendant(t1.source, t2.source)) {\n transitionsToRemove.add(t2);\n } else {\n t1Preempted = true;\n break;\n }\n }\n }\n if (!t1Preempted) {\n for (const t3 of transitionsToRemove) {\n filteredTransitions.delete(t3);\n }\n filteredTransitions.add(t1);\n }\n }\n\n return Array.from(filteredTransitions);\n}\n\ntype ResolvableTransition = Parameters<typeof getTransitionResult>[0];\ntype TransitionResultResolver = (\n transition: ResolvableTransition,\n // Whether the caller applies the result's `context` and `input`, rather\n // than only reading its targets\n applied?: boolean\n) => ReturnType<typeof getTransitionResult>;\n\nfunction createTransitionResultResolver(\n snapshot: AnyMachineSnapshot,\n event: AnyEventObject,\n actorScope: AnyActorScope,\n resolveActions: boolean,\n selectionResults?: TransitionSelectionResults\n): TransitionResultResolver {\n let cache:\n | Map<ResolvableTransition, ReturnType<typeof getTransitionResult>>\n | undefined;\n return (transition, applied) => {\n if (!transition.to && !applied) {\n // An object transition's targets are static, so reading them must not\n // run its `context` and `input` mappers\n return {\n targets: transition.target as AnyStateNode[] | undefined,\n context: undefined,\n reenter: transition.reenter,\n actions: undefined,\n internalEvents: undefined,\n input: undefined\n };\n }\n let result = cache?.get(transition);\n if (!result) {\n result = getTransitionResult(transition, snapshot, event, actorScope, {\n resolveActions,\n selectionResult: selectionResults?.get(\n transition as AnyTransitionDefinition\n )\n });\n (cache ??= new Map()).set(transition, result);\n }\n return result;\n };\n}\n\nfunction getEffectiveTargetStates(\n transition: Pick<AnyTransitionDefinition, 'target' | 'source'>,\n snapshot: AnyMachineSnapshot,\n resolveTransition: TransitionResultResolver\n): Array<AnyStateNode> {\n const historyValue = snapshot.historyValue;\n const { targets } = resolveTransition(transition);\n if (!targets) {\n return [];\n }\n\n const targetSet = new Set<AnyStateNode>();\n\n for (const targetNode of targets) {\n if (isHistoryNode(targetNode)) {\n if (historyValue[targetNode.id]) {\n for (const node of historyValue[targetNode.id]) {\n targetSet.add(node);\n }\n } else {\n for (const node of getEffectiveTargetStates(\n resolveHistoryDefaultTransition(targetNode),\n snapshot,\n resolveTransition\n )) {\n targetSet.add(node);\n }\n }\n } else {\n targetSet.add(targetNode);\n }\n }\n\n return [...targetSet];\n}\n\n/**\n * Narrows a parallel domain to the single child region that contains every\n * effective target, so that a transition confined to one region does not exit\n * (and reset) its sibling regions.\n */\nfunction narrowParallelDomain(\n domain: AnyStateNode,\n targetStates: Array<AnyStateNode>\n): AnyStateNode {\n let narrowed = domain;\n while (narrowed.type === 'parallel') {\n const region = getChildren(narrowed).find((child) =>\n targetStates.every(\n (target) => target === child || isDescendant(target, child)\n )\n );\n if (!region) {\n break;\n }\n narrowed = region;\n }\n return narrowed;\n}\n\nfunction getTransitionDomain(\n transition: AnyTransitionDefinition,\n snapshot: AnyMachineSnapshot,\n resolveTransition: TransitionResultResolver\n): AnyStateNode | undefined {\n const targetStates = getEffectiveTargetStates(\n transition,\n snapshot,\n resolveTransition\n );\n\n const { targets, reenter } = resolveTransition(transition);\n\n if (transition._transitionDomain) {\n if (\n transition._transitionDomain === 'internal' &&\n transition.source.type === 'compound' &&\n targetStates.every((target) => isDescendant(target, transition.source))\n ) {\n return transition.source;\n }\n\n const [head, ...tail] = targetStates.concat(transition.source);\n for (const ancestor of getProperAncestors(head, undefined)) {\n if (\n ancestor.type === 'compound' &&\n tail.every((stateNode) => isDescendant(stateNode, ancestor))\n ) {\n return ancestor;\n }\n }\n\n return;\n }\n\n // A history target that restores the source itself must exit and reenter\n // the source (SCXML domain = the source's ancestor), unlike a plain\n // non-reentering self-target: the enter set restores the stored\n // configuration from outside the source, so the exit set must match or the\n // source's invoked actors are re-created without being stopped.\n const restoresSourceViaHistory =\n targets?.some(isHistoryNode) &&\n targetStates.some((target) => target === transition.source);\n\n if (\n !restoresSourceViaHistory &&\n targetStates.every(\n (target) =>\n target === transition.source || isDescendant(target, transition.source)\n )\n ) {\n // Targets are contained within the source. A reentering transition\n // exits and reenters the source itself; otherwise the domain narrows\n // past parallel nodes so sibling regions are left untouched.\n return reenter\n ? transition.source\n : narrowParallelDomain(transition.source, targetStates);\n }\n\n const [head, ...tail] = targetStates.concat(transition.source);\n // Find the least common ancestor (LCA) of the source and effective targets.\n for (const ancestor of getProperAncestors(head, undefined)) {\n if (tail.every((sn) => isDescendant(sn, ancestor))) {\n // A cross-region transition (source in one parallel region, targets in\n // another) only exits the region containing its targets; the source\n // region and other sibling regions stay put unless it reenters.\n return reenter ? ancestor : narrowParallelDomain(ancestor, targetStates);\n }\n }\n\n // at this point we know that it's a root transition since LCA couldn't be found\n if (reenter) {\n return;\n }\n\n return narrowParallelDomain(transition.source.machine.root, targetStates);\n}\n\nfunction computeExitSet(\n transitions: Array<AnyTransitionDefinition>,\n stateNodeSet: Set<AnyStateNode>,\n snapshot: AnyMachineSnapshot,\n resolveTransition: TransitionResultResolver\n): Array<AnyStateNode> {\n const statesToExit = new Set<AnyStateNode>();\n for (const transition of transitions) {\n const { targets, reenter } = resolveTransition(transition);\n\n if (targets?.length) {\n const domain = getTransitionDomain(\n transition,\n snapshot,\n resolveTransition\n );\n\n if (reenter && transition.source === domain) {\n statesToExit.add(domain);\n }\n\n for (const stateNode of stateNodeSet) {\n if (isDescendant(stateNode, domain!)) {\n statesToExit.add(stateNode);\n }\n }\n }\n }\n\n return [...statesToExit];\n}\n\ntype Microstep = readonly [\n AnyMachineSnapshot,\n ExecutableEffect[],\n // The transitions taken in this microstep, when recorded by `macrostep()`\n transitions?: AnyTransitionDefinition[]\n];\n\nexport function initialMicrostep(\n root: AnyStateNode,\n preInitialState: AnyMachineSnapshot,\n actorScope: AnyActorScope,\n initEvent: AnyEventObject,\n internalQueue: AnyEventObject[]\n): Microstep {\n root.machine._microstepHooks?.begin(actorScope.self);\n const initialStateNodes = [...getInitialStateNodes(root)];\n const statesForDefaultEntry = new Set<AnyStateNode>();\n const collectDefaultEntryStates = (stateNode: AnyStateNode): void => {\n if (stateNode.type === 'compound') {\n statesForDefaultEntry.add(stateNode);\n for (const target of stateNode.initial.target ?? []) {\n collectDefaultEntryStates(target);\n }\n } else if (stateNode.type === 'parallel') {\n for (const child of getChildren(stateNode)) {\n collectDefaultEntryStates(child);\n }\n }\n };\n collectDefaultEntryStates(root);\n return microstep(\n [\n {\n target: initialStateNodes.filter(\n (stateNode) =>\n !initialStateNodes.some(\n (other) => other !== stateNode && isDescendant(other, stateNode)\n )\n ),\n source: root,\n reenter: true,\n eventType: null as any,\n toJSON: null as any,\n _statesForDefaultEntry: [...statesForDefaultEntry]\n } as AnyTransitionDefinition\n ],\n preInitialState,\n actorScope,\n initEvent,\n true,\n internalQueue\n );\n}\n\n/** https://www.w3.org/TR/scxml/#microstepProcedure */\nfunction microstep(\n transitions: Array<AnyTransitionDefinition>,\n currentSnapshot: AnyMachineSnapshot,\n actorScope: AnyActorScope,\n event: AnyEventObject,\n isInitial: boolean,\n internalQueue: Array<AnyEventObject>,\n selectionResults?: TransitionSelectionResults\n): Microstep {\n const executableActions: ExecutableEffect[] = [];\n const internalEvents = currentSnapshot.machine._microstepHooks?.drain(\n actorScope.self\n );\n if (internalEvents?.length) {\n internalQueue.push(...internalEvents);\n }\n\n if (!transitions.length) {\n return [currentSnapshot, executableActions];\n }\n\n {\n const mutStateNodeSet = new Set(currentSnapshot.nodes as StateNode[]);\n let historyValue = currentSnapshot.historyValue;\n const originalContext = currentSnapshot.context;\n\n const filteredTransitions =\n transitions.length === 1\n ? transitions\n : removeConflictingTransitions(\n transitions,\n mutStateNodeSet,\n currentSnapshot,\n createTransitionResultResolver(\n currentSnapshot,\n event,\n actorScope,\n false,\n selectionResults\n )\n );\n const getCurrentTransitionResult = createTransitionResultResolver(\n currentSnapshot,\n event,\n actorScope,\n true,\n selectionResults\n );\n const changesState = filteredTransitions.some((transition) => {\n const { targets, reenter } = getCurrentTransitionResult(transition);\n return !!targets?.length || !!reenter;\n });\n const getStateActionsAndContext = (\n transitionFn: any,\n context: MachineContext,\n children: AnyMachineSnapshot['children'],\n input: Record<string, unknown> | undefined,\n kind: 'entry' | 'exit' | 'transition',\n stateNode: AnyStateNode\n ): [\n actions: any[],\n context: MachineContext | undefined,\n internalEvents: EventObject[] | undefined,\n children: AnyMachineSnapshot['children'] | undefined\n ] => {\n const actions: any[] = [];\n const internalEvents: EventObject[] = [];\n let updatedContext: MachineContext | undefined;\n\n const enqueue = createTransitionEnqueue(\n actorScope,\n actions,\n internalEvents,\n true\n );\n\n const args = isLazyActorScope(actorScope)\n ? withActorScope(\n {\n context,\n event,\n output: getEventOutput(event),\n children,\n actions: currentSnapshot.machine.sources.actions,\n actors: currentSnapshot.machine.sources.actors,\n guards: currentSnapshot.machine.sources.guards,\n delays: currentSnapshot.machine.sources.delays,\n input,\n stateNode\n },\n actorScope\n )\n : {\n context,\n event,\n output: getEventOutput(event),\n parent: actorScope.self._parent,\n self: actorScope.self,\n children,\n system: actorScope.system,\n actions: currentSnapshot.machine.sources.actions,\n actors: currentSnapshot.machine.sources.actors,\n guards: currentSnapshot.machine.sources.guards,\n delays: currentSnapshot.machine.sources.delays,\n input,\n stateNode\n };\n let res;\n try {\n res = transitionFn(args, enqueue);\n } finally {\n closeTransitionEnqueue(enqueue);\n }\n assertSyncTransitionResult(res, event, stateNode.id, kind);\n\n if (res?.context !== undefined) {\n updatedContext = mergeContextPatch(context, res.context);\n }\n\n return [actions, updatedContext, internalEvents, res?.children];\n };\n\n let nextState = currentSnapshot;\n const getInvokeStopActions = (\n stateNode: AnyStateNode,\n children: AnyMachineSnapshot['children']\n ): AnyAction[] => {\n const actions: AnyAction[] = [];\n const enqueue = createTransitionEnqueue(actorScope, actions, []);\n for (const invokeDef of stateNode.invoke) {\n const child = children[invokeDef.id];\n if (child) {\n enqueue.stop(child);\n }\n }\n return actions;\n };\n const exitStates = () => {\n const statesToExit = computeExitSet(\n filteredTransitions,\n mutStateNodeSet,\n currentSnapshot,\n getCurrentTransitionResult\n );\n\n statesToExit.sort((a, b) => b.order - a.order);\n\n let changedHistory: HistoryValue | undefined;\n const currentStateNodes = [...mutStateNodeSet];\n\n // From SCXML algorithm: https://www.w3.org/TR/scxml/#exitStates\n for (const exitStateNode of statesToExit) {\n for (const historyNode of Object.values(exitStateNode.states)) {\n if (historyNode.type !== 'history') {\n continue;\n }\n\n const predicate =\n historyNode.history === 'deep'\n ? (sn: AnyStateNode) =>\n isAtomicStateNode(sn) && isDescendant(sn, exitStateNode)\n : (sn: AnyStateNode) => sn.parent === exitStateNode;\n\n changedHistory ??= { ...historyValue };\n changedHistory[historyNode.id] = currentStateNodes.filter(predicate);\n }\n }\n\n for (const exitStateNode of statesToExit) {\n const stateInput = getStateInput(currentSnapshot, exitStateNode.id);\n\n const [exitActions, nextContext, internalEvents, nextChildren] =\n exitStateNode.exit\n ? getStateActionsAndContext(\n exitStateNode.exit,\n nextState.context,\n nextState.children,\n stateInput,\n 'exit',\n exitStateNode\n )\n : [[], undefined, undefined, undefined];\n if (internalEvents?.length) {\n internalQueue.push(...internalEvents);\n }\n if (nextContext || nextChildren) {\n nextState = cloneMachineSnapshot(nextState, {\n ...(nextContext ? { context: nextContext } : {}),\n ...(nextChildren ? { children: nextChildren } : {})\n });\n }\n const [resolvedState, resolvedActions] = resolveActionsWithContext(\n nextState,\n event,\n actorScope,\n exitActions\n );\n nextState = resolvedState;\n executableActions.push(...resolvedActions);\n\n const invokeStopActions = getInvokeStopActions(\n exitStateNode,\n nextState.children\n );\n if (invokeStopActions.length) {\n const [stoppedState, stopEffects] = resolveActionsWithContext(\n nextState,\n event,\n actorScope,\n invokeStopActions\n );\n nextState = stoppedState;\n executableActions.push(...stopEffects);\n }\n\n mutStateNodeSet.delete(exitStateNode);\n }\n\n historyValue = changedHistory || historyValue;\n };\n\n // Exit states\n if (!isInitial && changesState) {\n exitStates();\n }\n\n let context = nextState.context;\n const transitionActions: AnyAction[] = [];\n const internalEvents: EventObject[] = [];\n\n const resolvedTransitions: AnyTransitionDefinition[] = [];\n for (const t of filteredTransitions) {\n const res = getCurrentTransitionResult(t, true);\n if (t.to) {\n const resolvedTransition = {\n ...t,\n target: res.targets,\n definition: t\n } as AnyTransitionDefinition & {\n toJSON: () => Record<string, unknown>;\n };\n resolvedTransition.toJSON = () =>\n transitionDefinitionToJSON(resolvedTransition);\n resolvedTransitions.push(resolvedTransition);\n } else {\n resolvedTransitions.push(t);\n }\n if (res.context !== undefined) {\n context = mergeContextPatch(context, res.context);\n }\n if (res.actions) {\n transitionActions.push(...res.actions);\n }\n if (res.internalEvents) {\n internalEvents.push(...res.internalEvents);\n }\n }\n\n if (internalEvents.length) {\n internalQueue.push(...internalEvents);\n }\n\n const enterStates = () => {\n const getMachineOutput = (rootCompletionNode: AnyStateNode) => {\n const rootNode = nextState.machine.root;\n\n let completionOutput: unknown;\n if (\n rootCompletionNode.output !== undefined &&\n rootCompletionNode.parent\n ) {\n const rootDoneEvent = internalQueue.find(\n (e) =>\n e.type === 'xstate.done.state' &&\n (e as DoneStateEvent).stateId === rootNode.id\n ) as DoneStateEvent | undefined;\n completionOutput =\n rootDoneEvent && rootCompletionNode.parent === rootNode\n ? rootDoneEvent.output\n : resolveOutput(\n rootCompletionNode.output,\n nextState.context,\n event,\n actorScope.self,\n stateInputMap[rootCompletionNode.id]\n );\n } else if (rootCompletionNode.type === 'parallel') {\n const parallelDoneEvent = internalQueue.find(\n (e) =>\n e.type === 'xstate.done.state' &&\n (e as DoneStateEvent).stateId === rootCompletionNode.id\n ) as DoneStateEvent | undefined;\n completionOutput = parallelDoneEvent?.output;\n }\n\n if (rootNode.output === undefined) {\n return rootCompletionNode.parent === rootNode\n ? completionOutput\n : undefined;\n }\n\n return resolveOutput(\n rootNode.output,\n nextState.context,\n createDoneStateEvent(rootCompletionNode.id, completionOutput),\n actorScope.self\n );\n };\n\n const statesToEnter = new Set<AnyStateNode>();\n // those are states that were directly targeted or indirectly targeted by the explicit target\n // in other words, those are states for which initial actions should be executed\n // when we target `#deep_child` initial actions of its ancestors shouldn't be executed\n const statesForDefaultEntry = new Set<AnyStateNode>();\n const historyDefaultsByParent = new Map<\n AnyStateNode,\n AnyTransitionDefinition[]\n >();\n const addAncestorStatesToEnter = (\n ancestors: AnyStateNode[],\n reentrancyDomain: AnyStateNode | undefined\n ) => {\n for (const anc of ancestors) {\n if (!reentrancyDomain || isDescendant(anc, reentrancyDomain)) {\n statesToEnter.add(anc);\n }\n if (anc.type === 'parallel') {\n for (const child of getChildren(anc)) {\n if (!hasDescendantState(statesToEnter, child)) {\n statesToEnter.add(child);\n addDescendantStatesToEnter(child);\n }\n }\n }\n }\n };\n\n const addDescendantStatesToEnter = (stateNode: AnyStateNode) => {\n if (isHistoryNode(stateNode)) {\n if (historyValue[stateNode.id]) {\n const historyStateNodes = historyValue[stateNode.id];\n for (const s of historyStateNodes) {\n statesToEnter.add(s);\n addDescendantStatesToEnter(s);\n }\n for (const s of historyStateNodes) {\n addAncestorStatesToEnter(\n getProperAncestors(s, stateNode.parent),\n undefined\n );\n }\n } else {\n const historyDefaultTransition =\n resolveHistoryDefaultTransition(stateNode);\n const historyParent = stateNode.parent!;\n statesForDefaultEntry.add(historyParent);\n const defaults = historyDefaultsByParent.get(historyParent) ?? [];\n defaults.push(historyDefaultTransition);\n historyDefaultsByParent.set(historyParent, defaults);\n const { targets } = getCurrentTransitionResult(\n historyDefaultTransition\n );\n for (const s of targets ?? []) {\n statesToEnter.add(s);\n\n if (historyDefaultTransition === stateNode.parent?.initial) {\n statesForDefaultEntry.add(stateNode.parent);\n }\n\n addDescendantStatesToEnter(s);\n }\n\n for (const s of targets ?? []) {\n addAncestorStatesToEnter(\n getProperAncestors(s, stateNode.parent),\n undefined\n );\n }\n }\n return;\n }\n\n if (stateNode.type === 'compound') {\n const initialStates =\n getCurrentTransitionResult(stateNode.initial).targets ?? [];\n\n for (const initialState of initialStates) {\n if (!isHistoryNode(initialState)) {\n statesToEnter.add(initialState);\n }\n }\n statesForDefaultEntry.add(stateNode);\n for (const initialState of initialStates) {\n addDescendantStatesToEnter(initialState);\n }\n for (const initialState of initialStates) {\n addAncestorStatesToEnter(\n getProperAncestors(initialState, stateNode),\n undefined\n );\n }\n return;\n }\n\n if (stateNode.type === 'parallel') {\n for (const child of getChildren(stateNode)) {\n if (!hasDescendantState(statesToEnter, child)) {\n statesToEnter.add(child);\n statesForDefaultEntry.add(child);\n addDescendantStatesToEnter(child);\n }\n }\n }\n };\n\n const enteredTargetsByTransition = new Map<\n AnyTransitionDefinition,\n Set<AnyStateNode>\n >();\n for (const transition of filteredTransitions) {\n const domain = getTransitionDomain(\n transition,\n currentSnapshot,\n getCurrentTransitionResult\n );\n\n const { targets, reenter } = getCurrentTransitionResult(transition);\n const enteredTargets = new Set<AnyStateNode>();\n enteredTargetsByTransition.set(transition, enteredTargets);\n\n for (const targetNode of targets ?? []) {\n if (\n !isHistoryNode(targetNode) &&\n (transition.source !== targetNode ||\n transition.source !== domain ||\n reenter)\n ) {\n enteredTargets.add(targetNode);\n statesToEnter.add(targetNode);\n statesForDefaultEntry.add(targetNode);\n }\n addDescendantStatesToEnter(targetNode);\n }\n const targetStates = getEffectiveTargetStates(\n transition,\n currentSnapshot,\n getCurrentTransitionResult\n );\n for (const s of targetStates) {\n const ancestors = getProperAncestors(s, domain);\n if (domain?.type === 'parallel') {\n ancestors.push(domain);\n }\n addAncestorStatesToEnter(\n ancestors,\n !transition.source.parent && reenter ? undefined : domain\n );\n }\n if (reenter && domain === transition.source) {\n // A reentering transition whose domain is its own source exits and\n // reenters the source, so the source must be entered explicitly —\n // it has no ancestor inside the domain to add it.\n statesToEnter.add(transition.source);\n }\n }\n\n if (isInitial) {\n for (const stateNode of (filteredTransitions[0] as any)\n ._statesForDefaultEntry ?? [currentSnapshot.machine.root]) {\n statesForDefaultEntry.add(stateNode);\n }\n }\n\n // Keep only the inputs of states still active after exiting, so exited\n // (and re-entered) states never see a stale input.\n const stateInputMap: Record<string, Record<string, unknown>> = {};\n let stateInputsChanged = false;\n const activeIds = new Set([...mutStateNodeSet].map((sn) => sn.id));\n for (const [id, input] of Object.entries(\n currentSnapshot._stateInputs ?? {}\n )) {\n if (activeIds.has(id)) {\n stateInputMap[id] = input;\n } else {\n stateInputsChanged = true;\n }\n }\n for (const transition of filteredTransitions) {\n const { targets, input } = getCurrentTransitionResult(transition, true);\n if (input && targets) {\n for (const targetNode of targets.filter((targetNode) =>\n enteredTargetsByTransition.get(transition)?.has(targetNode)\n )) {\n stateInputMap[targetNode.id] = input;\n stateInputsChanged = true;\n }\n }\n }\n\n const completedNodes = new Set<AnyStateNode>();\n for (const stateNodeToEnter of [...statesToEnter].sort(\n (a, b) => a.order - b.order\n )) {\n mutStateNodeSet.add(stateNodeToEnter);\n const actions: AnyAction[] = [];\n // Read the children for each state: the entry actions of the states\n // entered before this one may have spawned or stopped children.\n let children = nextState.children;\n\n // Final states are inert, so (as in SCXML) their invocations never\n // start.\n let invoked = false;\n for (const invokeDef of stateNodeToEnter.type === 'final'\n ? []\n : stateNodeToEnter.invoke) {\n invoked = true;\n\n let src = invokeDef.logic;\n if (typeof src === 'function') {\n src = src({\n actors: currentSnapshot.machine.sources.actors,\n context: nextState.context,\n event,\n self: actorScope.self\n });\n }\n\n const logic =\n typeof src === 'string'\n ? currentSnapshot.machine.sources.actors[src]\n : src;\n\n if (!logic) {\n throw new Error(\n isDevelopment\n ? `Actor logic '${typeof src === 'string' ? src : 'inline'}' not implemented in ${describeMachine(currentSnapshot.machine.id)}`\n : xstateError(15, typeof src === 'string' ? src : 'inline')\n );\n }\n\n const input =\n typeof invokeDef.input === 'function'\n ? invokeDef.input({\n self: actorScope.self,\n context: nextState.context,\n event,\n input: stateInputMap[stateNodeToEnter.id],\n output: getEventOutput(event)\n })\n : invokeDef.input;\n\n assertChildIdFree(actorScope, invokeDef.id);\n const actor = actorScope.system.createActorRef(logic, {\n ...invokeDef,\n // A `src` function may return a registered key, which persists.\n src: typeof src === 'string' ? src : undefined,\n input,\n parent: actorScope.self,\n syncSnapshot: !!invokeDef.onSnapshot\n });\n // Persistence restores a source-less child through its invoke\n // definition only when the invoke created it.\n (actor as { _invoked?: boolean })._invoked = true;\n\n actions.push({\n action: builtInActions['@xstate.spawn'],\n args: [actor]\n });\n\n if (invokeDef.id) {\n children = { ...children, [invokeDef.id]: actor };\n }\n }\n\n if (invoked) {\n nextState = cloneMachineSnapshot(nextState, { children });\n }\n let context = nextState.context;\n let contextChangedByEntry = false;\n\n const stateInput = stateInputMap[stateNodeToEnter.id];\n\n if (stateNodeToEnter.entry) {\n const [resultActions, nextContext, nextInternalEvents, nextChildren] =\n getStateActionsAndContext(\n stateNodeToEnter.entry,\n context,\n children,\n stateInput,\n 'entry',\n stateNodeToEnter\n );\n actions.push(...resultActions);\n if (nextInternalEvents?.length) {\n internalQueue.push(...nextInternalEvents);\n }\n if (nextContext) {\n context = nextContext;\n contextChangedByEntry = true;\n }\n if (nextChildren) {\n nextState = cloneMachineSnapshot(nextState, {\n children: nextChildren\n });\n }\n }\n\n if (contextChangedByEntry) {\n nextState = cloneMachineSnapshot(nextState, { context });\n }\n\n if (statesForDefaultEntry.has(stateNodeToEnter)) {\n const defaultTransitions = [\n stateNodeToEnter.initial,\n ...(historyDefaultsByParent.get(stateNodeToEnter) ?? [])\n ].filter(Boolean);\n for (const defaultTransition of defaultTransitions) {\n const {\n actions: initialActions,\n context: initialContext,\n input: initialInput,\n internalEvents: initialInternalEvents\n } = getTransitionResult(\n defaultTransition,\n nextState,\n event,\n actorScope\n );\n if (initialActions) {\n actions.push(...initialActions);\n }\n if (initialInternalEvents?.length) {\n internalQueue.push(...initialInternalEvents);\n }\n if (initialContext !== undefined) {\n nextState = cloneMachineSnapshot(nextState, {\n context: mergeContextPatch(nextState.context, initialContext)\n });\n }\n if (initialInput && defaultTransition.target) {\n for (const targetNode of defaultTransition.target) {\n stateInputMap[targetNode.id] = initialInput;\n stateInputsChanged = true;\n }\n }\n }\n }\n\n const [resolvedState, resolvedActions] = resolveActionsWithContext(\n nextState,\n event,\n actorScope,\n actions\n );\n nextState = resolvedState;\n actions.length = 0;\n executableActions.push(...resolvedActions);\n\n if (stateNodeToEnter.type !== 'final') {\n continue;\n }\n\n const parent = stateNodeToEnter.parent;\n let ancestorMarker =\n parent?.type === 'parallel' ? parent : parent?.parent;\n let rootCompletionNode = ancestorMarker || stateNodeToEnter;\n\n if (parent?.type === 'compound') {\n internalQueue.push(\n createDoneStateEvent(\n parent.id,\n stateNodeToEnter.output !== undefined\n ? resolveOutput(\n stateNodeToEnter.output,\n nextState.context,\n event,\n actorScope.self,\n stateInput\n )\n : undefined\n )\n );\n }\n\n while (\n ancestorMarker?.type === 'parallel' &&\n !completedNodes.has(ancestorMarker) &&\n isInFinalState(mutStateNodeSet, ancestorMarker)\n ) {\n completedNodes.add(ancestorMarker);\n const regionOutput: Record<string, unknown> = {};\n for (const region of getChildren(ancestorMarker)) {\n if (region.type === 'final') {\n regionOutput[region.key] =\n region.output !== undefined\n ? resolveOutput(\n region.output,\n nextState.context,\n event,\n actorScope.self,\n stateInputMap[region.id]\n )\n : undefined;\n continue;\n }\n\n if (region.type === 'parallel') {\n const regionDoneEvent = internalQueue.find(\n (e) =>\n e.type === 'xstate.done.state' &&\n (e as DoneStateEvent).stateId === region.id\n ) as DoneStateEvent | undefined;\n regionOutput[region.key] = regionDoneEvent?.output;\n continue;\n }\n\n const finalChild = getChildren(region).find(\n (s) => s.type === 'final' && mutStateNodeSet.has(s)\n );\n regionOutput[region.key] =\n finalChild?.output !== undefined\n ? resolveOutput(\n finalChild.output,\n nextState.context,\n event,\n actorScope.self,\n stateInputMap[finalChild.id]\n )\n : undefined;\n }\n internalQueue.push(\n createDoneStateEvent(ancestorMarker.id, regionOutput)\n );\n rootCompletionNode = ancestorMarker;\n ancestorMarker = ancestorMarker.parent;\n }\n if (ancestorMarker) {\n continue;\n }\n\n nextState = cloneMachineSnapshot(nextState, {\n status: 'done',\n output: getMachineOutput(rootCompletionNode)\n });\n }\n\n if (stateInputsChanged) {\n nextState = cloneMachineSnapshot(nextState, {\n _stateInputs: stateInputMap\n });\n }\n };\n\n // Execute transition content\n const [resolvedTransitionState, transitionExecutableEffects] =\n resolveActionsWithContext(\n nextState,\n event,\n actorScope,\n transitionActions\n );\n nextState = resolvedTransitionState;\n executableActions.push(...transitionExecutableEffects);\n if (context && context !== currentSnapshot.context) {\n nextState = cloneMachineSnapshot(nextState, { context });\n }\n\n const transitionContent =\n nextState.machine._microstepHooks?.transitionContent?.(\n filteredTransitions,\n [...mutStateNodeSet]\n );\n if (transitionContent) {\n const source = filteredTransitions[0].source;\n const [actions, nextContext, raisedEvents, nextChildren] =\n getStateActionsAndContext(\n transitionContent,\n nextState.context,\n nextState.children,\n getStateInput(nextState, source.id),\n 'transition',\n source\n );\n if (raisedEvents?.length) {\n internalQueue.push(...raisedEvents);\n }\n if (nextContext || nextChildren) {\n nextState = cloneMachineSnapshot(nextState, {\n ...(nextContext ? { context: nextContext } : {}),\n ...(nextChildren ? { children: nextChildren } : {})\n });\n }\n const [resolvedState, effects] = resolveActionsWithContext(\n nextState,\n event,\n actorScope,\n actions\n );\n nextState = resolvedState;\n executableActions.push(...effects);\n }\n\n // Enter states\n if (isInitial || changesState) {\n enterStates();\n }\n\n const nextStateNodes = [...mutStateNodeSet];\n\n if (nextState.status === 'done') {\n const allExitActions: AnyAction[] = [];\n const nextStateNodesToExit = nextStateNodes.sort(\n (a, b) => b.order - a.order\n );\n\n nextStateNodesToExit.forEach((stateNode) => {\n if (stateNode.exit) {\n const stateInput = getStateInput(nextState, stateNode.id);\n const [exitActions, nextContext, nextInternalEvents, nextChildren] =\n getStateActionsAndContext(\n stateNode.exit,\n nextState.context,\n nextState.children,\n stateInput,\n 'exit',\n stateNode\n );\n if (nextContext || nextChildren) {\n nextState = cloneMachineSnapshot(nextState, {\n ...(nextContext ? { context: nextContext } : {}),\n ...(nextChildren ? { children: nextChildren } : {})\n });\n }\n allExitActions.push(...exitActions);\n if (nextInternalEvents?.length) {\n internalQueue.push(...nextInternalEvents);\n }\n }\n });\n\n const [resolvedState, resolvedActions] = resolveActionsWithContext(\n nextState,\n event,\n actorScope,\n allExitActions\n );\n nextState = resolvedState;\n executableActions.push(...resolvedActions);\n\n const [stoppedState, stopEffects] = stopChildren(\n nextState,\n event,\n actorScope\n );\n nextState = stoppedState;\n executableActions.push(...stopEffects);\n\n const [withoutTimers, cancelEffects] = cancelTimers(\n nextState,\n event,\n actorScope\n );\n nextState = withoutTimers;\n executableActions.push(...cancelEffects);\n }\n\n if (\n historyValue === currentSnapshot.historyValue &&\n currentSnapshot.nodes.length === mutStateNodeSet.size &&\n currentSnapshot.nodes.every((node) =>\n mutStateNodeSet.has(node as StateNode)\n )\n ) {\n // If context was changed (e.g. by entry actions during self-transition),\n // clone to ensure reference inequality for eventless transition re-evaluation\n if (nextState.context !== originalContext) {\n return [\n nextState === currentSnapshot\n ? cloneMachineSnapshot(nextState)\n : nextState,\n executableActions,\n resolvedTransitions\n ];\n }\n return [nextState, executableActions, resolvedTransitions];\n }\n\n return [\n cloneMachineSnapshot(nextState, {\n _nodes: nextStateNodes,\n historyValue\n }),\n executableActions,\n resolvedTransitions\n ];\n }\n}\n\n/**\n * Gets the transition result for a given transition without executing the\n * transition.\n */\nexport function getTransitionResult(\n transition: Pick<AnyTransitionDefinition, 'target' | 'to' | 'source'> & {\n reenter?: AnyTransitionDefinition['reenter'];\n input?: AnyTransitionDefinition['input'];\n context?: AnyTransitionDefinition['context'];\n },\n snapshot: AnyMachineSnapshot,\n event: AnyEventObject,\n actorScope: AnyActorScope,\n options?: {\n resolveActions?: boolean;\n selectionResult?: TransitionSelectionResult;\n }\n): {\n targets: Readonly<AnyStateNode[]> | undefined;\n context: MachineContext | undefined;\n actions: AnyAction[] | undefined;\n reenter?: boolean;\n internalEvents: EventObject[] | undefined;\n input: Record<string, unknown> | undefined;\n} {\n let transitionArgs: any;\n const getTransitionArgs = () =>\n (transitionArgs ??= isLazyActorScope(actorScope)\n ? withActorScope(\n {\n context: snapshot.context,\n event,\n output: getEventOutput(event),\n value: snapshot.value,\n children: snapshot.children,\n actions: snapshot.machine.sources.actions,\n actors: snapshot.machine.sources.actors,\n guards: snapshot.machine.sources.guards,\n delays: snapshot.machine.sources.delays,\n input: getStateInput(snapshot, transition.source.id)\n },\n actorScope\n )\n : {\n context: snapshot.context,\n event,\n output: getEventOutput(event),\n value: snapshot.value,\n children: snapshot.children,\n system: actorScope.system,\n parent: actorScope.self._parent,\n self: actorScope.self,\n actions: snapshot.machine.sources.actions,\n actors: snapshot.machine.sources.actors,\n guards: snapshot.machine.sources.guards,\n delays: snapshot.machine.sources.delays,\n input: getStateInput(snapshot, transition.source.id)\n });\n\n if (transition.to) {\n const actions: AnyAction[] = [];\n const internalEvents: EventObject[] = [];\n let res;\n if (\n options?.selectionResult?.reusable &&\n (options.resolveActions === false ||\n options.selectionResult.operations.length === 0)\n ) {\n res = options.selectionResult.result;\n } else {\n const enqueue = createTransitionEnqueue(\n actorScope,\n actions,\n internalEvents,\n true,\n options?.resolveActions ?? true\n );\n const speculativeSelection =\n options?.resolveActions === false\n ? beginTransitionSelection(\n getActorScopeParent(actorScope),\n 'suppress'\n )\n : undefined;\n try {\n if (options?.selectionResult?.reusable) {\n res = options.selectionResult.result;\n for (const operation of options.selectionResult.operations) {\n operation(enqueue);\n }\n } else {\n res = transition.to(getTransitionArgs(), enqueue);\n assertSyncTransitionResult(res, event, transition.source.id);\n }\n } finally {\n speculativeSelection?.close();\n closeTransitionEnqueue(enqueue);\n }\n }\n\n const targets = res?.target\n ? resolveTarget(transition.source, toArray(res.target) as string[])\n : undefined;\n\n const resolvedInput =\n res?.input ??\n (typeof transition.input === 'function'\n ? transition.input({\n context: snapshot.context,\n event,\n output: getEventOutput(event)\n })\n : transition.input);\n\n return {\n targets: targets,\n context: res?.context,\n reenter: res?.reenter,\n actions,\n internalEvents,\n input: resolvedInput\n };\n }\n\n // Resolve input for regular transitions\n const resolvedInput =\n typeof transition.input === 'function'\n ? transition.input({\n context: snapshot.context,\n event,\n output: getEventOutput(event)\n })\n : transition.input;\n const resolvedContext =\n typeof transition.context === 'function'\n ? transition.context(getTransitionArgs())\n : transition.context;\n\n return {\n targets: transition.target as AnyStateNode[] | undefined,\n context: resolvedContext,\n reenter: transition.reenter,\n actions: undefined,\n internalEvents: undefined,\n input: resolvedInput\n };\n}\n\n/**\n * Microsteps one macrostep may take before development builds warn, when the\n * machine sets no `maxIterations` bound.\n */\nconst LONG_MACROSTEP_WARNING = 1000;\n\n/** Machines that already logged the long-macrostep warning. */\nconst warnedLongMacrostep = new WeakSet<object>();\n\n/**\n * Thrown when one macrostep takes more microsteps than the machine's\n * `options.maxIterations` (unbounded by default) without reaching a stable state,\n * usually because eventless transitions or raised events form a cycle.\n *\n * @public\n */\nexport class InfiniteTransitionError extends Error {\n /** The id of the actor that was transitioning, if any. */\n public readonly actorId: string | undefined;\n /** The event being processed. */\n public readonly event: EventObject;\n /** The microstep bound that was exceeded. */\n public readonly maxIterations: number;\n /** The last (up to 5) state values visited, oldest first. */\n public readonly states: StateValue[];\n\n constructor(\n actorId: string | undefined,\n event: EventObject,\n maxIterations: number,\n states: StateValue[]\n ) {\n super(\n isDevelopment\n ? `Infinite loop detected in actor \"${actorId}\" processing event \"${\n event.type\n }\": more than ${maxIterations} microsteps without reaching a stable state. Last states: ${states\n .map((value) => JSON.stringify(value))\n .join(\n ' -> '\n )}. Check for a cycle of eventless transitions or raised events, or raise the bound with createMachine({ options: { maxIterations } }).`\n : xstateError(16, actorId, event.type, maxIterations)\n );\n this.name = 'InfiniteTransitionError';\n this.actorId = actorId;\n this.event = event;\n this.maxIterations = maxIterations;\n this.states = states.slice();\n }\n}\n\nexport function macrostep(\n snapshot: AnyMachineSnapshot,\n event: EventObject,\n actorScope: AnyActorScope,\n internalQueue: AnyEventObject[],\n initialMicrosteps: Microstep[] = []\n): {\n snapshot: typeof snapshot;\n microsteps: Microstep[];\n} {\n // A done, error or stopped snapshot processes no events, as in an actor:\n // every event is unhandled. The initial macrostep passes `initialMicrosteps`\n // and may start from a snapshot that is already done.\n if (snapshot.status !== 'active' && !initialMicrosteps.length) {\n return { snapshot, microsteps: [[snapshot, [], []]] };\n }\n let nextSnapshot = snapshot;\n const microsteps: Microstep[] = initialMicrosteps.slice();\n // Whether a transition handled the external event. A handled event always\n // yields a new snapshot object, so `result[0] === snapshot` (with no\n // effects) identifies an unhandled event.\n let handled = false;\n\n function removeTerminatedChild(terminalEvent: EventObject) {\n if (\n terminalEvent.type !== 'xstate.done.actor' &&\n terminalEvent.type !== 'xstate.error.actor'\n ) {\n return;\n }\n\n const { actorId, sessionId } = terminalEvent as AnyEventObject & {\n actorId?: string;\n sessionId?: string;\n };\n if (!actorId) {\n return;\n }\n const child = nextSnapshot.children[actorId];\n if (!child) {\n return;\n }\n // The same staleness rule matchesActorSession applies to transition\n // selection: a completion from a different incarnation must not remove\n // the still-running child either.\n if (child.sessionId !== undefined && child.sessionId !== sessionId) {\n return;\n }\n\n const children = { ...nextSnapshot.children };\n delete children[actorId];\n actorScope.system._unregister(child);\n nextSnapshot = cloneMachineSnapshot(nextSnapshot, { children });\n\n if (microsteps.length) {\n const [, lastEffects, lastTransitions] = microsteps.at(-1)!;\n microsteps[microsteps.length - 1] = [\n nextSnapshot,\n lastEffects,\n lastTransitions\n ];\n } else {\n microsteps.push([nextSnapshot, [], []]);\n }\n }\n\n function completeMacrostep() {\n if (handled && nextSnapshot === snapshot) {\n nextSnapshot = cloneMachineSnapshot(snapshot, {});\n if (microsteps.at(-1)?.[0] === snapshot) {\n const [, lastEffects, lastTransitions] = microsteps.at(-1)!;\n microsteps[microsteps.length - 1] = [\n nextSnapshot,\n lastEffects,\n lastTransitions\n ];\n }\n }\n const effects = microsteps.flatMap(([, actions]) => actions);\n const starts = deriveDeferredStarts(effects);\n const shouldTerminate =\n (snapshot.status === 'active' || initialMicrosteps.length > 0) &&\n (nextSnapshot.status === 'done' || nextSnapshot.status === 'error');\n\n if (starts.length || shouldTerminate) {\n const terminalEffects = shouldTerminate\n ? [...starts, createTerminationEffect(actorScope, nextSnapshot)]\n : starts;\n if (microsteps.length) {\n const [lastSnapshot, lastEffects, lastTransitions] = microsteps.at(-1)!;\n microsteps[microsteps.length - 1] = [\n lastSnapshot,\n [...lastEffects, ...terminalEffects],\n lastTransitions\n ];\n } else {\n microsteps.push([nextSnapshot, terminalEffects, []]);\n }\n }\n\n return { snapshot: nextSnapshot, microsteps };\n }\n\n function addMicrostep(\n step: Microstep,\n transitions: AnyTransitionDefinition[]\n ) {\n transitions = step[2] ?? transitions;\n // collect microsteps; their transitions are surfaced on the enclosing\n // '@xstate.transition' event via its `microsteps[]` facet (there is no\n // standalone microstep event) and returned by `getMicrosteps()`\n if (\n !isInertActorScope(actorScope) &&\n (event.type === XSTATE_INIT ||\n (actorScope.system._hasInspectionObservers?.() ?? true))\n ) {\n const collectedMicrosteps =\n ((actorScope.self as any)._collectedMicrosteps as any[]) || [];\n collectedMicrosteps.push(...transitions);\n (actorScope.self as any)._collectedMicrosteps = collectedMicrosteps;\n }\n microsteps.push([step[0], step[1], transitions]);\n }\n\n // Handle stop event\n if (event.type === XSTATE_STOP) {\n const [stoppedChildrenSnapshot, stopEffects] = stopChildren(\n nextSnapshot,\n event,\n actorScope\n );\n const [withoutTimers, cancelEffects] = cancelTimers(\n stoppedChildrenSnapshot,\n event,\n actorScope\n );\n nextSnapshot = cloneMachineSnapshot(withoutTimers, {\n status: 'stopped'\n });\n addMicrostep([nextSnapshot, [...stopEffects, ...cancelEffects]], []);\n return completeMacrostep();\n }\n\n let nextEvent = event;\n\n if (event.type === XSTATE_TIMER) {\n const key = readTimerKey(event);\n const index = key\n ? nextSnapshot.timers.findIndex((timer) => matchesTimerKey(timer, key))\n : -1;\n if (index === -1) {\n return completeMacrostep();\n }\n\n const timer = nextSnapshot.timers[index];\n const timers = nextSnapshot.timers.filter((_, i) => i !== index);\n nextSnapshot = cloneMachineSnapshot(nextSnapshot, { timers });\n if (timer.type === '@xstate.raise') {\n internalQueue.push(timer.event);\n addMicrostep([nextSnapshot, []], []);\n } else {\n const target = timer.target === 'self' ? actorScope.self : timer.target;\n addMicrostep(\n [nextSnapshot, [createSendToEffect(actorScope, target, timer.event)]],\n []\n );\n }\n }\n\n // Assume the state is at rest (no raised events)\n // Determine the next state based on the next microstep\n if (nextEvent.type !== XSTATE_INIT && nextEvent.type !== XSTATE_TIMER) {\n const currentEvent = nextEvent;\n const isErr = isErrorEvent(currentEvent);\n const selectionResults: TransitionSelectionResults = new Map();\n\n const transitions = nextSnapshot.machine.getTransitionData(\n nextSnapshot as any,\n currentEvent,\n actorScope,\n selectionResults\n );\n\n if (isErr && !transitions.length) {\n if (\n currentEvent.type === 'xstate.error.actor' &&\n !matchesActorSession(\n currentEvent,\n nextSnapshot,\n (currentEvent as AnyEventObject).actorId\n )\n ) {\n return completeMacrostep();\n }\n // TODO: we should likely only allow transitions selected by very explicit descriptors\n // `*` shouldn't be matched, likely `xstate.error.*` shouldn't be either\n nextSnapshot = cloneMachineSnapshot<typeof snapshot>(snapshot, {\n status: 'error',\n error: currentEvent.error\n });\n addMicrostep([nextSnapshot, []], []);\n removeTerminatedChild(currentEvent);\n return completeMacrostep();\n }\n handled = transitions.length > 0;\n const step = microstep(\n transitions,\n snapshot,\n actorScope,\n nextEvent,\n false, // isInitial\n internalQueue,\n selectionResults\n );\n nextSnapshot = step[0];\n addMicrostep(step, transitions);\n removeTerminatedChild(currentEvent);\n }\n\n if (\n !internalQueue.length &&\n snapshot.machine._hasEventlessTransitions === false\n ) {\n return completeMacrostep();\n }\n\n let shouldSelectEventlessTransitions = true;\n const maxIterations = snapshot.machine.options?.maxIterations ?? Infinity;\n let iterationCount = 0;\n // The last few state values visited, for the infinite-loop error.\n const recentStates: StateValue[] = [];\n\n while (nextSnapshot.status === 'active') {\n iterationCount++;\n if (iterationCount > maxIterations) {\n throw new InfiniteTransitionError(\n actorScope.self?.id,\n event,\n maxIterations,\n recentStates\n );\n }\n if (\n isDevelopment &&\n iterationCount === LONG_MACROSTEP_WARNING + 1 &&\n maxIterations === Infinity &&\n !warnedLongMacrostep.has(snapshot.machine)\n ) {\n warnedLongMacrostep.add(snapshot.machine);\n console.warn(\n `Actor \"${actorScope.self?.id}\" took more than ${LONG_MACROSTEP_WARNING} microsteps processing event \"${event.type}\" without reaching a stable state. Last states: ${recentStates\n .map((value) => JSON.stringify(value))\n .join(\n ' -> '\n )}. Check for a cycle of eventless transitions or raised events. To stop a runaway macrostep with an InfiniteTransitionError, set createMachine({ options: { maxIterations } }).`\n );\n }\n recentStates.push(nextSnapshot.value);\n if (recentStates.length > 5) {\n recentStates.shift();\n }\n\n let selectionResults: TransitionSelectionResults | undefined;\n let enabledTransitions: AnyTransitionDefinition[] =\n shouldSelectEventlessTransitions\n ? selectEventlessTransitions(nextSnapshot, nextEvent, actorScope)\n : [];\n\n // eventless transitions should always be selected after selecting *regular* transitions\n // by assigning `undefined` to `previousState` we ensure that `shouldSelectEventlessTransitions` gets always computed to true in such a case\n const previousState = enabledTransitions.length ? nextSnapshot : undefined;\n // Failed eventless guards can raise events even when no transition wins.\n const raisedEvents = nextSnapshot.machine._microstepHooks?.drain(\n actorScope.self\n );\n if (raisedEvents?.length) {\n internalQueue.push(...raisedEvents);\n }\n\n if (!enabledTransitions.length) {\n if (!internalQueue.length) {\n break;\n }\n nextEvent = internalQueue.shift()!;\n selectionResults = new Map();\n enabledTransitions = nextSnapshot.machine.getTransitionData(\n nextSnapshot as any,\n nextEvent,\n actorScope,\n selectionResults\n );\n }\n\n const step = microstep(\n enabledTransitions,\n nextSnapshot,\n actorScope,\n nextEvent,\n false,\n internalQueue,\n selectionResults\n );\n nextSnapshot = step[0];\n shouldSelectEventlessTransitions = nextSnapshot !== previousState;\n addMicrostep(step, enabledTransitions);\n removeTerminatedChild(nextEvent);\n }\n\n return completeMacrostep();\n}\n\n/**\n * Resolves a partial state value with its full representation in the state\n * node's machine.\n *\n * @param stateValue The partial state value to resolve.\n */\nexport function resolveStateValue(\n rootNode: AnyStateNode,\n stateValue: StateValue\n): StateValue {\n const allStateNodes = getAllStateNodes(getStateNodes(rootNode, stateValue));\n return getStateValue(rootNode, allStateNodes);\n}\n\nexport function hasEffect(\n transition: AnyTransitionDefinition,\n context: MachineContext,\n event: EventObject,\n snapshot: AnyMachineSnapshot,\n actorScope: AnyActorScope\n): boolean {\n if (transition.to) {\n return evaluateTransitionFunction(\n transition.to,\n context,\n event,\n snapshot,\n actorScope,\n snapshot.machine.sources,\n transition.source.id\n ).enabled;\n }\n\n return false;\n}\n\n/**\n * Throws when a transition, entry, or exit function returned a promise. The promise's\n * rejection is observed so it is never reported as unhandled.\n */\nfunction assertSyncTransitionResult(\n res: unknown,\n event: EventObject,\n sourceId: string,\n kind?: 'entry' | 'exit' | 'transition'\n): void {\n if (res && typeof (res as PromiseLike<unknown>).then === 'function') {\n void Promise.resolve(res as PromiseLike<unknown>).catch(() => {});\n throw new Error(\n !isDevelopment\n ? xstateError(17, kind ?? 'transition', sourceId, event.type)\n : kind && kind !== 'transition'\n ? `${kind === 'entry' ? 'Entry' : 'Exit'} functions must be synchronous. The ${kind} function of state \"${sourceId}\" returned a promise (event \"${event.type}\"). Move async work into an invoked or spawned actor, or enq.effect.`\n : `Transition functions must be synchronous. Transition for event \"${event.type}\" in state \"${sourceId}\" returned a promise. Move async work into an invoked or spawned actor, or enq.effect.`\n );\n }\n}\n\ntype RecordedEnqueue = (enqueue: EnqueueObject<any, any>) => void;\n\nfunction createTransitionSelection(parent: AnyActor | undefined) {\n const selection = beginTransitionSelection(parent);\n const { frame } = selection;\n const operations: RecordedEnqueue[] = [];\n let closed = false;\n const record = (operation: RecordedEnqueue) => {\n if (closed) {\n return lateEnqueueCall();\n }\n operations.push(operation);\n };\n const abortRefProducingCall = (): any => {\n if (closed) {\n return lateEnqueueCall();\n }\n frame.requiresReevaluation = true;\n throw transitionEffectSignal;\n };\n const enqueue = createEnqueueObject(\n {\n cancel: (...args) => record((enq) => enq.cancel(...args)),\n emit: (...args) => record((enq) => enq.emit(...args)),\n log: (...args) => record((enq) => enq.log(...args)),\n raise: (event, options) => {\n if (closed) {\n return lateEnqueueCall();\n }\n assertRaiseEvent(event);\n record((enq) => enq.raise(event, options));\n },\n sendTo: (...args) => record((enq) => enq.sendTo(...args)),\n stop: (...args) => record((enq) => enq.stop(...args)),\n spawn: abortRefProducingCall,\n listen: abortRefProducingCall,\n subscribeTo: abortRefProducingCall\n },\n (...args) => record((enq) => enq(...args))\n );\n return {\n frame,\n enqueue,\n operations,\n close() {\n closed = true;\n selection.close();\n }\n };\n}\n\nfunction evaluateTransitionFunction(\n transitionTo: NonNullable<AnyTransitionDefinition['to']>,\n context: MachineContext,\n event: EventObject,\n snapshot: AnyMachineSnapshot,\n actorScope: AnyActorScope,\n sources: AnyMachineSnapshot['machine']['sources'],\n sourceId: string\n): TransitionSelectionResult {\n let res;\n const selection = createTransitionSelection(getActorScopeParent(actorScope));\n try {\n res = transitionTo(\n withActorScope(\n {\n context,\n event,\n output: getEventOutput(event),\n value: snapshot.value,\n children: snapshot.children,\n actions: sources.actions,\n actors: sources.actors,\n guards: sources.guards,\n delays: sources.delays,\n input: getStateInput(snapshot, sourceId)\n },\n actorScope\n ),\n selection.enqueue\n );\n } catch (err) {\n if (err === transitionEffectSignal) {\n return { enabled: true, result: undefined, reusable: false };\n }\n throw err;\n } finally {\n selection.close();\n }\n assertSyncTransitionResult(res, event, sourceId);\n\n if (selection.frame.requiresReevaluation) {\n return { enabled: true, result: undefined, reusable: false };\n }\n return {\n enabled: res !== undefined || selection.operations.length > 0,\n result: res,\n reusable: true,\n operations: selection.operations\n };\n}\n\nfunction stopChildren(\n snapshot: AnyMachineSnapshot,\n event: AnyEventObject,\n actorScope: AnyActorScope\n): [AnyMachineSnapshot, ExecutableEffect[]] {\n let children: AnyActor[];\n if (\n !snapshot.children ||\n (children = Object.values(snapshot.children).filter(Boolean) as AnyActor[])\n .length === 0\n ) {\n return [snapshot, []];\n }\n const actions: AnyAction[] = [];\n const enqueue = createTransitionEnqueue(actorScope, actions, []);\n for (const child of children) {\n enqueue.stop(child);\n }\n return resolveActionsWithContext(snapshot, event, actorScope, actions);\n}\n\nfunction cancelTimers(\n snapshot: AnyMachineSnapshot,\n event: AnyEventObject,\n actorScope: AnyActorScope\n): [AnyMachineSnapshot, ExecutableEffect[]] {\n if (!snapshot.timers.length) {\n return [snapshot, []];\n }\n const actions: AnyAction[] = [];\n const enqueue = createTransitionEnqueue(actorScope, actions, []);\n for (const timer of snapshot.timers) {\n (enqueue.cancel as unknown as (key: TimerKey) => void)(getTimerKey(timer));\n }\n return resolveActionsWithContext(snapshot, event, actorScope, actions);\n}\n\nfunction selectEventlessTransitions(\n snapshot: AnyMachineSnapshot,\n event: AnyEventObject,\n actorScope: AnyActorScope\n) {\n snapshot.machine._microstepHooks?.begin(actorScope.self);\n const enabledTransitionSet: Set<AnyTransitionDefinition> = new Set();\n const atomicStates = snapshot.nodes.filter(isAtomicStateNode);\n\n for (const atomicStateNode of atomicStates) {\n loop: for (\n let stateNode: AnyStateNode | undefined = atomicStateNode;\n stateNode;\n stateNode = stateNode.parent\n ) {\n if (!stateNode.always) {\n continue;\n }\n for (const transition of stateNode.always) {\n if (\n evaluateCandidate(transition, event, snapshot, stateNode, actorScope)\n ) {\n enabledTransitionSet.add(transition);\n break loop;\n }\n }\n }\n }\n\n return removeConflictingTransitions(\n Array.from(enabledTransitionSet),\n new Set(snapshot.nodes),\n snapshot,\n createTransitionResultResolver(snapshot, event, actorScope, false)\n );\n}\n\nexport function evaluateCandidate(\n candidate: AnyTransitionDefinition,\n event: EventObject,\n snapshot: AnyMachineSnapshot,\n stateNode: AnyStateNode,\n actorScope: AnyActorScope,\n selectionResults?: TransitionSelectionResults\n): boolean {\n if (candidate.matches && !matchesEvent(event, candidate.matches)) {\n return false;\n }\n\n if (candidate._eventMatcher && !candidate._eventMatcher(event, snapshot)) {\n return false;\n }\n\n if (candidate.guard) {\n const guardArgs = withActorSelfAndParent(\n {\n context: snapshot.context,\n event,\n output: getEventOutput(event),\n children: snapshot.children,\n actions: stateNode.machine.sources.actions,\n actors: stateNode.machine.sources.actors,\n guards: stateNode.machine.sources.guards,\n delays: stateNode.machine.sources.delays,\n _snapshot: snapshot\n },\n actorScope\n );\n if (!(candidate.guard as (args: typeof guardArgs) => boolean)(guardArgs)) {\n return false;\n }\n }\n\n if (candidate.to) {\n const evaluation = evaluateTransitionFunction(\n candidate.to,\n snapshot.context,\n event,\n snapshot,\n actorScope,\n stateNode.machine.sources,\n candidate.source.id\n );\n selectionResults?.set(candidate, evaluation);\n return evaluation.enabled;\n }\n\n return true;\n}\n","export function parseDurationToMilliseconds(\n duration: string\n): number | undefined {\n const normalizedDuration = duration.trim();\n\n const millisecondsMatch = normalizedDuration.match(/^(\\d+)ms$/i);\n if (millisecondsMatch) {\n return parseInt(millisecondsMatch[1], 10);\n }\n\n const secondsMatch = normalizedDuration.match(/^(\\d*)(\\.?)(\\d*)s$/i);\n if (secondsMatch) {\n const wholePart = secondsMatch[1] ? parseInt(secondsMatch[1], 10) : 0;\n const hasDecimal = !!secondsMatch[2];\n const fracPart = secondsMatch[3]\n ? parseInt(secondsMatch[3].padEnd(3, '0').slice(0, 3), 10)\n : 0;\n\n return wholePart * 1000 + (hasDecimal ? fracPart : 0);\n }\n\n const iso8601DurationMatch = normalizedDuration.match(\n /^P(?:(?<weeks>\\d+(?:[.,]\\d+)?)W)?(?:(?<days>\\d+(?:[.,]\\d+)?)D)?(?:T(?:(?<hours>\\d+(?:[.,]\\d+)?)H)?(?:(?<minutes>\\d+(?:[.,]\\d+)?)M)?(?:(?<seconds>\\d+(?:[.,]\\d+)?)S)?)?$/i\n );\n\n if (!iso8601DurationMatch?.groups) {\n return undefined;\n }\n\n const { weeks, days, hours, minutes, seconds } = iso8601DurationMatch.groups;\n if (!weeks && !days && !hours && !minutes && !seconds) {\n return undefined;\n }\n\n const toNumber = (value: string | undefined) =>\n value ? Number(value.replace(',', '.')) : 0;\n\n return (\n toNumber(weeks) * 7 * 24 * 60 * 60 * 1000 +\n toNumber(days) * 24 * 60 * 60 * 1000 +\n toNumber(hours) * 60 * 60 * 1000 +\n toNumber(minutes) * 60 * 1000 +\n toNumber(seconds) * 1000\n );\n}\n\n/**\n * Converts a delay (milliseconds or an ISO 8601 duration string) to\n * milliseconds. Exported for `@xstate/scxml`; not part of the stable API.\n *\n * @experimental\n */\nexport function parseDelayToMilliseconds(\n delay: string | number | undefined\n): number | undefined {\n if (delay === undefined) {\n return undefined;\n }\n\n if (typeof delay === 'number') {\n return delay;\n }\n\n return parseDurationToMilliseconds(delay);\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 { 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 { 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","// Structural validation of persisted machine snapshots.\nimport type {\n AnyActorLogic,\n AnyStateMachine,\n AnyStateNode,\n StateValue\n} from './types.ts';\nimport { getAllStateNodes, getStateNodes } from './stateUtils.ts';\nimport isDevelopment from '#is-development';\nimport { describeMachine, resolveInvokedActorLogic } from './utils.ts';\nimport { xstateError } from './xstateError.ts';\nimport { isSerializedActorRef } from './remoteActorRef.ts';\n\n/**\n * The error a machine reports when a persisted snapshot cannot represent one\n * of its states: the snapshot has an invalid state value, malformed children\n * or timers, or a child source that the machine cannot restore.\n * `restoreActor(machine, snapshot)` reports it as an `'error'` snapshot\n * instead of starting.\n *\n * @public\n */\nexport class InvalidSnapshotError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'InvalidSnapshotError';\n }\n}\n\nexport function isSnapshotRecord(\n value: unknown\n): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction isActorLogic(value: unknown): value is AnyActorLogic {\n return (\n isSnapshotRecord(value) &&\n typeof value.transition === 'function' &&\n typeof value.getInitialSnapshot === 'function'\n );\n}\n\nfunction validatePersistedStateValue(\n machine: AnyStateMachine,\n stateValue: unknown,\n node: AnyStateNode,\n path: string[]\n): void {\n if (typeof stateValue === 'string') {\n if (!node.states[stateValue]) {\n throw new InvalidSnapshotError(\n isDevelopment\n ? `Persisted snapshot references state '${path.concat(stateValue).join('.')}' which does not exist on ${describeMachine(machine.id)}.`\n : xstateError(21, path.concat(stateValue).join('.'))\n );\n }\n return;\n }\n const invalidValue = (code: 22 | 23) =>\n new InvalidSnapshotError(\n isDevelopment\n ? `Persisted snapshot for ${describeMachine(machine.id)} has an invalid state value${path.length ? ` at '${path.join('.')}'` : ''}: ${\n code === 22\n ? 'expected a state name or an object of state values'\n : `state '${path.length ? path.join('.') : node.key}' is not parallel, so only one child state can be active`\n }.`\n : code === 22\n ? xstateError(22, path.join('.'))\n : xstateError(23, path.join('.'))\n );\n if (\n !stateValue ||\n typeof stateValue !== 'object' ||\n Array.isArray(stateValue)\n ) {\n throw invalidValue(22);\n }\n const keys = Object.keys(stateValue);\n if (keys.length > 1 && node.type !== 'parallel') {\n throw invalidValue(23);\n }\n for (const key of keys) {\n const childNode = node.states[key];\n if (!childNode) {\n throw new InvalidSnapshotError(\n isDevelopment\n ? `Persisted snapshot references state '${path.concat(key).join('.')}' which does not exist on ${describeMachine(machine.id)}.`\n : xstateError(21, path.concat(key).join('.'))\n );\n }\n validatePersistedStateValue(\n machine,\n\n (stateValue as Record<string, unknown>)[key],\n childNode,\n path.concat(key)\n );\n }\n}\n\nexport function validatePersistedSnapshot(\n machine: AnyStateMachine,\n snapshot: unknown\n): {\n nodes: AnyStateNode[];\n childLogics: Map<string, AnyActorLogic>;\n} {\n if (!isSnapshotRecord(snapshot)) {\n throw new InvalidSnapshotError(\n isDevelopment\n ? `Persisted snapshot for ${describeMachine(machine.id)} must be an object.`\n : xstateError(24, machine.id)\n );\n }\n if (snapshot.value === undefined) {\n throw new InvalidSnapshotError(\n isDevelopment\n ? `Persisted snapshot for ${describeMachine(machine.id)} has no state value.`\n : xstateError(25, machine.id)\n );\n }\n validatePersistedStateValue(machine, snapshot.value, machine.root, []);\n const nodes = Array.from(\n getAllStateNodes(getStateNodes(machine.root, snapshot.value as StateValue))\n );\n if (!isSnapshotRecord(snapshot.children)) {\n throw new InvalidSnapshotError(\n isDevelopment\n ? \"Persisted snapshot has invalid 'children'.\"\n : xstateError(26)\n );\n }\n const childLogics = new Map<string, AnyActorLogic>();\n for (const [id, child] of Object.entries(snapshot.children)) {\n if (\n !isSnapshotRecord(child) ||\n (child.remote !== undefined && typeof child.remote !== 'boolean') ||\n (child.address !== undefined && typeof child.address !== 'string') ||\n (child.syncSnapshot !== undefined &&\n typeof child.syncSnapshot !== 'boolean') ||\n (child.registryKey !== undefined &&\n typeof child.registryKey !== 'string') ||\n (child.incarnation !== undefined &&\n typeof child.incarnation !== 'string') ||\n (child.snapshot !== undefined && !isSnapshotRecord(child.snapshot))\n ) {\n throw new InvalidSnapshotError(\n isDevelopment\n ? `Persisted snapshot has invalid child '${id}'.`\n : xstateError(27, id)\n );\n }\n if (child.remote === true) {\n if (typeof child.address !== 'string' || typeof child.src !== 'string') {\n throw new InvalidSnapshotError(\n isDevelopment\n ? `Unable to restore remote child '${id}': a child referenced by address requires a registered source key and an address.`\n : xstateError(28, id)\n );\n }\n continue;\n }\n if (\n child.src !== undefined &&\n typeof child.src !== 'string' &&\n !isActorLogic(child.src)\n ) {\n throw new InvalidSnapshotError(\n isDevelopment\n ? `Persisted snapshot has invalid child '${id}'.`\n : xstateError(27, id)\n );\n }\n try {\n const logic =\n child.src === undefined\n ? resolveInvokedActorLogic(machine, nodes, id)\n : typeof child.src === 'string'\n ? Object.hasOwn(machine.sources.actors, child.src)\n ? machine.sources.actors[child.src]\n : undefined\n : child.src;\n if (!logic) {\n throw new InvalidSnapshotError(\n isDevelopment\n ? `Unable to restore child actor '${id}': child source '${typeof child.src === 'string' ? child.src : '<inline>'}' is not provided in ${describeMachine(machine.id)}.`\n : xstateError(\n 29,\n id,\n typeof child.src === 'string' ? child.src : '<inline>'\n )\n );\n }\n childLogics.set(id, logic);\n } catch (error) {\n if (error instanceof InvalidSnapshotError) {\n throw error;\n }\n throw new InvalidSnapshotError(\n error instanceof Error\n ? error.message\n : isDevelopment\n ? `Unable to restore child actor '${id}'.`\n : xstateError(30, id)\n );\n }\n }\n if (snapshot.timers !== undefined && !Array.isArray(snapshot.timers)) {\n throw new InvalidSnapshotError(\n isDevelopment\n ? \"Persisted snapshot has invalid 'timers'.\"\n : xstateError(31)\n );\n }\n for (const timer of snapshot.timers ?? []) {\n if (\n !isSnapshotRecord(timer) ||\n typeof timer.delay !== 'number' ||\n (timer.type !== '@xstate.raise' && timer.type !== '@xstate.sendTo') ||\n !isSnapshotRecord(timer.event) ||\n typeof timer.event.type !== 'string' ||\n (timer.id !== undefined && typeof timer.id !== 'string') ||\n (timer.seq !== undefined && typeof timer.seq !== 'number') ||\n (timer.scheduledAt !== undefined &&\n typeof timer.scheduledAt !== 'number') ||\n !(\n typeof timer.target === 'string' ||\n (isSnapshotRecord(timer.target) && timer.target.type === 'parent') ||\n isSerializedActorRef(timer.target)\n )\n ) {\n throw new InvalidSnapshotError(\n isDevelopment\n ? 'Persisted snapshot has invalid timer.'\n : xstateError(32)\n );\n }\n if (\n typeof timer.target === 'string' &&\n timer.target !== 'self' &&\n !Object.hasOwn(snapshot.children, timer.target)\n ) {\n throw new InvalidSnapshotError(\n isDevelopment\n ? `Unable to restore timer: target actor '${timer.target}' is unavailable.`\n : xstateError(33, timer.target)\n );\n }\n }\n return { nodes, childLogics };\n}\n","const cache = new WeakMap<any, any>();\n\nexport function memo<T>(object: any, key: string, fn: () => T): T {\n let memoizedData = cache.get(object);\n\n if (!memoizedData) {\n memoizedData = { [key]: fn() };\n cache.set(object, memoizedData);\n } else if (!(key in memoizedData)) {\n memoizedData[key] = fn();\n }\n\n return memoizedData[key];\n}\n","import isDevelopment from '#is-development';\nimport { xstateError } from './xstateError.ts';\nimport { NULL_EVENT, STATE_DELIMITER } from './constants.ts';\nimport type { SetupStateSchemas } from './schema.types.ts';\nimport { memo } from './memo.ts';\nimport {\n evaluateCandidate,\n formatTransition,\n getCandidates,\n getDelayedTransitions,\n matchesActorSession,\n type TransitionSelectionResults\n} from './stateUtils.ts';\nimport type {\n DelayedTransitionDefinition,\n EventObject,\n TimerKey,\n InitialTransitionDefinition,\n MachineContext,\n Mapper,\n TransitionDefinition,\n TransitionDefinitionMap,\n AnyStateMachine,\n AnyStateNodeConfig,\n EventDescriptor,\n AnyActorScope,\n AnyStateNode,\n AnyEventObject,\n AnyAction,\n AnyTransitionConfig,\n AnyTransitionDefinition,\n AnyMachineSnapshot,\n AnyInvokeDefinition,\n InvokeDefinition,\n MetaObject\n} from './types.ts';\nimport type { NonReducibleUnknown } from './typeUtils.ts';\nimport {\n createInvokeId,\n hasUnescapedDot,\n mapValues,\n toArray,\n toTransitionConfigArray\n} from './utils.ts';\n\nconst EMPTY_OBJECT = {};\nconst CHOICE_CONFIG_KEYS = [\n 'invoke',\n 'after',\n 'on',\n 'entry',\n 'exit',\n 'always',\n 'states',\n 'initial',\n 'onDone',\n 'timeout',\n 'onTimeout',\n 'history',\n 'target',\n 'output'\n] as const;\n\ninterface StateNodeOptions<\n TStateMeta extends MetaObject,\n TTransitionMeta extends MetaObject\n> {\n _key: string;\n _parent?: StateNode<any, any, TStateMeta, TTransitionMeta>;\n _machine: AnyStateMachine;\n}\n\n/** @public */\nexport class StateNode<\n TContext extends MachineContext = MachineContext,\n TEvent extends EventObject = EventObject,\n TStateMeta extends MetaObject = any,\n TTransitionMeta extends MetaObject = TStateMeta\n> {\n /**\n * The relative key of the state node, which represents its location in the\n * overall state value.\n */\n public key: string;\n /** The unique ID of the state node. */\n public id: string;\n /**\n * The type of this state node:\n *\n * - `'atomic'` - no child state nodes\n * - `'compound'` - nested child state nodes (XOR)\n * - `'parallel'` - orthogonal nested child state nodes (AND)\n * - `'history'` - history state node\n * - `'choice'` - pure routing decision state node\n * - `'final'` - final state node\n */\n public type:\n | 'atomic'\n | 'compound'\n | 'parallel'\n | 'final'\n | 'history'\n | 'choice';\n /** The string path from the root machine node to this node. */\n public path: string[];\n /** The child state nodes. */\n public states: Record<\n string,\n StateNode<TContext, TEvent, TStateMeta, TTransitionMeta>\n >;\n /**\n * The type of history on this state node. Can be:\n *\n * - `'shallow'` - recalls only top-level historical state value\n * - `'deep'` - recalls historical state value at all levels\n */\n public history: false | 'shallow' | 'deep';\n /** The action(s) to be executed upon entering the state node. */\n public entry: AnyAction | undefined;\n /** The action(s) to be executed upon exiting the state node. */\n public exit: AnyAction | undefined;\n /** The parent state node. */\n public parent?: StateNode<TContext, TEvent, TStateMeta, TTransitionMeta>;\n /** The root machine node. */\n public machine: AnyStateMachine;\n /**\n * The meta data associated with this state node, which will be returned in\n * State instances.\n */\n public meta?: TStateMeta;\n /**\n * The output data sent with the `xstate.done.state` event if this is a final\n * state node.\n */\n public output?:\n | Mapper<MachineContext, EventObject, unknown, EventObject>\n | NonReducibleUnknown;\n\n /**\n * The order this state node appears. Corresponds to the implicit document\n * order.\n */\n public order: number = -1;\n\n public description?: string;\n\n public schemas: SetupStateSchemas | undefined;\n\n public tags: string[] = [];\n public transitions!: Map<\n string,\n TransitionDefinition<any, any, TTransitionMeta>[]\n >;\n public always?: Array<TransitionDefinition<any, any, TTransitionMeta>>;\n public invoke: Array<\n InvokeDefinition<any, any, any, TTransitionMeta, any, any, any, any>\n >;\n public on!: TransitionDefinitionMap<any, any, TTransitionMeta>;\n public after!: Array<DelayedTransitionDefinition<any, any, TTransitionMeta>>;\n public events!: Array<EventDescriptor<any>>;\n public ownEvents!: Array<EventDescriptor<any>>;\n private _candidateCache?: Map<string, AnyTransitionDefinition[]>;\n\n constructor(\n /** The raw config used to create the machine. */\n public config: AnyStateNodeConfig,\n options: StateNodeOptions<TStateMeta, TTransitionMeta>\n ) {\n this.parent = options._parent;\n this.key = options._key;\n this.machine = options._machine;\n if (this.parent && hasUnescapedDot(this.key)) {\n throw new Error(\n isDevelopment\n ? // The suggestion is written as a JS string literal.\n `State key \"${this.key}\" contains \".\" — nest the states or escape it as \"${this.key.replaceAll(/(?<!\\\\)\\./g, '\\\\\\\\.')}\".`\n : xstateError(57, this.key)\n );\n }\n this.path = this.parent ? this.parent.path.concat(this.key) : [];\n const firstStateKey = this.config.states\n ? Object.keys(this.config.states)[0]\n : undefined;\n // The implicit id is the path from the root, prefixed by the machine id\n // when it has one: `shop.checkout`, or `checkout` without a machine id.\n this.id =\n this.config.id ||\n (this.machine.id ? [this.machine.id, ...this.path] : this.path).join(\n STATE_DELIMITER\n );\n this.type =\n this.config.type ||\n (firstStateKey !== undefined\n ? 'compound'\n : this.config.history\n ? 'history'\n : 'atomic');\n this.description = this.config.description;\n this.schemas = this.config.schemas;\n\n validateStateNodeConfig(this);\n if (isDevelopment) {\n warnOnFinalStateBehavior(this);\n }\n\n const existing = this.machine.idMap.get(this.id);\n // Valid keys escape their dots, so two implicit ids cannot coincide; an\n // explicit id that equals another id would make `#id` ambiguous.\n if (existing) {\n throw new Error(\n isDevelopment\n ? `Duplicate state id '${this.id}': the states at '${existing.path.join(STATE_DELIMITER)}' and '${this.path.join(STATE_DELIMITER)}' both have it. State ids must be unique; rename the explicit \\`id\\`.`\n : xstateError(58, this.id)\n );\n }\n this.order = this.machine.idMap.size;\n this.machine.idMap.set(this.id, this);\n\n this.states = (\n this.config.states\n ? mapValues(\n this.config.states,\n (stateConfig: AnyStateNodeConfig, key) => {\n const stateNode = new StateNode<\n any,\n any,\n TStateMeta,\n TTransitionMeta\n >(stateConfig, {\n _parent: this,\n _key: key,\n _machine: this.machine\n });\n return stateNode;\n }\n )\n : EMPTY_OBJECT\n ) as typeof this.states;\n\n if (this.type === 'compound' && !this.config.initial) {\n throw new Error(\n isDevelopment\n ? `No initial state specified for compound state node \"#${\n this.id\n }\". Try adding { initial: \"${firstStateKey}\" } to the state config.`\n : xstateError(59, this.id)\n );\n }\n\n // History config\n this.history =\n this.config.history === true ? 'shallow' : this.config.history || false;\n\n this.entry = this.config.entry as AnyAction | undefined;\n this.exit = this.config.exit as AnyAction | undefined;\n\n this.meta = this.config.meta;\n this.output =\n this.type === 'final' || !this.parent ? this.config.output : undefined;\n this.tags = toArray(config.tags).slice();\n this.invoke = toArray(this.config.invoke).map((invokeConfig, i) => {\n const { src, registryKey } = invokeConfig;\n const invokeId = createInvokeId(this.id, i);\n const resolvedId = invokeConfig.id ?? invokeId;\n\n return {\n ...invokeConfig,\n // Registered (string) sources persist by key; inline logic has no\n // source key and restores through this invoke definition's id.\n src: typeof src === 'string' ? src : undefined,\n logic: src,\n id: resolvedId,\n registryKey\n } as AnyInvokeDefinition;\n }) as typeof this.invoke;\n }\n\n /** @internal */\n public _initialize() {\n this.after = getDelayedTransitions(this) as any;\n this.transitions = formatTransitions(this) as typeof this.transitions;\n if (this.type === 'choice') {\n this.always = formatChoiceTransitions(this) as typeof this.always;\n } else if (this.config.always) {\n this.always = mapTransitionConfigs(\n this,\n 'always',\n this.config.always,\n (transition) => formatTransition(this, NULL_EVENT, transition)\n ) as typeof this.always;\n }\n\n for (const key of Object.keys(this.states)) {\n this.states[key]._initialize();\n }\n\n this._refreshEventMetadata();\n }\n\n /** @internal */\n public _refreshEventMetadata() {\n const on = {} as TransitionDefinitionMap<any, any, TTransitionMeta>;\n const ownEvents: EventDescriptor<any>[] = [];\n for (const [descriptor, transitions] of this.transitions) {\n (on as any)[descriptor] = transitions.slice();\n if (\n transitions.some(\n (transition) =>\n transition.target || transition.reenter || transition.to\n )\n ) {\n ownEvents.push(descriptor);\n }\n }\n this.on = on;\n this.ownEvents = ownEvents;\n\n const events = new Set<EventDescriptor<any>>(ownEvents);\n for (const state of Object.values(this.states)) {\n for (const event of state.events) {\n events.add(event);\n }\n }\n this.events = Array.from(events);\n }\n\n public get initial(): InitialTransitionDefinition<TTransitionMeta> {\n return memo(this, 'initial', () =>\n formatInitialTransition(this, this.config.initial)\n ) as InitialTransitionDefinition<TTransitionMeta>;\n }\n\n /** @internal */\n public next(\n snapshot: AnyMachineSnapshot,\n event: AnyEventObject,\n actorScope: AnyActorScope,\n selectionResults?: TransitionSelectionResults\n ): Array<AnyTransitionDefinition> | undefined {\n // Final states are inert: as in SCXML, they take no transitions.\n if (this.type === 'final') {\n return undefined;\n }\n let candidates = this._candidateCache?.get(event.type);\n if (!candidates) {\n candidates = getCandidates(this, event);\n (this._candidateCache ??= new Map()).set(event.type, candidates);\n }\n\n for (const candidate of candidates) {\n const guardPassed = evaluateCandidate(\n candidate,\n event,\n snapshot,\n this,\n actorScope,\n selectionResults\n );\n\n if (guardPassed) {\n return [candidate];\n }\n }\n\n return undefined;\n }\n}\n\nfunction validateStateNodeConfig(stateNode: AnyStateNode) {\n const config = stateNode.config as any;\n\n if (\n stateNode.type === 'history' &&\n !(\n (typeof config.target === 'string' && config.target.trim().length > 0) ||\n (Array.isArray(config.target) &&\n config.target.length > 0 &&\n config.target.every(\n (target: unknown) =>\n typeof target === 'string' && target.trim().length > 0\n ))\n )\n ) {\n throw new Error(\n isDevelopment\n ? `History state \"${stateNode.id}\" must declare a non-empty \\`target\\`.`\n : xstateError(60, stateNode.id)\n );\n }\n\n if (stateNode.type !== 'choice') {\n if (isDevelopment && config.choice !== undefined) {\n throw new Error(\n `State \"${stateNode.id}\" has \\`choice\\`, but \\`choice\\` can only be used with \\`type: 'choice'\\`.`\n );\n }\n return;\n }\n\n if (typeof config.choice !== 'function') {\n throw new Error(\n isDevelopment\n ? `Choice state \"${stateNode.id}\" must declare a \\`choice\\` function.`\n : xstateError(61, stateNode.id)\n );\n }\n\n if (isDevelopment) {\n for (const key of CHOICE_CONFIG_KEYS) {\n if (config[key] !== undefined) {\n throw new Error(\n `Choice state \"${stateNode.id}\" cannot declare \\`${key}\\`.`\n );\n }\n }\n }\n}\n\nconst FINAL_STATE_IGNORED_KEYS = ['invoke', 'on', 'after'] as const;\n\n/**\n * Final states are inert: their `invoke`, `on` and `after` never run. Warn\n * instead of silently ignoring them.\n */\nfunction warnOnFinalStateBehavior(stateNode: AnyStateNode): void {\n if (stateNode.type !== 'final') {\n return;\n }\n const config = stateNode.config as Record<string, unknown>;\n const declared = FINAL_STATE_IGNORED_KEYS.filter(\n (key) => config[key] !== undefined\n );\n if (declared.length) {\n console.warn(\n `State \"${stateNode.id}\" is final and declares ${declared\n .map((key) => `\"${key}\"`)\n .join(', ')}; final states cannot run actors or take transitions.`\n );\n }\n}\n\nfunction formatChoiceTransitions(\n stateNode: AnyStateNode\n): AnyTransitionDefinition[] {\n const choice = (stateNode.config as any).choice;\n const validateChoiceResult = (result: any): AnyTransitionConfig => {\n if (!result || result.target === undefined) {\n throw new Error(\n isDevelopment\n ? `Choice state \"${stateNode.id}\" must resolve to a target.`\n : xstateError(62, stateNode.id)\n );\n }\n if (isDevelopment) {\n for (const key of ['actions', 'to'] as const) {\n if (result[key] !== undefined) {\n throw new Error(\n `Choice state \"${stateNode.id}\" cannot declare \\`${key}\\` on a choice.`\n );\n }\n }\n }\n return result;\n };\n\n return [\n formatTransition(stateNode, NULL_EVENT, {\n to: (args: any) => validateChoiceResult(choice(args))\n } as AnyTransitionConfig)\n ];\n}\n\nfunction mapTransitionConfigs<T>(\n stateNode: AnyStateNode,\n name: string,\n transitionsConfig: unknown,\n mapper: (transition: AnyTransitionConfig) => T\n): T[] {\n const transitionConfigs = toTransitionConfigArray(\n transitionsConfig as any,\n name,\n stateNode.id\n );\n const transitions = new Array<T>(transitionConfigs.length);\n\n for (let i = 0; i < transitionConfigs.length; i++) {\n transitions[i] = mapper(transitionConfigs[i]);\n }\n\n return transitions;\n}\n\nfunction formatTransitions<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n stateNode: AnyStateNode\n): Map<string, TransitionDefinition<TContext, TEvent>[]> {\n const transitions = new Map<\n string,\n TransitionDefinition<TContext, AnyEventObject>[]\n >();\n const addTransitions = (\n descriptor: string,\n additions: AnyTransitionDefinition[]\n ) => {\n transitions.set(descriptor, [\n ...(transitions.get(descriptor) ?? []),\n ...additions\n ]);\n };\n if (stateNode.config.on) {\n for (const descriptor of Object.keys(stateNode.config.on)) {\n if (descriptor === NULL_EVENT) {\n throw new Error(\n isDevelopment\n ? 'Null events (\"\") cannot be specified as a transition key. Use `always: { ... }` instead.'\n : xstateError(63, stateNode.id)\n );\n }\n const transitionsConfig = stateNode.config.on[descriptor];\n transitions.set(\n descriptor,\n mapTransitionConfigs(\n stateNode,\n descriptor,\n transitionsConfig,\n (transition) => formatTransition(stateNode, descriptor, transition)\n )\n );\n }\n }\n if (stateNode.config.onDone) {\n const descriptor = 'xstate.done.state';\n addTransitions(\n descriptor,\n mapTransitionConfigs(\n stateNode,\n 'onDone',\n stateNode.config.onDone,\n (transition) =>\n formatTransition(stateNode, descriptor, {\n ...transition,\n matches: { ...transition.matches, stateId: stateNode.id }\n })\n )\n );\n }\n if (stateNode.config.onError) {\n const descriptor = 'xstate.error.*';\n transitions.set(\n descriptor,\n mapTransitionConfigs(\n stateNode,\n 'onError',\n stateNode.config.onError,\n (transition) => formatTransition(stateNode, descriptor, transition)\n )\n );\n }\n const createCancelInvokeTimeoutTransition = (\n descriptor: string,\n timeoutKey: TimerKey,\n actorId: string\n ): AnyTransitionDefinition =>\n formatTransition(stateNode, descriptor, {\n matches: { actorId },\n _eventMatcher: (event: EventObject, snapshot: AnyMachineSnapshot) =>\n matchesActorSession(event, snapshot, actorId),\n to: (_args: any, enq: any) => {\n enq.cancel(timeoutKey);\n return {};\n }\n } as AnyTransitionConfig);\n const formatInvokeCompletionTransition = (\n descriptor: string,\n transitionConfig: AnyTransitionConfig,\n timeoutKey: TimerKey\n ): AnyTransitionDefinition => {\n const { target, to, reenter, ...rest } = transitionConfig;\n\n return formatTransition(stateNode, descriptor, {\n ...rest,\n reenter,\n to: (args: any, enq: any) => {\n if (to) {\n let didEnqueue = false;\n const trackingEnqueue = new Proxy(enq, {\n apply(target, thisArg, argArray) {\n didEnqueue = true;\n return Reflect.apply(target, thisArg, argArray);\n },\n get(target, prop, receiver) {\n const value = Reflect.get(target, prop, receiver);\n\n if (typeof value !== 'function') {\n return value;\n }\n\n return (...argArray: any[]) => {\n didEnqueue = true;\n return value.apply(target, argArray);\n };\n }\n });\n const result = to(args, trackingEnqueue);\n\n if (result !== undefined || didEnqueue) {\n enq.cancel(timeoutKey);\n }\n\n return result;\n }\n\n enq.cancel(timeoutKey);\n return {\n target,\n reenter\n };\n }\n } as AnyTransitionConfig);\n };\n for (const invokeDef of stateNode.invoke) {\n const withInvokeMatch = (transition: AnyTransitionConfig) => ({\n ...transition,\n matches: { ...transition.matches, actorId: invokeDef.id },\n _eventMatcher: (event: EventObject, snapshot: AnyMachineSnapshot) =>\n matchesActorSession(event, snapshot, invokeDef.id)\n });\n // Built-in timers have no id; the invoke timeout is keyed by its event.\n const invokeTimeoutKey: TimerKey | undefined =\n invokeDef.timeout !== undefined\n ? {\n event: {\n type: 'xstate.timeout.actor',\n actorId: invokeDef.id\n } as EventObject\n }\n : undefined;\n\n if (invokeDef.onDone) {\n const descriptor = 'xstate.done.actor';\n const invokeDoneTransitions = mapTransitionConfigs(\n stateNode,\n 'invoke.onDone',\n invokeDef.onDone,\n (rawTransition) => {\n const transition = withInvokeMatch(rawTransition);\n return invokeTimeoutKey\n ? formatInvokeCompletionTransition(\n descriptor,\n transition,\n invokeTimeoutKey\n )\n : formatTransition(stateNode, descriptor, transition);\n }\n );\n\n if (invokeTimeoutKey) {\n invokeDoneTransitions.push(\n createCancelInvokeTimeoutTransition(\n descriptor,\n invokeTimeoutKey,\n invokeDef.id\n )\n );\n }\n\n addTransitions(descriptor, invokeDoneTransitions);\n } else if (invokeTimeoutKey) {\n const descriptor = 'xstate.done.actor';\n addTransitions(descriptor, [\n createCancelInvokeTimeoutTransition(\n descriptor,\n invokeTimeoutKey,\n invokeDef.id\n )\n ]);\n }\n if (invokeDef.onError) {\n const descriptor = 'xstate.error.actor';\n addTransitions(\n descriptor,\n mapTransitionConfigs(\n stateNode,\n 'invoke.onError',\n invokeDef.onError,\n (rawTransition) => {\n const transition = withInvokeMatch(rawTransition);\n return invokeTimeoutKey\n ? formatInvokeCompletionTransition(\n descriptor,\n transition,\n invokeTimeoutKey\n )\n : formatTransition(stateNode, descriptor, transition);\n }\n )\n );\n }\n if (invokeDef.onSnapshot) {\n const descriptor = 'xstate.snapshot.actor';\n addTransitions(\n descriptor,\n mapTransitionConfigs(\n stateNode,\n 'invoke.onSnapshot',\n invokeDef.onSnapshot,\n (transition) =>\n formatTransition(stateNode, descriptor, withInvokeMatch(transition))\n )\n );\n }\n }\n for (const delayedTransition of stateNode.after) {\n let existing = transitions.get(delayedTransition.eventType);\n if (!existing) {\n existing = [];\n transitions.set(delayedTransition.eventType, existing);\n }\n existing.push(\n delayedTransition as TransitionDefinition<TContext, AnyEventObject>\n );\n }\n return transitions as Map<string, TransitionDefinition<TContext, any>[]>;\n}\n\nfunction formatInitialTransition(\n stateNode: AnyStateNode,\n _target:\n | string\n | {\n target: string | string[];\n input?: any;\n to?: (...args: any[]) => any;\n meta?: any;\n description?: string;\n }\n | undefined\n): InitialTransitionDefinition {\n const targetString =\n typeof _target === 'object' && _target !== null ? _target.target : _target;\n const input =\n typeof _target === 'object' && _target !== null ? _target.input : undefined;\n const to =\n typeof _target === 'object' && _target !== null ? _target.to : undefined;\n const meta =\n typeof _target === 'object' && _target !== null ? _target.meta : undefined;\n const description =\n typeof _target === 'object' && _target !== null\n ? _target.description\n : undefined;\n const targetStrings = Array.isArray(targetString)\n ? targetString\n : targetString\n ? [targetString]\n : [];\n const resolvedTargets = targetStrings.map((target) =>\n target.startsWith('#')\n ? stateNode.machine.getStateNodeById(target.slice(1))\n : stateNode.states[target]\n );\n if (resolvedTargets.some((target) => !target)) {\n throw new Error(\n isDevelopment\n ? `Initial state node \"${targetStrings.find((_, index) => !resolvedTargets[index])}\" not found on parent state node #${stateNode.id}`\n : xstateError(\n 64,\n targetStrings.find((_, index) => !resolvedTargets[index]),\n stateNode.id\n )\n );\n }\n const transition: InitialTransitionDefinition = {\n source: stateNode,\n target: resolvedTargets.length\n ? (resolvedTargets as AnyStateNode[])\n : undefined,\n input,\n to,\n meta,\n description\n };\n\n return transition;\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 isDevelopment from '#is-development';\nimport { xstateError } from './xstateError.ts';\nimport { createActor } from './createActor.ts';\nimport { createErrorPlatformEvent, createInitEvent } from './eventUtils.ts';\nimport { STATE_DELIMITER, XSTATE_TIMER } from './constants.ts';\n\nimport { createSpawner } from './spawn.ts';\nimport {\n attachSnapshotActorRef,\n createInertActorScope,\n isInertActorScope,\n setInertActorScopeSnapshot\n} from './inertActorScope.ts';\nimport { withActorSelf } from './actorScope.ts';\nimport {\n createMachineSnapshot,\n cloneMachineSnapshot,\n freezeContext,\n getPersistedSnapshot,\n MachineSnapshot\n} from './State.ts';\nimport { setSnapshotActorRef } from './snapshotActorRef.ts';\nimport { StateNode } from './StateNode.ts';\nimport {\n formatRouteTransitions,\n getAllStateNodes,\n getStateNodes,\n getTransitionResult,\n hasEffect,\n initialMicrostep,\n isInFinalState,\n isStateId,\n macrostep,\n resolveStateValue,\n transitionNode,\n type TransitionSelectionResults\n} from './stateUtils.ts';\nimport {\n beginSpawnAllocation,\n createDeadLetterEffect,\n createSpawnEffect,\n createStartEffect,\n detachedScopes,\n resolveActionsWithContext,\n mergeActorIdCounters,\n takeSpawnAllocationCounters\n} from './transitionActions.ts';\nimport { AnyActorSystem, type DeadLetterDetail } from './system.ts';\nimport type {\n ActorLogic,\n ActorLogicTransitionResult,\n ActorScope,\n AnyActor,\n AnyActorLogic,\n AnyActorRef,\n AnyActorScope,\n AnyEventObject,\n AnyStateMachine,\n AnyMachineSnapshot,\n AnyTransitionDefinition,\n EventDescriptor,\n EmittedFrom,\n EventObject,\n EventFromLogic,\n ExecutableEffect,\n ExecutableEffectFrom,\n HistoryValue,\n InputFrom,\n MachineContext,\n MetaObject,\n OutputFrom,\n SnapshotFrom,\n StateValue,\n StateSchema,\n SnapshotStatus,\n AnyStateNode\n} from './types.ts';\nimport type { Equals, IsAny } from './typeUtils.ts';\nimport {\n AnyMachineSchemas,\n DelaySourceMap,\n GuardSourceMap,\n Sources,\n Next_MachineConfig,\n MachineOptions\n} from './types.v6.ts';\nimport {\n describeMachine,\n assertUnreservedSourceName,\n matchesEventDescriptor,\n toStatePath\n} from './utils.ts';\nimport { assertValid } from './validation.ts';\nimport type { ActorLogicValidator } from './validation.types.ts';\n\nconst STATE_IDENTIFIER = '#';\n\nlet emptyCanActor: AnyActor | undefined;\nlet emptyCanActorScope: AnyActorScope | undefined;\n\nfunction getEmptyCanActor(): AnyActor {\n // A minimal inert actor used purely as the `self`/`parent` argument when\n // dry-running transitions for `snapshot.can(...)`. Intentionally not built\n // on `createStepLogic` so `can()` does not pull that machinery into bundles.\n return (emptyCanActor ??= createActor({\n transition: (snapshot: any) => [snapshot, []],\n initialTransition: () => [\n { status: 'active', output: undefined, error: undefined },\n []\n ],\n getInitialSnapshot: () => ({\n status: 'active',\n output: undefined,\n error: undefined\n }),\n getPersistedSnapshot: (snapshot: any) => snapshot\n } as any) as AnyActor);\n}\n\nfunction getEmptyCanActorScope(): AnyActorScope {\n if (emptyCanActorScope) {\n return emptyCanActorScope;\n }\n\n const actor = getEmptyCanActor();\n emptyCanActorScope = {\n self: actor,\n logger: () => {},\n id: '',\n sessionId: '',\n defer: () => {},\n system: actor.system,\n stopChild: () => {},\n emit: () => {},\n actionExecutor: () => {}\n };\n detachedScopes.add(emptyCanActorScope);\n return emptyCanActorScope;\n}\n\nexport type CompatibleProvidedActorSource<\n TExpected extends AnyActorLogic,\n TActual extends AnyActorLogic\n> =\n IsAny<TActual> extends true\n ? TActual\n : [OutputFrom<TActual>] extends [OutputFrom<TExpected>]\n ? [Omit<SnapshotFrom<TActual>, 'input'>] extends [\n Omit<SnapshotFrom<TExpected>, 'input'>\n ]\n ? [InputFrom<TExpected>] extends [InputFrom<TActual>]\n ? [EventFromLogic<TExpected>] extends [EventFromLogic<TActual>]\n ? [EmittedFrom<TActual>] extends [EmittedFrom<TExpected>]\n ? TActual\n : never\n : never\n : never\n : never\n : never;\n\ntype ProvidedActors<\n TExpectedActorMap extends Sources['actors'],\n TProvidedActorMap extends Partial<\n Record<keyof TExpectedActorMap & string, AnyActorLogic>\n >\n> = {\n [K in keyof TProvidedActorMap]: K extends keyof TExpectedActorMap\n ? TProvidedActorMap[K] extends AnyActorLogic\n ? CompatibleProvidedActorSource<\n TExpectedActorMap[K],\n TProvidedActorMap[K]\n >\n : never\n : never;\n};\n\n// A required override replaces its source; an optional override may leave\n// the original source in place. Keep both types in that case.\ntype ProvidedSourceMap<TDeclared, TProvided> = {\n [K in keyof TDeclared]: K extends keyof TProvided\n ? {} extends Pick<TProvided, K>\n ? TDeclared[K] | Exclude<TProvided[K], undefined>\n : Exclude<TProvided[K], undefined>\n : TDeclared[K];\n};\n\n// The action as the machine declared it. A provided action keeps its own type,\n// so integrations can infer from what it returns, and records the declared one,\n// so that the next `provide(...)` is checked against the same contract.\ntype DeclaredAction<T> = T extends {\n readonly '~declaredAction'?: infer TDeclared;\n}\n ? unknown extends TDeclared\n ? T\n : Exclude<TDeclared, undefined>\n : T;\n\ntype ProvidedActionSourceMap<TDeclared, TProvided> = {\n [K in keyof TDeclared]: K extends keyof TProvided\n ? ({} extends Pick<TProvided, K>\n ? TDeclared[K] | Exclude<TProvided[K], undefined>\n : Exclude<TProvided[K], undefined>) & {\n readonly '~declaredAction'?: DeclaredAction<TDeclared[K]>;\n }\n : TDeclared[K];\n};\n\n// Positional arguments must match the declared action. An action declared to\n// return nothing (or a result that admits `void`, as an action only declared\n// in `schemas.actions` does) is an effect: the implementation may return\n// integration-specific values, such as an Effect. Any other declared result,\n// such as a context patch, can be returned from a transition, which applies\n// it, so the implementation must return a compatible one.\nexport type ProvidedActionContracts<T> = {\n [K in keyof T]: DeclaredAction<T[K]> extends (\n ...args: infer TArgs\n ) => infer TResult\n ? (...args: TArgs) => ProvidedActionResult<TResult>\n : never;\n};\n\n// `Extract` keeps the result within `Sources['actions']`, which declared\n// actions already satisfy.\ntype ProvidedActionResult<TResult> = void extends TResult\n ? void\n : Extract<TResult, ReturnType<Sources['actions'][string]>>;\n\nexport { InvalidSnapshotError } from './persistedSnapshotValidation.ts';\n\n/**\n * The development message for an id that matches no state. When a prefix of\n * the id is a state id and the rest resolves beneath it as a relative path,\n * suggests the target's own id.\n */\nfunction describeUnknownStateId(\n idMap: Map<string, AnyStateNode>,\n id: string\n): string {\n const message = `No state has id \"${id}\".`;\n const segments = toStatePath(id);\n for (let i = segments.length - 1; i > 0; i--) {\n let node: AnyStateNode | undefined = idMap.get(\n segments.slice(0, i).join(STATE_DELIMITER)\n );\n for (let j = i; node && j < segments.length; j++) {\n node = node.states?.[segments[j]];\n }\n if (node) {\n return node.config.id\n ? `${message} Use \"#${node.id}\".`\n : `${message} Use \"#${node.id}\", or give that state an id.`;\n }\n }\n return message;\n}\n\n/** @public */\nexport class StateMachine<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TStateValue extends StateValue,\n TTag extends string,\n TInput,\n TOutput,\n TEmitted extends EventObject,\n TMeta extends MetaObject,\n TConfig extends StateSchema,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays'],\n TInternalEvent extends EventObject = never,\n TTransitionMeta extends MetaObject = TMeta\n> implements ActorLogic<\n MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n TEvent,\n TInput,\n AnyActorSystem,\n TEmitted\n> {\n /**\n * Type-only marker for the actor's internal event protocol. `actor.send` and\n * `actor.trigger` read it to drop internal events from the public protocol,\n * so it must survive `stripInternal` into the published declarations. Not\n * `declare` (the build's babel pipeline rejects declare class fields); the\n * one `undefined` property this emits per machine instance is inert.\n */\n readonly _internalEventType!: TInternalEvent;\n /** Type-only marker for transition metadata. Never assigned at runtime. */\n readonly _transitionMetaType!: TTransitionMeta;\n /**\n * Type-only marker for the declared input type. `getInitialSnapshot` takes\n * input optionally, so inferring input from it always adds `undefined`;\n * `InputFrom` reads this carrier instead. Method-shaped so it stays\n * bivariant like `getInitialSnapshot`. Never assigned at runtime.\n */\n readonly _inputType!: { carry(input: TInput): void }['carry'];\n\n /**\n * Type-level carriers for the machine's source maps and state schema. Type\n * helpers in integration packages read these to walk a machine's declared\n * actions, actors and invoked sources. They are never assigned at runtime.\n */\n readonly _actionMap!: TActionMap;\n readonly _actorMap!: TActorMap;\n readonly _stateSchema!: TConfig;\n\n /** The machine's own version. */\n public version: TConfig extends { version: infer TVersion extends string }\n ? TVersion\n : undefined;\n\n public schemas:\n | (TConfig extends { schemas: infer TSchemas extends AnyMachineSchemas }\n ? TSchemas\n : AnyMachineSchemas)\n | undefined;\n\n public sources: Sources;\n\n /** Runtime options for machine execution. */\n public options: MachineOptions;\n\n /** @internal */\n public idMap: Map<string, AnyStateNode> = new Map();\n\n public root: StateNode<TContext, TEvent, TMeta, TTransitionMeta>;\n\n /**\n * The machine's `id`, or the empty string when the config declares none.\n * The root state node has this id; a machine without one has no `#id` root.\n */\n public id: TConfig extends { id: infer TId extends string } ? TId : '';\n\n public states: StateNode<TContext, TEvent, TMeta, TTransitionMeta>['states'];\n public events: Array<EventDescriptor<TEvent>>;\n public internalEventDescriptors: ReadonlyArray<string>;\n /** @internal Skips eventless-selection scans for machines without `always`. */\n public _hasEventlessTransitions: boolean;\n\n /**\n * Adapter hooks for actor-local transition evaluation state. Used by\n * `@xstate/scxml`; not part of the stable API.\n *\n * @experimental\n */\n public _microstepHooks?: AnyStateMachine['_microstepHooks'];\n\n constructor(\n /** The raw config used to create the machine. */\n public config: Next_MachineConfig<\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any // TEmitted\n > & {\n schemas?: AnyMachineSchemas;\n },\n sources?: Sources,\n public validator?: ActorLogicValidator\n ) {\n if (config.version !== undefined && !config.id) {\n // Persisted snapshots record `{ id, version }`; a version needs an id.\n throw new Error(\n isDevelopment\n ? `Machine with version '${config.version}' must declare an id.`\n : xstateError(18, config.version)\n );\n }\n this.id = (config.id ?? '') as typeof this.id;\n this.sources = {\n actors: config.actors ?? {},\n actions: config.actions ?? {},\n delays: (config.delays ?? {}) as Sources['delays'],\n guards: config.guards ?? {},\n ...sources\n };\n if (isDevelopment) {\n for (const kind of ['actions', 'guards', 'actors', 'delays'] as const) {\n for (const key of Object.keys(this.sources[kind])) {\n assertUnreservedSourceName(kind, key);\n }\n }\n }\n this.version = this.config.version as typeof this.version;\n this.schemas = this.config.schemas as typeof this.schemas;\n this.internalEventDescriptors = Object.keys(\n this.schemas?.internalEvents ?? {}\n );\n this.options = { ...this.config.options };\n\n this.transition = this.transition.bind(this);\n this.initialTransition = this.initialTransition.bind(this);\n this.getInitialSnapshot = this.getInitialSnapshot.bind(this);\n this.getPersistedSnapshot = this.getPersistedSnapshot.bind(this);\n this.start = this.start.bind(this);\n\n this.root = new StateNode<TContext, TEvent, TMeta, TTransitionMeta>(\n config as any,\n {\n _key: this.id,\n _machine: this as any\n }\n );\n\n this.root._initialize();\n formatRouteTransitions(this.root);\n this.root._refreshEventMetadata();\n this._hasEventlessTransitions = Array.from(this.idMap.values()).some(\n (stateNode) => !!stateNode.always?.length\n );\n\n this.states = this.root.states; // TODO: remove!\n this.events = this.root.events;\n }\n\n /**\n * Clones this state machine with the provided sources.\n *\n * @param sources Options (`actions`, `guards`, `actors`, `delays`) to\n * recursively merge with the existing options.\n * @returns A new `StateMachine` instance with the provided sources.\n */\n public provide<\n const TProvidedActorMap extends Partial<\n Record<keyof TActorMap & string, AnyActorLogic>\n > = {},\n const TProvidedActionMap extends Partial<\n ProvidedActionContracts<TActionMap>\n > = {}\n >(sources: {\n actions?: TProvidedActionMap &\n Partial<ProvidedActionContracts<TActionMap>> &\n Record<Exclude<keyof TProvidedActionMap, keyof TActionMap>, never>;\n actors?: TProvidedActorMap & ProvidedActors<TActorMap, TProvidedActorMap>;\n // Mapped over the known names (not an index signature) so unknown source\n // names are still rejected, while entries keep typed args/return values.\n guards?: Partial<TGuardMap> & {\n [K in keyof TGuardMap]?: GuardSourceMap<TContext, TEvent>[string];\n };\n // Delays are widened to `number | fn` per entry (not Partial<TDelayMap>)\n // so a fixed delay can be swapped for a computed one and vice versa.\n delays?: {\n [K in keyof TDelayMap]?: DelaySourceMap<TContext, TEvent>[string];\n };\n }): StateMachine<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TInput,\n TOutput,\n TEmitted,\n TMeta,\n TConfig,\n ProvidedActionSourceMap<TActionMap, TProvidedActionMap>,\n ProvidedSourceMap<TActorMap, TProvidedActorMap>,\n TGuardMap,\n TDelayMap,\n TInternalEvent,\n TTransitionMeta\n > {\n const { actions, guards, actors, delays } = this.sources;\n\n const provided = new StateMachine(\n this.config,\n {\n actions: {\n ...actions,\n ...sources.actions\n } as Sources['actions'],\n guards: {\n ...guards,\n ...sources.guards\n } as Sources['guards'],\n actors: {\n ...actors,\n ...sources.actors\n } as Sources['actors'],\n delays: {\n ...delays,\n ...sources.delays\n } as Sources['delays']\n },\n this.validator\n ) as unknown as StateMachine<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TInput,\n TOutput,\n TEmitted,\n TMeta,\n TConfig,\n ProvidedActionSourceMap<TActionMap, TProvidedActionMap>,\n ProvidedSourceMap<TActorMap, TProvidedActorMap>,\n TGuardMap,\n TDelayMap,\n TInternalEvent,\n TTransitionMeta\n >;\n // Providing sources does not change the serializable definition.\n provided._json = this._json;\n provided.internalEventDescriptors = this.internalEventDescriptors;\n provided._microstepHooks = this._microstepHooks;\n return provided;\n }\n\n public resolveState(\n config: {\n value: StateValue;\n context?: TContext;\n historyValue?: HistoryValue;\n status?: SnapshotStatus;\n output?: TOutput;\n error?: unknown;\n } & ([TContext] extends [never]\n ? {}\n : Equals<TContext, MachineContext> extends false\n ? { context: unknown }\n : {})\n ): MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n > {\n const resolvedStateValue = resolveStateValue(this.root, config.value);\n const nodeSet = getAllStateNodes(\n getStateNodes(this.root, resolvedStateValue)\n );\n const nodes = [...nodeSet];\n\n return createMachineSnapshot(\n {\n _nodes: nodes,\n value: resolvedStateValue,\n context: config.context || ({} as TContext),\n children: {},\n status: isInFinalState(nodeSet, this.root)\n ? 'done'\n : config.status || 'active',\n output: config.output,\n error: config.error,\n historyValue: config.historyValue\n },\n this\n ) as MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >;\n }\n\n /**\n * Determines the next snapshot given the current `snapshot` and received\n * `event`. Calculates a full macrostep from all microsteps.\n *\n * @param snapshot The current snapshot\n * @param event The received event\n */\n public transition(\n snapshot: MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n event: TEvent,\n actorScope?: ActorScope<typeof snapshot, TEvent, AnyActorSystem, TEmitted>\n ): ActorLogicTransitionResult<\n MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n ExecutableEffectFrom<this>\n > {\n const usesInertScope = !actorScope;\n const resolvedActorScope = (actorScope ??\n createInertActorScope(\n this,\n snapshot as SnapshotFrom<this>\n )) as NonNullable<typeof actorScope>;\n if (usesInertScope) {\n setInertActorScopeSnapshot(resolvedActorScope, snapshot, false);\n }\n if (this.validator) {\n const sourceRef = actorScope && (actorScope.self as any)._lastSourceRef;\n const eventOrigin = sourceRef ? 'actor' : 'external';\n const error = this.validator.check({\n kind: 'event',\n logic: this,\n event,\n eventOrigin\n });\n if (error) {\n // Boundary fault: an invalid event arriving from outside the machine\n // is rejected (never delivered), not routed to the error channel. The\n // snapshot is returned unchanged; the rejection is represented as an\n // effect so hosts and the actor runtime can report it.\n return [\n snapshot,\n [\n createDeadLetterEffect(\n resolvedActorScope,\n sourceRef,\n event,\n 'invalidEvent',\n {\n issues: (error as { issues?: DeadLetterDetail['issues'] })\n .issues,\n error\n }\n ) as ExecutableEffectFrom<this>\n ]\n ];\n }\n }\n beginSpawnAllocation(resolvedActorScope);\n const fastSnapshot = this._transitionFast(\n snapshot,\n event,\n resolvedActorScope\n );\n if (fastSnapshot) {\n if (usesInertScope) {\n setInertActorScopeSnapshot(resolvedActorScope, fastSnapshot, false);\n }\n const returnedSnapshot =\n usesInertScope && fastSnapshot !== snapshot\n ? attachSnapshotActorRef(resolvedActorScope, fastSnapshot)\n : this._attachPureActorRef(fastSnapshot, resolvedActorScope);\n if (this.validator) {\n assertValid(this.validator, {\n kind: 'result',\n logic: this,\n snapshot: returnedSnapshot,\n effects: []\n });\n }\n return [returnedSnapshot, []];\n }\n\n const { snapshot: nextSnapshot, microsteps } = macrostep(\n snapshot,\n event,\n resolvedActorScope,\n []\n );\n\n if (usesInertScope) {\n setInertActorScopeSnapshot(resolvedActorScope, nextSnapshot, false);\n }\n const returnedSnapshot = usesInertScope\n ? nextSnapshot === snapshot\n ? nextSnapshot\n : attachSnapshotActorRef(resolvedActorScope, nextSnapshot)\n : this._attachPureActorRef(nextSnapshot, resolvedActorScope);\n const effects = this._collectEffects(microsteps);\n if (this.validator) {\n assertValid(this.validator, {\n kind: 'result',\n logic: this,\n snapshot: returnedSnapshot,\n effects\n });\n }\n return [\n returnedSnapshot as MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n effects\n ];\n }\n\n private _collectEffects(\n microsteps: ReadonlyArray<\n readonly [unknown, ReadonlyArray<ExecutableEffect>, ...unknown[]]\n >\n ): ExecutableEffectFrom<this>[] {\n return microsteps.flatMap(\n ([, actions]) => actions\n ) as ExecutableEffectFrom<this>[];\n }\n\n private _attachPureActorRef<TSnapshot extends AnyMachineSnapshot>(\n snapshot: TSnapshot,\n actorScope: AnyActorScope,\n skipInitializingActor = false\n ): TSnapshot {\n if (isInertActorScope(actorScope)) {\n return snapshot;\n }\n if (\n skipInitializingActor &&\n (\n actorScope.self as AnyActor & {\n _actorScope?: AnyActorScope;\n _snapshot?: unknown;\n }\n )._actorScope === actorScope &&\n (actorScope.self as AnyActor & { _snapshot?: unknown })._snapshot ===\n undefined\n ) {\n return snapshot;\n }\n setSnapshotActorRef(snapshot, actorScope.self, actorScope.system);\n return snapshot;\n }\n\n private _transitionFast(\n snapshot: MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n event: TEvent,\n actorScope: ActorScope<typeof snapshot, TEvent, AnyActorSystem, TEmitted>\n ):\n | MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >\n | undefined {\n if (\n snapshot.status !== 'active' ||\n typeof snapshot.value !== 'string' ||\n this.root.always?.length\n ) {\n return undefined;\n }\n\n const sourceNode = this.root.states[snapshot.value];\n if (\n !sourceNode ||\n sourceNode.type !== 'atomic' ||\n sourceNode.exit ||\n sourceNode.invoke.length ||\n sourceNode.always?.length ||\n sourceNode.after?.length\n ) {\n return undefined;\n }\n\n const transitions = sourceNode.transitions.get(event.type);\n if (transitions?.length !== 1) {\n return undefined;\n }\n\n const selected = transitions[0];\n if (\n selected.guard ||\n selected.actions ||\n selected.to ||\n selected.reenter ||\n selected.input ||\n typeof selected.context === 'function' ||\n (selected.target && selected.target.length !== 1)\n ) {\n return undefined;\n }\n\n const targetNode = selected.target?.[0] ?? sourceNode;\n const stateChanged = targetNode !== sourceNode;\n if (\n targetNode.parent !== this.root ||\n targetNode.type !== 'atomic' ||\n (stateChanged &&\n (targetNode.entry ||\n targetNode.invoke.length ||\n targetNode.always?.length ||\n targetNode.after?.length))\n ) {\n return undefined;\n }\n\n const context =\n selected.context !== undefined\n ? ({ ...snapshot.context, ...selected.context } as TContext)\n : snapshot.context;\n\n if (\n !isInertActorScope(actorScope) &&\n (actorScope.system._hasInspectionObservers?.() ?? true)\n ) {\n const collectedMicrosteps =\n ((actorScope.self as any)._collectedMicrosteps as any[]) || [];\n collectedMicrosteps.push(selected);\n (actorScope.self as any)._collectedMicrosteps = collectedMicrosteps;\n }\n\n const rootInput = snapshot._stateInputs[this.root.id];\n return cloneMachineSnapshot(snapshot, {\n ...(context !== snapshot.context ? { context } : {}),\n ...(stateChanged\n ? {\n _nodes: [this.root, targetNode],\n // The source state exited, so only the root input remains.\n _stateInputs: rootInput ? { [this.root.id]: rootInput } : {}\n }\n : {})\n });\n }\n\n /**\n * Determines the next state given the current `state` and `event`. Calculates\n * a microstep.\n *\n * @param state The current state\n * @param event The received event\n */\n public microstep(\n snapshot: MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n event: TEvent,\n actorScope: AnyActorScope\n ): Array<\n MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >\n > {\n const { microsteps } = macrostep(snapshot, event, actorScope, []);\n const snapshots = new Array(microsteps.length);\n\n for (let i = 0; i < microsteps.length; i++) {\n snapshots[i] = microsteps[i][0];\n }\n\n return snapshots;\n }\n\n public getTransitionData(\n snapshot: MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n event: TEvent,\n actorScope: AnyActorScope,\n selectionResults?: TransitionSelectionResults\n ): Array<AnyTransitionDefinition> {\n this._microstepHooks?.begin(actorScope.self);\n return (\n transitionNode(\n this.root,\n snapshot.value,\n snapshot,\n event,\n actorScope,\n selectionResults\n ) || []\n );\n }\n\n public isInternalEventType(eventType: string): boolean {\n if (eventType === XSTATE_TIMER) {\n return true;\n }\n for (const descriptor of this.internalEventDescriptors) {\n if (matchesEventDescriptor(eventType, descriptor)) {\n return true;\n }\n }\n\n return false;\n }\n\n /**\n * Determines whether sending the `event` to the given snapshot would select a\n * non-forbidden transition. Backs `snapshot.can(...)`; lives here so that\n * non-machine bundles don't pay for the transition-resolution machinery.\n *\n * @internal\n */\n public _canTransition(snapshot: AnyMachineSnapshot, event: TEvent): boolean {\n if (snapshot.status !== 'active') {\n return false;\n }\n const emptyActorScope = getEmptyCanActorScope();\n const transitionData = this.getTransitionData(\n snapshot as any,\n event,\n emptyActorScope\n );\n\n if (!transitionData?.length) {\n return false;\n }\n\n // Check that at least one transition is not forbidden\n for (const transition of transitionData) {\n if (transition.target !== undefined) {\n return true;\n }\n\n const res = getTransitionResult(\n transition,\n snapshot,\n event,\n emptyActorScope,\n { resolveActions: false }\n );\n if (\n res.targets?.length ||\n res.context ||\n hasEffect(\n transition,\n snapshot.context,\n event,\n snapshot,\n emptyActorScope\n )\n ) {\n return true;\n }\n }\n\n return false;\n }\n\n /**\n * Returns the error event that the actor should transition with to recover\n * from an execution error, if any active state node declares `onError`.\n *\n * @internal\n */\n public getExecutionErrorEvent(\n snapshot: MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n error: unknown\n ): TEvent | undefined {\n if (\n (snapshot as any)?.status !== 'active' ||\n !snapshot.nodes?.some((stateNode) => stateNode.config.onError)\n ) {\n return undefined;\n }\n return createErrorPlatformEvent('execution', error) as unknown as TEvent;\n }\n\n /**\n * The initial state _before_ evaluating any microsteps. This \"pre-initial\"\n * state is provided to initial actions executed in the initial state.\n *\n * @internal\n */\n _getPreInitialState(\n actorScope: AnyActorScope,\n initEvent: any\n ): MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n > {\n const { context } = this.config;\n\n const preInitial = createMachineSnapshot(\n {\n context:\n typeof context !== 'function' && context ? context : ({} as TContext),\n _nodes: [this.root],\n children: {},\n status: 'active'\n },\n this\n );\n\n if (typeof context === 'function') {\n const children = {};\n const spawn = createSpawner(actorScope, this.sources.actors, children);\n const resolvedContext = context(\n withActorSelf(\n {\n spawn,\n input: initEvent.input,\n actors: this.sources.actors\n },\n actorScope\n )\n );\n const [nextState] = resolveActionsWithContext(\n preInitial,\n initEvent,\n actorScope,\n []\n ) as any;\n if (resolvedContext) {\n nextState.context = resolvedContext;\n if (isDevelopment) {\n freezeContext(resolvedContext);\n }\n }\n if (Object.keys(children).length > 0) {\n nextState.children = {\n ...nextState.children,\n ...children\n };\n // Commit the transaction counters so context-factory allocations\n // persist with the snapshot: a freed id is never handed out again\n // after a restore or in a fresh replay process. (The spawner already\n // registered each child for string-id resolution.)\n const counters = takeSpawnAllocationCounters(actorScope);\n if (counters) {\n nextState._nextActorIds = mergeActorIdCounters(\n nextState._nextActorIds,\n counters\n );\n }\n }\n return nextState as SnapshotFrom<this>;\n }\n\n return preInitial as SnapshotFrom<this>;\n }\n\n /**\n * Returns the initial `State` instance, with reference to `self` as an\n * `ActorRef`.\n */\n public getInitialSnapshot(\n actorScope?: ActorScope<\n MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n TEvent,\n AnyActorSystem,\n TEmitted\n >,\n input?: TInput\n ): MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n > {\n return this.initialTransition(input, actorScope)[0];\n }\n\n public initialTransition(\n input: TInput | undefined,\n actorScope?: ActorScope<\n MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n TEvent,\n AnyActorSystem,\n TEmitted\n >\n ): ActorLogicTransitionResult<\n MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n ExecutableEffectFrom<this>\n > {\n if (this.validator) {\n assertValid(this.validator, {\n kind: 'input',\n logic: this,\n input\n });\n }\n const usesInertScope = !actorScope;\n const resolvedActorScope = (actorScope ??\n createInertActorScope(this)) as NonNullable<typeof actorScope>;\n beginSpawnAllocation(resolvedActorScope);\n const initEvent = createInitEvent(input) as unknown as TEvent; // TODO: fix;\n const internalQueue: AnyEventObject[] = [];\n const finalizeInitialResult = (\n macroState: AnyMachineSnapshot,\n microsteps: ReadonlyArray<\n readonly [unknown, ReadonlyArray<ExecutableEffect>, ...unknown[]]\n >\n ): ActorLogicTransitionResult<\n SnapshotFrom<this>,\n ExecutableEffectFrom<this>\n > => {\n if (usesInertScope) {\n setInertActorScopeSnapshot(resolvedActorScope, macroState, false);\n }\n const returnedSnapshot = usesInertScope\n ? attachSnapshotActorRef(resolvedActorScope, macroState)\n : this._attachPureActorRef(macroState, resolvedActorScope, true);\n const effects = this._collectEffects(microsteps);\n // Error snapshots may carry synthetic context (e.g. when the context\n // factory throws); validating them would mask the original error.\n if (this.validator && macroState.status !== 'error') {\n assertValid(this.validator, {\n kind: 'result',\n logic: this,\n snapshot: returnedSnapshot,\n effects\n });\n }\n return [returnedSnapshot as SnapshotFrom<this>, effects];\n };\n\n let preInitialState: AnyMachineSnapshot;\n try {\n preInitialState = this._getPreInitialState(resolvedActorScope, initEvent);\n } catch (error) {\n // Keep the machine snapshot shape (e.g. `matches`) on error snapshots\n // when initialization (e.g. the context factory) throws.\n const errorSnapshot = cloneMachineSnapshot(\n createMachineSnapshot(\n {\n context:\n typeof this.config.context !== 'function' && this.config.context\n ? this.config.context\n : ({} as TContext),\n _nodes: [this.root],\n children: {},\n status: 'active'\n },\n this\n ),\n { status: 'error', error }\n );\n return finalizeInitialResult(errorSnapshot, []);\n }\n const contextSpawnEffects = Object.values(preInitialState.children)\n .filter(Boolean)\n .map((actor) => createSpawnEffect(actor as AnyActor));\n\n try {\n const [nextState, initialActions] = initialMicrostep(\n this.root,\n preInitialState,\n resolvedActorScope,\n initEvent,\n internalQueue\n );\n\n const { snapshot: macroState, microsteps } = macrostep(\n nextState,\n initEvent as AnyEventObject,\n resolvedActorScope,\n internalQueue,\n [\n [nextState, [...contextSpawnEffects, ...initialActions]] as [\n AnyMachineSnapshot,\n ExecutableEffect[]\n ]\n ]\n );\n return finalizeInitialResult(macroState, microsteps);\n } catch (err) {\n if (!this.root.config.onError) {\n throw err;\n }\n const errorEvent = createErrorPlatformEvent('execution', err);\n const errorMacrostep = macrostep(\n preInitialState,\n errorEvent,\n resolvedActorScope,\n [],\n [\n [preInitialState, contextSpawnEffects] as [\n AnyMachineSnapshot,\n ExecutableEffect[]\n ]\n ]\n );\n return finalizeInitialResult(\n errorMacrostep.snapshot,\n errorMacrostep.microsteps\n );\n }\n }\n\n public start(\n snapshot?: MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n actorScope?: ActorScope<\n MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n TEvent,\n AnyActorSystem,\n TEmitted\n >\n ): void {\n // Start rehydrated children that were active when persisted. Freshly\n // invoked/spawned children are NOT started here — they start via deferred\n // `@xstate.start` actions so sync start errors route to `onError`.\n if (!snapshot?.children) {\n return;\n }\n const children = snapshot.children as unknown as Record<string, AnyActor>;\n for (const childId in children) {\n if (!Object.hasOwn(children, childId)) {\n continue;\n }\n const child = children[childId];\n if (\n (child as any)._rehydrated &&\n (child as any).getSnapshot?.().status === 'active'\n ) {\n if (actorScope) {\n actorScope.actionExecutor(createStartEffect(child));\n } else {\n void child.system.startActor(child);\n }\n }\n }\n }\n\n public getStateNodeById(\n stateId: string\n ): StateNode<TContext, TEvent, TMeta, TTransitionMeta> {\n // `#id` is an exact id lookup: the text after `#` is never split into a\n // path. It names a state's explicit `id` or its implicit id.\n const hasPrefix = isStateId(stateId);\n const id = hasPrefix ? stateId.slice(STATE_IDENTIFIER.length) : stateId;\n\n if (id === '' && hasPrefix) {\n throw new Error(\n !isDevelopment\n ? xstateError(19, this.id)\n : this.id\n ? `State id '#' is empty. Target the root of ${describeMachine(this.id)} with '#${this.id}'.`\n : \"State id '#' is empty: the root of a machine without an `id` cannot be referenced by id. Give the machine an `id` to reference its root as '#<id>'.\"\n );\n }\n const stateNode = this.idMap.get(id);\n if (stateNode) {\n return stateNode as StateNode<TContext, TEvent, TMeta, TTransitionMeta>;\n }\n throw new Error(\n isDevelopment\n ? describeUnknownStateId(this.idMap, id)\n : xstateError(20, id)\n );\n }\n\n public getPersistedSnapshot(\n snapshot: MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n options?: unknown\n ) {\n return getPersistedSnapshot(snapshot, options);\n }\n\n /**\n * The original JSON definition this machine was created from (set by\n * `machineFromJSON`), if any. Used by `machineToJSON` for lossless\n * round-trips.\n *\n * @internal\n */\n public _json?: Record<string, unknown>;\n}\n","import {\n allocateChildId,\n assertChildIdFree,\n reserveChildId\n} from './transitionActions.ts';\nimport { resolveRegisteredActorSource } from './actorSource.ts';\nimport {\n ActorFromLogic,\n AnyActorLogic,\n AnyActorRef,\n AnyActorScope,\n InputFrom,\n RegistryKeyForLogic,\n SystemRegistry,\n type RequiredLogicInput\n} from './types.ts';\nimport type { ConditionalRequired, IsNotNever } from './typeUtils.ts';\n\n/** @public */\nexport type Spawner<TSystemRegistry extends SystemRegistry = SystemRegistry> = <\n TLogic extends AnyActorLogic\n>(\n src: TLogic,\n ...[options]: ConditionalRequired<\n [\n options?: {\n id?: string;\n registryKey?: RegistryKeyForLogic<TLogic, TSystemRegistry>;\n input?: InputFrom<TLogic>;\n syncSnapshot?: boolean;\n } & { [K in RequiredLogicInput<TLogic>]: InputFrom<TLogic> }\n ],\n IsNotNever<RequiredLogicInput<TLogic>>\n >\n) => ActorFromLogic<TLogic>;\n\nexport function createSpawner(\n actorScope: AnyActorScope,\n actors: Record<string, AnyActorLogic>,\n spawnedChildren: Record<string, AnyActorRef>\n): Spawner {\n return ((src, options) => {\n const referencedSrc = resolveRegisteredActorSource(actors, src);\n // Generated ids come from the same transaction allocator as `enq.spawn`,\n // so context-factory allocations persist with the snapshot and never\n // collide with later spawns.\n const id =\n options?.id ?? allocateChildId(actorScope, referencedSrc ?? src).id;\n if (options?.id !== undefined) {\n assertChildIdFree(actorScope, options.id);\n reserveChildId(actorScope, options.id);\n }\n const actor = actorScope.system.createActorRef(src, {\n id,\n parent: actorScope.self,\n syncSnapshot: options?.syncSnapshot,\n input: options?.input,\n src: referencedSrc ?? src,\n registryKey: options?.registryKey\n });\n spawnedChildren[actor.id] = actor;\n return actor;\n }) as Spawner;\n}\n","import type { PublicEventFromMachine } from './eventTypes.ts';\nimport type { PersistedMachineSnapshot } from './machineVersion.types.ts';\nimport {\n isSnapshotRecord,\n validatePersistedSnapshot\n} from './persistedSnapshotValidation.ts';\nimport type { StandardSchemaV1 } from './schema.types.ts';\nimport type {\n AnyStateMachine,\n ContextFrom,\n EventFrom,\n EventObject,\n Snapshot\n} from './types.ts';\nimport { matchesEventDescriptor } from './utils.ts';\n\ntype PublicEventOf<TMachine extends AnyStateMachine> = PublicEventFromMachine<\n EventFrom<TMachine>,\n TMachine extends { _internalEventType: infer TInternal extends EventObject }\n ? TInternal\n : never\n>;\n\n/** @public */\nexport type MachinePersistedSnapshotSchema<TMachine extends AnyStateMachine> =\n StandardSchemaV1<\n unknown,\n Snapshot<unknown> &\n PersistedMachineSnapshot & { context: ContextFrom<TMachine> }\n >;\n\nfunction findEventSchema(\n schemas: Record<string, StandardSchemaV1> | undefined,\n eventType: string\n): StandardSchemaV1 | undefined {\n if (!schemas) {\n return undefined;\n }\n\n if (Object.hasOwn(schemas, eventType)) {\n return schemas[eventType];\n }\n\n const descriptor = Object.keys(schemas).find((key) =>\n matchesEventDescriptor(eventType, key)\n );\n return descriptor === undefined ? undefined : schemas[descriptor];\n}\n\nfunction memo<T>(cache: WeakMap<object, T>, key: object, create: () => T): T {\n let value = cache.get(key);\n if (!value) {\n cache.set(key, (value = create()));\n }\n return value;\n}\n\nconst snapshotSchemas = new WeakMap<object, StandardSchemaV1>();\nconst historicalEventSchemas = new WeakMap<object, StandardSchemaV1>();\nconst eventSchemas = new WeakMap<object, StandardSchemaV1>();\n\n/**\n * Standard Schema for snapshots persisted by `machine` (its version): checks\n * the snapshot structure against the machine's states and children, and the\n * context against `schemas.context`.\n *\n * @public\n */\nexport function snapshotSchema<TMachine extends AnyStateMachine>(\n machine: TMachine\n): MachinePersistedSnapshotSchema<TMachine> {\n return memo(\n snapshotSchemas,\n machine,\n (): MachinePersistedSnapshotSchema<TMachine> => ({\n '~standard': {\n version: 1,\n vendor: 'xstate',\n validate: async (value) => {\n if (value === null || typeof value !== 'object') {\n return { issues: [{ message: 'Expected a persisted snapshot.' }] };\n }\n const snapshot: Record<string, unknown> = {\n historyValue: {},\n timers: [],\n ...(value as Record<string, unknown>)\n };\n const contextSchema = machine.schemas?.context;\n let context = snapshot.context;\n if (contextSchema) {\n const result = await contextSchema['~standard'].validate(context);\n if (result.issues) {\n return {\n issues: [\n {\n message: `Invalid context for machine '${machine.id}' version '${machine.version}': ${result.issues[0]?.message}`\n }\n ]\n };\n }\n context = result.value;\n }\n for (const key of ['value', 'children'] as const) {\n if (!(key in snapshot)) {\n return {\n issues: [{ message: `Persisted snapshot is missing '${key}'.` }]\n };\n }\n }\n if (\n !['active', 'done', 'error', 'stopped'].includes(\n snapshot.status as string\n )\n ) {\n return {\n issues: [{ message: 'Persisted snapshot has invalid status.' }]\n };\n }\n if (!isSnapshotRecord(snapshot.historyValue)) {\n return {\n issues: [\n { message: \"Persisted snapshot has invalid 'historyValue'.\" }\n ]\n };\n }\n try {\n validatePersistedSnapshot(machine, snapshot);\n } catch (error) {\n return {\n issues: [\n {\n message:\n error instanceof Error\n ? error.message\n : 'Persisted snapshot has invalid state value.'\n }\n ]\n };\n }\n return {\n value: { ...snapshot, context } as Snapshot<unknown> &\n PersistedMachineSnapshot & { context: ContextFrom<TMachine> }\n };\n }\n }\n })\n ) as MachinePersistedSnapshotSchema<TMachine>;\n}\n\n/**\n * @internal Standard Schema for events in a machine's history, including\n * internal and runtime events that public input excludes.\n */\nexport function historicalEventSchema(\n machine: AnyStateMachine\n): StandardSchemaV1<unknown, EventObject> {\n return memo(\n historicalEventSchemas,\n machine,\n (): StandardSchemaV1<unknown, EventObject> => ({\n '~standard': {\n version: 1,\n vendor: 'xstate',\n validate: async (value) => {\n if (\n value === null ||\n typeof value !== 'object' ||\n typeof (value as EventObject).type !== 'string'\n ) {\n return { issues: [{ message: 'Expected an event object.' }] };\n }\n const event = value as EventObject;\n const eventSchemas = machine.schemas?.events;\n const internalEventSchemas = machine.schemas?.internalEvents;\n const isFrameworkEvent =\n event.type.startsWith('xstate.') ||\n event.type.startsWith('@xstate.');\n const schema =\n findEventSchema(internalEventSchemas, event.type) ??\n findEventSchema(eventSchemas, event.type);\n if (\n (eventSchemas || internalEventSchemas) &&\n !schema &&\n !isFrameworkEvent\n ) {\n return {\n issues: [\n {\n message: `Unknown event '${event.type}' for machine '${machine.id}' version '${machine.version}'.`\n }\n ]\n };\n }\n if (!schema) {\n return { value: event as EventObject };\n }\n const { type, ...payload } = event;\n const result = await schema['~standard'].validate(payload);\n if (result.issues) {\n return result;\n }\n if (result.value === null || typeof result.value !== 'object') {\n return { issues: [{ message: 'Expected an event payload.' }] };\n }\n return { value: { ...result.value, type } as EventObject };\n }\n }\n })\n ) as StandardSchemaV1<unknown, EventObject>;\n}\n\n/**\n * Standard Schema for complete public input events of `machine`; excludes\n * internal and runtime events.\n *\n * @public\n */\nexport function eventSchema<TMachine extends AnyStateMachine>(\n machine: TMachine\n): StandardSchemaV1<unknown, PublicEventOf<TMachine>> {\n return memo(\n eventSchemas,\n machine,\n (): StandardSchemaV1<unknown, PublicEventOf<TMachine>> => ({\n '~standard': {\n version: 1,\n vendor: 'xstate',\n validate: async (value) => {\n const event = value as EventObject;\n if (event && typeof event.type === 'string') {\n const internal = findEventSchema(\n machine.schemas?.internalEvents,\n event.type\n );\n const framework =\n event.type.startsWith('xstate.') ||\n event.type.startsWith('@xstate.');\n if (internal || framework) {\n if (!internal && event.type === 'xstate.route') {\n const result =\n await historicalEventSchema(machine)['~standard'].validate(\n value\n );\n if (result.issues) {\n return result;\n }\n const to = (result.value as EventObject & { to?: unknown }).to;\n const route =\n typeof to === 'string' && to.startsWith('#')\n ? machine.idMap.get(to.slice(1))\n : undefined;\n if (\n route &&\n route !== machine.root &&\n route.config.id &&\n route.config.route\n ) {\n return {\n value: result.value as PublicEventOf<TMachine>\n };\n }\n }\n return {\n issues: [\n {\n message: `Event '${event.type}' is not a public input event.`\n }\n ]\n };\n }\n }\n return historicalEventSchema(machine)['~standard'].validate(\n value\n ) as Promise<StandardSchemaV1.Result<PublicEventOf<TMachine>>>;\n }\n }\n })\n ) as StandardSchemaV1<unknown, PublicEventOf<TMachine>>;\n}\n","import isDevelopment from '#is-development';\nimport { Actor } from '../createActor.ts';\nimport { diagnoseActorOptions } from '../devDiagnostics.ts';\nimport { createInvokeTimeoutEvent } from '../eventUtils.ts';\nimport {\n attachSnapshotActorRef,\n createInertActorScope,\n isInertActorScope,\n setInertActorScopeSnapshot\n} from '../inertActorScope.ts';\nimport { setSnapshotActorRef } from '../snapshotActorRef.ts';\nimport { describeMachine } from '../utils.ts';\nimport { xstateError } from '../xstateError.ts';\nimport {\n InvalidSnapshotError,\n validatePersistedSnapshot\n} from '../persistedSnapshotValidation.ts';\nimport {\n createRemoteActorRef,\n isSerializedActorRef\n} from '../remoteActorRef.ts';\nimport { cloneMachineSnapshot, createMachineSnapshot } from '../State.ts';\nimport { StateMachine } from '../StateMachine.ts';\nimport { StateNode } from '../StateNode.ts';\nimport { parseGeneratedActorId } from '../system.ts';\nimport type {\n ActorOptions,\n ActorRestoreHook,\n AnyActor,\n AnyActorLogic,\n AnyActorScope,\n AnyEventObject,\n AnyMachineSnapshot,\n AnyStateMachine,\n AnyStateNode,\n EventObject,\n HistoryValue,\n LogicalTimer,\n RestorablePersistedSnapshotFor,\n Snapshot,\n SnapshotFrom\n} from '../types.ts';\n\nexport { snapshotSchema } from '../machineSchemas.ts';\nexport type { MachinePersistedSnapshotSchema } from '../machineSchemas.ts';\n\n/**\n * Options for {@link restoreActor}: the {@link ActorOptions} of `createActor`\n * except `input` (a restored actor resumes, it does not initialize).\n *\n * @public\n */\nexport type RestoreActorOptions<TLogic extends AnyActorLogic> = Omit<\n ActorOptions<TLogic>,\n 'input'\n> & {\n /** Restores the actor into this system (from `createSystem()`). */\n system?: { createActor: (logic: any, options?: any) => AnyActor };\n};\n\n/**\n * Creates an actor that resumes from a persisted snapshot instead of starting\n * fresh. Works for any actor logic. Machine snapshots are validated, migrated\n * (`migrate` in the machine config) and their invoked/spawned children are\n * restored recursively.\n *\n * A snapshot that cannot be restored produces an actor whose snapshot has\n * `status: 'error'`.\n *\n * @example\n *\n * ```ts\n * import { restoreActor } from 'xstate/persist';\n *\n * const actor = restoreActor(machine, persistedSnapshot).start();\n * ```\n *\n * @public\n */\nexport function restoreActor<TLogic extends AnyActorLogic>(\n logic: TLogic,\n persistedSnapshot: Snapshot<unknown> &\n Partial<RestorablePersistedSnapshotFor<NoInfer<TLogic>>>,\n options?: RestoreActorOptions<TLogic>\n): Actor<TLogic> {\n const { system, ...actorOptions } = options ?? {};\n diagnoseActorOptions(actorOptions);\n const resolvedOptions = {\n ...actorOptions,\n _restore: createRestoreHook(logic, persistedSnapshot)\n } as ActorOptions<TLogic>;\n return system\n ? (system.createActor(logic, resolvedOptions) as Actor<TLogic>)\n : new Actor(logic, resolvedOptions);\n}\n\n/**\n * @internal Restores `persisted` for any actor logic: machines through\n * {@link restoreMachineSnapshot}, other logic through its own\n * `restoreSnapshot` (or verbatim).\n */\nexport function restoreLogicSnapshot<TLogic extends AnyActorLogic>(\n logic: TLogic,\n persisted: unknown,\n actorScope?: AnyActorScope\n): SnapshotFrom<TLogic> {\n if (logic instanceof StateMachine) {\n return restoreMachineSnapshot(\n logic,\n persisted as Snapshot<unknown>,\n actorScope\n ) as SnapshotFrom<TLogic>;\n }\n // Only `undefined` means \"no snapshot\": an explicit `null` (or another\n // non-object) is a malformed snapshot the logic reports.\n if (!logic.restoreSnapshot && persisted === null) {\n throw new Error(\n isDevelopment ? 'Persisted snapshot must be an object.' : xstateError(46)\n );\n }\n return logic.restoreSnapshot\n ? logic.restoreSnapshot(persisted as Snapshot<unknown>, actorScope)\n : (persisted as SnapshotFrom<TLogic>);\n}\n\nfunction createRestoreHook(\n logic: AnyActorLogic,\n persisted: unknown\n): ActorRestoreHook {\n return {\n restore: (actorScope) => restoreLogicSnapshot(logic, persisted, actorScope),\n error: (error) =>\n logic instanceof StateMachine\n ? createRestoreErrorSnapshot(logic, persisted, error)\n : undefined\n };\n}\n\n/**\n * Builds a machine-shaped `'error'` snapshot (root configuration, no children)\n * for a persisted snapshot that failed to restore, so consumers keep\n * `matches()`, `can()` and friends.\n */\nfunction createRestoreErrorSnapshot(\n machine: AnyStateMachine,\n persisted: unknown,\n error: unknown\n): AnyMachineSnapshot {\n const context = (persisted as { context?: unknown } | undefined)?.context;\n return cloneMachineSnapshot(\n createMachineSnapshot(\n {\n context: context && typeof context === 'object' ? context : {},\n _nodes: [machine.root],\n children: {},\n status: 'active'\n },\n machine\n ),\n { status: 'error', error }\n ) as any;\n}\n\n/**\n * @internal Restores a persisted machine snapshot: validates it, runs\n * `migrate` on version mismatch, recursively restores children (remote\n * children become address handles) and revives timers, history and actor refs\n * in context.\n */\nexport function restoreMachineSnapshot<TMachine extends AnyStateMachine>(\n machine: TMachine,\n snapshot: Snapshot<unknown>,\n actorScope?: AnyActorScope\n): SnapshotFrom<TMachine> {\n const usesInertScope = !actorScope;\n const resolvedActorScope = (actorScope ??\n createInertActorScope(machine)) as AnyActorScope;\n if (!snapshot || typeof snapshot !== 'object' || Array.isArray(snapshot)) {\n throw new InvalidSnapshotError(\n isDevelopment\n ? `Persisted snapshot for ${describeMachine(machine.id)} must be an object.`\n : xstateError(24, machine.id)\n );\n }\n const snapshotMachine = (snapshot as any).machine;\n // A live machine snapshot carries its producing machine so helpers such as\n // `matches()` can resolve state nodes. That runtime association is not the\n // persisted `{ id, version }` identity written by getPersistedSnapshot().\n const persistedMachine =\n snapshotMachine &&\n typeof snapshotMachine === 'object' &&\n typeof snapshotMachine.transition === 'function' &&\n 'root' in snapshotMachine\n ? undefined\n : snapshotMachine;\n const legacyPersistedVersion: string | undefined = (snapshot as any).version;\n const persistedVersion: string | undefined =\n typeof persistedMachine?.version === 'string'\n ? persistedMachine.version\n : legacyPersistedVersion;\n if (\n legacyPersistedVersion !== undefined &&\n persistedMachine?.version !== undefined &&\n persistedMachine.version !== legacyPersistedVersion\n ) {\n throw new Error(\n isDevelopment\n ? `Persisted snapshot version '${legacyPersistedVersion}' conflicts with machine version '${persistedMachine.version}'.`\n : xstateError(34, legacyPersistedVersion, persistedMachine.version)\n );\n }\n if (\n persistedMachine &&\n typeof persistedMachine.id === 'string' &&\n persistedMachine.id !== machine.id\n ) {\n throw new Error(\n isDevelopment\n ? `Machine ID mismatch: persisted snapshot was created by machine '${persistedMachine.id}', but machine '${machine.id}' was provided.`\n : xstateError(35, persistedMachine.id, machine.id)\n );\n }\n if (persistedVersion !== machine.version) {\n const migrate = (machine.config as any).migrate;\n if (typeof migrate !== 'function') {\n throw new Error(\n isDevelopment\n ? `Persisted snapshot version '${persistedVersion}' does not match machine version '${machine.version}' for machine '${machine.id}'. Provide a \\`migrate(persistedSnapshot, fromVersion)\\` function in the machine config to migrate old snapshots.`\n : xstateError(36, persistedVersion, machine.version)\n );\n }\n snapshot = migrate(snapshot, persistedVersion);\n }\n\n const snapshotData = snapshot as any;\n const { nodes, childLogics } = validatePersistedSnapshot(\n machine,\n snapshotData\n );\n const children: Record<string, AnyActor> = {};\n const snapshotChildren: Record<\n string,\n {\n src?: string | AnyActorLogic;\n snapshot?: Snapshot<unknown>;\n address?: string;\n remote?: boolean;\n incarnation?: string;\n syncSnapshot?: boolean;\n registryKey?: string;\n }\n > = snapshotData.children;\n\n for (const actorId of Object.keys(snapshotChildren)) {\n const actorData = snapshotChildren[actorId];\n\n if (actorData.remote === true && actorData.address !== undefined) {\n if (typeof actorData.src !== 'string') {\n // Fail loudly instead of fabricating a source key that hosts would\n // route by.\n throw new Error(\n isDevelopment\n ? `Unable to restore remote child '${actorId}': a child referenced by address requires a registered source key.`\n : xstateError(28, actorId)\n );\n }\n // The child's state lives with another runtime; restore a\n // location-transparent handle constructed from its identity alone.\n // The handle keeps its persisted address verbatim: the owning\n // runtime's identity for the child wins over the local parent chain.\n const handle = createRemoteActorRef(resolvedActorScope.system, {\n id: actorId,\n address: actorData.address,\n src: actorData.src,\n parent: resolvedActorScope.self,\n registryKey: actorData.registryKey,\n syncSnapshot: actorData.syncSnapshot,\n incarnation: actorData.incarnation\n });\n if (actorData.registryKey) {\n resolvedActorScope.system._set(actorData.registryKey, handle);\n }\n children[actorId] = handle;\n continue;\n }\n\n const childState = actorData.snapshot;\n const src = actorData.src;\n\n const logic = childLogics.get(actorId)!;\n\n const actor = resolvedActorScope.system.createActorRef(logic, {\n id: actorId,\n parent: resolvedActorScope.self,\n syncSnapshot: actorData.syncSnapshot,\n ...(childState !== undefined\n ? { _restore: createRestoreHook(logic, childState) }\n : {}),\n src,\n registryKey: actorData.registryKey\n });\n // Mark so `start()` knows to start this child (freshly invoked/spawned\n // children are started via deferred `@xstate.start` actions instead).\n (actor as any)._rehydrated = true;\n if (src === undefined) {\n (actor as any)._invoked = true;\n }\n\n children[actorId] = actor;\n }\n\n const timers: LogicalTimer[] = [];\n const persistedTimers: Array<{\n id?: string;\n seq?: number;\n delay: number;\n type: '@xstate.raise' | '@xstate.sendTo';\n event: EventObject;\n target: string | { type: 'parent' };\n scheduledAt?: number;\n }> = snapshotData.timers ?? [];\n for (const timer of persistedTimers) {\n let event = timer.event;\n if (event.type === 'xstate.timeout.actor') {\n const actorId = (event as AnyEventObject).actorId as string;\n const child = children[actorId];\n if (child) {\n event = createInvokeTimeoutEvent(actorId, child.sessionId);\n }\n }\n const target =\n typeof timer.target === 'string'\n ? timer.target === 'self'\n ? 'self'\n : children[timer.target]\n : isSerializedActorRef(timer.target)\n ? (timer.target as unknown as AnyActor)\n : resolvedActorScope.self._parent;\n if (!target) {\n const targetDescription =\n typeof timer.target === 'string'\n ? timer.target\n : (timer.target as { type: string }).type;\n throw new InvalidSnapshotError(\n isDevelopment\n ? `Unable to restore timer ${timer.id !== undefined ? `'${timer.id}'` : `for event '${timer.event.type}'`}: target actor '${targetDescription}' is unavailable.`\n : xstateError(33, targetDescription)\n );\n }\n timers.push({ ...timer, event, target });\n }\n\n const reviveHistoryValue = (\n historyValue: Record<string, ({ id: string } | AnyStateNode)[]>\n ): HistoryValue => {\n if (!historyValue || typeof historyValue !== 'object') {\n return {};\n }\n const revived: HistoryValue = {};\n for (const key of Object.keys(historyValue)) {\n const arr = historyValue[key];\n\n for (const item of arr) {\n let resolved: AnyStateNode | undefined;\n\n if (item instanceof StateNode) {\n resolved = item;\n } else {\n try {\n resolved = machine.getStateNodeById(item.id);\n } catch {\n if (isDevelopment) {\n console.warn(`Could not resolve StateNode for id: ${item.id}`);\n }\n }\n }\n\n if (!resolved) {\n continue;\n }\n\n revived[key] ??= [];\n revived[key].push(resolved);\n }\n }\n return revived;\n };\n\n const revivedHistoryValue = reviveHistoryValue(snapshotData.historyValue);\n\n if (isDevelopment && snapshotData.status === 'active') {\n // Restored snapshots are opaque: eventless transitions are not\n // re-evaluated on restore. Detected structurally; guards never run.\n const eventlessNode = nodes.find(\n (node) => node.always?.length || node.type === 'choice'\n );\n if (eventlessNode) {\n console.warn(\n `Restored snapshot is in state \"${eventlessNode.id}\" which has eventless transitions; they are not re-evaluated until the next event`\n );\n }\n }\n\n const {\n version: _persistedSnapshotVersion,\n // The legacy system-wide counter: superseded by per-snapshot\n // `_nextActorIds` plus the child-id fold below; dropped so old and new\n // snapshots round-trip to the same shape.\n _nextActorId: _legacyNextActorId,\n ...persistedRest\n } = snapshot as any;\n // Fold generated-shaped child ids into the counters as a floor: snapshots\n // persisted before per-actor counters (or hand-crafted ones) still must\n // never reuse a live child's id.\n let restoredCounters: Record<string, number> | undefined =\n persistedRest._nextActorIds;\n for (const childId of Object.keys(snapshotChildren)) {\n const generated = parseGeneratedActorId(childId);\n if (\n generated &&\n (restoredCounters?.[generated.prefix] ?? 0) <= generated.index\n ) {\n restoredCounters = {\n ...restoredCounters,\n [generated.prefix]: generated.index + 1\n };\n }\n }\n // Revive actor-ref references into a copy: the persisted snapshot is\n // caller-owned and is never mutated or frozen. Only plain objects and\n // arrays are copied; other values are kept as is.\n const revived = new Map<object, unknown>();\n\n function reviveContext(value: any, isRoot = false): any {\n if (!value || typeof value !== 'object') {\n return value;\n }\n // The context object itself is data, never a serialized actor ref.\n // Only an object whose keys are exactly `$actor` (+ `incarnation`)\n // is a serialized ref; any other object is data.\n if (!isRoot && isSerializedActorRef(value)) {\n // A ref that names one of this snapshot's children revives to that\n // child; restored children are new incarnations, so a ref pinned to\n // an incarnation stays data. Any other ref (e.g. a `replyTo` from an\n // event) stays data and routes by address.\n if (value.incarnation !== undefined) {\n return value;\n }\n return (\n Object.values(children).find(\n (child) => child.address === value.$actor\n ) ?? value\n );\n }\n const proto = Object.getPrototypeOf(value);\n if (!Array.isArray(value) && proto !== Object.prototype && proto !== null) {\n return value;\n }\n let copy: any = revived.get(value);\n if (!copy) {\n revived.set(\n value,\n (copy = Array.isArray(value) ? [] : Object.create(proto))\n );\n for (const key of Object.keys(value)) {\n // defineProperty keeps keys like `__proto__` as own data properties.\n Object.defineProperty(copy, key, {\n value: reviveContext(value[key]),\n writable: true,\n enumerable: true,\n configurable: true\n });\n }\n }\n return copy;\n }\n\n const restoredSnapshot = createMachineSnapshot(\n {\n ...persistedRest,\n context: reviveContext(persistedRest.context, true),\n children,\n timers,\n _nextActorIds: restoredCounters,\n _nodes: nodes,\n // Derived from the resolved configuration, so a partial value such as\n // `{ active: {} }` is completed with initial states and agrees with\n // `nodes`.\n value: undefined,\n historyValue: revivedHistoryValue,\n // Inputs only belong to active states; drop any others.\n _stateInputs: Object.fromEntries(\n Object.entries(snapshotData.stateInputs ?? {}).filter(([id]) =>\n nodes.some((node) => node.id === id)\n )\n )\n },\n machine,\n resolvedActorScope.self\n ) as AnyMachineSnapshot;\n\n if (usesInertScope) {\n setInertActorScopeSnapshot(resolvedActorScope, restoredSnapshot, false);\n return attachSnapshotActorRef(\n resolvedActorScope,\n restoredSnapshot\n ) as SnapshotFrom<TMachine>;\n }\n\n if (!isInertActorScope(resolvedActorScope)) {\n setSnapshotActorRef(\n restoredSnapshot,\n resolvedActorScope.self,\n resolvedActorScope.system\n );\n }\n return restoredSnapshot as SnapshotFrom<TMachine>;\n}\n"],"names":["xstateError","code","values","length","map","value","JSON","stringify","String","join","ACTOR_OPTIONS","Set","diagnoseActorOptions","options","key","Object","keys","has","Error","XSTATE_INIT","XSTATE_SPAWN","XSTATE_STOP","XSTATE_TERMINATE","XSTATE_TIMER","emptySubscription","unsubscribe","isRemoteActorRef","actorRef","_remote","isSerializedActorRef","target","Array","isArray","$actor","incarnation","undefined","getAddressId","address","segment","slice","lastIndexOf","includes","replaceAll","createMissingAddressError","resolveSerializedActorRef","system","live","_getByAddress","sessionId","remoteSnapshot","freeze","status","output","error","createRemoteActorRef","handle","ref","id","src","registryKey","_parent","parent","_syncSnapshot","syncSnapshot","send","event","sendEvent","_send","type","getSnapshot","getPersistedSnapshot","start","_stop","stop","select","trigger","subscribe","on","_isRunning","toJSON","publishEmittedEvent","source","runtime","_notifyEmitted","emitEvent","pendingSteps","WeakMap","async","runStep","actor","exec","sendSelf","effect","effects","prototype","hasOwnProperty","call","getStepEffect","running","get","resolve","reject","promise","Promise","resolvePromise","rejectPromise","subscription","steps","Map","set","cleanup","delete","size","then","complete","catch","rejectUndeliverableEvent","runtimeTarget","logic","isInternalEventType","getEventBoundaryError","deadLetter","Mailbox","constructor","_process","this","_active","_current","_last","flush","clear","next","enqueue","enqueued","consumed","createAfterEvent","delayRef","delay","stateId","createInvokeTimeoutEvent","invokeId","actorId","createDoneStateEvent","createErrorPlatformEvent","kind","createInitEvent","input","reportUnhandledError","err","setTimeout","symbolObservable","Symbol","observable","selectionFrames","transitionEffectSignal","beginTransitionSelection","mode","frame","requiresReevaluation","push","close","pop","getBuiltInTimerIdentity","getTimerKey","timer","seq","readTimerKey","matchesTimerKey","pattern","field","getScheduledTimerKey","serializeTimerKey","starts","getTimerStart","scheduledAt","assertSendToEvent","builtInActions","spawnActor","startActor","@xstate.raise","actorScope","scheduleTimer","self","@xstate.sendTo","_relay","@xstate.cancel","cancelTimer","@xstate.stop","stopActor","@xstate.terminate","termination","terminateActor","sourceKeyCaches","resolveRegisteredActorSource","actors","cache","registeredLogic","systemLogicMetadata","subscriptions","createAttachedLogic","attach","initialTransition","_","state","parentSubscription","torndown","teardown","transition","getInitialSnapshot","snapshot","restoreSnapshot","defineProperty","relayMappedToParent","getEvent","createListenerLogic","eventType","mapper","isPartialWildcard","endsWith","emittedEvent","matchesEventDescriptor","listenerLogic","createSubscriptionLogic","mappers","done","onSnapshot","subscriptionLogic","execCustomEffect","result","action","args","execEmitEffect","execDeadLetterEffect","reason","detail","createDeadLetterEffect","params","createMissingTargetEffect","targetId","execSpawnEffect","execStartEffect","_processingStatus","execStopEffect","execTerminateEffect","execRaiseEffect","execSendToEffect","execCancelEffect","updateLogicalTimers","isBuiltInExecutableEffect","timers","some","filter","nextTimerId","_nextTimerId","index","findIndex","pending","i","mergeContextPatch","context","patch","pushBuiltInAction","actions","actionRecord","mergeActorIdCounters","current","update","merged","Math","max","applyChildUpdate","children","counters","_nextActorIds","owned","_unregister","getTransitionActionRecord","spawnAllocations","createSpawnAllocation","explicitIds","stoppedIds","beginSpawnAllocation","getWorkingSnapshotOf","_snapshot","nextChildIndex","allocation","prefix","nextFreeChildIndex","allocateChildId","localAllocation","getActorIdPrefix","assertChildIdFree","existing","occupied","add","reserveChildId","generated","parseGeneratedActorId","detachedScopes","WeakSet","assertRaiseEvent","createTransitionEnqueue","internalEvents","actorSubscriptions","createActors","props","cancel","emit","log","logger","raise","raisedEvent","spawn","registeredActors","sources","getRegisteredActors","resolveTransitionSpawnSource","createInertActorRef","encodeAddressSegment","createActorRef","childUpdate","pushSpawnedChild","sendTo","actorInstance","recordStoppedChild","assign","listen","listenerActor","subscribeTo","subscriptionActor","closed","guard","fn","lateEnqueueCall","createEnqueueObject","enqueueClosers","closeTransitionEnqueue","getBuiltInActionFields","createStartEffect","createSendToEffect","createTerminationEffect","finalizeTransitionResult","previousSnapshot","nextSnapshot","becameTerminal","wasTerminal","hasTerminationEffect","resolveActionsWithContext","currentSnapshot","_event","intermediateSnapshot","executableActions","isInline","resolvedActionArgs","childId","hasOwn","resolvedAction","bind","actionParams","_childUpdate","emittedEventParams","builtInFields","isEmittedEvent","typedExecutableEffect","name","enqueueFn","noop","emptyActor","snapshotActorRefs","lazySnapshotActorRefs","emptyKeyedActors","getKeyedActors","peek","_peekKeyedActors","keyedActors","markSystemSnapshotDirty","_snapshotVersion","getSystemSnapshotVersion","createSnapshotSystem","baseSystem","baseState","root","copyRegisteredActors","reverseKeyedActors","create","sourceVersion","_register","_set","getAll","fromEntries","onEmitted","listener","_hasInspectionObservers","_sendInspectionEvent","getSnapshotActorRef","created","copySnapshotActorRef","setSnapshotActorRef","previousRef","reusableRef","systemState","sourceSystem","capturedActors","_getRootActor","peekedChildren","_peekChildren","captureRegisteredActors","baseKeyedActors","child","getSnapshotChildren","lazyActorScope","isLazyActorScope","getActorScopeParent","withActorScope","actorArgs","defineProperties","enumerable","setInertActorScopeSnapshot","attachActorRef","lazyState","getLazyInertActorState","materialized","isInertActorScope","_inert","attachSnapshotActorRef","snapshotActorScopes","identityProvider","setLazySnapshotActorRef","lazyInertActorState","materializeInertActorScope","materialize","lazyInertActorScopePrototype","parentKnown","defer","stopChild","actionExecutor","createMaterializedInertActorScope","actorLogic","sourceRef","sourceChildren","sourceSelf","snapshotRef","previousSelf","createActor","_sessionId","_systemRef","_address","_actorScope","createInertActorScope","sourceActorScope","sourceScope","sourceState","eagerSourceRef","peekSnapshotActorRef","getSnapshotActorRefProvider","isMachineSnapshot","identitySnapshot","identitySourceRef","identitySourceChildren","identityScope","identityRef","getIdentityScope","scope","getConfiguredDelayValue","delaySource","referencedDelay","parsedDelay","duration","normalizedDuration","trim","millisecondsMatch","match","parseInt","secondsMatch","wholePart","hasDecimal","fracPart","padEnd","iso8601DurationMatch","groups","weeks","days","hours","minutes","seconds","toNumber","Number","replace","parseDurationToMilliseconds","resolveDelay","configuredDelay","getStateInput","stateNodeId","_stateInputs","isAtomicStateNode","stateNode","getChildren","states","sn","getProperAncestors","toStateNode","ancestors","m","getAllStateNodes","stateNodes","nodeSet","activeParentSet","s","initialStates","getInitialStateNodes","initialStateNode","getStateValue","rootNode","config","adjList","getValueFromAdj","baseNode","childStateNodes","childStateNode","stateValue","isInFinalState","stateNodeSet","every","isStateId","str","matchesActorSession","scheduleDelayedEvent","timerEvent","resolveEvent","resolveScheduledDelay","oldEntry","entry","x","enq","delays","oldExit","exit","formatTransition","descriptor","transitionConfig","removedKey","cond","getRemovedTransitionKey","normalizedTarget","normalizeTarget","reenter","resolveTarget","assertLegalTargetSet","transitionDefinitionToJSON","definition","serializableTransition","isStateNodeDescendantOf","ancestor","getLeastCommonStateNodeAncestor","left","right","leftAncestors","targets","leftIndex","rightIndex","commonAncestor","machine","getStateNodeById","isInternalTarget","getStateNodeByPath","resolvedTarget","message","resolveHistoryDefaultTransition","initial","t","to","_historyDefaultTransition","isHistoryNode","iter","descStateNode","initialState","getStateNode","stateKey","statePath","arrayStatePath","toStatePath","currentStateNode","shift","getStateNodes","childStateKeys","allStateNodes","subStateNode","transitionNode","selectionResults","subStateKeys","subStateKey","allInnerTransitions","subStateValue","innerTransitions","isDescendant","parentStateNode","marker","hasDescendantState","hasIntersection","s1","s2","s1Size","s2Size","set1","item","removeConflictingTransitions","enabledTransitions","resolveTransition","filteredTransitions","exitSets","getExitSet","exitSet","computeExitSet","t1","t1Preempted","transitionsToRemove","t2","t3","from","createTransitionResultResolver","resolveActions","applied","getTransitionResult","selectionResult","getEffectiveTargetStates","historyValue","targetSet","targetNode","node","narrowParallelDomain","domain","targetStates","narrowed","region","find","getTransitionDomain","_transitionDomain","head","tail","concat","transitions","statesToExit","microstep","isInitial","internalQueue","_microstepHooks","drain","mutStateNodeSet","nodes","originalContext","getCurrentTransitionResult","changesState","getStateActionsAndContext","transitionFn","updatedContext","getEventOutput","guards","res","assertSyncTransitionResult","nextState","getInvokeStopActions","invokeDef","invoke","exitStates","changedHistory","sort","a","b","order","currentStateNodes","exitStateNode","historyNode","predicate","history","stateInput","exitActions","nextContext","nextChildren","cloneMachineSnapshot","resolvedState","resolvedActions","invokeStopActions","stoppedState","stopEffects","transitionActions","resolvedTransitions","resolvedTransition","enterStates","getMachineOutput","rootCompletionNode","completionOutput","rootDoneEvent","e","resolveOutput","stateInputMap","parallelDoneEvent","statesToEnter","statesForDefaultEntry","historyDefaultsByParent","addAncestorStatesToEnter","reentrancyDomain","anc","addDescendantStatesToEnter","historyStateNodes","historyDefaultTransition","historyParent","defaults","enteredTargetsByTransition","enteredTargets","_statesForDefaultEntry","stateInputsChanged","activeIds","entries","completedNodes","stateNodeToEnter","invoked","_invoked","contextChangedByEntry","resultActions","nextInternalEvents","defaultTransitions","Boolean","defaultTransition","initialActions","initialContext","initialInput","initialInternalEvents","ancestorMarker","regionOutput","regionDoneEvent","finalChild","resolvedTransitionState","transitionExecutableEffects","transitionContent","raisedEvents","nextStateNodes","allExitActions","forEach","stopChildren","withoutTimers","cancelEffects","cancelTimers","_nodes","transitionArgs","getTransitionArgs","reusable","operations","speculativeSelection","operation","toArray","resolvedInput","resolvedContext","InfiniteTransitionError","maxIterations","super","macrostep","initialMicrosteps","microsteps","handled","removeTerminatedChild","terminalEvent","lastEffects","lastTransitions","at","completeMacrostep","attachedStarts","childStarts","deriveDeferredStarts","flatMap","shouldTerminate","terminalEffects","lastSnapshot","addMicrostep","step","collectedMicrosteps","_collectedMicrosteps","stoppedChildrenSnapshot","nextEvent","currentEvent","isErr","startsWith","isErrorEvent","getTransitionData","_hasEventlessTransitions","shouldSelectEventlessTransitions","Infinity","iterationCount","recentStates","selectEventlessTransitions","previousState","hasEffect","evaluateTransitionFunction","enabled","sourceId","transitionTo","selection","record","abortRefProducingCall","createTransitionSelection","begin","enabledTransitionSet","atomicStates","atomicStateNode","loop","always","evaluateCandidate","candidate","matches","is","matchesEvent","_eventMatcher","guardArgs","withActorSelfAndParent","evaluation","emptySnapshotRecord","emptyTimers","compactTimers","compactSnapshotRecord","machineSnapshotMatches","testValue","matchesState","machineSnapshotHasTag","tag","tags","machineSnapshotCan","_canTransition","machineSnapshotToJSON","getMeta","getInputs","can","hasTag","jsonValues","machineSnapshotGetMeta","meta","machineSnapshotGetInputs","collectTags","createMachineSnapshot","configWithSnapshot","clonedSnapshot","serializeHistoryValue","persistContext","contextPart","getActorId","path","copy","isActorRefLike","valuePath","parentStateId","childStateId","parentStateValue","toStateValue","childStateValue","charCodeAt","previous","pathToStateValue","toArrayStrict","isDoneEvent","toTransitionConfigArray","configLike","transitionLike","toObserver","nextHandler","errorHandler","completionHandler","isObserver","passive","resolveInvokedActorLogic","definitions","registered","partialEventTokens","split","eventTokens","tokenIndex","partialEventToken","eventToken","executionIdPrefix","nextExecutionId","createExecutionId","crypto","globalThis","getRandomValues","Uint32Array","toString","padStart","randomUUID","Date","now","random","createExecutionIdPrefix","logicId","separator","isSafeInteger","getActorIdCounterKey","bumpActorIdCounter","counterKey","emptyScheduledTimers","createScheduledTimerId","findLogicalTimer","RuntimeSystem","_children","_rootActor","_keyedActors","_reverseKeyedActors","_identity","executionId","nextSessionId","scheduler","_clock","_logger","clock","ambientInspector","getAmbientInspector","_scheduledTimers","_recordSent","_inspectionObservers","inspectionSource","_collectedSent","targetRef","schedule","scheduledTimerId","_timerMap","scheduledTimer","dueAt","timeout","_deliver","clearTimeout","cancelAll","serialized","deliverEvent","changed","inspect","observerOrFn","observer","onRejectedEvent","rejection","_rejectionListeners","emission","_emissionListeners","listeners","resolvedInspectionEvent","rootId","override","stopActorLocally","_terminate","terminateActorLocally","_emit","eventOrigin","issues","runLogic","cancelAllTimers","matched","abort","protectSelectionRelay","scheduledTimers","resetScheduledTimers","scheduledId","executingCustomAction","emptyInspectionRecords","reservedMachineEventTypes","ProcessingStatus","defaultOptions","ms","console","safeCall","arg","executeExecutableEffects","Actor","_trigger","Proxy","payload","_boundSend","_sendPublic","_boundProcess","mailbox","_mailboxStarted","observers","_errorObserved","eventListeners","NotStarted","_forceDeferredActions","_lastSourceRef","_collectedActions","_initialEffects","_deferred","_restored","_warnedUnhandledTypes","resolvedOptions","rootActor","createRuntimeSystem","initialize","requestedId","counter","resolveActorId","restore","_restore","_setSnapshot","parentRef","_getLogger","_defer","_stopChild","_executeAction","Running","saveExecutingCustomAction","Stopped","_recoverOrError","_setErrorSnapshot","_tryHandleExecutionError","_error","errorEvent","getExecutionErrorEvent","_next","deferred","deferredFn","_inspectTransition","sent","_flushInitialEffects","nextListenerOrObserver","errorListener","completeListener","handler","selector","equalityFn","selected","_stopProcedure","_complete","restored","refreshSnapshotActorRefRoot","wallClock","min","caughtError","_reportUnhandledEvent","onUnhandledEvent","_reportUnlessObserved","snapshotChildren","reportError","InvalidSnapshotError","isSnapshotRecord","isActorLogic","validatePersistedStateValue","invalidValue","childNode","validatePersistedSnapshot","childLogics","remote","EMPTY_OBJECT","StateNode","description","schemas","after","events","ownEvents","_candidateCache","_key","_machine","hasUnescapedDot","firstStateKey","choice","validateStateNodeConfig","idMap","collection","iteratee","collectionKeys","configurable","writable","mapValues","stateConfig","invokeConfig","resolvedId","_initialize","afterConfig","timeoutConfig","onTimeoutConfig","onTimeout","invokeDefs","isNaN","fromDelaysMap","eventMatcher","delayedTransitions","eventPattern","delayedTransition","getDelayedTransitions","addTransitions","additions","transitionsConfig","mapTransitionConfigs","onDone","onError","createCancelInvokeTimeoutTransition","timeoutKey","_args","formatInvokeCompletionTransition","rest","didEnqueue","trackingEnqueue","apply","thisArg","argArray","Reflect","prop","receiver","withInvokeMatch","invokeTimeoutKey","invokeDoneTransitions","rawTransition","formatTransitions","validateChoiceResult","formatChoiceTransitions","_refreshEventMetadata","object","memoizedData","memo","_target","targetString","targetStrings","resolvedTargets","formatInitialTransition","candidates","exactMatches","wildcardCandidates","eventDescriptor","getCandidates","transitionConfigs","assertValid","validator","request","check","emptyCanActor","emptyCanActorScope","getEmptyCanActorScope","StateMachine","_internalEventType","_transitionMetaType","_inputType","_actionMap","_actorMap","_stateSchema","version","internalEventDescriptors","_json","rootStateNode","routeTransitions","collectRoutes","route","routeId","routeConfig","routeMatches","_guard","routeOptions","formatRouteTransitions","provide","provided","resolveState","resolvedStateValue","usesInertScope","resolvedActorScope","fastSnapshot","_transitionFast","returnedSnapshot","_attachPureActorRef","_collectEffects","skipInitializingActor","sourceNode","stateChanged","rootInput","snapshots","emptyActorScope","transitionData","_getPreInitialState","initEvent","preInitial","spawnedChildren","referencedSrc","createSpawner","withActorSelf","takeSpawnAllocationCounters","finalizeInitialResult","macroState","preInitialState","contextSpawnEffects","createSpawnEffect","initialStateNodes","collectDefaultEntryStates","other","initialMicrostep","errorMacrostep","_rehydrated","hasPrefix","STATE_IDENTIFIER","childrenJson","timersJson","embedChildren","sourceKey","def","embed","snapshotActor","scheduled","persisted","stateInputs","snapshotSchemas","restoreLogicSnapshot","restoreMachineSnapshot","createRestoreHook","createRestoreErrorSnapshot","snapshotMachine","persistedMachine","legacyPersistedVersion","persistedVersion","migrate","snapshotData","actorData","childState","persistedTimers","targetDescription","revivedHistoryValue","revived","arr","resolved","reviveHistoryValue","_persistedSnapshotVersion","_nextActorId","_legacyNextActorId","persistedRest","restoredCounters","restoredSnapshot","reviveContext","isRoot","proto","getPrototypeOf","persistedSnapshot","actorOptions","vendor","validate","contextSchema"],"mappings":"oPAOO,SAASA,EAAYC,KAAiBC,GAC3C,MAAO,iBAAiBD,IACtBC,EAAOC,OACH,KAAKD,EACFE,IAAKC,GACa,iBAAVA,EAAqBC,KAAKC,UAAUF,GAASG,OAAOH,IAE5DI,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AAI7X,aAKhHnT,EAAU/B,EAAO/N,KACnB,CACA,IAAK,MAAMS,IAAO,CAAC,QAAS,YAC1B,KAAMA,KAAOmM,GACX,MAAO,CACLkuB,OAAQ,CAAC,CAAE7X,QAAS,kCAAkCxiB,SAI5D,IACG,CAAC,SAAU,OAAQ,QAAS,WAAW2B,SACtCwK,EAAS9J,QAGX,MAAO,CACLg4B,OAAQ,CAAC,CAAE7X,QAAS,4CAGxB,IAAKsd,GAAiB3zB,EAASga,cAC7B,MAAO,CACLkU,OAAQ,CACN,CAAE7X,QAAS,oDAIjB,IACE2d,GAA0Bhe,EAAShW,EACpC,CAAC,MAAO5J,GACP,MAAO,CACL83B,OAAQ,CACN,CACE7X,QACEjgB,aAAiBnC,MACbmC,EAAMigB,QACN,gDAId,CACA,MAAO,CACLjjB,MAAO,IAAK4M,EAAUkD,gBAOlC"}
1
+ {"version":3,"file":"xstate-persist.umd.min.js","sources":["../src/legacySnapshot.ts","../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/timerClock.ts","../src/actions.ts","../src/actorSource.ts","../src/systemLogicMetadata.ts","../src/actors/attached.ts","../src/actors/listener.ts","../src/actors/subscription.ts","../src/transitionActions.ts","../src/inspectionAmbient.ts","../src/snapshotActorRef.ts","../src/actorScope.ts","../src/inertActorScope.ts","../src/stateUtils.ts","../src/delay.ts","../src/utils.ts","../src/State.ts","../src/system.ts","../src/createActor.ts","../src/persistedSnapshotValidation.ts","../src/memo.ts","../src/StateNode.ts","../src/validation.ts","../src/StateMachine.ts","../src/spawn.ts","../src/machineSchemas.ts","../src/persist/index.ts"],"sourcesContent":["// TODO(v7): remove this module and its callers. It reads snapshots written by\n// 6.0.0-beta.1, which used `$`- and `_`-prefixed field names that stores such\n// as Convex reject. Snapshots are written with the new names only.\n\n// Legacy marker key -> [new key, other keys the marker object may have].\nconst markers: Record<string, [string, string[]]> = {\n $actor: ['@actor', ['incarnation']],\n $error: ['@error', ['message']],\n $stateNode: ['@stateNode', []],\n $systemMapper: ['@systemMapper', []]\n};\n\nconst fields: Record<string, string> = {\n _stateInputs: 'stateInputs',\n _nextTimerId: 'nextTimerId',\n _nextActorIds: 'nextActorIds'\n};\n\n// Persisted snapshots are JSON; live objects (actors, state nodes, errors)\n// are left alone.\nfunction isPlain(value: any): boolean {\n if (!value || typeof value !== 'object') return false;\n const proto = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null || Array.isArray(value);\n}\n\nfunction renameMarkers(value: any, allowed: readonly string[]): any {\n if (!isPlain(value)) return value;\n if (Array.isArray(value)) {\n const items = value.map((item) => renameMarkers(item, allowed));\n return items.some((item, i) => item !== value[i]) ? items : value;\n }\n const keys = Object.keys(value);\n const legacy = keys.find((key) => allowed.includes(key));\n if (\n legacy &&\n typeof value[legacy] === 'string' &&\n keys.every((key) => key === legacy || markers[legacy][1].includes(key))\n ) {\n const { [legacy]: name, ...rest } = value;\n return { [markers[legacy][0]]: name, ...rest };\n }\n let copy: any;\n for (const key of keys) {\n const item = renameMarkers(value[key], allowed);\n if (item !== value[key]) (copy ??= { ...value })[key] = item;\n }\n return copy ?? value;\n}\n\n// beta.1 always wrote `_nextTimerId` on machine snapshots. Current snapshots\n// write `nextTimerId`, so marker-shaped data in them is left alone.\nfunction isLegacyEnvelope(envelope: any): boolean {\n return (\n isPlain(envelope) &&\n '_nextTimerId' in envelope &&\n !('nextTimerId' in envelope)\n );\n}\n\nfunction renameFields(envelope: any): any {\n // A live machine snapshot keeps its `_`-prefixed in-memory fields.\n if (!isPlain(envelope) || typeof envelope.matches === 'function')\n return envelope;\n let copy: any;\n for (const [legacy, name] of Object.entries(fields)) {\n if (legacy in envelope && !(name in envelope)) {\n const { [legacy]: value, ...rest } = copy ?? envelope;\n copy = { ...rest, [name]: value };\n }\n }\n return copy ?? envelope;\n}\n\n/** Upgrades a persisted machine snapshot written by 6.0.0-beta.1. */\nexport function upgradeLegacyPersistedSnapshot<T>(snapshot: T): T {\n if (\n (snapshot as any)?.machine &&\n typeof (snapshot as any).matches === 'function'\n )\n return snapshot;\n if (!isLegacyEnvelope(snapshot)) return snapshot;\n return renameMarkers(renameFields(snapshot), ['$actor']);\n}\n\n/** Upgrades a `systemTransition` snapshot written by 6.0.0-beta.1. */\nexport function upgradeLegacySystemSnapshot<T>(snapshot: T): T {\n const actors: any[] = Object.values((snapshot as any)?.actors ?? {});\n if (!actors.some((actor) => isLegacyEnvelope(actor?.snapshot)))\n return snapshot;\n const upgraded = renameMarkers(snapshot, Object.keys(markers));\n if (!upgraded?.actors) return upgraded;\n let renamed: any;\n for (const [address, actor] of Object.entries<any>(upgraded.actors)) {\n const data = renameFields(actor?.snapshot);\n if (data !== actor?.snapshot)\n (renamed ??= { ...upgraded.actors })[address] = {\n ...actor,\n snapshot: data\n };\n }\n return renamed ? { ...upgraded, actors: renamed } : upgraded;\n}\n","/**\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 type { LogicalTimer } from './types.ts';\n\n// Runtime metadata stays outside pure snapshots. Timer objects survive unrelated\n// transitions; a cancelled/replaced timer gets a new object and a new deadline.\nconst starts = new WeakMap<LogicalTimer, number>();\n\n/** @internal */\nexport function getTimerStart(timer: LogicalTimer): number | undefined {\n return starts.get(timer) ?? timer.scheduledAt;\n}\n\n/** @internal */\nexport function recordTimerStart(\n timer: LogicalTimer,\n scheduledAt: number\n): void {\n starts.set(timer, scheduledAt);\n}\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 type { AnyActorLogic } from './types.ts';\n\nconst sourceKeyCaches = new WeakMap<object, Map<AnyActorLogic, string>>();\n\n/** @internal */\nexport function resolveRegisteredActorSource(\n actors: Record<string, AnyActorLogic>,\n logic: AnyActorLogic\n): string | undefined {\n let cache = sourceKeyCaches.get(actors);\n if (!cache) {\n cache = new Map();\n for (const key of Object.keys(actors)) {\n const registeredLogic = actors[key];\n // Several source keys may intentionally share one implementation. The\n // first key is its canonical persistence identity when spawning by the\n // raw logic value, which cannot retain which alias was used to access it.\n if (!cache.has(registeredLogic)) {\n cache.set(registeredLogic, key);\n }\n }\n sourceKeyCaches.set(actors, cache);\n }\n\n return cache.get(logic);\n}\n","/** Static scheduling metadata on actor definitions, never on live actors. @internal */\nexport const systemLogicMetadata = Symbol('xstate.systemLogicMetadata');\n","import { XSTATE_STOP } from '../constants.ts';\nimport { systemLogicMetadata } from '../systemLogicMetadata.ts';\nimport type { AnyActorSystem } from '../system.ts';\nimport type {\n AnyActor,\n EventObject,\n Snapshot,\n Subscription\n} from '../types.ts';\n\nconst subscriptions = /* #__PURE__ */ new WeakMap<AnyActor, Subscription>();\n\n/**\n * Internal factory for actor logic that attaches to another actor on start\n * (`enq.listen()` / `enq.subscribeTo()`) and detaches when stopped.\n */\nexport function createAttachedLogic(\n attach: (\n input: any,\n scope: { self: AnyActor; system: AnyActorSystem }\n ) => Subscription | undefined,\n /**\n * Names the logic so its generated actor ids get their own prefix, out of\n * the id space that user sources allocate from.\n */\n id?: string\n): any {\n const initialTransition = (input: unknown, _: unknown) =>\n [\n {\n status: 'active',\n output: undefined,\n error: undefined,\n input\n },\n []\n ] as const;\n\n const logic = {\n id,\n start: (state: any, { self, system }: any) => {\n // Don't attach if the target doesn't exist or is stopped.\n const target = state.input.actor;\n if (!target || target.getSnapshot().status === 'stopped') {\n return;\n }\n const subscription = attach(state.input, { self, system });\n if (!subscription) {\n return;\n }\n\n // Attached actors are not registered as children (their `input` holds\n // non-serializable function mappers), so a parent stop does not cascade\n // to them. Subscribe to the parent and tear down when it stops/errors,\n // so the subscription never relays to a stopped parent or leaks the\n // source subscription.\n let parentSubscription: Subscription | undefined;\n let torndown = false;\n const teardown = () => {\n if (torndown) {\n return;\n }\n torndown = true;\n subscription.unsubscribe();\n parentSubscription?.unsubscribe();\n };\n\n const parent: AnyActor | undefined = self._parent;\n if (parent) {\n parentSubscription = parent.subscribe({\n complete: teardown,\n error: teardown\n });\n }\n\n subscriptions.set(self, { unsubscribe: teardown });\n },\n transition: (state: any, event: EventObject, { self }: any) => {\n if (event.type === XSTATE_STOP) {\n subscriptions.get(self)?.unsubscribe();\n subscriptions.delete(self);\n return [\n {\n ...state,\n status: 'stopped',\n error: undefined\n },\n []\n ];\n }\n return [state, []];\n },\n initialTransition,\n getInitialSnapshot: (actorScope: unknown, input: unknown) =>\n initialTransition(input, actorScope)[0],\n getPersistedSnapshot: (snapshot: Snapshot<unknown>) => snapshot,\n restoreSnapshot: (snapshot: Snapshot<unknown>) => snapshot\n };\n Object.defineProperty(logic, systemLogicMetadata, { value: { kind: id } });\n return logic;\n}\n\n/**\n * Relays a mapped event to the attached actor's parent, unless the attached\n * actor has been stopped (the mapper is not called in that case).\n */\nexport function relayMappedToParent(\n self: AnyActor,\n system: AnyActorSystem,\n getEvent: () => EventObject\n): void {\n if (self.getSnapshot().status === 'stopped' || !self._parent) {\n return;\n }\n system._relay(self, self._parent, getEvent());\n}\n","import { AnyActorSystem } from '../system.ts';\nimport { matchesEventDescriptor } from '../utils.ts';\nimport {\n ActorLogic,\n ActorRefFrom,\n AnyActor,\n EventObject,\n Snapshot\n} from '../types';\nimport { createAttachedLogic, relayMappedToParent } from './attached.ts';\n\n/** @public */\nexport type ListenerSnapshot = Snapshot<undefined> & {\n input: ListenerInput<any, any>;\n};\n\n/** @public */\nexport interface ListenerInput<\n TEmitted extends EventObject,\n TMappedEvent extends EventObject\n> {\n actor: AnyActor;\n eventType: string;\n mapper: (event: TEmitted) => TMappedEvent;\n}\n\n/** @public */\nexport type ListenerActorLogic<\n TEmitted extends EventObject = EventObject,\n TMappedEvent extends EventObject = EventObject\n> = ActorLogic<\n ListenerSnapshot,\n EventObject,\n ListenerInput<TEmitted, TMappedEvent>,\n AnyActorSystem,\n EventObject\n>;\n\n/** @public */\nexport type ListenerActorRef<\n TEmitted extends EventObject = EventObject,\n TMappedEvent extends EventObject = EventObject\n> = ActorRefFrom<ListenerActorLogic<TEmitted, TMappedEvent>>;\n\n/**\n * Creates actor logic for listening to emitted events from another actor. Used\n * internally by `enq.listen()`.\n *\n * @public\n */\nexport function createListenerLogic<\n TEmitted extends EventObject = EventObject,\n TMappedEvent extends EventObject = EventObject\n>(): ListenerActorLogic<TEmitted, TMappedEvent> {\n return createAttachedLogic(\n (\n { actor, eventType, mapper }: ListenerInput<TEmitted, TMappedEvent>,\n { self, system }\n ) => {\n // Determine the subscription type:\n // - For exact matches or '*', subscribe directly\n // - For partial wildcards ('data.*'), subscribe to '*' and filter\n const isPartialWildcard = eventType !== '*' && eventType.endsWith('.*');\n\n return actor.on(isPartialWildcard ? '*' : eventType, (emittedEvent) => {\n if (\n isPartialWildcard &&\n !matchesEventDescriptor(emittedEvent.type, eventType)\n ) {\n return;\n }\n relayMappedToParent(self, system, () =>\n mapper(emittedEvent as TEmitted)\n );\n });\n },\n '@xstate.listener'\n );\n}\n\n/** @internal The logic of helper actors created by `enq.listen()`. */\nexport const listenerLogic = /* #__PURE__ */ createListenerLogic();\n","import { AnyActorSystem } from '../system.ts';\nimport {\n ActorLogic,\n ActorRefFrom,\n AnyActorRef,\n EventObject,\n Snapshot\n} from '../types';\nimport { createAttachedLogic, relayMappedToParent } from './attached.ts';\n\n/** @public */\nexport type SubscriptionSnapshot = Snapshot<undefined> & {\n input: SubscriptionInput<any, any, any, any>;\n};\n\n/** @public */\nexport interface SubscriptionMappers<\n TSnapshot extends Snapshot<unknown>,\n TOutput,\n TMappedEvent extends EventObject\n> {\n snapshot?: (snapshot: TSnapshot) => TMappedEvent;\n done?: (output: TOutput) => TMappedEvent;\n error?: (error: unknown) => TMappedEvent;\n}\n\n/** @public */\nexport interface SubscriptionInput<\n TSnapshot extends Snapshot<unknown>,\n TOutput,\n TMappedEvent extends EventObject,\n TMappers extends SubscriptionMappers<TSnapshot, TOutput, TMappedEvent>\n> {\n actor: AnyActorRef;\n mappers: TMappers;\n}\n\n/** @public */\nexport type SubscriptionActorLogic<\n TSnapshot extends Snapshot<unknown> = Snapshot<unknown>,\n TOutput = unknown,\n TMappedEvent extends EventObject = EventObject\n> = ActorLogic<\n SubscriptionSnapshot,\n EventObject,\n SubscriptionInput<\n TSnapshot,\n TOutput,\n TMappedEvent,\n SubscriptionMappers<TSnapshot, TOutput, TMappedEvent>\n >,\n AnyActorSystem,\n EventObject\n>;\n\n/** @public */\nexport type SubscriptionActorRef<\n TSnapshot extends Snapshot<unknown> = Snapshot<unknown>,\n TOutput = unknown,\n TMappedEvent extends EventObject = EventObject\n> = ActorRefFrom<SubscriptionActorLogic<TSnapshot, TOutput, TMappedEvent>>;\n\n/**\n * Creates actor logic for subscribing to lifecycle events (done/error/snapshot)\n * from another actor. Used internally by `enq.subscribeTo()`.\n *\n * @public\n */\nexport function createSubscriptionLogic<\n TSnapshot extends Snapshot<unknown> = Snapshot<unknown>,\n TOutput = unknown,\n TMappedEvent extends EventObject = EventObject\n>(): SubscriptionActorLogic<TSnapshot, TOutput, TMappedEvent> {\n return createAttachedLogic(({ actor, mappers }, { self, system }) => {\n const { done, error, snapshot: onSnapshot } = mappers;\n\n return actor.subscribe({\n next: (snapshot: TSnapshot) => {\n if (snapshot.status === 'done' && done) {\n relayMappedToParent(self, system, () =>\n done(snapshot.output as TOutput)\n );\n } else if (snapshot.status === 'error' && error) {\n relayMappedToParent(self, system, () => error(snapshot.error));\n } else if (snapshot.status === 'active' && onSnapshot) {\n relayMappedToParent(self, system, () => onSnapshot(snapshot));\n }\n },\n error: (err: unknown) => {\n if (error) {\n relayMappedToParent(self, system, () => error(err));\n }\n },\n complete: () => {\n // Actor completed without output (stopped); no action needed\n }\n });\n }, '@xstate.subscription');\n}\n\n/** @internal The logic of helper actors created by `enq.subscribeTo()`. */\nexport const subscriptionLogic = /* #__PURE__ */ createSubscriptionLogic();\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 type { InspectionEvent } from './inspection.ts';\n\n/**\n * The ambiently installed system inspector. Set for the duration of a durable\n * execution's transitions (`createDurable(..., { inspect })`), it makes the\n * pure-transition machinery observable: freshly constructed runtime systems\n * attach it, and snapshot systems created while it is set forward inspection\n * to their base system instead of stubbing it out.\n */\nlet ambientInspector: ((inspectionEvent: InspectionEvent) => void) | undefined;\n\n/** @internal */\nexport function hasAmbientInspector(): boolean {\n return ambientInspector !== undefined;\n}\n\n/** @internal */\nexport function getAmbientInspector():\n | ((inspectionEvent: InspectionEvent) => void)\n | undefined {\n return ambientInspector;\n}\n\n/**\n * Runs `fn` with systems it creates wired to `inspect` from construction, so\n * creation-time inspection events (the root actor's own registration, actors\n * spawned during the first transition) are observed too.\n *\n * @internal\n */\nexport function withSystemInspector<T>(\n inspect: ((inspectionEvent: InspectionEvent) => void) | undefined,\n fn: () => T\n): T {\n if (!inspect) {\n return fn();\n }\n const previous = ambientInspector;\n ambientInspector = inspect;\n try {\n return fn();\n } finally {\n ambientInspector = previous;\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 type { AnyActor, AnyActorScope } from './types.ts';\n\n/** Marks the internal lazy scope without imposing structure on custom runtimes. @internal */\nexport const lazyActorScope = Symbol();\n\ntype InternalActorScope = AnyActorScope & {\n _parent?: AnyActor;\n [lazyActorScope]?: true;\n};\n\n/** Whether actor capabilities are represented by a lazy pure-transition scope. @internal */\nexport function isLazyActorScope(actorScope: AnyActorScope): boolean {\n return !!(actorScope as InternalActorScope)[lazyActorScope];\n}\n\n/** Reads parent metadata without otherwise touching actor capabilities. @internal */\nexport function getActorScopeParent(\n actorScope: AnyActorScope\n): AnyActor | undefined {\n return isLazyActorScope(actorScope)\n ? (actorScope as InternalActorScope)._parent\n : actorScope.self._parent;\n}\n\n/** Adds only `self`, preserving callback surfaces that expose no other capabilities. @internal */\nexport function withActorSelf<T extends object>(\n args: T,\n actorScope: AnyActorScope\n): T & Pick<AnyActorScope, 'self'> {\n if (!isLazyActorScope(actorScope)) {\n return Object.assign(args, { self: actorScope.self });\n }\n Object.defineProperty(args, 'self', {\n enumerable: true,\n get: () => actorScope.self\n });\n return args as T & Pick<AnyActorScope, 'self'>;\n}\n\n/** Adds the actor reference and parent without exposing the system. @internal */\nexport function withActorSelfAndParent<T extends object>(\n args: T,\n actorScope: AnyActorScope\n): T & Pick<AnyActorScope, 'self'> & { parent: AnyActor | undefined } {\n if (!isLazyActorScope(actorScope)) {\n const self = actorScope.self;\n return Object.assign(args, { self, parent: self._parent });\n }\n Object.defineProperties(args, {\n self: { enumerable: true, get: () => actorScope.self },\n parent: { enumerable: true, get: () => getActorScopeParent(actorScope) }\n });\n return args as T &\n Pick<AnyActorScope, 'self'> & { parent: AnyActor | undefined };\n}\n\n/** Adds actor capabilities without reading them until the callback does. @internal */\nexport function withActorScope<T extends object>(\n args: T,\n actorScope: AnyActorScope\n): T &\n Pick<AnyActorScope, 'self' | 'system'> & {\n parent: AnyActor | undefined;\n } {\n if (!isLazyActorScope(actorScope)) {\n const actorArgs = args as T &\n Pick<AnyActorScope, 'self' | 'system'> & {\n parent: AnyActor | undefined;\n };\n const self = actorScope.self;\n actorArgs.self = self;\n actorArgs.system = actorScope.system;\n actorArgs.parent = self._parent;\n return actorArgs;\n }\n Object.defineProperties(args, {\n self: { enumerable: true, get: () => actorScope.self },\n system: { enumerable: true, get: () => actorScope.system },\n parent: { enumerable: true, get: () => getActorScopeParent(actorScope) }\n });\n return args as T &\n Pick<AnyActorScope, 'self' | 'system'> & {\n parent: AnyActor | undefined;\n };\n}\n","import { createActor } from './createActor.ts';\nimport { isMachineSnapshot } from './State.ts';\nimport {\n createSnapshotSystem,\n getSnapshotActorRef,\n getSnapshotActorRefProvider,\n peekSnapshotActorRef,\n setLazySnapshotActorRef,\n setSnapshotActorRef,\n takeExecutionOwner,\n type ExecutionOwner,\n type SnapshotActorRef\n} from './snapshotActorRef.ts';\nimport {\n ActorScope,\n AnyActor,\n AnyActorLogic,\n AnyActorScope,\n EmittedFrom,\n EventFromLogic,\n Snapshot,\n SnapshotFrom\n} from './types.ts';\nimport { lazyActorScope } from './actorScope.ts';\n\n/** @internal */\nexport function setInertActorScopeSnapshot<T>(\n actorScope: AnyActorScope,\n snapshot: T,\n attachActorRef = true\n): T {\n const lazyState = getLazyInertActorState(actorScope);\n if (lazyState) {\n lazyState.snapshot = snapshot;\n const scope = lazyState.materialized ?? lazyState.identityScope;\n if (scope) {\n (scope.self as any)._snapshot = snapshot;\n }\n } else {\n (actorScope.self as any)._snapshot = snapshot;\n }\n if (attachActorRef && snapshot && typeof snapshot === 'object') {\n setSnapshotActorRef(snapshot as any, actorScope.self);\n }\n return snapshot;\n}\n\n/** @internal */\nexport function isInertActorScope(actorScope: AnyActorScope): boolean {\n return (\n !!getLazyInertActorState(actorScope) ||\n !!(actorScope.self as any).options?._inert\n );\n}\n\n/** @internal */\nexport function attachSnapshotActorRef<TSnapshot>(\n actorScope: AnyActorScope,\n snapshot: TSnapshot\n): TSnapshot {\n setInertActorScopeSnapshot(actorScope, snapshot, false);\n const lazyState = getLazyInertActorState(actorScope);\n snapshotActorScopes.set(snapshot as object, actorScope);\n const create = () => {\n setSnapshotActorRef(\n snapshot as Snapshot<unknown>,\n actorScope.self,\n actorScope.system\n );\n return getSnapshotActorRef(snapshot as Snapshot<unknown>)!;\n };\n if (lazyState) {\n if (lazyState.materialized) {\n lazyState.identityProvider = create;\n } else {\n lazyState.identityProvider ??= create;\n }\n }\n setLazySnapshotActorRef(snapshot as Snapshot<unknown>, create);\n return snapshot;\n}\n\ntype LazyInertActorState = {\n snapshot: unknown;\n materialized?: AnyActorScope;\n identityScope?: AnyActorScope;\n sourceRef?: () => SnapshotActorRef;\n sourceChildren: Record<string, AnyActor | undefined>;\n identityProvider?: () => SnapshotActorRef;\n parent?: AnyActor;\n parentKnown: boolean;\n owner?: ExecutionOwner;\n materialize: () => AnyActorScope;\n};\n\n/** Records the materialized scope and releases its consumed source. */\nfunction commitMaterialization(\n state: LazyInertActorState,\n scope: AnyActorScope\n): AnyActorScope {\n // Dropping the consumed source keeps this scope from retaining earlier snapshots.\n state.sourceRef = undefined;\n state.sourceChildren = {};\n state.materialized = scope;\n state.materialize = () => scope;\n return scope;\n}\n\nconst lazyInertActorState = Symbol();\ntype LazyInertActorScope = AnyActorScope & {\n [lazyInertActorState]?: LazyInertActorState;\n};\nconst snapshotActorScopes = new WeakMap<object, AnyActorScope>();\nlet inertActorMaterializationObserver: (() => void) | undefined;\n\nfunction getLazyInertActorState(\n actorScope: AnyActorScope\n): LazyInertActorState | undefined {\n return (actorScope as LazyInertActorScope)[lazyInertActorState];\n}\n\nfunction materializeInertActorScope(actorScope: AnyActorScope): AnyActorScope {\n return getLazyInertActorState(actorScope)!.materialize();\n}\n\nconst lazyInertActorScopePrototype = {\n [lazyActorScope]: true,\n get _parent() {\n const actorScope = this as AnyActorScope;\n const state = getLazyInertActorState(actorScope)!;\n return state.parentKnown\n ? state.parent\n : materializeInertActorScope(actorScope).self._parent;\n },\n get self() {\n return materializeInertActorScope(this as AnyActorScope).self;\n },\n get defer() {\n return materializeInertActorScope(this as AnyActorScope).defer;\n },\n get id() {\n return materializeInertActorScope(this as AnyActorScope).id;\n },\n get logger() {\n return materializeInertActorScope(this as AnyActorScope).logger;\n },\n get sessionId() {\n return materializeInertActorScope(this as AnyActorScope).sessionId;\n },\n get stopChild() {\n return materializeInertActorScope(this as AnyActorScope).stopChild;\n },\n get system() {\n return materializeInertActorScope(this as AnyActorScope).system;\n },\n get emit() {\n return materializeInertActorScope(this as AnyActorScope).emit;\n },\n get actionExecutor() {\n return materializeInertActorScope(this as AnyActorScope).actionExecutor;\n }\n};\n\n/** Test-only allocation instrumentation. @internal */\nexport function setInertActorMaterializationObserver(\n observer: (() => void) | undefined\n): void {\n inertActorMaterializationObserver = observer;\n}\n\n/** Creates a transactional planning scope backed by an inert actor. */\nfunction createMaterializedInertActorScope<T extends AnyActorLogic>(\n actorLogic: T,\n sourceRef: (() => SnapshotActorRef) | undefined,\n sourceChildren: Record<string, AnyActor | undefined>,\n currentSnapshot: SnapshotFrom<T> | undefined,\n sourceSelf?: AnyActor,\n owner?: ExecutionOwner\n): AnyActorScope {\n inertActorMaterializationObserver?.();\n const snapshotRef = sourceRef?.();\n const previousSelf = sourceSelf ?? snapshotRef?.actor;\n const baseSystem = previousSelf?.system;\n const system =\n previousSelf && baseSystem\n ? createSnapshotSystem(\n baseSystem,\n sourceChildren,\n sourceSelf ? undefined : snapshotRef?.systemState,\n owner\n )\n : undefined;\n const self = createActor(\n actorLogic as AnyActorLogic,\n {\n _inert: true,\n ...(previousSelf\n ? {\n id: previousSelf.id,\n _sessionId: previousSelf.sessionId\n }\n : {}),\n ...(system ? { _systemRef: { current: system } } : {})\n } as any\n );\n if (previousSelf?._parent) {\n self._parent = previousSelf._parent;\n // `address` memoizes on first read assuming `_parent` is final; nothing\n // reads it between construction and this assignment, but drop any memo so\n // a future construction-time read cannot pin a root-shaped address.\n (self as unknown as { _address?: string })._address = undefined;\n }\n // Reuse the branch actor's scope while keeping planning transactional.\n const scope = Object.create((self as any)._actorScope, {\n defer: { value: () => {} },\n stopChild: { value: (child: AnyActor) => (child as any)._stop() },\n actionExecutor: { value: () => {} },\n _snapshot: {\n enumerable: true,\n configurable: true,\n get: () => (self as any)._snapshot,\n set: (snapshot: SnapshotFrom<T>) => {\n (self as any)._snapshot = snapshot;\n }\n }\n });\n if (currentSnapshot) {\n scope._snapshot = currentSnapshot;\n }\n return scope;\n}\n\n/** @internal */\nexport function createInertActorScope<T extends AnyActorLogic>(\n actorLogic: T,\n snapshot?: SnapshotFrom<T>,\n sourceSelf?: AnyActor,\n sourceActorScope?: AnyActorScope\n): AnyActorScope {\n const sourceScope =\n sourceActorScope ??\n (snapshot && typeof snapshot === 'object'\n ? snapshotActorScopes.get(snapshot as object)\n : undefined);\n const sourceState = sourceScope\n ? getLazyInertActorState(sourceScope)\n : undefined;\n const eagerSourceRef =\n snapshot && typeof snapshot === 'object'\n ? peekSnapshotActorRef(snapshot as Snapshot<unknown>)\n : undefined;\n const sourceRef =\n sourceState?.identityProvider ??\n (snapshot && typeof snapshot === 'object'\n ? getSnapshotActorRefProvider(snapshot as Snapshot<unknown>)\n : undefined);\n const state = {\n snapshot,\n sourceRef,\n sourceChildren: isMachineSnapshot(snapshot)\n ? (snapshot as any).children\n : {},\n identityProvider: sourceState?.identityProvider ?? sourceRef,\n parent:\n sourceSelf?._parent ??\n sourceState?.parent ??\n eagerSourceRef?.actor._parent,\n // Only the outermost scope of an owned transition belongs to the owner;\n // scopes for its intermediate snapshots inherit it, and nested pure\n // transitions run unowned.\n owner: sourceActorScope ? sourceState?.owner : takeExecutionOwner(),\n parentKnown:\n !!sourceSelf ||\n !!sourceState?.parentKnown ||\n !!eagerSourceRef ||\n !snapshot\n } as LazyInertActorState;\n state.materialize = () => {\n const scope = createMaterializedInertActorScope(\n actorLogic,\n state.sourceRef,\n state.sourceChildren,\n state.snapshot as SnapshotFrom<T>,\n sourceSelf,\n state.owner\n );\n return commitMaterialization(state, scope);\n };\n if (!state.identityProvider && !snapshot) {\n const identitySnapshot = {} as Snapshot<unknown>;\n let identityRef: SnapshotActorRef | undefined;\n const getIdentityScope = () => {\n if (!state.identityScope) {\n state.identityScope = createMaterializedInertActorScope(\n actorLogic,\n state.sourceRef,\n state.sourceChildren,\n undefined,\n sourceSelf,\n state.owner\n );\n if (state.snapshot !== undefined) {\n (state.identityScope.self as any)._snapshot = state.snapshot;\n }\n }\n return state.identityScope;\n };\n state.materialize = () => {\n const scope = getIdentityScope();\n if (state.snapshot !== undefined) {\n (scope.self as any)._snapshot = state.snapshot;\n }\n return commitMaterialization(state, scope);\n };\n state.identityProvider = () => {\n if (identityRef) {\n return identityRef;\n }\n const scope = getIdentityScope();\n setSnapshotActorRef(identitySnapshot, scope.self, scope.system);\n return (identityRef = getSnapshotActorRef(identitySnapshot)!);\n };\n }\n const actorScope = Object.create(lazyInertActorScopePrototype) as ActorScope<\n SnapshotFrom<T>,\n EventFromLogic<T>,\n any,\n EmittedFrom<T>\n >;\n (actorScope as LazyInertActorScope)[lazyInertActorState] = state;\n return actorScope;\n}\n","import isDevelopment from '#is-development';\nimport { xstateError } from './xstateError.ts';\nimport { MachineSnapshot, cloneMachineSnapshot } from './State.ts';\nimport type { StateNode } from './StateNode.ts';\nimport {\n createAfterEvent,\n createDoneStateEvent,\n createInvokeTimeoutEvent,\n createTimeoutEvent\n} from './eventUtils.ts';\nimport {\n getBuiltInTimerIdentity,\n getTimerKey,\n matchesTimerKey,\n readTimerKey\n} from './timerKey.ts';\nimport {\n XSTATE_INIT,\n STATE_DELIMITER,\n STATE_IDENTIFIER,\n XSTATE_STOP,\n XSTATE_TIMER\n} from './constants.ts';\nimport {\n describeMachine,\n getEventOutput,\n isErrorEvent,\n matchesEvent,\n matchesEventDescriptor\n} from './utils.ts';\nimport {\n AnyEventObject,\n AnyMachineSnapshot,\n AnyStateNode,\n AnyTransitionDefinition,\n DelayedTransitionDefinition,\n EventObject,\n ExecutableEffect,\n HistoryValue,\n MachineContext,\n StateValue,\n TransitionDefinition,\n TimerKey,\n AnyAction,\n AnyTransitionConfig,\n AnyActor,\n AnyActorScope,\n DoneStateEvent,\n EnqueueObject\n} from './types.ts';\nimport {\n resolveOutput,\n normalizeTarget,\n toArray,\n toStatePath,\n toTransitionConfigArray\n} from './utils.ts';\nimport { builtInActions } from './actions.ts';\nimport {\n assertChildIdFree,\n assertRaiseEvent,\n createEnqueueObject,\n lateEnqueueCall,\n createTerminationEffect,\n closeTransitionEnqueue,\n createTransitionEnqueue,\n createSendToEffect,\n deriveDeferredStarts,\n mergeContextPatch,\n resolveActionsWithContext\n} from './transitionActions.ts';\nimport { parseDurationToMilliseconds } from './delay.ts';\nimport {\n beginTransitionSelection,\n transitionEffectSignal\n} from './transitionSelection.ts';\nimport { isInertActorScope } from './inertActorScope.ts';\nimport {\n getActorScopeParent,\n isLazyActorScope,\n withActorSelfAndParent,\n withActorScope\n} from './actorScope.ts';\n\ntype AnyStateNodeIterable = Iterable<AnyStateNode>;\n\nfunction getConfiguredDelayValue(\n delay: number | string,\n delaySource: Record<string, any>\n) {\n if (typeof delay !== 'string') {\n return delay;\n }\n\n const referencedDelay = delaySource[delay];\n if (referencedDelay !== undefined) {\n return referencedDelay;\n }\n\n const parsedDelay = parseDurationToMilliseconds(delay);\n if (parsedDelay === undefined) {\n throw new Error(\n isDevelopment\n ? `Invalid delay \"${delay}\": not a configured delay name or a valid duration string (e.g. \"500ms\", \"1.5s\", \"PT1M30S\").`\n : xstateError(9, delay)\n );\n }\n return parsedDelay;\n}\n\nfunction resolveDelay(\n delay: number | string | ((args: any) => number),\n delaySource: Record<string, any>,\n args: {\n context: MachineContext;\n event: EventObject;\n stateNode: AnyStateNode;\n input?: Record<string, unknown>;\n }\n) {\n if (typeof delay === 'function') {\n return delay(args);\n }\n\n const configuredDelay = getConfiguredDelayValue(delay, delaySource);\n if (typeof configuredDelay === 'function') {\n return configuredDelay(args);\n }\n\n return configuredDelay;\n}\n\nfunction getStateInput(snapshot: AnyMachineSnapshot, stateNodeId: string) {\n return snapshot._stateInputs?.[stateNodeId];\n}\n\nexport function isAtomicStateNode(stateNode: AnyStateNode) {\n return (\n stateNode.type === 'atomic' ||\n stateNode.type === 'final' ||\n stateNode.type === 'choice'\n );\n}\n\nfunction getChildren(stateNode: AnyStateNode): Array<AnyStateNode> {\n return Object.values(stateNode.states).filter((sn) => sn.type !== 'history');\n}\n\nexport function getProperAncestors(\n stateNode: AnyStateNode,\n toStateNode: AnyStateNode | undefined\n): Array<typeof stateNode> {\n const ancestors: Array<typeof stateNode> = [];\n\n if (toStateNode === stateNode) {\n return ancestors;\n }\n\n // add all ancestors\n let m = stateNode.parent;\n while (m && m !== toStateNode) {\n ancestors.push(m);\n m = m.parent;\n }\n\n return ancestors;\n}\n\nexport function getAllStateNodes(\n stateNodes: Iterable<AnyStateNode>\n): Set<AnyStateNode> {\n const nodeSet = new Set(stateNodes);\n const activeParentSet = new Set<AnyStateNode>();\n for (const stateNode of nodeSet) {\n if (stateNode.parent) {\n activeParentSet.add(stateNode.parent);\n }\n }\n\n // add descendants\n for (const s of nodeSet) {\n // if previously active, add existing child nodes\n if (s.type === 'compound' && !activeParentSet.has(s)) {\n for (const sn of getInitialStateNodes(s)) {\n nodeSet.add(sn);\n }\n continue;\n }\n\n if (s.type === 'parallel') {\n for (const child of getChildren(s)) {\n if (!nodeSet.has(child)) {\n const initialStates = getInitialStateNodes(child);\n for (const initialStateNode of initialStates) {\n nodeSet.add(initialStateNode);\n }\n }\n }\n }\n }\n\n // add all ancestors\n // Stop walking up as soon as we hit a node already in the set: its own\n // ancestor chain is guaranteed to be added when it is visited by this loop\n // (Set iteration visits elements added during iteration), so shared ancestor\n // chains are never re-walked once per descendant.\n for (const s of nodeSet) {\n let m = s.parent;\n\n while (m && !nodeSet.has(m)) {\n nodeSet.add(m);\n m = m.parent;\n }\n }\n\n return nodeSet;\n}\n\nexport function getStateValue(\n rootNode: AnyStateNode,\n stateNodes: AnyStateNodeIterable\n): StateValue {\n const config = getAllStateNodes(stateNodes);\n const adjList = new Map<AnyStateNode, Array<AnyStateNode>>();\n\n for (const s of config) {\n if (!adjList.has(s)) {\n adjList.set(s, []);\n }\n\n if (!s.parent) {\n continue;\n }\n\n if (!adjList.has(s.parent)) {\n adjList.set(s.parent, []);\n }\n\n adjList.get(s.parent)!.push(s);\n }\n\n const getValueFromAdj = (baseNode: AnyStateNode): StateValue => {\n const childStateNodes = adjList.get(baseNode);\n\n if (!childStateNodes) {\n return {}; // todo: fix?\n }\n\n if (baseNode.type === 'compound') {\n const childStateNode = childStateNodes[0];\n if (!childStateNode) {\n return {};\n }\n if (isAtomicStateNode(childStateNode)) {\n return childStateNode.key;\n }\n }\n\n const stateValue: StateValue = {};\n for (const childStateNode of childStateNodes) {\n stateValue[childStateNode.key] = getValueFromAdj(childStateNode);\n }\n\n return stateValue;\n };\n\n return getValueFromAdj(rootNode);\n}\n\nexport function isInFinalState(\n stateNodeSet: Set<AnyStateNode>,\n stateNode: AnyStateNode\n): boolean {\n if (stateNode.type === 'compound') {\n return getChildren(stateNode).some(\n (s) => s.type === 'final' && stateNodeSet.has(s)\n );\n }\n if (stateNode.type === 'parallel') {\n return getChildren(stateNode).every((sn) =>\n isInFinalState(stateNodeSet, sn)\n );\n }\n\n return stateNode.type === 'final';\n}\n\nexport const isStateId = (str: string) => str[0] === STATE_IDENTIFIER;\n\nexport function matchesActorSession(\n event: EventObject,\n snapshot: AnyMachineSnapshot,\n actorId: string\n): boolean {\n const child = snapshot.children[actorId];\n if (!child || !('sessionId' in event)) {\n return true;\n }\n // One rule: a ref that knows its incarnation compares it; a remote handle\n // without a host-supplied token (sessionId undefined) defers to the\n // runtime that owns the child.\n return (\n child.sessionId === undefined ||\n child.sessionId === (event as { sessionId?: string }).sessionId\n );\n}\n\nexport function getCandidates<TEvent extends EventObject>(\n stateNode: StateNode<any, TEvent>,\n event: TEvent\n): Array<TransitionDefinition<any, TEvent>> {\n const exactMatches = stateNode.transitions.get(event.type) ?? [];\n const wildcardCandidates = [...stateNode.transitions.keys()]\n .filter(\n (eventDescriptor) =>\n eventDescriptor !== event.type &&\n matchesEventDescriptor(event.type, eventDescriptor)\n )\n .sort((a, b) => b.length - a.length)\n .flatMap((key) => stateNode.transitions.get(key)!);\n\n return exactMatches.length\n ? [...exactMatches, ...wildcardCandidates]\n : wildcardCandidates;\n}\n\nfunction scheduleDelayedEvent(\n stateNode: AnyStateNode,\n timerEvent: AnyEventObject,\n resolveEvent: (args: any) => AnyEventObject,\n resolveScheduledDelay: (x: {\n context: MachineContext;\n event: EventObject;\n delays: Record<string, any>;\n input?: Record<string, unknown>;\n }) => any\n) {\n const oldEntry = stateNode.entry;\n stateNode.entry = (x: any, enq: any) => {\n const result =\n typeof oldEntry === 'function' ? oldEntry(x, enq) : undefined;\n // The entry context patch is applied by the caller after this wrapper returns.\n const context =\n result?.context !== undefined\n ? mergeContextPatch(x.context, result.context)\n : x.context;\n // Built-in timers have no id: the event identifies them.\n enq.raise(resolveEvent(x) as any, {\n delay: resolveScheduledDelay({\n context,\n event: x.event,\n delays: x.delays,\n input: x.input\n })\n });\n return result;\n };\n const oldExit = stateNode.exit;\n stateNode.exit = (_: any, enq: any) => {\n enq.cancel({ event: getBuiltInTimerIdentity(timerEvent)! });\n return typeof oldExit === 'function' ? oldExit(_, enq) : undefined;\n };\n}\n\n/** All delayed transitions from the config. */\nexport function getDelayedTransitions(\n stateNode: AnyStateNode\n): Array<DelayedTransitionDefinition<MachineContext, EventObject>> {\n const afterConfig = stateNode.config.after;\n const timeoutConfig = (stateNode.config as any).timeout;\n const onTimeoutConfig = (stateNode.config as any).onTimeout;\n const invokeDefs = stateNode.invoke.filter(\n (invokeDef) => invokeDef.timeout !== undefined\n );\n\n if (!afterConfig && timeoutConfig === undefined && invokeDefs.length === 0) {\n return [];\n }\n\n if (isDevelopment && timeoutConfig !== undefined && !onTimeoutConfig) {\n throw new Error(\n `State \"${stateNode.id}\" has \\`timeout\\` but no \\`onTimeout\\` transition.`\n );\n }\n\n if (isDevelopment) {\n for (const invokeDef of invokeDefs) {\n if (!invokeDef.onTimeout) {\n throw new Error(\n `Invoke on state \"${stateNode.id}\" has \\`timeout\\` but no \\`onTimeout\\` transition.`\n );\n }\n }\n }\n\n // Every delayed transition — `after`, state-level `timeout`/`onTimeout`, and\n // invoke-level `timeout`/`onTimeout` — has the same shape: an event raised on\n // entry (and cancelled on exit) plus a transition that catches it. They\n // differ only in the event raised, the transition(s) caught, and whether the\n // delay resolves against the machine's `delays` map (invoke timeouts do not).\n //\n // `xstate.timeout.state` is a dedicated event category so a state-level `timeout`\n // cannot collide with an explicit `after` entry on the same state. Invoke\n // timeouts are scheduled on the enclosing state; completion transitions\n // cancel the timer separately, so it clears even when the parent stays active.\n const sources: Array<{\n event: AnyEventObject;\n resolveEvent?: (args: any) => AnyEventObject;\n eventMatcher?: (\n event: EventObject,\n snapshot: AnyMachineSnapshot\n ) => boolean;\n delay: any;\n transitions: unknown;\n fromDelaysMap: boolean;\n /** Where the transitions are authored, for error messages. */\n name: string;\n }> = [];\n\n if (afterConfig) {\n for (const key of Object.keys(afterConfig)) {\n const delay = Number.isNaN(+key) ? key : +key;\n sources.push({\n event: createAfterEvent(delay, stateNode.id),\n delay,\n transitions: afterConfig[key],\n fromDelaysMap: true,\n name: `after.${key}`\n });\n }\n }\n\n if (timeoutConfig !== undefined && onTimeoutConfig) {\n sources.push({\n event: createTimeoutEvent(stateNode.id),\n delay: timeoutConfig,\n transitions: onTimeoutConfig,\n fromDelaysMap: true,\n name: 'onTimeout'\n });\n }\n\n for (const invokeDef of invokeDefs) {\n sources.push({\n event: createInvokeTimeoutEvent(invokeDef.id),\n resolveEvent: ({ children }: any) =>\n createInvokeTimeoutEvent(\n invokeDef.id,\n children[invokeDef.id]?.sessionId\n ),\n eventMatcher: (event, snapshot) =>\n matchesActorSession(event, snapshot, invokeDef.id),\n delay: invokeDef.timeout!,\n transitions: invokeDef.onTimeout,\n fromDelaysMap: false,\n name: 'invoke.onTimeout'\n });\n }\n\n // `delay` here is the raw config value, retained only as metadata on the\n // transition definition — the live delay is resolved at runtime in the\n // scheduled entry action, so no eager resolution is needed.\n const delayedTransitions: Array<\n AnyTransitionConfig & {\n event: string;\n delay: any;\n _eventMatcher?: (\n event: EventObject,\n snapshot: AnyMachineSnapshot\n ) => boolean;\n }\n > = [];\n\n for (const {\n event,\n resolveEvent,\n eventMatcher,\n delay,\n transitions,\n fromDelaysMap,\n name\n } of sources) {\n scheduleDelayedEvent(stateNode, event, resolveEvent ?? (() => event), (x) =>\n resolveDelay(delay, fromDelaysMap ? x.delays : {}, {\n context: x.context,\n event: x.event,\n stateNode,\n input: x.input\n })\n );\n const { type: eventType, ...eventPattern } = event;\n for (const transition of toTransitionConfigArray(\n transitions as any,\n name,\n stateNode.id\n )) {\n delayedTransitions.push({\n ...transition,\n matches: {\n ...transition.matches,\n ...Object.fromEntries(\n Object.entries(eventPattern).filter(\n ([, value]) => value !== undefined\n )\n )\n },\n event: eventType,\n delay,\n _eventMatcher: eventMatcher\n });\n }\n }\n\n return delayedTransitions.map((delayedTransition) => ({\n ...formatTransition(\n stateNode,\n delayedTransition.event,\n delayedTransition as AnyTransitionConfig\n ),\n delay: delayedTransition.delay\n }));\n}\n\nexport function formatTransition(\n stateNode: AnyStateNode,\n descriptor: string,\n transitionConfig: AnyTransitionConfig\n): AnyTransitionDefinition {\n const removedKey = getRemovedTransitionKey(transitionConfig);\n if (removedKey) {\n throw new Error(\n isDevelopment\n ? `Transition \"${descriptor || 'always'}\" in state \"${stateNode.id}\" uses ${removedKey}, which was removed in v6. Use a transition function.`\n : xstateError(10, descriptor || 'always', stateNode.id, removedKey)\n );\n }\n const normalizedTarget = normalizeTarget(transitionConfig.target);\n const reenter = transitionConfig.reenter ?? false;\n const target = resolveTarget(stateNode, normalizedTarget);\n assertLegalTargetSet(stateNode, target);\n\n const transition = {\n ...transitionConfig,\n target,\n source: stateNode,\n reenter,\n eventType: descriptor,\n toJSON: () => transitionDefinitionToJSON(transition)\n };\n\n return transition;\n}\n\nfunction transitionDefinitionToJSON(\n transition: AnyTransitionDefinition\n): Record<string, unknown> {\n const { definition: _, ...serializableTransition } = transition;\n return {\n ...serializableTransition,\n source: `#${transition.source.id}`,\n target: transition.target?.map((target) => `#${target.id}`)\n };\n}\n\n/**\n * Returns the v5 key of a transition object that v6 would misread, in every\n * build: `cond` is never read, so the transition would always be taken,\n * transition `actions` would not run as written, and only a function `guard`\n * can be called. Development builds explain each key earlier, in\n * `diagnoseAuthorConfig`. Compiled configs (JSON, SCXML) never set them.\n */\nfunction getRemovedTransitionKey(\n transitionConfig: AnyTransitionConfig\n): string | undefined {\n const { cond, actions, guard } = transitionConfig as {\n cond?: unknown;\n actions?: unknown;\n guard?: unknown;\n };\n if (cond !== undefined) {\n return '\"cond\"';\n }\n if (actions !== undefined) {\n return '\"actions\"';\n }\n if (guard !== undefined && typeof guard !== 'function') {\n return 'an object-form \"guard\"';\n }\n return undefined;\n}\n\nfunction isStateNodeDescendantOf(\n stateNode: AnyStateNode,\n ancestor: AnyStateNode\n): boolean {\n for (let current = stateNode.parent; current; current = current.parent) {\n if (current === ancestor) {\n return true;\n }\n }\n return false;\n}\n\nfunction getLeastCommonStateNodeAncestor(\n left: AnyStateNode,\n right: AnyStateNode\n): AnyStateNode | undefined {\n const leftAncestors = new Set<AnyStateNode>();\n for (\n let current: AnyStateNode | undefined = left;\n current;\n current = current.parent\n ) {\n leftAncestors.add(current);\n }\n for (\n let current: AnyStateNode | undefined = right;\n current;\n current = current.parent\n ) {\n if (leftAncestors.has(current)) {\n return current;\n }\n }\n return undefined;\n}\n\nfunction assertLegalTargetSet(\n source: AnyStateNode,\n targets: readonly AnyStateNode[] | undefined\n): void {\n if (!targets || targets.length < 2) {\n return;\n }\n for (let leftIndex = 0; leftIndex < targets.length; leftIndex++) {\n for (\n let rightIndex = leftIndex + 1;\n rightIndex < targets.length;\n rightIndex++\n ) {\n const left = targets[leftIndex];\n const right = targets[rightIndex];\n const commonAncestor = getLeastCommonStateNodeAncestor(left, right);\n if (\n left === right ||\n isStateNodeDescendantOf(left, right) ||\n isStateNodeDescendantOf(right, left) ||\n commonAncestor?.type !== 'parallel'\n ) {\n throw new Error(\n isDevelopment\n ? `Invalid transition definition for state node '${source.id}': target set is not a legal SCXML configuration.`\n : xstateError(11, source.id)\n );\n }\n }\n }\n}\n\n/**\n * Collects route transitions from all descendants with explicit IDs. Called\n * once on the root node to avoid O(N²) repeated traversals.\n */\nexport function formatRouteTransitions(rootStateNode: AnyStateNode): void {\n const routeTransitions: AnyTransitionDefinition[] = [];\n const collectRoutes = (states: Record<string, AnyStateNode>) => {\n Object.values(states).forEach((sn) => {\n if (sn.config.route && sn.config.id) {\n const routeId = sn.config.id;\n const routeConfig = sn.config.route;\n const routeMatches = ({ event }: { event: any }) =>\n event.to === `#${routeId}`;\n\n if (typeof routeConfig === 'function') {\n // Transition-style route: the function is the guard and resolver.\n // Returning undefined/false blocks the route; returning true or a\n // config object allows it.\n routeTransitions.push(\n formatTransition(rootStateNode, 'xstate.route', {\n guard: routeMatches,\n to: (args: any) => {\n const result = routeConfig(args);\n if (!result) {\n return undefined;\n }\n return {\n ...(result === true ? {} : result),\n target: `#${routeId}`\n };\n }\n } as AnyTransitionConfig)\n );\n if (sn.states) {\n collectRoutes(sn.states);\n }\n return;\n }\n\n const { guard: _guard, ...routeOptions } = routeConfig as any;\n const transition: AnyTransitionConfig = {\n ...routeOptions,\n guard: routeMatches,\n target: `#${routeId}`\n };\n\n routeTransitions.push(\n formatTransition(rootStateNode, 'xstate.route', transition)\n );\n }\n if (sn.states) {\n collectRoutes(sn.states);\n }\n });\n };\n collectRoutes(rootStateNode.states);\n if (routeTransitions.length > 0) {\n rootStateNode.transitions.set('xstate.route', routeTransitions as any);\n }\n}\n\nfunction resolveTarget(\n stateNode: AnyStateNode,\n targets: ReadonlyArray<string | AnyStateNode> | undefined\n): ReadonlyArray<AnyStateNode> | undefined {\n if (targets === undefined) {\n // an undefined target signals that the state node should not transition from that state when receiving that event\n return undefined;\n }\n return targets.map((target) => {\n if (typeof target !== 'string') {\n return target;\n }\n if (isStateId(target)) {\n return stateNode.machine.getStateNodeById(target);\n }\n\n const isInternalTarget = target[0] === STATE_DELIMITER;\n // If internal target is defined on machine,\n // do not include machine key on target\n if (isInternalTarget && !stateNode.parent) {\n return getStateNodeByPath(stateNode, target.slice(1));\n }\n const resolvedTarget = isInternalTarget ? stateNode.key + target : target;\n if (stateNode.parent) {\n try {\n const targetStateNode = getStateNodeByPath(\n stateNode.parent,\n resolvedTarget\n );\n return targetStateNode;\n } catch (err: any) {\n throw new Error(\n isDevelopment\n ? `Invalid transition definition for state node '${stateNode.id}':\\n${err.message}`\n : xstateError(12, stateNode.id, err.message)\n );\n }\n } else {\n throw new Error(\n isDevelopment\n ? `Invalid target: \"${target}\" is not a valid target from the root node. Did you mean \".${target}\"?`\n : xstateError(13, target)\n );\n }\n });\n}\n\nfunction resolveHistoryDefaultTransition(\n stateNode: AnyStateNode & { type: 'history' }\n): AnyTransitionDefinition {\n const normalizedTarget = normalizeTarget(stateNode.config.target);\n if (!normalizedTarget) {\n if (stateNode.parent!.type === 'parallel') {\n return {\n target: [stateNode.parent!],\n source: stateNode,\n reenter: false,\n eventType: '' as any\n };\n }\n return stateNode.parent!.initial as AnyTransitionDefinition;\n }\n const target = normalizedTarget.map((t) =>\n typeof t === 'string' ? getStateNodeByPath(stateNode.parent!, t) : t\n );\n assertLegalTargetSet(stateNode, target);\n return {\n target,\n source: stateNode,\n reenter: false,\n eventType: '' as any,\n to: (stateNode.config as any)._historyDefaultTransition\n };\n}\n\nfunction isHistoryNode(\n stateNode: AnyStateNode\n): stateNode is AnyStateNode & { type: 'history' } {\n return stateNode.type === 'history';\n}\n\nfunction getInitialStateNodes(stateNode: AnyStateNode) {\n const set = new Set<AnyStateNode>();\n\n function iter(descStateNode: AnyStateNode): void {\n if (set.has(descStateNode)) {\n return;\n }\n set.add(descStateNode);\n if (descStateNode.type === 'compound') {\n for (const target of descStateNode.initial.target ?? []) {\n iter(target);\n }\n } else if (descStateNode.type === 'parallel') {\n for (const child of getChildren(descStateNode)) {\n iter(child);\n }\n }\n }\n\n iter(stateNode);\n for (const initialState of set) {\n for (const ancestor of getProperAncestors(initialState, stateNode)) {\n set.add(ancestor);\n }\n }\n\n return set;\n}\n\n/** Returns the child state node from its relative `stateKey`, or throws. */\nfunction getStateNode(stateNode: AnyStateNode, stateKey: string): AnyStateNode {\n const result = stateNode.states?.[stateKey];\n if (!result) {\n throw new Error(\n isDevelopment\n ? stateNode.states\n ? `Child state '${stateKey}' does not exist on '${stateNode.id}'`\n : `Unable to retrieve child state '${stateKey}' from '${stateNode.id}'; no child states exist.`\n : xstateError(14, stateKey, stateNode.id)\n );\n }\n return result;\n}\n\n/**\n * Returns the relative state node from the given `statePath`, or throws.\n *\n * @param statePath The string or string array relative path to the state node.\n */\nfunction getStateNodeByPath(\n stateNode: AnyStateNode,\n statePath: string | string[]\n): AnyStateNode {\n // `#id` is an exact id lookup, never an id followed by a path.\n if (typeof statePath === 'string' && isStateId(statePath)) {\n return stateNode.machine.getStateNodeById(statePath);\n }\n const arrayStatePath = toStatePath(statePath).slice();\n let currentStateNode: AnyStateNode = stateNode;\n while (arrayStatePath.length) {\n const key = arrayStatePath.shift()!;\n if (!key.length) {\n break;\n }\n currentStateNode = getStateNode(currentStateNode, key);\n }\n return currentStateNode;\n}\n\n/**\n * Returns the state nodes represented by the current state value.\n *\n * @param stateValue The state value or State instance\n * @public\n */\nexport function getStateNodes(\n stateNode: AnyStateNode,\n stateValue: StateValue\n): Array<AnyStateNode> {\n if (typeof stateValue === 'string') {\n const childStateNode = stateNode.states[stateValue];\n if (!childStateNode) {\n throw new Error(\n isDevelopment\n ? `State '${stateValue}' does not exist on '${stateNode.id}'`\n : xstateError(14, stateValue, stateNode.id)\n );\n }\n return [stateNode, childStateNode];\n }\n\n const childStateKeys = Object.keys(stateValue);\n const childStateNodes = new Array<AnyStateNode>(childStateKeys.length);\n const allStateNodes: Array<AnyStateNode> = [\n stateNode.machine.root,\n stateNode\n ];\n\n for (let i = 0; i < childStateKeys.length; i++) {\n const subStateNode = getStateNode(stateNode, childStateKeys[i]);\n childStateNodes[i] = subStateNode;\n allStateNodes.push(subStateNode);\n }\n\n for (let i = 0; i < childStateKeys.length; i++) {\n allStateNodes.push(\n ...getStateNodes(childStateNodes[i], stateValue[childStateKeys[i]]!)\n );\n }\n\n return allStateNodes;\n}\n\nexport type TransitionSelectionResult =\n | {\n enabled: boolean;\n result: unknown;\n reusable: true;\n operations: ReturnType<typeof createTransitionSelection>['operations'];\n }\n | { enabled: true; result: undefined; reusable: false };\n\nexport type TransitionSelectionResults = Map<\n AnyTransitionDefinition,\n TransitionSelectionResult\n>;\n\nexport function transitionNode<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n stateNode: AnyStateNode,\n stateValue: StateValue,\n snapshot: MachineSnapshot<\n TContext,\n TEvent,\n any,\n any,\n any,\n any,\n any,\n any // TStateSchema\n >,\n event: TEvent,\n actorScope: AnyActorScope,\n selectionResults?: TransitionSelectionResults\n): Array<TransitionDefinition<TContext, TEvent>> | undefined {\n // leaf node\n if (typeof stateValue === 'string') {\n const childStateNode = getStateNode(stateNode, stateValue);\n const next = childStateNode.next(\n snapshot,\n event,\n actorScope,\n selectionResults\n );\n\n if (!next || !next.length) {\n return stateNode.next(snapshot, event, actorScope, selectionResults);\n }\n\n return next;\n }\n\n const subStateKeys = Object.keys(stateValue);\n const subStateKey = subStateKeys[0];\n\n if (subStateKeys.length === 1) {\n const childStateNode = getStateNode(stateNode, subStateKey);\n const next = transitionNode(\n childStateNode,\n stateValue[subStateKey]!,\n snapshot,\n event,\n actorScope,\n selectionResults\n );\n\n if (!next || !next.length) {\n return stateNode.next(snapshot, event, actorScope, selectionResults);\n }\n\n return next;\n }\n\n const allInnerTransitions: Array<TransitionDefinition<TContext, TEvent>> = [];\n\n for (const subStateKey of subStateKeys) {\n const subStateValue = stateValue[subStateKey];\n\n if (!subStateValue) {\n continue;\n }\n\n const subStateNode = getStateNode(stateNode, subStateKey);\n const innerTransitions = transitionNode(\n subStateNode,\n subStateValue,\n snapshot,\n event,\n actorScope,\n selectionResults\n );\n if (innerTransitions) {\n allInnerTransitions.push(...innerTransitions);\n }\n }\n\n if (!allInnerTransitions.length) {\n return stateNode.next(snapshot, event, actorScope, selectionResults);\n }\n\n return allInnerTransitions;\n}\n\nfunction isDescendant(\n childStateNode: AnyStateNode,\n parentStateNode: AnyStateNode\n): boolean {\n let marker = childStateNode;\n while (marker.parent && marker.parent !== parentStateNode) {\n marker = marker.parent;\n }\n\n return marker.parent === parentStateNode;\n}\n\nfunction hasDescendantState(\n stateNodes: Set<AnyStateNode>,\n parentStateNode: AnyStateNode\n): boolean {\n for (const stateNode of stateNodes) {\n if (isDescendant(stateNode, parentStateNode)) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction hasIntersection<T>(s1: Iterable<T>, s2: Iterable<T>): boolean {\n const s1Size =\n s1 instanceof Set ? s1.size : Array.isArray(s1) ? s1.length : undefined;\n const s2Size =\n s2 instanceof Set ? s2.size : Array.isArray(s2) ? s2.length : undefined;\n\n if (s1Size !== undefined && s2Size !== undefined && s2Size < s1Size) {\n [s1, s2] = [s2, s1];\n }\n\n const set1 = s1 instanceof Set ? s1 : new Set(s1);\n for (const item of s2) {\n if (set1.has(item)) {\n return true;\n }\n }\n return false;\n}\n\nfunction removeConflictingTransitions(\n enabledTransitions: Array<AnyTransitionDefinition>,\n stateNodeSet: Set<AnyStateNode>,\n snapshot: AnyMachineSnapshot,\n resolveTransition: TransitionResultResolver\n): Array<AnyTransitionDefinition> {\n const filteredTransitions = new Set<AnyTransitionDefinition>();\n const exitSets = new Map<AnyTransitionDefinition, Array<AnyStateNode>>();\n\n const getExitSet = (transition: AnyTransitionDefinition) => {\n let exitSet = exitSets.get(transition);\n if (!exitSet) {\n exitSet = computeExitSet(\n [transition],\n stateNodeSet,\n snapshot,\n resolveTransition\n );\n exitSets.set(transition, exitSet);\n }\n\n return exitSet;\n };\n\n for (const t1 of enabledTransitions) {\n let t1Preempted = false;\n const transitionsToRemove = new Set<AnyTransitionDefinition>();\n for (const t2 of filteredTransitions) {\n if (hasIntersection(getExitSet(t1), getExitSet(t2))) {\n if (isDescendant(t1.source, t2.source)) {\n transitionsToRemove.add(t2);\n } else {\n t1Preempted = true;\n break;\n }\n }\n }\n if (!t1Preempted) {\n for (const t3 of transitionsToRemove) {\n filteredTransitions.delete(t3);\n }\n filteredTransitions.add(t1);\n }\n }\n\n return Array.from(filteredTransitions);\n}\n\ntype ResolvableTransition = Parameters<typeof getTransitionResult>[0];\ntype TransitionResultResolver = (\n transition: ResolvableTransition,\n // Whether the caller applies the result's `context` and `input`, rather\n // than only reading its targets\n applied?: boolean\n) => ReturnType<typeof getTransitionResult>;\n\nfunction createTransitionResultResolver(\n snapshot: AnyMachineSnapshot,\n event: AnyEventObject,\n actorScope: AnyActorScope,\n resolveActions: boolean,\n selectionResults?: TransitionSelectionResults\n): TransitionResultResolver {\n let cache:\n | Map<ResolvableTransition, ReturnType<typeof getTransitionResult>>\n | undefined;\n return (transition, applied) => {\n if (!transition.to && !applied) {\n // An object transition's targets are static, so reading them must not\n // run its `context` and `input` mappers\n return {\n targets: transition.target as AnyStateNode[] | undefined,\n context: undefined,\n reenter: transition.reenter,\n actions: undefined,\n internalEvents: undefined,\n input: undefined\n };\n }\n let result = cache?.get(transition);\n if (!result) {\n result = getTransitionResult(transition, snapshot, event, actorScope, {\n resolveActions,\n selectionResult: selectionResults?.get(\n transition as AnyTransitionDefinition\n )\n });\n (cache ??= new Map()).set(transition, result);\n }\n return result;\n };\n}\n\nfunction getEffectiveTargetStates(\n transition: Pick<AnyTransitionDefinition, 'target' | 'source'>,\n snapshot: AnyMachineSnapshot,\n resolveTransition: TransitionResultResolver\n): Array<AnyStateNode> {\n const historyValue = snapshot.historyValue;\n const { targets } = resolveTransition(transition);\n if (!targets) {\n return [];\n }\n\n const targetSet = new Set<AnyStateNode>();\n\n for (const targetNode of targets) {\n if (isHistoryNode(targetNode)) {\n if (historyValue[targetNode.id]) {\n for (const node of historyValue[targetNode.id]) {\n targetSet.add(node);\n }\n } else {\n for (const node of getEffectiveTargetStates(\n resolveHistoryDefaultTransition(targetNode),\n snapshot,\n resolveTransition\n )) {\n targetSet.add(node);\n }\n }\n } else {\n targetSet.add(targetNode);\n }\n }\n\n return [...targetSet];\n}\n\n/**\n * Narrows a parallel domain to the single child region that contains every\n * effective target, so that a transition confined to one region does not exit\n * (and reset) its sibling regions.\n */\nfunction narrowParallelDomain(\n domain: AnyStateNode,\n targetStates: Array<AnyStateNode>\n): AnyStateNode {\n let narrowed = domain;\n while (narrowed.type === 'parallel') {\n const region = getChildren(narrowed).find((child) =>\n targetStates.every(\n (target) => target === child || isDescendant(target, child)\n )\n );\n if (!region) {\n break;\n }\n narrowed = region;\n }\n return narrowed;\n}\n\nfunction getTransitionDomain(\n transition: AnyTransitionDefinition,\n snapshot: AnyMachineSnapshot,\n resolveTransition: TransitionResultResolver\n): AnyStateNode | undefined {\n const targetStates = getEffectiveTargetStates(\n transition,\n snapshot,\n resolveTransition\n );\n\n const { targets, reenter } = resolveTransition(transition);\n\n if (transition._transitionDomain) {\n if (\n transition._transitionDomain === 'internal' &&\n transition.source.type === 'compound' &&\n targetStates.every((target) => isDescendant(target, transition.source))\n ) {\n return transition.source;\n }\n\n const [head, ...tail] = targetStates.concat(transition.source);\n for (const ancestor of getProperAncestors(head, undefined)) {\n if (\n ancestor.type === 'compound' &&\n tail.every((stateNode) => isDescendant(stateNode, ancestor))\n ) {\n return ancestor;\n }\n }\n\n return;\n }\n\n // A history target that restores the source itself must exit and reenter\n // the source (SCXML domain = the source's ancestor), unlike a plain\n // non-reentering self-target: the enter set restores the stored\n // configuration from outside the source, so the exit set must match or the\n // source's invoked actors are re-created without being stopped.\n const restoresSourceViaHistory =\n targets?.some(isHistoryNode) &&\n targetStates.some((target) => target === transition.source);\n\n if (\n !restoresSourceViaHistory &&\n targetStates.every(\n (target) =>\n target === transition.source || isDescendant(target, transition.source)\n )\n ) {\n // Targets are contained within the source. A reentering transition\n // exits and reenters the source itself; otherwise the domain narrows\n // past parallel nodes so sibling regions are left untouched.\n return reenter\n ? transition.source\n : narrowParallelDomain(transition.source, targetStates);\n }\n\n const [head, ...tail] = targetStates.concat(transition.source);\n // Find the least common ancestor (LCA) of the source and effective targets.\n for (const ancestor of getProperAncestors(head, undefined)) {\n if (tail.every((sn) => isDescendant(sn, ancestor))) {\n // A cross-region transition (source in one parallel region, targets in\n // another) only exits the region containing its targets; the source\n // region and other sibling regions stay put unless it reenters.\n return reenter ? ancestor : narrowParallelDomain(ancestor, targetStates);\n }\n }\n\n // at this point we know that it's a root transition since LCA couldn't be found\n if (reenter) {\n return;\n }\n\n return narrowParallelDomain(transition.source.machine.root, targetStates);\n}\n\nfunction computeExitSet(\n transitions: Array<AnyTransitionDefinition>,\n stateNodeSet: Set<AnyStateNode>,\n snapshot: AnyMachineSnapshot,\n resolveTransition: TransitionResultResolver\n): Array<AnyStateNode> {\n const statesToExit = new Set<AnyStateNode>();\n for (const transition of transitions) {\n const { targets, reenter } = resolveTransition(transition);\n\n if (targets?.length) {\n const domain = getTransitionDomain(\n transition,\n snapshot,\n resolveTransition\n );\n\n if (reenter && transition.source === domain) {\n statesToExit.add(domain);\n }\n\n for (const stateNode of stateNodeSet) {\n if (isDescendant(stateNode, domain!)) {\n statesToExit.add(stateNode);\n }\n }\n }\n }\n\n return [...statesToExit];\n}\n\ntype Microstep = readonly [\n AnyMachineSnapshot,\n ExecutableEffect[],\n // The transitions taken in this microstep, when recorded by `macrostep()`\n transitions?: AnyTransitionDefinition[]\n];\n\nexport function initialMicrostep(\n root: AnyStateNode,\n preInitialState: AnyMachineSnapshot,\n actorScope: AnyActorScope,\n initEvent: AnyEventObject,\n internalQueue: AnyEventObject[]\n): Microstep {\n root.machine._microstepHooks?.begin(actorScope.self);\n const initialStateNodes = [...getInitialStateNodes(root)];\n const statesForDefaultEntry = new Set<AnyStateNode>();\n const collectDefaultEntryStates = (stateNode: AnyStateNode): void => {\n if (stateNode.type === 'compound') {\n statesForDefaultEntry.add(stateNode);\n for (const target of stateNode.initial.target ?? []) {\n collectDefaultEntryStates(target);\n }\n } else if (stateNode.type === 'parallel') {\n for (const child of getChildren(stateNode)) {\n collectDefaultEntryStates(child);\n }\n }\n };\n collectDefaultEntryStates(root);\n return microstep(\n [\n {\n target: initialStateNodes.filter(\n (stateNode) =>\n !initialStateNodes.some(\n (other) => other !== stateNode && isDescendant(other, stateNode)\n )\n ),\n source: root,\n reenter: true,\n eventType: null as any,\n toJSON: null as any,\n _statesForDefaultEntry: [...statesForDefaultEntry]\n } as AnyTransitionDefinition\n ],\n preInitialState,\n actorScope,\n initEvent,\n true,\n internalQueue\n );\n}\n\n/** https://www.w3.org/TR/scxml/#microstepProcedure */\nfunction microstep(\n transitions: Array<AnyTransitionDefinition>,\n currentSnapshot: AnyMachineSnapshot,\n actorScope: AnyActorScope,\n event: AnyEventObject,\n isInitial: boolean,\n internalQueue: Array<AnyEventObject>,\n selectionResults?: TransitionSelectionResults\n): Microstep {\n const executableActions: ExecutableEffect[] = [];\n const internalEvents = currentSnapshot.machine._microstepHooks?.drain(\n actorScope.self\n );\n if (internalEvents?.length) {\n internalQueue.push(...internalEvents);\n }\n\n if (!transitions.length) {\n return [currentSnapshot, executableActions];\n }\n\n {\n const mutStateNodeSet = new Set(currentSnapshot.nodes as StateNode[]);\n let historyValue = currentSnapshot.historyValue;\n const originalContext = currentSnapshot.context;\n\n const filteredTransitions =\n transitions.length === 1\n ? transitions\n : removeConflictingTransitions(\n transitions,\n mutStateNodeSet,\n currentSnapshot,\n createTransitionResultResolver(\n currentSnapshot,\n event,\n actorScope,\n false,\n selectionResults\n )\n );\n const getCurrentTransitionResult = createTransitionResultResolver(\n currentSnapshot,\n event,\n actorScope,\n true,\n selectionResults\n );\n const changesState = filteredTransitions.some((transition) => {\n const { targets, reenter } = getCurrentTransitionResult(transition);\n return !!targets?.length || !!reenter;\n });\n const getStateActionsAndContext = (\n transitionFn: any,\n context: MachineContext,\n children: AnyMachineSnapshot['children'],\n input: Record<string, unknown> | undefined,\n kind: 'entry' | 'exit' | 'transition',\n stateNode: AnyStateNode\n ): [\n actions: any[],\n context: MachineContext | undefined,\n internalEvents: EventObject[] | undefined,\n children: AnyMachineSnapshot['children'] | undefined\n ] => {\n const actions: any[] = [];\n const internalEvents: EventObject[] = [];\n let updatedContext: MachineContext | undefined;\n\n const enqueue = createTransitionEnqueue(\n actorScope,\n actions,\n internalEvents,\n true\n );\n\n const args = isLazyActorScope(actorScope)\n ? withActorScope(\n {\n context,\n event,\n output: getEventOutput(event),\n children,\n actions: currentSnapshot.machine.sources.actions,\n actors: currentSnapshot.machine.sources.actors,\n guards: currentSnapshot.machine.sources.guards,\n delays: currentSnapshot.machine.sources.delays,\n input,\n stateNode\n },\n actorScope\n )\n : {\n context,\n event,\n output: getEventOutput(event),\n parent: actorScope.self._parent,\n self: actorScope.self,\n children,\n system: actorScope.system,\n actions: currentSnapshot.machine.sources.actions,\n actors: currentSnapshot.machine.sources.actors,\n guards: currentSnapshot.machine.sources.guards,\n delays: currentSnapshot.machine.sources.delays,\n input,\n stateNode\n };\n let res;\n try {\n res = transitionFn(args, enqueue);\n } finally {\n closeTransitionEnqueue(enqueue);\n }\n assertSyncTransitionResult(res, event, stateNode.id, kind);\n\n if (res?.context !== undefined) {\n updatedContext = mergeContextPatch(context, res.context);\n }\n\n return [actions, updatedContext, internalEvents, res?.children];\n };\n\n let nextState = currentSnapshot;\n const getInvokeStopActions = (\n stateNode: AnyStateNode,\n children: AnyMachineSnapshot['children']\n ): AnyAction[] => {\n const actions: AnyAction[] = [];\n const enqueue = createTransitionEnqueue(actorScope, actions, []);\n for (const invokeDef of stateNode.invoke) {\n const child = children[invokeDef.id];\n if (child) {\n enqueue.stop(child);\n }\n }\n return actions;\n };\n const exitStates = () => {\n const statesToExit = computeExitSet(\n filteredTransitions,\n mutStateNodeSet,\n currentSnapshot,\n getCurrentTransitionResult\n );\n\n statesToExit.sort((a, b) => b.order - a.order);\n\n let changedHistory: HistoryValue | undefined;\n const currentStateNodes = [...mutStateNodeSet];\n\n // From SCXML algorithm: https://www.w3.org/TR/scxml/#exitStates\n for (const exitStateNode of statesToExit) {\n for (const historyNode of Object.values(exitStateNode.states)) {\n if (historyNode.type !== 'history') {\n continue;\n }\n\n const predicate =\n historyNode.history === 'deep'\n ? (sn: AnyStateNode) =>\n isAtomicStateNode(sn) && isDescendant(sn, exitStateNode)\n : (sn: AnyStateNode) => sn.parent === exitStateNode;\n\n changedHistory ??= { ...historyValue };\n changedHistory[historyNode.id] = currentStateNodes.filter(predicate);\n }\n }\n\n for (const exitStateNode of statesToExit) {\n const stateInput = getStateInput(currentSnapshot, exitStateNode.id);\n\n const [exitActions, nextContext, internalEvents, nextChildren] =\n exitStateNode.exit\n ? getStateActionsAndContext(\n exitStateNode.exit,\n nextState.context,\n nextState.children,\n stateInput,\n 'exit',\n exitStateNode\n )\n : [[], undefined, undefined, undefined];\n if (internalEvents?.length) {\n internalQueue.push(...internalEvents);\n }\n if (nextContext || nextChildren) {\n nextState = cloneMachineSnapshot(nextState, {\n ...(nextContext ? { context: nextContext } : {}),\n ...(nextChildren ? { children: nextChildren } : {})\n });\n }\n const [resolvedState, resolvedActions] = resolveActionsWithContext(\n nextState,\n event,\n actorScope,\n exitActions\n );\n nextState = resolvedState;\n executableActions.push(...resolvedActions);\n\n const invokeStopActions = getInvokeStopActions(\n exitStateNode,\n nextState.children\n );\n if (invokeStopActions.length) {\n const [stoppedState, stopEffects] = resolveActionsWithContext(\n nextState,\n event,\n actorScope,\n invokeStopActions\n );\n nextState = stoppedState;\n executableActions.push(...stopEffects);\n }\n\n mutStateNodeSet.delete(exitStateNode);\n }\n\n historyValue = changedHistory || historyValue;\n };\n\n // Exit states\n if (!isInitial && changesState) {\n exitStates();\n }\n\n let context = nextState.context;\n const transitionActions: AnyAction[] = [];\n const internalEvents: EventObject[] = [];\n\n const resolvedTransitions: AnyTransitionDefinition[] = [];\n for (const t of filteredTransitions) {\n const res = getCurrentTransitionResult(t, true);\n if (t.to) {\n const resolvedTransition = {\n ...t,\n target: res.targets,\n definition: t\n } as AnyTransitionDefinition & {\n toJSON: () => Record<string, unknown>;\n };\n resolvedTransition.toJSON = () =>\n transitionDefinitionToJSON(resolvedTransition);\n resolvedTransitions.push(resolvedTransition);\n } else {\n resolvedTransitions.push(t);\n }\n if (res.context !== undefined) {\n context = mergeContextPatch(context, res.context);\n }\n if (res.actions) {\n transitionActions.push(...res.actions);\n }\n if (res.internalEvents) {\n internalEvents.push(...res.internalEvents);\n }\n }\n\n if (internalEvents.length) {\n internalQueue.push(...internalEvents);\n }\n\n const enterStates = () => {\n const getMachineOutput = (rootCompletionNode: AnyStateNode) => {\n const rootNode = nextState.machine.root;\n\n let completionOutput: unknown;\n if (\n rootCompletionNode.output !== undefined &&\n rootCompletionNode.parent\n ) {\n const rootDoneEvent = internalQueue.find(\n (e) =>\n e.type === 'xstate.done.state' &&\n (e as DoneStateEvent).stateId === rootNode.id\n ) as DoneStateEvent | undefined;\n completionOutput =\n rootDoneEvent && rootCompletionNode.parent === rootNode\n ? rootDoneEvent.output\n : resolveOutput(\n rootCompletionNode.output,\n nextState.context,\n event,\n actorScope.self,\n stateInputMap[rootCompletionNode.id]\n );\n } else if (rootCompletionNode.type === 'parallel') {\n const parallelDoneEvent = internalQueue.find(\n (e) =>\n e.type === 'xstate.done.state' &&\n (e as DoneStateEvent).stateId === rootCompletionNode.id\n ) as DoneStateEvent | undefined;\n completionOutput = parallelDoneEvent?.output;\n }\n\n if (rootNode.output === undefined) {\n return rootCompletionNode.parent === rootNode\n ? completionOutput\n : undefined;\n }\n\n return resolveOutput(\n rootNode.output,\n nextState.context,\n createDoneStateEvent(rootCompletionNode.id, completionOutput),\n actorScope.self\n );\n };\n\n const statesToEnter = new Set<AnyStateNode>();\n // those are states that were directly targeted or indirectly targeted by the explicit target\n // in other words, those are states for which initial actions should be executed\n // when we target `#deep_child` initial actions of its ancestors shouldn't be executed\n const statesForDefaultEntry = new Set<AnyStateNode>();\n const historyDefaultsByParent = new Map<\n AnyStateNode,\n AnyTransitionDefinition[]\n >();\n const addAncestorStatesToEnter = (\n ancestors: AnyStateNode[],\n reentrancyDomain: AnyStateNode | undefined\n ) => {\n for (const anc of ancestors) {\n if (!reentrancyDomain || isDescendant(anc, reentrancyDomain)) {\n statesToEnter.add(anc);\n }\n if (anc.type === 'parallel') {\n for (const child of getChildren(anc)) {\n if (!hasDescendantState(statesToEnter, child)) {\n statesToEnter.add(child);\n addDescendantStatesToEnter(child);\n }\n }\n }\n }\n };\n\n const addDescendantStatesToEnter = (stateNode: AnyStateNode) => {\n if (isHistoryNode(stateNode)) {\n if (historyValue[stateNode.id]) {\n const historyStateNodes = historyValue[stateNode.id];\n for (const s of historyStateNodes) {\n statesToEnter.add(s);\n addDescendantStatesToEnter(s);\n }\n for (const s of historyStateNodes) {\n addAncestorStatesToEnter(\n getProperAncestors(s, stateNode.parent),\n undefined\n );\n }\n } else {\n const historyDefaultTransition =\n resolveHistoryDefaultTransition(stateNode);\n const historyParent = stateNode.parent!;\n statesForDefaultEntry.add(historyParent);\n const defaults = historyDefaultsByParent.get(historyParent) ?? [];\n defaults.push(historyDefaultTransition);\n historyDefaultsByParent.set(historyParent, defaults);\n const { targets } = getCurrentTransitionResult(\n historyDefaultTransition\n );\n for (const s of targets ?? []) {\n statesToEnter.add(s);\n\n if (historyDefaultTransition === stateNode.parent?.initial) {\n statesForDefaultEntry.add(stateNode.parent);\n }\n\n addDescendantStatesToEnter(s);\n }\n\n for (const s of targets ?? []) {\n addAncestorStatesToEnter(\n getProperAncestors(s, stateNode.parent),\n undefined\n );\n }\n }\n return;\n }\n\n if (stateNode.type === 'compound') {\n const initialStates =\n getCurrentTransitionResult(stateNode.initial).targets ?? [];\n\n for (const initialState of initialStates) {\n if (!isHistoryNode(initialState)) {\n statesToEnter.add(initialState);\n }\n }\n statesForDefaultEntry.add(stateNode);\n for (const initialState of initialStates) {\n addDescendantStatesToEnter(initialState);\n }\n for (const initialState of initialStates) {\n addAncestorStatesToEnter(\n getProperAncestors(initialState, stateNode),\n undefined\n );\n }\n return;\n }\n\n if (stateNode.type === 'parallel') {\n for (const child of getChildren(stateNode)) {\n if (!hasDescendantState(statesToEnter, child)) {\n statesToEnter.add(child);\n statesForDefaultEntry.add(child);\n addDescendantStatesToEnter(child);\n }\n }\n }\n };\n\n const enteredTargetsByTransition = new Map<\n AnyTransitionDefinition,\n Set<AnyStateNode>\n >();\n for (const transition of filteredTransitions) {\n const domain = getTransitionDomain(\n transition,\n currentSnapshot,\n getCurrentTransitionResult\n );\n\n const { targets, reenter } = getCurrentTransitionResult(transition);\n const enteredTargets = new Set<AnyStateNode>();\n enteredTargetsByTransition.set(transition, enteredTargets);\n\n for (const targetNode of targets ?? []) {\n if (\n !isHistoryNode(targetNode) &&\n (transition.source !== targetNode ||\n transition.source !== domain ||\n reenter)\n ) {\n enteredTargets.add(targetNode);\n statesToEnter.add(targetNode);\n statesForDefaultEntry.add(targetNode);\n }\n addDescendantStatesToEnter(targetNode);\n }\n const targetStates = getEffectiveTargetStates(\n transition,\n currentSnapshot,\n getCurrentTransitionResult\n );\n for (const s of targetStates) {\n const ancestors = getProperAncestors(s, domain);\n if (domain?.type === 'parallel') {\n ancestors.push(domain);\n }\n addAncestorStatesToEnter(\n ancestors,\n !transition.source.parent && reenter ? undefined : domain\n );\n }\n if (reenter && domain === transition.source) {\n // A reentering transition whose domain is its own source exits and\n // reenters the source, so the source must be entered explicitly —\n // it has no ancestor inside the domain to add it.\n statesToEnter.add(transition.source);\n }\n }\n\n if (isInitial) {\n for (const stateNode of (filteredTransitions[0] as any)\n ._statesForDefaultEntry ?? [currentSnapshot.machine.root]) {\n statesForDefaultEntry.add(stateNode);\n }\n }\n\n // Keep only the inputs of states still active after exiting, so exited\n // (and re-entered) states never see a stale input.\n const stateInputMap: Record<string, Record<string, unknown>> = {};\n let stateInputsChanged = false;\n const activeIds = new Set([...mutStateNodeSet].map((sn) => sn.id));\n for (const [id, input] of Object.entries(\n currentSnapshot._stateInputs ?? {}\n )) {\n if (activeIds.has(id)) {\n stateInputMap[id] = input;\n } else {\n stateInputsChanged = true;\n }\n }\n for (const transition of filteredTransitions) {\n const { targets, input } = getCurrentTransitionResult(transition, true);\n if (input && targets) {\n for (const targetNode of targets.filter((targetNode) =>\n enteredTargetsByTransition.get(transition)?.has(targetNode)\n )) {\n stateInputMap[targetNode.id] = input;\n stateInputsChanged = true;\n }\n }\n }\n\n const completedNodes = new Set<AnyStateNode>();\n for (const stateNodeToEnter of [...statesToEnter].sort(\n (a, b) => a.order - b.order\n )) {\n mutStateNodeSet.add(stateNodeToEnter);\n const actions: AnyAction[] = [];\n // Read the children for each state: the entry actions of the states\n // entered before this one may have spawned or stopped children.\n let children = nextState.children;\n\n // Final states are inert, so (as in SCXML) their invocations never\n // start.\n let invoked = false;\n for (const invokeDef of stateNodeToEnter.type === 'final'\n ? []\n : stateNodeToEnter.invoke) {\n invoked = true;\n\n let src = invokeDef.logic;\n if (typeof src === 'function') {\n src = src({\n actors: currentSnapshot.machine.sources.actors,\n context: nextState.context,\n event,\n self: actorScope.self\n });\n }\n\n const logic =\n typeof src === 'string'\n ? currentSnapshot.machine.sources.actors[src]\n : src;\n\n if (!logic) {\n throw new Error(\n isDevelopment\n ? `Actor logic '${typeof src === 'string' ? src : 'inline'}' not implemented in ${describeMachine(currentSnapshot.machine.id)}`\n : xstateError(15, typeof src === 'string' ? src : 'inline')\n );\n }\n\n const input =\n typeof invokeDef.input === 'function'\n ? invokeDef.input({\n self: actorScope.self,\n context: nextState.context,\n event,\n input: stateInputMap[stateNodeToEnter.id],\n output: getEventOutput(event)\n })\n : invokeDef.input;\n\n assertChildIdFree(actorScope, invokeDef.id);\n const actor = actorScope.system.createActorRef(logic, {\n ...invokeDef,\n // A `src` function may return a registered key, which persists.\n src: typeof src === 'string' ? src : undefined,\n input,\n parent: actorScope.self,\n syncSnapshot: !!invokeDef.onSnapshot\n });\n // Persistence restores a source-less child through its invoke\n // definition only when the invoke created it.\n (actor as { _invoked?: boolean })._invoked = true;\n\n actions.push({\n action: builtInActions['@xstate.spawn'],\n args: [actor]\n });\n\n if (invokeDef.id) {\n children = { ...children, [invokeDef.id]: actor };\n }\n }\n\n if (invoked) {\n nextState = cloneMachineSnapshot(nextState, { children });\n }\n let context = nextState.context;\n let contextChangedByEntry = false;\n\n const stateInput = stateInputMap[stateNodeToEnter.id];\n\n if (stateNodeToEnter.entry) {\n const [resultActions, nextContext, nextInternalEvents, nextChildren] =\n getStateActionsAndContext(\n stateNodeToEnter.entry,\n context,\n children,\n stateInput,\n 'entry',\n stateNodeToEnter\n );\n actions.push(...resultActions);\n if (nextInternalEvents?.length) {\n internalQueue.push(...nextInternalEvents);\n }\n if (nextContext) {\n context = nextContext;\n contextChangedByEntry = true;\n }\n if (nextChildren) {\n nextState = cloneMachineSnapshot(nextState, {\n children: nextChildren\n });\n }\n }\n\n if (contextChangedByEntry) {\n nextState = cloneMachineSnapshot(nextState, { context });\n }\n\n if (statesForDefaultEntry.has(stateNodeToEnter)) {\n const defaultTransitions = [\n stateNodeToEnter.initial,\n ...(historyDefaultsByParent.get(stateNodeToEnter) ?? [])\n ].filter(Boolean);\n for (const defaultTransition of defaultTransitions) {\n const {\n actions: initialActions,\n context: initialContext,\n input: initialInput,\n internalEvents: initialInternalEvents\n } = getTransitionResult(\n defaultTransition,\n nextState,\n event,\n actorScope\n );\n if (initialActions) {\n actions.push(...initialActions);\n }\n if (initialInternalEvents?.length) {\n internalQueue.push(...initialInternalEvents);\n }\n if (initialContext !== undefined) {\n nextState = cloneMachineSnapshot(nextState, {\n context: mergeContextPatch(nextState.context, initialContext)\n });\n }\n if (initialInput && defaultTransition.target) {\n for (const targetNode of defaultTransition.target) {\n stateInputMap[targetNode.id] = initialInput;\n stateInputsChanged = true;\n }\n }\n }\n }\n\n const [resolvedState, resolvedActions] = resolveActionsWithContext(\n nextState,\n event,\n actorScope,\n actions\n );\n nextState = resolvedState;\n actions.length = 0;\n executableActions.push(...resolvedActions);\n\n if (stateNodeToEnter.type !== 'final') {\n continue;\n }\n\n const parent = stateNodeToEnter.parent;\n let ancestorMarker =\n parent?.type === 'parallel' ? parent : parent?.parent;\n let rootCompletionNode = ancestorMarker || stateNodeToEnter;\n\n if (parent?.type === 'compound') {\n internalQueue.push(\n createDoneStateEvent(\n parent.id,\n stateNodeToEnter.output !== undefined\n ? resolveOutput(\n stateNodeToEnter.output,\n nextState.context,\n event,\n actorScope.self,\n stateInput\n )\n : undefined\n )\n );\n }\n\n while (\n ancestorMarker?.type === 'parallel' &&\n !completedNodes.has(ancestorMarker) &&\n isInFinalState(mutStateNodeSet, ancestorMarker)\n ) {\n completedNodes.add(ancestorMarker);\n const regionOutput: Record<string, unknown> = {};\n for (const region of getChildren(ancestorMarker)) {\n if (region.type === 'final') {\n regionOutput[region.key] =\n region.output !== undefined\n ? resolveOutput(\n region.output,\n nextState.context,\n event,\n actorScope.self,\n stateInputMap[region.id]\n )\n : undefined;\n continue;\n }\n\n if (region.type === 'parallel') {\n const regionDoneEvent = internalQueue.find(\n (e) =>\n e.type === 'xstate.done.state' &&\n (e as DoneStateEvent).stateId === region.id\n ) as DoneStateEvent | undefined;\n regionOutput[region.key] = regionDoneEvent?.output;\n continue;\n }\n\n const finalChild = getChildren(region).find(\n (s) => s.type === 'final' && mutStateNodeSet.has(s)\n );\n regionOutput[region.key] =\n finalChild?.output !== undefined\n ? resolveOutput(\n finalChild.output,\n nextState.context,\n event,\n actorScope.self,\n stateInputMap[finalChild.id]\n )\n : undefined;\n }\n internalQueue.push(\n createDoneStateEvent(ancestorMarker.id, regionOutput)\n );\n rootCompletionNode = ancestorMarker;\n ancestorMarker = ancestorMarker.parent;\n }\n if (ancestorMarker) {\n continue;\n }\n\n nextState = cloneMachineSnapshot(nextState, {\n status: 'done',\n output: getMachineOutput(rootCompletionNode)\n });\n }\n\n if (stateInputsChanged) {\n nextState = cloneMachineSnapshot(nextState, {\n _stateInputs: stateInputMap\n });\n }\n };\n\n // Execute transition content\n const [resolvedTransitionState, transitionExecutableEffects] =\n resolveActionsWithContext(\n nextState,\n event,\n actorScope,\n transitionActions\n );\n nextState = resolvedTransitionState;\n executableActions.push(...transitionExecutableEffects);\n if (context && context !== currentSnapshot.context) {\n nextState = cloneMachineSnapshot(nextState, { context });\n }\n\n const transitionContent =\n nextState.machine._microstepHooks?.transitionContent?.(\n filteredTransitions,\n [...mutStateNodeSet]\n );\n if (transitionContent) {\n const source = filteredTransitions[0].source;\n const [actions, nextContext, raisedEvents, nextChildren] =\n getStateActionsAndContext(\n transitionContent,\n nextState.context,\n nextState.children,\n getStateInput(nextState, source.id),\n 'transition',\n source\n );\n if (raisedEvents?.length) {\n internalQueue.push(...raisedEvents);\n }\n if (nextContext || nextChildren) {\n nextState = cloneMachineSnapshot(nextState, {\n ...(nextContext ? { context: nextContext } : {}),\n ...(nextChildren ? { children: nextChildren } : {})\n });\n }\n const [resolvedState, effects] = resolveActionsWithContext(\n nextState,\n event,\n actorScope,\n actions\n );\n nextState = resolvedState;\n executableActions.push(...effects);\n }\n\n // Enter states\n if (isInitial || changesState) {\n enterStates();\n }\n\n const nextStateNodes = [...mutStateNodeSet];\n\n if (nextState.status === 'done') {\n const allExitActions: AnyAction[] = [];\n const nextStateNodesToExit = nextStateNodes.sort(\n (a, b) => b.order - a.order\n );\n\n nextStateNodesToExit.forEach((stateNode) => {\n if (stateNode.exit) {\n const stateInput = getStateInput(nextState, stateNode.id);\n const [exitActions, nextContext, nextInternalEvents, nextChildren] =\n getStateActionsAndContext(\n stateNode.exit,\n nextState.context,\n nextState.children,\n stateInput,\n 'exit',\n stateNode\n );\n if (nextContext || nextChildren) {\n nextState = cloneMachineSnapshot(nextState, {\n ...(nextContext ? { context: nextContext } : {}),\n ...(nextChildren ? { children: nextChildren } : {})\n });\n }\n allExitActions.push(...exitActions);\n if (nextInternalEvents?.length) {\n internalQueue.push(...nextInternalEvents);\n }\n }\n });\n\n const [resolvedState, resolvedActions] = resolveActionsWithContext(\n nextState,\n event,\n actorScope,\n allExitActions\n );\n nextState = resolvedState;\n executableActions.push(...resolvedActions);\n\n const [stoppedState, stopEffects] = stopChildren(\n nextState,\n event,\n actorScope\n );\n nextState = stoppedState;\n executableActions.push(...stopEffects);\n\n const [withoutTimers, cancelEffects] = cancelTimers(\n nextState,\n event,\n actorScope\n );\n nextState = withoutTimers;\n executableActions.push(...cancelEffects);\n }\n\n if (\n historyValue === currentSnapshot.historyValue &&\n currentSnapshot.nodes.length === mutStateNodeSet.size &&\n currentSnapshot.nodes.every((node) =>\n mutStateNodeSet.has(node as StateNode)\n )\n ) {\n // If context was changed (e.g. by entry actions during self-transition),\n // clone to ensure reference inequality for eventless transition re-evaluation\n if (nextState.context !== originalContext) {\n return [\n nextState === currentSnapshot\n ? cloneMachineSnapshot(nextState)\n : nextState,\n executableActions,\n resolvedTransitions\n ];\n }\n return [nextState, executableActions, resolvedTransitions];\n }\n\n return [\n cloneMachineSnapshot(nextState, {\n _nodes: nextStateNodes,\n historyValue\n }),\n executableActions,\n resolvedTransitions\n ];\n }\n}\n\n/**\n * Gets the transition result for a given transition without executing the\n * transition.\n */\nexport function getTransitionResult(\n transition: Pick<AnyTransitionDefinition, 'target' | 'to' | 'source'> & {\n reenter?: AnyTransitionDefinition['reenter'];\n input?: AnyTransitionDefinition['input'];\n context?: AnyTransitionDefinition['context'];\n },\n snapshot: AnyMachineSnapshot,\n event: AnyEventObject,\n actorScope: AnyActorScope,\n options?: {\n resolveActions?: boolean;\n selectionResult?: TransitionSelectionResult;\n }\n): {\n targets: Readonly<AnyStateNode[]> | undefined;\n context: MachineContext | undefined;\n actions: AnyAction[] | undefined;\n reenter?: boolean;\n internalEvents: EventObject[] | undefined;\n input: Record<string, unknown> | undefined;\n} {\n let transitionArgs: any;\n const getTransitionArgs = () =>\n (transitionArgs ??= isLazyActorScope(actorScope)\n ? withActorScope(\n {\n context: snapshot.context,\n event,\n output: getEventOutput(event),\n value: snapshot.value,\n children: snapshot.children,\n actions: snapshot.machine.sources.actions,\n actors: snapshot.machine.sources.actors,\n guards: snapshot.machine.sources.guards,\n delays: snapshot.machine.sources.delays,\n input: getStateInput(snapshot, transition.source.id)\n },\n actorScope\n )\n : {\n context: snapshot.context,\n event,\n output: getEventOutput(event),\n value: snapshot.value,\n children: snapshot.children,\n system: actorScope.system,\n parent: actorScope.self._parent,\n self: actorScope.self,\n actions: snapshot.machine.sources.actions,\n actors: snapshot.machine.sources.actors,\n guards: snapshot.machine.sources.guards,\n delays: snapshot.machine.sources.delays,\n input: getStateInput(snapshot, transition.source.id)\n });\n\n if (transition.to) {\n const actions: AnyAction[] = [];\n const internalEvents: EventObject[] = [];\n let res;\n if (\n options?.selectionResult?.reusable &&\n (options.resolveActions === false ||\n options.selectionResult.operations.length === 0)\n ) {\n res = options.selectionResult.result;\n } else {\n const enqueue = createTransitionEnqueue(\n actorScope,\n actions,\n internalEvents,\n true,\n options?.resolveActions ?? true\n );\n const speculativeSelection =\n options?.resolveActions === false\n ? beginTransitionSelection(\n getActorScopeParent(actorScope),\n 'suppress'\n )\n : undefined;\n try {\n if (options?.selectionResult?.reusable) {\n res = options.selectionResult.result;\n for (const operation of options.selectionResult.operations) {\n operation(enqueue);\n }\n } else {\n res = transition.to(getTransitionArgs(), enqueue);\n assertSyncTransitionResult(res, event, transition.source.id);\n }\n } finally {\n speculativeSelection?.close();\n closeTransitionEnqueue(enqueue);\n }\n }\n\n const targets = res?.target\n ? resolveTarget(transition.source, toArray(res.target) as string[])\n : undefined;\n\n const resolvedInput =\n res?.input ??\n (typeof transition.input === 'function'\n ? transition.input({\n context: snapshot.context,\n event,\n output: getEventOutput(event)\n })\n : transition.input);\n\n return {\n targets: targets,\n context: res?.context,\n reenter: res?.reenter,\n actions,\n internalEvents,\n input: resolvedInput\n };\n }\n\n // Resolve input for regular transitions\n const resolvedInput =\n typeof transition.input === 'function'\n ? transition.input({\n context: snapshot.context,\n event,\n output: getEventOutput(event)\n })\n : transition.input;\n const resolvedContext =\n typeof transition.context === 'function'\n ? transition.context(getTransitionArgs())\n : transition.context;\n\n return {\n targets: transition.target as AnyStateNode[] | undefined,\n context: resolvedContext,\n reenter: transition.reenter,\n actions: undefined,\n internalEvents: undefined,\n input: resolvedInput\n };\n}\n\n/**\n * Microsteps one macrostep may take before development builds warn, when the\n * machine sets no `maxIterations` bound.\n */\nconst LONG_MACROSTEP_WARNING = 1000;\n\n/** Machines that already logged the long-macrostep warning. */\nconst warnedLongMacrostep = new WeakSet<object>();\n\n/**\n * Thrown when one macrostep takes more microsteps than the machine's\n * `options.maxIterations` (unbounded by default) without reaching a stable state,\n * usually because eventless transitions or raised events form a cycle.\n *\n * @public\n */\nexport class InfiniteTransitionError extends Error {\n /** The id of the actor that was transitioning, if any. */\n public readonly actorId: string | undefined;\n /** The event being processed. */\n public readonly event: EventObject;\n /** The microstep bound that was exceeded. */\n public readonly maxIterations: number;\n /** The last (up to 5) state values visited, oldest first. */\n public readonly states: StateValue[];\n\n constructor(\n actorId: string | undefined,\n event: EventObject,\n maxIterations: number,\n states: StateValue[]\n ) {\n super(\n isDevelopment\n ? `Infinite loop detected in actor \"${actorId}\" processing event \"${\n event.type\n }\": more than ${maxIterations} microsteps without reaching a stable state. Last states: ${states\n .map((value) => JSON.stringify(value))\n .join(\n ' -> '\n )}. Check for a cycle of eventless transitions or raised events, or raise the bound with createMachine({ options: { maxIterations } }).`\n : xstateError(16, actorId, event.type, maxIterations)\n );\n this.name = 'InfiniteTransitionError';\n this.actorId = actorId;\n this.event = event;\n this.maxIterations = maxIterations;\n this.states = states.slice();\n }\n}\n\nexport function macrostep(\n snapshot: AnyMachineSnapshot,\n event: EventObject,\n actorScope: AnyActorScope,\n internalQueue: AnyEventObject[],\n initialMicrosteps: Microstep[] = []\n): {\n snapshot: typeof snapshot;\n microsteps: Microstep[];\n} {\n // A done, error or stopped snapshot processes no events, as in an actor:\n // every event is unhandled. The initial macrostep passes `initialMicrosteps`\n // and may start from a snapshot that is already done.\n if (snapshot.status !== 'active' && !initialMicrosteps.length) {\n return { snapshot, microsteps: [[snapshot, [], []]] };\n }\n let nextSnapshot = snapshot;\n const microsteps: Microstep[] = initialMicrosteps.slice();\n // Whether a transition handled the external event. A handled event always\n // yields a new snapshot object, so `result[0] === snapshot` (with no\n // effects) identifies an unhandled event.\n let handled = false;\n\n function removeTerminatedChild(terminalEvent: EventObject) {\n if (\n terminalEvent.type !== 'xstate.done.actor' &&\n terminalEvent.type !== 'xstate.error.actor'\n ) {\n return;\n }\n\n const { actorId, sessionId } = terminalEvent as AnyEventObject & {\n actorId?: string;\n sessionId?: string;\n };\n if (!actorId) {\n return;\n }\n const child = nextSnapshot.children[actorId];\n if (!child) {\n return;\n }\n // The same staleness rule matchesActorSession applies to transition\n // selection: a completion from a different incarnation must not remove\n // the still-running child either.\n if (child.sessionId !== undefined && child.sessionId !== sessionId) {\n return;\n }\n\n const children = { ...nextSnapshot.children };\n delete children[actorId];\n actorScope.system._unregister(child);\n nextSnapshot = cloneMachineSnapshot(nextSnapshot, { children });\n\n if (microsteps.length) {\n const [, lastEffects, lastTransitions] = microsteps.at(-1)!;\n microsteps[microsteps.length - 1] = [\n nextSnapshot,\n lastEffects,\n lastTransitions\n ];\n } else {\n microsteps.push([nextSnapshot, [], []]);\n }\n }\n\n function completeMacrostep() {\n if (handled && nextSnapshot === snapshot) {\n nextSnapshot = cloneMachineSnapshot(snapshot, {});\n if (microsteps.at(-1)?.[0] === snapshot) {\n const [, lastEffects, lastTransitions] = microsteps.at(-1)!;\n microsteps[microsteps.length - 1] = [\n nextSnapshot,\n lastEffects,\n lastTransitions\n ];\n }\n }\n const effects = microsteps.flatMap(([, actions]) => actions);\n const starts = deriveDeferredStarts(effects);\n const shouldTerminate =\n (snapshot.status === 'active' || initialMicrosteps.length > 0) &&\n (nextSnapshot.status === 'done' || nextSnapshot.status === 'error');\n\n if (starts.length || shouldTerminate) {\n const terminalEffects = shouldTerminate\n ? [...starts, createTerminationEffect(actorScope, nextSnapshot)]\n : starts;\n if (microsteps.length) {\n const [lastSnapshot, lastEffects, lastTransitions] = microsteps.at(-1)!;\n microsteps[microsteps.length - 1] = [\n lastSnapshot,\n [...lastEffects, ...terminalEffects],\n lastTransitions\n ];\n } else {\n microsteps.push([nextSnapshot, terminalEffects, []]);\n }\n }\n\n return { snapshot: nextSnapshot, microsteps };\n }\n\n function addMicrostep(\n step: Microstep,\n transitions: AnyTransitionDefinition[]\n ) {\n transitions = step[2] ?? transitions;\n // collect microsteps; their transitions are surfaced on the enclosing\n // '@xstate.transition' event via its `microsteps[]` facet (there is no\n // standalone microstep event) and returned by `getMicrosteps()`\n if (\n !isInertActorScope(actorScope) &&\n (event.type === XSTATE_INIT ||\n (actorScope.system._hasInspectionObservers?.() ?? true))\n ) {\n const collectedMicrosteps =\n ((actorScope.self as any)._collectedMicrosteps as any[]) || [];\n collectedMicrosteps.push(...transitions);\n (actorScope.self as any)._collectedMicrosteps = collectedMicrosteps;\n }\n microsteps.push([step[0], step[1], transitions]);\n }\n\n // Handle stop event\n if (event.type === XSTATE_STOP) {\n const [stoppedChildrenSnapshot, stopEffects] = stopChildren(\n nextSnapshot,\n event,\n actorScope\n );\n const [withoutTimers, cancelEffects] = cancelTimers(\n stoppedChildrenSnapshot,\n event,\n actorScope\n );\n nextSnapshot = cloneMachineSnapshot(withoutTimers, {\n status: 'stopped'\n });\n addMicrostep([nextSnapshot, [...stopEffects, ...cancelEffects]], []);\n return completeMacrostep();\n }\n\n let nextEvent = event;\n\n if (event.type === XSTATE_TIMER) {\n const key = readTimerKey(event);\n const index = key\n ? nextSnapshot.timers.findIndex((timer) => matchesTimerKey(timer, key))\n : -1;\n if (index === -1) {\n return completeMacrostep();\n }\n\n const timer = nextSnapshot.timers[index];\n const timers = nextSnapshot.timers.filter((_, i) => i !== index);\n nextSnapshot = cloneMachineSnapshot(nextSnapshot, { timers });\n if (timer.type === '@xstate.raise') {\n internalQueue.push(timer.event);\n addMicrostep([nextSnapshot, []], []);\n } else {\n const target = timer.target === 'self' ? actorScope.self : timer.target;\n addMicrostep(\n [nextSnapshot, [createSendToEffect(actorScope, target, timer.event)]],\n []\n );\n }\n }\n\n // Assume the state is at rest (no raised events)\n // Determine the next state based on the next microstep\n if (nextEvent.type !== XSTATE_INIT && nextEvent.type !== XSTATE_TIMER) {\n const currentEvent = nextEvent;\n const isErr = isErrorEvent(currentEvent);\n const selectionResults: TransitionSelectionResults = new Map();\n\n const transitions = nextSnapshot.machine.getTransitionData(\n nextSnapshot as any,\n currentEvent,\n actorScope,\n selectionResults\n );\n\n if (isErr && !transitions.length) {\n if (\n currentEvent.type === 'xstate.error.actor' &&\n !matchesActorSession(\n currentEvent,\n nextSnapshot,\n (currentEvent as AnyEventObject).actorId\n )\n ) {\n return completeMacrostep();\n }\n // TODO: we should likely only allow transitions selected by very explicit descriptors\n // `*` shouldn't be matched, likely `xstate.error.*` shouldn't be either\n nextSnapshot = cloneMachineSnapshot<typeof snapshot>(snapshot, {\n status: 'error',\n error: currentEvent.error\n });\n addMicrostep([nextSnapshot, []], []);\n removeTerminatedChild(currentEvent);\n return completeMacrostep();\n }\n handled = transitions.length > 0;\n const step = microstep(\n transitions,\n snapshot,\n actorScope,\n nextEvent,\n false, // isInitial\n internalQueue,\n selectionResults\n );\n nextSnapshot = step[0];\n addMicrostep(step, transitions);\n removeTerminatedChild(currentEvent);\n }\n\n if (\n !internalQueue.length &&\n snapshot.machine._hasEventlessTransitions === false\n ) {\n return completeMacrostep();\n }\n\n let shouldSelectEventlessTransitions = true;\n const maxIterations = snapshot.machine.options?.maxIterations ?? Infinity;\n let iterationCount = 0;\n // The last few state values visited, for the infinite-loop error.\n const recentStates: StateValue[] = [];\n\n while (nextSnapshot.status === 'active') {\n iterationCount++;\n if (iterationCount > maxIterations) {\n throw new InfiniteTransitionError(\n actorScope.self?.id,\n event,\n maxIterations,\n recentStates\n );\n }\n if (\n isDevelopment &&\n iterationCount === LONG_MACROSTEP_WARNING + 1 &&\n maxIterations === Infinity &&\n !warnedLongMacrostep.has(snapshot.machine)\n ) {\n warnedLongMacrostep.add(snapshot.machine);\n console.warn(\n `Actor \"${actorScope.self?.id}\" took more than ${LONG_MACROSTEP_WARNING} microsteps processing event \"${event.type}\" without reaching a stable state. Last states: ${recentStates\n .map((value) => JSON.stringify(value))\n .join(\n ' -> '\n )}. Check for a cycle of eventless transitions or raised events. To stop a runaway macrostep with an InfiniteTransitionError, set createMachine({ options: { maxIterations } }).`\n );\n }\n recentStates.push(nextSnapshot.value);\n if (recentStates.length > 5) {\n recentStates.shift();\n }\n\n let selectionResults: TransitionSelectionResults | undefined;\n let enabledTransitions: AnyTransitionDefinition[] =\n shouldSelectEventlessTransitions\n ? selectEventlessTransitions(nextSnapshot, nextEvent, actorScope)\n : [];\n\n // eventless transitions should always be selected after selecting *regular* transitions\n // by assigning `undefined` to `previousState` we ensure that `shouldSelectEventlessTransitions` gets always computed to true in such a case\n const previousState = enabledTransitions.length ? nextSnapshot : undefined;\n // Failed eventless guards can raise events even when no transition wins.\n const raisedEvents = nextSnapshot.machine._microstepHooks?.drain(\n actorScope.self\n );\n if (raisedEvents?.length) {\n internalQueue.push(...raisedEvents);\n }\n\n if (!enabledTransitions.length) {\n if (!internalQueue.length) {\n break;\n }\n nextEvent = internalQueue.shift()!;\n selectionResults = new Map();\n enabledTransitions = nextSnapshot.machine.getTransitionData(\n nextSnapshot as any,\n nextEvent,\n actorScope,\n selectionResults\n );\n }\n\n const step = microstep(\n enabledTransitions,\n nextSnapshot,\n actorScope,\n nextEvent,\n false,\n internalQueue,\n selectionResults\n );\n nextSnapshot = step[0];\n shouldSelectEventlessTransitions = nextSnapshot !== previousState;\n addMicrostep(step, enabledTransitions);\n removeTerminatedChild(nextEvent);\n }\n\n return completeMacrostep();\n}\n\n/**\n * Resolves a partial state value with its full representation in the state\n * node's machine.\n *\n * @param stateValue The partial state value to resolve.\n */\nexport function resolveStateValue(\n rootNode: AnyStateNode,\n stateValue: StateValue\n): StateValue {\n const allStateNodes = getAllStateNodes(getStateNodes(rootNode, stateValue));\n return getStateValue(rootNode, allStateNodes);\n}\n\nexport function hasEffect(\n transition: AnyTransitionDefinition,\n context: MachineContext,\n event: EventObject,\n snapshot: AnyMachineSnapshot,\n actorScope: AnyActorScope\n): boolean {\n if (transition.to) {\n return evaluateTransitionFunction(\n transition.to,\n context,\n event,\n snapshot,\n actorScope,\n snapshot.machine.sources,\n transition.source.id\n ).enabled;\n }\n\n return false;\n}\n\n/**\n * Throws when a transition, entry, or exit function returned a promise. The promise's\n * rejection is observed so it is never reported as unhandled.\n */\nfunction assertSyncTransitionResult(\n res: unknown,\n event: EventObject,\n sourceId: string,\n kind?: 'entry' | 'exit' | 'transition'\n): void {\n if (res && typeof (res as PromiseLike<unknown>).then === 'function') {\n void Promise.resolve(res as PromiseLike<unknown>).catch(() => {});\n throw new Error(\n !isDevelopment\n ? xstateError(17, kind ?? 'transition', sourceId, event.type)\n : kind && kind !== 'transition'\n ? `${kind === 'entry' ? 'Entry' : 'Exit'} functions must be synchronous. The ${kind} function of state \"${sourceId}\" returned a promise (event \"${event.type}\"). Move async work into an invoked or spawned actor, or enq.effect.`\n : `Transition functions must be synchronous. Transition for event \"${event.type}\" in state \"${sourceId}\" returned a promise. Move async work into an invoked or spawned actor, or enq.effect.`\n );\n }\n}\n\ntype RecordedEnqueue = (enqueue: EnqueueObject<any, any>) => void;\n\nfunction createTransitionSelection(parent: AnyActor | undefined) {\n const selection = beginTransitionSelection(parent);\n const { frame } = selection;\n const operations: RecordedEnqueue[] = [];\n let closed = false;\n const record = (operation: RecordedEnqueue) => {\n if (closed) {\n return lateEnqueueCall();\n }\n operations.push(operation);\n };\n const abortRefProducingCall = (): any => {\n if (closed) {\n return lateEnqueueCall();\n }\n frame.requiresReevaluation = true;\n throw transitionEffectSignal;\n };\n const enqueue = createEnqueueObject(\n {\n cancel: (...args) => record((enq) => enq.cancel(...args)),\n emit: (...args) => record((enq) => enq.emit(...args)),\n log: (...args) => record((enq) => enq.log(...args)),\n raise: (event, options) => {\n if (closed) {\n return lateEnqueueCall();\n }\n assertRaiseEvent(event);\n record((enq) => enq.raise(event, options));\n },\n sendTo: (...args) => record((enq) => enq.sendTo(...args)),\n stop: (...args) => record((enq) => enq.stop(...args)),\n spawn: abortRefProducingCall,\n listen: abortRefProducingCall,\n subscribeTo: abortRefProducingCall\n },\n (...args) => record((enq) => enq(...args))\n );\n return {\n frame,\n enqueue,\n operations,\n close() {\n closed = true;\n selection.close();\n }\n };\n}\n\nfunction evaluateTransitionFunction(\n transitionTo: NonNullable<AnyTransitionDefinition['to']>,\n context: MachineContext,\n event: EventObject,\n snapshot: AnyMachineSnapshot,\n actorScope: AnyActorScope,\n sources: AnyMachineSnapshot['machine']['sources'],\n sourceId: string\n): TransitionSelectionResult {\n let res;\n const selection = createTransitionSelection(getActorScopeParent(actorScope));\n try {\n res = transitionTo(\n withActorScope(\n {\n context,\n event,\n output: getEventOutput(event),\n value: snapshot.value,\n children: snapshot.children,\n actions: sources.actions,\n actors: sources.actors,\n guards: sources.guards,\n delays: sources.delays,\n input: getStateInput(snapshot, sourceId)\n },\n actorScope\n ),\n selection.enqueue\n );\n } catch (err) {\n if (err === transitionEffectSignal) {\n return { enabled: true, result: undefined, reusable: false };\n }\n throw err;\n } finally {\n selection.close();\n }\n assertSyncTransitionResult(res, event, sourceId);\n\n if (selection.frame.requiresReevaluation) {\n return { enabled: true, result: undefined, reusable: false };\n }\n return {\n enabled: res !== undefined || selection.operations.length > 0,\n result: res,\n reusable: true,\n operations: selection.operations\n };\n}\n\nfunction stopChildren(\n snapshot: AnyMachineSnapshot,\n event: AnyEventObject,\n actorScope: AnyActorScope\n): [AnyMachineSnapshot, ExecutableEffect[]] {\n let children: AnyActor[];\n if (\n !snapshot.children ||\n (children = Object.values(snapshot.children).filter(Boolean) as AnyActor[])\n .length === 0\n ) {\n return [snapshot, []];\n }\n const actions: AnyAction[] = [];\n const enqueue = createTransitionEnqueue(actorScope, actions, []);\n for (const child of children) {\n enqueue.stop(child);\n }\n return resolveActionsWithContext(snapshot, event, actorScope, actions);\n}\n\nfunction cancelTimers(\n snapshot: AnyMachineSnapshot,\n event: AnyEventObject,\n actorScope: AnyActorScope\n): [AnyMachineSnapshot, ExecutableEffect[]] {\n if (!snapshot.timers.length) {\n return [snapshot, []];\n }\n const actions: AnyAction[] = [];\n const enqueue = createTransitionEnqueue(actorScope, actions, []);\n for (const timer of snapshot.timers) {\n (enqueue.cancel as unknown as (key: TimerKey) => void)(getTimerKey(timer));\n }\n return resolveActionsWithContext(snapshot, event, actorScope, actions);\n}\n\nfunction selectEventlessTransitions(\n snapshot: AnyMachineSnapshot,\n event: AnyEventObject,\n actorScope: AnyActorScope\n) {\n snapshot.machine._microstepHooks?.begin(actorScope.self);\n const enabledTransitionSet: Set<AnyTransitionDefinition> = new Set();\n const atomicStates = snapshot.nodes.filter(isAtomicStateNode);\n\n for (const atomicStateNode of atomicStates) {\n loop: for (\n let stateNode: AnyStateNode | undefined = atomicStateNode;\n stateNode;\n stateNode = stateNode.parent\n ) {\n if (!stateNode.always) {\n continue;\n }\n for (const transition of stateNode.always) {\n if (\n evaluateCandidate(transition, event, snapshot, stateNode, actorScope)\n ) {\n enabledTransitionSet.add(transition);\n break loop;\n }\n }\n }\n }\n\n return removeConflictingTransitions(\n Array.from(enabledTransitionSet),\n new Set(snapshot.nodes),\n snapshot,\n createTransitionResultResolver(snapshot, event, actorScope, false)\n );\n}\n\nexport function evaluateCandidate(\n candidate: AnyTransitionDefinition,\n event: EventObject,\n snapshot: AnyMachineSnapshot,\n stateNode: AnyStateNode,\n actorScope: AnyActorScope,\n selectionResults?: TransitionSelectionResults\n): boolean {\n if (candidate.matches && !matchesEvent(event, candidate.matches)) {\n return false;\n }\n\n if (candidate._eventMatcher && !candidate._eventMatcher(event, snapshot)) {\n return false;\n }\n\n if (candidate.guard) {\n const guardArgs = withActorSelfAndParent(\n {\n context: snapshot.context,\n event,\n output: getEventOutput(event),\n children: snapshot.children,\n actions: stateNode.machine.sources.actions,\n actors: stateNode.machine.sources.actors,\n guards: stateNode.machine.sources.guards,\n delays: stateNode.machine.sources.delays,\n _snapshot: snapshot\n },\n actorScope\n );\n if (!(candidate.guard as (args: typeof guardArgs) => boolean)(guardArgs)) {\n return false;\n }\n }\n\n if (candidate.to) {\n const evaluation = evaluateTransitionFunction(\n candidate.to,\n snapshot.context,\n event,\n snapshot,\n actorScope,\n stateNode.machine.sources,\n candidate.source.id\n );\n selectionResults?.set(candidate, evaluation);\n return evaluation.enabled;\n }\n\n return true;\n}\n","export function parseDurationToMilliseconds(\n duration: string\n): number | undefined {\n const normalizedDuration = duration.trim();\n\n const millisecondsMatch = normalizedDuration.match(/^(\\d+)ms$/i);\n if (millisecondsMatch) {\n return parseInt(millisecondsMatch[1], 10);\n }\n\n const secondsMatch = normalizedDuration.match(/^(\\d*)(\\.?)(\\d*)s$/i);\n if (secondsMatch) {\n const wholePart = secondsMatch[1] ? parseInt(secondsMatch[1], 10) : 0;\n const hasDecimal = !!secondsMatch[2];\n const fracPart = secondsMatch[3]\n ? parseInt(secondsMatch[3].padEnd(3, '0').slice(0, 3), 10)\n : 0;\n\n return wholePart * 1000 + (hasDecimal ? fracPart : 0);\n }\n\n const iso8601DurationMatch = normalizedDuration.match(\n /^P(?:(?<weeks>\\d+(?:[.,]\\d+)?)W)?(?:(?<days>\\d+(?:[.,]\\d+)?)D)?(?:T(?:(?<hours>\\d+(?:[.,]\\d+)?)H)?(?:(?<minutes>\\d+(?:[.,]\\d+)?)M)?(?:(?<seconds>\\d+(?:[.,]\\d+)?)S)?)?$/i\n );\n\n if (!iso8601DurationMatch?.groups) {\n return undefined;\n }\n\n const { weeks, days, hours, minutes, seconds } = iso8601DurationMatch.groups;\n if (!weeks && !days && !hours && !minutes && !seconds) {\n return undefined;\n }\n\n const toNumber = (value: string | undefined) =>\n value ? Number(value.replace(',', '.')) : 0;\n\n return (\n toNumber(weeks) * 7 * 24 * 60 * 60 * 1000 +\n toNumber(days) * 24 * 60 * 60 * 1000 +\n toNumber(hours) * 60 * 60 * 1000 +\n toNumber(minutes) * 60 * 1000 +\n toNumber(seconds) * 1000\n );\n}\n\n/**\n * Converts a delay (milliseconds or an ISO 8601 duration string) to\n * milliseconds. Exported for `@xstate/scxml`; not part of the stable API.\n *\n * @experimental\n */\nexport function parseDelayToMilliseconds(\n delay: string | number | undefined\n): number | undefined {\n if (delay === undefined) {\n return undefined;\n }\n\n if (typeof delay === 'number') {\n return delay;\n }\n\n return parseDurationToMilliseconds(delay);\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 { 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 { 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","// Structural validation of persisted machine snapshots.\nimport type {\n AnyActorLogic,\n AnyStateMachine,\n AnyStateNode,\n StateValue\n} from './types.ts';\nimport { getAllStateNodes, getStateNodes } from './stateUtils.ts';\nimport isDevelopment from '#is-development';\nimport { describeMachine, resolveInvokedActorLogic } from './utils.ts';\nimport { xstateError } from './xstateError.ts';\nimport { isSerializedActorRef } from './remoteActorRef.ts';\n\n/**\n * The error a machine reports when a persisted snapshot cannot represent one\n * of its states: the snapshot has an invalid state value, malformed children\n * or timers, or a child source that the machine cannot restore.\n * `restoreActor(machine, snapshot)` reports it as an `'error'` snapshot\n * instead of starting.\n *\n * @public\n */\nexport class InvalidSnapshotError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'InvalidSnapshotError';\n }\n}\n\nexport function isSnapshotRecord(\n value: unknown\n): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction isActorLogic(value: unknown): value is AnyActorLogic {\n return (\n isSnapshotRecord(value) &&\n typeof value.transition === 'function' &&\n typeof value.getInitialSnapshot === 'function'\n );\n}\n\nfunction validatePersistedStateValue(\n machine: AnyStateMachine,\n stateValue: unknown,\n node: AnyStateNode,\n path: string[]\n): void {\n if (typeof stateValue === 'string') {\n if (!node.states[stateValue]) {\n throw new InvalidSnapshotError(\n isDevelopment\n ? `Persisted snapshot references state '${path.concat(stateValue).join('.')}' which does not exist on ${describeMachine(machine.id)}.`\n : xstateError(21, path.concat(stateValue).join('.'))\n );\n }\n return;\n }\n const invalidValue = (code: 22 | 23) =>\n new InvalidSnapshotError(\n isDevelopment\n ? `Persisted snapshot for ${describeMachine(machine.id)} has an invalid state value${path.length ? ` at '${path.join('.')}'` : ''}: ${\n code === 22\n ? 'expected a state name or an object of state values'\n : `state '${path.length ? path.join('.') : node.key}' is not parallel, so only one child state can be active`\n }.`\n : code === 22\n ? xstateError(22, path.join('.'))\n : xstateError(23, path.join('.'))\n );\n if (\n !stateValue ||\n typeof stateValue !== 'object' ||\n Array.isArray(stateValue)\n ) {\n throw invalidValue(22);\n }\n const keys = Object.keys(stateValue);\n if (keys.length > 1 && node.type !== 'parallel') {\n throw invalidValue(23);\n }\n for (const key of keys) {\n const childNode = node.states[key];\n if (!childNode) {\n throw new InvalidSnapshotError(\n isDevelopment\n ? `Persisted snapshot references state '${path.concat(key).join('.')}' which does not exist on ${describeMachine(machine.id)}.`\n : xstateError(21, path.concat(key).join('.'))\n );\n }\n validatePersistedStateValue(\n machine,\n\n (stateValue as Record<string, unknown>)[key],\n childNode,\n path.concat(key)\n );\n }\n}\n\nexport function validatePersistedSnapshot(\n machine: AnyStateMachine,\n snapshot: unknown\n): {\n nodes: AnyStateNode[];\n childLogics: Map<string, AnyActorLogic>;\n} {\n if (!isSnapshotRecord(snapshot)) {\n throw new InvalidSnapshotError(\n isDevelopment\n ? `Persisted snapshot for ${describeMachine(machine.id)} must be an object.`\n : xstateError(24, machine.id)\n );\n }\n if (snapshot.value === undefined) {\n throw new InvalidSnapshotError(\n isDevelopment\n ? `Persisted snapshot for ${describeMachine(machine.id)} has no state value.`\n : xstateError(25, machine.id)\n );\n }\n validatePersistedStateValue(machine, snapshot.value, machine.root, []);\n const nodes = Array.from(\n getAllStateNodes(getStateNodes(machine.root, snapshot.value as StateValue))\n );\n if (!isSnapshotRecord(snapshot.children)) {\n throw new InvalidSnapshotError(\n isDevelopment\n ? \"Persisted snapshot has invalid 'children'.\"\n : xstateError(26)\n );\n }\n const childLogics = new Map<string, AnyActorLogic>();\n for (const [id, child] of Object.entries(snapshot.children)) {\n if (\n !isSnapshotRecord(child) ||\n (child.remote !== undefined && typeof child.remote !== 'boolean') ||\n (child.address !== undefined && typeof child.address !== 'string') ||\n (child.syncSnapshot !== undefined &&\n typeof child.syncSnapshot !== 'boolean') ||\n (child.registryKey !== undefined &&\n typeof child.registryKey !== 'string') ||\n (child.incarnation !== undefined &&\n typeof child.incarnation !== 'string') ||\n (child.snapshot !== undefined && !isSnapshotRecord(child.snapshot))\n ) {\n throw new InvalidSnapshotError(\n isDevelopment\n ? `Persisted snapshot has invalid child '${id}'.`\n : xstateError(27, id)\n );\n }\n if (child.remote === true) {\n if (typeof child.address !== 'string' || typeof child.src !== 'string') {\n throw new InvalidSnapshotError(\n isDevelopment\n ? `Unable to restore remote child '${id}': a child referenced by address requires a registered source key and an address.`\n : xstateError(28, id)\n );\n }\n continue;\n }\n if (\n child.src !== undefined &&\n typeof child.src !== 'string' &&\n !isActorLogic(child.src)\n ) {\n throw new InvalidSnapshotError(\n isDevelopment\n ? `Persisted snapshot has invalid child '${id}'.`\n : xstateError(27, id)\n );\n }\n try {\n const logic =\n child.src === undefined\n ? resolveInvokedActorLogic(machine, nodes, id)\n : typeof child.src === 'string'\n ? Object.hasOwn(machine.sources.actors, child.src)\n ? machine.sources.actors[child.src]\n : undefined\n : child.src;\n if (!logic) {\n throw new InvalidSnapshotError(\n isDevelopment\n ? `Unable to restore child actor '${id}': child source '${typeof child.src === 'string' ? child.src : '<inline>'}' is not provided in ${describeMachine(machine.id)}.`\n : xstateError(\n 29,\n id,\n typeof child.src === 'string' ? child.src : '<inline>'\n )\n );\n }\n childLogics.set(id, logic);\n } catch (error) {\n if (error instanceof InvalidSnapshotError) {\n throw error;\n }\n throw new InvalidSnapshotError(\n error instanceof Error\n ? error.message\n : isDevelopment\n ? `Unable to restore child actor '${id}'.`\n : xstateError(30, id)\n );\n }\n }\n if (snapshot.timers !== undefined && !Array.isArray(snapshot.timers)) {\n throw new InvalidSnapshotError(\n isDevelopment\n ? \"Persisted snapshot has invalid 'timers'.\"\n : xstateError(31)\n );\n }\n for (const timer of snapshot.timers ?? []) {\n if (\n !isSnapshotRecord(timer) ||\n typeof timer.delay !== 'number' ||\n (timer.type !== '@xstate.raise' && timer.type !== '@xstate.sendTo') ||\n !isSnapshotRecord(timer.event) ||\n typeof timer.event.type !== 'string' ||\n (timer.id !== undefined && typeof timer.id !== 'string') ||\n (timer.seq !== undefined && typeof timer.seq !== 'number') ||\n (timer.scheduledAt !== undefined &&\n typeof timer.scheduledAt !== 'number') ||\n !(\n typeof timer.target === 'string' ||\n (isSnapshotRecord(timer.target) && timer.target.type === 'parent') ||\n isSerializedActorRef(timer.target)\n )\n ) {\n throw new InvalidSnapshotError(\n isDevelopment\n ? 'Persisted snapshot has invalid timer.'\n : xstateError(32)\n );\n }\n if (\n typeof timer.target === 'string' &&\n timer.target !== 'self' &&\n !Object.hasOwn(snapshot.children, timer.target)\n ) {\n throw new InvalidSnapshotError(\n isDevelopment\n ? `Unable to restore timer: target actor '${timer.target}' is unavailable.`\n : xstateError(33, timer.target)\n );\n }\n }\n return { nodes, childLogics };\n}\n","const cache = new WeakMap<any, any>();\n\nexport function memo<T>(object: any, key: string, fn: () => T): T {\n let memoizedData = cache.get(object);\n\n if (!memoizedData) {\n memoizedData = { [key]: fn() };\n cache.set(object, memoizedData);\n } else if (!(key in memoizedData)) {\n memoizedData[key] = fn();\n }\n\n return memoizedData[key];\n}\n","import isDevelopment from '#is-development';\nimport { xstateError } from './xstateError.ts';\nimport { NULL_EVENT, STATE_DELIMITER } from './constants.ts';\nimport type { SetupStateSchemas } from './schema.types.ts';\nimport { memo } from './memo.ts';\nimport {\n evaluateCandidate,\n formatTransition,\n getCandidates,\n getDelayedTransitions,\n matchesActorSession,\n type TransitionSelectionResults\n} from './stateUtils.ts';\nimport type {\n DelayedTransitionDefinition,\n EventObject,\n TimerKey,\n InitialTransitionDefinition,\n MachineContext,\n Mapper,\n TransitionDefinition,\n TransitionDefinitionMap,\n AnyStateMachine,\n AnyStateNodeConfig,\n EventDescriptor,\n AnyActorScope,\n AnyStateNode,\n AnyEventObject,\n AnyAction,\n AnyTransitionConfig,\n AnyTransitionDefinition,\n AnyMachineSnapshot,\n AnyInvokeDefinition,\n InvokeDefinition,\n MetaObject\n} from './types.ts';\nimport type { NonReducibleUnknown } from './typeUtils.ts';\nimport {\n createInvokeId,\n hasUnescapedDot,\n mapValues,\n toArray,\n toTransitionConfigArray\n} from './utils.ts';\n\nconst EMPTY_OBJECT = {};\nconst CHOICE_CONFIG_KEYS = [\n 'invoke',\n 'after',\n 'on',\n 'entry',\n 'exit',\n 'always',\n 'states',\n 'initial',\n 'onDone',\n 'timeout',\n 'onTimeout',\n 'history',\n 'target',\n 'output'\n] as const;\n\ninterface StateNodeOptions<\n TStateMeta extends MetaObject,\n TTransitionMeta extends MetaObject\n> {\n _key: string;\n _parent?: StateNode<any, any, TStateMeta, TTransitionMeta>;\n _machine: AnyStateMachine;\n}\n\n/** @public */\nexport class StateNode<\n TContext extends MachineContext = MachineContext,\n TEvent extends EventObject = EventObject,\n TStateMeta extends MetaObject = any,\n TTransitionMeta extends MetaObject = TStateMeta\n> {\n /**\n * The relative key of the state node, which represents its location in the\n * overall state value.\n */\n public key: string;\n /** The unique ID of the state node. */\n public id: string;\n /**\n * The type of this state node:\n *\n * - `'atomic'` - no child state nodes\n * - `'compound'` - nested child state nodes (XOR)\n * - `'parallel'` - orthogonal nested child state nodes (AND)\n * - `'history'` - history state node\n * - `'choice'` - pure routing decision state node\n * - `'final'` - final state node\n */\n public type:\n | 'atomic'\n | 'compound'\n | 'parallel'\n | 'final'\n | 'history'\n | 'choice';\n /** The string path from the root machine node to this node. */\n public path: string[];\n /** The child state nodes. */\n public states: Record<\n string,\n StateNode<TContext, TEvent, TStateMeta, TTransitionMeta>\n >;\n /**\n * The type of history on this state node. Can be:\n *\n * - `'shallow'` - recalls only top-level historical state value\n * - `'deep'` - recalls historical state value at all levels\n */\n public history: false | 'shallow' | 'deep';\n /** The action(s) to be executed upon entering the state node. */\n public entry: AnyAction | undefined;\n /** The action(s) to be executed upon exiting the state node. */\n public exit: AnyAction | undefined;\n /** The parent state node. */\n public parent?: StateNode<TContext, TEvent, TStateMeta, TTransitionMeta>;\n /** The root machine node. */\n public machine: AnyStateMachine;\n /**\n * The meta data associated with this state node, which will be returned in\n * State instances.\n */\n public meta?: TStateMeta;\n /**\n * The output data sent with the `xstate.done.state` event if this is a final\n * state node.\n */\n public output?:\n | Mapper<MachineContext, EventObject, unknown, EventObject>\n | NonReducibleUnknown;\n\n /**\n * The order this state node appears. Corresponds to the implicit document\n * order.\n */\n public order: number = -1;\n\n public description?: string;\n\n public schemas: SetupStateSchemas | undefined;\n\n public tags: string[] = [];\n public transitions!: Map<\n string,\n TransitionDefinition<any, any, TTransitionMeta>[]\n >;\n public always?: Array<TransitionDefinition<any, any, TTransitionMeta>>;\n public invoke: Array<\n InvokeDefinition<any, any, any, TTransitionMeta, any, any, any, any>\n >;\n public on!: TransitionDefinitionMap<any, any, TTransitionMeta>;\n public after!: Array<DelayedTransitionDefinition<any, any, TTransitionMeta>>;\n public events!: Array<EventDescriptor<any>>;\n public ownEvents!: Array<EventDescriptor<any>>;\n private _candidateCache?: Map<string, AnyTransitionDefinition[]>;\n\n constructor(\n /** The raw config used to create the machine. */\n public config: AnyStateNodeConfig,\n options: StateNodeOptions<TStateMeta, TTransitionMeta>\n ) {\n this.parent = options._parent;\n this.key = options._key;\n this.machine = options._machine;\n if (this.parent && hasUnescapedDot(this.key)) {\n throw new Error(\n isDevelopment\n ? // The suggestion is written as a JS string literal.\n `State key \"${this.key}\" contains \".\". Nest the states or escape it as \"${this.key.replaceAll(/(?<!\\\\)\\./g, '\\\\\\\\.')}\".`\n : xstateError(57, this.key)\n );\n }\n this.path = this.parent ? this.parent.path.concat(this.key) : [];\n const firstStateKey = this.config.states\n ? Object.keys(this.config.states)[0]\n : undefined;\n // The implicit id is the path from the root, prefixed by the machine id\n // when it has one: `shop.checkout`, or `checkout` without a machine id.\n this.id =\n this.config.id ||\n (this.machine.id ? [this.machine.id, ...this.path] : this.path).join(\n STATE_DELIMITER\n );\n this.type =\n this.config.type ||\n (firstStateKey !== undefined\n ? 'compound'\n : this.config.history\n ? 'history'\n : 'atomic');\n this.description = this.config.description;\n this.schemas = this.config.schemas;\n\n validateStateNodeConfig(this);\n if (isDevelopment) {\n warnOnFinalStateBehavior(this);\n }\n\n const existing = this.machine.idMap.get(this.id);\n // Valid keys escape their dots, so two implicit ids cannot coincide; an\n // explicit id that equals another id would make `#id` ambiguous.\n if (existing) {\n throw new Error(\n isDevelopment\n ? `Duplicate state id '${this.id}': the states at '${existing.path.join(STATE_DELIMITER)}' and '${this.path.join(STATE_DELIMITER)}' both have it. State ids must be unique; rename the explicit \\`id\\`.`\n : xstateError(58, this.id)\n );\n }\n this.order = this.machine.idMap.size;\n this.machine.idMap.set(this.id, this);\n\n this.states = (\n this.config.states\n ? mapValues(\n this.config.states,\n (stateConfig: AnyStateNodeConfig, key) => {\n const stateNode = new StateNode<\n any,\n any,\n TStateMeta,\n TTransitionMeta\n >(stateConfig, {\n _parent: this,\n _key: key,\n _machine: this.machine\n });\n return stateNode;\n }\n )\n : EMPTY_OBJECT\n ) as typeof this.states;\n\n if (this.type === 'compound' && !this.config.initial) {\n throw new Error(\n isDevelopment\n ? `No initial state specified for compound state node \"#${\n this.id\n }\". Try adding { initial: \"${firstStateKey}\" } to the state config.`\n : xstateError(59, this.id)\n );\n }\n\n // History config\n this.history =\n this.config.history === true ? 'shallow' : this.config.history || false;\n\n this.entry = this.config.entry as AnyAction | undefined;\n this.exit = this.config.exit as AnyAction | undefined;\n\n this.meta = this.config.meta;\n this.output =\n this.type === 'final' || !this.parent ? this.config.output : undefined;\n this.tags = toArray(config.tags).slice();\n this.invoke = toArray(this.config.invoke).map((invokeConfig, i) => {\n const { src, registryKey } = invokeConfig;\n const invokeId = createInvokeId(this.id, i);\n const resolvedId = invokeConfig.id ?? invokeId;\n\n return {\n ...invokeConfig,\n // Registered (string) sources persist by key; inline logic has no\n // source key and restores through this invoke definition's id.\n src: typeof src === 'string' ? src : undefined,\n logic: src,\n id: resolvedId,\n registryKey\n } as AnyInvokeDefinition;\n }) as typeof this.invoke;\n }\n\n /** @internal */\n public _initialize() {\n this.after = getDelayedTransitions(this) as any;\n this.transitions = formatTransitions(this) as typeof this.transitions;\n if (this.type === 'choice') {\n this.always = formatChoiceTransitions(this) as typeof this.always;\n } else if (this.config.always) {\n this.always = mapTransitionConfigs(\n this,\n 'always',\n this.config.always,\n (transition) => formatTransition(this, NULL_EVENT, transition)\n ) as typeof this.always;\n }\n\n for (const key of Object.keys(this.states)) {\n this.states[key]._initialize();\n }\n\n this._refreshEventMetadata();\n }\n\n /** @internal */\n public _refreshEventMetadata() {\n const on = {} as TransitionDefinitionMap<any, any, TTransitionMeta>;\n const ownEvents: EventDescriptor<any>[] = [];\n for (const [descriptor, transitions] of this.transitions) {\n (on as any)[descriptor] = transitions.slice();\n if (\n transitions.some(\n (transition) =>\n transition.target || transition.reenter || transition.to\n )\n ) {\n ownEvents.push(descriptor);\n }\n }\n this.on = on;\n this.ownEvents = ownEvents;\n\n const events = new Set<EventDescriptor<any>>(ownEvents);\n for (const state of Object.values(this.states)) {\n for (const event of state.events) {\n events.add(event);\n }\n }\n this.events = Array.from(events);\n }\n\n public get initial(): InitialTransitionDefinition<TTransitionMeta> {\n return memo(this, 'initial', () =>\n formatInitialTransition(this, this.config.initial)\n ) as InitialTransitionDefinition<TTransitionMeta>;\n }\n\n /** @internal */\n public next(\n snapshot: AnyMachineSnapshot,\n event: AnyEventObject,\n actorScope: AnyActorScope,\n selectionResults?: TransitionSelectionResults\n ): Array<AnyTransitionDefinition> | undefined {\n // Final states are inert: as in SCXML, they take no transitions.\n if (this.type === 'final') {\n return undefined;\n }\n let candidates = this._candidateCache?.get(event.type);\n if (!candidates) {\n candidates = getCandidates(this, event);\n (this._candidateCache ??= new Map()).set(event.type, candidates);\n }\n\n for (const candidate of candidates) {\n const guardPassed = evaluateCandidate(\n candidate,\n event,\n snapshot,\n this,\n actorScope,\n selectionResults\n );\n\n if (guardPassed) {\n return [candidate];\n }\n }\n\n return undefined;\n }\n}\n\nfunction validateStateNodeConfig(stateNode: AnyStateNode) {\n const config = stateNode.config as any;\n\n if (\n stateNode.type === 'history' &&\n !(\n (typeof config.target === 'string' && config.target.trim().length > 0) ||\n (Array.isArray(config.target) &&\n config.target.length > 0 &&\n config.target.every(\n (target: unknown) =>\n typeof target === 'string' && target.trim().length > 0\n ))\n )\n ) {\n throw new Error(\n isDevelopment\n ? `History state \"${stateNode.id}\" must declare a non-empty \\`target\\`.`\n : xstateError(60, stateNode.id)\n );\n }\n\n if (stateNode.type !== 'choice') {\n if (isDevelopment && config.choice !== undefined) {\n throw new Error(\n `State \"${stateNode.id}\" has \\`choice\\`, but \\`choice\\` can only be used with \\`type: 'choice'\\`.`\n );\n }\n return;\n }\n\n if (typeof config.choice !== 'function') {\n throw new Error(\n isDevelopment\n ? `Choice state \"${stateNode.id}\" must declare a \\`choice\\` function.`\n : xstateError(61, stateNode.id)\n );\n }\n\n if (isDevelopment) {\n for (const key of CHOICE_CONFIG_KEYS) {\n if (config[key] !== undefined) {\n throw new Error(\n `Choice state \"${stateNode.id}\" cannot declare \\`${key}\\`.`\n );\n }\n }\n }\n}\n\nconst FINAL_STATE_IGNORED_KEYS = ['invoke', 'on', 'after'] as const;\n\n/**\n * Final states are inert: their `invoke`, `on` and `after` never run. Warn\n * instead of silently ignoring them.\n */\nfunction warnOnFinalStateBehavior(stateNode: AnyStateNode): void {\n if (stateNode.type !== 'final') {\n return;\n }\n const config = stateNode.config as Record<string, unknown>;\n const declared = FINAL_STATE_IGNORED_KEYS.filter(\n (key) => config[key] !== undefined\n );\n if (declared.length) {\n console.warn(\n `State \"${stateNode.id}\" is final and declares ${declared\n .map((key) => `\"${key}\"`)\n .join(', ')}; final states cannot run actors or take transitions.`\n );\n }\n}\n\nfunction formatChoiceTransitions(\n stateNode: AnyStateNode\n): AnyTransitionDefinition[] {\n const choice = (stateNode.config as any).choice;\n const validateChoiceResult = (result: any): AnyTransitionConfig => {\n if (!result || result.target === undefined) {\n throw new Error(\n isDevelopment\n ? `Choice state \"${stateNode.id}\" must resolve to a target.`\n : xstateError(62, stateNode.id)\n );\n }\n if (isDevelopment) {\n for (const key of ['actions', 'to'] as const) {\n if (result[key] !== undefined) {\n throw new Error(\n `Choice state \"${stateNode.id}\" cannot declare \\`${key}\\` on a choice.`\n );\n }\n }\n }\n return result;\n };\n\n return [\n formatTransition(stateNode, NULL_EVENT, {\n to: (args: any) => validateChoiceResult(choice(args))\n } as AnyTransitionConfig)\n ];\n}\n\nfunction mapTransitionConfigs<T>(\n stateNode: AnyStateNode,\n name: string,\n transitionsConfig: unknown,\n mapper: (transition: AnyTransitionConfig) => T\n): T[] {\n const transitionConfigs = toTransitionConfigArray(\n transitionsConfig as any,\n name,\n stateNode.id\n );\n const transitions = new Array<T>(transitionConfigs.length);\n\n for (let i = 0; i < transitionConfigs.length; i++) {\n transitions[i] = mapper(transitionConfigs[i]);\n }\n\n return transitions;\n}\n\nfunction formatTransitions<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n stateNode: AnyStateNode\n): Map<string, TransitionDefinition<TContext, TEvent>[]> {\n const transitions = new Map<\n string,\n TransitionDefinition<TContext, AnyEventObject>[]\n >();\n const addTransitions = (\n descriptor: string,\n additions: AnyTransitionDefinition[]\n ) => {\n transitions.set(descriptor, [\n ...(transitions.get(descriptor) ?? []),\n ...additions\n ]);\n };\n if (stateNode.config.on) {\n for (const descriptor of Object.keys(stateNode.config.on)) {\n if (descriptor === NULL_EVENT) {\n throw new Error(\n isDevelopment\n ? 'Null events (\"\") cannot be specified as a transition key. Use `always: { ... }` instead.'\n : xstateError(63, stateNode.id)\n );\n }\n const transitionsConfig = stateNode.config.on[descriptor];\n transitions.set(\n descriptor,\n mapTransitionConfigs(\n stateNode,\n descriptor,\n transitionsConfig,\n (transition) => formatTransition(stateNode, descriptor, transition)\n )\n );\n }\n }\n if (stateNode.config.onDone) {\n const descriptor = 'xstate.done.state';\n addTransitions(\n descriptor,\n mapTransitionConfigs(\n stateNode,\n 'onDone',\n stateNode.config.onDone,\n (transition) =>\n formatTransition(stateNode, descriptor, {\n ...transition,\n matches: { ...transition.matches, stateId: stateNode.id }\n })\n )\n );\n }\n if (stateNode.config.onError) {\n const descriptor = 'xstate.error.*';\n transitions.set(\n descriptor,\n mapTransitionConfigs(\n stateNode,\n 'onError',\n stateNode.config.onError,\n (transition) => formatTransition(stateNode, descriptor, transition)\n )\n );\n }\n const createCancelInvokeTimeoutTransition = (\n descriptor: string,\n timeoutKey: TimerKey,\n actorId: string\n ): AnyTransitionDefinition =>\n formatTransition(stateNode, descriptor, {\n matches: { actorId },\n _eventMatcher: (event: EventObject, snapshot: AnyMachineSnapshot) =>\n matchesActorSession(event, snapshot, actorId),\n to: (_args: any, enq: any) => {\n enq.cancel(timeoutKey);\n return {};\n }\n } as AnyTransitionConfig);\n const formatInvokeCompletionTransition = (\n descriptor: string,\n transitionConfig: AnyTransitionConfig,\n timeoutKey: TimerKey\n ): AnyTransitionDefinition => {\n const { target, to, reenter, ...rest } = transitionConfig;\n\n return formatTransition(stateNode, descriptor, {\n ...rest,\n reenter,\n to: (args: any, enq: any) => {\n if (to) {\n let didEnqueue = false;\n const trackingEnqueue = new Proxy(enq, {\n apply(target, thisArg, argArray) {\n didEnqueue = true;\n return Reflect.apply(target, thisArg, argArray);\n },\n get(target, prop, receiver) {\n const value = Reflect.get(target, prop, receiver);\n\n if (typeof value !== 'function') {\n return value;\n }\n\n return (...argArray: any[]) => {\n didEnqueue = true;\n return value.apply(target, argArray);\n };\n }\n });\n const result = to(args, trackingEnqueue);\n\n if (result !== undefined || didEnqueue) {\n enq.cancel(timeoutKey);\n }\n\n return result;\n }\n\n enq.cancel(timeoutKey);\n return {\n target,\n reenter\n };\n }\n } as AnyTransitionConfig);\n };\n for (const invokeDef of stateNode.invoke) {\n const withInvokeMatch = (transition: AnyTransitionConfig) => ({\n ...transition,\n matches: { ...transition.matches, actorId: invokeDef.id },\n _eventMatcher: (event: EventObject, snapshot: AnyMachineSnapshot) =>\n matchesActorSession(event, snapshot, invokeDef.id)\n });\n // Built-in timers have no id; the invoke timeout is keyed by its event.\n const invokeTimeoutKey: TimerKey | undefined =\n invokeDef.timeout !== undefined\n ? {\n event: {\n type: 'xstate.timeout.actor',\n actorId: invokeDef.id\n } as EventObject\n }\n : undefined;\n\n if (invokeDef.onDone) {\n const descriptor = 'xstate.done.actor';\n const invokeDoneTransitions = mapTransitionConfigs(\n stateNode,\n 'invoke.onDone',\n invokeDef.onDone,\n (rawTransition) => {\n const transition = withInvokeMatch(rawTransition);\n return invokeTimeoutKey\n ? formatInvokeCompletionTransition(\n descriptor,\n transition,\n invokeTimeoutKey\n )\n : formatTransition(stateNode, descriptor, transition);\n }\n );\n\n if (invokeTimeoutKey) {\n invokeDoneTransitions.push(\n createCancelInvokeTimeoutTransition(\n descriptor,\n invokeTimeoutKey,\n invokeDef.id\n )\n );\n }\n\n addTransitions(descriptor, invokeDoneTransitions);\n } else if (invokeTimeoutKey) {\n const descriptor = 'xstate.done.actor';\n addTransitions(descriptor, [\n createCancelInvokeTimeoutTransition(\n descriptor,\n invokeTimeoutKey,\n invokeDef.id\n )\n ]);\n }\n if (invokeDef.onError) {\n const descriptor = 'xstate.error.actor';\n addTransitions(\n descriptor,\n mapTransitionConfigs(\n stateNode,\n 'invoke.onError',\n invokeDef.onError,\n (rawTransition) => {\n const transition = withInvokeMatch(rawTransition);\n return invokeTimeoutKey\n ? formatInvokeCompletionTransition(\n descriptor,\n transition,\n invokeTimeoutKey\n )\n : formatTransition(stateNode, descriptor, transition);\n }\n )\n );\n }\n if (invokeDef.onSnapshot) {\n const descriptor = 'xstate.snapshot.actor';\n addTransitions(\n descriptor,\n mapTransitionConfigs(\n stateNode,\n 'invoke.onSnapshot',\n invokeDef.onSnapshot,\n (transition) =>\n formatTransition(stateNode, descriptor, withInvokeMatch(transition))\n )\n );\n }\n }\n for (const delayedTransition of stateNode.after) {\n let existing = transitions.get(delayedTransition.eventType);\n if (!existing) {\n existing = [];\n transitions.set(delayedTransition.eventType, existing);\n }\n existing.push(\n delayedTransition as TransitionDefinition<TContext, AnyEventObject>\n );\n }\n return transitions as Map<string, TransitionDefinition<TContext, any>[]>;\n}\n\nfunction formatInitialTransition(\n stateNode: AnyStateNode,\n _target:\n | string\n | {\n target: string | string[];\n input?: any;\n to?: (...args: any[]) => any;\n meta?: any;\n description?: string;\n }\n | undefined\n): InitialTransitionDefinition {\n const targetString =\n typeof _target === 'object' && _target !== null ? _target.target : _target;\n const input =\n typeof _target === 'object' && _target !== null ? _target.input : undefined;\n const to =\n typeof _target === 'object' && _target !== null ? _target.to : undefined;\n const meta =\n typeof _target === 'object' && _target !== null ? _target.meta : undefined;\n const description =\n typeof _target === 'object' && _target !== null\n ? _target.description\n : undefined;\n const targetStrings = Array.isArray(targetString)\n ? targetString\n : targetString\n ? [targetString]\n : [];\n const resolvedTargets = targetStrings.map((target) =>\n target.startsWith('#')\n ? stateNode.machine.getStateNodeById(target.slice(1))\n : stateNode.states[target]\n );\n if (resolvedTargets.some((target) => !target)) {\n throw new Error(\n isDevelopment\n ? `Initial state node \"${targetStrings.find((_, index) => !resolvedTargets[index])}\" not found on parent state node #${stateNode.id}`\n : xstateError(\n 64,\n targetStrings.find((_, index) => !resolvedTargets[index]),\n stateNode.id\n )\n );\n }\n const transition: InitialTransitionDefinition = {\n source: stateNode,\n target: resolvedTargets.length\n ? (resolvedTargets as AnyStateNode[])\n : undefined,\n input,\n to,\n meta,\n description\n };\n\n return transition;\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 isDevelopment from '#is-development';\nimport { xstateError } from './xstateError.ts';\nimport { createActor } from './createActor.ts';\nimport { createErrorPlatformEvent, createInitEvent } from './eventUtils.ts';\nimport { STATE_DELIMITER, XSTATE_TIMER } from './constants.ts';\n\nimport { createSpawner } from './spawn.ts';\nimport {\n attachSnapshotActorRef,\n createInertActorScope,\n isInertActorScope,\n setInertActorScopeSnapshot\n} from './inertActorScope.ts';\nimport { withActorSelf } from './actorScope.ts';\nimport {\n createMachineSnapshot,\n cloneMachineSnapshot,\n freezeContext,\n getPersistedSnapshot,\n MachineSnapshot\n} from './State.ts';\nimport { setSnapshotActorRef } from './snapshotActorRef.ts';\nimport { StateNode } from './StateNode.ts';\nimport {\n formatRouteTransitions,\n getAllStateNodes,\n getStateNodes,\n getTransitionResult,\n hasEffect,\n initialMicrostep,\n isInFinalState,\n isStateId,\n macrostep,\n resolveStateValue,\n transitionNode,\n type TransitionSelectionResults\n} from './stateUtils.ts';\nimport {\n beginSpawnAllocation,\n createDeadLetterEffect,\n createSpawnEffect,\n createStartEffect,\n detachedScopes,\n resolveActionsWithContext,\n mergeActorIdCounters,\n takeSpawnAllocationCounters\n} from './transitionActions.ts';\nimport { AnyActorSystem, type DeadLetterDetail } from './system.ts';\nimport type {\n ActorLogic,\n ActorLogicTransitionResult,\n ActorScope,\n AnyActor,\n AnyActorLogic,\n AnyActorRef,\n AnyActorScope,\n AnyEventObject,\n AnyStateMachine,\n AnyMachineSnapshot,\n AnyTransitionDefinition,\n EventDescriptor,\n EmittedFrom,\n EventObject,\n EventFromLogic,\n ExecutableEffect,\n ExecutableEffectFrom,\n HistoryValue,\n InputFrom,\n MachineContext,\n MetaObject,\n OutputFrom,\n SnapshotFrom,\n StateValue,\n StateSchema,\n SnapshotStatus,\n AnyStateNode\n} from './types.ts';\nimport type { Equals, IsAny } from './typeUtils.ts';\nimport {\n AnyMachineSchemas,\n DelaySourceMap,\n GuardSourceMap,\n Sources,\n Next_MachineConfig,\n MachineOptions\n} from './types.v6.ts';\nimport {\n describeMachine,\n assertUnreservedSourceName,\n matchesEventDescriptor,\n toStatePath\n} from './utils.ts';\nimport { assertValid } from './validation.ts';\nimport type { ActorLogicValidator } from './validation.types.ts';\n\nconst STATE_IDENTIFIER = '#';\n\nlet emptyCanActor: AnyActor | undefined;\nlet emptyCanActorScope: AnyActorScope | undefined;\n\nfunction getEmptyCanActor(): AnyActor {\n // A minimal inert actor used purely as the `self`/`parent` argument when\n // dry-running transitions for `snapshot.can(...)`. Intentionally not built\n // on `createStepLogic` so `can()` does not pull that machinery into bundles.\n return (emptyCanActor ??= createActor({\n transition: (snapshot: any) => [snapshot, []],\n initialTransition: () => [\n { status: 'active', output: undefined, error: undefined },\n []\n ],\n getInitialSnapshot: () => ({\n status: 'active',\n output: undefined,\n error: undefined\n }),\n getPersistedSnapshot: (snapshot: any) => snapshot\n } as any) as AnyActor);\n}\n\nfunction getEmptyCanActorScope(): AnyActorScope {\n if (emptyCanActorScope) {\n return emptyCanActorScope;\n }\n\n const actor = getEmptyCanActor();\n emptyCanActorScope = {\n self: actor,\n logger: () => {},\n id: '',\n sessionId: '',\n defer: () => {},\n system: actor.system,\n stopChild: () => {},\n emit: () => {},\n actionExecutor: () => {}\n };\n detachedScopes.add(emptyCanActorScope);\n return emptyCanActorScope;\n}\n\nexport type CompatibleProvidedActorSource<\n TExpected extends AnyActorLogic,\n TActual extends AnyActorLogic\n> =\n IsAny<TActual> extends true\n ? TActual\n : [OutputFrom<TActual>] extends [OutputFrom<TExpected>]\n ? [Omit<SnapshotFrom<TActual>, 'input'>] extends [\n Omit<SnapshotFrom<TExpected>, 'input'>\n ]\n ? [InputFrom<TExpected>] extends [InputFrom<TActual>]\n ? [EventFromLogic<TExpected>] extends [EventFromLogic<TActual>]\n ? [EmittedFrom<TActual>] extends [EmittedFrom<TExpected>]\n ? TActual\n : never\n : never\n : never\n : never\n : never;\n\ntype ProvidedActors<\n TExpectedActorMap extends Sources['actors'],\n TProvidedActorMap extends Partial<\n Record<keyof TExpectedActorMap & string, AnyActorLogic>\n >\n> = {\n [K in keyof TProvidedActorMap]: K extends keyof TExpectedActorMap\n ? TProvidedActorMap[K] extends AnyActorLogic\n ? CompatibleProvidedActorSource<\n TExpectedActorMap[K],\n TProvidedActorMap[K]\n >\n : never\n : never;\n};\n\n// A required override replaces its source; an optional override may leave\n// the original source in place. Keep both types in that case.\ntype ProvidedSourceMap<TDeclared, TProvided> = {\n [K in keyof TDeclared]: K extends keyof TProvided\n ? {} extends Pick<TProvided, K>\n ? TDeclared[K] | Exclude<TProvided[K], undefined>\n : Exclude<TProvided[K], undefined>\n : TDeclared[K];\n};\n\n// The action as the machine declared it. A provided action keeps its own type,\n// so integrations can infer from what it returns, and records the declared one,\n// so that the next `provide(...)` is checked against the same contract.\ntype DeclaredAction<T> = T extends {\n readonly '~declaredAction'?: infer TDeclared;\n}\n ? unknown extends TDeclared\n ? T\n : Exclude<TDeclared, undefined>\n : T;\n\ntype ProvidedActionSourceMap<TDeclared, TProvided> = {\n [K in keyof TDeclared]: K extends keyof TProvided\n ? ({} extends Pick<TProvided, K>\n ? TDeclared[K] | Exclude<TProvided[K], undefined>\n : Exclude<TProvided[K], undefined>) & {\n readonly '~declaredAction'?: DeclaredAction<TDeclared[K]>;\n }\n : TDeclared[K];\n};\n\n// Positional arguments must match the declared action. An action declared to\n// return nothing (or a result that admits `void`, as an action only declared\n// in `schemas.actions` does) is an effect: the implementation may return\n// integration-specific values, such as an Effect. Any other declared result,\n// such as a context patch, can be returned from a transition, which applies\n// it, so the implementation must return a compatible one.\nexport type ProvidedActionContracts<T> = {\n [K in keyof T]: DeclaredAction<T[K]> extends (\n ...args: infer TArgs\n ) => infer TResult\n ? (...args: TArgs) => ProvidedActionResult<TResult>\n : never;\n};\n\n// `Extract` keeps the result within `Sources['actions']`, which declared\n// actions already satisfy.\ntype ProvidedActionResult<TResult> = void extends TResult\n ? void\n : Extract<TResult, ReturnType<Sources['actions'][string]>>;\n\nexport { InvalidSnapshotError } from './persistedSnapshotValidation.ts';\n\n/**\n * The development message for an id that matches no state. When a prefix of\n * the id is a state id and the rest resolves beneath it as a relative path,\n * suggests the target's own id.\n */\nfunction describeUnknownStateId(\n idMap: Map<string, AnyStateNode>,\n id: string\n): string {\n const message = `No state has id \"${id}\".`;\n const segments = toStatePath(id);\n for (let i = segments.length - 1; i > 0; i--) {\n let node: AnyStateNode | undefined = idMap.get(\n segments.slice(0, i).join(STATE_DELIMITER)\n );\n for (let j = i; node && j < segments.length; j++) {\n node = node.states?.[segments[j]];\n }\n if (node) {\n return node.config.id\n ? `${message} Use \"#${node.id}\".`\n : `${message} Use \"#${node.id}\", or give that state an id.`;\n }\n }\n return message;\n}\n\n/** @public */\nexport class StateMachine<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TStateValue extends StateValue,\n TTag extends string,\n TInput,\n TOutput,\n TEmitted extends EventObject,\n TMeta extends MetaObject,\n TConfig extends StateSchema,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays'],\n TInternalEvent extends EventObject = never,\n TTransitionMeta extends MetaObject = TMeta\n> implements ActorLogic<\n MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n TEvent,\n TInput,\n AnyActorSystem,\n TEmitted\n> {\n /**\n * Type-only marker for the actor's internal event protocol. `actor.send` and\n * `actor.trigger` read it to drop internal events from the public protocol,\n * so it must survive `stripInternal` into the published declarations. Not\n * `declare` (the build's babel pipeline rejects declare class fields); the\n * one `undefined` property this emits per machine instance is inert.\n */\n readonly _internalEventType!: TInternalEvent;\n /** Type-only marker for transition metadata. Never assigned at runtime. */\n readonly _transitionMetaType!: TTransitionMeta;\n /**\n * Type-only marker for the declared input type. `getInitialSnapshot` takes\n * input optionally, so inferring input from it always adds `undefined`;\n * `InputFrom` reads this carrier instead. Method-shaped so it stays\n * bivariant like `getInitialSnapshot`. Never assigned at runtime.\n */\n readonly _inputType!: { carry(input: TInput): void }['carry'];\n\n /**\n * Type-level carriers for the machine's source maps and state schema. Type\n * helpers in integration packages read these to walk a machine's declared\n * actions, actors and invoked sources. They are never assigned at runtime.\n */\n readonly _actionMap!: TActionMap;\n readonly _actorMap!: TActorMap;\n readonly _stateSchema!: TConfig;\n\n /** The machine's own version. */\n public version: TConfig extends { version: infer TVersion extends string }\n ? TVersion\n : undefined;\n\n public schemas:\n | (TConfig extends { schemas: infer TSchemas extends AnyMachineSchemas }\n ? TSchemas\n : AnyMachineSchemas)\n | undefined;\n\n public sources: Sources;\n\n /** Runtime options for machine execution. */\n public options: MachineOptions;\n\n /** @internal */\n public idMap: Map<string, AnyStateNode> = new Map();\n\n public root: StateNode<TContext, TEvent, TMeta, TTransitionMeta>;\n\n /**\n * Returns the machine itself, never a Proxy wrapped around it (a function\n * member is not wrapped by reactive proxies, so it still closes over the raw\n * instance). Persistence resolves state nodes through it, matching the\n * bound `transition` / `getInitialSnapshot`.\n *\n * @internal\n */\n public readonly _raw: () => this = () => this;\n\n /**\n * The machine's `id`, or the empty string when the config declares none.\n * The root state node has this id; a machine without one has no `#id` root.\n */\n public id: TConfig extends { id: infer TId extends string } ? TId : '';\n\n public states: StateNode<TContext, TEvent, TMeta, TTransitionMeta>['states'];\n public events: Array<EventDescriptor<TEvent>>;\n public internalEventDescriptors: ReadonlyArray<string>;\n /** @internal Skips eventless-selection scans for machines without `always`. */\n public _hasEventlessTransitions: boolean;\n\n /**\n * Adapter hooks for actor-local transition evaluation state. Used by\n * `@xstate/scxml`; not part of the stable API.\n *\n * @experimental\n */\n public _microstepHooks?: AnyStateMachine['_microstepHooks'];\n\n constructor(\n /** The raw config used to create the machine. */\n public config: Next_MachineConfig<\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any // TEmitted\n > & {\n schemas?: AnyMachineSchemas;\n },\n sources?: Sources,\n public validator?: ActorLogicValidator\n ) {\n if (config.version !== undefined && !config.id) {\n // Persisted snapshots record `{ id, version }`; a version needs an id.\n throw new Error(\n isDevelopment\n ? `Machine with version '${config.version}' must declare an id.`\n : xstateError(18, config.version)\n );\n }\n this.id = (config.id ?? '') as typeof this.id;\n this.sources = {\n actors: config.actors ?? {},\n actions: config.actions ?? {},\n delays: (config.delays ?? {}) as Sources['delays'],\n guards: config.guards ?? {},\n ...sources\n };\n if (isDevelopment) {\n for (const kind of ['actions', 'guards', 'actors', 'delays'] as const) {\n for (const key of Object.keys(this.sources[kind])) {\n assertUnreservedSourceName(kind, key);\n }\n }\n }\n this.version = this.config.version as typeof this.version;\n this.schemas = this.config.schemas as typeof this.schemas;\n this.internalEventDescriptors = Object.keys(\n this.schemas?.internalEvents ?? {}\n );\n this.options = { ...this.config.options };\n\n this.transition = this.transition.bind(this);\n this.initialTransition = this.initialTransition.bind(this);\n this.getInitialSnapshot = this.getInitialSnapshot.bind(this);\n this.getPersistedSnapshot = this.getPersistedSnapshot.bind(this);\n this.start = this.start.bind(this);\n\n this.root = new StateNode<TContext, TEvent, TMeta, TTransitionMeta>(\n config as any,\n {\n _key: this.id,\n _machine: this as any\n }\n );\n\n this.root._initialize();\n formatRouteTransitions(this.root);\n this.root._refreshEventMetadata();\n this._hasEventlessTransitions = Array.from(this.idMap.values()).some(\n (stateNode) => !!stateNode.always?.length\n );\n\n this.states = this.root.states; // TODO: remove!\n this.events = this.root.events;\n }\n\n /**\n * Clones this state machine with the provided sources.\n *\n * @param sources Options (`actions`, `guards`, `actors`, `delays`) to\n * recursively merge with the existing options.\n * @returns A new `StateMachine` instance with the provided sources.\n */\n public provide<\n const TProvidedActorMap extends Partial<\n Record<keyof TActorMap & string, AnyActorLogic>\n > = {},\n const TProvidedActionMap extends Partial<\n ProvidedActionContracts<TActionMap>\n > = {}\n >(sources: {\n actions?: TProvidedActionMap &\n Partial<ProvidedActionContracts<TActionMap>> &\n Record<Exclude<keyof TProvidedActionMap, keyof TActionMap>, never>;\n actors?: TProvidedActorMap & ProvidedActors<TActorMap, TProvidedActorMap>;\n // Mapped over the known names (not an index signature) so unknown source\n // names are still rejected, while entries keep typed args/return values.\n guards?: Partial<TGuardMap> & {\n [K in keyof TGuardMap]?: GuardSourceMap<TContext, TEvent>[string];\n };\n // Delays are widened to `number | fn` per entry (not Partial<TDelayMap>)\n // so a fixed delay can be swapped for a computed one and vice versa.\n delays?: {\n [K in keyof TDelayMap]?: DelaySourceMap<TContext, TEvent>[string];\n };\n }): StateMachine<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TInput,\n TOutput,\n TEmitted,\n TMeta,\n TConfig,\n ProvidedActionSourceMap<TActionMap, TProvidedActionMap>,\n ProvidedSourceMap<TActorMap, TProvidedActorMap>,\n TGuardMap,\n TDelayMap,\n TInternalEvent,\n TTransitionMeta\n > {\n const { actions, guards, actors, delays } = this.sources;\n\n const provided = new StateMachine(\n this.config,\n {\n actions: {\n ...actions,\n ...sources.actions\n } as Sources['actions'],\n guards: {\n ...guards,\n ...sources.guards\n } as Sources['guards'],\n actors: {\n ...actors,\n ...sources.actors\n } as Sources['actors'],\n delays: {\n ...delays,\n ...sources.delays\n } as Sources['delays']\n },\n this.validator\n ) as unknown as StateMachine<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TInput,\n TOutput,\n TEmitted,\n TMeta,\n TConfig,\n ProvidedActionSourceMap<TActionMap, TProvidedActionMap>,\n ProvidedSourceMap<TActorMap, TProvidedActorMap>,\n TGuardMap,\n TDelayMap,\n TInternalEvent,\n TTransitionMeta\n >;\n // Providing sources does not change the serializable definition.\n provided._json = this._json;\n provided.internalEventDescriptors = this.internalEventDescriptors;\n provided._microstepHooks = this._microstepHooks;\n return provided;\n }\n\n public resolveState(\n config: {\n value: StateValue;\n context?: TContext;\n historyValue?: HistoryValue;\n status?: SnapshotStatus;\n output?: TOutput;\n error?: unknown;\n } & ([TContext] extends [never]\n ? {}\n : Equals<TContext, MachineContext> extends false\n ? { context: unknown }\n : {})\n ): MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n > {\n const resolvedStateValue = resolveStateValue(this.root, config.value);\n const nodeSet = getAllStateNodes(\n getStateNodes(this.root, resolvedStateValue)\n );\n const nodes = [...nodeSet];\n\n return createMachineSnapshot(\n {\n _nodes: nodes,\n value: resolvedStateValue,\n context: config.context || ({} as TContext),\n children: {},\n status: isInFinalState(nodeSet, this.root)\n ? 'done'\n : config.status || 'active',\n output: config.output,\n error: config.error,\n historyValue: config.historyValue\n },\n this\n ) as MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >;\n }\n\n /**\n * Determines the next snapshot given the current `snapshot` and received\n * `event`. Calculates a full macrostep from all microsteps.\n *\n * @param snapshot The current snapshot\n * @param event The received event\n */\n public transition(\n snapshot: MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n event: TEvent,\n actorScope?: ActorScope<typeof snapshot, TEvent, AnyActorSystem, TEmitted>\n ): ActorLogicTransitionResult<\n MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n ExecutableEffectFrom<this>\n > {\n const usesInertScope = !actorScope;\n const resolvedActorScope = (actorScope ??\n createInertActorScope(\n this,\n snapshot as SnapshotFrom<this>\n )) as NonNullable<typeof actorScope>;\n if (usesInertScope) {\n setInertActorScopeSnapshot(resolvedActorScope, snapshot, false);\n }\n if (this.validator) {\n const sourceRef = actorScope && (actorScope.self as any)._lastSourceRef;\n const eventOrigin = sourceRef ? 'actor' : 'external';\n const error = this.validator.check({\n kind: 'event',\n logic: this,\n event,\n eventOrigin\n });\n if (error) {\n // Boundary fault: an invalid event arriving from outside the machine\n // is rejected (never delivered), not routed to the error channel. The\n // snapshot is returned unchanged; the rejection is represented as an\n // effect so hosts and the actor runtime can report it.\n return [\n snapshot,\n [\n createDeadLetterEffect(\n resolvedActorScope,\n sourceRef,\n event,\n 'invalidEvent',\n {\n issues: (error as { issues?: DeadLetterDetail['issues'] })\n .issues,\n error\n }\n ) as ExecutableEffectFrom<this>\n ]\n ];\n }\n }\n beginSpawnAllocation(resolvedActorScope);\n const fastSnapshot = this._transitionFast(\n snapshot,\n event,\n resolvedActorScope\n );\n if (fastSnapshot) {\n if (usesInertScope) {\n setInertActorScopeSnapshot(resolvedActorScope, fastSnapshot, false);\n }\n const returnedSnapshot =\n usesInertScope && fastSnapshot !== snapshot\n ? attachSnapshotActorRef(resolvedActorScope, fastSnapshot)\n : this._attachPureActorRef(fastSnapshot, resolvedActorScope);\n if (this.validator) {\n assertValid(this.validator, {\n kind: 'result',\n logic: this,\n snapshot: returnedSnapshot,\n effects: []\n });\n }\n return [returnedSnapshot, []];\n }\n\n const { snapshot: nextSnapshot, microsteps } = macrostep(\n snapshot,\n event,\n resolvedActorScope,\n []\n );\n\n if (usesInertScope) {\n setInertActorScopeSnapshot(resolvedActorScope, nextSnapshot, false);\n }\n const returnedSnapshot = usesInertScope\n ? nextSnapshot === snapshot\n ? nextSnapshot\n : attachSnapshotActorRef(resolvedActorScope, nextSnapshot)\n : this._attachPureActorRef(nextSnapshot, resolvedActorScope);\n const effects = this._collectEffects(microsteps);\n if (this.validator) {\n assertValid(this.validator, {\n kind: 'result',\n logic: this,\n snapshot: returnedSnapshot,\n effects\n });\n }\n return [\n returnedSnapshot as MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n effects\n ];\n }\n\n private _collectEffects(\n microsteps: ReadonlyArray<\n readonly [unknown, ReadonlyArray<ExecutableEffect>, ...unknown[]]\n >\n ): ExecutableEffectFrom<this>[] {\n return microsteps.flatMap(\n ([, actions]) => actions\n ) as ExecutableEffectFrom<this>[];\n }\n\n private _attachPureActorRef<TSnapshot extends AnyMachineSnapshot>(\n snapshot: TSnapshot,\n actorScope: AnyActorScope,\n skipInitializingActor = false\n ): TSnapshot {\n if (isInertActorScope(actorScope)) {\n return snapshot;\n }\n if (\n skipInitializingActor &&\n (\n actorScope.self as AnyActor & {\n _actorScope?: AnyActorScope;\n _snapshot?: unknown;\n }\n )._actorScope === actorScope &&\n (actorScope.self as AnyActor & { _snapshot?: unknown })._snapshot ===\n undefined\n ) {\n return snapshot;\n }\n setSnapshotActorRef(snapshot, actorScope.self, actorScope.system);\n return snapshot;\n }\n\n private _transitionFast(\n snapshot: MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n event: TEvent,\n actorScope: ActorScope<typeof snapshot, TEvent, AnyActorSystem, TEmitted>\n ):\n | MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >\n | undefined {\n if (\n snapshot.status !== 'active' ||\n typeof snapshot.value !== 'string' ||\n this.root.always?.length\n ) {\n return undefined;\n }\n\n const sourceNode = this.root.states[snapshot.value];\n if (\n !sourceNode ||\n sourceNode.type !== 'atomic' ||\n sourceNode.exit ||\n sourceNode.invoke.length ||\n sourceNode.always?.length ||\n sourceNode.after?.length\n ) {\n return undefined;\n }\n\n const transitions = sourceNode.transitions.get(event.type);\n if (transitions?.length !== 1) {\n return undefined;\n }\n\n const selected = transitions[0];\n if (\n selected.guard ||\n selected.actions ||\n selected.to ||\n selected.reenter ||\n selected.input ||\n typeof selected.context === 'function' ||\n (selected.target && selected.target.length !== 1)\n ) {\n return undefined;\n }\n\n const targetNode = selected.target?.[0] ?? sourceNode;\n const stateChanged = targetNode !== sourceNode;\n if (\n targetNode.parent !== this.root ||\n targetNode.type !== 'atomic' ||\n (stateChanged &&\n (targetNode.entry ||\n targetNode.invoke.length ||\n targetNode.always?.length ||\n targetNode.after?.length))\n ) {\n return undefined;\n }\n\n const context =\n selected.context !== undefined\n ? ({ ...snapshot.context, ...selected.context } as TContext)\n : snapshot.context;\n\n if (\n !isInertActorScope(actorScope) &&\n (actorScope.system._hasInspectionObservers?.() ?? true)\n ) {\n const collectedMicrosteps =\n ((actorScope.self as any)._collectedMicrosteps as any[]) || [];\n collectedMicrosteps.push(selected);\n (actorScope.self as any)._collectedMicrosteps = collectedMicrosteps;\n }\n\n const rootInput = snapshot._stateInputs[this.root.id];\n return cloneMachineSnapshot(snapshot, {\n ...(context !== snapshot.context ? { context } : {}),\n ...(stateChanged\n ? {\n _nodes: [this.root, targetNode],\n // The source state exited, so only the root input remains.\n _stateInputs: rootInput ? { [this.root.id]: rootInput } : {}\n }\n : {})\n });\n }\n\n /**\n * Determines the next state given the current `state` and `event`. Calculates\n * a microstep.\n *\n * @param state The current state\n * @param event The received event\n */\n public microstep(\n snapshot: MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n event: TEvent,\n actorScope: AnyActorScope\n ): Array<\n MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >\n > {\n const { microsteps } = macrostep(snapshot, event, actorScope, []);\n const snapshots = new Array(microsteps.length);\n\n for (let i = 0; i < microsteps.length; i++) {\n snapshots[i] = microsteps[i][0];\n }\n\n return snapshots;\n }\n\n public getTransitionData(\n snapshot: MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n event: TEvent,\n actorScope: AnyActorScope,\n selectionResults?: TransitionSelectionResults\n ): Array<AnyTransitionDefinition> {\n this._microstepHooks?.begin(actorScope.self);\n return (\n transitionNode(\n this.root,\n snapshot.value,\n snapshot,\n event,\n actorScope,\n selectionResults\n ) || []\n );\n }\n\n public isInternalEventType(eventType: string): boolean {\n if (eventType === XSTATE_TIMER) {\n return true;\n }\n for (const descriptor of this.internalEventDescriptors) {\n if (matchesEventDescriptor(eventType, descriptor)) {\n return true;\n }\n }\n\n return false;\n }\n\n /**\n * Determines whether sending the `event` to the given snapshot would select a\n * non-forbidden transition. Backs `snapshot.can(...)`; lives here so that\n * non-machine bundles don't pay for the transition-resolution machinery.\n *\n * @internal\n */\n public _canTransition(snapshot: AnyMachineSnapshot, event: TEvent): boolean {\n if (snapshot.status !== 'active') {\n return false;\n }\n const emptyActorScope = getEmptyCanActorScope();\n const transitionData = this.getTransitionData(\n snapshot as any,\n event,\n emptyActorScope\n );\n\n if (!transitionData?.length) {\n return false;\n }\n\n // Check that at least one transition is not forbidden\n for (const transition of transitionData) {\n if (transition.target !== undefined) {\n return true;\n }\n\n const res = getTransitionResult(\n transition,\n snapshot,\n event,\n emptyActorScope,\n { resolveActions: false }\n );\n if (\n res.targets?.length ||\n res.context ||\n hasEffect(\n transition,\n snapshot.context,\n event,\n snapshot,\n emptyActorScope\n )\n ) {\n return true;\n }\n }\n\n return false;\n }\n\n /**\n * Returns the error event that the actor should transition with to recover\n * from an execution error, if any active state node declares `onError`.\n *\n * @internal\n */\n public getExecutionErrorEvent(\n snapshot: MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n error: unknown\n ): TEvent | undefined {\n if (\n (snapshot as any)?.status !== 'active' ||\n !snapshot.nodes?.some((stateNode) => stateNode.config.onError)\n ) {\n return undefined;\n }\n return createErrorPlatformEvent('execution', error) as unknown as TEvent;\n }\n\n /**\n * The initial state _before_ evaluating any microsteps. This \"pre-initial\"\n * state is provided to initial actions executed in the initial state.\n *\n * @internal\n */\n _getPreInitialState(\n actorScope: AnyActorScope,\n initEvent: any\n ): MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n > {\n const { context } = this.config;\n\n const preInitial = createMachineSnapshot(\n {\n context:\n typeof context !== 'function' && context ? context : ({} as TContext),\n _nodes: [this.root],\n children: {},\n status: 'active'\n },\n this\n );\n\n if (typeof context === 'function') {\n const children = {};\n const spawn = createSpawner(actorScope, this.sources.actors, children);\n const resolvedContext = context(\n withActorSelf(\n {\n spawn,\n input: initEvent.input,\n actors: this.sources.actors\n },\n actorScope\n )\n );\n const [nextState] = resolveActionsWithContext(\n preInitial,\n initEvent,\n actorScope,\n []\n ) as any;\n if (resolvedContext) {\n nextState.context = resolvedContext;\n if (isDevelopment) {\n freezeContext(resolvedContext);\n }\n }\n if (Object.keys(children).length > 0) {\n nextState.children = {\n ...nextState.children,\n ...children\n };\n // Commit the transaction counters so context-factory allocations\n // persist with the snapshot: a freed id is never handed out again\n // after a restore or in a fresh replay process. (The spawner already\n // registered each child for string-id resolution.)\n const counters = takeSpawnAllocationCounters(actorScope);\n if (counters) {\n nextState._nextActorIds = mergeActorIdCounters(\n nextState._nextActorIds,\n counters\n );\n }\n }\n return nextState as SnapshotFrom<this>;\n }\n\n return preInitial as SnapshotFrom<this>;\n }\n\n /**\n * Returns the initial `State` instance, with reference to `self` as an\n * `ActorRef`.\n */\n public getInitialSnapshot(\n actorScope?: ActorScope<\n MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n TEvent,\n AnyActorSystem,\n TEmitted\n >,\n input?: TInput\n ): MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n > {\n return this.initialTransition(input, actorScope)[0];\n }\n\n public initialTransition(\n input: TInput | undefined,\n actorScope?: ActorScope<\n MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n TEvent,\n AnyActorSystem,\n TEmitted\n >\n ): ActorLogicTransitionResult<\n MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n ExecutableEffectFrom<this>\n > {\n if (this.validator) {\n assertValid(this.validator, {\n kind: 'input',\n logic: this,\n input\n });\n }\n const usesInertScope = !actorScope;\n const resolvedActorScope = (actorScope ??\n createInertActorScope(this)) as NonNullable<typeof actorScope>;\n beginSpawnAllocation(resolvedActorScope);\n const initEvent = createInitEvent(input) as unknown as TEvent; // TODO: fix;\n const internalQueue: AnyEventObject[] = [];\n const finalizeInitialResult = (\n macroState: AnyMachineSnapshot,\n microsteps: ReadonlyArray<\n readonly [unknown, ReadonlyArray<ExecutableEffect>, ...unknown[]]\n >\n ): ActorLogicTransitionResult<\n SnapshotFrom<this>,\n ExecutableEffectFrom<this>\n > => {\n if (usesInertScope) {\n setInertActorScopeSnapshot(resolvedActorScope, macroState, false);\n }\n const returnedSnapshot = usesInertScope\n ? attachSnapshotActorRef(resolvedActorScope, macroState)\n : this._attachPureActorRef(macroState, resolvedActorScope, true);\n const effects = this._collectEffects(microsteps);\n // Error snapshots may carry synthetic context (e.g. when the context\n // factory throws); validating them would mask the original error.\n if (this.validator && macroState.status !== 'error') {\n assertValid(this.validator, {\n kind: 'result',\n logic: this,\n snapshot: returnedSnapshot,\n effects\n });\n }\n return [returnedSnapshot as SnapshotFrom<this>, effects];\n };\n\n let preInitialState: AnyMachineSnapshot;\n try {\n preInitialState = this._getPreInitialState(resolvedActorScope, initEvent);\n } catch (error) {\n // Keep the machine snapshot shape (e.g. `matches`) on error snapshots\n // when initialization (e.g. the context factory) throws.\n const errorSnapshot = cloneMachineSnapshot(\n createMachineSnapshot(\n {\n context:\n typeof this.config.context !== 'function' && this.config.context\n ? this.config.context\n : ({} as TContext),\n _nodes: [this.root],\n children: {},\n status: 'active'\n },\n this\n ),\n { status: 'error', error }\n );\n return finalizeInitialResult(errorSnapshot, []);\n }\n const contextSpawnEffects = Object.values(preInitialState.children)\n .filter(Boolean)\n .map((actor) => createSpawnEffect(actor as AnyActor));\n\n try {\n const [nextState, initialActions] = initialMicrostep(\n this.root,\n preInitialState,\n resolvedActorScope,\n initEvent,\n internalQueue\n );\n\n const { snapshot: macroState, microsteps } = macrostep(\n nextState,\n initEvent as AnyEventObject,\n resolvedActorScope,\n internalQueue,\n [\n [nextState, [...contextSpawnEffects, ...initialActions]] as [\n AnyMachineSnapshot,\n ExecutableEffect[]\n ]\n ]\n );\n return finalizeInitialResult(macroState, microsteps);\n } catch (err) {\n if (!this.root.config.onError) {\n throw err;\n }\n const errorEvent = createErrorPlatformEvent('execution', err);\n const errorMacrostep = macrostep(\n preInitialState,\n errorEvent,\n resolvedActorScope,\n [],\n [\n [preInitialState, contextSpawnEffects] as [\n AnyMachineSnapshot,\n ExecutableEffect[]\n ]\n ]\n );\n return finalizeInitialResult(\n errorMacrostep.snapshot,\n errorMacrostep.microsteps\n );\n }\n }\n\n public start(\n snapshot?: MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n actorScope?: ActorScope<\n MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n TEvent,\n AnyActorSystem,\n TEmitted\n >\n ): void {\n // Start rehydrated children that were active when persisted. Freshly\n // invoked/spawned children are NOT started here — they start via deferred\n // `@xstate.start` actions so sync start errors route to `onError`.\n if (!snapshot?.children) {\n return;\n }\n const children = snapshot.children as unknown as Record<string, AnyActor>;\n for (const childId in children) {\n if (!Object.hasOwn(children, childId)) {\n continue;\n }\n const child = children[childId];\n if (\n (child as any)._rehydrated &&\n (child as any).getSnapshot?.().status === 'active'\n ) {\n if (actorScope) {\n actorScope.actionExecutor(createStartEffect(child));\n } else {\n void child.system.startActor(child);\n }\n }\n }\n }\n\n public getStateNodeById(\n stateId: string\n ): StateNode<TContext, TEvent, TMeta, TTransitionMeta> {\n // `#id` is an exact id lookup: the text after `#` is never split into a\n // path. It names a state's explicit `id` or its implicit id.\n const hasPrefix = isStateId(stateId);\n const id = hasPrefix ? stateId.slice(STATE_IDENTIFIER.length) : stateId;\n\n if (id === '' && hasPrefix) {\n throw new Error(\n !isDevelopment\n ? xstateError(19, this.id)\n : this.id\n ? `State id '#' is empty. Target the root of ${describeMachine(this.id)} with '#${this.id}'.`\n : \"State id '#' is empty: the root of a machine without an `id` cannot be referenced by id. Give the machine an `id` to reference its root as '#<id>'.\"\n );\n }\n const stateNode = this.idMap.get(id);\n if (stateNode) {\n return stateNode as StateNode<TContext, TEvent, TMeta, TTransitionMeta>;\n }\n throw new Error(\n isDevelopment\n ? describeUnknownStateId(this.idMap, id)\n : xstateError(20, id)\n );\n }\n\n public getPersistedSnapshot(\n snapshot: MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n options?: unknown\n ) {\n return getPersistedSnapshot(snapshot, options);\n }\n\n /**\n * The original JSON definition this machine was created from (set by\n * `machineFromJSON`), if any. Used by `machineToJSON` for lossless\n * round-trips.\n *\n * @internal\n */\n public _json?: Record<string, unknown>;\n}\n","import {\n allocateChildId,\n assertChildIdFree,\n reserveChildId\n} from './transitionActions.ts';\nimport { resolveRegisteredActorSource } from './actorSource.ts';\nimport {\n ActorFromLogic,\n AnyActorLogic,\n AnyActorRef,\n AnyActorScope,\n InputFrom,\n RegistryKeyForLogic,\n SystemRegistry,\n type RequiredLogicInput\n} from './types.ts';\nimport type { ConditionalRequired, IsNotNever } from './typeUtils.ts';\n\n/** @public */\nexport type Spawner<TSystemRegistry extends SystemRegistry = SystemRegistry> = <\n TLogic extends AnyActorLogic\n>(\n src: TLogic,\n ...[options]: ConditionalRequired<\n [\n options?: {\n id?: string;\n registryKey?: RegistryKeyForLogic<TLogic, TSystemRegistry>;\n input?: InputFrom<TLogic>;\n syncSnapshot?: boolean;\n } & { [K in RequiredLogicInput<TLogic>]: InputFrom<TLogic> }\n ],\n IsNotNever<RequiredLogicInput<TLogic>>\n >\n) => ActorFromLogic<TLogic>;\n\nexport function createSpawner(\n actorScope: AnyActorScope,\n actors: Record<string, AnyActorLogic>,\n spawnedChildren: Record<string, AnyActorRef>\n): Spawner {\n return ((src, options) => {\n const referencedSrc = resolveRegisteredActorSource(actors, src);\n // Generated ids come from the same transaction allocator as `enq.spawn`,\n // so context-factory allocations persist with the snapshot and never\n // collide with later spawns.\n const id =\n options?.id ?? allocateChildId(actorScope, referencedSrc ?? src).id;\n if (options?.id !== undefined) {\n assertChildIdFree(actorScope, options.id);\n reserveChildId(actorScope, options.id);\n }\n const actor = actorScope.system.createActorRef(src, {\n id,\n parent: actorScope.self,\n syncSnapshot: options?.syncSnapshot,\n input: options?.input,\n src: referencedSrc ?? src,\n registryKey: options?.registryKey\n });\n spawnedChildren[actor.id] = actor;\n return actor;\n }) as Spawner;\n}\n","import type { PublicEventFromMachine } from './eventTypes.ts';\nimport type { PersistedMachineSnapshot } from './machineVersion.types.ts';\nimport {\n isSnapshotRecord,\n validatePersistedSnapshot\n} from './persistedSnapshotValidation.ts';\nimport type { StandardSchemaV1 } from './schema.types.ts';\nimport type {\n AnyStateMachine,\n ContextFrom,\n EventFrom,\n EventObject,\n Snapshot\n} from './types.ts';\nimport { matchesEventDescriptor } from './utils.ts';\n\ntype PublicEventOf<TMachine extends AnyStateMachine> = PublicEventFromMachine<\n EventFrom<TMachine>,\n TMachine extends { _internalEventType: infer TInternal extends EventObject }\n ? TInternal\n : never\n>;\n\n/** @public */\nexport type MachinePersistedSnapshotSchema<TMachine extends AnyStateMachine> =\n StandardSchemaV1<\n unknown,\n Snapshot<unknown> &\n PersistedMachineSnapshot & { context: ContextFrom<TMachine> }\n >;\n\nfunction findEventSchema(\n schemas: Record<string, StandardSchemaV1> | undefined,\n eventType: string\n): StandardSchemaV1 | undefined {\n if (!schemas) {\n return undefined;\n }\n\n if (Object.hasOwn(schemas, eventType)) {\n return schemas[eventType];\n }\n\n const descriptor = Object.keys(schemas).find((key) =>\n matchesEventDescriptor(eventType, key)\n );\n return descriptor === undefined ? undefined : schemas[descriptor];\n}\n\nfunction memo<T>(cache: WeakMap<object, T>, key: object, create: () => T): T {\n let value = cache.get(key);\n if (!value) {\n cache.set(key, (value = create()));\n }\n return value;\n}\n\nconst snapshotSchemas = new WeakMap<object, StandardSchemaV1>();\nconst historicalEventSchemas = new WeakMap<object, StandardSchemaV1>();\nconst eventSchemas = new WeakMap<object, StandardSchemaV1>();\n\n/**\n * Standard Schema for snapshots persisted by `machine` (its version): checks\n * the snapshot structure against the machine's states and children, and the\n * context against `schemas.context`.\n *\n * @public\n */\nexport function snapshotSchema<TMachine extends AnyStateMachine>(\n machine: TMachine\n): MachinePersistedSnapshotSchema<TMachine> {\n return memo(\n snapshotSchemas,\n machine,\n (): MachinePersistedSnapshotSchema<TMachine> => ({\n '~standard': {\n version: 1,\n vendor: 'xstate',\n validate: async (value) => {\n if (value === null || typeof value !== 'object') {\n return { issues: [{ message: 'Expected a persisted snapshot.' }] };\n }\n const snapshot: Record<string, unknown> = {\n historyValue: {},\n timers: [],\n ...(value as Record<string, unknown>)\n };\n const contextSchema = machine.schemas?.context;\n let context = snapshot.context;\n if (contextSchema) {\n const result = await contextSchema['~standard'].validate(context);\n if (result.issues) {\n return {\n issues: [\n {\n message: `Invalid context for machine '${machine.id}' version '${machine.version}': ${result.issues[0]?.message}`\n }\n ]\n };\n }\n context = result.value;\n }\n for (const key of ['value', 'children'] as const) {\n if (!(key in snapshot)) {\n return {\n issues: [{ message: `Persisted snapshot is missing '${key}'.` }]\n };\n }\n }\n if (\n !['active', 'done', 'error', 'stopped'].includes(\n snapshot.status as string\n )\n ) {\n return {\n issues: [{ message: 'Persisted snapshot has invalid status.' }]\n };\n }\n if (!isSnapshotRecord(snapshot.historyValue)) {\n return {\n issues: [\n { message: \"Persisted snapshot has invalid 'historyValue'.\" }\n ]\n };\n }\n try {\n validatePersistedSnapshot(machine, snapshot);\n } catch (error) {\n return {\n issues: [\n {\n message:\n error instanceof Error\n ? error.message\n : 'Persisted snapshot has invalid state value.'\n }\n ]\n };\n }\n return {\n value: { ...snapshot, context } as Snapshot<unknown> &\n PersistedMachineSnapshot & { context: ContextFrom<TMachine> }\n };\n }\n }\n })\n ) as MachinePersistedSnapshotSchema<TMachine>;\n}\n\n/**\n * @internal Standard Schema for events in a machine's history, including\n * internal and runtime events that public input excludes.\n */\nexport function historicalEventSchema(\n machine: AnyStateMachine\n): StandardSchemaV1<unknown, EventObject> {\n return memo(\n historicalEventSchemas,\n machine,\n (): StandardSchemaV1<unknown, EventObject> => ({\n '~standard': {\n version: 1,\n vendor: 'xstate',\n validate: async (value) => {\n if (\n value === null ||\n typeof value !== 'object' ||\n typeof (value as EventObject).type !== 'string'\n ) {\n return { issues: [{ message: 'Expected an event object.' }] };\n }\n const event = value as EventObject;\n const eventSchemas = machine.schemas?.events;\n const internalEventSchemas = machine.schemas?.internalEvents;\n const isFrameworkEvent =\n event.type.startsWith('xstate.') ||\n event.type.startsWith('@xstate.');\n const schema =\n findEventSchema(internalEventSchemas, event.type) ??\n findEventSchema(eventSchemas, event.type);\n if (\n (eventSchemas || internalEventSchemas) &&\n !schema &&\n !isFrameworkEvent\n ) {\n return {\n issues: [\n {\n message: `Unknown event '${event.type}' for machine '${machine.id}' version '${machine.version}'.`\n }\n ]\n };\n }\n if (!schema) {\n return { value: event as EventObject };\n }\n const { type, ...payload } = event;\n const result = await schema['~standard'].validate(payload);\n if (result.issues) {\n return result;\n }\n if (result.value === null || typeof result.value !== 'object') {\n return { issues: [{ message: 'Expected an event payload.' }] };\n }\n return { value: { ...result.value, type } as EventObject };\n }\n }\n })\n ) as StandardSchemaV1<unknown, EventObject>;\n}\n\n/**\n * Standard Schema for complete public input events of `machine`; excludes\n * internal and runtime events.\n *\n * @public\n */\nexport function eventSchema<TMachine extends AnyStateMachine>(\n machine: TMachine\n): StandardSchemaV1<unknown, PublicEventOf<TMachine>> {\n return memo(\n eventSchemas,\n machine,\n (): StandardSchemaV1<unknown, PublicEventOf<TMachine>> => ({\n '~standard': {\n version: 1,\n vendor: 'xstate',\n validate: async (value) => {\n const event = value as EventObject;\n if (event && typeof event.type === 'string') {\n const internal = findEventSchema(\n machine.schemas?.internalEvents,\n event.type\n );\n const framework =\n event.type.startsWith('xstate.') ||\n event.type.startsWith('@xstate.');\n if (internal || framework) {\n if (!internal && event.type === 'xstate.route') {\n const result =\n await historicalEventSchema(machine)['~standard'].validate(\n value\n );\n if (result.issues) {\n return result;\n }\n const to = (result.value as EventObject & { to?: unknown }).to;\n const route =\n typeof to === 'string' && to.startsWith('#')\n ? machine.idMap.get(to.slice(1))\n : undefined;\n if (\n route &&\n route !== machine.root &&\n route.config.id &&\n route.config.route\n ) {\n return {\n value: result.value as PublicEventOf<TMachine>\n };\n }\n }\n return {\n issues: [\n {\n message: `Event '${event.type}' is not a public input event.`\n }\n ]\n };\n }\n }\n return historicalEventSchema(machine)['~standard'].validate(\n value\n ) as Promise<StandardSchemaV1.Result<PublicEventOf<TMachine>>>;\n }\n }\n })\n ) as StandardSchemaV1<unknown, PublicEventOf<TMachine>>;\n}\n","import { upgradeLegacyPersistedSnapshot } from '../legacySnapshot.ts';\nimport isDevelopment from '#is-development';\nimport { Actor } from '../createActor.ts';\nimport { diagnoseActorOptions } from '../devDiagnostics.ts';\nimport { createInvokeTimeoutEvent } from '../eventUtils.ts';\nimport {\n attachSnapshotActorRef,\n createInertActorScope,\n isInertActorScope,\n setInertActorScopeSnapshot\n} from '../inertActorScope.ts';\nimport { setSnapshotActorRef } from '../snapshotActorRef.ts';\nimport { describeMachine } from '../utils.ts';\nimport { xstateError } from '../xstateError.ts';\nimport {\n InvalidSnapshotError,\n validatePersistedSnapshot\n} from '../persistedSnapshotValidation.ts';\nimport {\n createRemoteActorRef,\n isSerializedActorRef\n} from '../remoteActorRef.ts';\nimport { cloneMachineSnapshot, createMachineSnapshot } from '../State.ts';\nimport { StateMachine } from '../StateMachine.ts';\nimport { StateNode } from '../StateNode.ts';\nimport { parseGeneratedActorId } from '../system.ts';\nimport type {\n ActorOptions,\n ActorRestoreHook,\n AnyActor,\n AnyActorLogic,\n AnyActorScope,\n AnyEventObject,\n AnyMachineSnapshot,\n AnyStateMachine,\n AnyStateNode,\n EventObject,\n HistoryValue,\n LogicalTimer,\n RestorablePersistedSnapshotFor,\n Snapshot,\n SnapshotFrom\n} from '../types.ts';\n\nexport { snapshotSchema } from '../machineSchemas.ts';\nexport type { MachinePersistedSnapshotSchema } from '../machineSchemas.ts';\n\n/**\n * Options for {@link restoreActor}: the {@link ActorOptions} of `createActor`\n * except `input` (a restored actor resumes, it does not initialize).\n *\n * @public\n */\nexport type RestoreActorOptions<TLogic extends AnyActorLogic> = Omit<\n ActorOptions<TLogic>,\n 'input'\n> & {\n /** Restores the actor into this system (from `createSystem()`). */\n system?: { createActor: (logic: any, options?: any) => AnyActor };\n};\n\n/**\n * Creates an actor that resumes from a persisted snapshot instead of starting\n * fresh. Works for any actor logic. Machine snapshots are validated, migrated\n * (`migrate` in the machine config) and their invoked/spawned children are\n * restored recursively.\n *\n * A snapshot that cannot be restored produces an actor whose snapshot has\n * `status: 'error'`.\n *\n * @example\n *\n * ```ts\n * import { restoreActor } from 'xstate/persist';\n *\n * const actor = restoreActor(machine, persistedSnapshot).start();\n * ```\n *\n * @public\n */\nexport function restoreActor<TLogic extends AnyActorLogic>(\n logic: TLogic,\n persistedSnapshot: Snapshot<unknown> &\n Partial<RestorablePersistedSnapshotFor<NoInfer<TLogic>>>,\n options?: RestoreActorOptions<TLogic>\n): Actor<TLogic> {\n const { system, ...actorOptions } = options ?? {};\n diagnoseActorOptions(actorOptions);\n const resolvedOptions = {\n ...actorOptions,\n _restore: createRestoreHook(logic, persistedSnapshot)\n } as ActorOptions<TLogic>;\n return system\n ? (system.createActor(logic, resolvedOptions) as Actor<TLogic>)\n : new Actor(logic, resolvedOptions);\n}\n\n/**\n * @internal Restores `persisted` for any actor logic: machines through\n * {@link restoreMachineSnapshot}, other logic through its own\n * `restoreSnapshot` (or verbatim).\n */\nexport function restoreLogicSnapshot<TLogic extends AnyActorLogic>(\n logic: TLogic,\n persisted: unknown,\n actorScope?: AnyActorScope\n): SnapshotFrom<TLogic> {\n if (logic instanceof StateMachine) {\n return restoreMachineSnapshot(\n logic,\n persisted as Snapshot<unknown>,\n actorScope\n ) as SnapshotFrom<TLogic>;\n }\n // Only `undefined` means \"no snapshot\": an explicit `null` (or another\n // non-object) is a malformed snapshot the logic reports.\n if (!logic.restoreSnapshot && persisted === null) {\n throw new Error(\n isDevelopment ? 'Persisted snapshot must be an object.' : xstateError(46)\n );\n }\n return logic.restoreSnapshot\n ? logic.restoreSnapshot(persisted as Snapshot<unknown>, actorScope)\n : (persisted as SnapshotFrom<TLogic>);\n}\n\nfunction createRestoreHook(\n logic: AnyActorLogic,\n persisted: unknown\n): ActorRestoreHook {\n return {\n restore: (actorScope) => restoreLogicSnapshot(logic, persisted, actorScope),\n error: (error) =>\n logic instanceof StateMachine\n ? createRestoreErrorSnapshot(logic, persisted, error)\n : undefined\n };\n}\n\n/**\n * Builds a machine-shaped `'error'` snapshot (root configuration, no children)\n * for a persisted snapshot that failed to restore, so consumers keep\n * `matches()`, `can()` and friends.\n */\nfunction createRestoreErrorSnapshot(\n machine: AnyStateMachine,\n persisted: unknown,\n error: unknown\n): AnyMachineSnapshot {\n const context = (persisted as { context?: unknown } | undefined)?.context;\n return cloneMachineSnapshot(\n createMachineSnapshot(\n {\n context: context && typeof context === 'object' ? context : {},\n _nodes: [machine.root],\n children: {},\n status: 'active'\n },\n machine\n ),\n { status: 'error', error }\n ) as any;\n}\n\n/**\n * @internal Restores a persisted machine snapshot: validates it, runs\n * `migrate` on version mismatch, recursively restores children (remote\n * children become address handles) and revives timers, history and actor refs\n * in context.\n */\nexport function restoreMachineSnapshot<TMachine extends AnyStateMachine>(\n machine: TMachine,\n snapshot: Snapshot<unknown>,\n actorScope?: AnyActorScope\n): SnapshotFrom<TMachine> {\n // A reactive Proxy wraps state nodes but bound transitions use raw nodes.\n // Normalize here for both restoreActor and direct callers.\n if (machine instanceof StateMachine) {\n machine = machine._raw() as TMachine;\n }\n // TODO(v7): remove with legacySnapshot.ts.\n snapshot = upgradeLegacyPersistedSnapshot(snapshot);\n const usesInertScope = !actorScope;\n const resolvedActorScope = (actorScope ??\n createInertActorScope(machine)) as AnyActorScope;\n if (!snapshot || typeof snapshot !== 'object' || Array.isArray(snapshot)) {\n throw new InvalidSnapshotError(\n isDevelopment\n ? `Persisted snapshot for ${describeMachine(machine.id)} must be an object.`\n : xstateError(24, machine.id)\n );\n }\n const snapshotMachine = (snapshot as any).machine;\n // A live machine snapshot carries its producing machine so helpers such as\n // `matches()` can resolve state nodes. That runtime association is not the\n // persisted `{ id, version }` identity written by getPersistedSnapshot().\n const persistedMachine =\n snapshotMachine &&\n typeof snapshotMachine === 'object' &&\n typeof snapshotMachine.transition === 'function' &&\n 'root' in snapshotMachine\n ? undefined\n : snapshotMachine;\n const legacyPersistedVersion: string | undefined = (snapshot as any).version;\n const persistedVersion: string | undefined =\n typeof persistedMachine?.version === 'string'\n ? persistedMachine.version\n : legacyPersistedVersion;\n if (\n legacyPersistedVersion !== undefined &&\n persistedMachine?.version !== undefined &&\n persistedMachine.version !== legacyPersistedVersion\n ) {\n throw new Error(\n isDevelopment\n ? `Persisted snapshot version '${legacyPersistedVersion}' conflicts with machine version '${persistedMachine.version}'.`\n : xstateError(34, legacyPersistedVersion, persistedMachine.version)\n );\n }\n if (\n persistedMachine &&\n typeof persistedMachine.id === 'string' &&\n persistedMachine.id !== machine.id\n ) {\n throw new Error(\n isDevelopment\n ? `Machine ID mismatch: persisted snapshot was created by machine '${persistedMachine.id}', but machine '${machine.id}' was provided.`\n : xstateError(35, persistedMachine.id, machine.id)\n );\n }\n if (persistedVersion !== machine.version) {\n const migrate = (machine.config as any).migrate;\n if (typeof migrate !== 'function') {\n throw new Error(\n isDevelopment\n ? `Persisted snapshot version '${persistedVersion}' does not match machine version '${machine.version}' for machine '${machine.id}'. Provide a \\`migrate(persistedSnapshot, fromVersion)\\` function in the machine config to migrate old snapshots.`\n : xstateError(36, persistedVersion, machine.version)\n );\n }\n snapshot = migrate(snapshot, persistedVersion);\n }\n\n const snapshotData = snapshot as any;\n const { nodes, childLogics } = validatePersistedSnapshot(\n machine,\n snapshotData\n );\n const children: Record<string, AnyActor> = {};\n const snapshotChildren: Record<\n string,\n {\n src?: string | AnyActorLogic;\n snapshot?: Snapshot<unknown>;\n address?: string;\n remote?: boolean;\n incarnation?: string;\n syncSnapshot?: boolean;\n registryKey?: string;\n }\n > = snapshotData.children;\n\n for (const actorId of Object.keys(snapshotChildren)) {\n const actorData = snapshotChildren[actorId];\n\n if (actorData.remote === true && actorData.address !== undefined) {\n if (typeof actorData.src !== 'string') {\n // Fail loudly instead of fabricating a source key that hosts would\n // route by.\n throw new Error(\n isDevelopment\n ? `Unable to restore remote child '${actorId}': a child referenced by address requires a registered source key.`\n : xstateError(28, actorId)\n );\n }\n // The child's state lives with another runtime; restore a\n // location-transparent handle constructed from its identity alone.\n // The handle keeps its persisted address verbatim: the owning\n // runtime's identity for the child wins over the local parent chain.\n const handle = createRemoteActorRef(resolvedActorScope.system, {\n id: actorId,\n address: actorData.address,\n src: actorData.src,\n parent: resolvedActorScope.self,\n registryKey: actorData.registryKey,\n syncSnapshot: actorData.syncSnapshot,\n incarnation: actorData.incarnation\n });\n if (actorData.registryKey) {\n resolvedActorScope.system._set(actorData.registryKey, handle);\n }\n children[actorId] = handle;\n continue;\n }\n\n const childState = actorData.snapshot;\n const src = actorData.src;\n\n const logic = childLogics.get(actorId)!;\n\n const actor = resolvedActorScope.system.createActorRef(logic, {\n id: actorId,\n parent: resolvedActorScope.self,\n syncSnapshot: actorData.syncSnapshot,\n ...(childState !== undefined\n ? { _restore: createRestoreHook(logic, childState) }\n : {}),\n src,\n registryKey: actorData.registryKey\n });\n // Mark so `start()` knows to start this child (freshly invoked/spawned\n // children are started via deferred `@xstate.start` actions instead).\n (actor as any)._rehydrated = true;\n if (src === undefined) {\n (actor as any)._invoked = true;\n }\n\n children[actorId] = actor;\n }\n\n const timers: LogicalTimer[] = [];\n const persistedTimers: Array<{\n id?: string;\n seq?: number;\n delay: number;\n type: '@xstate.raise' | '@xstate.sendTo';\n event: EventObject;\n target: string | { type: 'parent' };\n scheduledAt?: number;\n }> = snapshotData.timers ?? [];\n for (const timer of persistedTimers) {\n let event = timer.event;\n if (event.type === 'xstate.timeout.actor') {\n const actorId = (event as AnyEventObject).actorId as string;\n const child = children[actorId];\n if (child) {\n event = createInvokeTimeoutEvent(actorId, child.sessionId);\n }\n }\n const target =\n typeof timer.target === 'string'\n ? timer.target === 'self'\n ? 'self'\n : children[timer.target]\n : isSerializedActorRef(timer.target)\n ? (timer.target as unknown as AnyActor)\n : resolvedActorScope.self._parent;\n if (!target) {\n const targetDescription =\n typeof timer.target === 'string'\n ? timer.target\n : (timer.target as { type: string }).type;\n throw new InvalidSnapshotError(\n isDevelopment\n ? `Unable to restore timer ${timer.id !== undefined ? `'${timer.id}'` : `for event '${timer.event.type}'`}: target actor '${targetDescription}' is unavailable.`\n : xstateError(33, targetDescription)\n );\n }\n timers.push({ ...timer, event, target });\n }\n\n const reviveHistoryValue = (\n historyValue: Record<string, ({ id: string } | AnyStateNode)[]>\n ): HistoryValue => {\n if (!historyValue || typeof historyValue !== 'object') {\n return {};\n }\n const revived: HistoryValue = {};\n for (const key of Object.keys(historyValue)) {\n const arr = historyValue[key];\n\n for (const item of arr) {\n let resolved: AnyStateNode | undefined;\n\n if (item instanceof StateNode) {\n resolved = item;\n } else {\n try {\n resolved = machine.getStateNodeById(item.id);\n } catch {\n if (isDevelopment) {\n console.warn(`Could not resolve StateNode for id: ${item.id}`);\n }\n }\n }\n\n if (!resolved) {\n continue;\n }\n\n revived[key] ??= [];\n revived[key].push(resolved);\n }\n }\n return revived;\n };\n\n const revivedHistoryValue = reviveHistoryValue(snapshotData.historyValue);\n\n if (isDevelopment && snapshotData.status === 'active') {\n // Restored snapshots are opaque: eventless transitions are not\n // re-evaluated on restore. Detected structurally; guards never run.\n const eventlessNode = nodes.find(\n (node) => node.always?.length || node.type === 'choice'\n );\n if (eventlessNode) {\n console.warn(\n `Restored snapshot is in state \"${eventlessNode.id}\" which has eventless transitions; they are not re-evaluated until the next event`\n );\n }\n }\n\n const {\n version: _persistedSnapshotVersion,\n // The legacy system-wide counter: superseded by per-snapshot\n // `_nextActorIds` plus the child-id fold below; dropped so old and new\n // snapshots round-trip to the same shape.\n _nextActorId: _legacyNextActorId,\n nextTimerId,\n nextActorIds,\n stateInputs: _persistedStateInputs,\n ...persistedRest\n } = snapshot as any;\n // Fold generated-shaped child ids into the counters as a floor: snapshots\n // persisted before per-actor counters (or hand-crafted ones) still must\n // never reuse a live child's id.\n let restoredCounters: Record<string, number> | undefined = nextActorIds;\n for (const childId of Object.keys(snapshotChildren)) {\n const generated = parseGeneratedActorId(childId);\n if (\n generated &&\n (restoredCounters?.[generated.prefix] ?? 0) <= generated.index\n ) {\n restoredCounters = {\n ...restoredCounters,\n [generated.prefix]: generated.index + 1\n };\n }\n }\n // Revive actor-ref references into a copy: the persisted snapshot is\n // caller-owned and is never mutated or frozen. Only plain objects and\n // arrays are copied; other values are kept as is.\n const revived = new Map<object, unknown>();\n\n function reviveContext(value: any, isRoot = false): any {\n if (!value || typeof value !== 'object') {\n return value;\n }\n // The context object itself is data, never a serialized actor ref.\n // Only an object whose keys are exactly `@actor` (+ `incarnation`)\n // is a serialized ref; any other object is data.\n if (!isRoot && isSerializedActorRef(value)) {\n // A ref that names one of this snapshot's children revives to that\n // child; restored children are new incarnations, so a ref pinned to\n // an incarnation stays data. Any other ref (e.g. a `replyTo` from an\n // event) stays data and routes by address.\n if (value.incarnation !== undefined) {\n return value;\n }\n return (\n Object.values(children).find(\n (child) => child.address === value['@actor']\n ) ?? value\n );\n }\n const proto = Object.getPrototypeOf(value);\n if (!Array.isArray(value) && proto !== Object.prototype && proto !== null) {\n return value;\n }\n let copy: any = revived.get(value);\n if (!copy) {\n revived.set(\n value,\n (copy = Array.isArray(value) ? [] : Object.create(proto))\n );\n for (const key of Object.keys(value)) {\n // defineProperty keeps keys like `__proto__` as own data properties.\n Object.defineProperty(copy, key, {\n value: reviveContext(value[key]),\n writable: true,\n enumerable: true,\n configurable: true\n });\n }\n }\n return copy;\n }\n\n const restoredSnapshot = createMachineSnapshot(\n {\n ...persistedRest,\n context: reviveContext(persistedRest.context, true),\n children,\n timers,\n _nextTimerId: nextTimerId,\n _nextActorIds: restoredCounters,\n _nodes: nodes,\n // Derived from the resolved configuration, so a partial value such as\n // `{ active: {} }` is completed with initial states and agrees with\n // `nodes`.\n value: undefined,\n historyValue: revivedHistoryValue,\n // Inputs only belong to active states; drop any others.\n _stateInputs: Object.fromEntries(\n Object.entries(snapshotData.stateInputs ?? {}).filter(([id]) =>\n nodes.some((node) => node.id === id)\n )\n )\n },\n machine,\n resolvedActorScope.self\n ) as AnyMachineSnapshot;\n\n if (usesInertScope) {\n setInertActorScopeSnapshot(resolvedActorScope, restoredSnapshot, false);\n return attachSnapshotActorRef(\n resolvedActorScope,\n restoredSnapshot\n ) as SnapshotFrom<TMachine>;\n }\n\n if (!isInertActorScope(resolvedActorScope)) {\n setSnapshotActorRef(\n restoredSnapshot,\n resolvedActorScope.self,\n resolvedActorScope.system\n );\n }\n return restoredSnapshot as SnapshotFrom<TMachine>;\n}\n"],"names":["markers","$actor","$error","$stateNode","$systemMapper","fields","_stateInputs","_nextTimerId","_nextActorIds","isPlain","value","proto","Object","getPrototypeOf","prototype","Array","isArray","renameMarkers","allowed","items","map","item","some","i","keys","legacy","find","key","includes","every","name","rest","copy","upgradeLegacyPersistedSnapshot","snapshot","machine","matches","envelope","entries","renameFields","xstateError","code","values","length","JSON","stringify","String","join","ACTOR_OPTIONS","Set","diagnoseActorOptions","options","has","Error","XSTATE_INIT","XSTATE_SPAWN","XSTATE_STOP","XSTATE_TERMINATE","XSTATE_TIMER","emptySubscription","unsubscribe","isRemoteActorRef","actorRef","_remote","isSerializedActorRef","target","incarnation","undefined","getAddressId","address","segment","slice","lastIndexOf","replaceAll","createMissingAddressError","resolveSerializedActorRef","system","live","_getByAddress","sessionId","remoteSnapshot","freeze","status","output","error","createRemoteActorRef","handle","ref","id","src","registryKey","_parent","parent","_syncSnapshot","syncSnapshot","send","event","sendEvent","_send","type","getSnapshot","getPersistedSnapshot","start","_stop","stop","select","trigger","subscribe","on","_isRunning","toJSON","publishEmittedEvent","source","runtime","_notifyEmitted","emitEvent","pendingSteps","WeakMap","async","runStep","actor","exec","sendSelf","effect","effects","hasOwnProperty","call","getStepEffect","running","get","resolve","reject","promise","Promise","resolvePromise","rejectPromise","subscription","steps","Map","set","cleanup","delete","size","then","complete","catch","rejectUndeliverableEvent","runtimeTarget","logic","isInternalEventType","getEventBoundaryError","deadLetter","Mailbox","constructor","_process","this","_active","_current","_last","flush","clear","next","enqueue","enqueued","consumed","createAfterEvent","delayRef","delay","stateId","createInvokeTimeoutEvent","invokeId","actorId","createDoneStateEvent","createErrorPlatformEvent","kind","createInitEvent","input","reportUnhandledError","err","setTimeout","symbolObservable","Symbol","observable","selectionFrames","transitionEffectSignal","beginTransitionSelection","mode","frame","requiresReevaluation","push","close","pop","getBuiltInTimerIdentity","getTimerKey","timer","seq","readTimerKey","matchesTimerKey","pattern","field","getScheduledTimerKey","serializeTimerKey","starts","getTimerStart","scheduledAt","assertSendToEvent","builtInActions","spawnActor","startActor","@xstate.raise","actorScope","scheduleTimer","self","@xstate.sendTo","_relay","@xstate.cancel","cancelTimer","@xstate.stop","stopActor","@xstate.terminate","termination","terminateActor","sourceKeyCaches","resolveRegisteredActorSource","actors","cache","registeredLogic","systemLogicMetadata","subscriptions","createAttachedLogic","attach","initialTransition","_","state","parentSubscription","torndown","teardown","transition","getInitialSnapshot","restoreSnapshot","defineProperty","relayMappedToParent","getEvent","createListenerLogic","eventType","mapper","isPartialWildcard","endsWith","emittedEvent","matchesEventDescriptor","listenerLogic","createSubscriptionLogic","mappers","done","onSnapshot","subscriptionLogic","execCustomEffect","result","action","args","execEmitEffect","execDeadLetterEffect","reason","detail","createDeadLetterEffect","params","createMissingTargetEffect","targetId","execSpawnEffect","execStartEffect","_processingStatus","execStopEffect","execTerminateEffect","execRaiseEffect","execSendToEffect","execCancelEffect","updateLogicalTimers","isBuiltInExecutableEffect","timers","filter","nextTimerId","index","findIndex","pending","mergeContextPatch","context","patch","pushBuiltInAction","actions","actionRecord","mergeActorIdCounters","current","update","merged","Math","max","applyChildUpdate","children","counters","owned","_unregister","getTransitionActionRecord","spawnAllocations","createSpawnAllocation","explicitIds","stoppedIds","beginSpawnAllocation","getWorkingSnapshotOf","_snapshot","nextChildIndex","allocation","prefix","nextFreeChildIndex","allocateChildId","localAllocation","getActorIdPrefix","assertChildIdFree","existing","occupied","add","reserveChildId","generated","parseGeneratedActorId","detachedScopes","WeakSet","assertRaiseEvent","createTransitionEnqueue","internalEvents","actorSubscriptions","createActors","props","cancel","emit","log","logger","raise","raisedEvent","spawn","registeredActors","sources","getRegisteredActors","resolveTransitionSpawnSource","createInertActorRef","encodeAddressSegment","createActorRef","childUpdate","pushSpawnedChild","sendTo","actorInstance","recordStoppedChild","assign","listen","listenerActor","subscribeTo","subscriptionActor","closed","guard","fn","lateEnqueueCall","createEnqueueObject","enqueueClosers","closeTransitionEnqueue","getBuiltInActionFields","createStartEffect","createSendToEffect","createTerminationEffect","finalizeTransitionResult","previousSnapshot","nextSnapshot","becameTerminal","wasTerminal","hasTerminationEffect","resolveActionsWithContext","currentSnapshot","_event","intermediateSnapshot","executableActions","isInline","resolvedActionArgs","childId","hasOwn","resolvedAction","bind","actionParams","_childUpdate","emittedEventParams","builtInFields","isEmittedEvent","typedExecutableEffect","enqueueFn","noop","emptyActor","ambientInspector","getAmbientInspector","snapshotSystemViews","executionFacilities","executionOwners","ambientExecutionOwner","snapshotActorRefs","lazySnapshotActorRefs","emptyKeyedActors","getKeyedActors","peek","_peekKeyedActors","keyedActors","markSystemSnapshotDirty","_snapshotVersion","getSystemSnapshotVersion","createSnapshotSystem","baseSystem","baseState","owner","baseView","baseExecutionSystem","executionSystem","rootSystem","forks","forwardInspection","inspect","root","copyRegisteredActors","reverseKeyedActors","execution","forwards","create","sourceVersion","_register","_set","getAll","fromEntries","onEmitted","listener","_hasInspectionObservers","_sendInspectionEvent","from","_timerMap","configurable","writable","forkFacilities","takeExecutionOwner","getSnapshotActorRef","created","copySnapshotActorRef","setSnapshotActorRef","previousRef","reusableRef","systemState","sourceSystem","capturedActors","_getRootActor","peekedChildren","_peekChildren","captureRegisteredActors","baseKeyedActors","child","getSnapshotChildren","lazyActorScope","isLazyActorScope","getActorScopeParent","withActorScope","actorArgs","defineProperties","enumerable","setInertActorScopeSnapshot","attachActorRef","lazyState","getLazyInertActorState","scope","materialized","identityScope","isInertActorScope","_inert","attachSnapshotActorRef","snapshotActorScopes","identityProvider","setLazySnapshotActorRef","commitMaterialization","sourceRef","sourceChildren","materialize","lazyInertActorState","materializeInertActorScope","lazyInertActorScopePrototype","parentKnown","defer","stopChild","actionExecutor","createMaterializedInertActorScope","actorLogic","sourceSelf","snapshotRef","previousSelf","createActor","_sessionId","_systemRef","_address","_actorScope","createInertActorScope","sourceActorScope","sourceScope","sourceState","eagerSourceRef","peekSnapshotActorRef","getSnapshotActorRefProvider","isMachineSnapshot","identitySnapshot","identityRef","getIdentityScope","getConfiguredDelayValue","delaySource","referencedDelay","parsedDelay","duration","normalizedDuration","trim","millisecondsMatch","match","parseInt","secondsMatch","wholePart","hasDecimal","fracPart","padEnd","iso8601DurationMatch","groups","weeks","days","hours","minutes","seconds","toNumber","Number","replace","parseDurationToMilliseconds","resolveDelay","configuredDelay","getStateInput","stateNodeId","isAtomicStateNode","stateNode","getChildren","states","sn","getProperAncestors","toStateNode","ancestors","m","getAllStateNodes","stateNodes","nodeSet","activeParentSet","s","initialStates","getInitialStateNodes","initialStateNode","getStateValue","rootNode","config","adjList","getValueFromAdj","baseNode","childStateNodes","childStateNode","stateValue","isInFinalState","stateNodeSet","isStateId","str","matchesActorSession","scheduleDelayedEvent","timerEvent","resolveEvent","resolveScheduledDelay","oldEntry","entry","x","enq","delays","oldExit","exit","formatTransition","descriptor","transitionConfig","removedKey","cond","getRemovedTransitionKey","normalizedTarget","normalizeTarget","reenter","resolveTarget","assertLegalTargetSet","transitionDefinitionToJSON","definition","serializableTransition","isStateNodeDescendantOf","ancestor","getLeastCommonStateNodeAncestor","left","right","leftAncestors","targets","leftIndex","rightIndex","commonAncestor","getStateNodeById","isInternalTarget","getStateNodeByPath","resolvedTarget","message","resolveHistoryDefaultTransition","initial","t","to","_historyDefaultTransition","isHistoryNode","iter","descStateNode","initialState","getStateNode","stateKey","statePath","arrayStatePath","toStatePath","currentStateNode","shift","getStateNodes","childStateKeys","allStateNodes","subStateNode","transitionNode","selectionResults","subStateKeys","subStateKey","allInnerTransitions","subStateValue","innerTransitions","isDescendant","parentStateNode","marker","hasDescendantState","hasIntersection","s1","s2","s1Size","s2Size","set1","removeConflictingTransitions","enabledTransitions","resolveTransition","filteredTransitions","exitSets","getExitSet","exitSet","computeExitSet","t1","t1Preempted","transitionsToRemove","t2","t3","createTransitionResultResolver","resolveActions","applied","getTransitionResult","selectionResult","getEffectiveTargetStates","historyValue","targetSet","targetNode","node","narrowParallelDomain","domain","targetStates","narrowed","region","getTransitionDomain","_transitionDomain","head","tail","concat","transitions","statesToExit","microstep","isInitial","internalQueue","_microstepHooks","drain","mutStateNodeSet","nodes","originalContext","getCurrentTransitionResult","changesState","getStateActionsAndContext","transitionFn","updatedContext","getEventOutput","guards","res","assertSyncTransitionResult","nextState","getInvokeStopActions","invokeDef","invoke","exitStates","changedHistory","sort","a","b","order","currentStateNodes","exitStateNode","historyNode","predicate","history","stateInput","exitActions","nextContext","nextChildren","cloneMachineSnapshot","resolvedState","resolvedActions","invokeStopActions","stoppedState","stopEffects","transitionActions","resolvedTransitions","resolvedTransition","enterStates","getMachineOutput","rootCompletionNode","completionOutput","rootDoneEvent","e","resolveOutput","stateInputMap","parallelDoneEvent","statesToEnter","statesForDefaultEntry","historyDefaultsByParent","addAncestorStatesToEnter","reentrancyDomain","anc","addDescendantStatesToEnter","historyStateNodes","historyDefaultTransition","historyParent","defaults","enteredTargetsByTransition","enteredTargets","_statesForDefaultEntry","stateInputsChanged","activeIds","completedNodes","stateNodeToEnter","invoked","_invoked","contextChangedByEntry","resultActions","nextInternalEvents","defaultTransitions","Boolean","defaultTransition","initialActions","initialContext","initialInput","initialInternalEvents","ancestorMarker","regionOutput","regionDoneEvent","finalChild","resolvedTransitionState","transitionExecutableEffects","transitionContent","raisedEvents","nextStateNodes","allExitActions","forEach","stopChildren","withoutTimers","cancelEffects","cancelTimers","_nodes","transitionArgs","getTransitionArgs","reusable","operations","speculativeSelection","operation","toArray","resolvedInput","resolvedContext","InfiniteTransitionError","maxIterations","super","macrostep","initialMicrosteps","microsteps","handled","removeTerminatedChild","terminalEvent","lastEffects","lastTransitions","at","completeMacrostep","attachedStarts","childStarts","deriveDeferredStarts","flatMap","shouldTerminate","terminalEffects","lastSnapshot","addMicrostep","step","collectedMicrosteps","_collectedMicrosteps","stoppedChildrenSnapshot","nextEvent","currentEvent","isErr","startsWith","isErrorEvent","getTransitionData","_hasEventlessTransitions","shouldSelectEventlessTransitions","Infinity","iterationCount","recentStates","selectEventlessTransitions","previousState","hasEffect","evaluateTransitionFunction","enabled","sourceId","transitionTo","selection","record","abortRefProducingCall","createTransitionSelection","begin","enabledTransitionSet","atomicStates","atomicStateNode","loop","always","evaluateCandidate","candidate","is","matchesEvent","_eventMatcher","guardArgs","withActorSelfAndParent","evaluation","emptySnapshotRecord","emptyTimers","compactTimers","compactSnapshotRecord","machineSnapshotMatches","testValue","matchesState","machineSnapshotHasTag","tag","tags","machineSnapshotCan","_canTransition","machineSnapshotToJSON","getMeta","getInputs","can","hasTag","jsonValues","machineSnapshotGetMeta","meta","machineSnapshotGetInputs","collectTags","createMachineSnapshot","configWithSnapshot","clonedSnapshot","serializeHistoryValue","persistContext","contextPart","getActorId","path","isActorRefLike","valuePath","parentStateId","childStateId","parentStateValue","toStateValue","childStateValue","charCodeAt","previous","pathToStateValue","toArrayStrict","isDoneEvent","toTransitionConfigArray","configLike","transitionLike","toObserver","nextHandler","errorHandler","completionHandler","isObserver","passive","resolveInvokedActorLogic","definitions","registered","partialEventTokens","split","eventTokens","tokenIndex","partialEventToken","eventToken","executionIdPrefix","nextExecutionId","createExecutionId","crypto","globalThis","getRandomValues","Uint32Array","toString","padStart","randomUUID","Date","now","random","createExecutionIdPrefix","logicId","separator","isSafeInteger","getActorIdCounterKey","bumpActorIdCounter","counterKey","emptyScheduledTimers","createScheduledTimerId","findLogicalTimer","RuntimeSystem","_children","_rootActor","_keyedActors","_reverseKeyedActors","_identity","executionId","nextSessionId","scheduler","_clock","_logger","clock","_scheduledTimers","_recordSent","_inspectionObservers","inspectionSource","_inTransition","_collectedSent","targetRef","schedule","scheduledTimerId","scheduledTimer","dueAt","timeout","_deliver","clearTimeout","cancelAll","serialized","deliverEvent","changed","observerOrFn","observer","onRejectedEvent","rejection","_rejectionListeners","emission","_emissionListeners","listeners","resolvedInspectionEvent","rootId","override","stopActorLocally","_terminate","terminateActorLocally","_emit","eventOrigin","issues","runLogic","cancelAllTimers","matched","abort","protectSelectionRelay","scheduledTimers","resetScheduledTimers","scheduledId","executingCustomAction","emptyInspectionRecords","reservedMachineEventTypes","ProcessingStatus","defaultOptions","ms","console","safeCall","arg","executeExecutableEffects","Actor","_trigger","Proxy","payload","_boundSend","_sendPublic","_boundProcess","mailbox","_mailboxStarted","observers","_errorObserved","eventListeners","NotStarted","_forceDeferredActions","_lastSourceRef","_collectedActions","_initialEffects","_deferred","_restored","_warnedUnhandledTypes","resolvedOptions","rootActor","createRuntimeSystem","initialize","requestedId","counter","resolveActorId","restore","_restore","_setSnapshot","parentRef","_getLogger","_defer","_stopChild","_executeAction","Running","saveExecutingCustomAction","Stopped","_recoverOrError","_setErrorSnapshot","_tryHandleExecutionError","_error","errorEvent","getExecutionErrorEvent","inTransition","_next","deferred","deferredFn","_inspectTransition","sent","_flushInitialEffects","nextListenerOrObserver","errorListener","completeListener","handler","selector","equalityFn","selected","_start","_stopProcedure","_complete","restored","refreshSnapshotActorRefRoot","wallClock","min","_processEvent","caughtError","_reportUnhandledEvent","onUnhandledEvent","_reportUnlessObserved","snapshotChildren","reportError","InvalidSnapshotError","isSnapshotRecord","isActorLogic","validatePersistedStateValue","invalidValue","childNode","validatePersistedSnapshot","childLogics","remote","EMPTY_OBJECT","StateNode","description","schemas","after","events","ownEvents","_candidateCache","_key","_machine","hasUnescapedDot","firstStateKey","choice","validateStateNodeConfig","idMap","collection","iteratee","collectionKeys","mapValues","stateConfig","invokeConfig","resolvedId","_initialize","afterConfig","timeoutConfig","onTimeoutConfig","onTimeout","invokeDefs","isNaN","fromDelaysMap","eventMatcher","delayedTransitions","eventPattern","delayedTransition","getDelayedTransitions","addTransitions","additions","transitionsConfig","mapTransitionConfigs","onDone","onError","createCancelInvokeTimeoutTransition","timeoutKey","_args","formatInvokeCompletionTransition","didEnqueue","trackingEnqueue","apply","thisArg","argArray","Reflect","prop","receiver","withInvokeMatch","invokeTimeoutKey","invokeDoneTransitions","rawTransition","formatTransitions","validateChoiceResult","formatChoiceTransitions","_refreshEventMetadata","object","memoizedData","memo","_target","targetString","targetStrings","resolvedTargets","formatInitialTransition","candidates","exactMatches","wildcardCandidates","eventDescriptor","getCandidates","transitionConfigs","assertValid","validator","request","check","emptyCanActor","emptyCanActorScope","getEmptyCanActorScope","StateMachine","_internalEventType","_transitionMetaType","_inputType","_actionMap","_actorMap","_stateSchema","version","_raw","internalEventDescriptors","_json","rootStateNode","routeTransitions","collectRoutes","route","routeId","routeConfig","routeMatches","_guard","routeOptions","formatRouteTransitions","provide","provided","resolveState","resolvedStateValue","usesInertScope","resolvedActorScope","fastSnapshot","_transitionFast","returnedSnapshot","_attachPureActorRef","_collectEffects","skipInitializingActor","sourceNode","stateChanged","rootInput","snapshots","emptyActorScope","transitionData","_getPreInitialState","initEvent","preInitial","spawnedChildren","referencedSrc","createSpawner","withActorSelf","takeSpawnAllocationCounters","finalizeInitialResult","macroState","preInitialState","contextSpawnEffects","createSpawnEffect","initialStateNodes","collectDefaultEntryStates","other","initialMicrostep","errorMacrostep","_rehydrated","hasPrefix","STATE_IDENTIFIER","childrenJson","timersJson","embedChildren","sourceKey","def","embed","snapshotActor","scheduled","persisted","stateInputs","nextActorIds","snapshotSchemas","restoreLogicSnapshot","restoreMachineSnapshot","createRestoreHook","createRestoreErrorSnapshot","snapshotMachine","persistedMachine","legacyPersistedVersion","persistedVersion","migrate","snapshotData","actorData","childState","persistedTimers","targetDescription","revivedHistoryValue","revived","arr","resolved","reviveHistoryValue","_persistedSnapshotVersion","_nextActorId","_legacyNextActorId","_persistedStateInputs","persistedRest","restoredCounters","restoredSnapshot","reviveContext","isRoot","persistedSnapshot","actorOptions","vendor","validate","contextSchema"],"mappings":"oPAKA,MAAMA,EAA8C,CAClDC,OAAQ,CAAC,SAAU,CAAC,gBACpBC,OAAQ,CAAC,SAAU,CAAC,YACpBC,WAAY,CAAC,aAAc,IAC3BC,cAAe,CAAC,gBAAiB,KAG7BC,EAAiC,CACrCC,aAAc,cACdC,aAAc,cACdC,cAAe,gBAKjB,SAASC,EAAQC,GACf,IAAKA,GAA0B,iBAAVA,EAAoB,OAAO,EAChD,MAAMC,EAAQC,OAAOC,eAAeH,GACpC,OAAOC,IAAUC,OAAOE,WAAuB,OAAVH,GAAkBI,MAAMC,QAAQN,EACvE,CAEA,SAASO,EAAcP,EAAYQ,GACjC,IAAKT,EA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