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