xstate 4.31.0 → 5.0.0-alpha.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 (206) hide show
  1. package/CHANGELOG.md +526 -0
  2. package/actions/ExecutableAction.ts +58 -0
  3. package/actions/dist/xstate-actions.cjs.d.ts +1 -0
  4. package/actions/dist/xstate-actions.cjs.dev.js +32 -0
  5. package/actions/dist/xstate-actions.cjs.js +7 -0
  6. package/actions/dist/xstate-actions.cjs.prod.js +32 -0
  7. package/actions/dist/xstate-actions.esm.js +2 -0
  8. package/actions/dynamicAction.ts +34 -0
  9. package/actions/package.json +4 -0
  10. package/actors/dist/xstate-actors.cjs.d.ts +1 -0
  11. package/actors/dist/xstate-actors.cjs.dev.js +21 -0
  12. package/actors/dist/xstate-actors.cjs.js +7 -0
  13. package/actors/dist/xstate-actors.cjs.prod.js +21 -0
  14. package/actors/dist/xstate-actors.esm.js +2 -0
  15. package/actors/package.json +4 -0
  16. package/dev/dist/xstate-dev.cjs.d.ts +1 -0
  17. package/dev/dist/xstate-dev.cjs.dev.js +11 -0
  18. package/dev/dist/xstate-dev.cjs.js +7 -0
  19. package/{lib/devTools.js → dev/dist/xstate-dev.cjs.prod.js} +17 -10
  20. package/dev/dist/xstate-dev.esm.js +1 -0
  21. package/dev/package.json +4 -0
  22. package/dist/Machine-9ce74c11.cjs.dev.js +755 -0
  23. package/dist/Machine-dca041dc.cjs.prod.js +749 -0
  24. package/dist/Machine-fb2f47f5.esm.js +751 -0
  25. package/dist/actions-6b86876d.cjs.dev.js +4815 -0
  26. package/dist/actions-70094c93.cjs.prod.js +4765 -0
  27. package/dist/actions-ff512f16.esm.js +4757 -0
  28. package/dist/declarations/actions/ExecutableAction.d.ts +23 -0
  29. package/dist/declarations/actions/dynamicAction.d.ts +3 -0
  30. package/dist/declarations/src/Machine.d.ts +4 -0
  31. package/dist/declarations/src/Mailbox.d.ts +12 -0
  32. package/dist/declarations/src/ObservableActorRef.d.ts +25 -0
  33. package/{lib → dist/declarations/src}/SimulatedClock.d.ts +0 -1
  34. package/dist/declarations/src/State.d.ts +104 -0
  35. package/dist/declarations/src/StateMachine.d.ts +112 -0
  36. package/dist/declarations/src/StateNode.d.ts +127 -0
  37. package/{es → dist/declarations/src}/actionTypes.d.ts +0 -3
  38. package/dist/declarations/src/actions/assign.d.ts +7 -0
  39. package/dist/declarations/src/actions/cancel.d.ts +10 -0
  40. package/dist/declarations/src/actions/choose.d.ts +3 -0
  41. package/dist/declarations/src/actions/invoke.d.ts +3 -0
  42. package/dist/declarations/src/actions/log.d.ts +11 -0
  43. package/dist/declarations/src/actions/pure.d.ts +3 -0
  44. package/dist/declarations/src/actions/raise.d.ts +9 -0
  45. package/dist/declarations/src/actions/send.d.ts +55 -0
  46. package/dist/declarations/src/actions/stop.d.ts +8 -0
  47. package/dist/declarations/src/actions.d.ts +44 -0
  48. package/dist/declarations/src/actors.d.ts +38 -0
  49. package/dist/declarations/src/constants.d.ts +5 -0
  50. package/{lib/devTools.d.ts → dist/declarations/src/dev/index.d.ts} +2 -2
  51. package/{es → dist/declarations/src}/environment.d.ts +0 -1
  52. package/dist/declarations/src/guards.d.ts +9 -0
  53. package/dist/declarations/src/index.d.ts +47 -0
  54. package/dist/declarations/src/interpreter.d.ts +147 -0
  55. package/{es → dist/declarations/src}/mapState.d.ts +0 -1
  56. package/dist/declarations/src/match.d.ts +5 -0
  57. package/dist/declarations/src/memo.d.ts +1 -0
  58. package/dist/declarations/src/model.d.ts +5 -0
  59. package/{lib → dist/declarations/src}/model.types.d.ts +10 -9
  60. package/dist/declarations/src/registry.d.ts +8 -0
  61. package/{es → dist/declarations/src}/schema.d.ts +0 -1
  62. package/dist/declarations/src/spawn.d.ts +2 -0
  63. package/dist/declarations/src/stateUtils.d.ts +85 -0
  64. package/{lib → dist/declarations/src}/typegenTypes.d.ts +28 -26
  65. package/dist/declarations/src/types.d.ts +1026 -0
  66. package/dist/declarations/src/utils.d.ts +56 -0
  67. package/{es/devTools.js → dist/index-20b364c4.esm.js} +18 -6
  68. package/dist/index-2a564d03.cjs.dev.js +64 -0
  69. package/dist/xstate.cjs.d.ts +1 -0
  70. package/dist/xstate.cjs.dev.js +217 -0
  71. package/dist/xstate.cjs.js +7 -0
  72. package/dist/xstate.cjs.prod.js +217 -0
  73. package/dist/xstate.esm.js +172 -0
  74. package/guards/dist/xstate-guards.cjs.d.ts +1 -0
  75. package/guards/dist/xstate-guards.cjs.dev.js +15 -0
  76. package/guards/dist/xstate-guards.cjs.js +7 -0
  77. package/guards/dist/xstate-guards.cjs.prod.js +15 -0
  78. package/guards/dist/xstate-guards.esm.js +2 -0
  79. package/guards/package.json +4 -0
  80. package/invoke/package.json +4 -0
  81. package/model/dist/xstate-model.cjs.d.ts +1 -0
  82. package/model/dist/xstate-model.cjs.dev.js +41 -0
  83. package/model/dist/xstate-model.cjs.js +7 -0
  84. package/model/dist/xstate-model.cjs.prod.js +41 -0
  85. package/model/dist/xstate-model.esm.js +37 -0
  86. package/model/package.json +4 -0
  87. package/package.json +21 -30
  88. package/dist/xstate.interpreter.js +0 -15
  89. package/dist/xstate.js +0 -15
  90. package/dist/xstate.web.js +0 -15
  91. package/es/Actor.d.ts +0 -25
  92. package/es/Actor.js +0 -99
  93. package/es/Machine.d.ts +0 -12
  94. package/es/Machine.js +0 -14
  95. package/es/SimulatedClock.d.ts +0 -17
  96. package/es/SimulatedClock.js +0 -81
  97. package/es/State.d.ts +0 -123
  98. package/es/State.js +0 -274
  99. package/es/StateNode.d.ts +0 -287
  100. package/es/StateNode.js +0 -1566
  101. package/es/_virtual/_tslib.js +0 -78
  102. package/es/actionTypes.js +0 -22
  103. package/es/actions.d.ts +0 -154
  104. package/es/actions.js +0 -520
  105. package/es/behaviors.d.ts +0 -37
  106. package/es/behaviors.js +0 -131
  107. package/es/constants.d.ts +0 -6
  108. package/es/constants.js +0 -6
  109. package/es/devTools.d.ts +0 -14
  110. package/es/each.d.ts +0 -4
  111. package/es/each.js +0 -13
  112. package/es/environment.js +0 -3
  113. package/es/index.d.ts +0 -22
  114. package/es/index.js +0 -23
  115. package/es/interpreter.d.ts +0 -209
  116. package/es/interpreter.js +0 -1402
  117. package/es/invoke.d.ts +0 -11
  118. package/es/invokeUtils.d.ts +0 -7
  119. package/es/invokeUtils.js +0 -40
  120. package/es/json.d.ts +0 -31
  121. package/es/json.js +0 -86
  122. package/es/mapState.js +0 -32
  123. package/es/match.d.ts +0 -9
  124. package/es/match.js +0 -34
  125. package/es/model.d.ts +0 -5
  126. package/es/model.js +0 -50
  127. package/es/model.types.d.ts +0 -52
  128. package/es/patterns.d.ts +0 -14
  129. package/es/patterns.js +0 -48
  130. package/es/registry.d.ts +0 -9
  131. package/es/registry.js +0 -19
  132. package/es/scheduler.d.ts +0 -17
  133. package/es/scheduler.js +0 -79
  134. package/es/schema.js +0 -6
  135. package/es/scxml.d.ts +0 -6
  136. package/es/serviceScope.d.ts +0 -4
  137. package/es/serviceScope.js +0 -16
  138. package/es/stateUtils.d.ts +0 -17
  139. package/es/stateUtils.js +0 -259
  140. package/es/typegenTypes.d.ts +0 -130
  141. package/es/types.d.ts +0 -1037
  142. package/es/types.js +0 -33
  143. package/es/utils.d.ts +0 -72
  144. package/es/utils.js +0 -626
  145. package/es/waitFor.d.ts +0 -32
  146. package/es/waitFor.js +0 -66
  147. package/lib/Actor.d.ts +0 -25
  148. package/lib/Actor.js +0 -108
  149. package/lib/Machine.d.ts +0 -12
  150. package/lib/Machine.js +0 -19
  151. package/lib/SimulatedClock.js +0 -85
  152. package/lib/State.d.ts +0 -123
  153. package/lib/State.js +0 -282
  154. package/lib/StateNode.d.ts +0 -287
  155. package/lib/StateNode.js +0 -1570
  156. package/lib/_virtual/_tslib.js +0 -85
  157. package/lib/actionTypes.d.ts +0 -20
  158. package/lib/actionTypes.js +0 -43
  159. package/lib/actions.d.ts +0 -154
  160. package/lib/actions.js +0 -552
  161. package/lib/behaviors.d.ts +0 -37
  162. package/lib/behaviors.js +0 -137
  163. package/lib/constants.d.ts +0 -6
  164. package/lib/constants.js +0 -13
  165. package/lib/each.d.ts +0 -4
  166. package/lib/each.js +0 -17
  167. package/lib/environment.d.ts +0 -2
  168. package/lib/environment.js +0 -7
  169. package/lib/index.d.ts +0 -22
  170. package/lib/index.js +0 -60
  171. package/lib/interpreter.d.ts +0 -209
  172. package/lib/interpreter.js +0 -1408
  173. package/lib/invoke.d.ts +0 -11
  174. package/lib/invoke.js +0 -20
  175. package/lib/invokeUtils.d.ts +0 -7
  176. package/lib/invokeUtils.js +0 -45
  177. package/lib/json.d.ts +0 -31
  178. package/lib/json.js +0 -94
  179. package/lib/mapState.d.ts +0 -4
  180. package/lib/mapState.js +0 -36
  181. package/lib/match.d.ts +0 -9
  182. package/lib/match.js +0 -38
  183. package/lib/model.d.ts +0 -5
  184. package/lib/model.js +0 -54
  185. package/lib/model.types.js +0 -2
  186. package/lib/patterns.d.ts +0 -14
  187. package/lib/patterns.js +0 -53
  188. package/lib/registry.d.ts +0 -9
  189. package/lib/registry.js +0 -23
  190. package/lib/scheduler.d.ts +0 -17
  191. package/lib/scheduler.js +0 -83
  192. package/lib/schema.d.ts +0 -3
  193. package/lib/schema.js +0 -11
  194. package/lib/scxml.d.ts +0 -6
  195. package/lib/scxml.js +0 -350
  196. package/lib/serviceScope.d.ts +0 -4
  197. package/lib/serviceScope.js +0 -21
  198. package/lib/stateUtils.d.ts +0 -17
  199. package/lib/stateUtils.js +0 -273
  200. package/lib/typegenTypes.js +0 -2
  201. package/lib/types.d.ts +0 -1037
  202. package/lib/types.js +0 -35
  203. package/lib/utils.d.ts +0 -72
  204. package/lib/utils.js +0 -673
  205. package/lib/waitFor.d.ts +0 -32
  206. package/lib/waitFor.js +0 -70
