xstate 5.0.0-beta.43 → 5.0.0-beta.44

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 (46) hide show
  1. package/actions/dist/xstate-actions.cjs.js +2 -3
  2. package/actions/dist/xstate-actions.development.cjs.js +2 -3
  3. package/actions/dist/xstate-actions.development.esm.js +2 -3
  4. package/actions/dist/xstate-actions.esm.js +2 -3
  5. package/actions/dist/xstate-actions.umd.min.js +1 -1
  6. package/actions/dist/xstate-actions.umd.min.js.map +1 -1
  7. package/actors/dist/xstate-actors.cjs.js +6 -6
  8. package/actors/dist/xstate-actors.development.cjs.js +6 -6
  9. package/actors/dist/xstate-actors.development.esm.js +1 -1
  10. package/actors/dist/xstate-actors.esm.js +1 -1
  11. package/actors/dist/xstate-actors.umd.min.js +1 -1
  12. package/actors/dist/xstate-actors.umd.min.js.map +1 -1
  13. package/dist/declarations/src/State.d.ts +3 -7
  14. package/dist/declarations/src/actions/spawn.d.ts +11 -16
  15. package/dist/declarations/src/guards.d.ts +2 -2
  16. package/dist/declarations/src/index.d.ts +1 -1
  17. package/dist/declarations/src/spawn.d.ts +9 -13
  18. package/dist/declarations/src/stateUtils.d.ts +4 -4
  19. package/dist/declarations/src/types.d.ts +15 -16
  20. package/dist/declarations/src/utils.d.ts +1 -3
  21. package/dist/{raise-e0fe5c2d.cjs.js → raise-348cc74e.development.esm.js} +946 -68
  22. package/dist/{raise-f4ad5a87.development.esm.js → raise-5854eaca.esm.js} +860 -49
  23. package/dist/{raise-23dea0d7.development.cjs.js → raise-ed700d14.development.cjs.js} +922 -36
  24. package/dist/{raise-8dc8e1aa.esm.js → raise-fb6f017b.cjs.js} +907 -2
  25. package/dist/{send-0174c155.development.cjs.js → send-00466e37.development.cjs.js} +11 -12
  26. package/dist/{send-87bbaaab.cjs.js → send-53e5693c.cjs.js} +11 -12
  27. package/dist/{send-5d129d95.development.esm.js → send-a0193bdb.development.esm.js} +2 -3
  28. package/dist/{send-84e2e742.esm.js → send-b7b4befa.esm.js} +2 -3
  29. package/dist/xstate.cjs.js +25 -25
  30. package/dist/xstate.cjs.mjs +1 -0
  31. package/dist/xstate.development.cjs.js +25 -25
  32. package/dist/xstate.development.cjs.mjs +1 -0
  33. package/dist/xstate.development.esm.js +4 -6
  34. package/dist/xstate.esm.js +4 -6
  35. package/dist/xstate.umd.min.js +1 -1
  36. package/dist/xstate.umd.min.js.map +1 -1
  37. package/guards/dist/xstate-guards.cjs.js +1 -2
  38. package/guards/dist/xstate-guards.development.cjs.js +1 -2
  39. package/guards/dist/xstate-guards.development.esm.js +1 -2
  40. package/guards/dist/xstate-guards.esm.js +1 -2
  41. package/guards/dist/xstate-guards.umd.min.js.map +1 -1
  42. package/package.json +1 -1
  43. package/dist/interpreter-36d5556e.cjs.js +0 -887
  44. package/dist/interpreter-4e8e2a0d.development.cjs.js +0 -898
  45. package/dist/interpreter-63c80754.esm.js +0 -857
  46. package/dist/interpreter-80eb3bec.development.esm.js +0 -868
