xstate 5.0.0-beta.43 → 5.0.0-beta.45

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 (55) 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 +98 -10
  8. package/actors/dist/xstate-actors.development.cjs.js +98 -10
  9. package/actors/dist/xstate-actors.development.esm.js +93 -5
  10. package/actors/dist/xstate-actors.esm.js +93 -5
  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 +14 -18
  14. package/dist/declarations/src/StateMachine.d.ts +1 -1
  15. package/dist/declarations/src/actions/choose.d.ts +3 -3
  16. package/dist/declarations/src/actions/pure.d.ts +4 -4
  17. package/dist/declarations/src/actions/spawn.d.ts +11 -16
  18. package/dist/declarations/src/actors/observable.d.ts +39 -0
  19. package/dist/declarations/src/actors/transition.d.ts +53 -4
  20. package/dist/declarations/src/{Machine.d.ts → createMachine.d.ts} +1 -1
  21. package/dist/declarations/src/guards.d.ts +27 -5
  22. package/dist/declarations/src/index.d.ts +3 -2
  23. package/dist/declarations/src/interpreter.d.ts +1 -0
  24. package/dist/declarations/src/setup.d.ts +32 -0
  25. package/dist/declarations/src/spawn.d.ts +9 -13
  26. package/dist/declarations/src/stateUtils.d.ts +11 -11
  27. package/dist/declarations/src/types.d.ts +31 -29
  28. package/dist/declarations/src/utils.d.ts +1 -3
  29. package/dist/{raise-8dc8e1aa.esm.js → raise-2b5a4e4c.esm.js} +934 -103
  30. package/dist/{raise-f4ad5a87.development.esm.js → raise-90139fbc.development.esm.js} +945 -103
  31. package/dist/{raise-23dea0d7.development.cjs.js → raise-b3fb3c65.development.cjs.js} +999 -137
  32. package/dist/{raise-e0fe5c2d.cjs.js → raise-fabffc3d.cjs.js} +986 -135
  33. package/dist/{send-5d129d95.development.esm.js → send-24cc8018.development.esm.js} +4 -30
  34. package/dist/{send-84e2e742.esm.js → send-8e7e41e7.esm.js} +4 -30
  35. package/dist/{send-87bbaaab.cjs.js → send-c124176f.cjs.js} +13 -39
  36. package/dist/{send-0174c155.development.cjs.js → send-d0bc7eed.development.cjs.js} +13 -39
  37. package/dist/xstate.cjs.js +67 -35
  38. package/dist/xstate.cjs.mjs +2 -0
  39. package/dist/xstate.development.cjs.js +67 -35
  40. package/dist/xstate.development.cjs.mjs +2 -0
  41. package/dist/xstate.development.esm.js +42 -13
  42. package/dist/xstate.esm.js +42 -13
  43. package/dist/xstate.umd.min.js +1 -1
  44. package/dist/xstate.umd.min.js.map +1 -1
  45. package/guards/dist/xstate-guards.cjs.js +1 -2
  46. package/guards/dist/xstate-guards.development.cjs.js +1 -2
  47. package/guards/dist/xstate-guards.development.esm.js +1 -2
  48. package/guards/dist/xstate-guards.esm.js +1 -2
  49. package/guards/dist/xstate-guards.umd.min.js +1 -1
  50. package/guards/dist/xstate-guards.umd.min.js.map +1 -1
  51. package/package.json +1 -1
  52. package/dist/interpreter-36d5556e.cjs.js +0 -887
  53. package/dist/interpreter-4e8e2a0d.development.cjs.js +0 -898
  54. package/dist/interpreter-63c80754.esm.js +0 -857
  55. package/dist/interpreter-80eb3bec.development.esm.js +0 -868
