xstate 5.32.2 → 6.0.0-alpha.10

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