xstate 5.0.0-beta.10 → 5.0.0-beta.11

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 (55) hide show
  1. package/actions/dist/xstate-actions.cjs.js +29 -5
  2. package/actions/dist/{xstate-actions.cjs.dev.js → xstate-actions.development.cjs.js} +2 -2
  3. package/actions/dist/xstate-actions.development.esm.js +2 -0
  4. package/actions/dist/xstate-actions.esm.js +2 -2
  5. package/actions/dist/xstate-actions.umd.min.js +1 -1
  6. package/actions/dist/xstate-actions.umd.min.js.map +1 -1
  7. package/actors/dist/xstate-actors.cjs.js +20 -5
  8. package/actors/dist/{xstate-actors.cjs.dev.js → xstate-actors.development.cjs.js} +2 -2
  9. package/actors/dist/xstate-actors.development.esm.js +2 -0
  10. package/actors/dist/xstate-actors.esm.js +2 -2
  11. package/actors/dist/xstate-actors.umd.min.js +1 -1
  12. package/actors/dist/xstate-actors.umd.min.js.map +1 -1
  13. package/dev/dist/xstate-dev.cjs.js +45 -4
  14. package/{dist/index-0f3fdf0c.cjs.prod.js → dev/dist/xstate-dev.development.cjs.js} +6 -7
  15. package/{dist/index-50bd0aff.esm.js → dev/dist/xstate-dev.development.esm.js} +6 -8
  16. package/dev/dist/xstate-dev.esm.js +42 -1
  17. package/dev/dist/xstate-dev.umd.min.js +1 -1
  18. package/dev/dist/xstate-dev.umd.min.js.map +1 -1
  19. package/dist/actions-26f9aa9d.cjs.js +3388 -0
  20. package/dist/actions-acbe7aa1.development.cjs.js +3423 -0
  21. package/dist/actions-b82e841e.esm.js +3306 -0
  22. package/dist/actions-cff79077.development.esm.js +3341 -0
  23. package/dist/declarations/src/utils.d.ts +0 -1
  24. package/dist/declarations/src/waitFor.d.ts +1 -1
  25. package/dist/xstate.cjs.js +802 -4
  26. package/dist/xstate.development.cjs.js +808 -0
  27. package/dist/xstate.development.esm.js +770 -0
  28. package/dist/xstate.esm.js +543 -662
  29. package/dist/xstate.umd.min.js +1 -1
  30. package/dist/xstate.umd.min.js.map +1 -1
  31. package/guards/dist/xstate-guards.cjs.js +13 -5
  32. package/guards/dist/{xstate-guards.cjs.prod.js → xstate-guards.development.cjs.js} +2 -2
  33. package/guards/dist/xstate-guards.development.esm.js +2 -0
  34. package/guards/dist/xstate-guards.esm.js +2 -2
  35. package/guards/dist/xstate-guards.umd.min.js +1 -1
  36. package/guards/dist/xstate-guards.umd.min.js.map +1 -1
  37. package/package.json +52 -1
  38. package/actions/dist/xstate-actions.cjs.prod.js +0 -31
  39. package/actors/dist/xstate-actors.cjs.prod.js +0 -22
  40. package/dev/dist/xstate-dev.cjs.dev.js +0 -11
  41. package/dev/dist/xstate-dev.cjs.prod.js +0 -11
  42. package/dist/actions-109712d3.cjs.dev.js +0 -4357
  43. package/dist/actions-67f1d04e.esm.js +0 -4270
  44. package/dist/actions-d0262a43.cjs.prod.js +0 -4333
  45. package/dist/declarations/actions/dynamicAction.d.ts +0 -5
  46. package/dist/declarations/src/Mailbox.d.ts +0 -12
  47. package/dist/declarations/src/actions/invoke.d.ts +0 -3
  48. package/dist/declarations/src/environment.d.ts +0 -1
  49. package/dist/declarations/src/memo.d.ts +0 -2
  50. package/dist/declarations/src/spawn.d.ts +0 -2
  51. package/dist/declarations/src/system.d.ts +0 -2
  52. package/dist/index-ebaab3c9.cjs.dev.js +0 -52
  53. package/dist/xstate.cjs.dev.js +0 -933
  54. package/dist/xstate.cjs.prod.js +0 -930
  55. package/guards/dist/xstate-guards.cjs.dev.js +0 -15
