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