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