xstate 5.32.0 → 6.0.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/README.md +7 -8
  2. package/dist/StateMachine-47e60715.esm.js +720 -0
  3. package/dist/StateMachine-48dcad8f.cjs.js +723 -0
  4. package/dist/StateMachine-6e063ac1.development.cjs.js +740 -0
  5. package/dist/StateMachine-6ec50e21.development.esm.js +737 -0
  6. package/dist/declarations/src/State.d.ts +11 -13
  7. package/dist/declarations/src/StateMachine.d.ts +27 -21
  8. package/dist/declarations/src/StateNode.d.ts +18 -54
  9. package/dist/declarations/src/actions.d.ts +14 -9
  10. package/dist/declarations/src/actors/callback.d.ts +42 -16
  11. package/dist/declarations/src/actors/index.d.ts +9 -6
  12. package/dist/declarations/src/actors/listener.d.ts +18 -0
  13. package/dist/declarations/src/actors/logic.d.ts +105 -0
  14. package/dist/declarations/src/actors/observable.d.ts +72 -27
  15. package/dist/declarations/src/actors/promise.d.ts +133 -48
  16. package/dist/declarations/src/actors/subscription.d.ts +22 -0
  17. package/dist/declarations/src/atom.d.ts +81 -0
  18. package/dist/declarations/src/createActor.d.ts +31 -33
  19. package/dist/declarations/src/createMachine.d.ts +35 -7
  20. package/dist/declarations/src/createMachineFromConfig.d.ts +176 -0
  21. package/dist/declarations/src/graph/graph.d.ts +4 -2
  22. package/dist/declarations/src/index.d.ts +12 -8
  23. package/dist/declarations/src/inspection.d.ts +84 -30
  24. package/dist/declarations/src/mapState.d.ts +4 -2
  25. package/dist/declarations/src/schema.types.d.ts +90 -0
  26. package/dist/declarations/src/serialize.d.ts +44 -0
  27. package/dist/declarations/src/setup.d.ts +251 -123
  28. package/dist/declarations/src/spawn.d.ts +6 -31
  29. package/dist/declarations/src/stateUtils.d.ts +21 -19
  30. package/dist/declarations/src/system.d.ts +8 -7
  31. package/dist/declarations/src/transition.d.ts +5 -5
  32. package/dist/declarations/src/types.d.ts +407 -406
  33. package/dist/declarations/src/types.v6.d.ts +392 -0
  34. package/dist/declarations/src/utils.d.ts +4 -3
  35. package/dist/index-39259ea4.development.esm.js +4948 -0
  36. package/dist/index-688701ed.esm.js +4909 -0
  37. package/dist/index-c35824b4.development.cjs.js +5007 -0
  38. package/dist/index-f0d7107d.cjs.js +4968 -0
  39. package/dist/xstate-actors.cjs.js +12 -838
  40. package/dist/xstate-actors.cjs.mjs +10 -5
  41. package/dist/xstate-actors.development.cjs.js +12 -838
  42. package/dist/xstate-actors.development.cjs.mjs +10 -5
  43. package/dist/xstate-actors.development.esm.js +1 -836
  44. package/dist/xstate-actors.esm.js +1 -836
  45. package/dist/xstate-actors.umd.min.js +1 -1
  46. package/dist/xstate-actors.umd.min.js.map +1 -1
  47. package/dist/xstate-graph.cjs.js +18 -29
  48. package/dist/xstate-graph.development.cjs.js +18 -29
  49. package/dist/xstate-graph.development.esm.js +15 -26
  50. package/dist/xstate-graph.esm.js +15 -26
  51. package/dist/xstate-graph.umd.min.js +1 -1
  52. package/dist/xstate-graph.umd.min.js.map +1 -1
  53. package/dist/xstate.cjs.js +1316 -108
  54. package/dist/xstate.cjs.mjs +22 -22
  55. package/dist/xstate.development.cjs.js +1316 -108
  56. package/dist/xstate.development.cjs.mjs +22 -22
  57. package/dist/xstate.development.esm.js +1278 -72
  58. package/dist/xstate.esm.js +1278 -72
  59. package/dist/xstate.umd.min.js +1 -1
  60. package/dist/xstate.umd.min.js.map +1 -1
  61. package/package.json +3 -47
  62. package/dist/StateMachine-45e79c35.esm.js +0 -560
  63. package/dist/StateMachine-be2e51a3.development.cjs.js +0 -569
  64. package/dist/StateMachine-e0178d48.development.esm.js +0 -566
  65. package/dist/StateMachine-e6732977.cjs.js +0 -563
  66. package/dist/assign-2aa58daa.esm.js +0 -127
  67. package/dist/assign-927227d6.development.cjs.js +0 -135
  68. package/dist/assign-e8f2bd75.cjs.js +0 -129
  69. package/dist/assign-f338cee3.development.esm.js +0 -133
  70. package/dist/declarations/src/actions/assign.d.ts +0 -45
  71. package/dist/declarations/src/actions/cancel.d.ts +0 -39
  72. package/dist/declarations/src/actions/emit.d.ts +0 -44
  73. package/dist/declarations/src/actions/enqueueActions.d.ts +0 -57
  74. package/dist/declarations/src/actions/log.d.ts +0 -16
  75. package/dist/declarations/src/actions/raise.d.ts +0 -21
  76. package/dist/declarations/src/actions/send.d.ts +0 -42
  77. package/dist/declarations/src/actions/spawnChild.d.ts +0 -34
  78. package/dist/declarations/src/actions/stopChild.d.ts +0 -19
  79. package/dist/declarations/src/actors/transition.d.ts +0 -143
  80. package/dist/declarations/src/dev/index.d.ts +0 -14
  81. package/dist/declarations/src/guards.d.ts +0 -128
  82. package/dist/log-029f180b.development.cjs.js +0 -433
  83. package/dist/log-5a37e0ee.development.esm.js +0 -425
  84. package/dist/log-605ef461.esm.js +0 -397
  85. package/dist/log-fedf0966.cjs.js +0 -405
  86. package/dist/raise-74097812.development.esm.js +0 -2823
  87. package/dist/raise-7c948725.cjs.js +0 -2816
  88. package/dist/raise-964cd4e9.development.cjs.js +0 -2878
  89. package/dist/raise-e974d1c9.esm.js +0 -2761
  90. package/dist/xstate-actions.cjs.d.mts +0 -2
  91. package/dist/xstate-actions.cjs.d.ts +0 -2
  92. package/dist/xstate-actions.cjs.js +0 -23
  93. package/dist/xstate-actions.cjs.mjs +0 -14
  94. package/dist/xstate-actions.development.cjs.js +0 -23
  95. package/dist/xstate-actions.development.cjs.mjs +0 -14
  96. package/dist/xstate-actions.development.esm.js +0 -4
  97. package/dist/xstate-actions.esm.js +0 -4
  98. package/dist/xstate-actions.umd.min.js +0 -2
  99. package/dist/xstate-actions.umd.min.js.map +0 -1
  100. package/dist/xstate-dev.cjs.d.mts +0 -2
  101. package/dist/xstate-dev.cjs.d.ts +0 -2
  102. package/dist/xstate-dev.cjs.js +0 -48
  103. package/dist/xstate-dev.cjs.mjs +0 -5
  104. package/dist/xstate-dev.development.cjs.js +0 -51
  105. package/dist/xstate-dev.development.cjs.mjs +0 -5
  106. package/dist/xstate-dev.development.esm.js +0 -45
  107. package/dist/xstate-dev.esm.js +0 -42
  108. package/dist/xstate-dev.umd.min.js +0 -2
  109. package/dist/xstate-dev.umd.min.js.map +0 -1
  110. package/dist/xstate-guards.cjs.d.mts +0 -2
  111. package/dist/xstate-guards.cjs.d.ts +0 -2
  112. package/dist/xstate-guards.cjs.js +0 -14
  113. package/dist/xstate-guards.cjs.mjs +0 -7
  114. package/dist/xstate-guards.development.cjs.js +0 -14
  115. package/dist/xstate-guards.development.cjs.mjs +0 -7
  116. package/dist/xstate-guards.development.esm.js +0 -2
  117. package/dist/xstate-guards.esm.js +0 -2
  118. package/dist/xstate-guards.umd.min.js +0 -2
  119. package/dist/xstate-guards.umd.min.js.map +0 -1
