All files / xstate/src StateNode.ts

93.06% Statements 550/591
89.11% Branches 352/395
93.65% Functions 118/126
93.01% Lines 506/544

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 16271x                           1x                                                                 1x 1x 1x 1x                       1x   1x 1x 1x 1x   1x   25323x 828x       1x   1x                                               835x           835x   835x 835x 2498x           835x   835x 835x                 835x 835x 835x 835x     835x         835x 835x   835x       721x           721x       721x           835x       835x 835x 835x 835x 835x 835x 17x     1x       1x                   1x         30x               11x                     1x 10741x   10741x   1x 2785x   5149x   5149x     5149x 5070x     79x 22x             57x   57x         57x 57x   57x 55x     2x   2x                 57x   57x   2403x     2403x       2403x       2403x 1586x   1586x         817x 817x 1066x     817x     1066x       1066x           1x         1x           1552x 1552x   1544x 800x           800x               744x   1x           519x   519x 519x             519x 134x           134x               385x   147x           147x 147x   147x 327x   327x       327x   327x             327x 221x     327x     147x 259x     147x 72x           72x               75x 170x 170x   75x 31x     75x     75x       1x       2x   2x             2x           74x 168x 168x       168x     74x 94x     74x       168x       168x 65x     103x             168x         1x             2218x 1552x       666x 519x       147x   2558x         2558x 2558x 2558x       2558x 1628x               930x     1048x 1048x       1048x   1048x             1048x                   904x 904x 904x 904x         929x 131x     131x               798x 25x               773x   786x       772x         772x   799x   808x 772x 32x     766x             1x 808x   808x   1x     799x 640x     159x 159x   159x 42x 42x   159x   159x   1x 2238x   1x 799x 121x     678x   678x 1261x 38x   1223x     640x   1x             360x   360x 4x 1x             3x   356x     359x   2331x 2331x 36x     2331x         1489x       1489x           1489x       1489x 125x     1489x     1314x   55x 19x 19x           1017x   14x 17x         1489x         1058x     1489x   1x 207x   207x   1x         17x   17x   1x       991x       991x   991x 846x       846x 12x       991x 854x       854x 17x       991x   1x           1377x           1374x   1374x 1374x   1373x 8x 1x           1372x         1372x             1364x         1364x           1x         1489x     1489x           1489x 991x 991x                   1489x 1489x         1489x                   1489x   1058x       1489x   1058x         1489x 1058x     1489x           1489x       1797x 1489x 339x     1489x 3408x 3x   3408x     1489x                               1489x   498x       991x 485x     991x 991x 691x 691x 691x             691x     991x   1x         1651x   340x   340x   340x 321x         19x 22x   22x             340x       1651x   991x 991x         991x 1157x     1157x 1157x   1157x 1913x 166x 166x                       1747x 1747x         1747x       1x 23909x       23909x               23909x 23909x 4x         23905x   1x 356x       356x 102x     254x   254x           254x   1x                   4031x 4031x 2626x 2623x       42x     2581x   1405x 14x     1391x 304x     670x                 1087x 1087x           1x 3382x   3382x 6x     14x 14x         3376x   2994x     382x       1x 250x 4x       4x       4x     246x   1x 3515x 642x     2873x     81x 85x           2873x   2873x   1x   324x   162x 162x   162x 338x 338x   338x 338x 36x 36x         162x 127x     162x           162x                     162x   1x 126x   126x 1x         125x 125x                     1x   10x 10x       10x 6x               4x       10x   1x                                         1x     3902x   1959x 311x   311x             1648x   1648x   1648x         1647x 15x   1632x 1635x     1942x 1942x 1873x       69x             69x 69x 69x   88x                   1x       4476x 1723x     2753x   2753x           2753x   2752x 26x     2726x       2726x   1x               1877x 5065x 4054x     1011x     1011x       1011x           866x         1x     4023x 2677x     1346x         3503x 4x       3499x       3499x       3617x                   33x     33x       33x   33x 7x     3x           26x       26x 8x     18x   22x           1x               1x 87x 14x   73x 73x   73x 73x 64x 64x 112x 112x           73x   91x 91x   89x 89x 89x                 91x   2696x         2696x       2696x 234x                         2462x     2462x   2583x 2583x       2583x 10x     2573x     2462x               2785x 2785x 2785x         2785x         2785x 2479x 36x     2443x 788x 1041x               1655x 1462x     193x 193x 362x                       193x                 2785x 19x   19x               2785x   1x   1x  
import {
  getEventType,
  toStatePath,
  toStateValue,
  mapValues,
  path,
  toStatePaths,
  pathToStateValue,
  flatten,
  mapFilterValues,
  nestedPath,
  toArray,
  keys
} from './utils';
import {
  Event,
  StateValue,
  Action,
  TransitionConfig,
  ActivityMap,
  EntryExitStates,
  StateTransition,
  StateValueMap,
  MachineOptions,
  Condition,
  ConditionPredicate,
  EventObject,
  HistoryStateNodeConfig,
  HistoryValue,
  DefaultContext,
  StateNodeDefinition,
  TransitionDefinition,
  AssignAction,
  DelayedTransitionDefinition,
  ActivityDefinition,
  Delay,
  StateTypes,
  StateNodeConfig,
  Activity,
  StateSchema,
  TransitionsDefinition,
  StatesDefinition,
  StateNodesConfig,
  ActionTypes,
  AnyEvent,
  RaisedEvent
} from './types';
import { matchesState } from './utils';
import { State } from './State';
import * as actionTypes from './actionTypes';
import {
  start,
  stop,
  toEventObject,
  toActionObjects,
  toActivityDefinition,
  send,
  cancel,
  after,
  raise,
  done
} from './actions';
import { StateTree } from './StateTree';
 
const STATE_DELIMITER = '.';
const NULL_EVENT = '';
const STATE_IDENTIFIER = '#';
const TARGETLESS_KEY = '';
 
const EMPTY_OBJECT = {};
 
