xstate 6.0.0-alpha.4 → 6.0.0-alpha.40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/README.md +19 -17
  2. package/bin/xstate.js +36 -0
  3. package/dist/StateMachine-1464d5e4.cjs.js +1139 -0
  4. package/dist/StateMachine-6082c3cf.esm.js +1136 -0
  5. package/dist/StateMachine-76ee1d6e.development.cjs.js +1171 -0
  6. package/dist/StateMachine-f8c7feca.development.esm.js +1168 -0
  7. package/dist/{index-ccbe7c0b.development.esm.js → createActor-2a03d4b2.development.esm.js} +2395 -1861
  8. package/dist/{index-9cce3480.esm.js → createActor-a211c276.esm.js} +2380 -1846
  9. package/dist/{index-ebaf6fd8.development.cjs.js → createActor-c0f78b8a.development.cjs.js} +2424 -1868
  10. package/dist/{index-918ab496.cjs.js → createActor-d5305cc9.cjs.js} +2409 -1853
  11. package/dist/declarations/src/State.d.ts +17 -4
  12. package/dist/declarations/src/StateMachine.d.ts +37 -16
  13. package/dist/declarations/src/StateNode.d.ts +5 -2
  14. package/dist/declarations/src/actions.d.ts +10 -7
  15. package/dist/declarations/src/actors/callback.d.ts +2 -0
  16. package/dist/declarations/src/actors/logic.d.ts +7 -21
  17. package/dist/declarations/src/actors/observable.d.ts +3 -0
  18. package/dist/declarations/src/actors/promise.d.ts +6 -2
  19. package/dist/declarations/src/createActor.d.ts +24 -15
  20. package/dist/declarations/src/createMachine.d.ts +21 -13
  21. package/dist/declarations/src/createMachineFromConfig.d.ts +64 -30
  22. package/dist/declarations/src/durable/index.d.ts +66 -0
  23. package/dist/declarations/src/fsm.d.ts +76 -0
  24. package/dist/declarations/src/index.d.ts +12 -7
  25. package/dist/declarations/src/machineVersion.types.d.ts +37 -0
  26. package/dist/declarations/src/machineVersions.d.ts +100 -0
  27. package/dist/declarations/src/schema.types.d.ts +5 -0
  28. package/dist/declarations/src/serialize.d.ts +9 -22
  29. package/dist/declarations/src/setup.d.ts +317 -64
  30. package/dist/declarations/src/spawn.d.ts +5 -5
  31. package/dist/declarations/src/stateUtils.d.ts +19 -7
  32. package/dist/declarations/src/system.d.ts +38 -11
  33. package/dist/declarations/src/transitionActions.d.ts +14 -2
  34. package/dist/declarations/src/types.d.ts +300 -134
  35. package/dist/declarations/src/types.v6.d.ts +306 -52
  36. package/dist/declarations/src/utils.d.ts +5 -3
  37. package/dist/declarations/src/validation/index.d.ts +37 -0
  38. package/dist/declarations/src/validation.types.d.ts +22 -0
  39. package/dist/index-17f889df.development.esm.js +976 -0
  40. package/dist/index-21d08fff.cjs.js +985 -0
  41. package/dist/index-3d1368f7.development.cjs.js +985 -0
  42. package/dist/index-7020402e.esm.js +976 -0
  43. package/dist/transition-2dcabac8.cjs.js +148 -0
  44. package/dist/transition-4ba58b71.development.cjs.js +148 -0
  45. package/dist/transition-e8a13c00.esm.js +142 -0
  46. package/dist/transition-f581ffa6.development.esm.js +142 -0
  47. package/dist/xstate-actors.cjs.js +6 -5
  48. package/dist/xstate-actors.development.cjs.js +6 -5
  49. package/dist/xstate-actors.development.esm.js +2 -1
  50. package/dist/xstate-actors.esm.js +2 -1
  51. package/dist/xstate-actors.umd.min.js +1 -1
  52. package/dist/xstate-actors.umd.min.js.map +1 -1
  53. package/dist/xstate-durable.cjs.d.mts +2 -0
  54. package/dist/xstate-durable.cjs.d.ts +2 -0
  55. package/dist/xstate-durable.cjs.js +106 -0
  56. package/dist/xstate-durable.cjs.mjs +5 -0
  57. package/dist/xstate-durable.development.cjs.js +106 -0
  58. package/dist/xstate-durable.development.cjs.mjs +5 -0
  59. package/dist/xstate-durable.development.esm.js +100 -0
  60. package/dist/xstate-durable.esm.js +100 -0
  61. package/dist/xstate-durable.umd.min.js +2 -0
  62. package/dist/xstate-durable.umd.min.js.map +1 -0
  63. package/dist/xstate-graph.cjs.js +16 -19
  64. package/dist/xstate-graph.development.cjs.js +16 -19
  65. package/dist/xstate-graph.development.esm.js +13 -16
  66. package/dist/xstate-graph.esm.js +13 -16
  67. package/dist/xstate-graph.umd.min.js +1 -1
  68. package/dist/xstate-graph.umd.min.js.map +1 -1
  69. package/dist/xstate-validation.cjs.d.mts +2 -0
  70. package/dist/xstate-validation.cjs.d.ts +2 -0
  71. package/dist/xstate-validation.cjs.js +277 -0
  72. package/dist/xstate-validation.cjs.mjs +5 -0
  73. package/dist/xstate-validation.development.cjs.js +277 -0
  74. package/dist/xstate-validation.development.cjs.mjs +5 -0
  75. package/dist/xstate-validation.development.esm.js +271 -0
  76. package/dist/xstate-validation.esm.js +271 -0
  77. package/dist/xstate-validation.umd.min.js +2 -0
  78. package/dist/xstate-validation.umd.min.js.map +1 -0
  79. package/dist/xstate.cjs.js +1350 -412
  80. package/dist/xstate.cjs.mjs +4 -0
  81. package/dist/xstate.development.cjs.js +1350 -412
  82. package/dist/xstate.development.cjs.mjs +4 -0
  83. package/dist/xstate.development.esm.js +1326 -392
  84. package/dist/xstate.esm.js +1326 -392
  85. package/dist/xstate.umd.min.js +1 -1
  86. package/dist/xstate.umd.min.js.map +1 -1
  87. package/durable/package.json +8 -0
  88. package/package.json +39 -3
  89. package/validation/package.json +8 -0
  90. package/dist/StateMachine-445a8480.cjs.js +0 -732
  91. package/dist/StateMachine-4deb4090.development.esm.js +0 -746
  92. package/dist/StateMachine-f310bc72.esm.js +0 -729
  93. package/dist/StateMachine-f83f01f9.development.cjs.js +0 -749
