xstate 4.31.0 → 5.0.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (206) hide show
  1. package/CHANGELOG.md +526 -0
  2. package/actions/ExecutableAction.ts +58 -0
  3. package/actions/dist/xstate-actions.cjs.d.ts +1 -0
  4. package/actions/dist/xstate-actions.cjs.dev.js +32 -0
  5. package/actions/dist/xstate-actions.cjs.js +7 -0
  6. package/actions/dist/xstate-actions.cjs.prod.js +32 -0
  7. package/actions/dist/xstate-actions.esm.js +2 -0
  8. package/actions/dynamicAction.ts +34 -0
  9. package/actions/package.json +4 -0
  10. package/actors/dist/xstate-actors.cjs.d.ts +1 -0
  11. package/actors/dist/xstate-actors.cjs.dev.js +21 -0
  12. package/actors/dist/xstate-actors.cjs.js +7 -0
  13. package/actors/dist/xstate-actors.cjs.prod.js +21 -0
  14. package/actors/dist/xstate-actors.esm.js +2 -0
  15. package/actors/package.json +4 -0
  16. package/dev/dist/xstate-dev.cjs.d.ts +1 -0
  17. package/dev/dist/xstate-dev.cjs.dev.js +11 -0
  18. package/dev/dist/xstate-dev.cjs.js +7 -0
  19. package/{lib/devTools.js → dev/dist/xstate-dev.cjs.prod.js} +17 -10
  20. package/dev/dist/xstate-dev.esm.js +1 -0
  21. package/dev/package.json +4 -0
  22. package/dist/Machine-9ce74c11.cjs.dev.js +755 -0
  23. package/dist/Machine-dca041dc.cjs.prod.js +749 -0
  24. package/dist/Machine-fb2f47f5.esm.js +751 -0
  25. package/dist/actions-6b86876d.cjs.dev.js +4815 -0
  26. package/dist/actions-70094c93.cjs.prod.js +4765 -0
  27. package/dist/actions-ff512f16.esm.js +4757 -0
  28. package/dist/declarations/actions/ExecutableAction.d.ts +23 -0
  29. package/dist/declarations/actions/dynamicAction.d.ts +3 -0
  30. package/dist/declarations/src/Machine.d.ts +4 -0
  31. package/dist/declarations/src/Mailbox.d.ts +12 -0
  32. package/dist/declarations/src/ObservableActorRef.d.ts +25 -0
  33. package/{lib → dist/declarations/src}/SimulatedClock.d.ts +0 -1
  34. package/dist/declarations/src/State.d.ts +104 -0
  35. package/dist/declarations/src/StateMachine.d.ts +112 -0
  36. package/dist/declarations/src/StateNode.d.ts +127 -0
  37. package/{es → dist/declarations/src}/actionTypes.d.ts +0 -3
  38. package/dist/declarations/src/actions/assign.d.ts +7 -0
  39. package/dist/declarations/src/actions/cancel.d.ts +10 -0
  40. package/dist/declarations/src/actions/choose.d.ts +3 -0
  41. package/dist/declarations/src/actions/invoke.d.ts +3 -0
  42. package/dist/declarations/src/actions/log.d.ts +11 -0
  43. package/dist/declarations/src/actions/pure.d.ts +3 -0
  44. package/dist/declarations/src/actions/raise.d.ts +9 -0
  45. package/dist/declarations/src/actions/send.d.ts +55 -0
  46. package/dist/declarations/src/actions/stop.d.ts +8 -0
  47. package/dist/declarations/src/actions.d.ts +44 -0
  48. package/dist/declarations/src/actors.d.ts +38 -0
  49. package/dist/declarations/src/constants.d.ts +5 -0
  50. package/{lib/devTools.d.ts → dist/declarations/src/dev/index.d.ts} +2 -2
  51. package/{es → dist/declarations/src}/environment.d.ts +0 -1
  52. package/dist/declarations/src/guards.d.ts +9 -0
  53. package/dist/declarations/src/index.d.ts +47 -0
  54. package/dist/declarations/src/interpreter.d.ts +147 -0
  55. package/{es → dist/declarations/src}/mapState.d.ts +0 -1
  56. package/dist/declarations/src/match.d.ts +5 -0
  57. package/dist/declarations/src/memo.d.ts +1 -0
  58. package/dist/declarations/src/model.d.ts +5 -0
  59. package/{lib → dist/declarations/src}/model.types.d.ts +10 -9
  60. package/dist/declarations/src/registry.d.ts +8 -0
  61. package/{es → dist/declarations/src}/schema.d.ts +0 -1
  62. package/dist/declarations/src/spawn.d.ts +2 -0
  63. package/dist/declarations/src/stateUtils.d.ts +85 -0
  64. package/{lib → dist/declarations/src}/typegenTypes.d.ts +28 -26
  65. package/dist/declarations/src/types.d.ts +1026 -0
  66. package/dist/declarations/src/utils.d.ts +56 -0
  67. package/{es/devTools.js → dist/index-20b364c4.esm.js} +18 -6
  68. package/dist/index-2a564d03.cjs.dev.js +64 -0
  69. package/dist/xstate.cjs.d.ts +1 -0
  70. package/dist/xstate.cjs.dev.js +217 -0
  71. package/dist/xstate.cjs.js +7 -0
  72. package/dist/xstate.cjs.prod.js +217 -0
  73. package/dist/xstate.esm.js +172 -0
  74. package/guards/dist/xstate-guards.cjs.d.ts +1 -0
  75. package/guards/dist/xstate-guards.cjs.dev.js +15 -0
  76. package/guards/dist/xstate-guards.cjs.js +7 -0
  77. package/guards/dist/xstate-guards.cjs.prod.js +15 -0
  78. package/guards/dist/xstate-guards.esm.js +2 -0
  79. package/guards/package.json +4 -0
  80. package/invoke/package.json +4 -0
  81. package/model/dist/xstate-model.cjs.d.ts +1 -0
  82. package/model/dist/xstate-model.cjs.dev.js +41 -0
  83. package/model/dist/xstate-model.cjs.js +7 -0
  84. package/model/dist/xstate-model.cjs.prod.js +41 -0
  85. package/model/dist/xstate-model.esm.js +37 -0
  86. package/model/package.json +4 -0
  87. package/package.json +21 -30
  88. package/dist/xstate.interpreter.js +0 -15
  89. package/dist/xstate.js +0 -15
  90. package/dist/xstate.web.js +0 -15
  91. package/es/Actor.d.ts +0 -25
  92. package/es/Actor.js +0 -99
  93. package/es/Machine.d.ts +0 -12
  94. package/es/Machine.js +0 -14
  95. package/es/SimulatedClock.d.ts +0 -17
  96. package/es/SimulatedClock.js +0 -81
  97. package/es/State.d.ts +0 -123
  98. package/es/State.js +0 -274
  99. package/es/StateNode.d.ts +0 -287
  100. package/es/StateNode.js +0 -1566
  101. package/es/_virtual/_tslib.js +0 -78
  102. package/es/actionTypes.js +0 -22
  103. package/es/actions.d.ts +0 -154
  104. package/es/actions.js +0 -520
  105. package/es/behaviors.d.ts +0 -37
  106. package/es/behaviors.js +0 -131
  107. package/es/constants.d.ts +0 -6
  108. package/es/constants.js +0 -6
  109. package/es/devTools.d.ts +0 -14
  110. package/es/each.d.ts +0 -4
  111. package/es/each.js +0 -13
  112. package/es/environment.js +0 -3
  113. package/es/index.d.ts +0 -22
  114. package/es/index.js +0 -23
  115. package/es/interpreter.d.ts +0 -209
  116. package/es/interpreter.js +0 -1402
  117. package/es/invoke.d.ts +0 -11
  118. package/es/invokeUtils.d.ts +0 -7
  119. package/es/invokeUtils.js +0 -40
  120. package/es/json.d.ts +0 -31
  121. package/es/json.js +0 -86
  122. package/es/mapState.js +0 -32
  123. package/es/match.d.ts +0 -9
  124. package/es/match.js +0 -34
  125. package/es/model.d.ts +0 -5
  126. package/es/model.js +0 -50
  127. package/es/model.types.d.ts +0 -52
  128. package/es/patterns.d.ts +0 -14
  129. package/es/patterns.js +0 -48
  130. package/es/registry.d.ts +0 -9
  131. package/es/registry.js +0 -19
  132. package/es/scheduler.d.ts +0 -17
  133. package/es/scheduler.js +0 -79
  134. package/es/schema.js +0 -6
  135. package/es/scxml.d.ts +0 -6
  136. package/es/serviceScope.d.ts +0 -4
  137. package/es/serviceScope.js +0 -16
  138. package/es/stateUtils.d.ts +0 -17
  139. package/es/stateUtils.js +0 -259
  140. package/es/typegenTypes.d.ts +0 -130
  141. package/es/types.d.ts +0 -1037
  142. package/es/types.js +0 -33
  143. package/es/utils.d.ts +0 -72
  144. package/es/utils.js +0 -626
  145. package/es/waitFor.d.ts +0 -32
  146. package/es/waitFor.js +0 -66
  147. package/lib/Actor.d.ts +0 -25
  148. package/lib/Actor.js +0 -108
  149. package/lib/Machine.d.ts +0 -12
  150. package/lib/Machine.js +0 -19
  151. package/lib/SimulatedClock.js +0 -85
  152. package/lib/State.d.ts +0 -123
  153. package/lib/State.js +0 -282
  154. package/lib/StateNode.d.ts +0 -287
  155. package/lib/StateNode.js +0 -1570
  156. package/lib/_virtual/_tslib.js +0 -85
  157. package/lib/actionTypes.d.ts +0 -20
  158. package/lib/actionTypes.js +0 -43
  159. package/lib/actions.d.ts +0 -154
  160. package/lib/actions.js +0 -552
  161. package/lib/behaviors.d.ts +0 -37
  162. package/lib/behaviors.js +0 -137
  163. package/lib/constants.d.ts +0 -6
  164. package/lib/constants.js +0 -13
  165. package/lib/each.d.ts +0 -4
  166. package/lib/each.js +0 -17
  167. package/lib/environment.d.ts +0 -2
  168. package/lib/environment.js +0 -7
  169. package/lib/index.d.ts +0 -22
  170. package/lib/index.js +0 -60
  171. package/lib/interpreter.d.ts +0 -209
  172. package/lib/interpreter.js +0 -1408
  173. package/lib/invoke.d.ts +0 -11
  174. package/lib/invoke.js +0 -20
  175. package/lib/invokeUtils.d.ts +0 -7
  176. package/lib/invokeUtils.js +0 -45
  177. package/lib/json.d.ts +0 -31
  178. package/lib/json.js +0 -94
  179. package/lib/mapState.d.ts +0 -4
  180. package/lib/mapState.js +0 -36
  181. package/lib/match.d.ts +0 -9
  182. package/lib/match.js +0 -38
  183. package/lib/model.d.ts +0 -5
  184. package/lib/model.js +0 -54
  185. package/lib/model.types.js +0 -2
  186. package/lib/patterns.d.ts +0 -14
  187. package/lib/patterns.js +0 -53
  188. package/lib/registry.d.ts +0 -9
  189. package/lib/registry.js +0 -23
  190. package/lib/scheduler.d.ts +0 -17
  191. package/lib/scheduler.js +0 -83
  192. package/lib/schema.d.ts +0 -3
  193. package/lib/schema.js +0 -11
  194. package/lib/scxml.d.ts +0 -6
  195. package/lib/scxml.js +0 -350
  196. package/lib/serviceScope.d.ts +0 -4
  197. package/lib/serviceScope.js +0 -21
  198. package/lib/stateUtils.d.ts +0 -17
  199. package/lib/stateUtils.js +0 -273
  200. package/lib/typegenTypes.js +0 -2
  201. package/lib/types.d.ts +0 -1037
  202. package/lib/types.js +0 -35
  203. package/lib/utils.d.ts +0 -72
  204. package/lib/utils.js +0 -673
  205. package/lib/waitFor.d.ts +0 -32
  206. package/lib/waitFor.js +0 -70
