xstate 5.0.0-beta.27 → 5.0.0-beta.29

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 (67) 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 +395 -28
  11. package/actors/dist/xstate-actors.cjs.mjs +1 -3
  12. package/actors/dist/xstate-actors.development.cjs.js +395 -28
  13. package/actors/dist/xstate-actors.development.cjs.mjs +1 -3
  14. package/actors/dist/xstate-actors.development.esm.js +389 -21
  15. package/actors/dist/xstate-actors.esm.js +389 -21
  16. package/actors/dist/xstate-actors.umd.min.js +1 -1
  17. package/actors/dist/xstate-actors.umd.min.js.map +1 -1
  18. package/dist/declarations/src/StateNode.d.ts +3 -3
  19. package/dist/declarations/src/actions/assign.d.ts +9 -4
  20. package/dist/declarations/src/actions/cancel.d.ts +4 -4
  21. package/dist/declarations/src/actions/choose.d.ts +5 -4
  22. package/dist/declarations/src/actions/log.d.ts +4 -4
  23. package/dist/declarations/src/actions/pure.d.ts +6 -5
  24. package/dist/declarations/src/actions/raise.d.ts +2 -2
  25. package/dist/declarations/src/actions/send.d.ts +7 -7
  26. package/dist/declarations/src/actions/stop.d.ts +4 -4
  27. package/dist/declarations/src/actions.d.ts +8 -44
  28. package/dist/declarations/src/actors/callback.d.ts +2 -2
  29. package/dist/declarations/src/actors/index.d.ts +3 -5
  30. package/dist/declarations/src/constants.d.ts +1 -0
  31. package/dist/declarations/src/index.d.ts +9 -16
  32. package/dist/declarations/src/spawn.d.ts +25 -0
  33. package/dist/declarations/src/stateUtils.d.ts +1 -1
  34. package/dist/declarations/src/typegenTypes.d.ts +4 -4
  35. package/dist/declarations/src/types.d.ts +92 -122
  36. package/dist/declarations/src/utils.d.ts +2 -2
  37. package/dist/interpreter-498891b2.esm.js +741 -0
  38. package/dist/interpreter-6e7909c8.development.esm.js +749 -0
  39. package/dist/interpreter-c357bc50.cjs.js +773 -0
  40. package/dist/interpreter-e2c6a579.development.cjs.js +781 -0
  41. package/dist/{actions-9754d2ca.development.esm.js → raise-03e57569.cjs.js} +130 -1307
  42. package/dist/{actions-d1dba4ac.cjs.js → raise-59f2c242.esm.js} +65 -1267
  43. package/dist/{actions-020463e9.esm.js → raise-e778a828.development.esm.js} +109 -1203
  44. package/dist/{actions-ca622922.development.cjs.js → raise-f751dfac.development.cjs.js} +101 -1306
  45. package/dist/send-42c83fb2.development.esm.js +364 -0
  46. package/dist/send-51717e53.cjs.js +349 -0
  47. package/dist/send-f53778f6.development.cjs.js +374 -0
  48. package/dist/send-fff224db.esm.js +339 -0
  49. package/dist/xstate.cjs.js +114 -112
  50. package/dist/xstate.cjs.mjs +2 -2
  51. package/dist/xstate.development.cjs.js +114 -112
  52. package/dist/xstate.development.cjs.mjs +2 -2
  53. package/dist/xstate.development.esm.js +78 -74
  54. package/dist/xstate.esm.js +78 -74
  55. package/dist/xstate.umd.min.js +1 -1
  56. package/dist/xstate.umd.min.js.map +1 -1
  57. package/guards/dist/xstate-guards.cjs.js +2 -1
  58. package/guards/dist/xstate-guards.development.cjs.js +2 -1
  59. package/guards/dist/xstate-guards.development.esm.js +2 -1
  60. package/guards/dist/xstate-guards.esm.js +2 -1
  61. package/guards/dist/xstate-guards.umd.min.js.map +1 -1
  62. package/package.json +1 -1
  63. package/dist/declarations/src/constantPrefixes.d.ts +0 -6
  64. package/dist/promise-2ad94e3b.development.esm.js +0 -406
  65. package/dist/promise-3b7e3357.development.cjs.js +0 -412
  66. package/dist/promise-5b07c38e.esm.js +0 -406
  67. package/dist/promise-7a8c1768.cjs.js +0 -412
