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.
Files changed (127) hide show
  1. package/README.md +10 -8
  2. package/actions/dist/xstate-actions.cjs.d.mts +2 -0
  3. package/actions/dist/xstate-actions.cjs.d.mts.map +1 -0
  4. package/actions/dist/xstate-actions.cjs.d.ts +1 -0
  5. package/actions/dist/xstate-actions.cjs.d.ts.map +1 -0
  6. package/actions/dist/xstate-actions.cjs.js +19 -5
  7. package/actions/dist/xstate-actions.cjs.mjs +13 -0
  8. package/actions/dist/xstate-actions.development.cjs.js +21 -0
  9. package/actions/dist/xstate-actions.development.cjs.mjs +13 -0
  10. package/actions/dist/xstate-actions.development.esm.js +3 -0
  11. package/actions/dist/xstate-actions.esm.js +3 -2
  12. package/actions/dist/xstate-actions.umd.min.js +1 -1
  13. package/actions/dist/xstate-actions.umd.min.js.map +1 -1
  14. package/actors/dist/xstate-actors.cjs.d.mts +2 -0
  15. package/actors/dist/xstate-actors.cjs.d.mts.map +1 -0
  16. package/actors/dist/xstate-actors.cjs.d.ts +1 -0
  17. package/actors/dist/xstate-actors.cjs.d.ts.map +1 -0
  18. package/actors/dist/xstate-actors.cjs.js +621 -4
  19. package/actors/dist/xstate-actors.cjs.mjs +8 -0
  20. package/actors/dist/xstate-actors.development.cjs.js +624 -0
  21. package/actors/dist/xstate-actors.development.cjs.mjs +8 -0
  22. package/actors/dist/xstate-actors.development.esm.js +615 -0
  23. package/actors/dist/xstate-actors.esm.js +615 -2
  24. package/actors/dist/xstate-actors.umd.min.js +1 -1
  25. package/actors/dist/xstate-actors.umd.min.js.map +1 -1
  26. package/dev/dist/xstate-dev.cjs.d.mts +2 -0
  27. package/dev/dist/xstate-dev.cjs.d.mts.map +1 -0
  28. package/dev/dist/xstate-dev.cjs.d.ts +1 -0
  29. package/dev/dist/xstate-dev.cjs.d.ts.map +1 -0
  30. package/dev/dist/xstate-dev.cjs.js +45 -4
  31. package/dev/dist/xstate-dev.cjs.mjs +5 -0
  32. package/{dist/index-ebaab3c9.cjs.dev.js → dev/dist/xstate-dev.development.cjs.js} +6 -7
  33. package/dev/dist/xstate-dev.development.cjs.mjs +5 -0
  34. package/{dist/index-50bd0aff.esm.js → dev/dist/xstate-dev.development.esm.js} +6 -8
  35. package/dev/dist/xstate-dev.esm.js +42 -1
  36. package/dev/dist/xstate-dev.umd.min.js +1 -1
  37. package/dev/dist/xstate-dev.umd.min.js.map +1 -1
  38. package/dist/declarations/src/SimulatedClock.d.ts +1 -1
  39. package/dist/declarations/src/State.d.ts +47 -73
  40. package/dist/declarations/src/StateMachine.d.ts +29 -57
  41. package/dist/declarations/src/StateNode.d.ts +36 -33
  42. package/dist/declarations/src/actions/assign.d.ts +11 -2
  43. package/dist/declarations/src/actions/cancel.d.ts +7 -3
  44. package/dist/declarations/src/actions/enqueueActions.d.ts +32 -0
  45. package/dist/declarations/src/actions/log.d.ts +7 -3
  46. package/dist/declarations/src/actions/raise.d.ts +7 -2
  47. package/dist/declarations/src/actions/send.d.ts +14 -36
  48. package/dist/declarations/src/actions/spawnChild.d.ts +29 -0
  49. package/dist/declarations/src/actions/stopChild.d.ts +18 -0
  50. package/dist/declarations/src/actions.d.ts +8 -48
  51. package/dist/declarations/src/actors/callback.d.ts +91 -8
  52. package/dist/declarations/src/actors/index.d.ts +6 -28
  53. package/dist/declarations/src/actors/observable.d.ts +101 -18
  54. package/dist/declarations/src/actors/promise.d.ts +80 -10
  55. package/dist/declarations/src/actors/transition.d.ts +64 -9
  56. package/dist/declarations/src/constants.d.ts +3 -0
  57. package/dist/declarations/src/createMachine.d.ts +20 -0
  58. package/dist/declarations/src/dev/index.d.ts +6 -6
  59. package/dist/declarations/src/guards.d.ts +41 -8
  60. package/dist/declarations/src/index.d.ts +18 -23
  61. package/dist/declarations/src/interpreter.d.ts +150 -41
  62. package/dist/declarations/src/setup.d.ts +51 -0
  63. package/dist/declarations/src/spawn.d.ts +23 -2
  64. package/dist/declarations/src/stateUtils.d.ts +30 -45
  65. package/dist/declarations/src/system.d.ts +26 -2
  66. package/dist/declarations/src/typegenTypes.d.ts +40 -22
  67. package/dist/declarations/src/types.d.ts +528 -669
  68. package/dist/declarations/src/utils.d.ts +15 -52
  69. package/dist/declarations/src/waitFor.d.ts +2 -2
  70. package/dist/log-22e678c5.esm.js +364 -0
  71. package/dist/log-5e226275.cjs.js +372 -0
  72. package/dist/log-641cd926.development.cjs.js +394 -0
  73. package/dist/log-f196f85f.development.esm.js +386 -0
  74. package/dist/raise-34e25c2c.cjs.js +2368 -0
  75. package/dist/raise-62704519.development.cjs.js +2422 -0
  76. package/dist/raise-89c581c4.development.esm.js +2371 -0
  77. package/dist/raise-8bc422d1.esm.js +2317 -0
  78. package/dist/xstate.cjs.d.mts +2 -0
  79. package/dist/xstate.cjs.d.mts.map +1 -0
  80. package/dist/xstate.cjs.d.ts +1 -0
  81. package/dist/xstate.cjs.d.ts.map +1 -0
  82. package/dist/xstate.cjs.js +728 -4
  83. package/dist/xstate.cjs.mjs +39 -0
  84. package/dist/xstate.development.cjs.js +737 -0
  85. package/dist/xstate.development.cjs.mjs +39 -0
  86. package/dist/xstate.development.esm.js +699 -0
  87. package/dist/xstate.esm.js +561 -770
  88. package/dist/xstate.umd.min.js +1 -1
  89. package/dist/xstate.umd.min.js.map +1 -1
  90. package/guards/dist/xstate-guards.cjs.d.mts +2 -0
  91. package/guards/dist/xstate-guards.cjs.d.mts.map +1 -0
  92. package/guards/dist/xstate-guards.cjs.d.ts +1 -0
  93. package/guards/dist/xstate-guards.cjs.d.ts.map +1 -0
  94. package/guards/dist/xstate-guards.cjs.js +12 -5
  95. package/guards/dist/xstate-guards.cjs.mjs +7 -0
  96. package/guards/dist/xstate-guards.development.cjs.js +14 -0
  97. package/guards/dist/xstate-guards.development.cjs.mjs +7 -0
  98. package/guards/dist/xstate-guards.development.esm.js +2 -0
  99. package/guards/dist/xstate-guards.esm.js +2 -2
  100. package/guards/dist/xstate-guards.umd.min.js +1 -1
  101. package/guards/dist/xstate-guards.umd.min.js.map +1 -1
  102. package/package.json +59 -1
  103. package/actions/dist/xstate-actions.cjs.dev.js +0 -32
  104. package/actions/dist/xstate-actions.cjs.prod.js +0 -32
  105. package/actions/dynamicAction.ts +0 -42
  106. package/actors/dist/xstate-actors.cjs.dev.js +0 -22
  107. package/actors/dist/xstate-actors.cjs.prod.js +0 -22
  108. package/dev/dist/xstate-dev.cjs.dev.js +0 -11
  109. package/dev/dist/xstate-dev.cjs.prod.js +0 -48
  110. package/dist/actions-900f9761.cjs.prod.js +0 -4349
  111. package/dist/actions-c8d7df32.esm.js +0 -4332
  112. package/dist/actions-d06ca158.cjs.dev.js +0 -4387
  113. package/dist/declarations/actions/dynamicAction.d.ts +0 -5
  114. package/dist/declarations/src/Machine.d.ts +0 -4
  115. package/dist/declarations/src/Mailbox.d.ts +0 -12
  116. package/dist/declarations/src/actionTypes.d.ts +0 -16
  117. package/dist/declarations/src/actions/choose.d.ts +0 -3
  118. package/dist/declarations/src/actions/invoke.d.ts +0 -3
  119. package/dist/declarations/src/actions/pure.d.ts +0 -6
  120. package/dist/declarations/src/actions/stop.d.ts +0 -7
  121. package/dist/declarations/src/environment.d.ts +0 -1
  122. package/dist/declarations/src/mapState.d.ts +0 -3
  123. package/dist/declarations/src/memo.d.ts +0 -2
  124. package/dist/xstate.cjs.dev.js +0 -956
  125. package/dist/xstate.cjs.prod.js +0 -953
  126. package/guards/dist/xstate-guards.cjs.dev.js +0 -15
  127. package/guards/dist/xstate-guards.cjs.prod.js +0 -15
