xstate 5.0.0-beta.10 → 5.0.0-beta.12

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 (57) 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-b34f6ce7.esm.js +3292 -0
  20. package/dist/actions-c8b9504d.development.esm.js +3327 -0
  21. package/dist/actions-d9c19f35.development.cjs.js +3409 -0
  22. package/dist/actions-e4c704f3.cjs.js +3374 -0
  23. package/dist/declarations/src/interpreter.d.ts +1 -6
  24. package/dist/declarations/src/types.d.ts +1 -0
  25. package/dist/declarations/src/utils.d.ts +0 -1
  26. package/dist/declarations/src/waitFor.d.ts +1 -1
  27. package/dist/xstate.cjs.js +802 -4
  28. package/dist/xstate.development.cjs.js +808 -0
  29. package/dist/xstate.development.esm.js +770 -0
  30. package/dist/xstate.esm.js +543 -662
  31. package/dist/xstate.umd.min.js +1 -1
  32. package/dist/xstate.umd.min.js.map +1 -1
  33. package/guards/dist/xstate-guards.cjs.js +13 -5
  34. package/guards/dist/{xstate-guards.cjs.prod.js → xstate-guards.development.cjs.js} +2 -2
  35. package/guards/dist/xstate-guards.development.esm.js +2 -0
  36. package/guards/dist/xstate-guards.esm.js +2 -2
  37. package/guards/dist/xstate-guards.umd.min.js +1 -1
  38. package/guards/dist/xstate-guards.umd.min.js.map +1 -1
  39. package/package.json +52 -1
  40. package/actions/dist/xstate-actions.cjs.prod.js +0 -31
  41. package/actors/dist/xstate-actors.cjs.prod.js +0 -22
  42. package/dev/dist/xstate-dev.cjs.dev.js +0 -11
  43. package/dev/dist/xstate-dev.cjs.prod.js +0 -11
  44. package/dist/actions-109712d3.cjs.dev.js +0 -4357
  45. package/dist/actions-67f1d04e.esm.js +0 -4270
  46. package/dist/actions-d0262a43.cjs.prod.js +0 -4333
  47. package/dist/declarations/actions/dynamicAction.d.ts +0 -5
  48. package/dist/declarations/src/Mailbox.d.ts +0 -12
  49. package/dist/declarations/src/actions/invoke.d.ts +0 -3
  50. package/dist/declarations/src/environment.d.ts +0 -1
  51. package/dist/declarations/src/memo.d.ts +0 -2
  52. package/dist/declarations/src/spawn.d.ts +0 -2
  53. package/dist/declarations/src/system.d.ts +0 -2
  54. package/dist/index-ebaab3c9.cjs.dev.js +0 -52
  55. package/dist/xstate.cjs.dev.js +0 -933
  56. package/dist/xstate.cjs.prod.js +0 -930
  57. package/guards/dist/xstate-guards.cjs.dev.js +0 -15
