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