@@ -0,0 +1,741 @@
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 isArray(value) {
283
+ return Array.isArray(value);
284
+ }
285
+ function isErrorActorEvent(event) {
286
+ return event.type.startsWith('xstate.error.actor');
287
+ }
288
+ function toTransitionConfigArray(configLike) {
289
+ return toArrayStrict(configLike).map(transitionLike => {
290
+ if (typeof transitionLike === 'undefined' || typeof transitionLike === 'string') {
291
+ return {
292
+ target: transitionLike
293
+ };
294
+ }
295
+ return transitionLike;
296
+ });
297
+ }
298
+ function normalizeTarget(target) {
299
+ if (target === undefined || target === TARGETLESS_KEY) {
300
+ return undefined;
301
+ }
302
+ return toArray(target);
303
+ }
304
+ function toObserver(nextHandler, errorHandler, completionHandler) {
305
+ const isObserver = typeof nextHandler === 'object';
306
+ const self = isObserver ? nextHandler : undefined;
307
+ return {
308
+ next: (isObserver ? nextHandler.next : nextHandler)?.bind(self),
309
+ error: (isObserver ? nextHandler.error : errorHandler)?.bind(self),
310
+ complete: (isObserver ? nextHandler.complete : completionHandler)?.bind(self)
311
+ };
312
+ }
313
+ function createInvokeId(stateNodeId, index) {
314
+ return `${stateNodeId}:invocation[${index}]`;
315
+ }
316
+ function resolveReferencedActor(referenced) {
317
+ return referenced ? 'transition' in referenced ? {
318
+ src: referenced,
319
+ input: undefined
320
+ } : referenced : undefined;
321
+ }
322
+
323
+ let ActorStatus = /*#__PURE__*/function (ActorStatus) {
324
+ ActorStatus[ActorStatus["NotStarted"] = 0] = "NotStarted";
325
+ ActorStatus[ActorStatus["Running"] = 1] = "Running";
326
+ ActorStatus[ActorStatus["Stopped"] = 2] = "Stopped";
327
+ return ActorStatus;
328
+ }({});
329
+
330
+ /**
331
+ * @deprecated Use `ActorStatus` instead.
332
+ */
333
+ const InterpreterStatus = ActorStatus;
334
+ const defaultOptions = {
335
+ clock: {
336
+ setTimeout: (fn, ms) => {
337
+ return setTimeout(fn, ms);
338
+ },
339
+ clearTimeout: id => {
340
+ return clearTimeout(id);
341
+ }
342
+ },
343
+ logger: console.log.bind(console),
344
+ devTools: false
345
+ };
346
+ class Actor {
347
+ /**
348
+ * The current internal state of the actor.
349
+ */
350
+
351
+ /**
352
+ * The clock that is responsible for setting and clearing timeouts, such as delayed events and transitions.
353
+ */
354
+
355
+ /**
356
+ * The unique identifier for this actor relative to its parent.
357
+ */
358
+
359
+ /**
360
+ * Whether the service is started.
361
+ */
362
+
363
+ // Actor Ref
364
+
365
+ // TODO: add typings for system
366
+
367
+ /**
368
+ * The globally unique process ID for this invocation.
369
+ */
370
+
371
+ /**
372
+ * Creates a new actor instance for the given logic with the provided options, if any.
373
+ *
374
+ * @param logic The logic to create an actor from
375
+ * @param options Actor options
376
+ */
377
+ constructor(logic, options) {
378
+ this.logic = logic;
379
+ this._state = void 0;
380
+ this.clock = void 0;
381
+ this.options = void 0;
382
+ this.id = void 0;
383
+ this.mailbox = new Mailbox(this._process.bind(this));
384
+ this.delayedEventsMap = {};
385
+ this.observers = new Set();
386
+ this.logger = void 0;
387
+ this.status = ActorStatus.NotStarted;
388
+ this._parent = void 0;
389
+ this.ref = void 0;
390
+ this._actorContext = void 0;
391
+ this._systemId = void 0;
392
+ this.sessionId = void 0;
393
+ this.system = void 0;
394
+ this._doneEvent = void 0;
395
+ this.src = void 0;
396
+ this._deferred = [];
397
+ const resolvedOptions = {
398
+ ...defaultOptions,
399
+ ...options
400
+ };
401
+ const {
402
+ clock,
403
+ logger,
404
+ parent,
405
+ id,
406
+ systemId
407
+ } = resolvedOptions;
408
+ const self = this;
409
+ this.system = parent?.system ?? createSystem();
410
+ if (systemId) {
411
+ this._systemId = systemId;
412
+ this.system._set(systemId, this);
413
+ }
414
+ this.sessionId = this.system._bookId();
415
+ this.id = id ?? this.sessionId;
416
+ this.logger = logger;
417
+ this.clock = clock;
418
+ this._parent = parent;
419
+ this.options = resolvedOptions;
420
+ this.src = resolvedOptions.src;
421
+ this.ref = this;
422
+ this._actorContext = {
423
+ self,
424
+ id: this.id,
425
+ sessionId: this.sessionId,
426
+ logger: this.logger,
427
+ defer: fn => {
428
+ this._deferred.push(fn);
429
+ },
430
+ system: this.system,
431
+ stopChild: child => {
432
+ if (child._parent !== this) {
433
+ throw new Error(`Cannot stop child actor ${child.id} of ${this.id} because it is not a child`);
434
+ }
435
+ child._stop();
436
+ }
437
+ };
438
+
439
+ // Ensure that the send method is bound to this Actor instance
440
+ // if destructured
441
+ this.send = this.send.bind(this);
442
+ this._initState();
443
+ }
444
+ _initState() {
445
+ 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);
446
+ }
447
+
448
+ // array of functions to defer
449
+
450
+ update(state) {
451
+ // Update state
452
+ this._state = state;
453
+ const snapshot = this.getSnapshot();
454
+
455
+ // Execute deferred effects
456
+ let deferredFn;
457
+ while (deferredFn = this._deferred.shift()) {
458
+ deferredFn();
459
+ }
460
+ for (const observer of this.observers) {
461
+ // TODO: should observers be notified in case of the error?
462
+ try {
463
+ observer.next?.(snapshot);
464
+ } catch (err) {
465
+ reportUnhandledError(err);
466
+ }
467
+ }
468
+ const status = this.logic.getStatus?.(state);
469
+ switch (status?.status) {
470
+ case 'done':
471
+ this._stopProcedure();
472
+ this._complete();
473
+ this._doneEvent = createDoneActorEvent(this.id, status.data);
474
+ this._parent?.send(this._doneEvent);
475
+ break;
476
+ case 'error':
477
+ this._stopProcedure();
478
+ this._error(status.data);
479
+ this._parent?.send(createErrorActorEvent(this.id, status.data));
480
+ break;
481
+ }
482
+ }
483
+ subscribe(nextListenerOrObserver, errorListener, completeListener) {
484
+ const observer = toObserver(nextListenerOrObserver, errorListener, completeListener);
485
+ if (this.status !== ActorStatus.Stopped) {
486
+ this.observers.add(observer);
487
+ } else {
488
+ try {
489
+ observer.complete?.();
490
+ } catch (err) {
491
+ reportUnhandledError(err);
492
+ }
493
+ }
494
+ return {
495
+ unsubscribe: () => {
496
+ this.observers.delete(observer);
497
+ }
498
+ };
499
+ }
500
+
501
+ /**
502
+ * Starts the Actor from the initial state
503
+ */
504
+ start() {
505
+ if (this.status === ActorStatus.Running) {
506
+ // Do not restart the service if it is already started
507
+ return this;
508
+ }
509
+ this.system._register(this.sessionId, this);
510
+ if (this._systemId) {
511
+ this.system._set(this._systemId, this);
512
+ }
513
+ this.status = ActorStatus.Running;
514
+ const status = this.logic.getStatus?.(this._state);
515
+ switch (status?.status) {
516
+ case 'done':
517
+ // a state machine can be "done" upon intialization (it could reach a final state using initial microsteps)
518
+ // we still need to complete observers, flush deferreds etc
519
+ this.update(this._state);
520
+ // fallthrough
521
+ case 'error':
522
+ // TODO: rethink cleanup of observers, mailbox, etc
523
+ return this;
524
+ }
525
+ if (this.logic.start) {
526
+ try {
527
+ this.logic.start(this._state, this._actorContext);
528
+ } catch (err) {
529
+ this._stopProcedure();
530
+ this._error(err);
531
+ this._parent?.send(createErrorActorEvent(this.id, err));
532
+ return this;
533
+ }
534
+ }
535
+
536
+ // TODO: this notifies all subscribers but usually this is redundant
537
+ // there is no real change happening here
538
+ // we need to rethink if this needs to be refactored
539
+ this.update(this._state);
540
+ if (this.options.devTools) {
541
+ this.attachDevTools();
542
+ }
543
+ this.mailbox.start();
544
+ return this;
545
+ }
546
+ _process(event) {
547
+ // TODO: reexamine what happens when an action (or a guard or smth) throws
548
+ let nextState;
549
+ let caughtError;
550
+ try {
551
+ nextState = this.logic.transition(this._state, event, this._actorContext);
552
+ } catch (err) {
553
+ // we wrap it in a box so we can rethrow it later even if falsy value gets caught here
554
+ caughtError = {
555
+ err
556
+ };
557
+ }
558
+ if (caughtError) {
559
+ const {
560
+ err
561
+ } = caughtError;
562
+ this._stopProcedure();
563
+ this._error(err);
564
+ this._parent?.send(createErrorActorEvent(this.id, err));
565
+ return;
566
+ }
567
+ this.update(nextState);
568
+ if (event.type === XSTATE_STOP) {
569
+ this._stopProcedure();
570
+ this._complete();
571
+ }
572
+ }
573
+ _stop() {
574
+ if (this.status === ActorStatus.Stopped) {
575
+ return this;
576
+ }
577
+ this.mailbox.clear();
578
+ if (this.status === ActorStatus.NotStarted) {
579
+ this.status = ActorStatus.Stopped;
580
+ return this;
581
+ }
582
+ this.mailbox.enqueue({
583
+ type: XSTATE_STOP
584
+ });
585
+ return this;
586
+ }
587
+
588
+ /**
589
+ * Stops the Actor and unsubscribe all listeners.
590
+ */
591
+ stop() {
592
+ if (this._parent) {
593
+ throw new Error('A non-root actor cannot be stopped directly.');
594
+ }
595
+ return this._stop();
596
+ }
597
+ _complete() {
598
+ for (const observer of this.observers) {
599
+ try {
600
+ observer.complete?.();
601
+ } catch (err) {
602
+ reportUnhandledError(err);
603
+ }
604
+ }
605
+ this.observers.clear();
606
+ }
607
+ _error(err) {
608
+ if (!this.observers.size) {
609
+ if (!this._parent) {
610
+ reportUnhandledError(err);
611
+ }
612
+ return;
613
+ }
614
+ let reportError = false;
615
+ for (const observer of this.observers) {
616
+ const errorListener = observer.error;
617
+ reportError ||= !errorListener;
618
+ try {
619
+ errorListener?.(err);
620
+ } catch (err2) {
621
+ reportUnhandledError(err2);
622
+ }
623
+ }
624
+ this.observers.clear();
625
+ if (reportError) {
626
+ reportUnhandledError(err);
627
+ }
628
+ }
629
+ _stopProcedure() {
630
+ if (this.status !== ActorStatus.Running) {
631
+ // Actor already stopped; do nothing
632
+ return this;
633
+ }
634
+
635
+ // Cancel all delayed events
636
+ for (const key of Object.keys(this.delayedEventsMap)) {
637
+ this.clock.clearTimeout(this.delayedEventsMap[key]);
638
+ }
639
+
640
+ // TODO: mailbox.reset
641
+ this.mailbox.clear();
642
+ // TODO: after `stop` we must prepare ourselves for receiving events again
643
+ // events sent *after* stop signal must be queued
644
+ // it seems like this should be the common behavior for all of our consumers
645
+ // so perhaps this should be unified somehow for all of them
646
+ this.mailbox = new Mailbox(this._process.bind(this));
647
+ this.status = ActorStatus.Stopped;
648
+ this.system._unregister(this);
649
+ return this;
650
+ }
651
+
652
+ /**
653
+ * Sends an event to the running Actor to trigger a transition.
654
+ *
655
+ * @param event The event to send
656
+ */
657
+ send(event) {
658
+ if (typeof event === 'string') {
659
+ throw new Error(`Only event objects may be sent to actors; use .send({ type: "${event}" }) instead`);
660
+ }
661
+ if (this.status === ActorStatus.Stopped) {
662
+ return;
663
+ }
664
+ this.mailbox.enqueue(event);
665
+ }
666
+
667
+ // TODO: make private (and figure out a way to do this within the machine)
668
+ delaySend({
669
+ event,
670
+ id,
671
+ delay,
672
+ to
673
+ }) {
674
+ const timerId = this.clock.setTimeout(() => {
675
+ if (to) {
676
+ to.send(event);
677
+ } else {
678
+ this.send(event);
679
+ }
680
+ }, delay);
681
+
682
+ // TODO: consider the rehydration story here
683
+ if (id) {
684
+ this.delayedEventsMap[id] = timerId;
685
+ }
686
+ }
687
+
688
+ // TODO: make private (and figure out a way to do this within the machine)
689
+ cancel(sendId) {
690
+ this.clock.clearTimeout(this.delayedEventsMap[sendId]);
691
+ delete this.delayedEventsMap[sendId];
692
+ }
693
+ attachDevTools() {
694
+ const {
695
+ devTools
696
+ } = this.options;
697
+ if (devTools) {
698
+ const resolvedDevToolsAdapter = typeof devTools === 'function' ? devTools : devToolsAdapter;
699
+ resolvedDevToolsAdapter(this);
700
+ }
701
+ }
702
+ toJSON() {
703
+ return {
704
+ id: this.id
705
+ };
706
+ }
707
+ getPersistedState() {
708
+ return this.logic.getPersistedState?.(this._state);
709
+ }
710
+ [symbolObservable]() {
711
+ return this;
712
+ }
713
+ getSnapshot() {
714
+ return this.logic.getSnapshot ? this.logic.getSnapshot(this._state) : this._state;
715
+ }
716
+ }
717
+
718
+ /**
719
+ * Creates a new `ActorRef` instance for the given machine with the provided options, if any.
720
+ *
721
+ * @param machine The machine to create an actor from
722
+ * @param options `ActorRef` options
723
+ */
724
+
725
+ function createActor(logic, options) {
726
+ const interpreter = new Actor(logic, options);
727
+ return interpreter;
728
+ }
729
+
730
+ /**
731
+ * Creates a new Interpreter instance for the given machine with the provided options, if any.
732
+ *
733
+ * @deprecated Use `createActor` instead
734
+ */
735
+ const interpret = createActor;
736
+
737
+ /**
738
+ * @deprecated Use `Actor` instead.
739
+ */
740
+
741
+ export { Actor as A, 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, XSTATE_STOP as j, createErrorActorEvent as k, toStateValue as l, mapValues as m, STATE_IDENTIFIER as n, normalizeTarget as o, pathToStateValue as p, toStatePath as q, resolveReferencedActor as r, createDoneStateEvent as s, toArray as t, mapContext as u, isArray as v, createAfterEvent as w, flatten as x, XSTATE_ERROR as y };