@@ -0,0 +1,3374 @@
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
+ * Starts the interpreter from the initial state
1185
+ */
1186
+ start() {
1187
+ if (this.status === ActorStatus.Running) {
1188
+ // Do not restart the service if it is already started
1189
+ return this;
1190
+ }
1191
+ this.system._register(this.sessionId, this);
1192
+ if (this._systemId) {
1193
+ this.system._set(this._systemId, this);
1194
+ }
1195
+ this.status = ActorStatus.Running;
1196
+ if (this.behavior.start) {
1197
+ this.behavior.start(this._state, this._actorContext);
1198
+ }
1199
+
1200
+ // TODO: this notifies all subscribers but usually this is redundant
1201
+ // there is no real change happening here
1202
+ // we need to rethink if this needs to be refactored
1203
+ this.update(this._state);
1204
+ if (this.options.devTools) {
1205
+ this.attachDevTools();
1206
+ }
1207
+ this.mailbox.start();
1208
+ return this;
1209
+ }
1210
+ _process(event) {
1211
+ try {
1212
+ const nextState = this.behavior.transition(this._state, event, this._actorContext);
1213
+ this.update(nextState);
1214
+ if (event.type === stopSignalType) {
1215
+ this._stopProcedure();
1216
+ this._complete();
1217
+ }
1218
+ } catch (err) {
1219
+ // TODO: properly handle errors
1220
+ if (this.observers.size > 0) {
1221
+ this.observers.forEach(observer => {
1222
+ observer.error?.(err);
1223
+ });
1224
+ this.stop();
1225
+ } else {
1226
+ throw err;
1227
+ }
1228
+ }
1229
+ }
1230
+ _stop() {
1231
+ if (this.status === ActorStatus.Stopped) {
1232
+ return this;
1233
+ }
1234
+ this.mailbox.clear();
1235
+ if (this.status === ActorStatus.NotStarted) {
1236
+ this.status = ActorStatus.Stopped;
1237
+ return this;
1238
+ }
1239
+ this.mailbox.enqueue({
1240
+ type: stopSignalType
1241
+ });
1242
+ return this;
1243
+ }
1244
+
1245
+ /**
1246
+ * Stops the interpreter and unsubscribe all listeners.
1247
+ */
1248
+ stop() {
1249
+ if (this._parent) {
1250
+ throw new Error('A non-root actor cannot be stopped directly.');
1251
+ }
1252
+ return this._stop();
1253
+ }
1254
+ _complete() {
1255
+ for (const observer of this.observers) {
1256
+ observer.complete?.();
1257
+ }
1258
+ this.observers.clear();
1259
+ }
1260
+ _error(data) {
1261
+ for (const observer of this.observers) {
1262
+ observer.error?.(data);
1263
+ }
1264
+ this.observers.clear();
1265
+ }
1266
+ _stopProcedure() {
1267
+ if (this.status !== ActorStatus.Running) {
1268
+ // Interpreter already stopped; do nothing
1269
+ return this;
1270
+ }
1271
+
1272
+ // Cancel all delayed events
1273
+ for (const key of Object.keys(this.delayedEventsMap)) {
1274
+ this.clock.clearTimeout(this.delayedEventsMap[key]);
1275
+ }
1276
+
1277
+ // TODO: mailbox.reset
1278
+ this.mailbox.clear();
1279
+ // TODO: after `stop` we must prepare ourselves for receiving events again
1280
+ // events sent *after* stop signal must be queued
1281
+ // it seems like this should be the common behavior for all of our consumers
1282
+ // so perhaps this should be unified somehow for all of them
1283
+ this.mailbox = new Mailbox(this._process.bind(this));
1284
+ this.status = ActorStatus.Stopped;
1285
+ this.system._unregister(this);
1286
+ return this;
1287
+ }
1288
+
1289
+ /**
1290
+ * Sends an event to the running interpreter to trigger a transition.
1291
+ *
1292
+ * @param event The event to send
1293
+ */
1294
+ send(event) {
1295
+ if (typeof event === 'string') {
1296
+ throw new Error(`Only event objects may be sent to actors; use .send({ type: "${event}" }) instead`);
1297
+ }
1298
+ if (this.status === ActorStatus.Stopped) {
1299
+ return;
1300
+ }
1301
+ if (this.status !== ActorStatus.Running && !this.options.deferEvents) {
1302
+ throw new Error(`Event "${event.type}" was sent to uninitialized actor "${this.id
1303
+ // tslint:disable-next-line:max-line-length
1304
+ }". Make sure .start() is called for this actor, or set { deferEvents: true } in the actor options.\nEvent: ${JSON.stringify(event)}`);
1305
+ }
1306
+ this.mailbox.enqueue(event);
1307
+ }
1308
+
1309
+ // TODO: make private (and figure out a way to do this within the machine)
1310
+ delaySend(sendAction) {
1311
+ this.delayedEventsMap[sendAction.params.id] = this.clock.setTimeout(() => {
1312
+ if ('to' in sendAction.params && sendAction.params.to) {
1313
+ sendAction.params.to.send(sendAction.params.event);
1314
+ } else {
1315
+ this.send(sendAction.params.event);
1316
+ }
1317
+ }, sendAction.params.delay);
1318
+ }
1319
+
1320
+ // TODO: make private (and figure out a way to do this within the machine)
1321
+ cancel(sendId) {
1322
+ this.clock.clearTimeout(this.delayedEventsMap[sendId]);
1323
+ delete this.delayedEventsMap[sendId];
1324
+ }
1325
+ attachDevTools() {
1326
+ const {
1327
+ devTools
1328
+ } = this.options;
1329
+ if (devTools) {
1330
+ const resolvedDevToolsAdapter = typeof devTools === 'function' ? devTools : dev_dist_xstateDev.devToolsAdapter;
1331
+ resolvedDevToolsAdapter(this);
1332
+ }
1333
+ }
1334
+ toJSON() {
1335
+ return {
1336
+ id: this.id
1337
+ };
1338
+ }
1339
+ getPersistedState() {
1340
+ return this.behavior.getPersistedState?.(this._state);
1341
+ }
1342
+ [symbolObservable]() {
1343
+ return this;
1344
+ }
1345
+ getSnapshot() {
1346
+ return this.behavior.getSnapshot ? this.behavior.getSnapshot(this._state) : this._state;
1347
+ }
1348
+ }
1349
+
1350
+ /**
1351
+ * Creates a new Interpreter instance for the given machine with the provided options, if any.
1352
+ *
1353
+ * @param machine The machine to interpret
1354
+ * @param options Interpreter options
1355
+ */
1356
+
1357
+ function interpret(behavior, options) {
1358
+ const interpreter = new Interpreter(behavior, options);
1359
+ return interpreter;
1360
+ }
1361
+
1362
+ /**
1363
+ * Stops an actor.
1364
+ *
1365
+ * @param actorRef The actor to stop.
1366
+ */
1367
+
1368
+ function stop(actorRef) {
1369
+ const actor = actorRef;
1370
+ return createDynamicAction({
1371
+ type: stop$1,
1372
+ params: {
1373
+ actor
1374
+ }
1375
+ }, (event, {
1376
+ state
1377
+ }) => {
1378
+ const actorRefOrString = isFunction(actor) ? actor({
1379
+ context: state.context,
1380
+ event
1381
+ }) : actor;
1382
+ const actorRef = typeof actorRefOrString === 'string' ? state.children[actorRefOrString] : actorRefOrString;
1383
+ return [state, {
1384
+ type: 'xstate.stop',
1385
+ params: {
1386
+ actor: actorRef
1387
+ },
1388
+ execute: actorCtx => {
1389
+ if (!actorRef) {
1390
+ return;
1391
+ }
1392
+ if (actorRef.status !== ActorStatus.Running) {
1393
+ actorCtx.stopChild(actorRef);
1394
+ return;
1395
+ }
1396
+ actorCtx.defer(() => {
1397
+ actorCtx.stopChild(actorRef);
1398
+ });
1399
+ }
1400
+ }];
1401
+ });
1402
+ }
1403
+
1404
+ const defaultLogExpr = ({
1405
+ context,
1406
+ event
1407
+ }) => ({
1408
+ context,
1409
+ event
1410
+ });
1411
+
1412
+ /**
1413
+ *
1414
+ * @param expr The expression function to evaluate which will be logged.
1415
+ * Takes in 2 arguments:
1416
+ * - `ctx` - the current state context
1417
+ * - `event` - the event that caused this action to be executed.
1418
+ * @param label The label to give to the logged expression.
1419
+ */
1420
+
1421
+ function log(expr = defaultLogExpr, label) {
1422
+ return createDynamicAction({
1423
+ type: log$1,
1424
+ params: {
1425
+ label,
1426
+ expr
1427
+ }
1428
+ }, (event, {
1429
+ state,
1430
+ actorContext
1431
+ }) => {
1432
+ const resolvedValue = typeof expr === 'function' ? expr({
1433
+ context: state.context,
1434
+ event,
1435
+ self: actorContext?.self ?? {},
1436
+ system: actorContext?.system
1437
+ }) : expr;
1438
+ return [state, {
1439
+ type: 'xstate.log',
1440
+ params: {
1441
+ label,
1442
+ value: resolvedValue
1443
+ },
1444
+ execute: actorCtx => {
1445
+ if (label) {
1446
+ actorCtx.logger?.(label, resolvedValue);
1447
+ } else {
1448
+ actorCtx.logger?.(resolvedValue);
1449
+ }
1450
+ }
1451
+ }];
1452
+ });
1453
+ }
1454
+
1455
+ /**
1456
+ * Cancels an in-flight `send(...)` action. A canceled sent action will not
1457
+ * be executed, nor will its event be sent, unless it has already been sent
1458
+ * (e.g., if `cancel(...)` is called after the `send(...)` action's `delay`).
1459
+ *
1460
+ * @param sendId The `id` of the `send(...)` action to cancel.
1461
+ */
1462
+
1463
+ function cancel(sendId) {
1464
+ return createDynamicAction({
1465
+ type: cancel$1,
1466
+ params: {
1467
+ sendId
1468
+ }
1469
+ }, (event, {
1470
+ state,
1471
+ actorContext
1472
+ }) => {
1473
+ const resolvedSendId = isFunction(sendId) ? sendId({
1474
+ context: state.context,
1475
+ event,
1476
+ self: actorContext?.self ?? {},
1477
+ system: actorContext?.system
1478
+ }) : sendId;
1479
+ return [state, {
1480
+ type: 'xstate.cancel',
1481
+ params: {
1482
+ sendId: resolvedSendId
1483
+ },
1484
+ execute: actorCtx => {
1485
+ const interpreter = actorCtx.self;
1486
+ interpreter.cancel(resolvedSendId);
1487
+ }
1488
+ }];
1489
+ });
1490
+ }
1491
+
1492
+ const cache = new WeakMap();
1493
+ function memo(object, key, fn) {
1494
+ let memoizedData = cache.get(object);
1495
+ if (!memoizedData) {
1496
+ memoizedData = {
1497
+ [key]: fn()
1498
+ };
1499
+ cache.set(object, memoizedData);
1500
+ } else if (!(key in memoizedData)) {
1501
+ memoizedData[key] = fn();
1502
+ }
1503
+ return memoizedData[key];
1504
+ }
1505
+
1506
+ function stateIn(stateValue) {
1507
+ return {
1508
+ type: 'xstate.guard:in',
1509
+ params: {
1510
+ stateValue
1511
+ },
1512
+ predicate: ({
1513
+ state
1514
+ }) => {
1515
+ if (isString(stateValue) && isStateId(stateValue)) {
1516
+ return state.configuration.some(sn => sn.id === stateValue.slice(1));
1517
+ }
1518
+ return state.matches(stateValue);
1519
+ }
1520
+ };
1521
+ }
1522
+ function not(guard) {
1523
+ return {
1524
+ type: 'xstate.boolean',
1525
+ params: {
1526
+ op: 'not'
1527
+ },
1528
+ children: [toGuardDefinition(guard)],
1529
+ predicate: ({
1530
+ evaluate,
1531
+ guard,
1532
+ context,
1533
+ event,
1534
+ state
1535
+ }) => {
1536
+ return !evaluate(guard.children[0], context, event, state);
1537
+ }
1538
+ };
1539
+ }
1540
+ function and(guards) {
1541
+ return {
1542
+ type: 'xstate.boolean',
1543
+ params: {
1544
+ op: 'and'
1545
+ },
1546
+ children: guards.map(guard => toGuardDefinition(guard)),
1547
+ predicate: ({
1548
+ evaluate,
1549
+ guard,
1550
+ context,
1551
+ event,
1552
+ state
1553
+ }) => {
1554
+ return guard.children.every(childGuard => {
1555
+ return evaluate(childGuard, context, event, state);
1556
+ });
1557
+ }
1558
+ };
1559
+ }
1560
+ function or(guards) {
1561
+ return {
1562
+ type: 'xstate.boolean',
1563
+ params: {
1564
+ op: 'or'
1565
+ },
1566
+ children: guards.map(guard => toGuardDefinition(guard)),
1567
+ predicate: ({
1568
+ evaluate,
1569
+ guard,
1570
+ context,
1571
+ event,
1572
+ state
1573
+ }) => {
1574
+ return guard.children.some(childGuard => {
1575
+ return evaluate(childGuard, context, event, state);
1576
+ });
1577
+ }
1578
+ };
1579
+ }
1580
+ function evaluateGuard(guard, context, event, state) {
1581
+ const {
1582
+ machine
1583
+ } = state;
1584
+ const predicate = machine?.options?.guards?.[guard.type] ?? guard.predicate;
1585
+ if (!predicate) {
1586
+ throw new Error(`Guard '${guard.type}' is not implemented.'.`);
1587
+ }
1588
+ return predicate({
1589
+ context,
1590
+ event,
1591
+ state,
1592
+ guard,
1593
+ evaluate: evaluateGuard
1594
+ });
1595
+ }
1596
+ function toGuardDefinition(guardConfig, getPredicate) {
1597
+ if (isString(guardConfig)) {
1598
+ return {
1599
+ type: guardConfig,
1600
+ predicate: getPredicate?.(guardConfig) || undefined,
1601
+ params: {
1602
+ type: guardConfig
1603
+ }
1604
+ };
1605
+ }
1606
+ if (isFunction(guardConfig)) {
1607
+ return {
1608
+ type: guardConfig.name,
1609
+ predicate: guardConfig,
1610
+ params: {
1611
+ type: guardConfig.name,
1612
+ name: guardConfig.name
1613
+ }
1614
+ };
1615
+ }
1616
+ return {
1617
+ type: guardConfig.type,
1618
+ params: guardConfig.params || guardConfig,
1619
+ children: guardConfig.children?.map(childGuard => toGuardDefinition(childGuard, getPredicate)),
1620
+ predicate: getPredicate?.(guardConfig.type) || guardConfig.predicate
1621
+ };
1622
+ }
1623
+
1624
+ function getOutput(configuration, context, event) {
1625
+ const machine = configuration[0].machine;
1626
+ const finalChildStateNode = configuration.find(stateNode => stateNode.type === 'final' && stateNode.parent === machine.root);
1627
+ return finalChildStateNode && finalChildStateNode.output ? mapContext(finalChildStateNode.output, context, event) : undefined;
1628
+ }
1629
+ const isAtomicStateNode = stateNode => stateNode.type === 'atomic' || stateNode.type === 'final';
1630
+ function getChildren(stateNode) {
1631
+ return Object.values(stateNode.states).filter(sn => sn.type !== 'history');
1632
+ }
1633
+ function getProperAncestors(stateNode, toStateNode) {
1634
+ const ancestors = [];
1635
+
1636
+ // add all ancestors
1637
+ let m = stateNode.parent;
1638
+ while (m && m !== toStateNode) {
1639
+ ancestors.push(m);
1640
+ m = m.parent;
1641
+ }
1642
+ return ancestors;
1643
+ }
1644
+ function getConfiguration(stateNodes) {
1645
+ const configuration = new Set(stateNodes);
1646
+ const configurationSet = new Set(stateNodes);
1647
+ const adjList = getAdjList(configurationSet);
1648
+
1649
+ // add descendants
1650
+ for (const s of configuration) {
1651
+ // if previously active, add existing child nodes
1652
+ if (s.type === 'compound' && (!adjList.get(s) || !adjList.get(s).length)) {
1653
+ getInitialStateNodes(s).forEach(sn => configurationSet.add(sn));
1654
+ } else {
1655
+ if (s.type === 'parallel') {
1656
+ for (const child of getChildren(s)) {
1657
+ if (child.type === 'history') {
1658
+ continue;
1659
+ }
1660
+ if (!configurationSet.has(child)) {
1661
+ for (const initialStateNode of getInitialStateNodes(child)) {
1662
+ configurationSet.add(initialStateNode);
1663
+ }
1664
+ }
1665
+ }
1666
+ }
1667
+ }
1668
+ }
1669
+
1670
+ // add all ancestors
1671
+ for (const s of configurationSet) {
1672
+ let m = s.parent;
1673
+ while (m) {
1674
+ configurationSet.add(m);
1675
+ m = m.parent;
1676
+ }
1677
+ }
1678
+ return configurationSet;
1679
+ }
1680
+ function getValueFromAdj(baseNode, adjList) {
1681
+ const childStateNodes = adjList.get(baseNode);
1682
+ if (!childStateNodes) {
1683
+ return {}; // todo: fix?
1684
+ }
1685
+
1686
+ if (baseNode.type === 'compound') {
1687
+ const childStateNode = childStateNodes[0];
1688
+ if (childStateNode) {
1689
+ if (isAtomicStateNode(childStateNode)) {
1690
+ return childStateNode.key;
1691
+ }
1692
+ } else {
1693
+ return {};
1694
+ }
1695
+ }
1696
+ const stateValue = {};
1697
+ for (const childStateNode of childStateNodes) {
1698
+ stateValue[childStateNode.key] = getValueFromAdj(childStateNode, adjList);
1699
+ }
1700
+ return stateValue;
1701
+ }
1702
+ function getAdjList(configuration) {
1703
+ const adjList = new Map();
1704
+ for (const s of configuration) {
1705
+ if (!adjList.has(s)) {
1706
+ adjList.set(s, []);
1707
+ }
1708
+ if (s.parent) {
1709
+ if (!adjList.has(s.parent)) {
1710
+ adjList.set(s.parent, []);
1711
+ }
1712
+ adjList.get(s.parent).push(s);
1713
+ }
1714
+ }
1715
+ return adjList;
1716
+ }
1717
+ function getStateValue(rootNode, configuration) {
1718
+ const config = getConfiguration(configuration);
1719
+ return getValueFromAdj(rootNode, getAdjList(config));
1720
+ }
1721
+ function isInFinalState(configuration, stateNode = configuration[0].machine.root) {
1722
+ if (stateNode.type === 'compound') {
1723
+ return getChildren(stateNode).some(s => s.type === 'final' && configuration.includes(s));
1724
+ }
1725
+ if (stateNode.type === 'parallel') {
1726
+ return getChildren(stateNode).every(sn => isInFinalState(configuration, sn));
1727
+ }
1728
+ return false;
1729
+ }
1730
+ const isStateId = str => str[0] === STATE_IDENTIFIER;
1731
+ function getCandidates(stateNode, receivedEventType) {
1732
+ const candidates = stateNode.transitions.filter(transition => {
1733
+ const {
1734
+ eventType
1735
+ } = transition;
1736
+ // First, check the trivial case: event names are exactly equal
1737
+ if (eventType === receivedEventType) {
1738
+ return true;
1739
+ }
1740
+
1741
+ // Then, check if transition is a wildcard transition,
1742
+ // which matches any non-transient events
1743
+ if (eventType === WILDCARD) {
1744
+ return true;
1745
+ }
1746
+ if (!eventType.endsWith('.*')) {
1747
+ return false;
1748
+ }
1749
+ const partialEventTokens = eventType.split('.');
1750
+ const eventTokens = receivedEventType.split('.');
1751
+ for (let tokenIndex = 0; tokenIndex < partialEventTokens.length; tokenIndex++) {
1752
+ const partialEventToken = partialEventTokens[tokenIndex];
1753
+ const eventToken = eventTokens[tokenIndex];
1754
+ if (partialEventToken === '*') {
1755
+ const isLastToken = tokenIndex === partialEventTokens.length - 1;
1756
+ return isLastToken;
1757
+ }
1758
+ if (partialEventToken !== eventToken) {
1759
+ return false;
1760
+ }
1761
+ }
1762
+ return true;
1763
+ });
1764
+ return candidates;
1765
+ }
1766
+
1767
+ /**
1768
+ * All delayed transitions from the config.
1769
+ */
1770
+ function getDelayedTransitions(stateNode) {
1771
+ const afterConfig = stateNode.config.after;
1772
+ if (!afterConfig) {
1773
+ return [];
1774
+ }
1775
+ const mutateEntryExit = (delay, i) => {
1776
+ const delayRef = isFunction(delay) ? `${stateNode.id}:delay[${i}]` : delay;
1777
+ const eventType = after(delayRef, stateNode.id);
1778
+ stateNode.entry.push(raise({
1779
+ type: eventType
1780
+ }, {
1781
+ delay
1782
+ }));
1783
+ stateNode.exit.push(cancel(eventType));
1784
+ return eventType;
1785
+ };
1786
+ const delayedTransitions = isArray(afterConfig) ? afterConfig.map((transition, i) => {
1787
+ const eventType = mutateEntryExit(transition.delay, i);
1788
+ return {
1789
+ ...transition,
1790
+ event: eventType
1791
+ };
1792
+ }) : Object.keys(afterConfig).flatMap((delay, i) => {
1793
+ const configTransition = afterConfig[delay];
1794
+ const resolvedTransition = isString(configTransition) ? {
1795
+ target: configTransition
1796
+ } : configTransition;
1797
+ const resolvedDelay = !isNaN(+delay) ? +delay : delay;
1798
+ const eventType = mutateEntryExit(resolvedDelay, i);
1799
+ return toArray(resolvedTransition).map(transition => ({
1800
+ ...transition,
1801
+ event: eventType,
1802
+ delay: resolvedDelay
1803
+ }));
1804
+ });
1805
+ return delayedTransitions.map(delayedTransition => {
1806
+ const {
1807
+ delay
1808
+ } = delayedTransition;
1809
+ return {
1810
+ ...formatTransition(stateNode, delayedTransition),
1811
+ delay
1812
+ };
1813
+ });
1814
+ }
1815
+ function formatTransition(stateNode, transitionConfig) {
1816
+ const normalizedTarget = normalizeTarget(transitionConfig.target);
1817
+ const reenter = transitionConfig.reenter ?? false;
1818
+ const {
1819
+ guards
1820
+ } = stateNode.machine.options;
1821
+ const target = resolveTarget(stateNode, normalizedTarget);
1822
+ const transition = {
1823
+ ...transitionConfig,
1824
+ actions: toActionObjects(toArray(transitionConfig.actions)),
1825
+ guard: transitionConfig.guard ? toGuardDefinition(transitionConfig.guard, guardType => guards[guardType]) : undefined,
1826
+ target,
1827
+ source: stateNode,
1828
+ reenter,
1829
+ eventType: transitionConfig.event,
1830
+ toJSON: () => ({
1831
+ ...transition,
1832
+ source: `#${stateNode.id}`,
1833
+ target: target ? target.map(t => `#${t.id}`) : undefined
1834
+ })
1835
+ };
1836
+ return transition;
1837
+ }
1838
+ function formatTransitions(stateNode) {
1839
+ const transitionConfigs = [];
1840
+ if (Array.isArray(stateNode.config.on)) {
1841
+ transitionConfigs.push(...stateNode.config.on);
1842
+ } else if (stateNode.config.on) {
1843
+ const {
1844
+ [WILDCARD]: wildcardConfigs = [],
1845
+ ...namedTransitionConfigs
1846
+ } = stateNode.config.on;
1847
+ for (const eventType of Object.keys(namedTransitionConfigs)) {
1848
+ if (eventType === NULL_EVENT) {
1849
+ throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');
1850
+ }
1851
+ const eventTransitionConfigs = toTransitionConfigArray(eventType, namedTransitionConfigs[eventType]);
1852
+ transitionConfigs.push(...eventTransitionConfigs);
1853
+ // TODO: add dev-mode validation for unreachable transitions
1854
+ }
1855
+
1856
+ transitionConfigs.push(...toTransitionConfigArray(WILDCARD, wildcardConfigs));
1857
+ }
1858
+ const doneConfig = stateNode.config.onDone ? toTransitionConfigArray(String(done(stateNode.id)), stateNode.config.onDone) : [];
1859
+ const invokeConfig = stateNode.invoke.flatMap(invokeDef => {
1860
+ const settleTransitions = [];
1861
+ if (invokeDef.onDone) {
1862
+ settleTransitions.push(...toTransitionConfigArray(`done.invoke.${invokeDef.id}`, invokeDef.onDone));
1863
+ }
1864
+ if (invokeDef.onError) {
1865
+ settleTransitions.push(...toTransitionConfigArray(`error.platform.${invokeDef.id}`, invokeDef.onError));
1866
+ }
1867
+ if (invokeDef.onSnapshot) {
1868
+ settleTransitions.push(...toTransitionConfigArray(`xstate.snapshot.${invokeDef.id}`, invokeDef.onSnapshot));
1869
+ }
1870
+ return settleTransitions;
1871
+ });
1872
+ const delayedTransitions = stateNode.after;
1873
+ const formattedTransitions = [...doneConfig, ...invokeConfig, ...transitionConfigs].flatMap(transitionConfig => toArray(transitionConfig).map(transition => formatTransition(stateNode, transition)));
1874
+ for (const delayedTransition of delayedTransitions) {
1875
+ formattedTransitions.push(delayedTransition);
1876
+ }
1877
+ return formattedTransitions;
1878
+ }
1879
+ function formatInitialTransition(stateNode, _target) {
1880
+ if (isString(_target) || isArray(_target)) {
1881
+ const targets = toArray(_target).map(t => {
1882
+ // Resolve state string keys (which represent children)
1883
+ // to their state node
1884
+ const descStateNode = isString(t) ? isStateId(t) ? stateNode.machine.getStateNodeById(t) : stateNode.states[t] : t;
1885
+ if (!descStateNode) {
1886
+ throw new Error(`Initial state node "${t}" not found on parent state node #${stateNode.id}`);
1887
+ }
1888
+ if (!isDescendant(descStateNode, stateNode)) {
1889
+ throw new Error(`Invalid initial target: state node #${descStateNode.id} is not a descendant of #${stateNode.id}`);
1890
+ }
1891
+ return descStateNode;
1892
+ });
1893
+ const resolvedTarget = resolveTarget(stateNode, targets);
1894
+ const transition = {
1895
+ source: stateNode,
1896
+ actions: [],
1897
+ eventType: null,
1898
+ reenter: false,
1899
+ target: resolvedTarget,
1900
+ toJSON: () => ({
1901
+ ...transition,
1902
+ source: `#${stateNode.id}`,
1903
+ target: resolvedTarget ? resolvedTarget.map(t => `#${t.id}`) : undefined
1904
+ })
1905
+ };
1906
+ return transition;
1907
+ }
1908
+ return formatTransition(stateNode, {
1909
+ target: toArray(_target.target).map(t => {
1910
+ if (isString(t)) {
1911
+ return isStateId(t) ? t : `${stateNode.machine.delimiter}${t}`;
1912
+ }
1913
+ return t;
1914
+ }),
1915
+ actions: _target.actions,
1916
+ event: null
1917
+ });
1918
+ }
1919
+ function resolveTarget(stateNode, targets) {
1920
+ if (targets === undefined) {
1921
+ // an undefined target signals that the state node should not transition from that state when receiving that event
1922
+ return undefined;
1923
+ }
1924
+ return targets.map(target => {
1925
+ if (!isString(target)) {
1926
+ return target;
1927
+ }
1928
+ if (isStateId(target)) {
1929
+ return stateNode.machine.getStateNodeById(target);
1930
+ }
1931
+ const isInternalTarget = target[0] === stateNode.machine.delimiter;
1932
+ // If internal target is defined on machine,
1933
+ // do not include machine key on target
1934
+ if (isInternalTarget && !stateNode.parent) {
1935
+ return getStateNodeByPath(stateNode, target.slice(1));
1936
+ }
1937
+ const resolvedTarget = isInternalTarget ? stateNode.key + target : target;
1938
+ if (stateNode.parent) {
1939
+ try {
1940
+ const targetStateNode = getStateNodeByPath(stateNode.parent, resolvedTarget);
1941
+ return targetStateNode;
1942
+ } catch (err) {
1943
+ throw new Error(`Invalid transition definition for state node '${stateNode.id}':\n${err.message}`);
1944
+ }
1945
+ } else {
1946
+ throw new Error(`Invalid target: "${target}" is not a valid target from the root node. Did you mean ".${target}"?`);
1947
+ }
1948
+ });
1949
+ }
1950
+ function resolveHistoryTarget(stateNode) {
1951
+ const normalizedTarget = normalizeTarget(stateNode.target);
1952
+ if (!normalizedTarget) {
1953
+ return stateNode.parent.initial.target;
1954
+ }
1955
+ return normalizedTarget.map(t => typeof t === 'string' ? getStateNodeByPath(stateNode.parent, t) : t);
1956
+ }
1957
+ function isHistoryNode(stateNode) {
1958
+ return stateNode.type === 'history';
1959
+ }
1960
+ function getInitialStateNodes(stateNode) {
1961
+ const set = new Set();
1962
+ function iter(descStateNode) {
1963
+ if (set.has(descStateNode)) {
1964
+ return;
1965
+ }
1966
+ set.add(descStateNode);
1967
+ if (descStateNode.type === 'compound') {
1968
+ for (const targetStateNode of descStateNode.initial.target) {
1969
+ for (const a of getProperAncestors(targetStateNode, stateNode)) {
1970
+ set.add(a);
1971
+ }
1972
+ iter(targetStateNode);
1973
+ }
1974
+ } else if (descStateNode.type === 'parallel') {
1975
+ for (const child of getChildren(descStateNode)) {
1976
+ iter(child);
1977
+ }
1978
+ }
1979
+ }
1980
+ iter(stateNode);
1981
+ return [...set];
1982
+ }
1983
+ /**
1984
+ * Returns the child state node from its relative `stateKey`, or throws.
1985
+ */
1986
+ function getStateNode(stateNode, stateKey) {
1987
+ if (isStateId(stateKey)) {
1988
+ return stateNode.machine.getStateNodeById(stateKey);
1989
+ }
1990
+ if (!stateNode.states) {
1991
+ throw new Error(`Unable to retrieve child state '${stateKey}' from '${stateNode.id}'; no child states exist.`);
1992
+ }
1993
+ const result = stateNode.states[stateKey];
1994
+ if (!result) {
1995
+ throw new Error(`Child state '${stateKey}' does not exist on '${stateNode.id}'`);
1996
+ }
1997
+ return result;
1998
+ }
1999
+
2000
+ /**
2001
+ * Returns the relative state node from the given `statePath`, or throws.
2002
+ *
2003
+ * @param statePath The string or string array relative path to the state node.
2004
+ */
2005
+ function getStateNodeByPath(stateNode, statePath) {
2006
+ if (typeof statePath === 'string' && isStateId(statePath)) {
2007
+ try {
2008
+ return stateNode.machine.getStateNodeById(statePath);
2009
+ } catch (e) {
2010
+ // try individual paths
2011
+ // throw e;
2012
+ }
2013
+ }
2014
+ const arrayStatePath = toStatePath(statePath, stateNode.machine.delimiter).slice();
2015
+ let currentStateNode = stateNode;
2016
+ while (arrayStatePath.length) {
2017
+ const key = arrayStatePath.shift();
2018
+ if (!key.length) {
2019
+ break;
2020
+ }
2021
+ currentStateNode = getStateNode(currentStateNode, key);
2022
+ }
2023
+ return currentStateNode;
2024
+ }
2025
+
2026
+ /**
2027
+ * Returns the state nodes represented by the current state value.
2028
+ *
2029
+ * @param state The state value or State instance
2030
+ */
2031
+ function getStateNodes(stateNode, state) {
2032
+ const stateValue = state instanceof State ? state.value : toStateValue(state, stateNode.machine.delimiter);
2033
+ if (isString(stateValue)) {
2034
+ return [stateNode, stateNode.states[stateValue]];
2035
+ }
2036
+ const childStateKeys = Object.keys(stateValue);
2037
+ const childStateNodes = childStateKeys.map(subStateKey => getStateNode(stateNode, subStateKey)).filter(Boolean);
2038
+ return [stateNode.machine.root, stateNode].concat(childStateNodes, childStateKeys.reduce((allSubStateNodes, subStateKey) => {
2039
+ const subStateNode = getStateNode(stateNode, subStateKey);
2040
+ if (!subStateNode) {
2041
+ return allSubStateNodes;
2042
+ }
2043
+ const subStateNodes = getStateNodes(subStateNode, stateValue[subStateKey]);
2044
+ return allSubStateNodes.concat(subStateNodes);
2045
+ }, []));
2046
+ }
2047
+ function transitionAtomicNode(stateNode, stateValue, state, event) {
2048
+ const childStateNode = getStateNode(stateNode, stateValue);
2049
+ const next = childStateNode.next(state, event);
2050
+ if (!next || !next.length) {
2051
+ return stateNode.next(state, event);
2052
+ }
2053
+ return next;
2054
+ }
2055
+ function transitionCompoundNode(stateNode, stateValue, state, event) {
2056
+ const subStateKeys = Object.keys(stateValue);
2057
+ const childStateNode = getStateNode(stateNode, subStateKeys[0]);
2058
+ const next = transitionNode(childStateNode, stateValue[subStateKeys[0]], state, event);
2059
+ if (!next || !next.length) {
2060
+ return stateNode.next(state, event);
2061
+ }
2062
+ return next;
2063
+ }
2064
+ function transitionParallelNode(stateNode, stateValue, state, event) {
2065
+ const allInnerTransitions = [];
2066
+ for (const subStateKey of Object.keys(stateValue)) {
2067
+ const subStateValue = stateValue[subStateKey];
2068
+ if (!subStateValue) {
2069
+ continue;
2070
+ }
2071
+ const subStateNode = getStateNode(stateNode, subStateKey);
2072
+ const innerTransitions = transitionNode(subStateNode, subStateValue, state, event);
2073
+ if (innerTransitions) {
2074
+ allInnerTransitions.push(...innerTransitions);
2075
+ }
2076
+ }
2077
+ if (!allInnerTransitions.length) {
2078
+ return stateNode.next(state, event);
2079
+ }
2080
+ return allInnerTransitions;
2081
+ }
2082
+ function transitionNode(stateNode, stateValue, state, event) {
2083
+ // leaf node
2084
+ if (isString(stateValue)) {
2085
+ return transitionAtomicNode(stateNode, stateValue, state, event);
2086
+ }
2087
+
2088
+ // compound node
2089
+ if (Object.keys(stateValue).length === 1) {
2090
+ return transitionCompoundNode(stateNode, stateValue, state, event);
2091
+ }
2092
+
2093
+ // parallel node
2094
+ return transitionParallelNode(stateNode, stateValue, state, event);
2095
+ }
2096
+ function getHistoryNodes(stateNode) {
2097
+ return Object.keys(stateNode.states).map(key => stateNode.states[key]).filter(sn => sn.type === 'history');
2098
+ }
2099
+ function isDescendant(childStateNode, parentStateNode) {
2100
+ let marker = childStateNode;
2101
+ while (marker.parent && marker.parent !== parentStateNode) {
2102
+ marker = marker.parent;
2103
+ }
2104
+ return marker.parent === parentStateNode;
2105
+ }
2106
+ function getPathFromRootToNode(stateNode) {
2107
+ const path = [];
2108
+ let marker = stateNode.parent;
2109
+ while (marker) {
2110
+ path.unshift(marker);
2111
+ marker = marker.parent;
2112
+ }
2113
+ return path;
2114
+ }
2115
+ function hasIntersection(s1, s2) {
2116
+ const set1 = new Set(s1);
2117
+ const set2 = new Set(s2);
2118
+ for (const item of set1) {
2119
+ if (set2.has(item)) {
2120
+ return true;
2121
+ }
2122
+ }
2123
+ for (const item of set2) {
2124
+ if (set1.has(item)) {
2125
+ return true;
2126
+ }
2127
+ }
2128
+ return false;
2129
+ }
2130
+ function removeConflictingTransitions(enabledTransitions, configuration, historyValue) {
2131
+ const filteredTransitions = new Set();
2132
+ for (const t1 of enabledTransitions) {
2133
+ let t1Preempted = false;
2134
+ const transitionsToRemove = new Set();
2135
+ for (const t2 of filteredTransitions) {
2136
+ if (hasIntersection(computeExitSet([t1], configuration, historyValue), computeExitSet([t2], configuration, historyValue))) {
2137
+ if (isDescendant(t1.source, t2.source)) {
2138
+ transitionsToRemove.add(t2);
2139
+ } else {
2140
+ t1Preempted = true;
2141
+ break;
2142
+ }
2143
+ }
2144
+ }
2145
+ if (!t1Preempted) {
2146
+ for (const t3 of transitionsToRemove) {
2147
+ filteredTransitions.delete(t3);
2148
+ }
2149
+ filteredTransitions.add(t1);
2150
+ }
2151
+ }
2152
+ return Array.from(filteredTransitions);
2153
+ }
2154
+ function findLCCA(stateNodes) {
2155
+ const [head] = stateNodes;
2156
+ let current = getPathFromRootToNode(head);
2157
+ let candidates = [];
2158
+ for (const stateNode of stateNodes) {
2159
+ const path = getPathFromRootToNode(stateNode);
2160
+ candidates = current.filter(sn => path.includes(sn));
2161
+ current = candidates;
2162
+ candidates = [];
2163
+ }
2164
+ return current[current.length - 1];
2165
+ }
2166
+ function getEffectiveTargetStates(transition, historyValue) {
2167
+ if (!transition.target) {
2168
+ return [];
2169
+ }
2170
+ const targets = new Set();
2171
+ for (const targetNode of transition.target) {
2172
+ if (isHistoryNode(targetNode)) {
2173
+ if (historyValue[targetNode.id]) {
2174
+ for (const node of historyValue[targetNode.id]) {
2175
+ targets.add(node);
2176
+ }
2177
+ } else {
2178
+ for (const node of getEffectiveTargetStates({
2179
+ target: resolveHistoryTarget(targetNode)
2180
+ }, historyValue)) {
2181
+ targets.add(node);
2182
+ }
2183
+ }
2184
+ } else {
2185
+ targets.add(targetNode);
2186
+ }
2187
+ }
2188
+ return [...targets];
2189
+ }
2190
+ function getTransitionDomain(transition, historyValue) {
2191
+ const targetStates = getEffectiveTargetStates(transition, historyValue);
2192
+ if (!targetStates) {
2193
+ return null;
2194
+ }
2195
+ if (!transition.reenter && transition.source.type !== 'parallel' && targetStates.every(targetStateNode => isDescendant(targetStateNode, transition.source))) {
2196
+ return transition.source;
2197
+ }
2198
+ const lcca = findLCCA(targetStates.concat(transition.source));
2199
+ return lcca;
2200
+ }
2201
+ function computeExitSet(transitions, configuration, historyValue) {
2202
+ const statesToExit = new Set();
2203
+ for (const t of transitions) {
2204
+ if (t.target?.length) {
2205
+ const domain = getTransitionDomain(t, historyValue);
2206
+ for (const stateNode of configuration) {
2207
+ if (isDescendant(stateNode, domain)) {
2208
+ statesToExit.add(stateNode);
2209
+ }
2210
+ }
2211
+ }
2212
+ }
2213
+ return [...statesToExit];
2214
+ }
2215
+
2216
+ /**
2217
+ * https://www.w3.org/TR/scxml/#microstepProcedure
2218
+ *
2219
+ * @private
2220
+ * @param transitions
2221
+ * @param currentState
2222
+ * @param mutConfiguration
2223
+ */
2224
+
2225
+ function microstep(transitions, currentState, actorCtx, event) {
2226
+ const {
2227
+ machine
2228
+ } = currentState;
2229
+ // Transition will "apply" if:
2230
+ // - the state node is the initial state (there is no current state)
2231
+ // - OR there are transitions
2232
+ const willTransition = currentState._initial || transitions.length > 0;
2233
+ const mutConfiguration = new Set(currentState.configuration);
2234
+ if (!currentState._initial && !willTransition) {
2235
+ const inertState = cloneState(currentState, {
2236
+ event,
2237
+ actions: [],
2238
+ transitions: []
2239
+ });
2240
+ inertState.changed = false;
2241
+ return inertState;
2242
+ }
2243
+ const microstate = microstepProcedure(currentState._initial ? [{
2244
+ target: [...currentState.configuration].filter(isAtomicStateNode),
2245
+ source: machine.root,
2246
+ reenter: true,
2247
+ actions: [],
2248
+ eventType: null,
2249
+ toJSON: null // TODO: fix
2250
+ }] : transitions, currentState, mutConfiguration, event, actorCtx);
2251
+ const {
2252
+ context,
2253
+ actions: nonRaisedActions
2254
+ } = microstate;
2255
+ const children = setChildren(currentState, nonRaisedActions);
2256
+ const nextState = cloneState(microstate, {
2257
+ value: {},
2258
+ // TODO: make optional
2259
+ transitions,
2260
+ children
2261
+ });
2262
+ nextState.changed = currentState._initial ? undefined : !stateValuesEqual(nextState.value, currentState.value) || nextState.actions.length > 0 || context !== currentState.context;
2263
+ return nextState;
2264
+ }
2265
+ function setChildren(currentState, nonRaisedActions) {
2266
+ const children = {
2267
+ ...currentState.children
2268
+ };
2269
+ for (const action of nonRaisedActions) {
2270
+ if (action.type === invoke$1 && action.params.ref) {
2271
+ const ref = action.params.ref;
2272
+ if (ref) {
2273
+ children[ref.id] = ref;
2274
+ }
2275
+ } else if (action.type === stop$1) {
2276
+ const ref = action.params.actor;
2277
+ if (ref) {
2278
+ delete children[ref.id];
2279
+ }
2280
+ }
2281
+ }
2282
+ return children;
2283
+ }
2284
+ function microstepProcedure(transitions, currentState, mutConfiguration, event, actorCtx) {
2285
+ const actions = [];
2286
+ const historyValue = {
2287
+ ...currentState.historyValue
2288
+ };
2289
+ const filteredTransitions = removeConflictingTransitions(transitions, mutConfiguration, historyValue);
2290
+ const internalQueue = [...currentState._internalQueue];
2291
+
2292
+ // Exit states
2293
+ if (!currentState._initial) {
2294
+ exitStates(filteredTransitions, mutConfiguration, historyValue, actions);
2295
+ }
2296
+
2297
+ // Execute transition content
2298
+ actions.push(...filteredTransitions.flatMap(t => t.actions));
2299
+
2300
+ // Enter states
2301
+ enterStates(filteredTransitions, mutConfiguration, actions, internalQueue, currentState, historyValue);
2302
+ const nextConfiguration = [...mutConfiguration];
2303
+ const done = isInFinalState(nextConfiguration);
2304
+ if (done) {
2305
+ const finalActions = nextConfiguration.sort((a, b) => b.order - a.order).flatMap(state => state.exit);
2306
+ actions.push(...finalActions);
2307
+ }
2308
+ try {
2309
+ const {
2310
+ nextState
2311
+ } = resolveActionsAndContext(actions, event, currentState, actorCtx);
2312
+ const output = done ? getOutput(nextConfiguration, nextState.context, event) : undefined;
2313
+ internalQueue.push(...nextState._internalQueue);
2314
+ return cloneState(currentState, {
2315
+ actions: nextState.actions,
2316
+ configuration: nextConfiguration,
2317
+ historyValue,
2318
+ _internalQueue: internalQueue,
2319
+ context: nextState.context,
2320
+ event,
2321
+ done,
2322
+ output,
2323
+ children: nextState.children
2324
+ });
2325
+ } catch (e) {
2326
+ // TODO: Refactor this once proper error handling is implemented.
2327
+ // See https://github.com/statelyai/rfcs/pull/4
2328
+ throw e;
2329
+ }
2330
+ }
2331
+ function enterStates(filteredTransitions, mutConfiguration, actions, internalQueue, currentState, historyValue) {
2332
+ const statesToEnter = new Set();
2333
+ const statesForDefaultEntry = new Set();
2334
+ computeEntrySet(filteredTransitions, historyValue, statesForDefaultEntry, statesToEnter);
2335
+
2336
+ // In the initial state, the root state node is "entered".
2337
+ if (currentState._initial) {
2338
+ statesForDefaultEntry.add(currentState.machine.root);
2339
+ }
2340
+ for (const stateNodeToEnter of [...statesToEnter].sort((a, b) => a.order - b.order)) {
2341
+ mutConfiguration.add(stateNodeToEnter);
2342
+ for (const invokeDef of stateNodeToEnter.invoke) {
2343
+ actions.push(invoke(invokeDef));
2344
+ }
2345
+
2346
+ // Add entry actions
2347
+ actions.push(...stateNodeToEnter.entry);
2348
+ if (statesForDefaultEntry.has(stateNodeToEnter)) {
2349
+ for (const stateNode of statesForDefaultEntry) {
2350
+ const initialActions = stateNode.initial.actions;
2351
+ actions.push(...initialActions);
2352
+ }
2353
+ }
2354
+ if (stateNodeToEnter.type === 'final') {
2355
+ const parent = stateNodeToEnter.parent;
2356
+ if (!parent.parent) {
2357
+ continue;
2358
+ }
2359
+ internalQueue.push(done(parent.id, stateNodeToEnter.output ? mapContext(stateNodeToEnter.output, currentState.context, currentState.event) : undefined));
2360
+ if (parent.parent) {
2361
+ const grandparent = parent.parent;
2362
+ if (grandparent.type === 'parallel') {
2363
+ if (getChildren(grandparent).every(parentNode => isInFinalState([...mutConfiguration], parentNode))) {
2364
+ internalQueue.push(done(grandparent.id));
2365
+ }
2366
+ }
2367
+ }
2368
+ }
2369
+ }
2370
+ }
2371
+ function computeEntrySet(transitions, historyValue, statesForDefaultEntry, statesToEnter) {
2372
+ for (const t of transitions) {
2373
+ for (const s of t.target || []) {
2374
+ addDescendantStatesToEnter(s, historyValue, statesForDefaultEntry, statesToEnter);
2375
+ }
2376
+ const ancestor = getTransitionDomain(t, historyValue);
2377
+ const targetStates = getEffectiveTargetStates(t, historyValue);
2378
+ for (const s of targetStates) {
2379
+ addAncestorStatesToEnter(s, ancestor, statesToEnter, historyValue, statesForDefaultEntry);
2380
+ }
2381
+ }
2382
+ }
2383
+ function addDescendantStatesToEnter(stateNode, historyValue, statesForDefaultEntry, statesToEnter) {
2384
+ if (isHistoryNode(stateNode)) {
2385
+ if (historyValue[stateNode.id]) {
2386
+ const historyStateNodes = historyValue[stateNode.id];
2387
+ for (const s of historyStateNodes) {
2388
+ addDescendantStatesToEnter(s, historyValue, statesForDefaultEntry, statesToEnter);
2389
+ }
2390
+ for (const s of historyStateNodes) {
2391
+ addAncestorStatesToEnter(s, stateNode.parent, statesToEnter, historyValue, statesForDefaultEntry);
2392
+ for (const stateForDefaultEntry of statesForDefaultEntry) {
2393
+ statesForDefaultEntry.add(stateForDefaultEntry);
2394
+ }
2395
+ }
2396
+ } else {
2397
+ const targets = resolveHistoryTarget(stateNode);
2398
+ for (const s of targets) {
2399
+ addDescendantStatesToEnter(s, historyValue, statesForDefaultEntry, statesToEnter);
2400
+ }
2401
+ for (const s of targets) {
2402
+ addAncestorStatesToEnter(s, stateNode, statesToEnter, historyValue, statesForDefaultEntry);
2403
+ for (const stateForDefaultEntry of statesForDefaultEntry) {
2404
+ statesForDefaultEntry.add(stateForDefaultEntry);
2405
+ }
2406
+ }
2407
+ }
2408
+ } else {
2409
+ statesToEnter.add(stateNode);
2410
+ if (stateNode.type === 'compound') {
2411
+ statesForDefaultEntry.add(stateNode);
2412
+ const initialStates = stateNode.initial.target;
2413
+ for (const initialState of initialStates) {
2414
+ addDescendantStatesToEnter(initialState, historyValue, statesForDefaultEntry, statesToEnter);
2415
+ }
2416
+ for (const initialState of initialStates) {
2417
+ addAncestorStatesToEnter(initialState, stateNode, statesToEnter, historyValue, statesForDefaultEntry);
2418
+ }
2419
+ } else {
2420
+ if (stateNode.type === 'parallel') {
2421
+ for (const child of getChildren(stateNode).filter(sn => !isHistoryNode(sn))) {
2422
+ if (![...statesToEnter].some(s => isDescendant(s, child))) {
2423
+ addDescendantStatesToEnter(child, historyValue, statesForDefaultEntry, statesToEnter);
2424
+ }
2425
+ }
2426
+ }
2427
+ }
2428
+ }
2429
+ }
2430
+ function addAncestorStatesToEnter(stateNode, toStateNode, statesToEnter, historyValue, statesForDefaultEntry) {
2431
+ const properAncestors = getProperAncestors(stateNode, toStateNode);
2432
+ for (const anc of properAncestors) {
2433
+ statesToEnter.add(anc);
2434
+ if (anc.type === 'parallel') {
2435
+ for (const child of getChildren(anc).filter(sn => !isHistoryNode(sn))) {
2436
+ if (![...statesToEnter].some(s => isDescendant(s, child))) {
2437
+ addDescendantStatesToEnter(child, historyValue, statesForDefaultEntry, statesToEnter);
2438
+ }
2439
+ }
2440
+ }
2441
+ }
2442
+ }
2443
+ function exitStates(transitions, mutConfiguration, historyValue, actions) {
2444
+ const statesToExit = computeExitSet(transitions, mutConfiguration, historyValue);
2445
+ statesToExit.sort((a, b) => b.order - a.order);
2446
+
2447
+ // From SCXML algorithm: https://www.w3.org/TR/scxml/#exitStates
2448
+ for (const exitStateNode of statesToExit) {
2449
+ for (const historyNode of getHistoryNodes(exitStateNode)) {
2450
+ let predicate;
2451
+ if (historyNode.history === 'deep') {
2452
+ predicate = sn => isAtomicStateNode(sn) && isDescendant(sn, exitStateNode);
2453
+ } else {
2454
+ predicate = sn => {
2455
+ return sn.parent === exitStateNode;
2456
+ };
2457
+ }
2458
+ historyValue[historyNode.id] = Array.from(mutConfiguration).filter(predicate);
2459
+ }
2460
+ }
2461
+ for (const s of statesToExit) {
2462
+ actions.push(...s.exit.flat(), ...s.invoke.map(def => stop(def.id)));
2463
+ mutConfiguration.delete(s);
2464
+ }
2465
+ }
2466
+ function resolveActionsAndContext(actions, event, currentState, actorCtx) {
2467
+ const {
2468
+ machine
2469
+ } = currentState;
2470
+ const resolvedActions = [];
2471
+ const raiseActions = [];
2472
+ let intermediateState = currentState;
2473
+ function handleAction(action) {
2474
+ resolvedActions.push(action);
2475
+ if (actorCtx?.self.status === ActorStatus.Running) {
2476
+ action.execute?.(actorCtx);
2477
+ // TODO: this is hacky; re-evaluate
2478
+ delete action.execute;
2479
+ }
2480
+ }
2481
+ function resolveAction(actionObject) {
2482
+ const executableActionObject = resolveActionObject(actionObject, machine.options.actions);
2483
+ if (isDynamicAction(executableActionObject)) {
2484
+ const [nextState, resolvedAction] = executableActionObject.resolve(event, {
2485
+ state: intermediateState,
2486
+ action: actionObject,
2487
+ actorContext: actorCtx
2488
+ });
2489
+ const matchedActions = resolvedAction.params?.actions;
2490
+ intermediateState = nextState;
2491
+ if ((resolvedAction.type === raise$1 || resolvedAction.type === send$1 && resolvedAction.params.internal) && typeof resolvedAction.params.delay !== 'number') {
2492
+ raiseActions.push(resolvedAction);
2493
+ }
2494
+
2495
+ // TODO: remove the check; just handleAction
2496
+ if (resolvedAction.type !== pure$1) {
2497
+ handleAction(resolvedAction);
2498
+ }
2499
+ toActionObjects(matchedActions).forEach(resolveAction);
2500
+ return;
2501
+ }
2502
+ handleAction(executableActionObject);
2503
+ }
2504
+ for (const actionObject of actions) {
2505
+ resolveAction(actionObject);
2506
+ }
2507
+ return {
2508
+ nextState: cloneState(intermediateState, {
2509
+ actions: resolvedActions,
2510
+ _internalQueue: raiseActions.map(a => a.params.event)
2511
+ })
2512
+ };
2513
+ }
2514
+ function macrostep(state, event, actorCtx) {
2515
+ let nextState = state;
2516
+ const states = [];
2517
+
2518
+ // Handle stop event
2519
+ if (event.type === stopSignalType) {
2520
+ nextState = stopStep(event, nextState, actorCtx);
2521
+ states.push(nextState);
2522
+ return {
2523
+ state: nextState,
2524
+ microstates: states
2525
+ };
2526
+ }
2527
+
2528
+ // Assume the state is at rest (no raised events)
2529
+ // Determine the next state based on the next microstep
2530
+ if (event.type !== init) {
2531
+ const transitions = selectTransitions(event, nextState);
2532
+ nextState = microstep(transitions, state, actorCtx, event);
2533
+ states.push(nextState);
2534
+ }
2535
+ while (!nextState.done) {
2536
+ let enabledTransitions = selectEventlessTransitions(nextState);
2537
+ if (enabledTransitions.length === 0) {
2538
+ // TODO: this is a bit of a hack, we need to review this
2539
+ // this matches the behavior from v4 for eventless transitions
2540
+ // where for `hasAlwaysTransitions` we were always trying to resolve with a NULL event
2541
+ // and if a transition was not selected the `state.transitions` stayed empty
2542
+ // without this we get into an infinite loop in the dieHard test in `@xstate/test` for the `simplePathsTo`
2543
+ if (nextState.configuration.some(state => state.always)) {
2544
+ nextState.transitions = [];
2545
+ }
2546
+ if (!nextState._internalQueue.length) {
2547
+ break;
2548
+ } else {
2549
+ const currentActions = nextState.actions;
2550
+ const nextEvent = nextState._internalQueue[0];
2551
+ const transitions = selectTransitions(nextEvent, nextState);
2552
+ nextState = microstep(transitions, nextState, actorCtx, nextEvent);
2553
+ nextState._internalQueue.shift();
2554
+ nextState.actions.unshift(...currentActions);
2555
+ states.push(nextState);
2556
+ }
2557
+ }
2558
+ if (enabledTransitions.length) {
2559
+ const currentActions = nextState.actions;
2560
+ nextState = microstep(enabledTransitions, nextState, actorCtx, nextState.event);
2561
+ nextState.actions.unshift(...currentActions);
2562
+ states.push(nextState);
2563
+ }
2564
+ }
2565
+ if (nextState.done) {
2566
+ // Perform the stop step to ensure that child actors are stopped
2567
+ stopStep(nextState.event, nextState, actorCtx);
2568
+ }
2569
+ return {
2570
+ state: nextState,
2571
+ microstates: states
2572
+ };
2573
+ }
2574
+ function stopStep(event, nextState, actorCtx) {
2575
+ const actions = [];
2576
+ for (const stateNode of nextState.configuration.sort((a, b) => b.order - a.order)) {
2577
+ actions.push(...stateNode.exit);
2578
+ }
2579
+ for (const child of Object.values(nextState.children)) {
2580
+ actions.push(stop(child));
2581
+ }
2582
+ const {
2583
+ nextState: stoppedState
2584
+ } = resolveActionsAndContext(actions, event, nextState, actorCtx);
2585
+ return stoppedState;
2586
+ }
2587
+ function selectTransitions(event, nextState) {
2588
+ return nextState.machine.getTransitionData(nextState, event);
2589
+ }
2590
+ function selectEventlessTransitions(nextState) {
2591
+ const enabledTransitionSet = new Set();
2592
+ const atomicStates = nextState.configuration.filter(isAtomicStateNode);
2593
+ for (const stateNode of atomicStates) {
2594
+ loop: for (const s of [stateNode].concat(getProperAncestors(stateNode, null))) {
2595
+ if (!s.always) {
2596
+ continue;
2597
+ }
2598
+ for (const transition of s.always) {
2599
+ if (transition.guard === undefined || evaluateGuard(transition.guard, nextState.context, nextState.event, nextState)) {
2600
+ enabledTransitionSet.add(transition);
2601
+ break loop;
2602
+ }
2603
+ }
2604
+ }
2605
+ }
2606
+ return removeConflictingTransitions(Array.from(enabledTransitionSet), new Set(nextState.configuration), nextState.historyValue);
2607
+ }
2608
+
2609
+ /**
2610
+ * Resolves a partial state value with its full representation in the state node's machine.
2611
+ *
2612
+ * @param stateValue The partial state value to resolve.
2613
+ */
2614
+ function resolveStateValue(rootNode, stateValue) {
2615
+ const configuration = getConfiguration(getStateNodes(rootNode, stateValue));
2616
+ return getStateValue(rootNode, [...configuration]);
2617
+ }
2618
+ function stateValuesEqual(a, b) {
2619
+ if (a === b) {
2620
+ return true;
2621
+ }
2622
+ if (a === undefined || b === undefined) {
2623
+ return false;
2624
+ }
2625
+ if (isString(a) || isString(b)) {
2626
+ return a === b;
2627
+ }
2628
+ const aKeys = Object.keys(a);
2629
+ const bKeys = Object.keys(b);
2630
+ return aKeys.length === bKeys.length && aKeys.every(key => stateValuesEqual(a[key], b[key]));
2631
+ }
2632
+ function getInitialConfiguration(rootNode) {
2633
+ const configuration = [];
2634
+ const initialTransition = rootNode.initial;
2635
+ const statesToEnter = new Set();
2636
+ const statesForDefaultEntry = new Set([rootNode]);
2637
+ computeEntrySet([initialTransition], {}, statesForDefaultEntry, statesToEnter);
2638
+ for (const stateNodeToEnter of [...statesToEnter].sort((a, b) => a.order - b.order)) {
2639
+ configuration.push(stateNodeToEnter);
2640
+ }
2641
+ return configuration;
2642
+ }
2643
+
2644
+ class State {
2645
+ /**
2646
+ * Indicates whether the state is a final state.
2647
+ */
2648
+
2649
+ /**
2650
+ * The done data of the top-level finite state.
2651
+ */
2652
+ // TODO: add an explicit type for `output`
2653
+
2654
+ /**
2655
+ * Indicates whether the state has changed from the previous state. A state is considered "changed" if:
2656
+ *
2657
+ * - Its value is not equal to its previous value, or:
2658
+ * - It has any new actions (side-effects) to execute.
2659
+ *
2660
+ * An initial state (with no history) will return `undefined`.
2661
+ */
2662
+
2663
+ /**
2664
+ * The enabled state nodes representative of the state value.
2665
+ */
2666
+
2667
+ /**
2668
+ * The transition definitions that resulted in this state.
2669
+ */
2670
+
2671
+ /**
2672
+ * An object mapping actor names to spawned/invoked actors.
2673
+ */
2674
+
2675
+ /**
2676
+ * Creates a new State instance for the given `stateValue` and `context`.
2677
+ * @param stateValue
2678
+ * @param context
2679
+ */
2680
+ static from(stateValue, context = {}, machine) {
2681
+ if (stateValue instanceof State) {
2682
+ if (stateValue.context !== context) {
2683
+ return new State({
2684
+ value: stateValue.value,
2685
+ context,
2686
+ event: stateValue.event,
2687
+ actions: [],
2688
+ meta: {},
2689
+ configuration: [],
2690
+ // TODO: fix,
2691
+ transitions: [],
2692
+ children: {}
2693
+ }, machine);
2694
+ }
2695
+ return stateValue;
2696
+ }
2697
+ const event = createInitEvent({}); // TODO: fix
2698
+
2699
+ const configuration = getConfiguration(getStateNodes(machine.root, stateValue));
2700
+ return new State({
2701
+ value: stateValue,
2702
+ context,
2703
+ event,
2704
+ actions: [],
2705
+ meta: undefined,
2706
+ configuration: Array.from(configuration),
2707
+ transitions: [],
2708
+ children: {}
2709
+ }, machine);
2710
+ }
2711
+
2712
+ /**
2713
+ * Creates a new `State` instance that represents the current state of a running machine.
2714
+ *
2715
+ * @param config
2716
+ */
2717
+ constructor(config, machine) {
2718
+ this.machine = machine;
2719
+ this.tags = void 0;
2720
+ this.value = void 0;
2721
+ this.done = void 0;
2722
+ this.output = void 0;
2723
+ this.context = void 0;
2724
+ this.historyValue = {};
2725
+ this.actions = [];
2726
+ this.event = void 0;
2727
+ this._internalQueue = void 0;
2728
+ this._initial = false;
2729
+ this.changed = void 0;
2730
+ this.configuration = void 0;
2731
+ this.transitions = void 0;
2732
+ this.children = void 0;
2733
+ this.context = config.context;
2734
+ this._internalQueue = config._internalQueue ?? [];
2735
+ this.event = config.event;
2736
+ this.historyValue = config.historyValue || {};
2737
+ this.actions = config.actions ?? [];
2738
+ this.matches = this.matches.bind(this);
2739
+ this.toStrings = this.toStrings.bind(this);
2740
+ this.configuration = config.configuration ?? Array.from(getConfiguration(getStateNodes(machine.root, config.value)));
2741
+ this.transitions = config.transitions;
2742
+ this.children = config.children;
2743
+ this.value = getStateValue(machine.root, this.configuration);
2744
+ this.tags = new Set(flatten(this.configuration.map(sn => sn.tags)));
2745
+ this.done = config.done ?? false;
2746
+ this.output = config.output;
2747
+ }
2748
+
2749
+ /**
2750
+ * Returns an array of all the string leaf state node paths.
2751
+ * @param stateValue
2752
+ * @param delimiter The character(s) that separate each subpath in the string state node path.
2753
+ */
2754
+ toStrings(stateValue = this.value, delimiter = '.') {
2755
+ if (isString(stateValue)) {
2756
+ return [stateValue];
2757
+ }
2758
+ const valueKeys = Object.keys(stateValue);
2759
+ return valueKeys.concat(...valueKeys.map(key => this.toStrings(stateValue[key], delimiter).map(s => key + delimiter + s)));
2760
+ }
2761
+ toJSON() {
2762
+ const {
2763
+ configuration,
2764
+ transitions,
2765
+ tags,
2766
+ machine,
2767
+ ...jsonValues
2768
+ } = this;
2769
+ return {
2770
+ ...jsonValues,
2771
+ tags: Array.from(tags),
2772
+ meta: this.meta
2773
+ };
2774
+ }
2775
+
2776
+ /**
2777
+ * Whether the current state value is a subset of the given parent state value.
2778
+ * @param parentStateValue
2779
+ */
2780
+ matches(parentStateValue) {
2781
+ return matchesState(parentStateValue, this.value);
2782
+ }
2783
+
2784
+ /**
2785
+ * Whether the current state configuration has a state node with the specified `tag`.
2786
+ * @param tag
2787
+ */
2788
+ hasTag(tag) {
2789
+ return this.tags.has(tag);
2790
+ }
2791
+
2792
+ /**
2793
+ * Determines whether sending the `event` will cause a non-forbidden transition
2794
+ * to be selected, even if the transitions have no actions nor
2795
+ * change the state value.
2796
+ *
2797
+ * @param event The event to test
2798
+ * @returns Whether the event will cause a transition
2799
+ */
2800
+ can(event) {
2801
+ const transitionData = this.machine.getTransitionData(this, event);
2802
+ return !!transitionData?.length &&
2803
+ // Check that at least one transition is not forbidden
2804
+ transitionData.some(t => t.target !== undefined || t.actions.length);
2805
+ }
2806
+
2807
+ /**
2808
+ * The next events that will cause a transition from the current state.
2809
+ */
2810
+ get nextEvents() {
2811
+ return memo(this, 'nextEvents', () => {
2812
+ return [...new Set(flatten([...this.configuration.map(sn => sn.ownEvents)]))];
2813
+ });
2814
+ }
2815
+ get meta() {
2816
+ return this.configuration.reduce((acc, stateNode) => {
2817
+ if (stateNode.meta !== undefined) {
2818
+ acc[stateNode.id] = stateNode.meta;
2819
+ }
2820
+ return acc;
2821
+ }, {});
2822
+ }
2823
+ }
2824
+ function cloneState(state, config = {}) {
2825
+ return new State({
2826
+ ...state,
2827
+ ...config
2828
+ }, state.machine);
2829
+ }
2830
+ function getPersistedState(state) {
2831
+ const {
2832
+ configuration,
2833
+ transitions,
2834
+ tags,
2835
+ machine,
2836
+ children,
2837
+ ...jsonValues
2838
+ } = state;
2839
+ const childrenJson = {};
2840
+ for (const id in children) {
2841
+ childrenJson[id] = {
2842
+ state: children[id].getPersistedState?.(),
2843
+ src: children[id].src
2844
+ };
2845
+ }
2846
+ return {
2847
+ ...jsonValues,
2848
+ children: childrenJson
2849
+ };
2850
+ }
2851
+
2852
+ function invoke(invokeDef) {
2853
+ return createDynamicAction({
2854
+ type: invoke$1,
2855
+ params: invokeDef
2856
+ }, (event, {
2857
+ state,
2858
+ actorContext
2859
+ }) => {
2860
+ const type = invoke$1;
2861
+ const {
2862
+ id,
2863
+ src
2864
+ } = invokeDef;
2865
+ let resolvedInvokeAction;
2866
+ if (isActorRef(src)) {
2867
+ resolvedInvokeAction = {
2868
+ type,
2869
+ params: {
2870
+ ...invokeDef,
2871
+ ref: src
2872
+ }
2873
+ };
2874
+ } else {
2875
+ const referenced = resolveReferencedActor(state.machine.options.actors[src]);
2876
+ if (!referenced) {
2877
+ resolvedInvokeAction = {
2878
+ type,
2879
+ params: invokeDef
2880
+ };
2881
+ } else {
2882
+ const input = 'input' in invokeDef ? invokeDef.input : referenced.input;
2883
+ const ref = interpret(referenced.src, {
2884
+ id,
2885
+ src,
2886
+ parent: actorContext?.self,
2887
+ systemId: invokeDef.systemId,
2888
+ input: typeof input === 'function' ? input({
2889
+ context: state.context,
2890
+ event,
2891
+ self: actorContext?.self
2892
+ }) : input
2893
+ });
2894
+ resolvedInvokeAction = {
2895
+ type,
2896
+ params: {
2897
+ ...invokeDef,
2898
+ ref
2899
+ }
2900
+ };
2901
+ }
2902
+ }
2903
+ const actorRef = resolvedInvokeAction.params.ref;
2904
+ const invokedState = cloneState(state, {
2905
+ children: {
2906
+ ...state.children,
2907
+ [id]: actorRef
2908
+ }
2909
+ });
2910
+ resolvedInvokeAction.execute = actorCtx => {
2911
+ const parent = actorCtx.self;
2912
+ const {
2913
+ id,
2914
+ ref
2915
+ } = resolvedInvokeAction.params;
2916
+ if (!ref) {
2917
+ return;
2918
+ }
2919
+ actorCtx.defer(() => {
2920
+ if (actorRef.status === ActorStatus.Stopped) {
2921
+ return;
2922
+ }
2923
+ try {
2924
+ actorRef.start?.();
2925
+ } catch (err) {
2926
+ parent.send(error(id, err));
2927
+ return;
2928
+ }
2929
+ });
2930
+ };
2931
+ return [invokedState, resolvedInvokeAction];
2932
+ });
2933
+ }
2934
+
2935
+ function createSpawner(self, machine, context, event, mutCapturedActions) {
2936
+ return (src, options = {}) => {
2937
+ const {
2938
+ systemId
2939
+ } = options;
2940
+ if (isString(src)) {
2941
+ const referenced = resolveReferencedActor(machine.options.actors[src]);
2942
+ if (referenced) {
2943
+ const resolvedName = options.id ?? 'anon'; // TODO: better name
2944
+ const input = 'input' in options ? options.input : referenced.input;
2945
+
2946
+ // TODO: this should also receive `src`
2947
+ const actorRef = interpret(referenced.src, {
2948
+ id: resolvedName,
2949
+ parent: self,
2950
+ input: typeof input === 'function' ? input({
2951
+ context,
2952
+ event,
2953
+ self
2954
+ }) : input
2955
+ });
2956
+ mutCapturedActions.push(invoke({
2957
+ id: actorRef.id,
2958
+ // @ts-ignore TODO: fix types
2959
+ src: actorRef,
2960
+ // TODO
2961
+ ref: actorRef,
2962
+ meta: undefined,
2963
+ input,
2964
+ systemId
2965
+ }));
2966
+ return actorRef; // TODO: fix types
2967
+ }
2968
+
2969
+ throw new Error(`Behavior '${src}' not implemented in machine '${machine.id}'`);
2970
+ } else {
2971
+ // TODO: this should also receive `src`
2972
+ // TODO: instead of anonymous, it should be a unique stable ID
2973
+ const actorRef = interpret(src, {
2974
+ id: options.id || 'anonymous',
2975
+ parent: self,
2976
+ input: options.input,
2977
+ systemId
2978
+ });
2979
+ mutCapturedActions.push(invoke({
2980
+ // @ts-ignore TODO: fix types
2981
+ src: actorRef,
2982
+ ref: actorRef,
2983
+ id: actorRef.id,
2984
+ meta: undefined,
2985
+ input: options.input
2986
+ }));
2987
+ return actorRef; // TODO: fix types
2988
+ }
2989
+ };
2990
+ }
2991
+
2992
+ /**
2993
+ * Updates the current context of the machine.
2994
+ *
2995
+ * @param assignment An object that represents the partial context to update.
2996
+ */
2997
+ function assign(assignment) {
2998
+ return createDynamicAction({
2999
+ type: assign$1,
3000
+ params: {
3001
+ assignment
3002
+ }
3003
+ }, (event, {
3004
+ state,
3005
+ action,
3006
+ actorContext
3007
+ }) => {
3008
+ const capturedActions = [];
3009
+ if (!state.context) {
3010
+ throw new Error('Cannot assign to undefined `context`. Ensure that `context` is defined in the machine config.');
3011
+ }
3012
+ const args = {
3013
+ context: state.context,
3014
+ event,
3015
+ action,
3016
+ spawn: createSpawner(actorContext?.self, state.machine, state.context, event, capturedActions),
3017
+ self: actorContext?.self ?? {},
3018
+ system: actorContext?.system
3019
+ };
3020
+ let partialUpdate = {};
3021
+ if (isFunction(assignment)) {
3022
+ partialUpdate = assignment(args);
3023
+ } else {
3024
+ for (const key of Object.keys(assignment)) {
3025
+ const propAssignment = assignment[key];
3026
+ partialUpdate[key] = isFunction(propAssignment) ? propAssignment(args) : propAssignment;
3027
+ }
3028
+ }
3029
+ const updatedContext = Object.assign({}, state.context, partialUpdate);
3030
+ return [cloneState(state, {
3031
+ context: updatedContext
3032
+ }), {
3033
+ type: assign$1,
3034
+ params: {
3035
+ context: updatedContext,
3036
+ actions: capturedActions
3037
+ }
3038
+ }];
3039
+ });
3040
+ }
3041
+
3042
+ /**
3043
+ * Raises an event. This places the event in the internal event queue, so that
3044
+ * the event is immediately consumed by the machine in the current step.
3045
+ *
3046
+ * @param eventType The event to raise.
3047
+ */
3048
+
3049
+ function raise(eventOrExpr, options) {
3050
+ return createDynamicAction({
3051
+ type: raise$1,
3052
+ params: {
3053
+ delay: options ? options.delay : undefined,
3054
+ event: eventOrExpr,
3055
+ id: options && options.id !== undefined ? options.id : typeof eventOrExpr === 'function' ? eventOrExpr.name : eventOrExpr.type
3056
+ }
3057
+ }, (event, {
3058
+ state,
3059
+ actorContext
3060
+ }) => {
3061
+ const params = {
3062
+ delay: options ? options.delay : undefined,
3063
+ event: eventOrExpr,
3064
+ id: options && options.id !== undefined ? options.id : typeof eventOrExpr === 'function' ? eventOrExpr.name : eventOrExpr.type
3065
+ };
3066
+ const args = {
3067
+ context: state.context,
3068
+ event,
3069
+ self: actorContext?.self ?? {},
3070
+ system: actorContext?.system
3071
+ };
3072
+ const delaysMap = state.machine.options.delays;
3073
+
3074
+ // TODO: helper function for resolving Expr
3075
+ if (typeof eventOrExpr === 'string') {
3076
+ throw new Error(`Only event objects may be used with raise; use raise({ type: "${eventOrExpr}" }) instead`);
3077
+ }
3078
+ const resolvedEvent = typeof eventOrExpr === 'function' ? eventOrExpr(args) : eventOrExpr;
3079
+ let resolvedDelay;
3080
+ if (typeof params.delay === 'string') {
3081
+ const configDelay = delaysMap && delaysMap[params.delay];
3082
+ resolvedDelay = typeof configDelay === 'function' ? configDelay(args) : configDelay;
3083
+ } else {
3084
+ resolvedDelay = typeof params.delay === 'function' ? params.delay(args) : params.delay;
3085
+ }
3086
+ const resolvedAction = {
3087
+ type: raise$1,
3088
+ params: {
3089
+ ...params,
3090
+ event: resolvedEvent,
3091
+ delay: resolvedDelay
3092
+ },
3093
+ execute: actorCtx => {
3094
+ if (typeof resolvedAction.params.delay === 'number') {
3095
+ actorCtx.self.delaySend(resolvedAction);
3096
+ return;
3097
+ }
3098
+ }
3099
+ };
3100
+ return [state, resolvedAction];
3101
+ });
3102
+ }
3103
+
3104
+ function choose(guards) {
3105
+ return createDynamicAction({
3106
+ type: choose$1,
3107
+ params: {
3108
+ guards
3109
+ }
3110
+ }, (event, {
3111
+ state
3112
+ }) => {
3113
+ const matchedActions = guards.find(condition => {
3114
+ const guard = condition.guard && toGuardDefinition(condition.guard, guardType => state.machine.options.guards[guardType]);
3115
+ return !guard || evaluateGuard(guard, state.context, event, state);
3116
+ })?.actions;
3117
+ return [state, {
3118
+ type: choose$1,
3119
+ params: {
3120
+ actions: toActionObjects(matchedActions)
3121
+ }
3122
+ }];
3123
+ });
3124
+ }
3125
+
3126
+ function pure(getActions) {
3127
+ return createDynamicAction({
3128
+ type: pure$1,
3129
+ params: {
3130
+ get: getActions
3131
+ }
3132
+ }, (event, {
3133
+ state
3134
+ }) => {
3135
+ return [state, {
3136
+ type: pure$1,
3137
+ params: {
3138
+ actions: toArray(toActionObjects(getActions({
3139
+ context: state.context,
3140
+ event
3141
+ }))) ?? []
3142
+ }
3143
+ }];
3144
+ });
3145
+ }
3146
+
3147
+ const initEvent = {
3148
+ type: init
3149
+ };
3150
+ function resolveActionObject(actionObject, actionFunctionMap) {
3151
+ if (isDynamicAction(actionObject)) {
3152
+ return actionObject;
3153
+ }
3154
+ const dereferencedAction = actionFunctionMap[actionObject.type];
3155
+ if (typeof dereferencedAction === 'function') {
3156
+ return createDynamicAction({
3157
+ type: 'xstate.function',
3158
+ params: actionObject.params ?? {}
3159
+ }, (event, {
3160
+ state
3161
+ }) => {
3162
+ const a = {
3163
+ type: actionObject.type,
3164
+ params: actionObject.params,
3165
+ execute: actorCtx => {
3166
+ return dereferencedAction({
3167
+ context: state.context,
3168
+ event,
3169
+ action: a,
3170
+ system: actorCtx.system,
3171
+ self: actorCtx.self
3172
+ });
3173
+ }
3174
+ };
3175
+ return [state, a];
3176
+ });
3177
+ } else if (dereferencedAction) {
3178
+ return dereferencedAction;
3179
+ } else {
3180
+ return actionObject;
3181
+ }
3182
+ }
3183
+ function toActionObject(action) {
3184
+ if (isDynamicAction(action)) {
3185
+ return action;
3186
+ }
3187
+ if (typeof action === 'string') {
3188
+ return {
3189
+ type: action,
3190
+ params: {}
3191
+ };
3192
+ }
3193
+ if (typeof action === 'function') {
3194
+ const type = 'xstate.function';
3195
+ return createDynamicAction({
3196
+ type,
3197
+ params: {}
3198
+ }, (event, {
3199
+ state
3200
+ }) => {
3201
+ const actionObject = {
3202
+ type,
3203
+ params: {
3204
+ function: action
3205
+ },
3206
+ execute: actorCtx => {
3207
+ return action({
3208
+ context: state.context,
3209
+ event: event,
3210
+ action: actionObject,
3211
+ self: actorCtx.self,
3212
+ system: actorCtx.system
3213
+ });
3214
+ }
3215
+ };
3216
+ return [state, actionObject];
3217
+ });
3218
+ }
3219
+
3220
+ // action is already a BaseActionObject
3221
+ return action;
3222
+ }
3223
+ const toActionObjects = action => {
3224
+ if (!action) {
3225
+ return [];
3226
+ }
3227
+ const actions = isArray(action) ? action : [action];
3228
+ return actions.map(toActionObject);
3229
+ };
3230
+
3231
+ /**
3232
+ * Returns an event type that represents an implicit event that
3233
+ * is sent after the specified `delay`.
3234
+ *
3235
+ * @param delayRef The delay in milliseconds
3236
+ * @param id The state node ID where this event is handled
3237
+ */
3238
+ function after(delayRef, id) {
3239
+ const idSuffix = id ? `#${id}` : '';
3240
+ return `${ActionTypes.After}(${delayRef})${idSuffix}`;
3241
+ }
3242
+
3243
+ /**
3244
+ * Returns an event that represents that a final state node
3245
+ * has been reached in the parent state node.
3246
+ *
3247
+ * @param id The final state node's parent state node `id`
3248
+ * @param output The data to pass into the event
3249
+ */
3250
+ function done(id, output) {
3251
+ const type = `${ActionTypes.DoneState}.${id}`;
3252
+ const eventObject = {
3253
+ type,
3254
+ output
3255
+ };
3256
+ eventObject.toString = () => type;
3257
+ return eventObject;
3258
+ }
3259
+
3260
+ /**
3261
+ * Returns an event that represents that an invoked service has terminated.
3262
+ *
3263
+ * An invoked service is terminated when it has reached a top-level final state node,
3264
+ * but not when it is canceled.
3265
+ *
3266
+ * @param invokeId The invoked service ID
3267
+ * @param output The data to pass into the event
3268
+ */
3269
+ function doneInvoke(invokeId, output) {
3270
+ const type = `${ActionTypes.DoneInvoke}.${invokeId}`;
3271
+ const eventObject = {
3272
+ type,
3273
+ output
3274
+ };
3275
+ eventObject.toString = () => type;
3276
+ return eventObject;
3277
+ }
3278
+ function error(id, data) {
3279
+ const type = `${ActionTypes.ErrorPlatform}.${id}`;
3280
+ const eventObject = {
3281
+ type,
3282
+ data
3283
+ };
3284
+ eventObject.toString = () => type;
3285
+ return eventObject;
3286
+ }
3287
+ function createInitEvent(input) {
3288
+ return {
3289
+ type: init,
3290
+ input
3291
+ };
3292
+ }
3293
+
3294
+ exports.ActionTypes = ActionTypes;
3295
+ exports.ActorStatus = ActorStatus;
3296
+ exports.Interpreter = Interpreter;
3297
+ exports.NULL_EVENT = NULL_EVENT;
3298
+ exports.STATE_DELIMITER = STATE_DELIMITER;
3299
+ exports.SpecialTargets = SpecialTargets;
3300
+ exports.State = State;
3301
+ exports.actionTypes = actionTypes;
3302
+ exports.after = after;
3303
+ exports.and = and;
3304
+ exports.assign = assign;
3305
+ exports.cancel = cancel;
3306
+ exports.choose = choose;
3307
+ exports.createEmptyActor = createEmptyActor;
3308
+ exports.createInitEvent = createInitEvent;
3309
+ exports.createInvokeId = createInvokeId;
3310
+ exports.createSpawner = createSpawner;
3311
+ exports.done = done;
3312
+ exports.doneInvoke = doneInvoke;
3313
+ exports.error = error;
3314
+ exports.escalate = escalate;
3315
+ exports.evaluateGuard = evaluateGuard;
3316
+ exports.flatten = flatten;
3317
+ exports.formatInitialTransition = formatInitialTransition;
3318
+ exports.formatTransition = formatTransition;
3319
+ exports.formatTransitions = formatTransitions;
3320
+ exports.forwardTo = forwardTo;
3321
+ exports.fromCallback = fromCallback;
3322
+ exports.fromEventObservable = fromEventObservable;
3323
+ exports.fromObservable = fromObservable;
3324
+ exports.fromPromise = fromPromise;
3325
+ exports.fromTransition = fromTransition;
3326
+ exports.getCandidates = getCandidates;
3327
+ exports.getConfiguration = getConfiguration;
3328
+ exports.getDelayedTransitions = getDelayedTransitions;
3329
+ exports.getInitialConfiguration = getInitialConfiguration;
3330
+ exports.getPersistedState = getPersistedState;
3331
+ exports.getStateNodeByPath = getStateNodeByPath;
3332
+ exports.getStateNodes = getStateNodes;
3333
+ exports.initEvent = initEvent;
3334
+ exports.interpret = interpret;
3335
+ exports.invoke = invoke$1;
3336
+ exports.isActorRef = isActorRef;
3337
+ exports.isErrorEvent = isErrorEvent;
3338
+ exports.isInFinalState = isInFinalState;
3339
+ exports.isSignal = isSignal;
3340
+ exports.isStateId = isStateId;
3341
+ exports.isString = isString;
3342
+ exports.log = log;
3343
+ exports.macrostep = macrostep;
3344
+ exports.mapValues = mapValues;
3345
+ exports.matchesState = matchesState;
3346
+ exports.memo = memo;
3347
+ exports.microstep = microstep;
3348
+ exports.not = not;
3349
+ exports.or = or;
3350
+ exports.pathToStateValue = pathToStateValue;
3351
+ exports.pure = pure;
3352
+ exports.raise = raise;
3353
+ exports.resolveActionObject = resolveActionObject;
3354
+ exports.resolveActionsAndContext = resolveActionsAndContext;
3355
+ exports.resolveReferencedActor = resolveReferencedActor;
3356
+ exports.resolveStateValue = resolveStateValue;
3357
+ exports.send = send;
3358
+ exports.sendParent = sendParent;
3359
+ exports.sendTo = sendTo;
3360
+ exports.startSignal = startSignal;
3361
+ exports.startSignalType = startSignalType;
3362
+ exports.stateIn = stateIn;
3363
+ exports.stop = stop;
3364
+ exports.stopSignal = stopSignal;
3365
+ exports.stopSignalType = stopSignalType;
3366
+ exports.toActionObject = toActionObject;
3367
+ exports.toActionObjects = toActionObjects;
3368
+ exports.toActorRef = toActorRef;
3369
+ exports.toArray = toArray;
3370
+ exports.toGuardDefinition = toGuardDefinition;
3371
+ exports.toInvokeConfig = toInvokeConfig;
3372
+ exports.toObserver = toObserver;
3373
+ exports.toTransitionConfigArray = toTransitionConfigArray;
3374
+ exports.transitionNode = transitionNode;