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