UNPKG

54.3 kBJavaScriptView Raw
1import { __assign, __spreadArray, __read, __values, __rest } from './_virtual/_tslib.js';
2import { isFunction, mapValues, isArray, flatten, toArray, toStateValue, isString, getEventType, toSCXMLEvent, matchesState, path, evaluateGuard, mapContext, isRaisableAction, pathToStateValue, isBuiltInEvent, partition, updateHistoryValue, toStatePath, mapFilterValues, warn, toStatePaths, nestedPath, normalizeTarget, toGuard, toTransitionConfigArray, isMachine, createInvokeId } from './utils.js';
3import { State, stateValuesEqual } from './State.js';
4import { start as start$1, stop as stop$1, invoke, update, nullEvent } from './actionTypes.js';
5import { done, start, toActionObjects, raise, stop, resolveActions, doneInvoke, error, toActionObject, toActivityDefinition, after, send, cancel, initEvent } from './actions.js';
6import { IS_PRODUCTION } from './environment.js';
7import { STATE_DELIMITER } from './constants.js';
8import { getAllStateNodes, getConfiguration, isInFinalState, getTagsFromConfiguration, has, getChildren, getValue, isLeafNode, getAllChildren } from './stateUtils.js';
9import { createInvocableActor } from './Actor.js';
10import { toInvokeDefinition } from './invokeUtils.js';
11
12var NULL_EVENT = '';
13var STATE_IDENTIFIER = '#';
14var WILDCARD = '*';
15var EMPTY_OBJECT = {};
16
17var isStateId = function (str) {
18 return str[0] === STATE_IDENTIFIER;
19};
20
21var createDefaultOptions = function () {
22 return {
23 actions: {},
24 guards: {},
25 services: {},
26 activities: {},
27 delays: {}
28 };
29};
30
31var validateArrayifiedTransitions = function (stateNode, event, transitions) {
32 var hasNonLastUnguardedTarget = transitions.slice(0, -1).some(function (transition) {
33 return !('cond' in transition) && !('in' in transition) && (isString(transition.target) || isMachine(transition.target));
34 });
35 var eventText = event === NULL_EVENT ? 'the transient event' : "event '".concat(event, "'");
36 warn(!hasNonLastUnguardedTarget, "One or more transitions for ".concat(eventText, " on state '").concat(stateNode.id, "' are unreachable. ") + "Make sure that the default transition is the last one defined.");
37};
38
39var StateNode =
40/*#__PURE__*/
41
42/** @class */
43function () {
44 function StateNode(
45 /**
46 * The raw config used to create the machine.
47 */
48 config, options,
49 /**
50 * The initial extended state
51 */
52 _context, // TODO: this is unsafe, but we're removing it in v5 anyway
53 _stateInfo) {
54 if (_context === void 0) {
55 _context = 'context' in config ? config.context : undefined;
56 }
57
58 var _this = this;
59
60 var _a;
61
62 this.config = config;
63 this._context = _context;
64 /**
65 * The order this state node appears. Corresponds to the implicit SCXML document order.
66 */
67
68 this.order = -1;
69 this.__xstatenode = true;
70 this.__cache = {
71 events: undefined,
72 relativeValue: new Map(),
73 initialStateValue: undefined,
74 initialState: undefined,
75 on: undefined,
76 transitions: undefined,
77 candidates: {},
78 delayedTransitions: undefined
79 };
80 this.idMap = {};
81 this.tags = [];
82 this.options = Object.assign(createDefaultOptions(), options);
83 this.parent = _stateInfo === null || _stateInfo === void 0 ? void 0 : _stateInfo.parent;
84 this.key = this.config.key || (_stateInfo === null || _stateInfo === void 0 ? void 0 : _stateInfo.key) || this.config.id || '(machine)';
85 this.machine = this.parent ? this.parent.machine : this;
86 this.path = this.parent ? this.parent.path.concat(this.key) : [];
87 this.delimiter = this.config.delimiter || (this.parent ? this.parent.delimiter : STATE_DELIMITER);
88 this.id = this.config.id || __spreadArray([this.machine.key], __read(this.path), false).join(this.delimiter);
89 this.version = this.parent ? this.parent.version : this.config.version;
90 this.type = this.config.type || (this.config.parallel ? 'parallel' : this.config.states && Object.keys(this.config.states).length ? 'compound' : this.config.history ? 'history' : 'atomic');
91 this.schema = this.parent ? this.machine.schema : (_a = this.config.schema) !== null && _a !== void 0 ? _a : {};
92 this.description = this.config.description;
93
94 if (!IS_PRODUCTION) {
95 warn(!('parallel' in this.config), "The \"parallel\" property is deprecated and will be removed in version 4.1. ".concat(this.config.parallel ? "Replace with `type: 'parallel'`" : "Use `type: '".concat(this.type, "'`"), " in the config for state node '").concat(this.id, "' instead."));
96 }
97
98 this.initial = this.config.initial;
99 this.states = this.config.states ? mapValues(this.config.states, function (stateConfig, key) {
100 var _a;
101
102 var stateNode = new StateNode(stateConfig, {}, undefined, {
103 parent: _this,
104 key: key
105 });
106 Object.assign(_this.idMap, __assign((_a = {}, _a[stateNode.id] = stateNode, _a), stateNode.idMap));
107 return stateNode;
108 }) : EMPTY_OBJECT; // Document order
109
110 var order = 0;
111
112 function dfs(stateNode) {
113 var e_1, _a;
114
115 stateNode.order = order++;
116
117 try {
118 for (var _b = __values(getAllChildren(stateNode)), _c = _b.next(); !_c.done; _c = _b.next()) {
119 var child = _c.value;
120 dfs(child);
121 }
122 } catch (e_1_1) {
123 e_1 = {
124 error: e_1_1
125 };
126 } finally {
127 try {
128 if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
129 } finally {
130 if (e_1) throw e_1.error;
131 }
132 }
133 }
134
135 dfs(this); // History config
136
137 this.history = this.config.history === true ? 'shallow' : this.config.history || false;
138 this._transient = !!this.config.always || (!this.config.on ? false : Array.isArray(this.config.on) ? this.config.on.some(function (_a) {
139 var event = _a.event;
140 return event === NULL_EVENT;
141 }) : NULL_EVENT in this.config.on);
142 this.strict = !!this.config.strict; // TODO: deprecate (entry)
143
144 this.onEntry = toArray(this.config.entry || this.config.onEntry).map(function (action) {
145 return toActionObject(action);
146 }); // TODO: deprecate (exit)
147
148 this.onExit = toArray(this.config.exit || this.config.onExit).map(function (action) {
149 return toActionObject(action);
150 });
151 this.meta = this.config.meta;
152 this.doneData = this.type === 'final' ? this.config.data : undefined;
153 this.invoke = toArray(this.config.invoke).map(function (invokeConfig, i) {
154 var _a, _b;
155
156 if (isMachine(invokeConfig)) {
157 var invokeId = createInvokeId(_this.id, i);
158 _this.machine.options.services = __assign((_a = {}, _a[invokeId] = invokeConfig, _a), _this.machine.options.services);
159 return toInvokeDefinition({
160 src: invokeId,
161 id: invokeId
162 });
163 } else if (isString(invokeConfig.src)) {
164 var invokeId = invokeConfig.id || createInvokeId(_this.id, i);
165 return toInvokeDefinition(__assign(__assign({}, invokeConfig), {
166 id: invokeId,
167 src: invokeConfig.src
168 }));
169 } else if (isMachine(invokeConfig.src) || isFunction(invokeConfig.src)) {
170 var invokeId = invokeConfig.id || createInvokeId(_this.id, i);
171 _this.machine.options.services = __assign((_b = {}, _b[invokeId] = invokeConfig.src, _b), _this.machine.options.services);
172 return toInvokeDefinition(__assign(__assign({
173 id: invokeId
174 }, invokeConfig), {
175 src: invokeId
176 }));
177 } else {
178 var invokeSource = invokeConfig.src;
179 return toInvokeDefinition(__assign(__assign({
180 id: createInvokeId(_this.id, i)
181 }, invokeConfig), {
182 src: invokeSource
183 }));
184 }
185 });
186 this.activities = toArray(this.config.activities).concat(this.invoke).map(function (activity) {
187 return toActivityDefinition(activity);
188 });
189 this.transition = this.transition.bind(this);
190 this.tags = toArray(this.config.tags); // TODO: this is the real fix for initialization once
191 // state node getters are deprecated
192 // if (!this.parent) {
193 // this._init();
194 // }
195 }
196
197 StateNode.prototype._init = function () {
198 if (this.__cache.transitions) {
199 return;
200 }
201
202 getAllStateNodes(this).forEach(function (stateNode) {
203 return stateNode.on;
204 });
205 };
206 /**
207 * Clones this state machine with custom options and context.
208 *
209 * @param options Options (actions, guards, activities, services) to recursively merge with the existing options.
210 * @param context Custom context (will override predefined context)
211 */
212
213
214 StateNode.prototype.withConfig = function (options, context) {
215 var _a = this.options,
216 actions = _a.actions,
217 activities = _a.activities,
218 guards = _a.guards,
219 services = _a.services,
220 delays = _a.delays;
221 return new StateNode(this.config, {
222 actions: __assign(__assign({}, actions), options.actions),
223 activities: __assign(__assign({}, activities), options.activities),
224 guards: __assign(__assign({}, guards), options.guards),
225 services: __assign(__assign({}, services), options.services),
226 delays: __assign(__assign({}, delays), options.delays)
227 }, context !== null && context !== void 0 ? context : this.context);
228 };
229 /**
230 * Clones this state machine with custom context.
231 *
232 * @param context Custom context (will override predefined context, not recursive)
233 */
234
235
236 StateNode.prototype.withContext = function (context) {
237 return new StateNode(this.config, this.options, context);
238 };
239
240 Object.defineProperty(StateNode.prototype, "context", {
241 get: function () {
242 return isFunction(this._context) ? this._context() : this._context;
243 },
244 enumerable: false,
245 configurable: true
246 });
247 Object.defineProperty(StateNode.prototype, "definition", {
248 /**
249 * The well-structured state node definition.
250 */
251 get: function () {
252 return {
253 id: this.id,
254 key: this.key,
255 version: this.version,
256 context: this.context,
257 type: this.type,
258 initial: this.initial,
259 history: this.history,
260 states: mapValues(this.states, function (state) {
261 return state.definition;
262 }),
263 on: this.on,
264 transitions: this.transitions,
265 entry: this.onEntry,
266 exit: this.onExit,
267 activities: this.activities || [],
268 meta: this.meta,
269 order: this.order || -1,
270 data: this.doneData,
271 invoke: this.invoke,
272 description: this.description,
273 tags: this.tags
274 };
275 },
276 enumerable: false,
277 configurable: true
278 });
279
280 StateNode.prototype.toJSON = function () {
281 return this.definition;
282 };
283
284 Object.defineProperty(StateNode.prototype, "on", {
285 /**
286 * The mapping of events to transitions.
287 */
288 get: function () {
289 if (this.__cache.on) {
290 return this.__cache.on;
291 }
292
293 var transitions = this.transitions;
294 return this.__cache.on = transitions.reduce(function (map, transition) {
295 map[transition.eventType] = map[transition.eventType] || [];
296 map[transition.eventType].push(transition);
297 return map;
298 }, {});
299 },
300 enumerable: false,
301 configurable: true
302 });
303 Object.defineProperty(StateNode.prototype, "after", {
304 get: function () {
305 return this.__cache.delayedTransitions || (this.__cache.delayedTransitions = this.getDelayedTransitions(), this.__cache.delayedTransitions);
306 },
307 enumerable: false,
308 configurable: true
309 });
310 Object.defineProperty(StateNode.prototype, "transitions", {
311 /**
312 * All the transitions that can be taken from this state node.
313 */
314 get: function () {
315 return this.__cache.transitions || (this.__cache.transitions = this.formatTransitions(), this.__cache.transitions);
316 },
317 enumerable: false,
318 configurable: true
319 });
320
321 StateNode.prototype.getCandidates = function (eventName) {
322 if (this.__cache.candidates[eventName]) {
323 return this.__cache.candidates[eventName];
324 }
325
326 var transient = eventName === NULL_EVENT;
327 var candidates = this.transitions.filter(function (transition) {
328 var sameEventType = transition.eventType === eventName; // null events should only match against eventless transitions
329
330 return transient ? sameEventType : sameEventType || transition.eventType === WILDCARD;
331 });
332 this.__cache.candidates[eventName] = candidates;
333 return candidates;
334 };
335 /**
336 * All delayed transitions from the config.
337 */
338
339
340 StateNode.prototype.getDelayedTransitions = function () {
341 var _this = this;
342
343 var afterConfig = this.config.after;
344
345 if (!afterConfig) {
346 return [];
347 }
348
349 var mutateEntryExit = function (delay, i) {
350 var delayRef = isFunction(delay) ? "".concat(_this.id, ":delay[").concat(i, "]") : delay;
351 var eventType = after(delayRef, _this.id);
352
353 _this.onEntry.push(send(eventType, {
354 delay: delay
355 }));
356
357 _this.onExit.push(cancel(eventType));
358
359 return eventType;
360 };
361
362 var delayedTransitions = isArray(afterConfig) ? afterConfig.map(function (transition, i) {
363 var eventType = mutateEntryExit(transition.delay, i);
364 return __assign(__assign({}, transition), {
365 event: eventType
366 });
367 }) : flatten(Object.keys(afterConfig).map(function (delay, i) {
368 var configTransition = afterConfig[delay];
369 var resolvedTransition = isString(configTransition) ? {
370 target: configTransition
371 } : configTransition;
372 var resolvedDelay = !isNaN(+delay) ? +delay : delay;
373 var eventType = mutateEntryExit(resolvedDelay, i);
374 return toArray(resolvedTransition).map(function (transition) {
375 return __assign(__assign({}, transition), {
376 event: eventType,
377 delay: resolvedDelay
378 });
379 });
380 }));
381 return delayedTransitions.map(function (delayedTransition) {
382 var delay = delayedTransition.delay;
383 return __assign(__assign({}, _this.formatTransition(delayedTransition)), {
384 delay: delay
385 });
386 });
387 };
388 /**
389 * Returns the state nodes represented by the current state value.
390 *
391 * @param state The state value or State instance
392 */
393
394
395 StateNode.prototype.getStateNodes = function (state) {
396 var _a;
397
398 var _this = this;
399
400 if (!state) {
401 return [];
402 }
403
404 var stateValue = state instanceof State ? state.value : toStateValue(state, this.delimiter);
405
406 if (isString(stateValue)) {
407 var initialStateValue = this.getStateNode(stateValue).initial;
408 return initialStateValue !== undefined ? this.getStateNodes((_a = {}, _a[stateValue] = initialStateValue, _a)) : [this, this.states[stateValue]];
409 }
410
411 var subStateKeys = Object.keys(stateValue);
412 var subStateNodes = [this];
413 subStateNodes.push.apply(subStateNodes, __spreadArray([], __read(flatten(subStateKeys.map(function (subStateKey) {
414 return _this.getStateNode(subStateKey).getStateNodes(stateValue[subStateKey]);
415 }))), false));
416 return subStateNodes;
417 };
418 /**
419 * Returns `true` if this state node explicitly handles the given event.
420 *
421 * @param event The event in question
422 */
423
424
425 StateNode.prototype.handles = function (event) {
426 var eventType = getEventType(event);
427 return this.events.includes(eventType);
428 };
429 /**
430 * Resolves the given `state` to a new `State` instance relative to this machine.
431 *
432 * This ensures that `.events` and `.nextEvents` represent the correct values.
433 *
434 * @param state The state to resolve
435 */
436
437
438 StateNode.prototype.resolveState = function (state) {
439 var stateFromConfig = state instanceof State ? state : State.create(state);
440 var configuration = Array.from(getConfiguration([], this.getStateNodes(stateFromConfig.value)));
441 return new State(__assign(__assign({}, stateFromConfig), {
442 value: this.resolve(stateFromConfig.value),
443 configuration: configuration,
444 done: isInFinalState(configuration, this),
445 tags: getTagsFromConfiguration(configuration),
446 machine: this.machine
447 }));
448 };
449
450 StateNode.prototype.transitionLeafNode = function (stateValue, state, _event) {
451 var stateNode = this.getStateNode(stateValue);
452 var next = stateNode.next(state, _event);
453
454 if (!next || !next.transitions.length) {
455 return this.next(state, _event);
456 }
457
458 return next;
459 };
460
461 StateNode.prototype.transitionCompoundNode = function (stateValue, state, _event) {
462 var subStateKeys = Object.keys(stateValue);
463 var stateNode = this.getStateNode(subStateKeys[0]);
464
465 var next = stateNode._transition(stateValue[subStateKeys[0]], state, _event);
466
467 if (!next || !next.transitions.length) {
468 return this.next(state, _event);
469 }
470
471 return next;
472 };
473
474 StateNode.prototype.transitionParallelNode = function (stateValue, state, _event) {
475 var e_2, _a;
476
477 var transitionMap = {};
478
479 try {
480 for (var _b = __values(Object.keys(stateValue)), _c = _b.next(); !_c.done; _c = _b.next()) {
481 var subStateKey = _c.value;
482 var subStateValue = stateValue[subStateKey];
483
484 if (!subStateValue) {
485 continue;
486 }
487
488 var subStateNode = this.getStateNode(subStateKey);
489
490 var next = subStateNode._transition(subStateValue, state, _event);
491
492 if (next) {
493 transitionMap[subStateKey] = next;
494 }
495 }
496 } catch (e_2_1) {
497 e_2 = {
498 error: e_2_1
499 };
500 } finally {
501 try {
502 if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
503 } finally {
504 if (e_2) throw e_2.error;
505 }
506 }
507
508 var stateTransitions = Object.keys(transitionMap).map(function (key) {
509 return transitionMap[key];
510 });
511 var enabledTransitions = flatten(stateTransitions.map(function (st) {
512 return st.transitions;
513 }));
514 var willTransition = stateTransitions.some(function (st) {
515 return st.transitions.length > 0;
516 });
517
518 if (!willTransition) {
519 return this.next(state, _event);
520 }
521
522 var configuration = flatten(Object.keys(transitionMap).map(function (key) {
523 return transitionMap[key].configuration;
524 }));
525 return {
526 transitions: enabledTransitions,
527 exitSet: flatten(stateTransitions.map(function (t) {
528 return t.exitSet;
529 })),
530 configuration: configuration,
531 source: state,
532 actions: flatten(Object.keys(transitionMap).map(function (key) {
533 return transitionMap[key].actions;
534 }))
535 };
536 };
537
538 StateNode.prototype._transition = function (stateValue, state, _event) {
539 // leaf node
540 if (isString(stateValue)) {
541 return this.transitionLeafNode(stateValue, state, _event);
542 } // hierarchical node
543
544
545 if (Object.keys(stateValue).length === 1) {
546 return this.transitionCompoundNode(stateValue, state, _event);
547 } // orthogonal node
548
549
550 return this.transitionParallelNode(stateValue, state, _event);
551 };
552
553 StateNode.prototype.getTransitionData = function (state, event) {
554 return this._transition(state.value, state, toSCXMLEvent(event));
555 };
556
557 StateNode.prototype.next = function (state, _event) {
558 var e_3, _a;
559
560 var _this = this;
561
562 var eventName = _event.name;
563 var actions = [];
564 var nextStateNodes = [];
565 var selectedTransition;
566
567 try {
568 for (var _b = __values(this.getCandidates(eventName)), _c = _b.next(); !_c.done; _c = _b.next()) {
569 var candidate = _c.value;
570 var cond = candidate.cond,
571 stateIn = candidate.in;
572 var resolvedContext = state.context;
573 var isInState = stateIn ? isString(stateIn) && isStateId(stateIn) ? // Check if in state by ID
574 state.matches(toStateValue(this.getStateNodeById(stateIn).path, this.delimiter)) : // Check if in state by relative grandparent
575 matchesState(toStateValue(stateIn, this.delimiter), path(this.path.slice(0, -2))(state.value)) : true;
576 var guardPassed = false;
577
578 try {
579 guardPassed = !cond || evaluateGuard(this.machine, cond, resolvedContext, _event, state);
580 } catch (err) {
581 throw new Error("Unable to evaluate guard '".concat(cond.name || cond.type, "' in transition for event '").concat(eventName, "' in state node '").concat(this.id, "':\n").concat(err.message));
582 }
583
584 if (guardPassed && isInState) {
585 if (candidate.target !== undefined) {
586 nextStateNodes = candidate.target;
587 }
588
589 actions.push.apply(actions, __spreadArray([], __read(candidate.actions), false));
590 selectedTransition = candidate;
591 break;
592 }
593 }
594 } catch (e_3_1) {
595 e_3 = {
596 error: e_3_1
597 };
598 } finally {
599 try {
600 if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
601 } finally {
602 if (e_3) throw e_3.error;
603 }
604 }
605
606 if (!selectedTransition) {
607 return undefined;
608 }
609
610 if (!nextStateNodes.length) {
611 return {
612 transitions: [selectedTransition],
613 exitSet: [],
614 configuration: state.value ? [this] : [],
615 source: state,
616 actions: actions
617 };
618 }
619
620 var allNextStateNodes = flatten(nextStateNodes.map(function (stateNode) {
621 return _this.getRelativeStateNodes(stateNode, state.historyValue);
622 }));
623 var isInternal = !!selectedTransition.internal;
624 return {
625 transitions: [selectedTransition],
626 exitSet: isInternal ? [] : flatten(nextStateNodes.map(function (targetNode) {
627 return _this.getPotentiallyReenteringNodes(targetNode);
628 })),
629 configuration: allNextStateNodes,
630 source: state,
631 actions: actions
632 };
633 }; // even though the name of this function mentions reentry nodes
634 // we are pushing its result into `exitSet`
635 // that's because what we exit might be reentered (it's an invariant of reentrancy)
636
637
638 StateNode.prototype.getPotentiallyReenteringNodes = function (targetNode) {
639 if (this.order < targetNode.order) {
640 return [this];
641 }
642
643 var nodes = [];
644 var marker = this;
645 var possibleAncestor = targetNode;
646
647 while (marker && marker !== possibleAncestor) {
648 nodes.push(marker);
649 marker = marker.parent;
650 }
651
652 if (marker !== possibleAncestor) {
653 // we never got to `possibleAncestor`, therefore the initial `marker` "escapes" it
654 // it's in a different part of the tree so no states will be reentered for such an external transition
655 return [];
656 }
657
658 nodes.push(possibleAncestor);
659 return nodes;
660 };
661
662 StateNode.prototype.getActions = function (resolvedConfig, isDone, transition, currentContext, _event, prevState, predictableExec) {
663 var e_4, _a, e_5, _b;
664
665 var _this = this;
666
667 var prevConfig = prevState ? getConfiguration([], this.getStateNodes(prevState.value)) : [];
668 var entrySet = new Set();
669
670 try {
671 for (var _c = __values(Array.from(resolvedConfig).sort(function (a, b) {
672 return a.order - b.order;
673 })), _d = _c.next(); !_d.done; _d = _c.next()) {
674 var sn = _d.value;
675
676 if (!has(prevConfig, sn) || has(transition.exitSet, sn) || sn.parent && entrySet.has(sn.parent)) {
677 entrySet.add(sn);
678 }
679 }
680 } catch (e_4_1) {
681 e_4 = {
682 error: e_4_1
683 };
684 } finally {
685 try {
686 if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
687 } finally {
688 if (e_4) throw e_4.error;
689 }
690 }
691
692 try {
693 for (var prevConfig_1 = __values(prevConfig), prevConfig_1_1 = prevConfig_1.next(); !prevConfig_1_1.done; prevConfig_1_1 = prevConfig_1.next()) {
694 var sn = prevConfig_1_1.value;
695
696 if (!has(resolvedConfig, sn) || has(transition.exitSet, sn.parent)) {
697 transition.exitSet.push(sn);
698 }
699 }
700 } catch (e_5_1) {
701 e_5 = {
702 error: e_5_1
703 };
704 } finally {
705 try {
706 if (prevConfig_1_1 && !prevConfig_1_1.done && (_b = prevConfig_1.return)) _b.call(prevConfig_1);
707 } finally {
708 if (e_5) throw e_5.error;
709 }
710 }
711
712 transition.exitSet.sort(function (a, b) {
713 return b.order - a.order;
714 });
715 var entryStates = Array.from(entrySet).sort(function (a, b) {
716 return a.order - b.order;
717 });
718 var exitStates = new Set(transition.exitSet);
719 var doneEvents = flatten(entryStates.map(function (sn) {
720 var events = [];
721
722 if (sn.type !== 'final') {
723 return events;
724 }
725
726 var parent = sn.parent;
727
728 if (!parent.parent) {
729 return events;
730 }
731
732 events.push(done(sn.id, sn.doneData), // TODO: deprecate - final states should not emit done events for their own state.
733 done(parent.id, sn.doneData ? mapContext(sn.doneData, currentContext, _event) : undefined));
734 var grandparent = parent.parent;
735
736 if (grandparent.type === 'parallel') {
737 if (getChildren(grandparent).every(function (parentNode) {
738 return isInFinalState(transition.configuration, parentNode);
739 })) {
740 events.push(done(grandparent.id));
741 }
742 }
743
744 return events;
745 }));
746 var entryActions = entryStates.map(function (stateNode) {
747 var entryActions = stateNode.onEntry;
748 var invokeActions = stateNode.activities.map(function (activity) {
749 return start(activity);
750 });
751 return {
752 type: 'entry',
753 actions: toActionObjects(predictableExec ? __spreadArray(__spreadArray([], __read(entryActions), false), __read(invokeActions), false) : __spreadArray(__spreadArray([], __read(invokeActions), false), __read(entryActions), false), _this.machine.options.actions)
754 };
755 }).concat({
756 type: 'state_done',
757 actions: doneEvents.map(function (event) {
758 return raise(event);
759 })
760 });
761 var exitActions = Array.from(exitStates).map(function (stateNode) {
762 return {
763 type: 'exit',
764 actions: toActionObjects(__spreadArray(__spreadArray([], __read(stateNode.onExit), false), __read(stateNode.activities.map(function (activity) {
765 return stop(activity);
766 })), false), _this.machine.options.actions)
767 };
768 });
769 var actions = exitActions.concat({
770 type: 'transition',
771 actions: toActionObjects(transition.actions, this.machine.options.actions)
772 }).concat(entryActions);
773
774 if (isDone) {
775 var stopActions = toActionObjects(flatten(__spreadArray([], __read(resolvedConfig), false).sort(function (a, b) {
776 return b.order - a.order;
777 }).map(function (stateNode) {
778 return stateNode.onExit;
779 })), this.machine.options.actions).filter(function (action) {
780 return !isRaisableAction(action);
781 });
782 return actions.concat({
783 type: 'stop',
784 actions: stopActions
785 });
786 }
787
788 return actions;
789 };
790 /**
791 * Determines the next state given the current `state` and sent `event`.
792 *
793 * @param state The current State instance or state value
794 * @param event The event that was sent at the current state
795 * @param context The current context (extended state) of the current state
796 */
797
798
799 StateNode.prototype.transition = function (state, event, context, exec) {
800 if (state === void 0) {
801 state = this.initialState;
802 }
803
804 var _event = toSCXMLEvent(event);
805
806 var currentState;
807
808 if (state instanceof State) {
809 currentState = context === undefined ? state : this.resolveState(State.from(state, context));
810 } else {
811 var resolvedStateValue = isString(state) ? this.resolve(pathToStateValue(this.getResolvedPath(state))) : this.resolve(state);
812 var resolvedContext = context !== null && context !== void 0 ? context : this.machine.context;
813 currentState = this.resolveState(State.from(resolvedStateValue, resolvedContext));
814 }
815
816 if (!IS_PRODUCTION && _event.name === WILDCARD) {
817 throw new Error("An event cannot have the wildcard type ('".concat(WILDCARD, "')"));
818 }
819
820 if (this.strict) {
821 if (!this.events.includes(_event.name) && !isBuiltInEvent(_event.name)) {
822 throw new Error("Machine '".concat(this.id, "' does not accept event '").concat(_event.name, "'"));
823 }
824 }
825
826 var stateTransition = this._transition(currentState.value, currentState, _event) || {
827 transitions: [],
828 configuration: [],
829 exitSet: [],
830 source: currentState,
831 actions: []
832 };
833 var prevConfig = getConfiguration([], this.getStateNodes(currentState.value));
834 var resolvedConfig = stateTransition.configuration.length ? getConfiguration(prevConfig, stateTransition.configuration) : prevConfig;
835 stateTransition.configuration = __spreadArray([], __read(resolvedConfig), false);
836 return this.resolveTransition(stateTransition, currentState, currentState.context, exec, _event);
837 };
838
839 StateNode.prototype.resolveRaisedTransition = function (state, _event, originalEvent, predictableExec) {
840 var _a;
841
842 var currentActions = state.actions;
843 state = this.transition(state, _event, undefined, predictableExec); // Save original event to state
844 // TODO: this should be the raised event! Delete in V5 (breaking)
845
846 state._event = originalEvent;
847 state.event = originalEvent.data;
848
849 (_a = state.actions).unshift.apply(_a, __spreadArray([], __read(currentActions), false));
850
851 return state;
852 };
853
854 StateNode.prototype.resolveTransition = function (stateTransition, currentState, context, predictableExec, _event) {
855 var e_6, _a, e_7, _b;
856
857 var _this = this;
858
859 if (_event === void 0) {
860 _event = initEvent;
861 }
862
863 var configuration = stateTransition.configuration; // Transition will "apply" if:
864 // - this is the initial state (there is no current state)
865 // - OR there are transitions
866
867 var willTransition = !currentState || stateTransition.transitions.length > 0;
868 var resolvedConfiguration = willTransition ? stateTransition.configuration : currentState ? currentState.configuration : [];
869 var isDone = isInFinalState(resolvedConfiguration, this);
870 var resolvedStateValue = willTransition ? getValue(this.machine, configuration) : undefined;
871 var historyValue = currentState ? currentState.historyValue ? currentState.historyValue : stateTransition.source ? this.machine.historyValue(currentState.value) : undefined : undefined;
872 var actionBlocks = this.getActions(new Set(resolvedConfiguration), isDone, stateTransition, context, _event, currentState, predictableExec);
873 var activities = currentState ? __assign({}, currentState.activities) : {};
874
875 try {
876 for (var actionBlocks_1 = __values(actionBlocks), actionBlocks_1_1 = actionBlocks_1.next(); !actionBlocks_1_1.done; actionBlocks_1_1 = actionBlocks_1.next()) {
877 var block = actionBlocks_1_1.value;
878
879 try {
880 for (var _c = (e_7 = void 0, __values(block.actions)), _d = _c.next(); !_d.done; _d = _c.next()) {
881 var action = _d.value;
882
883 if (action.type === start$1) {
884 activities[action.activity.id || action.activity.type] = action;
885 } else if (action.type === stop$1) {
886 activities[action.activity.id || action.activity.type] = false;
887 }
888 }
889 } catch (e_7_1) {
890 e_7 = {
891 error: e_7_1
892 };
893 } finally {
894 try {
895 if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
896 } finally {
897 if (e_7) throw e_7.error;
898 }
899 }
900 }
901 } catch (e_6_1) {
902 e_6 = {
903 error: e_6_1
904 };
905 } finally {
906 try {
907 if (actionBlocks_1_1 && !actionBlocks_1_1.done && (_a = actionBlocks_1.return)) _a.call(actionBlocks_1);
908 } finally {
909 if (e_6) throw e_6.error;
910 }
911 }
912
913 var _e = __read(resolveActions(this, currentState, context, _event, actionBlocks, predictableExec, this.machine.config.predictableActionArguments || this.machine.config.preserveActionOrder), 2),
914 resolvedActions = _e[0],
915 updatedContext = _e[1];
916
917 var _f = __read(partition(resolvedActions, isRaisableAction), 2),
918 raisedEvents = _f[0],
919 nonRaisedActions = _f[1];
920
921 var invokeActions = resolvedActions.filter(function (action) {
922 var _a;
923
924 return action.type === start$1 && ((_a = action.activity) === null || _a === void 0 ? void 0 : _a.type) === invoke;
925 });
926 var children = invokeActions.reduce(function (acc, action) {
927 acc[action.activity.id] = createInvocableActor(action.activity, _this.machine, updatedContext, _event);
928 return acc;
929 }, currentState ? __assign({}, currentState.children) : {});
930 var nextState = new State({
931 value: resolvedStateValue || currentState.value,
932 context: updatedContext,
933 _event: _event,
934 // Persist _sessionid between states
935 _sessionid: currentState ? currentState._sessionid : null,
936 historyValue: resolvedStateValue ? historyValue ? updateHistoryValue(historyValue, resolvedStateValue) : undefined : currentState ? currentState.historyValue : undefined,
937 history: !resolvedStateValue || stateTransition.source ? currentState : undefined,
938 actions: resolvedStateValue ? nonRaisedActions : [],
939 activities: resolvedStateValue ? activities : currentState ? currentState.activities : {},
940 events: [],
941 configuration: resolvedConfiguration,
942 transitions: stateTransition.transitions,
943 children: children,
944 done: isDone,
945 tags: getTagsFromConfiguration(resolvedConfiguration),
946 machine: this
947 });
948 var didUpdateContext = context !== updatedContext;
949 nextState.changed = _event.name === update || didUpdateContext; // Dispose of penultimate histories to prevent memory leaks
950
951 var history = nextState.history;
952
953 if (history) {
954 delete history.history;
955 } // There are transient transitions if the machine is not in a final state
956 // and if some of the state nodes have transient ("always") transitions.
957
958
959 var hasAlwaysTransitions = !isDone && (this._transient || configuration.some(function (stateNode) {
960 return stateNode._transient;
961 })); // If there are no enabled transitions, check if there are transient transitions.
962 // If there are transient transitions, continue checking for more transitions
963 // because an transient transition should be triggered even if there are no
964 // enabled transitions.
965 //
966 // If we're already working on an transient transition then stop to prevent an infinite loop.
967 //
968 // Otherwise, if there are no enabled nor transient transitions, we are done.
969
970 if (!willTransition && (!hasAlwaysTransitions || _event.name === NULL_EVENT)) {
971 return nextState;
972 }
973
974 var maybeNextState = nextState;
975
976 if (!isDone) {
977 if (hasAlwaysTransitions) {
978 maybeNextState = this.resolveRaisedTransition(maybeNextState, {
979 type: nullEvent
980 }, _event, predictableExec);
981 }
982
983 while (raisedEvents.length) {
984 var raisedEvent = raisedEvents.shift();
985 maybeNextState = this.resolveRaisedTransition(maybeNextState, raisedEvent._event, _event, predictableExec);
986 }
987 } // Detect if state changed
988
989
990 var changed = maybeNextState.changed || (history ? !!maybeNextState.actions.length || didUpdateContext || typeof history.value !== typeof maybeNextState.value || !stateValuesEqual(maybeNextState.value, history.value) : undefined);
991 maybeNextState.changed = changed; // Preserve original history after raised events
992
993 maybeNextState.history = history;
994 return maybeNextState;
995 };
996 /**
997 * Returns the child state node from its relative `stateKey`, or throws.
998 */
999
1000
1001 StateNode.prototype.getStateNode = function (stateKey) {
1002 if (isStateId(stateKey)) {
1003 return this.machine.getStateNodeById(stateKey);
1004 }
1005
1006 if (!this.states) {
1007 throw new Error("Unable to retrieve child state '".concat(stateKey, "' from '").concat(this.id, "'; no child states exist."));
1008 }
1009
1010 var result = this.states[stateKey];
1011
1012 if (!result) {
1013 throw new Error("Child state '".concat(stateKey, "' does not exist on '").concat(this.id, "'"));
1014 }
1015
1016 return result;
1017 };
1018 /**
1019 * Returns the state node with the given `stateId`, or throws.
1020 *
1021 * @param stateId The state ID. The prefix "#" is removed.
1022 */
1023
1024
1025 StateNode.prototype.getStateNodeById = function (stateId) {
1026 var resolvedStateId = isStateId(stateId) ? stateId.slice(STATE_IDENTIFIER.length) : stateId;
1027
1028 if (resolvedStateId === this.id) {
1029 return this;
1030 }
1031
1032 var stateNode = this.machine.idMap[resolvedStateId];
1033
1034 if (!stateNode) {
1035 throw new Error("Child state node '#".concat(resolvedStateId, "' does not exist on machine '").concat(this.id, "'"));
1036 }
1037
1038 return stateNode;
1039 };
1040 /**
1041 * Returns the relative state node from the given `statePath`, or throws.
1042 *
1043 * @param statePath The string or string array relative path to the state node.
1044 */
1045
1046
1047 StateNode.prototype.getStateNodeByPath = function (statePath) {
1048 if (typeof statePath === 'string' && isStateId(statePath)) {
1049 try {
1050 return this.getStateNodeById(statePath.slice(1));
1051 } catch (e) {// try individual paths
1052 // throw e;
1053 }
1054 }
1055
1056 var arrayStatePath = toStatePath(statePath, this.delimiter).slice();
1057 var currentStateNode = this;
1058
1059 while (arrayStatePath.length) {
1060 var key = arrayStatePath.shift();
1061
1062 if (!key.length) {
1063 break;
1064 }
1065
1066 currentStateNode = currentStateNode.getStateNode(key);
1067 }
1068
1069 return currentStateNode;
1070 };
1071 /**
1072 * Resolves a partial state value with its full representation in this machine.
1073 *
1074 * @param stateValue The partial state value to resolve.
1075 */
1076
1077
1078 StateNode.prototype.resolve = function (stateValue) {
1079 var _a;
1080
1081 var _this = this;
1082
1083 if (!stateValue) {
1084 return this.initialStateValue || EMPTY_OBJECT; // TODO: type-specific properties
1085 }
1086
1087 switch (this.type) {
1088 case 'parallel':
1089 return mapValues(this.initialStateValue, function (subStateValue, subStateKey) {
1090 return subStateValue ? _this.getStateNode(subStateKey).resolve(stateValue[subStateKey] || subStateValue) : EMPTY_OBJECT;
1091 });
1092
1093 case 'compound':
1094 if (isString(stateValue)) {
1095 var subStateNode = this.getStateNode(stateValue);
1096
1097 if (subStateNode.type === 'parallel' || subStateNode.type === 'compound') {
1098 return _a = {}, _a[stateValue] = subStateNode.initialStateValue, _a;
1099 }
1100
1101 return stateValue;
1102 }
1103
1104 if (!Object.keys(stateValue).length) {
1105 return this.initialStateValue || {};
1106 }
1107
1108 return mapValues(stateValue, function (subStateValue, subStateKey) {
1109 return subStateValue ? _this.getStateNode(subStateKey).resolve(subStateValue) : EMPTY_OBJECT;
1110 });
1111
1112 default:
1113 return stateValue || EMPTY_OBJECT;
1114 }
1115 };
1116
1117 StateNode.prototype.getResolvedPath = function (stateIdentifier) {
1118 if (isStateId(stateIdentifier)) {
1119 var stateNode = this.machine.idMap[stateIdentifier.slice(STATE_IDENTIFIER.length)];
1120
1121 if (!stateNode) {
1122 throw new Error("Unable to find state node '".concat(stateIdentifier, "'"));
1123 }
1124
1125 return stateNode.path;
1126 }
1127
1128 return toStatePath(stateIdentifier, this.delimiter);
1129 };
1130
1131 Object.defineProperty(StateNode.prototype, "initialStateValue", {
1132 get: function () {
1133 var _a;
1134
1135 if (this.__cache.initialStateValue) {
1136 return this.__cache.initialStateValue;
1137 }
1138
1139 var initialStateValue;
1140
1141 if (this.type === 'parallel') {
1142 initialStateValue = mapFilterValues(this.states, function (state) {
1143 return state.initialStateValue || EMPTY_OBJECT;
1144 }, function (stateNode) {
1145 return !(stateNode.type === 'history');
1146 });
1147 } else if (this.initial !== undefined) {
1148 if (!this.states[this.initial]) {
1149 throw new Error("Initial state '".concat(this.initial, "' not found on '").concat(this.key, "'"));
1150 }
1151
1152 initialStateValue = isLeafNode(this.states[this.initial]) ? this.initial : (_a = {}, _a[this.initial] = this.states[this.initial].initialStateValue, _a);
1153 } else {
1154 // The finite state value of a machine without child states is just an empty object
1155 initialStateValue = {};
1156 }
1157
1158 this.__cache.initialStateValue = initialStateValue;
1159 return this.__cache.initialStateValue;
1160 },
1161 enumerable: false,
1162 configurable: true
1163 });
1164
1165 StateNode.prototype.getInitialState = function (stateValue, context) {
1166 this._init(); // TODO: this should be in the constructor (see note in constructor)
1167
1168
1169 var configuration = this.getStateNodes(stateValue);
1170 return this.resolveTransition({
1171 configuration: configuration,
1172 exitSet: [],
1173 transitions: [],
1174 source: undefined,
1175 actions: []
1176 }, undefined, context !== null && context !== void 0 ? context : this.machine.context, undefined);
1177 };
1178
1179 Object.defineProperty(StateNode.prototype, "initialState", {
1180 /**
1181 * The initial State instance, which includes all actions to be executed from
1182 * entering the initial state.
1183 */
1184 get: function () {
1185 var initialStateValue = this.initialStateValue;
1186
1187 if (!initialStateValue) {
1188 throw new Error("Cannot retrieve initial state from simple state '".concat(this.id, "'."));
1189 }
1190
1191 return this.getInitialState(initialStateValue);
1192 },
1193 enumerable: false,
1194 configurable: true
1195 });
1196 Object.defineProperty(StateNode.prototype, "target", {
1197 /**
1198 * The target state value of the history state node, if it exists. This represents the
1199 * default state value to transition to if no history value exists yet.
1200 */
1201 get: function () {
1202 var target;
1203
1204 if (this.type === 'history') {
1205 var historyConfig = this.config;
1206
1207 if (isString(historyConfig.target)) {
1208 target = isStateId(historyConfig.target) ? pathToStateValue(this.machine.getStateNodeById(historyConfig.target).path.slice(this.path.length - 1)) : historyConfig.target;
1209 } else {
1210 target = historyConfig.target;
1211 }
1212 }
1213
1214 return target;
1215 },
1216 enumerable: false,
1217 configurable: true
1218 });
1219 /**
1220 * Returns the leaf nodes from a state path relative to this state node.
1221 *
1222 * @param relativeStateId The relative state path to retrieve the state nodes
1223 * @param history The previous state to retrieve history
1224 * @param resolve Whether state nodes should resolve to initial child state nodes
1225 */
1226
1227 StateNode.prototype.getRelativeStateNodes = function (relativeStateId, historyValue, resolve) {
1228 if (resolve === void 0) {
1229 resolve = true;
1230 }
1231
1232 return resolve ? relativeStateId.type === 'history' ? relativeStateId.resolveHistory(historyValue) : relativeStateId.initialStateNodes : [relativeStateId];
1233 };
1234
1235 Object.defineProperty(StateNode.prototype, "initialStateNodes", {
1236 get: function () {
1237 var _this = this;
1238
1239 if (isLeafNode(this)) {
1240 return [this];
1241 } // Case when state node is compound but no initial state is defined
1242
1243
1244 if (this.type === 'compound' && !this.initial) {
1245 if (!IS_PRODUCTION) {
1246 warn(false, "Compound state node '".concat(this.id, "' has no initial state."));
1247 }
1248
1249 return [this];
1250 }
1251
1252 var initialStateNodePaths = toStatePaths(this.initialStateValue);
1253 return flatten(initialStateNodePaths.map(function (initialPath) {
1254 return _this.getFromRelativePath(initialPath);
1255 }));
1256 },
1257 enumerable: false,
1258 configurable: true
1259 });
1260 /**
1261 * Retrieves state nodes from a relative path to this state node.
1262 *
1263 * @param relativePath The relative path from this state node
1264 * @param historyValue
1265 */
1266
1267 StateNode.prototype.getFromRelativePath = function (relativePath) {
1268 if (!relativePath.length) {
1269 return [this];
1270 }
1271
1272 var _a = __read(relativePath),
1273 stateKey = _a[0],
1274 childStatePath = _a.slice(1);
1275
1276 if (!this.states) {
1277 throw new Error("Cannot retrieve subPath '".concat(stateKey, "' from node with no states"));
1278 }
1279
1280 var childStateNode = this.getStateNode(stateKey);
1281
1282 if (childStateNode.type === 'history') {
1283 return childStateNode.resolveHistory();
1284 }
1285
1286 if (!this.states[stateKey]) {
1287 throw new Error("Child state '".concat(stateKey, "' does not exist on '").concat(this.id, "'"));
1288 }
1289
1290 return this.states[stateKey].getFromRelativePath(childStatePath);
1291 };
1292
1293 StateNode.prototype.historyValue = function (relativeStateValue) {
1294 if (!Object.keys(this.states).length) {
1295 return undefined;
1296 }
1297
1298 return {
1299 current: relativeStateValue || this.initialStateValue,
1300 states: mapFilterValues(this.states, function (stateNode, key) {
1301 if (!relativeStateValue) {
1302 return stateNode.historyValue();
1303 }
1304
1305 var subStateValue = isString(relativeStateValue) ? undefined : relativeStateValue[key];
1306 return stateNode.historyValue(subStateValue || stateNode.initialStateValue);
1307 }, function (stateNode) {
1308 return !stateNode.history;
1309 })
1310 };
1311 };
1312 /**
1313 * Resolves to the historical value(s) of the parent state node,
1314 * represented by state nodes.
1315 *
1316 * @param historyValue
1317 */
1318
1319
1320 StateNode.prototype.resolveHistory = function (historyValue) {
1321 var _this = this;
1322
1323 if (this.type !== 'history') {
1324 return [this];
1325 }
1326
1327 var parent = this.parent;
1328
1329 if (!historyValue) {
1330 var historyTarget = this.target;
1331 return historyTarget ? flatten(toStatePaths(historyTarget).map(function (relativeChildPath) {
1332 return parent.getFromRelativePath(relativeChildPath);
1333 })) : parent.initialStateNodes;
1334 }
1335
1336 var subHistoryValue = nestedPath(parent.path, 'states')(historyValue).current;
1337
1338 if (isString(subHistoryValue)) {
1339 return [parent.getStateNode(subHistoryValue)];
1340 }
1341
1342 return flatten(toStatePaths(subHistoryValue).map(function (subStatePath) {
1343 return _this.history === 'deep' ? parent.getFromRelativePath(subStatePath) : [parent.states[subStatePath[0]]];
1344 }));
1345 };
1346
1347 Object.defineProperty(StateNode.prototype, "stateIds", {
1348 /**
1349 * All the state node IDs of this state node and its descendant state nodes.
1350 */
1351 get: function () {
1352 var _this = this;
1353
1354 var childStateIds = flatten(Object.keys(this.states).map(function (stateKey) {
1355 return _this.states[stateKey].stateIds;
1356 }));
1357 return [this.id].concat(childStateIds);
1358 },
1359 enumerable: false,
1360 configurable: true
1361 });
1362 Object.defineProperty(StateNode.prototype, "events", {
1363 /**
1364 * All the event types accepted by this state node and its descendants.
1365 */
1366 get: function () {
1367 var e_8, _a, e_9, _b;
1368
1369 if (this.__cache.events) {
1370 return this.__cache.events;
1371 }
1372
1373 var states = this.states;
1374 var events = new Set(this.ownEvents);
1375
1376 if (states) {
1377 try {
1378 for (var _c = __values(Object.keys(states)), _d = _c.next(); !_d.done; _d = _c.next()) {
1379 var stateId = _d.value;
1380 var state = states[stateId];
1381
1382 if (state.states) {
1383 try {
1384 for (var _e = (e_9 = void 0, __values(state.events)), _f = _e.next(); !_f.done; _f = _e.next()) {
1385 var event_1 = _f.value;
1386 events.add("".concat(event_1));
1387 }
1388 } catch (e_9_1) {
1389 e_9 = {
1390 error: e_9_1
1391 };
1392 } finally {
1393 try {
1394 if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
1395 } finally {
1396 if (e_9) throw e_9.error;
1397 }
1398 }
1399 }
1400 }
1401 } catch (e_8_1) {
1402 e_8 = {
1403 error: e_8_1
1404 };
1405 } finally {
1406 try {
1407 if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
1408 } finally {
1409 if (e_8) throw e_8.error;
1410 }
1411 }
1412 }
1413
1414 return this.__cache.events = Array.from(events);
1415 },
1416 enumerable: false,
1417 configurable: true
1418 });
1419 Object.defineProperty(StateNode.prototype, "ownEvents", {
1420 /**
1421 * All the events that have transitions directly from this state node.
1422 *
1423 * Excludes any inert events.
1424 */
1425 get: function () {
1426 var events = new Set(this.transitions.filter(function (transition) {
1427 return !(!transition.target && !transition.actions.length && transition.internal);
1428 }).map(function (transition) {
1429 return transition.eventType;
1430 }));
1431 return Array.from(events);
1432 },
1433 enumerable: false,
1434 configurable: true
1435 });
1436
1437 StateNode.prototype.resolveTarget = function (_target) {
1438 var _this = this;
1439
1440 if (_target === undefined) {
1441 // an undefined target signals that the state node should not transition from that state when receiving that event
1442 return undefined;
1443 }
1444
1445 return _target.map(function (target) {
1446 if (!isString(target)) {
1447 return target;
1448 }
1449
1450 var isInternalTarget = target[0] === _this.delimiter; // If internal target is defined on machine,
1451 // do not include machine key on target
1452
1453 if (isInternalTarget && !_this.parent) {
1454 return _this.getStateNodeByPath(target.slice(1));
1455 }
1456
1457 var resolvedTarget = isInternalTarget ? _this.key + target : target;
1458
1459 if (_this.parent) {
1460 try {
1461 var targetStateNode = _this.parent.getStateNodeByPath(resolvedTarget);
1462
1463 return targetStateNode;
1464 } catch (err) {
1465 throw new Error("Invalid transition definition for state node '".concat(_this.id, "':\n").concat(err.message));
1466 }
1467 } else {
1468 return _this.getStateNodeByPath(resolvedTarget);
1469 }
1470 });
1471 };
1472
1473 StateNode.prototype.formatTransition = function (transitionConfig) {
1474 var _this = this;
1475
1476 var normalizedTarget = normalizeTarget(transitionConfig.target);
1477 var internal = 'internal' in transitionConfig ? transitionConfig.internal : normalizedTarget ? normalizedTarget.some(function (_target) {
1478 return isString(_target) && _target[0] === _this.delimiter;
1479 }) : true;
1480 var guards = this.machine.options.guards;
1481 var target = this.resolveTarget(normalizedTarget);
1482
1483 var transition = __assign(__assign({}, transitionConfig), {
1484 actions: toActionObjects(toArray(transitionConfig.actions)),
1485 cond: toGuard(transitionConfig.cond, guards),
1486 target: target,
1487 source: this,
1488 internal: internal,
1489 eventType: transitionConfig.event,
1490 toJSON: function () {
1491 return __assign(__assign({}, transition), {
1492 target: transition.target ? transition.target.map(function (t) {
1493 return "#".concat(t.id);
1494 }) : undefined,
1495 source: "#".concat(_this.id)
1496 });
1497 }
1498 });
1499
1500 return transition;
1501 };
1502
1503 StateNode.prototype.formatTransitions = function () {
1504 var e_10, _a;
1505
1506 var _this = this;
1507
1508 var onConfig;
1509
1510 if (!this.config.on) {
1511 onConfig = [];
1512 } else if (Array.isArray(this.config.on)) {
1513 onConfig = this.config.on;
1514 } else {
1515 var _b = this.config.on,
1516 _c = WILDCARD,
1517 _d = _b[_c],
1518 wildcardConfigs = _d === void 0 ? [] : _d,
1519 strictTransitionConfigs_1 = __rest(_b, [typeof _c === "symbol" ? _c : _c + ""]);
1520
1521 onConfig = flatten(Object.keys(strictTransitionConfigs_1).map(function (key) {
1522 if (!IS_PRODUCTION && key === NULL_EVENT) {
1523 warn(false, "Empty string transition configs (e.g., `{ on: { '': ... }}`) for transient transitions are deprecated. Specify the transition in the `{ always: ... }` property instead. " + "Please check the `on` configuration for \"#".concat(_this.id, "\"."));
1524 }
1525
1526 var transitionConfigArray = toTransitionConfigArray(key, strictTransitionConfigs_1[key]);
1527
1528 if (!IS_PRODUCTION) {
1529 validateArrayifiedTransitions(_this, key, transitionConfigArray);
1530 }
1531
1532 return transitionConfigArray;
1533 }).concat(toTransitionConfigArray(WILDCARD, wildcardConfigs)));
1534 }
1535
1536 var eventlessConfig = this.config.always ? toTransitionConfigArray('', this.config.always) : [];
1537 var doneConfig = this.config.onDone ? toTransitionConfigArray(String(done(this.id)), this.config.onDone) : [];
1538
1539 if (!IS_PRODUCTION) {
1540 warn(!(this.config.onDone && !this.parent), "Root nodes cannot have an \".onDone\" transition. Please check the config of \"".concat(this.id, "\"."));
1541 }
1542
1543 var invokeConfig = flatten(this.invoke.map(function (invokeDef) {
1544 var settleTransitions = [];
1545
1546 if (invokeDef.onDone) {
1547 settleTransitions.push.apply(settleTransitions, __spreadArray([], __read(toTransitionConfigArray(String(doneInvoke(invokeDef.id)), invokeDef.onDone)), false));
1548 }
1549
1550 if (invokeDef.onError) {
1551 settleTransitions.push.apply(settleTransitions, __spreadArray([], __read(toTransitionConfigArray(String(error(invokeDef.id)), invokeDef.onError)), false));
1552 }
1553
1554 return settleTransitions;
1555 }));
1556 var delayedTransitions = this.after;
1557 var formattedTransitions = flatten(__spreadArray(__spreadArray(__spreadArray(__spreadArray([], __read(doneConfig), false), __read(invokeConfig), false), __read(onConfig), false), __read(eventlessConfig), false).map(function (transitionConfig) {
1558 return toArray(transitionConfig).map(function (transition) {
1559 return _this.formatTransition(transition);
1560 });
1561 }));
1562
1563 try {
1564 for (var delayedTransitions_1 = __values(delayedTransitions), delayedTransitions_1_1 = delayedTransitions_1.next(); !delayedTransitions_1_1.done; delayedTransitions_1_1 = delayedTransitions_1.next()) {
1565 var delayedTransition = delayedTransitions_1_1.value;
1566 formattedTransitions.push(delayedTransition);
1567 }
1568 } catch (e_10_1) {
1569 e_10 = {
1570 error: e_10_1
1571 };
1572 } finally {
1573 try {
1574 if (delayedTransitions_1_1 && !delayedTransitions_1_1.done && (_a = delayedTransitions_1.return)) _a.call(delayedTransitions_1);
1575 } finally {
1576 if (e_10) throw e_10.error;
1577 }
1578 }
1579
1580 return formattedTransitions;
1581 };
1582
1583 return StateNode;
1584}();
1585
1586export { StateNode };