xstate 5.0.0-beta.8 → 5.0.0
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.
- package/README.md +10 -8
- package/actions/dist/xstate-actions.cjs.d.mts +2 -0
- package/actions/dist/xstate-actions.cjs.d.mts.map +1 -0
- package/actions/dist/xstate-actions.cjs.d.ts +1 -0
- package/actions/dist/xstate-actions.cjs.d.ts.map +1 -0
- package/actions/dist/xstate-actions.cjs.js +19 -5
- package/actions/dist/xstate-actions.cjs.mjs +13 -0
- package/actions/dist/xstate-actions.development.cjs.js +21 -0
- package/actions/dist/xstate-actions.development.cjs.mjs +13 -0
- package/actions/dist/xstate-actions.development.esm.js +3 -0
- package/actions/dist/xstate-actions.esm.js +3 -2
- package/actions/dist/xstate-actions.umd.min.js +1 -1
- package/actions/dist/xstate-actions.umd.min.js.map +1 -1
- package/actors/dist/xstate-actors.cjs.d.mts +2 -0
- package/actors/dist/xstate-actors.cjs.d.mts.map +1 -0
- package/actors/dist/xstate-actors.cjs.d.ts +1 -0
- package/actors/dist/xstate-actors.cjs.d.ts.map +1 -0
- package/actors/dist/xstate-actors.cjs.js +621 -4
- package/actors/dist/xstate-actors.cjs.mjs +8 -0
- package/actors/dist/xstate-actors.development.cjs.js +624 -0
- package/actors/dist/xstate-actors.development.cjs.mjs +8 -0
- package/actors/dist/xstate-actors.development.esm.js +615 -0
- package/actors/dist/xstate-actors.esm.js +615 -2
- package/actors/dist/xstate-actors.umd.min.js +1 -1
- package/actors/dist/xstate-actors.umd.min.js.map +1 -1
- package/dev/dist/xstate-dev.cjs.d.mts +2 -0
- package/dev/dist/xstate-dev.cjs.d.mts.map +1 -0
- package/dev/dist/xstate-dev.cjs.d.ts +1 -0
- package/dev/dist/xstate-dev.cjs.d.ts.map +1 -0
- package/dev/dist/xstate-dev.cjs.js +45 -4
- package/dev/dist/xstate-dev.cjs.mjs +5 -0
- package/{dist/index-ebaab3c9.cjs.dev.js → dev/dist/xstate-dev.development.cjs.js} +6 -7
- package/dev/dist/xstate-dev.development.cjs.mjs +5 -0
- package/{dist/index-50bd0aff.esm.js → dev/dist/xstate-dev.development.esm.js} +6 -8
- package/dev/dist/xstate-dev.esm.js +42 -1
- package/dev/dist/xstate-dev.umd.min.js +1 -1
- package/dev/dist/xstate-dev.umd.min.js.map +1 -1
- package/dist/declarations/src/SimulatedClock.d.ts +1 -1
- package/dist/declarations/src/State.d.ts +47 -73
- package/dist/declarations/src/StateMachine.d.ts +29 -57
- package/dist/declarations/src/StateNode.d.ts +36 -33
- package/dist/declarations/src/actions/assign.d.ts +11 -2
- package/dist/declarations/src/actions/cancel.d.ts +7 -3
- package/dist/declarations/src/actions/enqueueActions.d.ts +32 -0
- package/dist/declarations/src/actions/log.d.ts +7 -3
- package/dist/declarations/src/actions/raise.d.ts +7 -2
- package/dist/declarations/src/actions/send.d.ts +14 -36
- package/dist/declarations/src/actions/spawnChild.d.ts +29 -0
- package/dist/declarations/src/actions/stopChild.d.ts +18 -0
- package/dist/declarations/src/actions.d.ts +8 -48
- package/dist/declarations/src/actors/callback.d.ts +91 -8
- package/dist/declarations/src/actors/index.d.ts +6 -28
- package/dist/declarations/src/actors/observable.d.ts +101 -18
- package/dist/declarations/src/actors/promise.d.ts +80 -10
- package/dist/declarations/src/actors/transition.d.ts +64 -9
- package/dist/declarations/src/constants.d.ts +3 -0
- package/dist/declarations/src/createMachine.d.ts +20 -0
- package/dist/declarations/src/dev/index.d.ts +6 -6
- package/dist/declarations/src/guards.d.ts +41 -8
- package/dist/declarations/src/index.d.ts +18 -23
- package/dist/declarations/src/interpreter.d.ts +150 -41
- package/dist/declarations/src/setup.d.ts +51 -0
- package/dist/declarations/src/spawn.d.ts +23 -2
- package/dist/declarations/src/stateUtils.d.ts +30 -45
- package/dist/declarations/src/system.d.ts +26 -2
- package/dist/declarations/src/typegenTypes.d.ts +40 -22
- package/dist/declarations/src/types.d.ts +528 -669
- package/dist/declarations/src/utils.d.ts +15 -52
- package/dist/declarations/src/waitFor.d.ts +2 -2
- package/dist/log-22e678c5.esm.js +364 -0
- package/dist/log-5e226275.cjs.js +372 -0
- package/dist/log-641cd926.development.cjs.js +394 -0
- package/dist/log-f196f85f.development.esm.js +386 -0
- package/dist/raise-34e25c2c.cjs.js +2368 -0
- package/dist/raise-62704519.development.cjs.js +2422 -0
- package/dist/raise-89c581c4.development.esm.js +2371 -0
- package/dist/raise-8bc422d1.esm.js +2317 -0
- package/dist/xstate.cjs.d.mts +2 -0
- package/dist/xstate.cjs.d.mts.map +1 -0
- package/dist/xstate.cjs.d.ts +1 -0
- package/dist/xstate.cjs.d.ts.map +1 -0
- package/dist/xstate.cjs.js +728 -4
- package/dist/xstate.cjs.mjs +39 -0
- package/dist/xstate.development.cjs.js +737 -0
- package/dist/xstate.development.cjs.mjs +39 -0
- package/dist/xstate.development.esm.js +699 -0
- package/dist/xstate.esm.js +561 -770
- package/dist/xstate.umd.min.js +1 -1
- package/dist/xstate.umd.min.js.map +1 -1
- package/guards/dist/xstate-guards.cjs.d.mts +2 -0
- package/guards/dist/xstate-guards.cjs.d.mts.map +1 -0
- package/guards/dist/xstate-guards.cjs.d.ts +1 -0
- package/guards/dist/xstate-guards.cjs.d.ts.map +1 -0
- package/guards/dist/xstate-guards.cjs.js +12 -5
- package/guards/dist/xstate-guards.cjs.mjs +7 -0
- package/guards/dist/xstate-guards.development.cjs.js +14 -0
- package/guards/dist/xstate-guards.development.cjs.mjs +7 -0
- package/guards/dist/xstate-guards.development.esm.js +2 -0
- package/guards/dist/xstate-guards.esm.js +2 -2
- package/guards/dist/xstate-guards.umd.min.js +1 -1
- package/guards/dist/xstate-guards.umd.min.js.map +1 -1
- package/package.json +59 -1
- package/actions/dist/xstate-actions.cjs.dev.js +0 -32
- package/actions/dist/xstate-actions.cjs.prod.js +0 -32
- package/actions/dynamicAction.ts +0 -42
- package/actors/dist/xstate-actors.cjs.dev.js +0 -22
- package/actors/dist/xstate-actors.cjs.prod.js +0 -22
- package/dev/dist/xstate-dev.cjs.dev.js +0 -11
- package/dev/dist/xstate-dev.cjs.prod.js +0 -48
- package/dist/actions-900f9761.cjs.prod.js +0 -4349
- package/dist/actions-c8d7df32.esm.js +0 -4332
- package/dist/actions-d06ca158.cjs.dev.js +0 -4387
- package/dist/declarations/actions/dynamicAction.d.ts +0 -5
- package/dist/declarations/src/Machine.d.ts +0 -4
- package/dist/declarations/src/Mailbox.d.ts +0 -12
- package/dist/declarations/src/actionTypes.d.ts +0 -16
- package/dist/declarations/src/actions/choose.d.ts +0 -3
- package/dist/declarations/src/actions/invoke.d.ts +0 -3
- package/dist/declarations/src/actions/pure.d.ts +0 -6
- package/dist/declarations/src/actions/stop.d.ts +0 -7
- package/dist/declarations/src/environment.d.ts +0 -1
- package/dist/declarations/src/mapState.d.ts +0 -3
- package/dist/declarations/src/memo.d.ts +0 -2
- package/dist/xstate.cjs.dev.js +0 -956
- package/dist/xstate.cjs.prod.js +0 -953
- package/guards/dist/xstate-guards.cjs.dev.js +0 -15
- package/guards/dist/xstate-guards.cjs.prod.js +0 -15
|
@@ -1,2 +1,615 @@
|
|
|
1
|
-
|
|
2
|
-
import '../../dist/
|
|
1
|
+
import { X as XSTATE_STOP, z as createActor } from '../../dist/raise-8bc422d1.esm.js';
|
|
2
|
+
import '../../dev/dist/xstate-dev.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 };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).XStateActors={})}(this,(function(t){"use strict";function e(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var n=t[Symbol.toPrimitive];if(void 0!==n){var r=n.call(t,e||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}function n(t,n,r){return(n=e(n))in t?Object.defineProperty(t,n,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[n]=r,t}function r(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,r)}return n}function i(t){for(var e=1;e<arguments.length;e++){var i=null!=arguments[e]?arguments[e]:{};e%2?r(Object(i),!0).forEach((function(e){n(t,e,i[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):r(Object(i)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(i,e))}))}return t}function s(t){return(s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}var o="function"==typeof Symbol&&Symbol.observable||"@@observable";function a(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n<e;n++)r[n]=t[n];return r}function u(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!n){if(Array.isArray(t)||(n=function(t,e){if(t){if("string"==typeof t)return a(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?a(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var r=0,i=function(){};return{s:i,n:function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}},e:function(t){throw t},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var s,o=!0,u=!1;return{s:function(){n=n.call(t)},n:function(){var t=n.next();return o=t.done,t},e:function(t){u=!0,s=t},f:function(){try{o||null==n.return||n.return()}finally{if(u)throw s}}}}function c(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function l(t,n){for(var r=0;r<n.length;r++){var i=n[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,e(i.key),i)}}function d(t,e,n){return e&&l(t.prototype,e),n&&l(t,n),Object.defineProperty(t,"prototype",{writable:!1}),t}var f,h,v=function(){function t(e){c(this,t),this._process=e,n(this,"_active",!1),n(this,"_current",null),n(this,"_last",null)}return d(t,[{key:"start",value:function(){this._active=!0,this.flush()}},{key:"clear",value:function(){this._current&&(this._current.next=null,this._last=this._current)}},{key:"prepend",value:function(t){this._current?this._current={value:t,next:this._current}:this.enqueue(t)}},{key:"enqueue",value:function(t){var e={value:t,next:null};if(this._current)return this._last.next=e,void(this._last=e);this._current=e,this._last=e,this._active&&this.flush()}},{key:"flush",value:function(){for(;this._current;){var t=this._current;this._process(t.value),t===this._current&&(this._current=this._current.next)}this._last=null}}]),t}();!function(t){t.Stop="xstate.stop",t.Raise="xstate.raise",t.Send="xstate.send",t.Cancel="xstate.cancel",t.Assign="xstate.assign",t.After="xstate.after",t.DoneState="done.state",t.DoneInvoke="done.invoke",t.Log="xstate.log",t.Init="xstate.init",t.Invoke="xstate.invoke",t.ErrorExecution="error.execution",t.ErrorCommunication="error.communication",t.ErrorPlatform="error.platform",t.ErrorCustom="xstate.error",t.Pure="xstate.pure",t.Choose="xstate.choose"}(f||(f={})),function(t){t.Parent="#_parent",t.Internal="#_internal"}(h||(h={}));f.Stop,f.Raise,f.Send,f.Cancel,f.Assign,f.After,f.DoneState,f.Log;var p=f.Init;f.Invoke,f.ErrorExecution,f.ErrorPlatform,f.ErrorCustom,f.Choose,f.Pure;function y(t){return"function"==typeof t}function b(t){return"$$type"in t&&"scxml"===t.$$type}function m(t,e){return b(t)?t:i({name:t.type,data:t,$$type:"scxml",type:"external"},e)}m({type:p});function g(t,e){var n="".concat(f.DoneInvoke,".").concat(t),r={type:n,output:e,toString:function(){return n}};return r}function _(t,e){var n="".concat(f.ErrorPlatform,".").concat(t),r={type:n,data:e,toString:function(){return n}};return r}function S(){var t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:window;if(t.__xstate__)return t.__xstate__}var x,k=function(t){var e=S();e&&e.register(t)};!function(t){t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped"}(x||(x={}));var w={deferEvents:!0,clock:{setTimeout:function(t){function e(e,n){return t.apply(this,arguments)}return e.toString=function(){return t.toString()},e}((function(t,e){return setTimeout(t,e)})),clearTimeout:function(t){function e(e){return t.apply(this,arguments)}return e.toString=function(){return t.toString()},e}((function(t){return clearTimeout(t)}))},logger:console.log.bind(console),devTools:!1},E=function(){function t(e,r){var s,o=this;c(this,t),this.behavior=e,n(this,"_state",void 0),n(this,"clock",void 0),n(this,"options",void 0),n(this,"id",void 0),n(this,"mailbox",new v(this._process.bind(this))),n(this,"delayedEventsMap",{}),n(this,"observers",new Set),n(this,"logger",void 0),n(this,"status",x.NotStarted),n(this,"_parent",void 0),n(this,"ref",void 0),n(this,"_actorContext",void 0),n(this,"_systemId",void 0),n(this,"sessionId",void 0),n(this,"system",void 0),n(this,"_doneEvent",void 0),n(this,"src",void 0),n(this,"_deferred",[]);var a,u,l,d,f=i(i({},w),r),h=f.clock,p=f.logger,y=f.parent,b=f.id,m=f.systemId;this.system=null!==(s=null==y?void 0:y.system)&&void 0!==s?s:(a=0,u=new Map,l=new Map,d=new WeakMap,{_bookId:function(){return"x:".concat(a++)},_register:function(t,e){return u.set(t,e),t},_unregister:function(t){u.delete(t.sessionId);var e=d.get(t);void 0!==e&&(l.delete(e),d.delete(t))},get:function(t){return l.get(t)},_set:function(t,e){var n=l.get(t);if(n&&n!==e)throw new Error("Actor with system ID '".concat(t,"' already exists."));l.set(t,e),d.set(e,t)}}),m&&(this._systemId=m,this.system._set(m,this)),this.sessionId=this.system._bookId(),this.id=null!=b?b:this.sessionId,this.logger=p,this.clock=h,this._parent=y,this.options=f,this.src=f.src,this.ref=this,this._actorContext={self:this,id:this.id,sessionId:this.sessionId,logger:this.logger,defer:function(t){o._deferred.push(t)},system:this.system,stopChild:function(t){if(t._parent!==o)throw new Error("Cannot stop child actor ".concat(t.id," of ").concat(o.id," because it is not a child"));t._stop()}},this.send=this.send.bind(this),this._initState()}return d(t,[{key:"_initState",value:function(){var t;this._state=this.options.state?this.behavior.restoreState?this.behavior.restoreState(this.options.state,this._actorContext):this.options.state:this.behavior.getInitialState(this._actorContext,null===(t=this.options)||void 0===t?void 0:t.input)}},{key:"update",value:function(t){var e,n,r,i;this._state=t;for(var s,o=this.getSnapshot();s=this._deferred.shift();)s(t);var a,c=u(this.observers);try{for(c.s();!(a=c.n()).done;){var l,d=a.value;null===(l=d.next)||void 0===l||l.call(d,o)}}catch(t){c.e(t)}finally{c.f()}var f=null===(e=(n=this.behavior).getStatus)||void 0===e?void 0:e.call(n,t);switch(null==f?void 0:f.status){case"done":this._doneEvent=g(this.id,f.data),null===(r=this._parent)||void 0===r||r.send(m(this._doneEvent,{origin:this,invokeid:this.id})),this._stopProcedure();break;case"error":null===(i=this._parent)||void 0===i||i.send(m(_(this.id,f.data),{origin:this}));var h,v=u(this.observers);try{for(v.s();!(h=v.n()).done;){var p,y=h.value;null===(p=y.error)||void 0===p||p.call(y,f.data)}}catch(t){v.e(t)}finally{v.f()}}}},{key:"subscribe",value:function(t,e,n){var r,i=this,o=function(t,e,n){var r=function(){},i="object"===s(t),o=i?t:null;return{next:((i?t.next:t)||r).bind(o),error:((i?t.error:e)||r).bind(o),complete:((i?t.complete:n)||r).bind(o)}}(t,e,n);(this.observers.add(o),this.status===x.Stopped)&&(null===(r=o.complete)||void 0===r||r.call(o),this.observers.delete(o));return{unsubscribe:function(){i.observers.delete(o)}}}},{key:"onDone",value:function(t){var e=this;return this.status===x.Stopped&&this._doneEvent?t(this._doneEvent):this.observers.add({complete:function(){e._doneEvent&&t(e._doneEvent)}}),this}},{key:"start",value:function(){return this.status===x.Running||(this.system._register(this.sessionId,this),this._systemId&&this.system._set(this._systemId,this),this.status=x.Running,this.behavior.start&&this.behavior.start(this._state,this._actorContext),this.update(this._state),this.options.devTools&&this.attachDevTools(),this.mailbox.start()),this}},{key:"_process",value:function(t){try{var e=this.behavior.transition(this._state,t,this._actorContext);this.update(e),t.name===O&&this._stopProcedure()}catch(t){if(!(this.observers.size>0))throw t;this.observers.forEach((function(e){var n;null===(n=e.error)||void 0===n||n.call(e,t)})),this.stop()}}},{key:"_stop",value:function(){return this.status===x.Stopped?this:(this.mailbox.clear(),this.status===x.NotStarted?(this.status=x.Stopped,this):(this.mailbox.enqueue(m({type:O})),this))}},{key:"stop",value:function(){if(this._parent)throw new Error("A non-root actor cannot be stopped directly.");return this._stop()}},{key:"_complete",value:function(){var t,e=u(this.observers);try{for(e.s();!(t=e.n()).done;){var n,r=t.value;null===(n=r.complete)||void 0===n||n.call(r)}}catch(t){e.e(t)}finally{e.f()}this.observers.clear()}},{key:"_stopProcedure",value:function(){if(this._complete(),this.status!==x.Running)return this;for(var t=0,e=Object.keys(this.delayedEventsMap);t<e.length;t++){var n=e[t];this.clock.clearTimeout(this.delayedEventsMap[n])}return this.mailbox.clear(),this.mailbox=new v(this._process.bind(this)),this.status=x.Stopped,this.system._unregister(this),this}},{key:"send",value:function(t){if("string"==typeof t)throw new Error('Only event objects may be sent to actors; use .send({ type: "'.concat(t,'" }) instead'));var e=m(t);if(this.status!==x.Stopped){if(this.status!==x.Running&&!this.options.deferEvents)throw new Error('Event "'.concat(e.name,'" was sent to uninitialized actor "').concat(this.id,'". Make sure .start() is called for this actor, or set { deferEvents: true } in the actor options.\nEvent: ').concat(JSON.stringify(e.data)));this.mailbox.enqueue(e)}}},{key:"delaySend",value:function(t){var e=this;this.delayedEventsMap[t.params.id]=this.clock.setTimeout((function(){"to"in t.params&&t.params.to?t.params.to.send(t.params._event):e.send(t.params._event)}),t.params.delay)}},{key:"cancel",value:function(t){this.clock.clearTimeout(this.delayedEventsMap[t]),delete this.delayedEventsMap[t]}},{key:"attachDevTools",value:function(){var t=this.options.devTools;t&&("function"==typeof t?t:k)(this)}},{key:"toJSON",value:function(){return{id:this.id}}},{key:"getPersistedState",value:function(){var t,e;return null===(t=(e=this.behavior).getPersistedState)||void 0===t?void 0:t.call(e,this._state)}},{key:o,value:function(){return this}},{key:"getSnapshot",value:function(){return this.behavior.getSnapshot?this.behavior.getSnapshot(this._state):this._state}}]),t}();function P(t,e){return{transition:function(e,n,r){var i=b(n)?n.data:n;return t(e,i,r)},getInitialState:function(t,n){return"function"==typeof e?e({input:n}):e},getSnapshot:function(t){return t},getPersistedState:function(t){return t},restoreState:function(t){return t}}}var I="xstate.init",O="xstate.stop";function j(t){return t===I||t===O}var T=P((function(t){}),void 0);t.createEmptyActor=function(){return new E(T,t);var t},t.fromCallback=function(t){return{start:function(t,e){e.self.send({type:I})},transition:function(e,n,r){var i,o=r.self,a=r.id,u=m(n);if(u.name===I){return e.dispose=t((function(t){var n;e.canceled||null===(n=o._parent)||void 0===n||n.send(m(t,{origin:o}))}),(function(t){e.receivers.add(t)}),{input:e.input}),((i=e.dispose)instanceof Promise||null!==i&&(y(i)||"object"===s(i))&&y(i.then))&&e.dispose.then((function(t){var n;null===(n=o._parent)||void 0===n||n.send(m(g(a,t),{origin:o})),e.canceled=!0}),(function(t){var n,r=_(a,t);null===(n=o._parent)||void 0===n||n.send(m(r,{origin:o})),e.canceled=!0})),e}if(u.name===O)return e.canceled=!0,y(e.dispose)&&e.dispose(),e;if(j(u.name))return e;var c=b(n)?n.data:n;return j(c.type)||e.receivers.forEach((function(t){return t(c)})),e},getInitialState:function(t,e){return{canceled:!1,receivers:new Set,dispose:void 0,input:e}},getSnapshot:function(){},getPersistedState:function(t){return t.input}}},t.fromEventObservable=function(t){var e="$$xstate.error",n="$$xstate.complete";return{transition:function(t,r){var s=m(r);if("active"!==t.status)return t;switch(s.name){case e:return i(i({},t),{},{status:"error",input:void 0,data:s.data.data,subscription:void 0});case n:return i(i({},t),{},{status:"done",input:void 0,subscription:void 0});case O:return t.subscription.unsubscribe(),i(i({},t),{},{status:"canceled",input:void 0,subscription:void 0});default:return t}},getInitialState:function(){return{subscription:void 0,status:"active",data:void 0}},start:function(r,i){var s=i.self;"done"!==r.status&&(r.subscription=t({input:r.input}).subscribe({next:function(t){var e;null===(e=s._parent)||void 0===e||e.send(m(t,{origin:s}))},error:function(t){s.send({type:e,data:t})},complete:function(){s.send({type:n})}}))},getSnapshot:function(t){},getPersistedState:function(t){return{status:t.status,data:t.data,input:t.input}},getStatus:function(t){return t},restoreState:function(t){return i(i({},t),{},{subscription:void 0})}}},t.fromObservable=function(t){var e="$$xstate.next",n="$$xstate.error",r="$$xstate.complete";return{transition:function(t,s,o){var a=o.self,u=o.id,c=o.defer,l=m(s);if("active"!==t.status)return t;switch(l.name){case e:return c((function(){var t;null===(t=a._parent)||void 0===t||t.send(m({type:"xstate.snapshot.".concat(u),data:l.data.data},{origin:a}))})),i(i({},t),{},{data:s.data.data});case n:return i(i({},t),{},{status:"error",input:void 0,data:l.data.data,subscription:void 0});case r:return i(i({},t),{},{status:"done",input:void 0,subscription:void 0});case O:return t.subscription.unsubscribe(),i(i({},t),{},{status:"canceled",input:void 0,subscription:void 0});default:return t}},getInitialState:function(t,e){return{subscription:void 0,status:"active",data:void 0,input:e}},start:function(i,s){var o=s.self;"done"!==i.status&&(i.subscription=t({input:i.input}).subscribe({next:function(t){o.send({type:e,data:t})},error:function(t){o.send({type:n,data:t})},complete:function(){o.send({type:r})}}))},getSnapshot:function(t){return t.data},getPersistedState:function(t){return{status:t.status,data:t.data,input:t.input}},getStatus:function(t){return t},restoreState:function(t){return i(i({},t),{},{subscription:void 0})}}},t.fromPromise=function(t){var e="$$xstate.resolve",n="$$xstate.reject";return{transition:function(t,r){var s=m(r);if("active"!==t.status)return t;var o=s.data;switch(s.name){case e:return i(i({},t),{},{status:"done",data:o.data,input:void 0});case n:return i(i({},t),{},{status:"error",data:o.data,input:void 0});case O:return i(i({},t),{},{status:"canceled",input:void 0});default:return t}},start:function(r,i){var s=i.self;"active"===r.status&&Promise.resolve(t({input:r.input})).then((function(t){s.send({type:e,data:t})}),(function(t){s.send({type:n,data:t})}))},getInitialState:function(t,e){return{status:"active",data:void 0,input:e}},getSnapshot:function(t){return t.data},getStatus:function(t){return t},getPersistedState:function(t){return t},restoreState:function(t){return t}}},t.fromTransition=P,t.isActorRef=function(t){return!!t&&"object"===s(t)&&"function"==typeof t.send},t.isSignal=j,t.startSignal={type:"xstate.init"},t.startSignalType=I,t.stopSignal={type:"xstate.stop"},t.stopSignalType=O,t.toActorRef=function(t){var e;return i((n(e={subscribe:function(){return{unsubscribe:function(){}}},id:"anonymous",sessionId:"",getSnapshot:function(){}},o,(function(){return this})),n(e,"status",x.Running),n(e,"stop",(function(){})),e),t)},Object.defineProperty(t,"__esModule",{value:!0})}));
|
|
1
|
+
!function(t,s){"object"==typeof exports&&"undefined"!=typeof module?s(exports):"function"==typeof define&&define.amd?define(["exports"],s):s((t="undefined"!=typeof globalThis?globalThis:t||self).XStateActors={})}(this,(function(t){"use strict";class s{constructor(t){this._process=t,this._active=!1,this._current=null,this._last=null}start(){this._active=!0,this.flush()}clear(){this._current&&(this._current.next=null,this._last=this._current)}enqueue(t){const s={value:t,next:null};if(this._current)return this._last.next=s,void(this._last=s);this._current=s,this._last=s,this._active&&this.flush()}flush(){for(;this._current;){const t=this._current;this._process(t.value),this._current=t.next}this._last=null}}const e="xstate.stop";function i(){const t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:window;if(t.__xstate__)return t.__xstate__}const o=t=>{const s=i();s&&s.register(t)};function r(t){setTimeout((()=>{throw t}))}const n="function"==typeof Symbol&&Symbol.observable||"@@observable";let a=0;function h(t,s,e){const i="object"==typeof t,o=i?t:void 0;return{next:(i?t.next:t)?.bind(o),error:(i?t.error:s)?.bind(o),complete:(i?t.complete:e)?.bind(o)}}let c=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const p={clock:{setTimeout:(t,s)=>setTimeout(t,s),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console),devTools:!1};class u{constructor(t,e){this.logic=t,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this.mailbox=new s(this._process.bind(this)),this.delayedEventsMap={},this.observers=new Set,this.logger=void 0,this._processingStatus=c.NotStarted,this._parent=void 0,this._syncSnapshot=void 0,this.ref=void 0,this._actorScope=void 0,this._systemId=void 0,this.sessionId=void 0,this.system=void 0,this._doneEvent=void 0,this.src=void 0,this._deferred=[];const i={...p,...e},{clock:o,logger:r,parent:n,syncSnapshot:u,id:d,systemId:l,inspect:_}=i;this.system=n?.system??function(t){const s=new Map,e=new Map,i=new WeakMap,o=new Set,r={_bookId:()=>"x:"+a++,_register:(t,e)=>(s.set(t,e),t),_unregister:t=>{s.delete(t.sessionId);const o=i.get(t);void 0!==o&&(e.delete(o),i.delete(t))},get:t=>e.get(t),_set:(t,s)=>{const o=e.get(t);if(o&&o!==s)throw new Error(`Actor with system ID '${t}' already exists.`);e.set(t,s),i.set(s,t)},inspect:t=>{o.add(t)},_sendInspectionEvent:s=>{const e={...s,rootId:t.sessionId};o.forEach((t=>t.next?.(e)))},_relay:(t,s,e)=>{r._sendInspectionEvent({type:"@xstate.event",sourceRef:t,actorRef:s,event:e}),s._send(e)}};return r}(this),_&&!n&&this.system.inspect(h(_)),this.sessionId=this.system._bookId(),this.id=d??this.sessionId,this.logger=r,this.clock=o,this._parent=n,this._syncSnapshot=u,this.options=i,this.src=i.src??t,this.ref=this,this._actorScope={self:this,id:this.id,sessionId:this.sessionId,logger:this.logger,defer:t=>{this._deferred.push(t)},system:this.system,stopChild:t=>{if(t._parent!==this)throw new Error(`Cannot stop child actor ${t.id} of ${this.id} because it is not a child`);t._stop()}},this.send=this.send.bind(this),this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this}),l&&(this._systemId=l,this.system._set(l,this)),this._initState(e?.snapshot??e?.state),l&&"active"!==this._snapshot.status&&this.system._unregister(this)}_initState(t){try{this._snapshot=t?this.logic.restoreSnapshot?this.logic.restoreSnapshot(t,this._actorScope):t:this.logic.getInitialSnapshot(this._actorScope,this.options?.input)}catch(t){this._snapshot={status:"error",output:void 0,error:t}}}update(t,s){let e;for(this._snapshot=t;e=this._deferred.shift();)try{e()}catch(s){this._deferred.length=0,this._snapshot={...t,status:"error",error:s}}switch(this._snapshot.status){case"active":for(const s of this.observers)try{s.next?.(t)}catch(t){r(t)}break;case"done":for(const s of this.observers)try{s.next?.(t)}catch(t){r(t)}this._stopProcedure(),this._complete(),this._doneEvent=(i=this.id,o=this._snapshot.output,{type:`xstate.done.actor.${i}`,output:o}),this._parent&&this.system._relay(this,this._parent,this._doneEvent);break;case"error":this._error(this._snapshot.error)}var i,o;this.system._sendInspectionEvent({type:"@xstate.snapshot",actorRef:this,event:s,snapshot:t})}subscribe(t,s,e){const i=h(t,s,e);if(this._processingStatus!==c.Stopped)this.observers.add(i);else try{i.complete?.()}catch(t){r(t)}return{unsubscribe:()=>{this.observers.delete(i)}}}start(){if(this._processingStatus===c.Running)return this;this._syncSnapshot&&this.subscribe({next:t=>{"active"===t.status&&this.system._relay(this,this._parent,{type:`xstate.snapshot.${this.id}`,snapshot:t})},error:()=>{}}),this.system._register(this.sessionId,this),this._systemId&&this.system._set(this._systemId,this),this._processingStatus=c.Running;const t={type:"xstate.init",input:this.options.input};this.system._sendInspectionEvent({type:"@xstate.event",sourceRef:this._parent,actorRef:this,event:t});switch(this._snapshot.status){case"done":return this.update(this._snapshot,t),this;case"error":return this._error(this._snapshot.error),this}if(this.logic.start)try{this.logic.start(this._snapshot,this._actorScope)}catch(t){return this._snapshot={...this._snapshot,status:"error",error:t},this._error(t),this}return this.update(this._snapshot,t),this.options.devTools&&this.attachDevTools(),this.mailbox.start(),this}_process(t){let s,i;try{s=this.logic.transition(this._snapshot,t,this._actorScope)}catch(t){i={err:t}}if(i){const{err:t}=i;return this._snapshot={...this._snapshot,status:"error",error:t},void this._error(t)}this.update(s,t),t.type===e&&(this._stopProcedure(),this._complete())}_stop(){return this._processingStatus===c.Stopped?this:(this.mailbox.clear(),this._processingStatus===c.NotStarted?(this._processingStatus=c.Stopped,this):(this.mailbox.enqueue({type:e}),this))}stop(){if(this._parent)throw new Error("A non-root actor cannot be stopped directly.");return this._stop()}_complete(){for(const t of this.observers)try{t.complete?.()}catch(t){r(t)}this.observers.clear()}_reportError(t){if(!this.observers.size)return void(this._parent||r(t));let s=!1;for(const e of this.observers){const i=e.error;s||=!i;try{i?.(t)}catch(t){r(t)}}this.observers.clear(),s&&r(t)}_error(t){this._stopProcedure(),this._reportError(t),this._parent&&this.system._relay(this,this._parent,{type:`xstate.error.actor.${this.id}`,error:t})}_stopProcedure(){if(this._processingStatus!==c.Running)return this;for(const t of Object.keys(this.delayedEventsMap))this.clock.clearTimeout(this.delayedEventsMap[t]);return this.mailbox.clear(),this.mailbox=new s(this._process.bind(this)),this._processingStatus=c.Stopped,this.system._unregister(this),this}_send(t){this._processingStatus!==c.Stopped&&this.mailbox.enqueue(t)}send(t){this.system._relay(void 0,this,t)}delaySend(t){const{event:s,id:e,delay:i}=t,o=this.clock.setTimeout((()=>{this.system._relay(this,t.to??this,s)}),i);e&&(this.delayedEventsMap[e]=o)}cancel(t){this.clock.clearTimeout(this.delayedEventsMap[t]),delete this.delayedEventsMap[t]}attachDevTools(){const{devTools:t}=this.options;if(t){("function"==typeof t?t:o)(this)}}toJSON(){return{xstate$$type:1,id:this.id}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[n](){return this}getSnapshot(){return this._snapshot}}function d(t,s){return{config:t,transition:(s,e,i)=>({...s,context:t(s.context,e,i)}),getInitialSnapshot:(t,e)=>({status:"active",output:void 0,error:void 0,context:"function"==typeof s?s({input:e}):s}),getPersistedSnapshot:t=>t,restoreSnapshot:t=>t}}const l=new WeakMap;const _="xstate.observable.next",v="xstate.observable.error",f="xstate.observable.complete";const y="xstate.promise.resolve",b="xstate.promise.reject";const g=d((t=>{}),void 0);t.createEmptyActor=function(){return new u(g,t);var t},t.fromCallback=function(t){return{config:t,start:(s,e)=>{const{self:i,system:o}=e,r={receivers:void 0,dispose:void 0};l.set(i,r),r.dispose=t({input:s.input,system:o,self:i,sendBack:t=>{"stopped"!==i.getSnapshot().status&&i._parent&&o._relay(i,i._parent,t)},receive:t=>{r.receivers??=new Set,r.receivers.add(t)}})},transition:(t,s,i)=>{const o=l.get(i.self);return s.type===e?(t={...t,status:"stopped",error:void 0},o.dispose?.(),t):(o.receivers?.forEach((t=>t(s))),t)},getInitialSnapshot:(t,s)=>({status:"active",output:void 0,error:void 0,input:s}),getPersistedSnapshot:t=>t,restoreSnapshot:t=>t}},t.fromEventObservable=function(t){return{config:t,transition:(t,s)=>{if("active"!==t.status)return t;switch(s.type){case v:return{...t,status:"error",error:s.data,input:void 0,_subscription:void 0};case f:return{...t,status:"done",input:void 0,_subscription:void 0};case e:return t._subscription.unsubscribe(),{...t,status:"stopped",input:void 0,_subscription:void 0};default:return t}},getInitialSnapshot:(t,s)=>({status:"active",output:void 0,error:void 0,context:void 0,input:s,_subscription:void 0}),start:(s,{self:e,system:i})=>{"done"!==s.status&&(s._subscription=t({input:s.input,system:i,self:e}).subscribe({next:t=>{e._parent&&i._relay(e,e._parent,t)},error:t=>{i._relay(e,e,{type:v,data:t})},complete:()=>{i._relay(e,e,{type:f})}}))},getPersistedSnapshot:({_subscription:t,...s})=>s,restoreSnapshot:t=>({...t,_subscription:void 0})}},t.fromObservable=function(t){return{config:t,transition:(t,s,{self:i,id:o,defer:r,system:n})=>{if("active"!==t.status)return t;switch(s.type){case _:return{...t,context:s.data};case v:return{...t,status:"error",error:s.data,input:void 0,_subscription:void 0};case f:return{...t,status:"done",input:void 0,_subscription:void 0};case e:return t._subscription.unsubscribe(),{...t,status:"stopped",input:void 0,_subscription:void 0};default:return t}},getInitialSnapshot:(t,s)=>({status:"active",output:void 0,error:void 0,context:void 0,input:s,_subscription:void 0}),start:(s,{self:e,system:i})=>{"done"!==s.status&&(s._subscription=t({input:s.input,system:i,self:e}).subscribe({next:t=>{i._relay(e,e,{type:_,data:t})},error:t=>{i._relay(e,e,{type:v,data:t})},complete:()=>{i._relay(e,e,{type:f})}}))},getPersistedSnapshot:({_subscription:t,...s})=>s,restoreSnapshot:t=>({...t,_subscription:void 0})}},t.fromPromise=function(t){return{config:t,transition:(t,s)=>{if("active"!==t.status)return t;switch(s.type){case y:{const e=s.data;return{...t,status:"done",output:e,input:void 0}}case b:return{...t,status:"error",error:s.data,input:void 0};case e:return{...t,status:"stopped",input:void 0};default:return t}},start:(s,{self:e,system:i})=>{if("active"!==s.status)return;Promise.resolve(t({input:s.input,system:i,self:e})).then((t=>{"active"===e.getSnapshot().status&&i._relay(e,e,{type:y,data:t})}),(t=>{"active"===e.getSnapshot().status&&i._relay(e,e,{type:b,data:t})}))},getInitialSnapshot:(t,s)=>({status:"active",output:void 0,error:void 0,input:s}),getPersistedSnapshot:t=>t,restoreSnapshot:t=>t}},t.fromTransition=d,Object.defineProperty(t,"__esModule",{value:!0})}));
|
|
2
2
|
//# sourceMappingURL=xstate-actors.umd.min.js.map
|