xstate 5.32.1 → 6.0.0-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/README.md +7 -8
  2. package/dist/StateMachine-2dcdb1f5.esm.js +720 -0
  3. package/dist/StateMachine-2ea0a7fa.development.esm.js +737 -0
  4. package/dist/StateMachine-64813f46.cjs.js +723 -0
  5. package/dist/StateMachine-8d22a79c.development.cjs.js +740 -0
  6. package/dist/declarations/src/State.d.ts +11 -13
  7. package/dist/declarations/src/StateMachine.d.ts +27 -21
  8. package/dist/declarations/src/StateNode.d.ts +18 -54
  9. package/dist/declarations/src/actions.d.ts +14 -9
  10. package/dist/declarations/src/actors/callback.d.ts +42 -16
  11. package/dist/declarations/src/actors/index.d.ts +9 -6
  12. package/dist/declarations/src/actors/listener.d.ts +18 -0
  13. package/dist/declarations/src/actors/logic.d.ts +105 -0
  14. package/dist/declarations/src/actors/observable.d.ts +72 -27
  15. package/dist/declarations/src/actors/promise.d.ts +133 -48
  16. package/dist/declarations/src/actors/subscription.d.ts +22 -0
  17. package/dist/declarations/src/atom.d.ts +81 -0
  18. package/dist/declarations/src/createActor.d.ts +31 -33
  19. package/dist/declarations/src/createMachine.d.ts +35 -7
  20. package/dist/declarations/src/createMachineFromConfig.d.ts +176 -0
  21. package/dist/declarations/src/graph/graph.d.ts +4 -2
  22. package/dist/declarations/src/index.d.ts +12 -8
  23. package/dist/declarations/src/inspection.d.ts +84 -30
  24. package/dist/declarations/src/mapState.d.ts +4 -2
  25. package/dist/declarations/src/schema.types.d.ts +90 -0
  26. package/dist/declarations/src/serialize.d.ts +44 -0
  27. package/dist/declarations/src/setup.d.ts +251 -135
  28. package/dist/declarations/src/spawn.d.ts +6 -31
  29. package/dist/declarations/src/stateUtils.d.ts +21 -19
  30. package/dist/declarations/src/system.d.ts +8 -7
  31. package/dist/declarations/src/transition.d.ts +5 -5
  32. package/dist/declarations/src/types.d.ts +405 -405
  33. package/dist/declarations/src/types.v6.d.ts +392 -0
  34. package/dist/declarations/src/utils.d.ts +4 -3
  35. package/dist/index-93edd3bd.esm.js +4909 -0
  36. package/dist/index-9cb3b3a0.cjs.js +4968 -0
  37. package/dist/index-e61170ba.development.esm.js +4948 -0
  38. package/dist/index-f6ef20d1.development.cjs.js +5007 -0
  39. package/dist/xstate-actors.cjs.js +12 -838
  40. package/dist/xstate-actors.cjs.mjs +10 -5
  41. package/dist/xstate-actors.development.cjs.js +12 -838
  42. package/dist/xstate-actors.development.cjs.mjs +10 -5
  43. package/dist/xstate-actors.development.esm.js +1 -836
  44. package/dist/xstate-actors.esm.js +1 -836
  45. package/dist/xstate-actors.umd.min.js +1 -1
  46. package/dist/xstate-actors.umd.min.js.map +1 -1
  47. package/dist/xstate-graph.cjs.js +18 -29
  48. package/dist/xstate-graph.development.cjs.js +18 -29
  49. package/dist/xstate-graph.development.esm.js +15 -26
  50. package/dist/xstate-graph.esm.js +15 -26
  51. package/dist/xstate-graph.umd.min.js +1 -1
  52. package/dist/xstate-graph.umd.min.js.map +1 -1
  53. package/dist/xstate.cjs.js +1316 -112
  54. package/dist/xstate.cjs.mjs +22 -22
  55. package/dist/xstate.development.cjs.js +1316 -112
  56. package/dist/xstate.development.cjs.mjs +22 -22
  57. package/dist/xstate.development.esm.js +1278 -76
  58. package/dist/xstate.esm.js +1278 -76
  59. package/dist/xstate.umd.min.js +1 -1
  60. package/dist/xstate.umd.min.js.map +1 -1
  61. package/package.json +3 -47
  62. package/dist/StateMachine-45e79c35.esm.js +0 -560
  63. package/dist/StateMachine-be2e51a3.development.cjs.js +0 -569
  64. package/dist/StateMachine-e0178d48.development.esm.js +0 -566
  65. package/dist/StateMachine-e6732977.cjs.js +0 -563
  66. package/dist/assign-2aa58daa.esm.js +0 -127
  67. package/dist/assign-927227d6.development.cjs.js +0 -135
  68. package/dist/assign-e8f2bd75.cjs.js +0 -129
  69. package/dist/assign-f338cee3.development.esm.js +0 -133
  70. package/dist/declarations/src/actions/assign.d.ts +0 -45
  71. package/dist/declarations/src/actions/cancel.d.ts +0 -39
  72. package/dist/declarations/src/actions/emit.d.ts +0 -44
  73. package/dist/declarations/src/actions/enqueueActions.d.ts +0 -57
  74. package/dist/declarations/src/actions/log.d.ts +0 -16
  75. package/dist/declarations/src/actions/raise.d.ts +0 -21
  76. package/dist/declarations/src/actions/send.d.ts +0 -42
  77. package/dist/declarations/src/actions/spawnChild.d.ts +0 -34
  78. package/dist/declarations/src/actions/stopChild.d.ts +0 -19
  79. package/dist/declarations/src/actors/transition.d.ts +0 -143
  80. package/dist/declarations/src/dev/index.d.ts +0 -14
  81. package/dist/declarations/src/guards.d.ts +0 -128
  82. package/dist/log-410e5e55.development.esm.js +0 -429
  83. package/dist/log-7776fcf2.cjs.js +0 -409
  84. package/dist/log-c2e11c01.development.cjs.js +0 -437
  85. package/dist/log-fa75ec2d.esm.js +0 -401
  86. package/dist/raise-74097812.development.esm.js +0 -2823
  87. package/dist/raise-7c948725.cjs.js +0 -2816
  88. package/dist/raise-964cd4e9.development.cjs.js +0 -2878
  89. package/dist/raise-e974d1c9.esm.js +0 -2761
  90. package/dist/xstate-actions.cjs.d.mts +0 -2
  91. package/dist/xstate-actions.cjs.d.ts +0 -2
  92. package/dist/xstate-actions.cjs.js +0 -23
  93. package/dist/xstate-actions.cjs.mjs +0 -14
  94. package/dist/xstate-actions.development.cjs.js +0 -23
  95. package/dist/xstate-actions.development.cjs.mjs +0 -14
  96. package/dist/xstate-actions.development.esm.js +0 -4
  97. package/dist/xstate-actions.esm.js +0 -4
  98. package/dist/xstate-actions.umd.min.js +0 -2
  99. package/dist/xstate-actions.umd.min.js.map +0 -1
  100. package/dist/xstate-dev.cjs.d.mts +0 -2
  101. package/dist/xstate-dev.cjs.d.ts +0 -2
  102. package/dist/xstate-dev.cjs.js +0 -48
  103. package/dist/xstate-dev.cjs.mjs +0 -5
  104. package/dist/xstate-dev.development.cjs.js +0 -51
  105. package/dist/xstate-dev.development.cjs.mjs +0 -5
  106. package/dist/xstate-dev.development.esm.js +0 -45
  107. package/dist/xstate-dev.esm.js +0 -42
  108. package/dist/xstate-dev.umd.min.js +0 -2
  109. package/dist/xstate-dev.umd.min.js.map +0 -1
  110. package/dist/xstate-guards.cjs.d.mts +0 -2
  111. package/dist/xstate-guards.cjs.d.ts +0 -2
  112. package/dist/xstate-guards.cjs.js +0 -14
  113. package/dist/xstate-guards.cjs.mjs +0 -7
  114. package/dist/xstate-guards.development.cjs.js +0 -14
  115. package/dist/xstate-guards.development.cjs.mjs +0 -7
  116. package/dist/xstate-guards.development.esm.js +0 -2
  117. package/dist/xstate-guards.esm.js +0 -2
  118. package/dist/xstate-guards.umd.min.js +0 -2
  119. package/dist/xstate-guards.umd.min.js.map +0 -1
