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