xstate 5.0.0-beta.9 → 5.0.1

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 (107) hide show
  1. package/README.md +10 -8
  2. package/actions/dist/xstate-actions.cjs.js +19 -5
  3. package/actions/dist/xstate-actions.cjs.mjs +3 -15
  4. package/actions/dist/xstate-actions.development.cjs.js +21 -0
  5. package/actions/dist/xstate-actions.development.cjs.mjs +13 -0
  6. package/actions/dist/xstate-actions.development.esm.js +3 -0
  7. package/actions/dist/xstate-actions.esm.js +3 -2
  8. package/actions/dist/xstate-actions.umd.min.js +1 -1
  9. package/actions/dist/xstate-actions.umd.min.js.map +1 -1
  10. package/actors/dist/xstate-actors.cjs.js +621 -4
  11. package/actors/dist/xstate-actors.cjs.mjs +1 -8
  12. package/actors/dist/xstate-actors.development.cjs.js +624 -0
  13. package/actors/dist/xstate-actors.development.cjs.mjs +8 -0
  14. package/actors/dist/xstate-actors.development.esm.js +615 -0
  15. package/actors/dist/xstate-actors.esm.js +615 -2
  16. package/actors/dist/xstate-actors.umd.min.js +1 -1
  17. package/actors/dist/xstate-actors.umd.min.js.map +1 -1
  18. package/dev/dist/xstate-dev.cjs.js +45 -4
  19. package/{dist/index-0f3fdf0c.cjs.prod.js → dev/dist/xstate-dev.development.cjs.js} +6 -7
  20. package/dev/dist/xstate-dev.development.cjs.mjs +5 -0
  21. package/{dist/index-50bd0aff.esm.js → dev/dist/xstate-dev.development.esm.js} +6 -8
  22. package/dev/dist/xstate-dev.esm.js +42 -1
  23. package/dev/dist/xstate-dev.umd.min.js +1 -1
  24. package/dev/dist/xstate-dev.umd.min.js.map +1 -1
  25. package/dist/declarations/src/SimulatedClock.d.ts +1 -1
  26. package/dist/declarations/src/State.d.ts +47 -73
  27. package/dist/declarations/src/StateMachine.d.ts +29 -57
  28. package/dist/declarations/src/StateNode.d.ts +36 -33
  29. package/dist/declarations/src/actions/assign.d.ts +11 -2
  30. package/dist/declarations/src/actions/cancel.d.ts +7 -3
  31. package/dist/declarations/src/actions/enqueueActions.d.ts +32 -0
  32. package/dist/declarations/src/actions/log.d.ts +7 -3
  33. package/dist/declarations/src/actions/raise.d.ts +7 -2
  34. package/dist/declarations/src/actions/send.d.ts +14 -36
  35. package/dist/declarations/src/actions/spawnChild.d.ts +29 -0
  36. package/dist/declarations/src/actions/stopChild.d.ts +18 -0
  37. package/dist/declarations/src/actions.d.ts +8 -48
  38. package/dist/declarations/src/actors/callback.d.ts +91 -8
  39. package/dist/declarations/src/actors/index.d.ts +6 -28
  40. package/dist/declarations/src/actors/observable.d.ts +101 -18
  41. package/dist/declarations/src/actors/promise.d.ts +80 -10
  42. package/dist/declarations/src/actors/transition.d.ts +64 -9
  43. package/dist/declarations/src/constants.d.ts +3 -0
  44. package/dist/declarations/src/createMachine.d.ts +20 -0
  45. package/dist/declarations/src/dev/index.d.ts +6 -6
  46. package/dist/declarations/src/guards.d.ts +41 -8
  47. package/dist/declarations/src/index.d.ts +18 -23
  48. package/dist/declarations/src/interpreter.d.ts +149 -41
  49. package/dist/declarations/src/setup.d.ts +51 -0
  50. package/dist/declarations/src/spawn.d.ts +23 -2
  51. package/dist/declarations/src/stateUtils.d.ts +30 -45
  52. package/dist/declarations/src/system.d.ts +26 -2
  53. package/dist/declarations/src/typegenTypes.d.ts +34 -22
  54. package/dist/declarations/src/types.d.ts +527 -669
  55. package/dist/declarations/src/utils.d.ts +15 -52
  56. package/dist/declarations/src/waitFor.d.ts +2 -2
  57. package/dist/log-22e678c5.esm.js +364 -0
  58. package/dist/log-5e226275.cjs.js +372 -0
  59. package/dist/log-641cd926.development.cjs.js +394 -0
  60. package/dist/log-f196f85f.development.esm.js +386 -0
  61. package/dist/raise-34e25c2c.cjs.js +2368 -0
  62. package/dist/raise-62704519.development.cjs.js +2422 -0
  63. package/dist/raise-89c581c4.development.esm.js +2371 -0
  64. package/dist/raise-8bc422d1.esm.js +2317 -0
  65. package/dist/xstate.cjs.js +728 -4
  66. package/dist/xstate.cjs.mjs +9 -9
  67. package/dist/xstate.development.cjs.js +737 -0
  68. package/dist/xstate.development.cjs.mjs +39 -0
  69. package/dist/xstate.development.esm.js +699 -0
  70. package/dist/xstate.esm.js +561 -770
  71. package/dist/xstate.umd.min.js +1 -1
  72. package/dist/xstate.umd.min.js.map +1 -1
  73. package/guards/dist/xstate-guards.cjs.js +12 -5
  74. package/guards/dist/xstate-guards.cjs.mjs +1 -2
  75. package/guards/dist/xstate-guards.development.cjs.js +14 -0
  76. package/guards/dist/xstate-guards.development.cjs.mjs +7 -0
  77. package/guards/dist/xstate-guards.development.esm.js +2 -0
  78. package/guards/dist/xstate-guards.esm.js +2 -2
  79. package/guards/dist/xstate-guards.umd.min.js +1 -1
  80. package/guards/dist/xstate-guards.umd.min.js.map +1 -1
  81. package/package.json +53 -1
  82. package/actions/dist/xstate-actions.cjs.dev.js +0 -32
  83. package/actions/dist/xstate-actions.cjs.prod.js +0 -32
  84. package/actions/dynamicAction.ts +0 -42
  85. package/actors/dist/xstate-actors.cjs.dev.js +0 -22
  86. package/actors/dist/xstate-actors.cjs.prod.js +0 -22
  87. package/dev/dist/xstate-dev.cjs.dev.js +0 -11
  88. package/dev/dist/xstate-dev.cjs.prod.js +0 -11
  89. package/dist/actions-b6357569.cjs.dev.js +0 -4437
  90. package/dist/actions-bd4a184d.cjs.prod.js +0 -4423
  91. package/dist/actions-de434a04.esm.js +0 -4348
  92. package/dist/declarations/actions/dynamicAction.d.ts +0 -5
  93. package/dist/declarations/src/Machine.d.ts +0 -4
  94. package/dist/declarations/src/Mailbox.d.ts +0 -12
  95. package/dist/declarations/src/actionTypes.d.ts +0 -16
  96. package/dist/declarations/src/actions/choose.d.ts +0 -3
  97. package/dist/declarations/src/actions/invoke.d.ts +0 -3
  98. package/dist/declarations/src/actions/pure.d.ts +0 -6
  99. package/dist/declarations/src/actions/stop.d.ts +0 -7
  100. package/dist/declarations/src/environment.d.ts +0 -1
  101. package/dist/declarations/src/mapState.d.ts +0 -3
  102. package/dist/declarations/src/memo.d.ts +0 -2
  103. package/dist/index-ebaab3c9.cjs.dev.js +0 -52
  104. package/dist/xstate.cjs.dev.js +0 -950
  105. package/dist/xstate.cjs.prod.js +0 -947
  106. package/guards/dist/xstate-guards.cjs.dev.js +0 -15
  107. package/guards/dist/xstate-guards.cjs.prod.js +0 -15
