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