xstate 5.0.0-beta.26 → 5.0.0-beta.28

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 (71) hide show
  1. package/README.md +9 -7
  2. package/actions/dist/xstate-actions.cjs.js +14 -18
  3. package/actions/dist/xstate-actions.cjs.mjs +0 -6
  4. package/actions/dist/xstate-actions.development.cjs.js +14 -18
  5. package/actions/dist/xstate-actions.development.cjs.mjs +0 -6
  6. package/actions/dist/xstate-actions.development.esm.js +3 -1
  7. package/actions/dist/xstate-actions.esm.js +3 -1
  8. package/actions/dist/xstate-actions.umd.min.js +1 -1
  9. package/actions/dist/xstate-actions.umd.min.js.map +1 -1
  10. package/actors/dist/xstate-actors.cjs.js +439 -14
  11. package/actors/dist/xstate-actors.cjs.mjs +0 -5
  12. package/actors/dist/xstate-actors.development.cjs.js +439 -14
  13. package/actors/dist/xstate-actors.development.cjs.mjs +0 -5
  14. package/actors/dist/xstate-actors.development.esm.js +435 -1
  15. package/actors/dist/xstate-actors.esm.js +435 -1
  16. package/actors/dist/xstate-actors.umd.min.js +1 -1
  17. package/actors/dist/xstate-actors.umd.min.js.map +1 -1
  18. package/dist/declarations/src/Machine.d.ts +4 -3
  19. package/dist/declarations/src/State.d.ts +1 -1
  20. package/dist/declarations/src/StateNode.d.ts +3 -12
  21. package/dist/declarations/src/actions/assign.d.ts +11 -11
  22. package/dist/declarations/src/actions/cancel.d.ts +5 -12
  23. package/dist/declarations/src/actions/choose.d.ts +9 -7
  24. package/dist/declarations/src/actions/log.d.ts +5 -20
  25. package/dist/declarations/src/actions/pure.d.ts +11 -9
  26. package/dist/declarations/src/actions/raise.d.ts +6 -5
  27. package/dist/declarations/src/actions/send.d.ts +7 -12
  28. package/dist/declarations/src/actions/stop.d.ts +5 -12
  29. package/dist/declarations/src/actions.d.ts +8 -42
  30. package/dist/declarations/src/actors/index.d.ts +2 -22
  31. package/dist/declarations/src/actors/promise.d.ts +2 -1
  32. package/dist/declarations/src/constants.d.ts +8 -0
  33. package/dist/declarations/src/guards.d.ts +2 -2
  34. package/dist/declarations/src/index.d.ts +11 -18
  35. package/dist/declarations/src/spawn.d.ts +25 -0
  36. package/dist/declarations/src/stateUtils.d.ts +1 -1
  37. package/dist/declarations/src/typegenTypes.d.ts +5 -5
  38. package/dist/declarations/src/types.d.ts +81 -108
  39. package/dist/declarations/src/utils.d.ts +2 -3
  40. package/dist/interpreter-672794ae.cjs.js +792 -0
  41. package/dist/interpreter-a1432c7d.development.cjs.js +800 -0
  42. package/dist/interpreter-a77bb0ec.development.esm.js +765 -0
  43. package/dist/interpreter-b5203bcb.esm.js +757 -0
  44. package/dist/raise-436a57a2.cjs.js +1458 -0
  45. package/dist/raise-74b72ca5.development.cjs.js +1498 -0
  46. package/dist/raise-a60c9290.development.esm.js +1468 -0
  47. package/dist/raise-b9c9a234.esm.js +1428 -0
  48. package/dist/send-35e1a689.cjs.js +349 -0
  49. package/dist/send-4192e7bc.esm.js +339 -0
  50. package/dist/send-e63b7b83.development.esm.js +364 -0
  51. package/dist/send-e8b55d00.development.cjs.js +374 -0
  52. package/dist/xstate.cjs.js +140 -160
  53. package/dist/xstate.cjs.mjs +4 -2
  54. package/dist/xstate.development.cjs.js +140 -160
  55. package/dist/xstate.development.cjs.mjs +4 -2
  56. package/dist/xstate.development.esm.js +75 -95
  57. package/dist/xstate.esm.js +75 -95
  58. package/dist/xstate.umd.min.js +1 -1
  59. package/dist/xstate.umd.min.js.map +1 -1
  60. package/guards/dist/xstate-guards.cjs.js +7 -6
  61. package/guards/dist/xstate-guards.development.cjs.js +7 -6
  62. package/guards/dist/xstate-guards.development.esm.js +2 -1
  63. package/guards/dist/xstate-guards.esm.js +2 -1
  64. package/guards/dist/xstate-guards.umd.min.js +1 -1
  65. package/guards/dist/xstate-guards.umd.min.js.map +1 -1
  66. package/package.json +1 -1
  67. package/dist/actions-0971b43d.development.cjs.js +0 -3168
  68. package/dist/actions-319cefe7.cjs.js +0 -3095
  69. package/dist/actions-5943a9db.esm.js +0 -3018
  70. package/dist/actions-cf69419d.development.esm.js +0 -3091
  71. package/dist/declarations/src/constantPrefixes.d.ts +0 -6
