xstate 6.0.0-alpha.4 → 6.0.0-alpha.41

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