@@ -1,857 +0,0 @@
1
- import { devToolsAdapter } from '../dev/dist/xstate-dev.esm.js';
2
-
3
- class Mailbox {
4
- constructor(_process) {
5
- this._process = _process;
6
- this._active = false;
7
- this._current = null;
8
- this._last = null;
9
- }
10
- start() {
11
- this._active = true;
12
- this.flush();
13
- }
14
- clear() {
15
- // we can't set _current to null because we might be currently processing
16
- // and enqueue following clear shouldnt start processing the enqueued item immediately
17
- if (this._current) {
18
- this._current.next = null;
19
- this._last = this._current;
20
- }
21
- }
22
- enqueue(event) {
23
- const enqueued = {
24
- value: event,
25
- next: null
26
- };
27
- if (this._current) {
28
- this._last.next = enqueued;
29
- this._last = enqueued;
30
- return;
31
- }
32
- this._current = enqueued;
33
- this._last = enqueued;
34
- if (this._active) {
35
- this.flush();
36
- }
37
- }
38
- flush() {
39
- while (this._current) {
40
- // atm the given _process is responsible for implementing proper try/catch handling
41
- // we assume here that this won't throw in a way that can affect this mailbox
42
- const consumed = this._current;
43
- this._process(consumed.value);
44
- this._current = consumed.next;
45
- }
46
- this._last = null;
47
- }
48
- }
49
-
50
- const STATE_DELIMITER = '.';
51
- const TARGETLESS_KEY = '';
52
- const NULL_EVENT = '';
53
- const STATE_IDENTIFIER = '#';
54
- const WILDCARD = '*';
55
- const XSTATE_INIT = 'xstate.init';
56
- const XSTATE_ERROR = 'xstate.error';
57
- const XSTATE_STOP = 'xstate.stop';
58
-
59
- /**
60
- * Returns an event that represents an implicit event that
61
- * is sent after the specified `delay`.
62
- *
63
- * @param delayRef The delay in milliseconds
64
- * @param id The state node ID where this event is handled
65
- */
66
- function createAfterEvent(delayRef, id) {
67
- const idSuffix = id ? `#${id}` : '';
68
- return {
69
- type: `xstate.after(${delayRef})${idSuffix}`
70
- };
71
- }
72
-
73
- /**
74
- * Returns an event that represents that a final state node
75
- * has been reached in the parent state node.
76
- *
77
- * @param id The final state node's parent state node `id`
78
- * @param output The data to pass into the event
79
- */
80
- function createDoneStateEvent(id, output) {
81
- return {
82
- type: `xstate.done.state.${id}`,
83
- output
84
- };
85
- }
86
-
87
- /**
88
- * Returns an event that represents that an invoked service has terminated.
89
- *
90
- * An invoked service is terminated when it has reached a top-level final state node,
91
- * but not when it is canceled.
92
- *
93
- * @param invokeId The invoked service ID
94
- * @param output The data to pass into the event
95
- */
96
- function createDoneActorEvent(invokeId, output) {
97
- return {
98
- type: `xstate.done.actor.${invokeId}`,
99
- output
100
- };
101
- }
102
- function createErrorActorEvent(id, data) {
103
- return {
104
- type: `xstate.error.actor.${id}`,
105
- data
106
- };
107
- }
108
- function createInitEvent(input) {
109
- return {
110
- type: XSTATE_INIT,
111
- input
112
- };
113
- }
114
-
115
- /**
116
- * This function makes sure that unhandled errors are thrown in a separate macrotask.
117
- * It allows those errors to be detected by global error handlers and reported to bug tracking services
118
- * without interrupting our own stack of execution.
119
- *
120
- * @param err error to be thrown
121
- */
122
- function reportUnhandledError(err) {
123
- setTimeout(() => {
124
- throw err;
125
- });
126
- }
127
-
128
- const symbolObservable = (() => typeof Symbol === 'function' && Symbol.observable || '@@observable')();
129
-
130
- let idCounter = 0;
131
- function createSystem(rootActor) {
132
- const children = new Map();
133
- const keyedActors = new Map();
134
- const reverseKeyedActors = new WeakMap();
135
- const observers = new Set();
136
- const system = {
137
- _bookId: () => `x:${idCounter++}`,
138
- _register: (sessionId, actorRef) => {
139
- children.set(sessionId, actorRef);
140
- return sessionId;
141
- },
142
- _unregister: actorRef => {
143
- children.delete(actorRef.sessionId);
144
- const systemId = reverseKeyedActors.get(actorRef);
145
- if (systemId !== undefined) {
146
- keyedActors.delete(systemId);
147
- reverseKeyedActors.delete(actorRef);
148
- }
149
- },
150
- get: systemId => {
151
- return keyedActors.get(systemId);
152
- },
153
- _set: (systemId, actorRef) => {
154
- const existing = keyedActors.get(systemId);
155
- if (existing && existing !== actorRef) {
156
- throw new Error(`Actor with system ID '${systemId}' already exists.`);
157
- }
158
- keyedActors.set(systemId, actorRef);
159
- reverseKeyedActors.set(actorRef, systemId);
160
- },
161
- inspect: observer => {
162
- observers.add(observer);
163
- },
164
- _sendInspectionEvent: event => {
165
- const resolvedInspectionEvent = {
166
- ...event,
167
- rootId: rootActor.sessionId
168
- };
169
- observers.forEach(observer => observer.next?.(resolvedInspectionEvent));
170
- },
171
- _relay: (source, target, event) => {
172
- system._sendInspectionEvent({
173
- type: '@xstate.event',
174
- sourceRef: source,
175
- actorRef: target,
176
- event
177
- });
178
- target._send(event);
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 resolveOutput(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}[${index}]`;
315
- }
316
- function resolveReferencedActor(machine, src) {
317
- if (src.startsWith('xstate#')) {
318
- const [, indexStr] = src.match(/\[(\d+)\]$/);
319
- const node = machine.getStateNodeById(src.slice(7, -(indexStr.length + 2)));
320
- const invokeConfig = node.config.invoke;
321
- return (Array.isArray(invokeConfig) ? invokeConfig[indexStr] : invokeConfig).src;
322
- }
323
- return machine.implementations.actors[src];
324
- }
325
-
326
- const $$ACTOR_TYPE = 1;
327
- // those values are currently used by @xstate/react directly so it's important to keep the assigned values in sync
328
- let ProcessingStatus = /*#__PURE__*/function (ProcessingStatus) {
329
- ProcessingStatus[ProcessingStatus["NotStarted"] = 0] = "NotStarted";
330
- ProcessingStatus[ProcessingStatus["Running"] = 1] = "Running";
331
- ProcessingStatus[ProcessingStatus["Stopped"] = 2] = "Stopped";
332
- return ProcessingStatus;
333
- }({});
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
-
347
- /**
348
- * An Actor is a running process that can receive events, send events and change its behavior based on the events it receives, which can cause effects outside of the actor. When you run a state machine, it becomes an actor.
349
- */
350
- class Actor {
351
- /**
352
- * The current internal state of the actor.
353
- */
354
-
355
- /**
356
- * The clock that is responsible for setting and clearing timeouts, such as delayed events and transitions.
357
- */
358
-
359
- /**
360
- * The unique identifier for this actor relative to its parent.
361
- */
362
-
363
- /** @internal */
364
-
365
- // Actor Ref
366
-
367
- // TODO: add typings for system
368
-
369
- /**
370
- * The globally unique process ID for this invocation.
371
- */
372
-
373
- /**
374
- * The system to which this actor belongs.
375
- */
376
-
377
- /**
378
- * Creates a new actor instance for the given logic with the provided options, if any.
379
- *
380
- * @param logic The logic to create an actor from
381
- * @param options Actor options
382
- */
383
- constructor(logic, options) {
384
- this.logic = logic;
385
- this._state = void 0;
386
- this.clock = void 0;
387
- this.options = void 0;
388
- this.id = void 0;
389
- this.mailbox = new Mailbox(this._process.bind(this));
390
- this.delayedEventsMap = {};
391
- this.observers = new Set();
392
- this.logger = void 0;
393
- this._processingStatus = ProcessingStatus.NotStarted;
394
- this._parent = void 0;
395
- this.ref = void 0;
396
- this._actorScope = void 0;
397
- this._systemId = void 0;
398
- this.sessionId = void 0;
399
- this.system = void 0;
400
- this._doneEvent = void 0;
401
- this.src = void 0;
402
- this._deferred = [];
403
- const resolvedOptions = {
404
- ...defaultOptions,
405
- ...options
406
- };
407
- const {
408
- clock,
409
- logger,
410
- parent,
411
- id,
412
- systemId,
413
- inspect
414
- } = resolvedOptions;
415
- this.system = parent?.system ?? createSystem(this);
416
- if (inspect && !parent) {
417
- // Always inspect at the system-level
418
- this.system.inspect(toObserver(inspect));
419
- }
420
- this.sessionId = this.system._bookId();
421
- this.id = id ?? this.sessionId;
422
- this.logger = logger;
423
- this.clock = clock;
424
- this._parent = parent;
425
- this.options = resolvedOptions;
426
- this.src = resolvedOptions.src ?? logic;
427
- this.ref = this;
428
- this._actorScope = {
429
- self: this,
430
- id: this.id,
431
- sessionId: this.sessionId,
432
- logger: this.logger,
433
- defer: fn => {
434
- this._deferred.push(fn);
435
- },
436
- system: this.system,
437
- stopChild: child => {
438
- if (child._parent !== this) {
439
- throw new Error(`Cannot stop child actor ${child.id} of ${this.id} because it is not a child`);
440
- }
441
- child._stop();
442
- }
443
- };
444
-
445
- // Ensure that the send method is bound to this Actor instance
446
- // if destructured
447
- this.send = this.send.bind(this);
448
- this.system._sendInspectionEvent({
449
- type: '@xstate.actor',
450
- actorRef: this
451
- });
452
- this._initState(options?.state);
453
- if (systemId && this._state.status === 'active') {
454
- this._systemId = systemId;
455
- this.system._set(systemId, this);
456
- }
457
- }
458
- _initState(persistedState) {
459
- this._state = persistedState ? this.logic.restoreState ? this.logic.restoreState(persistedState, this._actorScope) : persistedState : this.logic.getInitialState(this._actorScope, this.options?.input);
460
- }
461
-
462
- // array of functions to defer
463
-
464
- update(snapshot, event) {
465
- // Update state
466
- this._state = snapshot;
467
-
468
- // Execute deferred effects
469
- let deferredFn;
470
- while (deferredFn = this._deferred.shift()) {
471
- deferredFn();
472
- }
473
- for (const observer of this.observers) {
474
- try {
475
- observer.next?.(snapshot);
476
- } catch (err) {
477
- reportUnhandledError(err);
478
- }
479
- }
480
- switch (this._state.status) {
481
- case 'done':
482
- this._stopProcedure();
483
- this._complete();
484
- this._doneEvent = createDoneActorEvent(this.id, this._state.output);
485
- if (this._parent) {
486
- this.system._relay(this, this._parent, this._doneEvent);
487
- }
488
- break;
489
- case 'error':
490
- this._stopProcedure();
491
- this._error(this._state.error);
492
- if (this._parent) {
493
- this.system._relay(this, this._parent, createErrorActorEvent(this.id, this._state.error));
494
- }
495
- break;
496
- }
497
- this.system._sendInspectionEvent({
498
- type: '@xstate.snapshot',
499
- actorRef: this,
500
- event,
501
- snapshot
502
- });
503
- }
504
-
505
- /**
506
- * Subscribe an observer to an actor’s snapshot values.
507
- *
508
- * @remarks
509
- * The observer will receive the actor’s snapshot value when it is emitted. The observer can be:
510
- * - A plain function that receives the latest snapshot, or
511
- * - An observer object whose `.next(snapshot)` method receives the latest snapshot
512
- *
513
- * @example
514
- * ```ts
515
- * // Observer as a plain function
516
- * const subscription = actor.subscribe((snapshot) => {
517
- * console.log(snapshot);
518
- * });
519
- * ```
520
- *
521
- * @example
522
- * ```ts
523
- * // Observer as an object
524
- * const subscription = actor.subscribe({
525
- * next(snapshot) {
526
- * console.log(snapshot);
527
- * },
528
- * error(err) {
529
- * // ...
530
- * },
531
- * complete() {
532
- * // ...
533
- * },
534
- * });
535
- * ```
536
- *
537
- * The return value of `actor.subscribe(observer)` is a subscription object that has an `.unsubscribe()` method. You can call `subscription.unsubscribe()` to unsubscribe the observer:
538
- *
539
- * @example
540
- * ```ts
541
- * const subscription = actor.subscribe((snapshot) => {
542
- * // ...
543
- * });
544
- *
545
- * // Unsubscribe the observer
546
- * subscription.unsubscribe();
547
- * ```
548
- *
549
- * When the actor is stopped, all of its observers will automatically be unsubscribed.
550
- *
551
- * @param observer - Either a plain function that receives the latest snapshot, or an observer object whose `.next(snapshot)` method receives the latest snapshot
552
- */
553
-
554
- subscribe(nextListenerOrObserver, errorListener, completeListener) {
555
- const observer = toObserver(nextListenerOrObserver, errorListener, completeListener);
556
- if (this._processingStatus !== ProcessingStatus.Stopped) {
557
- this.observers.add(observer);
558
- } else {
559
- try {
560
- observer.complete?.();
561
- } catch (err) {
562
- reportUnhandledError(err);
563
- }
564
- }
565
- return {
566
- unsubscribe: () => {
567
- this.observers.delete(observer);
568
- }
569
- };
570
- }
571
-
572
- /**
573
- * Starts the Actor from the initial state
574
- */
575
- start() {
576
- if (this._processingStatus === ProcessingStatus.Running) {
577
- // Do not restart the service if it is already started
578
- return this;
579
- }
580
- this.system._register(this.sessionId, this);
581
- if (this._systemId) {
582
- this.system._set(this._systemId, this);
583
- }
584
- this._processingStatus = ProcessingStatus.Running;
585
-
586
- // TODO: this isn't correct when rehydrating
587
- const initEvent = createInitEvent(this.options.input);
588
- this.system._sendInspectionEvent({
589
- type: '@xstate.event',
590
- sourceRef: this._parent,
591
- actorRef: this,
592
- event: initEvent
593
- });
594
- const status = this._state.status;
595
- switch (status) {
596
- case 'done':
597
- // a state machine can be "done" upon initialization (it could reach a final state using initial microsteps)
598
- // we still need to complete observers, flush deferreds etc
599
- this.update(this._state, initEvent);
600
- // fallthrough
601
- case 'error':
602
- // TODO: rethink cleanup of observers, mailbox, etc
603
- return this;
604
- }
605
- if (this.logic.start) {
606
- try {
607
- this.logic.start(this._state, this._actorScope);
608
- } catch (err) {
609
- this._stopProcedure();
610
- this._error(err);
611
- this._parent?.send(createErrorActorEvent(this.id, err));
612
- return this;
613
- }
614
- }
615
-
616
- // TODO: this notifies all subscribers but usually this is redundant
617
- // there is no real change happening here
618
- // we need to rethink if this needs to be refactored
619
- this.update(this._state, initEvent);
620
- if (this.options.devTools) {
621
- this.attachDevTools();
622
- }
623
- this.mailbox.start();
624
- return this;
625
- }
626
- _process(event) {
627
- // TODO: reexamine what happens when an action (or a guard or smth) throws
628
- let nextState;
629
- let caughtError;
630
- try {
631
- nextState = this.logic.transition(this._state, event, this._actorScope);
632
- } catch (err) {
633
- // we wrap it in a box so we can rethrow it later even if falsy value gets caught here
634
- caughtError = {
635
- err
636
- };
637
- }
638
- if (caughtError) {
639
- const {
640
- err
641
- } = caughtError;
642
- this._stopProcedure();
643
- this._error(err);
644
- this._parent?.send(createErrorActorEvent(this.id, err));
645
- return;
646
- }
647
- this.update(nextState, event);
648
- if (event.type === XSTATE_STOP) {
649
- this._stopProcedure();
650
- this._complete();
651
- }
652
- }
653
- _stop() {
654
- if (this._processingStatus === ProcessingStatus.Stopped) {
655
- return this;
656
- }
657
- this.mailbox.clear();
658
- if (this._processingStatus === ProcessingStatus.NotStarted) {
659
- this._processingStatus = ProcessingStatus.Stopped;
660
- return this;
661
- }
662
- this.mailbox.enqueue({
663
- type: XSTATE_STOP
664
- });
665
- return this;
666
- }
667
-
668
- /**
669
- * Stops the Actor and unsubscribe all listeners.
670
- */
671
- stop() {
672
- if (this._parent) {
673
- throw new Error('A non-root actor cannot be stopped directly.');
674
- }
675
- return this._stop();
676
- }
677
- _complete() {
678
- for (const observer of this.observers) {
679
- try {
680
- observer.complete?.();
681
- } catch (err) {
682
- reportUnhandledError(err);
683
- }
684
- }
685
- this.observers.clear();
686
- }
687
- _error(err) {
688
- if (!this.observers.size) {
689
- if (!this._parent) {
690
- reportUnhandledError(err);
691
- }
692
- return;
693
- }
694
- let reportError = false;
695
- for (const observer of this.observers) {
696
- const errorListener = observer.error;
697
- reportError ||= !errorListener;
698
- try {
699
- errorListener?.(err);
700
- } catch (err2) {
701
- reportUnhandledError(err2);
702
- }
703
- }
704
- this.observers.clear();
705
- if (reportError) {
706
- reportUnhandledError(err);
707
- }
708
- }
709
- _stopProcedure() {
710
- if (this._processingStatus !== ProcessingStatus.Running) {
711
- // Actor already stopped; do nothing
712
- return this;
713
- }
714
-
715
- // Cancel all delayed events
716
- for (const key of Object.keys(this.delayedEventsMap)) {
717
- this.clock.clearTimeout(this.delayedEventsMap[key]);
718
- }
719
-
720
- // TODO: mailbox.reset
721
- this.mailbox.clear();
722
- // TODO: after `stop` we must prepare ourselves for receiving events again
723
- // events sent *after* stop signal must be queued
724
- // it seems like this should be the common behavior for all of our consumers
725
- // so perhaps this should be unified somehow for all of them
726
- this.mailbox = new Mailbox(this._process.bind(this));
727
- this._processingStatus = ProcessingStatus.Stopped;
728
- this.system._unregister(this);
729
- return this;
730
- }
731
-
732
- /**
733
- * @internal
734
- */
735
- _send(event) {
736
- if (this._processingStatus === ProcessingStatus.Stopped) {
737
- return;
738
- }
739
- this.mailbox.enqueue(event);
740
- }
741
-
742
- /**
743
- * Sends an event to the running Actor to trigger a transition.
744
- *
745
- * @param event The event to send
746
- */
747
- send(event) {
748
- this.system._relay(undefined, this, event);
749
- }
750
-
751
- /**
752
- * TODO: figure out a way to do this within the machine
753
- * @internal
754
- */
755
- delaySend(params) {
756
- const {
757
- event,
758
- id,
759
- delay
760
- } = params;
761
- const timerId = this.clock.setTimeout(() => {
762
- this.system._relay(this, params.to ?? this, event);
763
- }, delay);
764
-
765
- // TODO: consider the rehydration story here
766
- if (id) {
767
- this.delayedEventsMap[id] = timerId;
768
- }
769
- }
770
-
771
- /**
772
- * TODO: figure out a way to do this within the machine
773
- * @internal
774
- */
775
- cancel(sendId) {
776
- this.clock.clearTimeout(this.delayedEventsMap[sendId]);
777
- delete this.delayedEventsMap[sendId];
778
- }
779
- attachDevTools() {
780
- const {
781
- devTools
782
- } = this.options;
783
- if (devTools) {
784
- const resolvedDevToolsAdapter = typeof devTools === 'function' ? devTools : devToolsAdapter;
785
- resolvedDevToolsAdapter(this);
786
- }
787
- }
788
- toJSON() {
789
- return {
790
- xstate$$type: $$ACTOR_TYPE,
791
- id: this.id
792
- };
793
- }
794
-
795
- /**
796
- * Obtain the internal state of the actor, which can be persisted.
797
- *
798
- * @remarks
799
- * The internal state can be persisted from any actor, not only machines.
800
- *
801
- * Note that the persisted state is not the same as the snapshot from {@link Actor.getSnapshot}. Persisted state represents the internal state of the actor, while snapshots represent the actor's last emitted value.
802
- *
803
- * Can be restored with {@link ActorOptions.state}
804
- *
805
- * @see https://stately.ai/docs/persistence
806
- */
807
-
808
- getPersistedState(options) {
809
- return this.logic.getPersistedState(this._state, options);
810
- }
811
- [symbolObservable]() {
812
- return this;
813
- }
814
-
815
- /**
816
- * Read an actor’s snapshot synchronously.
817
- *
818
- * @remarks
819
- * The snapshot represent an actor's last emitted value.
820
- *
821
- * When an actor receives an event, its internal state may change.
822
- * An actor may emit a snapshot when a state transition occurs.
823
- *
824
- * Note that some actors, such as callback actors generated with `fromCallback`, will not emit snapshots.
825
- *
826
- * @see {@link Actor.subscribe} to subscribe to an actor’s snapshot values.
827
- * @see {@link Actor.getPersistedState} to persist the internal state of an actor (which is more than just a snapshot).
828
- */
829
- getSnapshot() {
830
- return this._state;
831
- }
832
- }
833
-
834
- /**
835
- * Creates a new `ActorRef` instance for the given machine with the provided options, if any.
836
- *
837
- * @param machine The machine to create an actor from
838
- * @param options `ActorRef` options
839
- */
840
-
841
- function createActor(logic, options) {
842
- const interpreter = new Actor(logic, options);
843
- return interpreter;
844
- }
845
-
846
- /**
847
- * Creates a new Interpreter instance for the given machine with the provided options, if any.
848
- *
849
- * @deprecated Use `createActor` instead
850
- */
851
- const interpret = createActor;
852
-
853
- /**
854
- * @deprecated Use `Actor` instead.
855
- */
856
-
857
- export { $$ACTOR_TYPE as $, Actor as A, NULL_EVENT as N, ProcessingStatus as P, STATE_DELIMITER as S, WILDCARD as W, XSTATE_STOP as X, toTransitionConfigArray as a, createInitEvent as b, createInvokeId as c, createActor as d, interpret as e, matchesState as f, toObserver as g, createErrorActorEvent as h, isErrorActorEvent as i, STATE_IDENTIFIER as j, toStatePath as k, createDoneStateEvent as l, mapValues as m, normalizeTarget as n, resolveOutput as o, pathToStateValue as p, XSTATE_INIT as q, resolveReferencedActor as r, createAfterEvent as s, toArray as t, flatten as u, XSTATE_ERROR as v };