@@ -0,0 +1,1428 @@
1
+ import { r as resolveReferencedActor, d as createActor, f as ActorStatus, l as createErrorActorEvent, o as toStateValue, q as STATE_IDENTIFIER, u as normalizeTarget, t as toArray, N as NULL_EVENT, a as toTransitionConfigArray, S as STATE_DELIMITER, v as toStatePath, w as createDoneStateEvent, x as mapContext, n as XSTATE_STOP, X as XSTATE_INIT, W as WILDCARD, y as isArray, z as createAfterEvent, B as flatten, e as matchesState } from './interpreter-b5203bcb.esm.js';
2
+
3
+ const cache = new WeakMap();
4
+ function memo(object, key, fn) {
5
+ let memoizedData = cache.get(object);
6
+ if (!memoizedData) {
7
+ memoizedData = {
8
+ [key]: fn()
9
+ };
10
+ cache.set(object, memoizedData);
11
+ } else if (!(key in memoizedData)) {
12
+ memoizedData[key] = fn();
13
+ }
14
+ return memoizedData[key];
15
+ }
16
+
17
+ function resolve$3(_, state, actionArgs, {
18
+ sendId
19
+ }) {
20
+ const resolvedSendId = typeof sendId === 'function' ? sendId(actionArgs) : sendId;
21
+ return [state, resolvedSendId];
22
+ }
23
+ function execute$3(actorContext, resolvedSendId) {
24
+ actorContext.self.cancel(resolvedSendId);
25
+ }
26
+ /**
27
+ * Cancels an in-flight `send(...)` action. A canceled sent action will not
28
+ * be executed, nor will its event be sent, unless it has already been sent
29
+ * (e.g., if `cancel(...)` is called after the `send(...)` action's `delay`).
30
+ *
31
+ * @param sendId The `id` of the `send(...)` action to cancel.
32
+ */
33
+ function cancel(sendId) {
34
+ function cancel(_) {
35
+ }
36
+ cancel.type = 'xstate.cancel';
37
+ cancel.sendId = sendId;
38
+ cancel.resolve = resolve$3;
39
+ cancel.execute = execute$3;
40
+ return cancel;
41
+ }
42
+
43
+ function resolve$2(actorContext, state, actionArgs, {
44
+ id,
45
+ systemId,
46
+ src,
47
+ input
48
+ }) {
49
+ const referenced = resolveReferencedActor(state.machine.implementations.actors[src]);
50
+ let actorRef;
51
+ if (referenced) {
52
+ // TODO: inline `input: undefined` should win over the referenced one
53
+ const configuredInput = input || referenced.input;
54
+ actorRef = createActor(referenced.src, {
55
+ id,
56
+ src,
57
+ parent: actorContext?.self,
58
+ systemId,
59
+ input: typeof configuredInput === 'function' ? configuredInput({
60
+ context: state.context,
61
+ event: actionArgs.event,
62
+ self: actorContext?.self
63
+ }) : configuredInput
64
+ });
65
+ }
66
+ return [cloneState(state, {
67
+ children: {
68
+ ...state.children,
69
+ [id]: actorRef
70
+ }
71
+ }), {
72
+ id,
73
+ actorRef
74
+ }];
75
+ }
76
+ function execute$2(actorContext, {
77
+ id,
78
+ actorRef
79
+ }) {
80
+ if (!actorRef) {
81
+ return;
82
+ }
83
+ actorContext.defer(() => {
84
+ if (actorRef.status === ActorStatus.Stopped) {
85
+ return;
86
+ }
87
+ try {
88
+ actorRef.start?.();
89
+ } catch (err) {
90
+ actorContext.self.send(createErrorActorEvent(id, err));
91
+ return;
92
+ }
93
+ });
94
+ }
95
+
96
+ // we don't export this since it's an internal action that is not meant to be used in the user's code
97
+
98
+ function invoke({
99
+ id,
100
+ systemId,
101
+ src,
102
+ input
103
+ }) {
104
+ function invoke(_) {
105
+ }
106
+ invoke.type = 'xstate.invoke';
107
+ invoke.id = id;
108
+ invoke.systemId = systemId;
109
+ invoke.src = src;
110
+ invoke.input = input;
111
+ invoke.resolve = resolve$2;
112
+ invoke.execute = execute$2;
113
+ return invoke;
114
+ }
115
+
116
+ function resolve$1(_, state, args, {
117
+ actorRef
118
+ }) {
119
+ const actorRefOrString = typeof actorRef === 'function' ? actorRef(args) : actorRef;
120
+ const resolvedActorRef = typeof actorRefOrString === 'string' ? state.children[actorRefOrString] : actorRefOrString;
121
+ let children = state.children;
122
+ if (resolvedActorRef) {
123
+ children = {
124
+ ...children
125
+ };
126
+ delete children[resolvedActorRef.id];
127
+ }
128
+ return [cloneState(state, {
129
+ children
130
+ }), resolvedActorRef];
131
+ }
132
+ function execute$1(actorContext, actorRef) {
133
+ if (!actorRef) {
134
+ return;
135
+ }
136
+ if (actorRef.status !== ActorStatus.Running) {
137
+ actorContext.stopChild(actorRef);
138
+ return;
139
+ }
140
+ // TODO: recheck why this one has to be deferred
141
+ actorContext.defer(() => {
142
+ actorContext.stopChild(actorRef);
143
+ });
144
+ }
145
+ /**
146
+ * Stops an actor.
147
+ *
148
+ * @param actorRef The actor to stop.
149
+ */
150
+ function stop(actorRef) {
151
+ function stop(_) {
152
+ }
153
+ stop.type = 'xstate.stop';
154
+ stop.actorRef = actorRef;
155
+ stop.resolve = resolve$1;
156
+ stop.execute = execute$1;
157
+ return stop;
158
+ }
159
+
160
+ function checkStateIn(state, _, {
161
+ stateValue
162
+ }) {
163
+ if (typeof stateValue === 'string' && isStateId(stateValue)) {
164
+ return state.configuration.some(sn => sn.id === stateValue.slice(1));
165
+ }
166
+ return state.matches(stateValue);
167
+ }
168
+ function stateIn(stateValue) {
169
+ function stateIn(_) {
170
+ return false;
171
+ }
172
+ stateIn.check = checkStateIn;
173
+ stateIn.stateValue = stateValue;
174
+ return stateIn;
175
+ }
176
+ function checkNot(state, {
177
+ context,
178
+ event
179
+ }, {
180
+ guards
181
+ }) {
182
+ return !evaluateGuard(guards[0], context, event, state);
183
+ }
184
+ function not(guard) {
185
+ function not(_) {
186
+ return false;
187
+ }
188
+ not.check = checkNot;
189
+ not.guards = [guard];
190
+ return not;
191
+ }
192
+ function checkAnd(state, {
193
+ context,
194
+ event
195
+ }, {
196
+ guards
197
+ }) {
198
+ return guards.every(guard => evaluateGuard(guard, context, event, state));
199
+ }
200
+ function and(guards) {
201
+ function and(_) {
202
+ return false;
203
+ }
204
+ and.check = checkAnd;
205
+ and.guards = guards;
206
+ return and;
207
+ }
208
+ function checkOr(state, {
209
+ context,
210
+ event
211
+ }, {
212
+ guards
213
+ }) {
214
+ return guards.some(guard => evaluateGuard(guard, context, event, state));
215
+ }
216
+ function or(guards) {
217
+ function or(_) {
218
+ return false;
219
+ }
220
+ or.check = checkOr;
221
+ or.guards = guards;
222
+ return or;
223
+ }
224
+
225
+ // TODO: throw on cycles (depth check should be enough)
226
+ function evaluateGuard(guard, context, event, state) {
227
+ const {
228
+ machine
229
+ } = state;
230
+ const isInline = typeof guard === 'function';
231
+ const resolved = isInline ? guard : machine.implementations.guards[typeof guard === 'string' ? guard : guard.type];
232
+ if (!isInline && !resolved) {
233
+ throw new Error(`Guard '${typeof guard === 'string' ? guard : guard.type}' is not implemented.'.`);
234
+ }
235
+ if (typeof resolved !== 'function') {
236
+ return evaluateGuard(resolved, context, event, state);
237
+ }
238
+ const guardArgs = {
239
+ context,
240
+ event,
241
+ guard: isInline ? undefined : typeof guard === 'string' ? {
242
+ type: guard
243
+ } : typeof guard.params === 'function' ? {
244
+ type: guard.type,
245
+ params: guard.params({
246
+ context,
247
+ event
248
+ })
249
+ } : guard
250
+ };
251
+ if (!('check' in resolved)) {
252
+ // the existing type of `.guards` assumes non-nullable `TExpressionGuard`
253
+ // inline guards expect `TExpressionGuard` to be set to `undefined`
254
+ // it's fine to cast this here, our logic makes sure that we call those 2 "variants" correctly
255
+ return resolved(guardArgs);
256
+ }
257
+ const builtinGuard = resolved;
258
+ return builtinGuard.check(state, guardArgs, resolved // this holds all params
259
+ );
260
+ }
261
+
262
+ function getOutput(configuration, context, event, self) {
263
+ const machine = configuration[0].machine;
264
+ const finalChildStateNode = configuration.find(stateNode => stateNode.type === 'final' && stateNode.parent === machine.root);
265
+ return finalChildStateNode && finalChildStateNode.output ? mapContext(finalChildStateNode.output, context, event, self) : undefined;
266
+ }
267
+ const isAtomicStateNode = stateNode => stateNode.type === 'atomic' || stateNode.type === 'final';
268
+ function getChildren(stateNode) {
269
+ return Object.values(stateNode.states).filter(sn => sn.type !== 'history');
270
+ }
271
+ function getProperAncestors(stateNode, toStateNode) {
272
+ const ancestors = [];
273
+
274
+ // add all ancestors
275
+ let m = stateNode.parent;
276
+ while (m && m !== toStateNode) {
277
+ ancestors.push(m);
278
+ m = m.parent;
279
+ }
280
+ return ancestors;
281
+ }
282
+ function getConfiguration(stateNodes) {
283
+ const configuration = new Set(stateNodes);
284
+ const configurationSet = new Set(stateNodes);
285
+ const adjList = getAdjList(configurationSet);
286
+
287
+ // add descendants
288
+ for (const s of configuration) {
289
+ // if previously active, add existing child nodes
290
+ if (s.type === 'compound' && (!adjList.get(s) || !adjList.get(s).length)) {
291
+ getInitialStateNodes(s).forEach(sn => configurationSet.add(sn));
292
+ } else {
293
+ if (s.type === 'parallel') {
294
+ for (const child of getChildren(s)) {
295
+ if (child.type === 'history') {
296
+ continue;
297
+ }
298
+ if (!configurationSet.has(child)) {
299
+ for (const initialStateNode of getInitialStateNodes(child)) {
300
+ configurationSet.add(initialStateNode);
301
+ }
302
+ }
303
+ }
304
+ }
305
+ }
306
+ }
307
+
308
+ // add all ancestors
309
+ for (const s of configurationSet) {
310
+ let m = s.parent;
311
+ while (m) {
312
+ configurationSet.add(m);
313
+ m = m.parent;
314
+ }
315
+ }
316
+ return configurationSet;
317
+ }
318
+ function getValueFromAdj(baseNode, adjList) {
319
+ const childStateNodes = adjList.get(baseNode);
320
+ if (!childStateNodes) {
321
+ return {}; // todo: fix?
322
+ }
323
+
324
+ if (baseNode.type === 'compound') {
325
+ const childStateNode = childStateNodes[0];
326
+ if (childStateNode) {
327
+ if (isAtomicStateNode(childStateNode)) {
328
+ return childStateNode.key;
329
+ }
330
+ } else {
331
+ return {};
332
+ }
333
+ }
334
+ const stateValue = {};
335
+ for (const childStateNode of childStateNodes) {
336
+ stateValue[childStateNode.key] = getValueFromAdj(childStateNode, adjList);
337
+ }
338
+ return stateValue;
339
+ }
340
+ function getAdjList(configuration) {
341
+ const adjList = new Map();
342
+ for (const s of configuration) {
343
+ if (!adjList.has(s)) {
344
+ adjList.set(s, []);
345
+ }
346
+ if (s.parent) {
347
+ if (!adjList.has(s.parent)) {
348
+ adjList.set(s.parent, []);
349
+ }
350
+ adjList.get(s.parent).push(s);
351
+ }
352
+ }
353
+ return adjList;
354
+ }
355
+ function getStateValue(rootNode, configuration) {
356
+ const config = getConfiguration(configuration);
357
+ return getValueFromAdj(rootNode, getAdjList(config));
358
+ }
359
+ function isInFinalState(configuration, stateNode = configuration[0].machine.root) {
360
+ if (stateNode.type === 'compound') {
361
+ return getChildren(stateNode).some(s => s.type === 'final' && configuration.includes(s));
362
+ }
363
+ if (stateNode.type === 'parallel') {
364
+ return getChildren(stateNode).every(sn => isInFinalState(configuration, sn));
365
+ }
366
+ return false;
367
+ }
368
+ const isStateId = str => str[0] === STATE_IDENTIFIER;
369
+ function getCandidates(stateNode, receivedEventType) {
370
+ const candidates = stateNode.transitions.get(receivedEventType) || [...stateNode.transitions.keys()].filter(descriptor => {
371
+ // check if transition is a wildcard transition,
372
+ // which matches any non-transient events
373
+ if (descriptor === WILDCARD) {
374
+ return true;
375
+ }
376
+ if (!descriptor.endsWith('.*')) {
377
+ return false;
378
+ }
379
+ const partialEventTokens = descriptor.split('.');
380
+ const eventTokens = receivedEventType.split('.');
381
+ for (let tokenIndex = 0; tokenIndex < partialEventTokens.length; tokenIndex++) {
382
+ const partialEventToken = partialEventTokens[tokenIndex];
383
+ const eventToken = eventTokens[tokenIndex];
384
+ if (partialEventToken === '*') {
385
+ const isLastToken = tokenIndex === partialEventTokens.length - 1;
386
+ return isLastToken;
387
+ }
388
+ if (partialEventToken !== eventToken) {
389
+ return false;
390
+ }
391
+ }
392
+ return true;
393
+ }).sort((a, b) => b.length - a.length).flatMap(key => stateNode.transitions.get(key));
394
+ return candidates;
395
+ }
396
+
397
+ /**
398
+ * All delayed transitions from the config.
399
+ */
400
+ function getDelayedTransitions(stateNode) {
401
+ const afterConfig = stateNode.config.after;
402
+ if (!afterConfig) {
403
+ return [];
404
+ }
405
+ const mutateEntryExit = (delay, i) => {
406
+ const delayRef = typeof delay === 'function' ? `${stateNode.id}:delay[${i}]` : delay;
407
+ const afterEvent = createAfterEvent(delayRef, stateNode.id);
408
+ const eventType = afterEvent.type;
409
+ stateNode.entry.push(raise(afterEvent, {
410
+ id: eventType,
411
+ delay
412
+ }));
413
+ stateNode.exit.push(cancel(eventType));
414
+ return eventType;
415
+ };
416
+ const delayedTransitions = isArray(afterConfig) ? afterConfig.map((transition, i) => {
417
+ const eventType = mutateEntryExit(transition.delay, i);
418
+ return {
419
+ ...transition,
420
+ event: eventType
421
+ };
422
+ }) : Object.keys(afterConfig).flatMap((delay, i) => {
423
+ const configTransition = afterConfig[delay];
424
+ const resolvedTransition = typeof configTransition === 'string' ? {
425
+ target: configTransition
426
+ } : configTransition;
427
+ const resolvedDelay = !isNaN(+delay) ? +delay : delay;
428
+ const eventType = mutateEntryExit(resolvedDelay, i);
429
+ return toArray(resolvedTransition).map(transition => ({
430
+ ...transition,
431
+ event: eventType,
432
+ delay: resolvedDelay
433
+ }));
434
+ });
435
+ return delayedTransitions.map(delayedTransition => {
436
+ const {
437
+ delay
438
+ } = delayedTransition;
439
+ return {
440
+ ...formatTransition(stateNode, delayedTransition.event, delayedTransition),
441
+ delay
442
+ };
443
+ });
444
+ }
445
+ function formatTransition(stateNode, descriptor, transitionConfig) {
446
+ const normalizedTarget = normalizeTarget(transitionConfig.target);
447
+ const reenter = transitionConfig.reenter ?? false;
448
+ const target = resolveTarget(stateNode, normalizedTarget);
449
+ const transition = {
450
+ ...transitionConfig,
451
+ actions: toArray(transitionConfig.actions),
452
+ guard: transitionConfig.guard,
453
+ target,
454
+ source: stateNode,
455
+ reenter,
456
+ eventType: descriptor,
457
+ toJSON: () => ({
458
+ ...transition,
459
+ source: `#${stateNode.id}`,
460
+ target: target ? target.map(t => `#${t.id}`) : undefined
461
+ })
462
+ };
463
+ return transition;
464
+ }
465
+ function formatTransitions(stateNode) {
466
+ const transitions = new Map();
467
+ if (stateNode.config.on) {
468
+ for (const descriptor of Object.keys(stateNode.config.on)) {
469
+ if (descriptor === NULL_EVENT) {
470
+ throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');
471
+ }
472
+ const transitionsConfig = stateNode.config.on[descriptor];
473
+ transitions.set(descriptor, toTransitionConfigArray(transitionsConfig).map(t => formatTransition(stateNode, descriptor, t)));
474
+ }
475
+ }
476
+ if (stateNode.config.onDone) {
477
+ const descriptor = `xstate.done.state.${stateNode.id}`;
478
+ transitions.set(descriptor, toTransitionConfigArray(stateNode.config.onDone).map(t => formatTransition(stateNode, descriptor, t)));
479
+ }
480
+ for (const invokeDef of stateNode.invoke) {
481
+ if (invokeDef.onDone) {
482
+ const descriptor = `xstate.done.actor.${invokeDef.id}`;
483
+ transitions.set(descriptor, toTransitionConfigArray(invokeDef.onDone).map(t => formatTransition(stateNode, descriptor, t)));
484
+ }
485
+ if (invokeDef.onError) {
486
+ const descriptor = `xstate.error.actor.${invokeDef.id}`;
487
+ transitions.set(descriptor, toTransitionConfigArray(invokeDef.onError).map(t => formatTransition(stateNode, descriptor, t)));
488
+ }
489
+ if (invokeDef.onSnapshot) {
490
+ const descriptor = `xstate.snapshot.${invokeDef.id}`;
491
+ transitions.set(descriptor, toTransitionConfigArray(invokeDef.onSnapshot).map(t => formatTransition(stateNode, descriptor, t)));
492
+ }
493
+ }
494
+ for (const delayedTransition of stateNode.after) {
495
+ let existing = transitions.get(delayedTransition.eventType);
496
+ if (!existing) {
497
+ existing = [];
498
+ transitions.set(delayedTransition.eventType, existing);
499
+ }
500
+ existing.push(delayedTransition);
501
+ }
502
+ return transitions;
503
+ }
504
+ function formatInitialTransition(stateNode, _target) {
505
+ if (typeof _target === 'string' || isArray(_target)) {
506
+ const targets = toArray(_target).map(t => {
507
+ // Resolve state string keys (which represent children)
508
+ // to their state node
509
+ const descStateNode = typeof t === 'string' ? isStateId(t) ? stateNode.machine.getStateNodeById(t) : stateNode.states[t] : t;
510
+ if (!descStateNode) {
511
+ throw new Error(`Initial state node "${t}" not found on parent state node #${stateNode.id}`);
512
+ }
513
+ if (!isDescendant(descStateNode, stateNode)) {
514
+ throw new Error(`Invalid initial target: state node #${descStateNode.id} is not a descendant of #${stateNode.id}`);
515
+ }
516
+ return descStateNode;
517
+ });
518
+ const resolvedTarget = resolveTarget(stateNode, targets);
519
+ const transition = {
520
+ source: stateNode,
521
+ actions: [],
522
+ eventType: null,
523
+ reenter: false,
524
+ target: resolvedTarget,
525
+ toJSON: () => ({
526
+ ...transition,
527
+ source: `#${stateNode.id}`,
528
+ target: resolvedTarget ? resolvedTarget.map(t => `#${t.id}`) : undefined
529
+ })
530
+ };
531
+ return transition;
532
+ }
533
+ return formatTransition(stateNode, '__INITIAL__', {
534
+ target: toArray(_target.target).map(t => {
535
+ if (typeof t === 'string') {
536
+ return isStateId(t) ? t : `${STATE_DELIMITER}${t}`;
537
+ }
538
+ return t;
539
+ }),
540
+ actions: _target.actions
541
+ });
542
+ }
543
+ function resolveTarget(stateNode, targets) {
544
+ if (targets === undefined) {
545
+ // an undefined target signals that the state node should not transition from that state when receiving that event
546
+ return undefined;
547
+ }
548
+ return targets.map(target => {
549
+ if (typeof target !== 'string') {
550
+ return target;
551
+ }
552
+ if (isStateId(target)) {
553
+ return stateNode.machine.getStateNodeById(target);
554
+ }
555
+ const isInternalTarget = target[0] === STATE_DELIMITER;
556
+ // If internal target is defined on machine,
557
+ // do not include machine key on target
558
+ if (isInternalTarget && !stateNode.parent) {
559
+ return getStateNodeByPath(stateNode, target.slice(1));
560
+ }
561
+ const resolvedTarget = isInternalTarget ? stateNode.key + target : target;
562
+ if (stateNode.parent) {
563
+ try {
564
+ const targetStateNode = getStateNodeByPath(stateNode.parent, resolvedTarget);
565
+ return targetStateNode;
566
+ } catch (err) {
567
+ throw new Error(`Invalid transition definition for state node '${stateNode.id}':\n${err.message}`);
568
+ }
569
+ } else {
570
+ throw new Error(`Invalid target: "${target}" is not a valid target from the root node. Did you mean ".${target}"?`);
571
+ }
572
+ });
573
+ }
574
+ function resolveHistoryTarget(stateNode) {
575
+ const normalizedTarget = normalizeTarget(stateNode.config.target);
576
+ if (!normalizedTarget) {
577
+ return stateNode.parent.initial.target;
578
+ }
579
+ return normalizedTarget.map(t => typeof t === 'string' ? getStateNodeByPath(stateNode.parent, t) : t);
580
+ }
581
+ function isHistoryNode(stateNode) {
582
+ return stateNode.type === 'history';
583
+ }
584
+ function getInitialStateNodes(stateNode) {
585
+ const set = new Set();
586
+ function iter(descStateNode) {
587
+ if (set.has(descStateNode)) {
588
+ return;
589
+ }
590
+ set.add(descStateNode);
591
+ if (descStateNode.type === 'compound') {
592
+ for (const targetStateNode of descStateNode.initial.target) {
593
+ for (const a of getProperAncestors(targetStateNode, stateNode)) {
594
+ set.add(a);
595
+ }
596
+ iter(targetStateNode);
597
+ }
598
+ } else if (descStateNode.type === 'parallel') {
599
+ for (const child of getChildren(descStateNode)) {
600
+ iter(child);
601
+ }
602
+ }
603
+ }
604
+ iter(stateNode);
605
+ return [...set];
606
+ }
607
+ /**
608
+ * Returns the child state node from its relative `stateKey`, or throws.
609
+ */
610
+ function getStateNode(stateNode, stateKey) {
611
+ if (isStateId(stateKey)) {
612
+ return stateNode.machine.getStateNodeById(stateKey);
613
+ }
614
+ if (!stateNode.states) {
615
+ throw new Error(`Unable to retrieve child state '${stateKey}' from '${stateNode.id}'; no child states exist.`);
616
+ }
617
+ const result = stateNode.states[stateKey];
618
+ if (!result) {
619
+ throw new Error(`Child state '${stateKey}' does not exist on '${stateNode.id}'`);
620
+ }
621
+ return result;
622
+ }
623
+
624
+ /**
625
+ * Returns the relative state node from the given `statePath`, or throws.
626
+ *
627
+ * @param statePath The string or string array relative path to the state node.
628
+ */
629
+ function getStateNodeByPath(stateNode, statePath) {
630
+ if (typeof statePath === 'string' && isStateId(statePath)) {
631
+ try {
632
+ return stateNode.machine.getStateNodeById(statePath);
633
+ } catch (e) {
634
+ // try individual paths
635
+ // throw e;
636
+ }
637
+ }
638
+ const arrayStatePath = toStatePath(statePath).slice();
639
+ let currentStateNode = stateNode;
640
+ while (arrayStatePath.length) {
641
+ const key = arrayStatePath.shift();
642
+ if (!key.length) {
643
+ break;
644
+ }
645
+ currentStateNode = getStateNode(currentStateNode, key);
646
+ }
647
+ return currentStateNode;
648
+ }
649
+
650
+ /**
651
+ * Returns the state nodes represented by the current state value.
652
+ *
653
+ * @param state The state value or State instance
654
+ */
655
+ function getStateNodes(stateNode, state) {
656
+ const stateValue = state instanceof State ? state.value : toStateValue(state);
657
+ if (typeof stateValue === 'string') {
658
+ return [stateNode, stateNode.states[stateValue]];
659
+ }
660
+ const childStateKeys = Object.keys(stateValue);
661
+ const childStateNodes = childStateKeys.map(subStateKey => getStateNode(stateNode, subStateKey)).filter(Boolean);
662
+ return [stateNode.machine.root, stateNode].concat(childStateNodes, childStateKeys.reduce((allSubStateNodes, subStateKey) => {
663
+ const subStateNode = getStateNode(stateNode, subStateKey);
664
+ if (!subStateNode) {
665
+ return allSubStateNodes;
666
+ }
667
+ const subStateNodes = getStateNodes(subStateNode, stateValue[subStateKey]);
668
+ return allSubStateNodes.concat(subStateNodes);
669
+ }, []));
670
+ }
671
+ function transitionAtomicNode(stateNode, stateValue, state, event) {
672
+ const childStateNode = getStateNode(stateNode, stateValue);
673
+ const next = childStateNode.next(state, event);
674
+ if (!next || !next.length) {
675
+ return stateNode.next(state, event);
676
+ }
677
+ return next;
678
+ }
679
+ function transitionCompoundNode(stateNode, stateValue, state, event) {
680
+ const subStateKeys = Object.keys(stateValue);
681
+ const childStateNode = getStateNode(stateNode, subStateKeys[0]);
682
+ const next = transitionNode(childStateNode, stateValue[subStateKeys[0]], state, event);
683
+ if (!next || !next.length) {
684
+ return stateNode.next(state, event);
685
+ }
686
+ return next;
687
+ }
688
+ function transitionParallelNode(stateNode, stateValue, state, event) {
689
+ const allInnerTransitions = [];
690
+ for (const subStateKey of Object.keys(stateValue)) {
691
+ const subStateValue = stateValue[subStateKey];
692
+ if (!subStateValue) {
693
+ continue;
694
+ }
695
+ const subStateNode = getStateNode(stateNode, subStateKey);
696
+ const innerTransitions = transitionNode(subStateNode, subStateValue, state, event);
697
+ if (innerTransitions) {
698
+ allInnerTransitions.push(...innerTransitions);
699
+ }
700
+ }
701
+ if (!allInnerTransitions.length) {
702
+ return stateNode.next(state, event);
703
+ }
704
+ return allInnerTransitions;
705
+ }
706
+ function transitionNode(stateNode, stateValue, state, event) {
707
+ // leaf node
708
+ if (typeof stateValue === 'string') {
709
+ return transitionAtomicNode(stateNode, stateValue, state, event);
710
+ }
711
+
712
+ // compound node
713
+ if (Object.keys(stateValue).length === 1) {
714
+ return transitionCompoundNode(stateNode, stateValue, state, event);
715
+ }
716
+
717
+ // parallel node
718
+ return transitionParallelNode(stateNode, stateValue, state, event);
719
+ }
720
+ function getHistoryNodes(stateNode) {
721
+ return Object.keys(stateNode.states).map(key => stateNode.states[key]).filter(sn => sn.type === 'history');
722
+ }
723
+ function isDescendant(childStateNode, parentStateNode) {
724
+ let marker = childStateNode;
725
+ while (marker.parent && marker.parent !== parentStateNode) {
726
+ marker = marker.parent;
727
+ }
728
+ return marker.parent === parentStateNode;
729
+ }
730
+ function getPathFromRootToNode(stateNode) {
731
+ const path = [];
732
+ let marker = stateNode.parent;
733
+ while (marker) {
734
+ path.unshift(marker);
735
+ marker = marker.parent;
736
+ }
737
+ return path;
738
+ }
739
+ function hasIntersection(s1, s2) {
740
+ const set1 = new Set(s1);
741
+ const set2 = new Set(s2);
742
+ for (const item of set1) {
743
+ if (set2.has(item)) {
744
+ return true;
745
+ }
746
+ }
747
+ for (const item of set2) {
748
+ if (set1.has(item)) {
749
+ return true;
750
+ }
751
+ }
752
+ return false;
753
+ }
754
+ function removeConflictingTransitions(enabledTransitions, configuration, historyValue) {
755
+ const filteredTransitions = new Set();
756
+ for (const t1 of enabledTransitions) {
757
+ let t1Preempted = false;
758
+ const transitionsToRemove = new Set();
759
+ for (const t2 of filteredTransitions) {
760
+ if (hasIntersection(computeExitSet([t1], configuration, historyValue), computeExitSet([t2], configuration, historyValue))) {
761
+ if (isDescendant(t1.source, t2.source)) {
762
+ transitionsToRemove.add(t2);
763
+ } else {
764
+ t1Preempted = true;
765
+ break;
766
+ }
767
+ }
768
+ }
769
+ if (!t1Preempted) {
770
+ for (const t3 of transitionsToRemove) {
771
+ filteredTransitions.delete(t3);
772
+ }
773
+ filteredTransitions.add(t1);
774
+ }
775
+ }
776
+ return Array.from(filteredTransitions);
777
+ }
778
+ function findLCCA(stateNodes) {
779
+ const [head] = stateNodes;
780
+ let current = getPathFromRootToNode(head);
781
+ let candidates = [];
782
+ for (const stateNode of stateNodes) {
783
+ const path = getPathFromRootToNode(stateNode);
784
+ candidates = current.filter(sn => path.includes(sn));
785
+ current = candidates;
786
+ candidates = [];
787
+ }
788
+ return current[current.length - 1];
789
+ }
790
+ function getEffectiveTargetStates(transition, historyValue) {
791
+ if (!transition.target) {
792
+ return [];
793
+ }
794
+ const targets = new Set();
795
+ for (const targetNode of transition.target) {
796
+ if (isHistoryNode(targetNode)) {
797
+ if (historyValue[targetNode.id]) {
798
+ for (const node of historyValue[targetNode.id]) {
799
+ targets.add(node);
800
+ }
801
+ } else {
802
+ for (const node of getEffectiveTargetStates({
803
+ target: resolveHistoryTarget(targetNode)
804
+ }, historyValue)) {
805
+ targets.add(node);
806
+ }
807
+ }
808
+ } else {
809
+ targets.add(targetNode);
810
+ }
811
+ }
812
+ return [...targets];
813
+ }
814
+ function getTransitionDomain(transition, historyValue) {
815
+ const targetStates = getEffectiveTargetStates(transition, historyValue);
816
+ if (!targetStates) {
817
+ return null;
818
+ }
819
+ if (!transition.reenter && transition.source.type !== 'parallel' && targetStates.every(targetStateNode => isDescendant(targetStateNode, transition.source))) {
820
+ return transition.source;
821
+ }
822
+ const lcca = findLCCA(targetStates.concat(transition.source));
823
+ return lcca;
824
+ }
825
+ function computeExitSet(transitions, configuration, historyValue) {
826
+ const statesToExit = new Set();
827
+ for (const t of transitions) {
828
+ if (t.target?.length) {
829
+ const domain = getTransitionDomain(t, historyValue);
830
+ for (const stateNode of configuration) {
831
+ if (isDescendant(stateNode, domain)) {
832
+ statesToExit.add(stateNode);
833
+ }
834
+ }
835
+ }
836
+ }
837
+ return [...statesToExit];
838
+ }
839
+
840
+ /**
841
+ * https://www.w3.org/TR/scxml/#microstepProcedure
842
+ *
843
+ * @private
844
+ * @param transitions
845
+ * @param currentState
846
+ * @param mutConfiguration
847
+ */
848
+
849
+ function microstep(transitions, currentState, actorCtx, event, isInitial) {
850
+ const mutConfiguration = new Set(currentState.configuration);
851
+ if (!transitions.length) {
852
+ return currentState;
853
+ }
854
+ const microstate = microstepProcedure(transitions, currentState, mutConfiguration, event, actorCtx, isInitial);
855
+ return cloneState(microstate, {
856
+ value: {} // TODO: make optional
857
+ });
858
+ }
859
+
860
+ function microstepProcedure(transitions, currentState, mutConfiguration, event, actorCtx, isInitial) {
861
+ const actions = [];
862
+ const historyValue = {
863
+ ...currentState.historyValue
864
+ };
865
+ const filteredTransitions = removeConflictingTransitions(transitions, mutConfiguration, historyValue);
866
+ const internalQueue = [...currentState._internalQueue];
867
+
868
+ // Exit states
869
+ if (!isInitial) {
870
+ exitStates(filteredTransitions, mutConfiguration, historyValue, actions);
871
+ }
872
+
873
+ // Execute transition content
874
+ actions.push(...filteredTransitions.flatMap(t => t.actions));
875
+
876
+ // Enter states
877
+ enterStates(event, filteredTransitions, mutConfiguration, actions, internalQueue, currentState, historyValue, isInitial, actorCtx);
878
+ const nextConfiguration = [...mutConfiguration];
879
+ const done = isInFinalState(nextConfiguration);
880
+ if (done) {
881
+ const finalActions = nextConfiguration.sort((a, b) => b.order - a.order).flatMap(state => state.exit);
882
+ actions.push(...finalActions);
883
+ }
884
+ try {
885
+ const nextState = resolveActionsAndContext(actions, event, currentState, actorCtx);
886
+ const output = done ? getOutput(nextConfiguration, nextState.context, event, actorCtx.self) : undefined;
887
+ internalQueue.push(...nextState._internalQueue);
888
+ return cloneState(currentState, {
889
+ configuration: nextConfiguration,
890
+ historyValue,
891
+ _internalQueue: internalQueue,
892
+ context: nextState.context,
893
+ done,
894
+ output,
895
+ children: nextState.children
896
+ });
897
+ } catch (e) {
898
+ // TODO: Refactor this once proper error handling is implemented.
899
+ // See https://github.com/statelyai/rfcs/pull/4
900
+ throw e;
901
+ }
902
+ }
903
+ function enterStates(event, filteredTransitions, mutConfiguration, actions, internalQueue, currentState, historyValue, isInitial, actorContext) {
904
+ const statesToEnter = new Set();
905
+ const statesForDefaultEntry = new Set();
906
+ computeEntrySet(filteredTransitions, historyValue, statesForDefaultEntry, statesToEnter);
907
+
908
+ // In the initial state, the root state node is "entered".
909
+ if (isInitial) {
910
+ statesForDefaultEntry.add(currentState.machine.root);
911
+ }
912
+ for (const stateNodeToEnter of [...statesToEnter].sort((a, b) => a.order - b.order)) {
913
+ mutConfiguration.add(stateNodeToEnter);
914
+ for (const invokeDef of stateNodeToEnter.invoke) {
915
+ actions.push(invoke(invokeDef));
916
+ }
917
+
918
+ // Add entry actions
919
+ actions.push(...stateNodeToEnter.entry);
920
+ if (statesForDefaultEntry.has(stateNodeToEnter)) {
921
+ for (const stateNode of statesForDefaultEntry) {
922
+ const initialActions = stateNode.initial.actions;
923
+ actions.push(...initialActions);
924
+ }
925
+ }
926
+ if (stateNodeToEnter.type === 'final') {
927
+ const parent = stateNodeToEnter.parent;
928
+ if (!parent.parent) {
929
+ continue;
930
+ }
931
+ internalQueue.push(createDoneStateEvent(parent.id, stateNodeToEnter.output ? mapContext(stateNodeToEnter.output, currentState.context, event, actorContext.self) : undefined));
932
+ if (parent.parent) {
933
+ const grandparent = parent.parent;
934
+ if (grandparent.type === 'parallel') {
935
+ if (getChildren(grandparent).every(parentNode => isInFinalState([...mutConfiguration], parentNode))) {
936
+ internalQueue.push(createDoneStateEvent(grandparent.id));
937
+ }
938
+ }
939
+ }
940
+ }
941
+ }
942
+ }
943
+ function computeEntrySet(transitions, historyValue, statesForDefaultEntry, statesToEnter) {
944
+ for (const t of transitions) {
945
+ for (const s of t.target || []) {
946
+ addDescendantStatesToEnter(s, historyValue, statesForDefaultEntry, statesToEnter);
947
+ }
948
+ const ancestor = getTransitionDomain(t, historyValue);
949
+ const targetStates = getEffectiveTargetStates(t, historyValue);
950
+ for (const s of targetStates) {
951
+ addAncestorStatesToEnter(s, ancestor, statesToEnter, historyValue, statesForDefaultEntry);
952
+ }
953
+ }
954
+ }
955
+ function addDescendantStatesToEnter(stateNode, historyValue, statesForDefaultEntry, statesToEnter) {
956
+ if (isHistoryNode(stateNode)) {
957
+ if (historyValue[stateNode.id]) {
958
+ const historyStateNodes = historyValue[stateNode.id];
959
+ for (const s of historyStateNodes) {
960
+ addDescendantStatesToEnter(s, historyValue, statesForDefaultEntry, statesToEnter);
961
+ }
962
+ for (const s of historyStateNodes) {
963
+ addAncestorStatesToEnter(s, stateNode.parent, statesToEnter, historyValue, statesForDefaultEntry);
964
+ for (const stateForDefaultEntry of statesForDefaultEntry) {
965
+ statesForDefaultEntry.add(stateForDefaultEntry);
966
+ }
967
+ }
968
+ } else {
969
+ const targets = resolveHistoryTarget(stateNode);
970
+ for (const s of targets) {
971
+ addDescendantStatesToEnter(s, historyValue, statesForDefaultEntry, statesToEnter);
972
+ }
973
+ for (const s of targets) {
974
+ addAncestorStatesToEnter(s, stateNode, statesToEnter, historyValue, statesForDefaultEntry);
975
+ for (const stateForDefaultEntry of statesForDefaultEntry) {
976
+ statesForDefaultEntry.add(stateForDefaultEntry);
977
+ }
978
+ }
979
+ }
980
+ } else {
981
+ statesToEnter.add(stateNode);
982
+ if (stateNode.type === 'compound') {
983
+ statesForDefaultEntry.add(stateNode);
984
+ const initialStates = stateNode.initial.target;
985
+ for (const initialState of initialStates) {
986
+ addDescendantStatesToEnter(initialState, historyValue, statesForDefaultEntry, statesToEnter);
987
+ }
988
+ for (const initialState of initialStates) {
989
+ addAncestorStatesToEnter(initialState, stateNode, statesToEnter, historyValue, statesForDefaultEntry);
990
+ }
991
+ } else {
992
+ if (stateNode.type === 'parallel') {
993
+ for (const child of getChildren(stateNode).filter(sn => !isHistoryNode(sn))) {
994
+ if (![...statesToEnter].some(s => isDescendant(s, child))) {
995
+ addDescendantStatesToEnter(child, historyValue, statesForDefaultEntry, statesToEnter);
996
+ }
997
+ }
998
+ }
999
+ }
1000
+ }
1001
+ }
1002
+ function addAncestorStatesToEnter(stateNode, toStateNode, statesToEnter, historyValue, statesForDefaultEntry) {
1003
+ const properAncestors = getProperAncestors(stateNode, toStateNode);
1004
+ for (const anc of properAncestors) {
1005
+ statesToEnter.add(anc);
1006
+ if (anc.type === 'parallel') {
1007
+ for (const child of getChildren(anc).filter(sn => !isHistoryNode(sn))) {
1008
+ if (![...statesToEnter].some(s => isDescendant(s, child))) {
1009
+ addDescendantStatesToEnter(child, historyValue, statesForDefaultEntry, statesToEnter);
1010
+ }
1011
+ }
1012
+ }
1013
+ }
1014
+ }
1015
+ function exitStates(transitions, mutConfiguration, historyValue, actions) {
1016
+ const statesToExit = computeExitSet(transitions, mutConfiguration, historyValue);
1017
+ statesToExit.sort((a, b) => b.order - a.order);
1018
+
1019
+ // From SCXML algorithm: https://www.w3.org/TR/scxml/#exitStates
1020
+ for (const exitStateNode of statesToExit) {
1021
+ for (const historyNode of getHistoryNodes(exitStateNode)) {
1022
+ let predicate;
1023
+ if (historyNode.history === 'deep') {
1024
+ predicate = sn => isAtomicStateNode(sn) && isDescendant(sn, exitStateNode);
1025
+ } else {
1026
+ predicate = sn => {
1027
+ return sn.parent === exitStateNode;
1028
+ };
1029
+ }
1030
+ historyValue[historyNode.id] = Array.from(mutConfiguration).filter(predicate);
1031
+ }
1032
+ }
1033
+ for (const s of statesToExit) {
1034
+ actions.push(...s.exit, ...s.invoke.map(def => stop(def.id)));
1035
+ mutConfiguration.delete(s);
1036
+ }
1037
+ }
1038
+ function resolveActionsAndContext(actions, event, currentState, actorCtx) {
1039
+ const {
1040
+ machine
1041
+ } = currentState;
1042
+ // TODO: this `cloneState` is really just a hack to prevent infinite loops
1043
+ // we need to take another look at how internal queue is managed
1044
+ let intermediateState = cloneState(currentState, {
1045
+ _internalQueue: []
1046
+ });
1047
+ for (const action of actions) {
1048
+ const isInline = typeof action === 'function';
1049
+ const resolved = isInline ? action :
1050
+ // the existing type of `.actions` assumes non-nullable `TExpressionAction`
1051
+ // it's fine to cast this here to get a common type and lack of errors in the rest of the code
1052
+ // our logic below makes sure that we call those 2 "variants" correctly
1053
+ machine.implementations.actions[typeof action === 'string' ? action : action.type];
1054
+ if (!resolved) {
1055
+ continue;
1056
+ }
1057
+ const actionArgs = {
1058
+ context: intermediateState.context,
1059
+ event,
1060
+ self: actorCtx?.self,
1061
+ system: actorCtx?.system,
1062
+ action: isInline ? undefined : typeof action === 'string' ? {
1063
+ type: action
1064
+ } : typeof action.params === 'function' ? {
1065
+ type: action.type,
1066
+ params: action.params({
1067
+ context: intermediateState.context,
1068
+ event
1069
+ })
1070
+ } :
1071
+ // TS isn't able to narrow it down here
1072
+ action
1073
+ };
1074
+ if (!('resolve' in resolved)) {
1075
+ if (actorCtx?.self.status === ActorStatus.Running) {
1076
+ resolved(actionArgs);
1077
+ } else {
1078
+ actorCtx?.defer(() => resolved(actionArgs));
1079
+ }
1080
+ continue;
1081
+ }
1082
+ const builtinAction = resolved;
1083
+ const [nextState, params, actions] = builtinAction.resolve(actorCtx, intermediateState, actionArgs, resolved // this holds all params
1084
+ );
1085
+
1086
+ intermediateState = nextState;
1087
+ if ('execute' in resolved) {
1088
+ if (actorCtx?.self.status === ActorStatus.Running) {
1089
+ builtinAction.execute(actorCtx, params);
1090
+ } else {
1091
+ actorCtx?.defer(builtinAction.execute.bind(null, actorCtx, params));
1092
+ }
1093
+ }
1094
+ if (actions) {
1095
+ intermediateState = resolveActionsAndContext(actions, event, intermediateState, actorCtx);
1096
+ }
1097
+ }
1098
+ return intermediateState;
1099
+ }
1100
+ function macrostep(state, event, actorCtx) {
1101
+ let nextState = state;
1102
+ const states = [];
1103
+
1104
+ // Handle stop event
1105
+ if (event.type === XSTATE_STOP) {
1106
+ nextState = stopStep(event, nextState, actorCtx);
1107
+ states.push(nextState);
1108
+ return {
1109
+ state: nextState,
1110
+ microstates: states
1111
+ };
1112
+ }
1113
+ let nextEvent = event;
1114
+
1115
+ // Assume the state is at rest (no raised events)
1116
+ // Determine the next state based on the next microstep
1117
+ if (nextEvent.type !== XSTATE_INIT) {
1118
+ const transitions = selectTransitions(nextEvent, nextState);
1119
+ nextState = microstep(transitions, state, actorCtx, nextEvent, false);
1120
+ states.push(nextState);
1121
+ }
1122
+ while (!nextState.done) {
1123
+ let enabledTransitions = selectEventlessTransitions(nextState, nextEvent);
1124
+ if (!enabledTransitions.length) {
1125
+ if (!nextState._internalQueue.length) {
1126
+ break;
1127
+ } else {
1128
+ nextEvent = nextState._internalQueue[0];
1129
+ const transitions = selectTransitions(nextEvent, nextState);
1130
+ nextState = microstep(transitions, nextState, actorCtx, nextEvent, false);
1131
+ nextState._internalQueue.shift();
1132
+ states.push(nextState);
1133
+ }
1134
+ } else {
1135
+ nextState = microstep(enabledTransitions, nextState, actorCtx, nextEvent, false);
1136
+ states.push(nextState);
1137
+ }
1138
+ }
1139
+ if (nextState.done) {
1140
+ // Perform the stop step to ensure that child actors are stopped
1141
+ stopStep(nextEvent, nextState, actorCtx);
1142
+ }
1143
+ return {
1144
+ state: nextState,
1145
+ microstates: states
1146
+ };
1147
+ }
1148
+ function stopStep(event, nextState, actorCtx) {
1149
+ const actions = [];
1150
+ for (const stateNode of nextState.configuration.sort((a, b) => b.order - a.order)) {
1151
+ actions.push(...stateNode.exit);
1152
+ }
1153
+ for (const child of Object.values(nextState.children)) {
1154
+ actions.push(stop(child));
1155
+ }
1156
+ return resolveActionsAndContext(actions, event, nextState, actorCtx);
1157
+ }
1158
+ function selectTransitions(event, nextState) {
1159
+ return nextState.machine.getTransitionData(nextState, event);
1160
+ }
1161
+ function selectEventlessTransitions(nextState, event) {
1162
+ const enabledTransitionSet = new Set();
1163
+ const atomicStates = nextState.configuration.filter(isAtomicStateNode);
1164
+ for (const stateNode of atomicStates) {
1165
+ loop: for (const s of [stateNode].concat(getProperAncestors(stateNode, null))) {
1166
+ if (!s.always) {
1167
+ continue;
1168
+ }
1169
+ for (const transition of s.always) {
1170
+ if (transition.guard === undefined || evaluateGuard(transition.guard, nextState.context, event, nextState)) {
1171
+ enabledTransitionSet.add(transition);
1172
+ break loop;
1173
+ }
1174
+ }
1175
+ }
1176
+ }
1177
+ return removeConflictingTransitions(Array.from(enabledTransitionSet), new Set(nextState.configuration), nextState.historyValue);
1178
+ }
1179
+
1180
+ /**
1181
+ * Resolves a partial state value with its full representation in the state node's machine.
1182
+ *
1183
+ * @param stateValue The partial state value to resolve.
1184
+ */
1185
+ function resolveStateValue(rootNode, stateValue) {
1186
+ const configuration = getConfiguration(getStateNodes(rootNode, stateValue));
1187
+ return getStateValue(rootNode, [...configuration]);
1188
+ }
1189
+ function getInitialConfiguration(rootNode) {
1190
+ const configuration = [];
1191
+ const initialTransition = rootNode.initial;
1192
+ const statesToEnter = new Set();
1193
+ const statesForDefaultEntry = new Set([rootNode]);
1194
+ computeEntrySet([initialTransition], {}, statesForDefaultEntry, statesToEnter);
1195
+ for (const stateNodeToEnter of [...statesToEnter].sort((a, b) => a.order - b.order)) {
1196
+ configuration.push(stateNodeToEnter);
1197
+ }
1198
+ return configuration;
1199
+ }
1200
+
1201
+ class State {
1202
+ /**
1203
+ * Indicates whether the state is a final state.
1204
+ */
1205
+
1206
+ /**
1207
+ * The output data of the top-level finite state.
1208
+ */
1209
+
1210
+ /**
1211
+ * The enabled state nodes representative of the state value.
1212
+ */
1213
+
1214
+ /**
1215
+ * An object mapping actor names to spawned/invoked actors.
1216
+ */
1217
+
1218
+ /**
1219
+ * Creates a new State instance for the given `stateValue` and `context`.
1220
+ * @param stateValue
1221
+ * @param context
1222
+ */
1223
+ static from(stateValue, context = {}, machine) {
1224
+ if (stateValue instanceof State) {
1225
+ if (stateValue.context !== context) {
1226
+ return new State({
1227
+ value: stateValue.value,
1228
+ context,
1229
+ meta: {},
1230
+ configuration: [],
1231
+ // TODO: fix,
1232
+ children: {}
1233
+ }, machine);
1234
+ }
1235
+ return stateValue;
1236
+ }
1237
+ const configuration = getConfiguration(getStateNodes(machine.root, stateValue));
1238
+ return new State({
1239
+ value: stateValue,
1240
+ context,
1241
+ meta: undefined,
1242
+ configuration: Array.from(configuration),
1243
+ children: {}
1244
+ }, machine);
1245
+ }
1246
+
1247
+ /**
1248
+ * Creates a new `State` instance that represents the current state of a running machine.
1249
+ *
1250
+ * @param config
1251
+ */
1252
+ constructor(config, machine) {
1253
+ this.machine = machine;
1254
+ this.tags = void 0;
1255
+ this.value = void 0;
1256
+ this.done = void 0;
1257
+ this.output = void 0;
1258
+ this.error = void 0;
1259
+ this.context = void 0;
1260
+ this.historyValue = {};
1261
+ this._internalQueue = void 0;
1262
+ this.configuration = void 0;
1263
+ this.children = void 0;
1264
+ this.context = config.context;
1265
+ this._internalQueue = config._internalQueue ?? [];
1266
+ this.historyValue = config.historyValue || {};
1267
+ this.matches = this.matches.bind(this);
1268
+ this.toStrings = this.toStrings.bind(this);
1269
+ this.configuration = config.configuration ?? Array.from(getConfiguration(getStateNodes(machine.root, config.value)));
1270
+ this.children = config.children;
1271
+ this.value = getStateValue(machine.root, this.configuration);
1272
+ this.tags = new Set(flatten(this.configuration.map(sn => sn.tags)));
1273
+ this.done = config.done ?? false;
1274
+ this.output = config.output;
1275
+ this.error = config.error;
1276
+ }
1277
+
1278
+ /**
1279
+ * Returns an array of all the string leaf state node paths.
1280
+ * @param stateValue
1281
+ * @param delimiter The character(s) that separate each subpath in the string state node path.
1282
+ */
1283
+ toStrings(stateValue = this.value) {
1284
+ if (typeof stateValue === 'string') {
1285
+ return [stateValue];
1286
+ }
1287
+ const valueKeys = Object.keys(stateValue);
1288
+ return valueKeys.concat(...valueKeys.map(key => this.toStrings(stateValue[key]).map(s => key + STATE_DELIMITER + s)));
1289
+ }
1290
+ toJSON() {
1291
+ const {
1292
+ configuration,
1293
+ tags,
1294
+ machine,
1295
+ ...jsonValues
1296
+ } = this;
1297
+ return {
1298
+ ...jsonValues,
1299
+ tags: Array.from(tags),
1300
+ meta: this.meta
1301
+ };
1302
+ }
1303
+
1304
+ /**
1305
+ * Whether the current state value is a subset of the given parent state value.
1306
+ * @param parentStateValue
1307
+ */
1308
+ matches(parentStateValue) {
1309
+ return matchesState(parentStateValue, this.value);
1310
+ }
1311
+
1312
+ /**
1313
+ * Whether the current state configuration has a state node with the specified `tag`.
1314
+ * @param tag
1315
+ */
1316
+ hasTag(tag) {
1317
+ return this.tags.has(tag);
1318
+ }
1319
+
1320
+ /**
1321
+ * Determines whether sending the `event` will cause a non-forbidden transition
1322
+ * to be selected, even if the transitions have no actions nor
1323
+ * change the state value.
1324
+ *
1325
+ * @param event The event to test
1326
+ * @returns Whether the event will cause a transition
1327
+ */
1328
+ can(event) {
1329
+ const transitionData = this.machine.getTransitionData(this, event);
1330
+ return !!transitionData?.length &&
1331
+ // Check that at least one transition is not forbidden
1332
+ transitionData.some(t => t.target !== undefined || t.actions.length);
1333
+ }
1334
+
1335
+ /**
1336
+ * The next events that will cause a transition from the current state.
1337
+ */
1338
+ get nextEvents() {
1339
+ return memo(this, 'nextEvents', () => {
1340
+ return [...new Set(flatten([...this.configuration.map(sn => sn.ownEvents)]))];
1341
+ });
1342
+ }
1343
+ get meta() {
1344
+ return this.configuration.reduce((acc, stateNode) => {
1345
+ if (stateNode.meta !== undefined) {
1346
+ acc[stateNode.id] = stateNode.meta;
1347
+ }
1348
+ return acc;
1349
+ }, {});
1350
+ }
1351
+ }
1352
+ function cloneState(state, config = {}) {
1353
+ return new State({
1354
+ ...state,
1355
+ ...config
1356
+ }, state.machine);
1357
+ }
1358
+ function getPersistedState(state) {
1359
+ const {
1360
+ configuration,
1361
+ tags,
1362
+ machine,
1363
+ children,
1364
+ ...jsonValues
1365
+ } = state;
1366
+ const childrenJson = {};
1367
+ for (const id in children) {
1368
+ childrenJson[id] = {
1369
+ state: children[id].getPersistedState?.(),
1370
+ src: children[id].src
1371
+ };
1372
+ }
1373
+ return {
1374
+ ...jsonValues,
1375
+ children: childrenJson
1376
+ };
1377
+ }
1378
+
1379
+ function resolve(_, state, args, {
1380
+ event: eventOrExpr,
1381
+ id,
1382
+ delay
1383
+ }) {
1384
+ const delaysMap = state.machine.implementations.delays;
1385
+ if (typeof eventOrExpr === 'string') {
1386
+ throw new Error(`Only event objects may be used with raise; use raise({ type: "${eventOrExpr}" }) instead`);
1387
+ }
1388
+ const resolvedEvent = typeof eventOrExpr === 'function' ? eventOrExpr(args) : eventOrExpr;
1389
+ let resolvedDelay;
1390
+ if (typeof delay === 'string') {
1391
+ const configDelay = delaysMap && delaysMap[delay];
1392
+ resolvedDelay = typeof configDelay === 'function' ? configDelay(args) : configDelay;
1393
+ } else {
1394
+ resolvedDelay = typeof delay === 'function' ? delay(args) : delay;
1395
+ }
1396
+ return [typeof resolvedDelay !== 'number' ? cloneState(state, {
1397
+ _internalQueue: state._internalQueue.concat(resolvedEvent)
1398
+ }) : state, {
1399
+ event: resolvedEvent,
1400
+ id,
1401
+ delay: resolvedDelay
1402
+ }];
1403
+ }
1404
+ function execute(actorContext, params) {
1405
+ if (typeof params.delay === 'number') {
1406
+ actorContext.self.delaySend(params);
1407
+ return;
1408
+ }
1409
+ }
1410
+ /**
1411
+ * Raises an event. This places the event in the internal event queue, so that
1412
+ * the event is immediately consumed by the machine in the current step.
1413
+ *
1414
+ * @param eventType The event to raise.
1415
+ */
1416
+ function raise(eventOrExpr, options) {
1417
+ function raise(_) {
1418
+ }
1419
+ raise.type = 'xstate.raise';
1420
+ raise.event = eventOrExpr;
1421
+ raise.id = options?.id;
1422
+ raise.delay = options?.delay;
1423
+ raise.resolve = resolve;
1424
+ raise.execute = execute;
1425
+ return raise;
1426
+ }
1427
+
1428
+ export { raise as A, stop as B, State as S, formatTransition as a, formatInitialTransition as b, getCandidates as c, getConfiguration as d, evaluateGuard as e, formatTransitions as f, getDelayedTransitions as g, getStateNodes as h, isInFinalState as i, cloneState as j, macrostep as k, getInitialConfiguration as l, memo as m, resolveActionsAndContext as n, microstep as o, isAtomicStateNode as p, isStateId as q, resolveStateValue as r, getStateNodeByPath as s, transitionNode as t, getPersistedState as u, and as v, not as w, or as x, stateIn as y, cancel as z };