@@ -0,0 +1,4765 @@
1
+ 'use strict';
2
+
3
+ var dev_dist_xstateDev = require('../dev/dist/xstate-dev.cjs.prod.js');
4
+
5
+ // https://github.com/microsoft/TypeScript/issues/23182#issuecomment-379091887
6
+
7
+ (function (ActionTypes) {
8
+ ActionTypes["Stop"] = "xstate.stop";
9
+ ActionTypes["Raise"] = "xstate.raise";
10
+ ActionTypes["Send"] = "xstate.send";
11
+ ActionTypes["Cancel"] = "xstate.cancel";
12
+ ActionTypes["Assign"] = "xstate.assign";
13
+ ActionTypes["After"] = "xstate.after";
14
+ ActionTypes["DoneState"] = "done.state";
15
+ ActionTypes["DoneInvoke"] = "done.invoke";
16
+ ActionTypes["Log"] = "xstate.log";
17
+ ActionTypes["Init"] = "xstate.init";
18
+ ActionTypes["Invoke"] = "xstate.invoke";
19
+ ActionTypes["ErrorExecution"] = "error.execution";
20
+ ActionTypes["ErrorCommunication"] = "error.communication";
21
+ ActionTypes["ErrorPlatform"] = "error.platform";
22
+ ActionTypes["ErrorCustom"] = "xstate.error";
23
+ ActionTypes["Update"] = "xstate.update";
24
+ ActionTypes["Pure"] = "xstate.pure";
25
+ ActionTypes["Choose"] = "xstate.choose";
26
+ })(exports.ActionTypes || (exports.ActionTypes = {}));
27
+
28
+ (function (SpecialTargets) {
29
+ SpecialTargets["Parent"] = "#_parent";
30
+ SpecialTargets["Internal"] = "#_internal";
31
+ })(exports.SpecialTargets || (exports.SpecialTargets = {}));
32
+
33
+ var stop = exports.ActionTypes.Stop;
34
+ var raise = exports.ActionTypes.Raise;
35
+ var send = exports.ActionTypes.Send;
36
+ var cancel = exports.ActionTypes.Cancel;
37
+ var assign = exports.ActionTypes.Assign;
38
+ var after = exports.ActionTypes.After;
39
+ var doneState = exports.ActionTypes.DoneState;
40
+ var log = exports.ActionTypes.Log;
41
+ var init = exports.ActionTypes.Init;
42
+ var invoke = exports.ActionTypes.Invoke;
43
+ var errorExecution = exports.ActionTypes.ErrorExecution;
44
+ var errorPlatform = exports.ActionTypes.ErrorPlatform;
45
+ var error = exports.ActionTypes.ErrorCustom;
46
+ var update = exports.ActionTypes.Update;
47
+ var choose = exports.ActionTypes.Choose;
48
+ var pure = exports.ActionTypes.Pure;
49
+
50
+ var actionTypes = /*#__PURE__*/Object.freeze({
51
+ __proto__: null,
52
+ stop: stop,
53
+ raise: raise,
54
+ send: send,
55
+ cancel: cancel,
56
+ assign: assign,
57
+ after: after,
58
+ doneState: doneState,
59
+ log: log,
60
+ init: init,
61
+ invoke: invoke,
62
+ errorExecution: errorExecution,
63
+ errorPlatform: errorPlatform,
64
+ error: error,
65
+ update: update,
66
+ choose: choose,
67
+ pure: pure
68
+ });
69
+
70
+ function _defineProperty(obj, key, value) {
71
+ if (key in obj) {
72
+ Object.defineProperty(obj, key, {
73
+ value: value,
74
+ enumerable: true,
75
+ configurable: true,
76
+ writable: true
77
+ });
78
+ } else {
79
+ obj[key] = value;
80
+ }
81
+
82
+ return obj;
83
+ }
84
+
85
+ function ownKeys(object, enumerableOnly) {
86
+ var keys = Object.keys(object);
87
+
88
+ if (Object.getOwnPropertySymbols) {
89
+ var symbols = Object.getOwnPropertySymbols(object);
90
+ if (enumerableOnly) symbols = symbols.filter(function (sym) {
91
+ return Object.getOwnPropertyDescriptor(object, sym).enumerable;
92
+ });
93
+ keys.push.apply(keys, symbols);
94
+ }
95
+
96
+ return keys;
97
+ }
98
+
99
+ function _objectSpread2(target) {
100
+ for (var i = 1; i < arguments.length; i++) {
101
+ var source = arguments[i] != null ? arguments[i] : {};
102
+
103
+ if (i % 2) {
104
+ ownKeys(Object(source), true).forEach(function (key) {
105
+ _defineProperty(target, key, source[key]);
106
+ });
107
+ } else if (Object.getOwnPropertyDescriptors) {
108
+ Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
109
+ } else {
110
+ ownKeys(Object(source)).forEach(function (key) {
111
+ Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
112
+ });
113
+ }
114
+ }
115
+
116
+ return target;
117
+ }
118
+
119
+ function _arrayWithHoles(arr) {
120
+ if (Array.isArray(arr)) return arr;
121
+ }
122
+
123
+ function _iterableToArrayLimit(arr, i) {
124
+ if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return;
125
+ var _arr = [];
126
+ var _n = true;
127
+ var _d = false;
128
+ var _e = undefined;
129
+
130
+ try {
131
+ for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
132
+ _arr.push(_s.value);
133
+
134
+ if (i && _arr.length === i) break;
135
+ }
136
+ } catch (err) {
137
+ _d = true;
138
+ _e = err;
139
+ } finally {
140
+ try {
141
+ if (!_n && _i["return"] != null) _i["return"]();
142
+ } finally {
143
+ if (_d) throw _e;
144
+ }
145
+ }
146
+
147
+ return _arr;
148
+ }
149
+
150
+ function _arrayLikeToArray(arr, len) {
151
+ if (len == null || len > arr.length) len = arr.length;
152
+
153
+ for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
154
+
155
+ return arr2;
156
+ }
157
+
158
+ function _unsupportedIterableToArray(o, minLen) {
159
+ if (!o) return;
160
+ if (typeof o === "string") return _arrayLikeToArray(o, minLen);
161
+ var n = Object.prototype.toString.call(o).slice(8, -1);
162
+ if (n === "Object" && o.constructor) n = o.constructor.name;
163
+ if (n === "Map" || n === "Set") return Array.from(o);
164
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
165
+ }
166
+
167
+ function _nonIterableRest() {
168
+ throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
169
+ }
170
+
171
+ function _slicedToArray(arr, i) {
172
+ return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
173
+ }
174
+
175
+ function _arrayWithoutHoles(arr) {
176
+ if (Array.isArray(arr)) return _arrayLikeToArray(arr);
177
+ }
178
+
179
+ function _iterableToArray(iter) {
180
+ if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter);
181
+ }
182
+
183
+ function _nonIterableSpread() {
184
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
185
+ }
186
+
187
+ function _toConsumableArray(arr) {
188
+ return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
189
+ }
190
+
191
+ function _createForOfIteratorHelper(o, allowArrayLike) {
192
+ var it;
193
+
194
+ if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) {
195
+ if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
196
+ if (it) o = it;
197
+ var i = 0;
198
+
199
+ var F = function () {};
200
+
201
+ return {
202
+ s: F,
203
+ n: function () {
204
+ if (i >= o.length) return {
205
+ done: true
206
+ };
207
+ return {
208
+ done: false,
209
+ value: o[i++]
210
+ };
211
+ },
212
+ e: function (e) {
213
+ throw e;
214
+ },
215
+ f: F
216
+ };
217
+ }
218
+
219
+ throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
220
+ }
221
+
222
+ var normalCompletion = true,
223
+ didErr = false,
224
+ err;
225
+ return {
226
+ s: function () {
227
+ it = o[Symbol.iterator]();
228
+ },
229
+ n: function () {
230
+ var step = it.next();
231
+ normalCompletion = step.done;
232
+ return step;
233
+ },
234
+ e: function (e) {
235
+ didErr = true;
236
+ err = e;
237
+ },
238
+ f: function () {
239
+ try {
240
+ if (!normalCompletion && it.return != null) it.return();
241
+ } finally {
242
+ if (didErr) throw err;
243
+ }
244
+ }
245
+ };
246
+ }
247
+
248
+ function _typeof(obj) {
249
+ "@babel/helpers - typeof";
250
+
251
+ if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
252
+ _typeof = function (obj) {
253
+ return typeof obj;
254
+ };
255
+ } else {
256
+ _typeof = function (obj) {
257
+ return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
258
+ };
259
+ }
260
+
261
+ return _typeof(obj);
262
+ }
263
+
264
+ var STATE_DELIMITER = '.';
265
+ var TARGETLESS_KEY = '';
266
+ var NULL_EVENT = '';
267
+ var STATE_IDENTIFIER = '#';
268
+ var WILDCARD = '*';
269
+
270
+ function matchesState(parentStateId, childStateId) {
271
+ var delimiter = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : STATE_DELIMITER;
272
+ var parentStateValue = toStateValue(parentStateId, delimiter);
273
+ var childStateValue = toStateValue(childStateId, delimiter);
274
+
275
+ if (isString(childStateValue)) {
276
+ if (isString(parentStateValue)) {
277
+ return childStateValue === parentStateValue;
278
+ } // Parent more specific than child
279
+
280
+
281
+ return false;
282
+ }
283
+
284
+ if (isString(parentStateValue)) {
285
+ return parentStateValue in childStateValue;
286
+ }
287
+
288
+ return Object.keys(parentStateValue).every(function (key) {
289
+ if (!(key in childStateValue)) {
290
+ return false;
291
+ }
292
+
293
+ return matchesState(parentStateValue[key], childStateValue[key]);
294
+ });
295
+ }
296
+ function getEventType(event) {
297
+ try {
298
+ return isString(event) || typeof event === 'number' ? "".concat(event) : event.type;
299
+ } catch (e) {
300
+ throw new Error('Events must be strings or objects with a string event.type property.');
301
+ }
302
+ }
303
+ function toStatePath(stateId, delimiter) {
304
+ try {
305
+ if (isArray(stateId)) {
306
+ return stateId;
307
+ }
308
+
309
+ return stateId.toString().split(delimiter);
310
+ } catch (e) {
311
+ throw new Error("'".concat(stateId, "' is not a valid state path."));
312
+ }
313
+ }
314
+ function isStateLike(state) {
315
+ return _typeof(state) === 'object' && 'value' in state && 'context' in state && 'event' in state && '_event' in state;
316
+ }
317
+ function toStateValue(stateValue, delimiter) {
318
+ if (isStateLike(stateValue)) {
319
+ return stateValue.value;
320
+ }
321
+
322
+ if (isArray(stateValue)) {
323
+ return pathToStateValue(stateValue);
324
+ }
325
+
326
+ if (typeof stateValue !== 'string') {
327
+ return stateValue;
328
+ }
329
+
330
+ var statePath = toStatePath(stateValue, delimiter);
331
+ return pathToStateValue(statePath);
332
+ }
333
+ function pathToStateValue(statePath) {
334
+ if (statePath.length === 1) {
335
+ return statePath[0];
336
+ }
337
+
338
+ var value = {};
339
+ var marker = value;
340
+
341
+ for (var _i = 0; _i < statePath.length - 1; _i++) {
342
+ if (_i === statePath.length - 2) {
343
+ marker[statePath[_i]] = statePath[_i + 1];
344
+ } else {
345
+ marker[statePath[_i]] = {};
346
+ marker = marker[statePath[_i]];
347
+ }
348
+ }
349
+
350
+ return value;
351
+ }
352
+ function mapValues(collection, iteratee) {
353
+ var result = {};
354
+ var collectionKeys = Object.keys(collection);
355
+
356
+ for (var _i2 = 0; _i2 < collectionKeys.length; _i2++) {
357
+ var _key = collectionKeys[_i2];
358
+ result[_key] = iteratee(collection[_key], _key, collection, _i2);
359
+ }
360
+
361
+ return result;
362
+ }
363
+ function flatten(array) {
364
+ var _ref;
365
+
366
+ return (_ref = []).concat.apply(_ref, _toConsumableArray(array));
367
+ }
368
+ function toArrayStrict(value) {
369
+ if (isArray(value)) {
370
+ return value;
371
+ }
372
+
373
+ return [value];
374
+ }
375
+ function toArray(value) {
376
+ if (value === undefined) {
377
+ return [];
378
+ }
379
+
380
+ return toArrayStrict(value);
381
+ }
382
+ function mapContext(mapper, context, _event) {
383
+ if (isFunction(mapper)) {
384
+ return mapper(context, _event.data);
385
+ }
386
+
387
+ var result = {};
388
+
389
+ for (var _i4 = 0, _Object$keys2 = Object.keys(mapper); _i4 < _Object$keys2.length; _i4++) {
390
+ var _key3 = _Object$keys2[_i4];
391
+ var subMapper = mapper[_key3];
392
+
393
+ if (isFunction(subMapper)) {
394
+ result[_key3] = subMapper(context, _event.data);
395
+ } else {
396
+ result[_key3] = subMapper;
397
+ }
398
+ }
399
+
400
+ return result;
401
+ }
402
+ function isBuiltInEvent(eventType) {
403
+ return /^(done|error)\./.test(eventType);
404
+ }
405
+ function isPromiseLike(value) {
406
+ if (value instanceof Promise) {
407
+ return true;
408
+ } // Check if shape matches the Promise/A+ specification for a "thenable".
409
+
410
+
411
+ if (value !== null && (isFunction(value) || _typeof(value) === 'object') && isFunction(value.then)) {
412
+ return true;
413
+ }
414
+
415
+ return false;
416
+ }
417
+
418
+ var warn = function warn() {};
419
+
420
+ function isArray(value) {
421
+ return Array.isArray(value);
422
+ } // tslint:disable-next-line:ban-types
423
+
424
+ function isFunction(value) {
425
+ return typeof value === 'function';
426
+ }
427
+ function isString(value) {
428
+ return typeof value === 'string';
429
+ }
430
+ var symbolObservable = function () {
431
+ return typeof Symbol === 'function' && Symbol.observable || '@@observable';
432
+ }();
433
+ function isStateMachine(value) {
434
+ return !!value && '__xstatenode' in value;
435
+ }
436
+ function toEventObject(event, payload) {
437
+ if (isString(event)) {
438
+ return _objectSpread2({
439
+ type: event
440
+ }, payload);
441
+ }
442
+
443
+ return event;
444
+ }
445
+ function isSCXMLEvent(event) {
446
+ return !isString(event) && '$$type' in event && event.$$type === 'scxml';
447
+ }
448
+ function isSCXMLErrorEvent(event) {
449
+ return event.name === errorExecution || event.name.startsWith(errorPlatform);
450
+ }
451
+ function toSCXMLEvent(event, scxmlEvent) {
452
+ if (isSCXMLEvent(event)) {
453
+ return event;
454
+ }
455
+
456
+ var eventObject = toEventObject(event);
457
+ return _objectSpread2({
458
+ name: eventObject.type,
459
+ data: eventObject,
460
+ $$type: 'scxml',
461
+ type: 'external'
462
+ }, scxmlEvent);
463
+ }
464
+ function toTransitionConfigArray(event, configLike) {
465
+ var transitions = toArrayStrict(configLike).map(function (transitionLike) {
466
+ if (typeof transitionLike === 'undefined' || typeof transitionLike === 'string' || isStateMachine(transitionLike)) {
467
+ return {
468
+ target: transitionLike,
469
+ event: event
470
+ };
471
+ }
472
+
473
+ return _objectSpread2(_objectSpread2({}, transitionLike), {}, {
474
+ event: event
475
+ });
476
+ });
477
+ return transitions;
478
+ }
479
+ function normalizeTarget(target) {
480
+ if (target === undefined || target === TARGETLESS_KEY) {
481
+ return undefined;
482
+ }
483
+
484
+ return toArray(target);
485
+ }
486
+ function toInvokeConfig(invocable, id) {
487
+ if (_typeof(invocable) === 'object') {
488
+ if ('src' in invocable) {
489
+ return invocable;
490
+ }
491
+
492
+ if ('transition' in invocable) {
493
+ return {
494
+ id: id,
495
+ src: function src() {
496
+ return invocable;
497
+ }
498
+ };
499
+ }
500
+ }
501
+
502
+ return {
503
+ id: id,
504
+ src: invocable
505
+ };
506
+ }
507
+ function toInvokeSource(src) {
508
+ if (typeof src === 'string') {
509
+ return {
510
+ type: src
511
+ };
512
+ }
513
+
514
+ return src;
515
+ }
516
+ function toObserver(nextHandler, errorHandler, completionHandler) {
517
+ if (_typeof(nextHandler) === 'object') {
518
+ return nextHandler;
519
+ }
520
+
521
+ var noop = function noop() {
522
+ return void 0;
523
+ };
524
+
525
+ return {
526
+ next: nextHandler,
527
+ error: errorHandler || noop,
528
+ complete: completionHandler || noop
529
+ };
530
+ }
531
+ function createInvokeId(stateNodeId, index) {
532
+ return "".concat(stateNodeId, ":invocation[").concat(index, "]");
533
+ }
534
+
535
+ function _classCallCheck(instance, Constructor) {
536
+ if (!(instance instanceof Constructor)) {
537
+ throw new TypeError("Cannot call a class as a function");
538
+ }
539
+ }
540
+
541
+ function _defineProperties(target, props) {
542
+ for (var i = 0; i < props.length; i++) {
543
+ var descriptor = props[i];
544
+ descriptor.enumerable = descriptor.enumerable || false;
545
+ descriptor.configurable = true;
546
+ if ("value" in descriptor) descriptor.writable = true;
547
+ Object.defineProperty(target, descriptor.key, descriptor);
548
+ }
549
+ }
550
+
551
+ function _createClass(Constructor, protoProps, staticProps) {
552
+ if (protoProps) _defineProperties(Constructor.prototype, protoProps);
553
+ if (staticProps) _defineProperties(Constructor, staticProps);
554
+ return Constructor;
555
+ }
556
+
557
+ // TODO: refactor out of class
558
+ var ExecutableAction = /*#__PURE__*/function () {
559
+ function ExecutableAction(actionObject, _exec) {
560
+ var _actionObject$params;
561
+
562
+ _classCallCheck(this, ExecutableAction);
563
+
564
+ this.actionObject = actionObject;
565
+ this._exec = _exec;
566
+
567
+ _defineProperty(this, "type", void 0);
568
+
569
+ _defineProperty(this, "params", void 0);
570
+
571
+ _defineProperty(this, "context", undefined);
572
+
573
+ this.type = actionObject.type;
574
+ this.params = (_actionObject$params = actionObject.params) !== null && _actionObject$params !== void 0 ? _actionObject$params : {};
575
+ }
576
+
577
+ _createClass(ExecutableAction, [{
578
+ key: "execute",
579
+ value: function execute(state) {
580
+ var _this$context, _this$_exec;
581
+
582
+ var context = (_this$context = this.context) !== null && _this$context !== void 0 ? _this$context : state.context;
583
+ return (_this$_exec = this._exec) === null || _this$_exec === void 0 ? void 0 : _this$_exec.call(this, context, state.event, {
584
+ action: this.actionObject,
585
+ _event: state._event,
586
+ state: state
587
+ });
588
+ }
589
+ }, {
590
+ key: "setContext",
591
+ value: function setContext(context) {
592
+ this.context = context;
593
+ }
594
+ }]);
595
+
596
+ return ExecutableAction;
597
+ }();
598
+ function isExecutableAction(action) {
599
+ return 'execute' in action && typeof action.execute === 'function';
600
+ }
601
+
602
+ function createDynamicAction(type, params, resolve) {
603
+ return {
604
+ type: type,
605
+ params: params,
606
+ resolve: resolve
607
+ };
608
+ }
609
+ function isDynamicAction(action) {
610
+ return _typeof(action) === 'object' && action !== null && 'resolve' in action;
611
+ }
612
+
613
+ /**
614
+ * Sends an event. This returns an action that will be read by an interpreter to
615
+ * send the event in the next step, after the current step is finished executing.
616
+ *
617
+ * @param event The event to send.
618
+ * @param options Options to pass into the send event:
619
+ * - `id` - The unique send event identifier (used with `cancel()`).
620
+ * - `delay` - The number of milliseconds to delay the sending of the event.
621
+ * - `to` - The target of this event (by default, the machine the event was sent from).
622
+ */
623
+
624
+ function send$1(event, options) {
625
+ var eventOrExpr = isFunction(event) ? event : toEventObject(event);
626
+ return createDynamicAction(send, {
627
+ to: options ? options.to : undefined,
628
+ delay: options ? options.delay : undefined,
629
+ event: eventOrExpr,
630
+ id: options && options.id !== undefined ? options.id : isFunction(event) ? event.name : getEventType(event)
631
+ }, function (_ref, ctx, _event, _ref2) {
632
+ var params = _ref.params;
633
+ var machine = _ref2.machine;
634
+ var meta = {
635
+ _event: _event
636
+ };
637
+ var delaysMap = machine.options.delays; // TODO: helper function for resolving Expr
638
+
639
+ var resolvedEvent = toSCXMLEvent(isFunction(eventOrExpr) ? eventOrExpr(ctx, _event.data, meta) : eventOrExpr);
640
+ var resolvedDelay;
641
+
642
+ if (isString(params.delay)) {
643
+ var configDelay = delaysMap && delaysMap[params.delay];
644
+ resolvedDelay = isFunction(configDelay) ? configDelay(ctx, _event.data, meta) : configDelay;
645
+ } else {
646
+ resolvedDelay = isFunction(params.delay) ? params.delay(ctx, _event.data, meta) : params.delay;
647
+ }
648
+
649
+ var resolvedTarget = isFunction(params.to) ? params.to(ctx, _event.data, meta) : params.to;
650
+ resolvedTarget = isString(resolvedTarget) && resolvedTarget !== exports.SpecialTargets.Parent && resolvedTarget !== exports.SpecialTargets.Internal && resolvedTarget.startsWith('#_') ? resolvedTarget.slice(2) : resolvedTarget;
651
+ return {
652
+ type: send,
653
+ params: _objectSpread2(_objectSpread2({
654
+ id: ''
655
+ }, params), {}, {
656
+ to: resolvedTarget,
657
+ _event: resolvedEvent,
658
+ event: resolvedEvent.data,
659
+ delay: resolvedDelay
660
+ })
661
+ };
662
+ });
663
+ }
664
+ /**
665
+ * Sends an update event to this machine's parent.
666
+ */
667
+
668
+ function sendUpdate() {
669
+ return sendParent(update);
670
+ }
671
+ /**
672
+ * Sends an event to this machine's parent.
673
+ *
674
+ * @param event The event to send to the parent machine.
675
+ * @param options Options to pass into the send event.
676
+ */
677
+
678
+ function sendParent(event, options) {
679
+ return send$1(event, _objectSpread2(_objectSpread2({}, options), {}, {
680
+ to: exports.SpecialTargets.Parent
681
+ }));
682
+ }
683
+ /**
684
+ * Sends an event back to the sender of the original event.
685
+ *
686
+ * @param event The event to send back to the sender
687
+ * @param options Options to pass into the send event
688
+ */
689
+
690
+ function respond(event, options) {
691
+ return send$1(event, _objectSpread2(_objectSpread2({}, options), {}, {
692
+ to: function to(_, __, _ref3) {
693
+ var _event = _ref3._event;
694
+ return _event.origin; // TODO: handle when _event.origin is undefined
695
+ }
696
+ }));
697
+ }
698
+ /**
699
+ * Forwards (sends) an event to a specified service.
700
+ *
701
+ * @param target The target service to forward the event to.
702
+ * @param options Options to pass into the send action creator.
703
+ */
704
+
705
+ function forwardTo(target, options) {
706
+ return send$1(function (_, event) {
707
+ return event;
708
+ }, _objectSpread2(_objectSpread2({}, options), {}, {
709
+ to: target
710
+ }));
711
+ }
712
+ /**
713
+ * Escalates an error by sending it as an event to this machine's parent.
714
+ *
715
+ * @param errorData The error data to send, or the expression function that
716
+ * takes in the `context`, `event`, and `meta`, and returns the error data to send.
717
+ * @param options Options to pass into the send action creator.
718
+ */
719
+
720
+ function escalate(errorData, options) {
721
+ return sendParent(function (context, event, meta) {
722
+ return {
723
+ type: error,
724
+ data: isFunction(errorData) ? errorData(context, event, meta) : errorData
725
+ };
726
+ }, _objectSpread2(_objectSpread2({}, options), {}, {
727
+ to: exports.SpecialTargets.Parent
728
+ }));
729
+ }
730
+ /**
731
+ * Sends an event to an actor.
732
+ *
733
+ * @param actor The `ActorRef` to send the event to.
734
+ * @param event The event to send, or an expression that evaluates to the event to send
735
+ * @param options Send action options
736
+ * @returns An XState send action object
737
+ */
738
+
739
+ function sendTo(actor, event, options) {
740
+ return send$1(event, _objectSpread2(_objectSpread2({}, options), {}, {
741
+ to: actor
742
+ }));
743
+ }
744
+
745
+ /**
746
+ * Stops an actor.
747
+ *
748
+ * @param actorRef The actor to stop.
749
+ */
750
+ function stop$1(actorRef) {
751
+ var actor = actorRef;
752
+ return createDynamicAction(stop, {
753
+ actor: actor
754
+ }, function (_ref, context, _event) {
755
+ var params = _ref.params,
756
+ type = _ref.type;
757
+ var actorRefOrString = isFunction(params.actor) ? params.actor(context, _event.data) : params.actor;
758
+ return {
759
+ type: type,
760
+ params: {
761
+ actor: actorRefOrString
762
+ }
763
+ };
764
+ });
765
+ }
766
+
767
+ var defaultLogExpr = function defaultLogExpr(context, event) {
768
+ return {
769
+ context: context,
770
+ event: event
771
+ };
772
+ };
773
+ /**
774
+ *
775
+ * @param expr The expression function to evaluate which will be logged.
776
+ * Takes in 2 arguments:
777
+ * - `ctx` - the current state context
778
+ * - `event` - the event that caused this action to be executed.
779
+ * @param label The label to give to the logged expression.
780
+ */
781
+
782
+
783
+ function log$1() {
784
+ var expr = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : defaultLogExpr;
785
+ var label = arguments.length > 1 ? arguments[1] : undefined;
786
+ return createDynamicAction(log, {
787
+ label: label,
788
+ expr: expr
789
+ }, function (_ref, ctx, _event) {
790
+ var type = _ref.type;
791
+ return {
792
+ type: type,
793
+ params: {
794
+ label: label,
795
+ value: typeof expr === 'function' ? expr(ctx, _event.data, {
796
+ _event: _event
797
+ }) : expr
798
+ }
799
+ };
800
+ });
801
+ }
802
+
803
+ /**
804
+ * Cancels an in-flight `send(...)` action. A canceled sent action will not
805
+ * be executed, nor will its event be sent, unless it has already been sent
806
+ * (e.g., if `cancel(...)` is called after the `send(...)` action's `delay`).
807
+ *
808
+ * @param sendId The `id` of the `send(...)` action to cancel.
809
+ */
810
+
811
+ function cancel$1(sendId) {
812
+ return createDynamicAction(cancel, {
813
+ sendId: sendId
814
+ }, function (_ref, ctx, _event) {
815
+ var params = _ref.params,
816
+ type = _ref.type;
817
+ var resolvedSendId = isFunction(params.sendId) ? params.sendId(ctx, _event.data, {
818
+ _event: _event
819
+ }) : params.sendId;
820
+ return {
821
+ type: type,
822
+ params: {
823
+ sendId: resolvedSendId
824
+ }
825
+ };
826
+ });
827
+ }
828
+
829
+ var Mailbox = /*#__PURE__*/function () {
830
+ function Mailbox(_process) {
831
+ _classCallCheck(this, Mailbox);
832
+
833
+ this._process = _process;
834
+
835
+ _defineProperty(this, "_active", false);
836
+
837
+ _defineProperty(this, "_current", null);
838
+
839
+ _defineProperty(this, "_last", null);
840
+ }
841
+
842
+ _createClass(Mailbox, [{
843
+ key: "start",
844
+ value: function start() {
845
+ this._active = true;
846
+ this.flush();
847
+ }
848
+ }, {
849
+ key: "clear",
850
+ value: function clear() {
851
+ // we can't set _current to null because we might be currently processing
852
+ // and enqueue following clear shouldnt start processing the enqueued item immediately
853
+ if (this._current) {
854
+ this._current.next = null;
855
+ this._last = this._current;
856
+ }
857
+ } // TODO: rethink this design
858
+
859
+ }, {
860
+ key: "prepend",
861
+ value: function prepend(event) {
862
+ if (!this._current) {
863
+ this.enqueue(event);
864
+ return;
865
+ } // we know that something is already queued up
866
+ // so the mailbox is already flushing or it's inactive
867
+ // therefore the only thing that we need to do is to reassign `this._current`
868
+
869
+
870
+ this._current = {
871
+ value: event,
872
+ next: this._current
873
+ };
874
+ }
875
+ }, {
876
+ key: "enqueue",
877
+ value: function enqueue(event) {
878
+ var enqueued = {
879
+ value: event,
880
+ next: null
881
+ };
882
+
883
+ if (this._current) {
884
+ this._last.next = enqueued;
885
+ this._last = enqueued;
886
+ return;
887
+ }
888
+
889
+ this._current = enqueued;
890
+ this._last = enqueued;
891
+
892
+ if (this._active) {
893
+ this.flush();
894
+ }
895
+ }
896
+ }, {
897
+ key: "flush",
898
+ value: function flush() {
899
+ while (this._current) {
900
+ // atm the given _process is responsible for implementing proper try/catch handling
901
+ // we assume here that this won't throw in a way that can affect this mailbox
902
+ var consumed = this._current;
903
+
904
+ this._process(consumed.value); // something could have been prepended in the meantime
905
+ // so we need to be defensive here to avoid skipping over a prepended item
906
+
907
+
908
+ if (consumed === this._current) {
909
+ this._current = this._current.next;
910
+ }
911
+ }
912
+
913
+ this._last = null;
914
+ }
915
+ }]);
916
+
917
+ return Mailbox;
918
+ }();
919
+
920
+ var children = new Map();
921
+ var sessionIdIndex = 0;
922
+ var registry = {
923
+ bookId: function bookId() {
924
+ return "x:".concat(sessionIdIndex++);
925
+ },
926
+ register: function register(id, actor) {
927
+ children.set(id, actor);
928
+ return id;
929
+ },
930
+ get: function get(id) {
931
+ return children.get(id);
932
+ },
933
+ free: function free(id) {
934
+ children["delete"](id);
935
+ }
936
+ };
937
+
938
+ function _objectWithoutPropertiesLoose(source, excluded) {
939
+ if (source == null) return {};
940
+ var target = {};
941
+ var sourceKeys = Object.keys(source);
942
+ var key, i;
943
+
944
+ for (i = 0; i < sourceKeys.length; i++) {
945
+ key = sourceKeys[i];
946
+ if (excluded.indexOf(key) >= 0) continue;
947
+ target[key] = source[key];
948
+ }
949
+
950
+ return target;
951
+ }
952
+
953
+ function _objectWithoutProperties(source, excluded) {
954
+ if (source == null) return {};
955
+ var target = _objectWithoutPropertiesLoose(source, excluded);
956
+ var key, i;
957
+
958
+ if (Object.getOwnPropertySymbols) {
959
+ var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
960
+
961
+ for (i = 0; i < sourceSymbolKeys.length; i++) {
962
+ key = sourceSymbolKeys[i];
963
+ if (excluded.indexOf(key) >= 0) continue;
964
+ if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
965
+ target[key] = source[key];
966
+ }
967
+ }
968
+
969
+ return target;
970
+ }
971
+
972
+ var cache = new WeakMap();
973
+ function memo(object, key, fn) {
974
+ var memoizedData = cache.get(object);
975
+
976
+ if (!memoizedData) {
977
+ memoizedData = _defineProperty({}, key, fn());
978
+ cache.set(object, memoizedData);
979
+ } else if (!(key in memoizedData)) {
980
+ memoizedData[key] = fn();
981
+ }
982
+
983
+ return memoizedData[key];
984
+ }
985
+
986
+ function _toPrimitive(input, hint) {
987
+ if (typeof input !== "object" || input === null) return input;
988
+ var prim = input[Symbol.toPrimitive];
989
+
990
+ if (prim !== undefined) {
991
+ var res = prim.call(input, hint || "default");
992
+ if (typeof res !== "object") return res;
993
+ throw new TypeError("@@toPrimitive must return a primitive value.");
994
+ }
995
+
996
+ return (hint === "string" ? String : Number)(input);
997
+ }
998
+
999
+ function _toPropertyKey(arg) {
1000
+ var key = _toPrimitive(arg, "string");
1001
+ return typeof key === "symbol" ? key : String(key);
1002
+ }
1003
+
1004
+ function invoke$1(invokeDef) {
1005
+ return createDynamicAction(invoke, invokeDef, function (_ref, context, _event, _ref2) {
1006
+ var params = _ref.params;
1007
+ var machine = _ref2.machine;
1008
+ var type = invoke;
1009
+ var id = params.id,
1010
+ data = params.data,
1011
+ src = params.src,
1012
+ meta = params.meta;
1013
+
1014
+ if (isActorRef(src)) {
1015
+ return {
1016
+ type: type,
1017
+ params: _objectSpread2(_objectSpread2({}, params), {}, {
1018
+ ref: src
1019
+ })
1020
+ };
1021
+ }
1022
+
1023
+ var behaviorImpl = machine.options.actors[src.type];
1024
+
1025
+ if (!behaviorImpl) {
1026
+ return {
1027
+ type: type,
1028
+ params: params
1029
+ };
1030
+ }
1031
+
1032
+ var behavior = typeof behaviorImpl === 'function' ? behaviorImpl(context, _event.data, {
1033
+ id: id,
1034
+ data: data && mapContext(data, context, _event),
1035
+ src: src,
1036
+ _event: _event,
1037
+ meta: meta
1038
+ }) : behaviorImpl;
1039
+ return {
1040
+ type: type,
1041
+ params: _objectSpread2(_objectSpread2({}, params), {}, {
1042
+ id: params.id,
1043
+ src: params.src,
1044
+ ref: new ObservableActorRef(behavior, id),
1045
+ meta: meta
1046
+ })
1047
+ };
1048
+ });
1049
+ }
1050
+
1051
+ function stateIn(stateValue) {
1052
+ return {
1053
+ type: 'xstate.guard:in',
1054
+ params: {
1055
+ stateValue: stateValue
1056
+ },
1057
+ predicate: function predicate(_, __, _ref) {
1058
+ var state = _ref.state;
1059
+
1060
+ if (isString(stateValue) && isStateId(stateValue)) {
1061
+ return state.configuration.some(function (sn) {
1062
+ return sn.id === stateValue.slice(1);
1063
+ });
1064
+ }
1065
+
1066
+ return state.matches(stateValue);
1067
+ }
1068
+ };
1069
+ }
1070
+ function not(guard) {
1071
+ return {
1072
+ type: 'xstate.boolean',
1073
+ params: {
1074
+ op: 'not'
1075
+ },
1076
+ children: [toGuardDefinition(guard)],
1077
+ predicate: function predicate(ctx, _, meta) {
1078
+ return !meta.evaluate(meta.guard.children[0], ctx, meta._event, meta.state, meta.state.machine);
1079
+ }
1080
+ };
1081
+ }
1082
+ function and(guards) {
1083
+ return {
1084
+ type: 'xstate.boolean',
1085
+ params: {
1086
+ op: 'and'
1087
+ },
1088
+ children: guards.map(function (guard) {
1089
+ return toGuardDefinition(guard);
1090
+ }),
1091
+ predicate: function predicate(ctx, _, meta) {
1092
+ return meta.guard.children.every(function (childGuard) {
1093
+ return meta.evaluate(childGuard, ctx, meta._event, meta.state, meta.state.machine);
1094
+ });
1095
+ }
1096
+ };
1097
+ }
1098
+ function or(guards) {
1099
+ return {
1100
+ type: 'xstate.boolean',
1101
+ params: {
1102
+ op: 'or'
1103
+ },
1104
+ children: guards.map(function (guard) {
1105
+ return toGuardDefinition(guard);
1106
+ }),
1107
+ predicate: function predicate(ctx, _, meta) {
1108
+ return meta.guard.children.some(function (childGuard) {
1109
+ return meta.evaluate(childGuard, ctx, meta._event, meta.state, meta.state.machine);
1110
+ });
1111
+ }
1112
+ };
1113
+ }
1114
+ function evaluateGuard(guard, context, _event, state, machine) {
1115
+ var _machine$options$guar, _machine$options, _machine$options$guar2;
1116
+
1117
+ var guardMeta = {
1118
+ state: state,
1119
+ guard: guard,
1120
+ _event: _event,
1121
+ evaluate: evaluateGuard
1122
+ };
1123
+ var predicate = (_machine$options$guar = machine === null || machine === void 0 ? void 0 : (_machine$options = machine.options) === null || _machine$options === void 0 ? void 0 : (_machine$options$guar2 = _machine$options.guards) === null || _machine$options$guar2 === void 0 ? void 0 : _machine$options$guar2[guard.type]) !== null && _machine$options$guar !== void 0 ? _machine$options$guar : guard.predicate;
1124
+
1125
+ if (!predicate) {
1126
+ throw new Error("Guard '".concat(guard.type, "' is not implemented.'."));
1127
+ }
1128
+
1129
+ return predicate(context, _event.data, guardMeta);
1130
+ }
1131
+ function toGuardDefinition(guardConfig, getPredicate) {
1132
+ var _guardConfig$children;
1133
+
1134
+ if (isString(guardConfig)) {
1135
+ return {
1136
+ type: guardConfig,
1137
+ predicate: (getPredicate === null || getPredicate === void 0 ? void 0 : getPredicate(guardConfig)) || undefined,
1138
+ params: {
1139
+ type: guardConfig
1140
+ }
1141
+ };
1142
+ }
1143
+
1144
+ if (isFunction(guardConfig)) {
1145
+ return {
1146
+ type: guardConfig.name,
1147
+ predicate: guardConfig,
1148
+ params: {
1149
+ type: guardConfig.name,
1150
+ name: guardConfig.name
1151
+ }
1152
+ };
1153
+ }
1154
+
1155
+ return {
1156
+ type: guardConfig.type,
1157
+ params: guardConfig.params || guardConfig,
1158
+ children: (_guardConfig$children = guardConfig.children) === null || _guardConfig$children === void 0 ? void 0 : _guardConfig$children.map(function (childGuard) {
1159
+ return toGuardDefinition(childGuard, getPredicate);
1160
+ }),
1161
+ predicate: (getPredicate === null || getPredicate === void 0 ? void 0 : getPredicate(guardConfig.type)) || guardConfig.predicate
1162
+ };
1163
+ }
1164
+
1165
+ var isAtomicStateNode = function isAtomicStateNode(stateNode) {
1166
+ return stateNode.type === 'atomic' || stateNode.type === 'final';
1167
+ };
1168
+ function getChildren(stateNode) {
1169
+ return Object.keys(stateNode.states).map(function (key) {
1170
+ return stateNode.states[key];
1171
+ }); // .filter((sn) => sn.type !== 'history');
1172
+ }
1173
+ function getProperAncestors(stateNode, toStateNode) {
1174
+ var ancestors = []; // add all ancestors
1175
+
1176
+ var m = stateNode.parent;
1177
+
1178
+ while (m && m !== toStateNode) {
1179
+ ancestors.push(m);
1180
+ m = m.parent;
1181
+ }
1182
+
1183
+ return ancestors;
1184
+ }
1185
+ function getConfiguration(stateNodes) {
1186
+ var configuration = new Set(stateNodes);
1187
+ var mutConfiguration = new Set(stateNodes);
1188
+ var adjList = getAdjList(mutConfiguration); // add descendants
1189
+
1190
+ var _iterator = _createForOfIteratorHelper(configuration),
1191
+ _step;
1192
+
1193
+ try {
1194
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
1195
+ var s = _step.value;
1196
+
1197
+ // if previously active, add existing child nodes
1198
+ if (s.type === 'compound' && (!adjList.get(s) || !adjList.get(s).length)) {
1199
+ getInitialStateNodes(s).forEach(function (sn) {
1200
+ return mutConfiguration.add(sn);
1201
+ });
1202
+ } else {
1203
+ if (s.type === 'parallel') {
1204
+ var _iterator3 = _createForOfIteratorHelper(getChildren(s)),
1205
+ _step3;
1206
+
1207
+ try {
1208
+ for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
1209
+ var child = _step3.value;
1210
+
1211
+ if (child.type === 'history') {
1212
+ continue;
1213
+ }
1214
+
1215
+ if (!mutConfiguration.has(child)) {
1216
+ getInitialStateNodes(child).forEach(function (sn) {
1217
+ return mutConfiguration.add(sn);
1218
+ });
1219
+ }
1220
+ }
1221
+ } catch (err) {
1222
+ _iterator3.e(err);
1223
+ } finally {
1224
+ _iterator3.f();
1225
+ }
1226
+ }
1227
+ }
1228
+ } // add all ancestors
1229
+
1230
+ } catch (err) {
1231
+ _iterator.e(err);
1232
+ } finally {
1233
+ _iterator.f();
1234
+ }
1235
+
1236
+ var _iterator2 = _createForOfIteratorHelper(mutConfiguration),
1237
+ _step2;
1238
+
1239
+ try {
1240
+ for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
1241
+ var _s = _step2.value;
1242
+ var m = _s.parent;
1243
+
1244
+ while (m) {
1245
+ mutConfiguration.add(m);
1246
+ m = m.parent;
1247
+ }
1248
+ }
1249
+ } catch (err) {
1250
+ _iterator2.e(err);
1251
+ } finally {
1252
+ _iterator2.f();
1253
+ }
1254
+
1255
+ return mutConfiguration;
1256
+ }
1257
+
1258
+ function getValueFromAdj(baseNode, adjList) {
1259
+ var childStateNodes = adjList.get(baseNode);
1260
+
1261
+ if (!childStateNodes) {
1262
+ return {}; // todo: fix?
1263
+ }
1264
+
1265
+ if (baseNode.type === 'compound') {
1266
+ var childStateNode = childStateNodes[0];
1267
+
1268
+ if (childStateNode) {
1269
+ if (isAtomicStateNode(childStateNode)) {
1270
+ return childStateNode.key;
1271
+ }
1272
+ } else {
1273
+ return {};
1274
+ }
1275
+ }
1276
+
1277
+ var stateValue = {};
1278
+ childStateNodes.forEach(function (csn) {
1279
+ stateValue[csn.key] = getValueFromAdj(csn, adjList);
1280
+ });
1281
+ return stateValue;
1282
+ }
1283
+
1284
+ function getAdjList(configuration) {
1285
+ var adjList = new Map();
1286
+
1287
+ var _iterator4 = _createForOfIteratorHelper(configuration),
1288
+ _step4;
1289
+
1290
+ try {
1291
+ for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
1292
+ var s = _step4.value;
1293
+
1294
+ if (!adjList.has(s)) {
1295
+ adjList.set(s, []);
1296
+ }
1297
+
1298
+ if (s.parent) {
1299
+ if (!adjList.has(s.parent)) {
1300
+ adjList.set(s.parent, []);
1301
+ }
1302
+
1303
+ adjList.get(s.parent).push(s);
1304
+ }
1305
+ }
1306
+ } catch (err) {
1307
+ _iterator4.e(err);
1308
+ } finally {
1309
+ _iterator4.f();
1310
+ }
1311
+
1312
+ return adjList;
1313
+ }
1314
+ function getStateValue(rootNode, configuration) {
1315
+ var config = getConfiguration(configuration);
1316
+ return getValueFromAdj(rootNode, getAdjList(config));
1317
+ }
1318
+ function has(iterable, item) {
1319
+ if (Array.isArray(iterable)) {
1320
+ return iterable.some(function (member) {
1321
+ return member === item;
1322
+ });
1323
+ }
1324
+
1325
+ if (iterable instanceof Set) {
1326
+ return iterable.has(item);
1327
+ }
1328
+
1329
+ return false; // TODO: fix
1330
+ }
1331
+ function nextEvents(configuration) {
1332
+ return _toConsumableArray(new Set(flatten(_toConsumableArray(configuration.map(function (sn) {
1333
+ return sn.ownEvents;
1334
+ })))));
1335
+ }
1336
+ function isInFinalState(configuration) {
1337
+ var stateNode = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : configuration[0].machine.root;
1338
+
1339
+ if (stateNode.type === 'compound') {
1340
+ return getChildren(stateNode).some(function (s) {
1341
+ return s.type === 'final' && has(configuration, s);
1342
+ });
1343
+ }
1344
+
1345
+ if (stateNode.type === 'parallel') {
1346
+ return getChildren(stateNode).every(function (sn) {
1347
+ return isInFinalState(configuration, sn);
1348
+ });
1349
+ }
1350
+
1351
+ return false;
1352
+ }
1353
+ var isStateId = function isStateId(str) {
1354
+ return str[0] === STATE_IDENTIFIER;
1355
+ };
1356
+ function getCandidates(stateNode, receivedEventType) {
1357
+ var partialMatch = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
1358
+ var candidates = stateNode.transitions.filter(function (transition) {
1359
+ var eventType = transition.eventType; // First, check the trivial case: event names are exactly equal
1360
+
1361
+ if (eventType === receivedEventType) {
1362
+ return true;
1363
+ } // Then, check if transition is a wildcard transition,
1364
+ // which matches any non-transient events
1365
+
1366
+
1367
+ if (eventType === WILDCARD) {
1368
+ return true;
1369
+ }
1370
+
1371
+ if (!partialMatch && !eventType.endsWith('.*')) {
1372
+ return false;
1373
+ }
1374
+
1375
+ var partialEventTokens = eventType.split('.');
1376
+ var eventTokens = receivedEventType.split('.');
1377
+
1378
+ for (var tokenIndex = 0; tokenIndex < partialEventTokens.length; tokenIndex++) {
1379
+ var partialEventToken = partialEventTokens[tokenIndex];
1380
+ var eventToken = eventTokens[tokenIndex];
1381
+
1382
+ if (partialEventToken === '*') {
1383
+ var isLastToken = tokenIndex === partialEventTokens.length - 1;
1384
+
1385
+ return isLastToken;
1386
+ }
1387
+
1388
+ if (partialEventToken !== eventToken) {
1389
+ return false;
1390
+ }
1391
+ }
1392
+
1393
+ return true;
1394
+ });
1395
+ return candidates;
1396
+ }
1397
+ /**
1398
+ * All delayed transitions from the config.
1399
+ */
1400
+
1401
+ function getDelayedTransitions(stateNode) {
1402
+ var afterConfig = stateNode.config.after;
1403
+
1404
+ if (!afterConfig) {
1405
+ return [];
1406
+ }
1407
+
1408
+ var mutateEntryExit = function mutateEntryExit(delay, i) {
1409
+ var delayRef = isFunction(delay) ? "".concat(stateNode.id, ":delay[").concat(i, "]") : delay;
1410
+ var eventType = after$1(delayRef, stateNode.id);
1411
+ stateNode.entry.push(send$1(eventType, {
1412
+ delay: delay
1413
+ }));
1414
+ stateNode.exit.push(cancel$1(eventType));
1415
+ return eventType;
1416
+ };
1417
+
1418
+ var delayedTransitions = isArray(afterConfig) ? afterConfig.map(function (transition, i) {
1419
+ var eventType = mutateEntryExit(transition.delay, i);
1420
+ return _objectSpread2(_objectSpread2({}, transition), {}, {
1421
+ event: eventType
1422
+ });
1423
+ }) : flatten(Object.keys(afterConfig).map(function (delay, i) {
1424
+ var configTransition = afterConfig[delay];
1425
+ var resolvedTransition = isString(configTransition) ? {
1426
+ target: configTransition
1427
+ } : configTransition;
1428
+ var resolvedDelay = !isNaN(+delay) ? +delay : delay;
1429
+ var eventType = mutateEntryExit(resolvedDelay, i);
1430
+ return toArray(resolvedTransition).map(function (transition) {
1431
+ return _objectSpread2(_objectSpread2({}, transition), {}, {
1432
+ event: eventType,
1433
+ delay: resolvedDelay
1434
+ });
1435
+ });
1436
+ }));
1437
+ return delayedTransitions.map(function (delayedTransition) {
1438
+ var delay = delayedTransition.delay;
1439
+ return _objectSpread2(_objectSpread2({}, formatTransition(stateNode, delayedTransition)), {}, {
1440
+ delay: delay
1441
+ });
1442
+ });
1443
+ }
1444
+ function formatTransition(stateNode, transitionConfig) {
1445
+ var normalizedTarget = normalizeTarget(transitionConfig.target);
1446
+ var internal = 'internal' in transitionConfig ? transitionConfig.internal : normalizedTarget ? normalizedTarget.some(function (_target) {
1447
+ return isString(_target) && _target[0] === stateNode.machine.delimiter;
1448
+ }) : true;
1449
+ var guards = stateNode.machine.options.guards;
1450
+ var target = resolveTarget(stateNode, normalizedTarget);
1451
+
1452
+ var transition = _objectSpread2(_objectSpread2({}, transitionConfig), {}, {
1453
+ actions: toActionObjects(toArray(transitionConfig.actions)),
1454
+ guard: transitionConfig.guard ? toGuardDefinition(transitionConfig.guard, function (guardType) {
1455
+ return guards[guardType];
1456
+ }) : undefined,
1457
+ target: target,
1458
+ source: stateNode,
1459
+ internal: internal,
1460
+ eventType: transitionConfig.event,
1461
+ toJSON: function toJSON() {
1462
+ return _objectSpread2(_objectSpread2({}, transition), {}, {
1463
+ source: "#".concat(stateNode.id),
1464
+ target: target ? target.map(function (t) {
1465
+ return "#".concat(t.id);
1466
+ }) : undefined
1467
+ });
1468
+ }
1469
+ });
1470
+
1471
+ return transition;
1472
+ }
1473
+ function formatTransitions(stateNode) {
1474
+ var transitionConfigs = [];
1475
+
1476
+ if (Array.isArray(stateNode.config.on)) {
1477
+ transitionConfigs.push.apply(transitionConfigs, _toConsumableArray(stateNode.config.on));
1478
+ } else if (stateNode.config.on) {
1479
+ var _stateNode$config$on = stateNode.config.on,
1480
+ _stateNode$config$on$ = _stateNode$config$on[WILDCARD],
1481
+ wildcardConfigs = _stateNode$config$on$ === void 0 ? [] : _stateNode$config$on$,
1482
+ namedTransitionConfigs = _objectWithoutProperties(_stateNode$config$on, [WILDCARD].map(_toPropertyKey));
1483
+
1484
+ Object.keys(namedTransitionConfigs).forEach(function (eventType) {
1485
+ if (eventType === NULL_EVENT) {
1486
+ throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');
1487
+ }
1488
+
1489
+ var eventTransitionConfigs = toTransitionConfigArray(eventType, namedTransitionConfigs[eventType]);
1490
+ transitionConfigs.push.apply(transitionConfigs, _toConsumableArray(eventTransitionConfigs)); // TODO: add dev-mode validation for unreachable transitions
1491
+ });
1492
+ transitionConfigs.push.apply(transitionConfigs, _toConsumableArray(toTransitionConfigArray(WILDCARD, wildcardConfigs)));
1493
+ }
1494
+
1495
+ var doneConfig = stateNode.config.onDone ? toTransitionConfigArray(String(done(stateNode.id)), stateNode.config.onDone) : [];
1496
+ var invokeConfig = flatten(stateNode.invoke.map(function (invokeDef) {
1497
+ var settleTransitions = [];
1498
+
1499
+ if (invokeDef.onDone) {
1500
+ settleTransitions.push.apply(settleTransitions, _toConsumableArray(toTransitionConfigArray("done.invoke.".concat(invokeDef.id), invokeDef.onDone)));
1501
+ }
1502
+
1503
+ if (invokeDef.onError) {
1504
+ settleTransitions.push.apply(settleTransitions, _toConsumableArray(toTransitionConfigArray("error.platform.".concat(invokeDef.id), invokeDef.onError)));
1505
+ }
1506
+
1507
+ if (invokeDef.onSnapshot) {
1508
+ settleTransitions.push.apply(settleTransitions, _toConsumableArray(toTransitionConfigArray("xstate.snapshot.".concat(invokeDef.id), invokeDef.onSnapshot)));
1509
+ }
1510
+
1511
+ return settleTransitions;
1512
+ }));
1513
+ var delayedTransitions = stateNode.after;
1514
+ var formattedTransitions = flatten([].concat(_toConsumableArray(doneConfig), _toConsumableArray(invokeConfig), transitionConfigs).map(function (transitionConfig) {
1515
+ return toArray(transitionConfig).map(function (transition) {
1516
+ return formatTransition(stateNode, transition);
1517
+ });
1518
+ }));
1519
+
1520
+ var _iterator5 = _createForOfIteratorHelper(delayedTransitions),
1521
+ _step5;
1522
+
1523
+ try {
1524
+ for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
1525
+ var delayedTransition = _step5.value;
1526
+ formattedTransitions.push(delayedTransition);
1527
+ }
1528
+ } catch (err) {
1529
+ _iterator5.e(err);
1530
+ } finally {
1531
+ _iterator5.f();
1532
+ }
1533
+
1534
+ return formattedTransitions;
1535
+ }
1536
+ function formatInitialTransition(stateNode, _target) {
1537
+ if (isString(_target) || isArray(_target)) {
1538
+ var targets = toArray(_target).map(function (t) {
1539
+ // Resolve state string keys (which represent children)
1540
+ // to their state node
1541
+ var descStateNode = isString(t) ? isStateId(t) ? stateNode.machine.getStateNodeById(t) : stateNode.states[t] : t;
1542
+
1543
+ if (!descStateNode) {
1544
+ throw new Error("Initial state node \"".concat(t, "\" not found on parent state node #").concat(stateNode.id));
1545
+ }
1546
+
1547
+ if (!isDescendant(descStateNode, stateNode)) {
1548
+ throw new Error("Invalid initial target: state node #".concat(descStateNode.id, " is not a descendant of #").concat(stateNode.id));
1549
+ }
1550
+
1551
+ return descStateNode;
1552
+ });
1553
+ var resolvedTarget = resolveTarget(stateNode, targets);
1554
+ var transition = {
1555
+ source: stateNode,
1556
+ actions: [],
1557
+ eventType: null,
1558
+ target: resolvedTarget,
1559
+ toJSON: function toJSON() {
1560
+ return _objectSpread2(_objectSpread2({}, transition), {}, {
1561
+ source: "#".concat(stateNode.id),
1562
+ target: resolvedTarget ? resolvedTarget.map(function (t) {
1563
+ return "#".concat(t.id);
1564
+ }) : undefined
1565
+ });
1566
+ }
1567
+ };
1568
+ return transition;
1569
+ }
1570
+
1571
+ return formatTransition(stateNode, {
1572
+ target: toArray(_target.target).map(function (t) {
1573
+ if (isString(t)) {
1574
+ return isStateId(t) ? t : "".concat(stateNode.machine.delimiter).concat(t);
1575
+ }
1576
+
1577
+ return t;
1578
+ }),
1579
+ actions: _target.actions,
1580
+ event: null
1581
+ });
1582
+ }
1583
+ function resolveTarget(stateNode, _target) {
1584
+ if (_target === undefined) {
1585
+ // an undefined target signals that the state node should not transition from that state when receiving that event
1586
+ return undefined;
1587
+ }
1588
+
1589
+ return _target.map(function (target) {
1590
+ if (!isString(target)) {
1591
+ return target;
1592
+ }
1593
+
1594
+ var isInternalTarget = target[0] === stateNode.machine.delimiter; // If internal target is defined on machine,
1595
+ // do not include machine key on target
1596
+
1597
+ if (isInternalTarget && !stateNode.parent) {
1598
+ return getStateNodeByPath(stateNode, target.slice(1));
1599
+ }
1600
+
1601
+ var resolvedTarget = isInternalTarget ? stateNode.key + target : target;
1602
+
1603
+ if (stateNode.parent) {
1604
+ try {
1605
+ var targetStateNode = getStateNodeByPath(stateNode.parent, resolvedTarget);
1606
+ return targetStateNode;
1607
+ } catch (err) {
1608
+ throw new Error("Invalid transition definition for state node '".concat(stateNode.id, "':\n").concat(err.message));
1609
+ }
1610
+ } else {
1611
+ return getStateNodeByPath(stateNode, resolvedTarget);
1612
+ }
1613
+ });
1614
+ }
1615
+
1616
+ function resolveHistoryTarget(stateNode) {
1617
+ var normalizedTarget = normalizeTarget(stateNode.target);
1618
+
1619
+ if (!normalizedTarget) {
1620
+ return stateNode.parent.initial.target;
1621
+ }
1622
+
1623
+ return normalizedTarget.map(function (t) {
1624
+ return typeof t === 'string' ? getStateNodeByPath(stateNode, t) : t;
1625
+ });
1626
+ }
1627
+
1628
+ function isHistoryNode(stateNode) {
1629
+ return stateNode.type === 'history';
1630
+ }
1631
+
1632
+ function getInitialStateNodes(stateNode) {
1633
+ var transitions = [{
1634
+ target: [stateNode],
1635
+ source: stateNode,
1636
+ actions: [],
1637
+ eventType: 'init',
1638
+ toJSON: null // TODO: fix
1639
+
1640
+ }];
1641
+ var mutStatesToEnter = new Set();
1642
+ var mutStatesForDefaultEntry = new Set();
1643
+ computeEntrySet(transitions, State.from({}), mutStatesToEnter, mutStatesForDefaultEntry);
1644
+ return _toConsumableArray(mutStatesToEnter);
1645
+ }
1646
+ /**
1647
+ * Returns the child state node from its relative `stateKey`, or throws.
1648
+ */
1649
+
1650
+ function getStateNode(stateNode, stateKey) {
1651
+ if (isStateId(stateKey)) {
1652
+ return stateNode.machine.getStateNodeById(stateKey);
1653
+ }
1654
+
1655
+ if (!stateNode.states) {
1656
+ throw new Error("Unable to retrieve child state '".concat(stateKey, "' from '").concat(stateNode.id, "'; no child states exist."));
1657
+ }
1658
+
1659
+ var result = stateNode.states[stateKey];
1660
+
1661
+ if (!result) {
1662
+ throw new Error("Child state '".concat(stateKey, "' does not exist on '").concat(stateNode.id, "'"));
1663
+ }
1664
+
1665
+ return result;
1666
+ }
1667
+ /**
1668
+ * Returns the relative state node from the given `statePath`, or throws.
1669
+ *
1670
+ * @param statePath The string or string array relative path to the state node.
1671
+ */
1672
+
1673
+ function getStateNodeByPath(stateNode, statePath) {
1674
+ if (typeof statePath === 'string' && isStateId(statePath)) {
1675
+ try {
1676
+ return stateNode.machine.getStateNodeById(statePath);
1677
+ } catch (e) {// try individual paths
1678
+ // throw e;
1679
+ }
1680
+ }
1681
+
1682
+ var arrayStatePath = toStatePath(statePath, stateNode.machine.delimiter).slice();
1683
+ var currentStateNode = stateNode;
1684
+
1685
+ while (arrayStatePath.length) {
1686
+ var key = arrayStatePath.shift();
1687
+
1688
+ if (!key.length) {
1689
+ break;
1690
+ }
1691
+
1692
+ currentStateNode = getStateNode(currentStateNode, key);
1693
+ }
1694
+
1695
+ return currentStateNode;
1696
+ }
1697
+ /**
1698
+ * Returns the state nodes represented by the current state value.
1699
+ *
1700
+ * @param state The state value or State instance
1701
+ */
1702
+
1703
+
1704
+ function getStateNodes(stateNode, state) {
1705
+ var stateValue = state instanceof State ? state.value : toStateValue(state, stateNode.machine.delimiter);
1706
+
1707
+ if (isString(stateValue)) {
1708
+ return [stateNode.states[stateValue]];
1709
+ }
1710
+
1711
+ var childStateKeys = Object.keys(stateValue);
1712
+ var childStateNodes = childStateKeys.map(function (subStateKey) {
1713
+ return getStateNode(stateNode, subStateKey);
1714
+ }).filter(Boolean);
1715
+ return childStateNodes.concat(childStateKeys.reduce(function (allSubStateNodes, subStateKey) {
1716
+ var subStateNode = getStateNode(stateNode, subStateKey);
1717
+
1718
+ if (!subStateNode) {
1719
+ return allSubStateNodes;
1720
+ }
1721
+
1722
+ var subStateNodes = getStateNodes(subStateNode, stateValue[subStateKey]);
1723
+ return allSubStateNodes.concat(subStateNodes);
1724
+ }, []));
1725
+ }
1726
+ function transitionLeafNode(stateNode, stateValue, state, _event) {
1727
+ var childStateNode = getStateNode(stateNode, stateValue);
1728
+ var next = childStateNode.next(state, _event);
1729
+
1730
+ if (!next || !next.length) {
1731
+ return stateNode.next(state, _event);
1732
+ }
1733
+
1734
+ return next;
1735
+ }
1736
+ function transitionCompoundNode(stateNode, stateValue, state, _event) {
1737
+ var subStateKeys = Object.keys(stateValue);
1738
+ var childStateNode = getStateNode(stateNode, subStateKeys[0]);
1739
+ var next = transitionNode(childStateNode, stateValue[subStateKeys[0]], state, _event);
1740
+
1741
+ if (!next || !next.length) {
1742
+ return stateNode.next(state, _event);
1743
+ }
1744
+
1745
+ return next;
1746
+ }
1747
+ function transitionParallelNode(stateNode, stateValue, state, _event) {
1748
+ var transitionMap = {};
1749
+
1750
+ for (var _i = 0, _Object$keys = Object.keys(stateValue); _i < _Object$keys.length; _i++) {
1751
+ var subStateKey = _Object$keys[_i];
1752
+ var subStateValue = stateValue[subStateKey];
1753
+
1754
+ if (!subStateValue) {
1755
+ continue;
1756
+ }
1757
+
1758
+ var subStateNode = getStateNode(stateNode, subStateKey);
1759
+ var nextStateNode = transitionNode(subStateNode, subStateValue, state, _event);
1760
+
1761
+ if (nextStateNode) {
1762
+ transitionMap[subStateKey] = nextStateNode;
1763
+ }
1764
+ }
1765
+
1766
+ var transitions = Object.keys(transitionMap).map(function (key) {
1767
+ return transitionMap[key];
1768
+ });
1769
+ var enabledTransitions = flatten(transitions);
1770
+ var willTransition = transitions.some(function (st) {
1771
+ return st.length > 0;
1772
+ });
1773
+
1774
+ if (!willTransition) {
1775
+ return stateNode.next(state, _event);
1776
+ }
1777
+
1778
+ return enabledTransitions;
1779
+ }
1780
+ function transitionNode(stateNode, stateValue, state, _event) {
1781
+ // leaf node
1782
+ if (isString(stateValue)) {
1783
+ return transitionLeafNode(stateNode, stateValue, state, _event);
1784
+ } // compound node
1785
+
1786
+
1787
+ if (Object.keys(stateValue).length === 1) {
1788
+ return transitionCompoundNode(stateNode, stateValue, state, _event);
1789
+ } // parallel node
1790
+
1791
+
1792
+ return transitionParallelNode(stateNode, stateValue, state, _event);
1793
+ }
1794
+
1795
+ function getHistoryNodes(stateNode) {
1796
+ return getChildren(stateNode).filter(function (sn) {
1797
+ return sn.type === 'history';
1798
+ });
1799
+ }
1800
+
1801
+ function isDescendant(childStateNode, parentStateNode) {
1802
+ var marker = childStateNode;
1803
+
1804
+ while (marker.parent && marker.parent !== parentStateNode) {
1805
+ marker = marker.parent;
1806
+ }
1807
+
1808
+ return marker.parent === parentStateNode;
1809
+ }
1810
+
1811
+ function getPathFromRootToNode(stateNode) {
1812
+ var path = [];
1813
+ var marker = stateNode.parent;
1814
+
1815
+ while (marker) {
1816
+ path.unshift(marker);
1817
+ marker = marker.parent;
1818
+ }
1819
+
1820
+ return path;
1821
+ }
1822
+
1823
+ function hasIntersection(s1, s2) {
1824
+ var set1 = new Set(s1);
1825
+ var set2 = new Set(s2);
1826
+
1827
+ var _iterator6 = _createForOfIteratorHelper(set1),
1828
+ _step6;
1829
+
1830
+ try {
1831
+ for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
1832
+ var item = _step6.value;
1833
+
1834
+ if (set2.has(item)) {
1835
+ return true;
1836
+ }
1837
+ }
1838
+ } catch (err) {
1839
+ _iterator6.e(err);
1840
+ } finally {
1841
+ _iterator6.f();
1842
+ }
1843
+
1844
+ var _iterator7 = _createForOfIteratorHelper(set2),
1845
+ _step7;
1846
+
1847
+ try {
1848
+ for (_iterator7.s(); !(_step7 = _iterator7.n()).done;) {
1849
+ var _item = _step7.value;
1850
+
1851
+ if (set1.has(_item)) {
1852
+ return true;
1853
+ }
1854
+ }
1855
+ } catch (err) {
1856
+ _iterator7.e(err);
1857
+ } finally {
1858
+ _iterator7.f();
1859
+ }
1860
+
1861
+ return false;
1862
+ }
1863
+
1864
+ function removeConflictingTransitions(enabledTransitions, configuration, state) {
1865
+ var filteredTransitions = new Set();
1866
+
1867
+ var _iterator8 = _createForOfIteratorHelper(enabledTransitions),
1868
+ _step8;
1869
+
1870
+ try {
1871
+ for (_iterator8.s(); !(_step8 = _iterator8.n()).done;) {
1872
+ var t1 = _step8.value;
1873
+ var t1Preempted = false;
1874
+ var transitionsToRemove = new Set();
1875
+
1876
+ var _iterator9 = _createForOfIteratorHelper(filteredTransitions),
1877
+ _step9;
1878
+
1879
+ try {
1880
+ for (_iterator9.s(); !(_step9 = _iterator9.n()).done;) {
1881
+ var t2 = _step9.value;
1882
+
1883
+ if (hasIntersection(computeExitSet([t1], configuration, state), computeExitSet([t2], configuration, state))) {
1884
+ if (isDescendant(t1.source, t2.source)) {
1885
+ transitionsToRemove.add(t2);
1886
+ } else {
1887
+ t1Preempted = true;
1888
+ break;
1889
+ }
1890
+ }
1891
+ }
1892
+ } catch (err) {
1893
+ _iterator9.e(err);
1894
+ } finally {
1895
+ _iterator9.f();
1896
+ }
1897
+
1898
+ if (!t1Preempted) {
1899
+ var _iterator10 = _createForOfIteratorHelper(transitionsToRemove),
1900
+ _step10;
1901
+
1902
+ try {
1903
+ for (_iterator10.s(); !(_step10 = _iterator10.n()).done;) {
1904
+ var t3 = _step10.value;
1905
+ filteredTransitions["delete"](t3);
1906
+ }
1907
+ } catch (err) {
1908
+ _iterator10.e(err);
1909
+ } finally {
1910
+ _iterator10.f();
1911
+ }
1912
+
1913
+ filteredTransitions.add(t1);
1914
+ }
1915
+ }
1916
+ } catch (err) {
1917
+ _iterator8.e(err);
1918
+ } finally {
1919
+ _iterator8.f();
1920
+ }
1921
+
1922
+ return Array.from(filteredTransitions);
1923
+ }
1924
+
1925
+ function findLCCA(stateNodes) {
1926
+ var _stateNodes = _slicedToArray(stateNodes, 1),
1927
+ head = _stateNodes[0];
1928
+
1929
+ var current = getPathFromRootToNode(head);
1930
+ var candidates = [];
1931
+ stateNodes.forEach(function (stateNode) {
1932
+ var path = getPathFromRootToNode(stateNode);
1933
+ candidates = current.filter(function (sn) {
1934
+ return path.includes(sn);
1935
+ });
1936
+ current = candidates;
1937
+ candidates = [];
1938
+ });
1939
+ return current[current.length - 1];
1940
+ }
1941
+
1942
+ function getEffectiveTargetStates(transition, state) {
1943
+ if (!transition.target) {
1944
+ return [];
1945
+ }
1946
+
1947
+ var targets = new Set();
1948
+
1949
+ var _iterator11 = _createForOfIteratorHelper(transition.target),
1950
+ _step11;
1951
+
1952
+ try {
1953
+ for (_iterator11.s(); !(_step11 = _iterator11.n()).done;) {
1954
+ var s = _step11.value;
1955
+
1956
+ if (isHistoryNode(s)) {
1957
+ if (state.historyValue[s.id]) {
1958
+ state.historyValue[s.id].forEach(function (node) {
1959
+ targets.add(node);
1960
+ });
1961
+ } else {
1962
+ getEffectiveTargetStates({
1963
+ target: resolveHistoryTarget(s)
1964
+ }, state).forEach(function (node) {
1965
+ targets.add(node);
1966
+ });
1967
+ }
1968
+ } else {
1969
+ targets.add(s);
1970
+ }
1971
+ }
1972
+ } catch (err) {
1973
+ _iterator11.e(err);
1974
+ } finally {
1975
+ _iterator11.f();
1976
+ }
1977
+
1978
+ return _toConsumableArray(targets);
1979
+ }
1980
+
1981
+ function getTransitionDomain(transition, state) {
1982
+ var targetStates = getEffectiveTargetStates(transition, state);
1983
+
1984
+ if (!targetStates) {
1985
+ return null;
1986
+ }
1987
+
1988
+ if (transition.internal && transition.source.type === 'compound' && targetStates.every(function (targetStateNode) {
1989
+ return isDescendant(targetStateNode, transition.source);
1990
+ })) {
1991
+ return transition.source;
1992
+ }
1993
+
1994
+ var lcca = findLCCA(targetStates.concat(transition.source));
1995
+ return lcca;
1996
+ }
1997
+
1998
+ function exitStates(transitions, mutConfiguration, state) {
1999
+ var statesToExit = computeExitSet(transitions, mutConfiguration, state);
2000
+ var actions = [];
2001
+ statesToExit.forEach(function (stateNode) {
2002
+ actions.push.apply(actions, _toConsumableArray(stateNode.invoke.map(function (def) {
2003
+ return stop$1(def.id);
2004
+ })));
2005
+ });
2006
+ statesToExit.sort(function (a, b) {
2007
+ return b.order - a.order;
2008
+ });
2009
+ var historyValue = resolveHistoryValue(state, statesToExit);
2010
+
2011
+ var _iterator12 = _createForOfIteratorHelper(statesToExit),
2012
+ _step12;
2013
+
2014
+ try {
2015
+ for (_iterator12.s(); !(_step12 = _iterator12.n()).done;) {
2016
+ var s = _step12.value;
2017
+ actions.push.apply(actions, _toConsumableArray(flatten(s.exit)));
2018
+ mutConfiguration["delete"](s);
2019
+ }
2020
+ } catch (err) {
2021
+ _iterator12.e(err);
2022
+ } finally {
2023
+ _iterator12.f();
2024
+ }
2025
+
2026
+ return {
2027
+ exitSet: statesToExit,
2028
+ historyValue: historyValue,
2029
+ actions: actions,
2030
+ configuration: mutConfiguration
2031
+ };
2032
+ }
2033
+
2034
+ function enterStates(transitions, mutConfiguration, state) {
2035
+ var statesToInvoke = new Set();
2036
+ var internalQueue = [];
2037
+ var actions = [];
2038
+ var mutStatesToEnter = new Set();
2039
+ var mutStatesForDefaultEntry = new Set();
2040
+ computeEntrySet(transitions, state, mutStatesToEnter, mutStatesForDefaultEntry);
2041
+
2042
+ var _iterator13 = _createForOfIteratorHelper(_toConsumableArray(mutStatesToEnter).sort(function (a, b) {
2043
+ return a.order - b.order;
2044
+ })),
2045
+ _step13;
2046
+
2047
+ try {
2048
+ for (_iterator13.s(); !(_step13 = _iterator13.n()).done;) {
2049
+ var stateNodeToEnter = _step13.value;
2050
+ mutConfiguration.add(stateNodeToEnter);
2051
+ statesToInvoke.add(stateNodeToEnter); // Add entry actions
2052
+
2053
+ actions.push.apply(actions, _toConsumableArray(stateNodeToEnter.entry));
2054
+
2055
+ if (mutStatesForDefaultEntry.has(stateNodeToEnter)) {
2056
+ mutStatesForDefaultEntry.forEach(function (stateNode) {
2057
+ actions.push.apply(actions, _toConsumableArray(stateNode.initial.actions));
2058
+ });
2059
+ } // if (defaultHistoryContent[s.id]) {
2060
+ // actions.push(...defaultHistoryContent[s.id])
2061
+ // }
2062
+
2063
+
2064
+ if (stateNodeToEnter.type === 'final') {
2065
+ var parent = stateNodeToEnter.parent;
2066
+
2067
+ if (!parent.parent) {
2068
+ continue;
2069
+ }
2070
+
2071
+ internalQueue.push(toSCXMLEvent(done(parent.id, stateNodeToEnter.doneData ? mapContext(stateNodeToEnter.doneData, state.context, state._event) : undefined)));
2072
+
2073
+ if (parent.parent) {
2074
+ var grandparent = parent.parent;
2075
+
2076
+ if (grandparent.type === 'parallel') {
2077
+ if (getChildren(grandparent).filter(function (child) {
2078
+ return child.type !== 'history';
2079
+ }).every(function (parentNode) {
2080
+ return isInFinalState(_toConsumableArray(mutConfiguration), parentNode);
2081
+ })) {
2082
+ internalQueue.push(toSCXMLEvent(done(grandparent.id)));
2083
+ }
2084
+ }
2085
+ }
2086
+ }
2087
+ }
2088
+ } catch (err) {
2089
+ _iterator13.e(err);
2090
+ } finally {
2091
+ _iterator13.f();
2092
+ }
2093
+
2094
+ return {
2095
+ statesToInvoke: statesToInvoke,
2096
+ internalQueue: internalQueue,
2097
+ actions: actions
2098
+ };
2099
+ }
2100
+
2101
+ function computeExitSet(transitions, configuration, state) {
2102
+ var statesToExit = new Set();
2103
+
2104
+ var _iterator14 = _createForOfIteratorHelper(transitions),
2105
+ _step14;
2106
+
2107
+ try {
2108
+ for (_iterator14.s(); !(_step14 = _iterator14.n()).done;) {
2109
+ var t = _step14.value;
2110
+
2111
+ if (t.target && t.target.length) {
2112
+ var domain = getTransitionDomain(t, state);
2113
+
2114
+ var _iterator15 = _createForOfIteratorHelper(configuration),
2115
+ _step15;
2116
+
2117
+ try {
2118
+ for (_iterator15.s(); !(_step15 = _iterator15.n()).done;) {
2119
+ var s = _step15.value;
2120
+
2121
+ if (isDescendant(s, domain)) {
2122
+ statesToExit.add(s);
2123
+ }
2124
+ }
2125
+ } catch (err) {
2126
+ _iterator15.e(err);
2127
+ } finally {
2128
+ _iterator15.f();
2129
+ }
2130
+ }
2131
+ }
2132
+ } catch (err) {
2133
+ _iterator14.e(err);
2134
+ } finally {
2135
+ _iterator14.f();
2136
+ }
2137
+
2138
+ return _toConsumableArray(statesToExit);
2139
+ }
2140
+
2141
+ function computeEntrySet(transitions, state, mutStatesToEnter, mutStatesForDefaultEntry) {
2142
+ var _iterator16 = _createForOfIteratorHelper(transitions),
2143
+ _step16;
2144
+
2145
+ try {
2146
+ for (_iterator16.s(); !(_step16 = _iterator16.n()).done;) {
2147
+ var t = _step16.value;
2148
+
2149
+ var _iterator17 = _createForOfIteratorHelper(t.target || []),
2150
+ _step17;
2151
+
2152
+ try {
2153
+ for (_iterator17.s(); !(_step17 = _iterator17.n()).done;) {
2154
+ var s = _step17.value;
2155
+ addDescendantStatesToEnter(s, state, mutStatesToEnter, mutStatesForDefaultEntry);
2156
+ }
2157
+ } catch (err) {
2158
+ _iterator17.e(err);
2159
+ } finally {
2160
+ _iterator17.f();
2161
+ }
2162
+
2163
+ var ancestor = getTransitionDomain(t, state);
2164
+ var targetStates = getEffectiveTargetStates(t, state);
2165
+
2166
+ var _iterator18 = _createForOfIteratorHelper(targetStates),
2167
+ _step18;
2168
+
2169
+ try {
2170
+ for (_iterator18.s(); !(_step18 = _iterator18.n()).done;) {
2171
+ var _s2 = _step18.value;
2172
+ addAncestorStatesToEnter(_s2, ancestor, state, mutStatesToEnter, mutStatesForDefaultEntry);
2173
+ }
2174
+ } catch (err) {
2175
+ _iterator18.e(err);
2176
+ } finally {
2177
+ _iterator18.f();
2178
+ }
2179
+ }
2180
+ } catch (err) {
2181
+ _iterator16.e(err);
2182
+ } finally {
2183
+ _iterator16.f();
2184
+ }
2185
+ }
2186
+
2187
+ function addDescendantStatesToEnter(stateNode, state, mutStatesToEnter, mutStatesForDefaultEntry) {
2188
+ if (isHistoryNode(stateNode)) {
2189
+ if (state.historyValue[stateNode.id]) {
2190
+ var historyStateNodes = state.historyValue[stateNode.id];
2191
+
2192
+ var _iterator19 = _createForOfIteratorHelper(historyStateNodes),
2193
+ _step19;
2194
+
2195
+ try {
2196
+ for (_iterator19.s(); !(_step19 = _iterator19.n()).done;) {
2197
+ var s = _step19.value;
2198
+ addDescendantStatesToEnter(s, state, mutStatesToEnter, mutStatesForDefaultEntry);
2199
+ }
2200
+ } catch (err) {
2201
+ _iterator19.e(err);
2202
+ } finally {
2203
+ _iterator19.f();
2204
+ }
2205
+
2206
+ var _iterator20 = _createForOfIteratorHelper(historyStateNodes),
2207
+ _step20;
2208
+
2209
+ try {
2210
+ for (_iterator20.s(); !(_step20 = _iterator20.n()).done;) {
2211
+ var _s3 = _step20.value;
2212
+ addAncestorStatesToEnter(_s3, stateNode.parent, state, mutStatesToEnter, mutStatesForDefaultEntry);
2213
+ mutStatesForDefaultEntry.forEach(function (stateForDefaultEntry) {
2214
+ return mutStatesForDefaultEntry.add(stateForDefaultEntry);
2215
+ });
2216
+ }
2217
+ } catch (err) {
2218
+ _iterator20.e(err);
2219
+ } finally {
2220
+ _iterator20.f();
2221
+ }
2222
+ } else {
2223
+ var targets = resolveHistoryTarget(stateNode);
2224
+
2225
+ var _iterator21 = _createForOfIteratorHelper(targets),
2226
+ _step21;
2227
+
2228
+ try {
2229
+ for (_iterator21.s(); !(_step21 = _iterator21.n()).done;) {
2230
+ var _s4 = _step21.value;
2231
+ addDescendantStatesToEnter(_s4, state, mutStatesToEnter, mutStatesForDefaultEntry);
2232
+ }
2233
+ } catch (err) {
2234
+ _iterator21.e(err);
2235
+ } finally {
2236
+ _iterator21.f();
2237
+ }
2238
+
2239
+ var _iterator22 = _createForOfIteratorHelper(targets),
2240
+ _step22;
2241
+
2242
+ try {
2243
+ for (_iterator22.s(); !(_step22 = _iterator22.n()).done;) {
2244
+ var _s5 = _step22.value;
2245
+ addAncestorStatesToEnter(_s5, stateNode, state, mutStatesToEnter, mutStatesForDefaultEntry);
2246
+ mutStatesForDefaultEntry.forEach(function (stateForDefaultEntry) {
2247
+ return mutStatesForDefaultEntry.add(stateForDefaultEntry);
2248
+ });
2249
+ }
2250
+ } catch (err) {
2251
+ _iterator22.e(err);
2252
+ } finally {
2253
+ _iterator22.f();
2254
+ }
2255
+ }
2256
+ } else {
2257
+ mutStatesToEnter.add(stateNode);
2258
+
2259
+ if (stateNode.type === 'compound') {
2260
+ mutStatesForDefaultEntry.add(stateNode);
2261
+ var initialStates = stateNode.initial.target;
2262
+
2263
+ var _iterator23 = _createForOfIteratorHelper(initialStates),
2264
+ _step23;
2265
+
2266
+ try {
2267
+ for (_iterator23.s(); !(_step23 = _iterator23.n()).done;) {
2268
+ var initialState = _step23.value;
2269
+ addDescendantStatesToEnter(initialState, state, mutStatesToEnter, mutStatesForDefaultEntry);
2270
+ }
2271
+ } catch (err) {
2272
+ _iterator23.e(err);
2273
+ } finally {
2274
+ _iterator23.f();
2275
+ }
2276
+
2277
+ var _iterator24 = _createForOfIteratorHelper(initialStates),
2278
+ _step24;
2279
+
2280
+ try {
2281
+ for (_iterator24.s(); !(_step24 = _iterator24.n()).done;) {
2282
+ var _initialState = _step24.value;
2283
+ addAncestorStatesToEnter(_initialState, stateNode, state, mutStatesToEnter, mutStatesForDefaultEntry);
2284
+ }
2285
+ } catch (err) {
2286
+ _iterator24.e(err);
2287
+ } finally {
2288
+ _iterator24.f();
2289
+ }
2290
+ } else {
2291
+ if (stateNode.type === 'parallel') {
2292
+ var _iterator25 = _createForOfIteratorHelper(getChildren(stateNode).filter(function (sn) {
2293
+ return !isHistoryNode(sn);
2294
+ })),
2295
+ _step25;
2296
+
2297
+ try {
2298
+ var _loop = function _loop() {
2299
+ var child = _step25.value;
2300
+
2301
+ if (!_toConsumableArray(mutStatesToEnter).some(function (s) {
2302
+ return isDescendant(s, child);
2303
+ })) {
2304
+ addDescendantStatesToEnter(child, state, mutStatesToEnter, mutStatesForDefaultEntry);
2305
+ }
2306
+ };
2307
+
2308
+ for (_iterator25.s(); !(_step25 = _iterator25.n()).done;) {
2309
+ _loop();
2310
+ }
2311
+ } catch (err) {
2312
+ _iterator25.e(err);
2313
+ } finally {
2314
+ _iterator25.f();
2315
+ }
2316
+ }
2317
+ }
2318
+ }
2319
+ }
2320
+
2321
+ function addAncestorStatesToEnter(stateNode, toStateNode, state, mutStatesToEnter, mutStatesForDefaultEntry) {
2322
+ var properAncestors = getProperAncestors(stateNode, toStateNode);
2323
+
2324
+ var _iterator26 = _createForOfIteratorHelper(properAncestors),
2325
+ _step26;
2326
+
2327
+ try {
2328
+ for (_iterator26.s(); !(_step26 = _iterator26.n()).done;) {
2329
+ var anc = _step26.value;
2330
+ mutStatesToEnter.add(anc);
2331
+
2332
+ if (anc.type === 'parallel') {
2333
+ var _iterator27 = _createForOfIteratorHelper(getChildren(anc).filter(function (sn) {
2334
+ return !isHistoryNode(sn);
2335
+ })),
2336
+ _step27;
2337
+
2338
+ try {
2339
+ var _loop2 = function _loop2() {
2340
+ var child = _step27.value;
2341
+
2342
+ if (!_toConsumableArray(mutStatesToEnter).some(function (s) {
2343
+ return isDescendant(s, child);
2344
+ })) {
2345
+ addDescendantStatesToEnter(child, state, mutStatesToEnter, mutStatesForDefaultEntry);
2346
+ }
2347
+ };
2348
+
2349
+ for (_iterator27.s(); !(_step27 = _iterator27.n()).done;) {
2350
+ _loop2();
2351
+ }
2352
+ } catch (err) {
2353
+ _iterator27.e(err);
2354
+ } finally {
2355
+ _iterator27.f();
2356
+ }
2357
+ }
2358
+ }
2359
+ } catch (err) {
2360
+ _iterator26.e(err);
2361
+ } finally {
2362
+ _iterator26.f();
2363
+ }
2364
+ }
2365
+ /**
2366
+ * https://www.w3.org/TR/scxml/#microstepProcedure
2367
+ *
2368
+ * @private
2369
+ * @param transitions
2370
+ * @param currentState
2371
+ * @param mutConfiguration
2372
+ */
2373
+
2374
+
2375
+ function microstep(transitions, currentState, context, mutConfiguration, machine, _event) {
2376
+ var actions = [];
2377
+ var filteredTransitions = removeConflictingTransitions(transitions, mutConfiguration, currentState || State.from({}));
2378
+ var historyValue = {};
2379
+ var internalQueue = []; // Exit states
2380
+
2381
+ if (!currentState._initial) {
2382
+ var _exitStates = exitStates(filteredTransitions, mutConfiguration, currentState),
2383
+ exitHistoryValue = _exitStates.historyValue,
2384
+ exitActions = _exitStates.actions;
2385
+
2386
+ actions.push.apply(actions, _toConsumableArray(exitActions));
2387
+ historyValue = exitHistoryValue;
2388
+ } // Transition
2389
+
2390
+
2391
+ var transitionActions = flatten(filteredTransitions.map(function (t) {
2392
+ return t.actions;
2393
+ }));
2394
+ actions.push.apply(actions, _toConsumableArray(transitionActions)); // Enter states
2395
+
2396
+ var res = enterStates(filteredTransitions, mutConfiguration, currentState || State.from({})); // Start invocations
2397
+
2398
+ actions.push.apply(actions, _toConsumableArray(flatten(_toConsumableArray(res.statesToInvoke).map(function (s) {
2399
+ return s.invoke.map(function (invokeDef) {
2400
+ return invoke$1(invokeDef);
2401
+ });
2402
+ }))));
2403
+ actions.push.apply(actions, _toConsumableArray(res.actions));
2404
+
2405
+ try {
2406
+ var _resolveActionsAndCon = resolveActionsAndContext(actions, machine, _event, currentState, context),
2407
+ resolvedActions = _resolveActionsAndCon.actions,
2408
+ raised = _resolveActionsAndCon.raised,
2409
+ resolvedContext = _resolveActionsAndCon.context;
2410
+
2411
+ internalQueue.push.apply(internalQueue, _toConsumableArray(res.internalQueue));
2412
+ internalQueue.push.apply(internalQueue, _toConsumableArray(raised.map(function (a) {
2413
+ return a.params._event;
2414
+ })));
2415
+ return {
2416
+ actions: resolvedActions,
2417
+ configuration: mutConfiguration,
2418
+ historyValue: historyValue,
2419
+ internalQueue: internalQueue,
2420
+ context: resolvedContext
2421
+ };
2422
+ } catch (e) {
2423
+ // TODO: Refactor this once proper error handling is implemented.
2424
+ // See https://github.com/statelyai/rfcs/pull/4
2425
+ if (machine.config.scxml) {
2426
+ return {
2427
+ actions: [],
2428
+ configuration: mutConfiguration,
2429
+ historyValue: historyValue,
2430
+ internalQueue: [toSCXMLEvent({
2431
+ type: 'error.execution'
2432
+ })],
2433
+ context: machine.context
2434
+ };
2435
+ } else {
2436
+ throw e;
2437
+ }
2438
+ }
2439
+ }
2440
+
2441
+ function selectEventlessTransitions(state, machine) {
2442
+ var enabledTransitions = new Set();
2443
+ var atomicStates = state.configuration.filter(isAtomicStateNode);
2444
+
2445
+ var _iterator28 = _createForOfIteratorHelper(atomicStates),
2446
+ _step28;
2447
+
2448
+ try {
2449
+ for (_iterator28.s(); !(_step28 = _iterator28.n()).done;) {
2450
+ var stateNode = _step28.value;
2451
+
2452
+ var _iterator29 = _createForOfIteratorHelper([stateNode].concat(getProperAncestors(stateNode, null))),
2453
+ _step29;
2454
+
2455
+ try {
2456
+ loop: for (_iterator29.s(); !(_step29 = _iterator29.n()).done;) {
2457
+ var s = _step29.value;
2458
+
2459
+ if (!s.always) {
2460
+ continue;
2461
+ }
2462
+
2463
+ var _iterator30 = _createForOfIteratorHelper(s.always),
2464
+ _step30;
2465
+
2466
+ try {
2467
+ for (_iterator30.s(); !(_step30 = _iterator30.n()).done;) {
2468
+ var t = _step30.value;
2469
+
2470
+ if (t.guard === undefined || evaluateGuard(t.guard, state.context, state._event, state, machine)) {
2471
+ enabledTransitions.add(t);
2472
+ break loop;
2473
+ }
2474
+ }
2475
+ } catch (err) {
2476
+ _iterator30.e(err);
2477
+ } finally {
2478
+ _iterator30.f();
2479
+ }
2480
+ }
2481
+ } catch (err) {
2482
+ _iterator29.e(err);
2483
+ } finally {
2484
+ _iterator29.f();
2485
+ }
2486
+ }
2487
+ } catch (err) {
2488
+ _iterator28.e(err);
2489
+ } finally {
2490
+ _iterator28.f();
2491
+ }
2492
+
2493
+ return removeConflictingTransitions(Array.from(enabledTransitions), new Set(state.configuration), state);
2494
+ }
2495
+
2496
+ function resolveMicroTransition(machine, transitions, currentState) {
2497
+ var _event = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : initEvent;
2498
+
2499
+ // Transition will "apply" if:
2500
+ // - the state node is the initial state (there is no current state)
2501
+ // - OR there are transitions
2502
+ // - OR there are eventless transitions (if there are no transitions)
2503
+ var willTransition = currentState._initial || transitions.length > 0 || selectEventlessTransitions(currentState, machine).length > 0;
2504
+ var prevConfig = getConfiguration(!currentState._initial ? currentState.configuration : [machine.root]);
2505
+ var resolved = microstep(!currentState._initial ? transitions : [{
2506
+ target: _toConsumableArray(prevConfig).filter(isAtomicStateNode),
2507
+ source: machine.root,
2508
+ actions: [],
2509
+ eventType: null,
2510
+ toJSON: null // TODO: fix
2511
+
2512
+ }], currentState, currentState.context, new Set(prevConfig), machine, _event);
2513
+
2514
+ if (!currentState._initial && !willTransition) {
2515
+ var inertState = State.inert(currentState);
2516
+ inertState.event = _event.data;
2517
+ inertState._event = _event;
2518
+ inertState.changed = _event.name === update;
2519
+ return inertState;
2520
+ }
2521
+
2522
+ var children = _objectSpread2({}, currentState.children);
2523
+
2524
+ var resolvedConfiguration = willTransition ? Array.from(resolved.configuration) : !currentState._initial ? currentState.configuration : [];
2525
+ var meta = resolvedConfiguration.reduce(function (acc, subStateNode) {
2526
+ if (subStateNode.meta !== undefined) {
2527
+ acc[subStateNode.id] = subStateNode.meta;
2528
+ }
2529
+
2530
+ return acc;
2531
+ }, {});
2532
+ var context = resolved.context,
2533
+ nonRaisedActions = resolved.actions;
2534
+ var nextState = machine.createState({
2535
+ value: getStateValue(machine.root, resolved.configuration),
2536
+ context: context,
2537
+ _event: _event,
2538
+ // Persist _sessionid between states
2539
+ _sessionid: !currentState._initial ? currentState._sessionid : null,
2540
+ actions: nonRaisedActions,
2541
+ meta: meta,
2542
+ configuration: resolvedConfiguration,
2543
+ transitions: transitions,
2544
+ children: children,
2545
+ historyValue: resolved.historyValue
2546
+ });
2547
+ nextState.changed = currentState._initial ? undefined : !stateValuesEqual(nextState.value, currentState.value) || _event.name === update || nextState.actions.length > 0 || context !== currentState.context;
2548
+ nextState._internalQueue = resolved.internalQueue;
2549
+ nextState.actions.forEach(function (action) {
2550
+ if (action.type === invoke && action.params.ref) {
2551
+ var ref = action.params.ref;
2552
+
2553
+ if (ref) {
2554
+ children[ref.name] = ref;
2555
+ }
2556
+ }
2557
+ });
2558
+ return nextState;
2559
+ }
2560
+
2561
+ function resolveActionsAndContext(actions, machine, _event, currentState, context) {
2562
+ var resolvedActions = [];
2563
+ var raiseActions = [];
2564
+ var preservedContexts = [context];
2565
+
2566
+ function resolveAction(actionObject) {
2567
+ var executableActionObject = resolveActionObject(actionObject, machine.options.actions);
2568
+
2569
+ if (isDynamicAction(executableActionObject)) {
2570
+ if (executableActionObject.type === pure || executableActionObject.type === choose) {
2571
+ var matchedActions = executableActionObject.resolve(executableActionObject, context, _event, {
2572
+ machine: machine,
2573
+ state: currentState,
2574
+ action: actionObject
2575
+ }).params.actions;
2576
+
2577
+ if (matchedActions) {
2578
+ toActionObjects(toArray(matchedActions), machine.options.actions).forEach(resolveAction);
2579
+ }
2580
+ } else if (executableActionObject.type === assign) {
2581
+ var resolvedActionObject = executableActionObject.resolve(executableActionObject, context, _event, {
2582
+ machine: machine,
2583
+ state: currentState,
2584
+ action: actionObject
2585
+ });
2586
+
2587
+ if (resolvedActionObject.type === raise) {
2588
+ raiseActions.push(resolvedActionObject);
2589
+ return;
2590
+ }
2591
+
2592
+ context = resolvedActionObject.params.context;
2593
+ preservedContexts.push(resolvedActionObject.params.context);
2594
+ resolvedActions.push.apply(resolvedActions, [resolvedActionObject].concat(_toConsumableArray(resolvedActionObject.params.actions)));
2595
+ } else {
2596
+ var _resolvedActionObject = executableActionObject.resolve(executableActionObject, context, _event, {
2597
+ machine: machine,
2598
+ state: currentState,
2599
+ action: actionObject
2600
+ });
2601
+
2602
+ if (_resolvedActionObject.type === raise || _resolvedActionObject.type === send && _resolvedActionObject.params.to === exports.SpecialTargets.Internal) {
2603
+ raiseActions.push(_resolvedActionObject);
2604
+ } else {
2605
+ resolvedActions.push(_resolvedActionObject);
2606
+ }
2607
+ }
2608
+
2609
+ return;
2610
+ }
2611
+
2612
+ switch (executableActionObject.type) {
2613
+ case raise:
2614
+ raiseActions.push(executableActionObject);
2615
+ break;
2616
+
2617
+ case choose:
2618
+ {
2619
+ var _chooseAction$params$;
2620
+
2621
+ var chooseAction = executableActionObject;
2622
+
2623
+ var _matchedActions = (_chooseAction$params$ = chooseAction.params.guards.find(function (condition) {
2624
+ var guard = condition.guard && toGuardDefinition(condition.guard, function (guardType) {
2625
+ return machine.options.guards[guardType];
2626
+ });
2627
+ return !guard || evaluateGuard(guard, context, _event, currentState, machine);
2628
+ })) === null || _chooseAction$params$ === void 0 ? void 0 : _chooseAction$params$.actions;
2629
+
2630
+ if (_matchedActions) {
2631
+ toActionObjects(toArray(_matchedActions), machine.options.actions).forEach(resolveAction);
2632
+ }
2633
+
2634
+ break;
2635
+ }
2636
+
2637
+ default:
2638
+ var contextIndex = preservedContexts.length - 1;
2639
+
2640
+ if (isExecutableAction(executableActionObject)) {
2641
+ executableActionObject.setContext(preservedContexts[contextIndex]);
2642
+ resolvedActions.push(executableActionObject);
2643
+ } else {
2644
+ var _resolvedActionObject2 = toActionObject(executableActionObject, machine.options.actions);
2645
+
2646
+ var actionExec = new ExecutableAction(_resolvedActionObject2);
2647
+ actionExec.setContext(preservedContexts[contextIndex]);
2648
+ resolvedActions.push(actionExec);
2649
+ }
2650
+
2651
+ break;
2652
+ }
2653
+ }
2654
+
2655
+ var _iterator31 = _createForOfIteratorHelper(actions),
2656
+ _step31;
2657
+
2658
+ try {
2659
+ for (_iterator31.s(); !(_step31 = _iterator31.n()).done;) {
2660
+ var actionObject = _step31.value;
2661
+ resolveAction(actionObject);
2662
+ }
2663
+ } catch (err) {
2664
+ _iterator31.e(err);
2665
+ } finally {
2666
+ _iterator31.f();
2667
+ }
2668
+
2669
+ return {
2670
+ actions: resolvedActions,
2671
+ raised: raiseActions,
2672
+ context: context
2673
+ };
2674
+ }
2675
+
2676
+ function macrostep(state, event, machine) {
2677
+ // Assume the state is at rest (no raised events)
2678
+ // Determine the next state based on the next microstep
2679
+ var nextState = event === null ? state : machine.microstep(state, event);
2680
+ var _internalQueue = nextState._internalQueue;
2681
+ var maybeNextState = nextState;
2682
+
2683
+ while (!maybeNextState.done) {
2684
+ var eventlessTransitions = selectEventlessTransitions(maybeNextState, machine);
2685
+
2686
+ if (eventlessTransitions.length === 0) {
2687
+ if (!_internalQueue.length) {
2688
+ break;
2689
+ } else {
2690
+ var _maybeNextState$actio;
2691
+
2692
+ var internalEvent = _internalQueue.shift();
2693
+
2694
+ var currentActions = maybeNextState.actions;
2695
+ maybeNextState = machine.microstep(maybeNextState, internalEvent);
2696
+
2697
+ _internalQueue.push.apply(_internalQueue, _toConsumableArray(maybeNextState._internalQueue)); // Since macrostep actions have not been executed yet,
2698
+ // prioritize them in the action queue
2699
+
2700
+
2701
+ (_maybeNextState$actio = maybeNextState.actions).unshift.apply(_maybeNextState$actio, _toConsumableArray(currentActions));
2702
+ }
2703
+ } else {
2704
+ var _maybeNextState$actio2;
2705
+
2706
+ var _currentActions = maybeNextState.actions;
2707
+ maybeNextState = resolveMicroTransition(machine, eventlessTransitions, maybeNextState, maybeNextState._event);
2708
+
2709
+ _internalQueue.push.apply(_internalQueue, _toConsumableArray(maybeNextState._internalQueue));
2710
+
2711
+ (_maybeNextState$actio2 = maybeNextState.actions).unshift.apply(_maybeNextState$actio2, _toConsumableArray(_currentActions));
2712
+ }
2713
+ } // Add tags
2714
+
2715
+
2716
+ maybeNextState.tags = new Set(flatten(maybeNextState.configuration.map(function (sn) {
2717
+ return sn.tags;
2718
+ })));
2719
+ maybeNextState.machine = machine;
2720
+ return maybeNextState;
2721
+ }
2722
+
2723
+ function resolveHistoryValue(currentState, exitSet) {
2724
+ var historyValue = currentState ? currentState.historyValue : {};
2725
+
2726
+ if (currentState && currentState.configuration) {
2727
+ // From SCXML algorithm: https://www.w3.org/TR/scxml/#exitStates
2728
+ var _iterator32 = _createForOfIteratorHelper(exitSet),
2729
+ _step32;
2730
+
2731
+ try {
2732
+ var _loop3 = function _loop3() {
2733
+ var exitStateNode = _step32.value;
2734
+
2735
+ var _iterator33 = _createForOfIteratorHelper(getHistoryNodes(exitStateNode)),
2736
+ _step33;
2737
+
2738
+ try {
2739
+ for (_iterator33.s(); !(_step33 = _iterator33.n()).done;) {
2740
+ var historyNode = _step33.value;
2741
+ var predicate = void 0;
2742
+
2743
+ if (historyNode.history === 'deep') {
2744
+ predicate = function predicate(sn) {
2745
+ return isAtomicStateNode(sn) && isDescendant(sn, exitStateNode);
2746
+ };
2747
+ } else {
2748
+ predicate = function predicate(sn) {
2749
+ return sn.parent === exitStateNode;
2750
+ };
2751
+ }
2752
+
2753
+ historyValue[historyNode.id] = currentState.configuration.filter(predicate);
2754
+ }
2755
+ } catch (err) {
2756
+ _iterator33.e(err);
2757
+ } finally {
2758
+ _iterator33.f();
2759
+ }
2760
+ };
2761
+
2762
+ for (_iterator32.s(); !(_step32 = _iterator32.n()).done;) {
2763
+ _loop3();
2764
+ }
2765
+ } catch (err) {
2766
+ _iterator32.e(err);
2767
+ } finally {
2768
+ _iterator32.f();
2769
+ }
2770
+ }
2771
+
2772
+ return historyValue;
2773
+ }
2774
+ /**
2775
+ * Resolves a partial state value with its full representation in the state node's machine.
2776
+ *
2777
+ * @param stateValue The partial state value to resolve.
2778
+ */
2779
+
2780
+
2781
+ function resolveStateValue(rootNode, stateValue) {
2782
+ var configuration = getConfiguration(getStateNodes(rootNode, stateValue));
2783
+ return getStateValue(rootNode, _toConsumableArray(configuration));
2784
+ }
2785
+ function toState(state, machine) {
2786
+ if (state instanceof State) {
2787
+ return state;
2788
+ } else {
2789
+ var resolvedStateValue = resolveStateValue(machine.root, state);
2790
+ var resolvedContext = machine.context;
2791
+ return machine.resolveState(State.from(resolvedStateValue, resolvedContext));
2792
+ }
2793
+ }
2794
+ function stateValuesEqual(a, b) {
2795
+ if (a === b) {
2796
+ return true;
2797
+ }
2798
+
2799
+ if (a === undefined || b === undefined) {
2800
+ return false;
2801
+ }
2802
+
2803
+ if (isString(a) || isString(b)) {
2804
+ return a === b;
2805
+ }
2806
+
2807
+ var aKeys = Object.keys(a);
2808
+ var bKeys = Object.keys(b);
2809
+ return aKeys.length === bKeys.length && aKeys.every(function (key) {
2810
+ return stateValuesEqual(a[key], b[key]);
2811
+ });
2812
+ }
2813
+ function getMeta() {
2814
+ var configuration = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
2815
+ return configuration.reduce(function (acc, stateNode) {
2816
+ if (stateNode.meta !== undefined) {
2817
+ acc[stateNode.id] = stateNode.meta;
2818
+ }
2819
+
2820
+ return acc;
2821
+ }, {});
2822
+ }
2823
+ function getTagsFromConfiguration(configuration) {
2824
+ return new Set(flatten(configuration.map(function (sn) {
2825
+ return sn.tags;
2826
+ })));
2827
+ }
2828
+
2829
+ var _excluded = ["configuration", "transitions", "tags", "machine"];
2830
+ function isStateConfig(state) {
2831
+ if (_typeof(state) !== 'object' || state === null) {
2832
+ return false;
2833
+ }
2834
+
2835
+ return 'value' in state && '_event' in state;
2836
+ }
2837
+ var State = /*#__PURE__*/function () {
2838
+ /**
2839
+ * Creates a new `State` instance that represents the current state of a running machine.
2840
+ *
2841
+ * @param config
2842
+ */
2843
+ function State(config) {
2844
+ _classCallCheck(this, State);
2845
+
2846
+ _defineProperty(this, "value", void 0);
2847
+
2848
+ _defineProperty(this, "context", void 0);
2849
+
2850
+ _defineProperty(this, "historyValue", {});
2851
+
2852
+ _defineProperty(this, "actions", []);
2853
+
2854
+ _defineProperty(this, "meta", {});
2855
+
2856
+ _defineProperty(this, "event", void 0);
2857
+
2858
+ _defineProperty(this, "_internalQueue", []);
2859
+
2860
+ _defineProperty(this, "_event", void 0);
2861
+
2862
+ _defineProperty(this, "_sessionid", void 0);
2863
+
2864
+ _defineProperty(this, "_initial", false);
2865
+
2866
+ _defineProperty(this, "changed", void 0);
2867
+
2868
+ _defineProperty(this, "configuration", void 0);
2869
+
2870
+ _defineProperty(this, "transitions", void 0);
2871
+
2872
+ _defineProperty(this, "children", void 0);
2873
+
2874
+ _defineProperty(this, "tags", void 0);
2875
+
2876
+ _defineProperty(this, "machine", void 0);
2877
+
2878
+ this.value = config.value;
2879
+ this.context = config.context;
2880
+ this._event = config._event;
2881
+ this._sessionid = config._sessionid;
2882
+ this.event = this._event.data;
2883
+ this.historyValue = config.historyValue || {};
2884
+ this.actions = config.actions || [];
2885
+ this.meta = getMeta(config.configuration);
2886
+ this.matches = this.matches.bind(this);
2887
+ this.toStrings = this.toStrings.bind(this);
2888
+ this.configuration = config.configuration;
2889
+ this.transitions = config.transitions;
2890
+ this.children = config.children;
2891
+ this.tags = config.configuration ? getTagsFromConfiguration(config.configuration) : config.tags ? new Set(config.tags) : new Set();
2892
+ this.machine = config.machine;
2893
+ }
2894
+ /**
2895
+ * Returns an array of all the string leaf state node paths.
2896
+ * @param stateValue
2897
+ * @param delimiter The character(s) that separate each subpath in the string state node path.
2898
+ */
2899
+
2900
+
2901
+ _createClass(State, [{
2902
+ key: "toStrings",
2903
+ value: function toStrings() {
2904
+ var _this = this;
2905
+
2906
+ var stateValue = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.value;
2907
+ var delimiter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '.';
2908
+
2909
+ if (isString(stateValue)) {
2910
+ return [stateValue];
2911
+ }
2912
+
2913
+ var valueKeys = Object.keys(stateValue);
2914
+ return valueKeys.concat.apply(valueKeys, _toConsumableArray(valueKeys.map(function (key) {
2915
+ return _this.toStrings(stateValue[key], delimiter).map(function (s) {
2916
+ return key + delimiter + s;
2917
+ });
2918
+ })));
2919
+ }
2920
+ }, {
2921
+ key: "toJSON",
2922
+ value: function toJSON() {
2923
+ var configuration = this.configuration,
2924
+ transitions = this.transitions,
2925
+ tags = this.tags,
2926
+ machine = this.machine,
2927
+ jsonValues = _objectWithoutProperties(this, _excluded);
2928
+
2929
+ return _objectSpread2(_objectSpread2({}, jsonValues), {}, {
2930
+ tags: Array.from(tags)
2931
+ });
2932
+ }
2933
+ /**
2934
+ * Whether the current state value is a subset of the given parent state value.
2935
+ * @param parentStateValue
2936
+ */
2937
+
2938
+ }, {
2939
+ key: "matches",
2940
+ value: function matches(parentStateValue) {
2941
+ return matchesState(parentStateValue, this.value);
2942
+ }
2943
+ /**
2944
+ * Indicates whether the state is a final state.
2945
+ */
2946
+
2947
+ }, {
2948
+ key: "done",
2949
+ get: function get() {
2950
+ return isInFinalState(this.configuration);
2951
+ }
2952
+ /**
2953
+ * Whether the current state configuration has a state node with the specified `tag`.
2954
+ * @param tag
2955
+ */
2956
+
2957
+ }, {
2958
+ key: "hasTag",
2959
+ value: function hasTag(tag) {
2960
+ return this.tags.has(tag);
2961
+ }
2962
+ /**
2963
+ * Determines whether sending the `event` will cause a non-forbidden transition
2964
+ * to be selected, even if the transitions have no actions nor
2965
+ * change the state value.
2966
+ *
2967
+ * @param event The event to test
2968
+ * @returns Whether the event will cause a transition
2969
+ */
2970
+
2971
+ }, {
2972
+ key: "can",
2973
+ value: function can(event) {
2974
+ var _this$machine;
2975
+
2976
+ {
2977
+ warn(!!this.machine);
2978
+ }
2979
+
2980
+ var transitionData = (_this$machine = this.machine) === null || _this$machine === void 0 ? void 0 : _this$machine.getTransitionData(this, toSCXMLEvent(event));
2981
+ return !!(transitionData !== null && transitionData !== void 0 && transitionData.length) && // Check that at least one transition is not forbidden
2982
+ transitionData.some(function (t) {
2983
+ return t.target !== undefined || t.actions.length;
2984
+ });
2985
+ }
2986
+ /**
2987
+ * The next events that will cause a transition from the current state.
2988
+ */
2989
+
2990
+ }, {
2991
+ key: "nextEvents",
2992
+ get: function get() {
2993
+ var _this2 = this;
2994
+
2995
+ return memo(this, 'nextEvents', function () {
2996
+ return nextEvents(_this2.configuration);
2997
+ });
2998
+ }
2999
+ }], [{
3000
+ key: "from",
3001
+ value:
3002
+ /**
3003
+ * Indicates whether the state has changed from the previous state. A state is considered "changed" if:
3004
+ *
3005
+ * - Its value is not equal to its previous value, or:
3006
+ * - It has any new actions (side-effects) to execute.
3007
+ *
3008
+ * An initial state (with no history) will return `undefined`.
3009
+ */
3010
+
3011
+ /**
3012
+ * The enabled state nodes representative of the state value.
3013
+ */
3014
+
3015
+ /**
3016
+ * The transition definitions that resulted in this state.
3017
+ */
3018
+
3019
+ /**
3020
+ * An object mapping actor names to spawned/invoked actors.
3021
+ */
3022
+
3023
+ /**
3024
+ * Creates a new State instance for the given `stateValue` and `context`.
3025
+ * @param stateValue
3026
+ * @param context
3027
+ */
3028
+ function from(stateValue) {
3029
+ var context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
3030
+
3031
+ if (stateValue instanceof State) {
3032
+ if (stateValue.context !== context) {
3033
+ return new State({
3034
+ value: stateValue.value,
3035
+ context: context,
3036
+ _event: stateValue._event,
3037
+ _sessionid: null,
3038
+ actions: [],
3039
+ meta: {},
3040
+ configuration: [],
3041
+ // TODO: fix,
3042
+ transitions: [],
3043
+ children: {}
3044
+ });
3045
+ }
3046
+
3047
+ return stateValue;
3048
+ }
3049
+
3050
+ var _event = initEvent;
3051
+ return new State({
3052
+ value: stateValue,
3053
+ context: context,
3054
+ _event: _event,
3055
+ _sessionid: null,
3056
+ actions: [],
3057
+ meta: undefined,
3058
+ configuration: [],
3059
+ transitions: [],
3060
+ children: {}
3061
+ });
3062
+ }
3063
+ /**
3064
+ * Creates a new State instance for the given `config`.
3065
+ * @param config The state config
3066
+ */
3067
+
3068
+ }, {
3069
+ key: "create",
3070
+ value: function create(config) {
3071
+ return new State(config);
3072
+ }
3073
+ /**
3074
+ * Creates a new `State` instance for the given `stateValue` and `context` with no actions (side-effects).
3075
+ * @param stateValue
3076
+ * @param context
3077
+ */
3078
+
3079
+ }, {
3080
+ key: "inert",
3081
+ value: function inert(stateValue, context) {
3082
+ if (stateValue instanceof State) {
3083
+ if (!stateValue.actions.length) {
3084
+ return stateValue;
3085
+ }
3086
+
3087
+ var _event = initEvent;
3088
+ return new State({
3089
+ value: stateValue.value,
3090
+ context: stateValue.context,
3091
+ _event: _event,
3092
+ _sessionid: null,
3093
+ configuration: stateValue.configuration,
3094
+ transitions: [],
3095
+ children: stateValue.children
3096
+ });
3097
+ }
3098
+
3099
+ return State.from(stateValue, context);
3100
+ }
3101
+ }]);
3102
+
3103
+ return State;
3104
+ }();
3105
+
3106
+ (function (InterpreterStatus) {
3107
+ InterpreterStatus[InterpreterStatus["NotStarted"] = 0] = "NotStarted";
3108
+ InterpreterStatus[InterpreterStatus["Running"] = 1] = "Running";
3109
+ InterpreterStatus[InterpreterStatus["Stopped"] = 2] = "Stopped";
3110
+ })(exports.InterpreterStatus || (exports.InterpreterStatus = {}));
3111
+
3112
+ var defaultOptions = {
3113
+ deferEvents: true,
3114
+ clock: {
3115
+ setTimeout: function (_setTimeout) {
3116
+ function setTimeout(_x, _x2) {
3117
+ return _setTimeout.apply(this, arguments);
3118
+ }
3119
+
3120
+ setTimeout.toString = function () {
3121
+ return _setTimeout.toString();
3122
+ };
3123
+
3124
+ return setTimeout;
3125
+ }(function (fn, ms) {
3126
+ return setTimeout(fn, ms);
3127
+ }),
3128
+ clearTimeout: function (_clearTimeout) {
3129
+ function clearTimeout(_x3) {
3130
+ return _clearTimeout.apply(this, arguments);
3131
+ }
3132
+
3133
+ clearTimeout.toString = function () {
3134
+ return _clearTimeout.toString();
3135
+ };
3136
+
3137
+ return clearTimeout;
3138
+ }(function (id) {
3139
+ return clearTimeout(id);
3140
+ })
3141
+ },
3142
+ logger: console.log.bind(console),
3143
+ devTools: false
3144
+ };
3145
+ var Interpreter = /*#__PURE__*/function () {
3146
+ /**
3147
+ * The current state of the interpreted machine.
3148
+ */
3149
+
3150
+ /**
3151
+ * The clock that is responsible for setting and clearing timeouts, such as delayed events and transitions.
3152
+ */
3153
+
3154
+ /**
3155
+ * Whether the service is started.
3156
+ */
3157
+ // Actor Ref
3158
+
3159
+ /**
3160
+ * The globally unique process ID for this invocation.
3161
+ */
3162
+
3163
+ /**
3164
+ * Creates a new Interpreter instance (i.e., service) for the given machine with the provided options, if any.
3165
+ *
3166
+ * @param machine The machine to be interpreted
3167
+ * @param options Interpreter options
3168
+ */
3169
+ function Interpreter(machine, options) {
3170
+ var _this = this;
3171
+
3172
+ _classCallCheck(this, Interpreter);
3173
+
3174
+ this.machine = machine;
3175
+
3176
+ _defineProperty(this, "_state", void 0);
3177
+
3178
+ _defineProperty(this, "_initialState", void 0);
3179
+
3180
+ _defineProperty(this, "clock", void 0);
3181
+
3182
+ _defineProperty(this, "options", void 0);
3183
+
3184
+ _defineProperty(this, "id", void 0);
3185
+
3186
+ _defineProperty(this, "mailbox", new Mailbox(this._process.bind(this)));
3187
+
3188
+ _defineProperty(this, "delayedEventsMap", {});
3189
+
3190
+ _defineProperty(this, "listeners", new Set());
3191
+
3192
+ _defineProperty(this, "stopListeners", new Set());
3193
+
3194
+ _defineProperty(this, "errorListeners", new Set());
3195
+
3196
+ _defineProperty(this, "doneListeners", new Set());
3197
+
3198
+ _defineProperty(this, "logger", void 0);
3199
+
3200
+ _defineProperty(this, "status", exports.InterpreterStatus.NotStarted);
3201
+
3202
+ _defineProperty(this, "_parent", void 0);
3203
+
3204
+ _defineProperty(this, "name", void 0);
3205
+
3206
+ _defineProperty(this, "ref", void 0);
3207
+
3208
+ _defineProperty(this, "sessionId", void 0);
3209
+
3210
+ _defineProperty(this, "forwardTo", new Set());
3211
+
3212
+ _defineProperty(this, "send", function (event, payload) {
3213
+ var eventObject = toEventObject(event, payload);
3214
+
3215
+ var _event = toSCXMLEvent(eventObject);
3216
+
3217
+ if (_this.status === exports.InterpreterStatus.Stopped) {
3218
+
3219
+ return;
3220
+ }
3221
+
3222
+ if (_this.status !== exports.InterpreterStatus.Running && !_this.options.deferEvents) {
3223
+ throw new Error("Event \"".concat(_event.name, "\" was sent to uninitialized service \"").concat(_this.machine.key // tslint:disable-next-line:max-line-length
3224
+ , "\". Make sure .start() is called for this service, or set { deferEvents: true } in the service options.\nEvent: ").concat(JSON.stringify(_event.data)));
3225
+ }
3226
+
3227
+ _this.mailbox.enqueue(_event);
3228
+ });
3229
+
3230
+ var resolvedOptions = _objectSpread2(_objectSpread2({}, defaultOptions), options);
3231
+
3232
+ var clock = resolvedOptions.clock,
3233
+ logger = resolvedOptions.logger,
3234
+ parent = resolvedOptions.parent,
3235
+ id = resolvedOptions.id;
3236
+ var resolvedId = id !== undefined ? id : machine.key;
3237
+ this.name = this.id = resolvedId;
3238
+ this.logger = logger;
3239
+ this.clock = clock;
3240
+ this._parent = parent;
3241
+ this.options = resolvedOptions;
3242
+ this.ref = this;
3243
+ this.sessionId = this.ref.name;
3244
+ }
3245
+
3246
+ _createClass(Interpreter, [{
3247
+ key: "initialized",
3248
+ get: function get() {
3249
+ return this.status === exports.InterpreterStatus.Running;
3250
+ }
3251
+ }, {
3252
+ key: "initialState",
3253
+ get: function get() {
3254
+ var initialState = this._initialState || (this._initialState = this.machine.getInitialState(), this._initialState);
3255
+ return initialState;
3256
+ }
3257
+ }, {
3258
+ key: "state",
3259
+ get: function get() {
3260
+ return this._state;
3261
+ }
3262
+ /**
3263
+ * Executes the actions of the given state, with that state's `context` and `event`.
3264
+ *
3265
+ * @param state The state whose actions will be executed
3266
+ */
3267
+
3268
+ }, {
3269
+ key: "execute",
3270
+ value: function execute(state) {
3271
+ var _iterator = _createForOfIteratorHelper(state.actions),
3272
+ _step;
3273
+
3274
+ try {
3275
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
3276
+ var action = _step.value;
3277
+ this.exec(action, state);
3278
+ }
3279
+ } catch (err) {
3280
+ _iterator.e(err);
3281
+ } finally {
3282
+ _iterator.f();
3283
+ }
3284
+ }
3285
+ }, {
3286
+ key: "update",
3287
+ value: function update(state) {
3288
+ var _this2 = this;
3289
+
3290
+ // Attach session ID to state
3291
+ state._sessionid = this.sessionId; // Update state
3292
+
3293
+ this._state = state; // Execute actions
3294
+
3295
+ this.execute(this.state);
3296
+
3297
+ var _iterator2 = _createForOfIteratorHelper(this.listeners),
3298
+ _step2;
3299
+
3300
+ try {
3301
+ for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
3302
+ var _listener = _step2.value;
3303
+
3304
+ _listener(state, state.event);
3305
+ }
3306
+ } catch (err) {
3307
+ _iterator2.e(err);
3308
+ } finally {
3309
+ _iterator2.f();
3310
+ }
3311
+
3312
+ var isDone = isInFinalState(state.configuration || [], this.machine.root);
3313
+
3314
+ if (this.state.configuration && isDone) {
3315
+ // get final child state node
3316
+ var finalChildStateNode = state.configuration.find(function (stateNode) {
3317
+ return stateNode.type === 'final' && stateNode.parent === _this2.machine.root;
3318
+ });
3319
+ var doneData = finalChildStateNode && finalChildStateNode.doneData ? mapContext(finalChildStateNode.doneData, state.context, state._event) : undefined;
3320
+
3321
+ var _iterator3 = _createForOfIteratorHelper(this.doneListeners),
3322
+ _step3;
3323
+
3324
+ try {
3325
+ for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
3326
+ var listener = _step3.value;
3327
+ listener(toSCXMLEvent(doneInvoke(this.name, doneData), {
3328
+ invokeid: this.name
3329
+ }));
3330
+ }
3331
+ } catch (err) {
3332
+ _iterator3.e(err);
3333
+ } finally {
3334
+ _iterator3.f();
3335
+ }
3336
+
3337
+ this.stop();
3338
+ }
3339
+ }
3340
+ /*
3341
+ * Adds a listener that is notified whenever a state transition happens. The listener is called with
3342
+ * the next state and the event object that caused the state transition.
3343
+ *
3344
+ * @param listener The state listener
3345
+ */
3346
+
3347
+ }, {
3348
+ key: "onTransition",
3349
+ value: function onTransition(listener) {
3350
+ this.listeners.add(listener); // Send current state to listener
3351
+
3352
+ if (this.status === exports.InterpreterStatus.Running) {
3353
+ listener(this.state, this.state.event);
3354
+ }
3355
+
3356
+ return this;
3357
+ }
3358
+ }, {
3359
+ key: "subscribe",
3360
+ value: function subscribe(nextListenerOrObserver, errorListener, completeListener) {
3361
+ var _this3 = this;
3362
+
3363
+ if (!nextListenerOrObserver) {
3364
+ return {
3365
+ unsubscribe: function unsubscribe() {
3366
+ return void 0;
3367
+ }
3368
+ };
3369
+ }
3370
+
3371
+ var listener;
3372
+ var resolvedCompleteListener = completeListener;
3373
+
3374
+ if (typeof nextListenerOrObserver === 'function') {
3375
+ listener = nextListenerOrObserver;
3376
+ } else {
3377
+ var _nextListenerOrObserv, _nextListenerOrObserv2;
3378
+
3379
+ listener = (_nextListenerOrObserv = nextListenerOrObserver.next) === null || _nextListenerOrObserv === void 0 ? void 0 : _nextListenerOrObserv.bind(nextListenerOrObserver);
3380
+ resolvedCompleteListener = (_nextListenerOrObserv2 = nextListenerOrObserver.complete) === null || _nextListenerOrObserv2 === void 0 ? void 0 : _nextListenerOrObserv2.bind(nextListenerOrObserver);
3381
+ }
3382
+
3383
+ if (listener) {
3384
+ this.listeners.add(listener);
3385
+ }
3386
+
3387
+ if (errorListener) {
3388
+ this.onError(errorListener);
3389
+ } // Send current state to listener
3390
+
3391
+
3392
+ if (this.status !== exports.InterpreterStatus.NotStarted) {
3393
+ listener(this.state);
3394
+ }
3395
+
3396
+ if (resolvedCompleteListener) {
3397
+ if (this.status === exports.InterpreterStatus.Stopped) {
3398
+ resolvedCompleteListener();
3399
+ } else {
3400
+ this.onDone(resolvedCompleteListener);
3401
+ }
3402
+ }
3403
+
3404
+ return {
3405
+ unsubscribe: function unsubscribe() {
3406
+ listener && _this3.off(listener);
3407
+ resolvedCompleteListener && _this3.off(resolvedCompleteListener);
3408
+ errorListener && _this3.off(errorListener);
3409
+ }
3410
+ };
3411
+ }
3412
+ /**
3413
+ * Adds a listener that is notified when the machine is stopped.
3414
+ *
3415
+ * @param listener The listener
3416
+ */
3417
+
3418
+ }, {
3419
+ key: "onStop",
3420
+ value: function onStop(listener) {
3421
+ this.stopListeners.add(listener);
3422
+ return this;
3423
+ }
3424
+ /**
3425
+ * Adds an error listener that is notified with an `Error` whenever an
3426
+ * error occurs during execution.
3427
+ *
3428
+ * @param listener The error listener
3429
+ */
3430
+
3431
+ }, {
3432
+ key: "onError",
3433
+ value: function onError(listener) {
3434
+ this.errorListeners.add(listener);
3435
+ return this;
3436
+ }
3437
+ /**
3438
+ * Adds a state listener that is notified when the statechart has reached its final state.
3439
+ * @param listener The state listener
3440
+ */
3441
+
3442
+ }, {
3443
+ key: "onDone",
3444
+ value: function onDone(listener) {
3445
+ this.doneListeners.add(listener);
3446
+ return this;
3447
+ }
3448
+ /**
3449
+ * Removes a listener.
3450
+ * @param listener The listener to remove
3451
+ */
3452
+
3453
+ }, {
3454
+ key: "off",
3455
+ value: function off(listener) {
3456
+ this.listeners["delete"](listener);
3457
+ this.stopListeners["delete"](listener);
3458
+ this.doneListeners["delete"](listener);
3459
+ this.errorListeners["delete"](listener);
3460
+ return this;
3461
+ }
3462
+ /**
3463
+ * Starts the interpreter from the given state, or the initial state.
3464
+ * @param initialState The state to start the statechart from
3465
+ */
3466
+
3467
+ }, {
3468
+ key: "start",
3469
+ value: function start(initialState) {
3470
+ if (this.status === exports.InterpreterStatus.Running) {
3471
+ // Do not restart the service if it is already started
3472
+ return this;
3473
+ }
3474
+
3475
+ registry.register(this.sessionId, this.ref);
3476
+ this.status = exports.InterpreterStatus.Running;
3477
+ var resolvedState = initialState === undefined ? this.initialState : isStateConfig(initialState) ? this.machine.resolveState(initialState) // TODO: fix this
3478
+ : this.machine.resolveState(State.from(initialState, this.machine.context));
3479
+ this._state = resolvedState; // TODO: this notifies all subscribers but usually this is redundant
3480
+ // if we are using the initialState as `resolvedState` then there is no real change happening here
3481
+ // we need to rethink if this needs to be refactored
3482
+
3483
+ this.update(resolvedState);
3484
+
3485
+ if (this.options.devTools) {
3486
+ this.attachDevTools();
3487
+ }
3488
+
3489
+ this.mailbox.start();
3490
+ return this;
3491
+ }
3492
+ }, {
3493
+ key: "_process",
3494
+ value: function _process(event) {
3495
+ // TODO: handle errors
3496
+ this.forward(event);
3497
+ var errored = false;
3498
+
3499
+ if (isSCXMLErrorEvent(event) && !this.state.nextEvents.some(function (nextEvent) {
3500
+ return nextEvent === event.name;
3501
+ })) {
3502
+ errored = true; // Error event unhandled by machine
3503
+
3504
+ if (this.errorListeners.size > 0) {
3505
+ this.errorListeners.forEach(function (listener) {
3506
+ listener(event.data.data);
3507
+ });
3508
+ } else {
3509
+ this.stop();
3510
+ throw event.data.data;
3511
+ }
3512
+ }
3513
+
3514
+ var nextState = this.nextState(event);
3515
+ this.update(nextState);
3516
+
3517
+ if (errored) {
3518
+ this.stop();
3519
+ }
3520
+ }
3521
+ /**
3522
+ * Stops the interpreter and unsubscribe all listeners.
3523
+ *
3524
+ * This will also notify the `onStop` listeners.
3525
+ */
3526
+
3527
+ }, {
3528
+ key: "stop",
3529
+ value: function stop() {
3530
+ var _this4 = this;
3531
+
3532
+ this.listeners.clear();
3533
+
3534
+ var _iterator4 = _createForOfIteratorHelper(this.stopListeners),
3535
+ _step4;
3536
+
3537
+ try {
3538
+ for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
3539
+ var listener = _step4.value;
3540
+ // call listener, then remove
3541
+ listener();
3542
+ }
3543
+ } catch (err) {
3544
+ _iterator4.e(err);
3545
+ } finally {
3546
+ _iterator4.f();
3547
+ }
3548
+
3549
+ this.stopListeners.clear();
3550
+ this.doneListeners.clear();
3551
+
3552
+ if (!this.initialized) {
3553
+ // Interpreter already stopped; do nothing
3554
+ return this;
3555
+ }
3556
+
3557
+ _toConsumableArray(this.state.configuration).sort(function (a, b) {
3558
+ return b.order - a.order;
3559
+ }).forEach(function (stateNode) {
3560
+ var _iterator5 = _createForOfIteratorHelper(stateNode.definition.exit),
3561
+ _step5;
3562
+
3563
+ try {
3564
+ for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
3565
+ var action = _step5.value;
3566
+
3567
+ _this4.exec(action, _this4.state);
3568
+ }
3569
+ } catch (err) {
3570
+ _iterator5.e(err);
3571
+ } finally {
3572
+ _iterator5.f();
3573
+ }
3574
+ }); // Stop all children
3575
+
3576
+
3577
+ Object.values(this.state.children).forEach(function (child) {
3578
+ if (isFunction(child.stop)) {
3579
+ child.stop();
3580
+ }
3581
+ }); // Cancel all delayed events
3582
+
3583
+ for (var _i = 0, _Object$keys = Object.keys(this.delayedEventsMap); _i < _Object$keys.length; _i++) {
3584
+ var key = _Object$keys[_i];
3585
+ this.clock.clearTimeout(this.delayedEventsMap[key]);
3586
+ }
3587
+
3588
+ this.mailbox.clear(); // TODO: after `stop` we must prepare ourselves for receiving events again
3589
+ // events sent *after* stop signal must be queued
3590
+ // it seems like this should be the common behavior for all of our consumers
3591
+ // so perhaps this should be unified somehow for all of them
3592
+
3593
+ this.mailbox = new Mailbox(this._process.bind(this));
3594
+ this.status = exports.InterpreterStatus.Stopped;
3595
+ this._initialState = undefined;
3596
+ registry.free(this.sessionId);
3597
+ return this;
3598
+ }
3599
+ /**
3600
+ * Sends an event to the running interpreter to trigger a transition.
3601
+ *
3602
+ * An array of events (batched) can be sent as well, which will send all
3603
+ * batched events to the running interpreter. The listeners will be
3604
+ * notified only **once** when all events are processed.
3605
+ *
3606
+ * @param event The event(s) to send
3607
+ */
3608
+
3609
+ }, {
3610
+ key: "sendTo",
3611
+ value: function sendTo(event, to) {
3612
+ var isParent = this._parent && to === exports.SpecialTargets.Parent;
3613
+ var target = isParent ? this._parent : isActorRef(to) ? to : this.state.children[to];
3614
+
3615
+ if (!target) {
3616
+ if (!isParent) {
3617
+ var executionError = new Error("Unable to send event to child '".concat(to, "' from service '").concat(this.name, "'."));
3618
+ this.send(toSCXMLEvent(errorExecution, {
3619
+ data: executionError // TODO: refine
3620
+
3621
+ }) // TODO: fix
3622
+ );
3623
+ } // tslint:disable-next-line:no-console
3624
+
3625
+ return;
3626
+ }
3627
+
3628
+ target.send(_objectSpread2(_objectSpread2({}, event), {}, {
3629
+ name: event.name === error ? "".concat(error$1(this.name)) : event.name,
3630
+ origin: this
3631
+ }));
3632
+ }
3633
+ /**
3634
+ * Returns the next state given the interpreter's current state and the event.
3635
+ *
3636
+ * This is a pure method that does _not_ update the interpreter's state.
3637
+ *
3638
+ * @param event The event to determine the next state
3639
+ */
3640
+
3641
+ }, {
3642
+ key: "nextState",
3643
+ value: function nextState(event) {
3644
+ return this.machine.transition(this.state, event);
3645
+ }
3646
+ }, {
3647
+ key: "forward",
3648
+ value: function forward(event) {
3649
+ var _iterator6 = _createForOfIteratorHelper(this.forwardTo),
3650
+ _step6;
3651
+
3652
+ try {
3653
+ for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
3654
+ var _id = _step6.value;
3655
+ var child = this.state.children[_id];
3656
+
3657
+ if (!child) {
3658
+ throw new Error("Unable to forward event '".concat(event.name, "' from interpreter '").concat(this.name, "' to nonexistant child '").concat(_id, "'."));
3659
+ }
3660
+
3661
+ child.send(event);
3662
+ }
3663
+ } catch (err) {
3664
+ _iterator6.e(err);
3665
+ } finally {
3666
+ _iterator6.f();
3667
+ }
3668
+ }
3669
+ }, {
3670
+ key: "defer",
3671
+ value: function defer(sendAction) {
3672
+ var _this5 = this;
3673
+
3674
+ this.delayedEventsMap[sendAction.params.id] = this.clock.setTimeout(function () {
3675
+ if (sendAction.params.to) {
3676
+ _this5.sendTo(sendAction.params._event, sendAction.params.to);
3677
+ } else {
3678
+ _this5.send(sendAction.params._event);
3679
+ }
3680
+ }, sendAction.params.delay);
3681
+ }
3682
+ }, {
3683
+ key: "cancel",
3684
+ value: function cancel(sendId) {
3685
+ this.clock.clearTimeout(this.delayedEventsMap[sendId]);
3686
+ delete this.delayedEventsMap[sendId];
3687
+ }
3688
+ }, {
3689
+ key: "getActionFunction",
3690
+ value: function getActionFunction(actionType) {
3691
+ var _this$machine$options,
3692
+ _this6 = this,
3693
+ _actionTypes$send$act;
3694
+
3695
+ return (_this$machine$options = this.machine.options.actions[actionType]) !== null && _this$machine$options !== void 0 ? _this$machine$options : (_actionTypes$send$act = {}, _defineProperty(_actionTypes$send$act, send, function (_ctx, _e, _ref) {
3696
+ var action = _ref.action;
3697
+ var sendAction = action;
3698
+
3699
+ if (typeof sendAction.params.delay === 'number') {
3700
+ _this6.defer(sendAction);
3701
+
3702
+ return;
3703
+ } else {
3704
+ if (sendAction.params.to) {
3705
+ _this6.sendTo(sendAction.params._event, sendAction.params.to);
3706
+ } else {
3707
+ _this6.send(sendAction.params._event);
3708
+ }
3709
+ }
3710
+ }), _defineProperty(_actionTypes$send$act, cancel, function (_ctx, _e, _ref2) {
3711
+ var action = _ref2.action;
3712
+
3713
+ _this6.cancel(action.params.sendId);
3714
+ }), _defineProperty(_actionTypes$send$act, invoke, function (_ctx, _e, _ref3) {
3715
+ var action = _ref3.action,
3716
+ state = _ref3.state;
3717
+ var _params = action.params,
3718
+ id = _params.id,
3719
+ autoForward = _params.autoForward,
3720
+ ref = _params.ref;
3721
+
3722
+ if (!ref) {
3723
+
3724
+ return;
3725
+ }
3726
+
3727
+ ref._parent = _this6; // TODO: fix
3728
+ // If the actor will be stopped right after it's started
3729
+ // (such as in transient states) don't bother starting the actor.
3730
+
3731
+ if (state.actions.find(function (otherAction) {
3732
+ return otherAction.type === stop && otherAction.params.actor === id;
3733
+ })) {
3734
+ return;
3735
+ }
3736
+
3737
+ try {
3738
+ var _ref$start;
3739
+
3740
+ if (autoForward) {
3741
+ _this6.forwardTo.add(id);
3742
+ } // TODO: determine how this can be immutably updated
3743
+
3744
+
3745
+ _this6.state.children[id] = ref;
3746
+ (_ref$start = ref.start) === null || _ref$start === void 0 ? void 0 : _ref$start.call(ref);
3747
+ } catch (err) {
3748
+ _this6.send(error$1(id, err));
3749
+
3750
+ return;
3751
+ }
3752
+ }), _defineProperty(_actionTypes$send$act, stop, function (_ctx, _e, _ref4) {
3753
+ var action = _ref4.action;
3754
+ var actor = action.params.actor;
3755
+ var actorRef = typeof actor === 'string' ? _this6.state.children[actor] : actor;
3756
+
3757
+ if (actorRef) {
3758
+ _this6.stopChild(actorRef.name);
3759
+ }
3760
+ }), _defineProperty(_actionTypes$send$act, log, function (_ctx, _e, _ref5) {
3761
+ var action = _ref5.action;
3762
+ var _params2 = action.params,
3763
+ label = _params2.label,
3764
+ value = _params2.value;
3765
+
3766
+ if (label) {
3767
+ _this6.logger(label, value);
3768
+ } else {
3769
+ _this6.logger(value);
3770
+ }
3771
+ }), _actionTypes$send$act)[actionType];
3772
+ }
3773
+ }, {
3774
+ key: "exec",
3775
+ value: function exec(action, state) {
3776
+
3777
+ var _event = state._event;
3778
+
3779
+ if (isExecutableAction(action)) {
3780
+ try {
3781
+ return action.execute(state);
3782
+ } catch (err) {
3783
+ var _this$_parent;
3784
+
3785
+ (_this$_parent = this._parent) === null || _this$_parent === void 0 ? void 0 : _this$_parent.send({
3786
+ type: 'xstate.error',
3787
+ data: err
3788
+ });
3789
+ throw err;
3790
+ }
3791
+ }
3792
+
3793
+ var actionOrExec = this.getActionFunction(action.type);
3794
+ var exec = isFunction(actionOrExec) ? actionOrExec : undefined;
3795
+
3796
+ if (exec) {
3797
+ try {
3798
+ return exec(state.context, _event.data, {
3799
+ action: action,
3800
+ state: this.state,
3801
+ _event: _event
3802
+ });
3803
+ } catch (err) {
3804
+ if (this._parent) {
3805
+ this._parent.send({
3806
+ type: 'xstate.error',
3807
+ data: err
3808
+ });
3809
+ }
3810
+
3811
+ throw err;
3812
+ }
3813
+ }
3814
+
3815
+ return undefined;
3816
+ }
3817
+ }, {
3818
+ key: "stopChild",
3819
+ value: function stopChild(childId) {
3820
+ var child = this.state.children[childId];
3821
+
3822
+ if (!child) {
3823
+ return;
3824
+ }
3825
+
3826
+ this.forwardTo["delete"](childId); // TODO: determine how this can be immutably updated
3827
+
3828
+ delete this.state.children[childId];
3829
+
3830
+ if (isFunction(child.stop)) {
3831
+ child.stop();
3832
+ }
3833
+ }
3834
+ }, {
3835
+ key: "attachDevTools",
3836
+ value: function attachDevTools() {
3837
+ var devTools = this.options.devTools;
3838
+
3839
+ if (devTools) {
3840
+ var resolvedDevToolsAdapter = typeof devTools === 'function' ? devTools : dev_dist_xstateDev.devToolsAdapter;
3841
+ resolvedDevToolsAdapter(this);
3842
+ }
3843
+ }
3844
+ }, {
3845
+ key: "toJSON",
3846
+ value: function toJSON() {
3847
+ return {
3848
+ id: this.name
3849
+ };
3850
+ }
3851
+ }, {
3852
+ key: symbolObservable,
3853
+ value: function value() {
3854
+ return this;
3855
+ }
3856
+ }, {
3857
+ key: "getSnapshot",
3858
+ value: function getSnapshot() {
3859
+ if (this.status === exports.InterpreterStatus.NotStarted) {
3860
+ return this.initialState;
3861
+ }
3862
+
3863
+ return this._state;
3864
+ }
3865
+ }]);
3866
+
3867
+ return Interpreter;
3868
+ }();
3869
+ /**
3870
+ * Creates a new Interpreter instance for the given machine with the provided options, if any.
3871
+ *
3872
+ * @param machine The machine to interpret
3873
+ * @param options Interpreter options
3874
+ */
3875
+
3876
+ function interpret(machine, options) {
3877
+ var interpreter = new Interpreter(machine, options);
3878
+ return interpreter;
3879
+ }
3880
+
3881
+ /**
3882
+ * Returns an actor behavior from a reducer and its initial state.
3883
+ *
3884
+ * @param transition The pure reducer that returns the next state given the current state and event.
3885
+ * @param initialState The initial state of the reducer.
3886
+ * @returns An actor behavior
3887
+ */
3888
+
3889
+ function fromReducer(_transition, initialState) {
3890
+ return {
3891
+ transition: function transition(state, event, actorCtx) {
3892
+ // @ts-ignore TODO
3893
+ var resolvedEvent = isSCXMLEvent(event) ? event.data : event; // @ts-ignore TODO
3894
+
3895
+ return _transition(state, resolvedEvent, actorCtx);
3896
+ },
3897
+ initialState: initialState
3898
+ };
3899
+ }
3900
+ var startSignalType = Symbol["for"]('xstate.invoke');
3901
+ var stopSignalType = Symbol["for"]('xstate.stop');
3902
+ var startSignal = {
3903
+ type: startSignalType
3904
+ };
3905
+ var stopSignal = {
3906
+ type: stopSignalType
3907
+ };
3908
+
3909
+ /**
3910
+ * An object that expresses the behavior of an actor in reaction to received events,
3911
+ * as well as an optionally emitted stream of values.
3912
+ *
3913
+ * @template TReceived The received event
3914
+ * @template TSnapshot The emitted value
3915
+ */
3916
+ function isSignal(event) {
3917
+ return _typeof(event.type) === 'symbol';
3918
+ }
3919
+
3920
+ function fromCallback(invokeCallback) {
3921
+ var canceled = false;
3922
+ var receivers = new Set();
3923
+ var dispose;
3924
+ var behavior = {
3925
+ transition: function transition(_, event, _ref) {
3926
+ var self = _ref.self,
3927
+ name = _ref.name;
3928
+ var parent = self._parent;
3929
+
3930
+ if (event.type === startSignalType) {
3931
+ var sender = function sender(e) {
3932
+ if (canceled) {
3933
+ return;
3934
+ }
3935
+
3936
+ parent === null || parent === void 0 ? void 0 : parent.send(toSCXMLEvent(e, {
3937
+ origin: self
3938
+ }));
3939
+ };
3940
+
3941
+ var receiver = function receiver(newListener) {
3942
+ receivers.add(newListener);
3943
+ };
3944
+
3945
+ dispose = invokeCallback(sender, receiver);
3946
+
3947
+ if (isPromiseLike(dispose)) {
3948
+ dispose.then(function (resolved) {
3949
+ var _self$_parent;
3950
+
3951
+ (_self$_parent = self._parent) === null || _self$_parent === void 0 ? void 0 : _self$_parent.send(toSCXMLEvent(doneInvoke(name, resolved), {
3952
+ origin: self
3953
+ }));
3954
+ canceled = true;
3955
+ }, function (errorData) {
3956
+ var _self$_parent2;
3957
+
3958
+ var errorEvent = error$1(name, errorData);
3959
+ (_self$_parent2 = self._parent) === null || _self$_parent2 === void 0 ? void 0 : _self$_parent2.send(toSCXMLEvent(errorEvent, {
3960
+ origin: self
3961
+ }));
3962
+ canceled = true;
3963
+ });
3964
+ }
3965
+
3966
+ return undefined;
3967
+ } else if (event.type === stopSignalType) {
3968
+ canceled = true;
3969
+
3970
+ if (isFunction(dispose)) {
3971
+ dispose();
3972
+ }
3973
+
3974
+ return undefined;
3975
+ }
3976
+
3977
+ if (isSignal(event)) {
3978
+ // TODO: unrecognized signal
3979
+ return undefined;
3980
+ }
3981
+
3982
+ var plainEvent = isSCXMLEvent(event) ? event.data : event;
3983
+ receivers.forEach(function (receiver) {
3984
+ return receiver(plainEvent);
3985
+ });
3986
+ return undefined;
3987
+ },
3988
+ initialState: undefined
3989
+ };
3990
+ return behavior;
3991
+ }
3992
+ function fromPromise(lazyPromise) {
3993
+ var canceled = false;
3994
+ var resolveEventType = Symbol('resolve');
3995
+ var rejectEventType = Symbol('reject'); // TODO: add event types
3996
+
3997
+ var behavior = {
3998
+ transition: function transition(state, event, _ref2) {
3999
+ var _self$_parent3, _self$_parent4;
4000
+
4001
+ var self = _ref2.self,
4002
+ name = _ref2.name;
4003
+
4004
+ if (canceled) {
4005
+ return state;
4006
+ }
4007
+
4008
+ switch (event.type) {
4009
+ case startSignalType:
4010
+ var resolvedPromise = Promise.resolve(lazyPromise());
4011
+ resolvedPromise.then(function (response) {
4012
+ self.send({
4013
+ type: resolveEventType,
4014
+ data: response
4015
+ });
4016
+ }, function (errorData) {
4017
+ self.send({
4018
+ type: rejectEventType,
4019
+ data: errorData
4020
+ });
4021
+ });
4022
+ return undefined;
4023
+
4024
+ case resolveEventType:
4025
+ (_self$_parent3 = self._parent) === null || _self$_parent3 === void 0 ? void 0 : _self$_parent3.send(toSCXMLEvent(doneInvoke(name, event.data), {
4026
+ origin: self
4027
+ }));
4028
+ return event.data;
4029
+
4030
+ case rejectEventType:
4031
+ var errorEvent = error$1(name, event.data);
4032
+ (_self$_parent4 = self._parent) === null || _self$_parent4 === void 0 ? void 0 : _self$_parent4.send(toSCXMLEvent(errorEvent, {
4033
+ origin: self
4034
+ }));
4035
+ return event.data;
4036
+
4037
+ case stopSignalType:
4038
+ canceled = true;
4039
+ return undefined;
4040
+
4041
+ default:
4042
+ return undefined;
4043
+ }
4044
+ },
4045
+ initialState: undefined
4046
+ };
4047
+ return behavior;
4048
+ }
4049
+ function fromObservable(lazyObservable) {
4050
+ var subscription;
4051
+ var observable;
4052
+ var nextEventType = Symbol('next');
4053
+ var errorEventType = Symbol('error');
4054
+ var completeEventType = Symbol('complete');
4055
+ var canceled = false; // TODO: add event types
4056
+
4057
+ var behavior = {
4058
+ transition: function transition(state, event, _ref3) {
4059
+ var _self$_parent5, _self$_parent6, _self$_parent7, _subscription;
4060
+
4061
+ var self = _ref3.self,
4062
+ name = _ref3.name;
4063
+
4064
+ if (canceled) {
4065
+ return state;
4066
+ }
4067
+
4068
+ switch (event.type) {
4069
+ case startSignalType:
4070
+ observable = lazyObservable();
4071
+ subscription = observable.subscribe({
4072
+ next: function next(value) {
4073
+ self.send({
4074
+ type: nextEventType,
4075
+ data: value
4076
+ });
4077
+ },
4078
+ error: function error(err) {
4079
+ self.send({
4080
+ type: errorEventType,
4081
+ data: err
4082
+ });
4083
+ },
4084
+ complete: function complete() {
4085
+ self.send({
4086
+ type: completeEventType
4087
+ });
4088
+ }
4089
+ });
4090
+ return state;
4091
+
4092
+ case nextEventType:
4093
+ (_self$_parent5 = self._parent) === null || _self$_parent5 === void 0 ? void 0 : _self$_parent5.send(toSCXMLEvent({
4094
+ type: "xstate.snapshot.".concat(name),
4095
+ data: event.data
4096
+ }, {
4097
+ origin: self
4098
+ }));
4099
+ return event.data;
4100
+
4101
+ case errorEventType:
4102
+ var errorEvent = error$1(name, event.data);
4103
+ (_self$_parent6 = self._parent) === null || _self$_parent6 === void 0 ? void 0 : _self$_parent6.send(toSCXMLEvent(errorEvent, {
4104
+ origin: self
4105
+ }));
4106
+ return state;
4107
+
4108
+ case completeEventType:
4109
+ (_self$_parent7 = self._parent) === null || _self$_parent7 === void 0 ? void 0 : _self$_parent7.send(toSCXMLEvent(doneInvoke(name), {
4110
+ origin: self
4111
+ }));
4112
+ return state;
4113
+
4114
+ case stopSignalType:
4115
+ canceled = true;
4116
+ (_subscription = subscription) === null || _subscription === void 0 ? void 0 : _subscription.unsubscribe();
4117
+ return state;
4118
+
4119
+ default:
4120
+ return state;
4121
+ }
4122
+ },
4123
+ initialState: undefined
4124
+ };
4125
+ return behavior;
4126
+ }
4127
+ /**
4128
+ * Creates an event observable behavior that listens to an observable
4129
+ * that delivers event objects.
4130
+ *
4131
+ *
4132
+ * @param lazyObservable A function that creates an observable
4133
+ * @returns An event observable behavior
4134
+ */
4135
+
4136
+ function fromEventObservable(lazyObservable) {
4137
+ var subscription;
4138
+ var observable;
4139
+ var nextEventType = Symbol('next');
4140
+ var errorEventType = Symbol('error');
4141
+ var completeEventType = Symbol('complete');
4142
+ var canceled = false; // TODO: event types
4143
+
4144
+ var behavior = {
4145
+ transition: function transition(state, event, _ref4) {
4146
+ var _self$_parent9, _self$_parent10, _subscription2;
4147
+
4148
+ var self = _ref4.self,
4149
+ name = _ref4.name;
4150
+
4151
+ if (canceled) {
4152
+ return state;
4153
+ }
4154
+
4155
+ switch (event.type) {
4156
+ case startSignalType:
4157
+ observable = lazyObservable();
4158
+ subscription = observable.subscribe({
4159
+ next: function next(value) {
4160
+ var _self$_parent8;
4161
+
4162
+ (_self$_parent8 = self._parent) === null || _self$_parent8 === void 0 ? void 0 : _self$_parent8.send(toSCXMLEvent(value, {
4163
+ origin: self
4164
+ }));
4165
+ },
4166
+ error: function error(err) {
4167
+ self.send({
4168
+ type: errorEventType,
4169
+ data: err
4170
+ });
4171
+ },
4172
+ complete: function complete() {
4173
+ self.send({
4174
+ type: completeEventType
4175
+ });
4176
+ }
4177
+ });
4178
+ return state;
4179
+
4180
+ case nextEventType:
4181
+ return event.data;
4182
+
4183
+ case errorEventType:
4184
+ var errorEvent = error$1(name, event.data);
4185
+ (_self$_parent9 = self._parent) === null || _self$_parent9 === void 0 ? void 0 : _self$_parent9.send(toSCXMLEvent(errorEvent, {
4186
+ origin: self
4187
+ }));
4188
+ return state;
4189
+
4190
+ case completeEventType:
4191
+ (_self$_parent10 = self._parent) === null || _self$_parent10 === void 0 ? void 0 : _self$_parent10.send(toSCXMLEvent(doneInvoke(name), {
4192
+ origin: self
4193
+ }));
4194
+ return state;
4195
+
4196
+ case stopSignalType:
4197
+ canceled = true;
4198
+ (_subscription2 = subscription) === null || _subscription2 === void 0 ? void 0 : _subscription2.unsubscribe();
4199
+ return state;
4200
+
4201
+ default:
4202
+ return state;
4203
+ }
4204
+ },
4205
+ initialState: undefined
4206
+ };
4207
+ return behavior;
4208
+ }
4209
+ function fromMachine(machine) {
4210
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
4211
+ var snapshotEventType = Symbol('snapshot');
4212
+ var castedMachine = machine;
4213
+ var service;
4214
+ var initialState; // TODO: use better type for `TEvent`
4215
+
4216
+ var behavior = {
4217
+ transition: function transition(state, event, actorContext) {
4218
+ var _service, _service2;
4219
+
4220
+ var parent = actorContext.self._parent;
4221
+
4222
+ switch (event.type) {
4223
+ case startSignalType:
4224
+ service = interpret(castedMachine, _objectSpread2(_objectSpread2({}, options), {}, {
4225
+ parent: parent,
4226
+ id: actorContext.name
4227
+ }));
4228
+ service.onDone(function (doneEvent) {
4229
+ parent === null || parent === void 0 ? void 0 : parent.send(toSCXMLEvent(doneEvent, {
4230
+ origin: actorContext.self
4231
+ }));
4232
+ });
4233
+ service.subscribe(function (state) {
4234
+ actorContext.self.send({
4235
+ type: snapshotEventType,
4236
+ snapshot: state
4237
+ });
4238
+ });
4239
+ service.start();
4240
+ return state;
4241
+
4242
+ case stopSignalType:
4243
+ (_service = service) === null || _service === void 0 ? void 0 : _service.stop();
4244
+ return state;
4245
+
4246
+ case snapshotEventType:
4247
+ {
4248
+ var snapshot = event.snapshot;
4249
+
4250
+ if (options.sync) {
4251
+ parent === null || parent === void 0 ? void 0 : parent.send(toSCXMLEvent({
4252
+ type: update,
4253
+ state: snapshot
4254
+ }, {
4255
+ origin: actorContext.self
4256
+ }));
4257
+ }
4258
+
4259
+ return snapshot;
4260
+ }
4261
+
4262
+ default:
4263
+ var _event = actorContext._event;
4264
+
4265
+ if (isSignal(_event)) {
4266
+ // TODO: unrecognized signal
4267
+ return state;
4268
+ }
4269
+
4270
+ (_service2 = service) === null || _service2 === void 0 ? void 0 : _service2.send(_event);
4271
+ return state;
4272
+ }
4273
+ },
4274
+
4275
+ get initialState() {
4276
+ // TODO: recheck if this caching is needed, write a test for its importance or remove the caching
4277
+ if (initialState) {
4278
+ return initialState;
4279
+ }
4280
+
4281
+ initialState = castedMachine.getInitialState();
4282
+ return initialState;
4283
+ }
4284
+
4285
+ };
4286
+ return behavior;
4287
+ }
4288
+ function isActorRef(item) {
4289
+ return !!item && _typeof(item) === 'object' && typeof item.send === 'function';
4290
+ } // TODO: refactor the return type, this could be written in a better way
4291
+ // but it's best to avoid unneccessary breaking changes now
4292
+
4293
+ function toActorRef(actorRefLike) {
4294
+ return _objectSpread2(_defineProperty({
4295
+ subscribe: function subscribe() {
4296
+ return {
4297
+ unsubscribe: function unsubscribe() {
4298
+ return void 0;
4299
+ }
4300
+ };
4301
+ },
4302
+ name: 'anonymous',
4303
+ getSnapshot: function getSnapshot() {
4304
+ return undefined;
4305
+ }
4306
+ }, symbolObservable, function () {
4307
+ return this;
4308
+ }), actorRefLike);
4309
+ }
4310
+
4311
+ var ObservableActorRef = /*#__PURE__*/function () {
4312
+ function ObservableActorRef(behavior, name) {
4313
+ _classCallCheck(this, ObservableActorRef);
4314
+
4315
+ this.behavior = behavior;
4316
+ this.name = name;
4317
+
4318
+ _defineProperty(this, "current", void 0);
4319
+
4320
+ _defineProperty(this, "context", void 0);
4321
+
4322
+ _defineProperty(this, "mailbox", new Mailbox(this._process.bind(this)));
4323
+
4324
+ _defineProperty(this, "_observers", new Set());
4325
+
4326
+ this.context = {
4327
+ self: this,
4328
+ name: this.name,
4329
+ _event: toSCXMLEvent({
4330
+ type: 'xstate.init'
4331
+ }) // TODO: fix
4332
+
4333
+ };
4334
+ this.current = this.behavior.initialState;
4335
+ }
4336
+
4337
+ _createClass(ObservableActorRef, [{
4338
+ key: "start",
4339
+ value: function start() {
4340
+ this.mailbox.prepend(startSignal);
4341
+ this.mailbox.start();
4342
+ return this;
4343
+ }
4344
+ }, {
4345
+ key: "stop",
4346
+ value: function stop() {
4347
+ this.mailbox.clear();
4348
+ this.mailbox.enqueue(stopSignal);
4349
+ return this;
4350
+ }
4351
+ }, {
4352
+ key: "subscribe",
4353
+ value: function subscribe(observer) {
4354
+ var _this = this;
4355
+
4356
+ var resolved = toObserver(observer);
4357
+
4358
+ this._observers.add(resolved);
4359
+
4360
+ return {
4361
+ unsubscribe: function unsubscribe() {
4362
+ _this._observers["delete"](resolved);
4363
+ }
4364
+ };
4365
+ }
4366
+ }, {
4367
+ key: "send",
4368
+ value: function send(event) {
4369
+ this.receive(event);
4370
+ }
4371
+ }, {
4372
+ key: "toJSON",
4373
+ value: function toJSON() {
4374
+ return {
4375
+ name: this.name,
4376
+ current: this.current
4377
+ };
4378
+ }
4379
+ }, {
4380
+ key: "getSnapshot",
4381
+ value: function getSnapshot() {
4382
+ return this.current;
4383
+ }
4384
+ }, {
4385
+ key: symbolObservable,
4386
+ value: function value() {
4387
+ return this;
4388
+ }
4389
+ }, {
4390
+ key: "receive",
4391
+ value: function receive(event) {
4392
+ this.mailbox.enqueue(event);
4393
+ }
4394
+ }, {
4395
+ key: "_process",
4396
+ value: function _process(event) {
4397
+ this.context._event = typeof event.type !== 'string' ? event : toSCXMLEvent(event);
4398
+ var previous = this.current;
4399
+ this.current = this.behavior.transition(this.current, typeof this.context._event.type !== 'string' ? this.context._event : this.context._event.data, this.context);
4400
+
4401
+ if (previous !== this.current) {
4402
+ var current = this.current;
4403
+
4404
+ this._observers.forEach(function (observer) {
4405
+ var _observer$next;
4406
+
4407
+ return (_observer$next = observer.next) === null || _observer$next === void 0 ? void 0 : _observer$next.call(observer, current);
4408
+ });
4409
+ }
4410
+ }
4411
+ }]);
4412
+
4413
+ return ObservableActorRef;
4414
+ }();
4415
+
4416
+ function createSpawner(machine, context, _event, mutCapturedActions) {
4417
+ return function (behavior, name) {
4418
+ if (isString(behavior)) {
4419
+ var behaviorCreator = machine.options.actors[behavior];
4420
+
4421
+ if (behaviorCreator) {
4422
+ var resolvedName = name !== null && name !== void 0 ? name : 'anon'; // TODO: better name
4423
+
4424
+ var createdBehavior = behaviorCreator(context, _event.data, {
4425
+ id: name || 'anon',
4426
+ src: {
4427
+ type: behavior
4428
+ },
4429
+ _event: _event,
4430
+ meta: undefined
4431
+ });
4432
+ var actorRef = new ObservableActorRef(createdBehavior, resolvedName);
4433
+ mutCapturedActions.push({
4434
+ type: exports.ActionTypes.Invoke,
4435
+ params: {
4436
+ src: actorRef,
4437
+ ref: actorRef,
4438
+ id: actorRef.name,
4439
+ meta: undefined
4440
+ }
4441
+ });
4442
+ return actorRef; // TODO: fix types
4443
+ }
4444
+
4445
+ throw new Error("Behavior '".concat(behavior, "' not implemented in machine '").concat(machine.key, "'"));
4446
+ } else {
4447
+ var _actorRef = new ObservableActorRef(behavior, name || 'anonymous');
4448
+
4449
+ mutCapturedActions.push({
4450
+ type: exports.ActionTypes.Invoke,
4451
+ params: {
4452
+ src: _actorRef,
4453
+ ref: _actorRef,
4454
+ id: _actorRef.name,
4455
+ meta: undefined
4456
+ }
4457
+ });
4458
+ return _actorRef; // TODO: fix types
4459
+ }
4460
+ };
4461
+ }
4462
+
4463
+ /**
4464
+ * Updates the current context of the machine.
4465
+ *
4466
+ * @param assignment An object that represents the partial context to update.
4467
+ */
4468
+
4469
+ function assign$1(assignment) {
4470
+ return createDynamicAction(assign, {
4471
+ assignment: assignment
4472
+ }, function (_, context, _event, _ref) {
4473
+ var machine = _ref.machine,
4474
+ state = _ref.state,
4475
+ action = _ref.action;
4476
+ var capturedActions = [];
4477
+
4478
+ if (!context) {
4479
+ throw new Error('Cannot assign to undefined `context`. Ensure that `context` is defined in the machine config.');
4480
+ }
4481
+
4482
+ var meta = {
4483
+ state: state,
4484
+ action: action,
4485
+ _event: _event,
4486
+ spawn: createSpawner(machine, context, _event, capturedActions)
4487
+ };
4488
+ var partialUpdate = {};
4489
+
4490
+ if (isFunction(assignment)) {
4491
+ partialUpdate = assignment(context, _event.data, meta);
4492
+ } else {
4493
+ for (var _i = 0, _Object$keys = Object.keys(assignment); _i < _Object$keys.length; _i++) {
4494
+ var key = _Object$keys[_i];
4495
+ var propAssignment = assignment[key];
4496
+ partialUpdate[key] = isFunction(propAssignment) ? propAssignment(context, _event.data, meta) : propAssignment;
4497
+ }
4498
+ }
4499
+
4500
+ var updatedContext = Object.assign({}, context, partialUpdate);
4501
+ return {
4502
+ type: assign,
4503
+ params: {
4504
+ context: updatedContext,
4505
+ actions: capturedActions
4506
+ }
4507
+ };
4508
+ });
4509
+ }
4510
+
4511
+ /**
4512
+ * Raises an event. This places the event in the internal event queue, so that
4513
+ * the event is immediately consumed by the machine in the current step.
4514
+ *
4515
+ * @param eventType The event to raise.
4516
+ */
4517
+ function raise$1(event) {
4518
+ return createDynamicAction(raise, {
4519
+ _event: toSCXMLEvent(event)
4520
+ }, function (_ref) {
4521
+ var params = _ref.params;
4522
+ return {
4523
+ type: raise,
4524
+ params: {
4525
+ _event: params._event
4526
+ }
4527
+ };
4528
+ });
4529
+ }
4530
+
4531
+ function choose$1(guards) {
4532
+ return createDynamicAction(choose, {
4533
+ guards: guards
4534
+ }, function (_ref, context, _event, _ref2) {
4535
+ var _params$guards$find;
4536
+
4537
+ var params = _ref.params;
4538
+ var machine = _ref2.machine,
4539
+ state = _ref2.state;
4540
+ var matchedActions = (_params$guards$find = params.guards.find(function (condition) {
4541
+ var guard = condition.guard && toGuardDefinition(condition.guard, function (guardType) {
4542
+ return machine.options.guards[guardType];
4543
+ });
4544
+ return !guard || evaluateGuard(guard, context, _event, state, machine);
4545
+ })) === null || _params$guards$find === void 0 ? void 0 : _params$guards$find.actions;
4546
+ return {
4547
+ type: choose,
4548
+ params: {
4549
+ actions: toArray(matchedActions).map(function (chosenAction) {
4550
+ return toActionObject(chosenAction);
4551
+ })
4552
+ }
4553
+ };
4554
+ });
4555
+ }
4556
+
4557
+ var initEvent = toSCXMLEvent({
4558
+ type: init
4559
+ });
4560
+ function getActionFunction(actionType, actionFunctionMap) {
4561
+ return actionFunctionMap ? actionFunctionMap[actionType] || undefined : undefined;
4562
+ }
4563
+ function resolveActionObject(actionObject, actionFunctionMap) {
4564
+ var exec = getActionFunction(actionObject.type, actionFunctionMap);
4565
+
4566
+ if (isFunction(exec)) {
4567
+ return new ExecutableAction(actionObject, exec);
4568
+ } else if (exec) {
4569
+ return exec;
4570
+ } else {
4571
+ return actionObject;
4572
+ }
4573
+ }
4574
+ function toActionObject(action, actionFunctionMap) {
4575
+ if (isDynamicAction(action)) {
4576
+ return action;
4577
+ }
4578
+
4579
+ if (isString(action) || typeof action === 'number') {
4580
+ return resolveActionObject({
4581
+ type: action,
4582
+ params: {}
4583
+ }, actionFunctionMap);
4584
+ } else if (isFunction(action)) {
4585
+ var _action$name;
4586
+
4587
+ return new ExecutableAction({
4588
+ type: (_action$name = action.name) !== null && _action$name !== void 0 ? _action$name : 'xstate:expr',
4589
+ params: {}
4590
+ }, action);
4591
+ } else {
4592
+ // action is already a BaseActionObject
4593
+ return action;
4594
+ }
4595
+ }
4596
+ var toActionObjects = function toActionObjects(action, actionFunctionMap) {
4597
+ if (!action) {
4598
+ return [];
4599
+ }
4600
+
4601
+ var actions = isArray(action) ? action : [action];
4602
+ return actions.map(function (subAction) {
4603
+ return toActionObject(subAction, actionFunctionMap);
4604
+ });
4605
+ };
4606
+ /**
4607
+ * Returns an event type that represents an implicit event that
4608
+ * is sent after the specified `delay`.
4609
+ *
4610
+ * @param delayRef The delay in milliseconds
4611
+ * @param id The state node ID where this event is handled
4612
+ */
4613
+
4614
+ function after$1(delayRef, id) {
4615
+ var idSuffix = id ? "#".concat(id) : '';
4616
+ return "".concat(exports.ActionTypes.After, "(").concat(delayRef, ")").concat(idSuffix);
4617
+ }
4618
+ /**
4619
+ * Returns an event that represents that a final state node
4620
+ * has been reached in the parent state node.
4621
+ *
4622
+ * @param id The final state node's parent state node `id`
4623
+ * @param data The data to pass into the event
4624
+ */
4625
+
4626
+ function done(id, data) {
4627
+ var type = "".concat(exports.ActionTypes.DoneState, ".").concat(id);
4628
+ var eventObject = {
4629
+ type: type,
4630
+ data: data
4631
+ };
4632
+
4633
+ eventObject.toString = function () {
4634
+ return type;
4635
+ };
4636
+
4637
+ return eventObject;
4638
+ }
4639
+ /**
4640
+ * Returns an event that represents that an invoked service has terminated.
4641
+ *
4642
+ * An invoked service is terminated when it has reached a top-level final state node,
4643
+ * but not when it is canceled.
4644
+ *
4645
+ * @param invokeId The invoked service ID
4646
+ * @param data The data to pass into the event
4647
+ */
4648
+
4649
+ function doneInvoke(invokeId, data) {
4650
+ var type = "".concat(exports.ActionTypes.DoneInvoke, ".").concat(invokeId);
4651
+ var eventObject = {
4652
+ type: type,
4653
+ data: data
4654
+ };
4655
+
4656
+ eventObject.toString = function () {
4657
+ return type;
4658
+ };
4659
+
4660
+ return eventObject;
4661
+ }
4662
+ function error$1(id, data) {
4663
+ var type = "".concat(exports.ActionTypes.ErrorPlatform, ".").concat(id);
4664
+ var eventObject = {
4665
+ type: type,
4666
+ data: data
4667
+ };
4668
+
4669
+ eventObject.toString = function () {
4670
+ return type;
4671
+ };
4672
+
4673
+ return eventObject;
4674
+ }
4675
+
4676
+ exports.Interpreter = Interpreter;
4677
+ exports.NULL_EVENT = NULL_EVENT;
4678
+ exports.ObservableActorRef = ObservableActorRef;
4679
+ exports.STATE_DELIMITER = STATE_DELIMITER;
4680
+ exports.State = State;
4681
+ exports._classCallCheck = _classCallCheck;
4682
+ exports._createClass = _createClass;
4683
+ exports._createForOfIteratorHelper = _createForOfIteratorHelper;
4684
+ exports._defineProperty = _defineProperty;
4685
+ exports._objectSpread2 = _objectSpread2;
4686
+ exports._objectWithoutProperties = _objectWithoutProperties;
4687
+ exports._slicedToArray = _slicedToArray;
4688
+ exports._toConsumableArray = _toConsumableArray;
4689
+ exports.actionTypes = actionTypes;
4690
+ exports.after = after$1;
4691
+ exports.and = and;
4692
+ exports.assign = assign$1;
4693
+ exports.cancel = cancel$1;
4694
+ exports.choose = choose$1;
4695
+ exports.createDynamicAction = createDynamicAction;
4696
+ exports.createInvokeId = createInvokeId;
4697
+ exports.createSpawner = createSpawner;
4698
+ exports.done = done;
4699
+ exports.doneInvoke = doneInvoke;
4700
+ exports.error = error$1;
4701
+ exports.escalate = escalate;
4702
+ exports.evaluateGuard = evaluateGuard;
4703
+ exports.flatten = flatten;
4704
+ exports.formatInitialTransition = formatInitialTransition;
4705
+ exports.formatTransition = formatTransition;
4706
+ exports.formatTransitions = formatTransitions;
4707
+ exports.forwardTo = forwardTo;
4708
+ exports.fromCallback = fromCallback;
4709
+ exports.fromEventObservable = fromEventObservable;
4710
+ exports.fromMachine = fromMachine;
4711
+ exports.fromObservable = fromObservable;
4712
+ exports.fromPromise = fromPromise;
4713
+ exports.fromReducer = fromReducer;
4714
+ exports.getActionFunction = getActionFunction;
4715
+ exports.getCandidates = getCandidates;
4716
+ exports.getConfiguration = getConfiguration;
4717
+ exports.getDelayedTransitions = getDelayedTransitions;
4718
+ exports.getEventType = getEventType;
4719
+ exports.getStateNodes = getStateNodes;
4720
+ exports.getStateValue = getStateValue;
4721
+ exports.initEvent = initEvent;
4722
+ exports.interpret = interpret;
4723
+ exports.invoke = invoke;
4724
+ exports.isActorRef = isActorRef;
4725
+ exports.isBuiltInEvent = isBuiltInEvent;
4726
+ exports.isFunction = isFunction;
4727
+ exports.isStateId = isStateId;
4728
+ exports.isString = isString;
4729
+ exports.log = log$1;
4730
+ exports.macrostep = macrostep;
4731
+ exports.mapValues = mapValues;
4732
+ exports.matchesState = matchesState;
4733
+ exports.memo = memo;
4734
+ exports.not = not;
4735
+ exports.or = or;
4736
+ exports.pathToStateValue = pathToStateValue;
4737
+ exports.pure = pure;
4738
+ exports.raise = raise$1;
4739
+ exports.resolveActionObject = resolveActionObject;
4740
+ exports.resolveMicroTransition = resolveMicroTransition;
4741
+ exports.resolveStateValue = resolveStateValue;
4742
+ exports.respond = respond;
4743
+ exports.send = send$1;
4744
+ exports.sendParent = sendParent;
4745
+ exports.sendTo = sendTo;
4746
+ exports.sendUpdate = sendUpdate;
4747
+ exports.startSignal = startSignal;
4748
+ exports.startSignalType = startSignalType;
4749
+ exports.stateIn = stateIn;
4750
+ exports.stop = stop$1;
4751
+ exports.stopSignal = stopSignal;
4752
+ exports.stopSignalType = stopSignalType;
4753
+ exports.toActionObject = toActionObject;
4754
+ exports.toActionObjects = toActionObjects;
4755
+ exports.toActorRef = toActorRef;
4756
+ exports.toArray = toArray;
4757
+ exports.toEventObject = toEventObject;
4758
+ exports.toGuardDefinition = toGuardDefinition;
4759
+ exports.toInvokeConfig = toInvokeConfig;
4760
+ exports.toInvokeSource = toInvokeSource;
4761
+ exports.toObserver = toObserver;
4762
+ exports.toSCXMLEvent = toSCXMLEvent;
4763
+ exports.toState = toState;
4764
+ exports.toTransitionConfigArray = toTransitionConfigArray;
4765
+ exports.transitionNode = transitionNode;