xstate 5.0.0-beta.10 → 5.0.0-beta.12

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 (57) hide show
  1. package/actions/dist/xstate-actions.cjs.js +29 -5
  2. package/actions/dist/{xstate-actions.cjs.dev.js → xstate-actions.development.cjs.js} +2 -2
  3. package/actions/dist/xstate-actions.development.esm.js +2 -0
  4. package/actions/dist/xstate-actions.esm.js +2 -2
  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 +20 -5
  8. package/actors/dist/{xstate-actors.cjs.dev.js → xstate-actors.development.cjs.js} +2 -2
  9. package/actors/dist/xstate-actors.development.esm.js +2 -0
  10. package/actors/dist/xstate-actors.esm.js +2 -2
  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/dev/dist/xstate-dev.cjs.js +45 -4
  14. package/{dist/index-0f3fdf0c.cjs.prod.js → dev/dist/xstate-dev.development.cjs.js} +6 -7
  15. package/{dist/index-50bd0aff.esm.js → dev/dist/xstate-dev.development.esm.js} +6 -8
  16. package/dev/dist/xstate-dev.esm.js +42 -1
  17. package/dev/dist/xstate-dev.umd.min.js +1 -1
  18. package/dev/dist/xstate-dev.umd.min.js.map +1 -1
  19. package/dist/actions-b34f6ce7.esm.js +3292 -0
  20. package/dist/actions-c8b9504d.development.esm.js +3327 -0
  21. package/dist/actions-d9c19f35.development.cjs.js +3409 -0
  22. package/dist/actions-e4c704f3.cjs.js +3374 -0
  23. package/dist/declarations/src/interpreter.d.ts +1 -6
  24. package/dist/declarations/src/types.d.ts +1 -0
  25. package/dist/declarations/src/utils.d.ts +0 -1
  26. package/dist/declarations/src/waitFor.d.ts +1 -1
  27. package/dist/xstate.cjs.js +802 -4
  28. package/dist/xstate.development.cjs.js +808 -0
  29. package/dist/xstate.development.esm.js +770 -0
  30. package/dist/xstate.esm.js +543 -662
  31. package/dist/xstate.umd.min.js +1 -1
  32. package/dist/xstate.umd.min.js.map +1 -1
  33. package/guards/dist/xstate-guards.cjs.js +13 -5
  34. package/guards/dist/{xstate-guards.cjs.prod.js → xstate-guards.development.cjs.js} +2 -2
  35. package/guards/dist/xstate-guards.development.esm.js +2 -0
  36. package/guards/dist/xstate-guards.esm.js +2 -2
  37. package/guards/dist/xstate-guards.umd.min.js +1 -1
  38. package/guards/dist/xstate-guards.umd.min.js.map +1 -1
  39. package/package.json +52 -1
  40. package/actions/dist/xstate-actions.cjs.prod.js +0 -31
  41. package/actors/dist/xstate-actors.cjs.prod.js +0 -22
  42. package/dev/dist/xstate-dev.cjs.dev.js +0 -11
  43. package/dev/dist/xstate-dev.cjs.prod.js +0 -11
  44. package/dist/actions-109712d3.cjs.dev.js +0 -4357
  45. package/dist/actions-67f1d04e.esm.js +0 -4270
  46. package/dist/actions-d0262a43.cjs.prod.js +0 -4333
  47. package/dist/declarations/actions/dynamicAction.d.ts +0 -5
  48. package/dist/declarations/src/Mailbox.d.ts +0 -12
  49. package/dist/declarations/src/actions/invoke.d.ts +0 -3
  50. package/dist/declarations/src/environment.d.ts +0 -1
  51. package/dist/declarations/src/memo.d.ts +0 -2
  52. package/dist/declarations/src/spawn.d.ts +0 -2
  53. package/dist/declarations/src/system.d.ts +0 -2
  54. package/dist/index-ebaab3c9.cjs.dev.js +0 -52
  55. package/dist/xstate.cjs.dev.js +0 -933
  56. package/dist/xstate.cjs.prod.js +0 -930
  57. package/guards/dist/xstate-guards.cjs.dev.js +0 -15
