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