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
@@ -0,0 +1,757 @@
1
+ import { devToolsAdapter } from '../dev/dist/xstate-dev.esm.js';
2
+
3
+ const STATE_DELIMITER = '.';
4
+ const TARGETLESS_KEY = '';
5
+ const NULL_EVENT = '';
6
+ const STATE_IDENTIFIER = '#';
7
+ const WILDCARD = '*';
8
+ const XSTATE_INIT = 'xstate.init';
9
+ const XSTATE_ERROR = 'xstate.error';
10
+ const XSTATE_STOP = 'xstate.stop';
11
+
12
+ /**
13
+ * Returns an event that represents an implicit event that
14
+ * is sent after the specified `delay`.
15
+ *
16
+ * @param delayRef The delay in milliseconds
17
+ * @param id The state node ID where this event is handled
18
+ */
19
+ function createAfterEvent(delayRef, id) {
20
+ const idSuffix = id ? `#${id}` : '';
21
+ return {
22
+ type: `xstate.after(${delayRef})${idSuffix}`
23
+ };
24
+ }
25
+
26
+ /**
27
+ * Returns an event that represents that a final state node
28
+ * has been reached in the parent state node.
29
+ *
30
+ * @param id The final state node's parent state node `id`
31
+ * @param output The data to pass into the event
32
+ */
33
+ function createDoneStateEvent(id, output) {
34
+ return {
35
+ type: `xstate.done.state.${id}`,
36
+ output
37
+ };
38
+ }
39
+
40
+ /**
41
+ * Returns an event that represents that an invoked service has terminated.
42
+ *
43
+ * An invoked service is terminated when it has reached a top-level final state node,
44
+ * but not when it is canceled.
45
+ *
46
+ * @param invokeId The invoked service ID
47
+ * @param output The data to pass into the event
48
+ */
49
+ function createDoneActorEvent(invokeId, output) {
50
+ return {
51
+ type: `xstate.done.actor.${invokeId}`,
52
+ output
53
+ };
54
+ }
55
+ function createErrorActorEvent(id, data) {
56
+ return {
57
+ type: `xstate.error.actor.${id}`,
58
+ data
59
+ };
60
+ }
61
+ function createInitEvent(input) {
62
+ return {
63
+ type: XSTATE_INIT,
64
+ input
65
+ };
66
+ }
67
+
68
+ class Mailbox {
69
+ constructor(_process) {
70
+ this._process = _process;
71
+ this._active = false;
72
+ this._current = null;
73
+ this._last = null;
74
+ }
75
+ start() {
76
+ this._active = true;
77
+ this.flush();
78
+ }
79
+ clear() {
80
+ // we can't set _current to null because we might be currently processing
81
+ // and enqueue following clear shouldnt start processing the enqueued item immediately
82
+ if (this._current) {
83
+ this._current.next = null;
84
+ this._last = this._current;
85
+ }
86
+ }
87
+
88
+ // TODO: rethink this design
89
+ prepend(event) {
90
+ if (!this._current) {
91
+ this.enqueue(event);
92
+ return;
93
+ }
94
+
95
+ // we know that something is already queued up
96
+ // so the mailbox is already flushing or it's inactive
97
+ // therefore the only thing that we need to do is to reassign `this._current`
98
+ this._current = {
99
+ value: event,
100
+ next: this._current
101
+ };
102
+ }
103
+ enqueue(event) {
104
+ const enqueued = {
105
+ value: event,
106
+ next: null
107
+ };
108
+ if (this._current) {
109
+ this._last.next = enqueued;
110
+ this._last = enqueued;
111
+ return;
112
+ }
113
+ this._current = enqueued;
114
+ this._last = enqueued;
115
+ if (this._active) {
116
+ this.flush();
117
+ }
118
+ }
119
+ flush() {
120
+ while (this._current) {
121
+ // atm the given _process is responsible for implementing proper try/catch handling
122
+ // we assume here that this won't throw in a way that can affect this mailbox
123
+ const consumed = this._current;
124
+ this._process(consumed.value);
125
+ // something could have been prepended in the meantime
126
+ // so we need to be defensive here to avoid skipping over a prepended item
127
+ if (consumed === this._current) {
128
+ this._current = this._current.next;
129
+ }
130
+ }
131
+ this._last = null;
132
+ }
133
+ }
134
+
135
+ /**
136
+ * This function makes sure that unhandled errors are thrown in a separate macrotask.
137
+ * It allows those errors to be detected by global error handlers and reported to bug tracking services
138
+ * without interrupting our own stack of execution.
139
+ *
140
+ * @param err error to be thrown
141
+ */
142
+ function reportUnhandledError(err) {
143
+ setTimeout(() => {
144
+ throw err;
145
+ });
146
+ }
147
+
148
+ const symbolObservable = (() => typeof Symbol === 'function' && Symbol.observable || '@@observable')();
149
+
150
+ function createSystem() {
151
+ let sessionIdCounter = 0;
152
+ const children = new Map();
153
+ const keyedActors = new Map();
154
+ const reverseKeyedActors = new WeakMap();
155
+ const system = {
156
+ _bookId: () => `x:${sessionIdCounter++}`,
157
+ _register: (sessionId, actorRef) => {
158
+ children.set(sessionId, actorRef);
159
+ return sessionId;
160
+ },
161
+ _unregister: actorRef => {
162
+ children.delete(actorRef.sessionId);
163
+ const systemId = reverseKeyedActors.get(actorRef);
164
+ if (systemId !== undefined) {
165
+ keyedActors.delete(systemId);
166
+ reverseKeyedActors.delete(actorRef);
167
+ }
168
+ },
169
+ get: systemId => {
170
+ return keyedActors.get(systemId);
171
+ },
172
+ _set: (systemId, actorRef) => {
173
+ const existing = keyedActors.get(systemId);
174
+ if (existing && existing !== actorRef) {
175
+ throw new Error(`Actor with system ID '${systemId}' already exists.`);
176
+ }
177
+ keyedActors.set(systemId, actorRef);
178
+ reverseKeyedActors.set(actorRef, systemId);
179
+ }
180
+ };
181
+ return system;
182
+ }
183
+
184
+ function matchesState(parentStateId, childStateId) {
185
+ const parentStateValue = toStateValue(parentStateId);
186
+ const childStateValue = toStateValue(childStateId);
187
+ if (typeof childStateValue === 'string') {
188
+ if (typeof parentStateValue === 'string') {
189
+ return childStateValue === parentStateValue;
190
+ }
191
+
192
+ // Parent more specific than child
193
+ return false;
194
+ }
195
+ if (typeof parentStateValue === 'string') {
196
+ return parentStateValue in childStateValue;
197
+ }
198
+ return Object.keys(parentStateValue).every(key => {
199
+ if (!(key in childStateValue)) {
200
+ return false;
201
+ }
202
+ return matchesState(parentStateValue[key], childStateValue[key]);
203
+ });
204
+ }
205
+ function toStatePath(stateId) {
206
+ try {
207
+ if (isArray(stateId)) {
208
+ return stateId;
209
+ }
210
+ return stateId.toString().split(STATE_DELIMITER);
211
+ } catch (e) {
212
+ throw new Error(`'${stateId}' is not a valid state path.`);
213
+ }
214
+ }
215
+ function isStateLike(state) {
216
+ return typeof state === 'object' && 'value' in state && 'context' in state && 'event' in state;
217
+ }
218
+ function toStateValue(stateValue) {
219
+ if (isStateLike(stateValue)) {
220
+ return stateValue.value;
221
+ }
222
+ if (isArray(stateValue)) {
223
+ return pathToStateValue(stateValue);
224
+ }
225
+ if (typeof stateValue !== 'string') {
226
+ return stateValue;
227
+ }
228
+ const statePath = toStatePath(stateValue);
229
+ return pathToStateValue(statePath);
230
+ }
231
+ function pathToStateValue(statePath) {
232
+ if (statePath.length === 1) {
233
+ return statePath[0];
234
+ }
235
+ const value = {};
236
+ let marker = value;
237
+ for (let i = 0; i < statePath.length - 1; i++) {
238
+ if (i === statePath.length - 2) {
239
+ marker[statePath[i]] = statePath[i + 1];
240
+ } else {
241
+ const previous = marker;
242
+ marker = {};
243
+ previous[statePath[i]] = marker;
244
+ }
245
+ }
246
+ return value;
247
+ }
248
+ function mapValues(collection, iteratee) {
249
+ const result = {};
250
+ const collectionKeys = Object.keys(collection);
251
+ for (let i = 0; i < collectionKeys.length; i++) {
252
+ const key = collectionKeys[i];
253
+ result[key] = iteratee(collection[key], key, collection, i);
254
+ }
255
+ return result;
256
+ }
257
+ function flatten(array) {
258
+ return [].concat(...array);
259
+ }
260
+ function toArrayStrict(value) {
261
+ if (isArray(value)) {
262
+ return value;
263
+ }
264
+ return [value];
265
+ }
266
+ function toArray(value) {
267
+ if (value === undefined) {
268
+ return [];
269
+ }
270
+ return toArrayStrict(value);
271
+ }
272
+ function mapContext(mapper, context, event, self) {
273
+ if (typeof mapper === 'function') {
274
+ return mapper({
275
+ context,
276
+ event,
277
+ self
278
+ });
279
+ }
280
+ return mapper;
281
+ }
282
+ function isPromiseLike(value) {
283
+ if (value instanceof Promise) {
284
+ return true;
285
+ }
286
+ // Check if shape matches the Promise/A+ specification for a "thenable".
287
+ if (value !== null && (typeof value === 'function' || typeof value === 'object') && typeof value.then === 'function') {
288
+ return true;
289
+ }
290
+ return false;
291
+ }
292
+ function isArray(value) {
293
+ return Array.isArray(value);
294
+ }
295
+ function isErrorActorEvent(event) {
296
+ return event.type.startsWith('xstate.error.actor');
297
+ }
298
+ function toTransitionConfigArray(configLike) {
299
+ return toArrayStrict(configLike).map(transitionLike => {
300
+ if (typeof transitionLike === 'undefined' || typeof transitionLike === 'string') {
301
+ return {
302
+ target: transitionLike
303
+ };
304
+ }
305
+ return transitionLike;
306
+ });
307
+ }
308
+ function normalizeTarget(target) {
309
+ if (target === undefined || target === TARGETLESS_KEY) {
310
+ return undefined;
311
+ }
312
+ return toArray(target);
313
+ }
314
+ function toObserver(nextHandler, errorHandler, completionHandler) {
315
+ const isObserver = typeof nextHandler === 'object';
316
+ const self = isObserver ? nextHandler : undefined;
317
+ return {
318
+ next: (isObserver ? nextHandler.next : nextHandler)?.bind(self),
319
+ error: (isObserver ? nextHandler.error : errorHandler)?.bind(self),
320
+ complete: (isObserver ? nextHandler.complete : completionHandler)?.bind(self)
321
+ };
322
+ }
323
+ function createInvokeId(stateNodeId, index) {
324
+ return `${stateNodeId}:invocation[${index}]`;
325
+ }
326
+ function resolveReferencedActor(referenced) {
327
+ return referenced ? 'transition' in referenced ? {
328
+ src: referenced,
329
+ input: undefined
330
+ } : referenced : undefined;
331
+ }
332
+
333
+ let ActorStatus = /*#__PURE__*/function (ActorStatus) {
334
+ ActorStatus[ActorStatus["NotStarted"] = 0] = "NotStarted";
335
+ ActorStatus[ActorStatus["Running"] = 1] = "Running";
336
+ ActorStatus[ActorStatus["Stopped"] = 2] = "Stopped";
337
+ return ActorStatus;
338
+ }({});
339
+
340
+ /**
341
+ * @deprecated Use `ActorStatus` instead.
342
+ */
343
+ const InterpreterStatus = ActorStatus;
344
+ const defaultOptions = {
345
+ deferEvents: true,
346
+ clock: {
347
+ setTimeout: (fn, ms) => {
348
+ return setTimeout(fn, ms);
349
+ },
350
+ clearTimeout: id => {
351
+ return clearTimeout(id);
352
+ }
353
+ },
354
+ logger: console.log.bind(console),
355
+ devTools: false
356
+ };
357
+ class Actor {
358
+ /**
359
+ * The current internal state of the actor.
360
+ */
361
+
362
+ /**
363
+ * The clock that is responsible for setting and clearing timeouts, such as delayed events and transitions.
364
+ */
365
+
366
+ /**
367
+ * The unique identifier for this actor relative to its parent.
368
+ */
369
+
370
+ /**
371
+ * Whether the service is started.
372
+ */
373
+
374
+ // Actor Ref
375
+
376
+ // TODO: add typings for system
377
+
378
+ /**
379
+ * The globally unique process ID for this invocation.
380
+ */
381
+
382
+ /**
383
+ * Creates a new actor instance for the given logic with the provided options, if any.
384
+ *
385
+ * @param logic The logic to create an actor from
386
+ * @param options Actor options
387
+ */
388
+ constructor(logic, options) {
389
+ this.logic = logic;
390
+ this._state = void 0;
391
+ this.clock = void 0;
392
+ this.options = void 0;
393
+ this.id = void 0;
394
+ this.mailbox = new Mailbox(this._process.bind(this));
395
+ this.delayedEventsMap = {};
396
+ this.observers = new Set();
397
+ this.logger = void 0;
398
+ this.status = ActorStatus.NotStarted;
399
+ this._parent = void 0;
400
+ this.ref = void 0;
401
+ this._actorContext = void 0;
402
+ this._systemId = void 0;
403
+ this.sessionId = void 0;
404
+ this.system = void 0;
405
+ this._doneEvent = void 0;
406
+ this.src = void 0;
407
+ this._deferred = [];
408
+ const resolvedOptions = {
409
+ ...defaultOptions,
410
+ ...options
411
+ };
412
+ const {
413
+ clock,
414
+ logger,
415
+ parent,
416
+ id,
417
+ systemId
418
+ } = resolvedOptions;
419
+ const self = this;
420
+ this.system = parent?.system ?? createSystem();
421
+ if (systemId) {
422
+ this._systemId = systemId;
423
+ this.system._set(systemId, this);
424
+ }
425
+ this.sessionId = this.system._bookId();
426
+ this.id = id ?? this.sessionId;
427
+ this.logger = logger;
428
+ this.clock = clock;
429
+ this._parent = parent;
430
+ this.options = resolvedOptions;
431
+ this.src = resolvedOptions.src;
432
+ this.ref = this;
433
+ this._actorContext = {
434
+ self,
435
+ id: this.id,
436
+ sessionId: this.sessionId,
437
+ logger: this.logger,
438
+ defer: fn => {
439
+ this._deferred.push(fn);
440
+ },
441
+ system: this.system,
442
+ stopChild: child => {
443
+ if (child._parent !== this) {
444
+ throw new Error(`Cannot stop child actor ${child.id} of ${this.id} because it is not a child`);
445
+ }
446
+ child._stop();
447
+ }
448
+ };
449
+
450
+ // Ensure that the send method is bound to this Actor instance
451
+ // if destructured
452
+ this.send = this.send.bind(this);
453
+ this._initState();
454
+ }
455
+ _initState() {
456
+ 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);
457
+ }
458
+
459
+ // array of functions to defer
460
+
461
+ update(state) {
462
+ // Update state
463
+ this._state = state;
464
+ const snapshot = this.getSnapshot();
465
+
466
+ // Execute deferred effects
467
+ let deferredFn;
468
+ while (deferredFn = this._deferred.shift()) {
469
+ deferredFn();
470
+ }
471
+ for (const observer of this.observers) {
472
+ // TODO: should observers be notified in case of the error?
473
+ try {
474
+ observer.next?.(snapshot);
475
+ } catch (err) {
476
+ reportUnhandledError(err);
477
+ }
478
+ }
479
+ const status = this.logic.getStatus?.(state);
480
+ switch (status?.status) {
481
+ case 'done':
482
+ this._stopProcedure();
483
+ this._complete();
484
+ this._doneEvent = createDoneActorEvent(this.id, status.data);
485
+ this._parent?.send(this._doneEvent);
486
+ break;
487
+ case 'error':
488
+ this._stopProcedure();
489
+ this._error(status.data);
490
+ this._parent?.send(createErrorActorEvent(this.id, status.data));
491
+ break;
492
+ }
493
+ }
494
+ subscribe(nextListenerOrObserver, errorListener, completeListener) {
495
+ const observer = toObserver(nextListenerOrObserver, errorListener, completeListener);
496
+ if (this.status !== ActorStatus.Stopped) {
497
+ this.observers.add(observer);
498
+ } else {
499
+ try {
500
+ observer.complete?.();
501
+ } catch (err) {
502
+ reportUnhandledError(err);
503
+ }
504
+ }
505
+ return {
506
+ unsubscribe: () => {
507
+ this.observers.delete(observer);
508
+ }
509
+ };
510
+ }
511
+
512
+ /**
513
+ * Starts the Actor from the initial state
514
+ */
515
+ start() {
516
+ if (this.status === ActorStatus.Running) {
517
+ // Do not restart the service if it is already started
518
+ return this;
519
+ }
520
+ this.system._register(this.sessionId, this);
521
+ if (this._systemId) {
522
+ this.system._set(this._systemId, this);
523
+ }
524
+ this.status = ActorStatus.Running;
525
+ const status = this.logic.getStatus?.(this._state);
526
+ switch (status?.status) {
527
+ case 'done':
528
+ // a state machine can be "done" upon intialization (it could reach a final state using initial microsteps)
529
+ // we still need to complete observers, flush deferreds etc
530
+ this.update(this._state);
531
+ // fallthrough
532
+ case 'error':
533
+ // TODO: rethink cleanup of observers, mailbox, etc
534
+ return this;
535
+ }
536
+ if (this.logic.start) {
537
+ try {
538
+ this.logic.start(this._state, this._actorContext);
539
+ } catch (err) {
540
+ this._stopProcedure();
541
+ this._error(err);
542
+ this._parent?.send(createErrorActorEvent(this.id, err));
543
+ return this;
544
+ }
545
+ }
546
+
547
+ // TODO: this notifies all subscribers but usually this is redundant
548
+ // there is no real change happening here
549
+ // we need to rethink if this needs to be refactored
550
+ this.update(this._state);
551
+ if (this.options.devTools) {
552
+ this.attachDevTools();
553
+ }
554
+ this.mailbox.start();
555
+ return this;
556
+ }
557
+ _process(event) {
558
+ // TODO: reexamine what happens when an action (or a guard or smth) throws
559
+ let nextState;
560
+ let caughtError;
561
+ try {
562
+ nextState = this.logic.transition(this._state, event, this._actorContext);
563
+ } catch (err) {
564
+ // we wrap it in a box so we can rethrow it later even if falsy value gets caught here
565
+ caughtError = {
566
+ err
567
+ };
568
+ }
569
+ if (caughtError) {
570
+ const {
571
+ err
572
+ } = caughtError;
573
+ this._stopProcedure();
574
+ this._error(err);
575
+ this._parent?.send(createErrorActorEvent(this.id, err));
576
+ return;
577
+ }
578
+ this.update(nextState);
579
+ if (event.type === XSTATE_STOP) {
580
+ this._stopProcedure();
581
+ this._complete();
582
+ }
583
+ }
584
+ _stop() {
585
+ if (this.status === ActorStatus.Stopped) {
586
+ return this;
587
+ }
588
+ this.mailbox.clear();
589
+ if (this.status === ActorStatus.NotStarted) {
590
+ this.status = ActorStatus.Stopped;
591
+ return this;
592
+ }
593
+ this.mailbox.enqueue({
594
+ type: XSTATE_STOP
595
+ });
596
+ return this;
597
+ }
598
+
599
+ /**
600
+ * Stops the Actor and unsubscribe all listeners.
601
+ */
602
+ stop() {
603
+ if (this._parent) {
604
+ throw new Error('A non-root actor cannot be stopped directly.');
605
+ }
606
+ return this._stop();
607
+ }
608
+ _complete() {
609
+ for (const observer of this.observers) {
610
+ try {
611
+ observer.complete?.();
612
+ } catch (err) {
613
+ reportUnhandledError(err);
614
+ }
615
+ }
616
+ this.observers.clear();
617
+ }
618
+ _error(err) {
619
+ if (!this.observers.size) {
620
+ if (!this._parent) {
621
+ reportUnhandledError(err);
622
+ }
623
+ return;
624
+ }
625
+ let reportError = false;
626
+ for (const observer of this.observers) {
627
+ const errorListener = observer.error;
628
+ reportError ||= !errorListener;
629
+ try {
630
+ errorListener?.(err);
631
+ } catch (err2) {
632
+ reportUnhandledError(err2);
633
+ }
634
+ }
635
+ this.observers.clear();
636
+ if (reportError) {
637
+ reportUnhandledError(err);
638
+ }
639
+ }
640
+ _stopProcedure() {
641
+ if (this.status !== ActorStatus.Running) {
642
+ // Actor already stopped; do nothing
643
+ return this;
644
+ }
645
+
646
+ // Cancel all delayed events
647
+ for (const key of Object.keys(this.delayedEventsMap)) {
648
+ this.clock.clearTimeout(this.delayedEventsMap[key]);
649
+ }
650
+
651
+ // TODO: mailbox.reset
652
+ this.mailbox.clear();
653
+ // TODO: after `stop` we must prepare ourselves for receiving events again
654
+ // events sent *after* stop signal must be queued
655
+ // it seems like this should be the common behavior for all of our consumers
656
+ // so perhaps this should be unified somehow for all of them
657
+ this.mailbox = new Mailbox(this._process.bind(this));
658
+ this.status = ActorStatus.Stopped;
659
+ this.system._unregister(this);
660
+ return this;
661
+ }
662
+
663
+ /**
664
+ * Sends an event to the running Actor to trigger a transition.
665
+ *
666
+ * @param event The event to send
667
+ */
668
+ send(event) {
669
+ if (typeof event === 'string') {
670
+ throw new Error(`Only event objects may be sent to actors; use .send({ type: "${event}" }) instead`);
671
+ }
672
+ if (this.status === ActorStatus.Stopped) {
673
+ return;
674
+ }
675
+ if (this.status !== ActorStatus.Running && !this.options.deferEvents) {
676
+ throw new Error(`Event "${event.type}" was sent to uninitialized actor "${this.id
677
+ // tslint:disable-next-line:max-line-length
678
+ }". Make sure .start() is called for this actor, or set { deferEvents: true } in the actor options.\nEvent: ${JSON.stringify(event)}`);
679
+ }
680
+ this.mailbox.enqueue(event);
681
+ }
682
+
683
+ // TODO: make private (and figure out a way to do this within the machine)
684
+ delaySend({
685
+ event,
686
+ id,
687
+ delay,
688
+ to
689
+ }) {
690
+ const timerId = this.clock.setTimeout(() => {
691
+ if (to) {
692
+ to.send(event);
693
+ } else {
694
+ this.send(event);
695
+ }
696
+ }, delay);
697
+
698
+ // TODO: consider the rehydration story here
699
+ if (id) {
700
+ this.delayedEventsMap[id] = timerId;
701
+ }
702
+ }
703
+
704
+ // TODO: make private (and figure out a way to do this within the machine)
705
+ cancel(sendId) {
706
+ this.clock.clearTimeout(this.delayedEventsMap[sendId]);
707
+ delete this.delayedEventsMap[sendId];
708
+ }
709
+ attachDevTools() {
710
+ const {
711
+ devTools
712
+ } = this.options;
713
+ if (devTools) {
714
+ const resolvedDevToolsAdapter = typeof devTools === 'function' ? devTools : devToolsAdapter;
715
+ resolvedDevToolsAdapter(this);
716
+ }
717
+ }
718
+ toJSON() {
719
+ return {
720
+ id: this.id
721
+ };
722
+ }
723
+ getPersistedState() {
724
+ return this.logic.getPersistedState?.(this._state);
725
+ }
726
+ [symbolObservable]() {
727
+ return this;
728
+ }
729
+ getSnapshot() {
730
+ return this.logic.getSnapshot ? this.logic.getSnapshot(this._state) : this._state;
731
+ }
732
+ }
733
+
734
+ /**
735
+ * Creates a new `ActorRef` instance for the given machine with the provided options, if any.
736
+ *
737
+ * @param machine The machine to create an actor from
738
+ * @param options `ActorRef` options
739
+ */
740
+
741
+ function createActor(logic, options) {
742
+ const interpreter = new Actor(logic, options);
743
+ return interpreter;
744
+ }
745
+
746
+ /**
747
+ * Creates a new Interpreter instance for the given machine with the provided options, if any.
748
+ *
749
+ * @deprecated Use `createActor` instead
750
+ */
751
+ const interpret = createActor;
752
+
753
+ /**
754
+ * @deprecated Use `Actor` instead.
755
+ */
756
+
757
+ export { Actor as A, flatten as B, XSTATE_ERROR as C, InterpreterStatus as I, NULL_EVENT as N, STATE_DELIMITER as S, WILDCARD as W, XSTATE_INIT as X, toTransitionConfigArray as a, createInitEvent as b, createInvokeId as c, createActor as d, matchesState as e, ActorStatus as f, interpret as g, toObserver as h, isErrorActorEvent as i, isPromiseLike as j, createDoneActorEvent as k, createErrorActorEvent as l, mapValues as m, XSTATE_STOP as n, toStateValue as o, pathToStateValue as p, STATE_IDENTIFIER as q, resolveReferencedActor as r, symbolObservable as s, toArray as t, normalizeTarget as u, toStatePath as v, createDoneStateEvent as w, mapContext as x, isArray as y, createAfterEvent as z };