@@ -0,0 +1,770 @@
1
+ import { m as mapValues, t as toActionObjects, a as toArray, f as formatTransitions, b as toTransitionConfigArray, N as NULL_EVENT, c as formatTransition, d as memo, e as evaluateGuard, g as flatten, h as createInvokeId, i as isString, j as invoke, k as getDelayedTransitions, l as formatInitialTransition, n as getCandidates, o as toInvokeConfig, p as createSpawner, S as STATE_DELIMITER, q as getConfiguration, r as getStateNodes, s as resolveStateValue, u as isInFinalState, v as State, w as isErrorEvent, x as macrostep, y as transitionNode, z as getInitialConfiguration, A as createInitEvent, B as resolveActionsAndContext, C as microstep, D as error, E as isStateId, F as getStateNodeByPath, G as getPersistedState, H as resolveReferencedActor, I as interpret, J as initEvent, K as matchesState } from './actions-c8b9504d.development.esm.js';
2
+ export { a9 as ActionTypes, P as Interpreter, Q as InterpreterStatus, aa as SpecialTargets, v as State, a7 as and, T as assign, U as cancel, V as choose, R as doneInvoke, O as forwardTo, a2 as fromCallback, a3 as fromEventObservable, a1 as fromObservable, a0 as fromPromise, a4 as fromTransition, r as getStateNodes, I as interpret, W as log, K as matchesState, a6 as not, a8 as or, _ as pathToStateValue, X as pure, Y as raise, M as sendParent, L as sendTo, a5 as stateIn, Z as stop, $ as toObserver } from './actions-c8b9504d.development.esm.js';
3
+ import '../dev/dist/xstate-dev.development.esm.js';
4
+
5
+ const EMPTY_OBJECT = {};
6
+ class StateNode {
7
+ /**
8
+ * The relative key of the state node, which represents its location in the overall state value.
9
+ */
10
+
11
+ /**
12
+ * The unique ID of the state node.
13
+ */
14
+
15
+ /**
16
+ * The type of this state node:
17
+ *
18
+ * - `'atomic'` - no child state nodes
19
+ * - `'compound'` - nested child state nodes (XOR)
20
+ * - `'parallel'` - orthogonal nested child state nodes (AND)
21
+ * - `'history'` - history state node
22
+ * - `'final'` - final state node
23
+ */
24
+
25
+ /**
26
+ * The string path from the root machine node to this node.
27
+ */
28
+
29
+ /**
30
+ * The child state nodes.
31
+ */
32
+
33
+ /**
34
+ * The type of history on this state node. Can be:
35
+ *
36
+ * - `'shallow'` - recalls only top-level historical state value
37
+ * - `'deep'` - recalls historical state value at all levels
38
+ */
39
+
40
+ /**
41
+ * The action(s) to be executed upon entering the state node.
42
+ */
43
+
44
+ /**
45
+ * The action(s) to be executed upon exiting the state node.
46
+ */
47
+
48
+ /**
49
+ * The parent state node.
50
+ */
51
+
52
+ /**
53
+ * The root machine node.
54
+ */
55
+
56
+ /**
57
+ * The meta data associated with this state node, which will be returned in State instances.
58
+ */
59
+
60
+ /**
61
+ * The output data sent with the "done.state._id_" event if this is a final state node.
62
+ */
63
+
64
+ /**
65
+ * The order this state node appears. Corresponds to the implicit document order.
66
+ */
67
+
68
+ constructor(
69
+ /**
70
+ * The raw config used to create the machine.
71
+ */
72
+ config, options) {
73
+ this.config = config;
74
+ this.key = void 0;
75
+ this.id = void 0;
76
+ this.type = void 0;
77
+ this.path = void 0;
78
+ this.states = void 0;
79
+ this.history = void 0;
80
+ this.entry = void 0;
81
+ this.exit = void 0;
82
+ this.parent = void 0;
83
+ this.machine = void 0;
84
+ this.meta = void 0;
85
+ this.output = void 0;
86
+ this.order = -1;
87
+ this.description = void 0;
88
+ this.tags = [];
89
+ this.transitions = void 0;
90
+ this.always = void 0;
91
+ this.parent = options._parent;
92
+ this.key = options._key;
93
+ this.machine = options._machine;
94
+ this.path = this.parent ? this.parent.path.concat(this.key) : [];
95
+ this.id = this.config.id || [this.machine.id, ...this.path].join(this.machine.delimiter);
96
+ this.type = this.config.type || (this.config.states && Object.keys(this.config.states).length ? 'compound' : this.config.history ? 'history' : 'atomic');
97
+ this.description = this.config.description;
98
+ this.order = this.machine.idMap.size;
99
+ this.machine.idMap.set(this.id, this);
100
+ this.states = this.config.states ? mapValues(this.config.states, (stateConfig, key) => {
101
+ const stateNode = new StateNode(stateConfig, {
102
+ _parent: this,
103
+ _key: key,
104
+ _machine: this.machine
105
+ });
106
+ return stateNode;
107
+ }) : EMPTY_OBJECT;
108
+ if (this.type === 'compound' && !this.config.initial) {
109
+ throw new Error(`No initial state specified for compound state node "#${this.id}". Try adding { initial: "${Object.keys(this.states)[0]}" } to the state config.`);
110
+ }
111
+
112
+ // History config
113
+ this.history = this.config.history === true ? 'shallow' : this.config.history || false;
114
+ this.entry = toActionObjects(this.config.entry);
115
+ this.exit = toActionObjects(this.config.exit);
116
+ this.meta = this.config.meta;
117
+ this.output = this.type === 'final' ? this.config.output : undefined;
118
+ this.tags = toArray(config.tags);
119
+ }
120
+ _initialize() {
121
+ this.transitions = formatTransitions(this);
122
+ if (this.config.always) {
123
+ this.always = toTransitionConfigArray(NULL_EVENT, this.config.always).map(t => formatTransition(this, t));
124
+ }
125
+ Object.keys(this.states).forEach(key => {
126
+ this.states[key]._initialize();
127
+ });
128
+ }
129
+
130
+ /**
131
+ * The well-structured state node definition.
132
+ */
133
+ get definition() {
134
+ return {
135
+ id: this.id,
136
+ key: this.key,
137
+ version: this.machine.version,
138
+ type: this.type,
139
+ initial: this.initial ? {
140
+ target: this.initial.target,
141
+ source: this,
142
+ actions: this.initial.actions,
143
+ eventType: null,
144
+ reenter: false,
145
+ toJSON: () => ({
146
+ target: this.initial.target.map(t => `#${t.id}`),
147
+ source: `#${this.id}`,
148
+ actions: this.initial.actions,
149
+ eventType: null
150
+ })
151
+ } : undefined,
152
+ history: this.history,
153
+ states: mapValues(this.states, state => {
154
+ return state.definition;
155
+ }),
156
+ on: this.on,
157
+ transitions: this.transitions,
158
+ entry: this.entry,
159
+ exit: this.exit,
160
+ meta: this.meta,
161
+ order: this.order || -1,
162
+ output: this.output,
163
+ invoke: this.invoke,
164
+ description: this.description,
165
+ tags: this.tags
166
+ };
167
+ }
168
+ toJSON() {
169
+ return this.definition;
170
+ }
171
+
172
+ /**
173
+ * The behaviors invoked as actors by this state node.
174
+ */
175
+ get invoke() {
176
+ return memo(this, 'invoke', () => toArray(this.config.invoke).map((invocable, i) => {
177
+ const generatedId = createInvokeId(this.id, i);
178
+ const invokeConfig = toInvokeConfig(invocable, generatedId);
179
+ const resolvedId = invokeConfig.id || generatedId;
180
+ const {
181
+ src,
182
+ systemId
183
+ } = invokeConfig;
184
+ const resolvedSrc = isString(src) ? src : !('type' in src) ? resolvedId : src;
185
+ if (!this.machine.options.actors[resolvedId] && typeof src !== 'string' && !('type' in src)) {
186
+ this.machine.options.actors = {
187
+ ...this.machine.options.actors,
188
+ // TODO: this should accept `src` as-is
189
+ [resolvedId]: src
190
+ };
191
+ }
192
+ return {
193
+ type: invoke,
194
+ ...invokeConfig,
195
+ src: resolvedSrc,
196
+ id: resolvedId,
197
+ systemId: systemId,
198
+ toJSON() {
199
+ const {
200
+ onDone,
201
+ onError,
202
+ ...invokeDefValues
203
+ } = invokeConfig;
204
+ return {
205
+ ...invokeDefValues,
206
+ type: invoke,
207
+ src: resolvedSrc,
208
+ id: resolvedId
209
+ };
210
+ }
211
+ };
212
+ }));
213
+ }
214
+
215
+ /**
216
+ * The mapping of events to transitions.
217
+ */
218
+ get on() {
219
+ return memo(this, 'on', () => {
220
+ const transitions = this.transitions;
221
+ return transitions.reduce((map, transition) => {
222
+ map[transition.eventType] = map[transition.eventType] || [];
223
+ map[transition.eventType].push(transition);
224
+ return map;
225
+ }, {});
226
+ });
227
+ }
228
+ get after() {
229
+ return memo(this, 'delayedTransitions', () => getDelayedTransitions(this));
230
+ }
231
+ get initial() {
232
+ return memo(this, 'initial', () => formatInitialTransition(this, this.config.initial || []));
233
+ }
234
+ next(state, event) {
235
+ const eventType = event.type;
236
+ const actions = [];
237
+ let selectedTransition;
238
+ const candidates = memo(this, `candidates-${eventType}`, () => getCandidates(this, eventType));
239
+ for (const candidate of candidates) {
240
+ const {
241
+ guard
242
+ } = candidate;
243
+ const resolvedContext = state.context;
244
+ let guardPassed = false;
245
+ try {
246
+ guardPassed = !guard || evaluateGuard(guard, resolvedContext, event, state);
247
+ } catch (err) {
248
+ throw new Error(`Unable to evaluate guard '${guard.type}' in transition for event '${eventType}' in state node '${this.id}':\n${err.message}`);
249
+ }
250
+ if (guardPassed) {
251
+ actions.push(...candidate.actions);
252
+ selectedTransition = candidate;
253
+ break;
254
+ }
255
+ }
256
+ return selectedTransition ? [selectedTransition] : undefined;
257
+ }
258
+
259
+ /**
260
+ * The target state value of the history state node, if it exists. This represents the
261
+ * default state value to transition to if no history value exists yet.
262
+ */
263
+ get target() {
264
+ if (this.type === 'history') {
265
+ const historyConfig = this.config;
266
+ return historyConfig.target;
267
+ }
268
+ return undefined;
269
+ }
270
+
271
+ /**
272
+ * All the state node IDs of this state node and its descendant state nodes.
273
+ */
274
+ get stateIds() {
275
+ const childStateIds = flatten(Object.keys(this.states).map(stateKey => {
276
+ return this.states[stateKey].stateIds;
277
+ }));
278
+ return [this.id].concat(childStateIds);
279
+ }
280
+
281
+ /**
282
+ * All the event types accepted by this state node and its descendants.
283
+ */
284
+ get events() {
285
+ return memo(this, 'events', () => {
286
+ const {
287
+ states
288
+ } = this;
289
+ const events = new Set(this.ownEvents);
290
+ if (states) {
291
+ for (const stateId of Object.keys(states)) {
292
+ const state = states[stateId];
293
+ if (state.states) {
294
+ for (const event of state.events) {
295
+ events.add(`${event}`);
296
+ }
297
+ }
298
+ }
299
+ }
300
+ return Array.from(events);
301
+ });
302
+ }
303
+
304
+ /**
305
+ * All the events that have transitions directly from this state node.
306
+ *
307
+ * Excludes any inert events.
308
+ */
309
+ get ownEvents() {
310
+ const events = new Set(this.transitions.filter(transition => {
311
+ return !(!transition.target && !transition.actions.length && !transition.reenter);
312
+ }).map(transition => transition.eventType));
313
+ return Array.from(events);
314
+ }
315
+ }
316
+
317
+ const STATE_IDENTIFIER = '#';
318
+ function createDefaultOptions() {
319
+ return {
320
+ actions: {},
321
+ actors: {},
322
+ delays: {},
323
+ guards: {},
324
+ context: {}
325
+ };
326
+ }
327
+ class StateMachine {
328
+ // TODO: this getter should be removed
329
+ getContext(input) {
330
+ return this.getContextAndActions(undefined, input)[0];
331
+ }
332
+ getContextAndActions(actorCtx, input) {
333
+ const actions = [];
334
+ const {
335
+ context
336
+ } = this.config;
337
+ const resolvedContext = typeof context === 'function' ? context({
338
+ spawn: createSpawner(actorCtx?.self, this, undefined,
339
+ // TODO: this requires `| undefined` for all referenced dynamic inputs that are spawnable in the context factory,
340
+ createInitEvent(input), actions),
341
+ input
342
+ }) : context;
343
+ return [resolvedContext || {}, actions];
344
+ }
345
+ /**
346
+ * The machine's own version.
347
+ */
348
+
349
+ constructor(
350
+ /**
351
+ * The raw config used to create the machine.
352
+ */
353
+ config, options) {
354
+ this.config = config;
355
+ this.version = void 0;
356
+ this.delimiter = void 0;
357
+ this.options = void 0;
358
+ this.types = void 0;
359
+ this.__xstatenode = true;
360
+ this.idMap = new Map();
361
+ this.root = void 0;
362
+ this.id = void 0;
363
+ this.states = void 0;
364
+ this.events = void 0;
365
+ this.__TContext = void 0;
366
+ this.__TEvent = void 0;
367
+ this.__TAction = void 0;
368
+ this.__TActorMap = void 0;
369
+ this.__TResolvedTypesMeta = void 0;
370
+ this.id = config.id || '(machine)';
371
+ this.options = Object.assign(createDefaultOptions(), options);
372
+ this.delimiter = this.config.delimiter || STATE_DELIMITER;
373
+ this.version = this.config.version;
374
+ this.types = this.config.types ?? {};
375
+ this.transition = this.transition.bind(this);
376
+ this.root = new StateNode(config, {
377
+ _key: this.id,
378
+ _machine: this
379
+ });
380
+ this.root._initialize();
381
+ this.states = this.root.states; // TODO: remove!
382
+ this.events = this.root.events;
383
+ }
384
+
385
+ /**
386
+ * Clones this state machine with the provided implementations
387
+ * and merges the `context` (if provided).
388
+ *
389
+ * @param implementations Options (`actions`, `guards`, `actors`, `delays`, `context`)
390
+ * to recursively merge with the existing options.
391
+ *
392
+ * @returns A new `StateMachine` instance with the provided implementations.
393
+ */
394
+ provide(implementations) {
395
+ const {
396
+ actions,
397
+ guards,
398
+ actors,
399
+ delays
400
+ } = this.options;
401
+ return new StateMachine(this.config, {
402
+ actions: {
403
+ ...actions,
404
+ ...implementations.actions
405
+ },
406
+ guards: {
407
+ ...guards,
408
+ ...implementations.guards
409
+ },
410
+ actors: {
411
+ ...actors,
412
+ ...implementations.actors
413
+ },
414
+ delays: {
415
+ ...delays,
416
+ ...implementations.delays
417
+ }
418
+ });
419
+ }
420
+
421
+ /**
422
+ * Resolves the given `state` to a new `State` instance relative to this machine.
423
+ *
424
+ * This ensures that `.nextEvents` represent the correct values.
425
+ *
426
+ * @param state The state to resolve
427
+ */
428
+ resolveState(state) {
429
+ const configurationSet = getConfiguration(getStateNodes(this.root, state.value));
430
+ const configuration = Array.from(configurationSet);
431
+ return this.createState({
432
+ ...state,
433
+ value: resolveStateValue(this.root, state.value),
434
+ configuration,
435
+ done: isInFinalState(configuration)
436
+ });
437
+ }
438
+ resolveStateValue(stateValue) {
439
+ const resolvedStateValue = resolveStateValue(this.root, stateValue);
440
+ const resolvedContext = this.getContext();
441
+ return this.resolveState(State.from(resolvedStateValue, resolvedContext, this));
442
+ }
443
+
444
+ /**
445
+ * Determines the next state given the current `state` and received `event`.
446
+ * Calculates a full macrostep from all microsteps.
447
+ *
448
+ * @param state The current State instance or state value
449
+ * @param event The received event
450
+ */
451
+ transition(state = this.initialState, event, actorCtx) {
452
+ const currentState = state instanceof State ? state : this.resolveStateValue(state);
453
+ // TODO: handle error events in a better way
454
+ if (isErrorEvent(event) && !currentState.nextEvents.some(nextEvent => nextEvent === event.type)) {
455
+ throw event.data;
456
+ }
457
+ const {
458
+ state: nextState
459
+ } = macrostep(currentState, event, actorCtx);
460
+ return nextState;
461
+ }
462
+
463
+ /**
464
+ * Determines the next state given the current `state` and `event`.
465
+ * Calculates a microstep.
466
+ *
467
+ * @param state The current state
468
+ * @param event The received event
469
+ */
470
+ microstep(state = this.initialState, event, actorCtx) {
471
+ return macrostep(state, event, actorCtx).microstates;
472
+ }
473
+ getTransitionData(state, event) {
474
+ return transitionNode(this.root, state.value, state, event) || [];
475
+ }
476
+
477
+ /**
478
+ * The initial state _before_ evaluating any microsteps.
479
+ * This "pre-initial" state is provided to initial actions executed in the initial state.
480
+ */
481
+ getPreInitialState(actorCtx, input) {
482
+ const [context, actions] = this.getContextAndActions(actorCtx, input);
483
+ const config = getInitialConfiguration(this.root);
484
+ const preInitial = this.resolveState(this.createState({
485
+ value: {},
486
+ // TODO: this is computed in state constructor
487
+ context,
488
+ event: createInitEvent({}),
489
+ actions: [],
490
+ meta: undefined,
491
+ configuration: config,
492
+ transitions: [],
493
+ children: {}
494
+ }));
495
+ preInitial._initial = true;
496
+ preInitial.actions.unshift(...actions);
497
+ if (actorCtx) {
498
+ const {
499
+ nextState
500
+ } = resolveActionsAndContext(actions, initEvent, preInitial, actorCtx);
501
+ preInitial.children = nextState.children;
502
+ preInitial.actions = nextState.actions;
503
+ }
504
+ return preInitial;
505
+ }
506
+
507
+ /**
508
+ * The initial State instance, which includes all actions to be executed from
509
+ * entering the initial state.
510
+ */
511
+ get initialState() {
512
+ return this.getInitialState();
513
+ }
514
+
515
+ /**
516
+ * Returns the initial `State` instance, with reference to `self` as an `ActorRef`.
517
+ */
518
+ getInitialState(actorCtx, input) {
519
+ const initEvent = createInitEvent(input); // TODO: fix;
520
+
521
+ const preInitialState = this.getPreInitialState(actorCtx, input);
522
+ const nextState = microstep([], preInitialState, actorCtx, initEvent);
523
+ nextState.actions.unshift(...preInitialState.actions);
524
+ const {
525
+ state: macroState
526
+ } = macrostep(nextState, initEvent, actorCtx);
527
+ return macroState;
528
+ }
529
+ start(state, actorCtx) {
530
+ state.actions.forEach(action => {
531
+ action.execute?.(actorCtx);
532
+ });
533
+ Object.values(state.children).forEach(child => {
534
+ if (child.status === 0) {
535
+ try {
536
+ child.start?.();
537
+ } catch (err) {
538
+ // TODO: unify error handling when child starts
539
+ actorCtx.self.send(error(child.id, err));
540
+ }
541
+ }
542
+ });
543
+ }
544
+ getStateNodeById(stateId) {
545
+ const fullPath = stateId.split(this.delimiter);
546
+ const relativePath = fullPath.slice(1);
547
+ const resolvedStateId = isStateId(fullPath[0]) ? fullPath[0].slice(STATE_IDENTIFIER.length) : fullPath[0];
548
+ const stateNode = this.idMap.get(resolvedStateId);
549
+ if (!stateNode) {
550
+ throw new Error(`Child state node '#${resolvedStateId}' does not exist on machine '${this.id}'`);
551
+ }
552
+ return getStateNodeByPath(stateNode, relativePath);
553
+ }
554
+ get definition() {
555
+ return {
556
+ context: this.getContext(),
557
+ ...this.root.definition
558
+ };
559
+ }
560
+ toJSON() {
561
+ return this.definition;
562
+ }
563
+ getPersistedState(state) {
564
+ return getPersistedState(state);
565
+ }
566
+ createState(stateConfig) {
567
+ const state = stateConfig instanceof State ? stateConfig : new State(stateConfig, this);
568
+ const {
569
+ nextState: resolvedState
570
+ } = resolveActionsAndContext(state.actions, state.event, state, undefined);
571
+ return resolvedState;
572
+ }
573
+ getStatus(state) {
574
+ return state.done ? {
575
+ status: 'done',
576
+ data: state.output
577
+ } : {
578
+ status: 'active'
579
+ };
580
+ }
581
+ restoreState(state, _actorCtx) {
582
+ const children = {};
583
+ Object.keys(state.children).forEach(actorId => {
584
+ const actorData = state.children[actorId];
585
+ const childState = actorData.state;
586
+ const src = actorData.src;
587
+ const behavior = src ? resolveReferencedActor(this.options.actors[src])?.src : undefined;
588
+ if (!behavior) {
589
+ return;
590
+ }
591
+ const actorState = behavior.restoreState?.(childState, _actorCtx);
592
+ const actorRef = interpret(behavior, {
593
+ id: actorId,
594
+ state: actorState
595
+ });
596
+ children[actorId] = actorRef;
597
+ });
598
+ const restoredState = this.createState(new State({
599
+ ...state,
600
+ children
601
+ }, this));
602
+
603
+ // TODO: DRY this up
604
+ restoredState.configuration.forEach(stateNode => {
605
+ if (stateNode.invoke) {
606
+ stateNode.invoke.forEach(invokeConfig => {
607
+ const {
608
+ id,
609
+ src
610
+ } = invokeConfig;
611
+ if (children[id]) {
612
+ return;
613
+ }
614
+ const referenced = resolveReferencedActor(this.options.actors[src]);
615
+ if (referenced) {
616
+ const actorRef = interpret(referenced.src, {
617
+ id,
618
+ parent: _actorCtx?.self,
619
+ input: 'input' in invokeConfig ? invokeConfig.input : referenced.input
620
+ });
621
+ children[id] = actorRef;
622
+ }
623
+ });
624
+ }
625
+ });
626
+ restoredState.actions = [];
627
+ return restoredState;
628
+ }
629
+
630
+ /**@deprecated an internal property acting as a "phantom" type, not meant to be used at runtime */
631
+ }
632
+
633
+ function createMachine(config, implementations) {
634
+ return new StateMachine(config, implementations);
635
+ }
636
+
637
+ function mapState(stateMap, stateId) {
638
+ let foundStateId;
639
+ for (const mappedStateId of Object.keys(stateMap)) {
640
+ if (matchesState(mappedStateId, stateId) && (!foundStateId || stateId.length > foundStateId.length)) {
641
+ foundStateId = mappedStateId;
642
+ }
643
+ }
644
+ return stateMap[foundStateId];
645
+ }
646
+
647
+ class SimulatedClock {
648
+ constructor() {
649
+ this.timeouts = new Map();
650
+ this._now = 0;
651
+ this._id = 0;
652
+ }
653
+ now() {
654
+ return this._now;
655
+ }
656
+ getId() {
657
+ return this._id++;
658
+ }
659
+ setTimeout(fn, timeout) {
660
+ const id = this.getId();
661
+ this.timeouts.set(id, {
662
+ start: this.now(),
663
+ timeout,
664
+ fn
665
+ });
666
+ return id;
667
+ }
668
+ clearTimeout(id) {
669
+ this.timeouts.delete(id);
670
+ }
671
+ set(time) {
672
+ if (this._now > time) {
673
+ throw new Error('Unable to travel back in time');
674
+ }
675
+ this._now = time;
676
+ this.flushTimeouts();
677
+ }
678
+ flushTimeouts() {
679
+ [...this.timeouts].sort(([_idA, timeoutA], [_idB, timeoutB]) => {
680
+ const endA = timeoutA.start + timeoutA.timeout;
681
+ const endB = timeoutB.start + timeoutB.timeout;
682
+ return endB > endA ? -1 : 1;
683
+ }).forEach(([id, timeout]) => {
684
+ if (this.now() - timeout.start >= timeout.timeout) {
685
+ this.timeouts.delete(id);
686
+ timeout.fn.call(null);
687
+ }
688
+ });
689
+ }
690
+ increment(ms) {
691
+ this._now += ms;
692
+ this.flushTimeouts();
693
+ }
694
+ }
695
+
696
+ const defaultWaitForOptions = {
697
+ timeout: 10_000 // 10 seconds
698
+ };
699
+
700
+ /**
701
+ * Subscribes to an actor ref and waits for its emitted value to satisfy
702
+ * a predicate, and then resolves with that value.
703
+ * Will throw if the desired state is not reached after a timeout
704
+ * (defaults to 10 seconds).
705
+ *
706
+ * @example
707
+ * ```js
708
+ * const state = await waitFor(someService, state => {
709
+ * return state.hasTag('loaded');
710
+ * });
711
+ *
712
+ * state.hasTag('loaded'); // true
713
+ * ```
714
+ *
715
+ * @param actorRef The actor ref to subscribe to
716
+ * @param predicate Determines if a value matches the condition to wait for
717
+ * @param options
718
+ * @returns A promise that eventually resolves to the emitted value
719
+ * that matches the condition
720
+ */
721
+ function waitFor(actorRef, predicate, options) {
722
+ const resolvedOptions = {
723
+ ...defaultWaitForOptions,
724
+ ...options
725
+ };
726
+ return new Promise((res, rej) => {
727
+ let done = false;
728
+ if (resolvedOptions.timeout < 0) {
729
+ console.error('`timeout` passed to `waitFor` is negative and it will reject its internal promise immediately.');
730
+ }
731
+ const handle = resolvedOptions.timeout === Infinity ? undefined : setTimeout(() => {
732
+ sub.unsubscribe();
733
+ rej(new Error(`Timeout of ${resolvedOptions.timeout} ms exceeded`));
734
+ }, resolvedOptions.timeout);
735
+ const dispose = () => {
736
+ clearTimeout(handle);
737
+ done = true;
738
+ sub?.unsubscribe();
739
+ };
740
+ function checkEmitted(emitted) {
741
+ if (predicate(emitted)) {
742
+ dispose();
743
+ res(emitted);
744
+ }
745
+ }
746
+ let sub; // avoid TDZ when disposing synchronously
747
+
748
+ // See if the current snapshot already matches the predicate
749
+ checkEmitted(actorRef.getSnapshot());
750
+ if (done) {
751
+ return;
752
+ }
753
+ sub = actorRef.subscribe({
754
+ next: checkEmitted,
755
+ error: err => {
756
+ dispose();
757
+ rej(err);
758
+ },
759
+ complete: () => {
760
+ dispose();
761
+ rej(new Error(`Actor terminated without satisfying predicate`));
762
+ }
763
+ });
764
+ if (done) {
765
+ sub.unsubscribe();
766
+ }
767
+ });
768
+ }
769
+
770
+ export { SimulatedClock, StateMachine, StateNode, createMachine, mapState, waitFor };