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