@@ -0,0 +1,4948 @@
1
+ /**
2
+ * Reactivity interop between actors and atoms.
3
+ *
4
+ * `Actor#get()` calls this hook (when installed) so that computed atoms can
5
+ * track actor reads as dependencies. The hook is installed by `atom.ts` on
6
+ * module evaluation, which only happens when atoms are actually used — apps
7
+ * that never import atoms don't bundle the reactive system.
8
+ */
9
+ let onActorRead;
10
+ function installActorReadHook(hook) {
11
+ onActorRead = hook;
12
+ }
13
+
14
+ class Mailbox {
15
+ constructor(_process) {
16
+ this._process = _process;
17
+ this._active = false;
18
+ this._current = null;
19
+ this._last = null;
20
+ }
21
+ start() {
22
+ this._active = true;
23
+ this.flush();
24
+ }
25
+ clear() {
26
+ // we can't set _current to null because we might be currently processing
27
+ // and enqueue following clear shouldn't start processing the enqueued item immediately
28
+ if (this._current) {
29
+ this._current.next = null;
30
+ this._last = this._current;
31
+ }
32
+ }
33
+ enqueue(event) {
34
+ const enqueued = {
35
+ value: event,
36
+ next: null
37
+ };
38
+ if (this._current) {
39
+ this._last.next = enqueued;
40
+ this._last = enqueued;
41
+ return;
42
+ }
43
+ this._current = enqueued;
44
+ this._last = enqueued;
45
+ if (this._active) {
46
+ this.flush();
47
+ }
48
+ }
49
+ flush() {
50
+ while (this._current) {
51
+ // atm the given _process is responsible for implementing proper try/catch handling
52
+ // we assume here that this won't throw in a way that can affect this mailbox
53
+ const consumed = this._current;
54
+ this._process(consumed.value);
55
+ this._current = consumed.next;
56
+ }
57
+ this._last = null;
58
+ }
59
+ }
60
+
61
+ const STATE_DELIMITER = '.';
62
+ const TARGETLESS_KEY = '';
63
+ const NULL_EVENT = '';
64
+ const STATE_IDENTIFIER = '#';
65
+ const WILDCARD = '*';
66
+ const XSTATE_INIT = '@xstate.init';
67
+ const XSTATE_STOP = '@xstate.stop';
68
+
69
+ /**
70
+ * Returns an event that represents an implicit event that is sent after the
71
+ * specified `delay`.
72
+ *
73
+ * @param delayRef The delay in milliseconds
74
+ * @param id The state node ID where this event is handled
75
+ */
76
+ function createAfterEvent(delayRef, id) {
77
+ return {
78
+ type: `xstate.after.${delayRef}.${id}`
79
+ };
80
+ }
81
+
82
+ /**
83
+ * Returns an event that represents an implicit state-level timeout. Fired when
84
+ * a state's `timeout` duration elapses without the state being exited.
85
+ *
86
+ * @param id The state node ID where this timeout is configured
87
+ */
88
+ function createTimeoutEvent(id) {
89
+ return {
90
+ type: `xstate.timeout.${id}`
91
+ };
92
+ }
93
+
94
+ /**
95
+ * Returns an event that represents an implicit invoke-level timeout. Fired when
96
+ * an invoked actor has not completed within its `timeout` duration.
97
+ *
98
+ * @param invokeId The invoked actor's ID
99
+ */
100
+ function createInvokeTimeoutEvent(invokeId) {
101
+ return {
102
+ type: `xstate.timeout.actor.${invokeId}`
103
+ };
104
+ }
105
+
106
+ /**
107
+ * Returns an event that represents that a final state node has been reached in
108
+ * the parent state node.
109
+ *
110
+ * @param id The final state node's parent state node `id`
111
+ * @param output The data to pass into the event
112
+ */
113
+ function createDoneStateEvent(id, output) {
114
+ return {
115
+ type: `xstate.done.state.${id}`,
116
+ output
117
+ };
118
+ }
119
+
120
+ /**
121
+ * Returns an event that represents that an invoked service has terminated.
122
+ *
123
+ * An invoked service is terminated when it has reached a top-level final state
124
+ * node, but not when it is canceled.
125
+ *
126
+ * @param invokeId The invoked service ID
127
+ * @param output The data to pass into the event
128
+ */
129
+ function createDoneActorEvent(invokeId, output) {
130
+ return {
131
+ type: `xstate.done.actor.${invokeId}`,
132
+ output,
133
+ actorId: invokeId
134
+ };
135
+ }
136
+ function createErrorActorEvent(id, error) {
137
+ return {
138
+ type: `xstate.error.actor.${id}`,
139
+ error,
140
+ actorId: id
141
+ };
142
+ }
143
+ function createInitEvent(input) {
144
+ return {
145
+ type: XSTATE_INIT,
146
+ input
147
+ };
148
+ }
149
+
150
+ /**
151
+ * This function makes sure that unhandled errors are thrown in a separate
152
+ * macrotask. It allows those errors to be detected by global error handlers and
153
+ * reported to bug tracking services without interrupting our own stack of
154
+ * execution.
155
+ *
156
+ * @param err Error to be thrown
157
+ */
158
+ function reportUnhandledError(err) {
159
+ setTimeout(() => {
160
+ throw err;
161
+ });
162
+ }
163
+
164
+ const symbolObservable = (() => typeof Symbol === 'function' && Symbol.observable || '@@observable')();
165
+
166
+ const builtInActions = {
167
+ ['@xstate.start']: actor => {
168
+ actor.start();
169
+ },
170
+ ['@xstate.raise']: (actorScope, event, options) => {
171
+ actorScope.system.scheduler.schedule(actorScope.self, actorScope.self, event, options?.delay ?? 0, options?.id);
172
+ },
173
+ ['@xstate.sendTo']: (actorScope, actor, event, options) => {
174
+ if (typeof event === 'string') {
175
+ throw new Error(// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
176
+ `Only event objects may be used with sendTo; use sendTo({ type: "${event}" }) instead` );
177
+ }
178
+ if (options?.delay !== undefined) {
179
+ actorScope.system.scheduler.schedule(actorScope.self, actor, event, options?.delay ?? 0, options?.id);
180
+ } else {
181
+ actorScope.defer(() => {
182
+ actorScope.system._relay(actorScope.self, actor, event);
183
+ });
184
+ }
185
+ },
186
+ ['@xstate.cancel']: (actorScope, sendId) => {
187
+ actorScope.system.scheduler.cancel(actorScope.self, sendId);
188
+ },
189
+ ['@xstate.stopChild']: (actorScope, actor) => {
190
+ actorScope.stopChild(actor);
191
+ }
192
+ };
193
+
194
+ const subscriptions = /* #__PURE__ */new WeakMap();
195
+
196
+ /**
197
+ * Internal factory for actor logic that attaches to another actor on start
198
+ * (`enq.listen()` / `enq.subscribeTo()`) and detaches when stopped.
199
+ */
200
+ function createAttachedLogic(attach) {
201
+ return {
202
+ start: (state, {
203
+ self,
204
+ system
205
+ }) => {
206
+ // Don't attach if the target doesn't exist, or (for actors) is stopped.
207
+ // Atoms have no `getSnapshot` / lifecycle, so they always attach.
208
+ const target = state.input.actor;
209
+ if (!target || typeof target.getSnapshot === 'function' && target.getSnapshot().status === 'stopped') {
210
+ return;
211
+ }
212
+ const subscription = attach(state.input, {
213
+ self,
214
+ system
215
+ });
216
+ if (!subscription) {
217
+ return;
218
+ }
219
+
220
+ // Attached actors are not registered as children (their `input` holds
221
+ // non-serializable function mappers), so a parent stop does not cascade
222
+ // to them. Subscribe to the parent and tear down when it stops/errors,
223
+ // so the subscription never relays to a stopped parent or leaks the
224
+ // source subscription.
225
+ let parentSubscription;
226
+ let torndown = false;
227
+ const teardown = () => {
228
+ if (torndown) {
229
+ return;
230
+ }
231
+ torndown = true;
232
+ subscription.unsubscribe();
233
+ parentSubscription?.unsubscribe();
234
+ };
235
+ const parent = self._parent;
236
+ if (parent) {
237
+ parentSubscription = parent.subscribe({
238
+ complete: teardown,
239
+ error: teardown
240
+ });
241
+ }
242
+ subscriptions.set(self, {
243
+ unsubscribe: teardown
244
+ });
245
+ },
246
+ transition: (state, event, {
247
+ self
248
+ }) => {
249
+ if (event.type === XSTATE_STOP) {
250
+ subscriptions.get(self)?.unsubscribe();
251
+ subscriptions.delete(self);
252
+ return {
253
+ ...state,
254
+ status: 'stopped',
255
+ error: undefined
256
+ };
257
+ }
258
+ return state;
259
+ },
260
+ getInitialSnapshot: (_, input) => ({
261
+ status: 'active',
262
+ output: undefined,
263
+ error: undefined,
264
+ input
265
+ }),
266
+ getPersistedSnapshot: snapshot => snapshot,
267
+ restoreSnapshot: snapshot => snapshot
268
+ };
269
+ }
270
+
271
+ /**
272
+ * Relays a mapped event to the attached actor's parent, unless the attached
273
+ * actor has been stopped (the mapper is not called in that case).
274
+ */
275
+ function relayMappedToParent(self, system, getEvent) {
276
+ if (self.getSnapshot().status === 'stopped' || !self._parent) {
277
+ return;
278
+ }
279
+ system._relay(self, self._parent, getEvent());
280
+ }
281
+
282
+ /**
283
+ * Creates actor logic for listening to emitted events from another actor. Used
284
+ * internally by `enq.listen()`.
285
+ */
286
+ function createListenerLogic() {
287
+ return createAttachedLogic(({
288
+ actor,
289
+ eventType,
290
+ mapper
291
+ }, {
292
+ self,
293
+ system
294
+ }) => {
295
+ // Determine the subscription type:
296
+ // - For exact matches or '*', subscribe directly
297
+ // - For partial wildcards ('data.*'), subscribe to '*' and filter
298
+ const isPartialWildcard = eventType !== '*' && eventType.endsWith('.*');
299
+ return actor.on(isPartialWildcard ? '*' : eventType, emittedEvent => {
300
+ if (isPartialWildcard && !matchesEventDescriptor(emittedEvent.type, eventType)) {
301
+ return;
302
+ }
303
+ relayMappedToParent(self, system, () => mapper(emittedEvent));
304
+ });
305
+ });
306
+ }
307
+
308
+ // Singleton logic instance
309
+ const listenerLogic = /* #__PURE__ */createListenerLogic();
310
+
311
+ /* eslint-disable */
312
+ // Adapted from Alien Signals
313
+ // https://github.com/stackblitz/alien-signals/
314
+
315
+ let ReactiveFlags = /*#__PURE__*/function (ReactiveFlags) {
316
+ ReactiveFlags[ReactiveFlags["None"] = 0] = "None";
317
+ ReactiveFlags[ReactiveFlags["Mutable"] = 1] = "Mutable";
318
+ ReactiveFlags[ReactiveFlags["Watching"] = 2] = "Watching";
319
+ ReactiveFlags[ReactiveFlags["RecursedCheck"] = 4] = "RecursedCheck";
320
+ ReactiveFlags[ReactiveFlags["Recursed"] = 8] = "Recursed";
321
+ ReactiveFlags[ReactiveFlags["Dirty"] = 16] = "Dirty";
322
+ ReactiveFlags[ReactiveFlags["Pending"] = 32] = "Pending";
323
+ return ReactiveFlags;
324
+ }({});
325
+ function createReactiveSystem({
326
+ update,
327
+ notify,
328
+ unwatched
329
+ }) {
330
+ return {
331
+ link,
332
+ unlink,
333
+ propagate,
334
+ checkDirty,
335
+ shallowPropagate
336
+ };
337
+ function link(dep, sub, version) {
338
+ const prevDep = sub.depsTail;
339
+ if (prevDep !== undefined && prevDep.dep === dep) {
340
+ return;
341
+ }
342
+ const nextDep = prevDep !== undefined ? prevDep.nextDep : sub.deps;
343
+ if (nextDep !== undefined && nextDep.dep === dep) {
344
+ nextDep.version = version;
345
+ sub.depsTail = nextDep;
346
+ return;
347
+ }
348
+ const prevSub = dep.subsTail;
349
+ if (prevSub !== undefined && prevSub.version === version && prevSub.sub === sub) {
350
+ return;
351
+ }
352
+ const newLink = sub.depsTail = dep.subsTail = {
353
+ version,
354
+ dep,
355
+ sub,
356
+ prevDep,
357
+ nextDep,
358
+ prevSub,
359
+ nextSub: undefined
360
+ };
361
+ if (nextDep !== undefined) {
362
+ nextDep.prevDep = newLink;
363
+ }
364
+ if (prevDep !== undefined) {
365
+ prevDep.nextDep = newLink;
366
+ } else {
367
+ sub.deps = newLink;
368
+ }
369
+ if (prevSub !== undefined) {
370
+ prevSub.nextSub = newLink;
371
+ } else {
372
+ dep.subs = newLink;
373
+ }
374
+ }
375
+ function unlink(link, sub = link.sub) {
376
+ const dep = link.dep;
377
+ const prevDep = link.prevDep;
378
+ const nextDep = link.nextDep;
379
+ const nextSub = link.nextSub;
380
+ const prevSub = link.prevSub;
381
+ if (nextDep !== undefined) {
382
+ nextDep.prevDep = prevDep;
383
+ } else {
384
+ sub.depsTail = prevDep;
385
+ }
386
+ if (prevDep !== undefined) {
387
+ prevDep.nextDep = nextDep;
388
+ } else {
389
+ sub.deps = nextDep;
390
+ }
391
+ if (nextSub !== undefined) {
392
+ nextSub.prevSub = prevSub;
393
+ } else {
394
+ dep.subsTail = prevSub;
395
+ }
396
+ if (prevSub !== undefined) {
397
+ prevSub.nextSub = nextSub;
398
+ } else if ((dep.subs = nextSub) === undefined) {
399
+ unwatched(dep);
400
+ }
401
+ return nextDep;
402
+ }
403
+ function propagate(link) {
404
+ let next = link.nextSub;
405
+ let stack;
406
+ top: do {
407
+ const sub = link.sub;
408
+ let flags = sub.flags;
409
+ if (!(flags & (ReactiveFlags.RecursedCheck | ReactiveFlags.Recursed | ReactiveFlags.Dirty | ReactiveFlags.Pending))) {
410
+ sub.flags = flags | ReactiveFlags.Pending;
411
+ } else if (!(flags & (ReactiveFlags.RecursedCheck | ReactiveFlags.Recursed))) {
412
+ flags = ReactiveFlags.None;
413
+ } else if (!(flags & ReactiveFlags.RecursedCheck)) {
414
+ sub.flags = flags & ~ReactiveFlags.Recursed | ReactiveFlags.Pending;
415
+ } else if (!(flags & (ReactiveFlags.Dirty | ReactiveFlags.Pending)) && isValidLink(link, sub)) {
416
+ sub.flags = flags | (ReactiveFlags.Recursed | ReactiveFlags.Pending);
417
+ flags &= ReactiveFlags.Mutable;
418
+ } else {
419
+ flags = ReactiveFlags.None;
420
+ }
421
+ if (flags & ReactiveFlags.Watching) {
422
+ notify(sub);
423
+ }
424
+ if (flags & ReactiveFlags.Mutable) {
425
+ const subSubs = sub.subs;
426
+ if (subSubs !== undefined) {
427
+ const nextSub = (link = subSubs).nextSub;
428
+ if (nextSub !== undefined) {
429
+ stack = {
430
+ value: next,
431
+ prev: stack
432
+ };
433
+ next = nextSub;
434
+ }
435
+ continue;
436
+ }
437
+ }
438
+ if ((link = next) !== undefined) {
439
+ next = link.nextSub;
440
+ continue;
441
+ }
442
+ while (stack !== undefined) {
443
+ link = stack.value;
444
+ stack = stack.prev;
445
+ if (link !== undefined) {
446
+ next = link.nextSub;
447
+ continue top;
448
+ }
449
+ }
450
+ break;
451
+ } while (true);
452
+ }
453
+ function checkDirty(link, sub) {
454
+ let stack;
455
+ let checkDepth = 0;
456
+ let dirty = false;
457
+ top: do {
458
+ const dep = link.dep;
459
+ const flags = dep.flags;
460
+ if (sub.flags & ReactiveFlags.Dirty) {
461
+ dirty = true;
462
+ } else if ((flags & (ReactiveFlags.Mutable | ReactiveFlags.Dirty)) === (ReactiveFlags.Mutable | ReactiveFlags.Dirty)) {
463
+ if (update(dep)) {
464
+ const subs = dep.subs;
465
+ if (subs.nextSub !== undefined) {
466
+ shallowPropagate(subs);
467
+ }
468
+ dirty = true;
469
+ }
470
+ } else if ((flags & (ReactiveFlags.Mutable | ReactiveFlags.Pending)) === (ReactiveFlags.Mutable | ReactiveFlags.Pending)) {
471
+ if (link.nextSub !== undefined || link.prevSub !== undefined) {
472
+ stack = {
473
+ value: link,
474
+ prev: stack
475
+ };
476
+ }
477
+ link = dep.deps;
478
+ sub = dep;
479
+ ++checkDepth;
480
+ continue;
481
+ }
482
+ if (!dirty) {
483
+ const nextDep = link.nextDep;
484
+ if (nextDep !== undefined) {
485
+ link = nextDep;
486
+ continue;
487
+ }
488
+ }
489
+ while (checkDepth--) {
490
+ const firstSub = sub.subs;
491
+ const hasMultipleSubs = firstSub.nextSub !== undefined;
492
+ if (hasMultipleSubs) {
493
+ link = stack.value;
494
+ stack = stack.prev;
495
+ } else {
496
+ link = firstSub;
497
+ }
498
+ if (dirty) {
499
+ if (update(sub)) {
500
+ if (hasMultipleSubs) {
501
+ shallowPropagate(firstSub);
502
+ }
503
+ sub = link.sub;
504
+ continue;
505
+ }
506
+ dirty = false;
507
+ } else {
508
+ sub.flags &= ~ReactiveFlags.Pending;
509
+ }
510
+ sub = link.sub;
511
+ const nextDep = link.nextDep;
512
+ if (nextDep !== undefined) {
513
+ link = nextDep;
514
+ continue top;
515
+ }
516
+ }
517
+ return dirty;
518
+ } while (true);
519
+ }
520
+ function shallowPropagate(link) {
521
+ do {
522
+ const sub = link.sub;
523
+ const flags = sub.flags;
524
+ if ((flags & (ReactiveFlags.Pending | ReactiveFlags.Dirty)) === ReactiveFlags.Pending) {
525
+ sub.flags = flags | ReactiveFlags.Dirty;
526
+ if ((flags & (ReactiveFlags.Watching | ReactiveFlags.RecursedCheck)) === ReactiveFlags.Watching) {
527
+ notify(sub);
528
+ }
529
+ }
530
+ } while ((link = link.nextSub) !== undefined);
531
+ }
532
+ function isValidLink(checkLink, sub) {
533
+ let link = sub.depsTail;
534
+ while (link !== undefined) {
535
+ if (link === checkLink) {
536
+ return true;
537
+ }
538
+ link = link.prevDep;
539
+ }
540
+ return false;
541
+ }
542
+ }
543
+
544
+ /**
545
+ * Nominal brand (phantom, compile-time only) marking a value as an XState atom.
546
+ * Real atoms get the runtime brand ({@link $$atom}) in `createAtom`; this type
547
+ * brand keeps atom-only APIs (e.g. `enq.subscribeTo`) from structurally
548
+ * accepting plain readables like `actor.select(...)` that would be dispatched
549
+ * down the non-atom path at runtime.
550
+ */
551
+
552
+ /** Brand marking an object as an atom, so it can be detected structurally. */
553
+ const $$atom = /* #__PURE__ */Symbol.for('xstate.atom');
554
+
555
+ /**
556
+ * Returns `true` if the value is an atom (writable, computed, async, or
557
+ * reducer). Lets actor-consuming APIs (e.g. `enq.subscribeTo`) accept atoms
558
+ * directly.
559
+ */
560
+ function isAtom(value) {
561
+ return !!value && typeof value === 'object' && $$atom in value;
562
+ }
563
+ const queuedEffects = [];
564
+ let cycle = 0;
565
+ // Initialized lazily on first atom creation (instead of at module evaluation)
566
+ // so the reactive system stays tree-shakeable for apps that never use atoms —
567
+
568
+ // would be retained by consumer bundlers even when atoms are unused.
569
+ let link;
570
+ let unlink;
571
+ let propagate;
572
+ let checkDirty;
573
+ let shallowPropagate;
574
+ let reactiveSystemInstalled = false;
575
+ function ensureReactiveSystem() {
576
+ if (reactiveSystemInstalled) {
577
+ return;
578
+ }
579
+ reactiveSystemInstalled = true;
580
+ ({
581
+ link,
582
+ unlink,
583
+ propagate,
584
+ checkDirty,
585
+ shallowPropagate
586
+ } = createReactiveSystem({
587
+ update(atom) {
588
+ return atom._update();
589
+ },
590
+ notify(effect) {
591
+ queuedEffects[queuedEffectsLength++] = effect;
592
+ effect.flags &= ~ReactiveFlags.Watching;
593
+ },
594
+ unwatched(atom) {
595
+ if (atom.depsTail !== undefined) {
596
+ atom.depsTail = undefined;
597
+ atom.flags = ReactiveFlags.Mutable | ReactiveFlags.Dirty;
598
+ purgeDeps(atom);
599
+ }
600
+ }
601
+ }));
602
+ }
603
+ let notifyIndex = 0;
604
+ let queuedEffectsLength = 0;
605
+ let activeSub;
606
+ function purgeDeps(sub) {
607
+ const depsTail = sub.depsTail;
608
+ let dep = depsTail !== undefined ? depsTail.nextDep : sub.deps;
609
+ while (dep !== undefined) {
610
+ dep = unlink(dep, sub);
611
+ }
612
+ }
613
+ function flush() {
614
+ while (notifyIndex < queuedEffectsLength) {
615
+ const effect = queuedEffects[notifyIndex];
616
+ queuedEffects[notifyIndex++] = undefined;
617
+ effect.notify();
618
+ }
619
+ notifyIndex = 0;
620
+ queuedEffectsLength = 0;
621
+ }
622
+
623
+ /** The current state of an async atom. */
624
+
625
+ /** Options passed to an async atom getter. */
626
+
627
+ function compareAsyncAtomState(a, b) {
628
+ if (a.status !== b.status) {
629
+ return false;
630
+ }
631
+ if (a.status === 'done' && b.status === 'done') {
632
+ return Object.is(a.data, b.data);
633
+ }
634
+ if (a.status === 'error' && b.status === 'error') {
635
+ return Object.is(a.error, b.error);
636
+ }
637
+ // both 'pending'
638
+ return true;
639
+ }
640
+ function updateAsyncAtom(atom, nextValue) {
641
+ if (atom._update(nextValue)) {
642
+ const subs = atom.subs;
643
+ if (subs !== undefined) {
644
+ propagate(subs);
645
+ shallowPropagate(subs);
646
+ flush();
647
+ }
648
+ }
649
+ }
650
+
651
+ /**
652
+ * Creates a read-only atom whose value is loaded from an async getter.
653
+ *
654
+ * The getter receives an `AbortSignal`; when the async atom recomputes, the
655
+ * previous signal is aborted and stale resolutions are ignored.
656
+ */
657
+ function createAsyncAtom(getValue, options) {
658
+ const ref = {};
659
+ let currentController;
660
+ let currentRunId = 0;
661
+ const atom = createAtom(() => {
662
+ currentController?.abort();
663
+ const controller = new AbortController();
664
+ const runId = ++currentRunId;
665
+ currentController = controller;
666
+ getValue({
667
+ signal: controller.signal
668
+ }).then(data => {
669
+ if (runId !== currentRunId || controller.signal.aborted) {
670
+ return;
671
+ }
672
+ updateAsyncAtom(ref.current, {
673
+ status: 'done',
674
+ data
675
+ });
676
+ }, error => {
677
+ if (runId !== currentRunId || controller.signal.aborted) {
678
+ return;
679
+ }
680
+ updateAsyncAtom(ref.current, {
681
+ status: 'error',
682
+ error
683
+ });
684
+ });
685
+ return {
686
+ status: 'pending'
687
+ };
688
+ }, {
689
+ compare: compareAsyncAtomState,
690
+ ...options
691
+ });
692
+ ref.current = atom;
693
+ return atom;
694
+ }
695
+
696
+ /**
697
+ * Mirror atoms that bump a version whenever a tracked actor emits a snapshot,
698
+ * letting computed atoms depend on `actor.get()` reads.
699
+ *
700
+ * The hook is installed lazily on first atom creation (not at module
701
+ * evaluation) so that it remains tree-shakeable for apps that never use atoms —
702
+ * any tracked read necessarily happens inside an atom computation, so first-use
703
+ * installation is always early enough.
704
+ */
705
+ let actorInteropInstalled = false;
706
+ function ensureActorInterop() {
707
+ if (actorInteropInstalled) {
708
+ return;
709
+ }
710
+ actorInteropInstalled = true;
711
+ const actorVersions = new WeakMap();
712
+ installActorReadHook(actorRef => {
713
+ if (activeSub === undefined) {
714
+ return;
715
+ }
716
+ let version = actorVersions.get(actorRef);
717
+ if (version === undefined) {
718
+ version = createAtom(0);
719
+ actorVersions.set(actorRef, version);
720
+ actorRef.subscribe({
721
+ next: () => version.set(v => v + 1),
722
+ error: () => {}
723
+ });
724
+ }
725
+ version.get();
726
+ });
727
+ }
728
+
729
+ /**
730
+ * Creates an atom.
731
+ *
732
+ * Pass a value for a writable atom or a getter for a computed read-only atom.
733
+ */
734
+
735
+ function createAtom(valueOrFn, optionsOrInput) {
736
+ ensureReactiveSystem();
737
+ ensureActorInterop();
738
+ const isComputed = typeof valueOrFn === 'function';
739
+ const getter = valueOrFn;
740
+
741
+ // Create plain object atom
742
+ const atom = {
743
+ _snapshot: isComputed ? undefined : valueOrFn,
744
+ subs: undefined,
745
+ subsTail: undefined,
746
+ deps: undefined,
747
+ depsTail: undefined,
748
+ flags: isComputed ? ReactiveFlags.None : ReactiveFlags.Mutable,
749
+ get() {
750
+ if (activeSub !== undefined) {
751
+ link(atom, activeSub, cycle);
752
+ }
753
+ return atom._snapshot;
754
+ },
755
+ subscribe(observerOrFn) {
756
+ const observer = typeof observerOrFn === 'function' ? {
757
+ next: observerOrFn
758
+ } : observerOrFn;
759
+ const observed = {
760
+ current: false
761
+ };
762
+ const e = effect(() => {
763
+ atom.get();
764
+ if (!observed.current) {
765
+ observed.current = true;
766
+ } else {
767
+ const prevSub = activeSub;
768
+ activeSub = undefined;
769
+ try {
770
+ observer.next?.(atom._snapshot);
771
+ } catch (err) {
772
+ reportUnhandledError(err);
773
+ } finally {
774
+ activeSub = prevSub;
775
+ }
776
+
777
+ // If the observer synchronously updates any of our deps we'll be
778
+ // marked as dirty preventing this effect from re-running. Request
779
+ // the value again to reconcile any dirty deps.
780
+ atom.get();
781
+ }
782
+ });
783
+ return {
784
+ unsubscribe: () => {
785
+ e.stop();
786
+ }
787
+ };
788
+ },
789
+ _update(getValue) {
790
+ const prevSub = activeSub;
791
+ const compare = optionsOrInput?.compare ?? Object.is;
792
+ activeSub = atom;
793
+ ++cycle;
794
+ atom.depsTail = undefined;
795
+ if (isComputed) {
796
+ atom.flags = ReactiveFlags.Mutable | ReactiveFlags.RecursedCheck;
797
+ }
798
+ try {
799
+ const oldValue = atom._snapshot;
800
+ const newValue = typeof getValue === 'function' ? getValue(oldValue) : getValue === undefined && isComputed ? getter(oldValue) : getValue;
801
+ if (oldValue === undefined || !compare(oldValue, newValue)) {
802
+ atom._snapshot = newValue;
803
+ return true;
804
+ }
805
+ return false;
806
+ } finally {
807
+ activeSub = prevSub;
808
+ if (isComputed) {
809
+ atom.flags &= ~ReactiveFlags.RecursedCheck;
810
+ }
811
+ purgeDeps(atom);
812
+ }
813
+ }
814
+ };
815
+ if (isComputed) {
816
+ atom.flags = ReactiveFlags.Mutable | ReactiveFlags.Dirty;
817
+ atom.get = function () {
818
+ const flags = atom.flags;
819
+ if (flags & ReactiveFlags.Dirty || flags & ReactiveFlags.Pending && checkDirty(atom.deps, atom)) {
820
+ if (atom._update()) {
821
+ const subs = atom.subs;
822
+ if (subs !== undefined) {
823
+ shallowPropagate(subs);
824
+ }
825
+ }
826
+ } else if (flags & ReactiveFlags.Pending) {
827
+ atom.flags = flags & ~ReactiveFlags.Pending;
828
+ }
829
+ if (activeSub !== undefined) {
830
+ link(atom, activeSub, cycle);
831
+ }
832
+ return atom._snapshot;
833
+ };
834
+ } else {
835
+ atom.set = function (valueOrFn) {
836
+ if (atom._update(valueOrFn)) {
837
+ const subs = atom.subs;
838
+ if (subs !== undefined) {
839
+ propagate(subs);
840
+ shallowPropagate(subs);
841
+ flush();
842
+ }
843
+ }
844
+ };
845
+ }
846
+ atom[$$atom] = true;
847
+ return atom;
848
+ }
849
+
850
+ /**
851
+ * Creates an inert atom config that can be instantiated later.
852
+ *
853
+ * Useful for framework hooks that need to create a stable local atom from
854
+ * component input.
855
+ */
856
+
857
+ function createAtomConfig(initialValueOrFn, options) {
858
+ return {
859
+ createAtom(input) {
860
+ const initialValue = typeof initialValueOrFn === 'function' ? initialValueOrFn(input) : initialValueOrFn;
861
+ return createAtom(initialValue, options);
862
+ }
863
+ };
864
+ }
865
+
866
+ /** Creates an atom whose updates are handled by a reducer function. */
867
+ function createReducerAtom(initialValue, reducer, options) {
868
+ const atom = createAtom(initialValue, options);
869
+ return {
870
+ [$$atom]: true,
871
+ get: atom.get.bind(atom),
872
+ subscribe: atom.subscribe.bind(atom),
873
+ send(event) {
874
+ const prevSub = activeSub;
875
+ activeSub = undefined;
876
+ let nextState;
877
+ try {
878
+ nextState = reducer(atom.get(), event);
879
+ } finally {
880
+ activeSub = prevSub;
881
+ }
882
+ atom.set(nextState);
883
+ }
884
+ };
885
+ }
886
+ function effect(fn) {
887
+ const run = () => {
888
+ const prevSub = activeSub;
889
+ activeSub = effectObj;
890
+ ++cycle;
891
+ effectObj.depsTail = undefined;
892
+ effectObj.flags = ReactiveFlags.Watching | ReactiveFlags.RecursedCheck;
893
+ try {
894
+ return fn();
895
+ } finally {
896
+ activeSub = prevSub;
897
+ effectObj.flags &= ~ReactiveFlags.RecursedCheck;
898
+ purgeDeps(effectObj);
899
+ }
900
+ };
901
+ const effectObj = {
902
+ deps: undefined,
903
+ depsTail: undefined,
904
+ subs: undefined,
905
+ subsTail: undefined,
906
+ flags: ReactiveFlags.Watching | ReactiveFlags.RecursedCheck,
907
+ notify() {
908
+ const flags = this.flags;
909
+ if (flags & ReactiveFlags.Dirty || flags & ReactiveFlags.Pending && checkDirty(this.deps, this)) {
910
+ run();
911
+ } else {
912
+ this.flags = ReactiveFlags.Watching;
913
+ }
914
+ },
915
+ stop() {
916
+ this.flags = ReactiveFlags.None;
917
+ this.depsTail = undefined;
918
+ purgeDeps(this);
919
+ }
920
+ };
921
+ run();
922
+ return effectObj;
923
+ }
924
+
925
+ /**
926
+ * Creates actor logic for subscribing to lifecycle events (done/error/snapshot)
927
+ * from another actor. Used internally by `enq.subscribeTo()`.
928
+ */
929
+ function createSubscriptionLogic() {
930
+ return createAttachedLogic(({
931
+ actor,
932
+ mappers
933
+ }, {
934
+ self,
935
+ system
936
+ }) => {
937
+ const {
938
+ done,
939
+ error,
940
+ snapshot: onSnapshot
941
+ } = mappers;
942
+
943
+ // Atoms emit a raw value (no `status`) and have no done/error lifecycle —
944
+ // pass the value straight to the `snapshot` mapper.
945
+ if (isAtom(actor)) {
946
+ if (!onSnapshot) {
947
+ return;
948
+ }
949
+ return actor.subscribe(value => relayMappedToParent(self, system, () => onSnapshot(value)));
950
+ }
951
+ return actor.subscribe({
952
+ next: snapshot => {
953
+ if (snapshot.status === 'done' && done) {
954
+ relayMappedToParent(self, system, () => done(snapshot.output));
955
+ } else if (snapshot.status === 'error' && error) {
956
+ relayMappedToParent(self, system, () => error(snapshot.error));
957
+ } else if (snapshot.status === 'active' && onSnapshot) {
958
+ relayMappedToParent(self, system, () => onSnapshot(snapshot));
959
+ }
960
+ },
961
+ error: err => {
962
+ if (error) {
963
+ relayMappedToParent(self, system, () => error(err));
964
+ }
965
+ },
966
+ complete: () => {
967
+ // Actor completed without output (stopped); no action needed
968
+ }
969
+ });
970
+ });
971
+ }
972
+
973
+ // Singleton logic instance
974
+ const subscriptionLogic = /* #__PURE__ */createSubscriptionLogic();
975
+
976
+ function pushBuiltInAction(actions, action, ...args) {
977
+ actions.push({
978
+ action,
979
+ args
980
+ });
981
+ }
982
+ function registerSpawnedChild(actor, id) {
983
+ return Object.assign(function registerChild(args) {
984
+ return {
985
+ children: {
986
+ ...args.children,
987
+ [id]: actor
988
+ }
989
+ };
990
+ }, {
991
+ _special: true
992
+ });
993
+ }
994
+ function unregisterChild(actor) {
995
+ return Object.assign(function removeChild(args) {
996
+ const children = {
997
+ ...args.children
998
+ };
999
+ for (const key of Object.keys(children)) {
1000
+ if (children[key] === actor) {
1001
+ delete children[key];
1002
+ }
1003
+ }
1004
+ return {
1005
+ children
1006
+ };
1007
+ }, {
1008
+ _special: true
1009
+ });
1010
+ }
1011
+ function pushStartedChild(actions, actor, id) {
1012
+ pushBuiltInAction(actions, builtInActions['@xstate.start'], actor);
1013
+ actions.push(registerSpawnedChild(actor, id ?? actor.id));
1014
+ }
1015
+ function createTransitionEnqueue(actorScope, actions, internalEvents, actorSubscriptions = false) {
1016
+ const props = {
1017
+ cancel: id => {
1018
+ pushBuiltInAction(actions, builtInActions['@xstate.cancel'], actorScope, id);
1019
+ },
1020
+ emit: emittedEvent => {
1021
+ actions.push(emittedEvent);
1022
+ },
1023
+ log: (...args) => {
1024
+ pushBuiltInAction(actions, actorScope.logger, ...args);
1025
+ },
1026
+ raise: (raisedEvent, options) => {
1027
+ if (typeof raisedEvent === 'string') {
1028
+ throw new Error(`Only event objects may be used with raise; use raise({ type: "${raisedEvent}" }) instead` );
1029
+ }
1030
+ if (options?.delay !== undefined) {
1031
+ pushBuiltInAction(actions, builtInActions['@xstate.raise'], actorScope, raisedEvent, options);
1032
+ } else {
1033
+ internalEvents.push(raisedEvent);
1034
+ }
1035
+ },
1036
+ spawn: (logic, options) => {
1037
+ const actor = createActor(logic, {
1038
+ ...options,
1039
+ parent: actorScope.self
1040
+ });
1041
+ pushStartedChild(actions, actor, options?.id);
1042
+ return actor;
1043
+ },
1044
+ sendTo: (actor, event, options) => {
1045
+ if (actor) {
1046
+ pushBuiltInAction(actions, builtInActions['@xstate.sendTo'], actorScope, actor, event, options);
1047
+ }
1048
+ },
1049
+ stop: actor => {
1050
+ if (actor) {
1051
+ pushBuiltInAction(actions, builtInActions['@xstate.stopChild'], actorScope, actor);
1052
+ actions.push(unregisterChild(actor));
1053
+ }
1054
+ }
1055
+ };
1056
+ if (actorSubscriptions) {
1057
+ Object.assign(props, {
1058
+ listen: (actor, eventType, mapper) => {
1059
+ const input = {
1060
+ actor,
1061
+ eventType,
1062
+ mapper
1063
+ };
1064
+ const listenerActor = createActor(listenerLogic, {
1065
+ input,
1066
+ parent: actorScope.self
1067
+ });
1068
+ pushBuiltInAction(actions, builtInActions['@xstate.start'], listenerActor);
1069
+ return listenerActor;
1070
+ },
1071
+ subscribeTo: (actor, mappers) => {
1072
+ const normalizedMappers = typeof mappers === 'function' ? {
1073
+ snapshot: mappers
1074
+ } : mappers;
1075
+ const input = {
1076
+ actor,
1077
+ mappers: normalizedMappers
1078
+ };
1079
+ const subscriptionActor = createActor(subscriptionLogic, {
1080
+ input,
1081
+ parent: actorScope.self
1082
+ });
1083
+ pushBuiltInAction(actions, builtInActions['@xstate.start'], subscriptionActor);
1084
+ return subscriptionActor;
1085
+ }
1086
+ });
1087
+ }
1088
+ return createEnqueueObject$1(props, (action, ...args) => {
1089
+ pushBuiltInAction(actions, action, ...args);
1090
+ });
1091
+ }
1092
+ function resolveAndExecuteActionsWithContext(currentSnapshot, event, actorScope, actions) {
1093
+ let intermediateSnapshot = currentSnapshot;
1094
+ for (const action of actions) {
1095
+ const isInline = typeof action === 'function';
1096
+ const resolvedAction = isInline ? action : typeof action === 'object' && 'action' in action && typeof action.action === 'function' ? action.action.bind(null, ...action.args) : false;
1097
+ if (!resolvedAction && typeof action === 'object' && action !== null) {
1098
+ actorScope.defer(() => {
1099
+ actorScope.emit(action);
1100
+ });
1101
+ }
1102
+ const actionArgs = {
1103
+ context: intermediateSnapshot.context,
1104
+ event,
1105
+ self: actorScope.self,
1106
+ system: actorScope.system,
1107
+ children: intermediateSnapshot.children,
1108
+ parent: actorScope.self._parent,
1109
+ actions: currentSnapshot.machine.implementations.actions,
1110
+ actors: currentSnapshot.machine.implementations.actors
1111
+ };
1112
+ let actionParams = undefined;
1113
+ if (typeof action === 'object' && action !== null) {
1114
+ const {
1115
+ type: _,
1116
+ ...emittedEventParams
1117
+ } = action;
1118
+ actionParams = emittedEventParams;
1119
+ }
1120
+ if (resolvedAction && '_special' in resolvedAction) {
1121
+ actorScope.actionExecutor({
1122
+ type: typeof action === 'object' ? 'action' in action && typeof action.action === 'function' ? action.action.name ?? '(anonymous)' : action.type ?? '(anonymous)' : action.name || '(anonymous)',
1123
+ params: actionParams,
1124
+ args: [],
1125
+ exec: undefined
1126
+ });
1127
+ const specialAction = resolvedAction;
1128
+ const res = specialAction(actionArgs, emptyEnqueueObject);
1129
+ if (res && ('context' in res || 'children' in res)) {
1130
+ intermediateSnapshot = cloneMachineSnapshot(intermediateSnapshot, {
1131
+ ...('context' in res ? {
1132
+ context: res.context
1133
+ } : {}),
1134
+ ...('children' in res ? {
1135
+ children: res.children
1136
+ } : {})
1137
+ });
1138
+ }
1139
+ continue;
1140
+ }
1141
+ if (!resolvedAction || !('resolve' in resolvedAction)) {
1142
+ actorScope.actionExecutor({
1143
+ type: typeof action === 'object' ? 'action' in action && typeof action.action === 'function' ? action.action.name ?? '(anonymous)' : action.type : action.name || '(anonymous)',
1144
+ params: actionParams,
1145
+ args: typeof action === 'object' && 'action' in action ? action.args : [],
1146
+ exec: resolvedAction
1147
+ });
1148
+ continue;
1149
+ }
1150
+ }
1151
+ return intermediateSnapshot;
1152
+ }
1153
+ function createEnqueueObject$1(props, action) {
1154
+ const enqueueFn = (fn, ...args) => {
1155
+ action(fn, ...args);
1156
+ };
1157
+ Object.assign(enqueueFn, {
1158
+ cancel: () => {},
1159
+ emit: () => {},
1160
+ log: () => {},
1161
+ raise: () => {},
1162
+ spawn: () => ({}),
1163
+ sendTo: () => {},
1164
+ stop: () => {},
1165
+ listen: () => ({}),
1166
+ subscribeTo: () => ({}),
1167
+ ...props
1168
+ });
1169
+ return enqueueFn;
1170
+ }
1171
+ const emptyEnqueueObject = createEnqueueObject$1({}, () => {});
1172
+
1173
+ function parseDurationToMilliseconds(duration) {
1174
+ const normalizedDuration = duration.trim();
1175
+ const millisecondsMatch = normalizedDuration.match(/^(\d+)ms$/i);
1176
+ if (millisecondsMatch) {
1177
+ return parseInt(millisecondsMatch[1], 10);
1178
+ }
1179
+ const secondsMatch = normalizedDuration.match(/^(\d*)(\.?)(\d*)s$/i);
1180
+ if (secondsMatch) {
1181
+ const wholePart = secondsMatch[1] ? parseInt(secondsMatch[1], 10) : 0;
1182
+ const hasDecimal = !!secondsMatch[2];
1183
+ const fracPart = secondsMatch[3] ? parseInt(secondsMatch[3].padEnd(3, '0').slice(0, 3), 10) : 0;
1184
+ return wholePart * 1000 + (hasDecimal ? fracPart : 0);
1185
+ }
1186
+ const iso8601DurationMatch = normalizedDuration.match(/^P(?:(?<weeks>\d+(?:[.,]\d+)?)W)?(?:(?<days>\d+(?:[.,]\d+)?)D)?(?:T(?:(?<hours>\d+(?:[.,]\d+)?)H)?(?:(?<minutes>\d+(?:[.,]\d+)?)M)?(?:(?<seconds>\d+(?:[.,]\d+)?)S)?)?$/i);
1187
+ if (!iso8601DurationMatch?.groups) {
1188
+ return undefined;
1189
+ }
1190
+ const {
1191
+ weeks,
1192
+ days,
1193
+ hours,
1194
+ minutes,
1195
+ seconds
1196
+ } = iso8601DurationMatch.groups;
1197
+ if (!weeks && !days && !hours && !minutes && !seconds) {
1198
+ return undefined;
1199
+ }
1200
+ const toNumber = value => value ? Number(value.replace(',', '.')) : 0;
1201
+ return toNumber(weeks) * 7 * 24 * 60 * 60 * 1000 + toNumber(days) * 24 * 60 * 60 * 1000 + toNumber(hours) * 60 * 60 * 1000 + toNumber(minutes) * 60 * 1000 + toNumber(seconds) * 1000;
1202
+ }
1203
+ function parseDelayToMilliseconds(delay) {
1204
+ if (delay === undefined) {
1205
+ return undefined;
1206
+ }
1207
+ if (typeof delay === 'number') {
1208
+ return delay;
1209
+ }
1210
+ return parseDurationToMilliseconds(delay);
1211
+ }
1212
+
1213
+ function getConfiguredDelayValue(delay, delaySource) {
1214
+ if (typeof delay !== 'string') {
1215
+ return delay;
1216
+ }
1217
+ const referencedDelay = delaySource[delay];
1218
+ if (referencedDelay !== undefined) {
1219
+ return referencedDelay;
1220
+ }
1221
+ return parseDurationToMilliseconds(delay) ?? delay;
1222
+ }
1223
+ function resolveDelay(delay, delaySource, args) {
1224
+ if (typeof delay === 'function') {
1225
+ return delay(args);
1226
+ }
1227
+ const configuredDelay = getConfiguredDelayValue(delay, delaySource);
1228
+ if (typeof configuredDelay === 'function') {
1229
+ return configuredDelay(args);
1230
+ }
1231
+ return configuredDelay;
1232
+ }
1233
+ function isAtomicStateNode(stateNode) {
1234
+ return stateNode.type === 'atomic' || stateNode.type === 'final' || stateNode.type === 'choice';
1235
+ }
1236
+ function getChildren(stateNode) {
1237
+ return Object.values(stateNode.states).filter(sn => sn.type !== 'history');
1238
+ }
1239
+ function getProperAncestors(stateNode, toStateNode) {
1240
+ const ancestors = [];
1241
+ if (toStateNode === stateNode) {
1242
+ return ancestors;
1243
+ }
1244
+
1245
+ // add all ancestors
1246
+ let m = stateNode.parent;
1247
+ while (m && m !== toStateNode) {
1248
+ ancestors.push(m);
1249
+ m = m.parent;
1250
+ }
1251
+ return ancestors;
1252
+ }
1253
+ function getAllStateNodes(stateNodes) {
1254
+ const nodeSet = new Set(stateNodes);
1255
+ const activeParentSet = new Set();
1256
+ for (const stateNode of nodeSet) {
1257
+ if (stateNode.parent) {
1258
+ activeParentSet.add(stateNode.parent);
1259
+ }
1260
+ }
1261
+
1262
+ // add descendants
1263
+ for (const s of nodeSet) {
1264
+ // if previously active, add existing child nodes
1265
+ if (s.type === 'compound' && !activeParentSet.has(s)) {
1266
+ for (const sn of getInitialStateNodes(s)) {
1267
+ nodeSet.add(sn);
1268
+ }
1269
+ continue;
1270
+ }
1271
+ if (s.type === 'parallel') {
1272
+ for (const child of getChildren(s)) {
1273
+ if (!nodeSet.has(child)) {
1274
+ const initialStates = getInitialStateNodes(child);
1275
+ for (const initialStateNode of initialStates) {
1276
+ nodeSet.add(initialStateNode);
1277
+ }
1278
+ }
1279
+ }
1280
+ }
1281
+ }
1282
+
1283
+ // add all ancestors
1284
+ // Stop walking up as soon as we hit a node already in the set: its own
1285
+ // ancestor chain is guaranteed to be added when it is visited by this loop
1286
+ // (Set iteration visits elements added during iteration), so shared ancestor
1287
+ // chains are never re-walked once per descendant.
1288
+ for (const s of nodeSet) {
1289
+ let m = s.parent;
1290
+ while (m && !nodeSet.has(m)) {
1291
+ nodeSet.add(m);
1292
+ m = m.parent;
1293
+ }
1294
+ }
1295
+ return nodeSet;
1296
+ }
1297
+ function getStateValue(rootNode, stateNodes) {
1298
+ const config = getAllStateNodes(stateNodes);
1299
+ const adjList = new Map();
1300
+ for (const s of config) {
1301
+ if (!adjList.has(s)) {
1302
+ adjList.set(s, []);
1303
+ }
1304
+ if (!s.parent) {
1305
+ continue;
1306
+ }
1307
+ if (!adjList.has(s.parent)) {
1308
+ adjList.set(s.parent, []);
1309
+ }
1310
+ adjList.get(s.parent).push(s);
1311
+ }
1312
+ const getValueFromAdj = baseNode => {
1313
+ const childStateNodes = adjList.get(baseNode);
1314
+ if (!childStateNodes) {
1315
+ return {}; // todo: fix?
1316
+ }
1317
+ if (baseNode.type === 'compound') {
1318
+ const childStateNode = childStateNodes[0];
1319
+ if (!childStateNode) {
1320
+ return {};
1321
+ }
1322
+ if (isAtomicStateNode(childStateNode)) {
1323
+ return childStateNode.key;
1324
+ }
1325
+ }
1326
+ const stateValue = {};
1327
+ for (const childStateNode of childStateNodes) {
1328
+ stateValue[childStateNode.key] = getValueFromAdj(childStateNode);
1329
+ }
1330
+ return stateValue;
1331
+ };
1332
+ return getValueFromAdj(rootNode);
1333
+ }
1334
+ function isInFinalState(stateNodeSet, stateNode) {
1335
+ if (stateNode.type === 'compound') {
1336
+ return getChildren(stateNode).some(s => s.type === 'final' && stateNodeSet.has(s));
1337
+ }
1338
+ if (stateNode.type === 'parallel') {
1339
+ return getChildren(stateNode).every(sn => isInFinalState(stateNodeSet, sn));
1340
+ }
1341
+ return stateNode.type === 'final';
1342
+ }
1343
+ const isStateId = str => str[0] === STATE_IDENTIFIER;
1344
+ function getCandidates(stateNode, receivedEventType) {
1345
+ const candidates = stateNode.transitions.get(receivedEventType);
1346
+ if (candidates) {
1347
+ return candidates;
1348
+ }
1349
+ const matchingDescriptors = [];
1350
+ for (const eventDescriptor of stateNode.transitions.keys()) {
1351
+ if (matchesEventDescriptor(receivedEventType, eventDescriptor)) {
1352
+ matchingDescriptors.push(eventDescriptor);
1353
+ }
1354
+ }
1355
+ matchingDescriptors.sort((a, b) => b.length - a.length);
1356
+ const wildcardCandidates = [];
1357
+ for (const descriptor of matchingDescriptors) {
1358
+ wildcardCandidates.push(...stateNode.transitions.get(descriptor));
1359
+ }
1360
+ return wildcardCandidates;
1361
+ }
1362
+ function scheduleDelayedEvent(stateNode, event, resolveScheduledDelay) {
1363
+ const eventType = event.type;
1364
+ const oldEntry = stateNode.entry;
1365
+ stateNode.entry = (x, enq) => {
1366
+ enq.raise(event, {
1367
+ id: eventType,
1368
+ delay: resolveScheduledDelay(x)
1369
+ });
1370
+ return typeof oldEntry === 'function' ? oldEntry(x, enq) : undefined;
1371
+ };
1372
+ const oldExit = stateNode.exit;
1373
+ stateNode.exit = (_, enq) => {
1374
+ enq.cancel(eventType);
1375
+ return typeof oldExit === 'function' ? oldExit(_, enq) : undefined;
1376
+ };
1377
+ return eventType;
1378
+ }
1379
+
1380
+ /** All delayed transitions from the config. */
1381
+ function getDelayedTransitions(stateNode) {
1382
+ const afterConfig = stateNode.config.after;
1383
+ const timeoutConfig = stateNode.config.timeout;
1384
+ const onTimeoutConfig = stateNode.config.onTimeout;
1385
+ const invokeDefs = stateNode.invoke.filter(invokeDef => invokeDef.timeout !== undefined);
1386
+ if (!afterConfig && timeoutConfig === undefined && invokeDefs.length === 0) {
1387
+ return [];
1388
+ }
1389
+ if (timeoutConfig !== undefined && !onTimeoutConfig) {
1390
+ throw new Error(`State "${stateNode.id}" has \`timeout\` but no \`onTimeout\` transition.`);
1391
+ }
1392
+ {
1393
+ for (const invokeDef of invokeDefs) {
1394
+ if (!invokeDef.onTimeout) {
1395
+ throw new Error(`Invoke on state "${stateNode.id}" has \`timeout\` but no \`onTimeout\` transition.`);
1396
+ }
1397
+ }
1398
+ }
1399
+ const mutateEntryExitWithDelay = delay => {
1400
+ const afterEvent = createAfterEvent(delay, stateNode.id);
1401
+ return scheduleDelayedEvent(stateNode, afterEvent, x => resolveDelay(delay, x.delays, {
1402
+ context: x.context,
1403
+ event: x.event,
1404
+ stateNode
1405
+ }));
1406
+ };
1407
+ const delayedTransitions = [];
1408
+ const addDelayedTransitions = (transitionsConfig, event, delay) => {
1409
+ for (const transition of toTransitionConfigArray(transitionsConfig)) {
1410
+ delayedTransitions.push({
1411
+ ...transition,
1412
+ event,
1413
+ delay
1414
+ });
1415
+ }
1416
+ };
1417
+ if (afterConfig) {
1418
+ for (const delay of Object.keys(afterConfig)) {
1419
+ const configTransition = afterConfig[delay];
1420
+ const parsedDelay = Number.isNaN(+delay) ? delay : +delay;
1421
+ const eventType = mutateEntryExitWithDelay(parsedDelay);
1422
+ const resolvedDelay = getConfiguredDelayValue(parsedDelay, stateNode.machine.implementations.delays);
1423
+ addDelayedTransitions(configTransition, eventType, resolvedDelay);
1424
+ }
1425
+ }
1426
+
1427
+ // Desugar state-level `timeout` + `onTimeout` into a delayed transition.
1428
+ // Uses a dedicated `xstate.timeout.<id>` event so it cannot collide with
1429
+ // explicit `after` entries on the same state.
1430
+ if (timeoutConfig !== undefined && onTimeoutConfig) {
1431
+ const timeoutEvent = createTimeoutEvent(stateNode.id);
1432
+ const timeoutEventType = scheduleDelayedEvent(stateNode, timeoutEvent, x => resolveDelay(timeoutConfig, x.delays, {
1433
+ context: x.context,
1434
+ event: x.event,
1435
+ stateNode
1436
+ }));
1437
+ const resolvedDelay = typeof timeoutConfig === 'function' ? timeoutConfig : getConfiguredDelayValue(timeoutConfig, stateNode.machine.implementations.delays);
1438
+ addDelayedTransitions(onTimeoutConfig, timeoutEventType, resolvedDelay);
1439
+ }
1440
+
1441
+ // Desugar invoke-level `timeout` + `onTimeout` into a delayed transition on
1442
+ // the enclosing state. Completion transitions cancel this timer separately,
1443
+ // so the timeout is cleared even when the parent state stays active.
1444
+ for (const invokeDef of invokeDefs) {
1445
+ const invokeTimeoutEvent = createInvokeTimeoutEvent(invokeDef.id);
1446
+ const invokeTimeout = invokeDef.timeout;
1447
+ const invokeTimeoutEventType = scheduleDelayedEvent(stateNode, invokeTimeoutEvent, x => resolveDelay(invokeTimeout, {}, {
1448
+ context: x.context,
1449
+ event: x.event,
1450
+ stateNode
1451
+ }));
1452
+ const invokeOnTimeout = invokeDef.onTimeout;
1453
+ addDelayedTransitions(invokeOnTimeout, invokeTimeoutEventType, invokeTimeout);
1454
+ }
1455
+ return delayedTransitions.map(delayedTransition => ({
1456
+ ...formatTransition(stateNode, delayedTransition.event, delayedTransition),
1457
+ delay: delayedTransition.delay
1458
+ }));
1459
+ }
1460
+ function formatTransition(stateNode, descriptor, transitionConfig) {
1461
+ const normalizedTarget = normalizeTarget(transitionConfig.target);
1462
+ const reenter = transitionConfig.reenter ?? false;
1463
+ const target = resolveTarget(stateNode, normalizedTarget);
1464
+ const transition = {
1465
+ ...transitionConfig,
1466
+ target,
1467
+ source: stateNode,
1468
+ reenter,
1469
+ eventType: descriptor,
1470
+ toJSON: () => ({
1471
+ ...transition,
1472
+ source: `#${stateNode.id}`,
1473
+ target: target ? target.map(t => `#${t.id}`) : undefined
1474
+ })
1475
+ };
1476
+ return transition;
1477
+ }
1478
+
1479
+ /**
1480
+ * Collects route transitions from all descendants with explicit IDs. Called
1481
+ * once on the root node to avoid O(N²) repeated traversals.
1482
+ */
1483
+ function formatRouteTransitions(rootStateNode) {
1484
+ const routeTransitions = [];
1485
+ const collectRoutes = states => {
1486
+ Object.values(states).forEach(sn => {
1487
+ if (sn.config.route && sn.config.id) {
1488
+ const routeId = sn.config.id;
1489
+ const routeConfig = sn.config.route;
1490
+ const routeMatches = ({
1491
+ event
1492
+ }) => event.to === `#${routeId}`;
1493
+ if (typeof routeConfig === 'function') {
1494
+ // Transition-style route: the function is the guard and resolver.
1495
+ // Returning undefined/false blocks the route; returning true or a
1496
+ // config object allows it.
1497
+ routeTransitions.push(formatTransition(rootStateNode, 'xstate.route', {
1498
+ guard: routeMatches,
1499
+ to: args => {
1500
+ const result = routeConfig(args);
1501
+ if (!result) {
1502
+ return undefined;
1503
+ }
1504
+ return {
1505
+ ...(result === true ? {} : result),
1506
+ target: `#${routeId}`
1507
+ };
1508
+ }
1509
+ }));
1510
+ if (sn.states) {
1511
+ collectRoutes(sn.states);
1512
+ }
1513
+ return;
1514
+ }
1515
+ if ('$unserializable' in routeConfig) {
1516
+ throw new Error(`State "${sn.id}" has a route that is not serializable. Re-provide the route function when reviving this machine.`);
1517
+ }
1518
+
1519
+ // Object-form route. A `guard` (string or function) on the object is
1520
+ // only produced by the JSON layer (createMachineFromConfig) —
1521
+ // authoring uses the function form above.
1522
+ const userGuard = routeConfig.guard;
1523
+ const transition = {
1524
+ ...routeConfig,
1525
+ guard: userGuard ? args => {
1526
+ if (!routeMatches(args)) return false;
1527
+ if (typeof userGuard === 'function') return userGuard(args);
1528
+ if (typeof userGuard === 'string') {
1529
+ const guardImpl = args.guards?.[userGuard];
1530
+ if (!guardImpl) {
1531
+ // A typo'd guard name must fail loudly — silently passing
1532
+ // would allow the route and corrupt machine behavior.
1533
+ throw new Error(`Guard '${userGuard}' is not implemented in machine '${rootStateNode.machine.id}'. Available guards: ${Object.keys(args.guards ?? {}).map(key => `'${key}'`).join(', ') || '(none)'}.` );
1534
+ }
1535
+ return guardImpl(args);
1536
+ }
1537
+ return true;
1538
+ } : routeMatches,
1539
+ target: `#${routeId}`
1540
+ };
1541
+ routeTransitions.push(formatTransition(rootStateNode, 'xstate.route', transition));
1542
+ }
1543
+ if (sn.states) {
1544
+ collectRoutes(sn.states);
1545
+ }
1546
+ });
1547
+ };
1548
+ collectRoutes(rootStateNode.states);
1549
+ if (routeTransitions.length > 0) {
1550
+ rootStateNode.transitions.set('xstate.route', routeTransitions);
1551
+ }
1552
+ }
1553
+ function resolveTarget(stateNode, targets) {
1554
+ if (targets === undefined) {
1555
+ // an undefined target signals that the state node should not transition from that state when receiving that event
1556
+ return undefined;
1557
+ }
1558
+ return targets.map(target => {
1559
+ if (typeof target !== 'string') {
1560
+ return target;
1561
+ }
1562
+ if (isStateId(target)) {
1563
+ return stateNode.machine.getStateNodeById(target);
1564
+ }
1565
+ const isInternalTarget = target[0] === STATE_DELIMITER;
1566
+ // If internal target is defined on machine,
1567
+ // do not include machine key on target
1568
+ if (isInternalTarget && !stateNode.parent) {
1569
+ return getStateNodeByPath(stateNode, target.slice(1));
1570
+ }
1571
+ const resolvedTarget = isInternalTarget ? stateNode.key + target : target;
1572
+ if (stateNode.parent) {
1573
+ try {
1574
+ const targetStateNode = getStateNodeByPath(stateNode.parent, resolvedTarget);
1575
+ return targetStateNode;
1576
+ } catch (err) {
1577
+ throw new Error(`Invalid transition definition for state node '${stateNode.id}':\n${err.message}`);
1578
+ }
1579
+ } else {
1580
+ throw new Error(`Invalid target: "${target}" is not a valid target from the root node. Did you mean ".${target}"?` );
1581
+ }
1582
+ });
1583
+ }
1584
+ function resolveHistoryDefaultTransition(stateNode) {
1585
+ const normalizedTarget = normalizeTarget(stateNode.config.target);
1586
+ if (!normalizedTarget) {
1587
+ return stateNode.parent.initial;
1588
+ }
1589
+ return {
1590
+ target: normalizedTarget.map(t => typeof t === 'string' ? getStateNodeByPath(stateNode.parent, t) : t),
1591
+ source: stateNode,
1592
+ reenter: false,
1593
+ eventType: ''
1594
+ };
1595
+ }
1596
+ function isHistoryNode(stateNode) {
1597
+ return stateNode.type === 'history';
1598
+ }
1599
+ function getInitialStateNodes(stateNode) {
1600
+ const set = new Set();
1601
+ function iter(descStateNode) {
1602
+ if (set.has(descStateNode)) {
1603
+ return;
1604
+ }
1605
+ set.add(descStateNode);
1606
+ if (descStateNode.type === 'compound') {
1607
+ iter(descStateNode.initial.target[0]);
1608
+ } else if (descStateNode.type === 'parallel') {
1609
+ for (const child of getChildren(descStateNode)) {
1610
+ iter(child);
1611
+ }
1612
+ }
1613
+ }
1614
+ iter(stateNode);
1615
+ for (const initialState of set) {
1616
+ for (const ancestor of getProperAncestors(initialState, stateNode)) {
1617
+ set.add(ancestor);
1618
+ }
1619
+ }
1620
+ return set;
1621
+ }
1622
+
1623
+ /** Returns the child state node from its relative `stateKey`, or throws. */
1624
+ function getStateNode(stateNode, stateKey) {
1625
+ if (isStateId(stateKey)) {
1626
+ return stateNode.machine.getStateNodeById(stateKey);
1627
+ }
1628
+ if (!stateNode.states) {
1629
+ throw new Error(`Unable to retrieve child state '${stateKey}' from '${stateNode.id}'; no child states exist.`);
1630
+ }
1631
+ const result = stateNode.states[stateKey];
1632
+ if (!result) {
1633
+ throw new Error(`Child state '${stateKey}' does not exist on '${stateNode.id}'`);
1634
+ }
1635
+ return result;
1636
+ }
1637
+
1638
+ /**
1639
+ * Returns the relative state node from the given `statePath`, or throws.
1640
+ *
1641
+ * @param statePath The string or string array relative path to the state node.
1642
+ */
1643
+ function getStateNodeByPath(stateNode, statePath) {
1644
+ if (typeof statePath === 'string' && isStateId(statePath)) {
1645
+ try {
1646
+ return stateNode.machine.getStateNodeById(statePath);
1647
+ } catch {
1648
+ // try individual paths
1649
+ // throw e;
1650
+ }
1651
+ }
1652
+ const arrayStatePath = toStatePath(statePath).slice();
1653
+ let currentStateNode = stateNode;
1654
+ while (arrayStatePath.length) {
1655
+ const key = arrayStatePath.shift();
1656
+ if (!key.length) {
1657
+ break;
1658
+ }
1659
+ currentStateNode = getStateNode(currentStateNode, key);
1660
+ }
1661
+ return currentStateNode;
1662
+ }
1663
+
1664
+ /**
1665
+ * Returns the state nodes represented by the current state value.
1666
+ *
1667
+ * @param stateValue The state value or State instance
1668
+ */
1669
+ function getStateNodes(stateNode, stateValue) {
1670
+ if (typeof stateValue === 'string') {
1671
+ const childStateNode = stateNode.states[stateValue];
1672
+ if (!childStateNode) {
1673
+ throw new Error(`State '${stateValue}' does not exist on '${stateNode.id}'`);
1674
+ }
1675
+ return [stateNode, childStateNode];
1676
+ }
1677
+ const childStateKeys = Object.keys(stateValue);
1678
+ const childStateNodes = new Array(childStateKeys.length);
1679
+ const allStateNodes = [stateNode.machine.root, stateNode];
1680
+ for (let i = 0; i < childStateKeys.length; i++) {
1681
+ const subStateNode = getStateNode(stateNode, childStateKeys[i]);
1682
+ childStateNodes[i] = subStateNode;
1683
+ allStateNodes.push(subStateNode);
1684
+ }
1685
+ for (let i = 0; i < childStateKeys.length; i++) {
1686
+ allStateNodes.push(...getStateNodes(childStateNodes[i], stateValue[childStateKeys[i]]));
1687
+ }
1688
+ return allStateNodes;
1689
+ }
1690
+ function transitionNode(stateNode, stateValue, snapshot, event, self) {
1691
+ // leaf node
1692
+ if (typeof stateValue === 'string') {
1693
+ const childStateNode = getStateNode(stateNode, stateValue);
1694
+ const next = childStateNode.next(snapshot, event, self);
1695
+ if (!next || !next.length) {
1696
+ return stateNode.next(snapshot, event, self);
1697
+ }
1698
+ return next;
1699
+ }
1700
+ const subStateKeys = Object.keys(stateValue);
1701
+ const subStateKey = subStateKeys[0];
1702
+ if (subStateKeys.length === 1) {
1703
+ const childStateNode = getStateNode(stateNode, subStateKey);
1704
+ const next = transitionNode(childStateNode, stateValue[subStateKey], snapshot, event, self);
1705
+ if (!next || !next.length) {
1706
+ return stateNode.next(snapshot, event, self);
1707
+ }
1708
+ return next;
1709
+ }
1710
+ const allInnerTransitions = [];
1711
+ for (const subStateKey of subStateKeys) {
1712
+ const subStateValue = stateValue[subStateKey];
1713
+ if (!subStateValue) {
1714
+ continue;
1715
+ }
1716
+ const subStateNode = getStateNode(stateNode, subStateKey);
1717
+ const innerTransitions = transitionNode(subStateNode, subStateValue, snapshot, event, self);
1718
+ if (innerTransitions) {
1719
+ allInnerTransitions.push(...innerTransitions);
1720
+ }
1721
+ }
1722
+ if (!allInnerTransitions.length) {
1723
+ return stateNode.next(snapshot, event, self);
1724
+ }
1725
+ return allInnerTransitions;
1726
+ }
1727
+ function isDescendant(childStateNode, parentStateNode) {
1728
+ let marker = childStateNode;
1729
+ while (marker.parent && marker.parent !== parentStateNode) {
1730
+ marker = marker.parent;
1731
+ }
1732
+ return marker.parent === parentStateNode;
1733
+ }
1734
+ function hasDescendantState(stateNodes, parentStateNode) {
1735
+ for (const stateNode of stateNodes) {
1736
+ if (isDescendant(stateNode, parentStateNode)) {
1737
+ return true;
1738
+ }
1739
+ }
1740
+ return false;
1741
+ }
1742
+ function hasIntersection(s1, s2) {
1743
+ const s1Size = s1 instanceof Set ? s1.size : Array.isArray(s1) ? s1.length : undefined;
1744
+ const s2Size = s2 instanceof Set ? s2.size : Array.isArray(s2) ? s2.length : undefined;
1745
+ if (s1Size !== undefined && s2Size !== undefined && s2Size < s1Size) {
1746
+ [s1, s2] = [s2, s1];
1747
+ }
1748
+ const set1 = s1 instanceof Set ? s1 : new Set(s1);
1749
+ for (const item of s2) {
1750
+ if (set1.has(item)) {
1751
+ return true;
1752
+ }
1753
+ }
1754
+ return false;
1755
+ }
1756
+ function removeConflictingTransitions(enabledTransitions, stateNodeSet, snapshot, event, actorScope) {
1757
+ const filteredTransitions = new Set();
1758
+ const exitSets = new Map();
1759
+ const getExitSet = transition => {
1760
+ let exitSet = exitSets.get(transition);
1761
+ if (!exitSet) {
1762
+ exitSet = computeExitSet([transition], stateNodeSet, snapshot, event, actorScope);
1763
+ exitSets.set(transition, exitSet);
1764
+ }
1765
+ return exitSet;
1766
+ };
1767
+ for (const t1 of enabledTransitions) {
1768
+ let t1Preempted = false;
1769
+ const transitionsToRemove = new Set();
1770
+ for (const t2 of filteredTransitions) {
1771
+ if (hasIntersection(getExitSet(t1), getExitSet(t2))) {
1772
+ if (isDescendant(t1.source, t2.source)) {
1773
+ transitionsToRemove.add(t2);
1774
+ } else {
1775
+ t1Preempted = true;
1776
+ break;
1777
+ }
1778
+ }
1779
+ }
1780
+ if (!t1Preempted) {
1781
+ for (const t3 of transitionsToRemove) {
1782
+ filteredTransitions.delete(t3);
1783
+ }
1784
+ filteredTransitions.add(t1);
1785
+ }
1786
+ }
1787
+ return Array.from(filteredTransitions);
1788
+ }
1789
+ function getEffectiveTargetStates(transition, snapshot, event, actorScope) {
1790
+ const historyValue = snapshot.historyValue;
1791
+ const {
1792
+ targets
1793
+ } = getTransitionResult(transition, snapshot, event, actorScope);
1794
+ if (!targets) {
1795
+ return [];
1796
+ }
1797
+ const targetSet = new Set();
1798
+ for (const targetNode of targets) {
1799
+ if (isHistoryNode(targetNode)) {
1800
+ if (historyValue[targetNode.id]) {
1801
+ for (const node of historyValue[targetNode.id]) {
1802
+ targetSet.add(node);
1803
+ }
1804
+ } else {
1805
+ for (const node of getEffectiveTargetStates(resolveHistoryDefaultTransition(targetNode), snapshot, event, actorScope)) {
1806
+ targetSet.add(node);
1807
+ }
1808
+ }
1809
+ } else {
1810
+ targetSet.add(targetNode);
1811
+ }
1812
+ }
1813
+ return [...targetSet];
1814
+ }
1815
+ function getTransitionDomain(transition, snapshot, event, actorScope) {
1816
+ const targetStates = getEffectiveTargetStates(transition, snapshot, event, actorScope);
1817
+ const {
1818
+ reenter
1819
+ } = getTransitionResult(transition, snapshot, event, actorScope);
1820
+ if (!reenter && targetStates.every(target => target === transition.source || isDescendant(target, transition.source))) {
1821
+ return transition.source;
1822
+ }
1823
+ const [head, ...tail] = targetStates.concat(transition.source);
1824
+ // Find the least common ancestor (LCA) of the source and effective targets.
1825
+ for (const ancestor of getProperAncestors(head, undefined)) {
1826
+ if (tail.every(sn => isDescendant(sn, ancestor))) {
1827
+ return ancestor;
1828
+ }
1829
+ }
1830
+
1831
+ // at this point we know that it's a root transition since LCA couldn't be found
1832
+ if (reenter) {
1833
+ return;
1834
+ }
1835
+ return transition.source.machine.root;
1836
+ }
1837
+ function computeExitSet(transitions, stateNodeSet, snapshot, event, actorScope) {
1838
+ const statesToExit = new Set();
1839
+ for (const transition of transitions) {
1840
+ const {
1841
+ targets
1842
+ } = getTransitionResult(transition, snapshot, event, actorScope);
1843
+ if (targets?.length) {
1844
+ const domain = getTransitionDomain(transition, snapshot, event, actorScope);
1845
+ if (transition.reenter && transition.source === domain) {
1846
+ statesToExit.add(domain);
1847
+ }
1848
+ for (const stateNode of stateNodeSet) {
1849
+ if (isDescendant(stateNode, domain)) {
1850
+ statesToExit.add(stateNode);
1851
+ }
1852
+ }
1853
+ }
1854
+ }
1855
+ return [...statesToExit];
1856
+ }
1857
+ function initialMicrostep(root, preInitialState, actorScope, initEvent, internalQueue) {
1858
+ return microstep([{
1859
+ target: [...getInitialStateNodes(root)],
1860
+ source: root,
1861
+ reenter: true,
1862
+ eventType: null,
1863
+ toJSON: null
1864
+ }], preInitialState, actorScope, initEvent, true, internalQueue);
1865
+ }
1866
+
1867
+ /** https://www.w3.org/TR/scxml/#microstepProcedure */
1868
+ function microstep(transitions, currentSnapshot, actorScope, event, isInitial, internalQueue) {
1869
+ const actions = [];
1870
+ if (!transitions.length) {
1871
+ return [currentSnapshot, actions];
1872
+ }
1873
+ const originalExecutor = actorScope.actionExecutor;
1874
+ actorScope.actionExecutor = action => {
1875
+ actions.push(action);
1876
+ originalExecutor(action);
1877
+ };
1878
+ try {
1879
+ const mutStateNodeSet = new Set(currentSnapshot._nodes);
1880
+ let historyValue = currentSnapshot.historyValue;
1881
+ const originalContext = currentSnapshot.context;
1882
+ const filteredTransitions = removeConflictingTransitions(transitions, mutStateNodeSet, currentSnapshot, event, actorScope);
1883
+ const getCurrentTransitionResult = transition => getTransitionResult(transition, currentSnapshot, event, actorScope);
1884
+ const getStateActionsAndContext = (transitionFn, context, children, input) => {
1885
+ if (transitionFn.length === 2) {
1886
+ // enqueue action; retrieve
1887
+ const actions = [];
1888
+ const internalEvents = [];
1889
+ let updatedContext;
1890
+ const enqueue = createTransitionEnqueue(actorScope, actions, internalEvents, true);
1891
+ const res = transitionFn({
1892
+ context,
1893
+ event,
1894
+ parent: actorScope.self._parent,
1895
+ self: actorScope.self,
1896
+ children,
1897
+ system: actorScope.system,
1898
+ actions: currentSnapshot.machine.implementations.actions,
1899
+ actors: currentSnapshot.machine.implementations.actors,
1900
+ guards: currentSnapshot.machine.implementations.guards,
1901
+ delays: currentSnapshot.machine.implementations.delays,
1902
+ input
1903
+ }, enqueue);
1904
+ if (res?.context) {
1905
+ updatedContext = res.context;
1906
+ }
1907
+ return [actions, updatedContext, internalEvents];
1908
+ }
1909
+
1910
+ // For 1-argument actions, wrap them to include input
1911
+ // Preserve _special flag if present (for entry/exit actions)
1912
+ const wrappedAction = Object.assign((args, enqueue) => transitionFn({
1913
+ ...args,
1914
+ input
1915
+ }, enqueue), '_special' in transitionFn ? {
1916
+ _special: true
1917
+ } : {});
1918
+ return [[wrappedAction], undefined, undefined];
1919
+ };
1920
+ let nextState = currentSnapshot;
1921
+ const exitStates = () => {
1922
+ const statesToExit = computeExitSet(filteredTransitions, mutStateNodeSet, currentSnapshot, event, actorScope);
1923
+ statesToExit.sort((a, b) => b.order - a.order);
1924
+ let changedHistory;
1925
+ const currentStateNodes = [...mutStateNodeSet];
1926
+
1927
+ // From SCXML algorithm: https://www.w3.org/TR/scxml/#exitStates
1928
+ for (const exitStateNode of statesToExit) {
1929
+ for (const historyNode of Object.values(exitStateNode.states)) {
1930
+ if (historyNode.type !== 'history') {
1931
+ continue;
1932
+ }
1933
+ const predicate = historyNode.history === 'deep' ? sn => isAtomicStateNode(sn) && isDescendant(sn, exitStateNode) : sn => sn.parent === exitStateNode;
1934
+ changedHistory ??= {
1935
+ ...historyValue
1936
+ };
1937
+ changedHistory[historyNode.id] = currentStateNodes.filter(predicate);
1938
+ }
1939
+ }
1940
+ for (const exitStateNode of statesToExit) {
1941
+ const stateInput = currentSnapshot._stateInputs?.[exitStateNode.id];
1942
+ const [exitActions, nextContext, internalEvents] = exitStateNode.exit ? getStateActionsAndContext(exitStateNode.exit, nextState.context, currentSnapshot.children, stateInput) : [[]];
1943
+ if (internalEvents?.length) {
1944
+ internalQueue.push(...internalEvents);
1945
+ }
1946
+ if (nextContext) {
1947
+ nextState = cloneMachineSnapshot(nextState, {
1948
+ context: nextContext
1949
+ });
1950
+ }
1951
+ nextState = resolveAndExecuteActionsWithContext(nextState, event, actorScope, exitActions);
1952
+ for (const def of exitStateNode.invoke) {
1953
+ const childActor = nextState.children[def.id];
1954
+ if (childActor && !childActor._isExternal) {
1955
+ actorScope.stopChild(childActor);
1956
+ }
1957
+ delete nextState.children[def.id];
1958
+ }
1959
+ mutStateNodeSet.delete(exitStateNode);
1960
+ }
1961
+ historyValue = changedHistory || historyValue;
1962
+ };
1963
+
1964
+ // Exit states
1965
+ if (!isInitial) {
1966
+ exitStates();
1967
+ }
1968
+ let context = nextState.context;
1969
+ const transitionActions = [];
1970
+ const internalEvents = [];
1971
+ for (const t of filteredTransitions) {
1972
+ if (t.actions) {
1973
+ transitionActions.push(...toArray(t.actions));
1974
+ }
1975
+ const res = getCurrentTransitionResult(t);
1976
+ if (res.context) {
1977
+ context = res.context;
1978
+ }
1979
+ if (res.actions) {
1980
+ transitionActions.push(...res.actions);
1981
+ }
1982
+ if (res.internalEvents) {
1983
+ internalEvents.push(...res.internalEvents);
1984
+ }
1985
+ }
1986
+ if (internalEvents.length) {
1987
+ internalQueue.push(...internalEvents);
1988
+ }
1989
+ const enterStates = () => {
1990
+ const getMachineOutput = rootCompletionNode => {
1991
+ const rootNode = nextState.machine.root;
1992
+ if (rootNode.output === undefined) {
1993
+ return;
1994
+ }
1995
+ let completionOutput;
1996
+ if (rootCompletionNode.output !== undefined && rootCompletionNode.parent) {
1997
+ completionOutput = resolveOutput(rootCompletionNode.output, nextState.context, event, actorScope.self);
1998
+ } else if (rootCompletionNode.type === 'parallel') {
1999
+ const parallelDoneType = `xstate.done.state.${rootCompletionNode.id}`;
2000
+ const parallelDoneEvent = internalQueue.find(e => e.type === parallelDoneType);
2001
+ completionOutput = parallelDoneEvent?.output;
2002
+ }
2003
+ return resolveOutput(rootNode.output, nextState.context, createDoneStateEvent(rootCompletionNode.id, completionOutput), actorScope.self);
2004
+ };
2005
+ const statesToEnter = new Set();
2006
+ // those are states that were directly targeted or indirectly targeted by the explicit target
2007
+ // in other words, those are states for which initial actions should be executed
2008
+ // when we target `#deep_child` initial actions of its ancestors shouldn't be executed
2009
+ const statesForDefaultEntry = new Set();
2010
+ const addAncestorStatesToEnter = (ancestors, reentrancyDomain) => {
2011
+ for (const anc of ancestors) {
2012
+ if (!reentrancyDomain || isDescendant(anc, reentrancyDomain)) {
2013
+ statesToEnter.add(anc);
2014
+ }
2015
+ if (anc.type === 'parallel') {
2016
+ for (const child of getChildren(anc)) {
2017
+ if (!hasDescendantState(statesToEnter, child)) {
2018
+ statesToEnter.add(child);
2019
+ addDescendantStatesToEnter(child);
2020
+ }
2021
+ }
2022
+ }
2023
+ }
2024
+ };
2025
+ const addDescendantStatesToEnter = stateNode => {
2026
+ if (isHistoryNode(stateNode)) {
2027
+ if (historyValue[stateNode.id]) {
2028
+ const historyStateNodes = historyValue[stateNode.id];
2029
+ for (const s of historyStateNodes) {
2030
+ statesToEnter.add(s);
2031
+ addDescendantStatesToEnter(s);
2032
+ }
2033
+ for (const s of historyStateNodes) {
2034
+ addAncestorStatesToEnter(getProperAncestors(s, stateNode.parent), undefined);
2035
+ }
2036
+ } else {
2037
+ const historyDefaultTransition = resolveHistoryDefaultTransition(stateNode);
2038
+ const {
2039
+ targets
2040
+ } = getCurrentTransitionResult(historyDefaultTransition);
2041
+ for (const s of targets ?? []) {
2042
+ statesToEnter.add(s);
2043
+ if (historyDefaultTransition === stateNode.parent?.initial) {
2044
+ statesForDefaultEntry.add(stateNode.parent);
2045
+ }
2046
+ addDescendantStatesToEnter(s);
2047
+ }
2048
+ for (const s of targets ?? []) {
2049
+ addAncestorStatesToEnter(getProperAncestors(s, stateNode.parent), undefined);
2050
+ }
2051
+ }
2052
+ return;
2053
+ }
2054
+ if (stateNode.type === 'compound') {
2055
+ const [initialState] = getCurrentTransitionResult(stateNode.initial).targets;
2056
+ if (!isHistoryNode(initialState)) {
2057
+ statesToEnter.add(initialState);
2058
+ statesForDefaultEntry.add(initialState);
2059
+ }
2060
+ addDescendantStatesToEnter(initialState);
2061
+ addAncestorStatesToEnter(getProperAncestors(initialState, stateNode), undefined);
2062
+ return;
2063
+ }
2064
+ if (stateNode.type === 'parallel') {
2065
+ for (const child of getChildren(stateNode)) {
2066
+ if (!hasDescendantState(statesToEnter, child)) {
2067
+ statesToEnter.add(child);
2068
+ statesForDefaultEntry.add(child);
2069
+ addDescendantStatesToEnter(child);
2070
+ }
2071
+ }
2072
+ }
2073
+ };
2074
+ for (const transition of filteredTransitions) {
2075
+ const domain = getTransitionDomain(transition, currentSnapshot, event, actorScope);
2076
+ const {
2077
+ targets,
2078
+ reenter
2079
+ } = getCurrentTransitionResult(transition);
2080
+ for (const targetNode of targets ?? []) {
2081
+ if (!isHistoryNode(targetNode) && (transition.source !== targetNode || transition.source !== domain || reenter)) {
2082
+ statesToEnter.add(targetNode);
2083
+ statesForDefaultEntry.add(targetNode);
2084
+ }
2085
+ addDescendantStatesToEnter(targetNode);
2086
+ }
2087
+ const targetStates = getEffectiveTargetStates(transition, currentSnapshot, event, actorScope);
2088
+ for (const s of targetStates) {
2089
+ const ancestors = getProperAncestors(s, domain);
2090
+ if (domain?.type === 'parallel') {
2091
+ ancestors.push(domain);
2092
+ }
2093
+ addAncestorStatesToEnter(ancestors, !transition.source.parent && reenter ? undefined : domain);
2094
+ }
2095
+ }
2096
+ if (isInitial) {
2097
+ statesForDefaultEntry.add(currentSnapshot.machine.root);
2098
+ }
2099
+ const stateInputMap = {
2100
+ ...currentSnapshot._stateInputs
2101
+ };
2102
+ for (const transition of filteredTransitions) {
2103
+ const {
2104
+ targets,
2105
+ input
2106
+ } = getCurrentTransitionResult(transition);
2107
+ if (input && targets) {
2108
+ for (const targetNode of targets) {
2109
+ stateInputMap[targetNode.id] = input;
2110
+ }
2111
+ }
2112
+ }
2113
+ const completedNodes = new Set();
2114
+ const children = {
2115
+ ...currentSnapshot.children
2116
+ };
2117
+ for (const stateNodeToEnter of [...statesToEnter].sort((a, b) => a.order - b.order)) {
2118
+ mutStateNodeSet.add(stateNodeToEnter);
2119
+ const actions = [];
2120
+ let invoked = false;
2121
+ for (const invokeDef of stateNodeToEnter.invoke) {
2122
+ invoked = true;
2123
+ let src = invokeDef.logic;
2124
+ if (typeof src === 'function') {
2125
+ src = src({
2126
+ actors: currentSnapshot.machine.implementations.actors,
2127
+ context: nextState.context,
2128
+ event,
2129
+ self: actorScope.self
2130
+ });
2131
+ }
2132
+ const logic = typeof src === 'string' ? resolveReferencedActor(currentSnapshot.machine, src) : src;
2133
+ if (!logic) {
2134
+ throw new Error(`Actor logic '${typeof src === 'string' ? src : 'inline'}' not implemented in machine '${currentSnapshot.machine.id}'`);
2135
+ }
2136
+ const input = typeof invokeDef.input === 'function' ? invokeDef.input({
2137
+ self: actorScope.self,
2138
+ context: nextState.context,
2139
+ event
2140
+ }) : invokeDef.input;
2141
+ const actor = createActor(logic, {
2142
+ ...invokeDef,
2143
+ input,
2144
+ parent: actorScope.self,
2145
+ syncSnapshot: !!invokeDef.onSnapshot
2146
+ });
2147
+ actions.push({
2148
+ action: builtInActions['@xstate.start'],
2149
+ args: [actor]
2150
+ });
2151
+ if (invokeDef.id) {
2152
+ children[invokeDef.id] = actor;
2153
+ }
2154
+ }
2155
+ if (invoked) {
2156
+ nextState = cloneMachineSnapshot(nextState, {
2157
+ children
2158
+ });
2159
+ }
2160
+ let context;
2161
+ const stateInput = stateInputMap[stateNodeToEnter.id];
2162
+ if (stateNodeToEnter.entry) {
2163
+ const [resultActions, nextContext, nextInternalEvents] = getStateActionsAndContext(stateNodeToEnter.entry, nextState.context, children, stateInput);
2164
+ actions.push(...resultActions);
2165
+ if (nextInternalEvents?.length) {
2166
+ internalQueue.push(...nextInternalEvents);
2167
+ }
2168
+ if (nextContext) {
2169
+ context = nextContext;
2170
+ }
2171
+ }
2172
+ if (statesForDefaultEntry.has(stateNodeToEnter)) {
2173
+ const {
2174
+ actions: initialActions,
2175
+ input: initialInput
2176
+ } = getTransitionResult(stateNodeToEnter.initial, nextState, event, actorScope);
2177
+ if (initialActions) {
2178
+ actions.push(...initialActions);
2179
+ }
2180
+ if (initialInput && stateNodeToEnter.initial?.target) {
2181
+ for (const targetNode of stateNodeToEnter.initial.target) {
2182
+ stateInputMap[targetNode.id] = initialInput;
2183
+ }
2184
+ }
2185
+ }
2186
+ nextState = resolveAndExecuteActionsWithContext(nextState, event, actorScope, actions);
2187
+ if (context) {
2188
+ nextState.context = context;
2189
+ }
2190
+ if (stateNodeToEnter.type !== 'final') {
2191
+ continue;
2192
+ }
2193
+ const parent = stateNodeToEnter.parent;
2194
+ let ancestorMarker = parent?.type === 'parallel' ? parent : parent?.parent;
2195
+ let rootCompletionNode = ancestorMarker || stateNodeToEnter;
2196
+ if (parent?.type === 'compound') {
2197
+ internalQueue.push(createDoneStateEvent(parent.id, stateNodeToEnter.output !== undefined ? resolveOutput(stateNodeToEnter.output, nextState.context, event, actorScope.self) : undefined));
2198
+ }
2199
+ while (ancestorMarker?.type === 'parallel' && !completedNodes.has(ancestorMarker) && isInFinalState(mutStateNodeSet, ancestorMarker)) {
2200
+ completedNodes.add(ancestorMarker);
2201
+ const regionOutput = {};
2202
+ for (const region of getChildren(ancestorMarker)) {
2203
+ if (region.type === 'final') {
2204
+ regionOutput[region.key] = region.output !== undefined ? resolveOutput(region.output, nextState.context, event, actorScope.self) : undefined;
2205
+ continue;
2206
+ }
2207
+ if (region.type === 'parallel') {
2208
+ const regionDoneType = `xstate.done.state.${region.id}`;
2209
+ const regionDoneEvent = internalQueue.find(e => e.type === regionDoneType);
2210
+ regionOutput[region.key] = regionDoneEvent?.output;
2211
+ continue;
2212
+ }
2213
+ const finalChild = getChildren(region).find(s => s.type === 'final' && mutStateNodeSet.has(s));
2214
+ regionOutput[region.key] = finalChild?.output !== undefined ? resolveOutput(finalChild.output, nextState.context, event, actorScope.self) : undefined;
2215
+ }
2216
+ internalQueue.push(createDoneStateEvent(ancestorMarker.id, regionOutput));
2217
+ rootCompletionNode = ancestorMarker;
2218
+ ancestorMarker = ancestorMarker.parent;
2219
+ }
2220
+ if (ancestorMarker) {
2221
+ continue;
2222
+ }
2223
+ nextState = cloneMachineSnapshot(nextState, {
2224
+ status: 'done',
2225
+ output: getMachineOutput(rootCompletionNode)
2226
+ });
2227
+ }
2228
+ const inputChanged = JSON.stringify(stateInputMap) !== JSON.stringify(currentSnapshot._stateInputs || {});
2229
+ if (inputChanged) {
2230
+ nextState = cloneMachineSnapshot(nextState, {
2231
+ _stateInputs: stateInputMap
2232
+ });
2233
+ }
2234
+ };
2235
+
2236
+ // Execute transition content
2237
+ nextState = resolveAndExecuteActionsWithContext(nextState, event, actorScope, transitionActions);
2238
+ if (context && context !== currentSnapshot.context) {
2239
+ nextState = cloneMachineSnapshot(nextState, {
2240
+ context
2241
+ });
2242
+ }
2243
+
2244
+ // Enter states
2245
+ enterStates();
2246
+ const nextStateNodes = [...mutStateNodeSet];
2247
+ if (nextState.status === 'done') {
2248
+ const allExitActions = [];
2249
+ const nextStateNodesToExit = nextStateNodes.sort((a, b) => b.order - a.order);
2250
+ nextStateNodesToExit.forEach(stateNode => {
2251
+ if (stateNode.exit) {
2252
+ const stateInput = nextState._stateInputs?.[stateNode.id];
2253
+ const [exitActions,, nextInternalEvents] = getStateActionsAndContext(stateNode.exit, nextState.context, nextState.children, stateInput);
2254
+ allExitActions.push(...exitActions);
2255
+ if (nextInternalEvents?.length) {
2256
+ internalQueue.push(...nextInternalEvents);
2257
+ }
2258
+ }
2259
+ });
2260
+ nextState = resolveAndExecuteActionsWithContext(nextState, event, actorScope, allExitActions);
2261
+ }
2262
+ if (historyValue === currentSnapshot.historyValue && currentSnapshot._nodes.length === mutStateNodeSet.size && currentSnapshot._nodes.every(node => mutStateNodeSet.has(node))) {
2263
+ // If context was changed (e.g. by entry actions during self-transition),
2264
+ // clone to ensure reference inequality for eventless transition re-evaluation
2265
+ if (nextState.context !== originalContext) {
2266
+ return [cloneMachineSnapshot(nextState), actions];
2267
+ }
2268
+ return [nextState, actions];
2269
+ }
2270
+ return [cloneMachineSnapshot(nextState, {
2271
+ _nodes: nextStateNodes,
2272
+ historyValue
2273
+ }), actions];
2274
+ } finally {
2275
+ actorScope.actionExecutor = originalExecutor;
2276
+ }
2277
+ }
2278
+
2279
+ /**
2280
+ * Gets the transition result for a given transition without executing the
2281
+ * transition.
2282
+ */
2283
+ function getTransitionResult(transition, snapshot, event, actorScope) {
2284
+ if (transition.to) {
2285
+ const actions = [];
2286
+ const internalEvents = [];
2287
+ const enqueue = createTransitionEnqueue(actorScope, actions, internalEvents);
2288
+ const res = transition.to({
2289
+ context: snapshot.context,
2290
+ event,
2291
+ value: snapshot.value,
2292
+ children: snapshot.children,
2293
+ parent: actorScope.self._parent,
2294
+ self: actorScope.self,
2295
+ actions: snapshot.machine.implementations.actions,
2296
+ actors: snapshot.machine.implementations.actors,
2297
+ guards: snapshot.machine.implementations.guards,
2298
+ delays: snapshot.machine.implementations.delays
2299
+ }, enqueue);
2300
+ const targets = res?.target ? resolveTarget(transition.source, toArray(res.target)) : undefined;
2301
+ // Resolve input for .to transitions
2302
+ const resolvedInput = typeof transition.input === 'function' ? transition.input({
2303
+ context: snapshot.context,
2304
+ event
2305
+ }) : transition.input;
2306
+ return {
2307
+ targets: targets,
2308
+ context: res?.context,
2309
+ reenter: res?.reenter,
2310
+ actions,
2311
+ internalEvents,
2312
+ input: resolvedInput
2313
+ };
2314
+ }
2315
+
2316
+ // Resolve input for regular transitions
2317
+ const resolvedInput = typeof transition.input === 'function' ? transition.input({
2318
+ context: snapshot.context,
2319
+ event
2320
+ }) : transition.input;
2321
+ return {
2322
+ targets: transition.target,
2323
+ context: undefined,
2324
+ reenter: transition.reenter,
2325
+ actions: undefined,
2326
+ internalEvents: undefined,
2327
+ input: resolvedInput
2328
+ };
2329
+ }
2330
+ function macrostep(snapshot, event, actorScope, internalQueue) {
2331
+ let nextSnapshot = snapshot;
2332
+ const microsteps = [];
2333
+ function addMicrostep(step, transitions) {
2334
+ // collect microsteps; surfaced on the enclosing '@xstate.transition' event
2335
+ // via its `microsteps[]` facet (there is no standalone microstep event)
2336
+ const collectedMicrosteps = actorScope.self._collectedMicrosteps || [];
2337
+ collectedMicrosteps.push(...transitions);
2338
+ actorScope.self._collectedMicrosteps = collectedMicrosteps;
2339
+ microsteps.push(step);
2340
+ }
2341
+
2342
+ // Handle stop event
2343
+ if (event.type === XSTATE_STOP) {
2344
+ nextSnapshot = cloneMachineSnapshot(stopChildren(nextSnapshot, actorScope), {
2345
+ status: 'stopped'
2346
+ });
2347
+ addMicrostep([nextSnapshot, []], []);
2348
+ return {
2349
+ snapshot: nextSnapshot,
2350
+ microsteps
2351
+ };
2352
+ }
2353
+ let nextEvent = event;
2354
+
2355
+ // Assume the state is at rest (no raised events)
2356
+ // Determine the next state based on the next microstep
2357
+ if (nextEvent.type !== XSTATE_INIT) {
2358
+ const currentEvent = nextEvent;
2359
+ const isErr = isErrorActorEvent(currentEvent);
2360
+ const transitions = nextSnapshot.machine.getTransitionData(nextSnapshot, currentEvent, actorScope.self);
2361
+ if (isErr && !transitions.length) {
2362
+ // TODO: we should likely only allow transitions selected by very explicit descriptors
2363
+ // `*` shouldn't be matched, likely `xstate.error.*` shouldn't be either
2364
+ // similarly `xstate.error.actor.*` and `xstate.error.actor.todo.*` have to be considered too
2365
+ nextSnapshot = cloneMachineSnapshot(snapshot, {
2366
+ status: 'error',
2367
+ error: currentEvent.error
2368
+ });
2369
+ addMicrostep([nextSnapshot, []], []);
2370
+ return {
2371
+ snapshot: nextSnapshot,
2372
+ microsteps
2373
+ };
2374
+ }
2375
+ const step = microstep(transitions, snapshot, actorScope, nextEvent, false,
2376
+ // isInitial
2377
+ internalQueue);
2378
+ nextSnapshot = step[0];
2379
+ addMicrostep(step, transitions);
2380
+ }
2381
+ let shouldSelectEventlessTransitions = true;
2382
+ const maxIterations = snapshot.machine.options?.maxIterations ?? Infinity;
2383
+ let iterationCount = 0;
2384
+ let microstepCount = 0;
2385
+ while (nextSnapshot.status === 'active') {
2386
+ microstepCount++;
2387
+ if (microstepCount > 1000) {
2388
+ throw new Error('Microstep count exceeded 1000');
2389
+ }
2390
+ iterationCount++;
2391
+ if (iterationCount > maxIterations) {
2392
+ throw new Error(`Infinite loop detected: the machine has processed more than ${maxIterations} microsteps without reaching a stable state. This usually happens when there's a cycle of transitions (e.g., eventless transitions or raised events causing state A -> B -> C -> A).` );
2393
+ }
2394
+ let enabledTransitions = shouldSelectEventlessTransitions ? selectEventlessTransitions(nextSnapshot, nextEvent, actorScope) : [];
2395
+
2396
+ // eventless transitions should always be selected after selecting *regular* transitions
2397
+ // by assigning `undefined` to `previousState` we ensure that `shouldSelectEventlessTransitions` gets always computed to true in such a case
2398
+ const previousState = enabledTransitions.length ? nextSnapshot : undefined;
2399
+ if (!enabledTransitions.length) {
2400
+ if (!internalQueue.length) {
2401
+ break;
2402
+ }
2403
+ nextEvent = internalQueue.shift();
2404
+ enabledTransitions = nextSnapshot.machine.getTransitionData(nextSnapshot, nextEvent, actorScope.self);
2405
+ }
2406
+ const step = microstep(enabledTransitions, nextSnapshot, actorScope, nextEvent, false, internalQueue);
2407
+ nextSnapshot = step[0];
2408
+ shouldSelectEventlessTransitions = nextSnapshot !== previousState;
2409
+ addMicrostep(step, enabledTransitions);
2410
+ }
2411
+ if (nextSnapshot.status !== 'active' && nextSnapshot.children) {
2412
+ stopChildren(nextSnapshot, actorScope);
2413
+ }
2414
+ return {
2415
+ snapshot: nextSnapshot,
2416
+ microsteps
2417
+ };
2418
+ }
2419
+
2420
+ /**
2421
+ * Resolves a partial state value with its full representation in the state
2422
+ * node's machine.
2423
+ *
2424
+ * @param stateValue The partial state value to resolve.
2425
+ */
2426
+ function resolveStateValue(rootNode, stateValue) {
2427
+ const allStateNodes = getAllStateNodes(getStateNodes(rootNode, stateValue));
2428
+ return getStateValue(rootNode, allStateNodes);
2429
+ }
2430
+ function createEnqueueObject(props, action) {
2431
+ const enqueueFn = (fn, ...args) => {
2432
+ action(fn, ...args);
2433
+ };
2434
+ Object.assign(enqueueFn, {
2435
+ cancel: () => {},
2436
+ emit: () => {},
2437
+ log: () => {},
2438
+ raise: () => {},
2439
+ spawn: () => ({}),
2440
+ sendTo: () => {},
2441
+ stop: () => {},
2442
+ listen: () => ({}),
2443
+ subscribeTo: () => ({}),
2444
+ ...props
2445
+ });
2446
+ return enqueueFn;
2447
+ }
2448
+ function hasEffect(transition, context, event, snapshot, self) {
2449
+ if (transition.to) {
2450
+ return transitionToHasEffect(transition.to, context, event, snapshot, self, snapshot.machine.implementations);
2451
+ }
2452
+ return false;
2453
+ }
2454
+ function transitionToHasEffect(transitionTo, context, event, snapshot, self, implementations) {
2455
+ let hasEffect = false;
2456
+ let res;
2457
+ try {
2458
+ const triggerEffect = () => {
2459
+ hasEffect = true;
2460
+ throw new Error('Effect triggered');
2461
+ };
2462
+ res = transitionTo({
2463
+ context,
2464
+ event,
2465
+ self,
2466
+ value: snapshot.value,
2467
+ children: snapshot.children,
2468
+ parent: {
2469
+ send: triggerEffect
2470
+ },
2471
+ actions: implementations.actions,
2472
+ actors: implementations.actors,
2473
+ guards: implementations.guards,
2474
+ delays: implementations.delays
2475
+ }, createEnqueueObject({
2476
+ emit: triggerEffect,
2477
+ cancel: triggerEffect,
2478
+ log: triggerEffect,
2479
+ raise: triggerEffect,
2480
+ spawn: triggerEffect,
2481
+ sendTo: triggerEffect,
2482
+ stop: triggerEffect
2483
+ }, triggerEffect));
2484
+ } catch (err) {
2485
+ if (hasEffect) {
2486
+ return true;
2487
+ }
2488
+ throw err;
2489
+ }
2490
+ return res !== undefined;
2491
+ }
2492
+ function stopChildren(snapshot, actorScope) {
2493
+ let children;
2494
+ if (!snapshot.children || (children = Object.values(snapshot.children).filter(Boolean)).length === 0) {
2495
+ return snapshot;
2496
+ }
2497
+ for (const child of children) {
2498
+ actorScope.stopChild(child);
2499
+ }
2500
+ return cloneMachineSnapshot(snapshot, {
2501
+ children: {}
2502
+ });
2503
+ }
2504
+ function selectEventlessTransitions(snapshot, event, actorScope) {
2505
+ const enabledTransitionSet = new Set();
2506
+ const atomicStates = snapshot._nodes.filter(isAtomicStateNode);
2507
+ for (const atomicStateNode of atomicStates) {
2508
+ loop: for (let stateNode = atomicStateNode; stateNode; stateNode = stateNode.parent) {
2509
+ if (!stateNode.always) {
2510
+ continue;
2511
+ }
2512
+ for (const transition of stateNode.always) {
2513
+ if (evaluateCandidate(transition, event, snapshot, stateNode, actorScope.self)) {
2514
+ enabledTransitionSet.add(transition);
2515
+ break loop;
2516
+ }
2517
+ }
2518
+ }
2519
+ }
2520
+ return removeConflictingTransitions(Array.from(enabledTransitionSet), new Set(snapshot._nodes), snapshot, event, actorScope);
2521
+ }
2522
+ function evaluateCandidate(candidate, event, snapshot, stateNode, self) {
2523
+ if (candidate.guard) {
2524
+ const guardArgs = {
2525
+ context: snapshot.context,
2526
+ event,
2527
+ self,
2528
+ parent: self._parent,
2529
+ children: snapshot.children,
2530
+ actions: stateNode.machine.implementations.actions,
2531
+ actors: stateNode.machine.implementations.actors,
2532
+ guards: stateNode.machine.implementations.guards,
2533
+ delays: stateNode.machine.implementations.delays,
2534
+ _snapshot: snapshot
2535
+ };
2536
+ const guardConfig = candidate.guard;
2537
+ const guardParams = typeof guardConfig?.params === 'function' ? guardConfig.params({
2538
+ context: snapshot.context,
2539
+ event
2540
+ }) : guardConfig?.params;
2541
+ let guardPassed = true;
2542
+ if (typeof guardConfig === 'function') {
2543
+ guardPassed = guardConfig(guardArgs, guardParams);
2544
+ } else if (typeof guardConfig?.type === 'string') {
2545
+ const guardImpl = stateNode.machine.implementations.guards[guardConfig.type];
2546
+ if (!guardImpl) {
2547
+ // A typo'd guard name must fail loudly — silently passing would
2548
+ // take the guarded transition and corrupt machine behavior.
2549
+ throw new Error(`Guard '${guardConfig.type}' is not implemented in machine '${stateNode.machine.id}'. Available guards: ${Object.keys(stateNode.machine.implementations.guards).map(key => `'${key}'`).join(', ') || '(none)'}.` );
2550
+ }
2551
+ guardPassed = guardImpl(guardArgs, guardParams);
2552
+ }
2553
+ if (!guardPassed) {
2554
+ return false;
2555
+ }
2556
+ }
2557
+ if (candidate.to) {
2558
+ return transitionToHasEffect(candidate.to, snapshot.context, event, snapshot, self, stateNode.machine.implementations);
2559
+ }
2560
+ return true;
2561
+ }
2562
+
2563
+ function isMachineSnapshot(value) {
2564
+ return !!value && typeof value === 'object' && 'machine' in value && 'value' in value;
2565
+ }
2566
+ let emptyCanActor;
2567
+ let emptyCanActorScope;
2568
+ function getEmptyCanActor() {
2569
+ return emptyCanActor ??= createEmptyActor();
2570
+ }
2571
+ function getEmptyCanActorScope() {
2572
+ if (emptyCanActorScope) {
2573
+ return emptyCanActorScope;
2574
+ }
2575
+ const actor = getEmptyCanActor();
2576
+ emptyCanActorScope = {
2577
+ self: actor,
2578
+ logger: () => {},
2579
+ id: '',
2580
+ sessionId: '',
2581
+ defer: () => {},
2582
+ system: actor.system,
2583
+ stopChild: () => {},
2584
+ emit: () => {},
2585
+ actionExecutor: () => {}
2586
+ };
2587
+ return emptyCanActorScope;
2588
+ }
2589
+ const machineSnapshotMatches = function matches(testValue) {
2590
+ return matchesState(testValue, this.value);
2591
+ };
2592
+ const machineSnapshotHasTag = function hasTag(tag) {
2593
+ return this.tags.has(tag);
2594
+ };
2595
+ const machineSnapshotCan = function can(event) {
2596
+ if (!this.machine) {
2597
+ console.warn(`state.can(...) used outside of a machine-created State object; this will always return false.`);
2598
+ }
2599
+ const emptyActor = getEmptyCanActor();
2600
+ const emptyActorScope = getEmptyCanActorScope();
2601
+ const transitionData = this.machine.getTransitionData(this, event, emptyActor);
2602
+ if (!transitionData?.length) {
2603
+ return false;
2604
+ }
2605
+
2606
+ // Check that at least one transition is not forbidden
2607
+ for (const transition of transitionData) {
2608
+ if (transition.target !== undefined) {
2609
+ return true;
2610
+ }
2611
+ const res = getTransitionResult(transition, this, event, emptyActorScope);
2612
+ if (res.targets?.length || res.context || hasEffect(transition, this.context, event, this, emptyActor)) {
2613
+ return true;
2614
+ }
2615
+ }
2616
+ return false;
2617
+ };
2618
+ const machineSnapshotToJSON = function toJSON() {
2619
+ const {
2620
+ _nodes: nodes,
2621
+ _stateInputs,
2622
+ tags,
2623
+ machine,
2624
+ getMeta,
2625
+ getInputs,
2626
+ toJSON,
2627
+ can,
2628
+ hasTag,
2629
+ matches,
2630
+ ...jsonValues
2631
+ } = this;
2632
+ return {
2633
+ ...jsonValues,
2634
+ tags: Array.from(tags)
2635
+ };
2636
+ };
2637
+ const machineSnapshotGetMeta = function getMeta() {
2638
+ const meta = {};
2639
+ for (const stateNode of this._nodes) {
2640
+ if (stateNode.meta !== undefined) {
2641
+ meta[stateNode.id] = stateNode.meta;
2642
+ }
2643
+ }
2644
+ return meta;
2645
+ };
2646
+ const machineSnapshotGetInputs = function getInputs() {
2647
+ return this._stateInputs;
2648
+ };
2649
+ function collectTags(stateNodes) {
2650
+ const tags = new Set();
2651
+ for (const stateNode of stateNodes) {
2652
+ for (const tag of stateNode.tags) {
2653
+ tags.add(tag);
2654
+ }
2655
+ }
2656
+ return tags;
2657
+ }
2658
+ function createMachineSnapshot(config, machine) {
2659
+ return {
2660
+ status: config.status,
2661
+ output: config.output,
2662
+ error: config.error,
2663
+ machine,
2664
+ context: config.context,
2665
+ _nodes: config._nodes,
2666
+ value: config.value ?? getStateValue(machine.root, config._nodes),
2667
+ tags: collectTags(config._nodes),
2668
+ children: config.children,
2669
+ historyValue: config.historyValue || {},
2670
+ _stateInputs: config._stateInputs || {},
2671
+ matches: machineSnapshotMatches,
2672
+ hasTag: machineSnapshotHasTag,
2673
+ can: machineSnapshotCan,
2674
+ getMeta: machineSnapshotGetMeta,
2675
+ getInputs: machineSnapshotGetInputs,
2676
+ toJSON: machineSnapshotToJSON
2677
+ };
2678
+ }
2679
+ function cloneMachineSnapshot(snapshot, config = {}) {
2680
+ const configWithSnapshot = {
2681
+ ...snapshot,
2682
+ ...config
2683
+ };
2684
+ if ((config._nodes ?? snapshot._nodes) === snapshot._nodes) {
2685
+ return {
2686
+ status: configWithSnapshot.status,
2687
+ output: configWithSnapshot.output,
2688
+ error: configWithSnapshot.error,
2689
+ machine: snapshot.machine,
2690
+ context: configWithSnapshot.context,
2691
+ _nodes: snapshot._nodes,
2692
+ value: snapshot.value,
2693
+ tags: snapshot.tags,
2694
+ children: configWithSnapshot.children,
2695
+ historyValue: configWithSnapshot.historyValue || {},
2696
+ _stateInputs: configWithSnapshot._stateInputs || {},
2697
+ matches: machineSnapshotMatches,
2698
+ hasTag: machineSnapshotHasTag,
2699
+ can: machineSnapshotCan,
2700
+ getMeta: machineSnapshotGetMeta,
2701
+ getInputs: machineSnapshotGetInputs,
2702
+ toJSON: machineSnapshotToJSON
2703
+ };
2704
+ }
2705
+ return createMachineSnapshot({
2706
+ ...configWithSnapshot,
2707
+ value: undefined
2708
+ }, snapshot.machine);
2709
+ }
2710
+ function serializeHistoryValue(historyValue) {
2711
+ const result = {};
2712
+ for (const key in historyValue) {
2713
+ const value = historyValue[key];
2714
+ if (Array.isArray(value)) {
2715
+ result[key] = value.map(item => ({
2716
+ id: item.id
2717
+ }));
2718
+ }
2719
+ }
2720
+ return result;
2721
+ }
2722
+ function getPersistedSnapshot(snapshot, options) {
2723
+ const {
2724
+ _nodes: nodes,
2725
+ _stateInputs,
2726
+ tags,
2727
+ machine,
2728
+ children,
2729
+ context,
2730
+ can,
2731
+ hasTag,
2732
+ matches,
2733
+ getMeta,
2734
+ getInputs,
2735
+ toJSON,
2736
+ ...jsonValues
2737
+ } = snapshot;
2738
+ const childrenJson = {};
2739
+ for (const id in children) {
2740
+ const child = children[id];
2741
+ if (typeof child.src !== 'string' && (!options || !('__unsafeAllowInlineActors' in options))) {
2742
+ throw new Error('An inline child actor cannot be persisted.');
2743
+ }
2744
+ childrenJson[id] = {
2745
+ snapshot: child.getPersistedSnapshot(options),
2746
+ src: child.src,
2747
+ systemId: child.systemId,
2748
+ syncSnapshot: child._syncSnapshot
2749
+ };
2750
+ }
2751
+ const persisted = {
2752
+ ...jsonValues,
2753
+ context: persistContext(context),
2754
+ children: childrenJson,
2755
+ historyValue: serializeHistoryValue(jsonValues.historyValue)
2756
+ };
2757
+ if (machine.version !== undefined) {
2758
+ persisted.version = machine.version;
2759
+ }
2760
+ return persisted;
2761
+ }
2762
+ function persistContext(contextPart) {
2763
+ let copy;
2764
+ for (const key in contextPart) {
2765
+ const value = contextPart[key];
2766
+ if (value && typeof value === 'object') {
2767
+ if ('sessionId' in value && 'send' in value && 'ref' in value) {
2768
+ copy ??= Array.isArray(contextPart) ? contextPart.slice() : {
2769
+ ...contextPart
2770
+ };
2771
+ copy[key] = {
2772
+ xstate$$type: $$ACTOR_TYPE,
2773
+ id: value.id
2774
+ };
2775
+ } else {
2776
+ const result = persistContext(value);
2777
+ if (result !== value) {
2778
+ copy ??= Array.isArray(contextPart) ? contextPart.slice() : {
2779
+ ...contextPart
2780
+ };
2781
+ copy[key] = result;
2782
+ }
2783
+ }
2784
+ }
2785
+ }
2786
+ return copy ?? contextPart;
2787
+ }
2788
+
2789
+ function matchesState(parentStateId, childStateId) {
2790
+ const parentStateValue = toStateValue(parentStateId);
2791
+ const childStateValue = toStateValue(childStateId);
2792
+ if (typeof childStateValue === 'string') {
2793
+ if (typeof parentStateValue === 'string') {
2794
+ return childStateValue === parentStateValue;
2795
+ }
2796
+
2797
+ // Parent more specific than child
2798
+ return false;
2799
+ }
2800
+ if (typeof parentStateValue === 'string') {
2801
+ return parentStateValue in childStateValue;
2802
+ }
2803
+ return Object.keys(parentStateValue).every(key => {
2804
+ if (!(key in childStateValue)) {
2805
+ return false;
2806
+ }
2807
+ return matchesState(parentStateValue[key], childStateValue[key]);
2808
+ });
2809
+ }
2810
+ function checkStateIn(snapshot, stateValue) {
2811
+ if (typeof stateValue === 'string' && isStateId(stateValue)) {
2812
+ const target = snapshot.machine.getStateNodeById(stateValue);
2813
+ return snapshot._nodes.some(sn => sn === target);
2814
+ }
2815
+ return snapshot.matches(stateValue);
2816
+ }
2817
+ function toStatePath(stateId) {
2818
+ if (isArray(stateId)) {
2819
+ return stateId;
2820
+ }
2821
+ const result = [];
2822
+ let segment = '';
2823
+ for (let i = 0; i < stateId.length; i++) {
2824
+ const char = stateId.charCodeAt(i);
2825
+ switch (char) {
2826
+ // \
2827
+ case 92:
2828
+ // consume the next character
2829
+ segment += stateId[i + 1];
2830
+ // and skip over it
2831
+ i++;
2832
+ continue;
2833
+ // .
2834
+ case 46:
2835
+ result.push(segment);
2836
+ segment = '';
2837
+ continue;
2838
+ }
2839
+ segment += stateId[i];
2840
+ }
2841
+ result.push(segment);
2842
+ return result;
2843
+ }
2844
+ function toStateValue(stateValue) {
2845
+ if (isMachineSnapshot(stateValue)) {
2846
+ return stateValue.value;
2847
+ }
2848
+ if (typeof stateValue !== 'string') {
2849
+ return stateValue;
2850
+ }
2851
+ const statePath = toStatePath(stateValue);
2852
+ return pathToStateValue(statePath);
2853
+ }
2854
+ function pathToStateValue(statePath) {
2855
+ if (statePath.length === 1) {
2856
+ return statePath[0];
2857
+ }
2858
+ const value = {};
2859
+ let marker = value;
2860
+ for (let i = 0; i < statePath.length - 1; i++) {
2861
+ if (i === statePath.length - 2) {
2862
+ marker[statePath[i]] = statePath[i + 1];
2863
+ } else {
2864
+ const previous = marker;
2865
+ marker = {};
2866
+ previous[statePath[i]] = marker;
2867
+ }
2868
+ }
2869
+ return value;
2870
+ }
2871
+ function mapValues(collection, iteratee) {
2872
+ const result = {};
2873
+ const collectionKeys = Object.keys(collection);
2874
+ for (let i = 0; i < collectionKeys.length; i++) {
2875
+ const key = collectionKeys[i];
2876
+ result[key] = iteratee(collection[key], key, collection, i);
2877
+ }
2878
+ return result;
2879
+ }
2880
+ function toArrayStrict(value) {
2881
+ if (isArray(value)) {
2882
+ return value;
2883
+ }
2884
+ return [value];
2885
+ }
2886
+ function toArray(value) {
2887
+ if (value === undefined) {
2888
+ return [];
2889
+ }
2890
+ return toArrayStrict(value);
2891
+ }
2892
+ function resolveOutput(mapper, context, event, self) {
2893
+ if (typeof mapper === 'function') {
2894
+ return mapper({
2895
+ context,
2896
+ event,
2897
+ self
2898
+ });
2899
+ }
2900
+ if (!!mapper && typeof mapper === 'object' && Object.values(mapper).some(val => typeof val === 'function')) {
2901
+ console.warn(`Dynamically mapping values to individual properties is deprecated. Use a single function that returns the mapped object instead.\nFound object containing properties whose values are possibly mapping functions: ${Object.entries(mapper).filter(([, value]) => typeof value === 'function').map(([key, value]) => `\n - ${key}: ${value.toString().replace(/\n\s*/g, '')}`).join('')}`);
2902
+ }
2903
+ return mapper;
2904
+ }
2905
+ function isArray(value) {
2906
+ return Array.isArray(value);
2907
+ }
2908
+ function isErrorActorEvent(event) {
2909
+ return event.type.startsWith('xstate.error.actor');
2910
+ }
2911
+ function toTransitionConfigArray(configLike) {
2912
+ return toArrayStrict(configLike).map(transitionLike => {
2913
+ if (typeof transitionLike === 'undefined' || typeof transitionLike === 'string') {
2914
+ return {
2915
+ target: transitionLike
2916
+ };
2917
+ }
2918
+ if (typeof transitionLike === 'function') {
2919
+ return {
2920
+ to: transitionLike
2921
+ };
2922
+ }
2923
+ return transitionLike;
2924
+ });
2925
+ }
2926
+ function normalizeTarget(target) {
2927
+ if (target === undefined || target === TARGETLESS_KEY) {
2928
+ return undefined;
2929
+ }
2930
+ return toArray(target);
2931
+ }
2932
+ function toObserver(nextHandler, errorHandler, completionHandler) {
2933
+ const isObserver = typeof nextHandler === 'object';
2934
+ const self = isObserver ? nextHandler : undefined;
2935
+ return {
2936
+ next: (isObserver ? nextHandler.next : nextHandler)?.bind(self),
2937
+ error: (isObserver ? nextHandler.error : errorHandler)?.bind(self),
2938
+ complete: (isObserver ? nextHandler.complete : completionHandler)?.bind(self)
2939
+ };
2940
+ }
2941
+ function createInvokeId(stateNodeId, index) {
2942
+ return `${index}.${stateNodeId}`;
2943
+ }
2944
+ function resolveReferencedActor(machine, src) {
2945
+ const match = src.match(/^xstate\.invoke\.(\d+)\.(.*)/);
2946
+ if (!match) {
2947
+ return machine.implementations.actors[src];
2948
+ }
2949
+ const [, indexStr, nodeId] = match;
2950
+ const node = machine.getStateNodeById(nodeId);
2951
+ const invokeConfig = node.config.invoke;
2952
+ const configSrc = (Array.isArray(invokeConfig) ? invokeConfig[indexStr] : invokeConfig).src;
2953
+ // A referenced actor may itself be registered by name.
2954
+ return typeof configSrc === 'string' ? machine.implementations.actors[configSrc] : configSrc;
2955
+ }
2956
+ function getAllOwnEventDescriptors(snapshot) {
2957
+ return [...new Set([...snapshot._nodes.flatMap(sn => sn.ownEvents)])];
2958
+ }
2959
+
2960
+ /**
2961
+ * Checks if an event type matches an event descriptor, supporting wildcards.
2962
+ * Event descriptors can be:
2963
+ *
2964
+ * - Exact matches: "event.type"
2965
+ * - Wildcard: "*"
2966
+ * - Partial matches: "event.*"
2967
+ *
2968
+ * @param eventType - The actual event type string
2969
+ * @param descriptor - The event descriptor to match against
2970
+ * @returns True if the event type matches the descriptor
2971
+ */
2972
+ function matchesEventDescriptor(eventType, descriptor) {
2973
+ if (descriptor === eventType) {
2974
+ return true;
2975
+ }
2976
+ if (descriptor === WILDCARD) {
2977
+ return true;
2978
+ }
2979
+ if (!descriptor.endsWith('.*')) {
2980
+ return false;
2981
+ }
2982
+ if (/.*\*.+/.test(descriptor)) {
2983
+ console.warn(`Wildcards can only be the last token of an event descriptor (e.g., "event.*") or the entire event descriptor ("*"). Check the "${descriptor}" event.`);
2984
+ }
2985
+ const partialEventTokens = descriptor.split('.');
2986
+ const eventTokens = eventType.split('.');
2987
+ for (let tokenIndex = 0; tokenIndex < partialEventTokens.length; tokenIndex++) {
2988
+ const partialEventToken = partialEventTokens[tokenIndex];
2989
+ const eventToken = eventTokens[tokenIndex];
2990
+ if (partialEventToken === '*') {
2991
+ const isLastToken = tokenIndex === partialEventTokens.length - 1;
2992
+ if (!isLastToken) {
2993
+ console.warn(`Infix wildcards in transition events are not allowed. Check the "${descriptor}" transition.`);
2994
+ }
2995
+ return isLastToken;
2996
+ }
2997
+ if (partialEventToken !== eventToken) {
2998
+ return false;
2999
+ }
3000
+ }
3001
+ return true;
3002
+ }
3003
+
3004
+ function createScheduledEventId(actor, id) {
3005
+ return `${actor.sessionId}.${id}`;
3006
+ }
3007
+ function createSystem(rootActor, options) {
3008
+ let idCounter = 0;
3009
+ const children = new Map();
3010
+ const keyedActors = new Map();
3011
+ const reverseKeyedActors = new WeakMap();
3012
+ const inspectionObservers = new Set();
3013
+ const timerMap = {};
3014
+ const {
3015
+ clock,
3016
+ logger
3017
+ } = options;
3018
+
3019
+ // Records a send on the *sender's* transition for the `sent[]` inspection
3020
+ // facet. Captures the send when it is initiated (including delayed sends that
3021
+ // may never deliver), keyed to the source actor's in-flight transition.
3022
+ const recordSent = (source, target, event, delay, id) => {
3023
+ if (!inspectionObservers.size || !source) {
3024
+ return;
3025
+ }
3026
+ const collected = source._collectedSent ??= [];
3027
+ collected.push({
3028
+ targetRef: target,
3029
+ targetId: target.id,
3030
+ event,
3031
+ delay,
3032
+ id
3033
+ });
3034
+ };
3035
+ const scheduler = {
3036
+ schedule: (source, target, event, delay, id = Math.random().toString(36).slice(2)) => {
3037
+ recordSent(source, target, event, delay, id);
3038
+ const scheduledEvent = {
3039
+ source,
3040
+ target,
3041
+ event,
3042
+ delay,
3043
+ id,
3044
+ startedAt: Date.now()
3045
+ };
3046
+ const scheduledEventId = createScheduledEventId(source, id);
3047
+ system._snapshot._scheduledEvents[scheduledEventId] = scheduledEvent;
3048
+ const timeout = clock.setTimeout(() => {
3049
+ delete timerMap[scheduledEventId];
3050
+ delete system._snapshot._scheduledEvents[scheduledEventId];
3051
+
3052
+ // The send was already recorded at schedule time on the sender's
3053
+ // transition, so deliver without re-recording.
3054
+ deliver(source, target, event);
3055
+ }, delay);
3056
+ timerMap[scheduledEventId] = timeout;
3057
+ },
3058
+ cancel: (source, id) => {
3059
+ const scheduledEventId = createScheduledEventId(source, id);
3060
+ const timeout = timerMap[scheduledEventId];
3061
+ delete timerMap[scheduledEventId];
3062
+ delete system._snapshot._scheduledEvents[scheduledEventId];
3063
+ if (timeout !== undefined) {
3064
+ clock.clearTimeout(timeout);
3065
+ }
3066
+ },
3067
+ cancelAll: actor => {
3068
+ for (const scheduledEventId in system._snapshot._scheduledEvents) {
3069
+ const scheduledEvent = system._snapshot._scheduledEvents[scheduledEventId];
3070
+ if (scheduledEvent.source === actor) {
3071
+ scheduler.cancel(actor, scheduledEvent.id);
3072
+ }
3073
+ }
3074
+ }
3075
+ };
3076
+ // Delivers an event to the target actor. Used by both `_relay` (which also
3077
+ // records the send) and the scheduler's timer (which already recorded it).
3078
+ const deliver = (source, target, event) => {
3079
+ const targetMachine = target.logic;
3080
+ const isInternalEvent = typeof targetMachine?.isInternalEventType === 'function' && targetMachine.isInternalEventType(event.type);
3081
+ if (isInternalEvent && source !== target) {
3082
+ throw new Error(`Internal event "${event.type}" cannot be sent to actor "${target.id}" from outside.`);
3083
+ }
3084
+
3085
+ // remember the last source for unified transition inspect event
3086
+ target._lastSourceRef = source;
3087
+ target._send(event);
3088
+ };
3089
+ const sendInspectionEvent = event => {
3090
+ if (!inspectionObservers.size) {
3091
+ return;
3092
+ }
3093
+ const resolvedInspectionEvent = {
3094
+ ...event,
3095
+ rootId: rootActor.sessionId
3096
+ };
3097
+ inspectionObservers.forEach(observer => observer.next?.(resolvedInspectionEvent));
3098
+ };
3099
+ const system = {
3100
+ children,
3101
+ reverseKeyedActors,
3102
+ keyedActors,
3103
+ _snapshot: {
3104
+ _scheduledEvents: (options?.snapshot && options.snapshot.scheduler) ?? {}
3105
+ },
3106
+ _bookId: () => `x:${idCounter++}`,
3107
+ _register: (sessionId, actor) => {
3108
+ children.set(sessionId, actor);
3109
+ return sessionId;
3110
+ },
3111
+ _unregister: actor => {
3112
+ children.delete(actor.sessionId);
3113
+ const systemId = reverseKeyedActors.get(actor);
3114
+ if (systemId !== undefined) {
3115
+ keyedActors.delete(systemId);
3116
+ reverseKeyedActors.delete(actor);
3117
+ }
3118
+ },
3119
+ get: systemId => {
3120
+ return keyedActors.get(systemId);
3121
+ },
3122
+ getAll: () => {
3123
+ return Object.fromEntries(keyedActors.entries());
3124
+ },
3125
+ _set: (systemId, actor) => {
3126
+ const existing = keyedActors.get(systemId);
3127
+ if (existing && existing !== actor) {
3128
+ throw new Error(`Actor with system ID '${systemId}' already exists.`);
3129
+ }
3130
+ keyedActors.set(systemId, actor);
3131
+ reverseKeyedActors.set(actor, systemId);
3132
+ },
3133
+ inspect: observerOrFn => {
3134
+ const observer = toObserver(observerOrFn);
3135
+ inspectionObservers.add(observer);
3136
+ return {
3137
+ unsubscribe() {
3138
+ inspectionObservers.delete(observer);
3139
+ }
3140
+ };
3141
+ },
3142
+ _sendInspectionEvent: sendInspectionEvent,
3143
+ _relay: (source, target, event) => {
3144
+ recordSent(source, target, event);
3145
+ deliver(source, target, event);
3146
+ },
3147
+ scheduler,
3148
+ getSnapshot: () => {
3149
+ return {
3150
+ _scheduledEvents: {
3151
+ ...system._snapshot._scheduledEvents
3152
+ }
3153
+ };
3154
+ },
3155
+ start: () => {
3156
+ const scheduledEvents = system._snapshot._scheduledEvents;
3157
+ system._snapshot._scheduledEvents = {};
3158
+ for (const scheduledId in scheduledEvents) {
3159
+ const {
3160
+ source,
3161
+ target,
3162
+ event,
3163
+ delay,
3164
+ id
3165
+ } = scheduledEvents[scheduledId];
3166
+ scheduler.schedule(source, target, event, delay, id);
3167
+ }
3168
+ },
3169
+ _clock: clock,
3170
+ _logger: logger,
3171
+ _timerStrategy: options.timers
3172
+ };
3173
+ return system;
3174
+ }
3175
+
3176
+ const effectStates = new WeakMap();
3177
+ const XSTATE_LOGIC_EFFECT_RESOLVE = 'xstate.logic.effect.resolve';
3178
+ const XSTATE_LOGIC_EFFECT_REJECT = 'xstate.logic.effect.reject';
3179
+ const XSTATE_LOGIC_EFFECT_START = 'xstate.logic.effect.start';
3180
+ function getEffectState(self) {
3181
+ let state = effectStates.get(self);
3182
+ if (!state) {
3183
+ state = new Map();
3184
+ effectStates.set(self, state);
3185
+ }
3186
+ return state;
3187
+ }
3188
+ function executeLogicEffects(effects, actorScope) {
3189
+ if (!effects?.length) {
3190
+ return;
3191
+ }
3192
+ for (const effect of effects) {
3193
+ switch (effect.type) {
3194
+ case 'emit':
3195
+ actorScope.emit(effect.event);
3196
+ break;
3197
+ case 'sendBack':
3198
+ {
3199
+ const parent = actorScope.self._parent;
3200
+ if (parent) {
3201
+ actorScope.system._relay(actorScope.self, parent, effect.event);
3202
+ }
3203
+ break;
3204
+ }
3205
+ case 'raise':
3206
+ actorScope.system._relay(actorScope.self, actorScope.self, effect.event);
3207
+ break;
3208
+ case 'effect':
3209
+ {
3210
+ if (!effect.key) {
3211
+ const cleanup = effect.exec();
3212
+ if (typeof cleanup === 'function') {
3213
+ getEffectState(actorScope.self).set(Symbol(), {
3214
+ cleanup
3215
+ });
3216
+ }
3217
+ break;
3218
+ }
3219
+ const state = getEffectState(actorScope.self);
3220
+ if (state.has(effect.key)) {
3221
+ break;
3222
+ }
3223
+ const cleanup = effect.exec();
3224
+ state.set(effect.key, {
3225
+ cleanup: typeof cleanup === 'function' ? cleanup : undefined
3226
+ });
3227
+ break;
3228
+ }
3229
+ case 'cleanupEffects':
3230
+ {
3231
+ const state = effectStates.get(actorScope.self);
3232
+ if (!state) {
3233
+ break;
3234
+ }
3235
+ for (const {
3236
+ cleanup
3237
+ } of state.values()) {
3238
+ cleanup?.();
3239
+ }
3240
+ effectStates.delete(actorScope.self);
3241
+ break;
3242
+ }
3243
+ }
3244
+ }
3245
+ }
3246
+ function resolveContext(context, input) {
3247
+ return typeof context === 'function' ? context({
3248
+ input
3249
+ }) : context;
3250
+ }
3251
+ function createLogic(config) {
3252
+ const transition = (snapshot, event, actorScope) => {
3253
+ if (snapshot.status !== 'active') {
3254
+ return [snapshot, []];
3255
+ }
3256
+ if (event.type === XSTATE_STOP) {
3257
+ return [{
3258
+ ...snapshot,
3259
+ status: 'stopped',
3260
+ input: undefined
3261
+ }, [{
3262
+ type: 'cleanupEffects'
3263
+ }]];
3264
+ }
3265
+ if (event.type === XSTATE_LOGIC_EFFECT_START) {
3266
+ return [{
3267
+ ...snapshot,
3268
+ effects: {
3269
+ ...snapshot.effects,
3270
+ [event.key]: {
3271
+ status: 'active'
3272
+ }
3273
+ }
3274
+ }, []];
3275
+ }
3276
+ if (event.type === XSTATE_LOGIC_EFFECT_RESOLVE) {
3277
+ return [{
3278
+ ...snapshot,
3279
+ effects: {
3280
+ ...snapshot.effects,
3281
+ [event.key]: {
3282
+ status: 'done',
3283
+ output: event.output
3284
+ }
3285
+ }
3286
+ }, []];
3287
+ }
3288
+ if (event.type === XSTATE_LOGIC_EFFECT_REJECT) {
3289
+ return [{
3290
+ ...snapshot,
3291
+ effects: {
3292
+ ...snapshot.effects,
3293
+ [event.key]: {
3294
+ status: 'error',
3295
+ error: event.error
3296
+ }
3297
+ }
3298
+ }, []];
3299
+ }
3300
+ const effects = [];
3301
+ const trackedEffects = {};
3302
+ const enqueueEffect = (key, exec) => {
3303
+ if (snapshot.effects?.[key]) {
3304
+ return;
3305
+ }
3306
+ effects.push({
3307
+ type: 'effect',
3308
+ key,
3309
+ exec
3310
+ });
3311
+ trackedEffects[key] = {
3312
+ status: 'active'
3313
+ };
3314
+ };
3315
+ const enq = {
3316
+ emit: emitted => {
3317
+ effects.push({
3318
+ type: 'emit',
3319
+ event: emitted
3320
+ });
3321
+ },
3322
+ sendBack: sentEvent => {
3323
+ effects.push({
3324
+ type: 'sendBack',
3325
+ event: sentEvent
3326
+ });
3327
+ },
3328
+ raise: raisedEvent => {
3329
+ effects.push({
3330
+ type: 'raise',
3331
+ event: raisedEvent
3332
+ });
3333
+ },
3334
+ effect: (keyOrExec, maybeExec) => {
3335
+ if (typeof keyOrExec === 'string') {
3336
+ enqueueEffect(keyOrExec, maybeExec);
3337
+ return;
3338
+ }
3339
+ effects.push({
3340
+ type: 'effect',
3341
+ exec: keyOrExec
3342
+ });
3343
+ }
3344
+ };
3345
+ const patch = config.run({
3346
+ context: snapshot.context,
3347
+ event,
3348
+ input: snapshot.input,
3349
+ system: actorScope.system,
3350
+ self: actorScope.self,
3351
+ emit: actorScope.emit
3352
+ }, enq);
3353
+ const nextSnapshot = {
3354
+ ...snapshot,
3355
+ ...(patch || {})
3356
+ };
3357
+ if ('context' in snapshot || patch?.context !== undefined) {
3358
+ nextSnapshot.context = patch?.context ?? snapshot.context;
3359
+ }
3360
+ if (patch?.effects || Object.keys(trackedEffects).length) {
3361
+ nextSnapshot.effects = {
3362
+ ...snapshot.effects,
3363
+ ...patch?.effects,
3364
+ ...trackedEffects
3365
+ };
3366
+ }
3367
+ return [nextSnapshot, effects];
3368
+ };
3369
+ const logic = {
3370
+ id: config.id,
3371
+ config,
3372
+ transition,
3373
+ start: (snapshot, actorScope) => {
3374
+ const [nextSnapshot, effects] = transition(snapshot, createInitEvent(snapshot.input), actorScope);
3375
+ Object.assign(snapshot, nextSnapshot);
3376
+ executeLogicEffects(effects, actorScope);
3377
+ },
3378
+ getInitialSnapshot: (_, input) => {
3379
+ const context = resolveContext(config.context, input);
3380
+ const snapshot = {
3381
+ status: 'active',
3382
+ output: undefined,
3383
+ error: undefined,
3384
+ input
3385
+ };
3386
+ if (context !== undefined) {
3387
+ snapshot.context = context;
3388
+ }
3389
+ return {
3390
+ ...snapshot
3391
+ };
3392
+ },
3393
+ getPersistedSnapshot: snapshot => snapshot,
3394
+ restoreSnapshot: snapshot => snapshot
3395
+ };
3396
+ return logic;
3397
+ }
3398
+
3399
+ // those are needed to make JSDoc `@link` work properly
3400
+
3401
+ let executingCustomAction = false;
3402
+ const $$ACTOR_TYPE = 1;
3403
+
3404
+ // those values are currently used by @xstate/react directly so it's important to keep the assigned values in sync
3405
+ let ProcessingStatus = /*#__PURE__*/function (ProcessingStatus) {
3406
+ ProcessingStatus[ProcessingStatus["NotStarted"] = 0] = "NotStarted";
3407
+ ProcessingStatus[ProcessingStatus["Running"] = 1] = "Running";
3408
+ ProcessingStatus[ProcessingStatus["Stopped"] = 2] = "Stopped";
3409
+ return ProcessingStatus;
3410
+ }({});
3411
+ const defaultOptions = {
3412
+ clock: {
3413
+ setTimeout: (fn, ms) => {
3414
+ return setTimeout(fn, ms);
3415
+ },
3416
+ clearTimeout: id => {
3417
+ return clearTimeout(id);
3418
+ }
3419
+ },
3420
+ logger: console.log.bind(console)
3421
+ };
3422
+
3423
+ /**
3424
+ * An Actor is a running process that can receive events, send events and change
3425
+ * its behavior based on the events it receives, which can cause effects outside
3426
+ * of the actor. When you run a state machine, it becomes an actor.
3427
+ *
3428
+ * An `Actor` is the concrete runtime instance with lifecycle methods and
3429
+ * system-owned internals. It also satisfies the narrower `ActorRef` contract,
3430
+ * so consumer APIs should accept `ActorRef` when they only need to send events
3431
+ * or read snapshots.
3432
+ */
3433
+ class Actor {
3434
+ /**
3435
+ * Creates a new actor instance for the given logic with the provided options,
3436
+ * if any.
3437
+ *
3438
+ * @param logic The logic to create an actor from
3439
+ * @param options Actor options
3440
+ */
3441
+ constructor(logic, options) {
3442
+ this.logic = logic;
3443
+ /** The current internal state of the actor. */
3444
+ this._snapshot = void 0;
3445
+ /**
3446
+ * The clock that is responsible for setting and clearing timeouts, such as
3447
+ * delayed events and transitions.
3448
+ */
3449
+ this.clock = void 0;
3450
+ this.options = void 0;
3451
+ /** The unique identifier for this actor relative to its parent. */
3452
+ this.id = void 0;
3453
+ this._boundProcess = this._process.bind(this);
3454
+ this.mailbox = new Mailbox(this._boundProcess);
3455
+ this.observers = new Set();
3456
+ this.eventListeners = new Map();
3457
+ this.logger = void 0;
3458
+ /** @internal */
3459
+ this._processingStatus = ProcessingStatus.NotStarted;
3460
+ // Actor Ref
3461
+ this._parent = void 0;
3462
+ /** @internal */
3463
+ this._syncSnapshot = void 0;
3464
+ this.ref = void 0;
3465
+ // TODO: add typings for system
3466
+ this._actorScope = void 0;
3467
+ /** @internal */
3468
+ this._lastSourceRef = void 0;
3469
+ /** @internal */
3470
+ this._collectedMicrosteps = [];
3471
+ /** @internal Actions executed during the in-flight transition. */
3472
+ this._collectedActions = [];
3473
+ /** @internal Events relayed to other actors during the in-flight transition. */
3474
+ this._collectedSent = [];
3475
+ this.systemId = void 0;
3476
+ /** The globally unique process ID for this invocation. */
3477
+ this.sessionId = void 0;
3478
+ /** The system to which this actor belongs. */
3479
+ this.system = void 0;
3480
+ this.trigger = void 0;
3481
+ this.src = void 0;
3482
+ // array of functions to defer
3483
+ this._deferred = [];
3484
+ // pending effects (timers) from a persisted snapshot, rescheduled on `start()`
3485
+ this._pendingEffects = void 0;
3486
+ const resolvedOptions = {
3487
+ ...defaultOptions,
3488
+ ...options
3489
+ };
3490
+ const {
3491
+ clock,
3492
+ logger,
3493
+ parent,
3494
+ syncSnapshot,
3495
+ id,
3496
+ systemId,
3497
+ inspect
3498
+ } = resolvedOptions;
3499
+ this.system = parent ? parent.system : createSystem(this, {
3500
+ clock,
3501
+ logger,
3502
+ timers: resolvedOptions.timers
3503
+ });
3504
+ if (inspect && !parent) {
3505
+ // Always inspect at the system-level
3506
+ this.system.inspect(toObserver(inspect));
3507
+ }
3508
+ this.sessionId = this.system._bookId();
3509
+ this.id = id ?? this.sessionId;
3510
+ this.logger = options?.logger ?? this.system._logger;
3511
+ this.clock = options?.clock ?? this.system._clock;
3512
+ this._parent = parent;
3513
+ this._syncSnapshot = syncSnapshot;
3514
+ this.options = resolvedOptions;
3515
+ this.src = resolvedOptions.src ?? logic;
3516
+ this.ref = this;
3517
+ this._actorScope = {
3518
+ self: this,
3519
+ id: this.id,
3520
+ sessionId: this.sessionId,
3521
+ logger: this.logger,
3522
+ defer: fn => {
3523
+ this._deferred.push(fn);
3524
+ },
3525
+ system: this.system,
3526
+ stopChild: child => {
3527
+ if (child._parent !== this) {
3528
+ throw new Error(`Cannot stop child actor ${child.id} of ${this.id} because it is not a child`);
3529
+ }
3530
+ child._stop();
3531
+ },
3532
+ emit: emittedEvent => {
3533
+ const listeners = this.eventListeners.get(emittedEvent.type);
3534
+ const wildcardListener = this.eventListeners.get('*');
3535
+ if (!listeners && !wildcardListener) {
3536
+ return;
3537
+ }
3538
+ if (listeners) {
3539
+ for (const handler of listeners) {
3540
+ try {
3541
+ handler(emittedEvent);
3542
+ } catch (err) {
3543
+ reportUnhandledError(err);
3544
+ }
3545
+ }
3546
+ }
3547
+ if (!wildcardListener) {
3548
+ return;
3549
+ }
3550
+ for (const handler of wildcardListener) {
3551
+ try {
3552
+ handler(emittedEvent);
3553
+ } catch (err) {
3554
+ reportUnhandledError(err);
3555
+ }
3556
+ }
3557
+ },
3558
+ actionExecutor: action => {
3559
+ const exec = () => {
3560
+ // Record every executed action for the '@xstate.transition' inspection
3561
+ // event's `actions[]` facet (replaces the v5 '@xstate.action' event).
3562
+ this._collectedActions.push({
3563
+ type: action.type,
3564
+ params: action.params
3565
+ });
3566
+ if (!action.exec) {
3567
+ return;
3568
+ }
3569
+ const saveExecutingCustomAction = executingCustomAction;
3570
+ try {
3571
+ executingCustomAction = true;
3572
+ action.exec();
3573
+ } finally {
3574
+ executingCustomAction = saveExecutingCustomAction;
3575
+ }
3576
+ };
3577
+ if (this._processingStatus === ProcessingStatus.Running) {
3578
+ exec();
3579
+ } else {
3580
+ this._deferred.push(exec);
3581
+ }
3582
+ }
3583
+ };
3584
+
3585
+ // Ensure that the send method is bound to this Actor instance
3586
+ // if destructured
3587
+ this.send = this.send.bind(this);
3588
+ this.trigger = new Proxy({}, {
3589
+ get: (_, eventType) => {
3590
+ return payload => {
3591
+ this.send({
3592
+ ...payload,
3593
+ type: eventType
3594
+ });
3595
+ };
3596
+ }
3597
+ });
3598
+
3599
+ // unified '@xstate.transition' event replaces '@xstate.actor'
3600
+
3601
+ if (systemId) {
3602
+ this.systemId = systemId;
3603
+ this.system._set(systemId, this);
3604
+ }
3605
+
3606
+ // prepare to collect initial microsteps during getInitialSnapshot
3607
+ this._collectedMicrosteps = [];
3608
+ let persistedState = options?.snapshot ?? options?.state;
3609
+ if (persistedState && typeof persistedState === 'object' && '_pendingEffects' in persistedState) {
3610
+ // Pending effects are restored by this actor on `start()`; the logic
3611
+ // only sees the rest of the persisted snapshot.
3612
+ const {
3613
+ _pendingEffects,
3614
+ ...rest
3615
+ } = persistedState;
3616
+ this._pendingEffects = _pendingEffects;
3617
+ persistedState = rest;
3618
+ }
3619
+ try {
3620
+ this._snapshot = persistedState ? this.logic.restoreSnapshot ? this.logic.restoreSnapshot(persistedState, this._actorScope) : persistedState : this.logic.getInitialSnapshot(this._actorScope, this.options?.input);
3621
+ } catch (err) {
3622
+ // if we get here then it means that we assign a value to this._snapshot that is not of the correct type
3623
+ // we can't get the true `TSnapshot & { status: 'error'; }`, it's impossible
3624
+ // so right now this is a lie of sorts
3625
+ this._snapshot = {
3626
+ status: 'error',
3627
+ output: undefined,
3628
+ error: err
3629
+ };
3630
+ // discard any functions deferred during the failed initial snapshot
3631
+ // computation so they can't run against an inconsistent actor
3632
+ this._deferred.length = 0;
3633
+ }
3634
+ if (systemId && this._snapshot.status !== 'active') {
3635
+ this.system._unregister(this);
3636
+ }
3637
+
3638
+ // Announce actor topology: emitted once for every actor (root and every
3639
+ // spawned/invoked child) so the actor graph can be drawn before any
3640
+ // transitions occur. This is the only place actor identity is announced.
3641
+ this.system._sendInspectionEvent({
3642
+ type: '@xstate.actor',
3643
+ actorRef: this,
3644
+ parentRef: this._parent,
3645
+ id: this.id,
3646
+ src: this.src,
3647
+ snapshot: this._snapshot
3648
+ });
3649
+ }
3650
+ _setErrorSnapshot(err, snapshot = this._snapshot) {
3651
+ this._snapshot = {
3652
+ ...snapshot,
3653
+ status: 'error',
3654
+ error: err
3655
+ };
3656
+ }
3657
+ _next(snapshot) {
3658
+ for (const observer of this.observers) {
3659
+ try {
3660
+ observer.next?.(snapshot);
3661
+ } catch (err) {
3662
+ reportUnhandledError(err);
3663
+ }
3664
+ }
3665
+ }
3666
+ update(snapshot, event) {
3667
+ // Update state
3668
+ this._snapshot = snapshot;
3669
+
3670
+ // Execute deferred effects
3671
+ for (let i = 0; i < this._deferred.length; i++) {
3672
+ const deferredFn = this._deferred[i];
3673
+ try {
3674
+ deferredFn();
3675
+ } catch (err) {
3676
+ // this error can only be caught when executing *initial* actions
3677
+ // it's the only time when we call actions provided by the user through those deferreds
3678
+ // when the actor is already running we always execute them synchronously while transitioning
3679
+ // no "builtin deferred" should actually throw an error since they are either safe
3680
+ // or the control flow is passed through the mailbox and errors should be caught by the `_process` used by the mailbox
3681
+ this._deferred.length = 0;
3682
+ this._setErrorSnapshot(err, snapshot);
3683
+ break;
3684
+ }
3685
+ }
3686
+ this._deferred.length = 0;
3687
+ switch (this._snapshot.status) {
3688
+ case 'active':
3689
+ this._next(snapshot);
3690
+ break;
3691
+ case 'done':
3692
+ {
3693
+ // next observers are meant to be notified about done snapshots
3694
+ // this can be seen as something that is different from how observable work
3695
+ // but with observables `complete` callback is called without any arguments
3696
+ // it's more ergonomic for XState to treat a done snapshot as a "next" value
3697
+ // and the completion event as something that is separate,
3698
+ // something that merely follows emitting that done snapshot
3699
+ this._next(snapshot);
3700
+ this._stopProcedure();
3701
+ this._complete();
3702
+ const doneEvent = createDoneActorEvent(this.id, this._snapshot.output);
3703
+ if (this._parent) {
3704
+ this.system._relay(this, this._parent, doneEvent);
3705
+ }
3706
+ break;
3707
+ }
3708
+ case 'error':
3709
+ this._error(this._snapshot.error);
3710
+ break;
3711
+ }
3712
+ this.system._sendInspectionEvent({
3713
+ type: '@xstate.transition',
3714
+ actorRef: this,
3715
+ event,
3716
+ sourceRef: this._lastSourceRef,
3717
+ targetRef: this,
3718
+ snapshot,
3719
+ microsteps: this._collectedMicrosteps,
3720
+ actions: this._collectedActions,
3721
+ sent: this._collectedSent,
3722
+ eventType: event.type
3723
+ });
3724
+ // reset facets after emission
3725
+ this._collectedMicrosteps = [];
3726
+ this._collectedActions = [];
3727
+ this._collectedSent = [];
3728
+ }
3729
+
3730
+ /**
3731
+ * Subscribe an observer to an actor’s snapshot values.
3732
+ *
3733
+ * @remarks
3734
+ * The observer will receive the actor’s snapshot value when it is emitted.
3735
+ * The observer can be:
3736
+ *
3737
+ * - A plain function that receives the latest snapshot, or
3738
+ * - An observer object whose `.next(snapshot)` method receives the latest
3739
+ * snapshot
3740
+ *
3741
+ * @example
3742
+ *
3743
+ * ```ts
3744
+ * // Observer as a plain function
3745
+ * const subscription = actor.subscribe((snapshot) => {
3746
+ * console.log(snapshot);
3747
+ * });
3748
+ * ```
3749
+ *
3750
+ * @example
3751
+ *
3752
+ * ```ts
3753
+ * // Observer as an object
3754
+ * const subscription = actor.subscribe({
3755
+ * next(snapshot) {
3756
+ * console.log(snapshot);
3757
+ * },
3758
+ * error(err) {
3759
+ * // ...
3760
+ * },
3761
+ * complete() {
3762
+ * // ...
3763
+ * }
3764
+ * });
3765
+ * ```
3766
+ *
3767
+ * The return value of `actor.subscribe(observer)` is a subscription object
3768
+ * that has an `.unsubscribe()` method. You can call
3769
+ * `subscription.unsubscribe()` to unsubscribe the observer:
3770
+ *
3771
+ * @example
3772
+ *
3773
+ * ```ts
3774
+ * const subscription = actor.subscribe((snapshot) => {
3775
+ * // ...
3776
+ * });
3777
+ *
3778
+ * // Unsubscribe the observer
3779
+ * subscription.unsubscribe();
3780
+ * ```
3781
+ *
3782
+ * When the actor is stopped, all of its observers will automatically be
3783
+ * unsubscribed.
3784
+ *
3785
+ * @param observer - Either a plain function that receives the latest
3786
+ * snapshot, or an observer object whose `.next(snapshot)` method receives
3787
+ * the latest snapshot
3788
+ */
3789
+
3790
+ subscribe(nextListenerOrObserver, errorListener, completeListener) {
3791
+ const observer = toObserver(nextListenerOrObserver, errorListener, completeListener);
3792
+ if (this._processingStatus !== ProcessingStatus.Stopped) {
3793
+ this.observers.add(observer);
3794
+ } else {
3795
+ switch (this._snapshot.status) {
3796
+ case 'done':
3797
+ try {
3798
+ observer.complete?.();
3799
+ } catch (err) {
3800
+ reportUnhandledError(err);
3801
+ }
3802
+ break;
3803
+ case 'error':
3804
+ {
3805
+ const err = this._snapshot.error;
3806
+ if (!observer.error) {
3807
+ reportUnhandledError(err);
3808
+ } else {
3809
+ try {
3810
+ observer.error(err);
3811
+ } catch (err) {
3812
+ reportUnhandledError(err);
3813
+ }
3814
+ }
3815
+ break;
3816
+ }
3817
+ }
3818
+ }
3819
+ return {
3820
+ unsubscribe: () => {
3821
+ this.observers.delete(observer);
3822
+ }
3823
+ };
3824
+ }
3825
+ on(type, handler) {
3826
+ let listeners = this.eventListeners.get(type);
3827
+ if (!listeners) {
3828
+ listeners = new Set();
3829
+ this.eventListeners.set(type, listeners);
3830
+ }
3831
+ listeners.add(handler);
3832
+ return {
3833
+ unsubscribe: () => {
3834
+ listeners.delete(handler);
3835
+ }
3836
+ };
3837
+ }
3838
+ select(selector, equalityFn = Object.is) {
3839
+ return {
3840
+ subscribe: (observerOrFn, errorListener, completeListener) => {
3841
+ const observer = toObserver(observerOrFn, errorListener, completeListener);
3842
+ let selected = selector(this.getSnapshot());
3843
+ return this.subscribe({
3844
+ next: snapshot => {
3845
+ const next = selector(snapshot);
3846
+ if (!equalityFn(selected, next)) {
3847
+ selected = next;
3848
+ observer.next?.(next);
3849
+ }
3850
+ },
3851
+ error: observer.error,
3852
+ complete: observer.complete
3853
+ });
3854
+ },
3855
+ get: () => selector(this.get())
3856
+ };
3857
+ }
3858
+
3859
+ /** Starts the Actor from the initial state */
3860
+ start() {
3861
+ if (this._processingStatus === ProcessingStatus.Running) {
3862
+ // Do not restart the service if it is already started
3863
+ return this;
3864
+ }
3865
+ if (this._syncSnapshot) {
3866
+ this.subscribe({
3867
+ next: snapshot => {
3868
+ if (snapshot.status === 'active') {
3869
+ this.system._relay(this, this._parent, {
3870
+ type: `xstate.snapshot.${this.id}`,
3871
+ snapshot
3872
+ });
3873
+ }
3874
+ },
3875
+ error: () => {}
3876
+ });
3877
+ }
3878
+ this.system._register(this.sessionId, this);
3879
+ if (this.systemId) {
3880
+ this.system._set(this.systemId, this);
3881
+ }
3882
+ this._processingStatus = ProcessingStatus.Running;
3883
+
3884
+ // TODO: this isn't correct when rehydrating
3885
+ const initEvent = createInitEvent(this.options.input);
3886
+ // remember source of init as parent for unified transition event
3887
+ this._lastSourceRef = this._parent;
3888
+ const status = this._snapshot.status;
3889
+ switch (status) {
3890
+ case 'done':
3891
+ // a state machine can be "done" upon initialization (it could reach a final state using initial microsteps)
3892
+ // we still need to complete observers, flush deferreds etc
3893
+ this.update(this._snapshot, initEvent);
3894
+ // TODO: rethink cleanup of observers, mailbox, etc
3895
+ return this;
3896
+ case 'error':
3897
+ this._error(this._snapshot.error);
3898
+ return this;
3899
+ }
3900
+ if (!this._parent) {
3901
+ this.system.start();
3902
+ }
3903
+ if (this.logic.start) {
3904
+ try {
3905
+ this.logic.start(this._snapshot, this._actorScope);
3906
+ } catch (err) {
3907
+ this._setErrorSnapshot(err);
3908
+ this._error(err);
3909
+ return this;
3910
+ }
3911
+ }
3912
+
3913
+ // TODO: this notifies all subscribers but usually this is redundant
3914
+ // there is no real change happening here
3915
+ // we need to rethink if this needs to be refactored
3916
+ this.update(this._snapshot, initEvent);
3917
+ if (this._pendingEffects) {
3918
+ const strategy = this.options.timers ?? this.system._timerStrategy ?? 'resume';
3919
+ for (const effect of this._pendingEffects) {
3920
+ // Re-execute the pending effect with its remaining delay. Only
3921
+ // self-targeted raises exist today; other effect types are ignored.
3922
+ if (effect.type === '@xstate.raise') {
3923
+ this.system.scheduler.schedule(this, this, effect.event, resolveRestoredTimerDelay(strategy, effect), effect.id);
3924
+ }
3925
+ }
3926
+ this._pendingEffects = undefined;
3927
+ }
3928
+ this.mailbox.start();
3929
+ return this;
3930
+ }
3931
+ _process(event) {
3932
+ let nextState;
3933
+ let caughtError;
3934
+ try {
3935
+ nextState = this.logic.transition(this._snapshot, event, this._actorScope);
3936
+ } catch (err) {
3937
+ // we wrap it in a box so we can rethrow it later even if falsy value gets caught here
3938
+ caughtError = {
3939
+ err
3940
+ };
3941
+ }
3942
+ if (caughtError) {
3943
+ const {
3944
+ err
3945
+ } = caughtError;
3946
+ this._setErrorSnapshot(err);
3947
+ this._error(err);
3948
+ return;
3949
+ }
3950
+ const [snapshot, effects] = Array.isArray(nextState) ? nextState : [nextState, undefined];
3951
+ this.update(snapshot, event);
3952
+ executeLogicEffects(effects, this._actorScope);
3953
+ if (event.type === XSTATE_STOP) {
3954
+ this._stopProcedure();
3955
+ this._complete();
3956
+ }
3957
+ }
3958
+
3959
+ /** @internal */
3960
+ _stop() {
3961
+ if (this._processingStatus === ProcessingStatus.Stopped) {
3962
+ return this;
3963
+ }
3964
+ this.mailbox.clear();
3965
+ if (this._processingStatus === ProcessingStatus.NotStarted) {
3966
+ this._processingStatus = ProcessingStatus.Stopped;
3967
+ return this;
3968
+ }
3969
+ this.mailbox.enqueue({
3970
+ type: XSTATE_STOP
3971
+ });
3972
+ this.system._unregister(this);
3973
+ return this;
3974
+ }
3975
+
3976
+ /** Stops the Actor and unsubscribe all listeners. */
3977
+ stop() {
3978
+ if (this._parent) {
3979
+ throw new Error('A non-root actor cannot be stopped directly.');
3980
+ }
3981
+ return this._stop();
3982
+ }
3983
+ _complete() {
3984
+ for (const observer of this.observers) {
3985
+ try {
3986
+ observer.complete?.();
3987
+ } catch (err) {
3988
+ reportUnhandledError(err);
3989
+ }
3990
+ }
3991
+ this.observers.clear();
3992
+ this.eventListeners.clear();
3993
+ }
3994
+ _error(err) {
3995
+ this._stopProcedure();
3996
+ if (!this.observers.size) {
3997
+ if (!this._parent) {
3998
+ reportUnhandledError(err);
3999
+ }
4000
+ this.eventListeners.clear();
4001
+ } else {
4002
+ let reportError = false;
4003
+ for (const observer of this.observers) {
4004
+ const errorListener = observer.error;
4005
+ reportError ||= !errorListener;
4006
+ try {
4007
+ errorListener?.(err);
4008
+ } catch (err2) {
4009
+ reportUnhandledError(err2);
4010
+ }
4011
+ }
4012
+ this.observers.clear();
4013
+ this.eventListeners.clear();
4014
+ if (reportError) {
4015
+ reportUnhandledError(err);
4016
+ }
4017
+ }
4018
+ if (this._parent) {
4019
+ this.system._relay(this, this._parent, createErrorActorEvent(this.id, err));
4020
+ }
4021
+ }
4022
+ // TODO: atm children don't belong entirely to the actor so
4023
+ // in a way - it's not even super aware of them
4024
+ // so we can't stop them from here but we really should!
4025
+ // right now, they are being stopped within the machine's transition
4026
+ // but that could throw and leave us with "orphaned" active actors
4027
+ _stopProcedure() {
4028
+ if (this._processingStatus !== ProcessingStatus.Running) {
4029
+ // Actor already stopped; do nothing
4030
+ return;
4031
+ }
4032
+
4033
+ // Cancel all delayed events
4034
+ this.system.scheduler.cancelAll(this);
4035
+
4036
+ // TODO: mailbox.reset
4037
+ this.mailbox.clear();
4038
+ // TODO: after `stop` we must prepare ourselves for receiving events again
4039
+ // events sent *after* stop signal must be queued
4040
+ // it seems like this should be the common behavior for all of our consumers
4041
+ // so perhaps this should be unified somehow for all of them
4042
+ this.mailbox = new Mailbox(this._boundProcess);
4043
+ this._processingStatus = ProcessingStatus.Stopped;
4044
+ this.system._unregister(this);
4045
+ }
4046
+
4047
+ /** @internal */
4048
+ _send(event) {
4049
+ if (this._processingStatus === ProcessingStatus.Stopped) {
4050
+ // do nothing
4051
+ {
4052
+ // TODO: circular serialization issues
4053
+ // const eventString = ''; //JSON.stringify(event);
4054
+
4055
+ console.warn(`Event "${event.type}" was sent to stopped actor "${this.id} (${this.sessionId})". This actor has already reached its final state, and will not transition.`);
4056
+ }
4057
+ return;
4058
+ }
4059
+ this.mailbox.enqueue(event);
4060
+ }
4061
+
4062
+ /**
4063
+ * Sends an event to the running Actor to trigger a transition.
4064
+ *
4065
+ * @param event The event to send
4066
+ */
4067
+ send(event) {
4068
+ if (typeof event === 'string') {
4069
+ throw new Error(`Only event objects may be sent to actors; use .send({ type: "${event}" }) instead`);
4070
+ }
4071
+ this.system._relay(undefined, this, event);
4072
+ }
4073
+ toJSON() {
4074
+ return {
4075
+ xstate$$type: $$ACTOR_TYPE,
4076
+ id: this.id
4077
+ };
4078
+ }
4079
+
4080
+ /**
4081
+ * Obtain the internal state of the actor, which can be persisted.
4082
+ *
4083
+ * @remarks
4084
+ * The internal state can be persisted from any actor, not only machines.
4085
+ *
4086
+ * Note that the persisted state is not the same as the snapshot from
4087
+ * {@link Actor.getSnapshot}. Persisted state represents the internal state of
4088
+ * the actor, while snapshots represent the actor's last emitted value.
4089
+ *
4090
+ * Can be restored with {@link ActorOptions.state}
4091
+ * @see https://stately.ai/docs/persistence
4092
+ */
4093
+
4094
+ getPersistedSnapshot(options) {
4095
+ const persisted = this.logic.getPersistedSnapshot(this._snapshot, options);
4096
+
4097
+ // Capture this actor's pending self-targeted effects (delayed
4098
+ // events/transitions) as serialized action descriptors plus their
4099
+ // runtime progress, so they can be restored on `start()`.
4100
+ const scheduledEvents = this.system._snapshot._scheduledEvents;
4101
+ let pendingEffects;
4102
+ const now = Date.now();
4103
+ for (const key in scheduledEvents) {
4104
+ const scheduled = scheduledEvents[key];
4105
+ if (scheduled.source === this && scheduled.target === this) {
4106
+ (pendingEffects ??= []).push({
4107
+ type: '@xstate.raise',
4108
+ event: scheduled.event,
4109
+ id: scheduled.id,
4110
+ delay: scheduled.delay,
4111
+ startedAt: scheduled.startedAt,
4112
+ elapsed: Math.max(0, now - scheduled.startedAt)
4113
+ });
4114
+ }
4115
+ }
4116
+
4117
+ // If this actor was restored but not yet started, its pending effects
4118
+ // are not in the scheduler yet — carry them through as-is.
4119
+ pendingEffects ??= this._pendingEffects;
4120
+ return pendingEffects ? {
4121
+ ...persisted,
4122
+ _pendingEffects: pendingEffects
4123
+ } : persisted;
4124
+ }
4125
+ [symbolObservable]() {
4126
+ return this;
4127
+ }
4128
+
4129
+ /**
4130
+ * Read an actor’s snapshot synchronously.
4131
+ *
4132
+ * @remarks
4133
+ * The snapshot represent an actor's last emitted value.
4134
+ *
4135
+ * When an actor receives an event, its internal state may change. An actor
4136
+ * may emit a snapshot when a state transition occurs.
4137
+ *
4138
+ * Note that some actors, such as callback actors generated with
4139
+ * `createCallbackLogic`, will not emit snapshots.
4140
+ * @see {@link Actor.subscribe} to subscribe to an actor’s snapshot values.
4141
+ * @see {@link Actor.getPersistedSnapshot} to persist the internal state of an actor (which is more than just a snapshot).
4142
+ */
4143
+ getSnapshot() {
4144
+ return this.get();
4145
+ }
4146
+
4147
+ /** Read the actor's current snapshot as an atom value. */
4148
+ get() {
4149
+ if (!this._snapshot) {
4150
+ throw new Error(`Snapshot can't be read while the actor initializes itself`);
4151
+ }
4152
+ onActorRead?.(this);
4153
+ return this._snapshot;
4154
+ }
4155
+ }
4156
+ function resolveRestoredTimerDelay(strategy, effect) {
4157
+ if (typeof strategy === 'function') {
4158
+ return strategy(effect);
4159
+ }
4160
+ switch (strategy) {
4161
+ case 'restart':
4162
+ return effect.delay;
4163
+ case 'absolute':
4164
+ return Math.max(0, effect.startedAt + effect.delay - Date.now());
4165
+ case 'resume':
4166
+ default:
4167
+ return Math.max(0, effect.delay - effect.elapsed);
4168
+ }
4169
+ }
4170
+ /**
4171
+ * Creates a new actor instance for the given actor logic with the provided
4172
+ * options, if any.
4173
+ *
4174
+ * @remarks
4175
+ * When you create an actor from actor logic via `createActor(logic)`, you
4176
+ * implicitly create an actor system where the created actor is the root actor.
4177
+ * Any actors spawned from this root actor and its descendants are part of that
4178
+ * actor system.
4179
+ * @example
4180
+ *
4181
+ * ```ts
4182
+ * import { createActor } from 'xstate';
4183
+ * import { someActorLogic } from './someActorLogic.ts';
4184
+ *
4185
+ * // Creating the actor, which implicitly creates an actor system with itself as the root actor
4186
+ * const actor = createActor(someActorLogic);
4187
+ *
4188
+ * actor.subscribe((snapshot) => {
4189
+ * console.log(snapshot);
4190
+ * });
4191
+ *
4192
+ * // Actors must be started by calling `actor.start()`, which will also start the actor system.
4193
+ * actor.start();
4194
+ *
4195
+ * // Actors can receive events
4196
+ * actor.send({ type: 'someEvent' });
4197
+ *
4198
+ * // You can stop root actors by calling `actor.stop()`, which will also stop the actor system and all actors in that system.
4199
+ * actor.stop();
4200
+ * ```
4201
+ *
4202
+ * @param logic - The actor logic to create an actor from. For a state machine
4203
+ * actor logic creator, see {@link createMachine}. Other actor logic creators
4204
+ * include {@link createCallbackLogic}, {@link createEventObservableLogic},
4205
+ * {@link createObservableLogic}, {@link createLogic}, and
4206
+ * {@link createAsyncLogic}.
4207
+ * @param options - Actor options
4208
+ */
4209
+ function createActor(logic, options) {
4210
+ return new Actor(logic, options);
4211
+ }
4212
+
4213
+ const instanceStates = /* #__PURE__ */new WeakMap();
4214
+
4215
+ /**
4216
+ * Represents an actor created by `createCallbackLogic`.
4217
+ *
4218
+ * The type of `self` within the actor's logic.
4219
+ *
4220
+ * @example
4221
+ *
4222
+ * ```ts
4223
+ * import { createCallbackLogic, createActor } from 'xstate';
4224
+ *
4225
+ * // The events the actor receives.
4226
+ * type Event = { type: 'someEvent' };
4227
+ * // The actor's input.
4228
+ * type Input = { name: string };
4229
+ *
4230
+ * // Actor logic that logs whenever it receives an event of type `someEvent`.
4231
+ * const logic = createCallbackLogic<Event, Input>(
4232
+ * ({ self, input, receive }) => {
4233
+ * self;
4234
+ * // ^? CallbackActorRef<Event, Input>
4235
+ *
4236
+ * receive((event) => {
4237
+ * if (event.type === 'someEvent') {
4238
+ * console.log(`${input.name}: received "someEvent" event`);
4239
+ * // logs 'myActor: received "someEvent" event'
4240
+ * }
4241
+ * });
4242
+ * }
4243
+ * );
4244
+ *
4245
+ * const actor = createActor(logic, { input: { name: 'myActor' } });
4246
+ * // ^? CallbackActorRef<Event, Input>
4247
+ * ```
4248
+ *
4249
+ * @see {@link createCallbackLogic}
4250
+ */
4251
+
4252
+ /**
4253
+ * An actor logic creator which returns callback logic as defined by a callback
4254
+ * function.
4255
+ *
4256
+ * @remarks
4257
+ * Useful for subscription-based or other free-form logic that can send events
4258
+ * back to the parent actor.
4259
+ *
4260
+ * Actors created from callback logic (“callback actors”) can:
4261
+ *
4262
+ * - Receive events via the `receive` function
4263
+ * - Send events to the parent actor via the `sendBack` function
4264
+ *
4265
+ * Callback actors are a bit different from other actors in that they:
4266
+ *
4267
+ * - Do not work with `onDone`
4268
+ * - Do not produce a snapshot using `.getSnapshot()`
4269
+ * - Do not emit values when used with `.subscribe()`
4270
+ * - Can not be stopped with `.stop()`
4271
+ *
4272
+ * @example
4273
+ *
4274
+ * ```typescript
4275
+ * const callbackLogic = createCallbackLogic(({ sendBack, receive }) => {
4276
+ * let lockStatus = 'unlocked';
4277
+ *
4278
+ * const handler = (event) => {
4279
+ * if (lockStatus === 'locked') {
4280
+ * return;
4281
+ * }
4282
+ * sendBack(event);
4283
+ * };
4284
+ *
4285
+ * receive((event) => {
4286
+ * if (event.type === 'lock') {
4287
+ * lockStatus = 'locked';
4288
+ * } else if (event.type === 'unlock') {
4289
+ * lockStatus = 'unlocked';
4290
+ * }
4291
+ * });
4292
+ *
4293
+ * document.body.addEventListener('click', handler);
4294
+ *
4295
+ * return () => {
4296
+ * document.body.removeEventListener('click', handler);
4297
+ * };
4298
+ * });
4299
+ * ```
4300
+ *
4301
+ * @param callback - The callback function used to describe the callback logic
4302
+ * The callback function is passed an object with the following properties:
4303
+ *
4304
+ * - `receive` - A function that can send events back to the parent actor; the
4305
+ * listener is then called whenever events are received by the callback
4306
+ * actor
4307
+ * - `sendBack` - A function that can send events back to the parent actor
4308
+ * - `input` - Data that was provided to the callback actor
4309
+ * - `self` - The parent actor of the callback actor
4310
+ * - `system` - The actor system to which the callback actor belongs The callback
4311
+ * function can (optionally) return a cleanup function, which is called
4312
+ * when the actor is stopped.
4313
+ *
4314
+ * @returns Callback logic
4315
+ * @see {@link CallbackLogicFunction} for more information about the callback function and its object argument
4316
+ * @see {@link https://stately.ai/docs/input | Input docs} for more information about how input is passed
4317
+ */
4318
+
4319
+ function createCallbackLogic(callbackOrConfig) {
4320
+ const callback = typeof callbackOrConfig === 'function' ? callbackOrConfig : callbackOrConfig.run;
4321
+ const schemas = typeof callbackOrConfig === 'function' ? undefined : callbackOrConfig.schemas;
4322
+ return createLogic({
4323
+ schemas,
4324
+ context: undefined,
4325
+ run: (args, enq) => {
4326
+ const {
4327
+ event,
4328
+ input,
4329
+ self,
4330
+ system
4331
+ } = args;
4332
+ const emit = args.emit;
4333
+ const callbackState = instanceStates.get(self);
4334
+ callbackState?.receivers?.forEach(receiver => receiver(event));
4335
+ enq.effect('callback', () => {
4336
+ const callbackState = {
4337
+ receivers: undefined,
4338
+ dispose: undefined
4339
+ };
4340
+ instanceStates.set(self, callbackState);
4341
+ callbackState.dispose = callback({
4342
+ input,
4343
+ system,
4344
+ self: self,
4345
+ sendBack: event => {
4346
+ if (self.getSnapshot().status === 'stopped') {
4347
+ return;
4348
+ }
4349
+ const parent = self._parent;
4350
+ if (parent) {
4351
+ system._relay(self, parent, event);
4352
+ }
4353
+ },
4354
+ receive: listener => {
4355
+ callbackState.receivers ??= new Set();
4356
+ callbackState.receivers.add(listener);
4357
+ },
4358
+ emit: emit
4359
+ });
4360
+ return () => {
4361
+ instanceStates.delete(self);
4362
+ callbackState.receivers?.clear();
4363
+ callbackState.dispose?.();
4364
+ };
4365
+ });
4366
+ }
4367
+ });
4368
+ }
4369
+
4370
+ const XSTATE_OBSERVABLE_NEXT = 'xstate.observable.next';
4371
+ const XSTATE_OBSERVABLE_ERROR = 'xstate.observable.error';
4372
+ const XSTATE_OBSERVABLE_COMPLETE = 'xstate.observable.complete';
4373
+
4374
+ /**
4375
+ * Represents an actor created by `createObservableLogic` or
4376
+ * `createEventObservableLogic`.
4377
+ *
4378
+ * The type of `self` within the actor's logic.
4379
+ *
4380
+ * @example
4381
+ *
4382
+ * ```ts
4383
+ * import { createObservableLogic, createActor } from 'xstate';
4384
+ * import { interval } from 'rxjs';
4385
+ *
4386
+ * // The type of the value observed by the actor's logic.
4387
+ * type Context = number;
4388
+ * // The actor's input.
4389
+ * type Input = { period?: number };
4390
+ *
4391
+ * // Actor logic that observes a number incremented every `input.period`
4392
+ * // milliseconds (default: 1_000).
4393
+ * const logic = createObservableLogic<Context, Input>(
4394
+ * ({ input, self }) => {
4395
+ * self;
4396
+ * // ^? ObservableActor<Event, Input>
4397
+ *
4398
+ * return interval(input.period ?? 1_000);
4399
+ * }
4400
+ * );
4401
+ *
4402
+ * const actor = createActor(logic, { input: { period: 2_000 } });
4403
+ * // ^? ObservableActor<Event, Input>
4404
+ * ```
4405
+ *
4406
+ * @see {@link createObservableLogic}
4407
+ * @see {@link createEventObservableLogic}
4408
+ */
4409
+
4410
+ /**
4411
+ * Observable actor logic is described by an observable stream of values. Actors
4412
+ * created from observable logic (“observable actors”) can:
4413
+ *
4414
+ * - Emit snapshots of the observable’s emitted value
4415
+ *
4416
+ * The observable’s emitted value is used as its observable actor’s `context`.
4417
+ *
4418
+ * Sending events to observable actors will have no effect.
4419
+ *
4420
+ * @example
4421
+ *
4422
+ * ```ts
4423
+ * import { createObservableLogic, createActor } from 'xstate';
4424
+ * import { interval } from 'rxjs';
4425
+ *
4426
+ * const logic = createObservableLogic((obj) => interval(1000));
4427
+ *
4428
+ * const actor = createActor(logic);
4429
+ *
4430
+ * actor.subscribe((snapshot) => {
4431
+ * console.log(snapshot.context);
4432
+ * });
4433
+ *
4434
+ * actor.start();
4435
+ * // At every second:
4436
+ * // Logs 0
4437
+ * // Logs 1
4438
+ * // Logs 2
4439
+ * // ...
4440
+ * ```
4441
+ *
4442
+ * @param observableCreator A function that creates an observable. It receives
4443
+ * one argument, an object with the following properties:
4444
+ *
4445
+ * - `input` - Data that was provided to the observable actor
4446
+ * - `self` - The parent actor
4447
+ * - `system` - The actor system to which the observable actor belongs
4448
+ *
4449
+ * It should return a {@link Subscribable}, which is compatible with an RxJS
4450
+ * Observable, although RxJS is not required to create them.
4451
+ * @see {@link https://rxjs.dev} for documentation on RxJS Observable and observable creators.
4452
+ * @see {@link Subscribable} interface in XState, which is based on and compatible with RxJS Observable.
4453
+ */
4454
+
4455
+ function createObservableLogic(observableCreatorOrConfig) {
4456
+ const observableCreator = typeof observableCreatorOrConfig === 'function' ? observableCreatorOrConfig : observableCreatorOrConfig.run;
4457
+ const schemas = typeof observableCreatorOrConfig === 'function' ? undefined : observableCreatorOrConfig.schemas;
4458
+ return createLogic({
4459
+ schemas,
4460
+ context: undefined,
4461
+ run: (args, enq) => {
4462
+ const {
4463
+ event,
4464
+ input,
4465
+ self,
4466
+ system
4467
+ } = args;
4468
+ const emit = args.emit;
4469
+ switch (event.type) {
4470
+ case XSTATE_OBSERVABLE_NEXT:
4471
+ {
4472
+ return {
4473
+ context: event.data
4474
+ };
4475
+ }
4476
+ case XSTATE_OBSERVABLE_ERROR:
4477
+ return {
4478
+ status: 'error',
4479
+ error: event.data,
4480
+ input: undefined,
4481
+ effects: {
4482
+ observable: {
4483
+ status: 'error',
4484
+ error: event.data
4485
+ }
4486
+ }
4487
+ };
4488
+ case XSTATE_OBSERVABLE_COMPLETE:
4489
+ return {
4490
+ status: 'done',
4491
+ input: undefined,
4492
+ effects: {
4493
+ observable: {
4494
+ status: 'done'
4495
+ }
4496
+ }
4497
+ };
4498
+ }
4499
+ enq.effect('observable', () => {
4500
+ const actorSelf = self;
4501
+ const subscription = observableCreator({
4502
+ input,
4503
+ system,
4504
+ self: self,
4505
+ emit: emit
4506
+ }).subscribe({
4507
+ next: value => {
4508
+ system._relay(actorSelf, actorSelf, {
4509
+ type: XSTATE_OBSERVABLE_NEXT,
4510
+ data: value
4511
+ });
4512
+ },
4513
+ error: err => {
4514
+ system._relay(actorSelf, actorSelf, {
4515
+ type: XSTATE_OBSERVABLE_ERROR,
4516
+ data: err
4517
+ });
4518
+ },
4519
+ complete: () => {
4520
+ system._relay(actorSelf, actorSelf, {
4521
+ type: XSTATE_OBSERVABLE_COMPLETE
4522
+ });
4523
+ }
4524
+ });
4525
+ return () => subscription.unsubscribe();
4526
+ });
4527
+ }
4528
+ });
4529
+ }
4530
+
4531
+ /**
4532
+ * Creates event observable logic that listens to an observable that delivers
4533
+ * event objects.
4534
+ *
4535
+ * Event observable actor logic is described by an observable stream of
4536
+ * {@link https://stately.ai/docs/transitions#event-objects | event objects}.
4537
+ * Actors created from event observable logic (“event observable actors”) can:
4538
+ *
4539
+ * - Implicitly send events to its parent actor
4540
+ * - Emit snapshots of its emitted event objects
4541
+ *
4542
+ * Sending events to event observable actors will have no effect.
4543
+ *
4544
+ * @example
4545
+ *
4546
+ * ```ts
4547
+ * import {
4548
+ * createEventObservableLogic,
4549
+ * Subscribable,
4550
+ * EventObject,
4551
+ * createMachine,
4552
+ * createActor
4553
+ * } from 'xstate';
4554
+ * import { fromEvent } from 'rxjs';
4555
+ *
4556
+ * const mouseClickLogic = createEventObservableLogic(
4557
+ * () => fromEvent(document.body, 'click') as Subscribable<EventObject>
4558
+ * );
4559
+ *
4560
+ * const canvasMachine = createMachine({
4561
+ * invoke: {
4562
+ * // Will send mouse `click` events to the canvas actor
4563
+ * src: mouseClickLogic
4564
+ * }
4565
+ * });
4566
+ *
4567
+ * const canvasActor = createActor(canvasMachine);
4568
+ * canvasActor.start();
4569
+ * ```
4570
+ *
4571
+ * @param lazyObservable A function that creates an observable that delivers
4572
+ * event objects. It receives one argument, an object with the following
4573
+ * properties:
4574
+ *
4575
+ * - `input` - Data that was provided to the event observable actor
4576
+ * - `self` - The parent actor
4577
+ * - `system` - The actor system to which the event observable actor belongs.
4578
+ *
4579
+ * It should return a {@link Subscribable}, which is compatible with an RxJS
4580
+ * Observable, although RxJS is not required to create them.
4581
+ */
4582
+
4583
+ function createEventObservableLogic(lazyObservableOrConfig) {
4584
+ const lazyObservable = typeof lazyObservableOrConfig === 'function' ? lazyObservableOrConfig : lazyObservableOrConfig.run;
4585
+
4586
+ // TODO: event types
4587
+ const logic = {
4588
+ config: lazyObservable,
4589
+ transition: (state, event) => {
4590
+ if (state.status !== 'active') {
4591
+ return state;
4592
+ }
4593
+ switch (event.type) {
4594
+ case XSTATE_OBSERVABLE_ERROR:
4595
+ return {
4596
+ ...state,
4597
+ status: 'error',
4598
+ error: event.data,
4599
+ input: undefined,
4600
+ _subscription: undefined
4601
+ };
4602
+ case XSTATE_OBSERVABLE_COMPLETE:
4603
+ return {
4604
+ ...state,
4605
+ status: 'done',
4606
+ input: undefined,
4607
+ _subscription: undefined
4608
+ };
4609
+ case XSTATE_STOP:
4610
+ state._subscription.unsubscribe();
4611
+ return {
4612
+ ...state,
4613
+ status: 'stopped',
4614
+ input: undefined,
4615
+ _subscription: undefined
4616
+ };
4617
+ default:
4618
+ return state;
4619
+ }
4620
+ },
4621
+ getInitialSnapshot: (_, input) => {
4622
+ return {
4623
+ status: 'active',
4624
+ output: undefined,
4625
+ error: undefined,
4626
+ context: undefined,
4627
+ input,
4628
+ _subscription: undefined
4629
+ };
4630
+ },
4631
+ start: (state, {
4632
+ self,
4633
+ system,
4634
+ emit
4635
+ }) => {
4636
+ if (state.status === 'done') {
4637
+ // Do not restart a completed observable
4638
+ return;
4639
+ }
4640
+ state._subscription = lazyObservable({
4641
+ input: state.input,
4642
+ system,
4643
+ self,
4644
+ emit
4645
+ }).subscribe({
4646
+ next: value => {
4647
+ if (self._parent) {
4648
+ system._relay(self, self._parent, value);
4649
+ }
4650
+ },
4651
+ error: err => {
4652
+ system._relay(self, self, {
4653
+ type: XSTATE_OBSERVABLE_ERROR,
4654
+ data: err
4655
+ });
4656
+ },
4657
+ complete: () => {
4658
+ system._relay(self, self, {
4659
+ type: XSTATE_OBSERVABLE_COMPLETE
4660
+ });
4661
+ }
4662
+ });
4663
+ },
4664
+ getPersistedSnapshot: ({
4665
+ _subscription,
4666
+ ...snapshot
4667
+ }) => snapshot,
4668
+ restoreSnapshot: snapshot => ({
4669
+ ...snapshot,
4670
+ _subscription: undefined
4671
+ })
4672
+ };
4673
+ return logic;
4674
+ }
4675
+
4676
+ const XSTATE_ASYNC_RESOLVE = 'xstate.async.resolve';
4677
+ const XSTATE_ASYNC_REJECT = 'xstate.async.reject';
4678
+ class TimeoutError extends Error {
4679
+ constructor(timeout) {
4680
+ super(`Async logic timed out after ${timeout}.`);
4681
+ this.name = 'TimeoutError';
4682
+ }
4683
+ }
4684
+
4685
+ /**
4686
+ * Represents an actor created by `createAsyncLogic`.
4687
+ *
4688
+ * The type of `self` within the actor's logic.
4689
+ *
4690
+ * @example
4691
+ *
4692
+ * ```ts
4693
+ * import { createAsyncLogic, createActor } from 'xstate';
4694
+ *
4695
+ * // The actor's resolved output
4696
+ * type Output = string;
4697
+ * // The actor's input.
4698
+ * type Input = { message: string };
4699
+ *
4700
+ * // Actor logic that fetches the url of an image of a cat saying `input.message`.
4701
+ * const logic = createAsyncLogic<Output, Input>({
4702
+ * run: async ({ input, self }, enq) => {
4703
+ * self;
4704
+ * // ^? AsyncActor<Output, Input>
4705
+ * enq.emit({ type: 'request.start' });
4706
+ *
4707
+ * const data = await fetch(
4708
+ * `https://cataas.com/cat/says/${input.message}`
4709
+ * );
4710
+ * const url = await data.json();
4711
+ * return url;
4712
+ * }
4713
+ * });
4714
+ *
4715
+ * const actor = createActor(logic, { input: { message: 'hello world' } });
4716
+ * // ^? AsyncActor<Output, Input>
4717
+ * ```
4718
+ *
4719
+ * @see {@link createAsyncLogic}
4720
+ */
4721
+
4722
+ /**
4723
+ * An actor logic creator which returns async logic as defined by an async
4724
+ * process that resolves or rejects after some time.
4725
+ *
4726
+ * Actors created from async actor logic can:
4727
+ *
4728
+ * - Output the resolved value of the async process
4729
+ * - Error with the rejected value of the async process
4730
+ * - Abort when stopped or timed out
4731
+ *
4732
+ * Sending events to async actors will have no effect.
4733
+ *
4734
+ * @example
4735
+ *
4736
+ * ```ts
4737
+ * const asyncLogic = createAsyncLogic({
4738
+ * id: 'fetch-user',
4739
+ * timeout: '30s',
4740
+ * run: async ({ signal }, enq) => {
4741
+ * enq.emit({ type: 'request.start' });
4742
+ * const result = await fetch('https://example.com/...', {
4743
+ * signal
4744
+ * }).then((data) => data.json());
4745
+ *
4746
+ * return result;
4747
+ * }
4748
+ * });
4749
+ *
4750
+ * const asyncActor = createActor(asyncLogic);
4751
+ * asyncActor.subscribe((snapshot) => {
4752
+ * console.log(snapshot);
4753
+ * });
4754
+ * asyncActor.start();
4755
+ * // => {
4756
+ * // output: undefined,
4757
+ * // status: 'active'
4758
+ * // ...
4759
+ * // }
4760
+ *
4761
+ * // After promise resolves
4762
+ * // => {
4763
+ * // output: { ... },
4764
+ * // status: 'done',
4765
+ * // ...
4766
+ * // }
4767
+ * ```
4768
+ *
4769
+ * @param asyncLogic A config object with a `run` function which returns a
4770
+ * Promise, and accepts an object with the following properties:
4771
+ *
4772
+ * - `input` - Data that was provided to the async actor
4773
+ * - `self` - The async actor ref
4774
+ * - `system` - The actor system to which the async actor belongs
4775
+ * - `signal` - An abort signal for cancellation
4776
+ *
4777
+ * `run` also receives an `enq` object with the following properties:
4778
+ *
4779
+ * - `emit` - Emits an event that can be observed with `actor.on(...)`
4780
+ *
4781
+ * @see {@link https://stately.ai/docs/input | Input docs} for more information about how input is passed
4782
+ */
4783
+
4784
+ function createAsyncLogic(asyncLogic) {
4785
+ const config = asyncLogic;
4786
+ function waitForEffect(self, key) {
4787
+ return new Promise((resolve, reject) => {
4788
+ const subscription = self.subscribe(snapshot => {
4789
+ const effect = snapshot.effects?.[key];
4790
+ if (effect?.status === 'done') {
4791
+ subscription.unsubscribe();
4792
+ resolve(effect.output);
4793
+ } else if (effect?.status === 'error') {
4794
+ subscription.unsubscribe();
4795
+ reject(effect.error);
4796
+ }
4797
+ });
4798
+ });
4799
+ }
4800
+ return createLogic({
4801
+ id: config.id,
4802
+ schemas: config.schemas,
4803
+ context: undefined,
4804
+ run: ({
4805
+ event,
4806
+ input,
4807
+ self,
4808
+ system
4809
+ }, enq) => {
4810
+ switch (event.type) {
4811
+ case XSTATE_ASYNC_RESOLVE:
4812
+ {
4813
+ const resolvedValue = event.data ?? event.output;
4814
+ return {
4815
+ status: 'done',
4816
+ output: resolvedValue,
4817
+ input: undefined,
4818
+ effects: {
4819
+ async: {
4820
+ status: 'done',
4821
+ output: resolvedValue
4822
+ }
4823
+ }
4824
+ };
4825
+ }
4826
+ case XSTATE_ASYNC_REJECT:
4827
+ {
4828
+ const error = event.data ?? event.error;
4829
+ return {
4830
+ status: 'error',
4831
+ error,
4832
+ input: undefined,
4833
+ effects: {
4834
+ async: {
4835
+ status: 'error',
4836
+ error
4837
+ }
4838
+ }
4839
+ };
4840
+ }
4841
+ }
4842
+ if (event.type !== XSTATE_INIT) {
4843
+ return;
4844
+ }
4845
+ enq.effect(() => {
4846
+ const actorSelf = self;
4847
+ const controller = new AbortController();
4848
+ const timeout = config.timeout;
4849
+ const timeoutMs = parseDelayToMilliseconds(timeout);
4850
+ const timeoutId = timeoutMs === undefined ? undefined : system._clock.setTimeout(() => {
4851
+ if (self.getSnapshot().status !== 'active') {
4852
+ return;
4853
+ }
4854
+ controller.abort();
4855
+ system._relay(actorSelf, actorSelf, {
4856
+ type: XSTATE_ASYNC_REJECT,
4857
+ data: new TimeoutError(timeout)
4858
+ });
4859
+ }, timeoutMs);
4860
+ const clearTimeout = () => {
4861
+ if (timeoutId !== undefined) {
4862
+ system._clock.clearTimeout(timeoutId);
4863
+ }
4864
+ };
4865
+ const resolvedPromise = Promise.resolve(config.run({
4866
+ input,
4867
+ system,
4868
+ self: self,
4869
+ signal: controller.signal
4870
+ }, {
4871
+ emit: enq.emit,
4872
+ step: async (key, exec) => {
4873
+ const effect = self.getSnapshot().effects?.[key];
4874
+ if (effect?.status === 'done') {
4875
+ return effect.output;
4876
+ }
4877
+ if (effect?.status === 'error') {
4878
+ throw effect.error;
4879
+ }
4880
+ if (effect?.status === 'active') {
4881
+ return waitForEffect(self, key);
4882
+ }
4883
+ system._relay(actorSelf, actorSelf, {
4884
+ type: XSTATE_LOGIC_EFFECT_START,
4885
+ key
4886
+ });
4887
+ try {
4888
+ const output = await exec();
4889
+ system._relay(actorSelf, actorSelf, {
4890
+ type: XSTATE_LOGIC_EFFECT_RESOLVE,
4891
+ key,
4892
+ output
4893
+ });
4894
+ return output;
4895
+ } catch (error) {
4896
+ system._relay(actorSelf, actorSelf, {
4897
+ type: XSTATE_LOGIC_EFFECT_REJECT,
4898
+ key,
4899
+ error
4900
+ });
4901
+ throw error;
4902
+ }
4903
+ }
4904
+ }));
4905
+ resolvedPromise.then(response => {
4906
+ clearTimeout();
4907
+ if (self.getSnapshot().status !== 'active') {
4908
+ return;
4909
+ }
4910
+ system._relay(actorSelf, actorSelf, {
4911
+ type: XSTATE_ASYNC_RESOLVE,
4912
+ data: response
4913
+ });
4914
+ }, errorData => {
4915
+ clearTimeout();
4916
+ if (self.getSnapshot().status !== 'active') {
4917
+ return;
4918
+ }
4919
+ system._relay(actorSelf, actorSelf, {
4920
+ type: XSTATE_ASYNC_REJECT,
4921
+ data: errorData
4922
+ });
4923
+ });
4924
+ return () => {
4925
+ controller.abort();
4926
+ clearTimeout();
4927
+ };
4928
+ });
4929
+ return {
4930
+ effects: {
4931
+ async: {
4932
+ status: 'active'
4933
+ }
4934
+ }
4935
+ };
4936
+ }
4937
+ });
4938
+ }
4939
+
4940
+ const emptyLogic = /* #__PURE__ */createLogic({
4941
+ context: undefined,
4942
+ run: () => undefined
4943
+ });
4944
+ function createEmptyActor() {
4945
+ return createActor(emptyLogic);
4946
+ }
4947
+
4948
+ export { isStateId as $, Actor as A, createAsyncLogic as B, createListenerLogic as C, listenerLogic as D, createSubscriptionLogic as E, subscriptionLogic as F, resolveReferencedActor as G, mapValues as H, createInvokeId as I, getDelayedTransitions as J, evaluateCandidate as K, formatTransition as L, toTransitionConfigArray as M, NULL_EVENT as N, createInvokeTimeoutEvent as O, ProcessingStatus as P, getCandidates as Q, formatRouteTransitions as R, STATE_DELIMITER as S, TimeoutError as T, resolveStateValue as U, getAllStateNodes as V, createMachineSnapshot as W, isInFinalState as X, transitionNode as Y, resolveAndExecuteActionsWithContext as Z, toStatePath as _, macrostep as a, getStateNodeByPath as a0, getPersistedSnapshot as a1, $$ACTOR_TYPE as a2, XSTATE_INIT as a3, createInitEvent as b, createActor as c, initialMicrostep as d, createAtom as e, createAtomConfig as f, getProperAncestors as g, createAsyncAtom as h, isAtomicStateNode as i, createReducerAtom as j, isAtom as k, isMachineSnapshot as l, matchesEventDescriptor as m, getStateNodes as n, getAllOwnEventDescriptors as o, parseDelayToMilliseconds as p, matchesState as q, checkStateIn as r, pathToStateValue as s, toArray as t, toObserver as u, createEmptyActor as v, createCallbackLogic as w, createObservableLogic as x, createEventObservableLogic as y, createLogic as z };