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