xstate 4.35.2 → 5.0.0-alpha.1

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