@@ -0,0 +1,1136 @@
1
+ import { S as STATE_DELIMITER, I as mapValues, t as toArray, J as createInvokeId, K as getDelayedTransitions, L as getEventDescriptorKey, M as getCandidates, N as evaluateCandidate, O as formatTransition, P as NULL_EVENT, Q as toTransitionConfigArray, R as createInvokeTimeoutEventId, T as matchesActorSession, U as formatRouteTransitions, V as resolveStateValue, W as getAllStateNodes, v as getStateNodes, Y as createMachineSnapshot, Z as isInFinalState, _ as createInertActorScope, $ as setInertActorScopeSnapshot, a0 as attachSnapshotActorRef, a1 as macrostep, a2 as isInertActorScope, a3 as setSnapshotActorRef, a4 as cloneMachineSnapshot, a5 as transitionNode, e as XSTATE_TIMER, m as matchesEventDescriptor, a6 as getTransitionResult, a7 as hasEffect, a8 as createErrorPlatformEvent, a9 as withActorSelf, r as resolveActionsWithContext, F as createInitEvent, aa as createSpawnEffect, ab as initialMicrostep, ac as toStatePath, ad as isStateId, ae as getStateNodeByPath, af as getPersistedSnapshot, ag as resolveReferencedActor, ah as createInvokeTimeoutEvent, ai as $$ACTOR_TYPE, j as createActor } from './createActor-a211c276.esm.js';
2
+ import { g as assertValid } from './index-7020402e.esm.js';
3
+
4
+ function createSpawner(actorScope, actors, spawnedChildren) {
5
+ return (src, options) => {
6
+ const referencedSrc = Object.entries(actors).find(([, logic]) => logic === src)?.[0];
7
+ const actor = actorScope.system.createActorRef(src, {
8
+ id: options?.id,
9
+ parent: actorScope.self,
10
+ syncSnapshot: options?.syncSnapshot,
11
+ input: options?.input,
12
+ src: referencedSrc ?? src,
13
+ registryKey: options?.registryKey
14
+ });
15
+ spawnedChildren[actor.id] = actor;
16
+ return actor;
17
+ };
18
+ }
19
+
20
+ const cache = new WeakMap();
21
+ function memo(object, key, fn) {
22
+ let memoizedData = cache.get(object);
23
+ if (!memoizedData) {
24
+ memoizedData = {
25
+ [key]: fn()
26
+ };
27
+ cache.set(object, memoizedData);
28
+ } else if (!(key in memoizedData)) {
29
+ memoizedData[key] = fn();
30
+ }
31
+ return memoizedData[key];
32
+ }
33
+
34
+ const EMPTY_OBJECT = {};
35
+ class StateNode {
36
+ constructor(/** The raw config used to create the machine. */
37
+ config, options) {
38
+ this.config = config;
39
+ /**
40
+ * The relative key of the state node, which represents its location in the
41
+ * overall state value.
42
+ */
43
+ this.key = void 0;
44
+ /** The unique ID of the state node. */
45
+ this.id = void 0;
46
+ /**
47
+ * The type of this state node:
48
+ *
49
+ * - `'atomic'` - no child state nodes
50
+ * - `'compound'` - nested child state nodes (XOR)
51
+ * - `'parallel'` - orthogonal nested child state nodes (AND)
52
+ * - `'history'` - history state node
53
+ * - `'choice'` - pure routing decision state node
54
+ * - `'final'` - final state node
55
+ */
56
+ this.type = void 0;
57
+ /** The string path from the root machine node to this node. */
58
+ this.path = void 0;
59
+ /** The child state nodes. */
60
+ this.states = void 0;
61
+ /**
62
+ * The type of history on this state node. Can be:
63
+ *
64
+ * - `'shallow'` - recalls only top-level historical state value
65
+ * - `'deep'` - recalls historical state value at all levels
66
+ */
67
+ this.history = void 0;
68
+ /** The action(s) to be executed upon entering the state node. */
69
+ this.entry = void 0;
70
+ /** The action(s) to be executed upon exiting the state node. */
71
+ this.exit = void 0;
72
+ /** The parent state node. */
73
+ this.parent = void 0;
74
+ /** The root machine node. */
75
+ this.machine = void 0;
76
+ /**
77
+ * The meta data associated with this state node, which will be returned in
78
+ * State instances.
79
+ */
80
+ this.meta = void 0;
81
+ /**
82
+ * The output data sent with the `xstate.done.state` event if this is a final
83
+ * state node.
84
+ */
85
+ this.output = void 0;
86
+ /**
87
+ * The order this state node appears. Corresponds to the implicit document
88
+ * order.
89
+ */
90
+ this.order = -1;
91
+ this.description = void 0;
92
+ this.schemas = void 0;
93
+ this.tags = [];
94
+ this.transitions = void 0;
95
+ this.always = void 0;
96
+ this.invoke = void 0;
97
+ this.on = void 0;
98
+ this.after = void 0;
99
+ this.events = void 0;
100
+ this.ownEvents = void 0;
101
+ this._candidateCache = void 0;
102
+ this.parent = options._parent;
103
+ this.key = options._key;
104
+ this.machine = options._machine;
105
+ this.path = this.parent ? this.parent.path.concat(this.key) : [];
106
+ const firstStateKey = this.config.states ? Object.keys(this.config.states)[0] : undefined;
107
+ this.id = this.config.id || [this.machine.id, ...this.path].join(STATE_DELIMITER);
108
+ this.type = this.config.type || (firstStateKey !== undefined ? 'compound' : this.config.history ? 'history' : 'atomic');
109
+ this.description = this.config.description;
110
+ this.schemas = this.config.schemas;
111
+ validateStateNodeConfig(this);
112
+ this.order = this.machine.idMap.size;
113
+ this.machine.idMap.set(this.id, this);
114
+ this.states = this.config.states ? mapValues(this.config.states, (stateConfig, key) => {
115
+ const stateNode = new StateNode(stateConfig, {
116
+ _parent: this,
117
+ _key: key,
118
+ _machine: this.machine
119
+ });
120
+ return stateNode;
121
+ }) : EMPTY_OBJECT;
122
+ if (this.type === 'compound' && !this.config.initial) {
123
+ throw new Error(`No initial state specified for compound state node "#${this.id}".`);
124
+ }
125
+
126
+ // History config
127
+ this.history = this.config.history === true ? 'shallow' : this.config.history || false;
128
+ this.entry = this.config.entry;
129
+ this.exit = this.config.exit;
130
+ if (this.entry) {
131
+ // @ts-expect-error _special is an internal marker not on the Action type
132
+ this.entry._special = true;
133
+ }
134
+ if (this.exit) {
135
+ // @ts-expect-error _special is an internal marker not on the Action type
136
+ this.exit._special = true;
137
+ }
138
+ this.meta = this.config.meta;
139
+ this.output = this.type === 'final' || !this.parent ? this.config.output : undefined;
140
+ this.tags = toArray(config.tags).slice();
141
+ this.invoke = toArray(this.config.invoke).map((invokeConfig, i) => {
142
+ const {
143
+ src,
144
+ registryKey
145
+ } = invokeConfig;
146
+ const invokeId = createInvokeId(this.id, i);
147
+ const resolvedId = invokeConfig.id ?? invokeId;
148
+ // Referenced (string) actors keep their logical name so persisted
149
+ // snapshots reference `src: 'fetchUser'` rather than a positional id;
150
+ // only inline logic gets the synthetic source name.
151
+ const sourceName = typeof src === 'string' ? src : `xstate.invoke.${invokeId}`;
152
+ return {
153
+ ...invokeConfig,
154
+ src: sourceName,
155
+ logic: src,
156
+ id: resolvedId,
157
+ registryKey
158
+ };
159
+ });
160
+ }
161
+
162
+ /** @internal */
163
+ _initialize() {
164
+ this.after = getDelayedTransitions(this);
165
+ this.transitions = formatTransitions(this);
166
+ if (this.type === 'choice') {
167
+ this.always = formatChoiceTransitions(this);
168
+ } else if (this.config.always) {
169
+ this.always = mapTransitionConfigs(this.config.always, transition => formatTransition(this, NULL_EVENT, transition));
170
+ }
171
+ for (const key of Object.keys(this.states)) {
172
+ this.states[key]._initialize();
173
+ }
174
+ this._refreshEventMetadata();
175
+ }
176
+
177
+ /** @internal */
178
+ _refreshEventMetadata() {
179
+ const on = {};
180
+ const ownEvents = [];
181
+ for (const [descriptor, transitions] of this.transitions) {
182
+ on[descriptor] = transitions.slice();
183
+ if (transitions.some(transition => transition.target || transition.reenter || transition.to)) {
184
+ ownEvents.push(descriptor);
185
+ }
186
+ }
187
+ this.on = on;
188
+ this.ownEvents = ownEvents;
189
+ const events = new Set(ownEvents);
190
+ for (const state of Object.values(this.states)) {
191
+ for (const event of state.events) {
192
+ events.add(event);
193
+ }
194
+ }
195
+ this.events = Array.from(events);
196
+ }
197
+ get initial() {
198
+ return memo(this, 'initial', () => formatInitialTransition(this, this.config.initial));
199
+ }
200
+
201
+ /** @internal */
202
+ next(snapshot, event, actorScope, selectionResults) {
203
+ const descriptorKey = getEventDescriptorKey(event);
204
+ let candidates = this._candidateCache?.get(descriptorKey);
205
+ if (!candidates) {
206
+ candidates = getCandidates(this, event);
207
+ (this._candidateCache ??= new Map()).set(descriptorKey, candidates);
208
+ }
209
+ for (const candidate of candidates) {
210
+ const guardPassed = evaluateCandidate(candidate, event, snapshot, this, actorScope, selectionResults);
211
+ if (guardPassed) {
212
+ return [candidate];
213
+ }
214
+ }
215
+ return undefined;
216
+ }
217
+ }
218
+ function validateStateNodeConfig(stateNode) {
219
+ const config = stateNode.config;
220
+ if (stateNode.type === 'history' && !(typeof config.target === 'string' && config.target.trim().length > 0 || Array.isArray(config.target) && config.target.length > 0 && config.target.every(target => typeof target === 'string' && target.trim().length > 0))) {
221
+ throw new Error(`Missing history target on "${stateNode.id}"`);
222
+ }
223
+ if (stateNode.type !== 'choice') {
224
+ return;
225
+ }
226
+ if (typeof config.choice !== 'function') {
227
+ throw new Error(`Missing \`choice\` function on "${stateNode.id}"`);
228
+ }
229
+ }
230
+ function formatChoiceTransitions(stateNode) {
231
+ const choice = stateNode.config.choice;
232
+ const validateChoiceResult = result => {
233
+ if (!result || result.target === undefined) {
234
+ throw new Error(`Choice "${stateNode.id}" has no target`);
235
+ }
236
+ return result;
237
+ };
238
+ return [formatTransition(stateNode, NULL_EVENT, {
239
+ to: args => validateChoiceResult(choice(args))
240
+ })];
241
+ }
242
+ function mapTransitionConfigs(transitionsConfig, mapper) {
243
+ const transitionConfigs = toTransitionConfigArray(transitionsConfig);
244
+ const transitions = new Array(transitionConfigs.length);
245
+ for (let i = 0; i < transitionConfigs.length; i++) {
246
+ transitions[i] = mapper(transitionConfigs[i]);
247
+ }
248
+ return transitions;
249
+ }
250
+ function formatTransitions(stateNode) {
251
+ const transitions = new Map();
252
+ const addTransitions = (descriptor, additions) => {
253
+ transitions.set(descriptor, [...(transitions.get(descriptor) ?? []), ...additions]);
254
+ };
255
+ if (stateNode.config.on) {
256
+ for (const descriptor of Object.keys(stateNode.config.on)) {
257
+ if (descriptor === NULL_EVENT) {
258
+ throw new Error('Null event transition key');
259
+ }
260
+ const transitionsConfig = stateNode.config.on[descriptor];
261
+ transitions.set(descriptor, mapTransitionConfigs(transitionsConfig, transition => formatTransition(stateNode, descriptor, transition)));
262
+ }
263
+ }
264
+ if (stateNode.config.onDone) {
265
+ const descriptor = 'xstate.done.state';
266
+ addTransitions(descriptor, mapTransitionConfigs(stateNode.config.onDone, transition => formatTransition(stateNode, descriptor, {
267
+ ...transition,
268
+ matches: {
269
+ ...transition.matches,
270
+ stateId: stateNode.id
271
+ }
272
+ })));
273
+ }
274
+ if (stateNode.config.onError) {
275
+ const descriptor = 'xstate.error.*';
276
+ transitions.set(descriptor, mapTransitionConfigs(stateNode.config.onError, transition => formatTransition(stateNode, descriptor, transition)));
277
+ }
278
+ const createCancelInvokeTimeoutTransition = (descriptor, timeoutEventId, actorId) => formatTransition(stateNode, descriptor, {
279
+ matches: {
280
+ actorId
281
+ },
282
+ _eventMatcher: (event, snapshot) => matchesActorSession(event, snapshot, actorId),
283
+ to: (_args, enq) => {
284
+ enq.cancel(timeoutEventId);
285
+ return {};
286
+ }
287
+ });
288
+ const formatInvokeCompletionTransition = (descriptor, transitionConfig, timeoutEventId) => {
289
+ const {
290
+ target,
291
+ to,
292
+ reenter,
293
+ ...rest
294
+ } = transitionConfig;
295
+ return formatTransition(stateNode, descriptor, {
296
+ ...rest,
297
+ reenter,
298
+ to: (args, enq) => {
299
+ if (to) {
300
+ let didEnqueue = false;
301
+ const trackingEnqueue = new Proxy(enq, {
302
+ apply(target, thisArg, argArray) {
303
+ didEnqueue = true;
304
+ return Reflect.apply(target, thisArg, argArray);
305
+ },
306
+ get(target, prop, receiver) {
307
+ const value = Reflect.get(target, prop, receiver);
308
+ if (typeof value !== 'function') {
309
+ return value;
310
+ }
311
+ return (...argArray) => {
312
+ didEnqueue = true;
313
+ return value.apply(target, argArray);
314
+ };
315
+ }
316
+ });
317
+ const result = to(args, trackingEnqueue);
318
+ if (result !== undefined || didEnqueue) {
319
+ enq.cancel(timeoutEventId);
320
+ }
321
+ return result;
322
+ }
323
+ enq.cancel(timeoutEventId);
324
+ return {
325
+ target,
326
+ reenter
327
+ };
328
+ }
329
+ });
330
+ };
331
+ for (const invokeDef of stateNode.invoke) {
332
+ const withInvokeMatch = transition => ({
333
+ ...transition,
334
+ matches: {
335
+ ...transition.matches,
336
+ actorId: invokeDef.id
337
+ },
338
+ _eventMatcher: (event, snapshot) => matchesActorSession(event, snapshot, invokeDef.id)
339
+ });
340
+ const invokeTimeoutEventId = invokeDef.timeout !== undefined ? createInvokeTimeoutEventId(invokeDef.id) : undefined;
341
+ if (invokeDef.onDone) {
342
+ const descriptor = 'xstate.done.actor';
343
+ const invokeDoneTransitions = mapTransitionConfigs(invokeDef.onDone, rawTransition => {
344
+ const transition = withInvokeMatch(rawTransition);
345
+ return invokeTimeoutEventId ? formatInvokeCompletionTransition(descriptor, transition, invokeTimeoutEventId) : formatTransition(stateNode, descriptor, transition);
346
+ });
347
+ if (invokeTimeoutEventId) {
348
+ invokeDoneTransitions.push(createCancelInvokeTimeoutTransition(descriptor, invokeTimeoutEventId, invokeDef.id));
349
+ }
350
+ addTransitions(descriptor, invokeDoneTransitions);
351
+ } else if (invokeTimeoutEventId) {
352
+ const descriptor = 'xstate.done.actor';
353
+ addTransitions(descriptor, [createCancelInvokeTimeoutTransition(descriptor, invokeTimeoutEventId, invokeDef.id)]);
354
+ }
355
+ if (invokeDef.onError) {
356
+ const descriptor = 'xstate.error.actor';
357
+ addTransitions(descriptor, mapTransitionConfigs(invokeDef.onError, rawTransition => {
358
+ const transition = withInvokeMatch(rawTransition);
359
+ return invokeTimeoutEventId ? formatInvokeCompletionTransition(descriptor, transition, invokeTimeoutEventId) : formatTransition(stateNode, descriptor, transition);
360
+ }));
361
+ }
362
+ if (invokeDef.onSnapshot) {
363
+ const descriptor = 'xstate.snapshot.actor';
364
+ addTransitions(descriptor, mapTransitionConfigs(invokeDef.onSnapshot, transition => formatTransition(stateNode, descriptor, withInvokeMatch(transition))));
365
+ }
366
+ }
367
+ for (const delayedTransition of stateNode.after) {
368
+ let existing = transitions.get(delayedTransition.eventType);
369
+ if (!existing) {
370
+ existing = [];
371
+ transitions.set(delayedTransition.eventType, existing);
372
+ }
373
+ existing.push(delayedTransition);
374
+ }
375
+ return transitions;
376
+ }
377
+ function formatInitialTransition(stateNode, _target) {
378
+ const targetString = typeof _target === 'object' && _target !== null ? _target.target : _target;
379
+ const input = typeof _target === 'object' && _target !== null ? _target.input : undefined;
380
+ const resolvedTarget = typeof targetString === 'string' ? stateNode.states[targetString] : undefined;
381
+ if (!resolvedTarget && targetString) {
382
+ throw new Error(`Initial state "${targetString}" not found on "#${stateNode.id}"`);
383
+ }
384
+ const transition = {
385
+ source: stateNode,
386
+ target: resolvedTarget ? [resolvedTarget] : undefined,
387
+ input
388
+ };
389
+ return transition;
390
+ }
391
+
392
+ const STATE_IDENTIFIER = '#';
393
+ let emptyCanActor;
394
+ let emptyCanActorScope;
395
+ function getEmptyCanActor() {
396
+ // A minimal inert actor used purely as the `self`/`parent` argument when
397
+ // dry-running transitions for `snapshot.can(...)`. Intentionally not built
398
+ // on `createLogic` so `can()` does not pull that machinery into bundles.
399
+ return emptyCanActor ??= createActor({
400
+ transition: snapshot => [snapshot, []],
401
+ initialTransition: () => [{
402
+ status: 'active',
403
+ output: undefined,
404
+ error: undefined
405
+ }, []],
406
+ getInitialSnapshot: () => ({
407
+ status: 'active',
408
+ output: undefined,
409
+ error: undefined
410
+ }),
411
+ getPersistedSnapshot: snapshot => snapshot
412
+ });
413
+ }
414
+ function getEmptyCanActorScope() {
415
+ if (emptyCanActorScope) {
416
+ return emptyCanActorScope;
417
+ }
418
+ const actor = getEmptyCanActor();
419
+ emptyCanActorScope = {
420
+ self: actor,
421
+ logger: () => {},
422
+ id: '',
423
+ sessionId: '',
424
+ defer: () => {},
425
+ system: actor.system,
426
+ stopChild: () => {},
427
+ emit: () => {},
428
+ actionExecutor: () => {}
429
+ };
430
+ return emptyCanActorScope;
431
+ }
432
+ class StateMachine {
433
+ constructor(/** The raw config used to create the machine. */
434
+ config, sources, validator) {
435
+ this.config = config;
436
+ this.validator = validator;
437
+ /** The machine's own version. */
438
+ this.version = void 0;
439
+ this.schemas = void 0;
440
+ /** Standard Schema for snapshots persisted by this machine version. */
441
+ this.snapshotSchema = void 0;
442
+ /** Standard Schema for complete events accepted by this machine version. */
443
+ this.eventSchema = void 0;
444
+ this.sources = void 0;
445
+ /** Runtime options for machine execution. */
446
+ this.options = void 0;
447
+ /** @internal */
448
+ this.idMap = new Map();
449
+ this.root = void 0;
450
+ this.id = void 0;
451
+ this.states = void 0;
452
+ this.events = void 0;
453
+ this.internalEventDescriptors = void 0;
454
+ /** @internal Skips eventless-selection scans for machines without `always`. */
455
+ this._hasEventlessTransitions = void 0;
456
+ /**
457
+ * The original JSON definition this machine was created from (set by
458
+ * `createMachineFromConfig`), if any. Used by `serializeMachine` for lossless
459
+ * round-trips.
460
+ *
461
+ * @internal
462
+ */
463
+ this._json = void 0;
464
+ this.id = config.id || '(machine)';
465
+ this.sources = {
466
+ actors: config.actors ?? {},
467
+ actions: config.actions ?? {},
468
+ delays: config.delays ?? {},
469
+ guards: config.guards ?? {},
470
+ ...sources
471
+ };
472
+ this.version = this.config.version;
473
+ this.schemas = this.config.schemas;
474
+ this.snapshotSchema = {
475
+ '~standard': {
476
+ version: 1,
477
+ vendor: 'xstate',
478
+ validate: async value => {
479
+ if (value === null || typeof value !== 'object') {
480
+ return {
481
+ issues: [{
482
+ message: 'Expected a persisted snapshot.'
483
+ }]
484
+ };
485
+ }
486
+ const snapshot = {
487
+ historyValue: {},
488
+ timers: {},
489
+ ...value
490
+ };
491
+ const contextSchema = this.schemas?.context;
492
+ let context = snapshot.context;
493
+ if (contextSchema) {
494
+ const result = await contextSchema['~standard'].validate(context);
495
+ if (result.issues) {
496
+ return {
497
+ issues: [{
498
+ message: `Invalid context for machine '${this.id}' version '${this.version}': ${result.issues[0]?.message}`
499
+ }]
500
+ };
501
+ }
502
+ context = result.value;
503
+ }
504
+ for (const key of ['value', 'children']) {
505
+ if (!(key in snapshot)) {
506
+ return {
507
+ issues: [{
508
+ message: `Persisted snapshot is missing '${key}'.`
509
+ }]
510
+ };
511
+ }
512
+ }
513
+ if (!['active', 'done', 'error', 'stopped'].includes(snapshot.status)) {
514
+ return {
515
+ issues: [{
516
+ message: 'Persisted snapshot has invalid status.'
517
+ }]
518
+ };
519
+ }
520
+ for (const key of ['children', 'historyValue', 'timers']) {
521
+ if (snapshot[key] === null || typeof snapshot[key] !== 'object' || Array.isArray(snapshot[key])) {
522
+ return {
523
+ issues: [{
524
+ message: `Persisted snapshot has invalid '${key}'.`
525
+ }]
526
+ };
527
+ }
528
+ }
529
+ try {
530
+ this.resolveState({
531
+ value: snapshot.value,
532
+ context
533
+ });
534
+ } catch (error) {
535
+ return {
536
+ issues: [{
537
+ message: error instanceof Error ? error.message : 'Persisted snapshot has invalid state value.'
538
+ }]
539
+ };
540
+ }
541
+ return {
542
+ value: {
543
+ ...snapshot,
544
+ context
545
+ }
546
+ };
547
+ }
548
+ }
549
+ };
550
+ this.eventSchema = {
551
+ '~standard': {
552
+ version: 1,
553
+ vendor: 'xstate',
554
+ validate: async value => {
555
+ if (value === null || typeof value !== 'object' || typeof value.type !== 'string') {
556
+ return {
557
+ issues: [{
558
+ message: 'Expected an event object.'
559
+ }]
560
+ };
561
+ }
562
+ const event = value;
563
+ const eventSchemas = this.schemas?.events;
564
+ const isFrameworkEvent = event.type.startsWith('xstate.') || event.type.startsWith('@xstate.');
565
+ const schema = eventSchemas && Object.hasOwn(eventSchemas, event.type) ? eventSchemas[event.type] : undefined;
566
+ if (eventSchemas && !schema && !isFrameworkEvent) {
567
+ return {
568
+ issues: [{
569
+ message: `Unknown event '${event.type}' for machine '${this.id}' version '${this.version}'.`
570
+ }]
571
+ };
572
+ }
573
+ if (!schema) {
574
+ return {
575
+ value: event
576
+ };
577
+ }
578
+ const {
579
+ type,
580
+ ...payload
581
+ } = event;
582
+ const result = await schema['~standard'].validate(payload);
583
+ if (result.issues) {
584
+ return result;
585
+ }
586
+ if (result.value === null || typeof result.value !== 'object') {
587
+ return {
588
+ issues: [{
589
+ message: 'Expected an event payload.'
590
+ }]
591
+ };
592
+ }
593
+ return {
594
+ value: {
595
+ ...result.value,
596
+ type
597
+ }
598
+ };
599
+ }
600
+ }
601
+ };
602
+ this.internalEventDescriptors = this.config.internalEvents ?? [];
603
+ this.options = {
604
+ maxIterations: Infinity,
605
+ ...this.config.options
606
+ };
607
+ this.transition = this.transition.bind(this);
608
+ this.initialTransition = this.initialTransition.bind(this);
609
+ this.getInitialSnapshot = this.getInitialSnapshot.bind(this);
610
+ this.getPersistedSnapshot = this.getPersistedSnapshot.bind(this);
611
+ this.restoreSnapshot = this.restoreSnapshot.bind(this);
612
+ this.start = this.start.bind(this);
613
+ this.root = new StateNode(config, {
614
+ _key: this.id,
615
+ _machine: this
616
+ });
617
+ this.root._initialize();
618
+ formatRouteTransitions(this.root);
619
+ this.root._refreshEventMetadata();
620
+ this._hasEventlessTransitions = Array.from(this.idMap.values()).some(stateNode => !!stateNode.always?.length);
621
+ this.states = this.root.states; // TODO: remove!
622
+ this.events = this.root.events;
623
+ }
624
+
625
+ /**
626
+ * Clones this state machine with the provided sources.
627
+ *
628
+ * @param sources Options (`actions`, `guards`, `actors`, `delays`) to
629
+ * recursively merge with the existing options.
630
+ * @returns A new `StateMachine` instance with the provided sources.
631
+ */
632
+ provide(sources) {
633
+ const {
634
+ actions,
635
+ guards,
636
+ actors,
637
+ delays
638
+ } = this.sources;
639
+ const provided = new StateMachine(this.config, {
640
+ actions: {
641
+ ...actions,
642
+ ...sources.actions
643
+ },
644
+ guards: {
645
+ ...guards,
646
+ ...sources.guards
647
+ },
648
+ actors: {
649
+ ...actors,
650
+ ...sources.actors
651
+ },
652
+ delays: {
653
+ ...delays,
654
+ ...sources.delays
655
+ }
656
+ }, this.validator);
657
+ // Providing sources does not change the serializable definition.
658
+ provided._json = this._json;
659
+ return provided;
660
+ }
661
+ resolveState(config) {
662
+ const resolvedStateValue = resolveStateValue(this.root, config.value);
663
+ const nodeSet = getAllStateNodes(getStateNodes(this.root, resolvedStateValue));
664
+ const nodes = [...nodeSet];
665
+ return createMachineSnapshot({
666
+ _nodes: nodes,
667
+ value: resolvedStateValue,
668
+ context: config.context || {},
669
+ children: {},
670
+ status: isInFinalState(nodeSet, this.root) ? 'done' : config.status || 'active',
671
+ output: config.output,
672
+ error: config.error,
673
+ historyValue: config.historyValue
674
+ }, this);
675
+ }
676
+
677
+ /**
678
+ * Determines the next snapshot given the current `snapshot` and received
679
+ * `event`. Calculates a full macrostep from all microsteps.
680
+ *
681
+ * @param snapshot The current snapshot
682
+ * @param event The received event
683
+ */
684
+ transition(snapshot, event, actorScope) {
685
+ const usesInertScope = !actorScope;
686
+ const resolvedActorScope = actorScope ?? createInertActorScope(this, snapshot);
687
+ if (this.validator) {
688
+ assertValid(this.validator, {
689
+ kind: 'event',
690
+ logic: this,
691
+ event,
692
+ eventOrigin: actorScope && actorScope.self._lastSourceRef ? 'actor' : 'external'
693
+ });
694
+ }
695
+ if (usesInertScope) {
696
+ setInertActorScopeSnapshot(resolvedActorScope, snapshot, false);
697
+ }
698
+ const fastSnapshot = this._transitionFast(snapshot, event, resolvedActorScope);
699
+ if (fastSnapshot) {
700
+ if (usesInertScope) {
701
+ setInertActorScopeSnapshot(resolvedActorScope, fastSnapshot, false);
702
+ }
703
+ const returnedSnapshot = usesInertScope && fastSnapshot !== snapshot ? attachSnapshotActorRef(resolvedActorScope, fastSnapshot) : this._attachPureActorRef(fastSnapshot, resolvedActorScope);
704
+ if (this.validator) {
705
+ assertValid(this.validator, {
706
+ kind: 'result',
707
+ logic: this,
708
+ snapshot: returnedSnapshot,
709
+ effects: []
710
+ });
711
+ }
712
+ return [returnedSnapshot, []];
713
+ }
714
+ const {
715
+ snapshot: nextSnapshot,
716
+ microsteps
717
+ } = macrostep(snapshot, event, resolvedActorScope, []);
718
+ if (usesInertScope) {
719
+ setInertActorScopeSnapshot(resolvedActorScope, nextSnapshot, false);
720
+ }
721
+ const returnedSnapshot = usesInertScope ? nextSnapshot === snapshot ? nextSnapshot : attachSnapshotActorRef(resolvedActorScope, nextSnapshot) : this._attachPureActorRef(nextSnapshot, resolvedActorScope);
722
+ const effects = this._collectEffects(microsteps);
723
+ if (this.validator) {
724
+ assertValid(this.validator, {
725
+ kind: 'result',
726
+ logic: this,
727
+ snapshot: returnedSnapshot,
728
+ effects
729
+ });
730
+ }
731
+ return [returnedSnapshot, effects];
732
+ }
733
+ _collectEffects(microsteps) {
734
+ return microsteps.flatMap(([, actions]) => actions);
735
+ }
736
+ _attachPureActorRef(snapshot, actorScope, skipInitializingActor = false) {
737
+ if (isInertActorScope(actorScope)) {
738
+ return snapshot;
739
+ }
740
+ if (skipInitializingActor && actorScope.self._actorScope === actorScope && actorScope.self._snapshot === undefined) {
741
+ return snapshot;
742
+ }
743
+ setSnapshotActorRef(snapshot, actorScope.self, actorScope.system);
744
+ return snapshot;
745
+ }
746
+ _transitionFast(snapshot, event, actorScope) {
747
+ if (snapshot.status !== 'active' || typeof snapshot.value !== 'string' || this.root.always?.length) {
748
+ return undefined;
749
+ }
750
+ const sourceNode = this.root.states[snapshot.value];
751
+ if (!sourceNode || sourceNode.type !== 'atomic' || sourceNode.exit || sourceNode.invoke.length || sourceNode.always?.length || sourceNode.after?.length) {
752
+ return undefined;
753
+ }
754
+ const transitions = sourceNode.transitions.get(event.type);
755
+ if (transitions?.length !== 1) {
756
+ return undefined;
757
+ }
758
+ const selected = transitions[0];
759
+ if (selected.guard || selected.actions || selected.to || selected.reenter || selected.input || typeof selected.context === 'function' || selected.target && selected.target.length !== 1) {
760
+ return undefined;
761
+ }
762
+ const targetNode = selected.target?.[0] ?? sourceNode;
763
+ const stateChanged = targetNode !== sourceNode;
764
+ if (targetNode.parent !== this.root || targetNode.type !== 'atomic' || stateChanged && (targetNode.entry || targetNode.invoke.length || targetNode.always?.length || targetNode.after?.length)) {
765
+ return undefined;
766
+ }
767
+ const context = selected.context !== undefined ? {
768
+ ...snapshot.context,
769
+ ...selected.context
770
+ } : snapshot.context;
771
+ if (!isInertActorScope(actorScope) && (actorScope.system._hasInspectionObservers?.() ?? true)) {
772
+ const collectedMicrosteps = actorScope.self._collectedMicrosteps || [];
773
+ collectedMicrosteps.push(selected);
774
+ actorScope.self._collectedMicrosteps = collectedMicrosteps;
775
+ }
776
+ return cloneMachineSnapshot(snapshot, {
777
+ ...(context !== snapshot.context ? {
778
+ context
779
+ } : {}),
780
+ ...(stateChanged ? {
781
+ _nodes: [this.root, targetNode]
782
+ } : {})
783
+ });
784
+ }
785
+
786
+ /**
787
+ * Determines the next state given the current `state` and `event`. Calculates
788
+ * a microstep.
789
+ *
790
+ * @param state The current state
791
+ * @param event The received event
792
+ */
793
+ microstep(snapshot, event, actorScope) {
794
+ const {
795
+ microsteps
796
+ } = macrostep(snapshot, event, actorScope, []);
797
+ const snapshots = new Array(microsteps.length);
798
+ for (let i = 0; i < microsteps.length; i++) {
799
+ snapshots[i] = microsteps[i][0];
800
+ }
801
+ return snapshots;
802
+ }
803
+ getTransitionData(snapshot, event, actorScope, selectionResults) {
804
+ return transitionNode(this.root, snapshot.value, snapshot, event, actorScope, selectionResults) || [];
805
+ }
806
+ isInternalEventType(eventType) {
807
+ if (eventType === XSTATE_TIMER) {
808
+ return true;
809
+ }
810
+ for (const descriptor of this.internalEventDescriptors) {
811
+ if (matchesEventDescriptor(eventType, descriptor)) {
812
+ return true;
813
+ }
814
+ }
815
+ return false;
816
+ }
817
+
818
+ /**
819
+ * Determines whether sending the `event` to the given snapshot would select a
820
+ * non-forbidden transition. Backs `snapshot.can(...)`; lives here so that
821
+ * non-machine bundles don't pay for the transition-resolution machinery.
822
+ *
823
+ * @internal
824
+ */
825
+ _canTransition(snapshot, event) {
826
+ const emptyActorScope = getEmptyCanActorScope();
827
+ const transitionData = this.getTransitionData(snapshot, event, emptyActorScope);
828
+ if (!transitionData?.length) {
829
+ return false;
830
+ }
831
+
832
+ // Check that at least one transition is not forbidden
833
+ for (const transition of transitionData) {
834
+ if (transition.target !== undefined) {
835
+ return true;
836
+ }
837
+ const res = getTransitionResult(transition, snapshot, event, emptyActorScope, {
838
+ resolveActions: false
839
+ });
840
+ if (res.targets?.length || res.context || hasEffect(transition, snapshot.context, event, snapshot, emptyActorScope)) {
841
+ return true;
842
+ }
843
+ }
844
+ return false;
845
+ }
846
+
847
+ /**
848
+ * Returns the error event that the actor should transition with to recover
849
+ * from an execution error, if any active state node declares `onError`.
850
+ *
851
+ * @internal
852
+ */
853
+ getExecutionErrorEvent(snapshot, error) {
854
+ if (snapshot?.status !== 'active' || !snapshot.nodes?.some(stateNode => stateNode.config.onError)) {
855
+ return undefined;
856
+ }
857
+ return createErrorPlatformEvent('execution', error);
858
+ }
859
+
860
+ /**
861
+ * The initial state _before_ evaluating any microsteps. This "pre-initial"
862
+ * state is provided to initial actions executed in the initial state.
863
+ *
864
+ * @internal
865
+ */
866
+ _getPreInitialState(actorScope, initEvent) {
867
+ const {
868
+ context
869
+ } = this.config;
870
+ const preInitial = createMachineSnapshot({
871
+ context: typeof context !== 'function' && context ? context : {},
872
+ _nodes: [this.root],
873
+ children: {},
874
+ status: 'active'
875
+ }, this);
876
+ if (typeof context === 'function') {
877
+ const children = {};
878
+ const spawn = createSpawner(actorScope, this.sources.actors, children);
879
+ const resolvedContext = context(withActorSelf({
880
+ spawn,
881
+ input: initEvent.input,
882
+ actors: this.sources.actors
883
+ }, actorScope));
884
+ const [nextState] = resolveActionsWithContext(preInitial, initEvent, actorScope, []);
885
+ if (resolvedContext) {
886
+ nextState.context = resolvedContext;
887
+ }
888
+ if (Object.keys(children).length > 0) {
889
+ nextState.children = {
890
+ ...nextState.children,
891
+ ...children
892
+ };
893
+ }
894
+ return nextState;
895
+ }
896
+ return preInitial;
897
+ }
898
+
899
+ /**
900
+ * Returns the initial `State` instance, with reference to `self` as an
901
+ * `ActorRef`.
902
+ */
903
+ getInitialSnapshot(actorScope, input) {
904
+ return this.initialTransition(input, actorScope)[0];
905
+ }
906
+ initialTransition(input, actorScope) {
907
+ if (this.validator) {
908
+ assertValid(this.validator, {
909
+ kind: 'input',
910
+ logic: this,
911
+ input
912
+ });
913
+ }
914
+ const usesInertScope = !actorScope;
915
+ const resolvedActorScope = actorScope ?? createInertActorScope(this);
916
+ const initEvent = createInitEvent(input); // TODO: fix;
917
+ const internalQueue = [];
918
+ const preInitialState = this._getPreInitialState(resolvedActorScope, initEvent);
919
+ const contextSpawnEffects = Object.values(preInitialState.children).filter(Boolean).map(actor => createSpawnEffect(actor));
920
+ const finalizeInitialResult = (macroState, microsteps) => {
921
+ if (usesInertScope) {
922
+ setInertActorScopeSnapshot(resolvedActorScope, macroState, false);
923
+ }
924
+ const returnedSnapshot = usesInertScope ? attachSnapshotActorRef(resolvedActorScope, macroState) : this._attachPureActorRef(macroState, resolvedActorScope, true);
925
+ const effects = this._collectEffects(microsteps);
926
+ if (this.validator) {
927
+ assertValid(this.validator, {
928
+ kind: 'result',
929
+ logic: this,
930
+ snapshot: returnedSnapshot,
931
+ effects
932
+ });
933
+ }
934
+ return [returnedSnapshot, effects];
935
+ };
936
+ try {
937
+ const [nextState, initialActions] = initialMicrostep(this.root, preInitialState, resolvedActorScope, initEvent, internalQueue);
938
+ const {
939
+ snapshot: macroState,
940
+ microsteps
941
+ } = macrostep(nextState, initEvent, resolvedActorScope, internalQueue, [[nextState, [...contextSpawnEffects, ...initialActions]]]);
942
+ return finalizeInitialResult(macroState, microsteps);
943
+ } catch (err) {
944
+ if (!this.root.config.onError) {
945
+ throw err;
946
+ }
947
+ const errorEvent = createErrorPlatformEvent('execution', err);
948
+ const errorMacrostep = macrostep(preInitialState, errorEvent, resolvedActorScope, [], [[preInitialState, contextSpawnEffects]]);
949
+ return finalizeInitialResult(errorMacrostep.snapshot, errorMacrostep.microsteps);
950
+ }
951
+ }
952
+ start(snapshot) {
953
+ // Start rehydrated children that were active when persisted. Freshly
954
+ // invoked/spawned children are NOT started here — they start via deferred
955
+ // `@xstate.start` actions so sync start errors route to `onError`.
956
+ if (!snapshot?.children) {
957
+ return;
958
+ }
959
+ const children = snapshot.children;
960
+ for (const childId in children) {
961
+ if (!Object.hasOwn(children, childId)) {
962
+ continue;
963
+ }
964
+ const child = children[childId];
965
+ if (child._rehydrated && child.getSnapshot?.().status === 'active') {
966
+ child.start();
967
+ }
968
+ }
969
+ }
970
+ getStateNodeById(stateId) {
971
+ const fullPath = toStatePath(stateId);
972
+ const relativePath = fullPath.slice(1);
973
+ const resolvedStateId = isStateId(fullPath[0]) ? fullPath[0].slice(STATE_IDENTIFIER.length) : fullPath[0];
974
+ const stateNode = this.idMap.get(resolvedStateId);
975
+ if (!stateNode) {
976
+ throw new Error(`Child state node '#${resolvedStateId}' does not exist on machine '${this.id}'`);
977
+ }
978
+ return getStateNodeByPath(stateNode, relativePath);
979
+ }
980
+ getPersistedSnapshot(snapshot, options) {
981
+ return getPersistedSnapshot(snapshot, options);
982
+ }
983
+ restoreSnapshot(snapshot, actorScope) {
984
+ const usesInertScope = !actorScope;
985
+ const resolvedActorScope = actorScope ?? createInertActorScope(this);
986
+ const persistedMachine = snapshot.machine;
987
+ const legacyPersistedVersion = snapshot.version;
988
+ const persistedVersion = typeof persistedMachine?.version === 'string' ? persistedMachine.version : legacyPersistedVersion;
989
+ if (legacyPersistedVersion !== undefined && persistedMachine?.version !== undefined && persistedMachine.version !== legacyPersistedVersion) {
990
+ throw new Error(`Persisted snapshot version '${legacyPersistedVersion}' conflicts with machine version '${persistedMachine.version}'.`);
991
+ }
992
+ if (persistedMachine && typeof persistedMachine.id === 'string' && persistedMachine.id !== this.id) {
993
+ throw new Error(`Machine ID mismatch: persisted snapshot machine '${persistedMachine.id}' does not match '${this.id}'.`);
994
+ }
995
+ if (persistedVersion !== this.version) {
996
+ const migrate = this.config.migrate;
997
+ if (typeof migrate !== 'function') {
998
+ throw new Error(`Persisted snapshot version '${persistedVersion}' does not match machine version '${this.version}'.`);
999
+ }
1000
+ snapshot = migrate(snapshot, persistedVersion);
1001
+ }
1002
+ const snapshotData = snapshot;
1003
+ const children = {};
1004
+ const snapshotChildren = snapshotData.children;
1005
+ for (const actorId of Object.keys(snapshotChildren)) {
1006
+ const actorData = snapshotChildren[actorId];
1007
+ const childState = actorData.snapshot;
1008
+ const src = actorData.src;
1009
+ const logic = typeof src === 'string' ? resolveReferencedActor(this, src) : src;
1010
+ if (!logic) {
1011
+ const sourceId = typeof src === 'string' ? src : '<unknown>';
1012
+ throw new Error(`Unable to restore child actor '${actorId}': child source '${sourceId}' is not provided in machine '${this.id}'.`);
1013
+ }
1014
+ const actor = resolvedActorScope.system.createActorRef(logic, {
1015
+ id: actorId,
1016
+ parent: resolvedActorScope.self,
1017
+ syncSnapshot: actorData.syncSnapshot,
1018
+ snapshot: childState,
1019
+ src,
1020
+ registryKey: actorData.registryKey
1021
+ });
1022
+ // Mark so `start()` knows to start this child (freshly invoked/spawned
1023
+ // children are started via deferred `@xstate.start` actions instead).
1024
+ actor._rehydrated = true;
1025
+ children[actorId] = actor;
1026
+ }
1027
+ const timers = {};
1028
+ const persistedTimers = snapshotData.timers ?? {};
1029
+ for (const [id, timer] of Object.entries(persistedTimers)) {
1030
+ let event = timer.event;
1031
+ if (event.type === 'xstate.timeout.actor') {
1032
+ const actorId = event.actorId;
1033
+ const child = children[actorId];
1034
+ if (child) {
1035
+ event = createInvokeTimeoutEvent(actorId, child.sessionId);
1036
+ }
1037
+ }
1038
+ const target = typeof timer.target === 'string' ? timer.target === 'self' ? 'self' : children[timer.target] : resolvedActorScope.self._parent;
1039
+ if (!target) {
1040
+ const targetDescription = typeof timer.target === 'string' ? timer.target : timer.target.type;
1041
+ throw new Error(`Unable to restore timer '${id}': target actor '${targetDescription}' is unavailable.`);
1042
+ }
1043
+ timers[id] = {
1044
+ ...timer,
1045
+ event,
1046
+ target
1047
+ };
1048
+ }
1049
+ const reviveHistoryValue = historyValue => {
1050
+ if (!historyValue || typeof historyValue !== 'object') {
1051
+ return {};
1052
+ }
1053
+ const revived = {};
1054
+ for (const key of Object.keys(historyValue)) {
1055
+ const arr = historyValue[key];
1056
+ for (const item of arr) {
1057
+ let resolved;
1058
+ if (item instanceof StateNode) {
1059
+ resolved = item;
1060
+ } else {
1061
+ try {
1062
+ resolved = this.root.machine.getStateNodeById(item.id);
1063
+ } catch {
1064
+ }
1065
+ }
1066
+ if (!resolved) {
1067
+ continue;
1068
+ }
1069
+ revived[key] ??= [];
1070
+ revived[key].push(resolved);
1071
+ }
1072
+ }
1073
+ return revived;
1074
+ };
1075
+ const revivedHistoryValue = reviveHistoryValue(snapshotData.historyValue);
1076
+ const validateStateValue = (stateValue, node, path) => {
1077
+ const missingStateError = statePath => new Error(`Persisted snapshot references state '${statePath.join('.')}' which does not exist on machine '${this.id}'.`);
1078
+ if (typeof stateValue === 'string') {
1079
+ if (!node.states[stateValue]) {
1080
+ throw missingStateError(path.concat(stateValue));
1081
+ }
1082
+ return;
1083
+ }
1084
+ if (!stateValue || typeof stateValue !== 'object') {
1085
+ return;
1086
+ }
1087
+ for (const key of Object.keys(stateValue)) {
1088
+ const childNode = node.states[key];
1089
+ if (!childNode) {
1090
+ throw missingStateError(path.concat(key));
1091
+ }
1092
+ validateStateValue(stateValue[key], childNode, path.concat(key));
1093
+ }
1094
+ };
1095
+ validateStateValue(snapshotData.value, this.root, []);
1096
+ const nodes = Array.from(getAllStateNodes(getStateNodes(this.root, snapshotData.value)));
1097
+ const {
1098
+ version: _persistedSnapshotVersion,
1099
+ ...persistedRest
1100
+ } = snapshot;
1101
+ const restoredSnapshot = createMachineSnapshot({
1102
+ ...persistedRest,
1103
+ children,
1104
+ timers,
1105
+ _nodes: nodes,
1106
+ value: snapshotData.value,
1107
+ historyValue: revivedHistoryValue,
1108
+ _stateInputs: snapshotData.stateInputs ?? {}
1109
+ }, this, resolvedActorScope.self);
1110
+ const seen = new WeakSet();
1111
+ function reviveContext(contextPart) {
1112
+ if (seen.has(contextPart)) {
1113
+ return;
1114
+ }
1115
+ seen.add(contextPart);
1116
+ for (const key of Object.keys(contextPart)) {
1117
+ const value = contextPart[key];
1118
+ if (value && typeof value === 'object') {
1119
+ if ('xstate$$type' in value && value.xstate$$type === $$ACTOR_TYPE) {
1120
+ contextPart[key] = children[value.id];
1121
+ continue;
1122
+ }
1123
+ reviveContext(value);
1124
+ }
1125
+ }
1126
+ }
1127
+ reviveContext(restoredSnapshot.context);
1128
+ if (usesInertScope) {
1129
+ setInertActorScopeSnapshot(resolvedActorScope, restoredSnapshot, false);
1130
+ return attachSnapshotActorRef(resolvedActorScope, restoredSnapshot);
1131
+ }
1132
+ return this._attachPureActorRef(restoredSnapshot, resolvedActorScope);
1133
+ }
1134
+ }
1135
+
1136
+ export { StateMachine as S, StateNode as a };