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