xstate 5.20.1 → 5.20.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.
- package/actions/dist/xstate-actions.cjs.js +3 -3
- package/actions/dist/xstate-actions.development.cjs.js +3 -3
- package/actions/dist/xstate-actions.development.esm.js +3 -3
- package/actions/dist/xstate-actions.esm.js +3 -3
- package/actions/dist/xstate-actions.umd.min.js +1 -1
- package/actions/dist/xstate-actions.umd.min.js.map +1 -1
- package/actors/dist/xstate-actors.cjs.js +1 -1
- package/actors/dist/xstate-actors.development.cjs.js +1 -1
- package/actors/dist/xstate-actors.development.esm.js +1 -1
- package/actors/dist/xstate-actors.esm.js +1 -1
- package/actors/dist/xstate-actors.umd.min.js +1 -1
- package/actors/dist/xstate-actors.umd.min.js.map +1 -1
- package/dev/dist/xstate-dev.umd.min.js +1 -1
- package/dev/dist/xstate-dev.umd.min.js.map +1 -1
- package/dist/{StateMachine-b4e94439.development.esm.js → StateMachine-30043f16.development.esm.js} +2 -2
- package/dist/{StateMachine-c88ea5dd.esm.js → StateMachine-31b70dc4.esm.js} +2 -2
- package/dist/{StateMachine-1cda96d3.cjs.js → StateMachine-865e00e8.cjs.js} +2 -2
- package/dist/{StateMachine-38b5bb3f.development.cjs.js → StateMachine-a87228f5.development.cjs.js} +2 -2
- package/dist/{assign-e9c344ea.cjs.js → assign-381d0341.cjs.js} +1 -1
- package/dist/{assign-6313ccb3.development.esm.js → assign-55675fdf.development.esm.js} +1 -1
- package/dist/{assign-c3259787.esm.js → assign-828d933a.esm.js} +1 -1
- package/dist/{assign-c84786ab.development.cjs.js → assign-a4be500b.development.cjs.js} +1 -1
- package/dist/{log-215998b6.cjs.js → log-63c8f21f.cjs.js} +2 -2
- package/dist/{log-ef959da6.development.esm.js → log-752e55b8.development.esm.js} +2 -2
- package/dist/{log-1c257a58.esm.js → log-b74eb32d.esm.js} +2 -2
- package/dist/{log-2c8d7f98.development.cjs.js → log-ee7045aa.development.cjs.js} +2 -2
- package/dist/{raise-78b8dcb8.development.esm.js → raise-3d0be313.development.esm.js} +5 -1
- package/dist/{raise-5872b9e8.cjs.js → raise-b4a670a0.cjs.js} +5 -1
- package/dist/{raise-b0a4e862.esm.js → raise-bfb6713e.esm.js} +5 -1
- package/dist/{raise-7a84f9f0.development.cjs.js → raise-c94748d0.development.cjs.js} +5 -1
- package/dist/xstate.cjs.js +4 -4
- package/dist/xstate.development.cjs.js +4 -4
- package/dist/xstate.development.esm.js +6 -6
- package/dist/xstate.esm.js +6 -6
- package/dist/xstate.umd.min.js +1 -1
- package/dist/xstate.umd.min.js.map +1 -1
- package/graph/dist/xstate-graph.cjs.js +3 -3
- package/graph/dist/xstate-graph.development.cjs.js +3 -3
- package/graph/dist/xstate-graph.development.esm.js +3 -3
- package/graph/dist/xstate-graph.esm.js +3 -3
- package/graph/dist/xstate-graph.umd.min.js +1 -1
- package/graph/dist/xstate-graph.umd.min.js.map +1 -1
- package/guards/dist/xstate-guards.cjs.js +1 -1
- package/guards/dist/xstate-guards.development.cjs.js +1 -1
- package/guards/dist/xstate-guards.development.esm.js +1 -1
- package/guards/dist/xstate-guards.esm.js +1 -1
- package/guards/dist/xstate-guards.umd.min.js +1 -1
- package/guards/dist/xstate-guards.umd.min.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"xstate-actions.umd.min.js","sources":["../../src/Mailbox.ts","../../src/constants.ts","../../src/dev/index.ts","../../src/eventUtils.ts","../../src/reportUnhandledError.ts","../../src/symbolObservable.ts","../../src/utils.ts","../../src/State.ts","../../src/system.ts","../../src/createActor.ts","../../src/actions/cancel.ts","../../src/actions/spawnChild.ts","../../src/actions/stopChild.ts","../../src/guards.ts","../../src/stateUtils.ts","../../src/spawn.ts","../../src/actions/assign.ts","../../src/actions/emit.ts","../../src/actions/raise.ts","../../src/types.ts","../../src/actions/send.ts","../../src/actions/enqueueActions.ts","../../src/actions/log.ts"],"sourcesContent":["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","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_ERROR = 'xstate.error';\nexport const XSTATE_STOP = 'xstate.stop';\n","import isDevelopment from '#is-development';\nimport { AnyActor, DevToolsAdapter } from '../types.ts';\n\ninterface DevInterface {\n services: Set<AnyActor>;\n register(service: AnyActor): void;\n onRegister(listener: ServiceListener): void;\n}\ntype ServiceListener = (service: AnyActor) => void;\n\nexport interface XStateDevInterface {\n register: (service: AnyActor) => void;\n unregister: (service: AnyActor) => void;\n onRegister: (listener: ServiceListener) => {\n unsubscribe: () => void;\n };\n services: Set<AnyActor>;\n}\n\n// From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis\nexport function getGlobal(): typeof globalThis | undefined {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n }\n if (typeof self !== 'undefined') {\n return self;\n }\n if (typeof window !== 'undefined') {\n return window;\n }\n if (typeof global !== 'undefined') {\n return global;\n }\n if (isDevelopment) {\n console.warn(\n 'XState could not find a global object in this environment. Please let the maintainers know and raise an issue here: https://github.com/statelyai/xstate/issues'\n );\n }\n}\n\nfunction getDevTools(): DevInterface | undefined {\n const w = getGlobal();\n if ((w as any).__xstate__) {\n return (w as any).__xstate__;\n }\n\n return undefined;\n}\n\nexport function registerService(service: AnyActor) {\n if (typeof window === 'undefined') {\n return;\n }\n\n const devTools = getDevTools();\n\n if (devTools) {\n devTools.register(service);\n }\n}\n\nexport const devToolsAdapter: DevToolsAdapter = (service) => {\n if (typeof window === 'undefined') {\n return;\n }\n\n const devTools = getDevTools();\n\n if (devTools) {\n devTools.register(service);\n }\n};\n","import { XSTATE_INIT } from './constants.ts';\nimport { DoneActorEvent, DoneStateEvent, ErrorActorEvent } 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(delayRef: number | string, id: string) {\n return { type: `xstate.after.${delayRef}.${id}` } as const;\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.${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 */\nexport function createDoneActorEvent(\n invokeId: string,\n output?: unknown\n): DoneActorEvent {\n return {\n type: `xstate.done.actor.${invokeId}`,\n output,\n actorId: invokeId\n };\n}\n\nexport function createErrorActorEvent(\n id: string,\n error?: unknown\n): ErrorActorEvent {\n return { type: `xstate.error.actor.${id}`, error, actorId: id };\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 isDevelopment from '#is-development';\nimport { isMachineSnapshot } from './State.ts';\nimport type { StateNode } from './StateNode.ts';\nimport { TARGETLESS_KEY } from './constants.ts';\nimport type {\n AnyActorRef,\n AnyEventObject,\n AnyMachineSnapshot,\n AnyStateMachine,\n AnyTransitionConfig,\n ErrorActorEvent,\n EventObject,\n InvokeConfig,\n MachineContext,\n Mapper,\n NonReducibleUnknown,\n Observer,\n SingleOrArray,\n StateLike,\n StateValue,\n TransitionConfigTarget\n} from './types.ts';\n\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\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 // consume the next character\n segment += 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\nexport function 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 result[key] = iteratee(collection[key], key, collection, i);\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: AnyActorRef\n): unknown {\n if (typeof mapper === 'function') {\n return mapper({ context, event, self });\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\nfunction isArray(value: any): value is readonly any[] {\n return Array.isArray(value);\n}\n\nexport function isErrorActorEvent(\n event: AnyEventObject\n): event is ErrorActorEvent {\n return event.type.startsWith('xstate.error.actor');\n}\n\nexport function toTransitionConfigArray(\n configLike: SingleOrArray<AnyTransitionConfig | TransitionConfigTarget>\n): Array<AnyTransitionConfig> {\n return toArrayStrict(configLike).map((transitionLike) => {\n if (\n typeof transitionLike === 'undefined' ||\n typeof transitionLike === 'string'\n ) {\n return { target: 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\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 };\n}\n\nexport function createInvokeId(stateNodeId: string, index: number): string {\n return `${index}.${stateNodeId}`;\n}\n\nexport function resolveReferencedActor(machine: AnyStateMachine, src: string) {\n const match = src.match(/^xstate\\.invoke\\.(\\d+)\\.(.*)/)!;\n if (!match) {\n return machine.implementations.actors[src];\n }\n const [, indexStr, nodeId] = match;\n const node = machine.getStateNodeById(nodeId);\n const invokeConfig = node.config.invoke!;\n return (\n Array.isArray(invokeConfig)\n ? invokeConfig[indexStr as any]\n : (invokeConfig as InvokeConfig<\n any,\n any,\n any,\n any,\n any,\n any,\n any, // TEmitted\n any // TMeta\n >)\n ).src;\n}\n\nexport function getAllOwnEventDescriptors(snapshot: AnyMachineSnapshot) {\n return [...new Set([...snapshot._nodes.flatMap((sn) => sn.ownEvents)])];\n}\n","import isDevelopment from '#is-development';\nimport { $$ACTOR_TYPE } from './createActor.ts';\nimport type { StateNode } from './StateNode.ts';\nimport type { StateMachine } from './StateMachine.ts';\nimport { getStateValue } from './stateUtils.ts';\nimport type {\n ProvidedActor,\n AnyMachineSnapshot,\n AnyStateMachine,\n EventObject,\n HistoryValue,\n MachineContext,\n StateConfig,\n StateValue,\n AnyActorRef,\n Snapshot,\n ParameterizedObject,\n IsNever,\n MetaObject,\n StateSchema,\n StateId,\n SnapshotStatus,\n PersistedHistoryValue\n} from './types.ts';\nimport { matchesState } from './utils.ts';\n\ntype ToTestStateValue<TStateValue extends StateValue> =\n TStateValue extends string\n ? TStateValue\n : IsNever<keyof TStateValue> extends true\n ? never\n :\n | keyof TStateValue\n | {\n [K in keyof TStateValue]?: ToTestStateValue<\n NonNullable<TStateValue[K]>\n >;\n };\n\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\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,\n TStateSchema extends StateSchema = StateSchema\n> {\n /** The state machine that produced this state snapshot. */\n machine: StateMachine<\n TContext,\n TEvent,\n TChildren,\n ProvidedActor,\n ParameterizedObject,\n ParameterizedObject,\n string,\n TStateValue,\n TTag,\n unknown,\n TOutput,\n EventObject, // TEmitted\n any, // TMeta\n TStateSchema\n >;\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<TContext, TEvent>>;\n /** The enabled state nodes representative of the state value. */\n _nodes: Array<StateNode<TContext, TEvent>>;\n /** An object mapping actor names to spawned/invoked actors. */\n children: TChildren;\n\n /**\n * Whether the current state value is a subset of the given partial state\n * value.\n *\n * @param partialStateValue\n */\n matches: (partialStateValue: ToTestStateValue<TStateValue>) => 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 * @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 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 TConfig extends StateSchema\n> extends MachineSnapshotBase<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\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 TConfig extends StateSchema\n> extends MachineSnapshotBase<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\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 TConfig extends StateSchema\n> extends MachineSnapshotBase<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\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 TConfig extends StateSchema\n> extends MachineSnapshotBase<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n > {\n status: 'stopped';\n output: undefined;\n error: undefined;\n}\n\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 TConfig extends StateSchema\n> =\n | ActiveMachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >\n | DoneMachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >\n | ErrorMachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >\n | StoppedMachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >;\n\nconst machineSnapshotMatches = function matches(\n this: AnyMachineSnapshot,\n testValue: StateValue\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 const transitionData = this.machine.getTransitionData(this, event);\n\n return (\n !!transitionData?.length &&\n // Check that at least one transition is not forbidden\n transitionData.some((t) => t.target !== undefined || t.actions.length)\n );\n};\n\nconst machineSnapshotToJSON = function toJSON(this: AnyMachineSnapshot) {\n const {\n _nodes: nodes,\n tags,\n machine,\n getMeta,\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 return this._nodes.reduce(\n (acc, stateNode) => {\n if (stateNode.meta !== undefined) {\n acc[stateNode.id] = stateNode.meta;\n }\n return acc;\n },\n {} as Record<string, any>\n );\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): MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n undefined,\n TMeta,\n TStateSchema\n> {\n return {\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: getStateValue(machine.root, config._nodes) as never,\n tags: new Set(config._nodes.flatMap((sn) => sn.tags)),\n children: config.children as any,\n historyValue: config.historyValue || {},\n matches: machineSnapshotMatches as never,\n hasTag: machineSnapshotHasTag,\n can: machineSnapshotCan,\n getMeta: machineSnapshotGetMeta,\n toJSON: machineSnapshotToJSON\n };\n}\n\nexport function cloneMachineSnapshot<TState extends AnyMachineSnapshot>(\n snapshot: TState,\n config: Partial<StateConfig<any, any>> = {}\n): TState {\n return createMachineSnapshot(\n { ...snapshot, ...config } as StateConfig<any, any>,\n snapshot.machine\n ) as TState;\n}\n\nfunction serializeHistoryValue<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(historyValue: HistoryValue<TContext, TEvent>): PersistedHistoryValue {\n if (typeof historyValue !== 'object' || historyValue === null) {\n return {};\n }\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: nodes,\n tags,\n machine,\n children,\n context,\n can,\n hasTag,\n matches,\n getMeta,\n toJSON,\n ...jsonValues\n } = snapshot;\n\n const childrenJson: Record<string, unknown> = {};\n\n for (const id in children) {\n const child = children[id] as any;\n if (\n isDevelopment &&\n typeof child.src !== 'string' &&\n (!options || !('__unsafeAllowInlineActors' in (options as object)))\n ) {\n throw new Error('An inline child actor cannot be persisted.');\n }\n childrenJson[id as keyof typeof childrenJson] = {\n snapshot: child.getPersistedSnapshot(options),\n src: child.src,\n systemId: child._systemId,\n syncSnapshot: child._syncSnapshot\n };\n }\n\n const persisted = {\n ...jsonValues,\n context: persistContext(context) as any,\n children: childrenJson,\n historyValue: serializeHistoryValue<TContext, TEvent>(\n jsonValues.historyValue\n )\n };\n\n return persisted;\n}\n\nfunction persistContext(contextPart: Record<string, unknown>) {\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 ('sessionId' in value && 'send' in value && 'ref' in value) {\n copy ??= Array.isArray(contextPart)\n ? (contextPart.slice() as typeof contextPart)\n : { ...contextPart };\n copy[key] = {\n xstate$$type: $$ACTOR_TYPE,\n id: (value as any as AnyActorRef).id\n };\n } else {\n const result = persistContext(value as typeof contextPart);\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 return copy ?? contextPart;\n}\n","import { InspectionEvent } from './inspection.ts';\nimport {\n AnyEventObject,\n ActorSystemInfo,\n AnyActorRef,\n Observer,\n HomomorphicOmit,\n EventObject,\n Subscription\n} from './types.ts';\nimport { toObserver } from './utils.ts';\n\ninterface ScheduledEvent {\n id: string;\n event: EventObject;\n startedAt: number; // timestamp\n delay: number;\n source: AnyActorRef;\n target: AnyActorRef;\n}\n\nexport interface Clock {\n setTimeout(fn: (...args: any[]) => void, timeout: number): any;\n clearTimeout(id: any): void;\n}\n\ninterface Scheduler {\n schedule(\n source: AnyActorRef,\n target: AnyActorRef,\n event: EventObject,\n delay: number,\n id: string | undefined\n ): void;\n cancel(source: AnyActorRef, id: string): void;\n cancelAll(actorRef: AnyActorRef): void;\n}\n\ntype ScheduledEventId = string & { __scheduledEventId: never };\n\nfunction createScheduledEventId(\n actorRef: AnyActorRef,\n id: string\n): ScheduledEventId {\n return `${actorRef.sessionId}.${id}` as ScheduledEventId;\n}\n\nexport interface ActorSystem<T extends ActorSystemInfo> {\n /** @internal */\n _bookId: () => string;\n /** @internal */\n _register: (sessionId: string, actorRef: AnyActorRef) => string;\n /** @internal */\n _unregister: (actorRef: AnyActorRef) => void;\n /** @internal */\n _set: <K extends keyof T['actors']>(key: K, actorRef: T['actors'][K]) => void;\n get: <K extends keyof T['actors']>(key: K) => T['actors'][K] | undefined;\n\n inspect: (\n observer:\n | Observer<InspectionEvent>\n | ((inspectionEvent: InspectionEvent) => void)\n ) => Subscription;\n /** @internal */\n _sendInspectionEvent: (\n event: HomomorphicOmit<InspectionEvent, 'rootId'>\n ) => void;\n /** @internal */\n _relay: (\n source: AnyActorRef | undefined,\n target: AnyActorRef,\n event: AnyEventObject\n ) => void;\n scheduler: Scheduler;\n getSnapshot: () => {\n _scheduledEvents: Record<string, ScheduledEvent>;\n };\n /** @internal */\n _snapshot: {\n _scheduledEvents: Record<ScheduledEventId, ScheduledEvent>;\n };\n start: () => void;\n _clock: Clock;\n _logger: (...args: any[]) => void;\n}\n\nexport type AnyActorSystem = ActorSystem<any>;\n\nlet idCounter = 0;\nexport function createSystem<T extends ActorSystemInfo>(\n rootActor: AnyActorRef,\n options: {\n clock: Clock;\n logger: (...args: any[]) => void;\n snapshot?: unknown;\n }\n): ActorSystem<T> {\n const children = new Map<string, AnyActorRef>();\n const keyedActors = new Map<keyof T['actors'], AnyActorRef | undefined>();\n const reverseKeyedActors = new WeakMap<AnyActorRef, keyof T['actors']>();\n const inspectionObservers = new Set<Observer<InspectionEvent>>();\n const timerMap: { [id: ScheduledEventId]: number } = {};\n const { clock, logger } = options;\n\n const scheduler: Scheduler = {\n schedule: (\n source,\n target,\n event,\n delay,\n id = Math.random().toString(36).slice(2)\n ) => {\n const scheduledEvent: ScheduledEvent = {\n source,\n target,\n event,\n delay,\n id,\n startedAt: Date.now()\n };\n const scheduledEventId = createScheduledEventId(source, id);\n system._snapshot._scheduledEvents[scheduledEventId] = scheduledEvent;\n\n const timeout = clock.setTimeout(() => {\n delete timerMap[scheduledEventId];\n delete system._snapshot._scheduledEvents[scheduledEventId];\n\n system._relay(source, target, event);\n }, delay);\n\n timerMap[scheduledEventId] = timeout;\n },\n cancel: (source, id: string) => {\n const scheduledEventId = createScheduledEventId(source, id);\n const timeout = timerMap[scheduledEventId];\n\n delete timerMap[scheduledEventId];\n delete system._snapshot._scheduledEvents[scheduledEventId];\n\n if (timeout !== undefined) {\n clock.clearTimeout(timeout);\n }\n },\n cancelAll: (actorRef) => {\n for (const scheduledEventId in system._snapshot._scheduledEvents) {\n const scheduledEvent =\n system._snapshot._scheduledEvents[\n scheduledEventId as ScheduledEventId\n ];\n if (scheduledEvent.source === actorRef) {\n scheduler.cancel(actorRef, scheduledEvent.id);\n }\n }\n }\n };\n const sendInspectionEvent = (event: InspectionEvent) => {\n if (!inspectionObservers.size) {\n return;\n }\n const resolvedInspectionEvent: InspectionEvent = {\n ...event,\n rootId: rootActor.sessionId\n };\n inspectionObservers.forEach((observer) =>\n observer.next?.(resolvedInspectionEvent)\n );\n };\n\n const system: ActorSystem<T> = {\n _snapshot: {\n _scheduledEvents:\n (options?.snapshot && (options.snapshot as any).scheduler) ?? {}\n },\n _bookId: () => `x:${idCounter++}`,\n _register: (sessionId, actorRef) => {\n children.set(sessionId, actorRef);\n return sessionId;\n },\n _unregister: (actorRef) => {\n children.delete(actorRef.sessionId);\n const systemId = reverseKeyedActors.get(actorRef);\n\n if (systemId !== undefined) {\n keyedActors.delete(systemId);\n reverseKeyedActors.delete(actorRef);\n }\n },\n get: (systemId) => {\n return keyedActors.get(systemId) as T['actors'][any];\n },\n _set: (systemId, actorRef) => {\n const existing = keyedActors.get(systemId);\n if (existing && existing !== actorRef) {\n throw new Error(\n `Actor with system ID '${systemId as string}' already exists.`\n );\n }\n\n keyedActors.set(systemId, actorRef);\n reverseKeyedActors.set(actorRef, systemId);\n },\n inspect: (observerOrFn) => {\n const observer = toObserver(observerOrFn);\n inspectionObservers.add(observer);\n\n return {\n unsubscribe() {\n inspectionObservers.delete(observer);\n }\n };\n },\n _sendInspectionEvent: sendInspectionEvent as any,\n _relay: (source, target, event) => {\n system._sendInspectionEvent({\n type: '@xstate.event',\n sourceRef: source,\n actorRef: target,\n event\n });\n\n target._send(event);\n },\n scheduler,\n getSnapshot: () => {\n return {\n _scheduledEvents: { ...system._snapshot._scheduledEvents }\n };\n },\n start: () => {\n const scheduledEvents = system._snapshot._scheduledEvents;\n system._snapshot._scheduledEvents = {};\n for (const scheduledId in scheduledEvents) {\n const { source, target, event, delay, id } =\n scheduledEvents[scheduledId as ScheduledEventId];\n scheduler.schedule(source, target, event, delay, id);\n }\n },\n _clock: clock,\n _logger: logger\n };\n\n return system;\n}\n","import isDevelopment from '#is-development';\nimport { Mailbox } from './Mailbox.ts';\nimport { XSTATE_STOP } from './constants.ts';\nimport { devToolsAdapter } from './dev/index.ts';\nimport {\n createDoneActorEvent,\n createErrorActorEvent,\n createInitEvent\n} from './eventUtils.ts';\nimport { reportUnhandledError } from './reportUnhandledError.ts';\nimport { symbolObservable } from './symbolObservable.ts';\nimport { AnyActorSystem, Clock, createSystem } from './system.ts';\n\n// those are needed to make JSDoc `@link` work properly\nimport type {\n fromObservable,\n fromEventObservable\n} from './actors/observable.ts';\nimport type { fromCallback } from './actors/callback.ts';\nimport type { fromPromise } from './actors/promise.ts';\nimport type { fromTransition } from './actors/transition.ts';\nimport type { createMachine } from './createMachine.ts';\n\nexport let executingCustomAction: boolean = false;\n\nimport type {\n ActorScope,\n AnyActorLogic,\n AnyActorRef,\n ConditionalRequired,\n DoneActorEvent,\n EmittedFrom,\n EventFromLogic,\n InputFrom,\n IsNotNever,\n Snapshot,\n SnapshotFrom\n} from './types.ts';\nimport {\n ActorOptions,\n ActorRef,\n EventObject,\n InteropSubscribable,\n Observer,\n Subscription\n} from './types.ts';\nimport { toObserver } from './utils.ts';\n\nexport const $$ACTOR_TYPE = 1;\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 = {\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 devTools: false\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 */\nexport class Actor<TLogic extends AnyActorLogic>\n implements\n ActorRef<SnapshotFrom<TLogic>, EventFromLogic<TLogic>, EmittedFrom<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 mailbox: Mailbox<EventFromLogic<TLogic>> = new Mailbox(\n this._process.bind(this)\n );\n\n private observers: Set<Observer<SnapshotFrom<TLogic>>> = new Set();\n private eventListeners: Map<\n string,\n Set<(emittedEvent: EmittedFrom<TLogic>) => void>\n > = new Map();\n private logger: (...args: any[]) => void;\n\n /** @internal */\n public _processingStatus: ProcessingStatus = ProcessingStatus.NotStarted;\n\n // Actor Ref\n public _parent?: AnyActorRef;\n /** @internal */\n public _syncSnapshot?: boolean;\n public ref: ActorRef<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>,\n EmittedFrom<TLogic>\n >;\n // TODO: add typings for system\n private _actorScope: ActorScope<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>,\n AnyActorSystem,\n EmittedFrom<TLogic>\n >;\n\n private _systemId: string | undefined;\n\n /** The globally unique process ID for this invocation. */\n public sessionId: string;\n\n /** The system to which this actor belongs. */\n public system: AnyActorSystem;\n private _doneEvent?: DoneActorEvent;\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 ...defaultOptions,\n ...options\n };\n\n const { clock, logger, parent, syncSnapshot, id, systemId, inspect } =\n resolvedOptions;\n\n this.system = parent\n ? parent.system\n : createSystem(this, {\n clock,\n logger\n });\n\n if (inspect && !parent) {\n // Always inspect at the system-level\n this.system.inspect(toObserver(inspect));\n }\n\n this.sessionId = this.system._bookId();\n this.id = id ?? this.sessionId;\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 = {\n self: this,\n id: this.id,\n sessionId: this.sessionId,\n logger: this.logger,\n defer: (fn) => {\n this._deferred.push(fn);\n },\n system: this.system,\n stopChild: (child) => {\n if (child._parent !== this) {\n throw new Error(\n `Cannot stop child actor ${child.id} of ${this.id} because it is not a child`\n );\n }\n (child as any)._stop();\n },\n emit: (emittedEvent) => {\n const listeners = this.eventListeners.get(emittedEvent.type);\n const wildcardListener = this.eventListeners.get('*');\n if (!listeners && !wildcardListener) {\n return;\n }\n const allListeners = [\n ...(listeners ? listeners.values() : []),\n ...(wildcardListener ? wildcardListener.values() : [])\n ];\n for (const handler of allListeners) {\n handler(emittedEvent);\n }\n },\n actionExecutor: (action) => {\n const exec = () => {\n this._actorScope.system._sendInspectionEvent({\n type: '@xstate.action',\n actorRef: this,\n action: {\n type: action.type,\n params: action.params\n }\n });\n if (!action.exec) {\n return;\n }\n const saveExecutingCustomAction = executingCustomAction;\n try {\n executingCustomAction = true;\n action.exec(action.info, action.params);\n } finally {\n executingCustomAction = saveExecutingCustomAction;\n }\n };\n if (this._processingStatus === ProcessingStatus.Running) {\n exec();\n } else {\n this._deferred.push(exec);\n }\n }\n };\n\n // Ensure that the send method is bound to this Actor instance\n // if destructured\n this.send = this.send.bind(this);\n\n this.system._sendInspectionEvent({\n type: '@xstate.actor',\n actorRef: this\n });\n\n if (systemId) {\n this._systemId = systemId;\n this.system._set(systemId, this);\n }\n\n this._initState(options?.snapshot ?? options?.state);\n\n if (systemId && (this._snapshot as any).status !== 'active') {\n this.system._unregister(this);\n }\n }\n\n private _initState(persistedState?: Snapshot<unknown>) {\n try {\n this._snapshot = persistedState\n ? this.logic.restoreSnapshot\n ? this.logic.restoreSnapshot(persistedState, this._actorScope)\n : persistedState\n : this.logic.getInitialSnapshot(this._actorScope, this.options?.input);\n } catch (err) {\n // if we get here then it means that we assign a value to this._snapshot that is not of the correct type\n // we can't get the true `TSnapshot & { status: 'error'; }`, it's impossible\n // so right now this is a lie of sorts\n this._snapshot = {\n status: 'error',\n output: undefined,\n error: err\n } as any;\n }\n }\n\n // array of functions to defer\n private _deferred: Array<() => void> = [];\n\n private update(snapshot: SnapshotFrom<TLogic>, event: EventObject): void {\n // Update state\n this._snapshot = snapshot;\n\n // Execute deferred effects\n let deferredFn: (typeof this._deferred)[number] | undefined;\n\n while ((deferredFn = this._deferred.shift())) {\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 this._deferred.length = 0;\n this._snapshot = {\n ...(snapshot as any),\n status: 'error',\n error: err\n };\n }\n }\n\n switch ((this._snapshot as any).status) {\n case 'active':\n for (const observer of this.observers) {\n try {\n observer.next?.(snapshot);\n } catch (err) {\n reportUnhandledError(err);\n }\n }\n break;\n case 'done':\n // next observers are meant to be notified about done snapshots\n // this can be seen as something that is different from how observable work\n // but with observables `complete` callback is called without any arguments\n // it's more ergonomic for XState to treat a done snapshot as a \"next\" value\n // and the completion event as something that is separate,\n // something that merely follows emitting that done snapshot\n for (const observer of this.observers) {\n try {\n observer.next?.(snapshot);\n } catch (err) {\n reportUnhandledError(err);\n }\n }\n\n this._stopProcedure();\n this._complete();\n this._doneEvent = createDoneActorEvent(\n this.id,\n (this._snapshot as any).output\n );\n if (this._parent) {\n this.system._relay(this, this._parent, this._doneEvent);\n }\n\n break;\n case 'error':\n this._error((this._snapshot as any).error);\n break;\n }\n this.system._sendInspectionEvent({\n type: '@xstate.snapshot',\n actorRef: this,\n event,\n snapshot\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.add(observer);\n } else {\n switch ((this._snapshot as any).status) {\n case 'done':\n try {\n observer.complete?.();\n } catch (err) {\n reportUnhandledError(err);\n }\n break;\n case 'error': {\n const err = (this._snapshot as any).error;\n if (!observer.error) {\n reportUnhandledError(err);\n } else {\n try {\n observer.error(err);\n } catch (err) {\n reportUnhandledError(err);\n }\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.set(type, listeners);\n }\n const wrappedHandler = handler.bind(undefined);\n listeners.add(wrappedHandler);\n\n return {\n unsubscribe: () => {\n listeners.delete(wrappedHandler);\n }\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._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.${this.id}`,\n snapshot\n });\n }\n },\n error: () => {}\n });\n }\n\n this.system._register(this.sessionId, this);\n if (this._systemId) {\n this.system._set(this._systemId, this);\n }\n this._processingStatus = ProcessingStatus.Running;\n\n // TODO: this isn't correct when rehydrating\n const initEvent = createInitEvent(this.options.input);\n\n this.system._sendInspectionEvent({\n type: '@xstate.event',\n sourceRef: this._parent,\n actorRef: this,\n event: initEvent\n });\n\n const status = (this._snapshot as any).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 this.update(\n this._snapshot,\n initEvent 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 any).error);\n return this;\n }\n\n if (!this._parent) {\n this.system.start();\n }\n\n if (this.logic.start) {\n try {\n this.logic.start(this._snapshot, this._actorScope);\n } catch (err) {\n this._snapshot = {\n ...(this._snapshot as any),\n status: 'error',\n error: err\n };\n this._error(err);\n return this;\n }\n }\n\n // TODO: this notifies all subscribers but usually this is redundant\n // there is no real change happening here\n // we need to rethink if this needs to be refactored\n this.update(this._snapshot, initEvent as unknown as EventFromLogic<TLogic>);\n\n if (this.options.devTools) {\n this.attachDevTools();\n }\n\n this.mailbox.start();\n\n return this;\n }\n\n private _process(event: EventFromLogic<TLogic>) {\n let nextState;\n let caughtError;\n try {\n nextState = this.logic.transition(\n this._snapshot,\n event,\n 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 const { err } = caughtError;\n\n this._snapshot = {\n ...(this._snapshot as any),\n status: 'error',\n error: err\n };\n this._error(err);\n return;\n }\n\n this.update(nextState, event);\n if (event.type === XSTATE_STOP) {\n this._stopProcedure();\n this._complete();\n }\n }\n\n private _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 return this;\n }\n this.mailbox.enqueue({ type: XSTATE_STOP } as any);\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('A non-root actor cannot be stopped directly.');\n }\n return this._stop();\n }\n private _complete(): void {\n for (const observer of this.observers) {\n try {\n observer.complete?.();\n } catch (err) {\n reportUnhandledError(err);\n }\n }\n this.observers.clear();\n }\n private _reportError(err: unknown): void {\n if (!this.observers.size) {\n if (!this._parent) {\n reportUnhandledError(err);\n }\n return;\n }\n let reportError = false;\n\n for (const observer of this.observers) {\n const errorListener = observer.error;\n reportError ||= !errorListener;\n try {\n errorListener?.(err);\n } catch (err2) {\n reportUnhandledError(err2);\n }\n }\n this.observers.clear();\n if (reportError) {\n reportUnhandledError(err);\n }\n }\n private _error(err: unknown): void {\n this._stopProcedure();\n this._reportError(err);\n if (this._parent) {\n this.system._relay(\n this,\n this._parent,\n createErrorActorEvent(this.id, err)\n );\n }\n }\n // TODO: atm children don't belong entirely to the actor so\n // in a way - it's not even super aware of them\n // so we can't stop them from here but we really should!\n // right now, they are being stopped within the machine's transition\n // but that could throw and leave us with \"orphaned\" active actors\n private _stopProcedure(): this {\n if (this._processingStatus !== ProcessingStatus.Running) {\n // Actor already stopped; do nothing\n return this;\n }\n\n // Cancel all delayed events\n this.system.scheduler.cancelAll(this);\n\n // TODO: mailbox.reset\n this.mailbox.clear();\n // TODO: after `stop` we must prepare ourselves for receiving events again\n // events sent *after* stop signal must be queued\n // it seems like this should be the common behavior for all of our consumers\n // so perhaps this should be unified somehow for all of them\n this.mailbox = new Mailbox(this._process.bind(this));\n\n this._processingStatus = ProcessingStatus.Stopped;\n this.system._unregister(this);\n\n return this;\n }\n\n /** @internal */\n public _send(event: EventFromLogic<TLogic>) {\n if (this._processingStatus === ProcessingStatus.Stopped) {\n // do nothing\n if (isDevelopment) {\n const eventString = JSON.stringify(event);\n\n console.warn(\n `Event \"${event.type}\" was sent to stopped actor \"${this.id} (${this.sessionId})\". This actor has already reached its final state, and will not transition.\\nEvent: ${eventString}`\n );\n }\n return;\n }\n\n this.mailbox.enqueue(event);\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 public send(event: EventFromLogic<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 private attachDevTools(): void {\n const { devTools } = this.options;\n if (devTools) {\n const resolvedDevToolsAdapter =\n typeof devTools === 'function' ? devTools : devToolsAdapter;\n\n resolvedDevToolsAdapter(this);\n }\n }\n public toJSON() {\n return {\n xstate$$type: $$ACTOR_TYPE,\n id: this.id\n };\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.state}\n * @see https://stately.ai/docs/persistence\n */\n public getPersistedSnapshot(): Snapshot<unknown>;\n public getPersistedSnapshot(options?: unknown): Snapshot<unknown> {\n return this.logic.getPersistedSnapshot(this._snapshot, options);\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 represent an actor's last emitted value.\n *\n * When an actor receives an event, its internal state may change. An actor\n * may emit a snapshot when a state transition occurs.\n *\n * Note that some actors, such as callback actors generated with\n * `fromCallback`, 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\nexport type RequiredActorOptionsKeys<TLogic extends AnyActorLogic> =\n undefined extends InputFrom<TLogic> ? never : 'input';\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 fromCallback}, {@link fromEventObservable},\n * {@link fromObservable}, {@link fromPromise}, and {@link fromTransition}.\n * @param options - Actor options\n */\nexport function createActor<TLogic extends AnyActorLogic>(\n logic: TLogic,\n ...[options]: ConditionalRequired<\n [\n options?: ActorOptions<TLogic> & {\n [K in RequiredActorOptionsKeys<TLogic>]: unknown;\n }\n ],\n IsNotNever<RequiredActorOptionsKeys<TLogic>>\n >\n): Actor<TLogic> {\n return new Actor(logic, options);\n}\n\n/**\n * Creates a new Interpreter instance for the given machine with the provided\n * options, if any.\n *\n * @deprecated Use `createActor` instead\n * @alias\n */\nexport const interpret = createActor;\n\n/**\n * @deprecated Use `Actor` instead.\n * @alias\n */\nexport type Interpreter = typeof Actor;\n","import isDevelopment from '#is-development';\nimport {\n AnyActorScope,\n AnyMachineSnapshot,\n EventObject,\n MachineContext,\n ActionArgs,\n ParameterizedObject,\n BuiltinActionResolution\n} from '../types.ts';\n\ntype ResolvableSendId<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject\n> =\n | string\n | ((\n args: ActionArgs<TContext, TExpressionEvent, TEvent>,\n params: TParams\n ) => string);\n\nfunction resolveCancel(\n _: AnyActorScope,\n snapshot: AnyMachineSnapshot,\n actionArgs: ActionArgs<any, any, any>,\n actionParams: ParameterizedObject['params'] | undefined,\n { sendId }: { sendId: ResolvableSendId<any, any, any, any> }\n): BuiltinActionResolution {\n const resolvedSendId =\n typeof sendId === 'function' ? sendId(actionArgs, actionParams) : sendId;\n return [snapshot, { sendId: resolvedSendId }, undefined];\n}\n\nfunction executeCancel(actorScope: AnyActorScope, params: { sendId: string }) {\n actorScope.defer(() => {\n actorScope.system.scheduler.cancel(actorScope.self, params.sendId);\n });\n}\n\nexport interface CancelAction<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject\n> {\n (args: ActionArgs<TContext, TExpressionEvent, TEvent>, params: TParams): void;\n}\n\n/**\n * Cancels a delayed `sendTo(...)` action that is waiting to be executed. The\n * canceled `sendTo(...)` action will not send its event or execute, unless the\n * `delay` has already elapsed before `cancel(...)` is called.\n *\n * @example\n *\n * ```ts\n * import { createMachine, sendTo, cancel } from 'xstate';\n *\n * const machine = createMachine({\n * // ...\n * on: {\n * sendEvent: {\n * actions: sendTo(\n * 'some-actor',\n * { type: 'someEvent' },\n * {\n * id: 'some-id',\n * delay: 1000\n * }\n * )\n * },\n * cancelEvent: {\n * actions: cancel('some-id')\n * }\n * }\n * });\n * ```\n *\n * @param sendId The `id` of the `sendTo(...)` action to cancel.\n */\nexport function cancel<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject\n>(\n sendId: ResolvableSendId<TContext, TExpressionEvent, TParams, TEvent>\n): CancelAction<TContext, TExpressionEvent, TParams, TEvent> {\n function cancel(\n _args: ActionArgs<TContext, TExpressionEvent, TEvent>,\n _params: TParams\n ) {\n if (isDevelopment) {\n throw new Error(`This isn't supposed to be called`);\n }\n }\n\n cancel.type = 'xstate.cancel';\n cancel.sendId = sendId;\n\n cancel.resolve = resolveCancel;\n cancel.execute = executeCancel;\n\n return cancel;\n}\n","import isDevelopment from '#is-development';\nimport { cloneMachineSnapshot } from '../State.ts';\nimport { ProcessingStatus, createActor } from '../createActor.ts';\nimport {\n ActionArgs,\n ActionFunction,\n AnyActorLogic,\n AnyActorRef,\n AnyActorScope,\n AnyMachineSnapshot,\n ConditionalRequired,\n EventObject,\n InputFrom,\n IsLiteralString,\n IsNotNever,\n MachineContext,\n Mapper,\n ParameterizedObject,\n ProvidedActor,\n RequiredActorOptions,\n BuiltinActionResolution,\n UnifiedArg\n} from '../types.ts';\nimport { resolveReferencedActor } from '../utils.ts';\n\ntype ResolvableActorId<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TEvent extends EventObject,\n TId extends string | undefined\n> = TId | ((args: UnifiedArg<TContext, TExpressionEvent, TEvent>) => TId);\n\nfunction resolveSpawn(\n actorScope: AnyActorScope,\n snapshot: AnyMachineSnapshot,\n actionArgs: ActionArgs<any, any, any>,\n _actionParams: ParameterizedObject['params'] | undefined,\n {\n id,\n systemId,\n src,\n input,\n syncSnapshot\n }: {\n id: ResolvableActorId<MachineContext, EventObject, EventObject, string>;\n systemId: string | undefined;\n src: AnyActorLogic | string;\n input?: unknown;\n syncSnapshot: boolean;\n }\n): BuiltinActionResolution {\n const logic =\n typeof src === 'string'\n ? resolveReferencedActor(snapshot.machine, src)\n : src;\n const resolvedId = typeof id === 'function' ? id(actionArgs) : id;\n let actorRef: AnyActorRef | undefined;\n let resolvedInput: unknown | undefined = undefined;\n\n if (logic) {\n resolvedInput =\n typeof input === 'function'\n ? input({\n context: snapshot.context,\n event: actionArgs.event,\n self: actorScope.self\n })\n : input;\n actorRef = createActor(logic, {\n id: resolvedId,\n src,\n parent: actorScope.self,\n syncSnapshot,\n systemId,\n input: resolvedInput\n });\n }\n\n if (isDevelopment && !actorRef) {\n console.warn(\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions,@typescript-eslint/no-base-to-string\n `Actor type '${src}' not found in machine '${actorScope.id}'.`\n );\n }\n return [\n cloneMachineSnapshot(snapshot, {\n children: {\n ...snapshot.children,\n [resolvedId]: actorRef!\n }\n }),\n {\n id,\n systemId,\n actorRef,\n src,\n input: resolvedInput\n },\n undefined\n ];\n}\n\nfunction executeSpawn(\n actorScope: AnyActorScope,\n { actorRef }: { id: string; actorRef: AnyActorRef }\n) {\n if (!actorRef) {\n return;\n }\n\n actorScope.defer(() => {\n if (actorRef._processingStatus === ProcessingStatus.Stopped) {\n return;\n }\n actorRef.start();\n });\n}\n\nexport interface SpawnAction<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject,\n TActor extends ProvidedActor\n> {\n (args: ActionArgs<TContext, TExpressionEvent, TEvent>, params: TParams): void;\n _out_TActor?: TActor;\n}\n\ninterface SpawnActionOptions<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TEvent extends EventObject,\n TActor extends ProvidedActor\n> {\n id?: ResolvableActorId<TContext, TExpressionEvent, TEvent, TActor['id']>;\n systemId?: string;\n input?:\n | Mapper<TContext, TEvent, InputFrom<TActor['logic']>, TEvent>\n | InputFrom<TActor['logic']>;\n syncSnapshot?: boolean;\n}\n\ntype DistributeActors<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TEvent extends EventObject,\n TActor extends ProvidedActor\n> =\n | (TActor extends any\n ? ConditionalRequired<\n [\n src: TActor['src'],\n options?: SpawnActionOptions<\n TContext,\n TExpressionEvent,\n TEvent,\n TActor\n > & {\n [K in RequiredActorOptions<TActor>]: unknown;\n }\n ],\n IsNotNever<RequiredActorOptions<TActor>>\n >\n : never)\n | [\n src: AnyActorLogic,\n options?: SpawnActionOptions<\n TContext,\n TExpressionEvent,\n TEvent,\n ProvidedActor\n > & { id?: never }\n ];\n\ntype SpawnArguments<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TEvent extends EventObject,\n TActor extends ProvidedActor\n> =\n IsLiteralString<TActor['src']> extends true\n ? DistributeActors<TContext, TExpressionEvent, TEvent, TActor>\n : [\n src: string | AnyActorLogic,\n options?: {\n id?: ResolvableActorId<TContext, TExpressionEvent, TEvent, string>;\n systemId?: string;\n input?: unknown;\n syncSnapshot?: boolean;\n }\n ];\n\nexport function spawnChild<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject,\n TActor extends ProvidedActor\n>(\n ...[\n src,\n { id, systemId, input, syncSnapshot = false } = {} as any\n ]: SpawnArguments<TContext, TExpressionEvent, TEvent, TActor>\n): ActionFunction<\n TContext,\n TExpressionEvent,\n TEvent,\n TParams,\n TActor,\n never,\n never,\n never,\n never\n> {\n function spawnChild(\n _args: ActionArgs<TContext, TExpressionEvent, TEvent>,\n _params: TParams\n ) {\n if (isDevelopment) {\n throw new Error(`This isn't supposed to be called`);\n }\n }\n\n spawnChild.type = 'xstate.spawnChild';\n spawnChild.id = id;\n spawnChild.systemId = systemId;\n spawnChild.src = src;\n spawnChild.input = input;\n spawnChild.syncSnapshot = syncSnapshot;\n\n spawnChild.resolve = resolveSpawn;\n spawnChild.execute = executeSpawn;\n\n return spawnChild;\n}\n","import isDevelopment from '#is-development';\nimport { cloneMachineSnapshot } from '../State.ts';\nimport { ProcessingStatus } from '../createActor.ts';\nimport {\n ActionArgs,\n AnyActorRef,\n AnyActorScope,\n AnyMachineSnapshot,\n EventObject,\n MachineContext,\n ParameterizedObject,\n BuiltinActionResolution\n} from '../types.ts';\n\ntype ResolvableActorRef<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject\n> =\n | string\n | AnyActorRef\n | ((\n args: ActionArgs<TContext, TExpressionEvent, TEvent>,\n params: TParams\n ) => AnyActorRef | string);\n\nfunction resolveStop(\n _: AnyActorScope,\n snapshot: AnyMachineSnapshot,\n args: ActionArgs<any, any, any>,\n actionParams: ParameterizedObject['params'] | undefined,\n { actorRef }: { actorRef: ResolvableActorRef<any, any, any, any> }\n): BuiltinActionResolution {\n const actorRefOrString =\n typeof actorRef === 'function' ? actorRef(args, actionParams) : actorRef;\n const resolvedActorRef: AnyActorRef | undefined =\n typeof actorRefOrString === 'string'\n ? snapshot.children[actorRefOrString]\n : actorRefOrString;\n\n let children = snapshot.children;\n if (resolvedActorRef) {\n children = { ...children };\n delete children[resolvedActorRef.id];\n }\n return [\n cloneMachineSnapshot(snapshot, {\n children\n }),\n resolvedActorRef,\n undefined\n ];\n}\nfunction executeStop(\n actorScope: AnyActorScope,\n actorRef: AnyActorRef | undefined\n) {\n if (!actorRef) {\n return;\n }\n\n // we need to eagerly unregister it here so a new actor with the same systemId can be registered immediately\n // since we defer actual stopping of the actor but we don't defer actor creations (and we can't do that)\n // this could throw on `systemId` collision, for example, when dealing with reentering transitions\n actorScope.system._unregister(actorRef);\n\n // this allows us to prevent an actor from being started if it gets stopped within the same macrostep\n // this can happen, for example, when the invoking state is being exited immediately by an always transition\n if (actorRef._processingStatus !== ProcessingStatus.Running) {\n actorScope.stopChild(actorRef);\n return;\n }\n // stopping a child enqueues a stop event in the child actor's mailbox\n // we need for all of the already enqueued events to be processed before we stop the child\n // the parent itself might want to send some events to a child (for example from exit actions on the invoking state)\n // and we don't want to ignore those events\n actorScope.defer(() => {\n actorScope.stopChild(actorRef);\n });\n}\n\nexport interface StopAction<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject\n> {\n (args: ActionArgs<TContext, TExpressionEvent, TEvent>, params: TParams): void;\n}\n\n/**\n * Stops a child actor.\n *\n * @param actorRef The actor to stop.\n */\nexport function stopChild<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject\n>(\n actorRef: ResolvableActorRef<TContext, TExpressionEvent, TParams, TEvent>\n): StopAction<TContext, TExpressionEvent, TParams, TEvent> {\n function stop(\n _args: ActionArgs<TContext, TExpressionEvent, TEvent>,\n _params: TParams\n ) {\n if (isDevelopment) {\n throw new Error(`This isn't supposed to be called`);\n }\n }\n\n stop.type = 'xstate.stopChild';\n stop.actorRef = actorRef;\n\n stop.resolve = resolveStop;\n stop.execute = executeStop;\n\n return stop;\n}\n\n/**\n * Stops a child actor.\n *\n * @deprecated Use `stopChild(...)` instead\n * @alias\n */\nexport const stop = stopChild;\n","import isDevelopment from '#is-development';\nimport type {\n EventObject,\n StateValue,\n MachineContext,\n ParameterizedObject,\n AnyMachineSnapshot,\n NoRequiredParams,\n WithDynamicParams,\n Identity,\n Elements,\n DoNotInfer\n} from './types.ts';\nimport { isStateId } from './stateUtils.ts';\n\ntype SingleGuardArg<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TGuardArg\n> = [TGuardArg] extends [{ type: string }]\n ? Identity<TGuardArg>\n : [TGuardArg] extends [string]\n ? TGuardArg\n : GuardPredicate<TContext, TExpressionEvent, TParams, ParameterizedObject>;\n\ntype NormalizeGuardArg<TGuardArg> = TGuardArg extends { type: string }\n ? Identity<TGuardArg> & { params: unknown }\n : TGuardArg extends string\n ? { type: TGuardArg; params: undefined }\n : '_out_TGuard' extends keyof TGuardArg\n ? TGuardArg['_out_TGuard'] & ParameterizedObject\n : never;\n\ntype NormalizeGuardArgArray<TArg extends unknown[]> = Elements<{\n [K in keyof TArg]: NormalizeGuardArg<TArg[K]>;\n}>;\n\nexport type GuardPredicate<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TGuard extends ParameterizedObject\n> = {\n (args: GuardArgs<TContext, TExpressionEvent>, params: TParams): boolean;\n _out_TGuard?: TGuard;\n};\n\nexport interface GuardArgs<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject\n> {\n context: TContext;\n event: TExpressionEvent;\n}\n\nexport type Guard<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TGuard extends ParameterizedObject\n> =\n | NoRequiredParams<TGuard>\n | WithDynamicParams<TContext, TExpressionEvent, TGuard>\n | GuardPredicate<TContext, TExpressionEvent, TParams, TGuard>;\n\nexport type UnknownGuard = UnknownReferencedGuard | UnknownInlineGuard;\n\ntype UnknownReferencedGuard = Guard<\n MachineContext,\n EventObject,\n ParameterizedObject['params'],\n ParameterizedObject\n>;\n\ntype UnknownInlineGuard = Guard<\n MachineContext,\n EventObject,\n undefined,\n ParameterizedObject\n>;\n\ninterface BuiltinGuard {\n (): boolean;\n check: (\n snapshot: AnyMachineSnapshot,\n guardArgs: GuardArgs<any, any>,\n params: unknown\n ) => boolean;\n}\n\nfunction checkStateIn(\n snapshot: AnyMachineSnapshot,\n _: GuardArgs<any, any>,\n { stateValue }: { stateValue: StateValue }\n) {\n if (typeof stateValue === 'string' && isStateId(stateValue)) {\n const target = snapshot.machine.getStateNodeById(stateValue);\n return snapshot._nodes.some((sn) => sn === target);\n }\n\n return snapshot.matches(stateValue);\n}\n\nexport function stateIn<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined\n>(\n stateValue: StateValue\n): GuardPredicate<\n TContext,\n TExpressionEvent,\n TParams,\n any // TODO: recheck if we could replace this with something better here\n> {\n function stateIn() {\n if (isDevelopment) {\n throw new Error(`This isn't supposed to be called`);\n }\n return false;\n }\n\n stateIn.check = checkStateIn;\n stateIn.stateValue = stateValue;\n\n return stateIn;\n}\n\nfunction checkNot(\n snapshot: AnyMachineSnapshot,\n { context, event }: GuardArgs<any, any>,\n { guards }: { guards: readonly UnknownGuard[] }\n) {\n return !evaluateGuard(guards[0], context, event, snapshot);\n}\n\n/**\n * Higher-order guard that evaluates to `true` if the `guard` passed to it\n * evaluates to `false`.\n *\n * @category Guards\n * @example\n *\n * ```ts\n * import { setup, not } from 'xstate';\n *\n * const machine = setup({\n * guards: {\n * someNamedGuard: () => false\n * }\n * }).createMachine({\n * on: {\n * someEvent: {\n * guard: not('someNamedGuard'),\n * actions: () => {\n * // will be executed if guard in `not(...)`\n * // evaluates to `false`\n * }\n * }\n * }\n * });\n * ```\n *\n * @returns A guard\n */\nexport function not<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TArg\n>(\n guard: SingleGuardArg<TContext, TExpressionEvent, unknown, TArg>\n): GuardPredicate<\n TContext,\n TExpressionEvent,\n unknown,\n NormalizeGuardArg<DoNotInfer<TArg>>\n> {\n function not(_args: GuardArgs<TContext, TExpressionEvent>, _params: unknown) {\n if (isDevelopment) {\n throw new Error(`This isn't supposed to be called`);\n }\n return false;\n }\n\n not.check = checkNot;\n not.guards = [guard];\n\n return not;\n}\n\nfunction checkAnd(\n snapshot: AnyMachineSnapshot,\n { context, event }: GuardArgs<any, any>,\n { guards }: { guards: readonly UnknownGuard[] }\n) {\n return guards.every((guard) =>\n evaluateGuard(guard, context, event, snapshot)\n );\n}\n\n/**\n * Higher-order guard that evaluates to `true` if all `guards` passed to it\n * evaluate to `true`.\n *\n * @category Guards\n * @example\n *\n * ```ts\n * import { setup, and } from 'xstate';\n *\n * const machine = setup({\n * guards: {\n * someNamedGuard: () => true\n * }\n * }).createMachine({\n * on: {\n * someEvent: {\n * guard: and([({ context }) => context.value > 0, 'someNamedGuard']),\n * actions: () => {\n * // will be executed if all guards in `and(...)`\n * // evaluate to true\n * }\n * }\n * }\n * });\n * ```\n *\n * @returns A guard action object\n */\nexport function and<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TArg extends unknown[]\n>(\n guards: readonly [\n ...{\n [K in keyof TArg]: SingleGuardArg<\n TContext,\n TExpressionEvent,\n unknown,\n TArg[K]\n >;\n }\n ]\n): GuardPredicate<\n TContext,\n TExpressionEvent,\n unknown,\n NormalizeGuardArgArray<DoNotInfer<TArg>>\n> {\n function and(_args: GuardArgs<TContext, TExpressionEvent>, _params: unknown) {\n if (isDevelopment) {\n throw new Error(`This isn't supposed to be called`);\n }\n return false;\n }\n\n and.check = checkAnd;\n and.guards = guards;\n\n return and;\n}\n\nfunction checkOr(\n snapshot: AnyMachineSnapshot,\n { context, event }: GuardArgs<any, any>,\n { guards }: { guards: readonly UnknownGuard[] }\n) {\n return guards.some((guard) => evaluateGuard(guard, context, event, snapshot));\n}\n\n/**\n * Higher-order guard that evaluates to `true` if any of the `guards` passed to\n * it evaluate to `true`.\n *\n * @category Guards\n * @example\n *\n * ```ts\n * import { setup, or } from 'xstate';\n *\n * const machine = setup({\n * guards: {\n * someNamedGuard: () => true\n * }\n * }).createMachine({\n * on: {\n * someEvent: {\n * guard: or([({ context }) => context.value > 0, 'someNamedGuard']),\n * actions: () => {\n * // will be executed if any of the guards in `or(...)`\n * // evaluate to true\n * }\n * }\n * }\n * });\n * ```\n *\n * @returns A guard action object\n */\nexport function or<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TArg extends unknown[]\n>(\n guards: readonly [\n ...{\n [K in keyof TArg]: SingleGuardArg<\n TContext,\n TExpressionEvent,\n unknown,\n TArg[K]\n >;\n }\n ]\n): GuardPredicate<\n TContext,\n TExpressionEvent,\n unknown,\n NormalizeGuardArgArray<DoNotInfer<TArg>>\n> {\n function or(_args: GuardArgs<TContext, TExpressionEvent>, _params: unknown) {\n if (isDevelopment) {\n throw new Error(`This isn't supposed to be called`);\n }\n return false;\n }\n\n or.check = checkOr;\n or.guards = guards;\n\n return or;\n}\n\n// TODO: throw on cycles (depth check should be enough)\nexport function evaluateGuard<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject\n>(\n guard: UnknownGuard | UnknownInlineGuard,\n context: TContext,\n event: TExpressionEvent,\n snapshot: AnyMachineSnapshot\n): boolean {\n const { machine } = snapshot;\n const isInline = typeof guard === 'function';\n\n const resolved = isInline\n ? guard\n : machine.implementations.guards[\n typeof guard === 'string' ? guard : guard.type\n ];\n\n if (!isInline && !resolved) {\n throw new Error(\n `Guard '${\n typeof guard === 'string' ? guard : guard.type\n }' is not implemented.'.`\n );\n }\n\n if (typeof resolved !== 'function') {\n return evaluateGuard(resolved!, context, event, snapshot);\n }\n\n const guardArgs = {\n context,\n event\n };\n\n const guardParams =\n isInline || typeof guard === 'string'\n ? undefined\n : 'params' in guard\n ? typeof guard.params === 'function'\n ? guard.params({ context, event })\n : guard.params\n : undefined;\n\n if (!('check' in resolved)) {\n // the existing type of `.guards` assumes non-nullable `TExpressionGuard`\n // inline guards expect `TExpressionGuard` to be set to `undefined`\n // it's fine to cast this here, our logic makes sure that we call those 2 \"variants\" correctly\n return resolved(guardArgs, guardParams as never);\n }\n\n const builtinGuard = resolved as unknown as BuiltinGuard;\n\n return builtinGuard.check(\n snapshot,\n guardArgs,\n resolved // this holds all params\n );\n}\n","import isDevelopment from '#is-development';\nimport { MachineSnapshot, cloneMachineSnapshot } from './State.ts';\nimport type { StateNode } from './StateNode.ts';\nimport { raise } from './actions.ts';\nimport { createAfterEvent, createDoneStateEvent } from './eventUtils.ts';\nimport { cancel } from './actions/cancel.ts';\nimport { spawnChild } from './actions/spawnChild.ts';\nimport { stopChild } from './actions/stopChild.ts';\nimport {\n XSTATE_INIT,\n NULL_EVENT,\n STATE_DELIMITER,\n STATE_IDENTIFIER,\n XSTATE_STOP,\n WILDCARD\n} from './constants.ts';\nimport { evaluateGuard } from './guards.ts';\nimport {\n ActionArgs,\n AnyEventObject,\n AnyHistoryValue,\n AnyMachineSnapshot,\n AnyStateNode,\n AnyTransitionDefinition,\n DelayedTransitionDefinition,\n EventObject,\n HistoryValue,\n InitialTransitionConfig,\n InitialTransitionDefinition,\n MachineContext,\n StateValue,\n StateValueMap,\n TransitionDefinition,\n TODO,\n UnknownAction,\n ParameterizedObject,\n AnyTransitionConfig,\n AnyActorScope,\n ActionExecutor,\n AnyStateMachine\n} from './types.ts';\nimport {\n resolveOutput,\n normalizeTarget,\n toArray,\n toStatePath,\n toTransitionConfigArray,\n isErrorActorEvent\n} from './utils.ts';\n\ntype StateNodeIterable<\n TContext extends MachineContext,\n TE extends EventObject\n> = Iterable<StateNode<TContext, TE>>;\ntype AnyStateNodeIterable = StateNodeIterable<any, any>;\n\ntype AdjList = Map<AnyStateNode, Array<AnyStateNode>>;\n\nconst isAtomicStateNode = (stateNode: StateNode<any, any>) =>\n stateNode.type === 'atomic' || stateNode.type === 'final';\n\nfunction getChildren<TContext extends MachineContext, TE extends EventObject>(\n stateNode: StateNode<TContext, TE>\n): Array<StateNode<TContext, TE>> {\n return Object.values(stateNode.states).filter((sn) => sn.type !== 'history');\n}\n\nfunction 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\n const adjList = getAdjList(nodeSet);\n\n // add descendants\n for (const s of nodeSet) {\n // if previously active, add existing child nodes\n if (s.type === 'compound' && (!adjList.get(s) || !adjList.get(s)!.length)) {\n getInitialStateNodesWithTheirAncestors(s).forEach((sn) =>\n nodeSet.add(sn)\n );\n } else {\n if (s.type === 'parallel') {\n for (const child of getChildren(s)) {\n if (child.type === 'history') {\n continue;\n }\n\n if (!nodeSet.has(child)) {\n const initialStates = getInitialStateNodesWithTheirAncestors(child);\n for (const initialStateNode of initialStates) {\n nodeSet.add(initialStateNode);\n }\n }\n }\n }\n }\n }\n\n // add all ancestors\n for (const s of nodeSet) {\n let m = s.parent;\n\n while (m) {\n nodeSet.add(m);\n m = m.parent;\n }\n }\n\n return nodeSet;\n}\n\nfunction getValueFromAdj(baseNode: AnyStateNode, adjList: AdjList): 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 if (isAtomicStateNode(childStateNode)) {\n return childStateNode.key;\n }\n } else {\n return {};\n }\n }\n\n const stateValue: StateValue = {};\n for (const childStateNode of childStateNodes) {\n stateValue[childStateNode.key] = getValueFromAdj(childStateNode, adjList);\n }\n\n return stateValue;\n}\n\nfunction getAdjList<TContext extends MachineContext, TE extends EventObject>(\n stateNodes: StateNodeIterable<TContext, TE>\n): AdjList {\n const adjList: AdjList = new Map();\n\n for (const s of stateNodes) {\n if (!adjList.has(s)) {\n adjList.set(s, []);\n }\n\n if (s.parent) {\n if (!adjList.has(s.parent)) {\n adjList.set(s.parent, []);\n }\n\n adjList.get(s.parent)!.push(s);\n }\n }\n\n return adjList;\n}\n\nexport function getStateValue(\n rootNode: AnyStateNode,\n stateNodes: AnyStateNodeIterable\n): StateValue {\n const config = getAllStateNodes(stateNodes);\n return getValueFromAdj(rootNode, getAdjList(config));\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 getCandidates<TEvent extends EventObject>(\n stateNode: StateNode<any, TEvent>,\n receivedEventType: TEvent['type']\n): Array<TransitionDefinition<any, TEvent>> {\n const candidates =\n stateNode.transitions.get(receivedEventType) ||\n [...stateNode.transitions.keys()]\n .filter((eventDescriptor) => {\n // check if transition is a wildcard transition,\n // which matches any non-transient events\n if (eventDescriptor === WILDCARD) {\n return true;\n }\n\n if (!eventDescriptor.endsWith('.*')) {\n return false;\n }\n\n if (isDevelopment && /.*\\*.+/.test(eventDescriptor)) {\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 \"${eventDescriptor}\" event.`\n );\n }\n\n const partialEventTokens = eventDescriptor.split('.');\n const eventTokens = receivedEventType.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 \"${eventDescriptor}\" transition.`\n );\n }\n\n return isLastToken;\n }\n\n if (partialEventToken !== eventToken) {\n return false;\n }\n }\n\n return true;\n })\n .sort((a, b) => b.length - a.length)\n .flatMap((key) => stateNode.transitions.get(key)!);\n\n return candidates;\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 if (!afterConfig) {\n return [];\n }\n\n const mutateEntryExit = (delay: string | number) => {\n const afterEvent = createAfterEvent(delay, stateNode.id);\n const eventType = afterEvent.type;\n\n stateNode.entry.push(\n raise(afterEvent, {\n id: eventType,\n delay\n })\n );\n stateNode.exit.push(cancel(eventType));\n return eventType;\n };\n\n const delayedTransitions = Object.keys(afterConfig).flatMap((delay) => {\n const configTransition = afterConfig[delay];\n const resolvedTransition =\n typeof configTransition === 'string'\n ? { target: configTransition }\n : configTransition;\n const resolvedDelay = Number.isNaN(+delay) ? delay : +delay;\n const eventType = mutateEntryExit(resolvedDelay);\n return toArray(resolvedTransition).map((transition) => ({\n ...transition,\n event: eventType,\n delay: resolvedDelay\n }));\n });\n return delayedTransitions.map((delayedTransition) => {\n const { delay } = delayedTransition;\n return {\n ...formatTransition(\n stateNode,\n delayedTransition.event,\n delayedTransition\n ),\n delay\n };\n });\n}\n\nexport function formatTransition(\n stateNode: AnyStateNode,\n descriptor: string,\n transitionConfig: AnyTransitionConfig\n): AnyTransitionDefinition {\n const normalizedTarget = normalizeTarget(transitionConfig.target);\n const reenter = transitionConfig.reenter ?? false;\n const target = resolveTarget(stateNode, normalizedTarget);\n\n // TODO: should this be part of a lint rule instead?\n if (isDevelopment && (transitionConfig as any).cond) {\n throw new Error(\n `State \"${stateNode.id}\" has declared \\`cond\\` for one of its transitions. This property has been renamed to \\`guard\\`. Please update your code.`\n );\n }\n\n const transition = {\n ...transitionConfig,\n actions: toArray(transitionConfig.actions),\n guard: transitionConfig.guard as never,\n target,\n source: stateNode,\n reenter,\n eventType: descriptor,\n toJSON: () => ({\n ...transition,\n source: `#${stateNode.id}`,\n target: target ? target.map((t) => `#${t.id}`) : undefined\n })\n };\n\n return transition;\n}\n\nexport function 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 if (stateNode.config.on) {\n for (const descriptor of Object.keys(stateNode.config.on)) {\n if (descriptor === NULL_EVENT) {\n throw new Error(\n 'Null events (\"\") cannot be specified as a transition key. Use `always: { ... }` instead.'\n );\n }\n const transitionsConfig = stateNode.config.on[descriptor];\n transitions.set(\n descriptor,\n toTransitionConfigArray(transitionsConfig).map((t) =>\n formatTransition(stateNode, descriptor, t)\n )\n );\n }\n }\n if (stateNode.config.onDone) {\n const descriptor = `xstate.done.state.${stateNode.id}`;\n transitions.set(\n descriptor,\n toTransitionConfigArray(stateNode.config.onDone).map((t) =>\n formatTransition(stateNode, descriptor, t)\n )\n );\n }\n for (const invokeDef of stateNode.invoke) {\n if (invokeDef.onDone) {\n const descriptor = `xstate.done.actor.${invokeDef.id}`;\n transitions.set(\n descriptor,\n toTransitionConfigArray(invokeDef.onDone).map((t) =>\n formatTransition(stateNode, descriptor, t)\n )\n );\n }\n if (invokeDef.onError) {\n const descriptor = `xstate.error.actor.${invokeDef.id}`;\n transitions.set(\n descriptor,\n toTransitionConfigArray(invokeDef.onError).map((t) =>\n formatTransition(stateNode, descriptor, t)\n )\n );\n }\n if (invokeDef.onSnapshot) {\n const descriptor = `xstate.snapshot.${invokeDef.id}`;\n transitions.set(\n descriptor,\n toTransitionConfigArray(invokeDef.onSnapshot).map((t) =>\n formatTransition(stateNode, descriptor, t)\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(delayedTransition);\n }\n return transitions as Map<string, TransitionDefinition<TContext, any>[]>;\n}\n\nexport function formatInitialTransition<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n stateNode: AnyStateNode,\n _target:\n | string\n | undefined\n | InitialTransitionConfig<TContext, TEvent, TODO, TODO, TODO, TODO>\n): InitialTransitionDefinition<TContext, TEvent> {\n const resolvedTarget =\n typeof _target === 'string'\n ? stateNode.states[_target]\n : _target\n ? stateNode.states[_target.target]\n : undefined;\n if (!resolvedTarget && _target) {\n throw new Error(\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions, @typescript-eslint/no-base-to-string\n `Initial state node \"${_target}\" not found on parent state node #${stateNode.id}`\n );\n }\n const transition: InitialTransitionDefinition<TContext, TEvent> = {\n source: stateNode,\n actions:\n !_target || typeof _target === 'string' ? [] : toArray(_target.actions),\n eventType: null as any,\n reenter: false,\n target: resolvedTarget ? [resolvedTarget] : [],\n toJSON: () => ({\n ...transition,\n source: `#${stateNode.id}`,\n target: resolvedTarget ? [`#${resolvedTarget.id}`] : []\n })\n };\n\n return transition;\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 `Invalid transition definition for state node '${stateNode.id}':\\n${err.message}`\n );\n }\n } else {\n throw new Error(\n `Invalid target: \"${target}\" is not a valid target from the root node. Did you mean \".${target}\"?`\n );\n }\n });\n}\n\nfunction resolveHistoryDefaultTransition<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(stateNode: AnyStateNode & { type: 'history' }) {\n const normalizedTarget = normalizeTarget<TContext, TEvent>(\n stateNode.config.target\n );\n if (!normalizedTarget) {\n return stateNode.parent!.initial;\n }\n return {\n target: normalizedTarget.map((t) =>\n typeof t === 'string' ? getStateNodeByPath(stateNode.parent!, t) : t\n )\n };\n}\n\nfunction isHistoryNode(\n stateNode: AnyStateNode\n): stateNode is AnyStateNode & { type: 'history' } {\n return stateNode.type === 'history';\n}\n\nfunction getInitialStateNodesWithTheirAncestors(stateNode: AnyStateNode) {\n const states = getInitialStateNodes(stateNode);\n for (const initialState of states) {\n for (const ancestor of getProperAncestors(initialState, stateNode)) {\n states.add(ancestor);\n }\n }\n return states;\n}\n\nexport function 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 iter(descStateNode.initial.target[0]);\n } else if (descStateNode.type === 'parallel') {\n for (const child of getChildren(descStateNode)) {\n iter(child);\n }\n }\n }\n\n iter(stateNode);\n\n return set;\n}\n/** Returns the child state node from its relative `stateKey`, or throws. */\nfunction getStateNode(stateNode: AnyStateNode, stateKey: string): AnyStateNode {\n if (isStateId(stateKey)) {\n return stateNode.machine.getStateNodeById(stateKey);\n }\n if (!stateNode.states) {\n throw new Error(\n `Unable to retrieve child state '${stateKey}' from '${stateNode.id}'; no child states exist.`\n );\n }\n const result = stateNode.states[stateKey];\n if (!result) {\n throw new Error(\n `Child state '${stateKey}' does not exist on '${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 */\nexport function getStateNodeByPath(\n stateNode: AnyStateNode,\n statePath: string | string[]\n): AnyStateNode {\n if (typeof statePath === 'string' && isStateId(statePath)) {\n try {\n return stateNode.machine.getStateNodeById(statePath);\n } catch {\n // try individual paths\n // throw e;\n }\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 */\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 `State '${stateValue}' does not exist on '${stateNode.id}'`\n );\n }\n return [stateNode, childStateNode];\n }\n\n const childStateKeys = Object.keys(stateValue);\n const childStateNodes: Array<AnyStateNode> = childStateKeys\n .map((subStateKey) => getStateNode(stateNode, subStateKey))\n .filter(Boolean);\n\n return [stateNode.machine.root, stateNode].concat(\n childStateNodes,\n childStateKeys.reduce((allSubStateNodes, subStateKey) => {\n const subStateNode = getStateNode(stateNode, subStateKey);\n if (!subStateNode) {\n return allSubStateNodes;\n }\n const subStateNodes = getStateNodes(\n subStateNode,\n stateValue[subStateKey]!\n );\n\n return allSubStateNodes.concat(subStateNodes);\n }, [] as Array<AnyStateNode>)\n );\n}\n\nfunction transitionAtomicNode<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n stateNode: AnyStateNode,\n stateValue: string,\n snapshot: MachineSnapshot<\n TContext,\n TEvent,\n any,\n any,\n any,\n any,\n any, // TMeta\n any // TStateSchema\n >,\n event: TEvent\n): Array<TransitionDefinition<TContext, TEvent>> | undefined {\n const childStateNode = getStateNode(stateNode, stateValue);\n const next = childStateNode.next(snapshot, event);\n\n if (!next || !next.length) {\n return stateNode.next(snapshot, event);\n }\n\n return next;\n}\n\nfunction transitionCompoundNode<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n stateNode: AnyStateNode,\n stateValue: StateValueMap,\n snapshot: MachineSnapshot<\n TContext,\n TEvent,\n any,\n any,\n any,\n any,\n any, // TMeta\n any // TStateSchema\n >,\n event: TEvent\n): Array<TransitionDefinition<TContext, TEvent>> | undefined {\n const subStateKeys = Object.keys(stateValue);\n\n const childStateNode = getStateNode(stateNode, subStateKeys[0]);\n const next = transitionNode(\n childStateNode,\n stateValue[subStateKeys[0]]!,\n snapshot,\n event\n );\n\n if (!next || !next.length) {\n return stateNode.next(snapshot, event);\n }\n\n return next;\n}\n\nfunction transitionParallelNode<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n stateNode: AnyStateNode,\n stateValue: StateValueMap,\n snapshot: MachineSnapshot<\n TContext,\n TEvent,\n any,\n any,\n any,\n any,\n any, // TMeta\n any // TStateSchema\n >,\n event: TEvent\n): Array<TransitionDefinition<TContext, TEvent>> | undefined {\n const allInnerTransitions: Array<TransitionDefinition<TContext, TEvent>> = [];\n\n for (const subStateKey of Object.keys(stateValue)) {\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 );\n if (innerTransitions) {\n allInnerTransitions.push(...innerTransitions);\n }\n }\n if (!allInnerTransitions.length) {\n return stateNode.next(snapshot, event);\n }\n\n return allInnerTransitions;\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): Array<TransitionDefinition<TContext, TEvent>> | undefined {\n // leaf node\n if (typeof stateValue === 'string') {\n return transitionAtomicNode(stateNode, stateValue, snapshot, event);\n }\n\n // compound node\n if (Object.keys(stateValue).length === 1) {\n return transitionCompoundNode(stateNode, stateValue, snapshot, event);\n }\n\n // parallel node\n return transitionParallelNode(stateNode, stateValue, snapshot, event);\n}\n\nfunction getHistoryNodes(stateNode: AnyStateNode): Array<AnyStateNode> {\n return Object.keys(stateNode.states)\n .map((key) => stateNode.states[key])\n .filter((sn) => sn.type === 'history');\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 hasIntersection<T>(s1: Iterable<T>, s2: Iterable<T>): boolean {\n const set1 = new Set(s1);\n const set2 = new Set(s2);\n\n for (const item of set1) {\n if (set2.has(item)) {\n return true;\n }\n }\n for (const item of set2) {\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 historyValue: AnyHistoryValue\n): Array<AnyTransitionDefinition> {\n const filteredTransitions = new Set<AnyTransitionDefinition>();\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 (\n hasIntersection(\n computeExitSet([t1], stateNodeSet, historyValue),\n computeExitSet([t2], stateNodeSet, historyValue)\n )\n ) {\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\nfunction findLeastCommonAncestor(\n stateNodes: Array<AnyStateNode>\n): AnyStateNode | undefined {\n const [head, ...tail] = stateNodes;\n for (const ancestor of getProperAncestors(head, undefined)) {\n if (tail.every((sn) => isDescendant(sn, ancestor))) {\n return ancestor;\n }\n }\n}\n\nfunction getEffectiveTargetStates(\n transition: Pick<AnyTransitionDefinition, 'target'>,\n historyValue: AnyHistoryValue\n): Array<AnyStateNode> {\n if (!transition.target) {\n return [];\n }\n\n const targets = new Set<AnyStateNode>();\n\n for (const targetNode of transition.target) {\n if (isHistoryNode(targetNode)) {\n if (historyValue[targetNode.id]) {\n for (const node of historyValue[targetNode.id]) {\n targets.add(node);\n }\n } else {\n for (const node of getEffectiveTargetStates(\n resolveHistoryDefaultTransition(targetNode),\n historyValue\n )) {\n targets.add(node);\n }\n }\n } else {\n targets.add(targetNode);\n }\n }\n\n return [...targets];\n}\n\nfunction getTransitionDomain(\n transition: AnyTransitionDefinition,\n historyValue: AnyHistoryValue\n): AnyStateNode | undefined {\n const targetStates = getEffectiveTargetStates(transition, historyValue);\n\n if (!targetStates) {\n return;\n }\n\n if (\n !transition.reenter &&\n targetStates.every(\n (target) =>\n target === transition.source || isDescendant(target, transition.source)\n )\n ) {\n return transition.source;\n }\n\n const lca = findLeastCommonAncestor(targetStates.concat(transition.source));\n\n if (lca) {\n return lca;\n }\n\n // at this point we know that it's a root transition since LCA couldn't be found\n if (transition.reenter) {\n return;\n }\n\n return transition.source.machine.root;\n}\n\nfunction computeExitSet(\n transitions: AnyTransitionDefinition[],\n stateNodeSet: Set<AnyStateNode>,\n historyValue: AnyHistoryValue\n): Array<AnyStateNode> {\n const statesToExit = new Set<AnyStateNode>();\n\n for (const t of transitions) {\n if (t.target?.length) {\n const domain = getTransitionDomain(t, historyValue);\n\n if (t.reenter && t.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\nfunction areStateNodeCollectionsEqual(\n prevStateNodes: StateNode[],\n nextStateNodeSet: Set<StateNode>\n) {\n if (prevStateNodes.length !== nextStateNodeSet.size) {\n return false;\n }\n for (const node of prevStateNodes) {\n if (!nextStateNodeSet.has(node)) {\n return false;\n }\n }\n return true;\n}\n\n/** https://www.w3.org/TR/scxml/#microstepProcedure */\nexport function microstep(\n transitions: Array<AnyTransitionDefinition>,\n currentSnapshot: AnyMachineSnapshot,\n actorScope: AnyActorScope,\n event: AnyEventObject,\n isInitial: boolean,\n internalQueue: Array<AnyEventObject>\n): AnyMachineSnapshot {\n if (!transitions.length) {\n return currentSnapshot;\n }\n const mutStateNodeSet = new Set(currentSnapshot._nodes);\n let historyValue = currentSnapshot.historyValue;\n\n const filteredTransitions = removeConflictingTransitions(\n transitions,\n mutStateNodeSet,\n historyValue\n );\n\n let nextState = currentSnapshot;\n\n // Exit states\n if (!isInitial) {\n [nextState, historyValue] = exitStates(\n nextState,\n event,\n actorScope,\n filteredTransitions,\n mutStateNodeSet,\n historyValue,\n internalQueue,\n actorScope.actionExecutor\n );\n }\n\n // Execute transition content\n nextState = resolveActionsAndContext(\n nextState,\n event,\n actorScope,\n filteredTransitions.flatMap((t) => t.actions),\n internalQueue,\n undefined\n );\n\n // Enter states\n nextState = enterStates(\n nextState,\n event,\n actorScope,\n filteredTransitions,\n mutStateNodeSet,\n internalQueue,\n historyValue,\n isInitial\n );\n\n const nextStateNodes = [...mutStateNodeSet];\n\n if (nextState.status === 'done') {\n nextState = resolveActionsAndContext(\n nextState,\n event,\n actorScope,\n nextStateNodes\n .sort((a, b) => b.order - a.order)\n .flatMap((state) => state.exit),\n internalQueue,\n undefined\n );\n }\n\n // eslint-disable-next-line no-useless-catch\n try {\n if (\n historyValue === currentSnapshot.historyValue &&\n areStateNodeCollectionsEqual(currentSnapshot._nodes, mutStateNodeSet)\n ) {\n return nextState;\n }\n return cloneMachineSnapshot(nextState, {\n _nodes: nextStateNodes,\n historyValue\n });\n } catch (e) {\n // TODO: Refactor this once proper error handling is implemented.\n // See https://github.com/statelyai/rfcs/pull/4\n throw e;\n }\n}\n\nfunction getMachineOutput(\n snapshot: AnyMachineSnapshot,\n event: AnyEventObject,\n actorScope: AnyActorScope,\n rootNode: AnyStateNode,\n rootCompletionNode: AnyStateNode\n) {\n if (rootNode.output === undefined) {\n return;\n }\n const doneStateEvent = createDoneStateEvent(\n rootCompletionNode.id,\n rootCompletionNode.output !== undefined && rootCompletionNode.parent\n ? resolveOutput(\n rootCompletionNode.output,\n snapshot.context,\n event,\n actorScope.self\n )\n : undefined\n );\n return resolveOutput(\n rootNode.output,\n snapshot.context,\n doneStateEvent,\n actorScope.self\n );\n}\n\nfunction enterStates(\n currentSnapshot: AnyMachineSnapshot,\n event: AnyEventObject,\n actorScope: AnyActorScope,\n filteredTransitions: AnyTransitionDefinition[],\n mutStateNodeSet: Set<AnyStateNode>,\n internalQueue: AnyEventObject[],\n historyValue: HistoryValue<any, any>,\n isInitial: boolean\n) {\n let nextSnapshot = currentSnapshot;\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 computeEntrySet(\n filteredTransitions,\n historyValue,\n statesForDefaultEntry,\n statesToEnter\n );\n\n // In the initial state, the root state node is \"entered\".\n if (isInitial) {\n statesForDefaultEntry.add(currentSnapshot.machine.root);\n }\n\n const completedNodes = new Set();\n\n for (const stateNodeToEnter of [...statesToEnter].sort(\n (a, b) => a.order - b.order\n )) {\n mutStateNodeSet.add(stateNodeToEnter);\n const actions: UnknownAction[] = [];\n\n // Add entry actions\n actions.push(...stateNodeToEnter.entry);\n\n for (const invokeDef of stateNodeToEnter.invoke) {\n actions.push(\n spawnChild(invokeDef.src, {\n ...invokeDef,\n syncSnapshot: !!invokeDef.onSnapshot\n })\n );\n }\n\n if (statesForDefaultEntry.has(stateNodeToEnter)) {\n const initialActions = stateNodeToEnter.initial.actions;\n actions.push(...initialActions);\n }\n\n nextSnapshot = resolveActionsAndContext(\n nextSnapshot,\n event,\n actorScope,\n actions,\n internalQueue,\n stateNodeToEnter.invoke.map((invokeDef) => invokeDef.id)\n );\n\n if (stateNodeToEnter.type === 'final') {\n const parent = stateNodeToEnter.parent;\n\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 nextSnapshot.context,\n event,\n actorScope.self\n )\n : undefined\n )\n );\n }\n while (\n ancestorMarker?.type === 'parallel' &&\n !completedNodes.has(ancestorMarker) &&\n isInFinalState(mutStateNodeSet, ancestorMarker)\n ) {\n completedNodes.add(ancestorMarker);\n internalQueue.push(createDoneStateEvent(ancestorMarker.id));\n rootCompletionNode = ancestorMarker;\n ancestorMarker = ancestorMarker.parent;\n }\n if (ancestorMarker) {\n continue;\n }\n\n nextSnapshot = cloneMachineSnapshot(nextSnapshot, {\n status: 'done',\n output: getMachineOutput(\n nextSnapshot,\n event,\n actorScope,\n nextSnapshot.machine.root,\n rootCompletionNode\n )\n });\n }\n }\n\n return nextSnapshot;\n}\n\nfunction computeEntrySet(\n transitions: Array<AnyTransitionDefinition>,\n historyValue: HistoryValue<any, any>,\n statesForDefaultEntry: Set<AnyStateNode>,\n statesToEnter: Set<AnyStateNode>\n) {\n for (const t of transitions) {\n const domain = getTransitionDomain(t, historyValue);\n\n for (const s of t.target || []) {\n if (\n !isHistoryNode(s) &&\n // if the target is different than the source then it will *definitely* be entered\n (t.source !== s ||\n // we know that the domain can't lie within the source\n // if it's different than the source then it's outside of it and it means that the target has to be entered as well\n t.source !== domain ||\n // reentering transitions always enter the target, even if it's the source itself\n t.reenter)\n ) {\n statesToEnter.add(s);\n statesForDefaultEntry.add(s);\n }\n addDescendantStatesToEnter(\n s,\n historyValue,\n statesForDefaultEntry,\n statesToEnter\n );\n }\n const targetStates = getEffectiveTargetStates(t, historyValue);\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 statesToEnter,\n historyValue,\n statesForDefaultEntry,\n ancestors,\n !t.source.parent && t.reenter ? undefined : domain\n );\n }\n }\n}\n\nfunction addDescendantStatesToEnter<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n stateNode: AnyStateNode,\n historyValue: HistoryValue<any, any>,\n statesForDefaultEntry: Set<AnyStateNode>,\n statesToEnter: Set<AnyStateNode>\n) {\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\n addDescendantStatesToEnter(\n s,\n historyValue,\n statesForDefaultEntry,\n statesToEnter\n );\n }\n for (const s of historyStateNodes) {\n addProperAncestorStatesToEnter(\n s,\n stateNode.parent,\n statesToEnter,\n historyValue,\n statesForDefaultEntry\n );\n }\n } else {\n const historyDefaultTransition = resolveHistoryDefaultTransition<\n TContext,\n TEvent\n >(stateNode);\n for (const s of historyDefaultTransition.target) {\n statesToEnter.add(s);\n\n if (historyDefaultTransition === stateNode.parent?.initial) {\n statesForDefaultEntry.add(stateNode.parent);\n }\n\n addDescendantStatesToEnter(\n s,\n historyValue,\n statesForDefaultEntry,\n statesToEnter\n );\n }\n\n for (const s of historyDefaultTransition.target) {\n addProperAncestorStatesToEnter(\n s,\n stateNode.parent,\n statesToEnter,\n historyValue,\n statesForDefaultEntry\n );\n }\n }\n } else {\n if (stateNode.type === 'compound') {\n const [initialState] = stateNode.initial.target;\n\n if (!isHistoryNode(initialState)) {\n statesToEnter.add(initialState);\n statesForDefaultEntry.add(initialState);\n }\n addDescendantStatesToEnter(\n initialState,\n historyValue,\n statesForDefaultEntry,\n statesToEnter\n );\n\n addProperAncestorStatesToEnter(\n initialState,\n stateNode,\n statesToEnter,\n historyValue,\n statesForDefaultEntry\n );\n } else {\n if (stateNode.type === 'parallel') {\n for (const child of getChildren(stateNode).filter(\n (sn) => !isHistoryNode(sn)\n )) {\n if (![...statesToEnter].some((s) => isDescendant(s, child))) {\n if (!isHistoryNode(child)) {\n statesToEnter.add(child);\n statesForDefaultEntry.add(child);\n }\n addDescendantStatesToEnter(\n child,\n historyValue,\n statesForDefaultEntry,\n statesToEnter\n );\n }\n }\n }\n }\n }\n}\n\nfunction addAncestorStatesToEnter(\n statesToEnter: Set<AnyStateNode>,\n historyValue: HistoryValue<any, any>,\n statesForDefaultEntry: Set<AnyStateNode>,\n ancestors: AnyStateNode[],\n reentrancyDomain?: AnyStateNode\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).filter((sn) => !isHistoryNode(sn))) {\n if (![...statesToEnter].some((s) => isDescendant(s, child))) {\n statesToEnter.add(child);\n addDescendantStatesToEnter(\n child,\n historyValue,\n statesForDefaultEntry,\n statesToEnter\n );\n }\n }\n }\n }\n}\n\nfunction addProperAncestorStatesToEnter(\n stateNode: AnyStateNode,\n toStateNode: AnyStateNode | undefined,\n statesToEnter: Set<AnyStateNode>,\n historyValue: HistoryValue<any, any>,\n statesForDefaultEntry: Set<AnyStateNode>\n) {\n addAncestorStatesToEnter(\n statesToEnter,\n historyValue,\n statesForDefaultEntry,\n getProperAncestors(stateNode, toStateNode)\n );\n}\n\nfunction exitStates(\n currentSnapshot: AnyMachineSnapshot,\n event: AnyEventObject,\n actorScope: AnyActorScope,\n transitions: AnyTransitionDefinition[],\n mutStateNodeSet: Set<AnyStateNode>,\n historyValue: HistoryValue<any, any>,\n internalQueue: AnyEventObject[],\n _actionExecutor: ActionExecutor\n) {\n let nextSnapshot = currentSnapshot;\n const statesToExit = computeExitSet(\n transitions,\n mutStateNodeSet,\n historyValue\n );\n\n statesToExit.sort((a, b) => b.order - a.order);\n\n let changedHistory: typeof historyValue | undefined;\n\n // From SCXML algorithm: https://www.w3.org/TR/scxml/#exitStates\n for (const exitStateNode of statesToExit) {\n for (const historyNode of getHistoryNodes(exitStateNode)) {\n let predicate: (sn: AnyStateNode) => boolean;\n if (historyNode.history === 'deep') {\n predicate = (sn) =>\n isAtomicStateNode(sn) && isDescendant(sn, exitStateNode);\n } else {\n predicate = (sn) => {\n return sn.parent === exitStateNode;\n };\n }\n changedHistory ??= { ...historyValue };\n changedHistory[historyNode.id] =\n Array.from(mutStateNodeSet).filter(predicate);\n }\n }\n\n for (const s of statesToExit) {\n nextSnapshot = resolveActionsAndContext(\n nextSnapshot,\n event,\n actorScope,\n [...s.exit, ...s.invoke.map((def) => stopChild(def.id))],\n internalQueue,\n undefined\n );\n mutStateNodeSet.delete(s);\n }\n return [nextSnapshot, changedHistory || historyValue] as const;\n}\n\nexport interface BuiltinAction {\n (): void;\n type: `xstate.${string}`;\n resolve: (\n actorScope: AnyActorScope,\n snapshot: AnyMachineSnapshot,\n actionArgs: ActionArgs<any, any, any>,\n actionParams: ParameterizedObject['params'] | undefined,\n action: unknown,\n extra: unknown\n ) => [\n newState: AnyMachineSnapshot,\n params: unknown,\n actions?: UnknownAction[]\n ];\n retryResolve: (\n actorScope: AnyActorScope,\n snapshot: AnyMachineSnapshot,\n params: unknown\n ) => void;\n execute: (actorScope: AnyActorScope, params: unknown) => void;\n}\n\nfunction getAction(machine: AnyStateMachine, actionType: string) {\n return machine.implementations.actions[actionType];\n}\n\nfunction resolveAndExecuteActionsWithContext(\n currentSnapshot: AnyMachineSnapshot,\n event: AnyEventObject,\n actorScope: AnyActorScope,\n actions: UnknownAction[],\n extra: {\n internalQueue: AnyEventObject[];\n deferredActorIds: string[] | undefined;\n },\n retries: (readonly [BuiltinAction, unknown])[] | undefined\n): AnyMachineSnapshot {\n const { machine } = currentSnapshot;\n let intermediateSnapshot = currentSnapshot;\n\n for (const action of actions) {\n const isInline = typeof action === 'function';\n const resolvedAction = isInline\n ? action\n : // the existing type of `.actions` assumes non-nullable `TExpressionAction`\n // it's fine to cast this here to get a common type and lack of errors in the rest of the code\n // our logic below makes sure that we call those 2 \"variants\" correctly\n\n getAction(machine, typeof action === 'string' ? action : action.type);\n const actionArgs = {\n context: intermediateSnapshot.context,\n event,\n self: actorScope.self,\n system: actorScope.system\n };\n\n const actionParams =\n isInline || typeof action === 'string'\n ? undefined\n : 'params' in action\n ? typeof action.params === 'function'\n ? action.params({ context: intermediateSnapshot.context, event })\n : action.params\n : undefined;\n\n if (!resolvedAction || !('resolve' in resolvedAction)) {\n actorScope.actionExecutor({\n type:\n typeof action === 'string'\n ? action\n : typeof action === 'object'\n ? action.type\n : action.name || '(anonymous)',\n info: actionArgs,\n params: actionParams,\n exec: resolvedAction\n });\n continue;\n }\n\n const builtinAction = resolvedAction as BuiltinAction;\n\n const [nextState, params, actions] = builtinAction.resolve(\n actorScope,\n intermediateSnapshot,\n actionArgs,\n actionParams,\n resolvedAction, // this holds all params\n extra\n );\n intermediateSnapshot = nextState;\n\n if ('retryResolve' in builtinAction) {\n retries?.push([builtinAction, params]);\n }\n\n if ('execute' in builtinAction) {\n actorScope.actionExecutor({\n type: builtinAction.type,\n info: actionArgs,\n params,\n exec: builtinAction.execute.bind(null, actorScope, params)\n });\n }\n\n if (actions) {\n intermediateSnapshot = resolveAndExecuteActionsWithContext(\n intermediateSnapshot,\n event,\n actorScope,\n actions,\n extra,\n retries\n );\n }\n }\n\n return intermediateSnapshot;\n}\n\nexport function resolveActionsAndContext(\n currentSnapshot: AnyMachineSnapshot,\n event: AnyEventObject,\n actorScope: AnyActorScope,\n actions: UnknownAction[],\n internalQueue: AnyEventObject[],\n deferredActorIds: string[] | undefined\n): AnyMachineSnapshot {\n const retries: (readonly [BuiltinAction, unknown])[] | undefined =\n deferredActorIds ? [] : undefined;\n const nextState = resolveAndExecuteActionsWithContext(\n currentSnapshot,\n event,\n actorScope,\n actions,\n { internalQueue, deferredActorIds },\n retries\n );\n retries?.forEach(([builtinAction, params]) => {\n builtinAction.retryResolve(actorScope, nextState, params);\n });\n return nextState;\n}\n\nexport function macrostep(\n snapshot: AnyMachineSnapshot,\n event: EventObject,\n actorScope: AnyActorScope,\n internalQueue: AnyEventObject[]\n): {\n snapshot: typeof snapshot;\n microstates: Array<typeof snapshot>;\n} {\n if (isDevelopment && event.type === WILDCARD) {\n throw new Error(`An event cannot have the wildcard type ('${WILDCARD}')`);\n }\n\n let nextSnapshot = snapshot;\n const microstates: AnyMachineSnapshot[] = [];\n\n function addMicrostate(\n microstate: AnyMachineSnapshot,\n event: AnyEventObject,\n transitions: AnyTransitionDefinition[]\n ) {\n actorScope.system._sendInspectionEvent({\n type: '@xstate.microstep',\n actorRef: actorScope.self,\n event,\n snapshot: microstate,\n _transitions: transitions\n });\n microstates.push(microstate);\n }\n\n // Handle stop event\n if (event.type === XSTATE_STOP) {\n nextSnapshot = cloneMachineSnapshot(\n stopChildren(nextSnapshot, event, actorScope),\n {\n status: 'stopped'\n }\n );\n addMicrostate(nextSnapshot, event, []);\n\n return {\n snapshot: nextSnapshot,\n microstates\n };\n }\n\n let nextEvent = event;\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) {\n const currentEvent = nextEvent;\n const isErr = isErrorActorEvent(currentEvent);\n\n const transitions = selectTransitions(currentEvent, nextSnapshot);\n\n if (isErr && !transitions.length) {\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 // similarly `xstate.error.actor.*` and `xstate.error.actor.todo.*` have to be considered too\n nextSnapshot = cloneMachineSnapshot<typeof snapshot>(snapshot, {\n status: 'error',\n error: currentEvent.error\n });\n addMicrostate(nextSnapshot, currentEvent, []);\n return {\n snapshot: nextSnapshot,\n microstates\n };\n }\n nextSnapshot = microstep(\n transitions,\n snapshot,\n actorScope,\n nextEvent,\n false, // isInitial\n internalQueue\n );\n addMicrostate(nextSnapshot, currentEvent, transitions);\n }\n\n let shouldSelectEventlessTransitions = true;\n\n while (nextSnapshot.status === 'active') {\n let enabledTransitions: AnyTransitionDefinition[] =\n shouldSelectEventlessTransitions\n ? selectEventlessTransitions(nextSnapshot, nextEvent)\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\n if (!enabledTransitions.length) {\n if (!internalQueue.length) {\n break;\n }\n nextEvent = internalQueue.shift()!;\n enabledTransitions = selectTransitions(nextEvent, nextSnapshot);\n }\n\n nextSnapshot = microstep(\n enabledTransitions,\n nextSnapshot,\n actorScope,\n nextEvent,\n false,\n internalQueue\n );\n shouldSelectEventlessTransitions = nextSnapshot !== previousState;\n addMicrostate(nextSnapshot, nextEvent, enabledTransitions);\n }\n\n if (nextSnapshot.status !== 'active') {\n stopChildren(nextSnapshot, nextEvent, actorScope);\n }\n\n return {\n snapshot: nextSnapshot,\n microstates\n };\n}\n\nfunction stopChildren(\n nextState: AnyMachineSnapshot,\n event: AnyEventObject,\n actorScope: AnyActorScope\n) {\n return resolveActionsAndContext(\n nextState,\n event,\n actorScope,\n Object.values(nextState.children).map((child: any) => stopChild(child)),\n [],\n undefined\n );\n}\n\nfunction selectTransitions(\n event: AnyEventObject,\n nextState: AnyMachineSnapshot\n): AnyTransitionDefinition[] {\n return nextState.machine.getTransitionData(nextState as any, event);\n}\n\nfunction selectEventlessTransitions(\n nextState: AnyMachineSnapshot,\n event: AnyEventObject\n): AnyTransitionDefinition[] {\n const enabledTransitionSet: Set<AnyTransitionDefinition> = new Set();\n const atomicStates = nextState._nodes.filter(isAtomicStateNode);\n\n for (const stateNode of atomicStates) {\n loop: for (const s of [stateNode].concat(\n getProperAncestors(stateNode, undefined)\n )) {\n if (!s.always) {\n continue;\n }\n for (const transition of s.always) {\n if (\n transition.guard === undefined ||\n evaluateGuard(transition.guard, nextState.context, event, nextState)\n ) {\n enabledTransitionSet.add(transition);\n break loop;\n }\n }\n }\n }\n\n return removeConflictingTransitions(\n Array.from(enabledTransitionSet),\n new Set(nextState._nodes),\n nextState.historyValue\n );\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","import { ProcessingStatus, createActor } from './createActor.ts';\nimport {\n ActorRefFromLogic,\n AnyActorLogic,\n AnyActorRef,\n AnyActorScope,\n AnyEventObject,\n AnyMachineSnapshot,\n ConditionalRequired,\n GetConcreteByKey,\n InputFrom,\n IsLiteralString,\n IsNotNever,\n ProvidedActor,\n RequiredActorOptions,\n TODO,\n type RequiredLogicInput\n} from './types.ts';\nimport { resolveReferencedActor } from './utils.ts';\n\ntype SpawnOptions<\n TActor extends ProvidedActor,\n TSrc extends TActor['src']\n> = TActor extends {\n src: TSrc;\n}\n ? ConditionalRequired<\n [\n options?: {\n id?: TActor['id'];\n systemId?: string;\n input?: InputFrom<TActor['logic']>;\n syncSnapshot?: boolean;\n } & { [K in RequiredActorOptions<TActor>]: unknown }\n ],\n IsNotNever<RequiredActorOptions<TActor>>\n >\n : never;\n\nexport type Spawner<TActor extends ProvidedActor> =\n IsLiteralString<TActor['src']> extends true\n ? {\n <TSrc extends TActor['src']>(\n logic: TSrc,\n ...[options]: SpawnOptions<TActor, TSrc>\n ): ActorRefFromLogic<GetConcreteByKey<TActor, 'src', TSrc>['logic']>;\n <TLogic extends AnyActorLogic>(\n src: TLogic,\n ...[options]: ConditionalRequired<\n [\n options?: {\n id?: never;\n systemId?: string;\n input?: InputFrom<TLogic>;\n syncSnapshot?: boolean;\n } & { [K in RequiredLogicInput<TLogic>]: unknown }\n ],\n IsNotNever<RequiredLogicInput<TLogic>>\n >\n ): ActorRefFromLogic<TLogic>;\n }\n : <TLogic extends AnyActorLogic | string>(\n src: TLogic,\n ...[options]: ConditionalRequired<\n [\n options?: {\n id?: string;\n systemId?: string;\n input?: TLogic extends string ? unknown : InputFrom<TLogic>;\n syncSnapshot?: boolean;\n } & (TLogic extends AnyActorLogic\n ? { [K in RequiredLogicInput<TLogic>]: unknown }\n : {})\n ],\n IsNotNever<\n TLogic extends AnyActorLogic ? RequiredLogicInput<TLogic> : never\n >\n >\n ) => TLogic extends AnyActorLogic\n ? ActorRefFromLogic<TLogic>\n : AnyActorRef;\n\nexport function createSpawner(\n actorScope: AnyActorScope,\n { machine, context }: AnyMachineSnapshot,\n event: AnyEventObject,\n spawnedChildren: Record<string, AnyActorRef>\n): Spawner<any> {\n const spawn: Spawner<any> = ((src, options) => {\n if (typeof src === 'string') {\n const logic = resolveReferencedActor(machine, src);\n\n if (!logic) {\n throw new Error(\n `Actor logic '${src}' not implemented in machine '${machine.id}'`\n );\n }\n\n const actorRef = createActor(logic, {\n id: options?.id,\n parent: actorScope.self,\n syncSnapshot: options?.syncSnapshot,\n input:\n typeof options?.input === 'function'\n ? options.input({\n context,\n event,\n self: actorScope.self\n })\n : options?.input,\n src,\n systemId: options?.systemId\n }) as any;\n\n spawnedChildren[actorRef.id] = actorRef;\n\n return actorRef;\n } else {\n const actorRef = createActor(src, {\n id: options?.id,\n parent: actorScope.self,\n syncSnapshot: options?.syncSnapshot,\n input: options?.input,\n src,\n systemId: options?.systemId\n });\n\n return actorRef;\n }\n }) as Spawner<any>;\n return ((src, options) => {\n const actorRef = spawn(src, options) as TODO; // TODO: fix types\n spawnedChildren[actorRef.id] = actorRef;\n actorScope.defer(() => {\n if (actorRef._processingStatus === ProcessingStatus.Stopped) {\n return;\n }\n actorRef.start();\n });\n return actorRef;\n }) as Spawner<any>;\n}\n","import isDevelopment from '#is-development';\nimport { cloneMachineSnapshot } from '../State.ts';\nimport { executingCustomAction } from '../createActor.ts';\nimport { Spawner, createSpawner } from '../spawn.ts';\nimport type {\n ActionArgs,\n AnyActorScope,\n AnyActorRef,\n AnyEventObject,\n AnyMachineSnapshot,\n Assigner,\n EventObject,\n LowInfer,\n MachineContext,\n ParameterizedObject,\n PropertyAssigner,\n ProvidedActor,\n ActionFunction,\n BuiltinActionResolution\n} from '../types.ts';\n\nexport interface AssignArgs<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TEvent extends EventObject,\n TActor extends ProvidedActor\n> extends ActionArgs<TContext, TExpressionEvent, TEvent> {\n spawn: Spawner<TActor>;\n}\n\nfunction resolveAssign(\n actorScope: AnyActorScope,\n snapshot: AnyMachineSnapshot,\n actionArgs: ActionArgs<any, any, any>,\n actionParams: ParameterizedObject['params'] | undefined,\n {\n assignment\n }: {\n assignment:\n | Assigner<any, any, any, any, any>\n | PropertyAssigner<any, any, any, any, any>;\n }\n): BuiltinActionResolution {\n if (!snapshot.context) {\n throw new Error(\n 'Cannot assign to undefined `context`. Ensure that `context` is defined in the machine config.'\n );\n }\n const spawnedChildren: Record<string, AnyActorRef> = {};\n\n const assignArgs: AssignArgs<any, any, any, any> = {\n context: snapshot.context,\n event: actionArgs.event,\n spawn: createSpawner(\n actorScope,\n snapshot,\n actionArgs.event,\n spawnedChildren\n ),\n self: actorScope.self,\n system: actorScope.system\n };\n let partialUpdate: Record<string, unknown> = {};\n if (typeof assignment === 'function') {\n partialUpdate = assignment(assignArgs, actionParams);\n } else {\n for (const key of Object.keys(assignment)) {\n const propAssignment = assignment[key];\n partialUpdate[key] =\n typeof propAssignment === 'function'\n ? propAssignment(assignArgs, actionParams)\n : propAssignment;\n }\n }\n\n const updatedContext = Object.assign({}, snapshot.context, partialUpdate);\n\n return [\n cloneMachineSnapshot(snapshot, {\n context: updatedContext,\n children: Object.keys(spawnedChildren).length\n ? {\n ...snapshot.children,\n ...spawnedChildren\n }\n : snapshot.children\n }),\n undefined,\n undefined\n ];\n}\n\nexport interface AssignAction<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject,\n TActor extends ProvidedActor\n> {\n (args: ActionArgs<TContext, TExpressionEvent, TEvent>, params: TParams): void;\n _out_TActor?: TActor;\n}\n\n/**\n * Updates the current context of the machine.\n *\n * @example\n *\n * ```ts\n * import { createMachine, assign } from 'xstate';\n *\n * const countMachine = createMachine({\n * context: {\n * count: 0,\n * message: ''\n * },\n * on: {\n * inc: {\n * actions: assign({\n * count: ({ context }) => context.count + 1\n * })\n * },\n * updateMessage: {\n * actions: assign(({ context, event }) => {\n * return {\n * message: event.message.trim()\n * };\n * })\n * }\n * }\n * });\n * ```\n *\n * @param assignment An object that represents the partial context to update, or\n * a function that returns an object that represents the partial context to\n * update.\n */\nexport function assign<\n TContext extends MachineContext,\n TExpressionEvent extends AnyEventObject, // TODO: consider using a stricter `EventObject` here\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject,\n TActor extends ProvidedActor\n>(\n assignment:\n | Assigner<LowInfer<TContext>, TExpressionEvent, TParams, TEvent, TActor>\n | PropertyAssigner<\n LowInfer<TContext>,\n TExpressionEvent,\n TParams,\n TEvent,\n TActor\n >\n): ActionFunction<\n TContext,\n TExpressionEvent,\n TEvent,\n TParams,\n TActor,\n never,\n never,\n never,\n never\n> {\n if (isDevelopment && executingCustomAction) {\n console.warn(\n 'Custom actions should not call `assign()` directly, as it is not imperative. See https://stately.ai/docs/actions#built-in-actions for more details.'\n );\n }\n\n function assign(\n _args: ActionArgs<TContext, TExpressionEvent, TEvent>,\n _params: TParams\n ) {\n if (isDevelopment) {\n throw new Error(`This isn't supposed to be called`);\n }\n }\n\n assign.type = 'xstate.assign';\n assign.assignment = assignment;\n\n assign.resolve = resolveAssign;\n\n return assign;\n}\n","import isDevelopment from '#is-development';\nimport { executingCustomAction } from '../createActor.ts';\nimport {\n ActionArgs,\n ActionFunction,\n AnyActorScope,\n AnyEventObject,\n AnyMachineSnapshot,\n DoNotInfer,\n EventObject,\n MachineContext,\n ParameterizedObject,\n SendExpr,\n BuiltinActionResolution\n} from '../types.ts';\n\nfunction resolveEmit(\n _: AnyActorScope,\n snapshot: AnyMachineSnapshot,\n args: ActionArgs<any, any, any>,\n actionParams: ParameterizedObject['params'] | undefined,\n {\n event: eventOrExpr\n }: {\n event:\n | EventObject\n | SendExpr<\n MachineContext,\n EventObject,\n ParameterizedObject['params'] | undefined,\n EventObject,\n EventObject\n >;\n }\n): BuiltinActionResolution {\n const resolvedEvent =\n typeof eventOrExpr === 'function'\n ? eventOrExpr(args, actionParams)\n : eventOrExpr;\n return [snapshot, { event: resolvedEvent }, undefined];\n}\n\nfunction executeEmit(\n actorScope: AnyActorScope,\n {\n event\n }: {\n event: EventObject;\n }\n) {\n actorScope.defer(() => actorScope.emit(event));\n}\n\nexport interface EmitAction<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject,\n TEmitted extends EventObject\n> {\n (args: ActionArgs<TContext, TExpressionEvent, TEvent>, params: TParams): void;\n _out_TEmitted?: TEmitted;\n}\n\n/**\n * Emits an event to event handlers registered on the actor via `actor.on(event,\n * handler)`.\n *\n * @example\n *\n * ```ts\n * import { emit } from 'xstate';\n *\n * const machine = createMachine({\n * // ...\n * on: {\n * something: {\n * actions: emit({\n * type: 'emitted',\n * some: 'data'\n * })\n * }\n * }\n * // ...\n * });\n *\n * const actor = createActor(machine).start();\n *\n * actor.on('emitted', (event) => {\n * console.log(event);\n * });\n *\n * actor.send({ type: 'something' });\n * // logs:\n * // {\n * // type: 'emitted',\n * // some: 'data'\n * // }\n * ```\n */\nexport function emit<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject,\n TEmitted extends AnyEventObject\n>(\n /** The event to emit, or an expression that returns an event to emit. */\n eventOrExpr:\n | DoNotInfer<TEmitted>\n | SendExpr<\n TContext,\n TExpressionEvent,\n TParams,\n DoNotInfer<TEmitted>,\n TEvent\n >\n): ActionFunction<\n TContext,\n TExpressionEvent,\n TEvent,\n TParams,\n never,\n never,\n never,\n never,\n TEmitted\n> {\n if (isDevelopment && executingCustomAction) {\n console.warn(\n 'Custom actions should not call `emit()` directly, as it is not imperative. See https://stately.ai/docs/actions#built-in-actions for more details.'\n );\n }\n\n function emit(\n _args: ActionArgs<TContext, TExpressionEvent, TEvent>,\n _params: TParams\n ) {\n if (isDevelopment) {\n throw new Error(`This isn't supposed to be called`);\n }\n }\n\n emit.type = 'xstate.emit';\n emit.event = eventOrExpr;\n\n emit.resolve = resolveEmit;\n emit.execute = executeEmit;\n\n return emit;\n}\n","import isDevelopment from '#is-development';\nimport { executingCustomAction } from '../createActor.ts';\nimport {\n ActionArgs,\n ActionFunction,\n AnyActorScope,\n AnyEventObject,\n AnyMachineSnapshot,\n DelayExpr,\n DoNotInfer,\n EventObject,\n ExecutableActionObject,\n MachineContext,\n ParameterizedObject,\n RaiseActionOptions,\n SendExpr,\n BuiltinActionResolution\n} from '../types.ts';\n\nfunction resolveRaise(\n _: AnyActorScope,\n snapshot: AnyMachineSnapshot,\n args: ActionArgs<any, any, any>,\n actionParams: ParameterizedObject['params'] | undefined,\n {\n event: eventOrExpr,\n id,\n delay\n }: {\n event:\n | EventObject\n | SendExpr<\n MachineContext,\n EventObject,\n ParameterizedObject['params'] | undefined,\n EventObject,\n EventObject\n >;\n id: string | undefined;\n delay:\n | string\n | number\n | DelayExpr<\n MachineContext,\n EventObject,\n ParameterizedObject['params'] | undefined,\n EventObject\n >\n | undefined;\n },\n { internalQueue }: { internalQueue: AnyEventObject[] }\n): BuiltinActionResolution {\n const delaysMap = snapshot.machine.implementations.delays;\n\n if (typeof eventOrExpr === 'string') {\n throw new Error(\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `Only event objects may be used with raise; use raise({ type: \"${eventOrExpr}\" }) instead`\n );\n }\n const resolvedEvent =\n typeof eventOrExpr === 'function'\n ? eventOrExpr(args, actionParams)\n : eventOrExpr;\n\n let resolvedDelay: number | undefined;\n if (typeof delay === 'string') {\n const configDelay = delaysMap && delaysMap[delay];\n resolvedDelay =\n typeof configDelay === 'function'\n ? configDelay(args, actionParams)\n : configDelay;\n } else {\n resolvedDelay =\n typeof delay === 'function' ? delay(args, actionParams) : delay;\n }\n if (typeof resolvedDelay !== 'number') {\n internalQueue.push(resolvedEvent);\n }\n return [\n snapshot,\n {\n event: resolvedEvent,\n id,\n delay: resolvedDelay\n },\n undefined\n ];\n}\n\nfunction executeRaise(\n actorScope: AnyActorScope,\n params: {\n event: EventObject;\n id: string | undefined;\n delay: number | undefined;\n }\n) {\n const { event, delay, id } = params;\n if (typeof delay === 'number') {\n actorScope.defer(() => {\n const self = actorScope.self;\n actorScope.system.scheduler.schedule(self, self, event, delay, id);\n });\n return;\n }\n}\n\nexport interface RaiseAction<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject,\n TDelay extends string\n> {\n (args: ActionArgs<TContext, TExpressionEvent, TEvent>, params: TParams): void;\n _out_TEvent?: TEvent;\n _out_TDelay?: TDelay;\n}\n\n/**\n * Raises an event. This places the event in the internal event queue, so that\n * the event is immediately consumed by the machine in the current step.\n *\n * @param eventType The event to raise.\n */\nexport function raise<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TDelay extends string = never,\n TUsedDelay extends TDelay = never\n>(\n eventOrExpr:\n | DoNotInfer<TEvent>\n | SendExpr<TContext, TExpressionEvent, TParams, DoNotInfer<TEvent>, TEvent>,\n options?: RaiseActionOptions<\n TContext,\n TExpressionEvent,\n TParams,\n DoNotInfer<TEvent>,\n TUsedDelay\n >\n): ActionFunction<\n TContext,\n TExpressionEvent,\n TEvent,\n TParams,\n never,\n never,\n never,\n TDelay,\n never\n> {\n if (isDevelopment && executingCustomAction) {\n console.warn(\n 'Custom actions should not call `raise()` directly, as it is not imperative. See https://stately.ai/docs/actions#built-in-actions for more details.'\n );\n }\n\n function raise(\n _args: ActionArgs<TContext, TExpressionEvent, TEvent>,\n _params: TParams\n ) {\n if (isDevelopment) {\n throw new Error(`This isn't supposed to be called`);\n }\n }\n\n raise.type = 'xstate.raise';\n raise.event = eventOrExpr;\n raise.id = options?.id;\n raise.delay = options?.delay;\n\n raise.resolve = resolveRaise;\n raise.execute = executeRaise;\n\n return raise;\n}\n\nexport interface ExecutableRaiseAction extends ExecutableActionObject {\n type: 'xstate.raise';\n params: {\n event: EventObject;\n id: string | undefined;\n delay: number | undefined;\n };\n}\n","import type { MachineSnapshot } from './State.ts';\nimport type { StateMachine } from './StateMachine.ts';\nimport type { StateNode } from './StateNode.ts';\nimport { AssignArgs } from './actions/assign.ts';\nimport { ExecutableRaiseAction } from './actions/raise.ts';\nimport { ExecutableSendToAction } from './actions/send.ts';\nimport { PromiseActorLogic } from './actors/promise.ts';\nimport type { Actor, ProcessingStatus } from './createActor.ts';\nimport { Guard, GuardPredicate, UnknownGuard } from './guards.ts';\nimport { InspectionEvent } from './inspection.ts';\nimport { Spawner } from './spawn.ts';\nimport { AnyActorSystem, Clock } from './system.ts';\n\n// this is needed to make JSDoc `@link` work properly\nimport type { SimulatedClock } from './SimulatedClock.ts';\n\nexport type Identity<T> = { [K in keyof T]: T[K] };\n\nexport type HomomorphicPick<T, K extends keyof any> = {\n [P in keyof T as P & K]: T[P];\n};\nexport type HomomorphicOmit<T, K extends keyof any> = {\n [P in keyof T as Exclude<P, K>]: T[P];\n};\n\nexport type Invert<T extends Record<PropertyKey, PropertyKey>> = {\n [K in keyof T as T[K]]: K;\n};\n\nexport type GetParameterizedParams<T extends ParameterizedObject | undefined> =\n T extends any ? ('params' extends keyof T ? T['params'] : undefined) : never;\n\n/**\n * @remarks\n * `T | unknown` reduces to `unknown` and that can be problematic when it comes\n * to contextual typing. It especially is a problem when the union has a\n * function member, like here:\n *\n * ```ts\n * declare function test(\n * cbOrVal: ((arg: number) => unknown) | unknown\n * ): void;\n * test((arg) => {}); // oops, implicit any\n * ```\n *\n * This type can be used to avoid this problem. This union represents the same\n * value space as `unknown`.\n */\nexport type NonReducibleUnknown = {} | null | undefined;\nexport type AnyFunction = (...args: any[]) => any;\n\ntype ReturnTypeOrValue<T> = T extends AnyFunction ? ReturnType<T> : T;\n\n// https://github.com/microsoft/TypeScript/issues/23182#issuecomment-379091887\nexport type IsNever<T> = [T] extends [never] ? true : false;\nexport type IsNotNever<T> = [T] extends [never] ? false : true;\n\nexport type Compute<A> = { [K in keyof A]: A[K] } & unknown;\nexport type Prop<T, K> = K extends keyof T ? T[K] : never;\nexport type Values<T> = T[keyof T];\nexport type Elements<T> = T[keyof T & `${number}`];\nexport type Merge<M, N> = Omit<M, keyof N> & N;\nexport type IndexByProp<T extends Record<P, string>, P extends keyof T> = {\n [E in T as E[P]]: E;\n};\n\nexport type IndexByType<T extends { type: string }> = IndexByProp<T, 'type'>;\n\nexport type Equals<A1, A2> =\n (<A>() => A extends A2 ? true : false) extends <A>() => A extends A1\n ? true\n : false\n ? true\n : false;\nexport type IsAny<T> = Equals<T, any>;\nexport type Cast<A, B> = A extends B ? A : B;\n// @TODO: we can't use native `NoInfer` as we need those:\n// https://github.com/microsoft/TypeScript/pull/61092\n// https://github.com/microsoft/TypeScript/pull/61077\n// but even with those fixes native NoInfer still doesn't work - further issues have to be reproduced and fixed\nexport type DoNotInfer<T> = [T][T extends any ? 0 : any];\n/** @deprecated Use the built-in `NoInfer` type instead */\nexport type NoInfer<T> = DoNotInfer<T>;\nexport type LowInfer<T> = T & NonNullable<unknown>;\n\nexport type MetaObject = Record<string, any>;\n\nexport type Lazy<T> = () => T;\nexport type MaybeLazy<T> = T | Lazy<T>;\n\n/** The full definition of an event, with a string `type`. */\nexport type EventObject = {\n /** The type of event that is sent. */\n type: string;\n};\n\nexport interface AnyEventObject extends EventObject {\n [key: string]: any;\n}\n\nexport interface ParameterizedObject {\n type: string;\n params?: NonReducibleUnknown;\n}\n\nexport interface UnifiedArg<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TEvent extends EventObject\n> {\n context: TContext;\n event: TExpressionEvent;\n self: ActorRef<\n MachineSnapshot<\n TContext,\n TEvent,\n Record<string, AnyActorRef | undefined>, // TODO: this should be replaced with `TChildren`\n StateValue,\n string,\n unknown,\n TODO, // TMeta\n TODO // State schema\n >,\n TEvent,\n AnyEventObject\n >;\n system: AnyActorSystem;\n}\n\nexport type MachineContext = Record<string, any>;\n\nexport interface ActionArgs<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TEvent extends EventObject\n> extends UnifiedArg<TContext, TExpressionEvent, TEvent> {}\n\nexport type InputFrom<T> =\n T extends StateMachine<\n infer _TContext,\n infer _TEvent,\n infer _TChildren,\n infer _TActor,\n infer _TAction,\n infer _TGuard,\n infer _TDelay,\n infer _TStateValue,\n infer _TTag,\n infer TInput,\n infer _TOutput,\n infer _TEmitted,\n infer _TMeta,\n infer _TStateSchema\n >\n ? TInput\n : T extends ActorLogic<\n infer _TSnapshot,\n infer _TEvent,\n infer TInput,\n infer _TSystem,\n infer _TEmitted\n >\n ? TInput\n : never;\n\nexport type OutputFrom<T> =\n T extends ActorLogic<\n infer TSnapshot,\n infer _TEvent,\n infer _TInput,\n infer _TSystem,\n infer _TEmitted\n >\n ? (TSnapshot & { status: 'done' })['output']\n : T extends ActorRef<infer TSnapshot, infer _TEvent, infer _TEmitted>\n ? (TSnapshot & { status: 'done' })['output']\n : never;\n\nexport type ActionFunction<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TActor extends ProvidedActor,\n TAction extends ParameterizedObject,\n TGuard extends ParameterizedObject,\n TDelay extends string,\n TEmitted extends EventObject\n> = {\n (args: ActionArgs<TContext, TExpressionEvent, TEvent>, params: TParams): void;\n _out_TEvent?: TEvent; // TODO: it feels like we should be able to remove this since now `TEvent` is \"observable\" by `self`\n _out_TActor?: TActor;\n _out_TAction?: TAction;\n _out_TGuard?: TGuard;\n _out_TDelay?: TDelay;\n _out_TEmitted?: TEmitted;\n};\n\nexport type NoRequiredParams<T extends ParameterizedObject> = T extends any\n ? undefined extends T['params']\n ? T['type']\n : never\n : never;\n\nexport type ConditionalRequired<\n T,\n Condition extends boolean\n> = Condition extends true ? Required<T> : T;\n\nexport type WithDynamicParams<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n T extends ParameterizedObject\n> = T extends any\n ? ConditionalRequired<\n {\n type: T['type'];\n params?:\n | T['params']\n | (({\n context,\n event\n }: {\n context: TContext;\n event: TExpressionEvent;\n }) => T['params']);\n },\n undefined extends T['params'] ? false : true\n >\n : never;\n\nexport type Action<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TActor extends ProvidedActor,\n TAction extends ParameterizedObject,\n TGuard extends ParameterizedObject,\n TDelay extends string,\n TEmitted extends EventObject\n> =\n // TODO: consider merging `NoRequiredParams` and `WithDynamicParams` into one\n // this way we could iterate over `TAction` (and `TGuard` in the `Guard` type) once and not twice\n | NoRequiredParams<TAction>\n | WithDynamicParams<TContext, TExpressionEvent, TAction>\n | ActionFunction<\n TContext,\n TExpressionEvent,\n TEvent,\n TParams,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted\n >;\n\nexport type UnknownAction = Action<\n MachineContext,\n EventObject,\n EventObject,\n ParameterizedObject['params'] | undefined,\n ProvidedActor,\n ParameterizedObject,\n ParameterizedObject,\n string,\n EventObject\n>;\n\nexport type Actions<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TActor extends ProvidedActor,\n TAction extends ParameterizedObject,\n TGuard extends ParameterizedObject,\n TDelay extends string,\n TEmitted extends EventObject\n> = SingleOrArray<\n Action<\n TContext,\n TExpressionEvent,\n TEvent,\n TParams,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted\n >\n>;\n\nexport type StateKey = string | AnyMachineSnapshot;\n\nexport interface StateValueMap {\n [key: string]: StateValue | undefined;\n}\n\n/**\n * The string or object representing the state value relative to the parent\n * state node.\n *\n * @remarks\n * - For a child atomic state node, this is a string, e.g., `\"pending\"`.\n * - For complex state nodes, this is an object, e.g., `{ success:\n * \"someChildState\" }`.\n */\nexport type StateValue = string | StateValueMap;\n\nexport type TransitionTarget = SingleOrArray<string>;\n\nexport interface TransitionConfig<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TEvent extends EventObject,\n TActor extends ProvidedActor,\n TAction extends ParameterizedObject,\n TGuard extends ParameterizedObject,\n TDelay extends string,\n TEmitted extends EventObject = EventObject,\n TMeta extends MetaObject = MetaObject\n> {\n guard?: Guard<TContext, TExpressionEvent, undefined, TGuard>;\n actions?: Actions<\n TContext,\n TExpressionEvent,\n TEvent,\n undefined,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted\n >;\n reenter?: boolean;\n target?: TransitionTarget | undefined;\n meta?: TMeta;\n description?: string;\n}\n\nexport interface InitialTransitionConfig<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TActor extends ProvidedActor,\n TAction extends ParameterizedObject,\n TGuard extends ParameterizedObject,\n TDelay extends string\n> extends TransitionConfig<\n TContext,\n TEvent,\n TEvent,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TODO, // TEmitted\n TODO // TMeta\n > {\n target: string;\n}\n\nexport type AnyTransitionConfig = TransitionConfig<\n any, // TContext\n any, // TExpressionEvent\n any, // TEvent\n any, // TActor\n any, // TAction\n any, // TGuard\n any, // TDelay\n any, // TEmitted\n any // TMeta\n>;\n\nexport interface InvokeDefinition<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TActor extends ProvidedActor,\n TAction extends ParameterizedObject,\n TGuard extends ParameterizedObject,\n TDelay extends string,\n TEmitted extends EventObject,\n TMeta extends MetaObject\n> {\n id: string;\n\n systemId: string | undefined;\n /** The source of the actor logic to be invoked */\n src: AnyActorLogic | string;\n\n input?:\n | Mapper<TContext, TEvent, NonReducibleUnknown, TEvent>\n | NonReducibleUnknown;\n /**\n * The transition to take upon the invoked child machine reaching its final\n * top-level state.\n */\n onDone?:\n | string\n | SingleOrArray<\n TransitionConfig<\n TContext,\n DoneActorEvent<unknown>,\n TEvent,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted,\n TMeta\n >\n >;\n /**\n * The transition to take upon the invoked child machine sending an error\n * event.\n */\n onError?:\n | string\n | SingleOrArray<\n TransitionConfig<\n TContext,\n ErrorActorEvent,\n TEvent,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted,\n TMeta\n >\n >;\n\n onSnapshot?:\n | string\n | SingleOrArray<\n TransitionConfig<\n TContext,\n SnapshotEvent,\n TEvent,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted,\n TMeta\n >\n >;\n\n toJSON: () => Omit<\n InvokeDefinition<\n TContext,\n TEvent,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted,\n TMeta\n >,\n 'onDone' | 'onError' | 'toJSON'\n >;\n}\n\ntype Delay<TDelay extends string> = TDelay | number;\n\nexport type DelayedTransitions<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TActor extends ProvidedActor,\n TAction extends ParameterizedObject,\n TGuard extends ParameterizedObject,\n TDelay extends string\n> = {\n [K in Delay<TDelay>]?:\n | string\n | SingleOrArray<\n TransitionConfig<\n TContext,\n TEvent,\n TEvent,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TODO, // TEmitted\n TODO // TMeta\n >\n >;\n};\n\nexport type StateTypes =\n | 'atomic'\n | 'compound'\n | 'parallel'\n | 'final'\n | 'history'\n | ({} & string);\n\nexport type SingleOrArray<T> = readonly T[] | T;\n\nexport type StateNodesConfig<\n TContext extends MachineContext,\n TEvent extends EventObject\n> = {\n [K in string]: StateNode<TContext, TEvent>;\n};\n\nexport type StatesConfig<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TActor extends ProvidedActor,\n TAction extends ParameterizedObject,\n TGuard extends ParameterizedObject,\n TDelay extends string,\n TTag extends string,\n TOutput,\n TEmitted extends EventObject,\n TMeta extends MetaObject\n> = {\n [K in string]: StateNodeConfig<\n TContext,\n TEvent,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TTag,\n TOutput,\n TEmitted,\n TMeta\n >;\n};\n\nexport type StatesDefinition<\n TContext extends MachineContext,\n TEvent extends EventObject\n> = {\n [K in string]: StateNodeDefinition<TContext, TEvent>;\n};\n\nexport type TransitionConfigTarget = string | undefined;\n\nexport type TransitionConfigOrTarget<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TEvent extends EventObject,\n TActor extends ProvidedActor,\n TAction extends ParameterizedObject,\n TGuard extends ParameterizedObject,\n TDelay extends string,\n TEmitted extends EventObject,\n TMeta extends MetaObject\n> = SingleOrArray<\n | TransitionConfigTarget\n | TransitionConfig<\n TContext,\n TExpressionEvent,\n TEvent,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted,\n TMeta\n >\n>;\n\nexport type TransitionsConfig<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TActor extends ProvidedActor,\n TAction extends ParameterizedObject,\n TGuard extends ParameterizedObject,\n TDelay extends string,\n TEmitted extends EventObject,\n TMeta extends MetaObject\n> = {\n [K in EventDescriptor<TEvent>]?: TransitionConfigOrTarget<\n TContext,\n ExtractEvent<TEvent, K>,\n TEvent,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted,\n TMeta\n >;\n};\n\ntype PartialEventDescriptor<TEventType extends string> =\n TEventType extends `${infer TLeading}.${infer TTail}`\n ? `${TLeading}.*` | `${TLeading}.${PartialEventDescriptor<TTail>}`\n : never;\n\nexport type EventDescriptor<TEvent extends EventObject> =\n | TEvent['type']\n | PartialEventDescriptor<TEvent['type']>\n | '*';\n\ntype NormalizeDescriptor<TDescriptor extends string> = TDescriptor extends '*'\n ? string\n : TDescriptor extends `${infer TLeading}.*`\n ? `${TLeading}.${string}`\n : TDescriptor;\n\nexport type IsLiteralString<T extends string> = string extends T ? false : true;\n\ntype DistributeActors<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TActor extends ProvidedActor,\n TAction extends ParameterizedObject,\n TGuard extends ParameterizedObject,\n TDelay extends string,\n TEmitted extends EventObject,\n TMeta extends MetaObject,\n TSpecificActor extends ProvidedActor\n> = TSpecificActor extends { src: infer TSrc }\n ?\n | Compute<\n {\n systemId?: string;\n /** The source of the machine to be invoked, or the machine itself. */\n src: TSrc;\n\n /**\n * The unique identifier for the invoked machine. If not specified,\n * this will be the machine's own `id`, or the URL (from `src`).\n */\n id?: TSpecificActor['id'];\n\n // TODO: currently we do not enforce required inputs here\n // in a sense, we shouldn't - they could be provided within the `implementations` object\n // how do we verify if the required input has been provided?\n input?:\n | Mapper<\n TContext,\n TEvent,\n InputFrom<TSpecificActor['logic']>,\n TEvent\n >\n | InputFrom<TSpecificActor['logic']>;\n /**\n * The transition to take upon the invoked child machine reaching\n * its final top-level state.\n */\n onDone?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n DoneActorEvent<OutputFrom<TSpecificActor['logic']>>,\n TEvent,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted,\n TMeta\n >\n >;\n /**\n * The transition to take upon the invoked child machine sending an\n * error event.\n */\n onError?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n ErrorActorEvent,\n TEvent,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted,\n TMeta\n >\n >;\n\n onSnapshot?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n SnapshotEvent<SnapshotFrom<TSpecificActor['logic']>>,\n TEvent,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted,\n TMeta\n >\n >;\n } & { [K in RequiredActorOptions<TSpecificActor>]: unknown }\n >\n | {\n id?: never;\n systemId?: string;\n src: AnyActorLogic;\n input?:\n | Mapper<TContext, TEvent, NonReducibleUnknown, TEvent>\n | NonReducibleUnknown;\n onDone?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n DoneActorEvent<unknown>,\n TEvent,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted,\n TMeta\n >\n >;\n onError?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n ErrorActorEvent,\n TEvent,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted,\n TMeta\n >\n >;\n\n onSnapshot?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n SnapshotEvent,\n TEvent,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted,\n TMeta\n >\n >;\n }\n : never;\n\nexport type InvokeConfig<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TActor extends ProvidedActor,\n TAction extends ParameterizedObject,\n TGuard extends ParameterizedObject,\n TDelay extends string,\n TEmitted extends EventObject,\n TMeta extends MetaObject\n> =\n IsLiteralString<TActor['src']> extends true\n ? DistributeActors<\n TContext,\n TEvent,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted,\n TMeta,\n TActor\n >\n : {\n /**\n * The unique identifier for the invoked machine. If not specified, this\n * will be the machine's own `id`, or the URL (from `src`).\n */\n id?: string;\n\n systemId?: string;\n /** The source of the machine to be invoked, or the machine itself. */\n src: AnyActorLogic | string; // TODO: fix types\n\n input?:\n | Mapper<TContext, TEvent, NonReducibleUnknown, TEvent>\n | NonReducibleUnknown;\n /**\n * The transition to take upon the invoked child machine reaching its\n * final top-level state.\n */\n onDone?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n DoneActorEvent<any>, // TODO: consider replacing with `unknown`\n TEvent,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted,\n TMeta\n >\n >;\n /**\n * The transition to take upon the invoked child machine sending an\n * error event.\n */\n onError?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n ErrorActorEvent,\n TEvent,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted,\n TMeta\n >\n >;\n\n onSnapshot?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n SnapshotEvent,\n TEvent,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted,\n TMeta\n >\n >;\n };\n\nexport type AnyInvokeConfig = InvokeConfig<\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any // TMeta\n>;\n\nexport interface StateNodeConfig<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TActor extends ProvidedActor,\n TAction extends ParameterizedObject,\n TGuard extends ParameterizedObject,\n TDelay extends string,\n TTag extends string,\n _TOutput,\n TEmitted extends EventObject,\n TMeta extends MetaObject\n> {\n /** The initial state transition. */\n initial?:\n | InitialTransitionConfig<TContext, TEvent, TActor, TAction, TGuard, TDelay>\n | string\n | undefined;\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 * - `'final'` - final state node\n */\n type?: 'atomic' | 'compound' | 'parallel' | 'final' | 'history';\n /**\n * Indicates whether the state node is a history state node, and what type of\n * history: shallow, deep, true (shallow), false (none), undefined (none)\n */\n history?: 'shallow' | 'deep' | boolean | undefined;\n /**\n * The mapping of state node keys to their state node configurations\n * (recursive).\n */\n states?:\n | StatesConfig<\n TContext,\n TEvent,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TTag,\n NonReducibleUnknown,\n TEmitted,\n TMeta\n >\n | undefined;\n /**\n * The services to invoke upon entering this state node. These services will\n * be stopped upon exiting this state node.\n */\n invoke?: SingleOrArray<\n InvokeConfig<\n TContext,\n TEvent,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted,\n TMeta\n >\n >;\n /** The mapping of event types to their potential transition(s). */\n on?: TransitionsConfig<\n TContext,\n TEvent,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted,\n TMeta\n >;\n /** The action(s) to be executed upon entering the state node. */\n entry?: Actions<\n TContext,\n TEvent,\n TEvent,\n undefined,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted\n >;\n /** The action(s) to be executed upon exiting the state node. */\n exit?: Actions<\n TContext,\n TEvent,\n TEvent,\n undefined,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted\n >;\n /**\n * The potential transition(s) to be taken upon reaching a final child state\n * node.\n *\n * This is equivalent to defining a `[done(id)]` transition on this state\n * node's `on` property.\n */\n onDone?:\n | string\n | SingleOrArray<\n TransitionConfig<\n TContext,\n DoneStateEvent,\n TEvent,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted,\n TMeta\n >\n >\n | undefined;\n /**\n * The mapping (or array) of delays (in milliseconds) to their potential\n * transition(s). The delayed transitions are taken after the specified delay\n * in an interpreter.\n */\n after?: DelayedTransitions<TContext, TEvent, TActor, TAction, TGuard, TDelay>;\n\n /**\n * An eventless transition that is always taken when this state node is\n * active.\n */\n always?: TransitionConfigOrTarget<\n TContext,\n TEvent,\n TEvent,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted,\n TMeta\n >;\n parent?: StateNode<TContext, TEvent>;\n /**\n * The meta data associated with this state node, which will be returned in\n * State instances.\n */\n meta?: TMeta;\n /**\n * The output data sent with the \"xstate.done.state._id_\" event if this is a\n * final state node.\n *\n * The output data will be evaluated with the current `context` and placed on\n * the `.data` property of the event.\n */\n output?: Mapper<TContext, TEvent, unknown, TEvent> | NonReducibleUnknown;\n /**\n * The unique ID of the state node, which can be referenced as a transition\n * target via the `#id` syntax.\n */\n id?: string | undefined;\n /**\n * The order this state node appears. Corresponds to the implicit document\n * order.\n */\n order?: number;\n\n /**\n * The tags for this state node, which are accumulated into the `state.tags`\n * property.\n */\n tags?: SingleOrArray<TTag>;\n /** A text description of the state node */\n description?: string;\n\n /** A default target for a history state */\n target?: string | undefined; // `| undefined` makes `HistoryStateNodeConfig` compatible with this interface (it extends it) under `exactOptionalPropertyTypes`\n}\n\nexport type AnyStateNodeConfig = StateNodeConfig<\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any, // emitted\n any // meta\n>;\n\nexport interface StateNodeDefinition<\n TContext extends MachineContext,\n TEvent extends EventObject\n> {\n id: string;\n version?: string | undefined;\n key: string;\n type: 'atomic' | 'compound' | 'parallel' | 'final' | 'history';\n initial: InitialTransitionDefinition<TContext, TEvent> | undefined;\n history: boolean | 'shallow' | 'deep' | undefined;\n states: StatesDefinition<TContext, TEvent>;\n on: TransitionDefinitionMap<TContext, TEvent>;\n transitions: Array<TransitionDefinition<TContext, TEvent>>;\n // TODO: establish what a definition really is\n entry: UnknownAction[];\n exit: UnknownAction[];\n meta: any;\n order: number;\n output?: StateNodeConfig<\n TContext,\n TEvent,\n ProvidedActor,\n ParameterizedObject,\n ParameterizedObject,\n string,\n string,\n unknown,\n EventObject, // TEmitted\n any // TMeta\n >['output'];\n invoke: Array<\n InvokeDefinition<\n TContext,\n TEvent,\n TODO,\n TODO,\n TODO,\n TODO,\n TODO, // TEmitted\n TODO // TMeta\n >\n >;\n description?: string;\n tags: string[];\n}\n\nexport interface StateMachineDefinition<\n TContext extends MachineContext,\n TEvent extends EventObject\n> extends StateNodeDefinition<TContext, TEvent> {}\n\nexport type AnyStateNode = StateNode<any, any>;\n\nexport type AnyStateNodeDefinition = StateNodeDefinition<any, any>;\n\nexport type AnyMachineSnapshot = MachineSnapshot<\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any\n>;\n\n/** @deprecated Use `AnyMachineSnapshot` instead */\nexport type AnyState = AnyMachineSnapshot;\n\nexport type AnyStateMachine = StateMachine<\n any, // context\n any, // event\n any, // children\n any, // actor\n any, // action\n any, // guard\n any, // delay\n any, // state value\n any, // tag\n any, // input\n any, // output\n any, // emitted\n any, // TMeta\n any // TStateSchema\n>;\n\nexport type AnyStateConfig = StateConfig<any, AnyEventObject>;\n\nexport interface AtomicStateNodeConfig<\n TContext extends MachineContext,\n TEvent extends EventObject\n> extends StateNodeConfig<\n TContext,\n TEvent,\n TODO,\n TODO,\n TODO,\n TODO,\n TODO,\n TODO,\n TODO, // emitted\n TODO // meta\n > {\n initial?: undefined;\n parallel?: false | undefined;\n states?: undefined;\n onDone?: undefined;\n}\n\nexport interface HistoryStateNodeConfig<\n TContext extends MachineContext,\n TEvent extends EventObject\n> extends AtomicStateNodeConfig<TContext, TEvent> {\n history: 'shallow' | 'deep' | true;\n target: string | undefined;\n}\n\nexport type SimpleOrStateNodeConfig<\n TContext extends MachineContext,\n TEvent extends EventObject\n> =\n | AtomicStateNodeConfig<TContext, TEvent>\n | StateNodeConfig<\n TContext,\n TEvent,\n TODO,\n TODO,\n TODO,\n TODO,\n TODO,\n TODO,\n TODO, // emitted\n TODO // meta\n >;\n\nexport type ActionFunctionMap<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TActor extends ProvidedActor,\n TAction extends ParameterizedObject = ParameterizedObject,\n TGuard extends ParameterizedObject = ParameterizedObject,\n TDelay extends string = string,\n TEmitted extends EventObject = EventObject\n> = {\n [K in TAction['type']]?: ActionFunction<\n TContext,\n TEvent,\n TEvent,\n GetParameterizedParams<TAction extends { type: K } ? TAction : never>,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted\n >;\n};\n\ntype GuardMap<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TGuard extends ParameterizedObject\n> = {\n [K in TGuard['type']]?: GuardPredicate<\n TContext,\n TEvent,\n GetParameterizedParams<TGuard extends { type: K } ? TGuard : never>,\n TGuard\n >;\n};\n\nexport type DelayFunctionMap<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TAction extends ParameterizedObject\n> = Record<string, DelayConfig<TContext, TEvent, TAction['params'], TEvent>>;\n\nexport type DelayConfig<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject\n> = number | DelayExpr<TContext, TExpressionEvent, TParams, TEvent>;\n\n// TODO: possibly refactor this somehow, use even a simpler type, and maybe even make `machine.options` private or something\n/** @ignore */\nexport interface MachineImplementationsSimplified<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TActor extends ProvidedActor = ProvidedActor,\n TAction extends ParameterizedObject = ParameterizedObject,\n TGuard extends ParameterizedObject = ParameterizedObject\n> {\n guards: GuardMap<TContext, TEvent, TGuard>;\n actions: ActionFunctionMap<TContext, TEvent, TActor, TAction>;\n actors: Record<\n string,\n | AnyActorLogic\n | {\n src: AnyActorLogic;\n input: Mapper<TContext, TEvent, unknown, TEvent> | NonReducibleUnknown;\n }\n >;\n delays: DelayFunctionMap<TContext, TEvent, TAction>;\n}\n\ntype MachineImplementationsActions<TTypes extends StateMachineTypes> = {\n [K in TTypes['actions']['type']]?: ActionFunction<\n TTypes['context'],\n TTypes['events'],\n TTypes['events'],\n GetConcreteByKey<TTypes['actions'], 'type', K>['params'],\n TTypes['actors'],\n TTypes['actions'],\n TTypes['guards'],\n TTypes['delays'],\n TTypes['emitted']\n >;\n};\n\ntype MachineImplementationsActors<TTypes extends StateMachineTypes> = {\n [K in TTypes['actors']['src']]?: GetConcreteByKey<\n TTypes['actors'],\n 'src',\n K\n >['logic'];\n};\n\ntype MachineImplementationsDelays<TTypes extends StateMachineTypes> = {\n [K in TTypes['delays']]?: DelayConfig<\n TTypes['context'],\n TTypes['events'],\n // delays in referenced send actions might use specific `TAction`\n // delays executed by auto-generated send actions related to after transitions won't have that\n // since they are effectively implicit inline actions\n undefined,\n TTypes['events']\n >;\n};\n\ntype MachineImplementationsGuards<TTypes extends StateMachineTypes> = {\n [K in TTypes['guards']['type']]?: Guard<\n TTypes['context'],\n TTypes['events'],\n GetConcreteByKey<TTypes['guards'], 'type', K>['params'],\n TTypes['guards']\n >;\n};\n\nexport type InternalMachineImplementations<TTypes extends StateMachineTypes> = {\n actions?: MachineImplementationsActions<TTypes>;\n actors?: MachineImplementationsActors<TTypes>;\n delays?: MachineImplementationsDelays<TTypes>;\n guards?: MachineImplementationsGuards<TTypes>;\n};\n\ntype InitialContext<\n TContext extends MachineContext,\n TActor extends ProvidedActor,\n TInput,\n TEvent extends EventObject\n> = TContext | ContextFactory<TContext, TActor, TInput, TEvent>;\n\nexport type ContextFactory<\n TContext extends MachineContext,\n TActor extends ProvidedActor,\n TInput,\n TEvent extends EventObject = EventObject\n> = ({\n spawn,\n input,\n self\n}: {\n spawn: Spawner<TActor>;\n input: TInput;\n self: ActorRef<\n MachineSnapshot<\n TContext,\n TEvent,\n Record<string, AnyActorRef | undefined>, // TODO: this should be replaced with `TChildren`\n StateValue,\n string,\n unknown,\n TODO, // TMeta\n TODO // State schema\n >,\n TEvent,\n AnyEventObject\n >;\n}) => TContext;\n\nexport type MachineConfig<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TActor extends ProvidedActor = ProvidedActor,\n TAction extends ParameterizedObject = ParameterizedObject,\n TGuard extends ParameterizedObject = ParameterizedObject,\n TDelay extends string = string,\n TTag extends string = string,\n TInput = any,\n TOutput = unknown,\n TEmitted extends EventObject = EventObject,\n TMeta extends MetaObject = MetaObject\n> = (Omit<\n StateNodeConfig<\n DoNotInfer<TContext>,\n DoNotInfer<TEvent>,\n DoNotInfer<TActor>,\n DoNotInfer<TAction>,\n DoNotInfer<TGuard>,\n DoNotInfer<TDelay>,\n DoNotInfer<TTag>,\n DoNotInfer<TOutput>,\n DoNotInfer<TEmitted>,\n DoNotInfer<TMeta>\n >,\n 'output'\n> & {\n /** The initial context (extended state) */\n /** The machine's own version. */\n version?: string;\n // TODO: make it conditionally required\n output?: Mapper<TContext, DoneStateEvent, TOutput, TEvent> | TOutput;\n}) &\n (MachineContext extends TContext\n ? { context?: InitialContext<LowInfer<TContext>, TActor, TInput, TEvent> }\n : { context: InitialContext<LowInfer<TContext>, TActor, TInput, TEvent> });\n\nexport type UnknownMachineConfig = MachineConfig<MachineContext, EventObject>;\n\nexport interface ProvidedActor {\n src: string;\n logic: UnknownActorLogic;\n id?: string | undefined; // `| undefined` is required here for compatibility with `exactOptionalPropertyTypes`, see #4613\n}\n\nexport interface SetupTypes<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildrenMap extends Record<string, string>,\n TTag extends string,\n TInput,\n TOutput,\n TEmitted extends EventObject,\n TMeta extends MetaObject\n> {\n context?: TContext;\n events?: TEvent;\n children?: TChildrenMap;\n tags?: TTag;\n input?: TInput;\n output?: TOutput;\n emitted?: TEmitted;\n meta?: TMeta;\n}\n\nexport interface MachineTypes<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TActor extends ProvidedActor,\n TAction extends ParameterizedObject,\n TGuard extends ParameterizedObject,\n TDelay extends string,\n TTag extends string,\n TInput,\n TOutput,\n TEmitted extends EventObject,\n TMeta extends MetaObject\n> extends SetupTypes<\n TContext,\n TEvent,\n // in machine types we currently don't support `TChildren`\n // and IDs can still be configured through `TActor['id']`\n never,\n TTag,\n TInput,\n TOutput,\n TEmitted,\n TMeta\n > {\n actors?: TActor;\n actions?: TAction;\n guards?: TGuard;\n delays?: TDelay;\n meta?: TMeta;\n}\n\nexport interface HistoryStateNode<TContext extends MachineContext>\n extends StateNode<TContext> {\n history: 'shallow' | 'deep';\n target: string | undefined;\n}\n\nexport type HistoryValue<\n TContext extends MachineContext,\n TEvent extends EventObject\n> = Record<string, Array<StateNode<TContext, TEvent>>>;\n\nexport type PersistedHistoryValue = Record<string, Array<{ id: string }>>;\n\nexport type AnyHistoryValue = HistoryValue<any, any>;\n\nexport type StateFrom<\n T extends AnyStateMachine | ((...args: any[]) => AnyStateMachine)\n> = T extends AnyStateMachine\n ? ReturnType<T['transition']>\n : T extends (...args: any[]) => AnyStateMachine\n ? ReturnType<ReturnType<T>['transition']>\n : never;\n\nexport type Transitions<\n TContext extends MachineContext,\n TEvent extends EventObject\n> = Array<TransitionDefinition<TContext, TEvent>>;\n\nexport interface DoneActorEvent<TOutput = unknown, TId extends string = string>\n extends EventObject {\n type: `xstate.done.actor.${TId}`;\n output: TOutput;\n actorId: TId;\n}\n\nexport interface ErrorActorEvent<\n TErrorData = unknown,\n TId extends string = string\n> extends EventObject {\n type: `xstate.error.actor.${TId}`;\n error: TErrorData;\n actorId: TId;\n}\n\nexport interface SnapshotEvent<\n TSnapshot extends Snapshot<unknown> = Snapshot<unknown>\n> extends EventObject {\n type: `xstate.snapshot.${string}`;\n snapshot: TSnapshot;\n}\n\nexport interface DoneStateEvent<TOutput = unknown> extends EventObject {\n type: `xstate.done.state.${string}`;\n output: TOutput;\n}\n\nexport type DelayExpr<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject\n> = (\n args: ActionArgs<TContext, TExpressionEvent, TEvent>,\n params: TParams\n) => number;\n\nexport type LogExpr<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject\n> = (\n args: ActionArgs<TContext, TExpressionEvent, TEvent>,\n params: TParams\n) => unknown;\n\nexport type SendExpr<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TSentEvent extends EventObject,\n TEvent extends EventObject\n> = (\n args: ActionArgs<TContext, TExpressionEvent, TEvent>,\n params: TParams\n) => TSentEvent;\n\nexport enum SpecialTargets {\n Parent = '#_parent',\n Internal = '#_internal'\n}\n\nexport interface SendToActionOptions<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject,\n TDelay extends string\n> extends RaiseActionOptions<\n TContext,\n TExpressionEvent,\n TParams,\n TEvent,\n TDelay\n > {}\n\nexport interface RaiseActionOptions<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject,\n TDelay extends string\n> {\n id?: string;\n delay?:\n | Delay<TDelay>\n | DelayExpr<TContext, TExpressionEvent, TParams, TEvent>;\n}\n\nexport interface RaiseActionParams<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject,\n TDelay extends string\n> extends RaiseActionOptions<\n TContext,\n TExpressionEvent,\n TParams,\n TEvent,\n TDelay\n > {\n event: TEvent | SendExpr<TContext, TExpressionEvent, TParams, TEvent, TEvent>;\n}\n\nexport interface SendToActionParams<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TSentEvent extends EventObject,\n TEvent extends EventObject,\n TDelay extends string\n> extends SendToActionOptions<\n TContext,\n TExpressionEvent,\n TParams,\n TEvent,\n TDelay\n > {\n event:\n | TSentEvent\n | SendExpr<TContext, TExpressionEvent, TParams, TSentEvent, TEvent>;\n}\n\nexport type Assigner<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject,\n TActor extends ProvidedActor\n> = (\n args: AssignArgs<TContext, TExpressionEvent, TEvent, TActor>,\n params: TParams\n) => Partial<TContext>;\n\nexport type PartialAssigner<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject,\n TActor extends ProvidedActor,\n TKey extends keyof TContext\n> = (\n args: AssignArgs<TContext, TExpressionEvent, TEvent, TActor>,\n params: TParams\n) => TContext[TKey];\n\nexport type PropertyAssigner<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject,\n TActor extends ProvidedActor\n> = {\n [K in keyof TContext]?:\n | PartialAssigner<TContext, TExpressionEvent, TParams, TEvent, TActor, K>\n | TContext[K];\n};\n\nexport type Mapper<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TResult,\n TEvent extends EventObject\n> = (args: {\n context: TContext;\n event: TExpressionEvent;\n self: ActorRef<\n MachineSnapshot<\n TContext,\n TEvent,\n Record<string, AnyActorRef>, // TODO: this should be replaced with `TChildren`\n StateValue,\n string,\n unknown,\n TODO, // TMeta\n TODO // State schema\n >,\n TEvent,\n AnyEventObject\n >;\n}) => TResult;\n\nexport interface TransitionDefinition<\n TContext extends MachineContext,\n TEvent extends EventObject\n> extends Omit<\n TransitionConfig<\n TContext,\n TEvent,\n TEvent,\n TODO,\n TODO,\n TODO,\n TODO,\n TODO, // TEmitted\n TODO // TMeta\n >,\n | 'target'\n // `guard` is correctly rejected by `extends` here and `actions` should be too\n // however, `any` passed to `TransitionConfig` as `TAction` collapses its `.actions` to `any` and it's accidentally allowed here\n // it doesn't exactly have to be incorrect, we are overriding this here anyway but it looks like a lucky accident rather than smth done on purpose\n | 'guard'\n > {\n target: ReadonlyArray<StateNode<TContext, TEvent>> | undefined;\n source: StateNode<TContext, TEvent>;\n actions: readonly UnknownAction[];\n reenter: boolean;\n guard?: UnknownGuard;\n eventType: EventDescriptor<TEvent>;\n toJSON: () => {\n target: string[] | undefined;\n source: string;\n actions: readonly UnknownAction[];\n guard?: UnknownGuard;\n eventType: EventDescriptor<TEvent>;\n meta?: Record<string, any>;\n };\n}\n\nexport type AnyTransitionDefinition = TransitionDefinition<any, any>;\n\nexport interface InitialTransitionDefinition<\n TContext extends MachineContext,\n TEvent extends EventObject\n> extends TransitionDefinition<TContext, TEvent> {\n target: ReadonlyArray<StateNode<TContext, TEvent>>;\n guard?: never;\n}\n\nexport type TransitionDefinitionMap<\n TContext extends MachineContext,\n TEvent extends EventObject\n> = {\n [K in EventDescriptor<TEvent>]: Array<\n TransitionDefinition<TContext, ExtractEvent<TEvent, K>>\n >;\n};\n\nexport interface DelayedTransitionDefinition<\n TContext extends MachineContext,\n TEvent extends EventObject\n> extends TransitionDefinition<TContext, TEvent> {\n delay: number | string | DelayExpr<TContext, TEvent, undefined, TEvent>;\n}\n\nexport interface StateLike<TContext extends MachineContext> {\n value: StateValue;\n context: TContext;\n event: EventObject;\n}\n\nexport interface StateConfig<\n TContext extends MachineContext,\n TEvent extends EventObject\n> {\n context: TContext;\n historyValue?: HistoryValue<TContext, TEvent>;\n /** @internal */\n _nodes: Array<StateNode<TContext, TEvent>>;\n children: Record<string, AnyActorRef>;\n status: SnapshotStatus;\n output?: any;\n error?: unknown;\n machine?: StateMachine<\n TContext,\n TEvent,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any, // TMeta\n any // TStateSchema\n >;\n}\n\nexport interface ActorOptions<TLogic extends AnyActorLogic> {\n /**\n * The clock that is responsible for setting and clearing timeouts, such as\n * delayed events and transitions.\n *\n * @remarks\n * You can create your own “clock”. The clock interface is an object with two\n * functions/methods:\n *\n * - `setTimeout` - same arguments as `window.setTimeout(fn, timeout)`\n * - `clearTimeout` - same arguments as `window.clearTimeout(id)`\n *\n * By default, the native `setTimeout` and `clearTimeout` functions are used.\n *\n * For testing, XState provides `SimulatedClock`.\n * @see {@link Clock}\n * @see {@link SimulatedClock}\n */\n clock?: Clock;\n /**\n * Specifies the logger to be used for `log(...)` actions. Defaults to the\n * native `console.log(...)` method.\n */\n logger?: (...args: any[]) => void;\n parent?: AnyActorRef;\n /** @internal */\n syncSnapshot?: boolean;\n /** The custom `id` for referencing this service. */\n id?: string;\n /** @deprecated Use `inspect` instead. */\n devTools?: never;\n\n /** The system ID to register this actor under. */\n systemId?: string;\n /** The input data to pass to the actor. */\n input?: InputFrom<TLogic>;\n\n /**\n * Initializes actor logic from a specific persisted internal state.\n *\n * @remarks\n * If the state is compatible with the actor logic, when the actor is started\n * it will be at that persisted state. Actions from machine actors will not be\n * re-executed, because they are assumed to have been already executed.\n * However, invocations will be restarted, and spawned actors will be restored\n * recursively.\n *\n * Can be generated with {@link Actor.getPersistedSnapshot}.\n * @see https://stately.ai/docs/persistence\n */\n snapshot?: Snapshot<unknown>;\n\n /** @deprecated Use `snapshot` instead. */\n state?: Snapshot<unknown>;\n\n /** The source actor logic. */\n src?: string | AnyActorLogic;\n\n /**\n * A callback function or observer object which can be used to inspect actor\n * system updates.\n *\n * @remarks\n * If a callback function is provided, it can accept an inspection event\n * argument. The types of inspection events that can be observed include:\n *\n * - `@xstate.actor` - An actor ref has been created in the system\n * - `@xstate.event` - An event was sent from a source actor ref to a target\n * actor ref in the system\n * - `@xstate.snapshot` - An actor ref emitted a snapshot due to a received\n * event\n *\n * @example\n *\n * ```ts\n * import { createMachine } from 'xstate';\n *\n * const machine = createMachine({\n * // ...\n * });\n *\n * const actor = createActor(machine, {\n * inspect: (inspectionEvent) => {\n * if (inspectionEvent.actorRef === actor) {\n * // This event is for the root actor\n * }\n *\n * if (inspectionEvent.type === '@xstate.actor') {\n * console.log(inspectionEvent.actorRef);\n * }\n *\n * if (inspectionEvent.type === '@xstate.event') {\n * console.log(inspectionEvent.sourceRef);\n * console.log(inspectionEvent.actorRef);\n * console.log(inspectionEvent.event);\n * }\n *\n * if (inspectionEvent.type === '@xstate.snapshot') {\n * console.log(inspectionEvent.actorRef);\n * console.log(inspectionEvent.event);\n * console.log(inspectionEvent.snapshot);\n * }\n * }\n * });\n * ```\n *\n * Alternately, an observer object (`{ next?, error?, complete? }`) can be\n * provided:\n *\n * @example\n *\n * ```ts\n * const actor = createActor(machine, {\n * inspect: {\n * next: (inspectionEvent) => {\n * if (inspectionEvent.actorRef === actor) {\n * // This event is for the root actor\n * }\n *\n * if (inspectionEvent.type === '@xstate.actor') {\n * console.log(inspectionEvent.actorRef);\n * }\n *\n * if (inspectionEvent.type === '@xstate.event') {\n * console.log(inspectionEvent.sourceRef);\n * console.log(inspectionEvent.actorRef);\n * console.log(inspectionEvent.event);\n * }\n *\n * if (inspectionEvent.type === '@xstate.snapshot') {\n * console.log(inspectionEvent.actorRef);\n * console.log(inspectionEvent.event);\n * console.log(inspectionEvent.snapshot);\n * }\n * }\n * }\n * });\n * ```\n */\n inspect?:\n | Observer<InspectionEvent>\n | ((inspectionEvent: InspectionEvent) => void);\n}\n\nexport type AnyActor = Actor<any>;\n\n/** @deprecated Use `AnyActor` instead. */\nexport type AnyInterpreter = AnyActor;\n\n// Based on RxJS types\nexport type Observer<T> = {\n next?: (value: T) => void;\n error?: (err: unknown) => void;\n complete?: () => void;\n};\n\nexport interface Subscription {\n unsubscribe(): void;\n}\n\nexport interface InteropObservable<T> {\n [Symbol.observable]: () => InteropSubscribable<T>;\n}\n\nexport interface InteropSubscribable<T> {\n subscribe(observer: Observer<T>): Subscription;\n}\n\nexport interface Subscribable<T> extends InteropSubscribable<T> {\n subscribe(observer: Observer<T>): Subscription;\n subscribe(\n next: (value: T) => void,\n error?: (error: any) => void,\n complete?: () => void\n ): Subscription;\n}\n\ntype EventDescriptorMatches<\n TEventType extends string,\n TNormalizedDescriptor\n> = TEventType extends TNormalizedDescriptor ? true : false;\n\nexport type ExtractEvent<\n TEvent extends EventObject,\n TDescriptor extends EventDescriptor<TEvent>\n> = string extends TEvent['type']\n ? TEvent\n : NormalizeDescriptor<TDescriptor> extends infer TNormalizedDescriptor\n ? TEvent extends any\n ? // true is the check type here to match both true and boolean\n true extends EventDescriptorMatches<\n TEvent['type'],\n TNormalizedDescriptor\n >\n ? TEvent\n : never\n : never\n : never;\n\nexport interface BaseActorRef<TEvent extends EventObject> {\n send: (event: TEvent) => void;\n}\n\nexport interface ActorLike<TCurrent, TEvent extends EventObject>\n extends Subscribable<TCurrent> {\n send: (event: TEvent) => void;\n}\n\nexport interface ActorRef<\n TSnapshot extends Snapshot<unknown>,\n TEvent extends EventObject,\n TEmitted extends EventObject = EventObject\n> extends Subscribable<TSnapshot>,\n InteropObservable<TSnapshot> {\n /** The unique identifier for this actor relative to its parent. */\n id: string;\n sessionId: string;\n /** @internal */\n _send: (event: TEvent) => void;\n send: (event: TEvent) => void;\n start: () => void;\n getSnapshot: () => TSnapshot;\n getPersistedSnapshot: () => Snapshot<unknown>;\n stop: () => void;\n toJSON?: () => any;\n // TODO: figure out how to hide this externally as `sendTo(ctx => ctx.actorRef._parent._parent._parent._parent)` shouldn't be allowed\n _parent?: AnyActorRef;\n system: AnyActorSystem;\n /** @internal */\n _processingStatus: ProcessingStatus;\n src: string | AnyActorLogic;\n // TODO: remove from ActorRef interface\n // (should only be available on Actor)\n on: <TType extends TEmitted['type'] | '*'>(\n type: TType,\n handler: (\n emitted: TEmitted & (TType extends '*' ? unknown : { type: TType })\n ) => void\n ) => Subscription;\n}\n\nexport type AnyActorRef = ActorRef<\n any,\n any, // TODO: shouldn't this be AnyEventObject?\n any\n>;\n\nexport type ActorRefLike = Pick<\n AnyActorRef,\n 'sessionId' | 'send' | 'getSnapshot'\n>;\n\nexport type UnknownActorRef = ActorRef<Snapshot<unknown>, EventObject>;\n\nexport type ActorLogicFrom<T> =\n ReturnTypeOrValue<T> extends infer R\n ? R extends StateMachine<\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, // TMeta\n any // TStateSchema\n >\n ? R\n : R extends Promise<infer U>\n ? PromiseActorLogic<U>\n : never\n : never;\n\n// TODO: in v6, this should only accept AnyActorLogic, like ActorRefFromLogic\nexport type ActorRefFrom<T> =\n ReturnTypeOrValue<T> extends infer R\n ? R extends StateMachine<\n infer TContext,\n infer TEvent,\n infer TChildren,\n infer _TActor,\n infer _TAction,\n infer _TGuard,\n infer _TDelay,\n infer TStateValue,\n infer TTag,\n infer _TInput,\n infer TOutput,\n infer TEmitted,\n infer TMeta,\n infer TStateSchema\n >\n ? ActorRef<\n MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TStateSchema\n >,\n TEvent,\n TEmitted\n >\n : R extends Promise<infer U>\n ? ActorRefFrom<PromiseActorLogic<U>>\n : R extends ActorLogic<\n infer TSnapshot,\n infer TEvent,\n infer _TInput,\n infer _TSystem,\n infer TEmitted\n >\n ? ActorRef<TSnapshot, TEvent, TEmitted>\n : never\n : never;\n\nexport type ActorRefFromLogic<T extends AnyActorLogic> = ActorRef<\n SnapshotFrom<T>,\n EventFromLogic<T>,\n EmittedFrom<T>\n>;\n\nexport type DevToolsAdapter = (service: AnyActor) => void;\n\n/** @deprecated Use `Actor<T>` instead. */\nexport type InterpreterFrom<\n T extends AnyStateMachine | ((...args: any[]) => AnyStateMachine)\n> =\n ReturnTypeOrValue<T> extends StateMachine<\n infer TContext,\n infer TEvent,\n infer TChildren,\n infer _TActor,\n infer _TAction,\n infer _TGuard,\n infer _TDelay,\n infer TStateValue,\n infer TTag,\n infer TInput,\n infer TOutput,\n infer TEmitted,\n infer TMeta,\n infer TStateSchema\n >\n ? Actor<\n ActorLogic<\n MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TStateSchema\n >,\n TEvent,\n TInput,\n AnyActorSystem,\n TEmitted\n >\n >\n : never;\n\nexport type MachineImplementationsFrom<\n T extends AnyStateMachine | ((...args: any[]) => AnyStateMachine)\n> =\n ReturnTypeOrValue<T> extends StateMachine<\n infer TContext,\n infer TEvent,\n infer _TChildren,\n infer TActor,\n infer TAction,\n infer TGuard,\n infer TDelay,\n infer _TStateValue,\n infer TTag,\n infer _TInput,\n infer _TOutput,\n infer TEmitted,\n infer _TMeta,\n infer _TStateSchema\n >\n ? InternalMachineImplementations<\n ResolvedStateMachineTypes<\n TContext,\n TEvent,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TTag,\n TEmitted\n >\n >\n : never;\n\nexport interface ActorScope<\n TSnapshot extends Snapshot<unknown>,\n TEvent extends EventObject,\n TSystem extends AnyActorSystem = AnyActorSystem,\n TEmitted extends EventObject = EventObject\n> {\n self: ActorRef<TSnapshot, TEvent, TEmitted>;\n id: string;\n sessionId: string;\n logger: (...args: any[]) => void;\n defer: (fn: () => void) => void;\n emit: (event: TEmitted) => void;\n system: TSystem;\n stopChild: (child: AnyActorRef) => void;\n actionExecutor: ActionExecutor;\n}\n\nexport type AnyActorScope = ActorScope<\n any, // TSnapshot\n any, // TEvent\n AnyActorSystem,\n any // TEmitted\n>;\n\nexport type SnapshotStatus = 'active' | 'done' | 'error' | 'stopped';\n\nexport type Snapshot<TOutput> =\n | {\n status: 'active';\n output: undefined;\n error: undefined;\n }\n | {\n status: 'done';\n output: TOutput;\n error: undefined;\n }\n | {\n status: 'error';\n output: undefined;\n error: unknown;\n }\n | {\n status: 'stopped';\n output: undefined;\n error: undefined;\n };\n\n/**\n * Represents logic which can be used by an actor.\n *\n * @template TSnapshot - The type of the snapshot.\n * @template TEvent - The type of the event object.\n * @template TInput - The type of the input.\n * @template TSystem - The type of the actor system.\n */\nexport interface ActorLogic<\n in out TSnapshot extends Snapshot<unknown>, // it's invariant because it's also part of `ActorScope[\"self\"][\"getSnapshot\"]`\n in out TEvent extends EventObject, // it's invariant because it's also part of `ActorScope[\"self\"][\"send\"]`\n in TInput = NonReducibleUnknown,\n TSystem extends AnyActorSystem = AnyActorSystem,\n in out TEmitted extends EventObject = EventObject // it's invariant because it's also aprt of `ActorScope[\"self\"][\"on\"]`\n> {\n /** The initial setup/configuration used to create the actor logic. */\n config?: unknown;\n /**\n * Transition function that processes the current state and an incoming event\n * to produce a new state.\n *\n * @param snapshot - The current state.\n * @param event - The incoming event.\n * @param actorScope - The actor scope.\n * @returns The new state.\n */\n transition: (\n snapshot: TSnapshot,\n event: TEvent,\n actorScope: ActorScope<TSnapshot, TEvent, TSystem, TEmitted>\n ) => TSnapshot;\n /**\n * Called to provide the initial state of the actor.\n *\n * @param actorScope - The actor scope.\n * @param input - The input for the initial state.\n * @returns The initial state.\n */\n getInitialSnapshot: (\n actorScope: ActorScope<TSnapshot, TEvent, TSystem, TEmitted>,\n input: TInput\n ) => TSnapshot;\n /**\n * Called when Actor is created to restore the internal state of the actor\n * given a persisted state. The persisted state can be created by\n * `getPersistedSnapshot`.\n *\n * @param persistedState - The persisted state to restore from.\n * @param actorScope - The actor scope.\n * @returns The restored state.\n */\n restoreSnapshot?: (\n persistedState: Snapshot<unknown>,\n actorScope: ActorScope<TSnapshot, TEvent, AnyActorSystem, TEmitted>\n ) => TSnapshot;\n /**\n * Called when the actor is started.\n *\n * @param snapshot - The starting state.\n * @param actorScope - The actor scope.\n */\n start?: (\n snapshot: TSnapshot,\n actorScope: ActorScope<TSnapshot, TEvent, AnyActorSystem, TEmitted>\n ) => void;\n /**\n * Obtains the internal state of the actor in a representation which can be be\n * persisted. The persisted state can be restored by `restoreSnapshot`.\n *\n * @param snapshot - The current state.\n * @returns The a representation of the internal state to be persisted.\n */\n getPersistedSnapshot: (\n snapshot: TSnapshot,\n options?: unknown\n ) => Snapshot<unknown>;\n}\n\nexport type AnyActorLogic = ActorLogic<\n any, // snapshot\n any, // event\n any, // input\n any, // system\n any // emitted\n>;\n\nexport type UnknownActorLogic = ActorLogic<\n any, // snapshot\n any, // event\n any, // input\n AnyActorSystem,\n any // emitted\n>;\n\nexport type SnapshotFrom<T> =\n ReturnTypeOrValue<T> extends infer R\n ? R extends ActorRef<infer TSnapshot, infer _, infer __>\n ? TSnapshot\n : R extends Actor<infer TLogic>\n ? SnapshotFrom<TLogic>\n : R extends ActorLogic<\n infer _TSnapshot,\n infer _TEvent,\n infer _TInput,\n infer _TEmitted,\n infer _TSystem\n >\n ? ReturnType<R['transition']>\n : R extends ActorScope<\n infer TSnapshot,\n infer _TEvent,\n infer _TEmitted,\n infer _TSystem\n >\n ? TSnapshot\n : never\n : never;\n\nexport type EventFromLogic<TLogic extends AnyActorLogic> =\n TLogic extends ActorLogic<\n infer _TSnapshot,\n infer TEvent,\n infer _TInput,\n infer _TEmitted,\n infer _TSystem\n >\n ? TEvent\n : never;\n\nexport type EmittedFrom<TLogic extends AnyActorLogic> =\n TLogic extends ActorLogic<\n infer _TSnapshot,\n infer _TEvent,\n infer _TInput,\n infer _TSystem,\n infer TEmitted\n >\n ? TEmitted\n : never;\n\ntype ResolveEventType<T> =\n ReturnTypeOrValue<T> extends infer R\n ? R extends StateMachine<\n infer _TContext,\n infer TEvent,\n infer _TChildren,\n infer _TActor,\n infer _TAction,\n infer _TGuard,\n infer _TDelay,\n infer _TStateValue,\n infer _TTag,\n infer _TInput,\n infer _TOutput,\n infer _TEmitted,\n infer _TMeta,\n infer _TStateSchema\n >\n ? TEvent\n : R extends MachineSnapshot<\n infer _TContext,\n infer TEvent,\n infer _TChildren,\n infer _TStateValue,\n infer _TTag,\n infer _TOutput,\n infer _TMeta,\n infer _TStateSchema\n >\n ? TEvent\n : R extends ActorRef<infer _TSnapshot, infer TEvent, infer _TEmitted>\n ? TEvent\n : never\n : never;\n\nexport type EventFrom<\n T,\n K extends Prop<TEvent, 'type'> = never,\n TEvent extends EventObject = ResolveEventType<T>\n> = IsNever<K> extends true ? TEvent : ExtractEvent<TEvent, K>;\n\nexport type ContextFrom<T> =\n ReturnTypeOrValue<T> extends infer R\n ? R extends StateMachine<\n infer TContext,\n infer _TEvent,\n infer _TChildren,\n infer _TActor,\n infer _TAction,\n infer _TGuard,\n infer _TDelay,\n infer _TStateValue,\n infer _TTag,\n infer _TInput,\n infer _TOutput,\n infer _TEmitted,\n infer _TMeta,\n infer _TStateSchema\n >\n ? TContext\n : R extends MachineSnapshot<\n infer TContext,\n infer _TEvent,\n infer _TChildren,\n infer _TStateValue,\n infer _TTag,\n infer _TOutput,\n infer _TMeta,\n infer _TStateSchema\n >\n ? TContext\n : R extends Actor<infer TActorLogic>\n ? TActorLogic extends StateMachine<\n infer TContext,\n infer _TEvent,\n infer _TChildren,\n infer _TActor,\n infer _TAction,\n infer _TGuard,\n infer _TDelay,\n infer _TStateValue,\n infer _TTag,\n infer _TInput,\n infer _TOutput,\n infer _TEmitted,\n infer _TMeta,\n infer _TStateSchema\n >\n ? TContext\n : never\n : never\n : never;\n\nexport type InferEvent<E extends EventObject> = {\n [T in E['type']]: { type: T } & Extract<E, { type: T }>;\n}[E['type']];\n\nexport type TODO = any;\n\nexport type StateValueFrom<TMachine extends AnyStateMachine> = Parameters<\n StateFrom<TMachine>['matches']\n>[0];\n\nexport type TagsFrom<TMachine extends AnyStateMachine> = Parameters<\n StateFrom<TMachine>['hasTag']\n>[0];\n\nexport interface ActorSystemInfo {\n actors: Record<string, AnyActorRef>;\n}\n\nexport type RequiredActorOptions<TActor extends ProvidedActor> =\n | (undefined extends TActor['id'] ? never : 'id')\n | (undefined extends InputFrom<TActor['logic']> ? never : 'input');\n\nexport type RequiredLogicInput<TLogic extends AnyActorLogic> =\n undefined extends InputFrom<TLogic> ? never : 'input';\n\ntype ExtractLiteralString<T extends string | undefined> = T extends string\n ? string extends T\n ? never\n : T\n : never;\n\ntype ToConcreteChildren<TActor extends ProvidedActor> = {\n [A in TActor as ExtractLiteralString<A['id']>]?: ActorRefFromLogic<\n A['logic']\n >;\n};\n\nexport type ToChildren<TActor extends ProvidedActor> =\n // only proceed further if all configured `src`s are literal strings\n string extends TActor['src']\n ? // TODO: replace `AnyActorRef` with `UnknownActorRef`~\n // or maybe even `TActor[\"logic\"]` since it's possible to configure `{ src: string; logic: SomeConcreteLogic }`\n // TODO: consider adding `| undefined` here\n Record<string, AnyActorRef>\n : Compute<\n ToConcreteChildren<TActor> &\n {\n include: {\n [id: string]: TActor extends any\n ? ActorRefFromLogic<TActor['logic']> | undefined\n : never;\n };\n exclude: unknown;\n }[undefined extends TActor['id'] // if not all actors have literal string IDs then we need to create an index signature containing all possible actor types\n ? 'include'\n : string extends TActor['id']\n ? 'include'\n : 'exclude']\n >;\n\nexport type StateSchema = {\n id?: string;\n states?: Record<string, StateSchema>;\n\n // Other types\n // Needed because TS treats objects with all optional properties as a \"weak\" object\n // https://github.com/statelyai/xstate/issues/5031\n type?: unknown;\n invoke?: unknown;\n on?: unknown;\n entry?: unknown;\n exit?: unknown;\n onDone?: unknown;\n after?: unknown;\n always?: unknown;\n meta?: unknown;\n output?: unknown;\n tags?: unknown;\n description?: unknown;\n};\n\nexport type StateId<\n TSchema extends StateSchema,\n TKey extends string = '(machine)',\n TParentKey extends string | null = null\n> =\n | (TSchema extends { id: string }\n ? TSchema['id']\n : TParentKey extends null\n ? TKey\n : `${TParentKey}.${TKey}`)\n | (TSchema['states'] extends Record<string, any>\n ? Values<{\n [K in keyof TSchema['states'] & string]: StateId<\n TSchema['states'][K],\n K,\n TParentKey extends string\n ? `${TParentKey}.${TKey}`\n : TSchema['id'] extends string\n ? TSchema['id']\n : TKey\n >;\n }>\n : never);\n\nexport interface StateMachineTypes {\n context: MachineContext;\n events: EventObject;\n actors: ProvidedActor;\n actions: ParameterizedObject;\n guards: ParameterizedObject;\n delays: string;\n tags: string;\n emitted: EventObject;\n}\n\n/** @deprecated */\nexport interface ResolvedStateMachineTypes<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TActor extends ProvidedActor,\n TAction extends ParameterizedObject,\n TGuard extends ParameterizedObject,\n TDelay extends string,\n TTag extends string,\n TEmitted extends EventObject = EventObject\n> {\n context: TContext;\n events: TEvent;\n actors: TActor;\n actions: TAction;\n guards: TGuard;\n delays: TDelay;\n tags: TTag;\n emitted: TEmitted;\n}\n\nexport type GetConcreteByKey<\n T,\n TKey extends keyof T,\n TValue extends T[TKey]\n> = T & Record<TKey, TValue>;\n\ntype _GroupStateKeys<\n T extends StateSchema,\n S extends keyof T['states']\n> = S extends any\n ? T['states'][S] extends { type: 'history' }\n ? [never, never]\n : T extends { type: 'parallel' }\n ? [S, never]\n : 'states' extends keyof T['states'][S]\n ? [S, never]\n : [never, S]\n : never;\n\ntype GroupStateKeys<T extends StateSchema, S extends keyof T['states']> = {\n nonLeaf: _GroupStateKeys<T, S & string>[0];\n leaf: _GroupStateKeys<T, S & string>[1];\n};\n\nexport type ToStateValue<T extends StateSchema> = T extends {\n states: Record<infer S, any>;\n}\n ? IsNever<S> extends true\n ? {}\n :\n | GroupStateKeys<T, S>['leaf']\n | (IsNever<GroupStateKeys<T, S>['nonLeaf']> extends false\n ? T extends { type: 'parallel' }\n ? {\n [K in GroupStateKeys<T, S>['nonLeaf']]: ToStateValue<\n T['states'][K]\n >;\n }\n : Compute<\n Values<{\n [K in GroupStateKeys<T, S>['nonLeaf']]: {\n [StateKey in K]: ToStateValue<T['states'][K]>;\n };\n }>\n >\n : never)\n : {};\n\nexport interface ExecutableActionObject {\n type: string;\n info: ActionArgs<MachineContext, EventObject, EventObject>;\n params: NonReducibleUnknown;\n exec:\n | ((info: ActionArgs<any, any, any>, params: unknown) => void)\n | undefined;\n}\n\nexport interface ToExecutableAction<T extends ParameterizedObject>\n extends ExecutableActionObject {\n type: T['type'];\n params: T['params'];\n exec: undefined;\n}\n\nexport interface ExecutableSpawnAction extends ExecutableActionObject {\n type: 'xstate.spawnChild';\n info: ActionArgs<MachineContext, EventObject, EventObject>;\n params: {\n id: string;\n actorRef: AnyActorRef | undefined;\n src: string | AnyActorLogic;\n };\n}\n\n// TODO: cover all that can be actually returned\nexport type SpecialExecutableAction =\n | ExecutableSpawnAction\n | ExecutableRaiseAction\n | ExecutableSendToAction;\n\nexport type ExecutableActionsFrom<T extends AnyActorLogic> =\n T extends StateMachine<\n infer _TContext,\n infer _TEvent,\n infer _TChildren,\n infer _TActor,\n infer TAction,\n infer _TGuard,\n infer _TDelay,\n infer _TStateValue,\n infer _TTag,\n infer _TInput,\n infer _TOutput,\n infer _TEmitted,\n infer _TMeta,\n infer _TConfig\n >\n ?\n | SpecialExecutableAction\n | (string extends TAction['type'] ? never : ToExecutableAction<TAction>)\n : never;\n\nexport type ActionExecutor = (actionToExecute: ExecutableActionObject) => void;\n\nexport type BuiltinActionResolution = [\n AnyMachineSnapshot,\n NonReducibleUnknown, // params\n UnknownAction[] | undefined\n];\n","import isDevelopment from '#is-development';\nimport { XSTATE_ERROR } from '../constants.ts';\nimport { createErrorActorEvent } from '../eventUtils.ts';\nimport { executingCustomAction } from '../createActor.ts';\nimport {\n ActionArgs,\n ActionFunction,\n AnyActorRef,\n AnyActorScope,\n AnyEventObject,\n AnyMachineSnapshot,\n Cast,\n DelayExpr,\n DoNotInfer,\n EventFrom,\n EventObject,\n ExecutableActionObject,\n InferEvent,\n MachineContext,\n ParameterizedObject,\n SendExpr,\n SendToActionOptions,\n BuiltinActionResolution,\n SpecialTargets,\n UnifiedArg\n} from '../types.ts';\n\nfunction resolveSendTo(\n actorScope: AnyActorScope,\n snapshot: AnyMachineSnapshot,\n args: ActionArgs<any, any, any>,\n actionParams: ParameterizedObject['params'] | undefined,\n {\n to,\n event: eventOrExpr,\n id,\n delay\n }: {\n to:\n | AnyActorRef\n | string\n | ((\n args: UnifiedArg<MachineContext, EventObject, EventObject>,\n params: ParameterizedObject['params'] | undefined\n ) => AnyActorRef | string);\n event:\n | EventObject\n | SendExpr<\n MachineContext,\n EventObject,\n ParameterizedObject['params'] | undefined,\n EventObject,\n EventObject\n >;\n id: string | undefined;\n delay:\n | string\n | number\n | DelayExpr<\n MachineContext,\n EventObject,\n ParameterizedObject['params'] | undefined,\n EventObject\n >\n | undefined;\n },\n extra: { deferredActorIds: string[] | undefined }\n): BuiltinActionResolution {\n const delaysMap = snapshot.machine.implementations.delays;\n\n if (typeof eventOrExpr === 'string') {\n throw new Error(\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `Only event objects may be used with sendTo; use sendTo({ type: \"${eventOrExpr}\" }) instead`\n );\n }\n const resolvedEvent =\n typeof eventOrExpr === 'function'\n ? eventOrExpr(args, actionParams)\n : eventOrExpr;\n\n let resolvedDelay: number | undefined;\n if (typeof delay === 'string') {\n const configDelay = delaysMap && delaysMap[delay];\n resolvedDelay =\n typeof configDelay === 'function'\n ? configDelay(args, actionParams)\n : configDelay;\n } else {\n resolvedDelay =\n typeof delay === 'function' ? delay(args, actionParams) : delay;\n }\n\n const resolvedTarget = typeof to === 'function' ? to(args, actionParams) : to;\n let targetActorRef: AnyActorRef | string | undefined;\n\n if (typeof resolvedTarget === 'string') {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison\n if (resolvedTarget === SpecialTargets.Parent) {\n targetActorRef = actorScope.self._parent;\n }\n // eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison\n else if (resolvedTarget === SpecialTargets.Internal) {\n targetActorRef = actorScope.self;\n } else if (resolvedTarget.startsWith('#_')) {\n // SCXML compatibility: https://www.w3.org/TR/scxml/#SCXMLEventProcessor\n // #_invokeid. If the target is the special term '#_invokeid', where invokeid is the invokeid of an SCXML session that the sending session has created by <invoke>, the Processor must add the event to the external queue of that session.\n targetActorRef = snapshot.children[resolvedTarget.slice(2)];\n } else {\n targetActorRef = extra.deferredActorIds?.includes(resolvedTarget)\n ? resolvedTarget\n : snapshot.children[resolvedTarget];\n }\n if (!targetActorRef) {\n throw new Error(\n `Unable to send event to actor '${resolvedTarget}' from machine '${snapshot.machine.id}'.`\n );\n }\n } else {\n targetActorRef = resolvedTarget || actorScope.self;\n }\n\n return [\n snapshot,\n {\n to: targetActorRef,\n targetId: typeof resolvedTarget === 'string' ? resolvedTarget : undefined,\n event: resolvedEvent,\n id,\n delay: resolvedDelay\n },\n undefined\n ];\n}\n\nfunction retryResolveSendTo(\n _: AnyActorScope,\n snapshot: AnyMachineSnapshot,\n params: {\n to: AnyActorRef;\n event: EventObject;\n id: string | undefined;\n delay: number | undefined;\n }\n) {\n if (typeof params.to === 'string') {\n params.to = snapshot.children[params.to];\n }\n}\n\nfunction executeSendTo(\n actorScope: AnyActorScope,\n params: {\n to: AnyActorRef;\n event: EventObject;\n id: string | undefined;\n delay: number | undefined;\n }\n) {\n // this forms an outgoing events queue\n // thanks to that the recipient actors are able to read the *updated* snapshot value of the sender\n actorScope.defer(() => {\n const { to, event, delay, id } = params;\n if (typeof delay === 'number') {\n actorScope.system.scheduler.schedule(\n actorScope.self,\n to,\n event,\n delay,\n id\n );\n return;\n }\n actorScope.system._relay(\n actorScope.self,\n // at this point, in a deferred task, it should already be mutated by retryResolveSendTo\n // if it initially started as a string\n to,\n event.type === XSTATE_ERROR\n ? createErrorActorEvent(actorScope.self.id, (event as any).data)\n : event\n );\n });\n}\n\nexport interface SendToAction<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject,\n TDelay extends string\n> {\n (args: ActionArgs<TContext, TExpressionEvent, TEvent>, params: TParams): void;\n _out_TDelay?: TDelay;\n}\n\n/**\n * Sends an event to an actor.\n *\n * @param actor The `ActorRef` to send the event to.\n * @param event The event to send, or an expression that evaluates to the event\n * to send\n * @param options Send action options\n *\n * - `id` - The unique send event identifier (used with `cancel()`).\n * - `delay` - The number of milliseconds to delay the sending of the event.\n */\nexport function sendTo<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TTargetActor extends AnyActorRef,\n TEvent extends EventObject,\n TDelay extends string = never,\n TUsedDelay extends TDelay = never\n>(\n to:\n | TTargetActor\n | string\n | ((\n args: ActionArgs<TContext, TExpressionEvent, TEvent>,\n params: TParams\n ) => TTargetActor | string),\n eventOrExpr:\n | EventFrom<TTargetActor>\n | SendExpr<\n TContext,\n TExpressionEvent,\n TParams,\n InferEvent<Cast<EventFrom<TTargetActor>, EventObject>>,\n TEvent\n >,\n options?: SendToActionOptions<\n TContext,\n TExpressionEvent,\n TParams,\n DoNotInfer<TEvent>,\n TUsedDelay\n >\n): ActionFunction<\n TContext,\n TExpressionEvent,\n TEvent,\n TParams,\n never,\n never,\n never,\n TDelay,\n never\n> {\n if (isDevelopment && executingCustomAction) {\n console.warn(\n 'Custom actions should not call `sendTo()` directly, as it is not imperative. See https://stately.ai/docs/actions#built-in-actions for more details.'\n );\n }\n\n function sendTo(\n _args: ActionArgs<TContext, TExpressionEvent, TEvent>,\n _params: TParams\n ) {\n if (isDevelopment) {\n throw new Error(`This isn't supposed to be called`);\n }\n }\n\n sendTo.type = 'xstate.sendTo';\n sendTo.to = to;\n sendTo.event = eventOrExpr;\n sendTo.id = options?.id;\n sendTo.delay = options?.delay;\n\n sendTo.resolve = resolveSendTo;\n sendTo.retryResolve = retryResolveSendTo;\n sendTo.execute = executeSendTo;\n\n return sendTo;\n}\n\n/**\n * Sends an event to this machine's parent.\n *\n * @param event The event to send to the parent machine.\n * @param options Options to pass into the send event.\n */\nexport function sendParent<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TSentEvent extends EventObject = AnyEventObject,\n TEvent extends EventObject = AnyEventObject,\n TDelay extends string = never,\n TUsedDelay extends TDelay = never\n>(\n event:\n | TSentEvent\n | SendExpr<TContext, TExpressionEvent, TParams, TSentEvent, TEvent>,\n options?: SendToActionOptions<\n TContext,\n TExpressionEvent,\n TParams,\n TEvent,\n TUsedDelay\n >\n) {\n return sendTo<\n TContext,\n TExpressionEvent,\n TParams,\n AnyActorRef,\n TEvent,\n TDelay,\n TUsedDelay\n >(SpecialTargets.Parent, event, options as any);\n}\n\ntype Target<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject\n> =\n | string\n | AnyActorRef\n | ((\n args: ActionArgs<TContext, TExpressionEvent, TEvent>,\n params: TParams\n ) => string | AnyActorRef);\n\n/**\n * Forwards (sends) an event to the `target` actor.\n *\n * @param target The target actor to forward the event to.\n * @param options Options to pass into the send action creator.\n */\nexport function forwardTo<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject,\n TDelay extends string = never,\n TUsedDelay extends TDelay = never\n>(\n target: Target<TContext, TExpressionEvent, TParams, TEvent>,\n options?: SendToActionOptions<\n TContext,\n TExpressionEvent,\n TParams,\n TEvent,\n TUsedDelay\n >\n) {\n if (isDevelopment && (!target || typeof target === 'function')) {\n const originalTarget = target;\n target = (...args) => {\n const resolvedTarget =\n typeof originalTarget === 'function'\n ? originalTarget(...args)\n : originalTarget;\n if (!resolvedTarget) {\n throw new Error(\n `Attempted to forward event to undefined actor. This risks an infinite loop in the sender.`\n );\n }\n return resolvedTarget;\n };\n }\n return sendTo<\n TContext,\n TExpressionEvent,\n TParams,\n AnyActorRef,\n TEvent,\n TDelay,\n TUsedDelay\n >(target, ({ event }: any) => event, options);\n}\n\nexport interface ExecutableSendToAction extends ExecutableActionObject {\n type: 'xstate.sendTo';\n params: {\n event: EventObject;\n id: string | undefined;\n delay: number | undefined;\n to: AnyActorRef;\n };\n}\n","import isDevelopment from '#is-development';\nimport { Guard, evaluateGuard } from '../guards.ts';\nimport {\n Action,\n ActionArgs,\n ActionFunction,\n AnyActorRef,\n AnyActorScope,\n AnyEventObject,\n AnyMachineSnapshot,\n EventObject,\n MachineContext,\n ParameterizedObject,\n ProvidedActor,\n BuiltinActionResolution,\n UnifiedArg\n} from '../types.ts';\nimport { assign } from './assign.ts';\nimport { cancel } from './cancel.ts';\nimport { emit } from './emit.ts';\nimport { raise } from './raise.ts';\nimport { sendParent, sendTo } from './send.ts';\nimport { spawnChild } from './spawnChild.ts';\nimport { stopChild } from './stopChild.ts';\n\ninterface ActionEnqueuer<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TEvent extends EventObject,\n TActor extends ProvidedActor,\n TAction extends ParameterizedObject,\n TGuard extends ParameterizedObject,\n TDelay extends string,\n TEmitted extends EventObject\n> {\n (\n action: Action<\n TContext,\n TExpressionEvent,\n TEvent,\n undefined,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted\n >\n ): void;\n assign: (\n ...args: Parameters<\n typeof assign<TContext, TExpressionEvent, undefined, TEvent, TActor>\n >\n ) => void;\n cancel: (\n ...args: Parameters<\n typeof cancel<TContext, TExpressionEvent, undefined, TEvent>\n >\n ) => void;\n raise: (\n ...args: Parameters<\n typeof raise<\n TContext,\n TExpressionEvent,\n TEvent,\n undefined,\n TDelay,\n TDelay\n >\n >\n ) => void;\n sendTo: <TTargetActor extends AnyActorRef>(\n ...args: Parameters<\n typeof sendTo<\n TContext,\n TExpressionEvent,\n undefined,\n TTargetActor,\n TEvent,\n TDelay,\n TDelay\n >\n >\n ) => void;\n sendParent: (\n ...args: Parameters<\n typeof sendParent<\n TContext,\n TExpressionEvent,\n undefined,\n AnyEventObject,\n TEvent,\n TDelay,\n TDelay\n >\n >\n ) => void;\n spawnChild: (\n ...args: Parameters<\n typeof spawnChild<TContext, TExpressionEvent, undefined, TEvent, TActor>\n >\n ) => void;\n stopChild: (\n ...args: Parameters<\n typeof stopChild<TContext, TExpressionEvent, undefined, TEvent>\n >\n ) => void;\n emit: (\n ...args: Parameters<\n typeof emit<TContext, TExpressionEvent, undefined, TEvent, TEmitted>\n >\n ) => void;\n}\n\nfunction resolveEnqueueActions(\n actorScope: AnyActorScope,\n snapshot: AnyMachineSnapshot,\n args: ActionArgs<any, any, any>,\n actionParams: ParameterizedObject['params'] | undefined,\n {\n collect\n }: {\n collect: CollectActions<\n MachineContext,\n EventObject,\n ParameterizedObject['params'] | undefined,\n EventObject,\n ProvidedActor,\n ParameterizedObject,\n ParameterizedObject,\n string,\n EventObject\n >;\n }\n): BuiltinActionResolution {\n const actions: any[] = [];\n const enqueue: Parameters<typeof collect>[0]['enqueue'] = function enqueue(\n action\n ) {\n actions.push(action);\n };\n enqueue.assign = (...args) => {\n actions.push(assign(...args));\n };\n enqueue.cancel = (...args) => {\n actions.push(cancel(...args));\n };\n enqueue.raise = (...args) => {\n // for some reason it fails to infer `TDelay` from `...args` here and picks its default (`never`)\n // then it fails to typecheck that because `...args` use `string` in place of `TDelay`\n actions.push((raise as typeof enqueue.raise)(...args));\n };\n enqueue.sendTo = (...args) => {\n // for some reason it fails to infer `TDelay` from `...args` here and picks its default (`never`)\n // then it fails to typecheck that because `...args` use `string` in place of `TDelay\n actions.push((sendTo as typeof enqueue.sendTo)(...args));\n };\n enqueue.sendParent = (...args) => {\n actions.push((sendParent as typeof enqueue.sendParent)(...args));\n };\n enqueue.spawnChild = (...args) => {\n actions.push(spawnChild(...args));\n };\n enqueue.stopChild = (...args) => {\n actions.push(stopChild(...args));\n };\n enqueue.emit = (...args) => {\n actions.push(emit(...args));\n };\n\n collect(\n {\n context: args.context,\n event: args.event,\n enqueue,\n check: (guard) =>\n evaluateGuard(guard, snapshot.context, args.event, snapshot),\n self: actorScope.self,\n system: actorScope.system\n },\n actionParams\n );\n\n return [snapshot, undefined, actions];\n}\n\nexport interface EnqueueActionsAction<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject,\n TActor extends ProvidedActor,\n TAction extends ParameterizedObject,\n TGuard extends ParameterizedObject,\n TDelay extends string\n> {\n (args: ActionArgs<TContext, TExpressionEvent, TEvent>, params: TParams): void;\n _out_TEvent?: TEvent;\n _out_TActor?: TActor;\n _out_TAction?: TAction;\n _out_TGuard?: TGuard;\n _out_TDelay?: TDelay;\n}\n\ninterface CollectActionsArg<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TEvent extends EventObject,\n TActor extends ProvidedActor,\n TAction extends ParameterizedObject,\n TGuard extends ParameterizedObject,\n TDelay extends string,\n TEmitted extends EventObject\n> extends UnifiedArg<TContext, TExpressionEvent, TEvent> {\n check: (\n guard: Guard<TContext, TExpressionEvent, undefined, TGuard>\n ) => boolean;\n enqueue: ActionEnqueuer<\n TContext,\n TExpressionEvent,\n TEvent,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted\n >;\n}\n\ntype CollectActions<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject,\n TActor extends ProvidedActor,\n TAction extends ParameterizedObject,\n TGuard extends ParameterizedObject,\n TDelay extends string,\n TEmitted extends EventObject\n> = (\n {\n context,\n event,\n check,\n enqueue,\n self\n }: CollectActionsArg<\n TContext,\n TExpressionEvent,\n TEvent,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted\n >,\n params: TParams\n) => void;\n\n/**\n * Creates an action object that will execute actions that are queued by the\n * `enqueue(action)` function.\n *\n * @example\n *\n * ```ts\n * import { createMachine, enqueueActions } from 'xstate';\n *\n * const machine = createMachine({\n * entry: enqueueActions(({ enqueue, check }) => {\n * enqueue.assign({ count: 0 });\n *\n * if (check('someGuard')) {\n * enqueue.assign({ count: 1 });\n * }\n *\n * enqueue('someAction');\n * })\n * });\n * ```\n */\nexport function enqueueActions<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject = TExpressionEvent,\n TActor extends ProvidedActor = ProvidedActor,\n TAction extends ParameterizedObject = ParameterizedObject,\n TGuard extends ParameterizedObject = ParameterizedObject,\n TDelay extends string = never,\n TEmitted extends EventObject = EventObject\n>(\n collect: CollectActions<\n TContext,\n TExpressionEvent,\n TParams,\n TEvent,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted\n >\n): ActionFunction<\n TContext,\n TExpressionEvent,\n TEvent,\n TParams,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted\n> {\n function enqueueActions(\n _args: ActionArgs<TContext, TExpressionEvent, TEvent>,\n _params: unknown\n ) {\n if (isDevelopment) {\n throw new Error(`This isn't supposed to be called`);\n }\n }\n\n enqueueActions.type = 'xstate.enqueueActions';\n enqueueActions.collect = collect;\n enqueueActions.resolve = resolveEnqueueActions;\n\n return enqueueActions;\n}\n","import isDevelopment from '#is-development';\nimport {\n ActionArgs,\n AnyActorScope,\n AnyMachineSnapshot,\n EventObject,\n LogExpr,\n MachineContext,\n ParameterizedObject,\n BuiltinActionResolution\n} from '../types.ts';\n\ntype ResolvableLogValue<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject\n> = string | LogExpr<TContext, TExpressionEvent, TParams, TEvent>;\n\nfunction resolveLog(\n _: AnyActorScope,\n snapshot: AnyMachineSnapshot,\n actionArgs: ActionArgs<any, any, any>,\n actionParams: ParameterizedObject['params'] | undefined,\n {\n value,\n label\n }: {\n value: ResolvableLogValue<any, any, any, any>;\n label: string | undefined;\n }\n): BuiltinActionResolution {\n return [\n snapshot,\n {\n value:\n typeof value === 'function' ? value(actionArgs, actionParams) : value,\n label\n },\n undefined\n ];\n}\n\nfunction executeLog(\n { logger }: AnyActorScope,\n { value, label }: { value: unknown; label: string | undefined }\n) {\n if (label) {\n logger(label, value);\n } else {\n logger(value);\n }\n}\n\nexport interface LogAction<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject\n> {\n (args: ActionArgs<TContext, TExpressionEvent, TEvent>, params: TParams): void;\n}\n\n/**\n * @param expr The expression function to evaluate which will be logged. Takes\n * in 2 arguments:\n *\n * - `ctx` - the current state context\n * - `event` - the event that caused this action to be executed.\n *\n * @param label The label to give to the logged expression.\n */\nexport function log<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject\n>(\n value: ResolvableLogValue<TContext, TExpressionEvent, TParams, TEvent> = ({\n context,\n event\n }) => ({ context, event }),\n label?: string\n): LogAction<TContext, TExpressionEvent, TParams, TEvent> {\n function log(\n _args: ActionArgs<TContext, TExpressionEvent, TEvent>,\n _params: TParams\n ) {\n if (isDevelopment) {\n throw new Error(`This isn't supposed to be called`);\n }\n }\n\n log.type = 'xstate.log';\n log.value = value;\n log.label = label;\n\n log.resolve = resolveLog;\n log.execute = executeLog;\n\n return log;\n}\n"],"names":["Mailbox","constructor","_process","this","_active","_current","_last","start","flush","clear","next","enqueue","event","enqueued","value","consumed","XSTATE_STOP","getDevTools","w","globalThis","self","window","__xstate__","devToolsAdapter","service","devTools","register","createErrorActorEvent","id","error","type","actorId","reportUnhandledError","err","setTimeout","symbolObservable","Symbol","observable","matchesState","parentStateId","childStateId","parentStateValue","toStateValue","childStateValue","Object","keys","every","key","toStatePath","stateId","Array","isArray","result","segment","i","length","charCodeAt","push","stateValue","statePath","marker","previous","pathToStateValue","toObserver","nextHandler","errorHandler","completionHandler","isObserver","undefined","bind","complete","resolveReferencedActor","machine","src","match","implementations","actors","indexStr","nodeId","invokeConfig","getStateNodeById","config","invoke","createScheduledEventId","actorRef","sessionId","idCounter","executingCustomAction","ProcessingStatus","defaultOptions","clock","fn","ms","clearTimeout","logger","console","log","Actor","logic","options","_snapshot","mailbox","observers","Set","eventListeners","Map","_processingStatus","NotStarted","_parent","_syncSnapshot","ref","_actorScope","_systemId","system","_doneEvent","_deferred","resolvedOptions","parent","syncSnapshot","systemId","inspect","rootActor","children","keyedActors","reverseKeyedActors","WeakMap","inspectionObservers","timerMap","scheduler","schedule","source","target","delay","Math","random","toString","slice","scheduledEvent","startedAt","Date","now","scheduledEventId","_scheduledEvents","timeout","_relay","cancel","cancelAll","snapshot","_bookId","_register","set","_unregister","delete","get","_set","existing","Error","observerOrFn","observer","add","unsubscribe","_sendInspectionEvent","size","resolvedInspectionEvent","rootId","forEach","sourceRef","_send","getSnapshot","scheduledEvents","scheduledId","_clock","_logger","createSystem","defer","stopChild","child","_stop","emit","emittedEvent","listeners","wildcardListener","allListeners","values","handler","actionExecutor","action","exec","params","saveExecutingCustomAction","info","Running","send","_initState","state","status","persistedState","restoreSnapshot","getInitialSnapshot","input","output","update","deferredFn","shift","_stopProcedure","_complete","invokeId","_error","subscribe","nextListenerOrObserver","errorListener","completeListener","Stopped","on","wrappedHandler","initEvent","attachDevTools","nextState","caughtError","transition","stop","_reportError","reportError","err2","toJSON","xstate$$type","getPersistedSnapshot","createActor","resolveCancel","_","actionArgs","actionParams","sendId","executeCancel","actorScope","_args","_params","resolve","execute","resolveSpawn","_actionParams","resolvedId","resolvedInput","context","cloneMachineSnapshot","executeSpawn","spawnChild","resolveStop","args","actorRefOrString","resolvedActorRef","executeStop","evaluateGuard","guard","isInline","resolved","guards","guardArgs","guardParams","check","isAtomicStateNode","stateNode","getChildren","states","filter","sn","getProperAncestors","toStateNode","ancestors","m","getValueFromAdj","baseNode","adjList","childStateNodes","childStateNode","getAdjList","stateNodes","s","has","getStateValue","rootNode","nodeSet","initialStates","getInitialStateNodesWithTheirAncestors","initialStateNode","getAllStateNodes","iter","descStateNode","initial","getInitialStateNodes","initialState","ancestor","machineSnapshotMatches","testValue","machineSnapshotHasTag","tag","tags","machineSnapshotCan","transitionData","getTransitionData","some","t","actions","machineSnapshotToJSON","_nodes","nodes","getMeta","can","hasTag","matches","jsonValues","from","machineSnapshotGetMeta","reduce","acc","meta","root","flatMap","historyValue","createMachineSnapshot","createSpawner","spawnedChildren","spawn","resolveAssign","assignment","assignArgs","partialUpdate","propAssignment","assign","resolveEmit","eventOrExpr","executeEmit","resolveRaise","internalQueue","delaysMap","delays","resolvedEvent","resolvedDelay","configDelay","executeRaise","raise","SpecialTargets","resolveSendTo","to","extra","resolvedTarget","targetActorRef","Parent","Internal","startsWith","deferredActorIds","includes","targetId","retryResolveSendTo","executeSendTo","data","sendTo","retryResolve","sendParent","resolveEnqueueActions","collect","resolveLog","label","executeLog","enqueueActions"],"mappings":"qPAKO,MAAMA,EAKXC,WAAAA,CAAoBC,GAA2BC,KAA3BD,SAAAA,EAAyBC,KAJrCC,SAAmB,EAAKD,KACxBE,SAAkC,KAAIF,KACtCG,MAA+B,IAES,CAEzCC,KAAAA,GACLJ,KAAKC,SAAU,EACfD,KAAKK,OACP,CAEOC,KAAAA,GAGDN,KAAKE,WACPF,KAAKE,SAASK,KAAO,KACrBP,KAAKG,MAAQH,KAAKE,SAEtB,CAEOM,OAAAA,CAAQC,GACb,MAAMC,EAAW,CACfC,MAAOF,EACPF,KAAM,MAGR,GAAIP,KAAKE,SAGP,OAFAF,KAAKG,MAAOI,KAAOG,OACnBV,KAAKG,MAAQO,GAIfV,KAAKE,SAAWQ,EAChBV,KAAKG,MAAQO,EAETV,KAAKC,SACPD,KAAKK,OAET,CAEQA,KAAAA,GACN,KAAOL,KAAKE,UAAU,CAGpB,MAAMU,EAAWZ,KAAKE,SACtBF,KAAKD,SAASa,EAASD,OACvBX,KAAKE,SAAWU,EAASL,IAC3B,CACAP,KAAKG,MAAQ,IACf,EClDK,MAEMU,EAAc,cCiC3B,SAASC,IACP,MAAMC,EApBoB,oBAAfC,WACFA,WAEW,oBAATC,KACFA,KAGAC,OAcT,GAAKH,EAAUI,W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AEuO,UAASvO,UAClB8V,GAEA,SAAS1Q,EACP2I,EACAC,GAKF,CASA,OAPA5I,EAAIlE,KAAO,aACXkE,EAAIlF,MAAQA,EACZkF,EAAI0Q,MAAQA,EAEZ1Q,EAAI6I,QAAU4H,GACdzQ,EAAI8I,QAAU6H,GAEP3Q,CACT"}
|
|
1
|
+
{"version":3,"file":"xstate-actions.umd.min.js","sources":["../../src/Mailbox.ts","../../src/constants.ts","../../src/dev/index.ts","../../src/eventUtils.ts","../../src/reportUnhandledError.ts","../../src/symbolObservable.ts","../../src/utils.ts","../../src/State.ts","../../src/system.ts","../../src/createActor.ts","../../src/actions/cancel.ts","../../src/actions/spawnChild.ts","../../src/actions/stopChild.ts","../../src/guards.ts","../../src/stateUtils.ts","../../src/spawn.ts","../../src/actions/assign.ts","../../src/actions/emit.ts","../../src/actions/raise.ts","../../src/types.ts","../../src/actions/send.ts","../../src/actions/enqueueActions.ts","../../src/actions/log.ts"],"sourcesContent":["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","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_ERROR = 'xstate.error';\nexport const XSTATE_STOP = 'xstate.stop';\n","import isDevelopment from '#is-development';\nimport { AnyActor, DevToolsAdapter } from '../types.ts';\n\ninterface DevInterface {\n services: Set<AnyActor>;\n register(service: AnyActor): void;\n onRegister(listener: ServiceListener): void;\n}\ntype ServiceListener = (service: AnyActor) => void;\n\nexport interface XStateDevInterface {\n register: (service: AnyActor) => void;\n unregister: (service: AnyActor) => void;\n onRegister: (listener: ServiceListener) => {\n unsubscribe: () => void;\n };\n services: Set<AnyActor>;\n}\n\n// From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis\nexport function getGlobal(): typeof globalThis | undefined {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n }\n if (typeof self !== 'undefined') {\n return self;\n }\n if (typeof window !== 'undefined') {\n return window;\n }\n if (typeof global !== 'undefined') {\n return global;\n }\n if (isDevelopment) {\n console.warn(\n 'XState could not find a global object in this environment. Please let the maintainers know and raise an issue here: https://github.com/statelyai/xstate/issues'\n );\n }\n}\n\nfunction getDevTools(): DevInterface | undefined {\n const w = getGlobal();\n if ((w as any).__xstate__) {\n return (w as any).__xstate__;\n }\n\n return undefined;\n}\n\nexport function registerService(service: AnyActor) {\n if (typeof window === 'undefined') {\n return;\n }\n\n const devTools = getDevTools();\n\n if (devTools) {\n devTools.register(service);\n }\n}\n\nexport const devToolsAdapter: DevToolsAdapter = (service) => {\n if (typeof window === 'undefined') {\n return;\n }\n\n const devTools = getDevTools();\n\n if (devTools) {\n devTools.register(service);\n }\n};\n","import { XSTATE_INIT } from './constants.ts';\nimport { DoneActorEvent, DoneStateEvent, ErrorActorEvent } 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(delayRef: number | string, id: string) {\n return { type: `xstate.after.${delayRef}.${id}` } as const;\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.${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 */\nexport function createDoneActorEvent(\n invokeId: string,\n output?: unknown\n): DoneActorEvent {\n return {\n type: `xstate.done.actor.${invokeId}`,\n output,\n actorId: invokeId\n };\n}\n\nexport function createErrorActorEvent(\n id: string,\n error?: unknown\n): ErrorActorEvent {\n return { type: `xstate.error.actor.${id}`, error, actorId: id };\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 isDevelopment from '#is-development';\nimport { isMachineSnapshot } from './State.ts';\nimport type { StateNode } from './StateNode.ts';\nimport { TARGETLESS_KEY } from './constants.ts';\nimport type {\n AnyActorRef,\n AnyEventObject,\n AnyMachineSnapshot,\n AnyStateMachine,\n AnyTransitionConfig,\n ErrorActorEvent,\n EventObject,\n InvokeConfig,\n MachineContext,\n Mapper,\n NonReducibleUnknown,\n Observer,\n SingleOrArray,\n StateLike,\n StateValue,\n TransitionConfigTarget\n} from './types.ts';\n\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\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 // consume the next character\n segment += 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\nexport function 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 result[key] = iteratee(collection[key], key, collection, i);\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: AnyActorRef\n): unknown {\n if (typeof mapper === 'function') {\n return mapper({ context, event, self });\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\nfunction isArray(value: any): value is readonly any[] {\n return Array.isArray(value);\n}\n\nexport function isErrorActorEvent(\n event: AnyEventObject\n): event is ErrorActorEvent {\n return event.type.startsWith('xstate.error.actor');\n}\n\nexport function toTransitionConfigArray(\n configLike: SingleOrArray<AnyTransitionConfig | TransitionConfigTarget>\n): Array<AnyTransitionConfig> {\n return toArrayStrict(configLike).map((transitionLike) => {\n if (\n typeof transitionLike === 'undefined' ||\n typeof transitionLike === 'string'\n ) {\n return { target: 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\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 };\n}\n\nexport function createInvokeId(stateNodeId: string, index: number): string {\n return `${index}.${stateNodeId}`;\n}\n\nexport function resolveReferencedActor(machine: AnyStateMachine, src: string) {\n const match = src.match(/^xstate\\.invoke\\.(\\d+)\\.(.*)/)!;\n if (!match) {\n return machine.implementations.actors[src];\n }\n const [, indexStr, nodeId] = match;\n const node = machine.getStateNodeById(nodeId);\n const invokeConfig = node.config.invoke!;\n return (\n Array.isArray(invokeConfig)\n ? invokeConfig[indexStr as any]\n : (invokeConfig as InvokeConfig<\n any,\n any,\n any,\n any,\n any,\n any,\n any, // TEmitted\n any // TMeta\n >)\n ).src;\n}\n\nexport function getAllOwnEventDescriptors(snapshot: AnyMachineSnapshot) {\n return [...new Set([...snapshot._nodes.flatMap((sn) => sn.ownEvents)])];\n}\n","import isDevelopment from '#is-development';\nimport { $$ACTOR_TYPE } from './createActor.ts';\nimport type { StateNode } from './StateNode.ts';\nimport type { StateMachine } from './StateMachine.ts';\nimport { getStateValue } from './stateUtils.ts';\nimport type {\n ProvidedActor,\n AnyMachineSnapshot,\n AnyStateMachine,\n EventObject,\n HistoryValue,\n MachineContext,\n StateConfig,\n StateValue,\n AnyActorRef,\n Snapshot,\n ParameterizedObject,\n IsNever,\n MetaObject,\n StateSchema,\n StateId,\n SnapshotStatus,\n PersistedHistoryValue\n} from './types.ts';\nimport { matchesState } from './utils.ts';\n\ntype ToTestStateValue<TStateValue extends StateValue> =\n TStateValue extends string\n ? TStateValue\n : IsNever<keyof TStateValue> extends true\n ? never\n :\n | keyof TStateValue\n | {\n [K in keyof TStateValue]?: ToTestStateValue<\n NonNullable<TStateValue[K]>\n >;\n };\n\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\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,\n TStateSchema extends StateSchema = StateSchema\n> {\n /** The state machine that produced this state snapshot. */\n machine: StateMachine<\n TContext,\n TEvent,\n TChildren,\n ProvidedActor,\n ParameterizedObject,\n ParameterizedObject,\n string,\n TStateValue,\n TTag,\n unknown,\n TOutput,\n EventObject, // TEmitted\n any, // TMeta\n TStateSchema\n >;\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<TContext, TEvent>>;\n /** The enabled state nodes representative of the state value. */\n _nodes: Array<StateNode<TContext, TEvent>>;\n /** An object mapping actor names to spawned/invoked actors. */\n children: TChildren;\n\n /**\n * Whether the current state value is a subset of the given partial state\n * value.\n *\n * @param partialStateValue\n */\n matches: (partialStateValue: ToTestStateValue<TStateValue>) => 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 * @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 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 TConfig extends StateSchema\n> extends MachineSnapshotBase<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\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 TConfig extends StateSchema\n> extends MachineSnapshotBase<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\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 TConfig extends StateSchema\n> extends MachineSnapshotBase<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\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 TConfig extends StateSchema\n> extends MachineSnapshotBase<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n > {\n status: 'stopped';\n output: undefined;\n error: undefined;\n}\n\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 TConfig extends StateSchema\n> =\n | ActiveMachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >\n | DoneMachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >\n | ErrorMachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >\n | StoppedMachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >;\n\nconst machineSnapshotMatches = function matches(\n this: AnyMachineSnapshot,\n testValue: StateValue\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 const transitionData = this.machine.getTransitionData(this, event);\n\n return (\n !!transitionData?.length &&\n // Check that at least one transition is not forbidden\n transitionData.some((t) => t.target !== undefined || t.actions.length)\n );\n};\n\nconst machineSnapshotToJSON = function toJSON(this: AnyMachineSnapshot) {\n const {\n _nodes: nodes,\n tags,\n machine,\n getMeta,\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 return this._nodes.reduce(\n (acc, stateNode) => {\n if (stateNode.meta !== undefined) {\n acc[stateNode.id] = stateNode.meta;\n }\n return acc;\n },\n {} as Record<string, any>\n );\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): MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n undefined,\n TMeta,\n TStateSchema\n> {\n return {\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: getStateValue(machine.root, config._nodes) as never,\n tags: new Set(config._nodes.flatMap((sn) => sn.tags)),\n children: config.children as any,\n historyValue: config.historyValue || {},\n matches: machineSnapshotMatches as never,\n hasTag: machineSnapshotHasTag,\n can: machineSnapshotCan,\n getMeta: machineSnapshotGetMeta,\n toJSON: machineSnapshotToJSON\n };\n}\n\nexport function cloneMachineSnapshot<TState extends AnyMachineSnapshot>(\n snapshot: TState,\n config: Partial<StateConfig<any, any>> = {}\n): TState {\n return createMachineSnapshot(\n { ...snapshot, ...config } as StateConfig<any, any>,\n snapshot.machine\n ) as TState;\n}\n\nfunction serializeHistoryValue<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(historyValue: HistoryValue<TContext, TEvent>): PersistedHistoryValue {\n if (typeof historyValue !== 'object' || historyValue === null) {\n return {};\n }\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: nodes,\n tags,\n machine,\n children,\n context,\n can,\n hasTag,\n matches,\n getMeta,\n toJSON,\n ...jsonValues\n } = snapshot;\n\n const childrenJson: Record<string, unknown> = {};\n\n for (const id in children) {\n const child = children[id] as any;\n if (\n isDevelopment &&\n typeof child.src !== 'string' &&\n (!options || !('__unsafeAllowInlineActors' in (options as object)))\n ) {\n throw new Error('An inline child actor cannot be persisted.');\n }\n childrenJson[id as keyof typeof childrenJson] = {\n snapshot: child.getPersistedSnapshot(options),\n src: child.src,\n systemId: child._systemId,\n syncSnapshot: child._syncSnapshot\n };\n }\n\n const persisted = {\n ...jsonValues,\n context: persistContext(context) as any,\n children: childrenJson,\n historyValue: serializeHistoryValue<TContext, TEvent>(\n jsonValues.historyValue\n )\n };\n\n return persisted;\n}\n\nfunction persistContext(contextPart: Record<string, unknown>) {\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 ('sessionId' in value && 'send' in value && 'ref' in value) {\n copy ??= Array.isArray(contextPart)\n ? (contextPart.slice() as typeof contextPart)\n : { ...contextPart };\n copy[key] = {\n xstate$$type: $$ACTOR_TYPE,\n id: (value as any as AnyActorRef).id\n };\n } else {\n const result = persistContext(value as typeof contextPart);\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 return copy ?? contextPart;\n}\n","import { InspectionEvent } from './inspection.ts';\nimport {\n AnyEventObject,\n ActorSystemInfo,\n AnyActorRef,\n Observer,\n HomomorphicOmit,\n EventObject,\n Subscription\n} from './types.ts';\nimport { toObserver } from './utils.ts';\n\ninterface ScheduledEvent {\n id: string;\n event: EventObject;\n startedAt: number; // timestamp\n delay: number;\n source: AnyActorRef;\n target: AnyActorRef;\n}\n\nexport interface Clock {\n setTimeout(fn: (...args: any[]) => void, timeout: number): any;\n clearTimeout(id: any): void;\n}\n\ninterface Scheduler {\n schedule(\n source: AnyActorRef,\n target: AnyActorRef,\n event: EventObject,\n delay: number,\n id: string | undefined\n ): void;\n cancel(source: AnyActorRef, id: string): void;\n cancelAll(actorRef: AnyActorRef): void;\n}\n\ntype ScheduledEventId = string & { __scheduledEventId: never };\n\nfunction createScheduledEventId(\n actorRef: AnyActorRef,\n id: string\n): ScheduledEventId {\n return `${actorRef.sessionId}.${id}` as ScheduledEventId;\n}\n\nexport interface ActorSystem<T extends ActorSystemInfo> {\n /** @internal */\n _bookId: () => string;\n /** @internal */\n _register: (sessionId: string, actorRef: AnyActorRef) => string;\n /** @internal */\n _unregister: (actorRef: AnyActorRef) => void;\n /** @internal */\n _set: <K extends keyof T['actors']>(key: K, actorRef: T['actors'][K]) => void;\n get: <K extends keyof T['actors']>(key: K) => T['actors'][K] | undefined;\n\n inspect: (\n observer:\n | Observer<InspectionEvent>\n | ((inspectionEvent: InspectionEvent) => void)\n ) => Subscription;\n /** @internal */\n _sendInspectionEvent: (\n event: HomomorphicOmit<InspectionEvent, 'rootId'>\n ) => void;\n /** @internal */\n _relay: (\n source: AnyActorRef | undefined,\n target: AnyActorRef,\n event: AnyEventObject\n ) => void;\n scheduler: Scheduler;\n getSnapshot: () => {\n _scheduledEvents: Record<string, ScheduledEvent>;\n };\n /** @internal */\n _snapshot: {\n _scheduledEvents: Record<ScheduledEventId, ScheduledEvent>;\n };\n start: () => void;\n _clock: Clock;\n _logger: (...args: any[]) => void;\n}\n\nexport type AnyActorSystem = ActorSystem<any>;\n\nlet idCounter = 0;\nexport function createSystem<T extends ActorSystemInfo>(\n rootActor: AnyActorRef,\n options: {\n clock: Clock;\n logger: (...args: any[]) => void;\n snapshot?: unknown;\n }\n): ActorSystem<T> {\n const children = new Map<string, AnyActorRef>();\n const keyedActors = new Map<keyof T['actors'], AnyActorRef | undefined>();\n const reverseKeyedActors = new WeakMap<AnyActorRef, keyof T['actors']>();\n const inspectionObservers = new Set<Observer<InspectionEvent>>();\n const timerMap: { [id: ScheduledEventId]: number } = {};\n const { clock, logger } = options;\n\n const scheduler: Scheduler = {\n schedule: (\n source,\n target,\n event,\n delay,\n id = Math.random().toString(36).slice(2)\n ) => {\n const scheduledEvent: ScheduledEvent = {\n source,\n target,\n event,\n delay,\n id,\n startedAt: Date.now()\n };\n const scheduledEventId = createScheduledEventId(source, id);\n system._snapshot._scheduledEvents[scheduledEventId] = scheduledEvent;\n\n const timeout = clock.setTimeout(() => {\n delete timerMap[scheduledEventId];\n delete system._snapshot._scheduledEvents[scheduledEventId];\n\n system._relay(source, target, event);\n }, delay);\n\n timerMap[scheduledEventId] = timeout;\n },\n cancel: (source, id: string) => {\n const scheduledEventId = createScheduledEventId(source, id);\n const timeout = timerMap[scheduledEventId];\n\n delete timerMap[scheduledEventId];\n delete system._snapshot._scheduledEvents[scheduledEventId];\n\n if (timeout !== undefined) {\n clock.clearTimeout(timeout);\n }\n },\n cancelAll: (actorRef) => {\n for (const scheduledEventId in system._snapshot._scheduledEvents) {\n const scheduledEvent =\n system._snapshot._scheduledEvents[\n scheduledEventId as ScheduledEventId\n ];\n if (scheduledEvent.source === actorRef) {\n scheduler.cancel(actorRef, scheduledEvent.id);\n }\n }\n }\n };\n const sendInspectionEvent = (event: InspectionEvent) => {\n if (!inspectionObservers.size) {\n return;\n }\n const resolvedInspectionEvent: InspectionEvent = {\n ...event,\n rootId: rootActor.sessionId\n };\n inspectionObservers.forEach((observer) =>\n observer.next?.(resolvedInspectionEvent)\n );\n };\n\n const system: ActorSystem<T> = {\n _snapshot: {\n _scheduledEvents:\n (options?.snapshot && (options.snapshot as any).scheduler) ?? {}\n },\n _bookId: () => `x:${idCounter++}`,\n _register: (sessionId, actorRef) => {\n children.set(sessionId, actorRef);\n return sessionId;\n },\n _unregister: (actorRef) => {\n children.delete(actorRef.sessionId);\n const systemId = reverseKeyedActors.get(actorRef);\n\n if (systemId !== undefined) {\n keyedActors.delete(systemId);\n reverseKeyedActors.delete(actorRef);\n }\n },\n get: (systemId) => {\n return keyedActors.get(systemId) as T['actors'][any];\n },\n _set: (systemId, actorRef) => {\n const existing = keyedActors.get(systemId);\n if (existing && existing !== actorRef) {\n throw new Error(\n `Actor with system ID '${systemId as string}' already exists.`\n );\n }\n\n keyedActors.set(systemId, actorRef);\n reverseKeyedActors.set(actorRef, systemId);\n },\n inspect: (observerOrFn) => {\n const observer = toObserver(observerOrFn);\n inspectionObservers.add(observer);\n\n return {\n unsubscribe() {\n inspectionObservers.delete(observer);\n }\n };\n },\n _sendInspectionEvent: sendInspectionEvent as any,\n _relay: (source, target, event) => {\n system._sendInspectionEvent({\n type: '@xstate.event',\n sourceRef: source,\n actorRef: target,\n event\n });\n\n target._send(event);\n },\n scheduler,\n getSnapshot: () => {\n return {\n _scheduledEvents: { ...system._snapshot._scheduledEvents }\n };\n },\n start: () => {\n const scheduledEvents = system._snapshot._scheduledEvents;\n system._snapshot._scheduledEvents = {};\n for (const scheduledId in scheduledEvents) {\n const { source, target, event, delay, id } =\n scheduledEvents[scheduledId as ScheduledEventId];\n scheduler.schedule(source, target, event, delay, id);\n }\n },\n _clock: clock,\n _logger: logger\n };\n\n return system;\n}\n","import isDevelopment from '#is-development';\nimport { Mailbox } from './Mailbox.ts';\nimport { XSTATE_STOP } from './constants.ts';\nimport { devToolsAdapter } from './dev/index.ts';\nimport {\n createDoneActorEvent,\n createErrorActorEvent,\n createInitEvent\n} from './eventUtils.ts';\nimport { reportUnhandledError } from './reportUnhandledError.ts';\nimport { symbolObservable } from './symbolObservable.ts';\nimport { AnyActorSystem, Clock, createSystem } from './system.ts';\n\n// those are needed to make JSDoc `@link` work properly\nimport type {\n fromObservable,\n fromEventObservable\n} from './actors/observable.ts';\nimport type { fromCallback } from './actors/callback.ts';\nimport type { fromPromise } from './actors/promise.ts';\nimport type { fromTransition } from './actors/transition.ts';\nimport type { createMachine } from './createMachine.ts';\n\nexport let executingCustomAction: boolean = false;\n\nimport type {\n ActorScope,\n AnyActorLogic,\n AnyActorRef,\n ConditionalRequired,\n DoneActorEvent,\n EmittedFrom,\n EventFromLogic,\n InputFrom,\n IsNotNever,\n Snapshot,\n SnapshotFrom\n} from './types.ts';\nimport {\n ActorOptions,\n ActorRef,\n EventObject,\n InteropSubscribable,\n Observer,\n Subscription\n} from './types.ts';\nimport { toObserver } from './utils.ts';\n\nexport const $$ACTOR_TYPE = 1;\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 = {\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 devTools: false\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 */\nexport class Actor<TLogic extends AnyActorLogic>\n implements\n ActorRef<SnapshotFrom<TLogic>, EventFromLogic<TLogic>, EmittedFrom<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 mailbox: Mailbox<EventFromLogic<TLogic>> = new Mailbox(\n this._process.bind(this)\n );\n\n private observers: Set<Observer<SnapshotFrom<TLogic>>> = new Set();\n private eventListeners: Map<\n string,\n Set<(emittedEvent: EmittedFrom<TLogic>) => void>\n > = new Map();\n private logger: (...args: any[]) => void;\n\n /** @internal */\n public _processingStatus: ProcessingStatus = ProcessingStatus.NotStarted;\n\n // Actor Ref\n public _parent?: AnyActorRef;\n /** @internal */\n public _syncSnapshot?: boolean;\n public ref: ActorRef<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>,\n EmittedFrom<TLogic>\n >;\n // TODO: add typings for system\n private _actorScope: ActorScope<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>,\n AnyActorSystem,\n EmittedFrom<TLogic>\n >;\n\n private _systemId: string | undefined;\n\n /** The globally unique process ID for this invocation. */\n public sessionId: string;\n\n /** The system to which this actor belongs. */\n public system: AnyActorSystem;\n private _doneEvent?: DoneActorEvent;\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 ...defaultOptions,\n ...options\n };\n\n const { clock, logger, parent, syncSnapshot, id, systemId, inspect } =\n resolvedOptions;\n\n this.system = parent\n ? parent.system\n : createSystem(this, {\n clock,\n logger\n });\n\n if (inspect && !parent) {\n // Always inspect at the system-level\n this.system.inspect(toObserver(inspect));\n }\n\n this.sessionId = this.system._bookId();\n this.id = id ?? this.sessionId;\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 = {\n self: this,\n id: this.id,\n sessionId: this.sessionId,\n logger: this.logger,\n defer: (fn) => {\n this._deferred.push(fn);\n },\n system: this.system,\n stopChild: (child) => {\n if (child._parent !== this) {\n throw new Error(\n `Cannot stop child actor ${child.id} of ${this.id} because it is not a child`\n );\n }\n (child as any)._stop();\n },\n emit: (emittedEvent) => {\n const listeners = this.eventListeners.get(emittedEvent.type);\n const wildcardListener = this.eventListeners.get('*');\n if (!listeners && !wildcardListener) {\n return;\n }\n const allListeners = [\n ...(listeners ? listeners.values() : []),\n ...(wildcardListener ? wildcardListener.values() : [])\n ];\n for (const handler of allListeners) {\n try {\n handler(emittedEvent);\n } catch (err) {\n reportUnhandledError(err);\n }\n }\n },\n actionExecutor: (action) => {\n const exec = () => {\n this._actorScope.system._sendInspectionEvent({\n type: '@xstate.action',\n actorRef: this,\n action: {\n type: action.type,\n params: action.params\n }\n });\n if (!action.exec) {\n return;\n }\n const saveExecutingCustomAction = executingCustomAction;\n try {\n executingCustomAction = true;\n action.exec(action.info, action.params);\n } finally {\n executingCustomAction = saveExecutingCustomAction;\n }\n };\n if (this._processingStatus === ProcessingStatus.Running) {\n exec();\n } else {\n this._deferred.push(exec);\n }\n }\n };\n\n // Ensure that the send method is bound to this Actor instance\n // if destructured\n this.send = this.send.bind(this);\n\n this.system._sendInspectionEvent({\n type: '@xstate.actor',\n actorRef: this\n });\n\n if (systemId) {\n this._systemId = systemId;\n this.system._set(systemId, this);\n }\n\n this._initState(options?.snapshot ?? options?.state);\n\n if (systemId && (this._snapshot as any).status !== 'active') {\n this.system._unregister(this);\n }\n }\n\n private _initState(persistedState?: Snapshot<unknown>) {\n try {\n this._snapshot = persistedState\n ? this.logic.restoreSnapshot\n ? this.logic.restoreSnapshot(persistedState, this._actorScope)\n : persistedState\n : this.logic.getInitialSnapshot(this._actorScope, this.options?.input);\n } catch (err) {\n // if we get here then it means that we assign a value to this._snapshot that is not of the correct type\n // we can't get the true `TSnapshot & { status: 'error'; }`, it's impossible\n // so right now this is a lie of sorts\n this._snapshot = {\n status: 'error',\n output: undefined,\n error: err\n } as any;\n }\n }\n\n // array of functions to defer\n private _deferred: Array<() => void> = [];\n\n private update(snapshot: SnapshotFrom<TLogic>, event: EventObject): void {\n // Update state\n this._snapshot = snapshot;\n\n // Execute deferred effects\n let deferredFn: (typeof this._deferred)[number] | undefined;\n\n while ((deferredFn = this._deferred.shift())) {\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 this._deferred.length = 0;\n this._snapshot = {\n ...(snapshot as any),\n status: 'error',\n error: err\n };\n }\n }\n\n switch ((this._snapshot as any).status) {\n case 'active':\n for (const observer of this.observers) {\n try {\n observer.next?.(snapshot);\n } catch (err) {\n reportUnhandledError(err);\n }\n }\n break;\n case 'done':\n // next observers are meant to be notified about done snapshots\n // this can be seen as something that is different from how observable work\n // but with observables `complete` callback is called without any arguments\n // it's more ergonomic for XState to treat a done snapshot as a \"next\" value\n // and the completion event as something that is separate,\n // something that merely follows emitting that done snapshot\n for (const observer of this.observers) {\n try {\n observer.next?.(snapshot);\n } catch (err) {\n reportUnhandledError(err);\n }\n }\n\n this._stopProcedure();\n this._complete();\n this._doneEvent = createDoneActorEvent(\n this.id,\n (this._snapshot as any).output\n );\n if (this._parent) {\n this.system._relay(this, this._parent, this._doneEvent);\n }\n\n break;\n case 'error':\n this._error((this._snapshot as any).error);\n break;\n }\n this.system._sendInspectionEvent({\n type: '@xstate.snapshot',\n actorRef: this,\n event,\n snapshot\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.add(observer);\n } else {\n switch ((this._snapshot as any).status) {\n case 'done':\n try {\n observer.complete?.();\n } catch (err) {\n reportUnhandledError(err);\n }\n break;\n case 'error': {\n const err = (this._snapshot as any).error;\n if (!observer.error) {\n reportUnhandledError(err);\n } else {\n try {\n observer.error(err);\n } catch (err) {\n reportUnhandledError(err);\n }\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.set(type, listeners);\n }\n const wrappedHandler = handler.bind(undefined);\n listeners.add(wrappedHandler);\n\n return {\n unsubscribe: () => {\n listeners.delete(wrappedHandler);\n }\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._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.${this.id}`,\n snapshot\n });\n }\n },\n error: () => {}\n });\n }\n\n this.system._register(this.sessionId, this);\n if (this._systemId) {\n this.system._set(this._systemId, this);\n }\n this._processingStatus = ProcessingStatus.Running;\n\n // TODO: this isn't correct when rehydrating\n const initEvent = createInitEvent(this.options.input);\n\n this.system._sendInspectionEvent({\n type: '@xstate.event',\n sourceRef: this._parent,\n actorRef: this,\n event: initEvent\n });\n\n const status = (this._snapshot as any).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 this.update(\n this._snapshot,\n initEvent 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 any).error);\n return this;\n }\n\n if (!this._parent) {\n this.system.start();\n }\n\n if (this.logic.start) {\n try {\n this.logic.start(this._snapshot, this._actorScope);\n } catch (err) {\n this._snapshot = {\n ...(this._snapshot as any),\n status: 'error',\n error: err\n };\n this._error(err);\n return this;\n }\n }\n\n // TODO: this notifies all subscribers but usually this is redundant\n // there is no real change happening here\n // we need to rethink if this needs to be refactored\n this.update(this._snapshot, initEvent as unknown as EventFromLogic<TLogic>);\n\n if (this.options.devTools) {\n this.attachDevTools();\n }\n\n this.mailbox.start();\n\n return this;\n }\n\n private _process(event: EventFromLogic<TLogic>) {\n let nextState;\n let caughtError;\n try {\n nextState = this.logic.transition(\n this._snapshot,\n event,\n 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 const { err } = caughtError;\n\n this._snapshot = {\n ...(this._snapshot as any),\n status: 'error',\n error: err\n };\n this._error(err);\n return;\n }\n\n this.update(nextState, event);\n if (event.type === XSTATE_STOP) {\n this._stopProcedure();\n this._complete();\n }\n }\n\n private _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 return this;\n }\n this.mailbox.enqueue({ type: XSTATE_STOP } as any);\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('A non-root actor cannot be stopped directly.');\n }\n return this._stop();\n }\n private _complete(): void {\n for (const observer of this.observers) {\n try {\n observer.complete?.();\n } catch (err) {\n reportUnhandledError(err);\n }\n }\n this.observers.clear();\n }\n private _reportError(err: unknown): void {\n if (!this.observers.size) {\n if (!this._parent) {\n reportUnhandledError(err);\n }\n return;\n }\n let reportError = false;\n\n for (const observer of this.observers) {\n const errorListener = observer.error;\n reportError ||= !errorListener;\n try {\n errorListener?.(err);\n } catch (err2) {\n reportUnhandledError(err2);\n }\n }\n this.observers.clear();\n if (reportError) {\n reportUnhandledError(err);\n }\n }\n private _error(err: unknown): void {\n this._stopProcedure();\n this._reportError(err);\n if (this._parent) {\n this.system._relay(\n this,\n this._parent,\n createErrorActorEvent(this.id, err)\n );\n }\n }\n // TODO: atm children don't belong entirely to the actor so\n // in a way - it's not even super aware of them\n // so we can't stop them from here but we really should!\n // right now, they are being stopped within the machine's transition\n // but that could throw and leave us with \"orphaned\" active actors\n private _stopProcedure(): this {\n if (this._processingStatus !== ProcessingStatus.Running) {\n // Actor already stopped; do nothing\n return this;\n }\n\n // Cancel all delayed events\n this.system.scheduler.cancelAll(this);\n\n // TODO: mailbox.reset\n this.mailbox.clear();\n // TODO: after `stop` we must prepare ourselves for receiving events again\n // events sent *after* stop signal must be queued\n // it seems like this should be the common behavior for all of our consumers\n // so perhaps this should be unified somehow for all of them\n this.mailbox = new Mailbox(this._process.bind(this));\n\n this._processingStatus = ProcessingStatus.Stopped;\n this.system._unregister(this);\n\n return this;\n }\n\n /** @internal */\n public _send(event: EventFromLogic<TLogic>) {\n if (this._processingStatus === ProcessingStatus.Stopped) {\n // do nothing\n if (isDevelopment) {\n const eventString = JSON.stringify(event);\n\n console.warn(\n `Event \"${event.type}\" was sent to stopped actor \"${this.id} (${this.sessionId})\". This actor has already reached its final state, and will not transition.\\nEvent: ${eventString}`\n );\n }\n return;\n }\n\n this.mailbox.enqueue(event);\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 public send(event: EventFromLogic<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 private attachDevTools(): void {\n const { devTools } = this.options;\n if (devTools) {\n const resolvedDevToolsAdapter =\n typeof devTools === 'function' ? devTools : devToolsAdapter;\n\n resolvedDevToolsAdapter(this);\n }\n }\n public toJSON() {\n return {\n xstate$$type: $$ACTOR_TYPE,\n id: this.id\n };\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.state}\n * @see https://stately.ai/docs/persistence\n */\n public getPersistedSnapshot(): Snapshot<unknown>;\n public getPersistedSnapshot(options?: unknown): Snapshot<unknown> {\n return this.logic.getPersistedSnapshot(this._snapshot, options);\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 represent an actor's last emitted value.\n *\n * When an actor receives an event, its internal state may change. An actor\n * may emit a snapshot when a state transition occurs.\n *\n * Note that some actors, such as callback actors generated with\n * `fromCallback`, 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\nexport type RequiredActorOptionsKeys<TLogic extends AnyActorLogic> =\n undefined extends InputFrom<TLogic> ? never : 'input';\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 fromCallback}, {@link fromEventObservable},\n * {@link fromObservable}, {@link fromPromise}, and {@link fromTransition}.\n * @param options - Actor options\n */\nexport function createActor<TLogic extends AnyActorLogic>(\n logic: TLogic,\n ...[options]: ConditionalRequired<\n [\n options?: ActorOptions<TLogic> & {\n [K in RequiredActorOptionsKeys<TLogic>]: unknown;\n }\n ],\n IsNotNever<RequiredActorOptionsKeys<TLogic>>\n >\n): Actor<TLogic> {\n return new Actor(logic, options);\n}\n\n/**\n * Creates a new Interpreter instance for the given machine with the provided\n * options, if any.\n *\n * @deprecated Use `createActor` instead\n * @alias\n */\nexport const interpret = createActor;\n\n/**\n * @deprecated Use `Actor` instead.\n * @alias\n */\nexport type Interpreter = typeof Actor;\n","import isDevelopment from '#is-development';\nimport {\n AnyActorScope,\n AnyMachineSnapshot,\n EventObject,\n MachineContext,\n ActionArgs,\n ParameterizedObject,\n BuiltinActionResolution\n} from '../types.ts';\n\ntype ResolvableSendId<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject\n> =\n | string\n | ((\n args: ActionArgs<TContext, TExpressionEvent, TEvent>,\n params: TParams\n ) => string);\n\nfunction resolveCancel(\n _: AnyActorScope,\n snapshot: AnyMachineSnapshot,\n actionArgs: ActionArgs<any, any, any>,\n actionParams: ParameterizedObject['params'] | undefined,\n { sendId }: { sendId: ResolvableSendId<any, any, any, any> }\n): BuiltinActionResolution {\n const resolvedSendId =\n typeof sendId === 'function' ? sendId(actionArgs, actionParams) : sendId;\n return [snapshot, { sendId: resolvedSendId }, undefined];\n}\n\nfunction executeCancel(actorScope: AnyActorScope, params: { sendId: string }) {\n actorScope.defer(() => {\n actorScope.system.scheduler.cancel(actorScope.self, params.sendId);\n });\n}\n\nexport interface CancelAction<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject\n> {\n (args: ActionArgs<TContext, TExpressionEvent, TEvent>, params: TParams): void;\n}\n\n/**\n * Cancels a delayed `sendTo(...)` action that is waiting to be executed. The\n * canceled `sendTo(...)` action will not send its event or execute, unless the\n * `delay` has already elapsed before `cancel(...)` is called.\n *\n * @example\n *\n * ```ts\n * import { createMachine, sendTo, cancel } from 'xstate';\n *\n * const machine = createMachine({\n * // ...\n * on: {\n * sendEvent: {\n * actions: sendTo(\n * 'some-actor',\n * { type: 'someEvent' },\n * {\n * id: 'some-id',\n * delay: 1000\n * }\n * )\n * },\n * cancelEvent: {\n * actions: cancel('some-id')\n * }\n * }\n * });\n * ```\n *\n * @param sendId The `id` of the `sendTo(...)` action to cancel.\n */\nexport function cancel<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject\n>(\n sendId: ResolvableSendId<TContext, TExpressionEvent, TParams, TEvent>\n): CancelAction<TContext, TExpressionEvent, TParams, TEvent> {\n function cancel(\n _args: ActionArgs<TContext, TExpressionEvent, TEvent>,\n _params: TParams\n ) {\n if (isDevelopment) {\n throw new Error(`This isn't supposed to be called`);\n }\n }\n\n cancel.type = 'xstate.cancel';\n cancel.sendId = sendId;\n\n cancel.resolve = resolveCancel;\n cancel.execute = executeCancel;\n\n return cancel;\n}\n","import isDevelopment from '#is-development';\nimport { cloneMachineSnapshot } from '../State.ts';\nimport { ProcessingStatus, createActor } from '../createActor.ts';\nimport {\n ActionArgs,\n ActionFunction,\n AnyActorLogic,\n AnyActorRef,\n AnyActorScope,\n AnyMachineSnapshot,\n ConditionalRequired,\n EventObject,\n InputFrom,\n IsLiteralString,\n IsNotNever,\n MachineContext,\n Mapper,\n ParameterizedObject,\n ProvidedActor,\n RequiredActorOptions,\n BuiltinActionResolution,\n UnifiedArg\n} from '../types.ts';\nimport { resolveReferencedActor } from '../utils.ts';\n\ntype ResolvableActorId<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TEvent extends EventObject,\n TId extends string | undefined\n> = TId | ((args: UnifiedArg<TContext, TExpressionEvent, TEvent>) => TId);\n\nfunction resolveSpawn(\n actorScope: AnyActorScope,\n snapshot: AnyMachineSnapshot,\n actionArgs: ActionArgs<any, any, any>,\n _actionParams: ParameterizedObject['params'] | undefined,\n {\n id,\n systemId,\n src,\n input,\n syncSnapshot\n }: {\n id: ResolvableActorId<MachineContext, EventObject, EventObject, string>;\n systemId: string | undefined;\n src: AnyActorLogic | string;\n input?: unknown;\n syncSnapshot: boolean;\n }\n): BuiltinActionResolution {\n const logic =\n typeof src === 'string'\n ? resolveReferencedActor(snapshot.machine, src)\n : src;\n const resolvedId = typeof id === 'function' ? id(actionArgs) : id;\n let actorRef: AnyActorRef | undefined;\n let resolvedInput: unknown | undefined = undefined;\n\n if (logic) {\n resolvedInput =\n typeof input === 'function'\n ? input({\n context: snapshot.context,\n event: actionArgs.event,\n self: actorScope.self\n })\n : input;\n actorRef = createActor(logic, {\n id: resolvedId,\n src,\n parent: actorScope.self,\n syncSnapshot,\n systemId,\n input: resolvedInput\n });\n }\n\n if (isDevelopment && !actorRef) {\n console.warn(\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions,@typescript-eslint/no-base-to-string\n `Actor type '${src}' not found in machine '${actorScope.id}'.`\n );\n }\n return [\n cloneMachineSnapshot(snapshot, {\n children: {\n ...snapshot.children,\n [resolvedId]: actorRef!\n }\n }),\n {\n id,\n systemId,\n actorRef,\n src,\n input: resolvedInput\n },\n undefined\n ];\n}\n\nfunction executeSpawn(\n actorScope: AnyActorScope,\n { actorRef }: { id: string; actorRef: AnyActorRef }\n) {\n if (!actorRef) {\n return;\n }\n\n actorScope.defer(() => {\n if (actorRef._processingStatus === ProcessingStatus.Stopped) {\n return;\n }\n actorRef.start();\n });\n}\n\nexport interface SpawnAction<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject,\n TActor extends ProvidedActor\n> {\n (args: ActionArgs<TContext, TExpressionEvent, TEvent>, params: TParams): void;\n _out_TActor?: TActor;\n}\n\ninterface SpawnActionOptions<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TEvent extends EventObject,\n TActor extends ProvidedActor\n> {\n id?: ResolvableActorId<TContext, TExpressionEvent, TEvent, TActor['id']>;\n systemId?: string;\n input?:\n | Mapper<TContext, TEvent, InputFrom<TActor['logic']>, TEvent>\n | InputFrom<TActor['logic']>;\n syncSnapshot?: boolean;\n}\n\ntype DistributeActors<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TEvent extends EventObject,\n TActor extends ProvidedActor\n> =\n | (TActor extends any\n ? ConditionalRequired<\n [\n src: TActor['src'],\n options?: SpawnActionOptions<\n TContext,\n TExpressionEvent,\n TEvent,\n TActor\n > & {\n [K in RequiredActorOptions<TActor>]: unknown;\n }\n ],\n IsNotNever<RequiredActorOptions<TActor>>\n >\n : never)\n | [\n src: AnyActorLogic,\n options?: SpawnActionOptions<\n TContext,\n TExpressionEvent,\n TEvent,\n ProvidedActor\n > & { id?: never }\n ];\n\ntype SpawnArguments<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TEvent extends EventObject,\n TActor extends ProvidedActor\n> =\n IsLiteralString<TActor['src']> extends true\n ? DistributeActors<TContext, TExpressionEvent, TEvent, TActor>\n : [\n src: string | AnyActorLogic,\n options?: {\n id?: ResolvableActorId<TContext, TExpressionEvent, TEvent, string>;\n systemId?: string;\n input?: unknown;\n syncSnapshot?: boolean;\n }\n ];\n\nexport function spawnChild<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject,\n TActor extends ProvidedActor\n>(\n ...[\n src,\n { id, systemId, input, syncSnapshot = false } = {} as any\n ]: SpawnArguments<TContext, TExpressionEvent, TEvent, TActor>\n): ActionFunction<\n TContext,\n TExpressionEvent,\n TEvent,\n TParams,\n TActor,\n never,\n never,\n never,\n never\n> {\n function spawnChild(\n _args: ActionArgs<TContext, TExpressionEvent, TEvent>,\n _params: TParams\n ) {\n if (isDevelopment) {\n throw new Error(`This isn't supposed to be called`);\n }\n }\n\n spawnChild.type = 'xstate.spawnChild';\n spawnChild.id = id;\n spawnChild.systemId = systemId;\n spawnChild.src = src;\n spawnChild.input = input;\n spawnChild.syncSnapshot = syncSnapshot;\n\n spawnChild.resolve = resolveSpawn;\n spawnChild.execute = executeSpawn;\n\n return spawnChild;\n}\n","import isDevelopment from '#is-development';\nimport { cloneMachineSnapshot } from '../State.ts';\nimport { ProcessingStatus } from '../createActor.ts';\nimport {\n ActionArgs,\n AnyActorRef,\n AnyActorScope,\n AnyMachineSnapshot,\n EventObject,\n MachineContext,\n ParameterizedObject,\n BuiltinActionResolution\n} from '../types.ts';\n\ntype ResolvableActorRef<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject\n> =\n | string\n | AnyActorRef\n | ((\n args: ActionArgs<TContext, TExpressionEvent, TEvent>,\n params: TParams\n ) => AnyActorRef | string);\n\nfunction resolveStop(\n _: AnyActorScope,\n snapshot: AnyMachineSnapshot,\n args: ActionArgs<any, any, any>,\n actionParams: ParameterizedObject['params'] | undefined,\n { actorRef }: { actorRef: ResolvableActorRef<any, any, any, any> }\n): BuiltinActionResolution {\n const actorRefOrString =\n typeof actorRef === 'function' ? actorRef(args, actionParams) : actorRef;\n const resolvedActorRef: AnyActorRef | undefined =\n typeof actorRefOrString === 'string'\n ? snapshot.children[actorRefOrString]\n : actorRefOrString;\n\n let children = snapshot.children;\n if (resolvedActorRef) {\n children = { ...children };\n delete children[resolvedActorRef.id];\n }\n return [\n cloneMachineSnapshot(snapshot, {\n children\n }),\n resolvedActorRef,\n undefined\n ];\n}\nfunction executeStop(\n actorScope: AnyActorScope,\n actorRef: AnyActorRef | undefined\n) {\n if (!actorRef) {\n return;\n }\n\n // we need to eagerly unregister it here so a new actor with the same systemId can be registered immediately\n // since we defer actual stopping of the actor but we don't defer actor creations (and we can't do that)\n // this could throw on `systemId` collision, for example, when dealing with reentering transitions\n actorScope.system._unregister(actorRef);\n\n // this allows us to prevent an actor from being started if it gets stopped within the same macrostep\n // this can happen, for example, when the invoking state is being exited immediately by an always transition\n if (actorRef._processingStatus !== ProcessingStatus.Running) {\n actorScope.stopChild(actorRef);\n return;\n }\n // stopping a child enqueues a stop event in the child actor's mailbox\n // we need for all of the already enqueued events to be processed before we stop the child\n // the parent itself might want to send some events to a child (for example from exit actions on the invoking state)\n // and we don't want to ignore those events\n actorScope.defer(() => {\n actorScope.stopChild(actorRef);\n });\n}\n\nexport interface StopAction<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject\n> {\n (args: ActionArgs<TContext, TExpressionEvent, TEvent>, params: TParams): void;\n}\n\n/**\n * Stops a child actor.\n *\n * @param actorRef The actor to stop.\n */\nexport function stopChild<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject\n>(\n actorRef: ResolvableActorRef<TContext, TExpressionEvent, TParams, TEvent>\n): StopAction<TContext, TExpressionEvent, TParams, TEvent> {\n function stop(\n _args: ActionArgs<TContext, TExpressionEvent, TEvent>,\n _params: TParams\n ) {\n if (isDevelopment) {\n throw new Error(`This isn't supposed to be called`);\n }\n }\n\n stop.type = 'xstate.stopChild';\n stop.actorRef = actorRef;\n\n stop.resolve = resolveStop;\n stop.execute = executeStop;\n\n return stop;\n}\n\n/**\n * Stops a child actor.\n *\n * @deprecated Use `stopChild(...)` instead\n * @alias\n */\nexport const stop = stopChild;\n","import isDevelopment from '#is-development';\nimport type {\n EventObject,\n StateValue,\n MachineContext,\n ParameterizedObject,\n AnyMachineSnapshot,\n NoRequiredParams,\n WithDynamicParams,\n Identity,\n Elements,\n DoNotInfer\n} from './types.ts';\nimport { isStateId } from './stateUtils.ts';\n\ntype SingleGuardArg<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TGuardArg\n> = [TGuardArg] extends [{ type: string }]\n ? Identity<TGuardArg>\n : [TGuardArg] extends [string]\n ? TGuardArg\n : GuardPredicate<TContext, TExpressionEvent, TParams, ParameterizedObject>;\n\ntype NormalizeGuardArg<TGuardArg> = TGuardArg extends { type: string }\n ? Identity<TGuardArg> & { params: unknown }\n : TGuardArg extends string\n ? { type: TGuardArg; params: undefined }\n : '_out_TGuard' extends keyof TGuardArg\n ? TGuardArg['_out_TGuard'] & ParameterizedObject\n : never;\n\ntype NormalizeGuardArgArray<TArg extends unknown[]> = Elements<{\n [K in keyof TArg]: NormalizeGuardArg<TArg[K]>;\n}>;\n\nexport type GuardPredicate<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TGuard extends ParameterizedObject\n> = {\n (args: GuardArgs<TContext, TExpressionEvent>, params: TParams): boolean;\n _out_TGuard?: TGuard;\n};\n\nexport interface GuardArgs<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject\n> {\n context: TContext;\n event: TExpressionEvent;\n}\n\nexport type Guard<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TGuard extends ParameterizedObject\n> =\n | NoRequiredParams<TGuard>\n | WithDynamicParams<TContext, TExpressionEvent, TGuard>\n | GuardPredicate<TContext, TExpressionEvent, TParams, TGuard>;\n\nexport type UnknownGuard = UnknownReferencedGuard | UnknownInlineGuard;\n\ntype UnknownReferencedGuard = Guard<\n MachineContext,\n EventObject,\n ParameterizedObject['params'],\n ParameterizedObject\n>;\n\ntype UnknownInlineGuard = Guard<\n MachineContext,\n EventObject,\n undefined,\n ParameterizedObject\n>;\n\ninterface BuiltinGuard {\n (): boolean;\n check: (\n snapshot: AnyMachineSnapshot,\n guardArgs: GuardArgs<any, any>,\n params: unknown\n ) => boolean;\n}\n\nfunction checkStateIn(\n snapshot: AnyMachineSnapshot,\n _: GuardArgs<any, any>,\n { stateValue }: { stateValue: StateValue }\n) {\n if (typeof stateValue === 'string' && isStateId(stateValue)) {\n const target = snapshot.machine.getStateNodeById(stateValue);\n return snapshot._nodes.some((sn) => sn === target);\n }\n\n return snapshot.matches(stateValue);\n}\n\nexport function stateIn<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined\n>(\n stateValue: StateValue\n): GuardPredicate<\n TContext,\n TExpressionEvent,\n TParams,\n any // TODO: recheck if we could replace this with something better here\n> {\n function stateIn() {\n if (isDevelopment) {\n throw new Error(`This isn't supposed to be called`);\n }\n return false;\n }\n\n stateIn.check = checkStateIn;\n stateIn.stateValue = stateValue;\n\n return stateIn;\n}\n\nfunction checkNot(\n snapshot: AnyMachineSnapshot,\n { context, event }: GuardArgs<any, any>,\n { guards }: { guards: readonly UnknownGuard[] }\n) {\n return !evaluateGuard(guards[0], context, event, snapshot);\n}\n\n/**\n * Higher-order guard that evaluates to `true` if the `guard` passed to it\n * evaluates to `false`.\n *\n * @category Guards\n * @example\n *\n * ```ts\n * import { setup, not } from 'xstate';\n *\n * const machine = setup({\n * guards: {\n * someNamedGuard: () => false\n * }\n * }).createMachine({\n * on: {\n * someEvent: {\n * guard: not('someNamedGuard'),\n * actions: () => {\n * // will be executed if guard in `not(...)`\n * // evaluates to `false`\n * }\n * }\n * }\n * });\n * ```\n *\n * @returns A guard\n */\nexport function not<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TArg\n>(\n guard: SingleGuardArg<TContext, TExpressionEvent, unknown, TArg>\n): GuardPredicate<\n TContext,\n TExpressionEvent,\n unknown,\n NormalizeGuardArg<DoNotInfer<TArg>>\n> {\n function not(_args: GuardArgs<TContext, TExpressionEvent>, _params: unknown) {\n if (isDevelopment) {\n throw new Error(`This isn't supposed to be called`);\n }\n return false;\n }\n\n not.check = checkNot;\n not.guards = [guard];\n\n return not;\n}\n\nfunction checkAnd(\n snapshot: AnyMachineSnapshot,\n { context, event }: GuardArgs<any, any>,\n { guards }: { guards: readonly UnknownGuard[] }\n) {\n return guards.every((guard) =>\n evaluateGuard(guard, context, event, snapshot)\n );\n}\n\n/**\n * Higher-order guard that evaluates to `true` if all `guards` passed to it\n * evaluate to `true`.\n *\n * @category Guards\n * @example\n *\n * ```ts\n * import { setup, and } from 'xstate';\n *\n * const machine = setup({\n * guards: {\n * someNamedGuard: () => true\n * }\n * }).createMachine({\n * on: {\n * someEvent: {\n * guard: and([({ context }) => context.value > 0, 'someNamedGuard']),\n * actions: () => {\n * // will be executed if all guards in `and(...)`\n * // evaluate to true\n * }\n * }\n * }\n * });\n * ```\n *\n * @returns A guard action object\n */\nexport function and<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TArg extends unknown[]\n>(\n guards: readonly [\n ...{\n [K in keyof TArg]: SingleGuardArg<\n TContext,\n TExpressionEvent,\n unknown,\n TArg[K]\n >;\n }\n ]\n): GuardPredicate<\n TContext,\n TExpressionEvent,\n unknown,\n NormalizeGuardArgArray<DoNotInfer<TArg>>\n> {\n function and(_args: GuardArgs<TContext, TExpressionEvent>, _params: unknown) {\n if (isDevelopment) {\n throw new Error(`This isn't supposed to be called`);\n }\n return false;\n }\n\n and.check = checkAnd;\n and.guards = guards;\n\n return and;\n}\n\nfunction checkOr(\n snapshot: AnyMachineSnapshot,\n { context, event }: GuardArgs<any, any>,\n { guards }: { guards: readonly UnknownGuard[] }\n) {\n return guards.some((guard) => evaluateGuard(guard, context, event, snapshot));\n}\n\n/**\n * Higher-order guard that evaluates to `true` if any of the `guards` passed to\n * it evaluate to `true`.\n *\n * @category Guards\n * @example\n *\n * ```ts\n * import { setup, or } from 'xstate';\n *\n * const machine = setup({\n * guards: {\n * someNamedGuard: () => true\n * }\n * }).createMachine({\n * on: {\n * someEvent: {\n * guard: or([({ context }) => context.value > 0, 'someNamedGuard']),\n * actions: () => {\n * // will be executed if any of the guards in `or(...)`\n * // evaluate to true\n * }\n * }\n * }\n * });\n * ```\n *\n * @returns A guard action object\n */\nexport function or<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TArg extends unknown[]\n>(\n guards: readonly [\n ...{\n [K in keyof TArg]: SingleGuardArg<\n TContext,\n TExpressionEvent,\n unknown,\n TArg[K]\n >;\n }\n ]\n): GuardPredicate<\n TContext,\n TExpressionEvent,\n unknown,\n NormalizeGuardArgArray<DoNotInfer<TArg>>\n> {\n function or(_args: GuardArgs<TContext, TExpressionEvent>, _params: unknown) {\n if (isDevelopment) {\n throw new Error(`This isn't supposed to be called`);\n }\n return false;\n }\n\n or.check = checkOr;\n or.guards = guards;\n\n return or;\n}\n\n// TODO: throw on cycles (depth check should be enough)\nexport function evaluateGuard<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject\n>(\n guard: UnknownGuard | UnknownInlineGuard,\n context: TContext,\n event: TExpressionEvent,\n snapshot: AnyMachineSnapshot\n): boolean {\n const { machine } = snapshot;\n const isInline = typeof guard === 'function';\n\n const resolved = isInline\n ? guard\n : machine.implementations.guards[\n typeof guard === 'string' ? guard : guard.type\n ];\n\n if (!isInline && !resolved) {\n throw new Error(\n `Guard '${\n typeof guard === 'string' ? guard : guard.type\n }' is not implemented.'.`\n );\n }\n\n if (typeof resolved !== 'function') {\n return evaluateGuard(resolved!, context, event, snapshot);\n }\n\n const guardArgs = {\n context,\n event\n };\n\n const guardParams =\n isInline || typeof guard === 'string'\n ? undefined\n : 'params' in guard\n ? typeof guard.params === 'function'\n ? guard.params({ context, event })\n : guard.params\n : undefined;\n\n if (!('check' in resolved)) {\n // the existing type of `.guards` assumes non-nullable `TExpressionGuard`\n // inline guards expect `TExpressionGuard` to be set to `undefined`\n // it's fine to cast this here, our logic makes sure that we call those 2 \"variants\" correctly\n return resolved(guardArgs, guardParams as never);\n }\n\n const builtinGuard = resolved as unknown as BuiltinGuard;\n\n return builtinGuard.check(\n snapshot,\n guardArgs,\n resolved // this holds all params\n );\n}\n","import isDevelopment from '#is-development';\nimport { MachineSnapshot, cloneMachineSnapshot } from './State.ts';\nimport type { StateNode } from './StateNode.ts';\nimport { raise } from './actions.ts';\nimport { createAfterEvent, createDoneStateEvent } from './eventUtils.ts';\nimport { cancel } from './actions/cancel.ts';\nimport { spawnChild } from './actions/spawnChild.ts';\nimport { stopChild } from './actions/stopChild.ts';\nimport {\n XSTATE_INIT,\n NULL_EVENT,\n STATE_DELIMITER,\n STATE_IDENTIFIER,\n XSTATE_STOP,\n WILDCARD\n} from './constants.ts';\nimport { evaluateGuard } from './guards.ts';\nimport {\n ActionArgs,\n AnyEventObject,\n AnyHistoryValue,\n AnyMachineSnapshot,\n AnyStateNode,\n AnyTransitionDefinition,\n DelayedTransitionDefinition,\n EventObject,\n HistoryValue,\n InitialTransitionConfig,\n InitialTransitionDefinition,\n MachineContext,\n StateValue,\n StateValueMap,\n TransitionDefinition,\n TODO,\n UnknownAction,\n ParameterizedObject,\n AnyTransitionConfig,\n AnyActorScope,\n ActionExecutor,\n AnyStateMachine\n} from './types.ts';\nimport {\n resolveOutput,\n normalizeTarget,\n toArray,\n toStatePath,\n toTransitionConfigArray,\n isErrorActorEvent\n} from './utils.ts';\n\ntype StateNodeIterable<\n TContext extends MachineContext,\n TE extends EventObject\n> = Iterable<StateNode<TContext, TE>>;\ntype AnyStateNodeIterable = StateNodeIterable<any, any>;\n\ntype AdjList = Map<AnyStateNode, Array<AnyStateNode>>;\n\nconst isAtomicStateNode = (stateNode: StateNode<any, any>) =>\n stateNode.type === 'atomic' || stateNode.type === 'final';\n\nfunction getChildren<TContext extends MachineContext, TE extends EventObject>(\n stateNode: StateNode<TContext, TE>\n): Array<StateNode<TContext, TE>> {\n return Object.values(stateNode.states).filter((sn) => sn.type !== 'history');\n}\n\nfunction 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\n const adjList = getAdjList(nodeSet);\n\n // add descendants\n for (const s of nodeSet) {\n // if previously active, add existing child nodes\n if (s.type === 'compound' && (!adjList.get(s) || !adjList.get(s)!.length)) {\n getInitialStateNodesWithTheirAncestors(s).forEach((sn) =>\n nodeSet.add(sn)\n );\n } else {\n if (s.type === 'parallel') {\n for (const child of getChildren(s)) {\n if (child.type === 'history') {\n continue;\n }\n\n if (!nodeSet.has(child)) {\n const initialStates = getInitialStateNodesWithTheirAncestors(child);\n for (const initialStateNode of initialStates) {\n nodeSet.add(initialStateNode);\n }\n }\n }\n }\n }\n }\n\n // add all ancestors\n for (const s of nodeSet) {\n let m = s.parent;\n\n while (m) {\n nodeSet.add(m);\n m = m.parent;\n }\n }\n\n return nodeSet;\n}\n\nfunction getValueFromAdj(baseNode: AnyStateNode, adjList: AdjList): 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 if (isAtomicStateNode(childStateNode)) {\n return childStateNode.key;\n }\n } else {\n return {};\n }\n }\n\n const stateValue: StateValue = {};\n for (const childStateNode of childStateNodes) {\n stateValue[childStateNode.key] = getValueFromAdj(childStateNode, adjList);\n }\n\n return stateValue;\n}\n\nfunction getAdjList<TContext extends MachineContext, TE extends EventObject>(\n stateNodes: StateNodeIterable<TContext, TE>\n): AdjList {\n const adjList: AdjList = new Map();\n\n for (const s of stateNodes) {\n if (!adjList.has(s)) {\n adjList.set(s, []);\n }\n\n if (s.parent) {\n if (!adjList.has(s.parent)) {\n adjList.set(s.parent, []);\n }\n\n adjList.get(s.parent)!.push(s);\n }\n }\n\n return adjList;\n}\n\nexport function getStateValue(\n rootNode: AnyStateNode,\n stateNodes: AnyStateNodeIterable\n): StateValue {\n const config = getAllStateNodes(stateNodes);\n return getValueFromAdj(rootNode, getAdjList(config));\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 getCandidates<TEvent extends EventObject>(\n stateNode: StateNode<any, TEvent>,\n receivedEventType: TEvent['type']\n): Array<TransitionDefinition<any, TEvent>> {\n const candidates =\n stateNode.transitions.get(receivedEventType) ||\n [...stateNode.transitions.keys()]\n .filter((eventDescriptor) => {\n // check if transition is a wildcard transition,\n // which matches any non-transient events\n if (eventDescriptor === WILDCARD) {\n return true;\n }\n\n if (!eventDescriptor.endsWith('.*')) {\n return false;\n }\n\n if (isDevelopment && /.*\\*.+/.test(eventDescriptor)) {\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 \"${eventDescriptor}\" event.`\n );\n }\n\n const partialEventTokens = eventDescriptor.split('.');\n const eventTokens = receivedEventType.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 \"${eventDescriptor}\" transition.`\n );\n }\n\n return isLastToken;\n }\n\n if (partialEventToken !== eventToken) {\n return false;\n }\n }\n\n return true;\n })\n .sort((a, b) => b.length - a.length)\n .flatMap((key) => stateNode.transitions.get(key)!);\n\n return candidates;\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 if (!afterConfig) {\n return [];\n }\n\n const mutateEntryExit = (delay: string | number) => {\n const afterEvent = createAfterEvent(delay, stateNode.id);\n const eventType = afterEvent.type;\n\n stateNode.entry.push(\n raise(afterEvent, {\n id: eventType,\n delay\n })\n );\n stateNode.exit.push(cancel(eventType));\n return eventType;\n };\n\n const delayedTransitions = Object.keys(afterConfig).flatMap((delay) => {\n const configTransition = afterConfig[delay];\n const resolvedTransition =\n typeof configTransition === 'string'\n ? { target: configTransition }\n : configTransition;\n const resolvedDelay = Number.isNaN(+delay) ? delay : +delay;\n const eventType = mutateEntryExit(resolvedDelay);\n return toArray(resolvedTransition).map((transition) => ({\n ...transition,\n event: eventType,\n delay: resolvedDelay\n }));\n });\n return delayedTransitions.map((delayedTransition) => {\n const { delay } = delayedTransition;\n return {\n ...formatTransition(\n stateNode,\n delayedTransition.event,\n delayedTransition\n ),\n delay\n };\n });\n}\n\nexport function formatTransition(\n stateNode: AnyStateNode,\n descriptor: string,\n transitionConfig: AnyTransitionConfig\n): AnyTransitionDefinition {\n const normalizedTarget = normalizeTarget(transitionConfig.target);\n const reenter = transitionConfig.reenter ?? false;\n const target = resolveTarget(stateNode, normalizedTarget);\n\n // TODO: should this be part of a lint rule instead?\n if (isDevelopment && (transitionConfig as any).cond) {\n throw new Error(\n `State \"${stateNode.id}\" has declared \\`cond\\` for one of its transitions. This property has been renamed to \\`guard\\`. Please update your code.`\n );\n }\n\n const transition = {\n ...transitionConfig,\n actions: toArray(transitionConfig.actions),\n guard: transitionConfig.guard as never,\n target,\n source: stateNode,\n reenter,\n eventType: descriptor,\n toJSON: () => ({\n ...transition,\n source: `#${stateNode.id}`,\n target: target ? target.map((t) => `#${t.id}`) : undefined\n })\n };\n\n return transition;\n}\n\nexport function 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 if (stateNode.config.on) {\n for (const descriptor of Object.keys(stateNode.config.on)) {\n if (descriptor === NULL_EVENT) {\n throw new Error(\n 'Null events (\"\") cannot be specified as a transition key. Use `always: { ... }` instead.'\n );\n }\n const transitionsConfig = stateNode.config.on[descriptor];\n transitions.set(\n descriptor,\n toTransitionConfigArray(transitionsConfig).map((t) =>\n formatTransition(stateNode, descriptor, t)\n )\n );\n }\n }\n if (stateNode.config.onDone) {\n const descriptor = `xstate.done.state.${stateNode.id}`;\n transitions.set(\n descriptor,\n toTransitionConfigArray(stateNode.config.onDone).map((t) =>\n formatTransition(stateNode, descriptor, t)\n )\n );\n }\n for (const invokeDef of stateNode.invoke) {\n if (invokeDef.onDone) {\n const descriptor = `xstate.done.actor.${invokeDef.id}`;\n transitions.set(\n descriptor,\n toTransitionConfigArray(invokeDef.onDone).map((t) =>\n formatTransition(stateNode, descriptor, t)\n )\n );\n }\n if (invokeDef.onError) {\n const descriptor = `xstate.error.actor.${invokeDef.id}`;\n transitions.set(\n descriptor,\n toTransitionConfigArray(invokeDef.onError).map((t) =>\n formatTransition(stateNode, descriptor, t)\n )\n );\n }\n if (invokeDef.onSnapshot) {\n const descriptor = `xstate.snapshot.${invokeDef.id}`;\n transitions.set(\n descriptor,\n toTransitionConfigArray(invokeDef.onSnapshot).map((t) =>\n formatTransition(stateNode, descriptor, t)\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(delayedTransition);\n }\n return transitions as Map<string, TransitionDefinition<TContext, any>[]>;\n}\n\nexport function formatInitialTransition<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n stateNode: AnyStateNode,\n _target:\n | string\n | undefined\n | InitialTransitionConfig<TContext, TEvent, TODO, TODO, TODO, TODO>\n): InitialTransitionDefinition<TContext, TEvent> {\n const resolvedTarget =\n typeof _target === 'string'\n ? stateNode.states[_target]\n : _target\n ? stateNode.states[_target.target]\n : undefined;\n if (!resolvedTarget && _target) {\n throw new Error(\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions, @typescript-eslint/no-base-to-string\n `Initial state node \"${_target}\" not found on parent state node #${stateNode.id}`\n );\n }\n const transition: InitialTransitionDefinition<TContext, TEvent> = {\n source: stateNode,\n actions:\n !_target || typeof _target === 'string' ? [] : toArray(_target.actions),\n eventType: null as any,\n reenter: false,\n target: resolvedTarget ? [resolvedTarget] : [],\n toJSON: () => ({\n ...transition,\n source: `#${stateNode.id}`,\n target: resolvedTarget ? [`#${resolvedTarget.id}`] : []\n })\n };\n\n return transition;\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 `Invalid transition definition for state node '${stateNode.id}':\\n${err.message}`\n );\n }\n } else {\n throw new Error(\n `Invalid target: \"${target}\" is not a valid target from the root node. Did you mean \".${target}\"?`\n );\n }\n });\n}\n\nfunction resolveHistoryDefaultTransition<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(stateNode: AnyStateNode & { type: 'history' }) {\n const normalizedTarget = normalizeTarget<TContext, TEvent>(\n stateNode.config.target\n );\n if (!normalizedTarget) {\n return stateNode.parent!.initial;\n }\n return {\n target: normalizedTarget.map((t) =>\n typeof t === 'string' ? getStateNodeByPath(stateNode.parent!, t) : t\n )\n };\n}\n\nfunction isHistoryNode(\n stateNode: AnyStateNode\n): stateNode is AnyStateNode & { type: 'history' } {\n return stateNode.type === 'history';\n}\n\nfunction getInitialStateNodesWithTheirAncestors(stateNode: AnyStateNode) {\n const states = getInitialStateNodes(stateNode);\n for (const initialState of states) {\n for (const ancestor of getProperAncestors(initialState, stateNode)) {\n states.add(ancestor);\n }\n }\n return states;\n}\n\nexport function 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 iter(descStateNode.initial.target[0]);\n } else if (descStateNode.type === 'parallel') {\n for (const child of getChildren(descStateNode)) {\n iter(child);\n }\n }\n }\n\n iter(stateNode);\n\n return set;\n}\n/** Returns the child state node from its relative `stateKey`, or throws. */\nfunction getStateNode(stateNode: AnyStateNode, stateKey: string): AnyStateNode {\n if (isStateId(stateKey)) {\n return stateNode.machine.getStateNodeById(stateKey);\n }\n if (!stateNode.states) {\n throw new Error(\n `Unable to retrieve child state '${stateKey}' from '${stateNode.id}'; no child states exist.`\n );\n }\n const result = stateNode.states[stateKey];\n if (!result) {\n throw new Error(\n `Child state '${stateKey}' does not exist on '${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 */\nexport function getStateNodeByPath(\n stateNode: AnyStateNode,\n statePath: string | string[]\n): AnyStateNode {\n if (typeof statePath === 'string' && isStateId(statePath)) {\n try {\n return stateNode.machine.getStateNodeById(statePath);\n } catch {\n // try individual paths\n // throw e;\n }\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 */\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 `State '${stateValue}' does not exist on '${stateNode.id}'`\n );\n }\n return [stateNode, childStateNode];\n }\n\n const childStateKeys = Object.keys(stateValue);\n const childStateNodes: Array<AnyStateNode> = childStateKeys\n .map((subStateKey) => getStateNode(stateNode, subStateKey))\n .filter(Boolean);\n\n return [stateNode.machine.root, stateNode].concat(\n childStateNodes,\n childStateKeys.reduce((allSubStateNodes, subStateKey) => {\n const subStateNode = getStateNode(stateNode, subStateKey);\n if (!subStateNode) {\n return allSubStateNodes;\n }\n const subStateNodes = getStateNodes(\n subStateNode,\n stateValue[subStateKey]!\n );\n\n return allSubStateNodes.concat(subStateNodes);\n }, [] as Array<AnyStateNode>)\n );\n}\n\nfunction transitionAtomicNode<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n stateNode: AnyStateNode,\n stateValue: string,\n snapshot: MachineSnapshot<\n TContext,\n TEvent,\n any,\n any,\n any,\n any,\n any, // TMeta\n any // TStateSchema\n >,\n event: TEvent\n): Array<TransitionDefinition<TContext, TEvent>> | undefined {\n const childStateNode = getStateNode(stateNode, stateValue);\n const next = childStateNode.next(snapshot, event);\n\n if (!next || !next.length) {\n return stateNode.next(snapshot, event);\n }\n\n return next;\n}\n\nfunction transitionCompoundNode<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n stateNode: AnyStateNode,\n stateValue: StateValueMap,\n snapshot: MachineSnapshot<\n TContext,\n TEvent,\n any,\n any,\n any,\n any,\n any, // TMeta\n any // TStateSchema\n >,\n event: TEvent\n): Array<TransitionDefinition<TContext, TEvent>> | undefined {\n const subStateKeys = Object.keys(stateValue);\n\n const childStateNode = getStateNode(stateNode, subStateKeys[0]);\n const next = transitionNode(\n childStateNode,\n stateValue[subStateKeys[0]]!,\n snapshot,\n event\n );\n\n if (!next || !next.length) {\n return stateNode.next(snapshot, event);\n }\n\n return next;\n}\n\nfunction transitionParallelNode<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n stateNode: AnyStateNode,\n stateValue: StateValueMap,\n snapshot: MachineSnapshot<\n TContext,\n TEvent,\n any,\n any,\n any,\n any,\n any, // TMeta\n any // TStateSchema\n >,\n event: TEvent\n): Array<TransitionDefinition<TContext, TEvent>> | undefined {\n const allInnerTransitions: Array<TransitionDefinition<TContext, TEvent>> = [];\n\n for (const subStateKey of Object.keys(stateValue)) {\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 );\n if (innerTransitions) {\n allInnerTransitions.push(...innerTransitions);\n }\n }\n if (!allInnerTransitions.length) {\n return stateNode.next(snapshot, event);\n }\n\n return allInnerTransitions;\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): Array<TransitionDefinition<TContext, TEvent>> | undefined {\n // leaf node\n if (typeof stateValue === 'string') {\n return transitionAtomicNode(stateNode, stateValue, snapshot, event);\n }\n\n // compound node\n if (Object.keys(stateValue).length === 1) {\n return transitionCompoundNode(stateNode, stateValue, snapshot, event);\n }\n\n // parallel node\n return transitionParallelNode(stateNode, stateValue, snapshot, event);\n}\n\nfunction getHistoryNodes(stateNode: AnyStateNode): Array<AnyStateNode> {\n return Object.keys(stateNode.states)\n .map((key) => stateNode.states[key])\n .filter((sn) => sn.type === 'history');\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 hasIntersection<T>(s1: Iterable<T>, s2: Iterable<T>): boolean {\n const set1 = new Set(s1);\n const set2 = new Set(s2);\n\n for (const item of set1) {\n if (set2.has(item)) {\n return true;\n }\n }\n for (const item of set2) {\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 historyValue: AnyHistoryValue\n): Array<AnyTransitionDefinition> {\n const filteredTransitions = new Set<AnyTransitionDefinition>();\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 (\n hasIntersection(\n computeExitSet([t1], stateNodeSet, historyValue),\n computeExitSet([t2], stateNodeSet, historyValue)\n )\n ) {\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\nfunction findLeastCommonAncestor(\n stateNodes: Array<AnyStateNode>\n): AnyStateNode | undefined {\n const [head, ...tail] = stateNodes;\n for (const ancestor of getProperAncestors(head, undefined)) {\n if (tail.every((sn) => isDescendant(sn, ancestor))) {\n return ancestor;\n }\n }\n}\n\nfunction getEffectiveTargetStates(\n transition: Pick<AnyTransitionDefinition, 'target'>,\n historyValue: AnyHistoryValue\n): Array<AnyStateNode> {\n if (!transition.target) {\n return [];\n }\n\n const targets = new Set<AnyStateNode>();\n\n for (const targetNode of transition.target) {\n if (isHistoryNode(targetNode)) {\n if (historyValue[targetNode.id]) {\n for (const node of historyValue[targetNode.id]) {\n targets.add(node);\n }\n } else {\n for (const node of getEffectiveTargetStates(\n resolveHistoryDefaultTransition(targetNode),\n historyValue\n )) {\n targets.add(node);\n }\n }\n } else {\n targets.add(targetNode);\n }\n }\n\n return [...targets];\n}\n\nfunction getTransitionDomain(\n transition: AnyTransitionDefinition,\n historyValue: AnyHistoryValue\n): AnyStateNode | undefined {\n const targetStates = getEffectiveTargetStates(transition, historyValue);\n\n if (!targetStates) {\n return;\n }\n\n if (\n !transition.reenter &&\n targetStates.every(\n (target) =>\n target === transition.source || isDescendant(target, transition.source)\n )\n ) {\n return transition.source;\n }\n\n const lca = findLeastCommonAncestor(targetStates.concat(transition.source));\n\n if (lca) {\n return lca;\n }\n\n // at this point we know that it's a root transition since LCA couldn't be found\n if (transition.reenter) {\n return;\n }\n\n return transition.source.machine.root;\n}\n\nfunction computeExitSet(\n transitions: AnyTransitionDefinition[],\n stateNodeSet: Set<AnyStateNode>,\n historyValue: AnyHistoryValue\n): Array<AnyStateNode> {\n const statesToExit = new Set<AnyStateNode>();\n\n for (const t of transitions) {\n if (t.target?.length) {\n const domain = getTransitionDomain(t, historyValue);\n\n if (t.reenter && t.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\nfunction areStateNodeCollectionsEqual(\n prevStateNodes: StateNode[],\n nextStateNodeSet: Set<StateNode>\n) {\n if (prevStateNodes.length !== nextStateNodeSet.size) {\n return false;\n }\n for (const node of prevStateNodes) {\n if (!nextStateNodeSet.has(node)) {\n return false;\n }\n }\n return true;\n}\n\n/** https://www.w3.org/TR/scxml/#microstepProcedure */\nexport function microstep(\n transitions: Array<AnyTransitionDefinition>,\n currentSnapshot: AnyMachineSnapshot,\n actorScope: AnyActorScope,\n event: AnyEventObject,\n isInitial: boolean,\n internalQueue: Array<AnyEventObject>\n): AnyMachineSnapshot {\n if (!transitions.length) {\n return currentSnapshot;\n }\n const mutStateNodeSet = new Set(currentSnapshot._nodes);\n let historyValue = currentSnapshot.historyValue;\n\n const filteredTransitions = removeConflictingTransitions(\n transitions,\n mutStateNodeSet,\n historyValue\n );\n\n let nextState = currentSnapshot;\n\n // Exit states\n if (!isInitial) {\n [nextState, historyValue] = exitStates(\n nextState,\n event,\n actorScope,\n filteredTransitions,\n mutStateNodeSet,\n historyValue,\n internalQueue,\n actorScope.actionExecutor\n );\n }\n\n // Execute transition content\n nextState = resolveActionsAndContext(\n nextState,\n event,\n actorScope,\n filteredTransitions.flatMap((t) => t.actions),\n internalQueue,\n undefined\n );\n\n // Enter states\n nextState = enterStates(\n nextState,\n event,\n actorScope,\n filteredTransitions,\n mutStateNodeSet,\n internalQueue,\n historyValue,\n isInitial\n );\n\n const nextStateNodes = [...mutStateNodeSet];\n\n if (nextState.status === 'done') {\n nextState = resolveActionsAndContext(\n nextState,\n event,\n actorScope,\n nextStateNodes\n .sort((a, b) => b.order - a.order)\n .flatMap((state) => state.exit),\n internalQueue,\n undefined\n );\n }\n\n // eslint-disable-next-line no-useless-catch\n try {\n if (\n historyValue === currentSnapshot.historyValue &&\n areStateNodeCollectionsEqual(currentSnapshot._nodes, mutStateNodeSet)\n ) {\n return nextState;\n }\n return cloneMachineSnapshot(nextState, {\n _nodes: nextStateNodes,\n historyValue\n });\n } catch (e) {\n // TODO: Refactor this once proper error handling is implemented.\n // See https://github.com/statelyai/rfcs/pull/4\n throw e;\n }\n}\n\nfunction getMachineOutput(\n snapshot: AnyMachineSnapshot,\n event: AnyEventObject,\n actorScope: AnyActorScope,\n rootNode: AnyStateNode,\n rootCompletionNode: AnyStateNode\n) {\n if (rootNode.output === undefined) {\n return;\n }\n const doneStateEvent = createDoneStateEvent(\n rootCompletionNode.id,\n rootCompletionNode.output !== undefined && rootCompletionNode.parent\n ? resolveOutput(\n rootCompletionNode.output,\n snapshot.context,\n event,\n actorScope.self\n )\n : undefined\n );\n return resolveOutput(\n rootNode.output,\n snapshot.context,\n doneStateEvent,\n actorScope.self\n );\n}\n\nfunction enterStates(\n currentSnapshot: AnyMachineSnapshot,\n event: AnyEventObject,\n actorScope: AnyActorScope,\n filteredTransitions: AnyTransitionDefinition[],\n mutStateNodeSet: Set<AnyStateNode>,\n internalQueue: AnyEventObject[],\n historyValue: HistoryValue<any, any>,\n isInitial: boolean\n) {\n let nextSnapshot = currentSnapshot;\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 computeEntrySet(\n filteredTransitions,\n historyValue,\n statesForDefaultEntry,\n statesToEnter\n );\n\n // In the initial state, the root state node is \"entered\".\n if (isInitial) {\n statesForDefaultEntry.add(currentSnapshot.machine.root);\n }\n\n const completedNodes = new Set();\n\n for (const stateNodeToEnter of [...statesToEnter].sort(\n (a, b) => a.order - b.order\n )) {\n mutStateNodeSet.add(stateNodeToEnter);\n const actions: UnknownAction[] = [];\n\n // Add entry actions\n actions.push(...stateNodeToEnter.entry);\n\n for (const invokeDef of stateNodeToEnter.invoke) {\n actions.push(\n spawnChild(invokeDef.src, {\n ...invokeDef,\n syncSnapshot: !!invokeDef.onSnapshot\n })\n );\n }\n\n if (statesForDefaultEntry.has(stateNodeToEnter)) {\n const initialActions = stateNodeToEnter.initial.actions;\n actions.push(...initialActions);\n }\n\n nextSnapshot = resolveActionsAndContext(\n nextSnapshot,\n event,\n actorScope,\n actions,\n internalQueue,\n stateNodeToEnter.invoke.map((invokeDef) => invokeDef.id)\n );\n\n if (stateNodeToEnter.type === 'final') {\n const parent = stateNodeToEnter.parent;\n\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 nextSnapshot.context,\n event,\n actorScope.self\n )\n : undefined\n )\n );\n }\n while (\n ancestorMarker?.type === 'parallel' &&\n !completedNodes.has(ancestorMarker) &&\n isInFinalState(mutStateNodeSet, ancestorMarker)\n ) {\n completedNodes.add(ancestorMarker);\n internalQueue.push(createDoneStateEvent(ancestorMarker.id));\n rootCompletionNode = ancestorMarker;\n ancestorMarker = ancestorMarker.parent;\n }\n if (ancestorMarker) {\n continue;\n }\n\n nextSnapshot = cloneMachineSnapshot(nextSnapshot, {\n status: 'done',\n output: getMachineOutput(\n nextSnapshot,\n event,\n actorScope,\n nextSnapshot.machine.root,\n rootCompletionNode\n )\n });\n }\n }\n\n return nextSnapshot;\n}\n\nfunction computeEntrySet(\n transitions: Array<AnyTransitionDefinition>,\n historyValue: HistoryValue<any, any>,\n statesForDefaultEntry: Set<AnyStateNode>,\n statesToEnter: Set<AnyStateNode>\n) {\n for (const t of transitions) {\n const domain = getTransitionDomain(t, historyValue);\n\n for (const s of t.target || []) {\n if (\n !isHistoryNode(s) &&\n // if the target is different than the source then it will *definitely* be entered\n (t.source !== s ||\n // we know that the domain can't lie within the source\n // if it's different than the source then it's outside of it and it means that the target has to be entered as well\n t.source !== domain ||\n // reentering transitions always enter the target, even if it's the source itself\n t.reenter)\n ) {\n statesToEnter.add(s);\n statesForDefaultEntry.add(s);\n }\n addDescendantStatesToEnter(\n s,\n historyValue,\n statesForDefaultEntry,\n statesToEnter\n );\n }\n const targetStates = getEffectiveTargetStates(t, historyValue);\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 statesToEnter,\n historyValue,\n statesForDefaultEntry,\n ancestors,\n !t.source.parent && t.reenter ? undefined : domain\n );\n }\n }\n}\n\nfunction addDescendantStatesToEnter<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n stateNode: AnyStateNode,\n historyValue: HistoryValue<any, any>,\n statesForDefaultEntry: Set<AnyStateNode>,\n statesToEnter: Set<AnyStateNode>\n) {\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\n addDescendantStatesToEnter(\n s,\n historyValue,\n statesForDefaultEntry,\n statesToEnter\n );\n }\n for (const s of historyStateNodes) {\n addProperAncestorStatesToEnter(\n s,\n stateNode.parent,\n statesToEnter,\n historyValue,\n statesForDefaultEntry\n );\n }\n } else {\n const historyDefaultTransition = resolveHistoryDefaultTransition<\n TContext,\n TEvent\n >(stateNode);\n for (const s of historyDefaultTransition.target) {\n statesToEnter.add(s);\n\n if (historyDefaultTransition === stateNode.parent?.initial) {\n statesForDefaultEntry.add(stateNode.parent);\n }\n\n addDescendantStatesToEnter(\n s,\n historyValue,\n statesForDefaultEntry,\n statesToEnter\n );\n }\n\n for (const s of historyDefaultTransition.target) {\n addProperAncestorStatesToEnter(\n s,\n stateNode.parent,\n statesToEnter,\n historyValue,\n statesForDefaultEntry\n );\n }\n }\n } else {\n if (stateNode.type === 'compound') {\n const [initialState] = stateNode.initial.target;\n\n if (!isHistoryNode(initialState)) {\n statesToEnter.add(initialState);\n statesForDefaultEntry.add(initialState);\n }\n addDescendantStatesToEnter(\n initialState,\n historyValue,\n statesForDefaultEntry,\n statesToEnter\n );\n\n addProperAncestorStatesToEnter(\n initialState,\n stateNode,\n statesToEnter,\n historyValue,\n statesForDefaultEntry\n );\n } else {\n if (stateNode.type === 'parallel') {\n for (const child of getChildren(stateNode).filter(\n (sn) => !isHistoryNode(sn)\n )) {\n if (![...statesToEnter].some((s) => isDescendant(s, child))) {\n if (!isHistoryNode(child)) {\n statesToEnter.add(child);\n statesForDefaultEntry.add(child);\n }\n addDescendantStatesToEnter(\n child,\n historyValue,\n statesForDefaultEntry,\n statesToEnter\n );\n }\n }\n }\n }\n }\n}\n\nfunction addAncestorStatesToEnter(\n statesToEnter: Set<AnyStateNode>,\n historyValue: HistoryValue<any, any>,\n statesForDefaultEntry: Set<AnyStateNode>,\n ancestors: AnyStateNode[],\n reentrancyDomain?: AnyStateNode\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).filter((sn) => !isHistoryNode(sn))) {\n if (![...statesToEnter].some((s) => isDescendant(s, child))) {\n statesToEnter.add(child);\n addDescendantStatesToEnter(\n child,\n historyValue,\n statesForDefaultEntry,\n statesToEnter\n );\n }\n }\n }\n }\n}\n\nfunction addProperAncestorStatesToEnter(\n stateNode: AnyStateNode,\n toStateNode: AnyStateNode | undefined,\n statesToEnter: Set<AnyStateNode>,\n historyValue: HistoryValue<any, any>,\n statesForDefaultEntry: Set<AnyStateNode>\n) {\n addAncestorStatesToEnter(\n statesToEnter,\n historyValue,\n statesForDefaultEntry,\n getProperAncestors(stateNode, toStateNode)\n );\n}\n\nfunction exitStates(\n currentSnapshot: AnyMachineSnapshot,\n event: AnyEventObject,\n actorScope: AnyActorScope,\n transitions: AnyTransitionDefinition[],\n mutStateNodeSet: Set<AnyStateNode>,\n historyValue: HistoryValue<any, any>,\n internalQueue: AnyEventObject[],\n _actionExecutor: ActionExecutor\n) {\n let nextSnapshot = currentSnapshot;\n const statesToExit = computeExitSet(\n transitions,\n mutStateNodeSet,\n historyValue\n );\n\n statesToExit.sort((a, b) => b.order - a.order);\n\n let changedHistory: typeof historyValue | undefined;\n\n // From SCXML algorithm: https://www.w3.org/TR/scxml/#exitStates\n for (const exitStateNode of statesToExit) {\n for (const historyNode of getHistoryNodes(exitStateNode)) {\n let predicate: (sn: AnyStateNode) => boolean;\n if (historyNode.history === 'deep') {\n predicate = (sn) =>\n isAtomicStateNode(sn) && isDescendant(sn, exitStateNode);\n } else {\n predicate = (sn) => {\n return sn.parent === exitStateNode;\n };\n }\n changedHistory ??= { ...historyValue };\n changedHistory[historyNode.id] =\n Array.from(mutStateNodeSet).filter(predicate);\n }\n }\n\n for (const s of statesToExit) {\n nextSnapshot = resolveActionsAndContext(\n nextSnapshot,\n event,\n actorScope,\n [...s.exit, ...s.invoke.map((def) => stopChild(def.id))],\n internalQueue,\n undefined\n );\n mutStateNodeSet.delete(s);\n }\n return [nextSnapshot, changedHistory || historyValue] as const;\n}\n\nexport interface BuiltinAction {\n (): void;\n type: `xstate.${string}`;\n resolve: (\n actorScope: AnyActorScope,\n snapshot: AnyMachineSnapshot,\n actionArgs: ActionArgs<any, any, any>,\n actionParams: ParameterizedObject['params'] | undefined,\n action: unknown,\n extra: unknown\n ) => [\n newState: AnyMachineSnapshot,\n params: unknown,\n actions?: UnknownAction[]\n ];\n retryResolve: (\n actorScope: AnyActorScope,\n snapshot: AnyMachineSnapshot,\n params: unknown\n ) => void;\n execute: (actorScope: AnyActorScope, params: unknown) => void;\n}\n\nfunction getAction(machine: AnyStateMachine, actionType: string) {\n return machine.implementations.actions[actionType];\n}\n\nfunction resolveAndExecuteActionsWithContext(\n currentSnapshot: AnyMachineSnapshot,\n event: AnyEventObject,\n actorScope: AnyActorScope,\n actions: UnknownAction[],\n extra: {\n internalQueue: AnyEventObject[];\n deferredActorIds: string[] | undefined;\n },\n retries: (readonly [BuiltinAction, unknown])[] | undefined\n): AnyMachineSnapshot {\n const { machine } = currentSnapshot;\n let intermediateSnapshot = currentSnapshot;\n\n for (const action of actions) {\n const isInline = typeof action === 'function';\n const resolvedAction = isInline\n ? action\n : // the existing type of `.actions` assumes non-nullable `TExpressionAction`\n // it's fine to cast this here to get a common type and lack of errors in the rest of the code\n // our logic below makes sure that we call those 2 \"variants\" correctly\n\n getAction(machine, typeof action === 'string' ? action : action.type);\n const actionArgs = {\n context: intermediateSnapshot.context,\n event,\n self: actorScope.self,\n system: actorScope.system\n };\n\n const actionParams =\n isInline || typeof action === 'string'\n ? undefined\n : 'params' in action\n ? typeof action.params === 'function'\n ? action.params({ context: intermediateSnapshot.context, event })\n : action.params\n : undefined;\n\n if (!resolvedAction || !('resolve' in resolvedAction)) {\n actorScope.actionExecutor({\n type:\n typeof action === 'string'\n ? action\n : typeof action === 'object'\n ? action.type\n : action.name || '(anonymous)',\n info: actionArgs,\n params: actionParams,\n exec: resolvedAction\n });\n continue;\n }\n\n const builtinAction = resolvedAction as BuiltinAction;\n\n const [nextState, params, actions] = builtinAction.resolve(\n actorScope,\n intermediateSnapshot,\n actionArgs,\n actionParams,\n resolvedAction, // this holds all params\n extra\n );\n intermediateSnapshot = nextState;\n\n if ('retryResolve' in builtinAction) {\n retries?.push([builtinAction, params]);\n }\n\n if ('execute' in builtinAction) {\n actorScope.actionExecutor({\n type: builtinAction.type,\n info: actionArgs,\n params,\n exec: builtinAction.execute.bind(null, actorScope, params)\n });\n }\n\n if (actions) {\n intermediateSnapshot = resolveAndExecuteActionsWithContext(\n intermediateSnapshot,\n event,\n actorScope,\n actions,\n extra,\n retries\n );\n }\n }\n\n return intermediateSnapshot;\n}\n\nexport function resolveActionsAndContext(\n currentSnapshot: AnyMachineSnapshot,\n event: AnyEventObject,\n actorScope: AnyActorScope,\n actions: UnknownAction[],\n internalQueue: AnyEventObject[],\n deferredActorIds: string[] | undefined\n): AnyMachineSnapshot {\n const retries: (readonly [BuiltinAction, unknown])[] | undefined =\n deferredActorIds ? [] : undefined;\n const nextState = resolveAndExecuteActionsWithContext(\n currentSnapshot,\n event,\n actorScope,\n actions,\n { internalQueue, deferredActorIds },\n retries\n );\n retries?.forEach(([builtinAction, params]) => {\n builtinAction.retryResolve(actorScope, nextState, params);\n });\n return nextState;\n}\n\nexport function macrostep(\n snapshot: AnyMachineSnapshot,\n event: EventObject,\n actorScope: AnyActorScope,\n internalQueue: AnyEventObject[]\n): {\n snapshot: typeof snapshot;\n microstates: Array<typeof snapshot>;\n} {\n if (isDevelopment && event.type === WILDCARD) {\n throw new Error(`An event cannot have the wildcard type ('${WILDCARD}')`);\n }\n\n let nextSnapshot = snapshot;\n const microstates: AnyMachineSnapshot[] = [];\n\n function addMicrostate(\n microstate: AnyMachineSnapshot,\n event: AnyEventObject,\n transitions: AnyTransitionDefinition[]\n ) {\n actorScope.system._sendInspectionEvent({\n type: '@xstate.microstep',\n actorRef: actorScope.self,\n event,\n snapshot: microstate,\n _transitions: transitions\n });\n microstates.push(microstate);\n }\n\n // Handle stop event\n if (event.type === XSTATE_STOP) {\n nextSnapshot = cloneMachineSnapshot(\n stopChildren(nextSnapshot, event, actorScope),\n {\n status: 'stopped'\n }\n );\n addMicrostate(nextSnapshot, event, []);\n\n return {\n snapshot: nextSnapshot,\n microstates\n };\n }\n\n let nextEvent = event;\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) {\n const currentEvent = nextEvent;\n const isErr = isErrorActorEvent(currentEvent);\n\n const transitions = selectTransitions(currentEvent, nextSnapshot);\n\n if (isErr && !transitions.length) {\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 // similarly `xstate.error.actor.*` and `xstate.error.actor.todo.*` have to be considered too\n nextSnapshot = cloneMachineSnapshot<typeof snapshot>(snapshot, {\n status: 'error',\n error: currentEvent.error\n });\n addMicrostate(nextSnapshot, currentEvent, []);\n return {\n snapshot: nextSnapshot,\n microstates\n };\n }\n nextSnapshot = microstep(\n transitions,\n snapshot,\n actorScope,\n nextEvent,\n false, // isInitial\n internalQueue\n );\n addMicrostate(nextSnapshot, currentEvent, transitions);\n }\n\n let shouldSelectEventlessTransitions = true;\n\n while (nextSnapshot.status === 'active') {\n let enabledTransitions: AnyTransitionDefinition[] =\n shouldSelectEventlessTransitions\n ? selectEventlessTransitions(nextSnapshot, nextEvent)\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\n if (!enabledTransitions.length) {\n if (!internalQueue.length) {\n break;\n }\n nextEvent = internalQueue.shift()!;\n enabledTransitions = selectTransitions(nextEvent, nextSnapshot);\n }\n\n nextSnapshot = microstep(\n enabledTransitions,\n nextSnapshot,\n actorScope,\n nextEvent,\n false,\n internalQueue\n );\n shouldSelectEventlessTransitions = nextSnapshot !== previousState;\n addMicrostate(nextSnapshot, nextEvent, enabledTransitions);\n }\n\n if (nextSnapshot.status !== 'active') {\n stopChildren(nextSnapshot, nextEvent, actorScope);\n }\n\n return {\n snapshot: nextSnapshot,\n microstates\n };\n}\n\nfunction stopChildren(\n nextState: AnyMachineSnapshot,\n event: AnyEventObject,\n actorScope: AnyActorScope\n) {\n return resolveActionsAndContext(\n nextState,\n event,\n actorScope,\n Object.values(nextState.children).map((child: any) => stopChild(child)),\n [],\n undefined\n );\n}\n\nfunction selectTransitions(\n event: AnyEventObject,\n nextState: AnyMachineSnapshot\n): AnyTransitionDefinition[] {\n return nextState.machine.getTransitionData(nextState as any, event);\n}\n\nfunction selectEventlessTransitions(\n nextState: AnyMachineSnapshot,\n event: AnyEventObject\n): AnyTransitionDefinition[] {\n const enabledTransitionSet: Set<AnyTransitionDefinition> = new Set();\n const atomicStates = nextState._nodes.filter(isAtomicStateNode);\n\n for (const stateNode of atomicStates) {\n loop: for (const s of [stateNode].concat(\n getProperAncestors(stateNode, undefined)\n )) {\n if (!s.always) {\n continue;\n }\n for (const transition of s.always) {\n if (\n transition.guard === undefined ||\n evaluateGuard(transition.guard, nextState.context, event, nextState)\n ) {\n enabledTransitionSet.add(transition);\n break loop;\n }\n }\n }\n }\n\n return removeConflictingTransitions(\n Array.from(enabledTransitionSet),\n new Set(nextState._nodes),\n nextState.historyValue\n );\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","import { ProcessingStatus, createActor } from './createActor.ts';\nimport {\n ActorRefFromLogic,\n AnyActorLogic,\n AnyActorRef,\n AnyActorScope,\n AnyEventObject,\n AnyMachineSnapshot,\n ConditionalRequired,\n GetConcreteByKey,\n InputFrom,\n IsLiteralString,\n IsNotNever,\n ProvidedActor,\n RequiredActorOptions,\n TODO,\n type RequiredLogicInput\n} from './types.ts';\nimport { resolveReferencedActor } from './utils.ts';\n\ntype SpawnOptions<\n TActor extends ProvidedActor,\n TSrc extends TActor['src']\n> = TActor extends {\n src: TSrc;\n}\n ? ConditionalRequired<\n [\n options?: {\n id?: TActor['id'];\n systemId?: string;\n input?: InputFrom<TActor['logic']>;\n syncSnapshot?: boolean;\n } & { [K in RequiredActorOptions<TActor>]: unknown }\n ],\n IsNotNever<RequiredActorOptions<TActor>>\n >\n : never;\n\nexport type Spawner<TActor extends ProvidedActor> =\n IsLiteralString<TActor['src']> extends true\n ? {\n <TSrc extends TActor['src']>(\n logic: TSrc,\n ...[options]: SpawnOptions<TActor, TSrc>\n ): ActorRefFromLogic<GetConcreteByKey<TActor, 'src', TSrc>['logic']>;\n <TLogic extends AnyActorLogic>(\n src: TLogic,\n ...[options]: ConditionalRequired<\n [\n options?: {\n id?: never;\n systemId?: string;\n input?: InputFrom<TLogic>;\n syncSnapshot?: boolean;\n } & { [K in RequiredLogicInput<TLogic>]: unknown }\n ],\n IsNotNever<RequiredLogicInput<TLogic>>\n >\n ): ActorRefFromLogic<TLogic>;\n }\n : <TLogic extends AnyActorLogic | string>(\n src: TLogic,\n ...[options]: ConditionalRequired<\n [\n options?: {\n id?: string;\n systemId?: string;\n input?: TLogic extends string ? unknown : InputFrom<TLogic>;\n syncSnapshot?: boolean;\n } & (TLogic extends AnyActorLogic\n ? { [K in RequiredLogicInput<TLogic>]: unknown }\n : {})\n ],\n IsNotNever<\n TLogic extends AnyActorLogic ? RequiredLogicInput<TLogic> : never\n >\n >\n ) => TLogic extends AnyActorLogic\n ? ActorRefFromLogic<TLogic>\n : AnyActorRef;\n\nexport function createSpawner(\n actorScope: AnyActorScope,\n { machine, context }: AnyMachineSnapshot,\n event: AnyEventObject,\n spawnedChildren: Record<string, AnyActorRef>\n): Spawner<any> {\n const spawn: Spawner<any> = ((src, options) => {\n if (typeof src === 'string') {\n const logic = resolveReferencedActor(machine, src);\n\n if (!logic) {\n throw new Error(\n `Actor logic '${src}' not implemented in machine '${machine.id}'`\n );\n }\n\n const actorRef = createActor(logic, {\n id: options?.id,\n parent: actorScope.self,\n syncSnapshot: options?.syncSnapshot,\n input:\n typeof options?.input === 'function'\n ? options.input({\n context,\n event,\n self: actorScope.self\n })\n : options?.input,\n src,\n systemId: options?.systemId\n }) as any;\n\n spawnedChildren[actorRef.id] = actorRef;\n\n return actorRef;\n } else {\n const actorRef = createActor(src, {\n id: options?.id,\n parent: actorScope.self,\n syncSnapshot: options?.syncSnapshot,\n input: options?.input,\n src,\n systemId: options?.systemId\n });\n\n return actorRef;\n }\n }) as Spawner<any>;\n return ((src, options) => {\n const actorRef = spawn(src, options) as TODO; // TODO: fix types\n spawnedChildren[actorRef.id] = actorRef;\n actorScope.defer(() => {\n if (actorRef._processingStatus === ProcessingStatus.Stopped) {\n return;\n }\n actorRef.start();\n });\n return actorRef;\n }) as Spawner<any>;\n}\n","import isDevelopment from '#is-development';\nimport { cloneMachineSnapshot } from '../State.ts';\nimport { executingCustomAction } from '../createActor.ts';\nimport { Spawner, createSpawner } from '../spawn.ts';\nimport type {\n ActionArgs,\n AnyActorScope,\n AnyActorRef,\n AnyEventObject,\n AnyMachineSnapshot,\n Assigner,\n EventObject,\n LowInfer,\n MachineContext,\n ParameterizedObject,\n PropertyAssigner,\n ProvidedActor,\n ActionFunction,\n BuiltinActionResolution\n} from '../types.ts';\n\nexport interface AssignArgs<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TEvent extends EventObject,\n TActor extends ProvidedActor\n> extends ActionArgs<TContext, TExpressionEvent, TEvent> {\n spawn: Spawner<TActor>;\n}\n\nfunction resolveAssign(\n actorScope: AnyActorScope,\n snapshot: AnyMachineSnapshot,\n actionArgs: ActionArgs<any, any, any>,\n actionParams: ParameterizedObject['params'] | undefined,\n {\n assignment\n }: {\n assignment:\n | Assigner<any, any, any, any, any>\n | PropertyAssigner<any, any, any, any, any>;\n }\n): BuiltinActionResolution {\n if (!snapshot.context) {\n throw new Error(\n 'Cannot assign to undefined `context`. Ensure that `context` is defined in the machine config.'\n );\n }\n const spawnedChildren: Record<string, AnyActorRef> = {};\n\n const assignArgs: AssignArgs<any, any, any, any> = {\n context: snapshot.context,\n event: actionArgs.event,\n spawn: createSpawner(\n actorScope,\n snapshot,\n actionArgs.event,\n spawnedChildren\n ),\n self: actorScope.self,\n system: actorScope.system\n };\n let partialUpdate: Record<string, unknown> = {};\n if (typeof assignment === 'function') {\n partialUpdate = assignment(assignArgs, actionParams);\n } else {\n for (const key of Object.keys(assignment)) {\n const propAssignment = assignment[key];\n partialUpdate[key] =\n typeof propAssignment === 'function'\n ? propAssignment(assignArgs, actionParams)\n : propAssignment;\n }\n }\n\n const updatedContext = Object.assign({}, snapshot.context, partialUpdate);\n\n return [\n cloneMachineSnapshot(snapshot, {\n context: updatedContext,\n children: Object.keys(spawnedChildren).length\n ? {\n ...snapshot.children,\n ...spawnedChildren\n }\n : snapshot.children\n }),\n undefined,\n undefined\n ];\n}\n\nexport interface AssignAction<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject,\n TActor extends ProvidedActor\n> {\n (args: ActionArgs<TContext, TExpressionEvent, TEvent>, params: TParams): void;\n _out_TActor?: TActor;\n}\n\n/**\n * Updates the current context of the machine.\n *\n * @example\n *\n * ```ts\n * import { createMachine, assign } from 'xstate';\n *\n * const countMachine = createMachine({\n * context: {\n * count: 0,\n * message: ''\n * },\n * on: {\n * inc: {\n * actions: assign({\n * count: ({ context }) => context.count + 1\n * })\n * },\n * updateMessage: {\n * actions: assign(({ context, event }) => {\n * return {\n * message: event.message.trim()\n * };\n * })\n * }\n * }\n * });\n * ```\n *\n * @param assignment An object that represents the partial context to update, or\n * a function that returns an object that represents the partial context to\n * update.\n */\nexport function assign<\n TContext extends MachineContext,\n TExpressionEvent extends AnyEventObject, // TODO: consider using a stricter `EventObject` here\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject,\n TActor extends ProvidedActor\n>(\n assignment:\n | Assigner<LowInfer<TContext>, TExpressionEvent, TParams, TEvent, TActor>\n | PropertyAssigner<\n LowInfer<TContext>,\n TExpressionEvent,\n TParams,\n TEvent,\n TActor\n >\n): ActionFunction<\n TContext,\n TExpressionEvent,\n TEvent,\n TParams,\n TActor,\n never,\n never,\n never,\n never\n> {\n if (isDevelopment && executingCustomAction) {\n console.warn(\n 'Custom actions should not call `assign()` directly, as it is not imperative. See https://stately.ai/docs/actions#built-in-actions for more details.'\n );\n }\n\n function assign(\n _args: ActionArgs<TContext, TExpressionEvent, TEvent>,\n _params: TParams\n ) {\n if (isDevelopment) {\n throw new Error(`This isn't supposed to be called`);\n }\n }\n\n assign.type = 'xstate.assign';\n assign.assignment = assignment;\n\n assign.resolve = resolveAssign;\n\n return assign;\n}\n","import isDevelopment from '#is-development';\nimport { executingCustomAction } from '../createActor.ts';\nimport {\n ActionArgs,\n ActionFunction,\n AnyActorScope,\n AnyEventObject,\n AnyMachineSnapshot,\n DoNotInfer,\n EventObject,\n MachineContext,\n ParameterizedObject,\n SendExpr,\n BuiltinActionResolution\n} from '../types.ts';\n\nfunction resolveEmit(\n _: AnyActorScope,\n snapshot: AnyMachineSnapshot,\n args: ActionArgs<any, any, any>,\n actionParams: ParameterizedObject['params'] | undefined,\n {\n event: eventOrExpr\n }: {\n event:\n | EventObject\n | SendExpr<\n MachineContext,\n EventObject,\n ParameterizedObject['params'] | undefined,\n EventObject,\n EventObject\n >;\n }\n): BuiltinActionResolution {\n const resolvedEvent =\n typeof eventOrExpr === 'function'\n ? eventOrExpr(args, actionParams)\n : eventOrExpr;\n return [snapshot, { event: resolvedEvent }, undefined];\n}\n\nfunction executeEmit(\n actorScope: AnyActorScope,\n {\n event\n }: {\n event: EventObject;\n }\n) {\n actorScope.defer(() => actorScope.emit(event));\n}\n\nexport interface EmitAction<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject,\n TEmitted extends EventObject\n> {\n (args: ActionArgs<TContext, TExpressionEvent, TEvent>, params: TParams): void;\n _out_TEmitted?: TEmitted;\n}\n\n/**\n * Emits an event to event handlers registered on the actor via `actor.on(event,\n * handler)`.\n *\n * @example\n *\n * ```ts\n * import { emit } from 'xstate';\n *\n * const machine = createMachine({\n * // ...\n * on: {\n * something: {\n * actions: emit({\n * type: 'emitted',\n * some: 'data'\n * })\n * }\n * }\n * // ...\n * });\n *\n * const actor = createActor(machine).start();\n *\n * actor.on('emitted', (event) => {\n * console.log(event);\n * });\n *\n * actor.send({ type: 'something' });\n * // logs:\n * // {\n * // type: 'emitted',\n * // some: 'data'\n * // }\n * ```\n */\nexport function emit<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject,\n TEmitted extends AnyEventObject\n>(\n /** The event to emit, or an expression that returns an event to emit. */\n eventOrExpr:\n | DoNotInfer<TEmitted>\n | SendExpr<\n TContext,\n TExpressionEvent,\n TParams,\n DoNotInfer<TEmitted>,\n TEvent\n >\n): ActionFunction<\n TContext,\n TExpressionEvent,\n TEvent,\n TParams,\n never,\n never,\n never,\n never,\n TEmitted\n> {\n if (isDevelopment && executingCustomAction) {\n console.warn(\n 'Custom actions should not call `emit()` directly, as it is not imperative. See https://stately.ai/docs/actions#built-in-actions for more details.'\n );\n }\n\n function emit(\n _args: ActionArgs<TContext, TExpressionEvent, TEvent>,\n _params: TParams\n ) {\n if (isDevelopment) {\n throw new Error(`This isn't supposed to be called`);\n }\n }\n\n emit.type = 'xstate.emit';\n emit.event = eventOrExpr;\n\n emit.resolve = resolveEmit;\n emit.execute = executeEmit;\n\n return emit;\n}\n","import isDevelopment from '#is-development';\nimport { executingCustomAction } from '../createActor.ts';\nimport {\n ActionArgs,\n ActionFunction,\n AnyActorScope,\n AnyEventObject,\n AnyMachineSnapshot,\n DelayExpr,\n DoNotInfer,\n EventObject,\n ExecutableActionObject,\n MachineContext,\n ParameterizedObject,\n RaiseActionOptions,\n SendExpr,\n BuiltinActionResolution\n} from '../types.ts';\n\nfunction resolveRaise(\n _: AnyActorScope,\n snapshot: AnyMachineSnapshot,\n args: ActionArgs<any, any, any>,\n actionParams: ParameterizedObject['params'] | undefined,\n {\n event: eventOrExpr,\n id,\n delay\n }: {\n event:\n | EventObject\n | SendExpr<\n MachineContext,\n EventObject,\n ParameterizedObject['params'] | undefined,\n EventObject,\n EventObject\n >;\n id: string | undefined;\n delay:\n | string\n | number\n | DelayExpr<\n MachineContext,\n EventObject,\n ParameterizedObject['params'] | undefined,\n EventObject\n >\n | undefined;\n },\n { internalQueue }: { internalQueue: AnyEventObject[] }\n): BuiltinActionResolution {\n const delaysMap = snapshot.machine.implementations.delays;\n\n if (typeof eventOrExpr === 'string') {\n throw new Error(\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `Only event objects may be used with raise; use raise({ type: \"${eventOrExpr}\" }) instead`\n );\n }\n const resolvedEvent =\n typeof eventOrExpr === 'function'\n ? eventOrExpr(args, actionParams)\n : eventOrExpr;\n\n let resolvedDelay: number | undefined;\n if (typeof delay === 'string') {\n const configDelay = delaysMap && delaysMap[delay];\n resolvedDelay =\n typeof configDelay === 'function'\n ? configDelay(args, actionParams)\n : configDelay;\n } else {\n resolvedDelay =\n typeof delay === 'function' ? delay(args, actionParams) : delay;\n }\n if (typeof resolvedDelay !== 'number') {\n internalQueue.push(resolvedEvent);\n }\n return [\n snapshot,\n {\n event: resolvedEvent,\n id,\n delay: resolvedDelay\n },\n undefined\n ];\n}\n\nfunction executeRaise(\n actorScope: AnyActorScope,\n params: {\n event: EventObject;\n id: string | undefined;\n delay: number | undefined;\n }\n) {\n const { event, delay, id } = params;\n if (typeof delay === 'number') {\n actorScope.defer(() => {\n const self = actorScope.self;\n actorScope.system.scheduler.schedule(self, self, event, delay, id);\n });\n return;\n }\n}\n\nexport interface RaiseAction<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject,\n TDelay extends string\n> {\n (args: ActionArgs<TContext, TExpressionEvent, TEvent>, params: TParams): void;\n _out_TEvent?: TEvent;\n _out_TDelay?: TDelay;\n}\n\n/**\n * Raises an event. This places the event in the internal event queue, so that\n * the event is immediately consumed by the machine in the current step.\n *\n * @param eventType The event to raise.\n */\nexport function raise<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TDelay extends string = never,\n TUsedDelay extends TDelay = never\n>(\n eventOrExpr:\n | DoNotInfer<TEvent>\n | SendExpr<TContext, TExpressionEvent, TParams, DoNotInfer<TEvent>, TEvent>,\n options?: RaiseActionOptions<\n TContext,\n TExpressionEvent,\n TParams,\n DoNotInfer<TEvent>,\n TUsedDelay\n >\n): ActionFunction<\n TContext,\n TExpressionEvent,\n TEvent,\n TParams,\n never,\n never,\n never,\n TDelay,\n never\n> {\n if (isDevelopment && executingCustomAction) {\n console.warn(\n 'Custom actions should not call `raise()` directly, as it is not imperative. See https://stately.ai/docs/actions#built-in-actions for more details.'\n );\n }\n\n function raise(\n _args: ActionArgs<TContext, TExpressionEvent, TEvent>,\n _params: TParams\n ) {\n if (isDevelopment) {\n throw new Error(`This isn't supposed to be called`);\n }\n }\n\n raise.type = 'xstate.raise';\n raise.event = eventOrExpr;\n raise.id = options?.id;\n raise.delay = options?.delay;\n\n raise.resolve = resolveRaise;\n raise.execute = executeRaise;\n\n return raise;\n}\n\nexport interface ExecutableRaiseAction extends ExecutableActionObject {\n type: 'xstate.raise';\n params: {\n event: EventObject;\n id: string | undefined;\n delay: number | undefined;\n };\n}\n","import type { MachineSnapshot } from './State.ts';\nimport type { StateMachine } from './StateMachine.ts';\nimport type { StateNode } from './StateNode.ts';\nimport { AssignArgs } from './actions/assign.ts';\nimport { ExecutableRaiseAction } from './actions/raise.ts';\nimport { ExecutableSendToAction } from './actions/send.ts';\nimport { PromiseActorLogic } from './actors/promise.ts';\nimport type { Actor, ProcessingStatus } from './createActor.ts';\nimport { Guard, GuardPredicate, UnknownGuard } from './guards.ts';\nimport { InspectionEvent } from './inspection.ts';\nimport { Spawner } from './spawn.ts';\nimport { AnyActorSystem, Clock } from './system.ts';\n\n// this is needed to make JSDoc `@link` work properly\nimport type { SimulatedClock } from './SimulatedClock.ts';\n\nexport type Identity<T> = { [K in keyof T]: T[K] };\n\nexport type HomomorphicPick<T, K extends keyof any> = {\n [P in keyof T as P & K]: T[P];\n};\nexport type HomomorphicOmit<T, K extends keyof any> = {\n [P in keyof T as Exclude<P, K>]: T[P];\n};\n\nexport type Invert<T extends Record<PropertyKey, PropertyKey>> = {\n [K in keyof T as T[K]]: K;\n};\n\nexport type GetParameterizedParams<T extends ParameterizedObject | undefined> =\n T extends any ? ('params' extends keyof T ? T['params'] : undefined) : never;\n\n/**\n * @remarks\n * `T | unknown` reduces to `unknown` and that can be problematic when it comes\n * to contextual typing. It especially is a problem when the union has a\n * function member, like here:\n *\n * ```ts\n * declare function test(\n * cbOrVal: ((arg: number) => unknown) | unknown\n * ): void;\n * test((arg) => {}); // oops, implicit any\n * ```\n *\n * This type can be used to avoid this problem. This union represents the same\n * value space as `unknown`.\n */\nexport type NonReducibleUnknown = {} | null | undefined;\nexport type AnyFunction = (...args: any[]) => any;\n\ntype ReturnTypeOrValue<T> = T extends AnyFunction ? ReturnType<T> : T;\n\n// https://github.com/microsoft/TypeScript/issues/23182#issuecomment-379091887\nexport type IsNever<T> = [T] extends [never] ? true : false;\nexport type IsNotNever<T> = [T] extends [never] ? false : true;\n\nexport type Compute<A> = { [K in keyof A]: A[K] } & unknown;\nexport type Prop<T, K> = K extends keyof T ? T[K] : never;\nexport type Values<T> = T[keyof T];\nexport type Elements<T> = T[keyof T & `${number}`];\nexport type Merge<M, N> = Omit<M, keyof N> & N;\nexport type IndexByProp<T extends Record<P, string>, P extends keyof T> = {\n [E in T as E[P]]: E;\n};\n\nexport type IndexByType<T extends { type: string }> = IndexByProp<T, 'type'>;\n\nexport type Equals<A1, A2> =\n (<A>() => A extends A2 ? true : false) extends <A>() => A extends A1\n ? true\n : false\n ? true\n : false;\nexport type IsAny<T> = Equals<T, any>;\nexport type Cast<A, B> = A extends B ? A : B;\n// @TODO: we can't use native `NoInfer` as we need those:\n// https://github.com/microsoft/TypeScript/pull/61092\n// https://github.com/microsoft/TypeScript/pull/61077\n// but even with those fixes native NoInfer still doesn't work - further issues have to be reproduced and fixed\nexport type DoNotInfer<T> = [T][T extends any ? 0 : any];\n/** @deprecated Use the built-in `NoInfer` type instead */\nexport type NoInfer<T> = DoNotInfer<T>;\nexport type LowInfer<T> = T & NonNullable<unknown>;\n\nexport type MetaObject = Record<string, any>;\n\nexport type Lazy<T> = () => T;\nexport type MaybeLazy<T> = T | Lazy<T>;\n\n/** The full definition of an event, with a string `type`. */\nexport type EventObject = {\n /** The type of event that is sent. */\n type: string;\n};\n\nexport interface AnyEventObject extends EventObject {\n [key: string]: any;\n}\n\nexport interface ParameterizedObject {\n type: string;\n params?: NonReducibleUnknown;\n}\n\nexport interface UnifiedArg<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TEvent extends EventObject\n> {\n context: TContext;\n event: TExpressionEvent;\n self: ActorRef<\n MachineSnapshot<\n TContext,\n TEvent,\n Record<string, AnyActorRef | undefined>, // TODO: this should be replaced with `TChildren`\n StateValue,\n string,\n unknown,\n TODO, // TMeta\n TODO // State schema\n >,\n TEvent,\n AnyEventObject\n >;\n system: AnyActorSystem;\n}\n\nexport type MachineContext = Record<string, any>;\n\nexport interface ActionArgs<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TEvent extends EventObject\n> extends UnifiedArg<TContext, TExpressionEvent, TEvent> {}\n\nexport type InputFrom<T> =\n T extends StateMachine<\n infer _TContext,\n infer _TEvent,\n infer _TChildren,\n infer _TActor,\n infer _TAction,\n infer _TGuard,\n infer _TDelay,\n infer _TStateValue,\n infer _TTag,\n infer TInput,\n infer _TOutput,\n infer _TEmitted,\n infer _TMeta,\n infer _TStateSchema\n >\n ? TInput\n : T extends ActorLogic<\n infer _TSnapshot,\n infer _TEvent,\n infer TInput,\n infer _TSystem,\n infer _TEmitted\n >\n ? TInput\n : never;\n\nexport type OutputFrom<T> =\n T extends ActorLogic<\n infer TSnapshot,\n infer _TEvent,\n infer _TInput,\n infer _TSystem,\n infer _TEmitted\n >\n ? (TSnapshot & { status: 'done' })['output']\n : T extends ActorRef<infer TSnapshot, infer _TEvent, infer _TEmitted>\n ? (TSnapshot & { status: 'done' })['output']\n : never;\n\nexport type ActionFunction<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TActor extends ProvidedActor,\n TAction extends ParameterizedObject,\n TGuard extends ParameterizedObject,\n TDelay extends string,\n TEmitted extends EventObject\n> = {\n (args: ActionArgs<TContext, TExpressionEvent, TEvent>, params: TParams): void;\n _out_TEvent?: TEvent; // TODO: it feels like we should be able to remove this since now `TEvent` is \"observable\" by `self`\n _out_TActor?: TActor;\n _out_TAction?: TAction;\n _out_TGuard?: TGuard;\n _out_TDelay?: TDelay;\n _out_TEmitted?: TEmitted;\n};\n\nexport type NoRequiredParams<T extends ParameterizedObject> = T extends any\n ? undefined extends T['params']\n ? T['type']\n : never\n : never;\n\nexport type ConditionalRequired<\n T,\n Condition extends boolean\n> = Condition extends true ? Required<T> : T;\n\nexport type WithDynamicParams<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n T extends ParameterizedObject\n> = T extends any\n ? ConditionalRequired<\n {\n type: T['type'];\n params?:\n | T['params']\n | (({\n context,\n event\n }: {\n context: TContext;\n event: TExpressionEvent;\n }) => T['params']);\n },\n undefined extends T['params'] ? false : true\n >\n : never;\n\nexport type Action<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TActor extends ProvidedActor,\n TAction extends ParameterizedObject,\n TGuard extends ParameterizedObject,\n TDelay extends string,\n TEmitted extends EventObject\n> =\n // TODO: consider merging `NoRequiredParams` and `WithDynamicParams` into one\n // this way we could iterate over `TAction` (and `TGuard` in the `Guard` type) once and not twice\n | NoRequiredParams<TAction>\n | WithDynamicParams<TContext, TExpressionEvent, TAction>\n | ActionFunction<\n TContext,\n TExpressionEvent,\n TEvent,\n TParams,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted\n >;\n\nexport type UnknownAction = Action<\n MachineContext,\n EventObject,\n EventObject,\n ParameterizedObject['params'] | undefined,\n ProvidedActor,\n ParameterizedObject,\n ParameterizedObject,\n string,\n EventObject\n>;\n\nexport type Actions<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TActor extends ProvidedActor,\n TAction extends ParameterizedObject,\n TGuard extends ParameterizedObject,\n TDelay extends string,\n TEmitted extends EventObject\n> = SingleOrArray<\n Action<\n TContext,\n TExpressionEvent,\n TEvent,\n TParams,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted\n >\n>;\n\nexport type StateKey = string | AnyMachineSnapshot;\n\nexport interface StateValueMap {\n [key: string]: StateValue | undefined;\n}\n\n/**\n * The string or object representing the state value relative to the parent\n * state node.\n *\n * @remarks\n * - For a child atomic state node, this is a string, e.g., `\"pending\"`.\n * - For complex state nodes, this is an object, e.g., `{ success:\n * \"someChildState\" }`.\n */\nexport type StateValue = string | StateValueMap;\n\nexport type TransitionTarget = SingleOrArray<string>;\n\nexport interface TransitionConfig<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TEvent extends EventObject,\n TActor extends ProvidedActor,\n TAction extends ParameterizedObject,\n TGuard extends ParameterizedObject,\n TDelay extends string,\n TEmitted extends EventObject = EventObject,\n TMeta extends MetaObject = MetaObject\n> {\n guard?: Guard<TContext, TExpressionEvent, undefined, TGuard>;\n actions?: Actions<\n TContext,\n TExpressionEvent,\n TEvent,\n undefined,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted\n >;\n reenter?: boolean;\n target?: TransitionTarget | undefined;\n meta?: TMeta;\n description?: string;\n}\n\nexport interface InitialTransitionConfig<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TActor extends ProvidedActor,\n TAction extends ParameterizedObject,\n TGuard extends ParameterizedObject,\n TDelay extends string\n> extends TransitionConfig<\n TContext,\n TEvent,\n TEvent,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TODO, // TEmitted\n TODO // TMeta\n > {\n target: string;\n}\n\nexport type AnyTransitionConfig = TransitionConfig<\n any, // TContext\n any, // TExpressionEvent\n any, // TEvent\n any, // TActor\n any, // TAction\n any, // TGuard\n any, // TDelay\n any, // TEmitted\n any // TMeta\n>;\n\nexport interface InvokeDefinition<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TActor extends ProvidedActor,\n TAction extends ParameterizedObject,\n TGuard extends ParameterizedObject,\n TDelay extends string,\n TEmitted extends EventObject,\n TMeta extends MetaObject\n> {\n id: string;\n\n systemId: string | undefined;\n /** The source of the actor logic to be invoked */\n src: AnyActorLogic | string;\n\n input?:\n | Mapper<TContext, TEvent, NonReducibleUnknown, TEvent>\n | NonReducibleUnknown;\n /**\n * The transition to take upon the invoked child machine reaching its final\n * top-level state.\n */\n onDone?:\n | string\n | SingleOrArray<\n TransitionConfig<\n TContext,\n DoneActorEvent<unknown>,\n TEvent,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted,\n TMeta\n >\n >;\n /**\n * The transition to take upon the invoked child machine sending an error\n * event.\n */\n onError?:\n | string\n | SingleOrArray<\n TransitionConfig<\n TContext,\n ErrorActorEvent,\n TEvent,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted,\n TMeta\n >\n >;\n\n onSnapshot?:\n | string\n | SingleOrArray<\n TransitionConfig<\n TContext,\n SnapshotEvent,\n TEvent,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted,\n TMeta\n >\n >;\n\n toJSON: () => Omit<\n InvokeDefinition<\n TContext,\n TEvent,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted,\n TMeta\n >,\n 'onDone' | 'onError' | 'toJSON'\n >;\n}\n\ntype Delay<TDelay extends string> = TDelay | number;\n\nexport type DelayedTransitions<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TActor extends ProvidedActor,\n TAction extends ParameterizedObject,\n TGuard extends ParameterizedObject,\n TDelay extends string\n> = {\n [K in Delay<TDelay>]?:\n | string\n | SingleOrArray<\n TransitionConfig<\n TContext,\n TEvent,\n TEvent,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TODO, // TEmitted\n TODO // TMeta\n >\n >;\n};\n\nexport type StateTypes =\n | 'atomic'\n | 'compound'\n | 'parallel'\n | 'final'\n | 'history'\n | ({} & string);\n\nexport type SingleOrArray<T> = readonly T[] | T;\n\nexport type StateNodesConfig<\n TContext extends MachineContext,\n TEvent extends EventObject\n> = {\n [K in string]: StateNode<TContext, TEvent>;\n};\n\nexport type StatesConfig<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TActor extends ProvidedActor,\n TAction extends ParameterizedObject,\n TGuard extends ParameterizedObject,\n TDelay extends string,\n TTag extends string,\n TOutput,\n TEmitted extends EventObject,\n TMeta extends MetaObject\n> = {\n [K in string]: StateNodeConfig<\n TContext,\n TEvent,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TTag,\n TOutput,\n TEmitted,\n TMeta\n >;\n};\n\nexport type StatesDefinition<\n TContext extends MachineContext,\n TEvent extends EventObject\n> = {\n [K in string]: StateNodeDefinition<TContext, TEvent>;\n};\n\nexport type TransitionConfigTarget = string | undefined;\n\nexport type TransitionConfigOrTarget<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TEvent extends EventObject,\n TActor extends ProvidedActor,\n TAction extends ParameterizedObject,\n TGuard extends ParameterizedObject,\n TDelay extends string,\n TEmitted extends EventObject,\n TMeta extends MetaObject\n> = SingleOrArray<\n | TransitionConfigTarget\n | TransitionConfig<\n TContext,\n TExpressionEvent,\n TEvent,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted,\n TMeta\n >\n>;\n\nexport type TransitionsConfig<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TActor extends ProvidedActor,\n TAction extends ParameterizedObject,\n TGuard extends ParameterizedObject,\n TDelay extends string,\n TEmitted extends EventObject,\n TMeta extends MetaObject\n> = {\n [K in EventDescriptor<TEvent>]?: TransitionConfigOrTarget<\n TContext,\n ExtractEvent<TEvent, K>,\n TEvent,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted,\n TMeta\n >;\n};\n\ntype PartialEventDescriptor<TEventType extends string> =\n TEventType extends `${infer TLeading}.${infer TTail}`\n ? `${TLeading}.*` | `${TLeading}.${PartialEventDescriptor<TTail>}`\n : never;\n\nexport type EventDescriptor<TEvent extends EventObject> =\n | TEvent['type']\n | PartialEventDescriptor<TEvent['type']>\n | '*';\n\ntype NormalizeDescriptor<TDescriptor extends string> = TDescriptor extends '*'\n ? string\n : TDescriptor extends `${infer TLeading}.*`\n ? `${TLeading}.${string}`\n : TDescriptor;\n\nexport type IsLiteralString<T extends string> = string extends T ? false : true;\n\ntype DistributeActors<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TActor extends ProvidedActor,\n TAction extends ParameterizedObject,\n TGuard extends ParameterizedObject,\n TDelay extends string,\n TEmitted extends EventObject,\n TMeta extends MetaObject,\n TSpecificActor extends ProvidedActor\n> = TSpecificActor extends { src: infer TSrc }\n ?\n | Compute<\n {\n systemId?: string;\n /** The source of the machine to be invoked, or the machine itself. */\n src: TSrc;\n\n /**\n * The unique identifier for the invoked machine. If not specified,\n * this will be the machine's own `id`, or the URL (from `src`).\n */\n id?: TSpecificActor['id'];\n\n // TODO: currently we do not enforce required inputs here\n // in a sense, we shouldn't - they could be provided within the `implementations` object\n // how do we verify if the required input has been provided?\n input?:\n | Mapper<\n TContext,\n TEvent,\n InputFrom<TSpecificActor['logic']>,\n TEvent\n >\n | InputFrom<TSpecificActor['logic']>;\n /**\n * The transition to take upon the invoked child machine reaching\n * its final top-level state.\n */\n onDone?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n DoneActorEvent<OutputFrom<TSpecificActor['logic']>>,\n TEvent,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted,\n TMeta\n >\n >;\n /**\n * The transition to take upon the invoked child machine sending an\n * error event.\n */\n onError?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n ErrorActorEvent,\n TEvent,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted,\n TMeta\n >\n >;\n\n onSnapshot?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n SnapshotEvent<SnapshotFrom<TSpecificActor['logic']>>,\n TEvent,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted,\n TMeta\n >\n >;\n } & { [K in RequiredActorOptions<TSpecificActor>]: unknown }\n >\n | {\n id?: never;\n systemId?: string;\n src: AnyActorLogic;\n input?:\n | Mapper<TContext, TEvent, NonReducibleUnknown, TEvent>\n | NonReducibleUnknown;\n onDone?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n DoneActorEvent<unknown>,\n TEvent,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted,\n TMeta\n >\n >;\n onError?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n ErrorActorEvent,\n TEvent,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted,\n TMeta\n >\n >;\n\n onSnapshot?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n SnapshotEvent,\n TEvent,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted,\n TMeta\n >\n >;\n }\n : never;\n\nexport type InvokeConfig<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TActor extends ProvidedActor,\n TAction extends ParameterizedObject,\n TGuard extends ParameterizedObject,\n TDelay extends string,\n TEmitted extends EventObject,\n TMeta extends MetaObject\n> =\n IsLiteralString<TActor['src']> extends true\n ? DistributeActors<\n TContext,\n TEvent,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted,\n TMeta,\n TActor\n >\n : {\n /**\n * The unique identifier for the invoked machine. If not specified, this\n * will be the machine's own `id`, or the URL (from `src`).\n */\n id?: string;\n\n systemId?: string;\n /** The source of the machine to be invoked, or the machine itself. */\n src: AnyActorLogic | string; // TODO: fix types\n\n input?:\n | Mapper<TContext, TEvent, NonReducibleUnknown, TEvent>\n | NonReducibleUnknown;\n /**\n * The transition to take upon the invoked child machine reaching its\n * final top-level state.\n */\n onDone?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n DoneActorEvent<any>, // TODO: consider replacing with `unknown`\n TEvent,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted,\n TMeta\n >\n >;\n /**\n * The transition to take upon the invoked child machine sending an\n * error event.\n */\n onError?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n ErrorActorEvent,\n TEvent,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted,\n TMeta\n >\n >;\n\n onSnapshot?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n SnapshotEvent,\n TEvent,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted,\n TMeta\n >\n >;\n };\n\nexport type AnyInvokeConfig = InvokeConfig<\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any // TMeta\n>;\n\nexport interface StateNodeConfig<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TActor extends ProvidedActor,\n TAction extends ParameterizedObject,\n TGuard extends ParameterizedObject,\n TDelay extends string,\n TTag extends string,\n _TOutput,\n TEmitted extends EventObject,\n TMeta extends MetaObject\n> {\n /** The initial state transition. */\n initial?:\n | InitialTransitionConfig<TContext, TEvent, TActor, TAction, TGuard, TDelay>\n | string\n | undefined;\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 * - `'final'` - final state node\n */\n type?: 'atomic' | 'compound' | 'parallel' | 'final' | 'history';\n /**\n * Indicates whether the state node is a history state node, and what type of\n * history: shallow, deep, true (shallow), false (none), undefined (none)\n */\n history?: 'shallow' | 'deep' | boolean | undefined;\n /**\n * The mapping of state node keys to their state node configurations\n * (recursive).\n */\n states?:\n | StatesConfig<\n TContext,\n TEvent,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TTag,\n NonReducibleUnknown,\n TEmitted,\n TMeta\n >\n | undefined;\n /**\n * The services to invoke upon entering this state node. These services will\n * be stopped upon exiting this state node.\n */\n invoke?: SingleOrArray<\n InvokeConfig<\n TContext,\n TEvent,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted,\n TMeta\n >\n >;\n /** The mapping of event types to their potential transition(s). */\n on?: TransitionsConfig<\n TContext,\n TEvent,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted,\n TMeta\n >;\n /** The action(s) to be executed upon entering the state node. */\n entry?: Actions<\n TContext,\n TEvent,\n TEvent,\n undefined,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted\n >;\n /** The action(s) to be executed upon exiting the state node. */\n exit?: Actions<\n TContext,\n TEvent,\n TEvent,\n undefined,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted\n >;\n /**\n * The potential transition(s) to be taken upon reaching a final child state\n * node.\n *\n * This is equivalent to defining a `[done(id)]` transition on this state\n * node's `on` property.\n */\n onDone?:\n | string\n | SingleOrArray<\n TransitionConfig<\n TContext,\n DoneStateEvent,\n TEvent,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted,\n TMeta\n >\n >\n | undefined;\n /**\n * The mapping (or array) of delays (in milliseconds) to their potential\n * transition(s). The delayed transitions are taken after the specified delay\n * in an interpreter.\n */\n after?: DelayedTransitions<TContext, TEvent, TActor, TAction, TGuard, TDelay>;\n\n /**\n * An eventless transition that is always taken when this state node is\n * active.\n */\n always?: TransitionConfigOrTarget<\n TContext,\n TEvent,\n TEvent,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted,\n TMeta\n >;\n parent?: StateNode<TContext, TEvent>;\n /**\n * The meta data associated with this state node, which will be returned in\n * State instances.\n */\n meta?: TMeta;\n /**\n * The output data sent with the \"xstate.done.state._id_\" event if this is a\n * final state node.\n *\n * The output data will be evaluated with the current `context` and placed on\n * the `.data` property of the event.\n */\n output?: Mapper<TContext, TEvent, unknown, TEvent> | NonReducibleUnknown;\n /**\n * The unique ID of the state node, which can be referenced as a transition\n * target via the `#id` syntax.\n */\n id?: string | undefined;\n /**\n * The order this state node appears. Corresponds to the implicit document\n * order.\n */\n order?: number;\n\n /**\n * The tags for this state node, which are accumulated into the `state.tags`\n * property.\n */\n tags?: SingleOrArray<TTag>;\n /** A text description of the state node */\n description?: string;\n\n /** A default target for a history state */\n target?: string | undefined; // `| undefined` makes `HistoryStateNodeConfig` compatible with this interface (it extends it) under `exactOptionalPropertyTypes`\n}\n\nexport type AnyStateNodeConfig = StateNodeConfig<\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any, // emitted\n any // meta\n>;\n\nexport interface StateNodeDefinition<\n TContext extends MachineContext,\n TEvent extends EventObject\n> {\n id: string;\n version?: string | undefined;\n key: string;\n type: 'atomic' | 'compound' | 'parallel' | 'final' | 'history';\n initial: InitialTransitionDefinition<TContext, TEvent> | undefined;\n history: boolean | 'shallow' | 'deep' | undefined;\n states: StatesDefinition<TContext, TEvent>;\n on: TransitionDefinitionMap<TContext, TEvent>;\n transitions: Array<TransitionDefinition<TContext, TEvent>>;\n // TODO: establish what a definition really is\n entry: UnknownAction[];\n exit: UnknownAction[];\n meta: any;\n order: number;\n output?: StateNodeConfig<\n TContext,\n TEvent,\n ProvidedActor,\n ParameterizedObject,\n ParameterizedObject,\n string,\n string,\n unknown,\n EventObject, // TEmitted\n any // TMeta\n >['output'];\n invoke: Array<\n InvokeDefinition<\n TContext,\n TEvent,\n TODO,\n TODO,\n TODO,\n TODO,\n TODO, // TEmitted\n TODO // TMeta\n >\n >;\n description?: string;\n tags: string[];\n}\n\nexport interface StateMachineDefinition<\n TContext extends MachineContext,\n TEvent extends EventObject\n> extends StateNodeDefinition<TContext, TEvent> {}\n\nexport type AnyStateNode = StateNode<any, any>;\n\nexport type AnyStateNodeDefinition = StateNodeDefinition<any, any>;\n\nexport type AnyMachineSnapshot = MachineSnapshot<\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any\n>;\n\n/** @deprecated Use `AnyMachineSnapshot` instead */\nexport type AnyState = AnyMachineSnapshot;\n\nexport type AnyStateMachine = StateMachine<\n any, // context\n any, // event\n any, // children\n any, // actor\n any, // action\n any, // guard\n any, // delay\n any, // state value\n any, // tag\n any, // input\n any, // output\n any, // emitted\n any, // TMeta\n any // TStateSchema\n>;\n\nexport type AnyStateConfig = StateConfig<any, AnyEventObject>;\n\nexport interface AtomicStateNodeConfig<\n TContext extends MachineContext,\n TEvent extends EventObject\n> extends StateNodeConfig<\n TContext,\n TEvent,\n TODO,\n TODO,\n TODO,\n TODO,\n TODO,\n TODO,\n TODO, // emitted\n TODO // meta\n > {\n initial?: undefined;\n parallel?: false | undefined;\n states?: undefined;\n onDone?: undefined;\n}\n\nexport interface HistoryStateNodeConfig<\n TContext extends MachineContext,\n TEvent extends EventObject\n> extends AtomicStateNodeConfig<TContext, TEvent> {\n history: 'shallow' | 'deep' | true;\n target: string | undefined;\n}\n\nexport type SimpleOrStateNodeConfig<\n TContext extends MachineContext,\n TEvent extends EventObject\n> =\n | AtomicStateNodeConfig<TContext, TEvent>\n | StateNodeConfig<\n TContext,\n TEvent,\n TODO,\n TODO,\n TODO,\n TODO,\n TODO,\n TODO,\n TODO, // emitted\n TODO // meta\n >;\n\nexport type ActionFunctionMap<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TActor extends ProvidedActor,\n TAction extends ParameterizedObject = ParameterizedObject,\n TGuard extends ParameterizedObject = ParameterizedObject,\n TDelay extends string = string,\n TEmitted extends EventObject = EventObject\n> = {\n [K in TAction['type']]?: ActionFunction<\n TContext,\n TEvent,\n TEvent,\n GetParameterizedParams<TAction extends { type: K } ? TAction : never>,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted\n >;\n};\n\ntype GuardMap<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TGuard extends ParameterizedObject\n> = {\n [K in TGuard['type']]?: GuardPredicate<\n TContext,\n TEvent,\n GetParameterizedParams<TGuard extends { type: K } ? TGuard : never>,\n TGuard\n >;\n};\n\nexport type DelayFunctionMap<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TAction extends ParameterizedObject\n> = Record<string, DelayConfig<TContext, TEvent, TAction['params'], TEvent>>;\n\nexport type DelayConfig<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject\n> = number | DelayExpr<TContext, TExpressionEvent, TParams, TEvent>;\n\n// TODO: possibly refactor this somehow, use even a simpler type, and maybe even make `machine.options` private or something\n/** @ignore */\nexport interface MachineImplementationsSimplified<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TActor extends ProvidedActor = ProvidedActor,\n TAction extends ParameterizedObject = ParameterizedObject,\n TGuard extends ParameterizedObject = ParameterizedObject\n> {\n guards: GuardMap<TContext, TEvent, TGuard>;\n actions: ActionFunctionMap<TContext, TEvent, TActor, TAction>;\n actors: Record<\n string,\n | AnyActorLogic\n | {\n src: AnyActorLogic;\n input: Mapper<TContext, TEvent, unknown, TEvent> | NonReducibleUnknown;\n }\n >;\n delays: DelayFunctionMap<TContext, TEvent, TAction>;\n}\n\ntype MachineImplementationsActions<TTypes extends StateMachineTypes> = {\n [K in TTypes['actions']['type']]?: ActionFunction<\n TTypes['context'],\n TTypes['events'],\n TTypes['events'],\n GetConcreteByKey<TTypes['actions'], 'type', K>['params'],\n TTypes['actors'],\n TTypes['actions'],\n TTypes['guards'],\n TTypes['delays'],\n TTypes['emitted']\n >;\n};\n\ntype MachineImplementationsActors<TTypes extends StateMachineTypes> = {\n [K in TTypes['actors']['src']]?: GetConcreteByKey<\n TTypes['actors'],\n 'src',\n K\n >['logic'];\n};\n\ntype MachineImplementationsDelays<TTypes extends StateMachineTypes> = {\n [K in TTypes['delays']]?: DelayConfig<\n TTypes['context'],\n TTypes['events'],\n // delays in referenced send actions might use specific `TAction`\n // delays executed by auto-generated send actions related to after transitions won't have that\n // since they are effectively implicit inline actions\n undefined,\n TTypes['events']\n >;\n};\n\ntype MachineImplementationsGuards<TTypes extends StateMachineTypes> = {\n [K in TTypes['guards']['type']]?: Guard<\n TTypes['context'],\n TTypes['events'],\n GetConcreteByKey<TTypes['guards'], 'type', K>['params'],\n TTypes['guards']\n >;\n};\n\nexport type InternalMachineImplementations<TTypes extends StateMachineTypes> = {\n actions?: MachineImplementationsActions<TTypes>;\n actors?: MachineImplementationsActors<TTypes>;\n delays?: MachineImplementationsDelays<TTypes>;\n guards?: MachineImplementationsGuards<TTypes>;\n};\n\ntype InitialContext<\n TContext extends MachineContext,\n TActor extends ProvidedActor,\n TInput,\n TEvent extends EventObject\n> = TContext | ContextFactory<TContext, TActor, TInput, TEvent>;\n\nexport type ContextFactory<\n TContext extends MachineContext,\n TActor extends ProvidedActor,\n TInput,\n TEvent extends EventObject = EventObject\n> = ({\n spawn,\n input,\n self\n}: {\n spawn: Spawner<TActor>;\n input: TInput;\n self: ActorRef<\n MachineSnapshot<\n TContext,\n TEvent,\n Record<string, AnyActorRef | undefined>, // TODO: this should be replaced with `TChildren`\n StateValue,\n string,\n unknown,\n TODO, // TMeta\n TODO // State schema\n >,\n TEvent,\n AnyEventObject\n >;\n}) => TContext;\n\nexport type MachineConfig<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TActor extends ProvidedActor = ProvidedActor,\n TAction extends ParameterizedObject = ParameterizedObject,\n TGuard extends ParameterizedObject = ParameterizedObject,\n TDelay extends string = string,\n TTag extends string = string,\n TInput = any,\n TOutput = unknown,\n TEmitted extends EventObject = EventObject,\n TMeta extends MetaObject = MetaObject\n> = (Omit<\n StateNodeConfig<\n DoNotInfer<TContext>,\n DoNotInfer<TEvent>,\n DoNotInfer<TActor>,\n DoNotInfer<TAction>,\n DoNotInfer<TGuard>,\n DoNotInfer<TDelay>,\n DoNotInfer<TTag>,\n DoNotInfer<TOutput>,\n DoNotInfer<TEmitted>,\n DoNotInfer<TMeta>\n >,\n 'output'\n> & {\n /** The initial context (extended state) */\n /** The machine's own version. */\n version?: string;\n // TODO: make it conditionally required\n output?: Mapper<TContext, DoneStateEvent, TOutput, TEvent> | TOutput;\n}) &\n (MachineContext extends TContext\n ? { context?: InitialContext<LowInfer<TContext>, TActor, TInput, TEvent> }\n : { context: InitialContext<LowInfer<TContext>, TActor, TInput, TEvent> });\n\nexport type UnknownMachineConfig = MachineConfig<MachineContext, EventObject>;\n\nexport interface ProvidedActor {\n src: string;\n logic: UnknownActorLogic;\n id?: string | undefined; // `| undefined` is required here for compatibility with `exactOptionalPropertyTypes`, see #4613\n}\n\nexport interface SetupTypes<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildrenMap extends Record<string, string>,\n TTag extends string,\n TInput,\n TOutput,\n TEmitted extends EventObject,\n TMeta extends MetaObject\n> {\n context?: TContext;\n events?: TEvent;\n children?: TChildrenMap;\n tags?: TTag;\n input?: TInput;\n output?: TOutput;\n emitted?: TEmitted;\n meta?: TMeta;\n}\n\nexport interface MachineTypes<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TActor extends ProvidedActor,\n TAction extends ParameterizedObject,\n TGuard extends ParameterizedObject,\n TDelay extends string,\n TTag extends string,\n TInput,\n TOutput,\n TEmitted extends EventObject,\n TMeta extends MetaObject\n> extends SetupTypes<\n TContext,\n TEvent,\n // in machine types we currently don't support `TChildren`\n // and IDs can still be configured through `TActor['id']`\n never,\n TTag,\n TInput,\n TOutput,\n TEmitted,\n TMeta\n > {\n actors?: TActor;\n actions?: TAction;\n guards?: TGuard;\n delays?: TDelay;\n meta?: TMeta;\n}\n\nexport interface HistoryStateNode<TContext extends MachineContext>\n extends StateNode<TContext> {\n history: 'shallow' | 'deep';\n target: string | undefined;\n}\n\nexport type HistoryValue<\n TContext extends MachineContext,\n TEvent extends EventObject\n> = Record<string, Array<StateNode<TContext, TEvent>>>;\n\nexport type PersistedHistoryValue = Record<string, Array<{ id: string }>>;\n\nexport type AnyHistoryValue = HistoryValue<any, any>;\n\nexport type StateFrom<\n T extends AnyStateMachine | ((...args: any[]) => AnyStateMachine)\n> = T extends AnyStateMachine\n ? ReturnType<T['transition']>\n : T extends (...args: any[]) => AnyStateMachine\n ? ReturnType<ReturnType<T>['transition']>\n : never;\n\nexport type Transitions<\n TContext extends MachineContext,\n TEvent extends EventObject\n> = Array<TransitionDefinition<TContext, TEvent>>;\n\nexport interface DoneActorEvent<TOutput = unknown, TId extends string = string>\n extends EventObject {\n type: `xstate.done.actor.${TId}`;\n output: TOutput;\n actorId: TId;\n}\n\nexport interface ErrorActorEvent<\n TErrorData = unknown,\n TId extends string = string\n> extends EventObject {\n type: `xstate.error.actor.${TId}`;\n error: TErrorData;\n actorId: TId;\n}\n\nexport interface SnapshotEvent<\n TSnapshot extends Snapshot<unknown> = Snapshot<unknown>\n> extends EventObject {\n type: `xstate.snapshot.${string}`;\n snapshot: TSnapshot;\n}\n\nexport interface DoneStateEvent<TOutput = unknown> extends EventObject {\n type: `xstate.done.state.${string}`;\n output: TOutput;\n}\n\nexport type DelayExpr<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject\n> = (\n args: ActionArgs<TContext, TExpressionEvent, TEvent>,\n params: TParams\n) => number;\n\nexport type LogExpr<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject\n> = (\n args: ActionArgs<TContext, TExpressionEvent, TEvent>,\n params: TParams\n) => unknown;\n\nexport type SendExpr<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TSentEvent extends EventObject,\n TEvent extends EventObject\n> = (\n args: ActionArgs<TContext, TExpressionEvent, TEvent>,\n params: TParams\n) => TSentEvent;\n\nexport enum SpecialTargets {\n Parent = '#_parent',\n Internal = '#_internal'\n}\n\nexport interface SendToActionOptions<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject,\n TDelay extends string\n> extends RaiseActionOptions<\n TContext,\n TExpressionEvent,\n TParams,\n TEvent,\n TDelay\n > {}\n\nexport interface RaiseActionOptions<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject,\n TDelay extends string\n> {\n id?: string;\n delay?:\n | Delay<TDelay>\n | DelayExpr<TContext, TExpressionEvent, TParams, TEvent>;\n}\n\nexport interface RaiseActionParams<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject,\n TDelay extends string\n> extends RaiseActionOptions<\n TContext,\n TExpressionEvent,\n TParams,\n TEvent,\n TDelay\n > {\n event: TEvent | SendExpr<TContext, TExpressionEvent, TParams, TEvent, TEvent>;\n}\n\nexport interface SendToActionParams<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TSentEvent extends EventObject,\n TEvent extends EventObject,\n TDelay extends string\n> extends SendToActionOptions<\n TContext,\n TExpressionEvent,\n TParams,\n TEvent,\n TDelay\n > {\n event:\n | TSentEvent\n | SendExpr<TContext, TExpressionEvent, TParams, TSentEvent, TEvent>;\n}\n\nexport type Assigner<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject,\n TActor extends ProvidedActor\n> = (\n args: AssignArgs<TContext, TExpressionEvent, TEvent, TActor>,\n params: TParams\n) => Partial<TContext>;\n\nexport type PartialAssigner<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject,\n TActor extends ProvidedActor,\n TKey extends keyof TContext\n> = (\n args: AssignArgs<TContext, TExpressionEvent, TEvent, TActor>,\n params: TParams\n) => TContext[TKey];\n\nexport type PropertyAssigner<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject,\n TActor extends ProvidedActor\n> = {\n [K in keyof TContext]?:\n | PartialAssigner<TContext, TExpressionEvent, TParams, TEvent, TActor, K>\n | TContext[K];\n};\n\nexport type Mapper<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TResult,\n TEvent extends EventObject\n> = (args: {\n context: TContext;\n event: TExpressionEvent;\n self: ActorRef<\n MachineSnapshot<\n TContext,\n TEvent,\n Record<string, AnyActorRef>, // TODO: this should be replaced with `TChildren`\n StateValue,\n string,\n unknown,\n TODO, // TMeta\n TODO // State schema\n >,\n TEvent,\n AnyEventObject\n >;\n}) => TResult;\n\nexport interface TransitionDefinition<\n TContext extends MachineContext,\n TEvent extends EventObject\n> extends Omit<\n TransitionConfig<\n TContext,\n TEvent,\n TEvent,\n TODO,\n TODO,\n TODO,\n TODO,\n TODO, // TEmitted\n TODO // TMeta\n >,\n | 'target'\n // `guard` is correctly rejected by `extends` here and `actions` should be too\n // however, `any` passed to `TransitionConfig` as `TAction` collapses its `.actions` to `any` and it's accidentally allowed here\n // it doesn't exactly have to be incorrect, we are overriding this here anyway but it looks like a lucky accident rather than smth done on purpose\n | 'guard'\n > {\n target: ReadonlyArray<StateNode<TContext, TEvent>> | undefined;\n source: StateNode<TContext, TEvent>;\n actions: readonly UnknownAction[];\n reenter: boolean;\n guard?: UnknownGuard;\n eventType: EventDescriptor<TEvent>;\n toJSON: () => {\n target: string[] | undefined;\n source: string;\n actions: readonly UnknownAction[];\n guard?: UnknownGuard;\n eventType: EventDescriptor<TEvent>;\n meta?: Record<string, any>;\n };\n}\n\nexport type AnyTransitionDefinition = TransitionDefinition<any, any>;\n\nexport interface InitialTransitionDefinition<\n TContext extends MachineContext,\n TEvent extends EventObject\n> extends TransitionDefinition<TContext, TEvent> {\n target: ReadonlyArray<StateNode<TContext, TEvent>>;\n guard?: never;\n}\n\nexport type TransitionDefinitionMap<\n TContext extends MachineContext,\n TEvent extends EventObject\n> = {\n [K in EventDescriptor<TEvent>]: Array<\n TransitionDefinition<TContext, ExtractEvent<TEvent, K>>\n >;\n};\n\nexport interface DelayedTransitionDefinition<\n TContext extends MachineContext,\n TEvent extends EventObject\n> extends TransitionDefinition<TContext, TEvent> {\n delay: number | string | DelayExpr<TContext, TEvent, undefined, TEvent>;\n}\n\nexport interface StateLike<TContext extends MachineContext> {\n value: StateValue;\n context: TContext;\n event: EventObject;\n}\n\nexport interface StateConfig<\n TContext extends MachineContext,\n TEvent extends EventObject\n> {\n context: TContext;\n historyValue?: HistoryValue<TContext, TEvent>;\n /** @internal */\n _nodes: Array<StateNode<TContext, TEvent>>;\n children: Record<string, AnyActorRef>;\n status: SnapshotStatus;\n output?: any;\n error?: unknown;\n machine?: StateMachine<\n TContext,\n TEvent,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any, // TMeta\n any // TStateSchema\n >;\n}\n\nexport interface ActorOptions<TLogic extends AnyActorLogic> {\n /**\n * The clock that is responsible for setting and clearing timeouts, such as\n * delayed events and transitions.\n *\n * @remarks\n * You can create your own “clock”. The clock interface is an object with two\n * functions/methods:\n *\n * - `setTimeout` - same arguments as `window.setTimeout(fn, timeout)`\n * - `clearTimeout` - same arguments as `window.clearTimeout(id)`\n *\n * By default, the native `setTimeout` and `clearTimeout` functions are used.\n *\n * For testing, XState provides `SimulatedClock`.\n * @see {@link Clock}\n * @see {@link SimulatedClock}\n */\n clock?: Clock;\n /**\n * Specifies the logger to be used for `log(...)` actions. Defaults to the\n * native `console.log(...)` method.\n */\n logger?: (...args: any[]) => void;\n parent?: AnyActorRef;\n /** @internal */\n syncSnapshot?: boolean;\n /** The custom `id` for referencing this service. */\n id?: string;\n /** @deprecated Use `inspect` instead. */\n devTools?: never;\n\n /** The system ID to register this actor under. */\n systemId?: string;\n /** The input data to pass to the actor. */\n input?: InputFrom<TLogic>;\n\n /**\n * Initializes actor logic from a specific persisted internal state.\n *\n * @remarks\n * If the state is compatible with the actor logic, when the actor is started\n * it will be at that persisted state. Actions from machine actors will not be\n * re-executed, because they are assumed to have been already executed.\n * However, invocations will be restarted, and spawned actors will be restored\n * recursively.\n *\n * Can be generated with {@link Actor.getPersistedSnapshot}.\n * @see https://stately.ai/docs/persistence\n */\n snapshot?: Snapshot<unknown>;\n\n /** @deprecated Use `snapshot` instead. */\n state?: Snapshot<unknown>;\n\n /** The source actor logic. */\n src?: string | AnyActorLogic;\n\n /**\n * A callback function or observer object which can be used to inspect actor\n * system updates.\n *\n * @remarks\n * If a callback function is provided, it can accept an inspection event\n * argument. The types of inspection events that can be observed include:\n *\n * - `@xstate.actor` - An actor ref has been created in the system\n * - `@xstate.event` - An event was sent from a source actor ref to a target\n * actor ref in the system\n * - `@xstate.snapshot` - An actor ref emitted a snapshot due to a received\n * event\n *\n * @example\n *\n * ```ts\n * import { createMachine } from 'xstate';\n *\n * const machine = createMachine({\n * // ...\n * });\n *\n * const actor = createActor(machine, {\n * inspect: (inspectionEvent) => {\n * if (inspectionEvent.actorRef === actor) {\n * // This event is for the root actor\n * }\n *\n * if (inspectionEvent.type === '@xstate.actor') {\n * console.log(inspectionEvent.actorRef);\n * }\n *\n * if (inspectionEvent.type === '@xstate.event') {\n * console.log(inspectionEvent.sourceRef);\n * console.log(inspectionEvent.actorRef);\n * console.log(inspectionEvent.event);\n * }\n *\n * if (inspectionEvent.type === '@xstate.snapshot') {\n * console.log(inspectionEvent.actorRef);\n * console.log(inspectionEvent.event);\n * console.log(inspectionEvent.snapshot);\n * }\n * }\n * });\n * ```\n *\n * Alternately, an observer object (`{ next?, error?, complete? }`) can be\n * provided:\n *\n * @example\n *\n * ```ts\n * const actor = createActor(machine, {\n * inspect: {\n * next: (inspectionEvent) => {\n * if (inspectionEvent.actorRef === actor) {\n * // This event is for the root actor\n * }\n *\n * if (inspectionEvent.type === '@xstate.actor') {\n * console.log(inspectionEvent.actorRef);\n * }\n *\n * if (inspectionEvent.type === '@xstate.event') {\n * console.log(inspectionEvent.sourceRef);\n * console.log(inspectionEvent.actorRef);\n * console.log(inspectionEvent.event);\n * }\n *\n * if (inspectionEvent.type === '@xstate.snapshot') {\n * console.log(inspectionEvent.actorRef);\n * console.log(inspectionEvent.event);\n * console.log(inspectionEvent.snapshot);\n * }\n * }\n * }\n * });\n * ```\n */\n inspect?:\n | Observer<InspectionEvent>\n | ((inspectionEvent: InspectionEvent) => void);\n}\n\nexport type AnyActor = Actor<any>;\n\n/** @deprecated Use `AnyActor` instead. */\nexport type AnyInterpreter = AnyActor;\n\n// Based on RxJS types\nexport type Observer<T> = {\n next?: (value: T) => void;\n error?: (err: unknown) => void;\n complete?: () => void;\n};\n\nexport interface Subscription {\n unsubscribe(): void;\n}\n\nexport interface InteropObservable<T> {\n [Symbol.observable]: () => InteropSubscribable<T>;\n}\n\nexport interface InteropSubscribable<T> {\n subscribe(observer: Observer<T>): Subscription;\n}\n\nexport interface Subscribable<T> extends InteropSubscribable<T> {\n subscribe(observer: Observer<T>): Subscription;\n subscribe(\n next: (value: T) => void,\n error?: (error: any) => void,\n complete?: () => void\n ): Subscription;\n}\n\ntype EventDescriptorMatches<\n TEventType extends string,\n TNormalizedDescriptor\n> = TEventType extends TNormalizedDescriptor ? true : false;\n\nexport type ExtractEvent<\n TEvent extends EventObject,\n TDescriptor extends EventDescriptor<TEvent>\n> = string extends TEvent['type']\n ? TEvent\n : NormalizeDescriptor<TDescriptor> extends infer TNormalizedDescriptor\n ? TEvent extends any\n ? // true is the check type here to match both true and boolean\n true extends EventDescriptorMatches<\n TEvent['type'],\n TNormalizedDescriptor\n >\n ? TEvent\n : never\n : never\n : never;\n\nexport interface BaseActorRef<TEvent extends EventObject> {\n send: (event: TEvent) => void;\n}\n\nexport interface ActorLike<TCurrent, TEvent extends EventObject>\n extends Subscribable<TCurrent> {\n send: (event: TEvent) => void;\n}\n\nexport interface ActorRef<\n TSnapshot extends Snapshot<unknown>,\n TEvent extends EventObject,\n TEmitted extends EventObject = EventObject\n> extends Subscribable<TSnapshot>,\n InteropObservable<TSnapshot> {\n /** The unique identifier for this actor relative to its parent. */\n id: string;\n sessionId: string;\n /** @internal */\n _send: (event: TEvent) => void;\n send: (event: TEvent) => void;\n start: () => void;\n getSnapshot: () => TSnapshot;\n getPersistedSnapshot: () => Snapshot<unknown>;\n stop: () => void;\n toJSON?: () => any;\n // TODO: figure out how to hide this externally as `sendTo(ctx => ctx.actorRef._parent._parent._parent._parent)` shouldn't be allowed\n _parent?: AnyActorRef;\n system: AnyActorSystem;\n /** @internal */\n _processingStatus: ProcessingStatus;\n src: string | AnyActorLogic;\n // TODO: remove from ActorRef interface\n // (should only be available on Actor)\n on: <TType extends TEmitted['type'] | '*'>(\n type: TType,\n handler: (\n emitted: TEmitted & (TType extends '*' ? unknown : { type: TType })\n ) => void\n ) => Subscription;\n}\n\nexport type AnyActorRef = ActorRef<\n any,\n any, // TODO: shouldn't this be AnyEventObject?\n any\n>;\n\nexport type ActorRefLike = Pick<\n AnyActorRef,\n 'sessionId' | 'send' | 'getSnapshot'\n>;\n\nexport type UnknownActorRef = ActorRef<Snapshot<unknown>, EventObject>;\n\nexport type ActorLogicFrom<T> =\n ReturnTypeOrValue<T> extends infer R\n ? R extends StateMachine<\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, // TMeta\n any // TStateSchema\n >\n ? R\n : R extends Promise<infer U>\n ? PromiseActorLogic<U>\n : never\n : never;\n\n// TODO: in v6, this should only accept AnyActorLogic, like ActorRefFromLogic\nexport type ActorRefFrom<T> =\n ReturnTypeOrValue<T> extends infer R\n ? R extends StateMachine<\n infer TContext,\n infer TEvent,\n infer TChildren,\n infer _TActor,\n infer _TAction,\n infer _TGuard,\n infer _TDelay,\n infer TStateValue,\n infer TTag,\n infer _TInput,\n infer TOutput,\n infer TEmitted,\n infer TMeta,\n infer TStateSchema\n >\n ? ActorRef<\n MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TStateSchema\n >,\n TEvent,\n TEmitted\n >\n : R extends Promise<infer U>\n ? ActorRefFrom<PromiseActorLogic<U>>\n : R extends ActorLogic<\n infer TSnapshot,\n infer TEvent,\n infer _TInput,\n infer _TSystem,\n infer TEmitted\n >\n ? ActorRef<TSnapshot, TEvent, TEmitted>\n : never\n : never;\n\nexport type ActorRefFromLogic<T extends AnyActorLogic> = ActorRef<\n SnapshotFrom<T>,\n EventFromLogic<T>,\n EmittedFrom<T>\n>;\n\nexport type DevToolsAdapter = (service: AnyActor) => void;\n\n/** @deprecated Use `Actor<T>` instead. */\nexport type InterpreterFrom<\n T extends AnyStateMachine | ((...args: any[]) => AnyStateMachine)\n> =\n ReturnTypeOrValue<T> extends StateMachine<\n infer TContext,\n infer TEvent,\n infer TChildren,\n infer _TActor,\n infer _TAction,\n infer _TGuard,\n infer _TDelay,\n infer TStateValue,\n infer TTag,\n infer TInput,\n infer TOutput,\n infer TEmitted,\n infer TMeta,\n infer TStateSchema\n >\n ? Actor<\n ActorLogic<\n MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TStateSchema\n >,\n TEvent,\n TInput,\n AnyActorSystem,\n TEmitted\n >\n >\n : never;\n\nexport type MachineImplementationsFrom<\n T extends AnyStateMachine | ((...args: any[]) => AnyStateMachine)\n> =\n ReturnTypeOrValue<T> extends StateMachine<\n infer TContext,\n infer TEvent,\n infer _TChildren,\n infer TActor,\n infer TAction,\n infer TGuard,\n infer TDelay,\n infer _TStateValue,\n infer TTag,\n infer _TInput,\n infer _TOutput,\n infer TEmitted,\n infer _TMeta,\n infer _TStateSchema\n >\n ? InternalMachineImplementations<\n ResolvedStateMachineTypes<\n TContext,\n TEvent,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TTag,\n TEmitted\n >\n >\n : never;\n\nexport interface ActorScope<\n TSnapshot extends Snapshot<unknown>,\n TEvent extends EventObject,\n TSystem extends AnyActorSystem = AnyActorSystem,\n TEmitted extends EventObject = EventObject\n> {\n self: ActorRef<TSnapshot, TEvent, TEmitted>;\n id: string;\n sessionId: string;\n logger: (...args: any[]) => void;\n defer: (fn: () => void) => void;\n emit: (event: TEmitted) => void;\n system: TSystem;\n stopChild: (child: AnyActorRef) => void;\n actionExecutor: ActionExecutor;\n}\n\nexport type AnyActorScope = ActorScope<\n any, // TSnapshot\n any, // TEvent\n AnyActorSystem,\n any // TEmitted\n>;\n\nexport type SnapshotStatus = 'active' | 'done' | 'error' | 'stopped';\n\nexport type Snapshot<TOutput> =\n | {\n status: 'active';\n output: undefined;\n error: undefined;\n }\n | {\n status: 'done';\n output: TOutput;\n error: undefined;\n }\n | {\n status: 'error';\n output: undefined;\n error: unknown;\n }\n | {\n status: 'stopped';\n output: undefined;\n error: undefined;\n };\n\n/**\n * Represents logic which can be used by an actor.\n *\n * @template TSnapshot - The type of the snapshot.\n * @template TEvent - The type of the event object.\n * @template TInput - The type of the input.\n * @template TSystem - The type of the actor system.\n */\nexport interface ActorLogic<\n in out TSnapshot extends Snapshot<unknown>, // it's invariant because it's also part of `ActorScope[\"self\"][\"getSnapshot\"]`\n in out TEvent extends EventObject, // it's invariant because it's also part of `ActorScope[\"self\"][\"send\"]`\n in TInput = NonReducibleUnknown,\n TSystem extends AnyActorSystem = AnyActorSystem,\n in out TEmitted extends EventObject = EventObject // it's invariant because it's also aprt of `ActorScope[\"self\"][\"on\"]`\n> {\n /** The initial setup/configuration used to create the actor logic. */\n config?: unknown;\n /**\n * Transition function that processes the current state and an incoming event\n * to produce a new state.\n *\n * @param snapshot - The current state.\n * @param event - The incoming event.\n * @param actorScope - The actor scope.\n * @returns The new state.\n */\n transition: (\n snapshot: TSnapshot,\n event: TEvent,\n actorScope: ActorScope<TSnapshot, TEvent, TSystem, TEmitted>\n ) => TSnapshot;\n /**\n * Called to provide the initial state of the actor.\n *\n * @param actorScope - The actor scope.\n * @param input - The input for the initial state.\n * @returns The initial state.\n */\n getInitialSnapshot: (\n actorScope: ActorScope<TSnapshot, TEvent, TSystem, TEmitted>,\n input: TInput\n ) => TSnapshot;\n /**\n * Called when Actor is created to restore the internal state of the actor\n * given a persisted state. The persisted state can be created by\n * `getPersistedSnapshot`.\n *\n * @param persistedState - The persisted state to restore from.\n * @param actorScope - The actor scope.\n * @returns The restored state.\n */\n restoreSnapshot?: (\n persistedState: Snapshot<unknown>,\n actorScope: ActorScope<TSnapshot, TEvent, AnyActorSystem, TEmitted>\n ) => TSnapshot;\n /**\n * Called when the actor is started.\n *\n * @param snapshot - The starting state.\n * @param actorScope - The actor scope.\n */\n start?: (\n snapshot: TSnapshot,\n actorScope: ActorScope<TSnapshot, TEvent, AnyActorSystem, TEmitted>\n ) => void;\n /**\n * Obtains the internal state of the actor in a representation which can be be\n * persisted. The persisted state can be restored by `restoreSnapshot`.\n *\n * @param snapshot - The current state.\n * @returns The a representation of the internal state to be persisted.\n */\n getPersistedSnapshot: (\n snapshot: TSnapshot,\n options?: unknown\n ) => Snapshot<unknown>;\n}\n\nexport type AnyActorLogic = ActorLogic<\n any, // snapshot\n any, // event\n any, // input\n any, // system\n any // emitted\n>;\n\nexport type UnknownActorLogic = ActorLogic<\n any, // snapshot\n any, // event\n any, // input\n AnyActorSystem,\n any // emitted\n>;\n\nexport type SnapshotFrom<T> =\n ReturnTypeOrValue<T> extends infer R\n ? R extends ActorRef<infer TSnapshot, infer _, infer __>\n ? TSnapshot\n : R extends Actor<infer TLogic>\n ? SnapshotFrom<TLogic>\n : R extends ActorLogic<\n infer _TSnapshot,\n infer _TEvent,\n infer _TInput,\n infer _TEmitted,\n infer _TSystem\n >\n ? ReturnType<R['transition']>\n : R extends ActorScope<\n infer TSnapshot,\n infer _TEvent,\n infer _TEmitted,\n infer _TSystem\n >\n ? TSnapshot\n : never\n : never;\n\nexport type EventFromLogic<TLogic extends AnyActorLogic> =\n TLogic extends ActorLogic<\n infer _TSnapshot,\n infer TEvent,\n infer _TInput,\n infer _TEmitted,\n infer _TSystem\n >\n ? TEvent\n : never;\n\nexport type EmittedFrom<TLogic extends AnyActorLogic> =\n TLogic extends ActorLogic<\n infer _TSnapshot,\n infer _TEvent,\n infer _TInput,\n infer _TSystem,\n infer TEmitted\n >\n ? TEmitted\n : never;\n\ntype ResolveEventType<T> =\n ReturnTypeOrValue<T> extends infer R\n ? R extends StateMachine<\n infer _TContext,\n infer TEvent,\n infer _TChildren,\n infer _TActor,\n infer _TAction,\n infer _TGuard,\n infer _TDelay,\n infer _TStateValue,\n infer _TTag,\n infer _TInput,\n infer _TOutput,\n infer _TEmitted,\n infer _TMeta,\n infer _TStateSchema\n >\n ? TEvent\n : R extends MachineSnapshot<\n infer _TContext,\n infer TEvent,\n infer _TChildren,\n infer _TStateValue,\n infer _TTag,\n infer _TOutput,\n infer _TMeta,\n infer _TStateSchema\n >\n ? TEvent\n : R extends ActorRef<infer _TSnapshot, infer TEvent, infer _TEmitted>\n ? TEvent\n : never\n : never;\n\nexport type EventFrom<\n T,\n K extends Prop<TEvent, 'type'> = never,\n TEvent extends EventObject = ResolveEventType<T>\n> = IsNever<K> extends true ? TEvent : ExtractEvent<TEvent, K>;\n\nexport type ContextFrom<T> =\n ReturnTypeOrValue<T> extends infer R\n ? R extends StateMachine<\n infer TContext,\n infer _TEvent,\n infer _TChildren,\n infer _TActor,\n infer _TAction,\n infer _TGuard,\n infer _TDelay,\n infer _TStateValue,\n infer _TTag,\n infer _TInput,\n infer _TOutput,\n infer _TEmitted,\n infer _TMeta,\n infer _TStateSchema\n >\n ? TContext\n : R extends MachineSnapshot<\n infer TContext,\n infer _TEvent,\n infer _TChildren,\n infer _TStateValue,\n infer _TTag,\n infer _TOutput,\n infer _TMeta,\n infer _TStateSchema\n >\n ? TContext\n : R extends Actor<infer TActorLogic>\n ? TActorLogic extends StateMachine<\n infer TContext,\n infer _TEvent,\n infer _TChildren,\n infer _TActor,\n infer _TAction,\n infer _TGuard,\n infer _TDelay,\n infer _TStateValue,\n infer _TTag,\n infer _TInput,\n infer _TOutput,\n infer _TEmitted,\n infer _TMeta,\n infer _TStateSchema\n >\n ? TContext\n : never\n : never\n : never;\n\nexport type InferEvent<E extends EventObject> = {\n [T in E['type']]: { type: T } & Extract<E, { type: T }>;\n}[E['type']];\n\nexport type TODO = any;\n\nexport type StateValueFrom<TMachine extends AnyStateMachine> = Parameters<\n StateFrom<TMachine>['matches']\n>[0];\n\nexport type TagsFrom<TMachine extends AnyStateMachine> = Parameters<\n StateFrom<TMachine>['hasTag']\n>[0];\n\nexport interface ActorSystemInfo {\n actors: Record<string, AnyActorRef>;\n}\n\nexport type RequiredActorOptions<TActor extends ProvidedActor> =\n | (undefined extends TActor['id'] ? never : 'id')\n | (undefined extends InputFrom<TActor['logic']> ? never : 'input');\n\nexport type RequiredLogicInput<TLogic extends AnyActorLogic> =\n undefined extends InputFrom<TLogic> ? never : 'input';\n\ntype ExtractLiteralString<T extends string | undefined> = T extends string\n ? string extends T\n ? never\n : T\n : never;\n\ntype ToConcreteChildren<TActor extends ProvidedActor> = {\n [A in TActor as ExtractLiteralString<A['id']>]?: ActorRefFromLogic<\n A['logic']\n >;\n};\n\nexport type ToChildren<TActor extends ProvidedActor> =\n // only proceed further if all configured `src`s are literal strings\n string extends TActor['src']\n ? // TODO: replace `AnyActorRef` with `UnknownActorRef`~\n // or maybe even `TActor[\"logic\"]` since it's possible to configure `{ src: string; logic: SomeConcreteLogic }`\n // TODO: consider adding `| undefined` here\n Record<string, AnyActorRef>\n : Compute<\n ToConcreteChildren<TActor> &\n {\n include: {\n [id: string]: TActor extends any\n ? ActorRefFromLogic<TActor['logic']> | undefined\n : never;\n };\n exclude: unknown;\n }[undefined extends TActor['id'] // if not all actors have literal string IDs then we need to create an index signature containing all possible actor types\n ? 'include'\n : string extends TActor['id']\n ? 'include'\n : 'exclude']\n >;\n\nexport type StateSchema = {\n id?: string;\n states?: Record<string, StateSchema>;\n\n // Other types\n // Needed because TS treats objects with all optional properties as a \"weak\" object\n // https://github.com/statelyai/xstate/issues/5031\n type?: unknown;\n invoke?: unknown;\n on?: unknown;\n entry?: unknown;\n exit?: unknown;\n onDone?: unknown;\n after?: unknown;\n always?: unknown;\n meta?: unknown;\n output?: unknown;\n tags?: unknown;\n description?: unknown;\n};\n\nexport type StateId<\n TSchema extends StateSchema,\n TKey extends string = '(machine)',\n TParentKey extends string | null = null\n> =\n | (TSchema extends { id: string }\n ? TSchema['id']\n : TParentKey extends null\n ? TKey\n : `${TParentKey}.${TKey}`)\n | (TSchema['states'] extends Record<string, any>\n ? Values<{\n [K in keyof TSchema['states'] & string]: StateId<\n TSchema['states'][K],\n K,\n TParentKey extends string\n ? `${TParentKey}.${TKey}`\n : TSchema['id'] extends string\n ? TSchema['id']\n : TKey\n >;\n }>\n : never);\n\nexport interface StateMachineTypes {\n context: MachineContext;\n events: EventObject;\n actors: ProvidedActor;\n actions: ParameterizedObject;\n guards: ParameterizedObject;\n delays: string;\n tags: string;\n emitted: EventObject;\n}\n\n/** @deprecated */\nexport interface ResolvedStateMachineTypes<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TActor extends ProvidedActor,\n TAction extends ParameterizedObject,\n TGuard extends ParameterizedObject,\n TDelay extends string,\n TTag extends string,\n TEmitted extends EventObject = EventObject\n> {\n context: TContext;\n events: TEvent;\n actors: TActor;\n actions: TAction;\n guards: TGuard;\n delays: TDelay;\n tags: TTag;\n emitted: TEmitted;\n}\n\nexport type GetConcreteByKey<\n T,\n TKey extends keyof T,\n TValue extends T[TKey]\n> = T & Record<TKey, TValue>;\n\ntype _GroupStateKeys<\n T extends StateSchema,\n S extends keyof T['states']\n> = S extends any\n ? T['states'][S] extends { type: 'history' }\n ? [never, never]\n : T extends { type: 'parallel' }\n ? [S, never]\n : 'states' extends keyof T['states'][S]\n ? [S, never]\n : [never, S]\n : never;\n\ntype GroupStateKeys<T extends StateSchema, S extends keyof T['states']> = {\n nonLeaf: _GroupStateKeys<T, S & string>[0];\n leaf: _GroupStateKeys<T, S & string>[1];\n};\n\nexport type ToStateValue<T extends StateSchema> = T extends {\n states: Record<infer S, any>;\n}\n ? IsNever<S> extends true\n ? {}\n :\n | GroupStateKeys<T, S>['leaf']\n | (IsNever<GroupStateKeys<T, S>['nonLeaf']> extends false\n ? T extends { type: 'parallel' }\n ? {\n [K in GroupStateKeys<T, S>['nonLeaf']]: ToStateValue<\n T['states'][K]\n >;\n }\n : Compute<\n Values<{\n [K in GroupStateKeys<T, S>['nonLeaf']]: {\n [StateKey in K]: ToStateValue<T['states'][K]>;\n };\n }>\n >\n : never)\n : {};\n\nexport interface ExecutableActionObject {\n type: string;\n info: ActionArgs<MachineContext, EventObject, EventObject>;\n params: NonReducibleUnknown;\n exec:\n | ((info: ActionArgs<any, any, any>, params: unknown) => void)\n | undefined;\n}\n\nexport interface ToExecutableAction<T extends ParameterizedObject>\n extends ExecutableActionObject {\n type: T['type'];\n params: T['params'];\n exec: undefined;\n}\n\nexport interface ExecutableSpawnAction extends ExecutableActionObject {\n type: 'xstate.spawnChild';\n info: ActionArgs<MachineContext, EventObject, EventObject>;\n params: {\n id: string;\n actorRef: AnyActorRef | undefined;\n src: string | AnyActorLogic;\n };\n}\n\n// TODO: cover all that can be actually returned\nexport type SpecialExecutableAction =\n | ExecutableSpawnAction\n | ExecutableRaiseAction\n | ExecutableSendToAction;\n\nexport type ExecutableActionsFrom<T extends AnyActorLogic> =\n T extends StateMachine<\n infer _TContext,\n infer _TEvent,\n infer _TChildren,\n infer _TActor,\n infer TAction,\n infer _TGuard,\n infer _TDelay,\n infer _TStateValue,\n infer _TTag,\n infer _TInput,\n infer _TOutput,\n infer _TEmitted,\n infer _TMeta,\n infer _TConfig\n >\n ?\n | SpecialExecutableAction\n | (string extends TAction['type'] ? never : ToExecutableAction<TAction>)\n : never;\n\nexport type ActionExecutor = (actionToExecute: ExecutableActionObject) => void;\n\nexport type BuiltinActionResolution = [\n AnyMachineSnapshot,\n NonReducibleUnknown, // params\n UnknownAction[] | undefined\n];\n","import isDevelopment from '#is-development';\nimport { XSTATE_ERROR } from '../constants.ts';\nimport { createErrorActorEvent } from '../eventUtils.ts';\nimport { executingCustomAction } from '../createActor.ts';\nimport {\n ActionArgs,\n ActionFunction,\n AnyActorRef,\n AnyActorScope,\n AnyEventObject,\n AnyMachineSnapshot,\n Cast,\n DelayExpr,\n DoNotInfer,\n EventFrom,\n EventObject,\n ExecutableActionObject,\n InferEvent,\n MachineContext,\n ParameterizedObject,\n SendExpr,\n SendToActionOptions,\n BuiltinActionResolution,\n SpecialTargets,\n UnifiedArg\n} from '../types.ts';\n\nfunction resolveSendTo(\n actorScope: AnyActorScope,\n snapshot: AnyMachineSnapshot,\n args: ActionArgs<any, any, any>,\n actionParams: ParameterizedObject['params'] | undefined,\n {\n to,\n event: eventOrExpr,\n id,\n delay\n }: {\n to:\n | AnyActorRef\n | string\n | ((\n args: UnifiedArg<MachineContext, EventObject, EventObject>,\n params: ParameterizedObject['params'] | undefined\n ) => AnyActorRef | string);\n event:\n | EventObject\n | SendExpr<\n MachineContext,\n EventObject,\n ParameterizedObject['params'] | undefined,\n EventObject,\n EventObject\n >;\n id: string | undefined;\n delay:\n | string\n | number\n | DelayExpr<\n MachineContext,\n EventObject,\n ParameterizedObject['params'] | undefined,\n EventObject\n >\n | undefined;\n },\n extra: { deferredActorIds: string[] | undefined }\n): BuiltinActionResolution {\n const delaysMap = snapshot.machine.implementations.delays;\n\n if (typeof eventOrExpr === 'string') {\n throw new Error(\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `Only event objects may be used with sendTo; use sendTo({ type: \"${eventOrExpr}\" }) instead`\n );\n }\n const resolvedEvent =\n typeof eventOrExpr === 'function'\n ? eventOrExpr(args, actionParams)\n : eventOrExpr;\n\n let resolvedDelay: number | undefined;\n if (typeof delay === 'string') {\n const configDelay = delaysMap && delaysMap[delay];\n resolvedDelay =\n typeof configDelay === 'function'\n ? configDelay(args, actionParams)\n : configDelay;\n } else {\n resolvedDelay =\n typeof delay === 'function' ? delay(args, actionParams) : delay;\n }\n\n const resolvedTarget = typeof to === 'function' ? to(args, actionParams) : to;\n let targetActorRef: AnyActorRef | string | undefined;\n\n if (typeof resolvedTarget === 'string') {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison\n if (resolvedTarget === SpecialTargets.Parent) {\n targetActorRef = actorScope.self._parent;\n }\n // eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison\n else if (resolvedTarget === SpecialTargets.Internal) {\n targetActorRef = actorScope.self;\n } else if (resolvedTarget.startsWith('#_')) {\n // SCXML compatibility: https://www.w3.org/TR/scxml/#SCXMLEventProcessor\n // #_invokeid. If the target is the special term '#_invokeid', where invokeid is the invokeid of an SCXML session that the sending session has created by <invoke>, the Processor must add the event to the external queue of that session.\n targetActorRef = snapshot.children[resolvedTarget.slice(2)];\n } else {\n targetActorRef = extra.deferredActorIds?.includes(resolvedTarget)\n ? resolvedTarget\n : snapshot.children[resolvedTarget];\n }\n if (!targetActorRef) {\n throw new Error(\n `Unable to send event to actor '${resolvedTarget}' from machine '${snapshot.machine.id}'.`\n );\n }\n } else {\n targetActorRef = resolvedTarget || actorScope.self;\n }\n\n return [\n snapshot,\n {\n to: targetActorRef,\n targetId: typeof resolvedTarget === 'string' ? resolvedTarget : undefined,\n event: resolvedEvent,\n id,\n delay: resolvedDelay\n },\n undefined\n ];\n}\n\nfunction retryResolveSendTo(\n _: AnyActorScope,\n snapshot: AnyMachineSnapshot,\n params: {\n to: AnyActorRef;\n event: EventObject;\n id: string | undefined;\n delay: number | undefined;\n }\n) {\n if (typeof params.to === 'string') {\n params.to = snapshot.children[params.to];\n }\n}\n\nfunction executeSendTo(\n actorScope: AnyActorScope,\n params: {\n to: AnyActorRef;\n event: EventObject;\n id: string | undefined;\n delay: number | undefined;\n }\n) {\n // this forms an outgoing events queue\n // thanks to that the recipient actors are able to read the *updated* snapshot value of the sender\n actorScope.defer(() => {\n const { to, event, delay, id } = params;\n if (typeof delay === 'number') {\n actorScope.system.scheduler.schedule(\n actorScope.self,\n to,\n event,\n delay,\n id\n );\n return;\n }\n actorScope.system._relay(\n actorScope.self,\n // at this point, in a deferred task, it should already be mutated by retryResolveSendTo\n // if it initially started as a string\n to,\n event.type === XSTATE_ERROR\n ? createErrorActorEvent(actorScope.self.id, (event as any).data)\n : event\n );\n });\n}\n\nexport interface SendToAction<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject,\n TDelay extends string\n> {\n (args: ActionArgs<TContext, TExpressionEvent, TEvent>, params: TParams): void;\n _out_TDelay?: TDelay;\n}\n\n/**\n * Sends an event to an actor.\n *\n * @param actor The `ActorRef` to send the event to.\n * @param event The event to send, or an expression that evaluates to the event\n * to send\n * @param options Send action options\n *\n * - `id` - The unique send event identifier (used with `cancel()`).\n * - `delay` - The number of milliseconds to delay the sending of the event.\n */\nexport function sendTo<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TTargetActor extends AnyActorRef,\n TEvent extends EventObject,\n TDelay extends string = never,\n TUsedDelay extends TDelay = never\n>(\n to:\n | TTargetActor\n | string\n | ((\n args: ActionArgs<TContext, TExpressionEvent, TEvent>,\n params: TParams\n ) => TTargetActor | string),\n eventOrExpr:\n | EventFrom<TTargetActor>\n | SendExpr<\n TContext,\n TExpressionEvent,\n TParams,\n InferEvent<Cast<EventFrom<TTargetActor>, EventObject>>,\n TEvent\n >,\n options?: SendToActionOptions<\n TContext,\n TExpressionEvent,\n TParams,\n DoNotInfer<TEvent>,\n TUsedDelay\n >\n): ActionFunction<\n TContext,\n TExpressionEvent,\n TEvent,\n TParams,\n never,\n never,\n never,\n TDelay,\n never\n> {\n if (isDevelopment && executingCustomAction) {\n console.warn(\n 'Custom actions should not call `sendTo()` directly, as it is not imperative. See https://stately.ai/docs/actions#built-in-actions for more details.'\n );\n }\n\n function sendTo(\n _args: ActionArgs<TContext, TExpressionEvent, TEvent>,\n _params: TParams\n ) {\n if (isDevelopment) {\n throw new Error(`This isn't supposed to be called`);\n }\n }\n\n sendTo.type = 'xstate.sendTo';\n sendTo.to = to;\n sendTo.event = eventOrExpr;\n sendTo.id = options?.id;\n sendTo.delay = options?.delay;\n\n sendTo.resolve = resolveSendTo;\n sendTo.retryResolve = retryResolveSendTo;\n sendTo.execute = executeSendTo;\n\n return sendTo;\n}\n\n/**\n * Sends an event to this machine's parent.\n *\n * @param event The event to send to the parent machine.\n * @param options Options to pass into the send event.\n */\nexport function sendParent<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TSentEvent extends EventObject = AnyEventObject,\n TEvent extends EventObject = AnyEventObject,\n TDelay extends string = never,\n TUsedDelay extends TDelay = never\n>(\n event:\n | TSentEvent\n | SendExpr<TContext, TExpressionEvent, TParams, TSentEvent, TEvent>,\n options?: SendToActionOptions<\n TContext,\n TExpressionEvent,\n TParams,\n TEvent,\n TUsedDelay\n >\n) {\n return sendTo<\n TContext,\n TExpressionEvent,\n TParams,\n AnyActorRef,\n TEvent,\n TDelay,\n TUsedDelay\n >(SpecialTargets.Parent, event, options as any);\n}\n\ntype Target<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject\n> =\n | string\n | AnyActorRef\n | ((\n args: ActionArgs<TContext, TExpressionEvent, TEvent>,\n params: TParams\n ) => string | AnyActorRef);\n\n/**\n * Forwards (sends) an event to the `target` actor.\n *\n * @param target The target actor to forward the event to.\n * @param options Options to pass into the send action creator.\n */\nexport function forwardTo<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject,\n TDelay extends string = never,\n TUsedDelay extends TDelay = never\n>(\n target: Target<TContext, TExpressionEvent, TParams, TEvent>,\n options?: SendToActionOptions<\n TContext,\n TExpressionEvent,\n TParams,\n TEvent,\n TUsedDelay\n >\n) {\n if (isDevelopment && (!target || typeof target === 'function')) {\n const originalTarget = target;\n target = (...args) => {\n const resolvedTarget =\n typeof originalTarget === 'function'\n ? originalTarget(...args)\n : originalTarget;\n if (!resolvedTarget) {\n throw new Error(\n `Attempted to forward event to undefined actor. This risks an infinite loop in the sender.`\n );\n }\n return resolvedTarget;\n };\n }\n return sendTo<\n TContext,\n TExpressionEvent,\n TParams,\n AnyActorRef,\n TEvent,\n TDelay,\n TUsedDelay\n >(target, ({ event }: any) => event, options);\n}\n\nexport interface ExecutableSendToAction extends ExecutableActionObject {\n type: 'xstate.sendTo';\n params: {\n event: EventObject;\n id: string | undefined;\n delay: number | undefined;\n to: AnyActorRef;\n };\n}\n","import isDevelopment from '#is-development';\nimport { Guard, evaluateGuard } from '../guards.ts';\nimport {\n Action,\n ActionArgs,\n ActionFunction,\n AnyActorRef,\n AnyActorScope,\n AnyEventObject,\n AnyMachineSnapshot,\n EventObject,\n MachineContext,\n ParameterizedObject,\n ProvidedActor,\n BuiltinActionResolution,\n UnifiedArg\n} from '../types.ts';\nimport { assign } from './assign.ts';\nimport { cancel } from './cancel.ts';\nimport { emit } from './emit.ts';\nimport { raise } from './raise.ts';\nimport { sendParent, sendTo } from './send.ts';\nimport { spawnChild } from './spawnChild.ts';\nimport { stopChild } from './stopChild.ts';\n\ninterface ActionEnqueuer<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TEvent extends EventObject,\n TActor extends ProvidedActor,\n TAction extends ParameterizedObject,\n TGuard extends ParameterizedObject,\n TDelay extends string,\n TEmitted extends EventObject\n> {\n (\n action: Action<\n TContext,\n TExpressionEvent,\n TEvent,\n undefined,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted\n >\n ): void;\n assign: (\n ...args: Parameters<\n typeof assign<TContext, TExpressionEvent, undefined, TEvent, TActor>\n >\n ) => void;\n cancel: (\n ...args: Parameters<\n typeof cancel<TContext, TExpressionEvent, undefined, TEvent>\n >\n ) => void;\n raise: (\n ...args: Parameters<\n typeof raise<\n TContext,\n TExpressionEvent,\n TEvent,\n undefined,\n TDelay,\n TDelay\n >\n >\n ) => void;\n sendTo: <TTargetActor extends AnyActorRef>(\n ...args: Parameters<\n typeof sendTo<\n TContext,\n TExpressionEvent,\n undefined,\n TTargetActor,\n TEvent,\n TDelay,\n TDelay\n >\n >\n ) => void;\n sendParent: (\n ...args: Parameters<\n typeof sendParent<\n TContext,\n TExpressionEvent,\n undefined,\n AnyEventObject,\n TEvent,\n TDelay,\n TDelay\n >\n >\n ) => void;\n spawnChild: (\n ...args: Parameters<\n typeof spawnChild<TContext, TExpressionEvent, undefined, TEvent, TActor>\n >\n ) => void;\n stopChild: (\n ...args: Parameters<\n typeof stopChild<TContext, TExpressionEvent, undefined, TEvent>\n >\n ) => void;\n emit: (\n ...args: Parameters<\n typeof emit<TContext, TExpressionEvent, undefined, TEvent, TEmitted>\n >\n ) => void;\n}\n\nfunction resolveEnqueueActions(\n actorScope: AnyActorScope,\n snapshot: AnyMachineSnapshot,\n args: ActionArgs<any, any, any>,\n actionParams: ParameterizedObject['params'] | undefined,\n {\n collect\n }: {\n collect: CollectActions<\n MachineContext,\n EventObject,\n ParameterizedObject['params'] | undefined,\n EventObject,\n ProvidedActor,\n ParameterizedObject,\n ParameterizedObject,\n string,\n EventObject\n >;\n }\n): BuiltinActionResolution {\n const actions: any[] = [];\n const enqueue: Parameters<typeof collect>[0]['enqueue'] = function enqueue(\n action\n ) {\n actions.push(action);\n };\n enqueue.assign = (...args) => {\n actions.push(assign(...args));\n };\n enqueue.cancel = (...args) => {\n actions.push(cancel(...args));\n };\n enqueue.raise = (...args) => {\n // for some reason it fails to infer `TDelay` from `...args` here and picks its default (`never`)\n // then it fails to typecheck that because `...args` use `string` in place of `TDelay`\n actions.push((raise as typeof enqueue.raise)(...args));\n };\n enqueue.sendTo = (...args) => {\n // for some reason it fails to infer `TDelay` from `...args` here and picks its default (`never`)\n // then it fails to typecheck that because `...args` use `string` in place of `TDelay\n actions.push((sendTo as typeof enqueue.sendTo)(...args));\n };\n enqueue.sendParent = (...args) => {\n actions.push((sendParent as typeof enqueue.sendParent)(...args));\n };\n enqueue.spawnChild = (...args) => {\n actions.push(spawnChild(...args));\n };\n enqueue.stopChild = (...args) => {\n actions.push(stopChild(...args));\n };\n enqueue.emit = (...args) => {\n actions.push(emit(...args));\n };\n\n collect(\n {\n context: args.context,\n event: args.event,\n enqueue,\n check: (guard) =>\n evaluateGuard(guard, snapshot.context, args.event, snapshot),\n self: actorScope.self,\n system: actorScope.system\n },\n actionParams\n );\n\n return [snapshot, undefined, actions];\n}\n\nexport interface EnqueueActionsAction<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject,\n TActor extends ProvidedActor,\n TAction extends ParameterizedObject,\n TGuard extends ParameterizedObject,\n TDelay extends string\n> {\n (args: ActionArgs<TContext, TExpressionEvent, TEvent>, params: TParams): void;\n _out_TEvent?: TEvent;\n _out_TActor?: TActor;\n _out_TAction?: TAction;\n _out_TGuard?: TGuard;\n _out_TDelay?: TDelay;\n}\n\ninterface CollectActionsArg<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TEvent extends EventObject,\n TActor extends ProvidedActor,\n TAction extends ParameterizedObject,\n TGuard extends ParameterizedObject,\n TDelay extends string,\n TEmitted extends EventObject\n> extends UnifiedArg<TContext, TExpressionEvent, TEvent> {\n check: (\n guard: Guard<TContext, TExpressionEvent, undefined, TGuard>\n ) => boolean;\n enqueue: ActionEnqueuer<\n TContext,\n TExpressionEvent,\n TEvent,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted\n >;\n}\n\ntype CollectActions<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject,\n TActor extends ProvidedActor,\n TAction extends ParameterizedObject,\n TGuard extends ParameterizedObject,\n TDelay extends string,\n TEmitted extends EventObject\n> = (\n {\n context,\n event,\n check,\n enqueue,\n self\n }: CollectActionsArg<\n TContext,\n TExpressionEvent,\n TEvent,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted\n >,\n params: TParams\n) => void;\n\n/**\n * Creates an action object that will execute actions that are queued by the\n * `enqueue(action)` function.\n *\n * @example\n *\n * ```ts\n * import { createMachine, enqueueActions } from 'xstate';\n *\n * const machine = createMachine({\n * entry: enqueueActions(({ enqueue, check }) => {\n * enqueue.assign({ count: 0 });\n *\n * if (check('someGuard')) {\n * enqueue.assign({ count: 1 });\n * }\n *\n * enqueue('someAction');\n * })\n * });\n * ```\n */\nexport function enqueueActions<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject = TExpressionEvent,\n TActor extends ProvidedActor = ProvidedActor,\n TAction extends ParameterizedObject = ParameterizedObject,\n TGuard extends ParameterizedObject = ParameterizedObject,\n TDelay extends string = never,\n TEmitted extends EventObject = EventObject\n>(\n collect: CollectActions<\n TContext,\n TExpressionEvent,\n TParams,\n TEvent,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted\n >\n): ActionFunction<\n TContext,\n TExpressionEvent,\n TEvent,\n TParams,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted\n> {\n function enqueueActions(\n _args: ActionArgs<TContext, TExpressionEvent, TEvent>,\n _params: unknown\n ) {\n if (isDevelopment) {\n throw new Error(`This isn't supposed to be called`);\n }\n }\n\n enqueueActions.type = 'xstate.enqueueActions';\n enqueueActions.collect = collect;\n enqueueActions.resolve = resolveEnqueueActions;\n\n return enqueueActions;\n}\n","import isDevelopment from '#is-development';\nimport {\n ActionArgs,\n AnyActorScope,\n AnyMachineSnapshot,\n EventObject,\n LogExpr,\n MachineContext,\n ParameterizedObject,\n BuiltinActionResolution\n} from '../types.ts';\n\ntype ResolvableLogValue<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject\n> = string | LogExpr<TContext, TExpressionEvent, TParams, TEvent>;\n\nfunction resolveLog(\n _: AnyActorScope,\n snapshot: AnyMachineSnapshot,\n actionArgs: ActionArgs<any, any, any>,\n actionParams: ParameterizedObject['params'] | undefined,\n {\n value,\n label\n }: {\n value: ResolvableLogValue<any, any, any, any>;\n label: string | undefined;\n }\n): BuiltinActionResolution {\n return [\n snapshot,\n {\n value:\n typeof value === 'function' ? value(actionArgs, actionParams) : value,\n label\n },\n undefined\n ];\n}\n\nfunction executeLog(\n { logger }: AnyActorScope,\n { value, label }: { value: unknown; label: string | undefined }\n) {\n if (label) {\n logger(label, value);\n } else {\n logger(value);\n }\n}\n\nexport interface LogAction<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject\n> {\n (args: ActionArgs<TContext, TExpressionEvent, TEvent>, params: TParams): void;\n}\n\n/**\n * @param expr The expression function to evaluate which will be logged. Takes\n * in 2 arguments:\n *\n * - `ctx` - the current state context\n * - `event` - the event that caused this action to be executed.\n *\n * @param label The label to give to the logged expression.\n */\nexport function log<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TEvent extends EventObject\n>(\n value: ResolvableLogValue<TContext, TExpressionEvent, TParams, TEvent> = ({\n context,\n event\n }) => ({ context, event }),\n label?: string\n): LogAction<TContext, TExpressionEvent, TParams, TEvent> {\n function log(\n _args: ActionArgs<TContext, TExpressionEvent, TEvent>,\n _params: TParams\n ) {\n if (isDevelopment) {\n throw new Error(`This isn't supposed to be called`);\n }\n }\n\n log.type = 'xstate.log';\n log.value = value;\n log.label = label;\n\n log.resolve = resolveLog;\n log.execute = executeLog;\n\n return log;\n}\n"],"names":["Mailbox","constructor","_process","this","_active","_current","_last","start","flush","clear","next","enqueue","event","enqueued","value","consumed","XSTATE_STOP","getDevTools","w","globalThis","self","window","__xstate__","devToolsAdapter","service","devTools","register","createErrorActorEvent","id","error","type","actorId","reportUnhandledError","err","setTimeout","symbolObservable","Symbol","observable","matchesState","parentStateId","childStateId","parentStateValue","toStateValue","childStateValue","Object","keys","every","key","toStatePath","stateId","Array","isArray","result","segment","i","length","charCodeAt","push","stateValue","statePath","marker","previous","pathToStateValue","toObserver","nextHandler","errorHandler","completionHandler","isObserver","undefined","bind","complete","resolveReferencedActor","machine","src","match","implementations","actors","indexStr","nodeId","invokeConfig","getStateNodeById","config","invoke","createScheduledEventId","actorRef","sessionId","idCounter","executingCustomAction","ProcessingStatus","defaultOptions","clock","fn","ms","clearTimeout","logger","console","log","Actor","logic","options","_snapshot","mailbox","observers","Set","eventListeners","Map","_processingStatus","NotStarted","_parent","_syncSnapshot","ref","_actorScope","_systemId","system","_doneEvent","_deferred","resolvedOptions","parent","syncSnapshot","systemId","inspect","rootActor","children","keyedActors","reverseKeyedActors","WeakMap","inspectionObservers","timerMap","scheduler","schedule","source","target","delay","Math","random","toString","slice","scheduledEvent","startedAt","Date","now","scheduledEventId","_scheduledEvents","timeout","_relay","cancel","cancelAll","snapshot","_bookId","_register","set","_unregister","delete","get","_set","existing","Error","observerOrFn","observer","add","unsubscribe","_sendInspectionEvent","size","resolvedInspectionEvent","rootId","forEach","sourceRef","_send","getSnapshot","scheduledEvents","scheduledId","_clock","_logger","createSystem","defer","stopChild","child","_stop","emit","emittedEvent","listeners","wildcardListener","allListeners","values","handler","actionExecutor","action","exec","params","saveExecutingCustomAction","info","Running","send","_initState","state","status","persistedState","restoreSnapshot","getInitialSnapshot","input","output","update","deferredFn","shift","_stopProcedure","_complete","invokeId","_error","subscribe","nextListenerOrObserver","errorListener","completeListener","Stopped","on","wrappedHandler","initEvent","attachDevTools","nextState","caughtError","transition","stop","_reportError","reportError","err2","toJSON","xstate$$type","getPersistedSnapshot","createActor","resolveCancel","_","actionArgs","actionParams","sendId","executeCancel","actorScope","_args","_params","resolve","execute","resolveSpawn","_actionParams","resolvedId","resolvedInput","context","cloneMachineSnapshot","executeSpawn","spawnChild","resolveStop","args","actorRefOrString","resolvedActorRef","executeStop","evaluateGuard","guard","isInline","resolved","guards","guardArgs","guardParams","check","isAtomicStateNode","stateNode","getChildren","states","filter","sn","getProperAncestors","toStateNode","ancestors","m","getValueFromAdj","baseNode","adjList","childStateNodes","childStateNode","getAdjList","stateNodes","s","has","getStateValue","rootNode","nodeSet","initialStates","getInitialStateNodesWithTheirAncestors","initialStateNode","getAllStateNodes","iter","descStateNode","initial","getInitialStateNodes","initialState","ancestor","machineSnapshotMatches","testValue","machineSnapshotHasTag","tag","tags","machineSnapshotCan","transitionData","getTransitionData","some","t","actions","machineSnapshotToJSON","_nodes","nodes","getMeta","can","hasTag","matches","jsonValues","from","machineSnapshotGetMeta","reduce","acc","meta","root","flatMap","historyValue","createMachineSnapshot","createSpawner","spawnedChildren","spawn","resolveAssign","assignment","assignArgs","partialUpdate","propAssignment","assign","resolveEmit","eventOrExpr","executeEmit","resolveRaise","internalQueue","delaysMap","delays","resolvedEvent","resolvedDelay","configDelay","executeRaise","raise","SpecialTargets","resolveSendTo","to","extra","resolvedTarget","targetActorRef","Parent","Internal","startsWith","deferredActorIds","includes","targetId","retryResolveSendTo","executeSendTo","data","sendTo","retryResolve","sendParent","resolveEnqueueActions","collect","resolveLog","label","executeLog","enqueueActions"],"mappings":"oPAKO,MAAMA,EAKXC,WAAAA,CAAoBC,GAA2BC,KAA3BD,SAAAA,EAAyBC,KAJrCC,SAAmB,EAAKD,KACxBE,SAAkC,KAAIF,KACtCG,MAA+B,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