@@ -0,0 +1,615 @@
1
+ import { X as XSTATE_STOP, z as createActor } from '../../dist/raise-89c581c4.development.esm.js';
2
+ import '../../dev/dist/xstate-dev.development.esm.js';
3
+
4
+ /**
5
+ * Returns actor logic given a transition function and its initial state.
6
+ *
7
+ * A “transition function” is a function that takes the current `state` and received `event` object as arguments, and returns the next state, similar to a reducer.
8
+ *
9
+ * Actors created from transition logic (“transition actors”) can:
10
+ *
11
+ * - Receive events
12
+ * - Emit snapshots of its state
13
+ *
14
+ * The transition function’s `state` is used as its transition actor’s `context`.
15
+ *
16
+ * Note that the "state" for a transition function is provided by the initial state argument, and is not the same as the State object of an actor or a state within a machine configuration.
17
+ *
18
+ * @param transition The transition function used to describe the transition logic. It should return the next state given the current state and event. It receives the following arguments:
19
+ * - `state` - the current state.
20
+ * - `event` - the received event.
21
+ * - `actorScope` - the actor scope object, with properties like `self` and `system`.
22
+ * @param initialContext The initial state of the transition function, either an object representing the state, or a function which returns a state object. If a function, it will receive as its only argument an object with the following properties:
23
+ * - `input` - the `input` provided to its parent transition actor.
24
+ * - `self` - a reference to its parent transition actor.
25
+ * @see {@link https://stately.ai/docs/input | Input docs} for more information about how input is passed
26
+ * @returns Actor logic
27
+ *
28
+ * @example
29
+ * ```ts
30
+ * const transitionLogic = fromTransition(
31
+ * (state, event) => {
32
+ * if (event.type === 'increment') {
33
+ * return {
34
+ * ...state,
35
+ * count: state.count + 1,
36
+ * };
37
+ * }
38
+ * return state;
39
+ * },
40
+ * { count: 0 },
41
+ * );
42
+ *
43
+ * const transitionActor = createActor(transitionLogic);
44
+ * transitionActor.subscribe((snapshot) => {
45
+ * console.log(snapshot);
46
+ * });
47
+ * transitionActor.start();
48
+ * // => {
49
+ * // status: 'active',
50
+ * // context: { count: 0 },
51
+ * // ...
52
+ * // }
53
+ *
54
+ * transitionActor.send({ type: 'increment' });
55
+ * // => {
56
+ * // status: 'active',
57
+ * // context: { count: 1 },
58
+ * // ...
59
+ * // }
60
+ * ```
61
+ */
62
+ function fromTransition(transition, initialContext) {
63
+ return {
64
+ config: transition,
65
+ transition: (snapshot, event, actorScope) => {
66
+ return {
67
+ ...snapshot,
68
+ context: transition(snapshot.context, event, actorScope)
69
+ };
70
+ },
71
+ getInitialSnapshot: (_, input) => {
72
+ return {
73
+ status: 'active',
74
+ output: undefined,
75
+ error: undefined,
76
+ context: typeof initialContext === 'function' ? initialContext({
77
+ input
78
+ }) : initialContext
79
+ };
80
+ },
81
+ getPersistedSnapshot: snapshot => snapshot,
82
+ restoreSnapshot: snapshot => snapshot
83
+ };
84
+ }
85
+
86
+ const instanceStates = /* #__PURE__ */new WeakMap();
87
+ /**
88
+ * An actor logic creator which returns callback logic as defined by a callback function.
89
+ *
90
+ * @remarks
91
+ * Useful for subscription-based or other free-form logic that can send events back to the parent actor.
92
+ *
93
+ * Actors created from callback logic (“callback actors”) can:
94
+ * - Receive events via the `receive` function
95
+ * - Send events to the parent actor via the `sendBack` function
96
+ *
97
+ * Callback actors are a bit different from other actors in that they:
98
+ * - Do not work with `onDone`
99
+ * - Do not produce a snapshot using `.getSnapshot()`
100
+ * - Do not emit values when used with `.subscribe()`
101
+ * - Can not be stopped with `.stop()`
102
+ *
103
+ * @param invokeCallback - The callback function used to describe the callback logic
104
+ * The callback function is passed an object with the following properties:
105
+ * - `receive` - A function that can send events back to the parent actor; the listener is then called whenever events are received by the callback actor
106
+ * - `sendBack` - A function that can send events back to the parent actor
107
+ * - `input` - Data that was provided to the callback actor
108
+ * - `self` - The parent actor of the callback actor
109
+ * - `system` - The actor system to which the callback actor belongs
110
+ * The callback function can (optionally) return a cleanup function, which is called when the actor is stopped.
111
+ * @see {@link InvokeCallback} for more information about the callback function and its object argument
112
+ * @see {@link https://stately.ai/docs/input | Input docs} for more information about how input is passed
113
+
114
+ * @returns Callback logic
115
+ *
116
+ * @example
117
+ * ```typescript
118
+ * const callbackLogic = fromCallback(({ sendBack, receive }) => {
119
+ * let lockStatus = 'unlocked';
120
+ *
121
+ * const handler = (event) => {
122
+ * if (lockStatus === 'locked') {
123
+ * return;
124
+ * }
125
+ * sendBack(event);
126
+ * };
127
+ *
128
+ * receive((event) => {
129
+ * if (event.type === 'lock') {
130
+ * lockStatus = 'locked';
131
+ * } else if (event.type === 'unlock') {
132
+ * lockStatus = 'unlocked';
133
+ * }
134
+ * });
135
+ *
136
+ * document.body.addEventListener('click', handler);
137
+ *
138
+ * return () => {
139
+ * document.body.removeEventListener('click', handler);
140
+ * };
141
+ * });
142
+ * ```
143
+ */
144
+ function fromCallback(invokeCallback) {
145
+ const logic = {
146
+ config: invokeCallback,
147
+ start: (state, actorScope) => {
148
+ const {
149
+ self,
150
+ system
151
+ } = actorScope;
152
+ const callbackState = {
153
+ receivers: undefined,
154
+ dispose: undefined
155
+ };
156
+ instanceStates.set(self, callbackState);
157
+ callbackState.dispose = invokeCallback({
158
+ input: state.input,
159
+ system,
160
+ self,
161
+ sendBack: event => {
162
+ if (self.getSnapshot().status === 'stopped') {
163
+ return;
164
+ }
165
+ if (self._parent) {
166
+ system._relay(self, self._parent, event);
167
+ }
168
+ },
169
+ receive: listener => {
170
+ callbackState.receivers ??= new Set();
171
+ callbackState.receivers.add(listener);
172
+ }
173
+ });
174
+ },
175
+ transition: (state, event, actorScope) => {
176
+ const callbackState = instanceStates.get(actorScope.self);
177
+ if (event.type === XSTATE_STOP) {
178
+ state = {
179
+ ...state,
180
+ status: 'stopped',
181
+ error: undefined
182
+ };
183
+ callbackState.dispose?.();
184
+ return state;
185
+ }
186
+ callbackState.receivers?.forEach(receiver => receiver(event));
187
+ return state;
188
+ },
189
+ getInitialSnapshot: (_, input) => {
190
+ return {
191
+ status: 'active',
192
+ output: undefined,
193
+ error: undefined,
194
+ input
195
+ };
196
+ },
197
+ getPersistedSnapshot: snapshot => snapshot,
198
+ restoreSnapshot: snapshot => snapshot
199
+ };
200
+ return logic;
201
+ }
202
+
203
+ const XSTATE_OBSERVABLE_NEXT = 'xstate.observable.next';
204
+ const XSTATE_OBSERVABLE_ERROR = 'xstate.observable.error';
205
+ const XSTATE_OBSERVABLE_COMPLETE = 'xstate.observable.complete';
206
+ /**
207
+ * Observable actor logic is described by an observable stream of values. Actors created from observable logic (“observable actors”) can:
208
+ *
209
+ * - Emit snapshots of the observable’s emitted value
210
+ *
211
+ * The observable’s emitted value is used as its observable actor’s `context`.
212
+ *
213
+ * Sending events to observable actors will have no effect.
214
+ *
215
+ * @param observableCreator A function that creates an observable. It receives one argument, an object with the following properties:
216
+ * - `input` - Data that was provided to the observable actor
217
+ * - `self` - The parent actor
218
+ * - `system` - The actor system to which the observable actor belongs
219
+ *
220
+ * It should return a {@link Subscribable}, which is compatible with an RxJS Observable, although RxJS is not required to create them.
221
+ *
222
+ * @example
223
+ * ```ts
224
+ * import { fromObservable, createActor } from 'xstate'
225
+ * import { interval } from 'rxjs';
226
+ *
227
+ * const logic = fromObservable((obj) => interval(1000));
228
+ *
229
+ * const actor = createActor(logic);
230
+ *
231
+ * actor.subscribe((snapshot) => {
232
+ * console.log(snapshot.context);
233
+ * });
234
+ *
235
+ * actor.start();
236
+ * // At every second:
237
+ * // Logs 0
238
+ * // Logs 1
239
+ * // Logs 2
240
+ * // ...
241
+ * ```
242
+ *
243
+ * @see {@link https://rxjs.dev} for documentation on RxJS Observable and observable creators.
244
+ * @see {@link Subscribable} interface in XState, which is based on and compatible with RxJS Observable.
245
+ */
246
+ function fromObservable(observableCreator) {
247
+ // TODO: add event types
248
+ const logic = {
249
+ config: observableCreator,
250
+ transition: (snapshot, event, {
251
+ self,
252
+ id,
253
+ defer,
254
+ system
255
+ }) => {
256
+ if (snapshot.status !== 'active') {
257
+ return snapshot;
258
+ }
259
+ switch (event.type) {
260
+ case XSTATE_OBSERVABLE_NEXT:
261
+ {
262
+ const newSnapshot = {
263
+ ...snapshot,
264
+ context: event.data
265
+ };
266
+ return newSnapshot;
267
+ }
268
+ case XSTATE_OBSERVABLE_ERROR:
269
+ return {
270
+ ...snapshot,
271
+ status: 'error',
272
+ error: event.data,
273
+ input: undefined,
274
+ _subscription: undefined
275
+ };
276
+ case XSTATE_OBSERVABLE_COMPLETE:
277
+ return {
278
+ ...snapshot,
279
+ status: 'done',
280
+ input: undefined,
281
+ _subscription: undefined
282
+ };
283
+ case XSTATE_STOP:
284
+ snapshot._subscription.unsubscribe();
285
+ return {
286
+ ...snapshot,
287
+ status: 'stopped',
288
+ input: undefined,
289
+ _subscription: undefined
290
+ };
291
+ default:
292
+ return snapshot;
293
+ }
294
+ },
295
+ getInitialSnapshot: (_, input) => {
296
+ return {
297
+ status: 'active',
298
+ output: undefined,
299
+ error: undefined,
300
+ context: undefined,
301
+ input,
302
+ _subscription: undefined
303
+ };
304
+ },
305
+ start: (state, {
306
+ self,
307
+ system
308
+ }) => {
309
+ if (state.status === 'done') {
310
+ // Do not restart a completed observable
311
+ return;
312
+ }
313
+ state._subscription = observableCreator({
314
+ input: state.input,
315
+ system,
316
+ self
317
+ }).subscribe({
318
+ next: value => {
319
+ system._relay(self, self, {
320
+ type: XSTATE_OBSERVABLE_NEXT,
321
+ data: value
322
+ });
323
+ },
324
+ error: err => {
325
+ system._relay(self, self, {
326
+ type: XSTATE_OBSERVABLE_ERROR,
327
+ data: err
328
+ });
329
+ },
330
+ complete: () => {
331
+ system._relay(self, self, {
332
+ type: XSTATE_OBSERVABLE_COMPLETE
333
+ });
334
+ }
335
+ });
336
+ },
337
+ getPersistedSnapshot: ({
338
+ _subscription,
339
+ ...state
340
+ }) => state,
341
+ restoreSnapshot: state => ({
342
+ ...state,
343
+ _subscription: undefined
344
+ })
345
+ };
346
+ return logic;
347
+ }
348
+
349
+ /**
350
+ * Creates event observable logic that listens to an observable that delivers event objects.
351
+ *
352
+ * Event observable actor logic is described by an observable stream of {@link https://stately.ai/docs/transitions#event-objects | event objects}. Actors created from event observable logic (“event observable actors”) can:
353
+ *
354
+ * - Implicitly send events to its parent actor
355
+ * - Emit snapshots of its emitted event objects
356
+ *
357
+ * Sending events to event observable actors will have no effect.
358
+ *
359
+ * @param lazyObservable A function that creates an observable that delivers event objects. It receives one argument, an object with the following properties:
360
+ *
361
+ * - `input` - Data that was provided to the event observable actor
362
+ * - `self` - The parent actor
363
+ * - `system` - The actor system to which the event observable actor belongs.
364
+ *
365
+ * It should return a {@link Subscribable}, which is compatible with an RxJS Observable, although RxJS is not required to create them.
366
+ *
367
+ * @example
368
+ * ```ts
369
+ * import {
370
+ * fromEventObservable,
371
+ * Subscribable,
372
+ * EventObject,
373
+ * createMachine,
374
+ * createActor
375
+ * } from 'xstate';
376
+ * import { fromEvent } from 'rxjs';
377
+ *
378
+ * const mouseClickLogic = fromEventObservable(() =>
379
+ * fromEvent(document.body, 'click') as Subscribable<EventObject>
380
+ * );
381
+ *
382
+ * const canvasMachine = createMachine({
383
+ * invoke: {
384
+ * // Will send mouse `click` events to the canvas actor
385
+ * src: mouseClickLogic,
386
+ * }
387
+ * });
388
+ *
389
+ * const canvasActor = createActor(canvasMachine);
390
+ * canvasActor.start();
391
+ * ```
392
+ */
393
+ function fromEventObservable(lazyObservable) {
394
+ // TODO: event types
395
+ const logic = {
396
+ config: lazyObservable,
397
+ transition: (state, event) => {
398
+ if (state.status !== 'active') {
399
+ return state;
400
+ }
401
+ switch (event.type) {
402
+ case XSTATE_OBSERVABLE_ERROR:
403
+ return {
404
+ ...state,
405
+ status: 'error',
406
+ error: event.data,
407
+ input: undefined,
408
+ _subscription: undefined
409
+ };
410
+ case XSTATE_OBSERVABLE_COMPLETE:
411
+ return {
412
+ ...state,
413
+ status: 'done',
414
+ input: undefined,
415
+ _subscription: undefined
416
+ };
417
+ case XSTATE_STOP:
418
+ state._subscription.unsubscribe();
419
+ return {
420
+ ...state,
421
+ status: 'stopped',
422
+ input: undefined,
423
+ _subscription: undefined
424
+ };
425
+ default:
426
+ return state;
427
+ }
428
+ },
429
+ getInitialSnapshot: (_, input) => {
430
+ return {
431
+ status: 'active',
432
+ output: undefined,
433
+ error: undefined,
434
+ context: undefined,
435
+ input,
436
+ _subscription: undefined
437
+ };
438
+ },
439
+ start: (state, {
440
+ self,
441
+ system
442
+ }) => {
443
+ if (state.status === 'done') {
444
+ // Do not restart a completed observable
445
+ return;
446
+ }
447
+ state._subscription = lazyObservable({
448
+ input: state.input,
449
+ system,
450
+ self
451
+ }).subscribe({
452
+ next: value => {
453
+ if (self._parent) {
454
+ system._relay(self, self._parent, value);
455
+ }
456
+ },
457
+ error: err => {
458
+ system._relay(self, self, {
459
+ type: XSTATE_OBSERVABLE_ERROR,
460
+ data: err
461
+ });
462
+ },
463
+ complete: () => {
464
+ system._relay(self, self, {
465
+ type: XSTATE_OBSERVABLE_COMPLETE
466
+ });
467
+ }
468
+ });
469
+ },
470
+ getPersistedSnapshot: ({
471
+ _subscription,
472
+ ...snapshot
473
+ }) => snapshot,
474
+ restoreSnapshot: snapshot => ({
475
+ ...snapshot,
476
+ _subscription: undefined
477
+ })
478
+ };
479
+ return logic;
480
+ }
481
+
482
+ const XSTATE_PROMISE_RESOLVE = 'xstate.promise.resolve';
483
+ const XSTATE_PROMISE_REJECT = 'xstate.promise.reject';
484
+ /**
485
+ * An actor logic creator which returns promise logic as defined by an async process that resolves or rejects after some time.
486
+ *
487
+ * Actors created from promise actor logic (“promise actors”) can:
488
+ * - Emit the resolved value of the promise
489
+ * - Output the resolved value of the promise
490
+ *
491
+ * Sending events to promise actors will have no effect.
492
+ *
493
+ * @param promiseCreator
494
+ * A function which returns a Promise, and accepts an object with the following properties:
495
+ * - `input` - Data that was provided to the promise actor
496
+ * - `self` - The parent actor of the promise actor
497
+ * - `system` - The actor system to which the promise actor belongs
498
+ * @see {@link https://stately.ai/docs/input | Input docs} for more information about how input is passed
499
+ *
500
+ * @example
501
+ * ```ts
502
+ * const promiseLogic = fromPromise(async () => {
503
+ * const result = await fetch('https://example.com/...')
504
+ * .then((data) => data.json());
505
+ *
506
+ * return result;
507
+ * });
508
+ *
509
+ * const promiseActor = createActor(promiseLogic);
510
+ * promiseActor.subscribe((snapshot) => {
511
+ * console.log(snapshot);
512
+ * });
513
+ * promiseActor.start();
514
+ * // => {
515
+ * // output: undefined,
516
+ * // status: 'active'
517
+ * // ...
518
+ * // }
519
+ *
520
+ * // After promise resolves
521
+ * // => {
522
+ * // output: { ... },
523
+ * // status: 'done',
524
+ * // ...
525
+ * // }
526
+ * ```
527
+ */
528
+ function fromPromise(promiseCreator) {
529
+ // TODO: add event types
530
+ const logic = {
531
+ config: promiseCreator,
532
+ transition: (state, event) => {
533
+ if (state.status !== 'active') {
534
+ return state;
535
+ }
536
+ switch (event.type) {
537
+ case XSTATE_PROMISE_RESOLVE:
538
+ {
539
+ const resolvedValue = event.data;
540
+ return {
541
+ ...state,
542
+ status: 'done',
543
+ output: resolvedValue,
544
+ input: undefined
545
+ };
546
+ }
547
+ case XSTATE_PROMISE_REJECT:
548
+ return {
549
+ ...state,
550
+ status: 'error',
551
+ error: event.data,
552
+ input: undefined
553
+ };
554
+ case XSTATE_STOP:
555
+ return {
556
+ ...state,
557
+ status: 'stopped',
558
+ input: undefined
559
+ };
560
+ default:
561
+ return state;
562
+ }
563
+ },
564
+ start: (state, {
565
+ self,
566
+ system
567
+ }) => {
568
+ // TODO: determine how to allow customizing this so that promises
569
+ // can be restarted if necessary
570
+ if (state.status !== 'active') {
571
+ return;
572
+ }
573
+ const resolvedPromise = Promise.resolve(promiseCreator({
574
+ input: state.input,
575
+ system,
576
+ self
577
+ }));
578
+ resolvedPromise.then(response => {
579
+ if (self.getSnapshot().status !== 'active') {
580
+ return;
581
+ }
582
+ system._relay(self, self, {
583
+ type: XSTATE_PROMISE_RESOLVE,
584
+ data: response
585
+ });
586
+ }, errorData => {
587
+ if (self.getSnapshot().status !== 'active') {
588
+ return;
589
+ }
590
+ system._relay(self, self, {
591
+ type: XSTATE_PROMISE_REJECT,
592
+ data: errorData
593
+ });
594
+ });
595
+ },
596
+ getInitialSnapshot: (_, input) => {
597
+ return {
598
+ status: 'active',
599
+ output: undefined,
600
+ error: undefined,
601
+ input
602
+ };
603
+ },
604
+ getPersistedSnapshot: snapshot => snapshot,
605
+ restoreSnapshot: snapshot => snapshot
606
+ };
607
+ return logic;
608
+ }
609
+
610
+ const emptyLogic = fromTransition(_ => undefined, undefined);
611
+ function createEmptyActor() {
612
+ return createActor(emptyLogic);
613
+ }
614
+
615
+ export { createEmptyActor, fromCallback, fromEventObservable, fromObservable, fromPromise, fromTransition };