@@ -1,868 +0,0 @@
1
- import { devToolsAdapter } from '../dev/dist/xstate-dev.development.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
- if (!!mapper && typeof mapper === 'object' && Object.values(mapper).some(val => typeof val === 'function')) {
281
- 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('')}`);
282
- }
283
- return mapper;
284
- }
285
- function isArray(value) {
286
- return Array.isArray(value);
287
- }
288
- function isErrorActorEvent(event) {
289
- return event.type.startsWith('xstate.error.actor');
290
- }
291
- function toTransitionConfigArray(configLike) {
292
- return toArrayStrict(configLike).map(transitionLike => {
293
- if (typeof transitionLike === 'undefined' || typeof transitionLike === 'string') {
294
- return {
295
- target: transitionLike
296
- };
297
- }
298
- return transitionLike;
299
- });
300
- }
301
- function normalizeTarget(target) {
302
- if (target === undefined || target === TARGETLESS_KEY) {
303
- return undefined;
304
- }
305
- return toArray(target);
306
- }
307
- function toObserver(nextHandler, errorHandler, completionHandler) {
308
- const isObserver = typeof nextHandler === 'object';
309
- const self = isObserver ? nextHandler : undefined;
310
- return {
311
- next: (isObserver ? nextHandler.next : nextHandler)?.bind(self),
312
- error: (isObserver ? nextHandler.error : errorHandler)?.bind(self),
313
- complete: (isObserver ? nextHandler.complete : completionHandler)?.bind(self)
314
- };
315
- }
316
- function createInvokeId(stateNodeId, index) {
317
- return `${stateNodeId}[${index}]`;
318
- }
319
- function resolveReferencedActor(machine, src) {
320
- if (src.startsWith('xstate#')) {
321
- const [, indexStr] = src.match(/\[(\d+)\]$/);
322
- const node = machine.getStateNodeById(src.slice(7, -(indexStr.length + 2)));
323
- const invokeConfig = node.config.invoke;
324
- return (Array.isArray(invokeConfig) ? invokeConfig[indexStr] : invokeConfig).src;
325
- }
326
- return machine.implementations.actors[src];
327
- }
328
-
329
- const $$ACTOR_TYPE = 1;
330
- // those values are currently used by @xstate/react directly so it's important to keep the assigned values in sync
331
- let ProcessingStatus = /*#__PURE__*/function (ProcessingStatus) {
332
- ProcessingStatus[ProcessingStatus["NotStarted"] = 0] = "NotStarted";
333
- ProcessingStatus[ProcessingStatus["Running"] = 1] = "Running";
334
- ProcessingStatus[ProcessingStatus["Stopped"] = 2] = "Stopped";
335
- return ProcessingStatus;
336
- }({});
337
- const defaultOptions = {
338
- clock: {
339
- setTimeout: (fn, ms) => {
340
- return setTimeout(fn, ms);
341
- },
342
- clearTimeout: id => {
343
- return clearTimeout(id);
344
- }
345
- },
346
- logger: console.log.bind(console),
347
- devTools: false
348
- };
349
-
350
- /**
351
- * 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.
352
- */
353
- class Actor {
354
- /**
355
- * The current internal state of the actor.
356
- */
357
-
358
- /**
359
- * The clock that is responsible for setting and clearing timeouts, such as delayed events and transitions.
360
- */
361
-
362
- /**
363
- * The unique identifier for this actor relative to its parent.
364
- */
365
-
366
- /** @internal */
367
-
368
- // Actor Ref
369
-
370
- // TODO: add typings for system
371
-
372
- /**
373
- * The globally unique process ID for this invocation.
374
- */
375
-
376
- /**
377
- * The system to which this actor belongs.
378
- */
379
-
380
- /**
381
- * Creates a new actor instance for the given logic with the provided options, if any.
382
- *
383
- * @param logic The logic to create an actor from
384
- * @param options Actor options
385
- */
386
- constructor(logic, options) {
387
- this.logic = logic;
388
- this._state = void 0;
389
- this.clock = void 0;
390
- this.options = void 0;
391
- this.id = void 0;
392
- this.mailbox = new Mailbox(this._process.bind(this));
393
- this.delayedEventsMap = {};
394
- this.observers = new Set();
395
- this.logger = void 0;
396
- this._processingStatus = ProcessingStatus.NotStarted;
397
- this._parent = void 0;
398
- this.ref = void 0;
399
- this._actorScope = void 0;
400
- this._systemId = void 0;
401
- this.sessionId = void 0;
402
- this.system = void 0;
403
- this._doneEvent = void 0;
404
- this.src = void 0;
405
- this._deferred = [];
406
- const resolvedOptions = {
407
- ...defaultOptions,
408
- ...options
409
- };
410
- const {
411
- clock,
412
- logger,
413
- parent,
414
- id,
415
- systemId,
416
- inspect
417
- } = resolvedOptions;
418
- this.system = parent?.system ?? createSystem(this);
419
- if (inspect && !parent) {
420
- // Always inspect at the system-level
421
- this.system.inspect(toObserver(inspect));
422
- }
423
- this.sessionId = this.system._bookId();
424
- this.id = id ?? this.sessionId;
425
- this.logger = logger;
426
- this.clock = clock;
427
- this._parent = parent;
428
- this.options = resolvedOptions;
429
- this.src = resolvedOptions.src ?? logic;
430
- this.ref = this;
431
- this._actorScope = {
432
- self: this,
433
- id: this.id,
434
- sessionId: this.sessionId,
435
- logger: this.logger,
436
- defer: fn => {
437
- this._deferred.push(fn);
438
- },
439
- system: this.system,
440
- stopChild: child => {
441
- if (child._parent !== this) {
442
- throw new Error(`Cannot stop child actor ${child.id} of ${this.id} because it is not a child`);
443
- }
444
- child._stop();
445
- }
446
- };
447
-
448
- // Ensure that the send method is bound to this Actor instance
449
- // if destructured
450
- this.send = this.send.bind(this);
451
- this.system._sendInspectionEvent({
452
- type: '@xstate.actor',
453
- actorRef: this
454
- });
455
- this._initState(options?.state);
456
- if (systemId && this._state.status === 'active') {
457
- this._systemId = systemId;
458
- this.system._set(systemId, this);
459
- }
460
- }
461
- _initState(persistedState) {
462
- this._state = persistedState ? this.logic.restoreState ? this.logic.restoreState(persistedState, this._actorScope) : persistedState : this.logic.getInitialState(this._actorScope, this.options?.input);
463
- }
464
-
465
- // array of functions to defer
466
-
467
- update(snapshot, event) {
468
- // Update state
469
- this._state = snapshot;
470
-
471
- // Execute deferred effects
472
- let deferredFn;
473
- while (deferredFn = this._deferred.shift()) {
474
- deferredFn();
475
- }
476
- for (const observer of this.observers) {
477
- try {
478
- observer.next?.(snapshot);
479
- } catch (err) {
480
- reportUnhandledError(err);
481
- }
482
- }
483
- switch (this._state.status) {
484
- case 'done':
485
- this._stopProcedure();
486
- this._complete();
487
- this._doneEvent = createDoneActorEvent(this.id, this._state.output);
488
- if (this._parent) {
489
- this.system._relay(this, this._parent, this._doneEvent);
490
- }
491
- break;
492
- case 'error':
493
- this._stopProcedure();
494
- this._error(this._state.error);
495
- if (this._parent) {
496
- this.system._relay(this, this._parent, createErrorActorEvent(this.id, this._state.error));
497
- }
498
- break;
499
- }
500
- this.system._sendInspectionEvent({
501
- type: '@xstate.snapshot',
502
- actorRef: this,
503
- event,
504
- snapshot
505
- });
506
- }
507
-
508
- /**
509
- * Subscribe an observer to an actor’s snapshot values.
510
- *
511
- * @remarks
512
- * The observer will receive the actor’s snapshot value when it is emitted. The observer can be:
513
- * - A plain function that receives the latest snapshot, or
514
- * - An observer object whose `.next(snapshot)` method receives the latest snapshot
515
- *
516
- * @example
517
- * ```ts
518
- * // Observer as a plain function
519
- * const subscription = actor.subscribe((snapshot) => {
520
- * console.log(snapshot);
521
- * });
522
- * ```
523
- *
524
- * @example
525
- * ```ts
526
- * // Observer as an object
527
- * const subscription = actor.subscribe({
528
- * next(snapshot) {
529
- * console.log(snapshot);
530
- * },
531
- * error(err) {
532
- * // ...
533
- * },
534
- * complete() {
535
- * // ...
536
- * },
537
- * });
538
- * ```
539
- *
540
- * 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:
541
- *
542
- * @example
543
- * ```ts
544
- * const subscription = actor.subscribe((snapshot) => {
545
- * // ...
546
- * });
547
- *
548
- * // Unsubscribe the observer
549
- * subscription.unsubscribe();
550
- * ```
551
- *
552
- * When the actor is stopped, all of its observers will automatically be unsubscribed.
553
- *
554
- * @param observer - Either a plain function that receives the latest snapshot, or an observer object whose `.next(snapshot)` method receives the latest snapshot
555
- */
556
-
557
- subscribe(nextListenerOrObserver, errorListener, completeListener) {
558
- const observer = toObserver(nextListenerOrObserver, errorListener, completeListener);
559
- if (this._processingStatus !== ProcessingStatus.Stopped) {
560
- this.observers.add(observer);
561
- } else {
562
- try {
563
- observer.complete?.();
564
- } catch (err) {
565
- reportUnhandledError(err);
566
- }
567
- }
568
- return {
569
- unsubscribe: () => {
570
- this.observers.delete(observer);
571
- }
572
- };
573
- }
574
-
575
- /**
576
- * Starts the Actor from the initial state
577
- */
578
- start() {
579
- if (this._processingStatus === ProcessingStatus.Running) {
580
- // Do not restart the service if it is already started
581
- return this;
582
- }
583
- this.system._register(this.sessionId, this);
584
- if (this._systemId) {
585
- this.system._set(this._systemId, this);
586
- }
587
- this._processingStatus = ProcessingStatus.Running;
588
-
589
- // TODO: this isn't correct when rehydrating
590
- const initEvent = createInitEvent(this.options.input);
591
- this.system._sendInspectionEvent({
592
- type: '@xstate.event',
593
- sourceRef: this._parent,
594
- actorRef: this,
595
- event: initEvent
596
- });
597
- const status = this._state.status;
598
- switch (status) {
599
- case 'done':
600
- // a state machine can be "done" upon initialization (it could reach a final state using initial microsteps)
601
- // we still need to complete observers, flush deferreds etc
602
- this.update(this._state, initEvent);
603
- // fallthrough
604
- case 'error':
605
- // TODO: rethink cleanup of observers, mailbox, etc
606
- return this;
607
- }
608
- if (this.logic.start) {
609
- try {
610
- this.logic.start(this._state, this._actorScope);
611
- } catch (err) {
612
- this._stopProcedure();
613
- this._error(err);
614
- this._parent?.send(createErrorActorEvent(this.id, err));
615
- return this;
616
- }
617
- }
618
-
619
- // TODO: this notifies all subscribers but usually this is redundant
620
- // there is no real change happening here
621
- // we need to rethink if this needs to be refactored
622
- this.update(this._state, initEvent);
623
- if (this.options.devTools) {
624
- this.attachDevTools();
625
- }
626
- this.mailbox.start();
627
- return this;
628
- }
629
- _process(event) {
630
- // TODO: reexamine what happens when an action (or a guard or smth) throws
631
- let nextState;
632
- let caughtError;
633
- try {
634
- nextState = this.logic.transition(this._state, event, this._actorScope);
635
- } catch (err) {
636
- // we wrap it in a box so we can rethrow it later even if falsy value gets caught here
637
- caughtError = {
638
- err
639
- };
640
- }
641
- if (caughtError) {
642
- const {
643
- err
644
- } = caughtError;
645
- this._stopProcedure();
646
- this._error(err);
647
- this._parent?.send(createErrorActorEvent(this.id, err));
648
- return;
649
- }
650
- this.update(nextState, event);
651
- if (event.type === XSTATE_STOP) {
652
- this._stopProcedure();
653
- this._complete();
654
- }
655
- }
656
- _stop() {
657
- if (this._processingStatus === ProcessingStatus.Stopped) {
658
- return this;
659
- }
660
- this.mailbox.clear();
661
- if (this._processingStatus === ProcessingStatus.NotStarted) {
662
- this._processingStatus = ProcessingStatus.Stopped;
663
- return this;
664
- }
665
- this.mailbox.enqueue({
666
- type: XSTATE_STOP
667
- });
668
- return this;
669
- }
670
-
671
- /**
672
- * Stops the Actor and unsubscribe all listeners.
673
- */
674
- stop() {
675
- if (this._parent) {
676
- throw new Error('A non-root actor cannot be stopped directly.');
677
- }
678
- return this._stop();
679
- }
680
- _complete() {
681
- for (const observer of this.observers) {
682
- try {
683
- observer.complete?.();
684
- } catch (err) {
685
- reportUnhandledError(err);
686
- }
687
- }
688
- this.observers.clear();
689
- }
690
- _error(err) {
691
- if (!this.observers.size) {
692
- if (!this._parent) {
693
- reportUnhandledError(err);
694
- }
695
- return;
696
- }
697
- let reportError = false;
698
- for (const observer of this.observers) {
699
- const errorListener = observer.error;
700
- reportError ||= !errorListener;
701
- try {
702
- errorListener?.(err);
703
- } catch (err2) {
704
- reportUnhandledError(err2);
705
- }
706
- }
707
- this.observers.clear();
708
- if (reportError) {
709
- reportUnhandledError(err);
710
- }
711
- }
712
- _stopProcedure() {
713
- if (this._processingStatus !== ProcessingStatus.Running) {
714
- // Actor already stopped; do nothing
715
- return this;
716
- }
717
-
718
- // Cancel all delayed events
719
- for (const key of Object.keys(this.delayedEventsMap)) {
720
- this.clock.clearTimeout(this.delayedEventsMap[key]);
721
- }
722
-
723
- // TODO: mailbox.reset
724
- this.mailbox.clear();
725
- // TODO: after `stop` we must prepare ourselves for receiving events again
726
- // events sent *after* stop signal must be queued
727
- // it seems like this should be the common behavior for all of our consumers
728
- // so perhaps this should be unified somehow for all of them
729
- this.mailbox = new Mailbox(this._process.bind(this));
730
- this._processingStatus = ProcessingStatus.Stopped;
731
- this.system._unregister(this);
732
- return this;
733
- }
734
-
735
- /**
736
- * @internal
737
- */
738
- _send(event) {
739
- if (this._processingStatus === ProcessingStatus.Stopped) {
740
- // do nothing
741
- {
742
- const eventString = JSON.stringify(event);
743
- console.warn(`Event "${event.type}" was sent to stopped actor "${this.id} (${this.sessionId})". This actor has already reached its final state, and will not transition.\nEvent: ${eventString}`);
744
- }
745
- return;
746
- }
747
- this.mailbox.enqueue(event);
748
- }
749
-
750
- /**
751
- * Sends an event to the running Actor to trigger a transition.
752
- *
753
- * @param event The event to send
754
- */
755
- send(event) {
756
- if (typeof event === 'string') {
757
- throw new Error(`Only event objects may be sent to actors; use .send({ type: "${event}" }) instead`);
758
- }
759
- this.system._relay(undefined, this, event);
760
- }
761
-
762
- /**
763
- * TODO: figure out a way to do this within the machine
764
- * @internal
765
- */
766
- delaySend(params) {
767
- const {
768
- event,
769
- id,
770
- delay
771
- } = params;
772
- const timerId = this.clock.setTimeout(() => {
773
- this.system._relay(this, params.to ?? this, event);
774
- }, delay);
775
-
776
- // TODO: consider the rehydration story here
777
- if (id) {
778
- this.delayedEventsMap[id] = timerId;
779
- }
780
- }
781
-
782
- /**
783
- * TODO: figure out a way to do this within the machine
784
- * @internal
785
- */
786
- cancel(sendId) {
787
- this.clock.clearTimeout(this.delayedEventsMap[sendId]);
788
- delete this.delayedEventsMap[sendId];
789
- }
790
- attachDevTools() {
791
- const {
792
- devTools
793
- } = this.options;
794
- if (devTools) {
795
- const resolvedDevToolsAdapter = typeof devTools === 'function' ? devTools : devToolsAdapter;
796
- resolvedDevToolsAdapter(this);
797
- }
798
- }
799
- toJSON() {
800
- return {
801
- xstate$$type: $$ACTOR_TYPE,
802
- id: this.id
803
- };
804
- }
805
-
806
- /**
807
- * Obtain the internal state of the actor, which can be persisted.
808
- *
809
- * @remarks
810
- * The internal state can be persisted from any actor, not only machines.
811
- *
812
- * 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.
813
- *
814
- * Can be restored with {@link ActorOptions.state}
815
- *
816
- * @see https://stately.ai/docs/persistence
817
- */
818
-
819
- getPersistedState(options) {
820
- return this.logic.getPersistedState(this._state, options);
821
- }
822
- [symbolObservable]() {
823
- return this;
824
- }
825
-
826
- /**
827
- * Read an actor’s snapshot synchronously.
828
- *
829
- * @remarks
830
- * The snapshot represent an actor's last emitted value.
831
- *
832
- * When an actor receives an event, its internal state may change.
833
- * An actor may emit a snapshot when a state transition occurs.
834
- *
835
- * Note that some actors, such as callback actors generated with `fromCallback`, will not emit snapshots.
836
- *
837
- * @see {@link Actor.subscribe} to subscribe to an actor’s snapshot values.
838
- * @see {@link Actor.getPersistedState} to persist the internal state of an actor (which is more than just a snapshot).
839
- */
840
- getSnapshot() {
841
- return this._state;
842
- }
843
- }
844
-
845
- /**
846
- * Creates a new `ActorRef` instance for the given machine with the provided options, if any.
847
- *
848
- * @param machine The machine to create an actor from
849
- * @param options `ActorRef` options
850
- */
851
-
852
- function createActor(logic, options) {
853
- const interpreter = new Actor(logic, options);
854
- return interpreter;
855
- }
856
-
857
- /**
858
- * Creates a new Interpreter instance for the given machine with the provided options, if any.
859
- *
860
- * @deprecated Use `createActor` instead
861
- */
862
- const interpret = createActor;
863
-
864
- /**
865
- * @deprecated Use `Actor` instead.
866
- */
867
-
868
- 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 };