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

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