@@ -1,2761 +0,0 @@
1
- import { devToolsAdapter } from './xstate-dev.esm.js';
2
-
3
- class Mailbox {
4
- constructor(_process) {
5
- this._process = _process;
6
- this._active = false;
7
- this._current = null;
8
- this._last = null;
9
- }
10
- start() {
11
- this._active = true;
12
- this.flush();
13
- }
14
- clear() {
15
- // we can't set _current to null because we might be currently processing
16
- // and enqueue following clear shouldn't start processing the enqueued item immediately
17
- if (this._current) {
18
- this._current.next = null;
19
- this._last = this._current;
20
- }
21
- }
22
- enqueue(event) {
23
- const enqueued = {
24
- value: event,
25
- next: null
26
- };
27
- if (this._current) {
28
- this._last.next = enqueued;
29
- this._last = enqueued;
30
- return;
31
- }
32
- this._current = enqueued;
33
- this._last = enqueued;
34
- if (this._active) {
35
- this.flush();
36
- }
37
- }
38
- flush() {
39
- while (this._current) {
40
- // atm the given _process is responsible for implementing proper try/catch handling
41
- // we assume here that this won't throw in a way that can affect this mailbox
42
- const consumed = this._current;
43
- this._process(consumed.value);
44
- this._current = consumed.next;
45
- }
46
- this._last = null;
47
- }
48
- }
49
-
50
- const STATE_DELIMITER = '.';
51
- const TARGETLESS_KEY = '';
52
- const NULL_EVENT = '';
53
- const STATE_IDENTIFIER = '#';
54
- const WILDCARD = '*';
55
- const XSTATE_INIT = 'xstate.init';
56
- const XSTATE_ERROR = 'xstate.error';
57
- const XSTATE_STOP = 'xstate.stop';
58
-
59
- /**
60
- * Returns an event that represents an implicit event that is sent after the
61
- * specified `delay`.
62
- *
63
- * @param delayRef The delay in milliseconds
64
- * @param id The state node ID where this event is handled
65
- */
66
- function createAfterEvent(delayRef, id) {
67
- return {
68
- type: `xstate.after.${delayRef}.${id}`
69
- };
70
- }
71
-
72
- /**
73
- * Returns an event that represents that a final state node has been reached in
74
- * the parent state node.
75
- *
76
- * @param id The final state node's parent state node `id`
77
- * @param output The data to pass into the event
78
- */
79
- function createDoneStateEvent(id, output) {
80
- return {
81
- type: `xstate.done.state.${id}`,
82
- output
83
- };
84
- }
85
-
86
- /**
87
- * Returns an event that represents that an invoked service has terminated.
88
- *
89
- * An invoked service is terminated when it has reached a top-level final state
90
- * node, but not when it is canceled.
91
- *
92
- * @param invokeId The invoked service ID
93
- * @param output The data to pass into the event
94
- */
95
- function createDoneActorEvent(invokeId, output) {
96
- return {
97
- type: `xstate.done.actor.${invokeId}`,
98
- output,
99
- actorId: invokeId
100
- };
101
- }
102
- function createErrorActorEvent(id, error) {
103
- return {
104
- type: `xstate.error.actor.${id}`,
105
- error,
106
- actorId: id
107
- };
108
- }
109
- function createInitEvent(input) {
110
- return {
111
- type: XSTATE_INIT,
112
- input
113
- };
114
- }
115
-
116
- /**
117
- * This function makes sure that unhandled errors are thrown in a separate
118
- * macrotask. It allows those errors to be detected by global error handlers and
119
- * reported to bug tracking services without interrupting our own stack of
120
- * execution.
121
- *
122
- * @param err Error to be thrown
123
- */
124
- function reportUnhandledError(err) {
125
- setTimeout(() => {
126
- throw err;
127
- });
128
- }
129
-
130
- const symbolObservable = (() => typeof Symbol === 'function' && Symbol.observable || '@@observable')();
131
-
132
- function matchesState(parentStateId, childStateId) {
133
- const parentStateValue = toStateValue(parentStateId);
134
- const childStateValue = toStateValue(childStateId);
135
- if (typeof childStateValue === 'string') {
136
- if (typeof parentStateValue === 'string') {
137
- return childStateValue === parentStateValue;
138
- }
139
-
140
- // Parent more specific than child
141
- return false;
142
- }
143
- if (typeof parentStateValue === 'string') {
144
- return parentStateValue in childStateValue;
145
- }
146
- return Object.keys(parentStateValue).every(key => {
147
- if (!(key in childStateValue)) {
148
- return false;
149
- }
150
- return matchesState(parentStateValue[key], childStateValue[key]);
151
- });
152
- }
153
- function toStatePath(stateId) {
154
- if (isArray(stateId)) {
155
- return stateId;
156
- }
157
- const result = [];
158
- let segment = '';
159
- for (let i = 0; i < stateId.length; i++) {
160
- const char = stateId.charCodeAt(i);
161
- switch (char) {
162
- // \
163
- case 92:
164
- // consume the next character
165
- segment += stateId[i + 1];
166
- // and skip over it
167
- i++;
168
- continue;
169
- // .
170
- case 46:
171
- result.push(segment);
172
- segment = '';
173
- continue;
174
- }
175
- segment += stateId[i];
176
- }
177
- result.push(segment);
178
- return result;
179
- }
180
- function toStateValue(stateValue) {
181
- if (isMachineSnapshot(stateValue)) {
182
- return stateValue.value;
183
- }
184
- if (typeof stateValue !== 'string') {
185
- return stateValue;
186
- }
187
- const statePath = toStatePath(stateValue);
188
- return pathToStateValue(statePath);
189
- }
190
- function pathToStateValue(statePath) {
191
- if (statePath.length === 1) {
192
- return statePath[0];
193
- }
194
- const value = {};
195
- let marker = value;
196
- for (let i = 0; i < statePath.length - 1; i++) {
197
- if (i === statePath.length - 2) {
198
- marker[statePath[i]] = statePath[i + 1];
199
- } else {
200
- const previous = marker;
201
- marker = {};
202
- previous[statePath[i]] = marker;
203
- }
204
- }
205
- return value;
206
- }
207
- function mapValues(collection, iteratee) {
208
- const result = {};
209
- const collectionKeys = Object.keys(collection);
210
- for (let i = 0; i < collectionKeys.length; i++) {
211
- const key = collectionKeys[i];
212
- result[key] = iteratee(collection[key], key, collection, i);
213
- }
214
- return result;
215
- }
216
- function toArrayStrict(value) {
217
- if (isArray(value)) {
218
- return value;
219
- }
220
- return [value];
221
- }
222
- function toArray(value) {
223
- if (value === undefined) {
224
- return [];
225
- }
226
- return toArrayStrict(value);
227
- }
228
- function resolveOutput(mapper, context, event, self) {
229
- if (typeof mapper === 'function') {
230
- return mapper({
231
- context,
232
- event,
233
- self
234
- });
235
- }
236
- return mapper;
237
- }
238
- function isArray(value) {
239
- return Array.isArray(value);
240
- }
241
- function isErrorActorEvent(event) {
242
- return event.type.startsWith('xstate.error.actor');
243
- }
244
- function toTransitionConfigArray(configLike) {
245
- return toArrayStrict(configLike).map(transitionLike => {
246
- if (typeof transitionLike === 'undefined' || typeof transitionLike === 'string') {
247
- return {
248
- target: transitionLike
249
- };
250
- }
251
- return transitionLike;
252
- });
253
- }
254
- function normalizeTarget(target) {
255
- if (target === undefined || target === TARGETLESS_KEY) {
256
- return undefined;
257
- }
258
- return toArray(target);
259
- }
260
- function toObserver(nextHandler, errorHandler, completionHandler) {
261
- const isObserver = typeof nextHandler === 'object';
262
- const self = isObserver ? nextHandler : undefined;
263
- return {
264
- next: (isObserver ? nextHandler.next : nextHandler)?.bind(self),
265
- error: (isObserver ? nextHandler.error : errorHandler)?.bind(self),
266
- complete: (isObserver ? nextHandler.complete : completionHandler)?.bind(self)
267
- };
268
- }
269
- function createInvokeId(stateNodeId, index) {
270
- return `${index}.${stateNodeId}`;
271
- }
272
- function resolveReferencedActor(machine, src) {
273
- const match = src.match(/^xstate\.invoke\.(\d+)\.(.*)/);
274
- if (!match) {
275
- return machine.implementations.actors[src];
276
- }
277
- const [, indexStr, nodeId] = match;
278
- const node = machine.getStateNodeById(nodeId);
279
- const invokeConfig = node.config.invoke;
280
- return (Array.isArray(invokeConfig) ? invokeConfig[indexStr] : invokeConfig).src;
281
- }
282
- function getAllOwnEventDescriptors(snapshot) {
283
- return [...new Set([...snapshot._nodes.flatMap(sn => sn.ownEvents)])];
284
- }
285
-
286
- /**
287
- * Checks if an event type matches an event descriptor, supporting wildcards.
288
- * Event descriptors can be:
289
- *
290
- * - Exact matches: "event.type"
291
- * - Wildcard: "*"
292
- * - Partial matches: "event.*"
293
- *
294
- * @param eventType - The actual event type string
295
- * @param descriptor - The event descriptor to match against
296
- * @returns True if the event type matches the descriptor
297
- */
298
- function matchesEventDescriptor(eventType, descriptor) {
299
- if (descriptor === eventType) {
300
- return true;
301
- }
302
- if (descriptor === WILDCARD) {
303
- return true;
304
- }
305
- if (!descriptor.endsWith('.*')) {
306
- return false;
307
- }
308
- const partialEventTokens = descriptor.split('.');
309
- const eventTokens = eventType.split('.');
310
- for (let tokenIndex = 0; tokenIndex < partialEventTokens.length; tokenIndex++) {
311
- const partialEventToken = partialEventTokens[tokenIndex];
312
- const eventToken = eventTokens[tokenIndex];
313
- if (partialEventToken === '*') {
314
- const isLastToken = tokenIndex === partialEventTokens.length - 1;
315
- return isLastToken;
316
- }
317
- if (partialEventToken !== eventToken) {
318
- return false;
319
- }
320
- }
321
- return true;
322
- }
323
-
324
- function createScheduledEventId(actorRef, id) {
325
- return `${actorRef.sessionId}.${id}`;
326
- }
327
- let idCounter = 0;
328
- function createSystem(rootActor, options) {
329
- const children = new Map();
330
- const keyedActors = new Map();
331
- const reverseKeyedActors = new WeakMap();
332
- const inspectionObservers = new Set();
333
- const timerMap = {};
334
- const {
335
- clock,
336
- logger
337
- } = options;
338
- const scheduler = {
339
- schedule: (source, target, event, delay, id = Math.random().toString(36).slice(2)) => {
340
- const scheduledEvent = {
341
- source,
342
- target,
343
- event,
344
- delay,
345
- id,
346
- startedAt: Date.now()
347
- };
348
- const scheduledEventId = createScheduledEventId(source, id);
349
- system._snapshot._scheduledEvents[scheduledEventId] = scheduledEvent;
350
- const timeout = clock.setTimeout(() => {
351
- delete timerMap[scheduledEventId];
352
- delete system._snapshot._scheduledEvents[scheduledEventId];
353
- system._relay(source, target, event);
354
- }, delay);
355
- timerMap[scheduledEventId] = timeout;
356
- },
357
- cancel: (source, id) => {
358
- const scheduledEventId = createScheduledEventId(source, id);
359
- const timeout = timerMap[scheduledEventId];
360
- delete timerMap[scheduledEventId];
361
- delete system._snapshot._scheduledEvents[scheduledEventId];
362
- if (timeout !== undefined) {
363
- clock.clearTimeout(timeout);
364
- }
365
- },
366
- cancelAll: actorRef => {
367
- for (const scheduledEventId in system._snapshot._scheduledEvents) {
368
- const scheduledEvent = system._snapshot._scheduledEvents[scheduledEventId];
369
- if (scheduledEvent.source === actorRef) {
370
- scheduler.cancel(actorRef, scheduledEvent.id);
371
- }
372
- }
373
- }
374
- };
375
- const sendInspectionEvent = event => {
376
- if (!inspectionObservers.size) {
377
- return;
378
- }
379
- const resolvedInspectionEvent = {
380
- ...event,
381
- rootId: rootActor.sessionId
382
- };
383
- inspectionObservers.forEach(observer => observer.next?.(resolvedInspectionEvent));
384
- };
385
- const system = {
386
- _snapshot: {
387
- _scheduledEvents: (options?.snapshot && options.snapshot.scheduler) ?? {}
388
- },
389
- _bookId: () => `x:${idCounter++}`,
390
- _register: (sessionId, actorRef) => {
391
- children.set(sessionId, actorRef);
392
- return sessionId;
393
- },
394
- _unregister: actorRef => {
395
- children.delete(actorRef.sessionId);
396
- const systemId = reverseKeyedActors.get(actorRef);
397
- if (systemId !== undefined) {
398
- keyedActors.delete(systemId);
399
- reverseKeyedActors.delete(actorRef);
400
- }
401
- },
402
- get: systemId => {
403
- return keyedActors.get(systemId);
404
- },
405
- getAll: () => {
406
- return Object.fromEntries(keyedActors.entries());
407
- },
408
- _set: (systemId, actorRef) => {
409
- const existing = keyedActors.get(systemId);
410
- if (existing && existing !== actorRef) {
411
- throw new Error(`Actor with system ID '${systemId}' already exists.`);
412
- }
413
- keyedActors.set(systemId, actorRef);
414
- reverseKeyedActors.set(actorRef, systemId);
415
- },
416
- inspect: observerOrFn => {
417
- const observer = toObserver(observerOrFn);
418
- inspectionObservers.add(observer);
419
- return {
420
- unsubscribe() {
421
- inspectionObservers.delete(observer);
422
- }
423
- };
424
- },
425
- _sendInspectionEvent: sendInspectionEvent,
426
- _relay: (source, target, event) => {
427
- system._sendInspectionEvent({
428
- type: '@xstate.event',
429
- sourceRef: source,
430
- actorRef: target,
431
- event
432
- });
433
- target._send(event);
434
- },
435
- scheduler,
436
- getSnapshot: () => {
437
- return {
438
- _scheduledEvents: {
439
- ...system._snapshot._scheduledEvents
440
- }
441
- };
442
- },
443
- start: () => {
444
- const scheduledEvents = system._snapshot._scheduledEvents;
445
- system._snapshot._scheduledEvents = {};
446
- for (const scheduledId in scheduledEvents) {
447
- const {
448
- source,
449
- target,
450
- event,
451
- delay,
452
- id
453
- } = scheduledEvents[scheduledId];
454
- scheduler.schedule(source, target, event, delay, id);
455
- }
456
- },
457
- _clock: clock,
458
- _logger: logger
459
- };
460
- return system;
461
- }
462
-
463
- // those are needed to make JSDoc `@link` work properly
464
-
465
- let executingCustomAction = false;
466
- const $$ACTOR_TYPE = 1;
467
-
468
- // those values are currently used by @xstate/react directly so it's important to keep the assigned values in sync
469
- let ProcessingStatus = /*#__PURE__*/function (ProcessingStatus) {
470
- ProcessingStatus[ProcessingStatus["NotStarted"] = 0] = "NotStarted";
471
- ProcessingStatus[ProcessingStatus["Running"] = 1] = "Running";
472
- ProcessingStatus[ProcessingStatus["Stopped"] = 2] = "Stopped";
473
- return ProcessingStatus;
474
- }({});
475
- const defaultOptions = {
476
- clock: {
477
- setTimeout: (fn, ms) => {
478
- return setTimeout(fn, ms);
479
- },
480
- clearTimeout: id => {
481
- return clearTimeout(id);
482
- }
483
- },
484
- logger: console.log.bind(console),
485
- devTools: false
486
- };
487
-
488
- /**
489
- * An Actor is a running process that can receive events, send events and change
490
- * its behavior based on the events it receives, which can cause effects outside
491
- * of the actor. When you run a state machine, it becomes an actor.
492
- */
493
- class Actor {
494
- /**
495
- * Creates a new actor instance for the given logic with the provided options,
496
- * if any.
497
- *
498
- * @param logic The logic to create an actor from
499
- * @param options Actor options
500
- */
501
- constructor(logic, options) {
502
- this.logic = logic;
503
- /** The current internal state of the actor. */
504
- this._snapshot = void 0;
505
- /**
506
- * The clock that is responsible for setting and clearing timeouts, such as
507
- * delayed events and transitions.
508
- */
509
- this.clock = void 0;
510
- this.options = void 0;
511
- /** The unique identifier for this actor relative to its parent. */
512
- this.id = void 0;
513
- this.mailbox = new Mailbox(this._process.bind(this));
514
- this.observers = new Set();
515
- this.eventListeners = new Map();
516
- this.logger = void 0;
517
- /** @internal */
518
- this._processingStatus = ProcessingStatus.NotStarted;
519
- // Actor Ref
520
- this._parent = void 0;
521
- /** @internal */
522
- this._syncSnapshot = void 0;
523
- this.ref = void 0;
524
- // TODO: add typings for system
525
- this._actorScope = void 0;
526
- this.systemId = void 0;
527
- /** The globally unique process ID for this invocation. */
528
- this.sessionId = void 0;
529
- /** The system to which this actor belongs. */
530
- this.system = void 0;
531
- this._doneEvent = void 0;
532
- this.src = void 0;
533
- // array of functions to defer
534
- this._deferred = [];
535
- const resolvedOptions = {
536
- ...defaultOptions,
537
- ...options
538
- };
539
- const {
540
- clock,
541
- logger,
542
- parent,
543
- syncSnapshot,
544
- id,
545
- systemId,
546
- inspect
547
- } = resolvedOptions;
548
- this.system = parent ? parent.system : createSystem(this, {
549
- clock,
550
- logger
551
- });
552
- if (inspect && !parent) {
553
- // Always inspect at the system-level
554
- this.system.inspect(toObserver(inspect));
555
- }
556
- this.sessionId = this.system._bookId();
557
- this.id = id ?? this.sessionId;
558
- this.logger = options?.logger ?? this.system._logger;
559
- this.clock = options?.clock ?? this.system._clock;
560
- this._parent = parent;
561
- this._syncSnapshot = syncSnapshot;
562
- this.options = resolvedOptions;
563
- this.src = resolvedOptions.src ?? logic;
564
- this.ref = this;
565
- this._actorScope = {
566
- self: this,
567
- id: this.id,
568
- sessionId: this.sessionId,
569
- logger: this.logger,
570
- defer: fn => {
571
- this._deferred.push(fn);
572
- },
573
- system: this.system,
574
- stopChild: child => {
575
- if (child._parent !== this) {
576
- throw new Error(`Cannot stop child actor ${child.id} of ${this.id} because it is not a child`);
577
- }
578
- child._stop();
579
- },
580
- emit: emittedEvent => {
581
- const listeners = this.eventListeners.get(emittedEvent.type);
582
- const wildcardListener = this.eventListeners.get('*');
583
- if (!listeners && !wildcardListener) {
584
- return;
585
- }
586
- const allListeners = [...(listeners ? listeners.values() : []), ...(wildcardListener ? wildcardListener.values() : [])];
587
- for (const handler of allListeners) {
588
- try {
589
- handler(emittedEvent);
590
- } catch (err) {
591
- reportUnhandledError(err);
592
- }
593
- }
594
- },
595
- actionExecutor: action => {
596
- const exec = () => {
597
- this._actorScope.system._sendInspectionEvent({
598
- type: '@xstate.action',
599
- actorRef: this,
600
- action: {
601
- type: action.type,
602
- params: action.params
603
- }
604
- });
605
- if (!action.exec) {
606
- return;
607
- }
608
- const saveExecutingCustomAction = executingCustomAction;
609
- try {
610
- executingCustomAction = true;
611
- action.exec(action.info, action.params);
612
- } finally {
613
- executingCustomAction = saveExecutingCustomAction;
614
- }
615
- };
616
- if (this._processingStatus === ProcessingStatus.Running) {
617
- exec();
618
- } else {
619
- this._deferred.push(exec);
620
- }
621
- }
622
- };
623
-
624
- // Ensure that the send method is bound to this Actor instance
625
- // if destructured
626
- this.send = this.send.bind(this);
627
- this.system._sendInspectionEvent({
628
- type: '@xstate.actor',
629
- actorRef: this
630
- });
631
- if (systemId) {
632
- this.systemId = systemId;
633
- this.system._set(systemId, this);
634
- }
635
- this._initState(options?.snapshot ?? options?.state);
636
- if (systemId && this._snapshot.status !== 'active') {
637
- this.system._unregister(this);
638
- }
639
- }
640
- _initState(persistedState) {
641
- try {
642
- this._snapshot = persistedState ? this.logic.restoreSnapshot ? this.logic.restoreSnapshot(persistedState, this._actorScope) : persistedState : this.logic.getInitialSnapshot(this._actorScope, this.options?.input);
643
- } catch (err) {
644
- // if we get here then it means that we assign a value to this._snapshot that is not of the correct type
645
- // we can't get the true `TSnapshot & { status: 'error'; }`, it's impossible
646
- // so right now this is a lie of sorts
647
- this._snapshot = {
648
- status: 'error',
649
- output: undefined,
650
- error: err
651
- };
652
- }
653
- }
654
- update(snapshot, event) {
655
- // Update state
656
- this._snapshot = snapshot;
657
-
658
- // Execute deferred effects
659
- let deferredFn;
660
- while (deferredFn = this._deferred.shift()) {
661
- try {
662
- deferredFn();
663
- } catch (err) {
664
- // this error can only be caught when executing *initial* actions
665
- // it's the only time when we call actions provided by the user through those deferreds
666
- // when the actor is already running we always execute them synchronously while transitioning
667
- // no "builtin deferred" should actually throw an error since they are either safe
668
- // or the control flow is passed through the mailbox and errors should be caught by the `_process` used by the mailbox
669
- this._deferred.length = 0;
670
- this._snapshot = {
671
- ...snapshot,
672
- status: 'error',
673
- error: err
674
- };
675
- }
676
- }
677
- switch (this._snapshot.status) {
678
- case 'active':
679
- for (const observer of this.observers) {
680
- try {
681
- observer.next?.(snapshot);
682
- } catch (err) {
683
- reportUnhandledError(err);
684
- }
685
- }
686
- break;
687
- case 'done':
688
- // next observers are meant to be notified about done snapshots
689
- // this can be seen as something that is different from how observable work
690
- // but with observables `complete` callback is called without any arguments
691
- // it's more ergonomic for XState to treat a done snapshot as a "next" value
692
- // and the completion event as something that is separate,
693
- // something that merely follows emitting that done snapshot
694
- for (const observer of this.observers) {
695
- try {
696
- observer.next?.(snapshot);
697
- } catch (err) {
698
- reportUnhandledError(err);
699
- }
700
- }
701
- this._stopProcedure();
702
- this._complete();
703
- this._doneEvent = createDoneActorEvent(this.id, this._snapshot.output);
704
- if (this._parent) {
705
- this.system._relay(this, this._parent, this._doneEvent);
706
- }
707
- break;
708
- case 'error':
709
- this._error(this._snapshot.error);
710
- break;
711
- }
712
- this.system._sendInspectionEvent({
713
- type: '@xstate.snapshot',
714
- actorRef: this,
715
- event,
716
- snapshot
717
- });
718
- }
719
-
720
- /**
721
- * Subscribe an observer to an actor’s snapshot values.
722
- *
723
- * @remarks
724
- * The observer will receive the actor’s snapshot value when it is emitted.
725
- * The observer can be:
726
- *
727
- * - A plain function that receives the latest snapshot, or
728
- * - An observer object whose `.next(snapshot)` method receives the latest
729
- * snapshot
730
- *
731
- * @example
732
- *
733
- * ```ts
734
- * // Observer as a plain function
735
- * const subscription = actor.subscribe((snapshot) => {
736
- * console.log(snapshot);
737
- * });
738
- * ```
739
- *
740
- * @example
741
- *
742
- * ```ts
743
- * // Observer as an object
744
- * const subscription = actor.subscribe({
745
- * next(snapshot) {
746
- * console.log(snapshot);
747
- * },
748
- * error(err) {
749
- * // ...
750
- * },
751
- * complete() {
752
- * // ...
753
- * }
754
- * });
755
- * ```
756
- *
757
- * The return value of `actor.subscribe(observer)` is a subscription object
758
- * that has an `.unsubscribe()` method. You can call
759
- * `subscription.unsubscribe()` to unsubscribe the observer:
760
- *
761
- * @example
762
- *
763
- * ```ts
764
- * const subscription = actor.subscribe((snapshot) => {
765
- * // ...
766
- * });
767
- *
768
- * // Unsubscribe the observer
769
- * subscription.unsubscribe();
770
- * ```
771
- *
772
- * When the actor is stopped, all of its observers will automatically be
773
- * unsubscribed.
774
- *
775
- * @param observer - Either a plain function that receives the latest
776
- * snapshot, or an observer object whose `.next(snapshot)` method receives
777
- * the latest snapshot
778
- */
779
-
780
- subscribe(nextListenerOrObserver, errorListener, completeListener) {
781
- const observer = toObserver(nextListenerOrObserver, errorListener, completeListener);
782
- if (this._processingStatus !== ProcessingStatus.Stopped) {
783
- this.observers.add(observer);
784
- } else {
785
- switch (this._snapshot.status) {
786
- case 'done':
787
- try {
788
- observer.complete?.();
789
- } catch (err) {
790
- reportUnhandledError(err);
791
- }
792
- break;
793
- case 'error':
794
- {
795
- const err = this._snapshot.error;
796
- if (!observer.error) {
797
- reportUnhandledError(err);
798
- } else {
799
- try {
800
- observer.error(err);
801
- } catch (err) {
802
- reportUnhandledError(err);
803
- }
804
- }
805
- break;
806
- }
807
- }
808
- }
809
- return {
810
- unsubscribe: () => {
811
- this.observers.delete(observer);
812
- }
813
- };
814
- }
815
- on(type, handler) {
816
- let listeners = this.eventListeners.get(type);
817
- if (!listeners) {
818
- listeners = new Set();
819
- this.eventListeners.set(type, listeners);
820
- }
821
- const wrappedHandler = handler.bind(undefined);
822
- listeners.add(wrappedHandler);
823
- return {
824
- unsubscribe: () => {
825
- listeners.delete(wrappedHandler);
826
- }
827
- };
828
- }
829
- select(selector, equalityFn = Object.is) {
830
- return {
831
- subscribe: observerOrFn => {
832
- const observer = toObserver(observerOrFn);
833
- const snapshot = this.getSnapshot();
834
- let previousSelected = selector(snapshot);
835
- return this.subscribe(snapshot => {
836
- const nextSelected = selector(snapshot);
837
- if (!equalityFn(previousSelected, nextSelected)) {
838
- previousSelected = nextSelected;
839
- observer.next?.(nextSelected);
840
- }
841
- });
842
- },
843
- get: () => selector(this.getSnapshot())
844
- };
845
- }
846
-
847
- /** Starts the Actor from the initial state */
848
- start() {
849
- if (this._processingStatus === ProcessingStatus.Running) {
850
- // Do not restart the service if it is already started
851
- return this;
852
- }
853
- if (this._syncSnapshot) {
854
- this.subscribe({
855
- next: snapshot => {
856
- if (snapshot.status === 'active') {
857
- this.system._relay(this, this._parent, {
858
- type: `xstate.snapshot.${this.id}`,
859
- snapshot
860
- });
861
- }
862
- },
863
- error: () => {}
864
- });
865
- }
866
- this.system._register(this.sessionId, this);
867
- if (this.systemId) {
868
- this.system._set(this.systemId, this);
869
- }
870
- this._processingStatus = ProcessingStatus.Running;
871
-
872
- // TODO: this isn't correct when rehydrating
873
- const initEvent = createInitEvent(this.options.input);
874
- this.system._sendInspectionEvent({
875
- type: '@xstate.event',
876
- sourceRef: this._parent,
877
- actorRef: this,
878
- event: initEvent
879
- });
880
- const status = this._snapshot.status;
881
- switch (status) {
882
- case 'done':
883
- // a state machine can be "done" upon initialization (it could reach a final state using initial microsteps)
884
- // we still need to complete observers, flush deferreds etc
885
- this.update(this._snapshot, initEvent);
886
- // TODO: rethink cleanup of observers, mailbox, etc
887
- return this;
888
- case 'error':
889
- this._error(this._snapshot.error);
890
- return this;
891
- }
892
- if (!this._parent) {
893
- this.system.start();
894
- }
895
- if (this.logic.start) {
896
- try {
897
- this.logic.start(this._snapshot, this._actorScope);
898
- } catch (err) {
899
- this._snapshot = {
900
- ...this._snapshot,
901
- status: 'error',
902
- error: err
903
- };
904
- this._error(err);
905
- return this;
906
- }
907
- }
908
-
909
- // TODO: this notifies all subscribers but usually this is redundant
910
- // there is no real change happening here
911
- // we need to rethink if this needs to be refactored
912
- this.update(this._snapshot, initEvent);
913
- if (this.options.devTools) {
914
- this.attachDevTools();
915
- }
916
- this.mailbox.start();
917
- return this;
918
- }
919
- _process(event) {
920
- let nextState;
921
- let caughtError;
922
- try {
923
- nextState = this.logic.transition(this._snapshot, event, this._actorScope);
924
- } catch (err) {
925
- // we wrap it in a box so we can rethrow it later even if falsy value gets caught here
926
- caughtError = {
927
- err
928
- };
929
- }
930
- if (caughtError) {
931
- const {
932
- err
933
- } = caughtError;
934
- this._snapshot = {
935
- ...this._snapshot,
936
- status: 'error',
937
- error: err
938
- };
939
- this._error(err);
940
- return;
941
- }
942
- this.update(nextState, event);
943
- if (event.type === XSTATE_STOP) {
944
- this._stopProcedure();
945
- this._complete();
946
- }
947
- }
948
- _stop() {
949
- if (this._processingStatus === ProcessingStatus.Stopped) {
950
- return this;
951
- }
952
- this.mailbox.clear();
953
- if (this._processingStatus === ProcessingStatus.NotStarted) {
954
- this._processingStatus = ProcessingStatus.Stopped;
955
- return this;
956
- }
957
- this.mailbox.enqueue({
958
- type: XSTATE_STOP
959
- });
960
- return this;
961
- }
962
-
963
- /** Stops the Actor and unsubscribe all listeners. */
964
- stop() {
965
- if (this._parent) {
966
- throw new Error('A non-root actor cannot be stopped directly.');
967
- }
968
- return this._stop();
969
- }
970
- _complete() {
971
- for (const observer of this.observers) {
972
- try {
973
- observer.complete?.();
974
- } catch (err) {
975
- reportUnhandledError(err);
976
- }
977
- }
978
- this.observers.clear();
979
- this.eventListeners.clear();
980
- }
981
- _reportError(err) {
982
- if (!this.observers.size) {
983
- if (!this._parent) {
984
- reportUnhandledError(err);
985
- }
986
- this.eventListeners.clear();
987
- return;
988
- }
989
- let reportError = false;
990
- for (const observer of this.observers) {
991
- const errorListener = observer.error;
992
- reportError ||= !errorListener;
993
- try {
994
- errorListener?.(err);
995
- } catch (err2) {
996
- reportUnhandledError(err2);
997
- }
998
- }
999
- this.observers.clear();
1000
- this.eventListeners.clear();
1001
- if (reportError) {
1002
- reportUnhandledError(err);
1003
- }
1004
- }
1005
- _error(err) {
1006
- this._stopProcedure();
1007
- this._reportError(err);
1008
- if (this._parent) {
1009
- this.system._relay(this, this._parent, createErrorActorEvent(this.id, err));
1010
- }
1011
- }
1012
- // TODO: atm children don't belong entirely to the actor so
1013
- // in a way - it's not even super aware of them
1014
- // so we can't stop them from here but we really should!
1015
- // right now, they are being stopped within the machine's transition
1016
- // but that could throw and leave us with "orphaned" active actors
1017
- _stopProcedure() {
1018
- if (this._processingStatus !== ProcessingStatus.Running) {
1019
- // Actor already stopped; do nothing
1020
- return this;
1021
- }
1022
-
1023
- // Cancel all delayed events
1024
- this.system.scheduler.cancelAll(this);
1025
-
1026
- // TODO: mailbox.reset
1027
- this.mailbox.clear();
1028
- // TODO: after `stop` we must prepare ourselves for receiving events again
1029
- // events sent *after* stop signal must be queued
1030
- // it seems like this should be the common behavior for all of our consumers
1031
- // so perhaps this should be unified somehow for all of them
1032
- this.mailbox = new Mailbox(this._process.bind(this));
1033
- this._processingStatus = ProcessingStatus.Stopped;
1034
- this.system._unregister(this);
1035
- return this;
1036
- }
1037
-
1038
- /** @internal */
1039
- _send(event) {
1040
- if (this._processingStatus === ProcessingStatus.Stopped) {
1041
- return;
1042
- }
1043
- this.mailbox.enqueue(event);
1044
- }
1045
-
1046
- /**
1047
- * Sends an event to the running Actor to trigger a transition.
1048
- *
1049
- * @param event The event to send
1050
- */
1051
- send(event) {
1052
- this.system._relay(undefined, this, event);
1053
- }
1054
- attachDevTools() {
1055
- const {
1056
- devTools
1057
- } = this.options;
1058
- if (devTools) {
1059
- const resolvedDevToolsAdapter = typeof devTools === 'function' ? devTools : devToolsAdapter;
1060
- resolvedDevToolsAdapter(this);
1061
- }
1062
- }
1063
- toJSON() {
1064
- return {
1065
- xstate$$type: $$ACTOR_TYPE,
1066
- id: this.id
1067
- };
1068
- }
1069
-
1070
- /**
1071
- * Obtain the internal state of the actor, which can be persisted.
1072
- *
1073
- * @remarks
1074
- * The internal state can be persisted from any actor, not only machines.
1075
- *
1076
- * Note that the persisted state is not the same as the snapshot from
1077
- * {@link Actor.getSnapshot}. Persisted state represents the internal state of
1078
- * the actor, while snapshots represent the actor's last emitted value.
1079
- *
1080
- * Can be restored with {@link ActorOptions.state}
1081
- * @see https://stately.ai/docs/persistence
1082
- */
1083
-
1084
- getPersistedSnapshot(options) {
1085
- return this.logic.getPersistedSnapshot(this._snapshot, options);
1086
- }
1087
- [symbolObservable]() {
1088
- return this;
1089
- }
1090
-
1091
- /**
1092
- * Read an actor’s snapshot synchronously.
1093
- *
1094
- * @remarks
1095
- * The snapshot represent an actor's last emitted value.
1096
- *
1097
- * When an actor receives an event, its internal state may change. An actor
1098
- * may emit a snapshot when a state transition occurs.
1099
- *
1100
- * Note that some actors, such as callback actors generated with
1101
- * `fromCallback`, will not emit snapshots.
1102
- * @see {@link Actor.subscribe} to subscribe to an actor’s snapshot values.
1103
- * @see {@link Actor.getPersistedSnapshot} to persist the internal state of an actor (which is more than just a snapshot).
1104
- */
1105
- getSnapshot() {
1106
- return this._snapshot;
1107
- }
1108
- }
1109
- /**
1110
- * Creates a new actor instance for the given actor logic with the provided
1111
- * options, if any.
1112
- *
1113
- * @remarks
1114
- * When you create an actor from actor logic via `createActor(logic)`, you
1115
- * implicitly create an actor system where the created actor is the root actor.
1116
- * Any actors spawned from this root actor and its descendants are part of that
1117
- * actor system.
1118
- * @example
1119
- *
1120
- * ```ts
1121
- * import { createActor } from 'xstate';
1122
- * import { someActorLogic } from './someActorLogic.ts';
1123
- *
1124
- * // Creating the actor, which implicitly creates an actor system with itself as the root actor
1125
- * const actor = createActor(someActorLogic);
1126
- *
1127
- * actor.subscribe((snapshot) => {
1128
- * console.log(snapshot);
1129
- * });
1130
- *
1131
- * // Actors must be started by calling `actor.start()`, which will also start the actor system.
1132
- * actor.start();
1133
- *
1134
- * // Actors can receive events
1135
- * actor.send({ type: 'someEvent' });
1136
- *
1137
- * // You can stop root actors by calling `actor.stop()`, which will also stop the actor system and all actors in that system.
1138
- * actor.stop();
1139
- * ```
1140
- *
1141
- * @param logic - The actor logic to create an actor from. For a state machine
1142
- * actor logic creator, see {@link createMachine}. Other actor logic creators
1143
- * include {@link fromCallback}, {@link fromEventObservable},
1144
- * {@link fromObservable}, {@link fromPromise}, and {@link fromTransition}.
1145
- * @param options - Actor options
1146
- */
1147
- function createActor(logic, ...[options]) {
1148
- return new Actor(logic, options);
1149
- }
1150
-
1151
- /**
1152
- * Creates a new Interpreter instance for the given machine with the provided
1153
- * options, if any.
1154
- *
1155
- * @deprecated Use `createActor` instead
1156
- * @alias
1157
- */
1158
- const interpret = createActor;
1159
-
1160
- /**
1161
- * @deprecated Use `Actor` instead.
1162
- * @alias
1163
- */
1164
-
1165
- function resolveCancel(_, snapshot, actionArgs, actionParams, {
1166
- sendId
1167
- }) {
1168
- const resolvedSendId = typeof sendId === 'function' ? sendId(actionArgs, actionParams) : sendId;
1169
- return [snapshot, {
1170
- sendId: resolvedSendId
1171
- }, undefined];
1172
- }
1173
- function executeCancel(actorScope, params) {
1174
- actorScope.defer(() => {
1175
- actorScope.system.scheduler.cancel(actorScope.self, params.sendId);
1176
- });
1177
- }
1178
- /**
1179
- * Cancels a delayed `sendTo(...)` action that is waiting to be executed. The
1180
- * canceled `sendTo(...)` action will not send its event or execute, unless the
1181
- * `delay` has already elapsed before `cancel(...)` is called.
1182
- *
1183
- * @example
1184
- *
1185
- * ```ts
1186
- * import { createMachine, sendTo, cancel } from 'xstate';
1187
- *
1188
- * const machine = createMachine({
1189
- * // ...
1190
- * on: {
1191
- * sendEvent: {
1192
- * actions: sendTo(
1193
- * 'some-actor',
1194
- * { type: 'someEvent' },
1195
- * {
1196
- * id: 'some-id',
1197
- * delay: 1000
1198
- * }
1199
- * )
1200
- * },
1201
- * cancelEvent: {
1202
- * actions: cancel('some-id')
1203
- * }
1204
- * }
1205
- * });
1206
- * ```
1207
- *
1208
- * @param sendId The `id` of the `sendTo(...)` action to cancel.
1209
- */
1210
- function cancel(sendId) {
1211
- function cancel(_args, _params) {
1212
- }
1213
- cancel.type = 'xstate.cancel';
1214
- cancel.sendId = sendId;
1215
- cancel.resolve = resolveCancel;
1216
- cancel.execute = executeCancel;
1217
- return cancel;
1218
- }
1219
-
1220
- function resolveSpawn(actorScope, snapshot, actionArgs, _actionParams, {
1221
- id,
1222
- systemId,
1223
- src,
1224
- input,
1225
- syncSnapshot
1226
- }) {
1227
- const logic = typeof src === 'string' ? resolveReferencedActor(snapshot.machine, src) : src;
1228
- const resolvedId = typeof id === 'function' ? id(actionArgs) : id;
1229
- let actorRef;
1230
- let resolvedInput = undefined;
1231
- if (logic) {
1232
- resolvedInput = typeof input === 'function' ? input({
1233
- context: snapshot.context,
1234
- event: actionArgs.event,
1235
- self: actorScope.self
1236
- }) : input;
1237
- actorRef = createActor(logic, {
1238
- id: resolvedId,
1239
- src,
1240
- parent: actorScope.self,
1241
- syncSnapshot,
1242
- systemId,
1243
- input: resolvedInput
1244
- });
1245
- }
1246
- return [cloneMachineSnapshot(snapshot, {
1247
- children: {
1248
- ...snapshot.children,
1249
- [resolvedId]: actorRef
1250
- }
1251
- }), {
1252
- id,
1253
- systemId,
1254
- actorRef,
1255
- src,
1256
- input: resolvedInput
1257
- }, undefined];
1258
- }
1259
- function executeSpawn(actorScope, {
1260
- actorRef
1261
- }) {
1262
- if (!actorRef) {
1263
- return;
1264
- }
1265
- actorScope.defer(() => {
1266
- if (actorRef._processingStatus === ProcessingStatus.Stopped) {
1267
- return;
1268
- }
1269
- actorRef.start();
1270
- });
1271
- }
1272
- function spawnChild(...[src, {
1273
- id,
1274
- systemId,
1275
- input,
1276
- syncSnapshot = false
1277
- } = {}]) {
1278
- function spawnChild(_args, _params) {
1279
- }
1280
- spawnChild.type = 'xstate.spawnChild';
1281
- spawnChild.id = id;
1282
- spawnChild.systemId = systemId;
1283
- spawnChild.src = src;
1284
- spawnChild.input = input;
1285
- spawnChild.syncSnapshot = syncSnapshot;
1286
- spawnChild.resolve = resolveSpawn;
1287
- spawnChild.execute = executeSpawn;
1288
- return spawnChild;
1289
- }
1290
-
1291
- function resolveStop(_, snapshot, args, actionParams, {
1292
- actorRef
1293
- }) {
1294
- const actorRefOrString = typeof actorRef === 'function' ? actorRef(args, actionParams) : actorRef;
1295
- const resolvedActorRef = typeof actorRefOrString === 'string' ? snapshot.children[actorRefOrString] : actorRefOrString;
1296
- let children = snapshot.children;
1297
- if (resolvedActorRef) {
1298
- children = {
1299
- ...children
1300
- };
1301
- delete children[resolvedActorRef.id];
1302
- }
1303
- return [cloneMachineSnapshot(snapshot, {
1304
- children
1305
- }), resolvedActorRef, undefined];
1306
- }
1307
- function unregisterRecursively(actorScope, actorRef) {
1308
- // unregister children first (depth-first)
1309
- const snapshot = actorRef.getSnapshot();
1310
- if (snapshot && 'children' in snapshot) {
1311
- for (const child of Object.values(snapshot.children)) {
1312
- unregisterRecursively(actorScope, child);
1313
- }
1314
- }
1315
- actorScope.system._unregister(actorRef);
1316
- }
1317
- function executeStop(actorScope, actorRef) {
1318
- if (!actorRef) {
1319
- return;
1320
- }
1321
-
1322
- // we need to eagerly unregister it here so a new actor with the same systemId can be registered immediately
1323
- // since we defer actual stopping of the actor but we don't defer actor creations (and we can't do that)
1324
- // this could throw on `systemId` collision, for example, when dealing with reentering transitions
1325
- // we also need to recursively unregister all nested children's systemIds
1326
- unregisterRecursively(actorScope, actorRef);
1327
-
1328
- // this allows us to prevent an actor from being started if it gets stopped within the same macrostep
1329
- // this can happen, for example, when the invoking state is being exited immediately by an always transition
1330
- if (actorRef._processingStatus !== ProcessingStatus.Running) {
1331
- actorScope.stopChild(actorRef);
1332
- return;
1333
- }
1334
- // stopping a child enqueues a stop event in the child actor's mailbox
1335
- // we need for all of the already enqueued events to be processed before we stop the child
1336
- // the parent itself might want to send some events to a child (for example from exit actions on the invoking state)
1337
- // and we don't want to ignore those events
1338
- actorScope.defer(() => {
1339
- actorScope.stopChild(actorRef);
1340
- });
1341
- }
1342
- /**
1343
- * Stops a child actor.
1344
- *
1345
- * @param actorRef The actor to stop.
1346
- */
1347
- function stopChild(actorRef) {
1348
- function stop(_args, _params) {
1349
- }
1350
- stop.type = 'xstate.stopChild';
1351
- stop.actorRef = actorRef;
1352
- stop.resolve = resolveStop;
1353
- stop.execute = executeStop;
1354
- return stop;
1355
- }
1356
-
1357
- /**
1358
- * Stops a child actor.
1359
- *
1360
- * @deprecated Use `stopChild(...)` instead
1361
- * @alias
1362
- */
1363
- const stop = stopChild;
1364
-
1365
- function checkStateIn(snapshot, _, {
1366
- stateValue
1367
- }) {
1368
- if (typeof stateValue === 'string' && isStateId(stateValue)) {
1369
- const target = snapshot.machine.getStateNodeById(stateValue);
1370
- return snapshot._nodes.some(sn => sn === target);
1371
- }
1372
- return snapshot.matches(stateValue);
1373
- }
1374
- function stateIn(stateValue) {
1375
- function stateIn() {
1376
- return false;
1377
- }
1378
- stateIn.check = checkStateIn;
1379
- stateIn.stateValue = stateValue;
1380
- return stateIn;
1381
- }
1382
- function checkNot(snapshot, {
1383
- context,
1384
- event
1385
- }, {
1386
- guards
1387
- }) {
1388
- return !evaluateGuard(guards[0], context, event, snapshot);
1389
- }
1390
-
1391
- /**
1392
- * Higher-order guard that evaluates to `true` if the `guard` passed to it
1393
- * evaluates to `false`.
1394
- *
1395
- * @category Guards
1396
- * @example
1397
- *
1398
- * ```ts
1399
- * import { setup, not } from 'xstate';
1400
- *
1401
- * const machine = setup({
1402
- * guards: {
1403
- * someNamedGuard: () => false
1404
- * }
1405
- * }).createMachine({
1406
- * on: {
1407
- * someEvent: {
1408
- * guard: not('someNamedGuard'),
1409
- * actions: () => {
1410
- * // will be executed if guard in `not(...)`
1411
- * // evaluates to `false`
1412
- * }
1413
- * }
1414
- * }
1415
- * });
1416
- * ```
1417
- *
1418
- * @returns A guard
1419
- */
1420
- function not(guard) {
1421
- function not(_args, _params) {
1422
- return false;
1423
- }
1424
- not.check = checkNot;
1425
- not.guards = [guard];
1426
- return not;
1427
- }
1428
- function checkAnd(snapshot, {
1429
- context,
1430
- event
1431
- }, {
1432
- guards
1433
- }) {
1434
- return guards.every(guard => evaluateGuard(guard, context, event, snapshot));
1435
- }
1436
-
1437
- /**
1438
- * Higher-order guard that evaluates to `true` if all `guards` passed to it
1439
- * evaluate to `true`.
1440
- *
1441
- * @category Guards
1442
- * @example
1443
- *
1444
- * ```ts
1445
- * import { setup, and } from 'xstate';
1446
- *
1447
- * const machine = setup({
1448
- * guards: {
1449
- * someNamedGuard: () => true
1450
- * }
1451
- * }).createMachine({
1452
- * on: {
1453
- * someEvent: {
1454
- * guard: and([({ context }) => context.value > 0, 'someNamedGuard']),
1455
- * actions: () => {
1456
- * // will be executed if all guards in `and(...)`
1457
- * // evaluate to true
1458
- * }
1459
- * }
1460
- * }
1461
- * });
1462
- * ```
1463
- *
1464
- * @returns A guard action object
1465
- */
1466
- function and(guards) {
1467
- function and(_args, _params) {
1468
- return false;
1469
- }
1470
- and.check = checkAnd;
1471
- and.guards = guards;
1472
- return and;
1473
- }
1474
- function checkOr(snapshot, {
1475
- context,
1476
- event
1477
- }, {
1478
- guards
1479
- }) {
1480
- return guards.some(guard => evaluateGuard(guard, context, event, snapshot));
1481
- }
1482
-
1483
- /**
1484
- * Higher-order guard that evaluates to `true` if any of the `guards` passed to
1485
- * it evaluate to `true`.
1486
- *
1487
- * @category Guards
1488
- * @example
1489
- *
1490
- * ```ts
1491
- * import { setup, or } from 'xstate';
1492
- *
1493
- * const machine = setup({
1494
- * guards: {
1495
- * someNamedGuard: () => true
1496
- * }
1497
- * }).createMachine({
1498
- * on: {
1499
- * someEvent: {
1500
- * guard: or([({ context }) => context.value > 0, 'someNamedGuard']),
1501
- * actions: () => {
1502
- * // will be executed if any of the guards in `or(...)`
1503
- * // evaluate to true
1504
- * }
1505
- * }
1506
- * }
1507
- * });
1508
- * ```
1509
- *
1510
- * @returns A guard action object
1511
- */
1512
- function or(guards) {
1513
- function or(_args, _params) {
1514
- return false;
1515
- }
1516
- or.check = checkOr;
1517
- or.guards = guards;
1518
- return or;
1519
- }
1520
-
1521
- // TODO: throw on cycles (depth check should be enough)
1522
- function evaluateGuard(guard, context, event, snapshot) {
1523
- const {
1524
- machine
1525
- } = snapshot;
1526
- const isInline = typeof guard === 'function';
1527
- const resolved = isInline ? guard : machine.implementations.guards[typeof guard === 'string' ? guard : guard.type];
1528
- if (!isInline && !resolved) {
1529
- throw new Error(`Guard '${typeof guard === 'string' ? guard : guard.type}' is not implemented.'.`);
1530
- }
1531
- if (typeof resolved !== 'function') {
1532
- return evaluateGuard(resolved, context, event, snapshot);
1533
- }
1534
- const guardArgs = {
1535
- context,
1536
- event
1537
- };
1538
- const guardParams = isInline || typeof guard === 'string' ? undefined : 'params' in guard ? typeof guard.params === 'function' ? guard.params({
1539
- context,
1540
- event
1541
- }) : guard.params : undefined;
1542
- if (!('check' in resolved)) {
1543
- // the existing type of `.guards` assumes non-nullable `TExpressionGuard`
1544
- // inline guards expect `TExpressionGuard` to be set to `undefined`
1545
- // it's fine to cast this here, our logic makes sure that we call those 2 "variants" correctly
1546
- return resolved(guardArgs, guardParams);
1547
- }
1548
- const builtinGuard = resolved;
1549
- return builtinGuard.check(snapshot, guardArgs, resolved // this holds all params
1550
- );
1551
- }
1552
-
1553
- function isAtomicStateNode(stateNode) {
1554
- return stateNode.type === 'atomic' || stateNode.type === 'final';
1555
- }
1556
- function getChildren(stateNode) {
1557
- return Object.values(stateNode.states).filter(sn => sn.type !== 'history');
1558
- }
1559
- function getProperAncestors(stateNode, toStateNode) {
1560
- const ancestors = [];
1561
- if (toStateNode === stateNode) {
1562
- return ancestors;
1563
- }
1564
-
1565
- // add all ancestors
1566
- let m = stateNode.parent;
1567
- while (m && m !== toStateNode) {
1568
- ancestors.push(m);
1569
- m = m.parent;
1570
- }
1571
- return ancestors;
1572
- }
1573
- function getAllStateNodes(stateNodes) {
1574
- const nodeSet = new Set(stateNodes);
1575
- const adjList = getAdjList(nodeSet);
1576
-
1577
- // add descendants
1578
- for (const s of nodeSet) {
1579
- // if previously active, add existing child nodes
1580
- if (s.type === 'compound' && (!adjList.get(s) || !adjList.get(s).length)) {
1581
- getInitialStateNodesWithTheirAncestors(s).forEach(sn => nodeSet.add(sn));
1582
- } else {
1583
- if (s.type === 'parallel') {
1584
- for (const child of getChildren(s)) {
1585
- if (child.type === 'history') {
1586
- continue;
1587
- }
1588
- if (!nodeSet.has(child)) {
1589
- const initialStates = getInitialStateNodesWithTheirAncestors(child);
1590
- for (const initialStateNode of initialStates) {
1591
- nodeSet.add(initialStateNode);
1592
- }
1593
- }
1594
- }
1595
- }
1596
- }
1597
- }
1598
-
1599
- // add all ancestors
1600
- for (const s of nodeSet) {
1601
- let m = s.parent;
1602
- while (m) {
1603
- nodeSet.add(m);
1604
- m = m.parent;
1605
- }
1606
- }
1607
- return nodeSet;
1608
- }
1609
- function getValueFromAdj(baseNode, adjList) {
1610
- const childStateNodes = adjList.get(baseNode);
1611
- if (!childStateNodes) {
1612
- return {}; // todo: fix?
1613
- }
1614
- if (baseNode.type === 'compound') {
1615
- const childStateNode = childStateNodes[0];
1616
- if (childStateNode) {
1617
- if (isAtomicStateNode(childStateNode)) {
1618
- return childStateNode.key;
1619
- }
1620
- } else {
1621
- return {};
1622
- }
1623
- }
1624
- const stateValue = {};
1625
- for (const childStateNode of childStateNodes) {
1626
- stateValue[childStateNode.key] = getValueFromAdj(childStateNode, adjList);
1627
- }
1628
- return stateValue;
1629
- }
1630
- function getAdjList(stateNodes) {
1631
- const adjList = new Map();
1632
- for (const s of stateNodes) {
1633
- if (!adjList.has(s)) {
1634
- adjList.set(s, []);
1635
- }
1636
- if (s.parent) {
1637
- if (!adjList.has(s.parent)) {
1638
- adjList.set(s.parent, []);
1639
- }
1640
- adjList.get(s.parent).push(s);
1641
- }
1642
- }
1643
- return adjList;
1644
- }
1645
- function getStateValue(rootNode, stateNodes) {
1646
- const config = getAllStateNodes(stateNodes);
1647
- return getValueFromAdj(rootNode, getAdjList(config));
1648
- }
1649
- function isInFinalState(stateNodeSet, stateNode) {
1650
- if (stateNode.type === 'compound') {
1651
- return getChildren(stateNode).some(s => s.type === 'final' && stateNodeSet.has(s));
1652
- }
1653
- if (stateNode.type === 'parallel') {
1654
- return getChildren(stateNode).every(sn => isInFinalState(stateNodeSet, sn));
1655
- }
1656
- return stateNode.type === 'final';
1657
- }
1658
- const isStateId = str => str[0] === STATE_IDENTIFIER;
1659
- function getCandidates(stateNode, receivedEventType) {
1660
- const candidates = stateNode.transitions.get(receivedEventType) || [...stateNode.transitions.keys()].filter(eventDescriptor => matchesEventDescriptor(receivedEventType, eventDescriptor)).sort((a, b) => b.length - a.length).flatMap(key => stateNode.transitions.get(key));
1661
- return candidates;
1662
- }
1663
-
1664
- /** All delayed transitions from the config. */
1665
- function getDelayedTransitions(stateNode) {
1666
- const afterConfig = stateNode.config.after;
1667
- if (!afterConfig) {
1668
- return [];
1669
- }
1670
- const mutateEntryExit = delay => {
1671
- const afterEvent = createAfterEvent(delay, stateNode.id);
1672
- const eventType = afterEvent.type;
1673
- stateNode.entry.push(raise(afterEvent, {
1674
- id: eventType,
1675
- delay
1676
- }));
1677
- stateNode.exit.push(cancel(eventType));
1678
- return eventType;
1679
- };
1680
- const delayedTransitions = Object.keys(afterConfig).flatMap(delay => {
1681
- const configTransition = afterConfig[delay];
1682
- const resolvedTransition = typeof configTransition === 'string' ? {
1683
- target: configTransition
1684
- } : configTransition;
1685
- const resolvedDelay = Number.isNaN(+delay) ? delay : +delay;
1686
- const eventType = mutateEntryExit(resolvedDelay);
1687
- return toArray(resolvedTransition).map(transition => ({
1688
- ...transition,
1689
- event: eventType,
1690
- delay: resolvedDelay
1691
- }));
1692
- });
1693
- return delayedTransitions.map(delayedTransition => {
1694
- const {
1695
- delay
1696
- } = delayedTransition;
1697
- return {
1698
- ...formatTransition(stateNode, delayedTransition.event, delayedTransition),
1699
- delay
1700
- };
1701
- });
1702
- }
1703
- function formatTransition(stateNode, descriptor, transitionConfig) {
1704
- const normalizedTarget = normalizeTarget(transitionConfig.target);
1705
- const reenter = transitionConfig.reenter ?? false;
1706
- const target = resolveTarget(stateNode, normalizedTarget);
1707
- const transition = {
1708
- ...transitionConfig,
1709
- actions: toArray(transitionConfig.actions),
1710
- guard: transitionConfig.guard,
1711
- target,
1712
- source: stateNode,
1713
- reenter,
1714
- eventType: descriptor,
1715
- toJSON: () => ({
1716
- ...transition,
1717
- source: `#${stateNode.id}`,
1718
- target: target ? target.map(t => `#${t.id}`) : undefined
1719
- })
1720
- };
1721
- return transition;
1722
- }
1723
- function formatTransitions(stateNode) {
1724
- const transitions = new Map();
1725
- if (stateNode.config.on) {
1726
- for (const descriptor of Object.keys(stateNode.config.on)) {
1727
- if (descriptor === NULL_EVENT) {
1728
- throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');
1729
- }
1730
- const transitionsConfig = stateNode.config.on[descriptor];
1731
- transitions.set(descriptor, toTransitionConfigArray(transitionsConfig).map(t => formatTransition(stateNode, descriptor, t)));
1732
- }
1733
- }
1734
- if (stateNode.config.onDone) {
1735
- const descriptor = `xstate.done.state.${stateNode.id}`;
1736
- transitions.set(descriptor, toTransitionConfigArray(stateNode.config.onDone).map(t => formatTransition(stateNode, descriptor, t)));
1737
- }
1738
- for (const invokeDef of stateNode.invoke) {
1739
- if (invokeDef.onDone) {
1740
- const descriptor = `xstate.done.actor.${invokeDef.id}`;
1741
- transitions.set(descriptor, toTransitionConfigArray(invokeDef.onDone).map(t => formatTransition(stateNode, descriptor, t)));
1742
- }
1743
- if (invokeDef.onError) {
1744
- const descriptor = `xstate.error.actor.${invokeDef.id}`;
1745
- transitions.set(descriptor, toTransitionConfigArray(invokeDef.onError).map(t => formatTransition(stateNode, descriptor, t)));
1746
- }
1747
- if (invokeDef.onSnapshot) {
1748
- const descriptor = `xstate.snapshot.${invokeDef.id}`;
1749
- transitions.set(descriptor, toTransitionConfigArray(invokeDef.onSnapshot).map(t => formatTransition(stateNode, descriptor, t)));
1750
- }
1751
- }
1752
- for (const delayedTransition of stateNode.after) {
1753
- let existing = transitions.get(delayedTransition.eventType);
1754
- if (!existing) {
1755
- existing = [];
1756
- transitions.set(delayedTransition.eventType, existing);
1757
- }
1758
- existing.push(delayedTransition);
1759
- }
1760
- return transitions;
1761
- }
1762
-
1763
- /**
1764
- * Collects route transitions from all descendants with explicit IDs. Called
1765
- * once on the root node to avoid O(N²) repeated traversals.
1766
- */
1767
- function formatRouteTransitions(rootStateNode) {
1768
- const routeTransitions = [];
1769
- const collectRoutes = states => {
1770
- Object.values(states).forEach(sn => {
1771
- if (sn.config.route && sn.config.id) {
1772
- const routeId = sn.config.id;
1773
- const userGuard = sn.config.route.guard;
1774
- const routeMatches = ({
1775
- event
1776
- }) => event.to === `#${routeId}`;
1777
- const transition = {
1778
- ...sn.config.route,
1779
- guard: userGuard ? and([routeMatches, userGuard]) : routeMatches,
1780
- target: `#${routeId}`
1781
- };
1782
- routeTransitions.push(formatTransition(rootStateNode, 'xstate.route', transition));
1783
- }
1784
- if (sn.states) {
1785
- collectRoutes(sn.states);
1786
- }
1787
- });
1788
- };
1789
- collectRoutes(rootStateNode.states);
1790
- if (routeTransitions.length > 0) {
1791
- rootStateNode.transitions.set('xstate.route', routeTransitions);
1792
- }
1793
- }
1794
- function formatInitialTransition(stateNode, _target) {
1795
- const resolvedTarget = typeof _target === 'string' ? stateNode.states[_target] : _target ? stateNode.states[_target.target] : undefined;
1796
- if (!resolvedTarget && _target) {
1797
- throw new Error(
1798
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions, @typescript-eslint/no-base-to-string
1799
- `Initial state node "${_target}" not found on parent state node #${stateNode.id}`);
1800
- }
1801
- const transition = {
1802
- source: stateNode,
1803
- actions: !_target || typeof _target === 'string' ? [] : toArray(_target.actions),
1804
- eventType: null,
1805
- reenter: false,
1806
- target: resolvedTarget ? [resolvedTarget] : [],
1807
- toJSON: () => ({
1808
- ...transition,
1809
- source: `#${stateNode.id}`,
1810
- target: resolvedTarget ? [`#${resolvedTarget.id}`] : []
1811
- })
1812
- };
1813
- return transition;
1814
- }
1815
- function resolveTarget(stateNode, targets) {
1816
- if (targets === undefined) {
1817
- // an undefined target signals that the state node should not transition from that state when receiving that event
1818
- return undefined;
1819
- }
1820
- return targets.map(target => {
1821
- if (typeof target !== 'string') {
1822
- return target;
1823
- }
1824
- if (isStateId(target)) {
1825
- return stateNode.machine.getStateNodeById(target);
1826
- }
1827
- const isInternalTarget = target[0] === STATE_DELIMITER;
1828
- // If internal target is defined on machine,
1829
- // do not include machine key on target
1830
- if (isInternalTarget && !stateNode.parent) {
1831
- return getStateNodeByPath(stateNode, target.slice(1));
1832
- }
1833
- const resolvedTarget = isInternalTarget ? stateNode.key + target : target;
1834
- if (stateNode.parent) {
1835
- try {
1836
- const targetStateNode = getStateNodeByPath(stateNode.parent, resolvedTarget);
1837
- return targetStateNode;
1838
- } catch (err) {
1839
- throw new Error(`Invalid transition definition for state node '${stateNode.id}':\n${err.message}`);
1840
- }
1841
- } else {
1842
- throw new Error(`Invalid target: "${target}" is not a valid target from the root node. Did you mean ".${target}"?`);
1843
- }
1844
- });
1845
- }
1846
- function resolveHistoryDefaultTransition(stateNode) {
1847
- const normalizedTarget = normalizeTarget(stateNode.config.target);
1848
- if (!normalizedTarget) {
1849
- return stateNode.parent.initial;
1850
- }
1851
- return {
1852
- target: normalizedTarget.map(t => typeof t === 'string' ? getStateNodeByPath(stateNode.parent, t) : t)
1853
- };
1854
- }
1855
- function isHistoryNode(stateNode) {
1856
- return stateNode.type === 'history';
1857
- }
1858
- function getInitialStateNodesWithTheirAncestors(stateNode) {
1859
- const states = getInitialStateNodes(stateNode);
1860
- for (const initialState of states) {
1861
- for (const ancestor of getProperAncestors(initialState, stateNode)) {
1862
- states.add(ancestor);
1863
- }
1864
- }
1865
- return states;
1866
- }
1867
- function getInitialStateNodes(stateNode) {
1868
- const set = new Set();
1869
- function iter(descStateNode) {
1870
- if (set.has(descStateNode)) {
1871
- return;
1872
- }
1873
- set.add(descStateNode);
1874
- if (descStateNode.type === 'compound') {
1875
- iter(descStateNode.initial.target[0]);
1876
- } else if (descStateNode.type === 'parallel') {
1877
- for (const child of getChildren(descStateNode)) {
1878
- iter(child);
1879
- }
1880
- }
1881
- }
1882
- iter(stateNode);
1883
- return set;
1884
- }
1885
- /** Returns the child state node from its relative `stateKey`, or throws. */
1886
- function getStateNode(stateNode, stateKey) {
1887
- if (isStateId(stateKey)) {
1888
- return stateNode.machine.getStateNodeById(stateKey);
1889
- }
1890
- if (!stateNode.states) {
1891
- throw new Error(`Unable to retrieve child state '${stateKey}' from '${stateNode.id}'; no child states exist.`);
1892
- }
1893
- const result = stateNode.states[stateKey];
1894
- if (!result) {
1895
- throw new Error(`Child state '${stateKey}' does not exist on '${stateNode.id}'`);
1896
- }
1897
- return result;
1898
- }
1899
-
1900
- /**
1901
- * Returns the relative state node from the given `statePath`, or throws.
1902
- *
1903
- * @param statePath The string or string array relative path to the state node.
1904
- */
1905
- function getStateNodeByPath(stateNode, statePath) {
1906
- if (typeof statePath === 'string' && isStateId(statePath)) {
1907
- try {
1908
- return stateNode.machine.getStateNodeById(statePath);
1909
- } catch {
1910
- // try individual paths
1911
- // throw e;
1912
- }
1913
- }
1914
- const arrayStatePath = toStatePath(statePath).slice();
1915
- let currentStateNode = stateNode;
1916
- while (arrayStatePath.length) {
1917
- const key = arrayStatePath.shift();
1918
- if (!key.length) {
1919
- break;
1920
- }
1921
- currentStateNode = getStateNode(currentStateNode, key);
1922
- }
1923
- return currentStateNode;
1924
- }
1925
-
1926
- /**
1927
- * Returns the state nodes represented by the current state value.
1928
- *
1929
- * @param stateValue The state value or State instance
1930
- */
1931
- function getStateNodes(stateNode, stateValue) {
1932
- if (typeof stateValue === 'string') {
1933
- const childStateNode = stateNode.states[stateValue];
1934
- if (!childStateNode) {
1935
- throw new Error(`State '${stateValue}' does not exist on '${stateNode.id}'`);
1936
- }
1937
- return [stateNode, childStateNode];
1938
- }
1939
- const childStateKeys = Object.keys(stateValue);
1940
- const childStateNodes = childStateKeys.map(subStateKey => getStateNode(stateNode, subStateKey)).filter(Boolean);
1941
- return [stateNode.machine.root, stateNode].concat(childStateNodes, childStateKeys.reduce((allSubStateNodes, subStateKey) => {
1942
- const subStateNode = getStateNode(stateNode, subStateKey);
1943
- if (!subStateNode) {
1944
- return allSubStateNodes;
1945
- }
1946
- const subStateNodes = getStateNodes(subStateNode, stateValue[subStateKey]);
1947
- return allSubStateNodes.concat(subStateNodes);
1948
- }, []));
1949
- }
1950
- function transitionAtomicNode(stateNode, stateValue, snapshot, event) {
1951
- const childStateNode = getStateNode(stateNode, stateValue);
1952
- const next = childStateNode.next(snapshot, event);
1953
- if (!next || !next.length) {
1954
- return stateNode.next(snapshot, event);
1955
- }
1956
- return next;
1957
- }
1958
- function transitionCompoundNode(stateNode, stateValue, snapshot, event) {
1959
- const subStateKeys = Object.keys(stateValue);
1960
- const childStateNode = getStateNode(stateNode, subStateKeys[0]);
1961
- const next = transitionNode(childStateNode, stateValue[subStateKeys[0]], snapshot, event);
1962
- if (!next || !next.length) {
1963
- return stateNode.next(snapshot, event);
1964
- }
1965
- return next;
1966
- }
1967
- function transitionParallelNode(stateNode, stateValue, snapshot, event) {
1968
- const allInnerTransitions = [];
1969
- for (const subStateKey of Object.keys(stateValue)) {
1970
- const subStateValue = stateValue[subStateKey];
1971
- if (!subStateValue) {
1972
- continue;
1973
- }
1974
- const subStateNode = getStateNode(stateNode, subStateKey);
1975
- const innerTransitions = transitionNode(subStateNode, subStateValue, snapshot, event);
1976
- if (innerTransitions) {
1977
- allInnerTransitions.push(...innerTransitions);
1978
- }
1979
- }
1980
- if (!allInnerTransitions.length) {
1981
- return stateNode.next(snapshot, event);
1982
- }
1983
- return allInnerTransitions;
1984
- }
1985
- function transitionNode(stateNode, stateValue, snapshot, event) {
1986
- // leaf node
1987
- if (typeof stateValue === 'string') {
1988
- return transitionAtomicNode(stateNode, stateValue, snapshot, event);
1989
- }
1990
-
1991
- // compound node
1992
- if (Object.keys(stateValue).length === 1) {
1993
- return transitionCompoundNode(stateNode, stateValue, snapshot, event);
1994
- }
1995
-
1996
- // parallel node
1997
- return transitionParallelNode(stateNode, stateValue, snapshot, event);
1998
- }
1999
- function getHistoryNodes(stateNode) {
2000
- return Object.keys(stateNode.states).map(key => stateNode.states[key]).filter(sn => sn.type === 'history');
2001
- }
2002
- function isDescendant(childStateNode, parentStateNode) {
2003
- let marker = childStateNode;
2004
- while (marker.parent && marker.parent !== parentStateNode) {
2005
- marker = marker.parent;
2006
- }
2007
- return marker.parent === parentStateNode;
2008
- }
2009
- function hasIntersection(s1, s2) {
2010
- const set1 = new Set(s1);
2011
- const set2 = new Set(s2);
2012
- for (const item of set1) {
2013
- if (set2.has(item)) {
2014
- return true;
2015
- }
2016
- }
2017
- for (const item of set2) {
2018
- if (set1.has(item)) {
2019
- return true;
2020
- }
2021
- }
2022
- return false;
2023
- }
2024
- function removeConflictingTransitions(enabledTransitions, stateNodeSet, historyValue) {
2025
- const filteredTransitions = new Set();
2026
- for (const t1 of enabledTransitions) {
2027
- let t1Preempted = false;
2028
- const transitionsToRemove = new Set();
2029
- for (const t2 of filteredTransitions) {
2030
- if (hasIntersection(computeExitSet([t1], stateNodeSet, historyValue), computeExitSet([t2], stateNodeSet, historyValue))) {
2031
- if (isDescendant(t1.source, t2.source)) {
2032
- transitionsToRemove.add(t2);
2033
- } else {
2034
- t1Preempted = true;
2035
- break;
2036
- }
2037
- }
2038
- }
2039
- if (!t1Preempted) {
2040
- for (const t3 of transitionsToRemove) {
2041
- filteredTransitions.delete(t3);
2042
- }
2043
- filteredTransitions.add(t1);
2044
- }
2045
- }
2046
- return Array.from(filteredTransitions);
2047
- }
2048
- function findLeastCommonAncestor(stateNodes) {
2049
- const [head, ...tail] = stateNodes;
2050
- for (const ancestor of getProperAncestors(head, undefined)) {
2051
- if (tail.every(sn => isDescendant(sn, ancestor))) {
2052
- return ancestor;
2053
- }
2054
- }
2055
- }
2056
- function getEffectiveTargetStates(transition, historyValue) {
2057
- if (!transition.target) {
2058
- return [];
2059
- }
2060
- const targets = new Set();
2061
- for (const targetNode of transition.target) {
2062
- if (isHistoryNode(targetNode)) {
2063
- if (historyValue[targetNode.id]) {
2064
- for (const node of historyValue[targetNode.id]) {
2065
- targets.add(node);
2066
- }
2067
- } else {
2068
- for (const node of getEffectiveTargetStates(resolveHistoryDefaultTransition(targetNode), historyValue)) {
2069
- targets.add(node);
2070
- }
2071
- }
2072
- } else {
2073
- targets.add(targetNode);
2074
- }
2075
- }
2076
- return [...targets];
2077
- }
2078
- function getTransitionDomain(transition, historyValue) {
2079
- const targetStates = getEffectiveTargetStates(transition, historyValue);
2080
- if (!targetStates) {
2081
- return;
2082
- }
2083
- if (!transition.reenter && targetStates.every(target => target === transition.source || isDescendant(target, transition.source))) {
2084
- return transition.source;
2085
- }
2086
- const lca = findLeastCommonAncestor(targetStates.concat(transition.source));
2087
- if (lca) {
2088
- return lca;
2089
- }
2090
-
2091
- // at this point we know that it's a root transition since LCA couldn't be found
2092
- if (transition.reenter) {
2093
- return;
2094
- }
2095
- return transition.source.machine.root;
2096
- }
2097
- function computeExitSet(transitions, stateNodeSet, historyValue) {
2098
- const statesToExit = new Set();
2099
- for (const t of transitions) {
2100
- if (t.target?.length) {
2101
- const domain = getTransitionDomain(t, historyValue);
2102
- if (t.reenter && t.source === domain) {
2103
- statesToExit.add(domain);
2104
- }
2105
- for (const stateNode of stateNodeSet) {
2106
- if (isDescendant(stateNode, domain)) {
2107
- statesToExit.add(stateNode);
2108
- }
2109
- }
2110
- }
2111
- }
2112
- return [...statesToExit];
2113
- }
2114
- function areStateNodeCollectionsEqual(prevStateNodes, nextStateNodeSet) {
2115
- if (prevStateNodes.length !== nextStateNodeSet.size) {
2116
- return false;
2117
- }
2118
- for (const node of prevStateNodes) {
2119
- if (!nextStateNodeSet.has(node)) {
2120
- return false;
2121
- }
2122
- }
2123
- return true;
2124
- }
2125
- function initialMicrostep(root, preInitialState, actorScope, initEvent, internalQueue) {
2126
- return microstep([{
2127
- target: [...getInitialStateNodes(root)],
2128
- source: root,
2129
- reenter: true,
2130
- actions: [],
2131
- eventType: null,
2132
- toJSON: null
2133
- }], preInitialState, actorScope, initEvent, true, internalQueue);
2134
- }
2135
-
2136
- /** https://www.w3.org/TR/scxml/#microstepProcedure */
2137
- function microstep(transitions, currentSnapshot, actorScope, event, isInitial, internalQueue) {
2138
- const actions = [];
2139
- if (!transitions.length) {
2140
- return [currentSnapshot, actions];
2141
- }
2142
- const originalExecutor = actorScope.actionExecutor;
2143
- actorScope.actionExecutor = action => {
2144
- actions.push(action);
2145
- originalExecutor(action);
2146
- };
2147
- try {
2148
- const mutStateNodeSet = new Set(currentSnapshot._nodes);
2149
- let historyValue = currentSnapshot.historyValue;
2150
- const filteredTransitions = removeConflictingTransitions(transitions, mutStateNodeSet, historyValue);
2151
- let nextState = currentSnapshot;
2152
-
2153
- // Exit states
2154
- if (!isInitial) {
2155
- [nextState, historyValue] = exitStates(nextState, event, actorScope, filteredTransitions, mutStateNodeSet, historyValue, internalQueue, actorScope.actionExecutor);
2156
- }
2157
-
2158
- // Execute transition content
2159
- nextState = resolveActionsAndContext(nextState, event, actorScope, filteredTransitions.flatMap(t => t.actions), internalQueue, undefined);
2160
-
2161
- // Enter states
2162
- nextState = enterStates(nextState, event, actorScope, filteredTransitions, mutStateNodeSet, internalQueue, historyValue, isInitial);
2163
- const nextStateNodes = [...mutStateNodeSet];
2164
- if (nextState.status === 'done') {
2165
- nextState = resolveActionsAndContext(nextState, event, actorScope, nextStateNodes.sort((a, b) => b.order - a.order).flatMap(state => state.exit), internalQueue, undefined);
2166
- }
2167
-
2168
- // eslint-disable-next-line no-useless-catch
2169
- try {
2170
- if (historyValue === currentSnapshot.historyValue && areStateNodeCollectionsEqual(currentSnapshot._nodes, mutStateNodeSet)) {
2171
- return [nextState, actions];
2172
- }
2173
- return [cloneMachineSnapshot(nextState, {
2174
- _nodes: nextStateNodes,
2175
- historyValue
2176
- }), actions];
2177
- } catch (e) {
2178
- // TODO: Refactor this once proper error handling is implemented.
2179
- // See https://github.com/statelyai/rfcs/pull/4
2180
- throw e;
2181
- }
2182
- } finally {
2183
- actorScope.actionExecutor = originalExecutor;
2184
- }
2185
- }
2186
- function getMachineOutput(snapshot, event, actorScope, rootNode, rootCompletionNode) {
2187
- if (rootNode.output === undefined) {
2188
- return;
2189
- }
2190
- const doneStateEvent = createDoneStateEvent(rootCompletionNode.id, rootCompletionNode.output !== undefined && rootCompletionNode.parent ? resolveOutput(rootCompletionNode.output, snapshot.context, event, actorScope.self) : undefined);
2191
- return resolveOutput(rootNode.output, snapshot.context, doneStateEvent, actorScope.self);
2192
- }
2193
- function enterStates(currentSnapshot, event, actorScope, filteredTransitions, mutStateNodeSet, internalQueue, historyValue, isInitial) {
2194
- let nextSnapshot = currentSnapshot;
2195
- const statesToEnter = new Set();
2196
- // those are states that were directly targeted or indirectly targeted by the explicit target
2197
- // in other words, those are states for which initial actions should be executed
2198
- // when we target `#deep_child` initial actions of its ancestors shouldn't be executed
2199
- const statesForDefaultEntry = new Set();
2200
- computeEntrySet(filteredTransitions, historyValue, statesForDefaultEntry, statesToEnter);
2201
-
2202
- // In the initial state, the root state node is "entered".
2203
- if (isInitial) {
2204
- statesForDefaultEntry.add(currentSnapshot.machine.root);
2205
- }
2206
- const completedNodes = new Set();
2207
- for (const stateNodeToEnter of [...statesToEnter].sort((a, b) => a.order - b.order)) {
2208
- mutStateNodeSet.add(stateNodeToEnter);
2209
- const actions = [];
2210
-
2211
- // Add entry actions
2212
- actions.push(...stateNodeToEnter.entry);
2213
- for (const invokeDef of stateNodeToEnter.invoke) {
2214
- actions.push(spawnChild(invokeDef.src, {
2215
- ...invokeDef,
2216
- syncSnapshot: !!invokeDef.onSnapshot
2217
- }));
2218
- }
2219
- if (statesForDefaultEntry.has(stateNodeToEnter)) {
2220
- const initialActions = stateNodeToEnter.initial.actions;
2221
- actions.push(...initialActions);
2222
- }
2223
- nextSnapshot = resolveActionsAndContext(nextSnapshot, event, actorScope, actions, internalQueue, stateNodeToEnter.invoke.map(invokeDef => invokeDef.id));
2224
- if (stateNodeToEnter.type === 'final') {
2225
- const parent = stateNodeToEnter.parent;
2226
- let ancestorMarker = parent?.type === 'parallel' ? parent : parent?.parent;
2227
- let rootCompletionNode = ancestorMarker || stateNodeToEnter;
2228
- if (parent?.type === 'compound') {
2229
- internalQueue.push(createDoneStateEvent(parent.id, stateNodeToEnter.output !== undefined ? resolveOutput(stateNodeToEnter.output, nextSnapshot.context, event, actorScope.self) : undefined));
2230
- }
2231
- while (ancestorMarker?.type === 'parallel' && !completedNodes.has(ancestorMarker) && isInFinalState(mutStateNodeSet, ancestorMarker)) {
2232
- completedNodes.add(ancestorMarker);
2233
- internalQueue.push(createDoneStateEvent(ancestorMarker.id));
2234
- rootCompletionNode = ancestorMarker;
2235
- ancestorMarker = ancestorMarker.parent;
2236
- }
2237
- if (ancestorMarker) {
2238
- continue;
2239
- }
2240
- nextSnapshot = cloneMachineSnapshot(nextSnapshot, {
2241
- status: 'done',
2242
- output: getMachineOutput(nextSnapshot, event, actorScope, nextSnapshot.machine.root, rootCompletionNode)
2243
- });
2244
- }
2245
- }
2246
- return nextSnapshot;
2247
- }
2248
- function computeEntrySet(transitions, historyValue, statesForDefaultEntry, statesToEnter) {
2249
- for (const t of transitions) {
2250
- const domain = getTransitionDomain(t, historyValue);
2251
- for (const s of t.target || []) {
2252
- if (!isHistoryNode(s) && (
2253
- // if the target is different than the source then it will *definitely* be entered
2254
- t.source !== s ||
2255
- // we know that the domain can't lie within the source
2256
- // if it's different than the source then it's outside of it and it means that the target has to be entered as well
2257
- t.source !== domain ||
2258
- // reentering transitions always enter the target, even if it's the source itself
2259
- t.reenter)) {
2260
- statesToEnter.add(s);
2261
- statesForDefaultEntry.add(s);
2262
- }
2263
- addDescendantStatesToEnter(s, historyValue, statesForDefaultEntry, statesToEnter);
2264
- }
2265
- const targetStates = getEffectiveTargetStates(t, historyValue);
2266
- for (const s of targetStates) {
2267
- const ancestors = getProperAncestors(s, domain);
2268
- if (domain?.type === 'parallel') {
2269
- ancestors.push(domain);
2270
- }
2271
- addAncestorStatesToEnter(statesToEnter, historyValue, statesForDefaultEntry, ancestors, !t.source.parent && t.reenter ? undefined : domain);
2272
- }
2273
- }
2274
- }
2275
- function addDescendantStatesToEnter(stateNode, historyValue, statesForDefaultEntry, statesToEnter) {
2276
- if (isHistoryNode(stateNode)) {
2277
- if (historyValue[stateNode.id]) {
2278
- const historyStateNodes = historyValue[stateNode.id];
2279
- for (const s of historyStateNodes) {
2280
- statesToEnter.add(s);
2281
- addDescendantStatesToEnter(s, historyValue, statesForDefaultEntry, statesToEnter);
2282
- }
2283
- for (const s of historyStateNodes) {
2284
- addProperAncestorStatesToEnter(s, stateNode.parent, statesToEnter, historyValue, statesForDefaultEntry);
2285
- }
2286
- } else {
2287
- const historyDefaultTransition = resolveHistoryDefaultTransition(stateNode);
2288
- for (const s of historyDefaultTransition.target) {
2289
- statesToEnter.add(s);
2290
- if (historyDefaultTransition === stateNode.parent?.initial) {
2291
- statesForDefaultEntry.add(stateNode.parent);
2292
- }
2293
- addDescendantStatesToEnter(s, historyValue, statesForDefaultEntry, statesToEnter);
2294
- }
2295
- for (const s of historyDefaultTransition.target) {
2296
- addProperAncestorStatesToEnter(s, stateNode.parent, statesToEnter, historyValue, statesForDefaultEntry);
2297
- }
2298
- }
2299
- } else {
2300
- if (stateNode.type === 'compound') {
2301
- const [initialState] = stateNode.initial.target;
2302
- if (!isHistoryNode(initialState)) {
2303
- statesToEnter.add(initialState);
2304
- statesForDefaultEntry.add(initialState);
2305
- }
2306
- addDescendantStatesToEnter(initialState, historyValue, statesForDefaultEntry, statesToEnter);
2307
- addProperAncestorStatesToEnter(initialState, stateNode, statesToEnter, historyValue, statesForDefaultEntry);
2308
- } else {
2309
- if (stateNode.type === 'parallel') {
2310
- for (const child of getChildren(stateNode).filter(sn => !isHistoryNode(sn))) {
2311
- if (![...statesToEnter].some(s => isDescendant(s, child))) {
2312
- if (!isHistoryNode(child)) {
2313
- statesToEnter.add(child);
2314
- statesForDefaultEntry.add(child);
2315
- }
2316
- addDescendantStatesToEnter(child, historyValue, statesForDefaultEntry, statesToEnter);
2317
- }
2318
- }
2319
- }
2320
- }
2321
- }
2322
- }
2323
- function addAncestorStatesToEnter(statesToEnter, historyValue, statesForDefaultEntry, ancestors, reentrancyDomain) {
2324
- for (const anc of ancestors) {
2325
- if (!reentrancyDomain || isDescendant(anc, reentrancyDomain)) {
2326
- statesToEnter.add(anc);
2327
- }
2328
- if (anc.type === 'parallel') {
2329
- for (const child of getChildren(anc).filter(sn => !isHistoryNode(sn))) {
2330
- if (![...statesToEnter].some(s => isDescendant(s, child))) {
2331
- statesToEnter.add(child);
2332
- addDescendantStatesToEnter(child, historyValue, statesForDefaultEntry, statesToEnter);
2333
- }
2334
- }
2335
- }
2336
- }
2337
- }
2338
- function addProperAncestorStatesToEnter(stateNode, toStateNode, statesToEnter, historyValue, statesForDefaultEntry) {
2339
- addAncestorStatesToEnter(statesToEnter, historyValue, statesForDefaultEntry, getProperAncestors(stateNode, toStateNode));
2340
- }
2341
- function exitStates(currentSnapshot, event, actorScope, transitions, mutStateNodeSet, historyValue, internalQueue, _actionExecutor) {
2342
- let nextSnapshot = currentSnapshot;
2343
- const statesToExit = computeExitSet(transitions, mutStateNodeSet, historyValue);
2344
- statesToExit.sort((a, b) => b.order - a.order);
2345
- let changedHistory;
2346
-
2347
- // From SCXML algorithm: https://www.w3.org/TR/scxml/#exitStates
2348
- for (const exitStateNode of statesToExit) {
2349
- for (const historyNode of getHistoryNodes(exitStateNode)) {
2350
- let predicate;
2351
- if (historyNode.history === 'deep') {
2352
- predicate = sn => isAtomicStateNode(sn) && isDescendant(sn, exitStateNode);
2353
- } else {
2354
- predicate = sn => {
2355
- return sn.parent === exitStateNode;
2356
- };
2357
- }
2358
- changedHistory ??= {
2359
- ...historyValue
2360
- };
2361
- changedHistory[historyNode.id] = Array.from(mutStateNodeSet).filter(predicate);
2362
- }
2363
- }
2364
- for (const s of statesToExit) {
2365
- nextSnapshot = resolveActionsAndContext(nextSnapshot, event, actorScope, [...s.exit, ...s.invoke.map(def => stopChild(def.id))], internalQueue, undefined);
2366
- mutStateNodeSet.delete(s);
2367
- }
2368
- return [nextSnapshot, changedHistory || historyValue];
2369
- }
2370
- function getAction(machine, actionType) {
2371
- return machine.implementations.actions[actionType];
2372
- }
2373
- function resolveAndExecuteActionsWithContext(currentSnapshot, event, actorScope, actions, extra, retries) {
2374
- const {
2375
- machine
2376
- } = currentSnapshot;
2377
- let intermediateSnapshot = currentSnapshot;
2378
- for (const action of actions) {
2379
- const isInline = typeof action === 'function';
2380
- const resolvedAction = isInline ? action :
2381
- // the existing type of `.actions` assumes non-nullable `TExpressionAction`
2382
- // it's fine to cast this here to get a common type and lack of errors in the rest of the code
2383
- // our logic below makes sure that we call those 2 "variants" correctly
2384
-
2385
- getAction(machine, typeof action === 'string' ? action : action.type);
2386
- const actionArgs = {
2387
- context: intermediateSnapshot.context,
2388
- event,
2389
- self: actorScope.self,
2390
- system: actorScope.system
2391
- };
2392
- const actionParams = isInline || typeof action === 'string' ? undefined : 'params' in action ? typeof action.params === 'function' ? action.params({
2393
- context: intermediateSnapshot.context,
2394
- event
2395
- }) : action.params : undefined;
2396
- if (!resolvedAction || !('resolve' in resolvedAction)) {
2397
- actorScope.actionExecutor({
2398
- type: typeof action === 'string' ? action : typeof action === 'object' ? action.type : action.name || '(anonymous)',
2399
- info: actionArgs,
2400
- params: actionParams,
2401
- exec: resolvedAction
2402
- });
2403
- continue;
2404
- }
2405
- const builtinAction = resolvedAction;
2406
- const [nextState, params, actions] = builtinAction.resolve(actorScope, intermediateSnapshot, actionArgs, actionParams, resolvedAction,
2407
- // this holds all params
2408
- extra);
2409
- intermediateSnapshot = nextState;
2410
- if ('retryResolve' in builtinAction) {
2411
- retries?.push([builtinAction, params]);
2412
- }
2413
- if ('execute' in builtinAction) {
2414
- actorScope.actionExecutor({
2415
- type: builtinAction.type,
2416
- info: actionArgs,
2417
- params,
2418
- exec: builtinAction.execute.bind(null, actorScope, params)
2419
- });
2420
- }
2421
- if (actions) {
2422
- intermediateSnapshot = resolveAndExecuteActionsWithContext(intermediateSnapshot, event, actorScope, actions, extra, retries);
2423
- }
2424
- }
2425
- return intermediateSnapshot;
2426
- }
2427
- function resolveActionsAndContext(currentSnapshot, event, actorScope, actions, internalQueue, deferredActorIds) {
2428
- const retries = deferredActorIds ? [] : undefined;
2429
- const nextState = resolveAndExecuteActionsWithContext(currentSnapshot, event, actorScope, actions, {
2430
- internalQueue,
2431
- deferredActorIds
2432
- }, retries);
2433
- retries?.forEach(([builtinAction, params]) => {
2434
- builtinAction.retryResolve(actorScope, nextState, params);
2435
- });
2436
- return nextState;
2437
- }
2438
- function macrostep(snapshot, event, actorScope, internalQueue) {
2439
- let nextSnapshot = snapshot;
2440
- const microsteps = [];
2441
- function addMicrostep(step, event, transitions) {
2442
- actorScope.system._sendInspectionEvent({
2443
- type: '@xstate.microstep',
2444
- actorRef: actorScope.self,
2445
- event,
2446
- snapshot: step[0],
2447
- _transitions: transitions
2448
- });
2449
- microsteps.push(step);
2450
- }
2451
-
2452
- // Handle stop event
2453
- if (event.type === XSTATE_STOP) {
2454
- nextSnapshot = cloneMachineSnapshot(stopChildren(nextSnapshot, event, actorScope), {
2455
- status: 'stopped'
2456
- });
2457
- addMicrostep([nextSnapshot, []], event, []);
2458
- return {
2459
- snapshot: nextSnapshot,
2460
- microsteps
2461
- };
2462
- }
2463
- let nextEvent = event;
2464
-
2465
- // Assume the state is at rest (no raised events)
2466
- // Determine the next state based on the next microstep
2467
- if (nextEvent.type !== XSTATE_INIT) {
2468
- const currentEvent = nextEvent;
2469
- const isErr = isErrorActorEvent(currentEvent);
2470
- const transitions = selectTransitions(currentEvent, nextSnapshot);
2471
- if (isErr && !transitions.length) {
2472
- // TODO: we should likely only allow transitions selected by very explicit descriptors
2473
- // `*` shouldn't be matched, likely `xstate.error.*` shouldn't be either
2474
- // similarly `xstate.error.actor.*` and `xstate.error.actor.todo.*` have to be considered too
2475
- nextSnapshot = cloneMachineSnapshot(snapshot, {
2476
- status: 'error',
2477
- error: currentEvent.error
2478
- });
2479
- addMicrostep([nextSnapshot, []], currentEvent, []);
2480
- return {
2481
- snapshot: nextSnapshot,
2482
- microsteps
2483
- };
2484
- }
2485
- const step = microstep(transitions, snapshot, actorScope, nextEvent, false,
2486
- // isInitial
2487
- internalQueue);
2488
- nextSnapshot = step[0];
2489
- addMicrostep(step, currentEvent, transitions);
2490
- }
2491
- let shouldSelectEventlessTransitions = true;
2492
- const maxIterations = snapshot.machine.options?.maxIterations ?? Infinity;
2493
- let iterationCount = 0;
2494
- while (nextSnapshot.status === 'active') {
2495
- iterationCount++;
2496
- if (iterationCount > maxIterations) {
2497
- throw new Error(`Infinite loop detected: the machine has processed more than ${maxIterations} microsteps without reaching a stable state. This usually happens when there's a cycle of transitions (e.g., eventless transitions or raised events causing state A -> B -> C -> A).`);
2498
- }
2499
- let enabledTransitions = shouldSelectEventlessTransitions ? selectEventlessTransitions(nextSnapshot, nextEvent) : [];
2500
-
2501
- // eventless transitions should always be selected after selecting *regular* transitions
2502
- // by assigning `undefined` to `previousState` we ensure that `shouldSelectEventlessTransitions` gets always computed to true in such a case
2503
- const previousState = enabledTransitions.length ? nextSnapshot : undefined;
2504
- if (!enabledTransitions.length) {
2505
- if (!internalQueue.length) {
2506
- break;
2507
- }
2508
- nextEvent = internalQueue.shift();
2509
- enabledTransitions = selectTransitions(nextEvent, nextSnapshot);
2510
- }
2511
- const step = microstep(enabledTransitions, nextSnapshot, actorScope, nextEvent, false, internalQueue);
2512
- nextSnapshot = step[0];
2513
- shouldSelectEventlessTransitions = nextSnapshot !== previousState;
2514
- addMicrostep(step, nextEvent, enabledTransitions);
2515
- }
2516
- if (nextSnapshot.status !== 'active') {
2517
- stopChildren(nextSnapshot, nextEvent, actorScope);
2518
- }
2519
- return {
2520
- snapshot: nextSnapshot,
2521
- microsteps
2522
- };
2523
- }
2524
- function stopChildren(nextState, event, actorScope) {
2525
- return resolveActionsAndContext(nextState, event, actorScope, Object.values(nextState.children).map(child => stopChild(child)), [], undefined);
2526
- }
2527
- function selectTransitions(event, nextState) {
2528
- return nextState.machine.getTransitionData(nextState, event);
2529
- }
2530
- function selectEventlessTransitions(nextState, event) {
2531
- const enabledTransitionSet = new Set();
2532
- const atomicStates = nextState._nodes.filter(isAtomicStateNode);
2533
- for (const stateNode of atomicStates) {
2534
- loop: for (const s of [stateNode].concat(getProperAncestors(stateNode, undefined))) {
2535
- if (!s.always) {
2536
- continue;
2537
- }
2538
- for (const transition of s.always) {
2539
- if (transition.guard === undefined || evaluateGuard(transition.guard, nextState.context, event, nextState)) {
2540
- enabledTransitionSet.add(transition);
2541
- break loop;
2542
- }
2543
- }
2544
- }
2545
- }
2546
- return removeConflictingTransitions(Array.from(enabledTransitionSet), new Set(nextState._nodes), nextState.historyValue);
2547
- }
2548
-
2549
- /**
2550
- * Resolves a partial state value with its full representation in the state
2551
- * node's machine.
2552
- *
2553
- * @param stateValue The partial state value to resolve.
2554
- */
2555
- function resolveStateValue(rootNode, stateValue) {
2556
- const allStateNodes = getAllStateNodes(getStateNodes(rootNode, stateValue));
2557
- return getStateValue(rootNode, [...allStateNodes]);
2558
- }
2559
-
2560
- function isMachineSnapshot(value) {
2561
- return !!value && typeof value === 'object' && 'machine' in value && 'value' in value;
2562
- }
2563
- const machineSnapshotMatches = function matches(testValue) {
2564
- return matchesState(testValue, this.value);
2565
- };
2566
- const machineSnapshotHasTag = function hasTag(tag) {
2567
- return this.tags.has(tag);
2568
- };
2569
- const machineSnapshotCan = function can(event) {
2570
- const transitionData = this.machine.getTransitionData(this, event);
2571
- return !!transitionData?.length &&
2572
- // Check that at least one transition is not forbidden
2573
- transitionData.some(t => t.target !== undefined || t.actions.length);
2574
- };
2575
- const machineSnapshotToJSON = function toJSON() {
2576
- const {
2577
- _nodes: nodes,
2578
- tags,
2579
- machine,
2580
- getMeta,
2581
- toJSON,
2582
- can,
2583
- hasTag,
2584
- matches,
2585
- ...jsonValues
2586
- } = this;
2587
- return {
2588
- ...jsonValues,
2589
- tags: Array.from(tags)
2590
- };
2591
- };
2592
- const machineSnapshotGetMeta = function getMeta() {
2593
- return this._nodes.reduce((acc, stateNode) => {
2594
- if (stateNode.meta !== undefined) {
2595
- acc[stateNode.id] = stateNode.meta;
2596
- }
2597
- return acc;
2598
- }, {});
2599
- };
2600
- function createMachineSnapshot(config, machine) {
2601
- return {
2602
- status: config.status,
2603
- output: config.output,
2604
- error: config.error,
2605
- machine,
2606
- context: config.context,
2607
- _nodes: config._nodes,
2608
- value: getStateValue(machine.root, config._nodes),
2609
- tags: new Set(config._nodes.flatMap(sn => sn.tags)),
2610
- children: config.children,
2611
- historyValue: config.historyValue || {},
2612
- matches: machineSnapshotMatches,
2613
- hasTag: machineSnapshotHasTag,
2614
- can: machineSnapshotCan,
2615
- getMeta: machineSnapshotGetMeta,
2616
- toJSON: machineSnapshotToJSON
2617
- };
2618
- }
2619
- function cloneMachineSnapshot(snapshot, config = {}) {
2620
- return createMachineSnapshot({
2621
- ...snapshot,
2622
- ...config
2623
- }, snapshot.machine);
2624
- }
2625
- function serializeHistoryValue(historyValue) {
2626
- if (typeof historyValue !== 'object' || historyValue === null) {
2627
- return {};
2628
- }
2629
- const result = {};
2630
- for (const key in historyValue) {
2631
- const value = historyValue[key];
2632
- if (Array.isArray(value)) {
2633
- result[key] = value.map(item => ({
2634
- id: item.id
2635
- }));
2636
- }
2637
- }
2638
- return result;
2639
- }
2640
- function getPersistedSnapshot(snapshot, options) {
2641
- const {
2642
- _nodes: nodes,
2643
- tags,
2644
- machine,
2645
- children,
2646
- context,
2647
- can,
2648
- hasTag,
2649
- matches,
2650
- getMeta,
2651
- toJSON,
2652
- ...jsonValues
2653
- } = snapshot;
2654
- const childrenJson = {};
2655
- for (const id in children) {
2656
- const child = children[id];
2657
- childrenJson[id] = {
2658
- snapshot: child.getPersistedSnapshot(options),
2659
- src: child.src,
2660
- systemId: child.systemId,
2661
- syncSnapshot: child._syncSnapshot
2662
- };
2663
- }
2664
- const persisted = {
2665
- ...jsonValues,
2666
- context: persistContext(context),
2667
- children: childrenJson,
2668
- historyValue: serializeHistoryValue(jsonValues.historyValue)
2669
- };
2670
- return persisted;
2671
- }
2672
- function persistContext(contextPart) {
2673
- let copy;
2674
- for (const key in contextPart) {
2675
- const value = contextPart[key];
2676
- if (value && typeof value === 'object') {
2677
- if ('sessionId' in value && 'send' in value && 'ref' in value) {
2678
- copy ??= Array.isArray(contextPart) ? contextPart.slice() : {
2679
- ...contextPart
2680
- };
2681
- copy[key] = {
2682
- xstate$$type: $$ACTOR_TYPE,
2683
- id: value.id
2684
- };
2685
- } else {
2686
- const result = persistContext(value);
2687
- if (result !== value) {
2688
- copy ??= Array.isArray(contextPart) ? contextPart.slice() : {
2689
- ...contextPart
2690
- };
2691
- copy[key] = result;
2692
- }
2693
- }
2694
- }
2695
- }
2696
- return copy ?? contextPart;
2697
- }
2698
-
2699
- function resolveRaise(_, snapshot, args, actionParams, {
2700
- event: eventOrExpr,
2701
- id,
2702
- delay
2703
- }, {
2704
- internalQueue
2705
- }) {
2706
- const delaysMap = snapshot.machine.implementations.delays;
2707
- if (typeof eventOrExpr === 'string') {
2708
- throw new Error(
2709
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
2710
- `Only event objects may be used with raise; use raise({ type: "${eventOrExpr}" }) instead`);
2711
- }
2712
- const resolvedEvent = typeof eventOrExpr === 'function' ? eventOrExpr(args, actionParams) : eventOrExpr;
2713
- let resolvedDelay;
2714
- if (typeof delay === 'string') {
2715
- const configDelay = delaysMap && delaysMap[delay];
2716
- resolvedDelay = typeof configDelay === 'function' ? configDelay(args, actionParams) : configDelay;
2717
- } else {
2718
- resolvedDelay = typeof delay === 'function' ? delay(args, actionParams) : delay;
2719
- }
2720
- if (typeof resolvedDelay !== 'number') {
2721
- internalQueue.push(resolvedEvent);
2722
- }
2723
- return [snapshot, {
2724
- event: resolvedEvent,
2725
- id,
2726
- delay: resolvedDelay
2727
- }, undefined];
2728
- }
2729
- function executeRaise(actorScope, params) {
2730
- const {
2731
- event,
2732
- delay,
2733
- id
2734
- } = params;
2735
- if (typeof delay === 'number') {
2736
- actorScope.defer(() => {
2737
- const self = actorScope.self;
2738
- actorScope.system.scheduler.schedule(self, self, event, delay, id);
2739
- });
2740
- return;
2741
- }
2742
- }
2743
- /**
2744
- * Raises an event. This places the event in the internal event queue, so that
2745
- * the event is immediately consumed by the machine in the current step.
2746
- *
2747
- * @param eventType The event to raise.
2748
- */
2749
- function raise(eventOrExpr, options) {
2750
- function raise(_args, _params) {
2751
- }
2752
- raise.type = 'xstate.raise';
2753
- raise.event = eventOrExpr;
2754
- raise.id = options?.id;
2755
- raise.delay = options?.delay;
2756
- raise.resolve = resolveRaise;
2757
- raise.execute = executeRaise;
2758
- return raise;
2759
- }
2760
-
2761
- export { $$ACTOR_TYPE as $, Actor as A, toTransitionConfigArray as B, formatTransition as C, evaluateGuard as D, createInvokeId as E, getDelayedTransitions as F, formatInitialTransition as G, getCandidates as H, formatRouteTransitions as I, resolveStateValue as J, getAllStateNodes as K, createMachineSnapshot as L, isInFinalState as M, NULL_EVENT as N, transitionNode as O, resolveActionsAndContext as P, toStatePath as Q, isStateId as R, STATE_DELIMITER as S, getStateNodeByPath as T, getPersistedSnapshot as U, resolveReferencedActor as V, XSTATE_ERROR as W, XSTATE_STOP as X, createErrorActorEvent as Y, ProcessingStatus as Z, cloneMachineSnapshot as _, cancel as a, spawnChild as b, createActor as c, macrostep as d, createInitEvent as e, initialMicrostep as f, getProperAncestors as g, interpret as h, isAtomicStateNode as i, and as j, stateIn as k, isMachineSnapshot as l, matchesEventDescriptor as m, not as n, or as o, getStateNodes as p, getAllOwnEventDescriptors as q, raise as r, stopChild as s, toArray as t, matchesState as u, pathToStateValue as v, toObserver as w, stop as x, mapValues as y, formatTransitions as z };