@@ -0,0 +1,3306 @@
1
+ import { devToolsAdapter } from '../dev/dist/xstate-dev.esm.js';
2
+
3
+ // https://github.com/microsoft/TypeScript/issues/23182#issuecomment-379091887
4
+
5
+ // TODO: replace in v5 with:
6
+ // export type IndexByType<T extends { type: string }> = { [E in T as E['type']]: E; };
7
+
8
+ /**
9
+ * The full definition of an event, with a string `type`.
10
+ */
11
+
12
+ // TODO: do not accept machines without all implementations
13
+ // we should also accept a raw machine as a behavior here
14
+ // or just make machine a behavior
15
+
16
+ // TODO: narrow this to behaviors from machine
17
+
18
+ // TODO: fix last param
19
+
20
+ /**
21
+ * Extracts action objects that have no extra properties.
22
+ */
23
+
24
+ /**
25
+ * The string or object representing the state value relative to the parent state node.
26
+ *
27
+ * - For a child atomic state node, this is a string, e.g., `"pending"`.
28
+ * - For complex state nodes, this is an object, e.g., `{ success: "someChildState" }`.
29
+ */
30
+
31
+ // TODO: remove once TS fixes this type-widening issue
32
+
33
+ // TODO: possibly refactor this somehow, use even a simpler type, and maybe even make `machine.options` private or something
34
+
35
+ let ActionTypes = /*#__PURE__*/function (ActionTypes) {
36
+ ActionTypes["Stop"] = "xstate.stop";
37
+ ActionTypes["Raise"] = "xstate.raise";
38
+ ActionTypes["Send"] = "xstate.send";
39
+ ActionTypes["Cancel"] = "xstate.cancel";
40
+ ActionTypes["Assign"] = "xstate.assign";
41
+ ActionTypes["After"] = "xstate.after";
42
+ ActionTypes["DoneState"] = "done.state";
43
+ ActionTypes["DoneInvoke"] = "done.invoke";
44
+ ActionTypes["Log"] = "xstate.log";
45
+ ActionTypes["Init"] = "xstate.init";
46
+ ActionTypes["Invoke"] = "xstate.invoke";
47
+ ActionTypes["ErrorExecution"] = "error.execution";
48
+ ActionTypes["ErrorCommunication"] = "error.communication";
49
+ ActionTypes["ErrorPlatform"] = "error.platform";
50
+ ActionTypes["ErrorCustom"] = "xstate.error";
51
+ ActionTypes["Pure"] = "xstate.pure";
52
+ ActionTypes["Choose"] = "xstate.choose";
53
+ return ActionTypes;
54
+ }({});
55
+ let SpecialTargets = /*#__PURE__*/function (SpecialTargets) {
56
+ SpecialTargets["Parent"] = "#_parent";
57
+ SpecialTargets["Internal"] = "#_internal";
58
+ return SpecialTargets;
59
+ }({});
60
+
61
+ // xstate-specific action types
62
+ const stop$1 = ActionTypes.Stop;
63
+ const raise$1 = ActionTypes.Raise;
64
+ const send$1 = ActionTypes.Send;
65
+ const cancel$1 = ActionTypes.Cancel;
66
+ const assign$1 = ActionTypes.Assign;
67
+ const after$1 = ActionTypes.After;
68
+ const doneState = ActionTypes.DoneState;
69
+ const log$1 = ActionTypes.Log;
70
+ const init = ActionTypes.Init;
71
+ const invoke$1 = ActionTypes.Invoke;
72
+ const errorExecution = ActionTypes.ErrorExecution;
73
+ const errorPlatform = ActionTypes.ErrorPlatform;
74
+ const error$1 = ActionTypes.ErrorCustom;
75
+ const choose$1 = ActionTypes.Choose;
76
+ const pure$1 = ActionTypes.Pure;
77
+
78
+ var actionTypes = /*#__PURE__*/Object.freeze({
79
+ __proto__: null,
80
+ stop: stop$1,
81
+ raise: raise$1,
82
+ send: send$1,
83
+ cancel: cancel$1,
84
+ assign: assign$1,
85
+ after: after$1,
86
+ doneState: doneState,
87
+ log: log$1,
88
+ init: init,
89
+ invoke: invoke$1,
90
+ errorExecution: errorExecution,
91
+ errorPlatform: errorPlatform,
92
+ error: error$1,
93
+ choose: choose$1,
94
+ pure: pure$1
95
+ });
96
+
97
+ const STATE_DELIMITER = '.';
98
+ const TARGETLESS_KEY = '';
99
+ const NULL_EVENT = '';
100
+ const STATE_IDENTIFIER = '#';
101
+ const WILDCARD = '*';
102
+
103
+ function matchesState(parentStateId, childStateId, delimiter = STATE_DELIMITER) {
104
+ const parentStateValue = toStateValue(parentStateId, delimiter);
105
+ const childStateValue = toStateValue(childStateId, delimiter);
106
+ if (isString(childStateValue)) {
107
+ if (isString(parentStateValue)) {
108
+ return childStateValue === parentStateValue;
109
+ }
110
+
111
+ // Parent more specific than child
112
+ return false;
113
+ }
114
+ if (isString(parentStateValue)) {
115
+ return parentStateValue in childStateValue;
116
+ }
117
+ return Object.keys(parentStateValue).every(key => {
118
+ if (!(key in childStateValue)) {
119
+ return false;
120
+ }
121
+ return matchesState(parentStateValue[key], childStateValue[key]);
122
+ });
123
+ }
124
+ function toStatePath(stateId, delimiter) {
125
+ try {
126
+ if (isArray(stateId)) {
127
+ return stateId;
128
+ }
129
+ return stateId.toString().split(delimiter);
130
+ } catch (e) {
131
+ throw new Error(`'${stateId}' is not a valid state path.`);
132
+ }
133
+ }
134
+ function isStateLike(state) {
135
+ return typeof state === 'object' && 'value' in state && 'context' in state && 'event' in state;
136
+ }
137
+ function toStateValue(stateValue, delimiter) {
138
+ if (isStateLike(stateValue)) {
139
+ return stateValue.value;
140
+ }
141
+ if (isArray(stateValue)) {
142
+ return pathToStateValue(stateValue);
143
+ }
144
+ if (typeof stateValue !== 'string') {
145
+ return stateValue;
146
+ }
147
+ const statePath = toStatePath(stateValue, delimiter);
148
+ return pathToStateValue(statePath);
149
+ }
150
+ function pathToStateValue(statePath) {
151
+ if (statePath.length === 1) {
152
+ return statePath[0];
153
+ }
154
+ const value = {};
155
+ let marker = value;
156
+ for (let i = 0; i < statePath.length - 1; i++) {
157
+ if (i === statePath.length - 2) {
158
+ marker[statePath[i]] = statePath[i + 1];
159
+ } else {
160
+ marker[statePath[i]] = {};
161
+ marker = marker[statePath[i]];
162
+ }
163
+ }
164
+ return value;
165
+ }
166
+ function mapValues(collection, iteratee) {
167
+ const result = {};
168
+ const collectionKeys = Object.keys(collection);
169
+ for (let i = 0; i < collectionKeys.length; i++) {
170
+ const key = collectionKeys[i];
171
+ result[key] = iteratee(collection[key], key, collection, i);
172
+ }
173
+ return result;
174
+ }
175
+ function flatten(array) {
176
+ return [].concat(...array);
177
+ }
178
+ function toArrayStrict(value) {
179
+ if (isArray(value)) {
180
+ return value;
181
+ }
182
+ return [value];
183
+ }
184
+ function toArray(value) {
185
+ if (value === undefined) {
186
+ return [];
187
+ }
188
+ return toArrayStrict(value);
189
+ }
190
+ function mapContext(mapper, context, event) {
191
+ if (isFunction(mapper)) {
192
+ return mapper({
193
+ context,
194
+ event
195
+ });
196
+ }
197
+ const result = {};
198
+ const args = {
199
+ context,
200
+ event
201
+ };
202
+ for (const key of Object.keys(mapper)) {
203
+ const subMapper = mapper[key];
204
+ if (isFunction(subMapper)) {
205
+ result[key] = subMapper(args);
206
+ } else {
207
+ result[key] = subMapper;
208
+ }
209
+ }
210
+ return result;
211
+ }
212
+ function isPromiseLike(value) {
213
+ if (value instanceof Promise) {
214
+ return true;
215
+ }
216
+ // Check if shape matches the Promise/A+ specification for a "thenable".
217
+ if (value !== null && (isFunction(value) || typeof value === 'object') && isFunction(value.then)) {
218
+ return true;
219
+ }
220
+ return false;
221
+ }
222
+ function isArray(value) {
223
+ return Array.isArray(value);
224
+ }
225
+
226
+ // tslint:disable-next-line:ban-types
227
+ function isFunction(value) {
228
+ return typeof value === 'function';
229
+ }
230
+ function isString(value) {
231
+ return typeof value === 'string';
232
+ }
233
+ function isErrorEvent(event) {
234
+ return typeof event.type === 'string' && (event.type === errorExecution || event.type.startsWith(errorPlatform));
235
+ }
236
+ function toTransitionConfigArray(event, configLike) {
237
+ const transitions = toArrayStrict(configLike).map(transitionLike => {
238
+ if (typeof transitionLike === 'undefined' || typeof transitionLike === 'string') {
239
+ return {
240
+ target: transitionLike,
241
+ event
242
+ };
243
+ }
244
+ return {
245
+ ...transitionLike,
246
+ event
247
+ };
248
+ });
249
+ return transitions;
250
+ }
251
+ function normalizeTarget(target) {
252
+ if (target === undefined || target === TARGETLESS_KEY) {
253
+ return undefined;
254
+ }
255
+ return toArray(target);
256
+ }
257
+ function toInvokeConfig(invocable, id) {
258
+ if (typeof invocable === 'object') {
259
+ if ('src' in invocable) {
260
+ return invocable;
261
+ }
262
+ if ('transition' in invocable) {
263
+ return {
264
+ id,
265
+ src: invocable
266
+ };
267
+ }
268
+ }
269
+ return {
270
+ id,
271
+ src: invocable
272
+ };
273
+ }
274
+ function toObserver(nextHandler, errorHandler, completionHandler) {
275
+ const noop = () => {};
276
+ const isObserver = typeof nextHandler === 'object';
277
+ const self = isObserver ? nextHandler : null;
278
+ return {
279
+ next: ((isObserver ? nextHandler.next : nextHandler) || noop).bind(self),
280
+ error: ((isObserver ? nextHandler.error : errorHandler) || noop).bind(self),
281
+ complete: ((isObserver ? nextHandler.complete : completionHandler) || noop).bind(self)
282
+ };
283
+ }
284
+ function createInvokeId(stateNodeId, index) {
285
+ return `${stateNodeId}:invocation[${index}]`;
286
+ }
287
+ function resolveReferencedActor(referenced) {
288
+ return referenced ? 'transition' in referenced ? {
289
+ src: referenced,
290
+ input: undefined
291
+ } : referenced : undefined;
292
+ }
293
+
294
+ function createDynamicAction(action, resolve) {
295
+ return {
296
+ type: action.type,
297
+ params: action.params,
298
+ resolve
299
+ };
300
+ }
301
+ function isDynamicAction(action) {
302
+ return typeof action === 'object' && action !== null && 'resolve' in action;
303
+ }
304
+
305
+ /**
306
+ * Sends an event. This returns an action that will be read by an interpreter to
307
+ * send the event in the next step, after the current step is finished executing.
308
+ *
309
+ * @deprecated Use the `sendTo(...)` action creator instead.
310
+ *
311
+ * @param eventOrExpr The event to send.
312
+ * @param options Options to pass into the send event:
313
+ * - `id` - The unique send event identifier (used with `cancel()`).
314
+ * - `delay` - The number of milliseconds to delay the sending of the event.
315
+ * - `to` - The target of this event (by default, the machine the event was sent from).
316
+ */
317
+ function send(eventOrExpr, options) {
318
+ return createDynamicAction({
319
+ type: send$1,
320
+ params: {
321
+ to: options ? options.to : undefined,
322
+ delay: options ? options.delay : undefined,
323
+ event: eventOrExpr,
324
+ id: options && options.id !== undefined ? options.id : isFunction(eventOrExpr) ? eventOrExpr.name : eventOrExpr.type
325
+ }
326
+ }, (event, {
327
+ actorContext,
328
+ state
329
+ }) => {
330
+ const params = {
331
+ to: options ? options.to : undefined,
332
+ delay: options ? options.delay : undefined,
333
+ event: eventOrExpr,
334
+ // TODO: don't auto-generate IDs here like that
335
+ // there is too big chance of the ID collision
336
+ id: options && options.id !== undefined ? options.id : isFunction(eventOrExpr) ? eventOrExpr.name : eventOrExpr.type
337
+ };
338
+ const args = {
339
+ context: state.context,
340
+ event,
341
+ self: actorContext?.self ?? null,
342
+ system: actorContext?.system
343
+ };
344
+ const delaysMap = state.machine.options.delays;
345
+
346
+ // TODO: helper function for resolving Expr
347
+ if (typeof eventOrExpr === 'string') {
348
+ throw new Error(`Only event objects may be used with sendTo; use sendTo({ type: "${eventOrExpr}" }) instead`);
349
+ }
350
+ const resolvedEvent = isFunction(eventOrExpr) ? eventOrExpr(args) : eventOrExpr;
351
+ let resolvedDelay;
352
+ if (isString(params.delay)) {
353
+ const configDelay = delaysMap && delaysMap[params.delay];
354
+ resolvedDelay = isFunction(configDelay) ? configDelay(args) : configDelay;
355
+ } else {
356
+ resolvedDelay = isFunction(params.delay) ? params.delay(args) : params.delay;
357
+ }
358
+ const resolvedTarget = isFunction(params.to) ? params.to(args) : params.to;
359
+ let targetActorRef;
360
+ if (typeof resolvedTarget === 'string') {
361
+ if (resolvedTarget === SpecialTargets.Parent) {
362
+ targetActorRef = actorContext?.self._parent;
363
+ } else if (resolvedTarget === SpecialTargets.Internal) {
364
+ targetActorRef = actorContext?.self;
365
+ } else if (resolvedTarget.startsWith('#_')) {
366
+ // SCXML compatibility: https://www.w3.org/TR/scxml/#SCXMLEventProcessor
367
+ // #_invokeid. If the target is the special term '#_invokeid', where invokeid is the invokeid of an SCXML session that the sending session has created by <invoke>, the Processor must add the event to the external queue of that session.
368
+ targetActorRef = state.children[resolvedTarget.slice(2)];
369
+ } else {
370
+ targetActorRef = state.children[resolvedTarget];
371
+ }
372
+ if (!targetActorRef) {
373
+ throw new Error(`Unable to send event to actor '${resolvedTarget}' from machine '${state.machine.id}'.`);
374
+ }
375
+ } else {
376
+ targetActorRef = resolvedTarget || actorContext?.self;
377
+ }
378
+ const resolvedAction = {
379
+ type: send$1,
380
+ params: {
381
+ ...params,
382
+ to: targetActorRef,
383
+ event: resolvedEvent,
384
+ delay: resolvedDelay,
385
+ internal: resolvedTarget === SpecialTargets.Internal
386
+ },
387
+ execute: actorCtx => {
388
+ const sendAction = resolvedAction;
389
+ if (typeof sendAction.params.delay === 'number') {
390
+ actorCtx.self.delaySend(sendAction);
391
+ return;
392
+ } else {
393
+ const target = sendAction.params.to;
394
+ const sentEvent = sendAction.params.event;
395
+ actorCtx.defer(() => {
396
+ target.send(sentEvent.type === error$1 ? {
397
+ type: `${error(actorCtx.self.id)}`,
398
+ data: sentEvent.data
399
+ } : sendAction.params.event);
400
+ });
401
+ }
402
+ }
403
+ };
404
+ return [state, resolvedAction];
405
+ });
406
+ }
407
+
408
+ /**
409
+ * Sends an event to this machine's parent.
410
+ *
411
+ * @param event The event to send to the parent machine.
412
+ * @param options Options to pass into the send event.
413
+ */
414
+ function sendParent(event, options) {
415
+ return send(event, {
416
+ ...options,
417
+ to: SpecialTargets.Parent
418
+ });
419
+ }
420
+
421
+ /**
422
+ * Forwards (sends) an event to a specified service.
423
+ *
424
+ * @param target The target service to forward the event to.
425
+ * @param options Options to pass into the send action creator.
426
+ */
427
+ function forwardTo(target, options) {
428
+ return send(({
429
+ event
430
+ }) => event, {
431
+ ...options,
432
+ to: target
433
+ });
434
+ }
435
+
436
+ /**
437
+ * Escalates an error by sending it as an event to this machine's parent.
438
+ *
439
+ * @param errorData The error data to send, or the expression function that
440
+ * takes in the `context`, `event`, and `meta`, and returns the error data to send.
441
+ * @param options Options to pass into the send action creator.
442
+ */
443
+ function escalate(errorData, options) {
444
+ return sendParent(arg => {
445
+ return {
446
+ type: error$1,
447
+ data: isFunction(errorData) ? errorData(arg) : errorData
448
+ };
449
+ }, {
450
+ ...options,
451
+ to: SpecialTargets.Parent
452
+ });
453
+ }
454
+
455
+ /**
456
+ * Sends an event to an actor.
457
+ *
458
+ * @param actor The `ActorRef` to send the event to.
459
+ * @param event The event to send, or an expression that evaluates to the event to send
460
+ * @param options Send action options
461
+ * @returns An XState send action object
462
+ */
463
+ function sendTo(actor, event, options) {
464
+ return send(event, {
465
+ ...options,
466
+ to: actor
467
+ });
468
+ }
469
+
470
+ class Mailbox {
471
+ constructor(_process) {
472
+ this._process = _process;
473
+ this._active = false;
474
+ this._current = null;
475
+ this._last = null;
476
+ }
477
+ start() {
478
+ this._active = true;
479
+ this.flush();
480
+ }
481
+ clear() {
482
+ // we can't set _current to null because we might be currently processing
483
+ // and enqueue following clear shouldnt start processing the enqueued item immediately
484
+ if (this._current) {
485
+ this._current.next = null;
486
+ this._last = this._current;
487
+ }
488
+ }
489
+
490
+ // TODO: rethink this design
491
+ prepend(event) {
492
+ if (!this._current) {
493
+ this.enqueue(event);
494
+ return;
495
+ }
496
+
497
+ // we know that something is already queued up
498
+ // so the mailbox is already flushing or it's inactive
499
+ // therefore the only thing that we need to do is to reassign `this._current`
500
+ this._current = {
501
+ value: event,
502
+ next: this._current
503
+ };
504
+ }
505
+ enqueue(event) {
506
+ const enqueued = {
507
+ value: event,
508
+ next: null
509
+ };
510
+ if (this._current) {
511
+ this._last.next = enqueued;
512
+ this._last = enqueued;
513
+ return;
514
+ }
515
+ this._current = enqueued;
516
+ this._last = enqueued;
517
+ if (this._active) {
518
+ this.flush();
519
+ }
520
+ }
521
+ flush() {
522
+ while (this._current) {
523
+ // atm the given _process is responsible for implementing proper try/catch handling
524
+ // we assume here that this won't throw in a way that can affect this mailbox
525
+ const consumed = this._current;
526
+ this._process(consumed.value);
527
+ // something could have been prepended in the meantime
528
+ // so we need to be defensive here to avoid skipping over a prepended item
529
+ if (consumed === this._current) {
530
+ this._current = this._current.next;
531
+ }
532
+ }
533
+ this._last = null;
534
+ }
535
+ }
536
+
537
+ const symbolObservable = (() => typeof Symbol === 'function' && Symbol.observable || '@@observable')();
538
+
539
+ /**
540
+ * Returns an actor behavior from a transition function and its initial state.
541
+ *
542
+ * A transition function is a function that takes the current state and an event and returns the next state.
543
+ *
544
+ * @param transition The transition function that returns the next state given the current state and event.
545
+ * @param initialState The initial state of the transition function.
546
+ * @returns An actor behavior
547
+ */
548
+ function fromTransition(transition, initialState) {
549
+ const behavior = {
550
+ config: transition,
551
+ transition: (state, event, actorContext) => {
552
+ return transition(state, event, actorContext);
553
+ },
554
+ getInitialState: (_, input) => {
555
+ return typeof initialState === 'function' ? initialState({
556
+ input
557
+ }) : initialState;
558
+ },
559
+ getSnapshot: state => state,
560
+ getPersistedState: state => state,
561
+ restoreState: state => state
562
+ };
563
+ return behavior;
564
+ }
565
+
566
+ function fromPromise(
567
+ // TODO: add types
568
+ promiseCreator) {
569
+ const resolveEventType = '$$xstate.resolve';
570
+ const rejectEventType = '$$xstate.reject';
571
+
572
+ // TODO: add event types
573
+ const behavior = {
574
+ config: promiseCreator,
575
+ transition: (state, event) => {
576
+ if (state.status !== 'active') {
577
+ return state;
578
+ }
579
+ switch (event.type) {
580
+ case resolveEventType:
581
+ return {
582
+ ...state,
583
+ status: 'done',
584
+ data: event.data,
585
+ input: undefined
586
+ };
587
+ case rejectEventType:
588
+ return {
589
+ ...state,
590
+ status: 'error',
591
+ data: event.data,
592
+ input: undefined
593
+ };
594
+ case stopSignalType:
595
+ return {
596
+ ...state,
597
+ status: 'canceled',
598
+ input: undefined
599
+ };
600
+ default:
601
+ return state;
602
+ }
603
+ },
604
+ start: (state, {
605
+ self
606
+ }) => {
607
+ // TODO: determine how to allow customizing this so that promises
608
+ // can be restarted if necessary
609
+ if (state.status !== 'active') {
610
+ return;
611
+ }
612
+ const resolvedPromise = Promise.resolve(promiseCreator({
613
+ input: state.input
614
+ }));
615
+ resolvedPromise.then(response => {
616
+ // TODO: remove this condition once dead letter queue lands
617
+ if (self._state.status !== 'active') {
618
+ return;
619
+ }
620
+ self.send({
621
+ type: resolveEventType,
622
+ data: response
623
+ });
624
+ }, errorData => {
625
+ // TODO: remove this condition once dead letter queue lands
626
+ if (self._state.status !== 'active') {
627
+ return;
628
+ }
629
+ self.send({
630
+ type: rejectEventType,
631
+ data: errorData
632
+ });
633
+ });
634
+ },
635
+ getInitialState: (_, input) => {
636
+ return {
637
+ status: 'active',
638
+ data: undefined,
639
+ input
640
+ };
641
+ },
642
+ getSnapshot: state => state.data,
643
+ getStatus: state => state,
644
+ getPersistedState: state => state,
645
+ restoreState: state => state
646
+ };
647
+ return behavior;
648
+ }
649
+
650
+ // TODO: this likely shouldn't accept TEvent, observable actor doesn't accept external events
651
+ function fromObservable(observableCreator) {
652
+ const nextEventType = '$$xstate.next';
653
+ const errorEventType = '$$xstate.error';
654
+ const completeEventType = '$$xstate.complete';
655
+
656
+ // TODO: add event types
657
+ const behavior = {
658
+ config: observableCreator,
659
+ transition: (state, event, {
660
+ self,
661
+ id,
662
+ defer
663
+ }) => {
664
+ if (state.status !== 'active') {
665
+ return state;
666
+ }
667
+ switch (event.type) {
668
+ case nextEventType:
669
+ // match the exact timing of events sent by machines
670
+ // send actions are not executed immediately
671
+ defer(() => {
672
+ self._parent?.send({
673
+ type: `xstate.snapshot.${id}`,
674
+ data: event.data
675
+ });
676
+ });
677
+ return {
678
+ ...state,
679
+ data: event.data
680
+ };
681
+ case errorEventType:
682
+ return {
683
+ ...state,
684
+ status: 'error',
685
+ input: undefined,
686
+ data: event.data,
687
+ subscription: undefined
688
+ };
689
+ case completeEventType:
690
+ return {
691
+ ...state,
692
+ status: 'done',
693
+ input: undefined,
694
+ subscription: undefined
695
+ };
696
+ case stopSignalType:
697
+ state.subscription.unsubscribe();
698
+ return {
699
+ ...state,
700
+ status: 'canceled',
701
+ input: undefined,
702
+ subscription: undefined
703
+ };
704
+ default:
705
+ return state;
706
+ }
707
+ },
708
+ getInitialState: (_, input) => {
709
+ return {
710
+ subscription: undefined,
711
+ status: 'active',
712
+ data: undefined,
713
+ input
714
+ };
715
+ },
716
+ start: (state, {
717
+ self
718
+ }) => {
719
+ if (state.status === 'done') {
720
+ // Do not restart a completed observable
721
+ return;
722
+ }
723
+ state.subscription = observableCreator({
724
+ input: state.input
725
+ }).subscribe({
726
+ next: value => {
727
+ self.send({
728
+ type: nextEventType,
729
+ data: value
730
+ });
731
+ },
732
+ error: err => {
733
+ self.send({
734
+ type: errorEventType,
735
+ data: err
736
+ });
737
+ },
738
+ complete: () => {
739
+ self.send({
740
+ type: completeEventType
741
+ });
742
+ }
743
+ });
744
+ },
745
+ getSnapshot: state => state.data,
746
+ getPersistedState: ({
747
+ status,
748
+ data,
749
+ input
750
+ }) => ({
751
+ status,
752
+ data,
753
+ input
754
+ }),
755
+ getStatus: state => state,
756
+ restoreState: state => ({
757
+ ...state,
758
+ subscription: undefined
759
+ })
760
+ };
761
+ return behavior;
762
+ }
763
+
764
+ /**
765
+ * Creates an event observable behavior that listens to an observable
766
+ * that delivers event objects.
767
+ *
768
+ *
769
+ * @param lazyObservable A function that creates an observable
770
+ * @returns An event observable behavior
771
+ */
772
+
773
+ function fromEventObservable(lazyObservable) {
774
+ const errorEventType = '$$xstate.error';
775
+ const completeEventType = '$$xstate.complete';
776
+
777
+ // TODO: event types
778
+ const behavior = {
779
+ config: lazyObservable,
780
+ transition: (state, event) => {
781
+ if (state.status !== 'active') {
782
+ return state;
783
+ }
784
+ switch (event.type) {
785
+ case errorEventType:
786
+ return {
787
+ ...state,
788
+ status: 'error',
789
+ input: undefined,
790
+ data: event.data,
791
+ subscription: undefined
792
+ };
793
+ case completeEventType:
794
+ return {
795
+ ...state,
796
+ status: 'done',
797
+ input: undefined,
798
+ subscription: undefined
799
+ };
800
+ case stopSignalType:
801
+ state.subscription.unsubscribe();
802
+ return {
803
+ ...state,
804
+ status: 'canceled',
805
+ input: undefined,
806
+ subscription: undefined
807
+ };
808
+ default:
809
+ return state;
810
+ }
811
+ },
812
+ getInitialState: (_, input) => {
813
+ return {
814
+ subscription: undefined,
815
+ status: 'active',
816
+ data: undefined,
817
+ input
818
+ };
819
+ },
820
+ start: (state, {
821
+ self
822
+ }) => {
823
+ if (state.status === 'done') {
824
+ // Do not restart a completed observable
825
+ return;
826
+ }
827
+ state.subscription = lazyObservable({
828
+ input: state.input
829
+ }).subscribe({
830
+ next: value => {
831
+ self._parent?.send(value);
832
+ },
833
+ error: err => {
834
+ self.send({
835
+ type: errorEventType,
836
+ data: err
837
+ });
838
+ },
839
+ complete: () => {
840
+ self.send({
841
+ type: completeEventType
842
+ });
843
+ }
844
+ });
845
+ },
846
+ getSnapshot: _ => undefined,
847
+ getPersistedState: ({
848
+ status,
849
+ data,
850
+ input
851
+ }) => ({
852
+ status,
853
+ data,
854
+ input
855
+ }),
856
+ getStatus: state => state,
857
+ restoreState: state => ({
858
+ ...state,
859
+ subscription: undefined
860
+ })
861
+ };
862
+ return behavior;
863
+ }
864
+
865
+ function fromCallback(invokeCallback) {
866
+ const behavior = {
867
+ config: invokeCallback,
868
+ start: (_state, {
869
+ self
870
+ }) => {
871
+ self.send({
872
+ type: startSignalType
873
+ });
874
+ },
875
+ transition: (state, event, {
876
+ self,
877
+ id
878
+ }) => {
879
+ if (event.type === startSignalType) {
880
+ const sender = eventForParent => {
881
+ if (state.canceled) {
882
+ return;
883
+ }
884
+ self._parent?.send(eventForParent);
885
+ };
886
+ const receiver = newListener => {
887
+ state.receivers.add(newListener);
888
+ };
889
+ state.dispose = invokeCallback(sender, receiver, {
890
+ input: state.input
891
+ });
892
+ if (isPromiseLike(state.dispose)) {
893
+ state.dispose.then(resolved => {
894
+ self._parent?.send(doneInvoke(id, resolved));
895
+ state.canceled = true;
896
+ }, errorData => {
897
+ state.canceled = true;
898
+ self._parent?.send(error(id, errorData));
899
+ });
900
+ }
901
+ return state;
902
+ }
903
+ if (event.type === stopSignalType) {
904
+ state.canceled = true;
905
+ if (isFunction(state.dispose)) {
906
+ state.dispose();
907
+ }
908
+ return state;
909
+ }
910
+ if (isSignal(event.type)) {
911
+ // TODO: unrecognized signal
912
+ return state;
913
+ }
914
+ if (!isSignal(event.type)) {
915
+ state.receivers.forEach(receiver => receiver(event));
916
+ }
917
+ return state;
918
+ },
919
+ getInitialState: (_, input) => {
920
+ return {
921
+ canceled: false,
922
+ receivers: new Set(),
923
+ dispose: undefined,
924
+ input
925
+ };
926
+ },
927
+ getSnapshot: () => undefined,
928
+ getPersistedState: ({
929
+ input
930
+ }) => input
931
+ };
932
+ return behavior;
933
+ }
934
+
935
+ const startSignalType = 'xstate.init';
936
+ const stopSignalType = 'xstate.stop';
937
+ const startSignal = {
938
+ type: 'xstate.init'
939
+ };
940
+ const stopSignal = {
941
+ type: 'xstate.stop'
942
+ };
943
+ /**
944
+ * An object that expresses the behavior of an actor in reaction to received events,
945
+ * as well as an optionally emitted stream of values.
946
+ *
947
+ * @template TReceived The received event
948
+ * @template TSnapshot The emitted value
949
+ */
950
+
951
+ function isSignal(eventType) {
952
+ return eventType === startSignalType || eventType === stopSignalType;
953
+ }
954
+ function isActorRef(item) {
955
+ return !!item && typeof item === 'object' && typeof item.send === 'function';
956
+ }
957
+
958
+ // TODO: refactor the return type, this could be written in a better way
959
+ // but it's best to avoid unneccessary breaking changes now
960
+ // @deprecated use `interpret(behavior)` instead
961
+ function toActorRef(actorRefLike) {
962
+ return {
963
+ subscribe: () => ({
964
+ unsubscribe: () => void 0
965
+ }),
966
+ id: 'anonymous',
967
+ sessionId: '',
968
+ getSnapshot: () => undefined,
969
+ [symbolObservable]: function () {
970
+ return this;
971
+ },
972
+ status: ActorStatus.Running,
973
+ stop: () => void 0,
974
+ ...actorRefLike
975
+ };
976
+ }
977
+ const emptyBehavior = fromTransition(_ => undefined, undefined);
978
+ function createEmptyActor() {
979
+ return interpret(emptyBehavior);
980
+ }
981
+
982
+ function createSystem() {
983
+ let sessionIdCounter = 0;
984
+ const children = new Map();
985
+ const keyedActors = new Map();
986
+ const reverseKeyedActors = new WeakMap();
987
+ const system = {
988
+ _bookId: () => `x:${sessionIdCounter++}`,
989
+ _register: (sessionId, actorRef) => {
990
+ children.set(sessionId, actorRef);
991
+ return sessionId;
992
+ },
993
+ _unregister: actorRef => {
994
+ children.delete(actorRef.sessionId);
995
+ const systemId = reverseKeyedActors.get(actorRef);
996
+ if (systemId !== undefined) {
997
+ keyedActors.delete(systemId);
998
+ reverseKeyedActors.delete(actorRef);
999
+ }
1000
+ },
1001
+ get: systemId => {
1002
+ return keyedActors.get(systemId);
1003
+ },
1004
+ _set: (systemId, actorRef) => {
1005
+ const existing = keyedActors.get(systemId);
1006
+ if (existing && existing !== actorRef) {
1007
+ throw new Error(`Actor with system ID '${systemId}' already exists.`);
1008
+ }
1009
+ keyedActors.set(systemId, actorRef);
1010
+ reverseKeyedActors.set(actorRef, systemId);
1011
+ }
1012
+ };
1013
+ return system;
1014
+ }
1015
+
1016
+ let ActorStatus = /*#__PURE__*/function (ActorStatus) {
1017
+ ActorStatus[ActorStatus["NotStarted"] = 0] = "NotStarted";
1018
+ ActorStatus[ActorStatus["Running"] = 1] = "Running";
1019
+ ActorStatus[ActorStatus["Stopped"] = 2] = "Stopped";
1020
+ return ActorStatus;
1021
+ }({});
1022
+ const defaultOptions = {
1023
+ deferEvents: true,
1024
+ clock: {
1025
+ setTimeout: (fn, ms) => {
1026
+ return setTimeout(fn, ms);
1027
+ },
1028
+ clearTimeout: id => {
1029
+ return clearTimeout(id);
1030
+ }
1031
+ },
1032
+ logger: console.log.bind(console),
1033
+ devTools: false
1034
+ };
1035
+ class Interpreter {
1036
+ /**
1037
+ * The current state of the interpreted behavior.
1038
+ */
1039
+
1040
+ /**
1041
+ * The clock that is responsible for setting and clearing timeouts, such as delayed events and transitions.
1042
+ */
1043
+
1044
+ /**
1045
+ * The unique identifier for this actor relative to its parent.
1046
+ */
1047
+
1048
+ /**
1049
+ * Whether the service is started.
1050
+ */
1051
+
1052
+ // Actor Ref
1053
+
1054
+ // TODO: add typings for system
1055
+
1056
+ /**
1057
+ * The globally unique process ID for this invocation.
1058
+ */
1059
+
1060
+ /**
1061
+ * Creates a new Interpreter instance (i.e., service) for the given behavior with the provided options, if any.
1062
+ *
1063
+ * @param behavior The behavior to be interpreted
1064
+ * @param options Interpreter options
1065
+ */
1066
+ constructor(behavior, options) {
1067
+ this.behavior = behavior;
1068
+ this._state = void 0;
1069
+ this.clock = void 0;
1070
+ this.options = void 0;
1071
+ this.id = void 0;
1072
+ this.mailbox = new Mailbox(this._process.bind(this));
1073
+ this.delayedEventsMap = {};
1074
+ this.observers = new Set();
1075
+ this.logger = void 0;
1076
+ this.status = ActorStatus.NotStarted;
1077
+ this._parent = void 0;
1078
+ this.ref = void 0;
1079
+ this._actorContext = void 0;
1080
+ this._systemId = void 0;
1081
+ this.sessionId = void 0;
1082
+ this.system = void 0;
1083
+ this._doneEvent = void 0;
1084
+ this.src = void 0;
1085
+ this._deferred = [];
1086
+ const resolvedOptions = {
1087
+ ...defaultOptions,
1088
+ ...options
1089
+ };
1090
+ const {
1091
+ clock,
1092
+ logger,
1093
+ parent,
1094
+ id,
1095
+ systemId
1096
+ } = resolvedOptions;
1097
+ const self = this;
1098
+ this.system = parent?.system ?? createSystem();
1099
+ if (systemId) {
1100
+ this._systemId = systemId;
1101
+ this.system._set(systemId, this);
1102
+ }
1103
+ this.sessionId = this.system._bookId();
1104
+ this.id = id ?? this.sessionId;
1105
+ this.logger = logger;
1106
+ this.clock = clock;
1107
+ this._parent = parent;
1108
+ this.options = resolvedOptions;
1109
+ this.src = resolvedOptions.src;
1110
+ this.ref = this;
1111
+ this._actorContext = {
1112
+ self,
1113
+ id: this.id,
1114
+ sessionId: this.sessionId,
1115
+ logger: this.logger,
1116
+ defer: fn => {
1117
+ this._deferred.push(fn);
1118
+ },
1119
+ system: this.system,
1120
+ stopChild: child => {
1121
+ if (child._parent !== this) {
1122
+ throw new Error(`Cannot stop child actor ${child.id} of ${this.id} because it is not a child`);
1123
+ }
1124
+ child._stop();
1125
+ }
1126
+ };
1127
+
1128
+ // Ensure that the send method is bound to this interpreter instance
1129
+ // if destructured
1130
+ this.send = this.send.bind(this);
1131
+ this._initState();
1132
+ }
1133
+ _initState() {
1134
+ this._state = this.options.state ? this.behavior.restoreState ? this.behavior.restoreState(this.options.state, this._actorContext) : this.options.state : this.behavior.getInitialState(this._actorContext, this.options?.input);
1135
+ }
1136
+
1137
+ // array of functions to defer
1138
+
1139
+ update(state) {
1140
+ // Update state
1141
+ this._state = state;
1142
+ const snapshot = this.getSnapshot();
1143
+
1144
+ // Execute deferred effects
1145
+ let deferredFn;
1146
+ while (deferredFn = this._deferred.shift()) {
1147
+ deferredFn(state);
1148
+ }
1149
+ for (const observer of this.observers) {
1150
+ observer.next?.(snapshot);
1151
+ }
1152
+ const status = this.behavior.getStatus?.(state);
1153
+ switch (status?.status) {
1154
+ case 'done':
1155
+ this._stopProcedure();
1156
+ this._doneEvent = doneInvoke(this.id, status.data);
1157
+ this._parent?.send(this._doneEvent);
1158
+ this._complete();
1159
+ break;
1160
+ case 'error':
1161
+ this._stopProcedure();
1162
+ this._parent?.send(error(this.id, status.data));
1163
+ this._error(status.data);
1164
+ break;
1165
+ }
1166
+ }
1167
+ subscribe(nextListenerOrObserver, errorListener, completeListener) {
1168
+ const observer = toObserver(nextListenerOrObserver, errorListener, completeListener);
1169
+ this.observers.add(observer);
1170
+ if (this.status === ActorStatus.Stopped) {
1171
+ observer.complete?.();
1172
+ this.observers.delete(observer);
1173
+ }
1174
+ return {
1175
+ unsubscribe: () => {
1176
+ this.observers.delete(observer);
1177
+ }
1178
+ };
1179
+ }
1180
+
1181
+ /**
1182
+ * Adds a state listener that is notified when the statechart has reached its final state.
1183
+ * @param listener The state listener
1184
+ */
1185
+ onDone(listener) {
1186
+ if (this.status === ActorStatus.Stopped && this._doneEvent) {
1187
+ listener(this._doneEvent);
1188
+ } else {
1189
+ this.observers.add({
1190
+ complete: () => {
1191
+ if (this._doneEvent) {
1192
+ listener(this._doneEvent);
1193
+ }
1194
+ }
1195
+ });
1196
+ }
1197
+ return this;
1198
+ }
1199
+
1200
+ /**
1201
+ * Starts the interpreter from the initial state
1202
+ */
1203
+ start() {
1204
+ if (this.status === ActorStatus.Running) {
1205
+ // Do not restart the service if it is already started
1206
+ return this;
1207
+ }
1208
+ this.system._register(this.sessionId, this);
1209
+ if (this._systemId) {
1210
+ this.system._set(this._systemId, this);
1211
+ }
1212
+ this.status = ActorStatus.Running;
1213
+ if (this.behavior.start) {
1214
+ this.behavior.start(this._state, this._actorContext);
1215
+ }
1216
+
1217
+ // TODO: this notifies all subscribers but usually this is redundant
1218
+ // there is no real change happening here
1219
+ // we need to rethink if this needs to be refactored
1220
+ this.update(this._state);
1221
+ if (this.options.devTools) {
1222
+ this.attachDevTools();
1223
+ }
1224
+ this.mailbox.start();
1225
+ return this;
1226
+ }
1227
+ _process(event) {
1228
+ try {
1229
+ const nextState = this.behavior.transition(this._state, event, this._actorContext);
1230
+ this.update(nextState);
1231
+ if (event.type === stopSignalType) {
1232
+ this._stopProcedure();
1233
+ this._complete();
1234
+ }
1235
+ } catch (err) {
1236
+ // TODO: properly handle errors
1237
+ if (this.observers.size > 0) {
1238
+ this.observers.forEach(observer => {
1239
+ observer.error?.(err);
1240
+ });
1241
+ this.stop();
1242
+ } else {
1243
+ throw err;
1244
+ }
1245
+ }
1246
+ }
1247
+ _stop() {
1248
+ if (this.status === ActorStatus.Stopped) {
1249
+ return this;
1250
+ }
1251
+ this.mailbox.clear();
1252
+ if (this.status === ActorStatus.NotStarted) {
1253
+ this.status = ActorStatus.Stopped;
1254
+ return this;
1255
+ }
1256
+ this.mailbox.enqueue({
1257
+ type: stopSignalType
1258
+ });
1259
+ return this;
1260
+ }
1261
+
1262
+ /**
1263
+ * Stops the interpreter and unsubscribe all listeners.
1264
+ */
1265
+ stop() {
1266
+ if (this._parent) {
1267
+ throw new Error('A non-root actor cannot be stopped directly.');
1268
+ }
1269
+ return this._stop();
1270
+ }
1271
+ _complete() {
1272
+ for (const observer of this.observers) {
1273
+ observer.complete?.();
1274
+ }
1275
+ this.observers.clear();
1276
+ }
1277
+ _error(data) {
1278
+ for (const observer of this.observers) {
1279
+ observer.error?.(data);
1280
+ }
1281
+ this.observers.clear();
1282
+ }
1283
+ _stopProcedure() {
1284
+ if (this.status !== ActorStatus.Running) {
1285
+ // Interpreter already stopped; do nothing
1286
+ return this;
1287
+ }
1288
+
1289
+ // Cancel all delayed events
1290
+ for (const key of Object.keys(this.delayedEventsMap)) {
1291
+ this.clock.clearTimeout(this.delayedEventsMap[key]);
1292
+ }
1293
+
1294
+ // TODO: mailbox.reset
1295
+ this.mailbox.clear();
1296
+ // TODO: after `stop` we must prepare ourselves for receiving events again
1297
+ // events sent *after* stop signal must be queued
1298
+ // it seems like this should be the common behavior for all of our consumers
1299
+ // so perhaps this should be unified somehow for all of them
1300
+ this.mailbox = new Mailbox(this._process.bind(this));
1301
+ this.status = ActorStatus.Stopped;
1302
+ this.system._unregister(this);
1303
+ return this;
1304
+ }
1305
+
1306
+ /**
1307
+ * Sends an event to the running interpreter to trigger a transition.
1308
+ *
1309
+ * @param event The event to send
1310
+ */
1311
+ send(event) {
1312
+ if (typeof event === 'string') {
1313
+ throw new Error(`Only event objects may be sent to actors; use .send({ type: "${event}" }) instead`);
1314
+ }
1315
+ if (this.status === ActorStatus.Stopped) {
1316
+ return;
1317
+ }
1318
+ if (this.status !== ActorStatus.Running && !this.options.deferEvents) {
1319
+ throw new Error(`Event "${event.type}" was sent to uninitialized actor "${this.id
1320
+ // tslint:disable-next-line:max-line-length
1321
+ }". Make sure .start() is called for this actor, or set { deferEvents: true } in the actor options.\nEvent: ${JSON.stringify(event)}`);
1322
+ }
1323
+ this.mailbox.enqueue(event);
1324
+ }
1325
+
1326
+ // TODO: make private (and figure out a way to do this within the machine)
1327
+ delaySend(sendAction) {
1328
+ this.delayedEventsMap[sendAction.params.id] = this.clock.setTimeout(() => {
1329
+ if ('to' in sendAction.params && sendAction.params.to) {
1330
+ sendAction.params.to.send(sendAction.params.event);
1331
+ } else {
1332
+ this.send(sendAction.params.event);
1333
+ }
1334
+ }, sendAction.params.delay);
1335
+ }
1336
+
1337
+ // TODO: make private (and figure out a way to do this within the machine)
1338
+ cancel(sendId) {
1339
+ this.clock.clearTimeout(this.delayedEventsMap[sendId]);
1340
+ delete this.delayedEventsMap[sendId];
1341
+ }
1342
+ attachDevTools() {
1343
+ const {
1344
+ devTools
1345
+ } = this.options;
1346
+ if (devTools) {
1347
+ const resolvedDevToolsAdapter = typeof devTools === 'function' ? devTools : devToolsAdapter;
1348
+ resolvedDevToolsAdapter(this);
1349
+ }
1350
+ }
1351
+ toJSON() {
1352
+ return {
1353
+ id: this.id
1354
+ };
1355
+ }
1356
+ getPersistedState() {
1357
+ return this.behavior.getPersistedState?.(this._state);
1358
+ }
1359
+ [symbolObservable]() {
1360
+ return this;
1361
+ }
1362
+ getSnapshot() {
1363
+ return this.behavior.getSnapshot ? this.behavior.getSnapshot(this._state) : this._state;
1364
+ }
1365
+ }
1366
+
1367
+ /**
1368
+ * Creates a new Interpreter instance for the given machine with the provided options, if any.
1369
+ *
1370
+ * @param machine The machine to interpret
1371
+ * @param options Interpreter options
1372
+ */
1373
+
1374
+ function interpret(behavior, options) {
1375
+ const interpreter = new Interpreter(behavior, options);
1376
+ return interpreter;
1377
+ }
1378
+
1379
+ /**
1380
+ * Stops an actor.
1381
+ *
1382
+ * @param actorRef The actor to stop.
1383
+ */
1384
+
1385
+ function stop(actorRef) {
1386
+ const actor = actorRef;
1387
+ return createDynamicAction({
1388
+ type: stop$1,
1389
+ params: {
1390
+ actor
1391
+ }
1392
+ }, (event, {
1393
+ state
1394
+ }) => {
1395
+ const actorRefOrString = isFunction(actor) ? actor({
1396
+ context: state.context,
1397
+ event
1398
+ }) : actor;
1399
+ const actorRef = typeof actorRefOrString === 'string' ? state.children[actorRefOrString] : actorRefOrString;
1400
+ return [state, {
1401
+ type: 'xstate.stop',
1402
+ params: {
1403
+ actor: actorRef
1404
+ },
1405
+ execute: actorCtx => {
1406
+ if (!actorRef) {
1407
+ return;
1408
+ }
1409
+ if (actorRef.status !== ActorStatus.Running) {
1410
+ actorCtx.stopChild(actorRef);
1411
+ return;
1412
+ }
1413
+ actorCtx.defer(() => {
1414
+ actorCtx.stopChild(actorRef);
1415
+ });
1416
+ }
1417
+ }];
1418
+ });
1419
+ }
1420
+
1421
+ const defaultLogExpr = ({
1422
+ context,
1423
+ event
1424
+ }) => ({
1425
+ context,
1426
+ event
1427
+ });
1428
+
1429
+ /**
1430
+ *
1431
+ * @param expr The expression function to evaluate which will be logged.
1432
+ * Takes in 2 arguments:
1433
+ * - `ctx` - the current state context
1434
+ * - `event` - the event that caused this action to be executed.
1435
+ * @param label The label to give to the logged expression.
1436
+ */
1437
+
1438
+ function log(expr = defaultLogExpr, label) {
1439
+ return createDynamicAction({
1440
+ type: log$1,
1441
+ params: {
1442
+ label,
1443
+ expr
1444
+ }
1445
+ }, (event, {
1446
+ state,
1447
+ actorContext
1448
+ }) => {
1449
+ const resolvedValue = typeof expr === 'function' ? expr({
1450
+ context: state.context,
1451
+ event,
1452
+ self: actorContext?.self ?? {},
1453
+ system: actorContext?.system
1454
+ }) : expr;
1455
+ return [state, {
1456
+ type: 'xstate.log',
1457
+ params: {
1458
+ label,
1459
+ value: resolvedValue
1460
+ },
1461
+ execute: actorCtx => {
1462
+ if (label) {
1463
+ actorCtx.logger?.(label, resolvedValue);
1464
+ } else {
1465
+ actorCtx.logger?.(resolvedValue);
1466
+ }
1467
+ }
1468
+ }];
1469
+ });
1470
+ }
1471
+
1472
+ /**
1473
+ * Cancels an in-flight `send(...)` action. A canceled sent action will not
1474
+ * be executed, nor will its event be sent, unless it has already been sent
1475
+ * (e.g., if `cancel(...)` is called after the `send(...)` action's `delay`).
1476
+ *
1477
+ * @param sendId The `id` of the `send(...)` action to cancel.
1478
+ */
1479
+
1480
+ function cancel(sendId) {
1481
+ return createDynamicAction({
1482
+ type: cancel$1,
1483
+ params: {
1484
+ sendId
1485
+ }
1486
+ }, (event, {
1487
+ state,
1488
+ actorContext
1489
+ }) => {
1490
+ const resolvedSendId = isFunction(sendId) ? sendId({
1491
+ context: state.context,
1492
+ event,
1493
+ self: actorContext?.self ?? {},
1494
+ system: actorContext?.system
1495
+ }) : sendId;
1496
+ return [state, {
1497
+ type: 'xstate.cancel',
1498
+ params: {
1499
+ sendId: resolvedSendId
1500
+ },
1501
+ execute: actorCtx => {
1502
+ const interpreter = actorCtx.self;
1503
+ interpreter.cancel(resolvedSendId);
1504
+ }
1505
+ }];
1506
+ });
1507
+ }
1508
+
1509
+ const cache = new WeakMap();
1510
+ function memo(object, key, fn) {
1511
+ let memoizedData = cache.get(object);
1512
+ if (!memoizedData) {
1513
+ memoizedData = {
1514
+ [key]: fn()
1515
+ };
1516
+ cache.set(object, memoizedData);
1517
+ } else if (!(key in memoizedData)) {
1518
+ memoizedData[key] = fn();
1519
+ }
1520
+ return memoizedData[key];
1521
+ }
1522
+
1523
+ function stateIn(stateValue) {
1524
+ return {
1525
+ type: 'xstate.guard:in',
1526
+ params: {
1527
+ stateValue
1528
+ },
1529
+ predicate: ({
1530
+ state
1531
+ }) => {
1532
+ if (isString(stateValue) && isStateId(stateValue)) {
1533
+ return state.configuration.some(sn => sn.id === stateValue.slice(1));
1534
+ }
1535
+ return state.matches(stateValue);
1536
+ }
1537
+ };
1538
+ }
1539
+ function not(guard) {
1540
+ return {
1541
+ type: 'xstate.boolean',
1542
+ params: {
1543
+ op: 'not'
1544
+ },
1545
+ children: [toGuardDefinition(guard)],
1546
+ predicate: ({
1547
+ evaluate,
1548
+ guard,
1549
+ context,
1550
+ event,
1551
+ state
1552
+ }) => {
1553
+ return !evaluate(guard.children[0], context, event, state);
1554
+ }
1555
+ };
1556
+ }
1557
+ function and(guards) {
1558
+ return {
1559
+ type: 'xstate.boolean',
1560
+ params: {
1561
+ op: 'and'
1562
+ },
1563
+ children: guards.map(guard => toGuardDefinition(guard)),
1564
+ predicate: ({
1565
+ evaluate,
1566
+ guard,
1567
+ context,
1568
+ event,
1569
+ state
1570
+ }) => {
1571
+ return guard.children.every(childGuard => {
1572
+ return evaluate(childGuard, context, event, state);
1573
+ });
1574
+ }
1575
+ };
1576
+ }
1577
+ function or(guards) {
1578
+ return {
1579
+ type: 'xstate.boolean',
1580
+ params: {
1581
+ op: 'or'
1582
+ },
1583
+ children: guards.map(guard => toGuardDefinition(guard)),
1584
+ predicate: ({
1585
+ evaluate,
1586
+ guard,
1587
+ context,
1588
+ event,
1589
+ state
1590
+ }) => {
1591
+ return guard.children.some(childGuard => {
1592
+ return evaluate(childGuard, context, event, state);
1593
+ });
1594
+ }
1595
+ };
1596
+ }
1597
+ function evaluateGuard(guard, context, event, state) {
1598
+ const {
1599
+ machine
1600
+ } = state;
1601
+ const predicate = machine?.options?.guards?.[guard.type] ?? guard.predicate;
1602
+ if (!predicate) {
1603
+ throw new Error(`Guard '${guard.type}' is not implemented.'.`);
1604
+ }
1605
+ return predicate({
1606
+ context,
1607
+ event,
1608
+ state,
1609
+ guard,
1610
+ evaluate: evaluateGuard
1611
+ });
1612
+ }
1613
+ function toGuardDefinition(guardConfig, getPredicate) {
1614
+ if (isString(guardConfig)) {
1615
+ return {
1616
+ type: guardConfig,
1617
+ predicate: getPredicate?.(guardConfig) || undefined,
1618
+ params: {
1619
+ type: guardConfig
1620
+ }
1621
+ };
1622
+ }
1623
+ if (isFunction(guardConfig)) {
1624
+ return {
1625
+ type: guardConfig.name,
1626
+ predicate: guardConfig,
1627
+ params: {
1628
+ type: guardConfig.name,
1629
+ name: guardConfig.name
1630
+ }
1631
+ };
1632
+ }
1633
+ return {
1634
+ type: guardConfig.type,
1635
+ params: guardConfig.params || guardConfig,
1636
+ children: guardConfig.children?.map(childGuard => toGuardDefinition(childGuard, getPredicate)),
1637
+ predicate: getPredicate?.(guardConfig.type) || guardConfig.predicate
1638
+ };
1639
+ }
1640
+
1641
+ function getOutput(configuration, context, event) {
1642
+ const machine = configuration[0].machine;
1643
+ const finalChildStateNode = configuration.find(stateNode => stateNode.type === 'final' && stateNode.parent === machine.root);
1644
+ return finalChildStateNode && finalChildStateNode.output ? mapContext(finalChildStateNode.output, context, event) : undefined;
1645
+ }
1646
+ const isAtomicStateNode = stateNode => stateNode.type === 'atomic' || stateNode.type === 'final';
1647
+ function getChildren(stateNode) {
1648
+ return Object.values(stateNode.states).filter(sn => sn.type !== 'history');
1649
+ }
1650
+ function getProperAncestors(stateNode, toStateNode) {
1651
+ const ancestors = [];
1652
+
1653
+ // add all ancestors
1654
+ let m = stateNode.parent;
1655
+ while (m && m !== toStateNode) {
1656
+ ancestors.push(m);
1657
+ m = m.parent;
1658
+ }
1659
+ return ancestors;
1660
+ }
1661
+ function getConfiguration(stateNodes) {
1662
+ const configuration = new Set(stateNodes);
1663
+ const configurationSet = new Set(stateNodes);
1664
+ const adjList = getAdjList(configurationSet);
1665
+
1666
+ // add descendants
1667
+ for (const s of configuration) {
1668
+ // if previously active, add existing child nodes
1669
+ if (s.type === 'compound' && (!adjList.get(s) || !adjList.get(s).length)) {
1670
+ getInitialStateNodes(s).forEach(sn => configurationSet.add(sn));
1671
+ } else {
1672
+ if (s.type === 'parallel') {
1673
+ for (const child of getChildren(s)) {
1674
+ if (child.type === 'history') {
1675
+ continue;
1676
+ }
1677
+ if (!configurationSet.has(child)) {
1678
+ for (const initialStateNode of getInitialStateNodes(child)) {
1679
+ configurationSet.add(initialStateNode);
1680
+ }
1681
+ }
1682
+ }
1683
+ }
1684
+ }
1685
+ }
1686
+
1687
+ // add all ancestors
1688
+ for (const s of configurationSet) {
1689
+ let m = s.parent;
1690
+ while (m) {
1691
+ configurationSet.add(m);
1692
+ m = m.parent;
1693
+ }
1694
+ }
1695
+ return configurationSet;
1696
+ }
1697
+ function getValueFromAdj(baseNode, adjList) {
1698
+ const childStateNodes = adjList.get(baseNode);
1699
+ if (!childStateNodes) {
1700
+ return {}; // todo: fix?
1701
+ }
1702
+
1703
+ if (baseNode.type === 'compound') {
1704
+ const childStateNode = childStateNodes[0];
1705
+ if (childStateNode) {
1706
+ if (isAtomicStateNode(childStateNode)) {
1707
+ return childStateNode.key;
1708
+ }
1709
+ } else {
1710
+ return {};
1711
+ }
1712
+ }
1713
+ const stateValue = {};
1714
+ for (const childStateNode of childStateNodes) {
1715
+ stateValue[childStateNode.key] = getValueFromAdj(childStateNode, adjList);
1716
+ }
1717
+ return stateValue;
1718
+ }
1719
+ function getAdjList(configuration) {
1720
+ const adjList = new Map();
1721
+ for (const s of configuration) {
1722
+ if (!adjList.has(s)) {
1723
+ adjList.set(s, []);
1724
+ }
1725
+ if (s.parent) {
1726
+ if (!adjList.has(s.parent)) {
1727
+ adjList.set(s.parent, []);
1728
+ }
1729
+ adjList.get(s.parent).push(s);
1730
+ }
1731
+ }
1732
+ return adjList;
1733
+ }
1734
+ function getStateValue(rootNode, configuration) {
1735
+ const config = getConfiguration(configuration);
1736
+ return getValueFromAdj(rootNode, getAdjList(config));
1737
+ }
1738
+ function isInFinalState(configuration, stateNode = configuration[0].machine.root) {
1739
+ if (stateNode.type === 'compound') {
1740
+ return getChildren(stateNode).some(s => s.type === 'final' && configuration.includes(s));
1741
+ }
1742
+ if (stateNode.type === 'parallel') {
1743
+ return getChildren(stateNode).every(sn => isInFinalState(configuration, sn));
1744
+ }
1745
+ return false;
1746
+ }
1747
+ const isStateId = str => str[0] === STATE_IDENTIFIER;
1748
+ function getCandidates(stateNode, receivedEventType) {
1749
+ const candidates = stateNode.transitions.filter(transition => {
1750
+ const {
1751
+ eventType
1752
+ } = transition;
1753
+ // First, check the trivial case: event names are exactly equal
1754
+ if (eventType === receivedEventType) {
1755
+ return true;
1756
+ }
1757
+
1758
+ // Then, check if transition is a wildcard transition,
1759
+ // which matches any non-transient events
1760
+ if (eventType === WILDCARD) {
1761
+ return true;
1762
+ }
1763
+ if (!eventType.endsWith('.*')) {
1764
+ return false;
1765
+ }
1766
+ const partialEventTokens = eventType.split('.');
1767
+ const eventTokens = receivedEventType.split('.');
1768
+ for (let tokenIndex = 0; tokenIndex < partialEventTokens.length; tokenIndex++) {
1769
+ const partialEventToken = partialEventTokens[tokenIndex];
1770
+ const eventToken = eventTokens[tokenIndex];
1771
+ if (partialEventToken === '*') {
1772
+ const isLastToken = tokenIndex === partialEventTokens.length - 1;
1773
+ return isLastToken;
1774
+ }
1775
+ if (partialEventToken !== eventToken) {
1776
+ return false;
1777
+ }
1778
+ }
1779
+ return true;
1780
+ });
1781
+ return candidates;
1782
+ }
1783
+
1784
+ /**
1785
+ * All delayed transitions from the config.
1786
+ */
1787
+ function getDelayedTransitions(stateNode) {
1788
+ const afterConfig = stateNode.config.after;
1789
+ if (!afterConfig) {
1790
+ return [];
1791
+ }
1792
+ const mutateEntryExit = (delay, i) => {
1793
+ const delayRef = isFunction(delay) ? `${stateNode.id}:delay[${i}]` : delay;
1794
+ const eventType = after(delayRef, stateNode.id);
1795
+ stateNode.entry.push(raise({
1796
+ type: eventType
1797
+ }, {
1798
+ delay
1799
+ }));
1800
+ stateNode.exit.push(cancel(eventType));
1801
+ return eventType;
1802
+ };
1803
+ const delayedTransitions = isArray(afterConfig) ? afterConfig.map((transition, i) => {
1804
+ const eventType = mutateEntryExit(transition.delay, i);
1805
+ return {
1806
+ ...transition,
1807
+ event: eventType
1808
+ };
1809
+ }) : Object.keys(afterConfig).flatMap((delay, i) => {
1810
+ const configTransition = afterConfig[delay];
1811
+ const resolvedTransition = isString(configTransition) ? {
1812
+ target: configTransition
1813
+ } : configTransition;
1814
+ const resolvedDelay = !isNaN(+delay) ? +delay : delay;
1815
+ const eventType = mutateEntryExit(resolvedDelay, i);
1816
+ return toArray(resolvedTransition).map(transition => ({
1817
+ ...transition,
1818
+ event: eventType,
1819
+ delay: resolvedDelay
1820
+ }));
1821
+ });
1822
+ return delayedTransitions.map(delayedTransition => {
1823
+ const {
1824
+ delay
1825
+ } = delayedTransition;
1826
+ return {
1827
+ ...formatTransition(stateNode, delayedTransition),
1828
+ delay
1829
+ };
1830
+ });
1831
+ }
1832
+ function formatTransition(stateNode, transitionConfig) {
1833
+ const normalizedTarget = normalizeTarget(transitionConfig.target);
1834
+ const reenter = transitionConfig.reenter ?? false;
1835
+ const {
1836
+ guards
1837
+ } = stateNode.machine.options;
1838
+ const target = resolveTarget(stateNode, normalizedTarget);
1839
+ const transition = {
1840
+ ...transitionConfig,
1841
+ actions: toActionObjects(toArray(transitionConfig.actions)),
1842
+ guard: transitionConfig.guard ? toGuardDefinition(transitionConfig.guard, guardType => guards[guardType]) : undefined,
1843
+ target,
1844
+ source: stateNode,
1845
+ reenter,
1846
+ eventType: transitionConfig.event,
1847
+ toJSON: () => ({
1848
+ ...transition,
1849
+ source: `#${stateNode.id}`,
1850
+ target: target ? target.map(t => `#${t.id}`) : undefined
1851
+ })
1852
+ };
1853
+ return transition;
1854
+ }
1855
+ function formatTransitions(stateNode) {
1856
+ const transitionConfigs = [];
1857
+ if (Array.isArray(stateNode.config.on)) {
1858
+ transitionConfigs.push(...stateNode.config.on);
1859
+ } else if (stateNode.config.on) {
1860
+ const {
1861
+ [WILDCARD]: wildcardConfigs = [],
1862
+ ...namedTransitionConfigs
1863
+ } = stateNode.config.on;
1864
+ for (const eventType of Object.keys(namedTransitionConfigs)) {
1865
+ if (eventType === NULL_EVENT) {
1866
+ throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');
1867
+ }
1868
+ const eventTransitionConfigs = toTransitionConfigArray(eventType, namedTransitionConfigs[eventType]);
1869
+ transitionConfigs.push(...eventTransitionConfigs);
1870
+ // TODO: add dev-mode validation for unreachable transitions
1871
+ }
1872
+
1873
+ transitionConfigs.push(...toTransitionConfigArray(WILDCARD, wildcardConfigs));
1874
+ }
1875
+ const doneConfig = stateNode.config.onDone ? toTransitionConfigArray(String(done(stateNode.id)), stateNode.config.onDone) : [];
1876
+ const invokeConfig = stateNode.invoke.flatMap(invokeDef => {
1877
+ const settleTransitions = [];
1878
+ if (invokeDef.onDone) {
1879
+ settleTransitions.push(...toTransitionConfigArray(`done.invoke.${invokeDef.id}`, invokeDef.onDone));
1880
+ }
1881
+ if (invokeDef.onError) {
1882
+ settleTransitions.push(...toTransitionConfigArray(`error.platform.${invokeDef.id}`, invokeDef.onError));
1883
+ }
1884
+ if (invokeDef.onSnapshot) {
1885
+ settleTransitions.push(...toTransitionConfigArray(`xstate.snapshot.${invokeDef.id}`, invokeDef.onSnapshot));
1886
+ }
1887
+ return settleTransitions;
1888
+ });
1889
+ const delayedTransitions = stateNode.after;
1890
+ const formattedTransitions = [...doneConfig, ...invokeConfig, ...transitionConfigs].flatMap(transitionConfig => toArray(transitionConfig).map(transition => formatTransition(stateNode, transition)));
1891
+ for (const delayedTransition of delayedTransitions) {
1892
+ formattedTransitions.push(delayedTransition);
1893
+ }
1894
+ return formattedTransitions;
1895
+ }
1896
+ function formatInitialTransition(stateNode, _target) {
1897
+ if (isString(_target) || isArray(_target)) {
1898
+ const targets = toArray(_target).map(t => {
1899
+ // Resolve state string keys (which represent children)
1900
+ // to their state node
1901
+ const descStateNode = isString(t) ? isStateId(t) ? stateNode.machine.getStateNodeById(t) : stateNode.states[t] : t;
1902
+ if (!descStateNode) {
1903
+ throw new Error(`Initial state node "${t}" not found on parent state node #${stateNode.id}`);
1904
+ }
1905
+ if (!isDescendant(descStateNode, stateNode)) {
1906
+ throw new Error(`Invalid initial target: state node #${descStateNode.id} is not a descendant of #${stateNode.id}`);
1907
+ }
1908
+ return descStateNode;
1909
+ });
1910
+ const resolvedTarget = resolveTarget(stateNode, targets);
1911
+ const transition = {
1912
+ source: stateNode,
1913
+ actions: [],
1914
+ eventType: null,
1915
+ reenter: false,
1916
+ target: resolvedTarget,
1917
+ toJSON: () => ({
1918
+ ...transition,
1919
+ source: `#${stateNode.id}`,
1920
+ target: resolvedTarget ? resolvedTarget.map(t => `#${t.id}`) : undefined
1921
+ })
1922
+ };
1923
+ return transition;
1924
+ }
1925
+ return formatTransition(stateNode, {
1926
+ target: toArray(_target.target).map(t => {
1927
+ if (isString(t)) {
1928
+ return isStateId(t) ? t : `${stateNode.machine.delimiter}${t}`;
1929
+ }
1930
+ return t;
1931
+ }),
1932
+ actions: _target.actions,
1933
+ event: null
1934
+ });
1935
+ }
1936
+ function resolveTarget(stateNode, targets) {
1937
+ if (targets === undefined) {
1938
+ // an undefined target signals that the state node should not transition from that state when receiving that event
1939
+ return undefined;
1940
+ }
1941
+ return targets.map(target => {
1942
+ if (!isString(target)) {
1943
+ return target;
1944
+ }
1945
+ if (isStateId(target)) {
1946
+ return stateNode.machine.getStateNodeById(target);
1947
+ }
1948
+ const isInternalTarget = target[0] === stateNode.machine.delimiter;
1949
+ // If internal target is defined on machine,
1950
+ // do not include machine key on target
1951
+ if (isInternalTarget && !stateNode.parent) {
1952
+ return getStateNodeByPath(stateNode, target.slice(1));
1953
+ }
1954
+ const resolvedTarget = isInternalTarget ? stateNode.key + target : target;
1955
+ if (stateNode.parent) {
1956
+ try {
1957
+ const targetStateNode = getStateNodeByPath(stateNode.parent, resolvedTarget);
1958
+ return targetStateNode;
1959
+ } catch (err) {
1960
+ throw new Error(`Invalid transition definition for state node '${stateNode.id}':\n${err.message}`);
1961
+ }
1962
+ } else {
1963
+ throw new Error(`Invalid target: "${target}" is not a valid target from the root node. Did you mean ".${target}"?`);
1964
+ }
1965
+ });
1966
+ }
1967
+ function resolveHistoryTarget(stateNode) {
1968
+ const normalizedTarget = normalizeTarget(stateNode.target);
1969
+ if (!normalizedTarget) {
1970
+ return stateNode.parent.initial.target;
1971
+ }
1972
+ return normalizedTarget.map(t => typeof t === 'string' ? getStateNodeByPath(stateNode.parent, t) : t);
1973
+ }
1974
+ function isHistoryNode(stateNode) {
1975
+ return stateNode.type === 'history';
1976
+ }
1977
+ function getInitialStateNodes(stateNode) {
1978
+ const set = new Set();
1979
+ function iter(descStateNode) {
1980
+ if (set.has(descStateNode)) {
1981
+ return;
1982
+ }
1983
+ set.add(descStateNode);
1984
+ if (descStateNode.type === 'compound') {
1985
+ for (const targetStateNode of descStateNode.initial.target) {
1986
+ for (const a of getProperAncestors(targetStateNode, stateNode)) {
1987
+ set.add(a);
1988
+ }
1989
+ iter(targetStateNode);
1990
+ }
1991
+ } else if (descStateNode.type === 'parallel') {
1992
+ for (const child of getChildren(descStateNode)) {
1993
+ iter(child);
1994
+ }
1995
+ }
1996
+ }
1997
+ iter(stateNode);
1998
+ return [...set];
1999
+ }
2000
+ /**
2001
+ * Returns the child state node from its relative `stateKey`, or throws.
2002
+ */
2003
+ function getStateNode(stateNode, stateKey) {
2004
+ if (isStateId(stateKey)) {
2005
+ return stateNode.machine.getStateNodeById(stateKey);
2006
+ }
2007
+ if (!stateNode.states) {
2008
+ throw new Error(`Unable to retrieve child state '${stateKey}' from '${stateNode.id}'; no child states exist.`);
2009
+ }
2010
+ const result = stateNode.states[stateKey];
2011
+ if (!result) {
2012
+ throw new Error(`Child state '${stateKey}' does not exist on '${stateNode.id}'`);
2013
+ }
2014
+ return result;
2015
+ }
2016
+
2017
+ /**
2018
+ * Returns the relative state node from the given `statePath`, or throws.
2019
+ *
2020
+ * @param statePath The string or string array relative path to the state node.
2021
+ */
2022
+ function getStateNodeByPath(stateNode, statePath) {
2023
+ if (typeof statePath === 'string' && isStateId(statePath)) {
2024
+ try {
2025
+ return stateNode.machine.getStateNodeById(statePath);
2026
+ } catch (e) {
2027
+ // try individual paths
2028
+ // throw e;
2029
+ }
2030
+ }
2031
+ const arrayStatePath = toStatePath(statePath, stateNode.machine.delimiter).slice();
2032
+ let currentStateNode = stateNode;
2033
+ while (arrayStatePath.length) {
2034
+ const key = arrayStatePath.shift();
2035
+ if (!key.length) {
2036
+ break;
2037
+ }
2038
+ currentStateNode = getStateNode(currentStateNode, key);
2039
+ }
2040
+ return currentStateNode;
2041
+ }
2042
+
2043
+ /**
2044
+ * Returns the state nodes represented by the current state value.
2045
+ *
2046
+ * @param state The state value or State instance
2047
+ */
2048
+ function getStateNodes(stateNode, state) {
2049
+ const stateValue = state instanceof State ? state.value : toStateValue(state, stateNode.machine.delimiter);
2050
+ if (isString(stateValue)) {
2051
+ return [stateNode, stateNode.states[stateValue]];
2052
+ }
2053
+ const childStateKeys = Object.keys(stateValue);
2054
+ const childStateNodes = childStateKeys.map(subStateKey => getStateNode(stateNode, subStateKey)).filter(Boolean);
2055
+ return [stateNode.machine.root, stateNode].concat(childStateNodes, childStateKeys.reduce((allSubStateNodes, subStateKey) => {
2056
+ const subStateNode = getStateNode(stateNode, subStateKey);
2057
+ if (!subStateNode) {
2058
+ return allSubStateNodes;
2059
+ }
2060
+ const subStateNodes = getStateNodes(subStateNode, stateValue[subStateKey]);
2061
+ return allSubStateNodes.concat(subStateNodes);
2062
+ }, []));
2063
+ }
2064
+ function transitionAtomicNode(stateNode, stateValue, state, event) {
2065
+ const childStateNode = getStateNode(stateNode, stateValue);
2066
+ const next = childStateNode.next(state, event);
2067
+ if (!next || !next.length) {
2068
+ return stateNode.next(state, event);
2069
+ }
2070
+ return next;
2071
+ }
2072
+ function transitionCompoundNode(stateNode, stateValue, state, event) {
2073
+ const subStateKeys = Object.keys(stateValue);
2074
+ const childStateNode = getStateNode(stateNode, subStateKeys[0]);
2075
+ const next = transitionNode(childStateNode, stateValue[subStateKeys[0]], state, event);
2076
+ if (!next || !next.length) {
2077
+ return stateNode.next(state, event);
2078
+ }
2079
+ return next;
2080
+ }
2081
+ function transitionParallelNode(stateNode, stateValue, state, event) {
2082
+ const allInnerTransitions = [];
2083
+ for (const subStateKey of Object.keys(stateValue)) {
2084
+ const subStateValue = stateValue[subStateKey];
2085
+ if (!subStateValue) {
2086
+ continue;
2087
+ }
2088
+ const subStateNode = getStateNode(stateNode, subStateKey);
2089
+ const innerTransitions = transitionNode(subStateNode, subStateValue, state, event);
2090
+ if (innerTransitions) {
2091
+ allInnerTransitions.push(...innerTransitions);
2092
+ }
2093
+ }
2094
+ if (!allInnerTransitions.length) {
2095
+ return stateNode.next(state, event);
2096
+ }
2097
+ return allInnerTransitions;
2098
+ }
2099
+ function transitionNode(stateNode, stateValue, state, event) {
2100
+ // leaf node
2101
+ if (isString(stateValue)) {
2102
+ return transitionAtomicNode(stateNode, stateValue, state, event);
2103
+ }
2104
+
2105
+ // compound node
2106
+ if (Object.keys(stateValue).length === 1) {
2107
+ return transitionCompoundNode(stateNode, stateValue, state, event);
2108
+ }
2109
+
2110
+ // parallel node
2111
+ return transitionParallelNode(stateNode, stateValue, state, event);
2112
+ }
2113
+ function getHistoryNodes(stateNode) {
2114
+ return Object.keys(stateNode.states).map(key => stateNode.states[key]).filter(sn => sn.type === 'history');
2115
+ }
2116
+ function isDescendant(childStateNode, parentStateNode) {
2117
+ let marker = childStateNode;
2118
+ while (marker.parent && marker.parent !== parentStateNode) {
2119
+ marker = marker.parent;
2120
+ }
2121
+ return marker.parent === parentStateNode;
2122
+ }
2123
+ function getPathFromRootToNode(stateNode) {
2124
+ const path = [];
2125
+ let marker = stateNode.parent;
2126
+ while (marker) {
2127
+ path.unshift(marker);
2128
+ marker = marker.parent;
2129
+ }
2130
+ return path;
2131
+ }
2132
+ function hasIntersection(s1, s2) {
2133
+ const set1 = new Set(s1);
2134
+ const set2 = new Set(s2);
2135
+ for (const item of set1) {
2136
+ if (set2.has(item)) {
2137
+ return true;
2138
+ }
2139
+ }
2140
+ for (const item of set2) {
2141
+ if (set1.has(item)) {
2142
+ return true;
2143
+ }
2144
+ }
2145
+ return false;
2146
+ }
2147
+ function removeConflictingTransitions(enabledTransitions, configuration, historyValue) {
2148
+ const filteredTransitions = new Set();
2149
+ for (const t1 of enabledTransitions) {
2150
+ let t1Preempted = false;
2151
+ const transitionsToRemove = new Set();
2152
+ for (const t2 of filteredTransitions) {
2153
+ if (hasIntersection(computeExitSet([t1], configuration, historyValue), computeExitSet([t2], configuration, historyValue))) {
2154
+ if (isDescendant(t1.source, t2.source)) {
2155
+ transitionsToRemove.add(t2);
2156
+ } else {
2157
+ t1Preempted = true;
2158
+ break;
2159
+ }
2160
+ }
2161
+ }
2162
+ if (!t1Preempted) {
2163
+ for (const t3 of transitionsToRemove) {
2164
+ filteredTransitions.delete(t3);
2165
+ }
2166
+ filteredTransitions.add(t1);
2167
+ }
2168
+ }
2169
+ return Array.from(filteredTransitions);
2170
+ }
2171
+ function findLCCA(stateNodes) {
2172
+ const [head] = stateNodes;
2173
+ let current = getPathFromRootToNode(head);
2174
+ let candidates = [];
2175
+ for (const stateNode of stateNodes) {
2176
+ const path = getPathFromRootToNode(stateNode);
2177
+ candidates = current.filter(sn => path.includes(sn));
2178
+ current = candidates;
2179
+ candidates = [];
2180
+ }
2181
+ return current[current.length - 1];
2182
+ }
2183
+ function getEffectiveTargetStates(transition, historyValue) {
2184
+ if (!transition.target) {
2185
+ return [];
2186
+ }
2187
+ const targets = new Set();
2188
+ for (const targetNode of transition.target) {
2189
+ if (isHistoryNode(targetNode)) {
2190
+ if (historyValue[targetNode.id]) {
2191
+ for (const node of historyValue[targetNode.id]) {
2192
+ targets.add(node);
2193
+ }
2194
+ } else {
2195
+ for (const node of getEffectiveTargetStates({
2196
+ target: resolveHistoryTarget(targetNode)
2197
+ }, historyValue)) {
2198
+ targets.add(node);
2199
+ }
2200
+ }
2201
+ } else {
2202
+ targets.add(targetNode);
2203
+ }
2204
+ }
2205
+ return [...targets];
2206
+ }
2207
+ function getTransitionDomain(transition, historyValue) {
2208
+ const targetStates = getEffectiveTargetStates(transition, historyValue);
2209
+ if (!targetStates) {
2210
+ return null;
2211
+ }
2212
+ if (!transition.reenter && transition.source.type !== 'parallel' && targetStates.every(targetStateNode => isDescendant(targetStateNode, transition.source))) {
2213
+ return transition.source;
2214
+ }
2215
+ const lcca = findLCCA(targetStates.concat(transition.source));
2216
+ return lcca;
2217
+ }
2218
+ function computeExitSet(transitions, configuration, historyValue) {
2219
+ const statesToExit = new Set();
2220
+ for (const t of transitions) {
2221
+ if (t.target?.length) {
2222
+ const domain = getTransitionDomain(t, historyValue);
2223
+ for (const stateNode of configuration) {
2224
+ if (isDescendant(stateNode, domain)) {
2225
+ statesToExit.add(stateNode);
2226
+ }
2227
+ }
2228
+ }
2229
+ }
2230
+ return [...statesToExit];
2231
+ }
2232
+
2233
+ /**
2234
+ * https://www.w3.org/TR/scxml/#microstepProcedure
2235
+ *
2236
+ * @private
2237
+ * @param transitions
2238
+ * @param currentState
2239
+ * @param mutConfiguration
2240
+ */
2241
+
2242
+ function microstep(transitions, currentState, actorCtx, event) {
2243
+ const {
2244
+ machine
2245
+ } = currentState;
2246
+ // Transition will "apply" if:
2247
+ // - the state node is the initial state (there is no current state)
2248
+ // - OR there are transitions
2249
+ const willTransition = currentState._initial || transitions.length > 0;
2250
+ const mutConfiguration = new Set(currentState.configuration);
2251
+ if (!currentState._initial && !willTransition) {
2252
+ const inertState = cloneState(currentState, {
2253
+ event,
2254
+ actions: [],
2255
+ transitions: []
2256
+ });
2257
+ inertState.changed = false;
2258
+ return inertState;
2259
+ }
2260
+ const microstate = microstepProcedure(currentState._initial ? [{
2261
+ target: [...currentState.configuration].filter(isAtomicStateNode),
2262
+ source: machine.root,
2263
+ reenter: true,
2264
+ actions: [],
2265
+ eventType: null,
2266
+ toJSON: null // TODO: fix
2267
+ }] : transitions, currentState, mutConfiguration, event, actorCtx);
2268
+ const {
2269
+ context,
2270
+ actions: nonRaisedActions
2271
+ } = microstate;
2272
+ const children = setChildren(currentState, nonRaisedActions);
2273
+ const nextState = cloneState(microstate, {
2274
+ value: {},
2275
+ // TODO: make optional
2276
+ transitions,
2277
+ children
2278
+ });
2279
+ nextState.changed = currentState._initial ? undefined : !stateValuesEqual(nextState.value, currentState.value) || nextState.actions.length > 0 || context !== currentState.context;
2280
+ return nextState;
2281
+ }
2282
+ function setChildren(currentState, nonRaisedActions) {
2283
+ const children = {
2284
+ ...currentState.children
2285
+ };
2286
+ for (const action of nonRaisedActions) {
2287
+ if (action.type === invoke$1 && action.params.ref) {
2288
+ const ref = action.params.ref;
2289
+ if (ref) {
2290
+ children[ref.id] = ref;
2291
+ }
2292
+ } else if (action.type === stop$1) {
2293
+ const ref = action.params.actor;
2294
+ if (ref) {
2295
+ delete children[ref.id];
2296
+ }
2297
+ }
2298
+ }
2299
+ return children;
2300
+ }
2301
+ function microstepProcedure(transitions, currentState, mutConfiguration, event, actorCtx) {
2302
+ const actions = [];
2303
+ const historyValue = {
2304
+ ...currentState.historyValue
2305
+ };
2306
+ const filteredTransitions = removeConflictingTransitions(transitions, mutConfiguration, historyValue);
2307
+ const internalQueue = [...currentState._internalQueue];
2308
+
2309
+ // Exit states
2310
+ if (!currentState._initial) {
2311
+ exitStates(filteredTransitions, mutConfiguration, historyValue, actions);
2312
+ }
2313
+
2314
+ // Execute transition content
2315
+ actions.push(...filteredTransitions.flatMap(t => t.actions));
2316
+
2317
+ // Enter states
2318
+ enterStates(filteredTransitions, mutConfiguration, actions, internalQueue, currentState, historyValue);
2319
+ const nextConfiguration = [...mutConfiguration];
2320
+ const done = isInFinalState(nextConfiguration);
2321
+ if (done) {
2322
+ const finalActions = nextConfiguration.sort((a, b) => b.order - a.order).flatMap(state => state.exit);
2323
+ actions.push(...finalActions);
2324
+ }
2325
+ try {
2326
+ const {
2327
+ nextState
2328
+ } = resolveActionsAndContext(actions, event, currentState, actorCtx);
2329
+ const output = done ? getOutput(nextConfiguration, nextState.context, event) : undefined;
2330
+ internalQueue.push(...nextState._internalQueue);
2331
+ return cloneState(currentState, {
2332
+ actions: nextState.actions,
2333
+ configuration: nextConfiguration,
2334
+ historyValue,
2335
+ _internalQueue: internalQueue,
2336
+ context: nextState.context,
2337
+ event,
2338
+ done,
2339
+ output,
2340
+ children: nextState.children
2341
+ });
2342
+ } catch (e) {
2343
+ // TODO: Refactor this once proper error handling is implemented.
2344
+ // See https://github.com/statelyai/rfcs/pull/4
2345
+ throw e;
2346
+ }
2347
+ }
2348
+ function enterStates(filteredTransitions, mutConfiguration, actions, internalQueue, currentState, historyValue) {
2349
+ const statesToEnter = new Set();
2350
+ const statesForDefaultEntry = new Set();
2351
+ computeEntrySet(filteredTransitions, historyValue, statesForDefaultEntry, statesToEnter);
2352
+
2353
+ // In the initial state, the root state node is "entered".
2354
+ if (currentState._initial) {
2355
+ statesForDefaultEntry.add(currentState.machine.root);
2356
+ }
2357
+ for (const stateNodeToEnter of [...statesToEnter].sort((a, b) => a.order - b.order)) {
2358
+ mutConfiguration.add(stateNodeToEnter);
2359
+ for (const invokeDef of stateNodeToEnter.invoke) {
2360
+ actions.push(invoke(invokeDef));
2361
+ }
2362
+
2363
+ // Add entry actions
2364
+ actions.push(...stateNodeToEnter.entry);
2365
+ if (statesForDefaultEntry.has(stateNodeToEnter)) {
2366
+ for (const stateNode of statesForDefaultEntry) {
2367
+ const initialActions = stateNode.initial.actions;
2368
+ actions.push(...initialActions);
2369
+ }
2370
+ }
2371
+ if (stateNodeToEnter.type === 'final') {
2372
+ const parent = stateNodeToEnter.parent;
2373
+ if (!parent.parent) {
2374
+ continue;
2375
+ }
2376
+ internalQueue.push(done(parent.id, stateNodeToEnter.output ? mapContext(stateNodeToEnter.output, currentState.context, currentState.event) : undefined));
2377
+ if (parent.parent) {
2378
+ const grandparent = parent.parent;
2379
+ if (grandparent.type === 'parallel') {
2380
+ if (getChildren(grandparent).every(parentNode => isInFinalState([...mutConfiguration], parentNode))) {
2381
+ internalQueue.push(done(grandparent.id));
2382
+ }
2383
+ }
2384
+ }
2385
+ }
2386
+ }
2387
+ }
2388
+ function computeEntrySet(transitions, historyValue, statesForDefaultEntry, statesToEnter) {
2389
+ for (const t of transitions) {
2390
+ for (const s of t.target || []) {
2391
+ addDescendantStatesToEnter(s, historyValue, statesForDefaultEntry, statesToEnter);
2392
+ }
2393
+ const ancestor = getTransitionDomain(t, historyValue);
2394
+ const targetStates = getEffectiveTargetStates(t, historyValue);
2395
+ for (const s of targetStates) {
2396
+ addAncestorStatesToEnter(s, ancestor, statesToEnter, historyValue, statesForDefaultEntry);
2397
+ }
2398
+ }
2399
+ }
2400
+ function addDescendantStatesToEnter(stateNode, historyValue, statesForDefaultEntry, statesToEnter) {
2401
+ if (isHistoryNode(stateNode)) {
2402
+ if (historyValue[stateNode.id]) {
2403
+ const historyStateNodes = historyValue[stateNode.id];
2404
+ for (const s of historyStateNodes) {
2405
+ addDescendantStatesToEnter(s, historyValue, statesForDefaultEntry, statesToEnter);
2406
+ }
2407
+ for (const s of historyStateNodes) {
2408
+ addAncestorStatesToEnter(s, stateNode.parent, statesToEnter, historyValue, statesForDefaultEntry);
2409
+ for (const stateForDefaultEntry of statesForDefaultEntry) {
2410
+ statesForDefaultEntry.add(stateForDefaultEntry);
2411
+ }
2412
+ }
2413
+ } else {
2414
+ const targets = resolveHistoryTarget(stateNode);
2415
+ for (const s of targets) {
2416
+ addDescendantStatesToEnter(s, historyValue, statesForDefaultEntry, statesToEnter);
2417
+ }
2418
+ for (const s of targets) {
2419
+ addAncestorStatesToEnter(s, stateNode, statesToEnter, historyValue, statesForDefaultEntry);
2420
+ for (const stateForDefaultEntry of statesForDefaultEntry) {
2421
+ statesForDefaultEntry.add(stateForDefaultEntry);
2422
+ }
2423
+ }
2424
+ }
2425
+ } else {
2426
+ statesToEnter.add(stateNode);
2427
+ if (stateNode.type === 'compound') {
2428
+ statesForDefaultEntry.add(stateNode);
2429
+ const initialStates = stateNode.initial.target;
2430
+ for (const initialState of initialStates) {
2431
+ addDescendantStatesToEnter(initialState, historyValue, statesForDefaultEntry, statesToEnter);
2432
+ }
2433
+ for (const initialState of initialStates) {
2434
+ addAncestorStatesToEnter(initialState, stateNode, statesToEnter, historyValue, statesForDefaultEntry);
2435
+ }
2436
+ } else {
2437
+ if (stateNode.type === 'parallel') {
2438
+ for (const child of getChildren(stateNode).filter(sn => !isHistoryNode(sn))) {
2439
+ if (![...statesToEnter].some(s => isDescendant(s, child))) {
2440
+ addDescendantStatesToEnter(child, historyValue, statesForDefaultEntry, statesToEnter);
2441
+ }
2442
+ }
2443
+ }
2444
+ }
2445
+ }
2446
+ }
2447
+ function addAncestorStatesToEnter(stateNode, toStateNode, statesToEnter, historyValue, statesForDefaultEntry) {
2448
+ const properAncestors = getProperAncestors(stateNode, toStateNode);
2449
+ for (const anc of properAncestors) {
2450
+ statesToEnter.add(anc);
2451
+ if (anc.type === 'parallel') {
2452
+ for (const child of getChildren(anc).filter(sn => !isHistoryNode(sn))) {
2453
+ if (![...statesToEnter].some(s => isDescendant(s, child))) {
2454
+ addDescendantStatesToEnter(child, historyValue, statesForDefaultEntry, statesToEnter);
2455
+ }
2456
+ }
2457
+ }
2458
+ }
2459
+ }
2460
+ function exitStates(transitions, mutConfiguration, historyValue, actions) {
2461
+ const statesToExit = computeExitSet(transitions, mutConfiguration, historyValue);
2462
+ statesToExit.sort((a, b) => b.order - a.order);
2463
+
2464
+ // From SCXML algorithm: https://www.w3.org/TR/scxml/#exitStates
2465
+ for (const exitStateNode of statesToExit) {
2466
+ for (const historyNode of getHistoryNodes(exitStateNode)) {
2467
+ let predicate;
2468
+ if (historyNode.history === 'deep') {
2469
+ predicate = sn => isAtomicStateNode(sn) && isDescendant(sn, exitStateNode);
2470
+ } else {
2471
+ predicate = sn => {
2472
+ return sn.parent === exitStateNode;
2473
+ };
2474
+ }
2475
+ historyValue[historyNode.id] = Array.from(mutConfiguration).filter(predicate);
2476
+ }
2477
+ }
2478
+ for (const s of statesToExit) {
2479
+ actions.push(...s.exit.flat(), ...s.invoke.map(def => stop(def.id)));
2480
+ mutConfiguration.delete(s);
2481
+ }
2482
+ }
2483
+ function resolveActionsAndContext(actions, event, currentState, actorCtx) {
2484
+ const {
2485
+ machine
2486
+ } = currentState;
2487
+ const resolvedActions = [];
2488
+ const raiseActions = [];
2489
+ let intermediateState = currentState;
2490
+ function handleAction(action) {
2491
+ resolvedActions.push(action);
2492
+ if (actorCtx?.self.status === ActorStatus.Running) {
2493
+ action.execute?.(actorCtx);
2494
+ // TODO: this is hacky; re-evaluate
2495
+ delete action.execute;
2496
+ }
2497
+ }
2498
+ function resolveAction(actionObject) {
2499
+ const executableActionObject = resolveActionObject(actionObject, machine.options.actions);
2500
+ if (isDynamicAction(executableActionObject)) {
2501
+ const [nextState, resolvedAction] = executableActionObject.resolve(event, {
2502
+ state: intermediateState,
2503
+ action: actionObject,
2504
+ actorContext: actorCtx
2505
+ });
2506
+ const matchedActions = resolvedAction.params?.actions;
2507
+ intermediateState = nextState;
2508
+ if ((resolvedAction.type === raise$1 || resolvedAction.type === send$1 && resolvedAction.params.internal) && typeof resolvedAction.params.delay !== 'number') {
2509
+ raiseActions.push(resolvedAction);
2510
+ }
2511
+
2512
+ // TODO: remove the check; just handleAction
2513
+ if (resolvedAction.type !== pure$1) {
2514
+ handleAction(resolvedAction);
2515
+ }
2516
+ toActionObjects(matchedActions).forEach(resolveAction);
2517
+ return;
2518
+ }
2519
+ handleAction(executableActionObject);
2520
+ }
2521
+ for (const actionObject of actions) {
2522
+ resolveAction(actionObject);
2523
+ }
2524
+ return {
2525
+ nextState: cloneState(intermediateState, {
2526
+ actions: resolvedActions,
2527
+ _internalQueue: raiseActions.map(a => a.params.event)
2528
+ })
2529
+ };
2530
+ }
2531
+ function macrostep(state, event, actorCtx) {
2532
+ let nextState = state;
2533
+ const states = [];
2534
+
2535
+ // Handle stop event
2536
+ if (event.type === stopSignalType) {
2537
+ nextState = stopStep(event, nextState, actorCtx);
2538
+ states.push(nextState);
2539
+ return {
2540
+ state: nextState,
2541
+ microstates: states
2542
+ };
2543
+ }
2544
+
2545
+ // Assume the state is at rest (no raised events)
2546
+ // Determine the next state based on the next microstep
2547
+ if (event.type !== init) {
2548
+ const transitions = selectTransitions(event, nextState);
2549
+ nextState = microstep(transitions, state, actorCtx, event);
2550
+ states.push(nextState);
2551
+ }
2552
+ while (!nextState.done) {
2553
+ let enabledTransitions = selectEventlessTransitions(nextState);
2554
+ if (enabledTransitions.length === 0) {
2555
+ // TODO: this is a bit of a hack, we need to review this
2556
+ // this matches the behavior from v4 for eventless transitions
2557
+ // where for `hasAlwaysTransitions` we were always trying to resolve with a NULL event
2558
+ // and if a transition was not selected the `state.transitions` stayed empty
2559
+ // without this we get into an infinite loop in the dieHard test in `@xstate/test` for the `simplePathsTo`
2560
+ if (nextState.configuration.some(state => state.always)) {
2561
+ nextState.transitions = [];
2562
+ }
2563
+ if (!nextState._internalQueue.length) {
2564
+ break;
2565
+ } else {
2566
+ const currentActions = nextState.actions;
2567
+ const nextEvent = nextState._internalQueue[0];
2568
+ const transitions = selectTransitions(nextEvent, nextState);
2569
+ nextState = microstep(transitions, nextState, actorCtx, nextEvent);
2570
+ nextState._internalQueue.shift();
2571
+ nextState.actions.unshift(...currentActions);
2572
+ states.push(nextState);
2573
+ }
2574
+ }
2575
+ if (enabledTransitions.length) {
2576
+ const currentActions = nextState.actions;
2577
+ nextState = microstep(enabledTransitions, nextState, actorCtx, nextState.event);
2578
+ nextState.actions.unshift(...currentActions);
2579
+ states.push(nextState);
2580
+ }
2581
+ }
2582
+ if (nextState.done) {
2583
+ // Perform the stop step to ensure that child actors are stopped
2584
+ stopStep(nextState.event, nextState, actorCtx);
2585
+ }
2586
+ return {
2587
+ state: nextState,
2588
+ microstates: states
2589
+ };
2590
+ }
2591
+ function stopStep(event, nextState, actorCtx) {
2592
+ const actions = [];
2593
+ for (const stateNode of nextState.configuration.sort((a, b) => b.order - a.order)) {
2594
+ actions.push(...stateNode.exit);
2595
+ }
2596
+ for (const child of Object.values(nextState.children)) {
2597
+ actions.push(stop(child));
2598
+ }
2599
+ const {
2600
+ nextState: stoppedState
2601
+ } = resolveActionsAndContext(actions, event, nextState, actorCtx);
2602
+ return stoppedState;
2603
+ }
2604
+ function selectTransitions(event, nextState) {
2605
+ return nextState.machine.getTransitionData(nextState, event);
2606
+ }
2607
+ function selectEventlessTransitions(nextState) {
2608
+ const enabledTransitionSet = new Set();
2609
+ const atomicStates = nextState.configuration.filter(isAtomicStateNode);
2610
+ for (const stateNode of atomicStates) {
2611
+ loop: for (const s of [stateNode].concat(getProperAncestors(stateNode, null))) {
2612
+ if (!s.always) {
2613
+ continue;
2614
+ }
2615
+ for (const transition of s.always) {
2616
+ if (transition.guard === undefined || evaluateGuard(transition.guard, nextState.context, nextState.event, nextState)) {
2617
+ enabledTransitionSet.add(transition);
2618
+ break loop;
2619
+ }
2620
+ }
2621
+ }
2622
+ }
2623
+ return removeConflictingTransitions(Array.from(enabledTransitionSet), new Set(nextState.configuration), nextState.historyValue);
2624
+ }
2625
+
2626
+ /**
2627
+ * Resolves a partial state value with its full representation in the state node's machine.
2628
+ *
2629
+ * @param stateValue The partial state value to resolve.
2630
+ */
2631
+ function resolveStateValue(rootNode, stateValue) {
2632
+ const configuration = getConfiguration(getStateNodes(rootNode, stateValue));
2633
+ return getStateValue(rootNode, [...configuration]);
2634
+ }
2635
+ function stateValuesEqual(a, b) {
2636
+ if (a === b) {
2637
+ return true;
2638
+ }
2639
+ if (a === undefined || b === undefined) {
2640
+ return false;
2641
+ }
2642
+ if (isString(a) || isString(b)) {
2643
+ return a === b;
2644
+ }
2645
+ const aKeys = Object.keys(a);
2646
+ const bKeys = Object.keys(b);
2647
+ return aKeys.length === bKeys.length && aKeys.every(key => stateValuesEqual(a[key], b[key]));
2648
+ }
2649
+ function getInitialConfiguration(rootNode) {
2650
+ const configuration = [];
2651
+ const initialTransition = rootNode.initial;
2652
+ const statesToEnter = new Set();
2653
+ const statesForDefaultEntry = new Set([rootNode]);
2654
+ computeEntrySet([initialTransition], {}, statesForDefaultEntry, statesToEnter);
2655
+ for (const stateNodeToEnter of [...statesToEnter].sort((a, b) => a.order - b.order)) {
2656
+ configuration.push(stateNodeToEnter);
2657
+ }
2658
+ return configuration;
2659
+ }
2660
+
2661
+ class State {
2662
+ /**
2663
+ * Indicates whether the state is a final state.
2664
+ */
2665
+
2666
+ /**
2667
+ * The done data of the top-level finite state.
2668
+ */
2669
+ // TODO: add an explicit type for `output`
2670
+
2671
+ /**
2672
+ * Indicates whether the state has changed from the previous state. A state is considered "changed" if:
2673
+ *
2674
+ * - Its value is not equal to its previous value, or:
2675
+ * - It has any new actions (side-effects) to execute.
2676
+ *
2677
+ * An initial state (with no history) will return `undefined`.
2678
+ */
2679
+
2680
+ /**
2681
+ * The enabled state nodes representative of the state value.
2682
+ */
2683
+
2684
+ /**
2685
+ * The transition definitions that resulted in this state.
2686
+ */
2687
+
2688
+ /**
2689
+ * An object mapping actor names to spawned/invoked actors.
2690
+ */
2691
+
2692
+ /**
2693
+ * Creates a new State instance for the given `stateValue` and `context`.
2694
+ * @param stateValue
2695
+ * @param context
2696
+ */
2697
+ static from(stateValue, context = {}, machine) {
2698
+ if (stateValue instanceof State) {
2699
+ if (stateValue.context !== context) {
2700
+ return new State({
2701
+ value: stateValue.value,
2702
+ context,
2703
+ event: stateValue.event,
2704
+ actions: [],
2705
+ meta: {},
2706
+ configuration: [],
2707
+ // TODO: fix,
2708
+ transitions: [],
2709
+ children: {}
2710
+ }, machine);
2711
+ }
2712
+ return stateValue;
2713
+ }
2714
+ const event = createInitEvent({}); // TODO: fix
2715
+
2716
+ const configuration = getConfiguration(getStateNodes(machine.root, stateValue));
2717
+ return new State({
2718
+ value: stateValue,
2719
+ context,
2720
+ event,
2721
+ actions: [],
2722
+ meta: undefined,
2723
+ configuration: Array.from(configuration),
2724
+ transitions: [],
2725
+ children: {}
2726
+ }, machine);
2727
+ }
2728
+
2729
+ /**
2730
+ * Creates a new `State` instance that represents the current state of a running machine.
2731
+ *
2732
+ * @param config
2733
+ */
2734
+ constructor(config, machine) {
2735
+ this.machine = machine;
2736
+ this.tags = void 0;
2737
+ this.value = void 0;
2738
+ this.done = void 0;
2739
+ this.output = void 0;
2740
+ this.context = void 0;
2741
+ this.historyValue = {};
2742
+ this.actions = [];
2743
+ this.event = void 0;
2744
+ this._internalQueue = void 0;
2745
+ this._initial = false;
2746
+ this.changed = void 0;
2747
+ this.configuration = void 0;
2748
+ this.transitions = void 0;
2749
+ this.children = void 0;
2750
+ this.context = config.context;
2751
+ this._internalQueue = config._internalQueue ?? [];
2752
+ this.event = config.event;
2753
+ this.historyValue = config.historyValue || {};
2754
+ this.actions = config.actions ?? [];
2755
+ this.matches = this.matches.bind(this);
2756
+ this.toStrings = this.toStrings.bind(this);
2757
+ this.configuration = config.configuration ?? Array.from(getConfiguration(getStateNodes(machine.root, config.value)));
2758
+ this.transitions = config.transitions;
2759
+ this.children = config.children;
2760
+ this.value = getStateValue(machine.root, this.configuration);
2761
+ this.tags = new Set(flatten(this.configuration.map(sn => sn.tags)));
2762
+ this.done = config.done ?? false;
2763
+ this.output = config.output;
2764
+ }
2765
+
2766
+ /**
2767
+ * Returns an array of all the string leaf state node paths.
2768
+ * @param stateValue
2769
+ * @param delimiter The character(s) that separate each subpath in the string state node path.
2770
+ */
2771
+ toStrings(stateValue = this.value, delimiter = '.') {
2772
+ if (isString(stateValue)) {
2773
+ return [stateValue];
2774
+ }
2775
+ const valueKeys = Object.keys(stateValue);
2776
+ return valueKeys.concat(...valueKeys.map(key => this.toStrings(stateValue[key], delimiter).map(s => key + delimiter + s)));
2777
+ }
2778
+ toJSON() {
2779
+ const {
2780
+ configuration,
2781
+ transitions,
2782
+ tags,
2783
+ machine,
2784
+ ...jsonValues
2785
+ } = this;
2786
+ return {
2787
+ ...jsonValues,
2788
+ tags: Array.from(tags),
2789
+ meta: this.meta
2790
+ };
2791
+ }
2792
+
2793
+ /**
2794
+ * Whether the current state value is a subset of the given parent state value.
2795
+ * @param parentStateValue
2796
+ */
2797
+ matches(parentStateValue) {
2798
+ return matchesState(parentStateValue, this.value);
2799
+ }
2800
+
2801
+ /**
2802
+ * Whether the current state configuration has a state node with the specified `tag`.
2803
+ * @param tag
2804
+ */
2805
+ hasTag(tag) {
2806
+ return this.tags.has(tag);
2807
+ }
2808
+
2809
+ /**
2810
+ * Determines whether sending the `event` will cause a non-forbidden transition
2811
+ * to be selected, even if the transitions have no actions nor
2812
+ * change the state value.
2813
+ *
2814
+ * @param event The event to test
2815
+ * @returns Whether the event will cause a transition
2816
+ */
2817
+ can(event) {
2818
+ const transitionData = this.machine.getTransitionData(this, event);
2819
+ return !!transitionData?.length &&
2820
+ // Check that at least one transition is not forbidden
2821
+ transitionData.some(t => t.target !== undefined || t.actions.length);
2822
+ }
2823
+
2824
+ /**
2825
+ * The next events that will cause a transition from the current state.
2826
+ */
2827
+ get nextEvents() {
2828
+ return memo(this, 'nextEvents', () => {
2829
+ return [...new Set(flatten([...this.configuration.map(sn => sn.ownEvents)]))];
2830
+ });
2831
+ }
2832
+ get meta() {
2833
+ return this.configuration.reduce((acc, stateNode) => {
2834
+ if (stateNode.meta !== undefined) {
2835
+ acc[stateNode.id] = stateNode.meta;
2836
+ }
2837
+ return acc;
2838
+ }, {});
2839
+ }
2840
+ }
2841
+ function cloneState(state, config = {}) {
2842
+ return new State({
2843
+ ...state,
2844
+ ...config
2845
+ }, state.machine);
2846
+ }
2847
+ function getPersistedState(state) {
2848
+ const {
2849
+ configuration,
2850
+ transitions,
2851
+ tags,
2852
+ machine,
2853
+ children,
2854
+ ...jsonValues
2855
+ } = state;
2856
+ const childrenJson = {};
2857
+ for (const id in children) {
2858
+ childrenJson[id] = {
2859
+ state: children[id].getPersistedState?.(),
2860
+ src: children[id].src
2861
+ };
2862
+ }
2863
+ return {
2864
+ ...jsonValues,
2865
+ children: childrenJson
2866
+ };
2867
+ }
2868
+
2869
+ function invoke(invokeDef) {
2870
+ return createDynamicAction({
2871
+ type: invoke$1,
2872
+ params: invokeDef
2873
+ }, (event, {
2874
+ state,
2875
+ actorContext
2876
+ }) => {
2877
+ const type = invoke$1;
2878
+ const {
2879
+ id,
2880
+ src
2881
+ } = invokeDef;
2882
+ let resolvedInvokeAction;
2883
+ if (isActorRef(src)) {
2884
+ resolvedInvokeAction = {
2885
+ type,
2886
+ params: {
2887
+ ...invokeDef,
2888
+ ref: src
2889
+ }
2890
+ };
2891
+ } else {
2892
+ const referenced = resolveReferencedActor(state.machine.options.actors[src]);
2893
+ if (!referenced) {
2894
+ resolvedInvokeAction = {
2895
+ type,
2896
+ params: invokeDef
2897
+ };
2898
+ } else {
2899
+ const input = 'input' in invokeDef ? invokeDef.input : referenced.input;
2900
+ const ref = interpret(referenced.src, {
2901
+ id,
2902
+ src,
2903
+ parent: actorContext?.self,
2904
+ systemId: invokeDef.systemId,
2905
+ input: typeof input === 'function' ? input({
2906
+ context: state.context,
2907
+ event,
2908
+ self: actorContext?.self
2909
+ }) : input
2910
+ });
2911
+ resolvedInvokeAction = {
2912
+ type,
2913
+ params: {
2914
+ ...invokeDef,
2915
+ ref
2916
+ }
2917
+ };
2918
+ }
2919
+ }
2920
+ const actorRef = resolvedInvokeAction.params.ref;
2921
+ const invokedState = cloneState(state, {
2922
+ children: {
2923
+ ...state.children,
2924
+ [id]: actorRef
2925
+ }
2926
+ });
2927
+ resolvedInvokeAction.execute = actorCtx => {
2928
+ const parent = actorCtx.self;
2929
+ const {
2930
+ id,
2931
+ ref
2932
+ } = resolvedInvokeAction.params;
2933
+ if (!ref) {
2934
+ return;
2935
+ }
2936
+ actorCtx.defer(() => {
2937
+ if (actorRef.status === ActorStatus.Stopped) {
2938
+ return;
2939
+ }
2940
+ try {
2941
+ actorRef.start?.();
2942
+ } catch (err) {
2943
+ parent.send(error(id, err));
2944
+ return;
2945
+ }
2946
+ });
2947
+ };
2948
+ return [invokedState, resolvedInvokeAction];
2949
+ });
2950
+ }
2951
+
2952
+ function createSpawner(self, machine, context, event, mutCapturedActions) {
2953
+ return (src, options = {}) => {
2954
+ if (isString(src)) {
2955
+ const referenced = resolveReferencedActor(machine.options.actors[src]);
2956
+ if (referenced) {
2957
+ const resolvedName = options.id ?? 'anon'; // TODO: better name
2958
+ const input = 'input' in options ? options.input : referenced.input;
2959
+
2960
+ // TODO: this should also receive `src`
2961
+ const actorRef = interpret(referenced.src, {
2962
+ id: resolvedName,
2963
+ parent: self,
2964
+ input: typeof input === 'function' ? input({
2965
+ context,
2966
+ event,
2967
+ self
2968
+ }) : input
2969
+ });
2970
+ mutCapturedActions.push(invoke({
2971
+ id: actorRef.id,
2972
+ // @ts-ignore TODO: fix types
2973
+ src: actorRef,
2974
+ // TODO
2975
+ ref: actorRef,
2976
+ meta: undefined,
2977
+ input
2978
+ }));
2979
+ return actorRef; // TODO: fix types
2980
+ }
2981
+
2982
+ throw new Error(`Behavior '${src}' not implemented in machine '${machine.id}'`);
2983
+ } else {
2984
+ // TODO: this should also receive `src`
2985
+ // TODO: instead of anonymous, it should be a unique stable ID
2986
+ const actorRef = interpret(src, {
2987
+ id: options.id || 'anonymous',
2988
+ parent: self,
2989
+ input: options.input
2990
+ });
2991
+ mutCapturedActions.push(invoke({
2992
+ // @ts-ignore TODO: fix types
2993
+ src: actorRef,
2994
+ ref: actorRef,
2995
+ id: actorRef.id,
2996
+ meta: undefined,
2997
+ input: options.input
2998
+ }));
2999
+ return actorRef; // TODO: fix types
3000
+ }
3001
+ };
3002
+ }
3003
+
3004
+ /**
3005
+ * Updates the current context of the machine.
3006
+ *
3007
+ * @param assignment An object that represents the partial context to update.
3008
+ */
3009
+ function assign(assignment) {
3010
+ return createDynamicAction({
3011
+ type: assign$1,
3012
+ params: {
3013
+ assignment
3014
+ }
3015
+ }, (event, {
3016
+ state,
3017
+ action,
3018
+ actorContext
3019
+ }) => {
3020
+ const capturedActions = [];
3021
+ if (!state.context) {
3022
+ throw new Error('Cannot assign to undefined `context`. Ensure that `context` is defined in the machine config.');
3023
+ }
3024
+ const args = {
3025
+ context: state.context,
3026
+ event,
3027
+ action,
3028
+ spawn: createSpawner(actorContext?.self, state.machine, state.context, event, capturedActions),
3029
+ self: actorContext?.self ?? {},
3030
+ system: actorContext?.system
3031
+ };
3032
+ let partialUpdate = {};
3033
+ if (isFunction(assignment)) {
3034
+ partialUpdate = assignment(args);
3035
+ } else {
3036
+ for (const key of Object.keys(assignment)) {
3037
+ const propAssignment = assignment[key];
3038
+ partialUpdate[key] = isFunction(propAssignment) ? propAssignment(args) : propAssignment;
3039
+ }
3040
+ }
3041
+ const updatedContext = Object.assign({}, state.context, partialUpdate);
3042
+ return [cloneState(state, {
3043
+ context: updatedContext
3044
+ }), {
3045
+ type: assign$1,
3046
+ params: {
3047
+ context: updatedContext,
3048
+ actions: capturedActions
3049
+ }
3050
+ }];
3051
+ });
3052
+ }
3053
+
3054
+ /**
3055
+ * Raises an event. This places the event in the internal event queue, so that
3056
+ * the event is immediately consumed by the machine in the current step.
3057
+ *
3058
+ * @param eventType The event to raise.
3059
+ */
3060
+
3061
+ function raise(eventOrExpr, options) {
3062
+ return createDynamicAction({
3063
+ type: raise$1,
3064
+ params: {
3065
+ delay: options ? options.delay : undefined,
3066
+ event: eventOrExpr,
3067
+ id: options && options.id !== undefined ? options.id : typeof eventOrExpr === 'function' ? eventOrExpr.name : eventOrExpr.type
3068
+ }
3069
+ }, (event, {
3070
+ state,
3071
+ actorContext
3072
+ }) => {
3073
+ const params = {
3074
+ delay: options ? options.delay : undefined,
3075
+ event: eventOrExpr,
3076
+ id: options && options.id !== undefined ? options.id : typeof eventOrExpr === 'function' ? eventOrExpr.name : eventOrExpr.type
3077
+ };
3078
+ const args = {
3079
+ context: state.context,
3080
+ event,
3081
+ self: actorContext?.self ?? {},
3082
+ system: actorContext?.system
3083
+ };
3084
+ const delaysMap = state.machine.options.delays;
3085
+
3086
+ // TODO: helper function for resolving Expr
3087
+ if (typeof eventOrExpr === 'string') {
3088
+ throw new Error(`Only event objects may be used with raise; use raise({ type: "${eventOrExpr}" }) instead`);
3089
+ }
3090
+ const resolvedEvent = typeof eventOrExpr === 'function' ? eventOrExpr(args) : eventOrExpr;
3091
+ let resolvedDelay;
3092
+ if (typeof params.delay === 'string') {
3093
+ const configDelay = delaysMap && delaysMap[params.delay];
3094
+ resolvedDelay = typeof configDelay === 'function' ? configDelay(args) : configDelay;
3095
+ } else {
3096
+ resolvedDelay = typeof params.delay === 'function' ? params.delay(args) : params.delay;
3097
+ }
3098
+ const resolvedAction = {
3099
+ type: raise$1,
3100
+ params: {
3101
+ ...params,
3102
+ event: resolvedEvent,
3103
+ delay: resolvedDelay
3104
+ },
3105
+ execute: actorCtx => {
3106
+ if (typeof resolvedAction.params.delay === 'number') {
3107
+ actorCtx.self.delaySend(resolvedAction);
3108
+ return;
3109
+ }
3110
+ }
3111
+ };
3112
+ return [state, resolvedAction];
3113
+ });
3114
+ }
3115
+
3116
+ function choose(guards) {
3117
+ return createDynamicAction({
3118
+ type: choose$1,
3119
+ params: {
3120
+ guards
3121
+ }
3122
+ }, (event, {
3123
+ state
3124
+ }) => {
3125
+ const matchedActions = guards.find(condition => {
3126
+ const guard = condition.guard && toGuardDefinition(condition.guard, guardType => state.machine.options.guards[guardType]);
3127
+ return !guard || evaluateGuard(guard, state.context, event, state);
3128
+ })?.actions;
3129
+ return [state, {
3130
+ type: choose$1,
3131
+ params: {
3132
+ actions: toActionObjects(matchedActions)
3133
+ }
3134
+ }];
3135
+ });
3136
+ }
3137
+
3138
+ function pure(getActions) {
3139
+ return createDynamicAction({
3140
+ type: pure$1,
3141
+ params: {
3142
+ get: getActions
3143
+ }
3144
+ }, (event, {
3145
+ state
3146
+ }) => {
3147
+ return [state, {
3148
+ type: pure$1,
3149
+ params: {
3150
+ actions: toArray(toActionObjects(getActions({
3151
+ context: state.context,
3152
+ event
3153
+ }))) ?? []
3154
+ }
3155
+ }];
3156
+ });
3157
+ }
3158
+
3159
+ const initEvent = {
3160
+ type: init
3161
+ };
3162
+ function resolveActionObject(actionObject, actionFunctionMap) {
3163
+ if (isDynamicAction(actionObject)) {
3164
+ return actionObject;
3165
+ }
3166
+ const dereferencedAction = actionFunctionMap[actionObject.type];
3167
+ if (typeof dereferencedAction === 'function') {
3168
+ return createDynamicAction({
3169
+ type: 'xstate.function',
3170
+ params: actionObject.params ?? {}
3171
+ }, (event, {
3172
+ state
3173
+ }) => {
3174
+ const a = {
3175
+ type: actionObject.type,
3176
+ params: actionObject.params,
3177
+ execute: actorCtx => {
3178
+ return dereferencedAction({
3179
+ context: state.context,
3180
+ event,
3181
+ action: a,
3182
+ system: actorCtx.system,
3183
+ self: actorCtx.self
3184
+ });
3185
+ }
3186
+ };
3187
+ return [state, a];
3188
+ });
3189
+ } else if (dereferencedAction) {
3190
+ return dereferencedAction;
3191
+ } else {
3192
+ return actionObject;
3193
+ }
3194
+ }
3195
+ function toActionObject(action) {
3196
+ if (isDynamicAction(action)) {
3197
+ return action;
3198
+ }
3199
+ if (typeof action === 'string') {
3200
+ return {
3201
+ type: action,
3202
+ params: {}
3203
+ };
3204
+ }
3205
+ if (typeof action === 'function') {
3206
+ const type = 'xstate.function';
3207
+ return createDynamicAction({
3208
+ type,
3209
+ params: {}
3210
+ }, (event, {
3211
+ state
3212
+ }) => {
3213
+ const actionObject = {
3214
+ type,
3215
+ params: {
3216
+ function: action
3217
+ },
3218
+ execute: actorCtx => {
3219
+ return action({
3220
+ context: state.context,
3221
+ event: event,
3222
+ action: actionObject,
3223
+ self: actorCtx.self,
3224
+ system: actorCtx.system
3225
+ });
3226
+ }
3227
+ };
3228
+ return [state, actionObject];
3229
+ });
3230
+ }
3231
+
3232
+ // action is already a BaseActionObject
3233
+ return action;
3234
+ }
3235
+ const toActionObjects = action => {
3236
+ if (!action) {
3237
+ return [];
3238
+ }
3239
+ const actions = isArray(action) ? action : [action];
3240
+ return actions.map(toActionObject);
3241
+ };
3242
+
3243
+ /**
3244
+ * Returns an event type that represents an implicit event that
3245
+ * is sent after the specified `delay`.
3246
+ *
3247
+ * @param delayRef The delay in milliseconds
3248
+ * @param id The state node ID where this event is handled
3249
+ */
3250
+ function after(delayRef, id) {
3251
+ const idSuffix = id ? `#${id}` : '';
3252
+ return `${ActionTypes.After}(${delayRef})${idSuffix}`;
3253
+ }
3254
+
3255
+ /**
3256
+ * Returns an event that represents that a final state node
3257
+ * has been reached in the parent state node.
3258
+ *
3259
+ * @param id The final state node's parent state node `id`
3260
+ * @param output The data to pass into the event
3261
+ */
3262
+ function done(id, output) {
3263
+ const type = `${ActionTypes.DoneState}.${id}`;
3264
+ const eventObject = {
3265
+ type,
3266
+ output
3267
+ };
3268
+ eventObject.toString = () => type;
3269
+ return eventObject;
3270
+ }
3271
+
3272
+ /**
3273
+ * Returns an event that represents that an invoked service has terminated.
3274
+ *
3275
+ * An invoked service is terminated when it has reached a top-level final state node,
3276
+ * but not when it is canceled.
3277
+ *
3278
+ * @param invokeId The invoked service ID
3279
+ * @param output The data to pass into the event
3280
+ */
3281
+ function doneInvoke(invokeId, output) {
3282
+ const type = `${ActionTypes.DoneInvoke}.${invokeId}`;
3283
+ const eventObject = {
3284
+ type,
3285
+ output
3286
+ };
3287
+ eventObject.toString = () => type;
3288
+ return eventObject;
3289
+ }
3290
+ function error(id, data) {
3291
+ const type = `${ActionTypes.ErrorPlatform}.${id}`;
3292
+ const eventObject = {
3293
+ type,
3294
+ data
3295
+ };
3296
+ eventObject.toString = () => type;
3297
+ return eventObject;
3298
+ }
3299
+ function createInitEvent(input) {
3300
+ return {
3301
+ type: init,
3302
+ input
3303
+ };
3304
+ }
3305
+
3306
+ export { toObserver as $, createInitEvent as A, resolveActionsAndContext as B, microstep as C, error as D, isStateId as E, getStateNodeByPath as F, getPersistedState as G, resolveReferencedActor as H, interpret as I, initEvent as J, matchesState as K, sendTo as L, sendParent as M, NULL_EVENT as N, forwardTo as O, Interpreter as P, ActorStatus as Q, doneInvoke as R, STATE_DELIMITER as S, assign as T, cancel as U, choose as V, log as W, pure as X, raise as Y, stop as Z, pathToStateValue as _, toArray as a, fromPromise as a0, fromObservable as a1, fromCallback as a2, fromEventObservable as a3, fromTransition as a4, stateIn as a5, not as a6, and as a7, or as a8, ActionTypes as a9, SpecialTargets as aa, startSignalType as ab, stopSignalType as ac, startSignal as ad, stopSignal as ae, isSignal as af, isActorRef as ag, toActorRef as ah, createEmptyActor as ai, toGuardDefinition as aj, actionTypes as ak, resolveActionObject as al, toActionObject as am, after as an, done as ao, send as ap, escalate as aq, toTransitionConfigArray as b, formatTransition as c, memo as d, evaluateGuard as e, formatTransitions as f, flatten as g, createInvokeId as h, isString as i, invoke$1 as j, getDelayedTransitions as k, formatInitialTransition as l, mapValues as m, getCandidates as n, toInvokeConfig as o, createSpawner as p, getConfiguration as q, getStateNodes as r, resolveStateValue as s, toActionObjects as t, isInFinalState as u, State as v, isErrorEvent as w, macrostep as x, transitionNode as y, getInitialConfiguration as z };