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

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