package/es/interpreter.js DELETED
@@ -1,1402 +0,0 @@
1
- import { __values, __spreadArray, __read, __assign } from './_virtual/_tslib.js';
2
- import { ActionTypes, SpecialTargets } from './types.js';
3
- import { isStateConfig, State, bindActionToState } from './State.js';
4
- import { errorPlatform, log, stop, start, cancel, send, update, error as error$1 } from './actionTypes.js';
5
- import { doneInvoke, initEvent, getActionFunction, error } from './actions.js';
6
- import { IS_PRODUCTION } from './environment.js';
7
- import { warn, mapContext, isFunction, toSCXMLEvent, toInvokeSource, isMachine, isPromiseLike, isObservable, isBehavior, reportUnhandledExceptionOnInvocation, symbolObservable, isArray, toEventObject, isString, isActor, uniqueId, toObserver } from './utils.js';
8
- import { Scheduler } from './scheduler.js';
9
- import { isSpawnedActor, createDeferredActor } from './Actor.js';
10
- import { isInFinalState } from './stateUtils.js';
11
- import { registry } from './registry.js';
12
- import { getGlobal, registerService } from './devTools.js';
13
- import { provide, consume } from './serviceScope.js';
14
- import { spawnBehavior } from './behaviors.js';
15
-
16
- var DEFAULT_SPAWN_OPTIONS = {
17
- sync: false,
18
- autoForward: false
19
- };
20
- var InterpreterStatus;
21
-
22
- (function (InterpreterStatus) {
23
- InterpreterStatus[InterpreterStatus["NotStarted"] = 0] = "NotStarted";
24
- InterpreterStatus[InterpreterStatus["Running"] = 1] = "Running";
25
- InterpreterStatus[InterpreterStatus["Stopped"] = 2] = "Stopped";
26
- })(InterpreterStatus || (InterpreterStatus = {}));
27
-
28
- var Interpreter =
29
- /*#__PURE__*/
30
-
31
- /** @class */
32
- function () {
33
- /**
34
- * Creates a new Interpreter instance (i.e., service) for the given machine with the provided options, if any.
35
- *
36
- * @param machine The machine to be interpreted
37
- * @param options Interpreter options
38
- */
39
- function Interpreter(machine, options) {
40
- var _this = this;
41
-
42
- if (options === void 0) {
43
- options = Interpreter.defaultOptions;
44
- }
45
-
46
- this.machine = machine;
47
- this.delayedEventsMap = {};
48
- this.listeners = new Set();
49
- this.contextListeners = new Set();
50
- this.stopListeners = new Set();
51
- this.doneListeners = new Set();
52
- this.eventListeners = new Set();
53
- this.sendListeners = new Set();
54
- /**
55
- * Whether the service is started.
56
- */
57
-
58
- this.initialized = false;
59
- this.status = InterpreterStatus.NotStarted;
60
- this.children = new Map();
61
- this.forwardTo = new Set();
62
- /**
63
- * Alias for Interpreter.prototype.start
64
- */
65
-
66
- this.init = this.start;
67
- /**
68
- * Sends an event to the running interpreter to trigger a transition.
69
- *
70
- * An array of events (batched) can be sent as well, which will send all
71
- * batched events to the running interpreter. The listeners will be
72
- * notified only **once** when all events are processed.
73
- *
74
- * @param event The event(s) to send
75
- */
76
-
77
- this.send = function (event, payload) {
78
- if (isArray(event)) {
79
- _this.batch(event);
80
-
81
- return _this.state;
82
- }
83
-
84
- var _event = toSCXMLEvent(toEventObject(event, payload));
85
-
86
- if (_this.status === InterpreterStatus.Stopped) {
87
- // do nothing
88
- if (!IS_PRODUCTION) {
89
- warn(false, "Event \"".concat(_event.name, "\" was sent to stopped service \"").concat(_this.machine.id, "\". This service has already reached its final state, and will not transition.\nEvent: ").concat(JSON.stringify(_event.data)));
90
- }
91
-
92
- return _this.state;
93
- }
94
-
95
- if (_this.status !== InterpreterStatus.Running && !_this.options.deferEvents) {
96
- throw new Error("Event \"".concat(_event.name, "\" was sent to uninitialized service \"").concat(_this.machine.id // tslint:disable-next-line:max-line-length
97
- , "\". Make sure .start() is called for this service, or set { deferEvents: true } in the service options.\nEvent: ").concat(JSON.stringify(_event.data)));
98
- }
99
-
100
- _this.scheduler.schedule(function () {
101
- // Forward copy of event to child actors
102
- _this.forward(_event);
103
-
104
- var nextState = _this.nextState(_event);
105
-
106
- _this.update(nextState, _event);
107
- });
108
-
109
- return _this._state; // TODO: deprecate (should return void)
110
- // tslint:disable-next-line:semicolon
111
- };
112
-
113
- this.sendTo = function (event, to) {
114
- var isParent = _this.parent && (to === SpecialTargets.Parent || _this.parent.id === to);
115
- var target = isParent ? _this.parent : isString(to) ? _this.children.get(to) || registry.get(to) : isActor(to) ? to : undefined;
116
-
117
- if (!target) {
118
- if (!isParent) {
119
- throw new Error("Unable to send event to child '".concat(to, "' from service '").concat(_this.id, "'."));
120
- } // tslint:disable-next-line:no-console
121
-
122
-
123
- if (!IS_PRODUCTION) {
124
- warn(false, "Service '".concat(_this.id, "' has no parent: unable to send event ").concat(event.type));
125
- }
126
-
127
- return;
128
- }
129
-
130
- if ('machine' in target) {
131
- // Send SCXML events to machines
132
- target.send(__assign(__assign({}, event), {
133
- name: event.name === error$1 ? "".concat(error(_this.id)) : event.name,
134
- origin: _this.sessionId
135
- }));
136
- } else {
137
- // Send normal events to other targets
138
- target.send(event.data);
139
- }
140
- };
141
-
142
- var resolvedOptions = __assign(__assign({}, Interpreter.defaultOptions), options);
143
-
144
- var clock = resolvedOptions.clock,
145
- logger = resolvedOptions.logger,
146
- parent = resolvedOptions.parent,
147
- id = resolvedOptions.id;
148
- var resolvedId = id !== undefined ? id : machine.id;
149
- this.id = resolvedId;
150
- this.logger = logger;
151
- this.clock = clock;
152
- this.parent = parent;
153
- this.options = resolvedOptions;
154
- this.scheduler = new Scheduler({
155
- deferEvents: this.options.deferEvents
156
- });
157
- this.sessionId = registry.bookId();
158
- }
159
-
160
- Object.defineProperty(Interpreter.prototype, "initialState", {
161
- get: function () {
162
- var _this = this;
163
-
164
- if (this._initialState) {
165
- return this._initialState;
166
- }
167
-
168
- return provide(this, function () {
169
- _this._initialState = _this.machine.initialState;
170
- return _this._initialState;
171
- });
172
- },
173
- enumerable: false,
174
- configurable: true
175
- });
176
- Object.defineProperty(Interpreter.prototype, "state", {
177
- get: function () {
178
- if (!IS_PRODUCTION) {
179
- warn(this.status !== InterpreterStatus.NotStarted, "Attempted to read state from uninitialized service '".concat(this.id, "'. Make sure the service is started first."));
180
- }
181
-
182
- return this._state;
183
- },
184
- enumerable: false,
185
- configurable: true
186
- });
187
- /**
188
- * Executes the actions of the given state, with that state's `context` and `event`.
189
- *
190
- * @param state The state whose actions will be executed
191
- * @param actionsConfig The action implementations to use
192
- */
193
-
194
- Interpreter.prototype.execute = function (state, actionsConfig) {
195
- var e_1, _a;
196
-
197
- try {
198
- for (var _b = __values(state.actions), _c = _b.next(); !_c.done; _c = _b.next()) {
199
- var action = _c.value;
200
- this.exec(action, state, actionsConfig);
201
- }
202
- } catch (e_1_1) {
203
- e_1 = {
204
- error: e_1_1
205
- };
206
- } finally {
207
- try {
208
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
209
- } finally {
210
- if (e_1) throw e_1.error;
211
- }
212
- }
213
- };
214
-
215
- Interpreter.prototype.update = function (state, _event) {
216
- var e_2, _a, e_3, _b, e_4, _c, e_5, _d;
217
-
218
- var _this = this; // Attach session ID to state
219
-
220
-
221
- state._sessionid = this.sessionId; // Update state
222
-
223
- this._state = state; // Execute actions
224
-
225
- if (this.options.execute) {
226
- this.execute(this.state);
227
- } // Update children
228
-
229
-
230
- this.children.forEach(function (child) {
231
- _this.state.children[child.id] = child;
232
- }); // Dev tools
233
-
234
- if (this.devTools) {
235
- this.devTools.send(_event.data, state);
236
- } // Execute listeners
237
-
238
-
239
- if (state.event) {
240
- try {
241
- for (var _e = __values(this.eventListeners), _f = _e.next(); !_f.done; _f = _e.next()) {
242
- var listener = _f.value;
243
- listener(state.event);
244
- }
245
- } catch (e_2_1) {
246
- e_2 = {
247
- error: e_2_1
248
- };
249
- } finally {
250
- try {
251
- if (_f && !_f.done && (_a = _e.return)) _a.call(_e);
252
- } finally {
253
- if (e_2) throw e_2.error;
254
- }
255
- }
256
- }
257
-
258
- try {
259
- for (var _g = __values(this.listeners), _h = _g.next(); !_h.done; _h = _g.next()) {
260
- var listener = _h.value;
261
- listener(state, state.event);
262
- }
263
- } catch (e_3_1) {
264
- e_3 = {
265
- error: e_3_1
266
- };
267
- } finally {
268
- try {
269
- if (_h && !_h.done && (_b = _g.return)) _b.call(_g);
270
- } finally {
271
- if (e_3) throw e_3.error;
272
- }
273
- }
274
-
275
- try {
276
- for (var _j = __values(this.contextListeners), _k = _j.next(); !_k.done; _k = _j.next()) {
277
- var contextListener = _k.value;
278
- contextListener(this.state.context, this.state.history ? this.state.history.context : undefined);
279
- }
280
- } catch (e_4_1) {
281
- e_4 = {
282
- error: e_4_1
283
- };
284
- } finally {
285
- try {
286
- if (_k && !_k.done && (_c = _j.return)) _c.call(_j);
287
- } finally {
288
- if (e_4) throw e_4.error;
289
- }
290
- }
291
-
292
- var isDone = isInFinalState(state.configuration || [], this.machine);
293
-
294
- if (this.state.configuration && isDone) {
295
- // get final child state node
296
- var finalChildStateNode = state.configuration.find(function (sn) {
297
- return sn.type === 'final' && sn.parent === _this.machine;
298
- });
299
- var doneData = finalChildStateNode && finalChildStateNode.doneData ? mapContext(finalChildStateNode.doneData, state.context, _event) : undefined;
300
-
301
- try {
302
- for (var _l = __values(this.doneListeners), _m = _l.next(); !_m.done; _m = _l.next()) {
303
- var listener = _m.value;
304
- listener(doneInvoke(this.id, doneData));
305
- }
306
- } catch (e_5_1) {
307
- e_5 = {
308
- error: e_5_1
309
- };
310
- } finally {
311
- try {
312
- if (_m && !_m.done && (_d = _l.return)) _d.call(_l);
313
- } finally {
314
- if (e_5) throw e_5.error;
315
- }
316
- }
317
-
318
- this.stop();
319
- }
320
- };
321
- /*
322
- * Adds a listener that is notified whenever a state transition happens. The listener is called with
323
- * the next state and the event object that caused the state transition.
324
- *
325
- * @param listener The state listener
326
- */
327
-
328
-
329
- Interpreter.prototype.onTransition = function (listener) {
330
- this.listeners.add(listener); // Send current state to listener
331
-
332
- if (this.status === InterpreterStatus.Running) {
333
- listener(this.state, this.state.event);
334
- }
335
-
336
- return this;
337
- };
338
-
339
- Interpreter.prototype.subscribe = function (nextListenerOrObserver, _, // TODO: error listener
340
- completeListener) {
341
- var _this = this;
342
-
343
- if (!nextListenerOrObserver) {
344
- return {
345
- unsubscribe: function () {
346
- return void 0;
347
- }
348
- };
349
- }
350
-
351
- var listener;
352
- var resolvedCompleteListener = completeListener;
353
-
354
- if (typeof nextListenerOrObserver === 'function') {
355
- listener = nextListenerOrObserver;
356
- } else {
357
- listener = nextListenerOrObserver.next.bind(nextListenerOrObserver);
358
- resolvedCompleteListener = nextListenerOrObserver.complete.bind(nextListenerOrObserver);
359
- }
360
-
361
- this.listeners.add(listener); // Send current state to listener
362
-
363
- if (this.status !== InterpreterStatus.NotStarted) {
364
- listener(this.state);
365
- }
366
-
367
- if (resolvedCompleteListener) {
368
- if (this.status === InterpreterStatus.Stopped) {
369
- resolvedCompleteListener();
370
- } else {
371
- this.onDone(resolvedCompleteListener);
372
- }
373
- }
374
-
375
- return {
376
- unsubscribe: function () {
377
- listener && _this.listeners.delete(listener);
378
- resolvedCompleteListener && _this.doneListeners.delete(resolvedCompleteListener);
379
- }
380
- };
381
- };
382
- /**
383
- * Adds an event listener that is notified whenever an event is sent to the running interpreter.
384
- * @param listener The event listener
385
- */
386
-
387
-
388
- Interpreter.prototype.onEvent = function (listener) {
389
- this.eventListeners.add(listener);
390
- return this;
391
- };
392
- /**
393
- * Adds an event listener that is notified whenever a `send` event occurs.
394
- * @param listener The event listener
395
- */
396
-
397
-
398
- Interpreter.prototype.onSend = function (listener) {
399
- this.sendListeners.add(listener);
400
- return this;
401
- };
402
- /**
403
- * Adds a context listener that is notified whenever the state context changes.
404
- * @param listener The context listener
405
- */
406
-
407
-
408
- Interpreter.prototype.onChange = function (listener) {
409
- this.contextListeners.add(listener);
410
- return this;
411
- };
412
- /**
413
- * Adds a listener that is notified when the machine is stopped.
414
- * @param listener The listener
415
- */
416
-
417
-
418
- Interpreter.prototype.onStop = function (listener) {
419
- this.stopListeners.add(listener);
420
- return this;
421
- };
422
- /**
423
- * Adds a state listener that is notified when the statechart has reached its final state.
424
- * @param listener The state listener
425
- */
426
-
427
-
428
- Interpreter.prototype.onDone = function (listener) {
429
- this.doneListeners.add(listener);
430
- return this;
431
- };
432
- /**
433
- * Removes a listener.
434
- * @param listener The listener to remove
435
- */
436
-
437
-
438
- Interpreter.prototype.off = function (listener) {
439
- this.listeners.delete(listener);
440
- this.eventListeners.delete(listener);
441
- this.sendListeners.delete(listener);
442
- this.stopListeners.delete(listener);
443
- this.doneListeners.delete(listener);
444
- this.contextListeners.delete(listener);
445
- return this;
446
- };
447
- /**
448
- * Starts the interpreter from the given state, or the initial state.
449
- * @param initialState The state to start the statechart from
450
- */
451
-
452
-
453
- Interpreter.prototype.start = function (initialState) {
454
- var _this = this;
455
-
456
- if (this.status === InterpreterStatus.Running) {
457
- // Do not restart the service if it is already started
458
- return this;
459
- } // yes, it's a hack but we need the related cache to be populated for some things to work (like delayed transitions)
460
- // this is usually called by `machine.getInitialState` but if we rehydrate from a state we might bypass this call
461
- // we also don't want to call this method here as it resolves the full initial state which might involve calling assign actions
462
- // and that could potentially lead to some unwanted side-effects (even such as creating some rogue actors)
463
-
464
-
465
- this.machine._init();
466
-
467
- registry.register(this.sessionId, this);
468
- this.initialized = true;
469
- this.status = InterpreterStatus.Running;
470
- var resolvedState = initialState === undefined ? this.initialState : provide(this, function () {
471
- return isStateConfig(initialState) ? _this.machine.resolveState(initialState) : _this.machine.resolveState(State.from(initialState, _this.machine.context));
472
- });
473
-
474
- if (this.options.devTools) {
475
- this.attachDev();
476
- }
477
-
478
- this.scheduler.initialize(function () {
479
- _this.update(resolvedState, initEvent);
480
- });
481
- return this;
482
- };
483
- /**
484
- * Stops the interpreter and unsubscribe all listeners.
485
- *
486
- * This will also notify the `onStop` listeners.
487
- */
488
-
489
-
490
- Interpreter.prototype.stop = function () {
491
- var e_6, _a, e_7, _b, e_8, _c, e_9, _d, e_10, _e;
492
-
493
- var _this = this;
494
-
495
- try {
496
- for (var _f = __values(this.listeners), _g = _f.next(); !_g.done; _g = _f.next()) {
497
- var listener = _g.value;
498
- this.listeners.delete(listener);
499
- }
500
- } catch (e_6_1) {
501
- e_6 = {
502
- error: e_6_1
503
- };
504
- } finally {
505
- try {
506
- if (_g && !_g.done && (_a = _f.return)) _a.call(_f);
507
- } finally {
508
- if (e_6) throw e_6.error;
509
- }
510
- }
511
-
512
- try {
513
- for (var _h = __values(this.stopListeners), _j = _h.next(); !_j.done; _j = _h.next()) {
514
- var listener = _j.value; // call listener, then remove
515
-
516
- listener();
517
- this.stopListeners.delete(listener);
518
- }
519
- } catch (e_7_1) {
520
- e_7 = {
521
- error: e_7_1
522
- };
523
- } finally {
524
- try {
525
- if (_j && !_j.done && (_b = _h.return)) _b.call(_h);
526
- } finally {
527
- if (e_7) throw e_7.error;
528
- }
529
- }
530
-
531
- try {
532
- for (var _k = __values(this.contextListeners), _l = _k.next(); !_l.done; _l = _k.next()) {
533
- var listener = _l.value;
534
- this.contextListeners.delete(listener);
535
- }
536
- } catch (e_8_1) {
537
- e_8 = {
538
- error: e_8_1
539
- };
540
- } finally {
541
- try {
542
- if (_l && !_l.done && (_c = _k.return)) _c.call(_k);
543
- } finally {
544
- if (e_8) throw e_8.error;
545
- }
546
- }
547
-
548
- try {
549
- for (var _m = __values(this.doneListeners), _o = _m.next(); !_o.done; _o = _m.next()) {
550
- var listener = _o.value;
551
- this.doneListeners.delete(listener);
552
- }
553
- } catch (e_9_1) {
554
- e_9 = {
555
- error: e_9_1
556
- };
557
- } finally {
558
- try {
559
- if (_o && !_o.done && (_d = _m.return)) _d.call(_m);
560
- } finally {
561
- if (e_9) throw e_9.error;
562
- }
563
- }
564
-
565
- if (!this.initialized) {
566
- // Interpreter already stopped; do nothing
567
- return this;
568
- }
569
-
570
- __spreadArray([], __read(this.state.configuration), false).sort(function (a, b) {
571
- return b.order - a.order;
572
- }).forEach(function (stateNode) {
573
- var e_11, _a;
574
-
575
- try {
576
- for (var _b = __values(stateNode.definition.exit), _c = _b.next(); !_c.done; _c = _b.next()) {
577
- var action = _c.value;
578
-
579
- _this.exec(action, _this.state);
580
- }
581
- } catch (e_11_1) {
582
- e_11 = {
583
- error: e_11_1
584
- };
585
- } finally {
586
- try {
587
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
588
- } finally {
589
- if (e_11) throw e_11.error;
590
- }
591
- }
592
- }); // Stop all children
593
-
594
-
595
- this.children.forEach(function (child) {
596
- if (isFunction(child.stop)) {
597
- child.stop();
598
- }
599
- });
600
- this.children.clear();
601
-
602
- try {
603
- // Cancel all delayed events
604
- for (var _p = __values(Object.keys(this.delayedEventsMap)), _q = _p.next(); !_q.done; _q = _p.next()) {
605
- var key = _q.value;
606
- this.clock.clearTimeout(this.delayedEventsMap[key]);
607
- }
608
- } catch (e_10_1) {
609
- e_10 = {
610
- error: e_10_1
611
- };
612
- } finally {
613
- try {
614
- if (_q && !_q.done && (_e = _p.return)) _e.call(_p);
615
- } finally {
616
- if (e_10) throw e_10.error;
617
- }
618
- }
619
-
620
- this.scheduler.clear();
621
- this.scheduler = new Scheduler({
622
- deferEvents: this.options.deferEvents
623
- });
624
- this.initialized = false;
625
- this.status = InterpreterStatus.Stopped;
626
- this._initialState = undefined;
627
- registry.free(this.sessionId);
628
- return this;
629
- };
630
-
631
- Interpreter.prototype.batch = function (events) {
632
- var _this = this;
633
-
634
- if (this.status === InterpreterStatus.NotStarted && this.options.deferEvents) {
635
- // tslint:disable-next-line:no-console
636
- if (!IS_PRODUCTION) {
637
- warn(false, "".concat(events.length, " event(s) were sent to uninitialized service \"").concat(this.machine.id, "\" and are deferred. Make sure .start() is called for this service.\nEvent: ").concat(JSON.stringify(event)));
638
- }
639
- } else if (this.status !== InterpreterStatus.Running) {
640
- throw new Error( // tslint:disable-next-line:max-line-length
641
- "".concat(events.length, " event(s) were sent to uninitialized service \"").concat(this.machine.id, "\". Make sure .start() is called for this service, or set { deferEvents: true } in the service options."));
642
- }
643
-
644
- this.scheduler.schedule(function () {
645
- var e_12, _a;
646
-
647
- var nextState = _this.state;
648
- var batchChanged = false;
649
- var batchedActions = [];
650
-
651
- var _loop_1 = function (event_1) {
652
- var _event = toSCXMLEvent(event_1);
653
-
654
- _this.forward(_event);
655
-
656
- nextState = provide(_this, function () {
657
- return _this.machine.transition(nextState, _event);
658
- });
659
- batchedActions.push.apply(batchedActions, __spreadArray([], __read(nextState.actions.map(function (a) {
660
- return bindActionToState(a, nextState);
661
- })), false));
662
- batchChanged = batchChanged || !!nextState.changed;
663
- };
664
-
665
- try {
666
- for (var events_1 = __values(events), events_1_1 = events_1.next(); !events_1_1.done; events_1_1 = events_1.next()) {
667
- var event_1 = events_1_1.value;
668
-
669
- _loop_1(event_1);
670
- }
671
- } catch (e_12_1) {
672
- e_12 = {
673
- error: e_12_1
674
- };
675
- } finally {
676
- try {
677
- if (events_1_1 && !events_1_1.done && (_a = events_1.return)) _a.call(events_1);
678
- } finally {
679
- if (e_12) throw e_12.error;
680
- }
681
- }
682
-
683
- nextState.changed = batchChanged;
684
- nextState.actions = batchedActions;
685
-
686
- _this.update(nextState, toSCXMLEvent(events[events.length - 1]));
687
- });
688
- };
689
- /**
690
- * Returns a send function bound to this interpreter instance.
691
- *
692
- * @param event The event to be sent by the sender.
693
- */
694
-
695
-
696
- Interpreter.prototype.sender = function (event) {
697
- return this.send.bind(this, event);
698
- };
699
- /**
700
- * Returns the next state given the interpreter's current state and the event.
701
- *
702
- * This is a pure method that does _not_ update the interpreter's state.
703
- *
704
- * @param event The event to determine the next state
705
- */
706
-
707
-
708
- Interpreter.prototype.nextState = function (event) {
709
- var _this = this;
710
-
711
- var _event = toSCXMLEvent(event);
712
-
713
- if (_event.name.indexOf(errorPlatform) === 0 && !this.state.nextEvents.some(function (nextEvent) {
714
- return nextEvent.indexOf(errorPlatform) === 0;
715
- })) {
716
- throw _event.data.data;
717
- }
718
-
719
- var nextState = provide(this, function () {
720
- return _this.machine.transition(_this.state, _event);
721
- });
722
- return nextState;
723
- };
724
-
725
- Interpreter.prototype.forward = function (event) {
726
- var e_13, _a;
727
-
728
- try {
729
- for (var _b = __values(this.forwardTo), _c = _b.next(); !_c.done; _c = _b.next()) {
730
- var id = _c.value;
731
- var child = this.children.get(id);
732
-
733
- if (!child) {
734
- throw new Error("Unable to forward event '".concat(event, "' from interpreter '").concat(this.id, "' to nonexistant child '").concat(id, "'."));
735
- }
736
-
737
- child.send(event);
738
- }
739
- } catch (e_13_1) {
740
- e_13 = {
741
- error: e_13_1
742
- };
743
- } finally {
744
- try {
745
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
746
- } finally {
747
- if (e_13) throw e_13.error;
748
- }
749
- }
750
- };
751
-
752
- Interpreter.prototype.defer = function (sendAction) {
753
- var _this = this;
754
-
755
- this.delayedEventsMap[sendAction.id] = this.clock.setTimeout(function () {
756
- if (sendAction.to) {
757
- _this.sendTo(sendAction._event, sendAction.to);
758
- } else {
759
- _this.send(sendAction._event);
760
- }
761
- }, sendAction.delay);
762
- };
763
-
764
- Interpreter.prototype.cancel = function (sendId) {
765
- this.clock.clearTimeout(this.delayedEventsMap[sendId]);
766
- delete this.delayedEventsMap[sendId];
767
- };
768
-
769
- Interpreter.prototype.exec = function (action, state, actionFunctionMap) {
770
- if (actionFunctionMap === void 0) {
771
- actionFunctionMap = this.machine.options.actions;
772
- }
773
-
774
- var context = state.context,
775
- _event = state._event;
776
- var actionOrExec = action.exec || getActionFunction(action.type, actionFunctionMap);
777
- var exec = isFunction(actionOrExec) ? actionOrExec : actionOrExec ? actionOrExec.exec : action.exec;
778
-
779
- if (exec) {
780
- try {
781
- return exec(context, _event.data, {
782
- action: action,
783
- state: this.state,
784
- _event: _event
785
- });
786
- } catch (err) {
787
- if (this.parent) {
788
- this.parent.send({
789
- type: 'xstate.error',
790
- data: err
791
- });
792
- }
793
-
794
- throw err;
795
- }
796
- }
797
-
798
- switch (action.type) {
799
- case send:
800
- var sendAction = action;
801
-
802
- if (typeof sendAction.delay === 'number') {
803
- this.defer(sendAction);
804
- return;
805
- } else {
806
- if (sendAction.to) {
807
- this.sendTo(sendAction._event, sendAction.to);
808
- } else {
809
- this.send(sendAction._event);
810
- }
811
- }
812
-
813
- break;
814
-
815
- case cancel:
816
- this.cancel(action.sendId);
817
- break;
818
-
819
- case start:
820
- {
821
- if (this.status !== InterpreterStatus.Running) {
822
- return;
823
- }
824
-
825
- var activity = action.activity; // If the activity will be stopped right after it's started
826
- // (such as in transient states)
827
- // don't bother starting the activity.
828
-
829
- if (!this.state.activities[activity.id || activity.type]) {
830
- break;
831
- } // Invoked services
832
-
833
-
834
- if (activity.type === ActionTypes.Invoke) {
835
- var invokeSource = toInvokeSource(activity.src);
836
- var serviceCreator = this.machine.options.services ? this.machine.options.services[invokeSource.type] : undefined;
837
- var id = activity.id,
838
- data = activity.data;
839
-
840
- if (!IS_PRODUCTION) {
841
- warn(!('forward' in activity), // tslint:disable-next-line:max-line-length
842
- "`forward` property is deprecated (found in invocation of '".concat(activity.src, "' in in machine '").concat(this.machine.id, "'). ") + "Please use `autoForward` instead.");
843
- }
844
-
845
- var autoForward = 'autoForward' in activity ? activity.autoForward : !!activity.forward;
846
-
847
- if (!serviceCreator) {
848
- // tslint:disable-next-line:no-console
849
- if (!IS_PRODUCTION) {
850
- warn(false, "No service found for invocation '".concat(activity.src, "' in machine '").concat(this.machine.id, "'."));
851
- }
852
-
853
- return;
854
- }
855
-
856
- var resolvedData = data ? mapContext(data, context, _event) : undefined;
857
-
858
- if (typeof serviceCreator === 'string') {
859
- // TODO: warn
860
- return;
861
- }
862
-
863
- var source = isFunction(serviceCreator) ? serviceCreator(context, _event.data, {
864
- data: resolvedData,
865
- src: invokeSource,
866
- meta: activity.meta
867
- }) : serviceCreator;
868
-
869
- if (!source) {
870
- // TODO: warn?
871
- return;
872
- }
873
-
874
- var options = void 0;
875
-
876
- if (isMachine(source)) {
877
- source = resolvedData ? source.withContext(resolvedData) : source;
878
- options = {
879
- autoForward: autoForward
880
- };
881
- }
882
-
883
- this.spawn(source, id, options);
884
- } else {
885
- this.spawnActivity(activity);
886
- }
887
-
888
- break;
889
- }
890
-
891
- case stop:
892
- {
893
- this.stopChild(action.activity.id);
894
- break;
895
- }
896
-
897
- case log:
898
- var label = action.label,
899
- value = action.value;
900
-
901
- if (label) {
902
- this.logger(label, value);
903
- } else {
904
- this.logger(value);
905
- }
906
-
907
- break;
908
-
909
- default:
910
- if (!IS_PRODUCTION) {
911
- warn(false, "No implementation found for action type '".concat(action.type, "'"));
912
- }
913
-
914
- break;
915
- }
916
-
917
- return undefined;
918
- };
919
-
920
- Interpreter.prototype.removeChild = function (childId) {
921
- var _a;
922
-
923
- this.children.delete(childId);
924
- this.forwardTo.delete(childId); // this.state might not exist at the time this is called,
925
- // such as when a child is added then removed while initializing the state
926
-
927
- (_a = this.state) === null || _a === void 0 ? true : delete _a.children[childId];
928
- };
929
-
930
- Interpreter.prototype.stopChild = function (childId) {
931
- var child = this.children.get(childId);
932
-
933
- if (!child) {
934
- return;
935
- }
936
-
937
- this.removeChild(childId);
938
-
939
- if (isFunction(child.stop)) {
940
- child.stop();
941
- }
942
- };
943
-
944
- Interpreter.prototype.spawn = function (entity, name, options) {
945
- if (isPromiseLike(entity)) {
946
- return this.spawnPromise(Promise.resolve(entity), name);
947
- } else if (isFunction(entity)) {
948
- return this.spawnCallback(entity, name);
949
- } else if (isSpawnedActor(entity)) {
950
- return this.spawnActor(entity, name);
951
- } else if (isObservable(entity)) {
952
- return this.spawnObservable(entity, name);
953
- } else if (isMachine(entity)) {
954
- return this.spawnMachine(entity, __assign(__assign({}, options), {
955
- id: name
956
- }));
957
- } else if (isBehavior(entity)) {
958
- return this.spawnBehavior(entity, name);
959
- } else {
960
- throw new Error("Unable to spawn entity \"".concat(name, "\" of type \"").concat(typeof entity, "\"."));
961
- }
962
- };
963
-
964
- Interpreter.prototype.spawnMachine = function (machine, options) {
965
- var _this = this;
966
-
967
- if (options === void 0) {
968
- options = {};
969
- }
970
-
971
- var childService = new Interpreter(machine, __assign(__assign({}, this.options), {
972
- parent: this,
973
- id: options.id || machine.id
974
- }));
975
-
976
- var resolvedOptions = __assign(__assign({}, DEFAULT_SPAWN_OPTIONS), options);
977
-
978
- if (resolvedOptions.sync) {
979
- childService.onTransition(function (state) {
980
- _this.send(update, {
981
- state: state,
982
- id: childService.id
983
- });
984
- });
985
- }
986
-
987
- var actor = childService;
988
- this.children.set(childService.id, actor);
989
-
990
- if (resolvedOptions.autoForward) {
991
- this.forwardTo.add(childService.id);
992
- }
993
-
994
- childService.onDone(function (doneEvent) {
995
- _this.removeChild(childService.id);
996
-
997
- _this.send(toSCXMLEvent(doneEvent, {
998
- origin: childService.id
999
- }));
1000
- }).start();
1001
- return actor;
1002
- };
1003
-
1004
- Interpreter.prototype.spawnBehavior = function (behavior, id) {
1005
- var actorRef = spawnBehavior(behavior, {
1006
- id: id,
1007
- parent: this
1008
- });
1009
- this.children.set(id, actorRef);
1010
- return actorRef;
1011
- };
1012
-
1013
- Interpreter.prototype.spawnPromise = function (promise, id) {
1014
- var _a;
1015
-
1016
- var _this = this;
1017
-
1018
- var canceled = false;
1019
- var resolvedData;
1020
- promise.then(function (response) {
1021
- if (!canceled) {
1022
- resolvedData = response;
1023
-
1024
- _this.removeChild(id);
1025
-
1026
- _this.send(toSCXMLEvent(doneInvoke(id, response), {
1027
- origin: id
1028
- }));
1029
- }
1030
- }, function (errorData) {
1031
- if (!canceled) {
1032
- _this.removeChild(id);
1033
-
1034
- var errorEvent = error(id, errorData);
1035
-
1036
- try {
1037
- // Send "error.platform.id" to this (parent).
1038
- _this.send(toSCXMLEvent(errorEvent, {
1039
- origin: id
1040
- }));
1041
- } catch (error) {
1042
- reportUnhandledExceptionOnInvocation(errorData, error, id);
1043
-
1044
- if (_this.devTools) {
1045
- _this.devTools.send(errorEvent, _this.state);
1046
- }
1047
-
1048
- if (_this.machine.strict) {
1049
- // it would be better to always stop the state machine if unhandled
1050
- // exception/promise rejection happens but because we don't want to
1051
- // break existing code so enforce it on strict mode only especially so
1052
- // because documentation says that onError is optional
1053
- _this.stop();
1054
- }
1055
- }
1056
- }
1057
- });
1058
- var actor = (_a = {
1059
- id: id,
1060
- send: function () {
1061
- return void 0;
1062
- },
1063
- subscribe: function (next, handleError, complete) {
1064
- var observer = toObserver(next, handleError, complete);
1065
- var unsubscribed = false;
1066
- promise.then(function (response) {
1067
- if (unsubscribed) {
1068
- return;
1069
- }
1070
-
1071
- observer.next(response);
1072
-
1073
- if (unsubscribed) {
1074
- return;
1075
- }
1076
-
1077
- observer.complete();
1078
- }, function (err) {
1079
- if (unsubscribed) {
1080
- return;
1081
- }
1082
-
1083
- observer.error(err);
1084
- });
1085
- return {
1086
- unsubscribe: function () {
1087
- return unsubscribed = true;
1088
- }
1089
- };
1090
- },
1091
- stop: function () {
1092
- canceled = true;
1093
- },
1094
- toJSON: function () {
1095
- return {
1096
- id: id
1097
- };
1098
- },
1099
- getSnapshot: function () {
1100
- return resolvedData;
1101
- }
1102
- }, _a[symbolObservable] = function () {
1103
- return this;
1104
- }, _a);
1105
- this.children.set(id, actor);
1106
- return actor;
1107
- };
1108
-
1109
- Interpreter.prototype.spawnCallback = function (callback, id) {
1110
- var _a;
1111
-
1112
- var _this = this;
1113
-
1114
- var canceled = false;
1115
- var receivers = new Set();
1116
- var listeners = new Set();
1117
- var emitted;
1118
-
1119
- var receive = function (e) {
1120
- emitted = e;
1121
- listeners.forEach(function (listener) {
1122
- return listener(e);
1123
- });
1124
-
1125
- if (canceled) {
1126
- return;
1127
- }
1128
-
1129
- _this.send(toSCXMLEvent(e, {
1130
- origin: id
1131
- }));
1132
- };
1133
-
1134
- var callbackStop;
1135
-
1136
- try {
1137
- callbackStop = callback(receive, function (newListener) {
1138
- receivers.add(newListener);
1139
- });
1140
- } catch (err) {
1141
- this.send(error(id, err));
1142
- }
1143
-
1144
- if (isPromiseLike(callbackStop)) {
1145
- // it turned out to be an async function, can't reliably check this before calling `callback`
1146
- // because transpiled async functions are not recognizable
1147
- return this.spawnPromise(callbackStop, id);
1148
- }
1149
-
1150
- var actor = (_a = {
1151
- id: id,
1152
- send: function (event) {
1153
- return receivers.forEach(function (receiver) {
1154
- return receiver(event);
1155
- });
1156
- },
1157
- subscribe: function (next) {
1158
- var observer = toObserver(next);
1159
- listeners.add(observer.next);
1160
- return {
1161
- unsubscribe: function () {
1162
- listeners.delete(observer.next);
1163
- }
1164
- };
1165
- },
1166
- stop: function () {
1167
- canceled = true;
1168
-
1169
- if (isFunction(callbackStop)) {
1170
- callbackStop();
1171
- }
1172
- },
1173
- toJSON: function () {
1174
- return {
1175
- id: id
1176
- };
1177
- },
1178
- getSnapshot: function () {
1179
- return emitted;
1180
- }
1181
- }, _a[symbolObservable] = function () {
1182
- return this;
1183
- }, _a);
1184
- this.children.set(id, actor);
1185
- return actor;
1186
- };
1187
-
1188
- Interpreter.prototype.spawnObservable = function (source, id) {
1189
- var _a;
1190
-
1191
- var _this = this;
1192
-
1193
- var emitted;
1194
- var subscription = source.subscribe(function (value) {
1195
- emitted = value;
1196
-
1197
- _this.send(toSCXMLEvent(value, {
1198
- origin: id
1199
- }));
1200
- }, function (err) {
1201
- _this.removeChild(id);
1202
-
1203
- _this.send(toSCXMLEvent(error(id, err), {
1204
- origin: id
1205
- }));
1206
- }, function () {
1207
- _this.removeChild(id);
1208
-
1209
- _this.send(toSCXMLEvent(doneInvoke(id), {
1210
- origin: id
1211
- }));
1212
- });
1213
- var actor = (_a = {
1214
- id: id,
1215
- send: function () {
1216
- return void 0;
1217
- },
1218
- subscribe: function (next, handleError, complete) {
1219
- return source.subscribe(next, handleError, complete);
1220
- },
1221
- stop: function () {
1222
- return subscription.unsubscribe();
1223
- },
1224
- getSnapshot: function () {
1225
- return emitted;
1226
- },
1227
- toJSON: function () {
1228
- return {
1229
- id: id
1230
- };
1231
- }
1232
- }, _a[symbolObservable] = function () {
1233
- return this;
1234
- }, _a);
1235
- this.children.set(id, actor);
1236
- return actor;
1237
- };
1238
-
1239
- Interpreter.prototype.spawnActor = function (actor, name) {
1240
- this.children.set(name, actor);
1241
- return actor;
1242
- };
1243
-
1244
- Interpreter.prototype.spawnActivity = function (activity) {
1245
- var implementation = this.machine.options && this.machine.options.activities ? this.machine.options.activities[activity.type] : undefined;
1246
-
1247
- if (!implementation) {
1248
- if (!IS_PRODUCTION) {
1249
- warn(false, "No implementation found for activity '".concat(activity.type, "'"));
1250
- } // tslint:disable-next-line:no-console
1251
-
1252
-
1253
- return;
1254
- } // Start implementation
1255
-
1256
-
1257
- var dispose = implementation(this.state.context, activity);
1258
- this.spawnEffect(activity.id, dispose);
1259
- };
1260
-
1261
- Interpreter.prototype.spawnEffect = function (id, dispose) {
1262
- var _a;
1263
-
1264
- this.children.set(id, (_a = {
1265
- id: id,
1266
- send: function () {
1267
- return void 0;
1268
- },
1269
- subscribe: function () {
1270
- return {
1271
- unsubscribe: function () {
1272
- return void 0;
1273
- }
1274
- };
1275
- },
1276
- stop: dispose || undefined,
1277
- getSnapshot: function () {
1278
- return undefined;
1279
- },
1280
- toJSON: function () {
1281
- return {
1282
- id: id
1283
- };
1284
- }
1285
- }, _a[symbolObservable] = function () {
1286
- return this;
1287
- }, _a));
1288
- };
1289
-
1290
- Interpreter.prototype.attachDev = function () {
1291
- var global = getGlobal();
1292
-
1293
- if (this.options.devTools && global) {
1294
- if (global.__REDUX_DEVTOOLS_EXTENSION__) {
1295
- var devToolsOptions = typeof this.options.devTools === 'object' ? this.options.devTools : undefined;
1296
- this.devTools = global.__REDUX_DEVTOOLS_EXTENSION__.connect(__assign(__assign({
1297
- name: this.id,
1298
- autoPause: true,
1299
- stateSanitizer: function (state) {
1300
- return {
1301
- value: state.value,
1302
- context: state.context,
1303
- actions: state.actions
1304
- };
1305
- }
1306
- }, devToolsOptions), {
1307
- features: __assign({
1308
- jump: false,
1309
- skip: false
1310
- }, devToolsOptions ? devToolsOptions.features : undefined)
1311
- }), this.machine);
1312
- this.devTools.init(this.state);
1313
- } // add XState-specific dev tooling hook
1314
-
1315
-
1316
- registerService(this);
1317
- }
1318
- };
1319
-
1320
- Interpreter.prototype.toJSON = function () {
1321
- return {
1322
- id: this.id
1323
- };
1324
- };
1325
-
1326
- Interpreter.prototype[symbolObservable] = function () {
1327
- return this;
1328
- };
1329
-
1330
- Interpreter.prototype.getSnapshot = function () {
1331
- if (this.status === InterpreterStatus.NotStarted) {
1332
- return this.initialState;
1333
- }
1334
-
1335
- return this._state;
1336
- };
1337
- /**
1338
- * The default interpreter options:
1339
- *
1340
- * - `clock` uses the global `setTimeout` and `clearTimeout` functions
1341
- * - `logger` uses the global `console.log()` method
1342
- */
1343
-
1344
-
1345
- Interpreter.defaultOptions = {
1346
- execute: true,
1347
- deferEvents: true,
1348
- clock: {
1349
- setTimeout: function (fn, ms) {
1350
- return setTimeout(fn, ms);
1351
- },
1352
- clearTimeout: function (id) {
1353
- return clearTimeout(id);
1354
- }
1355
- },
1356
- logger: /*#__PURE__*/console.log.bind(console),
1357
- devTools: false
1358
- };
1359
- Interpreter.interpret = interpret;
1360
- return Interpreter;
1361
- }();
1362
-
1363
- var resolveSpawnOptions = function (nameOrOptions) {
1364
- if (isString(nameOrOptions)) {
1365
- return __assign(__assign({}, DEFAULT_SPAWN_OPTIONS), {
1366
- name: nameOrOptions
1367
- });
1368
- }
1369
-
1370
- return __assign(__assign(__assign({}, DEFAULT_SPAWN_OPTIONS), {
1371
- name: uniqueId()
1372
- }), nameOrOptions);
1373
- };
1374
-
1375
- function spawn(entity, nameOrOptions) {
1376
- var resolvedOptions = resolveSpawnOptions(nameOrOptions);
1377
- return consume(function (service) {
1378
- if (!IS_PRODUCTION) {
1379
- var isLazyEntity = isMachine(entity) || isFunction(entity);
1380
- warn(!!service || isLazyEntity, "Attempted to spawn an Actor (ID: \"".concat(isMachine(entity) ? entity.id : 'undefined', "\") outside of a service. This will have no effect."));
1381
- }
1382
-
1383
- if (service) {
1384
- return service.spawn(entity, resolvedOptions.name, resolvedOptions);
1385
- } else {
1386
- return createDeferredActor(entity, resolvedOptions.name);
1387
- }
1388
- });
1389
- }
1390
- /**
1391
- * Creates a new Interpreter instance for the given machine with the provided options, if any.
1392
- *
1393
- * @param machine The machine to interpret
1394
- * @param options Interpreter options
1395
- */
1396
-
1397
- function interpret(machine, options) {
1398
- var interpreter = new Interpreter(machine, options);
1399
- return interpreter;
1400
- }
1401
-
1402
- export { Interpreter, InterpreterStatus, interpret, spawn };