const isStateId = (str: string) => str[0] === STATE_IDENTIFIER;
const createDefaultOptions = <TContext>(): MachineOptions<TContext, any> => ({
  guards: EMPTY_OBJECT
});
 
const IS_PRODUCTION = process.env.NODE_ENV === 'production';
 
class StateNode<
  TContext = DefaultContext,
  TStateSchema extends StateSchema = any,
  TEvents extends AnyEvent<EventObject> = AnyEvent<EventObject>
> {
  public key: string;
  public id: string;
  public type: StateTypes;
  public path: string[];
  public initial?: keyof TStateSchema['states'];
  public parallel: boolean;
  public transient: boolean;
  public states: StateNodesConfig<TContext, TStateSchema, TEvents>;
  public history: false | 'shallow' | 'deep';
  public onEntry: Array<Action<TContext>>;
  public onExit: Array<Action<TContext>>;
  public activities: Array<ActivityDefinition<TContext>>;
  public strict: boolean;
  public parent?: StateNode<TContext>;
  public machine: StateNode<TContext>;
  public data?: TStateSchema extends { data: infer D } ? D : any;
  public delimiter: string;
  public order: number;
 
  private __cache = {
    events: undefined as Array<TEvents['type']> | undefined,
    relativeValue: new Map() as Map<StateNode<TContext>, StateValue>,
    initialState: undefined as StateValue | undefined
  };
 
  private idMap: Record<string, StateNode<TContext>> = {};
 
  constructor(
    private _config: StateNodeConfig<TContext, TStateSchema, TEvents>,
    public options: Readonly<
      MachineOptions<TContext, TEvents>
    > = createDefaultOptions<TContext>(),
    /**
     * The initial extended state
     */
    public context?: Readonly<TContext>
  ) {
    this.key = _config.key || _config.id || '(machine)';
    this.type =
      _config.type ||
      (_config.parallel // TODO: deprecate
        ? 'parallel'
        : _config.states && keys(_config.states).length
          ? 'compound'
          : _config.history
            ? 'history'
            : 'atomic');
    this.parent = _config.parent;
    this.machine = this.parent ? this.parent.machine : this;
    this.path = this.parent ? this.parent.path.concat(this.key) : [];
    this.delimiter =
      _config.delimiter ||
      (this.parent ? this.parent.delimiter : STATE_DELIMITER);
    this.id =
      _config.id ||
      (this.machine
        ? [this.machine.key, ...this.path].join(this.delimiter)
        : this.key);
    this.initial = _config.initial;
    this.order = _config.order || -1;
 
    this.states = (_config.states
      ? mapValues(
          _config.states,
          (stateConfig: StateNodeConfig<TContext, any, TEvents>, key, _, i) => {
            const stateNode = new StateNode({
              ...stateConfig,
              key,
              order: stateConfig.order === undefined ? stateConfig.order : i,
              parent: this
            });
            Object.assign(this.idMap, {
              [stateNode.id]: stateNode,
              ...stateNode.idMap
            });
            return stateNode;
          }
        )
      : EMPTY_OBJECT) as StateNodesConfig<TContext, TStateSchema, TEvents>;
 
    // History config
    this.history =
      _config.history === true ? 'shallow' : _config.history || false;
 
    // this.on = config.on ? this.formatTransitions(config.on) : {};
    this.transient = !!(_config.on && _config.on[NULL_EVENT]);
    this.strict = !!_config.strict;
    this.onEntry = toArray(_config.onEntry);
    this.onExit = toArray(_config.onExit);
    this.data = _config.data;
    this.activities = toArray(_config.activities).map(activity =>
      this.resolveActivity(activity)
    );
  }
  public withConfig(
    options: MachineOptions<TContext, TEvents>,
    context?: TContext
  ): StateNode<TContext, TStateSchema, TEvents> {
    return new StateNode(
      this.definition,
      {
        actions: { ...this.options.actions, ...options.actions },
        activities: { ...this.options.activities, ...options.activities },
        guards: { ...this.options.guards, ...options.guards }
      },
      context
    );
  }
  public get definition(): StateNodeDefinition<
    TContext,
    TStateSchema,
    TEvents
  > {
    return {
      id: this.id,
      key: this.key,
      type: this.type,
      initial: this.initial,
      history: this.history,
      states: mapValues(
        this.states,
        (state: StateNode<TContext, any, TEvents>) => state.definition
      ) as StatesDefinition<TContext, TStateSchema, TEvents>,
      on: this.on,
      onEntry: this.onEntry,
      onExit: this.onExit,
      after: this.after,
      activities: this.activities || [],
      data: this.data,
      order: this.order || -1
    };
  }
  public get config(): StateNodeConfig<TContext, TStateSchema, TEvents> {
    const { parent, ...config } = this._config;
 
    return config;
  }
  public get on(): TransitionsDefinition<TContext, TEvents> {
    return this.formatTransitions();
  }
  public get after(): Array<DelayedTransitionDefinition<TContext, TEvents>> {
    const {
      config: { after: afterConfig }
    } = this;
 
    if (!afterConfig) {
      return [];
    }
 
    if (Array.isArray(afterConfig)) {
      return afterConfig.map(delayedTransition => ({
        event: after(delayedTransition.delay, this.id),
        ...delayedTransition,
        actions: toArray(delayedTransition.actions)
      }));
    }
 
    const allDelayedTransitions = flatten(
      keys(afterConfig).map(delayKey => {
        const delayedTransition = (afterConfig as Record<
          string,
          | TransitionConfig<TContext, TEvents>
          | Array<TransitionConfig<TContext, TEvents>>
        >)[delayKey];
        const delay = +delayKey;
        const event = after(delay, this.id);
 
        if (typeof delayedTransition === 'string') {
          return [{ target: delayedTransition, delay, event, actions: [] }];
        }
 
        const delayedTransitions = toArray(delayedTransition);
 
        return delayedTransitions.map(transition => ({
          event,
          delay,
          ...transition,
          actions: toArray(transition.actions)
        }));
      })
    );
 
    allDelayedTransitions.sort((a, b) => a.delay - b.delay);
 
    return allDelayedTransitions;
  }
  public getStateNodes(
    state: StateValue | State<TContext, TEvents>
  ): Array<StateNode<TContext>> {
    Iif (!state) {
      return [];
    }
    const stateValue =
      state instanceof State
        ? state.value
        : toStateValue(state, this.delimiter);
 
    if (typeof stateValue === 'string') {
      const initialStateValue = this.getStateNode(stateValue).initial;
 
      return initialStateValue
        ? this.getStateNodes({ [stateValue]: initialStateValue } as StateValue)
        : [this.states[stateValue]];
    }
 
    const subStateKeys = keys(stateValue);
    const subStateNodes: Array<StateNode<TContext>> = subStateKeys.map(
      subStateKey => this.getStateNode(subStateKey)
    );
 
    return subStateNodes.concat(
      subStateKeys.reduce(
        (allSubStateNodes, subStateKey) => {
          const subStateNode = this.getStateNode(subStateKey).getStateNodes(
            stateValue[subStateKey]
          );
 
          return allSubStateNodes.concat(subStateNode);
        },
        [] as Array<StateNode<TContext>>
      )
    );
  }
  public handles(event: Event<TEvents>): boolean {
    const eventType = getEventType<TEvents>(event);
 
    return this.events.indexOf(eventType) !== -1;
  }
  private transitionLeafNode(
    stateValue: string,
    state: State<TContext, TEvents>,
    eventObject: TEvents,
    context?: TContext
  ): StateTransition<TContext> {
    const stateNode = this.getStateNode(stateValue);
    const next = stateNode.next(state, eventObject, context);
 
    if (!next.tree) {
      const { reentryStates, actions, tree } = this.next(
        state,
        eventObject,
        context
      );
 
      return {
        tree,
        source: state,
        reentryStates,
        actions
      };
    }
 
    return next;
  }
  private transitionCompoundNode(
    stateValue: StateValueMap,
    state: State<TContext, TEvents>,
    eventObject: TEvents,
    context?: TContext
  ): StateTransition<TContext> {
    const subStateKeys = keys(stateValue);
 
    const stateNode = this.getStateNode(subStateKeys[0]);
    const next = stateNode._transition(
      stateValue[subStateKeys[0]],
      state,
      eventObject,
      context
    );
 
    if (!next.tree) {
      const { reentryStates, actions, tree } = this.next(
        state,
        eventObject,
        context
      );
 
      return {
        tree,
        source: state,
        reentryStates,
        actions
      };
    }
 
    return next;
  }
  private transitionParallelNode(
    stateValue: StateValueMap,
    state: State<TContext, TEvents>,
    eventObject: TEvents,
    context?: TContext
  ): StateTransition<TContext> {
    const noTransitionKeys: string[] = [];
    const transitionMap: Record<string, StateTransition<TContext>> = {};
 
    keys(stateValue).forEach(subStateKey => {
      const subStateValue = stateValue[subStateKey];
 
      Iif (!subStateValue) {
        return;
      }
 
      const subStateNode = this.getStateNode(subStateKey);
 
      const next = subStateNode._transition(
        subStateValue,
        state,
        eventObject,
        context
      );
 
      if (!next.tree) {
        noTransitionKeys.push(subStateKey);
      }
 
      transitionMap[subStateKey] = next;
    });
 
    const willTransition = keys(transitionMap).some(
      key => transitionMap[key].tree !== undefined
    );
 
    if (!willTransition) {
      const { reentryStates, actions, tree } = this.next(
        state,
        eventObject,
        context
      );
 
      return {
        tree,
        source: state,
        reentryStates,
        actions
      };
    }
 
    const allTrees = keys(transitionMap)
      .map(key => transitionMap[key].tree)
      .filter(t => t !== undefined) as StateTree[];
 
    const combinedTree = allTrees.reduce((acc, t) => {
      return acc.combine(t);
    });
 
    const allPaths = combinedTree.paths;
 
    // External transition that escapes orthogonal region
    if (
      allPaths.length === 1 &&
      !matchesState(toStateValue(this.path, this.delimiter), combinedTree.value)
    ) {
      return {
        tree: combinedTree,
        source: state,
        reentryStates: keys(transitionMap)
          .map(key => transitionMap[key].reentryStates)
          .reduce((allReentryStates, reentryStates) => {
            return new Set([
              ...Array.from(allReentryStates || []),
              ...Array.from(reentryStates || [])
            ]);
          }, new Set<StateNode<TContext>>()),
        actions: flatten(
          keys(transitionMap).map(key => {
            return transitionMap[key].actions;
          })
        )
      };
    }
 
    const allResolvedTrees = keys(transitionMap).map(key => {
      const transition = transitionMap[key];
      const subValue = path(this.path)(
        transition.tree ? transition.tree.value : state.value || state.value
      )[key];
 
      return new StateTree(this.getStateNode(key), subValue).absolute;
    });
 
    const finalCombinedTree = allResolvedTrees.reduce((acc, t) => {
      return acc.combine(t);
    });
 
    return {
      tree: finalCombinedTree,
      source: state,
      reentryStates: keys(transitionMap).reduce((allReentryStates, key) => {
        const { tree, reentryStates } = transitionMap[key];
 
        // If the event was not handled (no subStateValue),
        // machine should still be in state without reentry/exit.
        if (!tree || !reentryStates) {
          return allReentryStates;
        }
 
        return new Set([
          ...Array.from(allReentryStates),
          ...Array.from(reentryStates)
        ]);
      }, new Set<StateNode<TContext>>()),
      actions: flatten(
        keys(transitionMap).map(key => {
          return transitionMap[key].actions;
        })
      )
    };
  }
  public _transition(
    stateValue: StateValue,
    state: State<TContext, TEvents>,
    event: TEvents,
    context?: TContext
  ): StateTransition<TContext> {
    // leaf node
    if (typeof stateValue === 'string') {
      return this.transitionLeafNode(stateValue, state, event, context);
    }
 
    // hierarchical node
    if (keys(stateValue).length === 1) {
      return this.transitionCompoundNode(stateValue, state, event, context);
    }
 
    // orthogonal node
    return this.transitionParallelNode(stateValue, state, event, context);
  }
  private next(
    state: State<TContext, TEvents>,
    eventObject: TEvents,
    context?: TContext
  ): StateTransition<TContext> {
    const eventType = eventObject.type;
    const candidates = this.on[eventType];
    const actions: Array<Action<TContext>> = this.transient
      ? [{ type: actionTypes.null }]
      : [];
 
    if (!candidates || !candidates.length) {
      return {
        tree: undefined,
        source: state,
        reentryStates: undefined,
        actions
      };
    }
 
    let nextStateStrings: string[] = [];
    let selectedTransition: unknown;
 
    for (const candidate of candidates) {
      const { cond, in: stateIn } = candidate as TransitionConfig<
        TContext,
        TEvents
      >;
      const resolvedContext = context || (EMPTY_OBJECT as TContext);
 
      const isInState = stateIn
        ? matchesState(
            toStateValue(stateIn, this.delimiter),
            path(this.path.slice(0, -2))(state.value)
          )
        : true;
 
      if (
        (!cond ||
          this.evaluateGuard(
            cond,
            resolvedContext,
            eventObject,
            state.value
          )) &&
        isInState
      ) {
        nextStateStrings = toArray(candidate.target);
        actions.push(...toArray(candidate.actions));
        selectedTransition = candidate;
        break;
      }
    }
 
    // targetless transition
    if (selectedTransition && nextStateStrings.length === 0) {
      const tree = state.value
        ? this.machine.getStateTree(state.value)
        : undefined;
      return {
        tree,
        source: state,
        reentryStates: undefined,
        actions
      };
    }
 
    if (!selectedTransition && nextStateStrings.length === 0) {
      return {
        tree: undefined,
        source: state,
        reentryStates: undefined,
        actions
      };
    }
 
    const nextStateNodes = flatten(
      nextStateStrings.map(str =>
        this.getRelativeStateNodes(str, state.historyValue)
      )
    );
 
    const isInternal = !!(selectedTransition as TransitionDefinition<
      TContext,
      TEvents
    >).internal;
 
    const reentryNodes = isInternal
      ? []
      : flatten(nextStateNodes.map(n => this.nodesFromChild(n)));
 
    const trees = nextStateNodes.map(stateNode => stateNode.tree);
    const combinedTree = trees.reduce((acc, t) => {
      return acc.combine(t);
    });
 
    return {
      tree: combinedTree,
      source: state,
      reentryStates: new Set(reentryNodes),
      actions
    };
  }
  private get tree(): StateTree {
    const stateValue = toStateValue(this.path, this.delimiter);
 
    return new StateTree(this.machine, stateValue);
  }
  private nodesFromChild(
    childStateNode: StateNode<TContext>
  ): Array<StateNode<TContext>> {
    if (childStateNode.escapes(this)) {
      return [];
    }
 
    const nodes: Array<StateNode<TContext>> = [];
    let marker: StateNode<TContext> | undefined = childStateNode;
 
    while (marker && marker !== this) {
      nodes.push(marker);
      marker = marker.parent;
    }
    nodes.push(this); // inclusive
 
    return nodes;
  }
  private getStateTree(stateValue: StateValue): StateTree {
    return new StateTree(this, stateValue);
  }
  private escapes(stateNode: StateNode): boolean {
    if (this === stateNode) {
      return false;
    }
 
    let parent = this.parent;
 
    while (parent) {
      if (parent === stateNode) {
        return false;
      }
      parent = parent.parent;
    }
 
    return true;
  }
  private evaluateGuard(
    condition: Condition<TContext, TEvents>,
    context: TContext,
    eventObject: TEvents,
    interimState: StateValue
  ): boolean {
    let condFn: ConditionPredicate<TContext, TEvents>;
    const { guards } = this.machine.options;
 
    if (typeof condition === 'string') {
      if (!guards || !guards[condition]) {
        throw new Error(
          `Condition '${condition}' is not implemented on machine '${
            this.machine.id
          }'.`
        );
      }
 
      condFn = guards[condition];
    } else {
      condFn = condition;
    }
 
    return condFn(context, eventObject, interimState);
  }
  public get delays(): Delay[] {
    const delays = Array.from(
      new Set(this.after.map(delayedTransition => delayedTransition.delay))
    );
 
    return delays.map(delay => ({
      id: this.id,
      delay
    }));
  }
  private getActions(
    transition: StateTransition<TContext>,
    prevState: State<TContext>
  ): Array<Action<TContext>> {
    const entryExitStates = transition.tree
      ? transition.tree.resolved.getEntryExitStates(
          this.getStateTree(prevState.value),
          transition.reentryStates ? transition.reentryStates : undefined
        )
      : { entry: [], exit: [] };
    const doneEvents = transition.tree
      ? transition.tree.getDoneEvents(new Set(entryExitStates.entry))
      : [];
 
    if (!transition.source) {
      entryExitStates.exit = [];
    }
 
    const entryExitActions = {
      entry: flatten(
        Array.from(new Set(entryExitStates.entry)).map(stateNode => {
          return [
            ...stateNode.onEntry,
            ...stateNode.activities.map(activity => start(activity)),
            ...stateNode.delays.map(({ delay, id }) =>
              send(after(delay, id), { delay })
            )
          ];
        })
      ).concat(doneEvents.map(raise)),
      exit: flatten(
        Array.from(new Set(entryExitStates.exit)).map(stateNode => [
          ...stateNode.onExit,
          ...stateNode.activities.map(activity => stop(activity)),
          ...stateNode.delays.map(({ delay, id }) => cancel(after(delay, id)))
        ])
      )
    };
 
    const actions = entryExitActions.exit
      .concat(transition.actions)
      .concat(entryExitActions.entry)
      .map(
        action =>
          typeof action === 'string' ? this.resolveAction(action) : action
      );
 
    return actions;
  }
  private resolveAction(actionType: string): Action<TContext> {
    const { actions } = this.machine.options;
 
    return (actions ? actions[actionType] : actionType) || actionType;
  }
  private resolveActivity(
    activity: Activity<TContext>
  ): ActivityDefinition<TContext> {
    // const { activities } = this.machine.options;
 
    const activityDefinition = toActivityDefinition(activity);
 
    return activityDefinition;
  }
  private getActivities(
    entryExitStates?: EntryExitStates<TContext>,
    activities?: ActivityMap
  ): ActivityMap {
    Iif (!entryExitStates) {
      return EMPTY_OBJECT;
    }
 
    const activityMap = { ...activities };
 
    Array.from(entryExitStates.exit).forEach(stateNode => {
      Iif (!stateNode.activities) {
        return; // TODO: fixme
      }
 
      stateNode.activities.forEach(activity => {
        activityMap[activity.type] = false;
      });
    });
 
    Array.from(entryExitStates.entry).forEach(stateNode => {
      Iif (!stateNode.activities) {
        return; // TODO: fixme
      }
 
      stateNode.activities.forEach(activity => {
        activityMap[activity.type] = true;
      });
    });
 
    return activityMap;
  }
  public transition(
    state: StateValue | State<TContext, TEvents>,
    event: Event<TEvents>,
    context?: TContext
  ): State<TContext, TEvents> {
    const resolvedStateValue =
      typeof state === 'string'
        ? this.resolve(pathToStateValue(this.getResolvedPath(state)))
        : state instanceof State
          ? state
          : this.resolve(state);
    const resolvedContext =
      context ||
      ((state instanceof State ? state.context : undefined) as TContext);
    const eventObject = toEventObject(event);
    const eventType = eventObject.type;
 
    if (this.strict) {
      if (this.events.indexOf(eventType) === -1) {
        throw new Error(
          `Machine '${this.id}' does not accept event '${eventType}'`
        );
      }
    }
 
    const currentState = State.from<TContext, TEvents>(
      resolvedStateValue,
      resolvedContext
    );
 
    const stateTransition = this._transition(
      currentState.value,
      currentState,
      eventObject,
      resolvedContext
    );
 
    const resolvedStateTransition: StateTransition<TContext> = {
      ...stateTransition,
      tree: stateTransition.tree ? stateTransition.tree.resolved : undefined
    };
 
    return this.resolveTransition(
      resolvedStateTransition,
      currentState,
      eventObject
    );
  }
  private resolveTransition(
    stateTransition: StateTransition<TContext>,
    currentState: State<TContext, TEvents>,
    event?: TEvents
  ): State<TContext, TEvents> {
    const resolvedStateValue = stateTransition.tree
      ? stateTransition.tree.value
      : undefined;
    const historyValue = currentState.historyValue
      ? currentState.historyValue
      : stateTransition.source
        ? (this.machine.historyValue(currentState.value) as HistoryValue)
        : undefined;
 
    if (!IS_PRODUCTION && stateTransition.tree) {
      try {
        this.ensureValidPaths(stateTransition.tree.paths); // TODO: ensure code coverage for this
      } catch (e) {
        throw new Error(
          `Event '${
            event ? event.type : 'none'
          }' leads to an invalid configuration: ${e.message}`
        );
      }
    }
 
    const actions = this.getActions(stateTransition, currentState);
    const entryExitStates = stateTransition.tree
      ? stateTransition.tree.getEntryExitStates(
          this.getStateTree(currentState.value)
        )
      : { entry: [], exit: [] };
    const activities = stateTransition.tree
      ? this.getActivities(
          {
            entry: new Set(entryExitStates.entry),
            exit: new Set(entryExitStates.exit)
          },
          currentState.activities
        )
      : {};
 
    const raisedEvents = actions.filter(
      action =>
        typeof action === 'object' &&
        (action.type === actionTypes.raise || action.type === actionTypes.null)
    ) as Array<RaisedEvent<TEvents> | { type: ActionTypes.Null }>;
 
    const nonEventActions = actions.filter(
      action =>
        typeof action !== 'object' ||
        (action.type !== actionTypes.raise &&
          action.type !== actionTypes.null &&
          action.type !== actionTypes.assign)
    );
    const assignActions = actions.filter(
      action => typeof action === 'object' && action.type === actionTypes.assign
    ) as Array<AssignAction<TContext, TEvents>>;
 
    const updatedContext = StateNode.updateContext(
      currentState.context,
      event,
      assignActions
    );
 
    const stateNodes = resolvedStateValue
      ? this.getStateNodes(resolvedStateValue)
      : [];
 
    const isTransient = stateNodes.some(stateNode => stateNode.transient);
    if (isTransient) {
      raisedEvents.push({ type: actionTypes.null });
    }
 
    const data = [this, ...stateNodes].reduce((acc, stateNode) => {
      if (stateNode.data !== undefined) {
        acc[stateNode.id] = stateNode.data;
      }
      return acc;
    }, {});
 
    const nextState = resolvedStateValue
      ? new State<TContext, TEvents>(
          resolvedStateValue,
          updatedContext,
          historyValue
            ? StateNode.updateHistoryValue(historyValue, resolvedStateValue)
            : undefined,
          stateTransition.source ? currentState : undefined,
          toActionObjects(nonEventActions, this.options.actions),
          activities,
          data,
          raisedEvents as TEvents[],
          stateTransition.tree
        )
      : undefined;
 
    if (!nextState) {
      // Unchanged state should be returned with no actions
      return State.inert<TContext, TEvents>(currentState, updatedContext);
    }
 
    // Dispose of penultimate histories to prevent memory leaks
    if (currentState.history) {
      delete currentState.history.history;
    }
 
    let maybeNextState = nextState;
    while (raisedEvents.length) {
      const currentActions = maybeNextState.actions;
      const raisedEvent = raisedEvents.shift()!;
      maybeNextState = this.transition(
        maybeNextState,
        raisedEvent.type === actionTypes.null
          ? NULL_EVENT
          : (raisedEvent as RaisedEvent<TEvents>).event,
        maybeNextState.context
      );
      maybeNextState.actions.unshift(...currentActions);
    }
 
    return maybeNextState;
  }
  public static updateContext<TContext, TEvents extends EventObject>(
    context: TContext,
    event: TEvents | undefined,
    assignActions: Array<AssignAction<TContext, TEvents>>
  ): TContext {
    const updatedContext = context
      ? assignActions.reduce((acc, assignAction) => {
          const { assignment } = assignAction;
 
          let partialUpdate: Partial<TContext> = {};
 
          if (typeof assignment === 'function') {
            partialUpdate = assignment(
              acc,
              event || ({ type: ActionTypes.Init } as TEvents)
            );
          } else {
            keys(assignment).forEach(key => {
              const propAssignment = assignment[key];
 
              partialUpdate[key] =
                typeof propAssignment === 'function'
                  ? propAssignment(acc, event)
                  : propAssignment;
            });
          }
 
          return Object.assign({}, acc, partialUpdate);
        }, context)
      : context;
 
    return updatedContext;
  }
  private ensureValidPaths(paths: string[][]): void {
    const visitedParents = new Map<
      StateNode<TContext>,
      Array<StateNode<TContext>>
    >();
 
    const stateNodes = flatten(
      paths.map(_path => this.getRelativeStateNodes(_path))
    );
 
    outer: for (const stateNode of stateNodes) {
      let marker = stateNode;
 
      while (marker.parent) {
        if (visitedParents.has(marker.parent)) {
          Eif (marker.parent.type === 'parallel') {
            continue outer;
          }
 
          throw new Error(
            `State node '${stateNode.id}' shares parent '${
              marker.parent.id
            }' with state node '${visitedParents
              .get(marker.parent)!
              .map(a => a.id)}'`
          );
        }
 
        Eif (!visitedParents.get(marker.parent)) {
          visitedParents.set(marker.parent, [stateNode]);
        } else {
          visitedParents.get(marker.parent)!.push(stateNode);
        }
 
        marker = marker.parent;
      }
    }
  }
  public getStateNode(stateKey: string): StateNode<TContext> {
    Iif (isStateId(stateKey)) {
      return this.machine.getStateNodeById(stateKey);
    }
 
    Iif (!this.states) {
      throw new Error(
        `Unable to retrieve child state '${stateKey}' from '${
          this.id
        }'; no child states exist.`
      );
    }
 
    const result = this.states[stateKey];
    if (!result) {
      throw new Error(
        `Child state '${stateKey}' does not exist on '${this.id}'`
      );
    }
 
    return result;
  }
  public getStateNodeById(stateId: string): StateNode<TContext> {
    const resolvedStateId = isStateId(stateId)
      ? stateId.slice(STATE_IDENTIFIER.length)
      : stateId;
 
    if (resolvedStateId === this.id) {
      return this;
    }
 
    const stateNode = this.machine.idMap[resolvedStateId];
 
    Iif (!stateNode) {
      throw new Error(
        `Substate '#${resolvedStateId}' does not exist on '${this.id}'`
      );
    }
 
    return stateNode;
  }
  public getStateNodeByPath(statePath: string | string[]): StateNode<TContext> {
    const arrayStatePath = toStatePath(statePath, this.delimiter);
    let currentStateNode: StateNode<TContext> = this;
    while (arrayStatePath.length) {
      const key = arrayStatePath.shift()!;
      currentStateNode = currentStateNode.getStateNode(key);
    }
 
    return currentStateNode;
  }
  public resolve(stateValue: StateValue): StateValue {
    if (typeof stateValue === 'string') {
      const subStateNode = this.getStateNode(stateValue);
      if (
        subStateNode.type === 'parallel' ||
        subStateNode.type === 'compound'
      ) {
        return { [stateValue]: subStateNode.initialStateValue! };
      }
 
      return stateValue;
    }
    if (!keys(stateValue).length) {
      return this.initialStateValue || {};
    }
 
    if (this.type === 'parallel') {
      return mapValues(
        this.initialStateValue as Record<string, StateValue>,
        (subStateValue, subStateKey) => {
          return subStateValue
            ? this.getStateNode(subStateKey).resolve(
                stateValue[subStateKey] || subStateValue
              )
            : EMPTY_OBJECT;
        }
      );
    }
 
    return mapValues(stateValue, (subStateValue, subStateKey) => {
      return subStateValue
        ? this.getStateNode(subStateKey).resolve(subStateValue)
        : EMPTY_OBJECT;
    });
  }
 
  private get resolvedStateValue(): StateValue {
    const { key } = this;
 
    if (this.type === 'parallel') {
      return {
        [key]: mapFilterValues<StateNode<TContext>, StateValue>(
          this.states,
          stateNode => stateNode.resolvedStateValue[stateNode.key],
          stateNode => !stateNode.history
        )
      };
    }
 
    if (!this.initial) {
      // If leaf node, value is just the state node's key
      return key;
    }
 
    return {
      [key]: this.states[this.initial].resolvedStateValue
    };
  }
  private getResolvedPath(stateIdentifier: string): string[] {
    if (isStateId(stateIdentifier)) {
      const stateNode = this.machine.idMap[
        stateIdentifier.slice(STATE_IDENTIFIER.length)
      ];
 
      Iif (!stateNode) {
        throw new Error(`Unable to find state node '${stateIdentifier}'`);
      }
 
      return stateNode.path;
    }
 
    return toStatePath(stateIdentifier, this.delimiter);
  }
  private get initialStateValue(): StateValue | undefined {
    if (this.__cache.initialState) {
      return this.__cache.initialState;
    }
 
    const initialStateValue = (this.type === 'parallel'
      ? mapFilterValues(
          this.states as Record<string, StateNode<TContext>>,
          state => state.initialStateValue || EMPTY_OBJECT,
          stateNode => !stateNode.history
        )
      : typeof this.resolvedStateValue === 'string'
        ? undefined
        : this.resolvedStateValue[this.key]) as StateValue;
 
    this.__cache.initialState = initialStateValue;
 
    return this.__cache.initialState;
  }
  public getInitialState(
    stateValue: StateValue,
    Econtext: TContext = this.machine.context!
  ): State<TContext, TEvents> {
    const activityMap: ActivityMap = {};
    const actions: Array<Action<TContext>> = [];
 
    this.getStateNodes(stateValue).forEach(stateNode => {
      Eif (stateNode.onEntry) {
        actions.push(...stateNode.onEntry);
      }
      Eif (stateNode.activities) {
        stateNode.activities.forEach(activity => {
          activityMap[getEventType(activity) as string] = true; // TODO: fixme
          actions.push(start(activity));
        });
      }
    });
 
    const assignActions = actions.filter(
      action => typeof action === 'object' && action.type === actionTypes.assign
    ) as Array<AssignAction<TContext, TEvents>>;
 
    const updatedContext = StateNode.updateContext(
      context,
      undefined,
      assignActions
    );
 
    const initialNextState = new State<TContext, TEvents>(
      stateValue,
      updatedContext,
      undefined,
      undefined,
      undefined,
      activityMap,
      undefined,
      []
    );
 
    return initialNextState;
  }
  public get initialState(): State<TContext, TEvents> {
    const { initialStateValue } = this;
 
    if (!initialStateValue) {
      throw new Error(
        `Cannot retrieve initial state from simple state '${this.id}'.`
      );
    }
 
    const state = this.getInitialState(initialStateValue);
    return this.resolveTransition(
      {
        tree: this.getStateTree(initialStateValue),
        source: undefined,
        reentryStates: new Set(this.getStateNodes(initialStateValue)),
        actions: []
      },
      state,
      undefined
    );
  }
  public get target(): StateValue | undefined {
    let target;
    Eif (this.history) {
      const historyConfig = this.config as HistoryStateNodeConfig<
        TContext,
        TEvents
      >;
      if (historyConfig.target && typeof historyConfig.target === 'string') {
        target = isStateId(historyConfig.target)
          ? pathToStateValue(
              this.machine
                .getStateNodeById(historyConfig.target)
                .path.slice(this.path.length - 1)
            )
          : historyConfig.target;
      } else {
        target = historyConfig.target;
      }
    }
 
    return target;
  }
  public getStates(stateValue: StateValue): Array<StateNode<TContext>> {
    if (typeof stateValue === 'string') {
      return [this.states[stateValue]];
    }
 
    const stateNodes: Array<StateNode<TContext>> = [];
 
    keys(stateValue).forEach(key => {
      stateNodes.push(...this.states[key].getStates(stateValue[key]));
    });
 
    return stateNodes;
  }
 
  /**
   * Returns the leaf nodes from a state path relative to this state node.
   *
   * @param relativeStateId The relative state path to retrieve the state nodes
   * @param history The previous state to retrieve history
   * @param resolve Whether state nodes should resolve to initial child state nodes
   */
  public getRelativeStateNodes(
    relativeStateId: string | string[],
    historyValue?: HistoryValue,
    resolve: boolean = true
  ): Array<StateNode<TContext>> {
    if (typeof relativeStateId === 'string' && isStateId(relativeStateId)) {
      const unresolvedStateNode = this.getStateNodeById(relativeStateId);
 
      return resolve
        ? unresolvedStateNode.history
          ? unresolvedStateNode.resolveHistory(historyValue)
          : unresolvedStateNode.initialStateNodes
        : [unresolvedStateNode];
    }
 
    const statePath = toStatePath(relativeStateId, this.delimiter);
 
    const rootStateNode = this.parent || this;
 
    const unresolvedStateNodes = rootStateNode.getFromRelativePath(
      statePath,
      historyValue
    );
 
    if (!resolve) {
      return unresolvedStateNodes;
    }
    return flatten(
      unresolvedStateNodes.map(stateNode => stateNode.initialStateNodes)
    );
  }
  public get initialStateNodes(): Array<StateNode<TContext>> {
    if (this.type === 'atomic' || this.type === 'final') {
      return [this];
    }
 
    // Case when state node is compound but no initial state is defined
    Iif (this.type === 'compound' && !this.initial) {
      if (!IS_PRODUCTION) {
        console.warn(`Compound state node '${this.id}' has no initial state.`);
      }
      return [this];
    }
 
    const { initialStateValue } = this;
    const initialStateNodePaths = toStatePaths(initialStateValue!);
    return flatten(
      initialStateNodePaths.map(initialPath =>
        this.getFromRelativePath(initialPath)
      )
    );
  }
  /**
   * Retrieves state nodes from a relative path to this state node.
   *
   * @param relativePath The relative path from this state node
   * @param historyValue
   */
  public getFromRelativePath(
    relativePath: string[],
    historyValue?: HistoryValue
  ): Array<StateNode<TContext>> {
    if (!relativePath.length) {
      return [this];
    }
 
    const [x, ...xs] = relativePath;
 
    Iif (!this.states) {
      throw new Error(
        `Cannot retrieve subPath '${x}' from node with no states`
      );
    }
 
    const childStateNode = this.getStateNode(x);
 
    if (childStateNode.history) {
      return childStateNode.resolveHistory(historyValue);
    }
 
    Iif (!this.states[x]) {
      throw new Error(`Child state '${x}' does not exist on '${this.id}'`);
    }
 
    return this.states[x].getFromRelativePath(xs, historyValue);
  }
  public static updateHistoryValue(
    hist: HistoryValue,
    stateValue: StateValue
  ): HistoryValue {
    function update(
      _hist: HistoryValue,
      _sv: StateValue
    ): Record<string, HistoryValue | undefined> {
      return mapValues(_hist.states, (subHist, key) => {
        if (!subHist) {
          return undefined;
        }
        const subStateValue =
          (typeof _sv === 'string' ? undefined : _sv[key]) ||
          (subHist ? subHist.current : undefined);
 
        Iif (!subStateValue) {
          return undefined;
        }
 
        return {
          current: subStateValue,
          states: update(subHist, subStateValue)
        };
      });
    }
    return {
      current: stateValue,
      states: update(hist, stateValue)
    };
  }
  public historyValue(
    relativeStateValue?: StateValue | undefined
  ): HistoryValue | undefined {
    if (!keys(this.states).length) {
      return undefined;
    }
 
    return {
      current: relativeStateValue || this.initialStateValue,
      states: mapFilterValues<StateNode<TContext>, HistoryValue | undefined>(
        this.states,
        (stateNode, key) => {
          if (!relativeStateValue) {
            return stateNode.historyValue();
          }
 
          const subStateValue =
            typeof relativeStateValue === 'string'
              ? undefined
              : relativeStateValue[key];
 
          return stateNode.historyValue(
            subStateValue || stateNode.initialStateValue
          );
        },
        stateNode => !stateNode.history
      )
    };
  }
  /**
   * Resolves to the historical value(s) of the parent state node,
   * represented by state nodes.
   *
   * @param historyValue
   */
  private resolveHistory(
    historyValue?: HistoryValue
  ): Array<StateNode<TContext>> {
    Iif (!this.history) {
      return [this];
    }
 
    const parent = this.parent!;
 
    if (!historyValue) {
      return this.target
        ? flatten(
            toStatePaths(this.target).map(relativeChildPath =>
              parent.getFromRelativePath(relativeChildPath)
            )
          )
        : this.parent!.initialStateNodes;
    }
 
    const subHistoryValue = nestedPath<HistoryValue>(parent.path, 'states')(
      historyValue
    ).current;
 
    if (typeof subHistoryValue === 'string') {
      return [parent.getStateNode(subHistoryValue)];
    }
 
    return flatten(
      toStatePaths(subHistoryValue!).map(subStatePath => {
        return this.history === 'deep'
          ? parent.getFromRelativePath(subStatePath)
          : [parent.states[subStatePath[0]]];
      })
    );
  }
  public get stateIds(): string[] {
    const childStateIds = flatten(
      keys(this.states).map(stateKey => {
        return (this.states[stateKey] as StateNode<TContext>).stateIds;
      })
    );
    return [this.id].concat(childStateIds);
  }
  public get events(): Array<TEvents['type']> {
    if (this.__cache.events) {
      return this.__cache.events;
    }
    const { states } = this;
    const events = new Set(this.ownEvents);
 
    Eif (states) {
      keys(states).forEach(stateId => {
        const state = states[stateId];
        Eif (state.states) {
          for (const event of state.events) {
            events.add(`${event}`);
          }
        }
      });
    }
 
    return (this.__cache.events = Array.from(events));
  }
  public get ownEvents(): Array<TEvents['type']> {
    const events = new Set(
      keys(this.on).filter(key => {
        const transitions = this.on[key];
        return transitions.some(transition => {
          return !(
            !transition.target &&
            !transition.actions.length &&
            transition.internal
          );
        });
      })
    );
 
    return Array.from(events);
  }
  private formatTransition(
    target: string | string[] | undefined,
    transitionConfig: TransitionConfig<TContext, TEvents> | undefined,
    event: string
  ): TransitionDefinition<TContext, TEvents> {
    let internal = transitionConfig ? transitionConfig.internal : false;
 
    // Check if there is no target (targetless)
    // An undefined transition signals that the state node should not transition from that event.
    if (target === undefined || target === TARGETLESS_KEY) {
      return {
        ...transitionConfig,
        actions: transitionConfig ? toArray(transitionConfig.actions) : [],
        target: undefined,
        internal: transitionConfig
          ? transitionConfig.internal === undefined
            ? true
            : transitionConfig.internal
          : true,
        event
      };
    }
 
    const targets = toArray(target);
 
    // Format targets to their full string path
    const formattedTargets = targets.map(_target => {
      const internalTarget =
        typeof _target === 'string' && _target[0] === this.delimiter;
      internal = internal || internalTarget;
 
      // If internal target is defined on machine,
      // do not include machine key on target
      if (internalTarget && !this.parent) {
        return _target.slice(1);
      }
 
      return internalTarget ? this.key + _target : _target;
    });
 
    return {
      ...transitionConfig,
      actions: transitionConfig ? toArray(transitionConfig.actions) : [],
      target: formattedTargets,
      internal,
      event
    };
  }
  private formatTransitions(): TransitionsDefinition<TContext, TEvents> {
    const onConfig = this.config.on || EMPTY_OBJECT;
    const doneConfig = this.config.onDone
      ? {
          [done(this.id)]: this.config.onDone
        }
      : undefined;
    const delayedTransitions = this.after;
 
    const formattedTransitions: TransitionsDefinition<
      TContext,
      TEvents
    > = mapValues({ ...onConfig, ...doneConfig }, (value, event) => {
      if (value === undefined) {
        return [{ target: undefined, event, actions: [], internal: true }];
      }
 
      if (Array.isArray(value)) {
        return value.map(targetTransitionConfig =>
          this.formatTransition(
            targetTransitionConfig.target,
            targetTransitionConfig,
            event
          )
        );
      }
 
      if (typeof value === 'string') {
        return [this.formatTransition([value], undefined, event)];
      }
 
      Eif (!IS_PRODUCTION) {
        keys(value).forEach(key => {
          Iif (
            ['target', 'actions', 'internal', 'in', 'cond'].indexOf(key) === -1
          ) {
            throw new Error(
              `State object mapping of transitions is deprecated. Check the config for event '${event}' on state '${
                this.id
              }'.`
            );
          }
        });
      }
 
      return [
        this.formatTransition(
          (value as TransitionConfig<TContext, TEvents>).target,
          value,
          event
        )
      ];
    }) as TransitionsDefinition<TContext, TEvents>;
 
    delayedTransitions.forEach(delayedTransition => {
      formattedTransitions[delayedTransition.event] =
        formattedTransitions[delayedTransition.event] || [];
      formattedTransitions[delayedTransition.event].push(
        delayedTransition as TransitionDefinition<
          TContext,
          TEvents | EventObject
        >
      );
    });
 
    return formattedTransitions;
  }
}
 
export { StateNode };