xstate 5.0.0-beta.27 → 5.0.0-beta.28

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 (59) hide show
  1. package/README.md +9 -7
  2. package/actions/dist/xstate-actions.cjs.js +11 -17
  3. package/actions/dist/xstate-actions.cjs.mjs +0 -8
  4. package/actions/dist/xstate-actions.development.cjs.js +11 -17
  5. package/actions/dist/xstate-actions.development.cjs.mjs +0 -8
  6. package/actions/dist/xstate-actions.development.esm.js +3 -1
  7. package/actions/dist/xstate-actions.esm.js +3 -1
  8. package/actions/dist/xstate-actions.umd.min.js +1 -1
  9. package/actions/dist/xstate-actions.umd.min.js.map +1 -1
  10. package/actors/dist/xstate-actors.cjs.js +413 -11
  11. package/actors/dist/xstate-actors.development.cjs.js +413 -11
  12. package/actors/dist/xstate-actors.development.esm.js +405 -4
  13. package/actors/dist/xstate-actors.esm.js +405 -4
  14. package/actors/dist/xstate-actors.umd.min.js +1 -1
  15. package/actors/dist/xstate-actors.umd.min.js.map +1 -1
  16. package/dist/declarations/src/StateNode.d.ts +3 -3
  17. package/dist/declarations/src/actions/assign.d.ts +8 -3
  18. package/dist/declarations/src/actions/choose.d.ts +4 -3
  19. package/dist/declarations/src/actions/pure.d.ts +5 -4
  20. package/dist/declarations/src/actions.d.ts +8 -44
  21. package/dist/declarations/src/actors/index.d.ts +2 -2
  22. package/dist/declarations/src/constants.d.ts +1 -0
  23. package/dist/declarations/src/index.d.ts +9 -16
  24. package/dist/declarations/src/spawn.d.ts +25 -0
  25. package/dist/declarations/src/stateUtils.d.ts +1 -1
  26. package/dist/declarations/src/typegenTypes.d.ts +4 -4
  27. package/dist/declarations/src/types.d.ts +72 -94
  28. package/dist/declarations/src/utils.d.ts +2 -2
  29. package/dist/interpreter-672794ae.cjs.js +792 -0
  30. package/dist/interpreter-a1432c7d.development.cjs.js +800 -0
  31. package/dist/interpreter-a77bb0ec.development.esm.js +765 -0
  32. package/dist/interpreter-b5203bcb.esm.js +757 -0
  33. package/dist/{actions-9754d2ca.development.esm.js → raise-436a57a2.cjs.js} +130 -1307
  34. package/dist/{actions-ca622922.development.cjs.js → raise-74b72ca5.development.cjs.js} +101 -1306
  35. package/dist/{actions-020463e9.esm.js → raise-a60c9290.development.esm.js} +109 -1203
  36. package/dist/{actions-d1dba4ac.cjs.js → raise-b9c9a234.esm.js} +65 -1267
  37. package/dist/send-35e1a689.cjs.js +349 -0
  38. package/dist/send-4192e7bc.esm.js +339 -0
  39. package/dist/send-e63b7b83.development.esm.js +364 -0
  40. package/dist/send-e8b55d00.development.cjs.js +374 -0
  41. package/dist/xstate.cjs.js +110 -106
  42. package/dist/xstate.cjs.mjs +4 -2
  43. package/dist/xstate.development.cjs.js +110 -106
  44. package/dist/xstate.development.cjs.mjs +4 -2
  45. package/dist/xstate.development.esm.js +72 -68
  46. package/dist/xstate.esm.js +72 -68
  47. package/dist/xstate.umd.min.js +1 -1
  48. package/dist/xstate.umd.min.js.map +1 -1
  49. package/guards/dist/xstate-guards.cjs.js +2 -1
  50. package/guards/dist/xstate-guards.development.cjs.js +2 -1
  51. package/guards/dist/xstate-guards.development.esm.js +2 -1
  52. package/guards/dist/xstate-guards.esm.js +2 -1
  53. package/guards/dist/xstate-guards.umd.min.js.map +1 -1
  54. package/package.json +1 -1
  55. package/dist/declarations/src/constantPrefixes.d.ts +0 -6
  56. package/dist/promise-2ad94e3b.development.esm.js +0 -406
  57. package/dist/promise-3b7e3357.development.cjs.js +0 -412
  58. package/dist/promise-5b07c38e.esm.js +0 -406
  59. package/dist/promise-7a8c1768.cjs.js +0 -412
@@ -1,209 +1,6 @@
1
- import { devToolsAdapter } from '../dev/dist/xstate-dev.development.esm.js';
1
+ 'use strict';
2
2
 
3
- /**
4
- * `T | unknown` reduces to `unknown` and that can be problematic when it comes to contextual typing.
5
- * It especially is a problem when the union has a function member, like here:
6
- *
7
- * ```ts
8
- * declare function test(cbOrVal: ((arg: number) => unknown) | unknown): void;
9
- * test((arg) => {}) // oops, implicit any
10
- * ```
11
- *
12
- * This type can be used to avoid this problem. This union represents the same value space as `unknown`.
13
- */
14
-
15
- // https://github.com/microsoft/TypeScript/issues/23182#issuecomment-379091887
16
-
17
- /**
18
- * The full definition of an event, with a string `type`.
19
- */
20
-
21
- // TODO: do not accept machines without all implementations
22
- // we should also accept a raw machine as actor logic here
23
- // or just make machine actor logic
24
-
25
- /**
26
- * The string or object representing the state value relative to the parent state node.
27
- *
28
- * - For a child atomic state node, this is a string, e.g., `"pending"`.
29
- * - For complex state nodes, this is an object, e.g., `{ success: "someChildState" }`.
30
- */
31
-
32
- // TODO: remove once TS fixes this type-widening issue
33
-
34
- // TODO: possibly refactor this somehow, use even a simpler type, and maybe even make `machine.options` private or something
35
-
36
- let ConstantPrefix = /*#__PURE__*/function (ConstantPrefix) {
37
- ConstantPrefix["After"] = "xstate.after";
38
- ConstantPrefix["DoneState"] = "done.state";
39
- ConstantPrefix["DoneInvoke"] = "done.invoke";
40
- ConstantPrefix["ErrorExecution"] = "error.execution";
41
- ConstantPrefix["ErrorCommunication"] = "error.communication";
42
- ConstantPrefix["ErrorPlatform"] = "error.platform";
43
- ConstantPrefix["ErrorCustom"] = "xstate.error";
44
- return ConstantPrefix;
45
- }({});
46
- let SpecialTargets = /*#__PURE__*/function (SpecialTargets) {
47
- SpecialTargets["Parent"] = "#_parent";
48
- SpecialTargets["Internal"] = "#_internal";
49
- return SpecialTargets;
50
- }({});
51
-
52
- const after$1 = ConstantPrefix.After;
53
- const doneState = ConstantPrefix.DoneState;
54
- const errorExecution = ConstantPrefix.ErrorExecution;
55
- const errorPlatform = ConstantPrefix.ErrorPlatform;
56
- const error$1 = ConstantPrefix.ErrorCustom;
57
-
58
- var constantPrefixes = /*#__PURE__*/Object.freeze({
59
- __proto__: null,
60
- after: after$1,
61
- doneState: doneState,
62
- errorExecution: errorExecution,
63
- errorPlatform: errorPlatform,
64
- error: error$1
65
- });
66
-
67
- const STATE_DELIMITER = '.';
68
- const TARGETLESS_KEY = '';
69
- const NULL_EVENT = '';
70
- const STATE_IDENTIFIER = '#';
71
- const WILDCARD = '*';
72
- const XSTATE_INIT = 'xstate.init';
73
- const XSTATE_STOP = 'xstate.stop';
74
-
75
- function resolve$8(actorContext, state, args, {
76
- to,
77
- event: eventOrExpr,
78
- id,
79
- delay
80
- }) {
81
- const delaysMap = state.machine.implementations.delays;
82
- if (typeof eventOrExpr === 'string') {
83
- throw new Error(`Only event objects may be used with sendTo; use sendTo({ type: "${eventOrExpr}" }) instead`);
84
- }
85
- const resolvedEvent = typeof eventOrExpr === 'function' ? eventOrExpr(args) : eventOrExpr;
86
- let resolvedDelay;
87
- if (typeof delay === 'string') {
88
- const configDelay = delaysMap && delaysMap[delay];
89
- resolvedDelay = typeof configDelay === 'function' ? configDelay(args) : configDelay;
90
- } else {
91
- resolvedDelay = typeof delay === 'function' ? delay(args) : delay;
92
- }
93
- const resolvedTarget = typeof to === 'function' ? to(args) : to;
94
- let targetActorRef;
95
- if (typeof resolvedTarget === 'string') {
96
- if (resolvedTarget === SpecialTargets.Parent) {
97
- targetActorRef = actorContext?.self._parent;
98
- } else if (resolvedTarget === SpecialTargets.Internal) {
99
- targetActorRef = actorContext?.self;
100
- } else if (resolvedTarget.startsWith('#_')) {
101
- // SCXML compatibility: https://www.w3.org/TR/scxml/#SCXMLEventProcessor
102
- // #_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.
103
- targetActorRef = state.children[resolvedTarget.slice(2)];
104
- } else {
105
- targetActorRef = state.children[resolvedTarget];
106
- }
107
- if (!targetActorRef) {
108
- throw new Error(`Unable to send event to actor '${resolvedTarget}' from machine '${state.machine.id}'.`);
109
- }
110
- } else {
111
- targetActorRef = resolvedTarget || actorContext?.self;
112
- }
113
- return [state, {
114
- to: targetActorRef,
115
- event: resolvedEvent,
116
- id,
117
- delay: resolvedDelay
118
- }];
119
- }
120
- function execute$5(actorContext, params) {
121
- if (typeof params.delay === 'number') {
122
- actorContext.self.delaySend(params);
123
- return;
124
- }
125
- const {
126
- to,
127
- event
128
- } = params;
129
- actorContext.defer(() => {
130
- to.send(event.type === error$1 ? {
131
- type: `${error(actorContext.self.id)}`,
132
- data: event.data
133
- } : event);
134
- });
135
- }
136
- /**
137
- * Sends an event to an actor.
138
- *
139
- * @param actor The `ActorRef` to send the event to.
140
- * @param event The event to send, or an expression that evaluates to the event to send
141
- * @param options Send action options
142
- * - `id` - The unique send event identifier (used with `cancel()`).
143
- * - `delay` - The number of milliseconds to delay the sending of the event.
144
- */
145
- function sendTo(to, eventOrExpr, options) {
146
- function sendTo(_) {
147
- {
148
- throw new Error(`This isn't supposed to be called`);
149
- }
150
- }
151
- sendTo.type = 'xstate.sendTo';
152
- sendTo.to = to;
153
- sendTo.event = eventOrExpr;
154
- sendTo.id = options?.id;
155
- sendTo.delay = options?.delay;
156
- sendTo.resolve = resolve$8;
157
- sendTo.execute = execute$5;
158
- return sendTo;
159
- }
160
-
161
- /**
162
- * Sends an event to this machine's parent.
163
- *
164
- * @param event The event to send to the parent machine.
165
- * @param options Options to pass into the send event.
166
- */
167
- function sendParent(event, options) {
168
- return sendTo(SpecialTargets.Parent, event, options);
169
- }
170
- /**
171
- * Forwards (sends) an event to a specified service.
172
- *
173
- * @param target The target service to forward the event to.
174
- * @param options Options to pass into the send action creator.
175
- */
176
- function forwardTo(target, options) {
177
- if ((!target || typeof target === 'function')) {
178
- const originalTarget = target;
179
- target = (...args) => {
180
- const resolvedTarget = typeof originalTarget === 'function' ? originalTarget(...args) : originalTarget;
181
- if (!resolvedTarget) {
182
- throw new Error(`Attempted to forward event to undefined actor. This risks an infinite loop in the sender.`);
183
- }
184
- return resolvedTarget;
185
- };
186
- }
187
- return sendTo(target, ({
188
- event
189
- }) => event, options);
190
- }
191
-
192
- /**
193
- * Escalates an error by sending it as an event to this machine's parent.
194
- *
195
- * @param errorData The error data to send, or the expression function that
196
- * takes in the `context`, `event`, and `meta`, and returns the error data to send.
197
- * @param options Options to pass into the send action creator.
198
- */
199
- function escalate(errorData, options) {
200
- return sendParent(arg => {
201
- return {
202
- type: error$1,
203
- data: typeof errorData === 'function' ? errorData(arg) : errorData
204
- };
205
- }, options);
206
- }
3
+ var interpreter = require('./interpreter-672794ae.cjs.js');
207
4
 