@@ -0,0 +1,737 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var actors_dist_xstateActors = require('../actors/dist/xstate-actors.development.cjs.js');
6
+ var guards_dist_xstateGuards = require('./raise-62704519.development.cjs.js');
7
+ var log = require('./log-641cd926.development.cjs.js');
8
+ require('../dev/dist/xstate-dev.development.cjs.js');
9
+
10
+ class SimulatedClock {
11
+ constructor() {
12
+ this.timeouts = new Map();
13
+ this._now = 0;
14
+ this._id = 0;
15
+ }
16
+ now() {
17
+ return this._now;
18
+ }
19
+ getId() {
20
+ return this._id++;
21
+ }
22
+ setTimeout(fn, timeout) {
23
+ const id = this.getId();
24
+ this.timeouts.set(id, {
25
+ start: this.now(),
26
+ timeout,
27
+ fn
28
+ });
29
+ return id;
30
+ }
31
+ clearTimeout(id) {
32
+ this.timeouts.delete(id);
33
+ }
34
+ set(time) {
35
+ if (this._now > time) {
36
+ throw new Error('Unable to travel back in time');
37
+ }
38
+ this._now = time;
39
+ this.flushTimeouts();
40
+ }
41
+ flushTimeouts() {
42
+ [...this.timeouts].sort(([_idA, timeoutA], [_idB, timeoutB]) => {
43
+ const endA = timeoutA.start + timeoutA.timeout;
44
+ const endB = timeoutB.start + timeoutB.timeout;
45
+ return endB > endA ? -1 : 1;
46
+ }).forEach(([id, timeout]) => {
47
+ if (this.now() - timeout.start >= timeout.timeout) {
48
+ this.timeouts.delete(id);
49
+ timeout.fn.call(null);
50
+ }
51
+ });
52
+ }
53
+ increment(ms) {
54
+ this._now += ms;
55
+ this.flushTimeouts();
56
+ }
57
+ }
58
+
59
+ const cache = new WeakMap();
60
+ function memo(object, key, fn) {
61
+ let memoizedData = cache.get(object);
62
+ if (!memoizedData) {
63
+ memoizedData = {
64
+ [key]: fn()
65
+ };
66
+ cache.set(object, memoizedData);
67
+ } else if (!(key in memoizedData)) {
68
+ memoizedData[key] = fn();
69
+ }
70
+ return memoizedData[key];
71
+ }
72
+
73
+ const EMPTY_OBJECT = {};
74
+ const toSerializableAction = action => {
75
+ if (typeof action === 'string') {
76
+ return {
77
+ type: action
78
+ };
79
+ }
80
+ if (typeof action === 'function') {
81
+ if ('resolve' in action) {
82
+ return {
83
+ type: action.type
84
+ };
85
+ }
86
+ return {
87
+ type: action.name
88
+ };
89
+ }
90
+ return action;
91
+ };
92
+ class StateNode {
93
+ constructor(
94
+ /**
95
+ * The raw config used to create the machine.
96
+ */
97
+ config, options) {
98
+ this.config = config;
99
+ /**
100
+ * The relative key of the state node, which represents its location in the overall state value.
101
+ */
102
+ this.key = void 0;
103
+ /**
104
+ * The unique ID of the state node.
105
+ */
106
+ this.id = void 0;
107
+ /**
108
+ * The type of this state node:
109
+ *
110
+ * - `'atomic'` - no child state nodes
111
+ * - `'compound'` - nested child state nodes (XOR)
112
+ * - `'parallel'` - orthogonal nested child state nodes (AND)
113
+ * - `'history'` - history state node
114
+ * - `'final'` - final state node
115
+ */
116
+ this.type = void 0;
117
+ /**
118
+ * The string path from the root machine node to this node.
119
+ */
120
+ this.path = void 0;
121
+ /**
122
+ * The child state nodes.
123
+ */
124
+ this.states = void 0;
125
+ /**
126
+ * The type of history on this state node. Can be:
127
+ *
128
+ * - `'shallow'` - recalls only top-level historical state value
129
+ * - `'deep'` - recalls historical state value at all levels
130
+ */
131
+ this.history = void 0;
132
+ /**
133
+ * The action(s) to be executed upon entering the state node.
134
+ */
135
+ this.entry = void 0;
136
+ /**
137
+ * The action(s) to be executed upon exiting the state node.
138
+ */
139
+ this.exit = void 0;
140
+ /**
141
+ * The parent state node.
142
+ */
143
+ this.parent = void 0;
144
+ /**
145
+ * The root machine node.
146
+ */
147
+ this.machine = void 0;
148
+ /**
149
+ * The meta data associated with this state node, which will be returned in State instances.
150
+ */
151
+ this.meta = void 0;
152
+ /**
153
+ * The output data sent with the "xstate.done.state._id_" event if this is a final state node.
154
+ */
155
+ this.output = void 0;
156
+ /**
157
+ * The order this state node appears. Corresponds to the implicit document order.
158
+ */
159
+ this.order = -1;
160
+ this.description = void 0;
161
+ this.tags = [];
162
+ this.transitions = void 0;
163
+ this.always = void 0;
164
+ this.parent = options._parent;
165
+ this.key = options._key;
166
+ this.machine = options._machine;
167
+ this.path = this.parent ? this.parent.path.concat(this.key) : [];
168
+ this.id = this.config.id || [this.machine.id, ...this.path].join(guards_dist_xstateGuards.STATE_DELIMITER);
169
+ this.type = this.config.type || (this.config.states && Object.keys(this.config.states).length ? 'compound' : this.config.history ? 'history' : 'atomic');
170
+ this.description = this.config.description;
171
+ this.order = this.machine.idMap.size;
172
+ this.machine.idMap.set(this.id, this);
173
+ this.states = this.config.states ? guards_dist_xstateGuards.mapValues(this.config.states, (stateConfig, key) => {
174
+ const stateNode = new StateNode(stateConfig, {
175
+ _parent: this,
176
+ _key: key,
177
+ _machine: this.machine
178
+ });
179
+ return stateNode;
180
+ }) : EMPTY_OBJECT;
181
+ if (this.type === 'compound' && !this.config.initial) {
182
+ 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.`);
183
+ }
184
+
185
+ // History config
186
+ this.history = this.config.history === true ? 'shallow' : this.config.history || false;
187
+ this.entry = guards_dist_xstateGuards.toArray(this.config.entry).slice();
188
+ this.exit = guards_dist_xstateGuards.toArray(this.config.exit).slice();
189
+ this.meta = this.config.meta;
190
+ this.output = this.type === 'final' || !this.parent ? this.config.output : undefined;
191
+ this.tags = guards_dist_xstateGuards.toArray(config.tags).slice();
192
+ }
193
+ _initialize() {
194
+ this.transitions = guards_dist_xstateGuards.formatTransitions(this);
195
+ if (this.config.always) {
196
+ this.always = guards_dist_xstateGuards.toTransitionConfigArray(this.config.always).map(t => guards_dist_xstateGuards.formatTransition(this, guards_dist_xstateGuards.NULL_EVENT, t));
197
+ }
198
+ Object.keys(this.states).forEach(key => {
199
+ this.states[key]._initialize();
200
+ });
201
+ }
202
+
203
+ /**
204
+ * The well-structured state node definition.
205
+ */
206
+ get definition() {
207
+ return {
208
+ id: this.id,
209
+ key: this.key,
210
+ version: this.machine.version,
211
+ type: this.type,
212
+ initial: this.initial ? {
213
+ target: this.initial.target,
214
+ source: this,
215
+ actions: this.initial.actions.map(toSerializableAction),
216
+ eventType: null,
217
+ reenter: false,
218
+ toJSON: () => ({
219
+ target: this.initial.target.map(t => `#${t.id}`),
220
+ source: `#${this.id}`,
221
+ actions: this.initial.actions.map(toSerializableAction),
222
+ eventType: null
223
+ })
224
+ } : undefined,
225
+ history: this.history,
226
+ states: guards_dist_xstateGuards.mapValues(this.states, state => {
227
+ return state.definition;
228
+ }),
229
+ on: this.on,
230
+ transitions: [...this.transitions.values()].flat().map(t => ({
231
+ ...t,
232
+ actions: t.actions.map(toSerializableAction)
233
+ })),
234
+ entry: this.entry.map(toSerializableAction),
235
+ exit: this.exit.map(toSerializableAction),
236
+ meta: this.meta,
237
+ order: this.order || -1,
238
+ output: this.output,
239
+ invoke: this.invoke,
240
+ description: this.description,
241
+ tags: this.tags
242
+ };
243
+ }
244
+ toJSON() {
245
+ return this.definition;
246
+ }
247
+
248
+ /**
249
+ * The logic invoked as actors by this state node.
250
+ */
251
+ get invoke() {
252
+ return memo(this, 'invoke', () => guards_dist_xstateGuards.toArray(this.config.invoke).map((invokeConfig, i) => {
253
+ const {
254
+ src,
255
+ systemId
256
+ } = invokeConfig;
257
+ const resolvedId = invokeConfig.id ?? guards_dist_xstateGuards.createInvokeId(this.id, i);
258
+ const resolvedSrc = typeof src === 'string' ? src : `xstate.invoke.${guards_dist_xstateGuards.createInvokeId(this.id, i)}`;
259
+ return {
260
+ ...invokeConfig,
261
+ src: resolvedSrc,
262
+ id: resolvedId,
263
+ systemId: systemId,
264
+ toJSON() {
265
+ const {
266
+ onDone,
267
+ onError,
268
+ ...invokeDefValues
269
+ } = invokeConfig;
270
+ return {
271
+ ...invokeDefValues,
272
+ type: 'xstate.invoke',
273
+ src: resolvedSrc,
274
+ id: resolvedId
275
+ };
276
+ }
277
+ };
278
+ }));
279
+ }
280
+
281
+ /**
282
+ * The mapping of events to transitions.
283
+ */
284
+ get on() {
285
+ return memo(this, 'on', () => {
286
+ const transitions = this.transitions;
287
+ return [...transitions].flatMap(([descriptor, t]) => t.map(t => [descriptor, t])).reduce((map, [descriptor, transition]) => {
288
+ map[descriptor] = map[descriptor] || [];
289
+ map[descriptor].push(transition);
290
+ return map;
291
+ }, {});
292
+ });
293
+ }
294
+ get after() {
295
+ return memo(this, 'delayedTransitions', () => guards_dist_xstateGuards.getDelayedTransitions(this));
296
+ }
297
+ get initial() {
298
+ return memo(this, 'initial', () => guards_dist_xstateGuards.formatInitialTransition(this, this.config.initial));
299
+ }
300
+ next(snapshot, event) {
301
+ const eventType = event.type;
302
+ const actions = [];
303
+ let selectedTransition;
304
+ const candidates = memo(this, `candidates-${eventType}`, () => guards_dist_xstateGuards.getCandidates(this, eventType));
305
+ for (const candidate of candidates) {
306
+ const {
307
+ guard
308
+ } = candidate;
309
+ const resolvedContext = snapshot.context;
310
+ let guardPassed = false;
311
+ try {
312
+ guardPassed = !guard || guards_dist_xstateGuards.evaluateGuard(guard, resolvedContext, event, snapshot);
313
+ } catch (err) {
314
+ const guardType = typeof guard === 'string' ? guard : typeof guard === 'object' ? guard.type : undefined;
315
+ throw new Error(`Unable to evaluate guard ${guardType ? `'${guardType}' ` : ''}in transition for event '${eventType}' in state node '${this.id}':\n${err.message}`);
316
+ }
317
+ if (guardPassed) {
318
+ actions.push(...candidate.actions);
319
+ selectedTransition = candidate;
320
+ break;
321
+ }
322
+ }
323
+ return selectedTransition ? [selectedTransition] : undefined;
324
+ }
325
+
326
+ /**
327
+ * All the event types accepted by this state node and its descendants.
328
+ */
329
+ get events() {
330
+ return memo(this, 'events', () => {
331
+ const {
332
+ states
333
+ } = this;
334
+ const events = new Set(this.ownEvents);
335
+ if (states) {
336
+ for (const stateId of Object.keys(states)) {
337
+ const state = states[stateId];
338
+ if (state.states) {
339
+ for (const event of state.events) {
340
+ events.add(`${event}`);
341
+ }
342
+ }
343
+ }
344
+ }
345
+ return Array.from(events);
346
+ });
347
+ }
348
+
349
+ /**
350
+ * All the events that have transitions directly from this state node.
351
+ *
352
+ * Excludes any inert events.
353
+ */
354
+ get ownEvents() {
355
+ const events = new Set([...this.transitions.keys()].filter(descriptor => {
356
+ return this.transitions.get(descriptor).some(transition => !(!transition.target && !transition.actions.length && !transition.reenter));
357
+ }));
358
+ return Array.from(events);
359
+ }
360
+ }
361
+
362
+ const STATE_IDENTIFIER = '#';
363
+ class StateMachine {
364
+ constructor(
365
+ /**
366
+ * The raw config used to create the machine.
367
+ */
368
+ config, implementations) {
369
+ this.config = config;
370
+ /**
371
+ * The machine's own version.
372
+ */
373
+ this.version = void 0;
374
+ this.implementations = void 0;
375
+ this.__xstatenode = true;
376
+ this.idMap = new Map();
377
+ this.root = void 0;
378
+ this.id = void 0;
379
+ this.states = void 0;
380
+ this.events = void 0;
381
+ /** @deprecated an internal property acting as a "phantom" type, not meant to be used at runtime */
382
+ this.__TResolvedTypesMeta = void 0;
383
+ this.id = config.id || '(machine)';
384
+ this.implementations = {
385
+ actors: implementations?.actors ?? {},
386
+ actions: implementations?.actions ?? {},
387
+ delays: implementations?.delays ?? {},
388
+ guards: implementations?.guards ?? {}
389
+ };
390
+ this.version = this.config.version;
391
+ this.transition = this.transition.bind(this);
392
+ this.getInitialSnapshot = this.getInitialSnapshot.bind(this);
393
+ this.restoreSnapshot = this.restoreSnapshot.bind(this);
394
+ this.start = this.start.bind(this);
395
+ this.root = new StateNode(config, {
396
+ _key: this.id,
397
+ _machine: this
398
+ });
399
+ this.root._initialize();
400
+ this.states = this.root.states; // TODO: remove!
401
+ this.events = this.root.events;
402
+ if (!this.root.output && Object.values(this.states).some(state => state.type === 'final' && !!state.output)) {
403
+ console.warn('Missing `machine.output` declaration (top-level final state with output detected)');
404
+ }
405
+ }
406
+
407
+ /**
408
+ * Clones this state machine with the provided implementations
409
+ * and merges the `context` (if provided).
410
+ *
411
+ * @param implementations Options (`actions`, `guards`, `actors`, `delays`, `context`)
412
+ * to recursively merge with the existing options.
413
+ *
414
+ * @returns A new `StateMachine` instance with the provided implementations.
415
+ */
416
+ provide(implementations) {
417
+ const {
418
+ actions,
419
+ guards,
420
+ actors,
421
+ delays
422
+ } = this.implementations;
423
+ return new StateMachine(this.config, {
424
+ actions: {
425
+ ...actions,
426
+ ...implementations.actions
427
+ },
428
+ guards: {
429
+ ...guards,
430
+ ...implementations.guards
431
+ },
432
+ actors: {
433
+ ...actors,
434
+ ...implementations.actors
435
+ },
436
+ delays: {
437
+ ...delays,
438
+ ...implementations.delays
439
+ }
440
+ });
441
+ }
442
+ resolveState(config) {
443
+ const resolvedStateValue = guards_dist_xstateGuards.resolveStateValue(this.root, config.value);
444
+ const nodeSet = guards_dist_xstateGuards.getAllStateNodes(guards_dist_xstateGuards.getStateNodes(this.root, resolvedStateValue));
445
+ return guards_dist_xstateGuards.createMachineSnapshot({
446
+ _nodes: [...nodeSet],
447
+ context: config.context || {},
448
+ children: {},
449
+ status: guards_dist_xstateGuards.isInFinalState(nodeSet, this.root) ? 'done' : config.status || 'active',
450
+ output: config.output,
451
+ error: config.error,
452
+ historyValue: config.historyValue
453
+ }, this);
454
+ }
455
+
456
+ /**
457
+ * Determines the next snapshot given the current `snapshot` and received `event`.
458
+ * Calculates a full macrostep from all microsteps.
459
+ *
460
+ * @param snapshot The current snapshot
461
+ * @param event The received event
462
+ */
463
+ transition(snapshot, event, actorScope) {
464
+ return guards_dist_xstateGuards.macrostep(snapshot, event, actorScope).snapshot;
465
+ }
466
+
467
+ /**
468
+ * Determines the next state given the current `state` and `event`.
469
+ * Calculates a microstep.
470
+ *
471
+ * @param state The current state
472
+ * @param event The received event
473
+ */
474
+ microstep(snapshot, event, actorScope) {
475
+ return guards_dist_xstateGuards.macrostep(snapshot, event, actorScope).microstates;
476
+ }
477
+ getTransitionData(snapshot, event) {
478
+ return guards_dist_xstateGuards.transitionNode(this.root, snapshot.value, snapshot, event) || [];
479
+ }
480
+
481
+ /**
482
+ * The initial state _before_ evaluating any microsteps.
483
+ * This "pre-initial" state is provided to initial actions executed in the initial state.
484
+ */
485
+ getPreInitialState(actorScope, initEvent, internalQueue) {
486
+ const {
487
+ context
488
+ } = this.config;
489
+ const preInitial = guards_dist_xstateGuards.createMachineSnapshot({
490
+ context: typeof context !== 'function' && context ? context : {},
491
+ _nodes: [this.root],
492
+ children: {},
493
+ status: 'active'
494
+ }, this);
495
+ if (typeof context === 'function') {
496
+ const assignment = ({
497
+ spawn,
498
+ event
499
+ }) => context({
500
+ spawn,
501
+ input: event.input
502
+ });
503
+ return guards_dist_xstateGuards.resolveActionsAndContext(preInitial, initEvent, actorScope, [log.assign(assignment)], internalQueue);
504
+ }
505
+ return preInitial;
506
+ }
507
+
508
+ /**
509
+ * Returns the initial `State` instance, with reference to `self` as an `ActorRef`.
510
+ */
511
+ getInitialSnapshot(actorScope, input) {
512
+ const initEvent = guards_dist_xstateGuards.createInitEvent(input); // TODO: fix;
513
+ const internalQueue = [];
514
+ const preInitialState = this.getPreInitialState(actorScope, initEvent, internalQueue);
515
+ const nextState = guards_dist_xstateGuards.microstep([{
516
+ target: [...guards_dist_xstateGuards.getInitialStateNodes(this.root)],
517
+ source: this.root,
518
+ reenter: true,
519
+ actions: [],
520
+ eventType: null,
521
+ toJSON: null // TODO: fix
522
+ }], preInitialState, actorScope, initEvent, true, internalQueue);
523
+ const {
524
+ snapshot: macroState
525
+ } = guards_dist_xstateGuards.macrostep(nextState, initEvent, actorScope, internalQueue);
526
+ return macroState;
527
+ }
528
+ start(snapshot) {
529
+ Object.values(snapshot.children).forEach(child => {
530
+ if (child.getSnapshot().status === 'active') {
531
+ child.start();
532
+ }
533
+ });
534
+ }
535
+ getStateNodeById(stateId) {
536
+ const fullPath = stateId.split(guards_dist_xstateGuards.STATE_DELIMITER);
537
+ const relativePath = fullPath.slice(1);
538
+ const resolvedStateId = guards_dist_xstateGuards.isStateId(fullPath[0]) ? fullPath[0].slice(STATE_IDENTIFIER.length) : fullPath[0];
539
+ const stateNode = this.idMap.get(resolvedStateId);
540
+ if (!stateNode) {
541
+ throw new Error(`Child state node '#${resolvedStateId}' does not exist on machine '${this.id}'`);
542
+ }
543
+ return guards_dist_xstateGuards.getStateNodeByPath(stateNode, relativePath);
544
+ }
545
+ get definition() {
546
+ return this.root.definition;
547
+ }
548
+ toJSON() {
549
+ return this.definition;
550
+ }
551
+ getPersistedSnapshot(snapshot, options) {
552
+ return guards_dist_xstateGuards.getPersistedSnapshot(snapshot, options);
553
+ }
554
+ restoreSnapshot(snapshot, _actorScope) {
555
+ const children = {};
556
+ const snapshotChildren = snapshot.children;
557
+ Object.keys(snapshotChildren).forEach(actorId => {
558
+ const actorData = snapshotChildren[actorId];
559
+ const childState = actorData.snapshot;
560
+ const src = actorData.src;
561
+ const logic = typeof src === 'string' ? guards_dist_xstateGuards.resolveReferencedActor(this, src) : src;
562
+ if (!logic) {
563
+ return;
564
+ }
565
+ const actorRef = guards_dist_xstateGuards.createActor(logic, {
566
+ id: actorId,
567
+ parent: _actorScope?.self,
568
+ syncSnapshot: actorData.syncSnapshot,
569
+ snapshot: childState,
570
+ src,
571
+ systemId: actorData.systemId
572
+ });
573
+ children[actorId] = actorRef;
574
+ });
575
+ const restoredSnapshot = guards_dist_xstateGuards.createMachineSnapshot({
576
+ ...snapshot,
577
+ children,
578
+ _nodes: Array.from(guards_dist_xstateGuards.getAllStateNodes(guards_dist_xstateGuards.getStateNodes(this.root, snapshot.value)))
579
+ }, this);
580
+ let seen = new Set();
581
+ function reviveContext(contextPart, children) {
582
+ if (seen.has(contextPart)) {
583
+ return;
584
+ }
585
+ seen.add(contextPart);
586
+ for (let key in contextPart) {
587
+ const value = contextPart[key];
588
+ if (value && typeof value === 'object') {
589
+ if ('xstate$$type' in value && value.xstate$$type === guards_dist_xstateGuards.$$ACTOR_TYPE) {
590
+ contextPart[key] = children[value.id];
591
+ continue;
592
+ }
593
+ reviveContext(value, children);
594
+ }
595
+ }
596
+ }
597
+ reviveContext(restoredSnapshot.context, children);
598
+ return restoredSnapshot;
599
+ }
600
+ }
601
+
602
+ const defaultWaitForOptions = {
603
+ timeout: Infinity // much more than 10 seconds
604
+ };
605
+
606
+ /**
607
+ * Subscribes to an actor ref and waits for its emitted value to satisfy
608
+ * a predicate, and then resolves with that value.
609
+ * Will throw if the desired state is not reached after a timeout
610
+ * (defaults to 10 seconds).
611
+ *
612
+ * @example
613
+ * ```js
614
+ * const state = await waitFor(someService, state => {
615
+ * return state.hasTag('loaded');
616
+ * });
617
+ *
618
+ * state.hasTag('loaded'); // true
619
+ * ```
620
+ *
621
+ * @param actorRef The actor ref to subscribe to
622
+ * @param predicate Determines if a value matches the condition to wait for
623
+ * @param options
624
+ * @returns A promise that eventually resolves to the emitted value
625
+ * that matches the condition
626
+ */
627
+ function waitFor(actorRef, predicate, options) {
628
+ const resolvedOptions = {
629
+ ...defaultWaitForOptions,
630
+ ...options
631
+ };
632
+ return new Promise((res, rej) => {
633
+ let done = false;
634
+ if (resolvedOptions.timeout < 0) {
635
+ console.error('`timeout` passed to `waitFor` is negative and it will reject its internal promise immediately.');
636
+ }
637
+ const handle = resolvedOptions.timeout === Infinity ? undefined : setTimeout(() => {
638
+ sub.unsubscribe();
639
+ rej(new Error(`Timeout of ${resolvedOptions.timeout} ms exceeded`));
640
+ }, resolvedOptions.timeout);
641
+ const dispose = () => {
642
+ clearTimeout(handle);
643
+ done = true;
644
+ sub?.unsubscribe();
645
+ };
646
+ function checkEmitted(emitted) {
647
+ if (predicate(emitted)) {
648
+ dispose();
649
+ res(emitted);
650
+ }
651
+ }
652
+ let sub; // avoid TDZ when disposing synchronously
653
+
654
+ // See if the current snapshot already matches the predicate
655
+ checkEmitted(actorRef.getSnapshot());
656
+ if (done) {
657
+ return;
658
+ }
659
+ sub = actorRef.subscribe({
660
+ next: checkEmitted,
661
+ error: err => {
662
+ dispose();
663
+ rej(err);
664
+ },
665
+ complete: () => {
666
+ dispose();
667
+ rej(new Error(`Actor terminated without satisfying predicate`));
668
+ }
669
+ });
670
+ if (done) {
671
+ sub.unsubscribe();
672
+ }
673
+ });
674
+ }
675
+
676
+ // this is not 100% accurate since we can't make parallel regions required in the result
677
+ // `TTestValue` doesn't encode this information anyhow for us to be able to do that
678
+ // this is fine for most practical use cases anyway though
679
+ function createMachine(config, implementations) {
680
+ return new StateMachine(config, implementations);
681
+ }
682
+
683
+ // at the moment we allow extra actors - ones that are not specified by `children`
684
+ // this could be reconsidered in the future
685
+ function setup({
686
+ actors,
687
+ actions,
688
+ guards,
689
+ delays
690
+ }) {
691
+ return {
692
+ createMachine: config => createMachine(config, {
693
+ actors,
694
+ actions,
695
+ guards,
696
+ delays
697
+ })
698
+ };
699
+ }
700
+
701
+ exports.createEmptyActor = actors_dist_xstateActors.createEmptyActor;
702
+ exports.fromCallback = actors_dist_xstateActors.fromCallback;
703
+ exports.fromEventObservable = actors_dist_xstateActors.fromEventObservable;
704
+ exports.fromObservable = actors_dist_xstateActors.fromObservable;
705
+ exports.fromPromise = actors_dist_xstateActors.fromPromise;
706
+ exports.fromTransition = actors_dist_xstateActors.fromTransition;
707
+ exports.Actor = guards_dist_xstateGuards.Actor;
708
+ exports.__unsafe_getAllOwnEventDescriptors = guards_dist_xstateGuards.getAllOwnEventDescriptors;
709
+ exports.and = guards_dist_xstateGuards.and;
710
+ exports.cancel = guards_dist_xstateGuards.cancel;
711
+ exports.createActor = guards_dist_xstateGuards.createActor;
712
+ exports.getStateNodes = guards_dist_xstateGuards.getStateNodes;
713
+ exports.interpret = guards_dist_xstateGuards.interpret;
714
+ exports.isMachineSnapshot = guards_dist_xstateGuards.isMachineSnapshot;
715
+ exports.matchesState = guards_dist_xstateGuards.matchesState;
716
+ exports.not = guards_dist_xstateGuards.not;
717
+ exports.or = guards_dist_xstateGuards.or;
718
+ exports.pathToStateValue = guards_dist_xstateGuards.pathToStateValue;
719
+ exports.raise = guards_dist_xstateGuards.raise;
720
+ exports.spawnChild = guards_dist_xstateGuards.spawnChild;
721
+ exports.stateIn = guards_dist_xstateGuards.stateIn;
722
+ exports.stop = guards_dist_xstateGuards.stop;
723
+ exports.stopChild = guards_dist_xstateGuards.stopChild;
724
+ exports.toObserver = guards_dist_xstateGuards.toObserver;
725
+ exports.SpecialTargets = log.SpecialTargets;
726
+ exports.assign = log.assign;
727
+ exports.enqueueActions = log.enqueueActions;
728
+ exports.forwardTo = log.forwardTo;
729
+ exports.log = log.log;
730
+ exports.sendParent = log.sendParent;
731
+ exports.sendTo = log.sendTo;
732
+ exports.SimulatedClock = SimulatedClock;
733
+ exports.StateMachine = StateMachine;
734
+ exports.StateNode = StateNode;
735
+ exports.createMachine = createMachine;
736
+ exports.setup = setup;
737
+ exports.waitFor = waitFor;