208
5
  const cache = new WeakMap();
209
6
  function memo(object, key, fn) {
@@ -219,13 +16,13 @@ function memo(object, key, fn) {
219
16
  return memoizedData[key];
220
17
  }
221
18
 
222
- function resolve$7(_, state, actionArgs, {
19
+ function resolve$3(_, state, actionArgs, {
223
20
  sendId
224
21
  }) {
225
22
  const resolvedSendId = typeof sendId === 'function' ? sendId(actionArgs) : sendId;
226
23
  return [state, resolvedSendId];
227
24
  }
228
- function execute$4(actorContext, resolvedSendId) {
25
+ function execute$3(actorContext, resolvedSendId) {
229
26
  actorContext.self.cancel(resolvedSendId);
230
27
  }
231
28
  /**
@@ -237,726 +34,26 @@ function execute$4(actorContext, resolvedSendId) {
237
34
  */
238
35
  function cancel(sendId) {
239
36
  function cancel(_) {
240
- {
241
- throw new Error(`This isn't supposed to be called`);
242
- }
243
37
  }
244
38
  cancel.type = 'xstate.cancel';
245
39
  cancel.sendId = sendId;
246
- cancel.resolve = resolve$7;
247
- cancel.execute = execute$4;
40
+ cancel.resolve = resolve$3;
41
+ cancel.execute = execute$3;
248
42
  return cancel;
249
43
  }
250
44
 
251
- class Mailbox {
252
- constructor(_process) {
253
- this._process = _process;
254
- this._active = false;
255
- this._current = null;
256
- this._last = null;
257
- }
258
- start() {
259
- this._active = true;
260
- this.flush();
261
- }
262
- clear() {
263
- // we can't set _current to null because we might be currently processing
264
- // and enqueue following clear shouldnt start processing the enqueued item immediately
265
- if (this._current) {
266
- this._current.next = null;
267
- this._last = this._current;
268
- }
269
- }
270
-
271
- // TODO: rethink this design
272
- prepend(event) {
273
- if (!this._current) {
274
- this.enqueue(event);
275
- return;
276
- }
277
-
278
- // we know that something is already queued up
279
- // so the mailbox is already flushing or it's inactive
280
- // therefore the only thing that we need to do is to reassign `this._current`
281
- this._current = {
282
- value: event,
283
- next: this._current
284
- };
285
- }
286
- enqueue(event) {
287
- const enqueued = {
288
- value: event,
289
- next: null
290
- };
291
- if (this._current) {
292
- this._last.next = enqueued;
293
- this._last = enqueued;
294
- return;
295
- }
296
- this._current = enqueued;
297
- this._last = enqueued;
298
- if (this._active) {
299
- this.flush();
300
- }
301
- }
302
- flush() {
303
- while (this._current) {
304
- // atm the given _process is responsible for implementing proper try/catch handling
305
- // we assume here that this won't throw in a way that can affect this mailbox
306
- const consumed = this._current;
307
- this._process(consumed.value);
308
- // something could have been prepended in the meantime
309
- // so we need to be defensive here to avoid skipping over a prepended item
310
- if (consumed === this._current) {
311
- this._current = this._current.next;
312
- }
313
- }
314
- this._last = null;
315
- }
316
- }
317
-
318
- /**
319
- * This function makes sure that unhandled errors are thrown in a separate macrotask.
320
- * It allows those errors to be detected by global error handlers and reported to bug tracking services
321
- * without interrupting our own stack of execution.
322
- *
323
- * @param err error to be thrown
324
- */
325
- function reportUnhandledError(err) {
326
- setTimeout(() => {
327
- throw err;
328
- });
329
- }
330
-
331
- const symbolObservable = (() => typeof Symbol === 'function' && Symbol.observable || '@@observable')();
332
-
333
- function createSystem() {
334
- let sessionIdCounter = 0;
335
- const children = new Map();
336
- const keyedActors = new Map();
337
- const reverseKeyedActors = new WeakMap();
338
- const system = {
339
- _bookId: () => `x:${sessionIdCounter++}`,
340
- _register: (sessionId, actorRef) => {
341
- children.set(sessionId, actorRef);
342
- return sessionId;
343
- },
344
- _unregister: actorRef => {
345
- children.delete(actorRef.sessionId);
346
- const systemId = reverseKeyedActors.get(actorRef);
347
- if (systemId !== undefined) {
348
- keyedActors.delete(systemId);
349
- reverseKeyedActors.delete(actorRef);
350
- }
351
- },
352
- get: systemId => {
353
- return keyedActors.get(systemId);
354
- },
355
- _set: (systemId, actorRef) => {
356
- const existing = keyedActors.get(systemId);
357
- if (existing && existing !== actorRef) {
358
- throw new Error(`Actor with system ID '${systemId}' already exists.`);
359
- }
360
- keyedActors.set(systemId, actorRef);
361
- reverseKeyedActors.set(actorRef, systemId);
362
- }
363
- };
364
- return system;
365
- }
366
-
367
- function matchesState(parentStateId, childStateId) {
368
- const parentStateValue = toStateValue(parentStateId);
369
- const childStateValue = toStateValue(childStateId);
370
- if (typeof childStateValue === 'string') {
371
- if (typeof parentStateValue === 'string') {
372
- return childStateValue === parentStateValue;
373
- }
374
-
375
- // Parent more specific than child
376
- return false;
377
- }
378
- if (typeof parentStateValue === 'string') {
379
- return parentStateValue in childStateValue;
380
- }
381
- return Object.keys(parentStateValue).every(key => {
382
- if (!(key in childStateValue)) {
383
- return false;
384
- }
385
- return matchesState(parentStateValue[key], childStateValue[key]);
386
- });
387
- }
388
- function toStatePath(stateId) {
389
- try {
390
- if (isArray(stateId)) {
391
- return stateId;
392
- }
393
- return stateId.toString().split(STATE_DELIMITER);
394
- } catch (e) {
395
- throw new Error(`'${stateId}' is not a valid state path.`);
396
- }
397
- }
398
- function isStateLike(state) {
399
- return typeof state === 'object' && 'value' in state && 'context' in state && 'event' in state;
400
- }
401
- function toStateValue(stateValue) {
402
- if (isStateLike(stateValue)) {
403
- return stateValue.value;
404
- }
405
- if (isArray(stateValue)) {
406
- return pathToStateValue(stateValue);
407
- }
408
- if (typeof stateValue !== 'string') {
409
- return stateValue;
410
- }
411
- const statePath = toStatePath(stateValue);
412
- return pathToStateValue(statePath);
413
- }
414
- function pathToStateValue(statePath) {
415
- if (statePath.length === 1) {
416
- return statePath[0];
417
- }
418
- const value = {};
419
- let marker = value;
420
- for (let i = 0; i < statePath.length - 1; i++) {
421
- if (i === statePath.length - 2) {
422
- marker[statePath[i]] = statePath[i + 1];
423
- } else {
424
- const previous = marker;
425
- marker = {};
426
- previous[statePath[i]] = marker;
427
- }
428
- }
429
- return value;
430
- }
431
- function mapValues(collection, iteratee) {
432
- const result = {};
433
- const collectionKeys = Object.keys(collection);
434
- for (let i = 0; i < collectionKeys.length; i++) {
435
- const key = collectionKeys[i];
436
- result[key] = iteratee(collection[key], key, collection, i);
437
- }
438
- return result;
439
- }
440
- function flatten(array) {
441
- return [].concat(...array);
442
- }
443
- function toArrayStrict(value) {
444
- if (isArray(value)) {
445
- return value;
446
- }
447
- return [value];
448
- }
449
- function toArray(value) {
450
- if (value === undefined) {
451
- return [];
452
- }
453
- return toArrayStrict(value);
454
- }
455
- function mapContext(mapper, context, event, self) {
456
- if (typeof mapper === 'function') {
457
- return mapper({
458
- context,
459
- event,
460
- self
461
- });
462
- }
463
- if (typeof mapper === 'object' && Object.values(mapper).some(val => typeof val === 'function')) {
464
- console.warn(`Dynamically mapping values to individual properties is deprecated. Use a single function that returns the mapped object instead.\nFound object containing properties whose values are possibly mapping functions: ${Object.entries(mapper).filter(([key, value]) => typeof value === 'function').map(([key, value]) => `\n - ${key}: ${value.toString().replace(/\n\s*/g, '')}`).join('')}`);
465
- }
466
- return mapper;
467
- }
468
- function isPromiseLike(value) {
469
- if (value instanceof Promise) {
470
- return true;
471
- }
472
- // Check if shape matches the Promise/A+ specification for a "thenable".
473
- if (value !== null && (typeof value === 'function' || typeof value === 'object') && typeof value.then === 'function') {
474
- return true;
475
- }
476
- return false;
477
- }
478
- function isArray(value) {
479
- return Array.isArray(value);
480
- }
481
- function isErrorEvent(event) {
482
- return typeof event.type === 'string' && (event.type === errorExecution || event.type.startsWith(errorPlatform));
483
- }
484
- function toTransitionConfigArray(configLike) {
485
- return toArrayStrict(configLike).map(transitionLike => {
486
- if (typeof transitionLike === 'undefined' || typeof transitionLike === 'string') {
487
- return {
488
- target: transitionLike
489
- };
490
- }
491
- return transitionLike;
492
- });
493
- }
494
- function normalizeTarget(target) {
495
- if (target === undefined || target === TARGETLESS_KEY) {
496
- return undefined;
497
- }
498
- return toArray(target);
499
- }
500
- function toObserver(nextHandler, errorHandler, completionHandler) {
501
- const isObserver = typeof nextHandler === 'object';
502
- const self = isObserver ? nextHandler : undefined;
503
- return {
504
- next: (isObserver ? nextHandler.next : nextHandler)?.bind(self),
505
- error: (isObserver ? nextHandler.error : errorHandler)?.bind(self),
506
- complete: (isObserver ? nextHandler.complete : completionHandler)?.bind(self)
507
- };
508
- }
509
- function createInvokeId(stateNodeId, index) {
510
- return `${stateNodeId}:invocation[${index}]`;
511
- }
512
- function resolveReferencedActor(referenced) {
513
- return referenced ? 'transition' in referenced ? {
514
- src: referenced,
515
- input: undefined
516
- } : referenced : undefined;
517
- }
518
-
519
- let ActorStatus = /*#__PURE__*/function (ActorStatus) {
520
- ActorStatus[ActorStatus["NotStarted"] = 0] = "NotStarted";
521
- ActorStatus[ActorStatus["Running"] = 1] = "Running";
522
- ActorStatus[ActorStatus["Stopped"] = 2] = "Stopped";
523
- return ActorStatus;
524
- }({});
525
-
526
- /**
527
- * @deprecated Use `ActorStatus` instead.
528
- */
529
- const InterpreterStatus = ActorStatus;
530
- const defaultOptions = {
531
- deferEvents: true,
532
- clock: {
533
- setTimeout: (fn, ms) => {
534
- return setTimeout(fn, ms);
535
- },
536
- clearTimeout: id => {
537
- return clearTimeout(id);
538
- }
539
- },
540
- logger: console.log.bind(console),
541
- devTools: false
542
- };
543
- class Actor {
544
- /**
545
- * The current internal state of the actor.
546
- */
547
-
548
- /**
549
- * The clock that is responsible for setting and clearing timeouts, such as delayed events and transitions.
550
- */
551
-
552
- /**
553
- * The unique identifier for this actor relative to its parent.
554
- */
555
-
556
- /**
557
- * Whether the service is started.
558
- */
559
-
560
- // Actor Ref
561
-
562
- // TODO: add typings for system
563
-
564
- /**
565
- * The globally unique process ID for this invocation.
566
- */
567
-
568
- /**
569
- * Creates a new actor instance for the given logic with the provided options, if any.
570
- *
571
- * @param logic The logic to create an actor from
572
- * @param options Actor options
573
- */
574
- constructor(logic, options) {
575
- this.logic = logic;
576
- this._state = void 0;
577
- this.clock = void 0;
578
- this.options = void 0;
579
- this.id = void 0;
580
- this.mailbox = new Mailbox(this._process.bind(this));
581
- this.delayedEventsMap = {};
582
- this.observers = new Set();
583
- this.logger = void 0;
584
- this.status = ActorStatus.NotStarted;
585
- this._parent = void 0;
586
- this.ref = void 0;
587
- this._actorContext = void 0;
588
- this._systemId = void 0;
589
- this.sessionId = void 0;
590
- this.system = void 0;
591
- this._doneEvent = void 0;
592
- this.src = void 0;
593
- this._deferred = [];
594
- const resolvedOptions = {
595
- ...defaultOptions,
596
- ...options
597
- };
598
- const {
599
- clock,
600
- logger,
601
- parent,
602
- id,
603
- systemId
604
- } = resolvedOptions;
605
- const self = this;
606
- this.system = parent?.system ?? createSystem();
607
- if (systemId) {
608
- this._systemId = systemId;
609
- this.system._set(systemId, this);
610
- }
611
- this.sessionId = this.system._bookId();
612
- this.id = id ?? this.sessionId;
613
- this.logger = logger;
614
- this.clock = clock;
615
- this._parent = parent;
616
- this.options = resolvedOptions;
617
- this.src = resolvedOptions.src;
618
- this.ref = this;
619
- this._actorContext = {
620
- self,
621
- id: this.id,
622
- sessionId: this.sessionId,
623
- logger: this.logger,
624
- defer: fn => {
625
- this._deferred.push(fn);
626
- },
627
- system: this.system,
628
- stopChild: child => {
629
- if (child._parent !== this) {
630
- throw new Error(`Cannot stop child actor ${child.id} of ${this.id} because it is not a child`);
631
- }
632
- child._stop();
633
- }
634
- };
635
-
636
- // Ensure that the send method is bound to this Actor instance
637
- // if destructured
638
- this.send = this.send.bind(this);
639
- this._initState();
640
- }
641
- _initState() {
642
- this._state = this.options.state ? this.logic.restoreState ? this.logic.restoreState(this.options.state, this._actorContext) : this.options.state : this.logic.getInitialState(this._actorContext, this.options?.input);
643
- }
644
-
645
- // array of functions to defer
646
-
647
- update(state) {
648
- // Update state
649
- this._state = state;
650
- const snapshot = this.getSnapshot();
651
-
652
- // Execute deferred effects
653
- let deferredFn;
654
- while (deferredFn = this._deferred.shift()) {
655
- deferredFn();
656
- }
657
- for (const observer of this.observers) {
658
- // TODO: should observers be notified in case of the error?
659
- try {
660
- observer.next?.(snapshot);
661
- } catch (err) {
662
- reportUnhandledError(err);
663
- }
664
- }
665
- const status = this.logic.getStatus?.(state);
666
- switch (status?.status) {
667
- case 'done':
668
- this._stopProcedure();
669
- this._complete();
670
- this._doneEvent = doneInvoke(this.id, status.data);
671
- this._parent?.send(this._doneEvent);
672
- break;
673
- case 'error':
674
- this._stopProcedure();
675
- this._error(status.data);
676
- this._parent?.send(error(this.id, status.data));
677
- break;
678
- }
679
- }
680
- subscribe(nextListenerOrObserver, errorListener, completeListener) {
681
- const observer = toObserver(nextListenerOrObserver, errorListener, completeListener);
682
- if (this.status !== ActorStatus.Stopped) {
683
- this.observers.add(observer);
684
- } else {
685
- try {
686
- observer.complete?.();
687
- } catch (err) {
688
- reportUnhandledError(err);
689
- }
690
- }
691
- return {
692
- unsubscribe: () => {
693
- this.observers.delete(observer);
694
- }
695
- };
696
- }
697
-
698
- /**
699
- * Starts the Actor from the initial state
700
- */
701
- start() {
702
- if (this.status === ActorStatus.Running) {
703
- // Do not restart the service if it is already started
704
- return this;
705
- }
706
- this.system._register(this.sessionId, this);
707
- if (this._systemId) {
708
- this.system._set(this._systemId, this);
709
- }
710
- this.status = ActorStatus.Running;
711
- const status = this.logic.getStatus?.(this._state);
712
- switch (status?.status) {
713
- case 'done':
714
- // a state machine can be "done" upon intialization (it could reach a final state using initial microsteps)
715
- // we still need to complete observers, flush deferreds etc
716
- this.update(this._state);
717
- // fallthrough
718
- case 'error':
719
- // TODO: rethink cleanup of observers, mailbox, etc
720
- return this;
721
- }
722
- if (this.logic.start) {
723
- try {
724
- this.logic.start(this._state, this._actorContext);
725
- } catch (err) {
726
- this._stopProcedure();
727
- this._error(err);
728
- this._parent?.send(error(this.id, err));
729
- return this;
730
- }
731
- }
732
-
733
- // TODO: this notifies all subscribers but usually this is redundant
734
- // there is no real change happening here
735
- // we need to rethink if this needs to be refactored
736
- this.update(this._state);
737
- if (this.options.devTools) {
738
- this.attachDevTools();
739
- }
740
- this.mailbox.start();
741
- return this;
742
- }
743
- _process(event) {
744
- // TODO: reexamine what happens when an action (or a guard or smth) throws
745
- let nextState;
746
- let caughtError;
747
- try {
748
- nextState = this.logic.transition(this._state, event, this._actorContext);
749
- } catch (err) {
750
- // we wrap it in a box so we can rethrow it later even if falsy value gets caught here
751
- caughtError = {
752
- err
753
- };
754
- }
755
- if (caughtError) {
756
- const {
757
- err
758
- } = caughtError;
759
- this._stopProcedure();
760
- this._error(err);
761
- this._parent?.send(error(this.id, err));
762
- return;
763
- }
764
- this.update(nextState);
765
- if (event.type === XSTATE_STOP) {
766
- this._stopProcedure();
767
- this._complete();
768
- }
769
- }
770
- _stop() {
771
- if (this.status === ActorStatus.Stopped) {
772
- return this;
773
- }
774
- this.mailbox.clear();
775
- if (this.status === ActorStatus.NotStarted) {
776
- this.status = ActorStatus.Stopped;
777
- return this;
778
- }
779
- this.mailbox.enqueue({
780
- type: XSTATE_STOP
781
- });
782
- return this;
783
- }
784
-
785
- /**
786
- * Stops the Actor and unsubscribe all listeners.
787
- */
788
- stop() {
789
- if (this._parent) {
790
- throw new Error('A non-root actor cannot be stopped directly.');
791
- }
792
- return this._stop();
793
- }
794
- _complete() {
795
- for (const observer of this.observers) {
796
- try {
797
- observer.complete?.();
798
- } catch (err) {
799
- reportUnhandledError(err);
800
- }
801
- }
802
- this.observers.clear();
803
- }
804
- _error(err) {
805
- if (!this.observers.size) {
806
- if (!this._parent) {
807
- reportUnhandledError(err);
808
- }
809
- return;
810
- }
811
- let reportError = false;
812
- for (const observer of this.observers) {
813
- const errorListener = observer.error;
814
- reportError ||= !errorListener;
815
- try {
816
- errorListener?.(err);
817
- } catch (err2) {
818
- reportUnhandledError(err2);
819
- }
820
- }
821
- this.observers.clear();
822
- if (reportError) {
823
- reportUnhandledError(err);
824
- }
825
- }
826
- _stopProcedure() {
827
- if (this.status !== ActorStatus.Running) {
828
- // Actor already stopped; do nothing
829
- return this;
830
- }
831
-
832
- // Cancel all delayed events
833
- for (const key of Object.keys(this.delayedEventsMap)) {
834
- this.clock.clearTimeout(this.delayedEventsMap[key]);
835
- }
836
-
837
- // TODO: mailbox.reset
838
- this.mailbox.clear();
839
- // TODO: after `stop` we must prepare ourselves for receiving events again
840
- // events sent *after* stop signal must be queued
841
- // it seems like this should be the common behavior for all of our consumers
842
- // so perhaps this should be unified somehow for all of them
843
- this.mailbox = new Mailbox(this._process.bind(this));
844
- this.status = ActorStatus.Stopped;
845
- this.system._unregister(this);
846
- return this;
847
- }
848
-
849
- /**
850
- * Sends an event to the running Actor to trigger a transition.
851
- *
852
- * @param event The event to send
853
- */
854
- send(event) {
855
- if (typeof event === 'string') {
856
- throw new Error(`Only event objects may be sent to actors; use .send({ type: "${event}" }) instead`);
857
- }
858
- if (this.status === ActorStatus.Stopped) {
859
- // do nothing
860
- {
861
- const eventString = JSON.stringify(event);
862
- 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}`);
863
- }
864
- return;
865
- }
866
- if (this.status !== ActorStatus.Running && !this.options.deferEvents) {
867
- throw new Error(`Event "${event.type}" was sent to uninitialized actor "${this.id
868
- // tslint:disable-next-line:max-line-length
869
- }". Make sure .start() is called for this actor, or set { deferEvents: true } in the actor options.\nEvent: ${JSON.stringify(event)}`);
870
- }
871
- this.mailbox.enqueue(event);
872
- }
873
-
874
- // TODO: make private (and figure out a way to do this within the machine)
875
- delaySend({
876
- event,
877
- id,
878
- delay,
879
- to
880
- }) {
881
- const timerId = this.clock.setTimeout(() => {
882
- if (to) {
883
- to.send(event);
884
- } else {
885
- this.send(event);
886
- }
887
- }, delay);
888
-
889
- // TODO: consider the rehydration story here
890
- if (id) {
891
- this.delayedEventsMap[id] = timerId;
892
- }
893
- }
894
-
895
- // TODO: make private (and figure out a way to do this within the machine)
896
- cancel(sendId) {
897
- this.clock.clearTimeout(this.delayedEventsMap[sendId]);
898
- delete this.delayedEventsMap[sendId];
899
- }
900
- attachDevTools() {
901
- const {
902
- devTools
903
- } = this.options;
904
- if (devTools) {
905
- const resolvedDevToolsAdapter = typeof devTools === 'function' ? devTools : devToolsAdapter;
906
- resolvedDevToolsAdapter(this);
907
- }
908
- }
909
- toJSON() {
910
- return {
911
- id: this.id
912
- };
913
- }
914
- getPersistedState() {
915
- return this.logic.getPersistedState?.(this._state);
916
- }
917
- [symbolObservable]() {
918
- return this;
919
- }
920
- getSnapshot() {
921
- return this.logic.getSnapshot ? this.logic.getSnapshot(this._state) : this._state;
922
- }
923
- }
924
-
925
- /**
926
- * Creates a new `ActorRef` instance for the given machine with the provided options, if any.
927
- *
928
- * @param machine The machine to create an actor from
929
- * @param options `ActorRef` options
930
- */
931
-
932
- function createActor(logic, options) {
933
- const interpreter = new Actor(logic, options);
934
- return interpreter;
935
- }
936
-
937
- /**
938
- * Creates a new Interpreter instance for the given machine with the provided options, if any.
939
- *
940
- * @deprecated Use `createActor` instead
941
- */
942
- const interpret = createActor;
943
-
944
- /**
945
- * @deprecated Use `Actor` instead.
946
- */
947
-
948
- function resolve$6(actorContext, state, actionArgs, {
45
+ function resolve$2(actorContext, state, actionArgs, {
949
46
  id,
950
47
  systemId,
951
48
  src,
952
49
  input
953
50
  }) {
954
- const referenced = resolveReferencedActor(state.machine.implementations.actors[src]);
51
+ const referenced = interpreter.resolveReferencedActor(state.machine.implementations.actors[src]);
955
52
  let actorRef;
956
53
  if (referenced) {
957
54
  // TODO: inline `input: undefined` should win over the referenced one
958
55
  const configuredInput = input || referenced.input;
959
- actorRef = createActor(referenced.src, {
56
+ actorRef = interpreter.createActor(referenced.src, {
960
57
  id,
961
58
  src,
962
59
  parent: actorContext?.self,
@@ -968,9 +65,6 @@ function resolve$6(actorContext, state, actionArgs, {
968
65
  }) : configuredInput
969
66
  });
970
67
  }
971
- if (!actorRef) {
972
- console.warn(`Actor type '${src}' not found in machine '${actorContext.id}'.`);
973
- }
974
68
  return [cloneState(state, {
975
69
  children: {
976
70
  ...state.children,
@@ -981,7 +75,7 @@ function resolve$6(actorContext, state, actionArgs, {
981
75
  actorRef
982
76
  }];
983
77
  }
984
- function execute$3(actorContext, {
78
+ function execute$2(actorContext, {
985
79
  id,
986
80
  actorRef
987
81
  }) {
@@ -989,13 +83,13 @@ function execute$3(actorContext, {
989
83
  return;
990
84
  }
991
85
  actorContext.defer(() => {
992
- if (actorRef.status === ActorStatus.Stopped) {
86
+ if (actorRef.status === interpreter.ActorStatus.Stopped) {
993
87
  return;
994
88
  }
995
89
  try {
996
90
  actorRef.start?.();
997
91
  } catch (err) {
998
- actorContext.self.send(error(id, err));
92
+ actorContext.self.send(interpreter.createErrorActorEvent(id, err));
999
93
  return;
1000
94
  }
1001
95
  });
@@ -1010,20 +104,61 @@ function invoke({
1010
104
  input
1011
105
  }) {
1012
106
  function invoke(_) {
1013
- {
1014
- throw new Error(`This isn't supposed to be called`);
1015
- }
1016
107
  }
1017
108
  invoke.type = 'xstate.invoke';
1018
109
  invoke.id = id;
1019
110
  invoke.systemId = systemId;
1020
111
  invoke.src = src;
1021
112
  invoke.input = input;
1022
- invoke.resolve = resolve$6;
1023
- invoke.execute = execute$3;
113
+ invoke.resolve = resolve$2;
114
+ invoke.execute = execute$2;
1024
115
  return invoke;
1025
116
  }
1026
117
 
118
+ function resolve$1(_, state, args, {
119
+ actorRef
120
+ }) {
121
+ const actorRefOrString = typeof actorRef === 'function' ? actorRef(args) : actorRef;
122
+ const resolvedActorRef = typeof actorRefOrString === 'string' ? state.children[actorRefOrString] : actorRefOrString;
123
+ let children = state.children;
124
+ if (resolvedActorRef) {
125
+ children = {
126
+ ...children
127
+ };
128
+ delete children[resolvedActorRef.id];
129
+ }
130
+ return [cloneState(state, {
131
+ children
132
+ }), resolvedActorRef];
133
+ }
134
+ function execute$1(actorContext, actorRef) {
135
+ if (!actorRef) {
136
+ return;
137
+ }
138
+ if (actorRef.status !== interpreter.ActorStatus.Running) {
139
+ actorContext.stopChild(actorRef);
140
+ return;
141
+ }
142
+ // TODO: recheck why this one has to be deferred
143
+ actorContext.defer(() => {
144
+ actorContext.stopChild(actorRef);
145
+ });
146
+ }
147
+ /**
148
+ * Stops an actor.
149
+ *
150
+ * @param actorRef The actor to stop.
151
+ */
152
+ function stop(actorRef) {
153
+ function stop(_) {
154
+ }
155
+ stop.type = 'xstate.stop';
156
+ stop.actorRef = actorRef;
157
+ stop.resolve = resolve$1;
158
+ stop.execute = execute$1;
159
+ return stop;
160
+ }
161
+
1027
162
  function checkStateIn(state, _, {
1028
163
  stateValue
1029
164
  }) {
@@ -1034,9 +169,7 @@ function checkStateIn(state, _, {
1034
169
  }
1035
170
  function stateIn(stateValue) {
1036
171
  function stateIn(_) {
1037
- {
1038
- throw new Error(`This isn't supposed to be called`);
1039
- }
172
+ return false;
1040
173
  }
1041
174
  stateIn.check = checkStateIn;
1042
175
  stateIn.stateValue = stateValue;
@@ -1052,9 +185,7 @@ function checkNot(state, {
1052
185
  }
1053
186
  function not(guard) {
1054
187
  function not(_) {
1055
- {
1056
- throw new Error(`This isn't supposed to be called`);
1057
- }
188
+ return false;
1058
189
  }
1059
190
  not.check = checkNot;
1060
191
  not.guards = [guard];
@@ -1070,9 +201,7 @@ function checkAnd(state, {
1070
201
  }
1071
202
  function and(guards) {
1072
203
  function and(_) {
1073
- {
1074
- throw new Error(`This isn't supposed to be called`);
1075
- }
204
+ return false;
1076
205
  }
1077
206
  and.check = checkAnd;
1078
207
  and.guards = guards;
@@ -1088,9 +217,7 @@ function checkOr(state, {
1088
217
  }
1089
218
  function or(guards) {
1090
219
  function or(_) {
1091
- {
1092
- throw new Error(`This isn't supposed to be called`);
1093
- }
220
+ return false;
1094
221
  }
1095
222
  or.check = checkOr;
1096
223
  or.guards = guards;
@@ -1137,7 +264,7 @@ function evaluateGuard(guard, context, event, state) {
1137
264
  function getOutput(configuration, context, event, self) {
1138
265
  const machine = configuration[0].machine;
1139
266
  const finalChildStateNode = configuration.find(stateNode => stateNode.type === 'final' && stateNode.parent === machine.root);
1140
- return finalChildStateNode && finalChildStateNode.output ? mapContext(finalChildStateNode.output, context, event, self) : undefined;
267
+ return finalChildStateNode && finalChildStateNode.output ? interpreter.mapContext(finalChildStateNode.output, context, event, self) : undefined;
1141
268
  }
1142
269
  const isAtomicStateNode = stateNode => stateNode.type === 'atomic' || stateNode.type === 'final';
1143
270
  function getChildren(stateNode) {
@@ -1240,20 +367,17 @@ function isInFinalState(configuration, stateNode = configuration[0].machine.root
1240
367
  }
1241
368
  return false;
1242
369
  }
1243
- const isStateId = str => str[0] === STATE_IDENTIFIER;
370
+ const isStateId = str => str[0] === interpreter.STATE_IDENTIFIER;
1244
371
  function getCandidates(stateNode, receivedEventType) {
1245
372
  const candidates = stateNode.transitions.get(receivedEventType) || [...stateNode.transitions.keys()].filter(descriptor => {
1246
373
  // check if transition is a wildcard transition,
1247
374
  // which matches any non-transient events
1248
- if (descriptor === WILDCARD) {
375
+ if (descriptor === interpreter.WILDCARD) {
1249
376
  return true;
1250
377
  }
1251
378
  if (!descriptor.endsWith('.*')) {
1252
379
  return false;
1253
380
  }
1254
- if (/.*\*.+/.test(descriptor)) {
1255
- console.warn(`Wildcards can only be the last token of an event descriptor (e.g., "event.*") or the entire event descriptor ("*"). Check the "${descriptor}" event.`);
1256
- }
1257
381
  const partialEventTokens = descriptor.split('.');
1258
382
  const eventTokens = receivedEventType.split('.');
1259
383
  for (let tokenIndex = 0; tokenIndex < partialEventTokens.length; tokenIndex++) {
@@ -1261,9 +385,6 @@ function getCandidates(stateNode, receivedEventType) {
1261
385
  const eventToken = eventTokens[tokenIndex];
1262
386
  if (partialEventToken === '*') {
1263
387
  const isLastToken = tokenIndex === partialEventTokens.length - 1;
1264
- if (!isLastToken) {
1265
- console.warn(`Infix wildcards in transition events are not allowed. Check the "${descriptor}" transition.`);
1266
- }
1267
388
  return isLastToken;
1268
389
  }
1269
390
  if (partialEventToken !== eventToken) {
@@ -1285,17 +406,16 @@ function getDelayedTransitions(stateNode) {
1285
406
  }
1286
407
  const mutateEntryExit = (delay, i) => {
1287
408
  const delayRef = typeof delay === 'function' ? `${stateNode.id}:delay[${i}]` : delay;
1288
- const eventType = after(delayRef, stateNode.id);
1289
- stateNode.entry.push(raise({
1290
- type: eventType
1291
- }, {
409
+ const afterEvent = interpreter.createAfterEvent(delayRef, stateNode.id);
410
+ const eventType = afterEvent.type;
411
+ stateNode.entry.push(raise(afterEvent, {
1292
412
  id: eventType,
1293
413
  delay
1294
414
  }));
1295
415
  stateNode.exit.push(cancel(eventType));
1296
416
  return eventType;
1297
417
  };
1298
- const delayedTransitions = isArray(afterConfig) ? afterConfig.map((transition, i) => {
418
+ const delayedTransitions = interpreter.isArray(afterConfig) ? afterConfig.map((transition, i) => {
1299
419
  const eventType = mutateEntryExit(transition.delay, i);
1300
420
  return {
1301
421
  ...transition,
@@ -1308,7 +428,7 @@ function getDelayedTransitions(stateNode) {
1308
428
  } : configTransition;
1309
429
  const resolvedDelay = !isNaN(+delay) ? +delay : delay;
1310
430
  const eventType = mutateEntryExit(resolvedDelay, i);
1311
- return toArray(resolvedTransition).map(transition => ({
431
+ return interpreter.toArray(resolvedTransition).map(transition => ({
1312
432
  ...transition,
1313
433
  event: eventType,
1314
434
  delay: resolvedDelay
@@ -1325,17 +445,12 @@ function getDelayedTransitions(stateNode) {
1325
445
  });
1326
446
  }
1327
447
  function formatTransition(stateNode, descriptor, transitionConfig) {
1328
- const normalizedTarget = normalizeTarget(transitionConfig.target);
448
+ const normalizedTarget = interpreter.normalizeTarget(transitionConfig.target);
1329
449
  const reenter = transitionConfig.reenter ?? false;
1330
450
  const target = resolveTarget(stateNode, normalizedTarget);
1331
-
1332
- // TODO: should this be part of a lint rule instead?
1333
- if (transitionConfig.cond) {
1334
- 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.`);
1335
- }
1336
451
  const transition = {
1337
452
  ...transitionConfig,
1338
- actions: toArray(transitionConfig.actions),
453
+ actions: interpreter.toArray(transitionConfig.actions),
1339
454
  guard: transitionConfig.guard,
1340
455
  target,
1341
456
  source: stateNode,
@@ -1353,29 +468,29 @@ function formatTransitions(stateNode) {
1353
468
  const transitions = new Map();
1354
469
  if (stateNode.config.on) {
1355
470
  for (const descriptor of Object.keys(stateNode.config.on)) {
1356
- if (descriptor === NULL_EVENT) {
471
+ if (descriptor === interpreter.NULL_EVENT) {
1357
472
  throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');
1358
473
  }
1359
474
  const transitionsConfig = stateNode.config.on[descriptor];
1360
- transitions.set(descriptor, toTransitionConfigArray(transitionsConfig).map(t => formatTransition(stateNode, descriptor, t)));
475
+ transitions.set(descriptor, interpreter.toTransitionConfigArray(transitionsConfig).map(t => formatTransition(stateNode, descriptor, t)));
1361
476
  }
1362
477
  }
1363
478
  if (stateNode.config.onDone) {
1364
- const descriptor = String(done(stateNode.id));
1365
- transitions.set(descriptor, toTransitionConfigArray(stateNode.config.onDone).map(t => formatTransition(stateNode, descriptor, t)));
479
+ const descriptor = `xstate.done.state.${stateNode.id}`;
480
+ transitions.set(descriptor, interpreter.toTransitionConfigArray(stateNode.config.onDone).map(t => formatTransition(stateNode, descriptor, t)));
1366
481
  }
1367
482
  for (const invokeDef of stateNode.invoke) {
1368
483
  if (invokeDef.onDone) {
1369
- const descriptor = `done.invoke.${invokeDef.id}`;
1370
- transitions.set(descriptor, toTransitionConfigArray(invokeDef.onDone).map(t => formatTransition(stateNode, descriptor, t)));
484
+ const descriptor = `xstate.done.actor.${invokeDef.id}`;
485
+ transitions.set(descriptor, interpreter.toTransitionConfigArray(invokeDef.onDone).map(t => formatTransition(stateNode, descriptor, t)));
1371
486
  }
1372
487
  if (invokeDef.onError) {
1373
- const descriptor = `error.platform.${invokeDef.id}`;
1374
- transitions.set(descriptor, toTransitionConfigArray(invokeDef.onError).map(t => formatTransition(stateNode, descriptor, t)));
488
+ const descriptor = `xstate.error.actor.${invokeDef.id}`;
489
+ transitions.set(descriptor, interpreter.toTransitionConfigArray(invokeDef.onError).map(t => formatTransition(stateNode, descriptor, t)));
1375
490
  }
1376
491
  if (invokeDef.onSnapshot) {
1377
492
  const descriptor = `xstate.snapshot.${invokeDef.id}`;
1378
- transitions.set(descriptor, toTransitionConfigArray(invokeDef.onSnapshot).map(t => formatTransition(stateNode, descriptor, t)));
493
+ transitions.set(descriptor, interpreter.toTransitionConfigArray(invokeDef.onSnapshot).map(t => formatTransition(stateNode, descriptor, t)));
1379
494
  }
1380
495
  }
1381
496
  for (const delayedTransition of stateNode.after) {
@@ -1389,8 +504,8 @@ function formatTransitions(stateNode) {
1389
504
  return transitions;
1390
505
  }
1391
506
  function formatInitialTransition(stateNode, _target) {
1392
- if (typeof _target === 'string' || isArray(_target)) {
1393
- const targets = toArray(_target).map(t => {
507
+ if (typeof _target === 'string' || interpreter.isArray(_target)) {
508
+ const targets = interpreter.toArray(_target).map(t => {
1394
509
  // Resolve state string keys (which represent children)
1395
510
  // to their state node
1396
511
  const descStateNode = typeof t === 'string' ? isStateId(t) ? stateNode.machine.getStateNodeById(t) : stateNode.states[t] : t;
@@ -1418,9 +533,9 @@ function formatInitialTransition(stateNode, _target) {
1418
533
  return transition;
1419
534
  }
1420
535
  return formatTransition(stateNode, '__INITIAL__', {
1421
- target: toArray(_target.target).map(t => {
536
+ target: interpreter.toArray(_target.target).map(t => {
1422
537
  if (typeof t === 'string') {
1423
- return isStateId(t) ? t : `${STATE_DELIMITER}${t}`;
538
+ return isStateId(t) ? t : `${interpreter.STATE_DELIMITER}${t}`;
1424
539
  }
1425
540
  return t;
1426
541
  }),
@@ -1439,7 +554,7 @@ function resolveTarget(stateNode, targets) {
1439
554
  if (isStateId(target)) {
1440
555
  return stateNode.machine.getStateNodeById(target);
1441
556
  }
1442
- const isInternalTarget = target[0] === STATE_DELIMITER;
557
+ const isInternalTarget = target[0] === interpreter.STATE_DELIMITER;
1443
558
  // If internal target is defined on machine,
1444
559
  // do not include machine key on target
1445
560
  if (isInternalTarget && !stateNode.parent) {
@@ -1459,7 +574,7 @@ function resolveTarget(stateNode, targets) {
1459
574
  });
1460
575
  }
1461
576
  function resolveHistoryTarget(stateNode) {
1462
- const normalizedTarget = normalizeTarget(stateNode.config.target);
577
+ const normalizedTarget = interpreter.normalizeTarget(stateNode.config.target);
1463
578
  if (!normalizedTarget) {
1464
579
  return stateNode.parent.initial.target;
1465
580
  }
@@ -1522,7 +637,7 @@ function getStateNodeByPath(stateNode, statePath) {
1522
637
  // throw e;
1523
638
  }
1524
639
  }
1525
- const arrayStatePath = toStatePath(statePath).slice();
640
+ const arrayStatePath = interpreter.toStatePath(statePath).slice();
1526
641
  let currentStateNode = stateNode;
1527
642
  while (arrayStatePath.length) {
1528
643
  const key = arrayStatePath.shift();
@@ -1540,7 +655,7 @@ function getStateNodeByPath(stateNode, statePath) {
1540
655
  * @param state The state value or State instance
1541
656
  */
1542
657
  function getStateNodes(stateNode, state) {
1543
- const stateValue = state instanceof State ? state.value : toStateValue(state);
658
+ const stateValue = state instanceof State ? state.value : interpreter.toStateValue(state);
1544
659
  if (typeof stateValue === 'string') {
1545
660
  return [stateNode, stateNode.states[stateValue]];
1546
661
  }
@@ -1815,12 +930,12 @@ function enterStates(event, filteredTransitions, mutConfiguration, actions, inte
1815
930
  if (!parent.parent) {
1816
931
  continue;
1817
932
  }
1818
- internalQueue.push(done(parent.id, stateNodeToEnter.output ? mapContext(stateNodeToEnter.output, currentState.context, event, actorContext.self) : undefined));
933
+ internalQueue.push(interpreter.createDoneStateEvent(parent.id, stateNodeToEnter.output ? interpreter.mapContext(stateNodeToEnter.output, currentState.context, event, actorContext.self) : undefined));
1819
934
  if (parent.parent) {
1820
935
  const grandparent = parent.parent;
1821
936
  if (grandparent.type === 'parallel') {
1822
937
  if (getChildren(grandparent).every(parentNode => isInFinalState([...mutConfiguration], parentNode))) {
1823
- internalQueue.push(done(grandparent.id));
938
+ internalQueue.push(interpreter.createDoneStateEvent(grandparent.id));
1824
939
  }
1825
940
  }
1826
941
  }
@@ -1959,7 +1074,7 @@ function resolveActionsAndContext(actions, event, currentState, actorCtx) {
1959
1074
  action
1960
1075
  };
1961
1076
  if (!('resolve' in resolved)) {
1962
- if (actorCtx?.self.status === ActorStatus.Running) {
1077
+ if (actorCtx?.self.status === interpreter.ActorStatus.Running) {
1963
1078
  resolved(actionArgs);
1964
1079
  } else {
1965
1080
  actorCtx?.defer(() => resolved(actionArgs));
@@ -1972,7 +1087,7 @@ function resolveActionsAndContext(actions, event, currentState, actorCtx) {
1972
1087
 
1973
1088
  intermediateState = nextState;
1974
1089
  if ('execute' in resolved) {
1975
- if (actorCtx?.self.status === ActorStatus.Running) {
1090
+ if (actorCtx?.self.status === interpreter.ActorStatus.Running) {
1976
1091
  builtinAction.execute(actorCtx, params);
1977
1092
  } else {
1978
1093
  actorCtx?.defer(builtinAction.execute.bind(null, actorCtx, params));
@@ -1985,14 +1100,11 @@ function resolveActionsAndContext(actions, event, currentState, actorCtx) {
1985
1100
  return intermediateState;
1986
1101
  }
1987
1102
  function macrostep(state, event, actorCtx) {
1988
- if (event.type === WILDCARD) {
1989
- throw new Error(`An event cannot have the wildcard type ('${WILDCARD}')`);
1990
- }
1991
1103
  let nextState = state;
1992
1104
  const states = [];
1993
1105
 
1994
1106
  // Handle stop event
1995
- if (event.type === XSTATE_STOP) {
1107
+ if (event.type === interpreter.XSTATE_STOP) {
1996
1108
  nextState = stopStep(event, nextState, actorCtx);
1997
1109
  states.push(nextState);
1998
1110
  return {
@@ -2004,7 +1116,7 @@ function macrostep(state, event, actorCtx) {
2004
1116
 
2005
1117
  // Assume the state is at rest (no raised events)
2006
1118
  // Determine the next state based on the next microstep
2007
- if (nextEvent.type !== XSTATE_INIT) {
1119
+ if (nextEvent.type !== interpreter.XSTATE_INIT) {
2008
1120
  const transitions = selectTransitions(nextEvent, nextState);
2009
1121
  nextState = microstep(transitions, state, actorCtx, nextEvent, false);
2010
1122
  states.push(nextState);
@@ -2159,7 +1271,7 @@ class State {
2159
1271
  this.configuration = config.configuration ?? Array.from(getConfiguration(getStateNodes(machine.root, config.value)));
2160
1272
  this.children = config.children;
2161
1273
  this.value = getStateValue(machine.root, this.configuration);
2162
- this.tags = new Set(flatten(this.configuration.map(sn => sn.tags)));
1274
+ this.tags = new Set(interpreter.flatten(this.configuration.map(sn => sn.tags)));
2163
1275
  this.done = config.done ?? false;
2164
1276
  this.output = config.output;
2165
1277
  this.error = config.error;
@@ -2175,7 +1287,7 @@ class State {
2175
1287
  return [stateValue];
2176
1288
  }
2177
1289
  const valueKeys = Object.keys(stateValue);
2178
- return valueKeys.concat(...valueKeys.map(key => this.toStrings(stateValue[key]).map(s => key + STATE_DELIMITER + s)));
1290
+ return valueKeys.concat(...valueKeys.map(key => this.toStrings(stateValue[key]).map(s => key + interpreter.STATE_DELIMITER + s)));
2179
1291
  }
2180
1292
  toJSON() {
2181
1293
  const {
@@ -2196,7 +1308,7 @@ class State {
2196
1308
  * @param parentStateValue
2197
1309
  */
2198
1310
  matches(parentStateValue) {
2199
- return matchesState(parentStateValue, this.value);
1311
+ return interpreter.matchesState(parentStateValue, this.value);
2200
1312
  }
2201
1313
 
2202
1314
  /**
@@ -2216,9 +1328,6 @@ class State {
2216
1328
  * @returns Whether the event will cause a transition
2217
1329
  */
2218
1330
  can(event) {
2219
- if (!this.machine) {
2220
- console.warn(`state.can(...) used outside of a machine-created State object; this will always return false.`);
2221
- }
2222
1331
  const transitionData = this.machine.getTransitionData(this, event);
2223
1332
  return !!transitionData?.length &&
2224
1333
  // Check that at least one transition is not forbidden
@@ -2230,7 +1339,7 @@ class State {
2230
1339
  */
2231
1340
  get nextEvents() {
2232
1341
  return memo(this, 'nextEvents', () => {
2233
- return [...new Set(flatten([...this.configuration.map(sn => sn.ownEvents)]))];
1342
+ return [...new Set(interpreter.flatten([...this.configuration.map(sn => sn.ownEvents)]))];
2234
1343
  });
2235
1344
  }
2236
1345
  get meta() {
@@ -2269,209 +1378,7 @@ function getPersistedState(state) {
2269
1378
  };
2270
1379
  }
2271
1380
 
2272
- function resolve$5(_, state, args, {
2273
- actorRef
2274
- }) {
2275
- const actorRefOrString = typeof actorRef === 'function' ? actorRef(args) : actorRef;
2276
- const resolvedActorRef = typeof actorRefOrString === 'string' ? state.children[actorRefOrString] : actorRefOrString;
2277
- let children = state.children;
2278
- if (resolvedActorRef) {
2279
- children = {
2280
- ...children
2281
- };
2282
- delete children[resolvedActorRef.id];
2283
- }
2284
- return [cloneState(state, {
2285
- children
2286
- }), resolvedActorRef];
2287
- }
2288
- function execute$2(actorContext, actorRef) {
2289
- if (!actorRef) {
2290
- return;
2291
- }
2292
- if (actorRef.status !== ActorStatus.Running) {
2293
- actorContext.stopChild(actorRef);
2294
- return;
2295
- }
2296
- // TODO: recheck why this one has to be deferred
2297
- actorContext.defer(() => {
2298
- actorContext.stopChild(actorRef);
2299
- });
2300
- }
2301
- /**
2302
- * Stops an actor.
2303
- *
2304
- * @param actorRef The actor to stop.
2305
- */
2306
- function stop(actorRef) {
2307
- function stop(_) {
2308
- {
2309
- throw new Error(`This isn't supposed to be called`);
2310
- }
2311
- }
2312
- stop.type = 'xstate.stop';
2313
- stop.actorRef = actorRef;
2314
- stop.resolve = resolve$5;
2315
- stop.execute = execute$2;
2316
- return stop;
2317
- }
2318
-
2319
- function resolve$4(_, state, actionArgs, {
2320
- value,
2321
- label
2322
- }) {
2323
- return [state, {
2324
- value: typeof value === 'function' ? value(actionArgs) : value,
2325
- label
2326
- }];
2327
- }
2328
- function execute$1({
2329
- logger
2330
- }, {
2331
- value,
2332
- label
2333
- }) {
2334
- if (label) {
2335
- logger(label, value);
2336
- } else {
2337
- logger(value);
2338
- }
2339
- }
2340
- /**
2341
- *
2342
- * @param expr The expression function to evaluate which will be logged.
2343
- * Takes in 2 arguments:
2344
- * - `ctx` - the current state context
2345
- * - `event` - the event that caused this action to be executed.
2346
- * @param label The label to give to the logged expression.
2347
- */
2348
- function log(value = ({
2349
- context,
2350
- event
2351
- }) => ({
2352
- context,
2353
- event
2354
- }), label) {
2355
- function log(_) {
2356
- {
2357
- throw new Error(`This isn't supposed to be called`);
2358
- }
2359
- }
2360
- log.type = 'xstate.log';
2361
- log.value = value;
2362
- log.label = label;
2363
- log.resolve = resolve$4;
2364
- log.execute = execute$1;
2365
- return log;
2366
- }
2367
-
2368
- function createSpawner(actorContext, {
2369
- machine,
2370
- context
2371
- }, event, spawnedChildren) {
2372
- const spawn = (src, options = {}) => {
2373
- const {
2374
- systemId
2375
- } = options;
2376
- if (typeof src === 'string') {
2377
- const referenced = resolveReferencedActor(machine.implementations.actors[src]);
2378
- if (!referenced) {
2379
- throw new Error(`Actor logic '${src}' not implemented in machine '${machine.id}'`);
2380
- }
2381
- const input = 'input' in options ? options.input : referenced.input;
2382
-
2383
- // TODO: this should also receive `src`
2384
- const actor = createActor(referenced.src, {
2385
- id: options.id,
2386
- parent: actorContext.self,
2387
- input: typeof input === 'function' ? input({
2388
- context,
2389
- event,
2390
- self: actorContext.self
2391
- }) : input,
2392
- systemId
2393
- });
2394
- spawnedChildren[actor.id] = actor;
2395
- return actor;
2396
- } else {
2397
- // TODO: this should also receive `src`
2398
- return createActor(src, {
2399
- id: options.id,
2400
- parent: actorContext.self,
2401
- input: options.input,
2402
- systemId
2403
- });
2404
- }
2405
- };
2406
- return (src, options) => {
2407
- const actorRef = spawn(src, options); // TODO: fix types
2408
- spawnedChildren[actorRef.id] = actorRef;
2409
- actorContext.defer(() => {
2410
- if (actorRef.status === ActorStatus.Stopped) {
2411
- return;
2412
- }
2413
- try {
2414
- actorRef.start?.();
2415
- } catch (err) {
2416
- actorContext.self.send(error(actorRef.id, err));
2417
- return;
2418
- }
2419
- });
2420
- return actorRef;
2421
- };
2422
- }
2423
-
2424
- function resolve$3(actorContext, state, actionArgs, {
2425
- assignment
2426
- }) {
2427
- if (!state.context) {
2428
- throw new Error('Cannot assign to undefined `context`. Ensure that `context` is defined in the machine config.');
2429
- }
2430
- const spawnedChildren = {};
2431
- const assignArgs = {
2432
- context: state.context,
2433
- event: actionArgs.event,
2434
- action: actionArgs.action,
2435
- spawn: createSpawner(actorContext, state, actionArgs.event, spawnedChildren),
2436
- self: actorContext?.self,
2437
- system: actorContext?.system
2438
- };
2439
- let partialUpdate = {};
2440
- if (typeof assignment === 'function') {
2441
- partialUpdate = assignment(assignArgs);
2442
- } else {
2443
- for (const key of Object.keys(assignment)) {
2444
- const propAssignment = assignment[key];
2445
- partialUpdate[key] = typeof propAssignment === 'function' ? propAssignment(assignArgs) : propAssignment;
2446
- }
2447
- }
2448
- const updatedContext = Object.assign({}, state.context, partialUpdate);
2449
- return [cloneState(state, {
2450
- context: updatedContext,
2451
- children: Object.keys(spawnedChildren).length ? {
2452
- ...state.children,
2453
- ...spawnedChildren
2454
- } : state.children
2455
- })];
2456
- }
2457
- /**
2458
- * Updates the current context of the machine.
2459
- *
2460
- * @param assignment An object that represents the partial context to update.
2461
- */
2462
- function assign(assignment) {
2463
- function assign(_) {
2464
- {
2465
- throw new Error(`This isn't supposed to be called`);
2466
- }
2467
- }
2468
- assign.type = 'xstate.assign';
2469
- assign.assignment = assignment;
2470
- assign.resolve = resolve$3;
2471
- return assign;
2472
- }
2473
-
2474
- function resolve$2(_, state, args, {
1381
+ function resolve(_, state, args, {
2475
1382
  event: eventOrExpr,
2476
1383
  id,
2477
1384
  delay
@@ -2510,126 +1417,42 @@ function execute(actorContext, params) {
2510
1417
  */
2511
1418
  function raise(eventOrExpr, options) {
2512
1419
  function raise(_) {
2513
- {
2514
- throw new Error(`This isn't supposed to be called`);
2515
- }
2516
1420
  }
2517
1421
  raise.type = 'xstate.raise';
2518
1422
  raise.event = eventOrExpr;
2519
1423
  raise.id = options?.id;
2520
1424
  raise.delay = options?.delay;
2521
- raise.resolve = resolve$2;
1425
+ raise.resolve = resolve;
2522
1426
  raise.execute = execute;
2523
1427
  return raise;
2524
1428
  }
2525
1429
 
2526
- function resolve$1(_, state, actionArgs, {
2527
- branches
2528
- }) {
2529
- const matchedActions = branches.find(condition => {
2530
- return !condition.guard || evaluateGuard(condition.guard, state.context, actionArgs.event, state);
2531
- })?.actions;
2532
- return [state, undefined, toArray(matchedActions)];
2533
- }
2534
- function choose(branches) {
2535
- function choose(_) {
2536
- {
2537
- throw new Error(`This isn't supposed to be called`);
2538
- }
2539
- }
2540
- choose.type = 'xstate.choose';
2541
- choose.branches = branches;
2542
- choose.resolve = resolve$1;
2543
- return choose;
2544
- }
2545
-
2546
- function resolve(_, state, args, {
2547
- get
2548
- }) {
2549
- return [state, undefined, toArray(get({
2550
- context: args.context,
2551
- event: args.event
2552
- }))];
2553
- }
2554
- function pure(getActions) {
2555
- function pure(_) {
2556
- {
2557
- throw new Error(`This isn't supposed to be called`);
2558
- }
2559
- }
2560
- pure.type = 'xstate.pure';
2561
- pure.get = getActions;
2562
- pure.resolve = resolve;
2563
- return pure;
2564
- }
2565
-
2566
- /**
2567
- * Returns an event type that represents an implicit event that
2568
- * is sent after the specified `delay`.
2569
- *
2570
- * @param delayRef The delay in milliseconds
2571
- * @param id The state node ID where this event is handled
2572
- */
2573
- function after(delayRef, id) {
2574
- const idSuffix = id ? `#${id}` : '';
2575
- return `${ConstantPrefix.After}(${delayRef})${idSuffix}`;
2576
- }
2577
-
2578
- /**
2579
- * Returns an event that represents that a final state node
2580
- * has been reached in the parent state node.
2581
- *
2582
- * @param id The final state node's parent state node `id`
2583
- * @param output The data to pass into the event
2584
- */
2585
- function done(id, output) {
2586
- const type = `${ConstantPrefix.DoneState}.${id}`;
2587
- const eventObject = {
2588
- type,
2589
- output
2590
- };
2591
- eventObject.toString = () => type;
2592
- return eventObject;
2593
- }
2594
- function doneInvokeEventType(invokeId) {
2595
- return `${ConstantPrefix.DoneInvoke}.${invokeId}`;
2596
- }
2597
-
2598
- /**
2599
- * Returns an event that represents that an invoked service has terminated.
2600
- *
2601
- * An invoked service is terminated when it has reached a top-level final state node,
2602
- * but not when it is canceled.
2603
- *
2604
- * @param invokeId The invoked service ID
2605
- * @param output The data to pass into the event
2606
- */
2607
- function doneInvoke(invokeId, output) {
2608
- const type = doneInvokeEventType(invokeId);
2609
- const eventObject = {
2610
- type,
2611
- output
2612
- };
2613
- eventObject.toString = () => type;
2614
- return eventObject;
2615
- }
2616
- function errorEventType(id) {
2617
- return `${ConstantPrefix.ErrorPlatform}.${id}`;
2618
- }
2619
- function error(id, data) {
2620
- const type = errorEventType(id);
2621
- const eventObject = {
2622
- type,
2623
- data
2624
- };
2625
- eventObject.toString = () => type;
2626
- return eventObject;
2627
- }
2628
- function createInitEvent(input) {
2629
- return {
2630
- type: XSTATE_INIT,
2631
- input
2632
- };
2633
- }
2634
-
2635
- export { stateIn as $, isStateId as A, getStateNodeByPath as B, getPersistedState as C, resolveReferencedActor as D, createActor as E, matchesState as F, Actor as G, ActorStatus as H, doneInvoke as I, interpret as J, InterpreterStatus as K, cancel as L, choose as M, NULL_EVENT as N, log as O, pure as P, raise as Q, forwardTo as R, STATE_DELIMITER as S, sendParent as T, sendTo as U, stop as V, pathToStateValue as W, toObserver as X, and as Y, not as Z, or as _, toTransitionConfigArray as a, ConstantPrefix as a0, SpecialTargets as a1, XSTATE_INIT as a2, isPromiseLike as a3, error as a4, XSTATE_STOP as a5, symbolObservable as a6, constantPrefixes as a7, after as a8, done as a9, doneInvokeEventType as aa, errorEventType as ab, escalate as ac, formatTransition as b, memo as c, createInvokeId as d, evaluateGuard as e, formatTransitions as f, getDelayedTransitions as g, formatInitialTransition as h, getCandidates as i, getConfiguration as j, getStateNodes as k, isInFinalState as l, mapValues as m, State as n, isErrorEvent as o, cloneState as p, macrostep as q, resolveStateValue as r, transitionNode as s, toArray as t, getInitialConfiguration as u, resolveActionsAndContext as v, assign as w, createInitEvent as x, microstep as y, isAtomicStateNode as z };
1430
+ exports.State = State;
1431
+ exports.and = and;
1432
+ exports.cancel = cancel;
1433
+ exports.cloneState = cloneState;
1434
+ exports.evaluateGuard = evaluateGuard;
1435
+ exports.formatInitialTransition = formatInitialTransition;
1436
+ exports.formatTransition = formatTransition;
1437
+ exports.formatTransitions = formatTransitions;
1438
+ exports.getCandidates = getCandidates;
1439
+ exports.getConfiguration = getConfiguration;
1440
+ exports.getDelayedTransitions = getDelayedTransitions;
1441
+ exports.getInitialConfiguration = getInitialConfiguration;
1442
+ exports.getPersistedState = getPersistedState;
1443
+ exports.getStateNodeByPath = getStateNodeByPath;
1444
+ exports.getStateNodes = getStateNodes;
1445
+ exports.isAtomicStateNode = isAtomicStateNode;
1446
+ exports.isInFinalState = isInFinalState;
1447
+ exports.isStateId = isStateId;
1448
+ exports.macrostep = macrostep;
1449
+ exports.memo = memo;
1450
+ exports.microstep = microstep;
1451
+ exports.not = not;
1452
+ exports.or = or;
1453
+ exports.raise = raise;
1454
+ exports.resolveActionsAndContext = resolveActionsAndContext;
1455
+ exports.resolveStateValue = resolveStateValue;
1456
+ exports.stateIn = stateIn;
1457
+ exports.stop = stop;
1458
+ exports.transitionNode = transitionNode;