All files / core/blong-gogo/src load.ts

74.06% Statements 1568/2117
80.41% Branches 386/480
75.72% Functions 78/103
74.06% Lines 1568/2117

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 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 21181x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 351x 351x 351x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 702x 702x 702x 702x 702x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 47x 47x 47x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 47x 47x 47x 47x 47x 47x 47x 2347x 7x 2347x 810x 2347x 1537x 1537x 1537x 810x 810x 810x 810x 47x 47x 47x 47x 1x 1x 1x 1x 1x 263x 263x 263x 263x 263x 263x 263x 263x 7x 7x 7x 7x 371x 371x 371x 371x 245x 126x 422x 422x 5260x 263x 263x 1x 1x 1x 1x 1x                                                                                                                         304x 304x 304x 304x                         305x 305x 305x 305x 305x           305x 305x 1x 1x 1x 1x 34x 34x 34x 34x 34x 34x 34x 655x 655x 655x 655x 655x 655x 655x 655x 655x 655x 655x 655x 655x 655x 655x 655x 655x 655x 655x 655x 655x 655x 655x 655x 655x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 305x 305x 305x 305x 305x 305x 465x 465x 5x 465x 5x 5x 5x 5x 5x 5x 5x 5x 305x 76x 76x 76x 76x 76x 76x 5x 5x 5x 76x 76x 76x 305x     305x       305x 305x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 305x 305x 305x 305x 305x 305x 305x 4x 4x 8x 4x 4x 4x 1x 4x 4x 3x 1x 1x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 161x 161x 33x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 34x 34x 34x 34x 34x                                                                                                                                                                             7x                                                                                                                                                                                         47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 27x 47x 47x 33x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x     47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 21x 21x 21x 3x 18x 21x 47x 47x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 7x     7x 7x 7x 7x 7x 7x 7x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 1x 1x 1x 1x 1x 1x 1x 41x 41x                   810x 810x 810x                 304x 304x 304x 304x 304x 304x 304x 7x 7x 304x 304x 304x 304x 304x 304x 304x 304x 304x 1x 1x 304x 304x 304x 304x 304x 304x 304x 304x 304x 1x 304x 304x 304x 304x 304x 1x 1x 304x 304x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x     304x 304x 304x 304x 304x 304x 305x 211x 211x 1356x 1356x 211x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 257x 305x 23x 23x 23x 23x 23x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 305x 25x 25x 305x 305x 305x 305x 305x 305x 305x 305x 84x 305x 305x 305x 305x 305x 305x 304x 304x 304x 304x 304x 304x     305x 305x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 233x 263x 263x 263x 263x 263x 263x 263x 263x 263x 425x 425x 425x 425x 263x 305x                                                                     304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 207x 207x 207x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x   592x 1776x                 304x 304x 304x         304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 207x 47x 47x 47x 47x 47x 47x 47x 207x 207x 207x 207x 207x     207x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 305x           304x 304x 304x 304x 304x 304x 304x 304x 305x 304x 371x 51x 51x 51x 51x 51x                 51x 51x 51x 51x 320x 320x 304x 304x 304x 304x 304x 304x 304x 304x 305x 41x 246x 246x 246x 246x 246x 246x 246x 246x 246x 246x 246x 246x 246x 246x 246x 246x 41x 40x 246x 39x 39x 207x 229x 144x 47x 47x 144x 246x 246x 246x 246x 246x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 1852x 1852x 1852x 1852x 1852x 1852x 1852x 1852x 1852x 1852x 1852x 1852x 1852x 1805x 1805x             37x 37x 37x   37x 37x 37x 19x 29x 8x 8x 18x 18x 18x 18x                                                       18x 18x 18x 609x 572x 572x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x   42x 42x 42x 7x 7x 7x 35x 35x 35x 42x                 42x 42x 42x 42x 110x 110x 109x 109x 88x 88x 88x 88x 88x 88x 88x 88x 88x 88x 88x 88x 88x 88x 88x 88x 88x 109x 109x 196x 196x 196x 196x 196x 109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 109x                                                                 1648x 2261x 2261x 2261x 2261x 2261x 2261x 2261x 2261x 2261x 2261x 2062x 2062x 2062x 2062x 2261x 601x 601x 601x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x             47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 47x 47x 47x 47x 47x 25x 1x 1x 1x 1x 1x 1x 1x 1x 1x 47x 47x 47x 21x 47x                                                                             47x 2261x 1461x 141x 141x 141x 141x 257x 257x 257x 63x 63x 63x 63x 63x 63x 63x 63x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x                                             7x 7x 7x 7x 7x 7x 7x   7x 37x 34x 34x 34x 37x                     34x 34x 34x 34x 34x 37x         34x 34x 34x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 3937x 3937x 7x 1042x 1042x 745x 297x 1042x 1042x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x                                                     304x 304x 304x 304x 304x 304x 304x 304x                                       63x 25x 25x 305x 304x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 305x 305x 305x  
import {
    Internal,
    browser as browserFactory,
    kind,
    orchestrator,
    server as serverFactory,
    type IApiSchema,
    type IConfigRuntime,
    type IErrorFactory,
    type ILog,
    type ILogger,
    type IManifest,
    type IModuleConfig,
    type IPlatformApi,
    type IRegistry,
    type Kind,
    type Kinds,
    type SolutionFactory,
} from '@feasibleone/blong/types';
 
import {SLOW_STEP_MS, withProgress} from '@feasibleone/blong-lib';
import {WELL_KNOWN_LAYERS} from '@feasibleone/blong-lib/layers';
import {Type, type TSchema} from 'typebox';
import merge from 'ut-function.merge';
import {methodParts} from './lib.ts';
 
import {formatConfigIssues, validateConfigBlock} from './configValidation.ts';
import {devEncryptKey, devSignKey} from './devKeys.ts';
import {GENERATED_PAIR_WARNING, resolveGatewayPair} from './gatewayKeys.ts';
import layerProxy from './layerProxy.ts';
import RealmImpl, {type IRealm} from './Realm.ts';
import type {IWatch} from './Watch.ts';
 
/**
 * The extension of the source that is about to be imported — `.ts`, this file's own.
 *
 * Every loader below spells its specifier `import('./Mcp' + extension)`. Written as
 * a literal, the concatenation is folded by the bundler, the specifier gets resolved
 * and the module is bundled: the `@vite-ignore` comment silences the warning but does
 * not stop the resolution. That is how `fastify` and the observability service, or
 * `Gateway`, `RpcServer`, `Mcp` and the rest of the server half of the platform map,
 * ended up in browser builds whose `rootKind` never reaches them. Deriving the value
 * from this module's own url keeps the meaning while leaving those specifiers opaque.
 */
const extension = import.meta.url.endsWith('.ts') ? '.ts' : '.js';
 
/**
 * A module url as it is compared: the `file://` scheme is not part of a file's
 * identity, and one of the two sides of every comparison (`import.meta.url`) has
 * it while the other (`createRequire().resolve()`) does not.
 */
function normaliseUrl(url: string): string {
    return url.startsWith('file://') ? url.slice(7) : url;
}

const LAYER_FILE = 'layer' as const;
 
/**
 * Whether the process runs on CI.
 *
 * `load.ts` is shared by both platforms, and `process` does not exist in the
 * browser bundle — a bare `process.env.CI` throws a `ReferenceError` while the
 * browser realm loads (every browser test then fails with "process is not
 * defined"). The optional chain keeps the server behaviour and degrades to
 * `false` in the browser, which is correct: the server platform's `exit` drives
 * the shutdown of both.
 *
 * A function rather than a module constant so the value is read when the config
 * is built, not when the module is first imported.
 */
function isCI(): boolean {
    return Boolean(
        (globalThis as {process?: {env?: Record<string, string | undefined>}}).process?.env?.['CI'],
    );
}
 
/**
 * Whether stdout is a terminal, in a process that has one.
 *
 * The same reason as {@link isCI}: both platforms build this config block, and
 * `process` does not exist in the browser bundle. Absent, colour is off, which is
 * the right answer there anyway — a browser writes no stdout.
 *
 * It answers for a bare `dev` run, and nothing else: a runtime that pipes this
 * process's stdout can still be watched — Playwright relays the lines it captures
 * back into the terminal — so those runs say so with an intent instead
 * (`playwright`, and `ci` for the captured case), rather than leaving the
 * platform to infer it from a file descriptor.
 */
function isTTY(): boolean {
    return (globalThis as {process?: {stdout?: {isTTY?: boolean}}}).process?.stdout?.isTTY === true;
}
 
/**
 * An infrastructure item declaration with explicit dependencies.
 * Items are topologically sorted before instantiation so that each item's
 * dependencies are guaranteed to be available when it is created.
 */
interface InfraItem {
    /** Infrastructure item name (becomes the key in the `api` object). */
    name: string;
    /** Names of other infrastructure items this one depends on. */
    deps: string[];
    /** Factory that returns the module (via dynamic import). */
    load: () => Promise<unknown>;
}
 
/**
 * Topological sort of infrastructure items by their declared dependencies.
 * Throws if a cycle is detected.
 */
function topoSort(items: InfraItem[]): InfraItem[] {
    const byName = new Map(items.map(item => [item.name, item]));
    const sorted: InfraItem[] = [];
    const visited = new Set<string>();
    const visiting = new Set<string>();
 
    function visit(item: InfraItem): void {
        if (visited.has(item.name)) return;
        if (visiting.has(item.name))
            throw new Error(`Circular infrastructure dependency: ${item.name}`);
        visiting.add(item.name);
        for (const dep of item.deps) {
            const depItem = byName.get(dep);
            if (depItem) visit(depItem);
        }
        visiting.delete(item.name);
        visited.add(item.name);
        sorted.push(item);
    }
 
    for (const item of items) visit(item);
    return sorted;
}
 
/**
 * Discover layer folders in a realm directory that are not already listed as children.
 * Returns a map of folderName -> activation config.
 */
async function discoverLayerFolders(
    {existsSync, join}: IPlatformApi,
    base: string,
    kind_: 'server' | 'browser',
    explicitChildren: Set<string>,
): Promise<[string, object][]> {
    const result: [string, object][] = [];
    for (const name of Object.keys(WELL_KNOWN_LAYERS)) {
        if (explicitChildren.has(name)) continue;
        const layerFolder = join(base, name);
        if (!existsSync(layerFolder)) continue;
        const layerFile = join(base, name, `${LAYER_FILE}.${kind_}.ts`);
        if (existsSync(layerFile)) {
            // Read activation from layer.server.ts / layer.browser.ts
            const mod = await import(/* @vite-ignore */ layerFile).catch(() => null);
            const activation = mod?.default ?? {default: true};
            result.push([name, activation]);
        } else if (name in WELL_KNOWN_LAYERS && WELL_KNOWN_LAYERS[name][kind_]) {
            result.push([name, WELL_KNOWN_LAYERS[name][kind_]]);
        }
    }
    return result;
}
 
/**
 * Discover test method names from a realm's test/test/ folder.
 * Imports each handler file with a null proxy to extract method names.
 */
async function discoverRealmTestMethods(
    {existsSync, readdir, join, basename, extname}: IPlatformApi,
    base: string,
): Promise<string[]> {
    const testDir = join(base, 'test', 'test');
    if (!existsSync(testDir)) return [];
    const nullFn: unknown = new Proxy(
        function () {
            return nullFn;
        } as unknown as object,
        {
            get(_, key) {
                if (typeof key === 'symbol') return undefined;
                return nullFn;
            },
            apply() {
                return nullFn;
            },
        },
    );
    const files = (await readdir(testDir)).filter(
        f => f.isFile() && /\.(ts|mts|js|mjs)$/i.test(f.name) && !f.name.startsWith('~'),
    );
    const methods: string[] = [];
    for (const file of files) {
        const filePath = join(testDir, file.name);
        try {
            const mod = await import(/* @vite-ignore */ filePath);
            const fn = mod?.default;
            if (typeof fn === 'function') {
                const result = fn({
                    lib: nullFn,
                    handler: nullFn,
                    errors: nullFn,
                    config: {},
                    remote: nullFn,
                    local: nullFn,
                });
                if (result && typeof result === 'object' && !Array.isArray(result)) {
                    for (const key of Object.keys(result)) methods.push(methodParts(key));
                } else {
                    methods.push(methodParts(basename(file.name, extname(file.name))));
                }
            } else {
                methods.push(methodParts(basename(file.name, extname(file.name))));
            }
        } catch {
            methods.push(methodParts(basename(file.name, extname(file.name))));
        }
    }
    return methods;
}

/**
 * The margin a step of a load is measured against when the realm names none.
 *
 * Read off the log config (`log.slowMs`) so a realm or a runner can raise it for
 * a machine that is legitimately slow, and so one number tunes both halves of a
 * delayed start: the loader's steps and the retention store's own.
 */
function slowStepMs(log: unknown): number {
    const configured = (log as {slowMs?: unknown} | undefined)?.slowMs;
    return typeof configured === 'number' && configured >= 0 ? configured : SLOW_STEP_MS;
}

/**
 * A logger for the steps that run before the realm's own log exists.
 *
 * A root load builds the log component first, and until it is up there is nothing
 * to log through — which is exactly when a slow step is least visible and most
 * confusing, because the process prints nothing at all for as long as it takes.
 * This writes to stderr, where the framework's other startup messages go, and
 * stays silent in a platform that has no process (the browser bundle). Only
 * `warn` is answered: a step that is not slow has nothing to say, and the
 * loader's ordinary progress belongs in the log the realm is about to have.
 */
function bootstrapLogger(): {warn: (...args: unknown[]) => void} {
    return {
        // Pino-shaped, like every other logger `withProgress` is handed: the
        // details object first, the message second.
        warn: (...args: unknown[]) => {
            const [details, message] = args as [Record<string, unknown> | undefined, string];
            const stderr = (globalThis as {process?: {stderr?: {write: (text: string) => void}}})
                .process?.stderr;
            stderr?.write(`warn  blong ${message} ${JSON.stringify(details ?? {})}\n`);
        },
    };
}
 
const System: symbol = Symbol('system');
 
export function system(original: {[key: symbol]: boolean}): void {
    original[System] = true;
}
 
interface IConstructor {
    new (config?: object, api?: object): object;
}
 
function activeConfigs<T extends TSchema>(
    mod: IModuleConfig<T>,
    configNames: string[],
    platformConfigs: string[],
): (boolean | object)[] {
    return (
        (
            (['default'] as string[])
                .concat(configNames)
                .concat(platformConfigs)
                // A CI run *is* a captured run, so the `ci` block applies whether or not the
                // entry named the intent — the same reason `exit` is derived from `isCI()`
                // in the synthetic config. Which entry happened to know about CI decided
                // whether a package's tap leg wrote Allure results at all, and a package
                // whose only runner is tap then had no report to link.
                //
                // Named last, which is where a caller that passes it puts it: the Playwright
                // webServer passes `ci` after `playwright` so its colours win over the block's
                // `log.color = false`.
                .concat(isCI() ? ['ci'] : [])
                .map(name => (mod.config as unknown as Record<string, unknown>)?.[name])
                .filter(Boolean) as (boolean | object)[]
        ).concat({pkg: mod.pkg, children: mod.children, url: mod.url})
    );
}
 
/** A thenable value that can be externally resolved/rejected. */
interface IDeferred<T> {
    then: Promise<T>['then'];
    resolve: (value: T | PromiseLike<T>) => void;
    reject: (reason?: unknown) => void;
}
 
/** Create a thenable with externally callable `resolve` / `reject`. */
function createDeferred<T>(): IDeferred<T> {
    let resolve!: (value: T | PromiseLike<T>) => void;
    let reject!: (reason?: unknown) => void;
    const promise = new Promise<T>((res, rej) => {
        resolve = res;
        reject = rej;
    });
    return {
        then: promise.then.bind(promise),
        resolve,
        reject,
    };
}
 
/**
 * Wrap a plain manifest object in a Proxy that automatically creates
 * unresolved {@link IDeferred} values on first read of a missing property,
 * and resolves them on the first write.
 *
 * This lets users pass a plain `{}` to `load()` — properties like
 * `gatewayPort` are auto-provisioned as pending promises when read, and resolved
 * when the server-side component (e.g. Gateway) writes the actual value.
 * Consumers that await the property will transparently wait for the deferred
 * to be settled.
 */
function createManifestProxy(manifest: IManifest): IManifest {
    const pending = new Map<string, IDeferred<unknown>>();
    const OWN_KEYS = new Set<string>();
 
    return new Proxy(manifest, {
        get(target, prop: string | symbol) {
            if (typeof prop !== 'string') return Reflect.get(target, prop, target);
            if (prop in target) return target[prop];
            if (prop === '__proto__' || prop === 'constructor')
                return Reflect.get(target, prop, target);
            if (!pending.has(prop)) {
                const deferred = createDeferred();
                pending.set(prop, deferred);
                target[prop] = deferred;
                OWN_KEYS.add(prop);
            }
            return target[prop];
        },
        set(target, prop: string | symbol, value) {
            if (typeof prop !== 'string') return Reflect.set(target, prop, value, target);
            // Resolve any pending deferred — either from our own proxy instance
            // or one placed on the target by another proxy instance (when the
            // same manifest object is passed to separate load() calls).
            const existing = pending.get(prop) ?? target[prop];
            if (existing && typeof existing === 'object' && 'resolve' in (existing as object)) {
                (existing as IDeferred<unknown>).resolve(value);
                pending.delete(prop);
            }
            target[prop] = value;
            return true;
        },
        ownKeys(target) {
            return [...Reflect.ownKeys(target), ...OWN_KEYS];
        },
        has(target, prop: string | symbol) {
            if (OWN_KEYS.has(prop as string)) return true;
            return Reflect.has(target, prop);
        },
    });
}
 
/**
 * Refuse a combination the entry itself declared incompatible.
 *
 * `intentsExclusionGroups` on a `server()` definition names intents that must not run together: a
 * group allows at most one of its members to be active, and `dev` with `release` is the case that
 * motivated the field. Combining two of them is not a load error on its own — both configuration
 * blocks merge, in the order given, and the later one wins where they overlap — so the process is
 * neither the one nor the other and nothing says so. The check runs before a single source is
 * merged, which is what keeps the refusal cheap and the message the whole cost of it.
 */
const assertIntentsExclusion = (
    mod: unknown,
    configNames: readonly string[],
    name: string,
): void => {
    const groups = (mod as {intentsExclusionGroups?: readonly (readonly string[])[]} | undefined)
        ?.intentsExclusionGroups;
    if (!Array.isArray(groups)) return;
    for (const group of groups) {
        const active = (Array.isArray(group) ? group : []).filter(intent =>
            configNames.includes(intent),
        );
        if (active.length > 1)
            throw new Error(
                `${name} declares the intents ${active.join(' and ')} exclusive: at most one of them may run`,
            );
    }
};
 
export default async function loadRealm<T extends TSchema>(
    platformApi: IPlatformApi,
    def: SolutionFactory<T> & {[symbol: Kind]: Kinds},
    name: string,
    parentConfig: object | string,
    configNames: string[],
    manifest?: IManifest,
    api?: {
        platform: IPlatformApi;
        watch?: IWatch;
        apiSchema?: IApiSchema;
        error?: IErrorFactory;
        port?: () => void;
        log?: ILog;
        registry?: IRegistry;
        configRuntime?: IConfigRuntime;
        /**
         * The realms this load tree has produced, by the file they came from.
         *
         * Held on the shared `api` so a nested load can record the realm it
         * created, which is the only place the url is readable: a suite's child is
         * the realm *factory*, so the parent's own wrapper finds no `url` on it.
         * Filled for the platform root and inherited by every load beneath it.
         */
        loadedRealmUrls?: Set<string>;
        /**
         * The reload validators, one per module, filled as each module validates
         * its own config block and read by the root's validator hook, which
         * `ConfigRuntime` runs before installing a reloaded snapshot (@@D-548).
         */
        configValidators?: Array<(snapshot: object) => void>;
    } & {
        [key: string]: {init?: () => Promise<unknown>};
    },
    rootKind?: 'server' | 'browser',
    /**
     * Re-derives this module's config block from a whole candidate snapshot, so
     * the module's check runs against a reload as well as at startup. The root's
     * getter is the snapshot itself; a child's is its parent's getter indexed by
     * the child's name, which is why it is threaded through the recursion — the
     * alternative, a path, could not survive `loadRealm`'s re-entry for a realm
     * wrapped in its own minimal suite (@@D-548).
     */
    blockOf: (snapshot: object) => unknown = snapshot => snapshot,
): Promise<IRegistry> {
    /**
     * The attacher that turns a layer's declarations into the `signal` proxy its handlers call.
     *
     * Loaded lazily and cached per call — `loadRealm` is re-entered for every child realm, and the
     * module itself is a singleton anyway. It was skipped in the browser while lukaot's root still
     * reached pino and `node:async_hooks`; the root is platform-free and the node half lives behind
     * `@feasibleone/lukaot/node`, so the same attacher serves a page (@@D-912 @@D-920).
     */
    let attacher:
        | Promise<((port: object, vocabularies: readonly object[]) => void) | undefined>
        | undefined;
    const signalsAttacher = () =>
        (attacher ??= import('./signals.ts').then(
            ({attachSignals}) =>
                attachSignals as (port: object, vocabularies: readonly object[]) => void,
        ));
    // Wrap the manifest in a proxy that auto-creates Deferred values on first
    // read and resolves them on first write. This lets callers pass a plain
    // object and have properties like `gatewayPort` transparently work as
    // cross-platform synchronization points.
    //
    // A run that supplies no manifest still gets one, because the manifest is also how
    // a component tells **the rest of its own process** something only it can know: the
    // address of the in-process cluster service, which is bound on a port the operating
    // system chooses. Nothing about a caller that omits the object changes — it was
    // `undefined` before, and no component could publish into it.
    manifest = createManifestProxy(manifest ?? {});
    const defKind = kind(def);
    if (!rootKind) {
        if (defKind === 'server' || defKind === 'browser') rootKind = defKind;
        else if (defKind === 'solution') {
            // Realm passed directly as root — wrap in a minimal suite for isolated testing
            const realmMod = await def({type: Type, manifest});
            const realmUrl = realmMod.url as string;
            const realmFilePath = realmUrl.startsWith('file://') ? realmUrl.slice(7) : realmUrl;
            const realmBase = platformApi.dirname(realmFilePath);
            const realmFileName = platformApi.basename(realmFilePath);
            const realmName = platformApi.basename(realmBase);
            let pkg: {name: string; version: string} = realmMod.pkg || {
                name: realmName,
                version: '0.0.0',
            };
            if (platformApi.createRequire) {
                try {
                    pkg = platformApi.createRequire(realmUrl)('./package.json') as {
                        name: string;
                        version: string;
                    };
                } catch {}
            }
            const testMethods = await discoverRealmTestMethods(platformApi, realmBase);
            const realmChild = Object.defineProperty(
                async function () {
                    return {default: def};
                },
                'name',
                {value: realmName, configurable: true},
            );
            if (realmFileName.startsWith('browser')) {
                // Browser realm — wrap in a minimal browser suite
                const wrapper = browserFactory((() => ({
                    url: '',
                    pkg,
                    children: [realmChild],
                    config: {
                        default: {[realmName]: {}},
                        integration: {watch: {test: testMethods}},
                    },
                    // eslint-disable-next-line @typescript-eslint/no-explicit-any
                })) as () => any);
                return loadRealm(
                    platformApi,
                    // eslint-disable-next-line @typescript-eslint/no-explicit-any
                    wrapper as any,
                    name,
                    parentConfig,
                    configNames,
                    manifest,
                    // A wrapper replaces the realm at the same level, so the block
                    // getter is unchanged; `api`/`rootKind` stay undefined as before.
                    undefined,
                    undefined,
                    blockOf,
                );
            } else {
                // Server realm — single platform if no browser.ts alongside, else two-platform server half
                const hasBrowser = platformApi.existsSync(
                    platformApi.join(realmBase, 'browser.ts'),
                );
                const wrapper = serverFactory(() => ({
                    url: '',
                    pkg,
                    children: [realmChild],
                    config: {
                        default: {
                            rpcServer: {port: 0},
                            gateway: {port: hasBrowser ? 8080 : 0},
                            [realmName]: {},
                        },
                        integration: hasBrowser
                            ? {default: {}} // browser side handles watch.test;
                            : {
                                  default: {},
                                  watch: {test: testMethods},
                              },
                    },
                }));
                return loadRealm(
                    platformApi,
                    // eslint-disable-next-line @typescript-eslint/no-explicit-any
                    wrapper as any,
                    name,
                    parentConfig,
                    configNames,
                    manifest,
                    // A wrapper replaces the realm at the same level, so the block
                    // getter is unchanged; `api`/`rootKind` stay undefined as before.
                    undefined,
                    undefined,
                    blockOf,
                );
            }
        } else {
            throw new Error(`Root realm must be of kind "server" or "browser", got "${defKind}"`);
        }
    }
    // Whether this is the platform's own load — captured *before* `api` is assigned
    // below. Read afterwards, the check that gates framework realm auto-inclusion is
    // always false, and every framework realm is silently absent: the gateway then
    // refuses every unauthenticated route (no login realm) and RBAC resolves nothing.
    const isPlatformRoot = api === undefined;
    const bootstrap = bootstrapLogger();
    // A factory may answer with the module or with a promise for it, so the
    // measurement wraps whatever it answered rather than assuming the shape.
    const mod = await withProgress(
        bootstrap,
        `suite ${name}`,
        Promise.resolve(def({type: Type, manifest})),
        {slowMs: SLOW_STEP_MS},
    );
    // Record the realm's own file in the tree's set, so a realm reached twice -
    // once as a suite's child and once by the framework's `frameworkRealms` - is
    // recognised the second time. A realm answers with its *factory*, so its url
    // is readable only here, where the module has been created; the wrapper around
    // a suite's children sees the factory and can read nothing off it (F-194).
    if (typeof (mod as {url?: unknown}).url === 'string') {
        api?.loadedRealmUrls?.add(normaliseUrl((mod as {url?: string}).url as string));
    }
    if (!('pkg' in mod) && platformApi.platform === 'server')
        mod.pkg = platformApi.createRequire?.(mod.url)('./package.json');
    assertIntentsExclusion(mod, configNames, name);
    const loadedConfigs = [];
    /**
     * The framework's own intent blocks (`default` + the active intents),
     * resolved once per root load. Kept so their explicit `false` values can be
     * re-asserted after every source has merged.
     */
    let frameworkConfigs: (boolean | object)[] = [];
    let items:
        | IModuleConfig['children']
        | {
              path: string;
              name: string;
              isFile?: () => Promise<unknown>;
              isDirectory?: Record<string, () => Promise<unknown>>;
          }[] = [];
    if (!api) {
        api = {
            platform: platformApi,
            manifest,
            // One reload validator per module, filled as each module validates its
            // own config block and read by the root's validator hook (@@D-548).
            configValidators: [],
        } as unknown as typeof api;
        // Retained so the "an intent's `false` wins" reconciliation can re-assert
        // these after every source has merged (see below).
        frameworkConfigs = activeConfigs(
            {
                url: '',
                config: {
                    default: {
                        watch: {
                            test: [],
                            /**
                             * Allure reporting for handler tests. Off by default: a report is
                             * something a run is asked for, which is what `--watch.allure.enabled=true`
                             * on the blong CLI does for a dev run and what the `ci` block below does
                             * for a captured one. `blong-allure` is a dependency of this package, so
                             * the CLI that turns the results into HTML is the one they were written
                             * for rather than whatever is on the runner's PATH.
                             *
                             * The results have a directory of their own because a package can report
                             * to Allure from two producers — the browser tests of a realm and its
                             * handler tests — and each clears the directory it writes to before a run.
                             * `blong-dev` merges every producer's directory into the one report a
                             * package publishes.
                             */
                            allure: {
                                enabled: false,
                                outputDir: 'allure-results-tap',
                                historyPath: '.allure/history.jsonl',
                                generateOnEnd: false,
                            },
                        },
                        // The server's log implementation. The browser platform
                        // keeps its own logger regardless: the loader checks the
                        // platform before this key, because the emitter's store is
                        // node-only.
                        log: {
                            // Colour when a human is watching, plain text when the
                            // output is piped or captured, so a terminal keeps the
                            // colours the pino printer used to give it while a test
                            // run stays readable as text.
                            color: isTTY(),
                        },
                        apiSchema: {},
                        error: {},
                        registry: {},
                        port: {},
                        codec: {},
                        adapter: {},
                        orchestrator: {},
                        remote: {
                            canSkipSocket: rootKind === 'browser',
                        },
                        local: {},
                        rpcServer: {},
                        gateway: {},
                        restFs: {},
                        systemDebug: {},
                        mcp: {},
                        apiGateway: {},
                    },
                    dev: {
                        resolution: true,
                        rpcServer: {
                            port: 0,
                        },
                        log: {
                            // The semantic implementation's store, and the pino
                            // implementation's cache beside it: they share one
                            // directory and one key space, so a
                            // `semlog://r/<id>` reference resolves
                            // whichever implementation wrote the entry.
                            cache: {
                                dir: '~/.blong/log-cache',
                                // The framework's own bound, rather than the
                                // emitter's default: a verbose record is tens of
                                // kilobytes, so ten thousand of them is most of a
                                // gigabyte and a slower open for every process in
                                // dev.
                                limit: 5000,
                            },
                            cacache: {
                                cachePath: '~/.blong/log-cache',
                            },
                            // The service that turns the records into templates,
                            // flows and diagrams, run in this process: a
                            // development run can then be drawn from what it just
                            // did, and a test run leaves diagrams behind.
                            //
                            // The port is asked for, never named. Two framework
                            // processes on one machine are ordinary — a dev server
                            // beside a Playwright run, or CI running packages in
                            // parallel — and only one of them can hold a fixed port.
                            // The loser is not degraded but *blind*: its own records
                            // never reach a service, while its readers keep looking at
                            // whatever holds the port, which is another process's
                            // service. `0` asks the operating system, and the address
                            // it gets is published by the log it started
                            // (`ILog.clusterUrl`), which is how a realm's port learns
                            // where to read.
                            cluster: {enabled: true, port: 0},
                        },
                        gateway: {
                            port: 0,
                            static: {},
                            debug: true,
                            expectedErrors: true,
                            // Static development keys, so sessions survive server hot-reloads
                            // and so `blong grant` can mint a token the same server accepts
                            // (see `devKeys.ts`).
                            sign: devSignKey,
                            encrypt: devEncryptKey,
                        },
                        systemDebug: {enabled: true},
                    },
                    integration: {
                        remote: {canSkipSocket: true},
                        // Port 0, for the reason the `dev` block gives: two processes on
                        // one machine must not want the same socket.
                        log: {cluster: {enabled: true, port: 0}},
                        gateway: {
                            debug: true,
                            expectedErrors: true,
                        },
                        // Long-lived normally, but in CI the test run IS the
                        // work, so the process is expected to end after it.
                        exit: isCI(),
                    },
                    // Playwright drives the platform from its own webServer,
                    // so it has to outlive the test command. Declared here so
                    // the runner can ask the config instead of pattern-matching
                    // the intent names.
                    playwright: {
                        exit: false,
                        log: {
                            // Port 0, for the reason the `dev` block gives.
                            cluster: {enabled: true, port: 0},
                            // The runner pipes this process's stdout (`stdout: 'pipe'`),
                            // so `isTTY()` is false and the `dev` block would leave the
                            // records plain — while the runner relays those very lines
                            // into the terminal and colours its own output beside them.
                            // A Playwright run is watched, so the records are too; the
                            // `ci` block below takes that back for a captured run.
                            color: true,
                        },
                    },
                    /**
                     * A run whose output is captured rather than watched. The
                     * Playwright webServer passes this last in CI, so it wins over the
                     * `playwright` block's colours. A captured run is also the run whose
                     * report nobody is watching, so its Allure results are written and
                     * its HTML report generated at the end.
                     *
                     * On CI the block applies whether or not the intent was named: the
                     * environment already says the output is captured, and an entry that
                     * has to remember to pass `ci` for its package to have a report is a
                     * trap for the next package (`activeConfigs`).
                     */
                    ci: {
                        log: {color: false},
                        // Results, not a report: `blong-dev` turns every producer's results
                        // into the one report a package publishes, so generating here would
                        // be the same work again, into a directory nobody uploads.
                        watch: {allure: {enabled: true}},
                    },
                    /**
                     * A deployed process never runs the service itself: the
                     * service is deployed once, beside the processes whose
                     * records it assembles, and they point at it with
                     * `log.cluster.url`. Left out, a process that happened to
                     * carry both this intent and a development one would start a
                     * second service per replica.
                     *
                     * `release` is the one block uat, staging and production
                     * share (Q8): one name for one idea, and no alias for the
                     * `prod` it replaces, because what a release runs has to be
                     * the configuration that was tested. It is also where the
                     * `semlog://` references stop: they are a development aid
                     * rendered into the text of a record, and noise in the
                     * stdout of a service nobody reads by hand. `log.impl` stays
                     * unset here, so the semantic package is never imported — the
                     * refs it renders are the ones being suppressed.
                     *
                     * It is also the *deployment* block, so it carries the two settings a deployed
                     * process differs by, and nothing else: where a service id resolves (the
                     * cluster's Services, not ports on this machine — the local resolver would
                     * answer `ENOTFOUND rpc-subject` for the framework's own namespace) and that a
                     * call answering for a namespace this very process serves is dispatched
                     * in-process rather than over a socket to itself (`canSkipSocket`; a call to
                     * another process still goes over the socket). A suite overrides either in its
                     * own `release` block; the layers it activates are not decided here at all, and
                     * `release` names none (`core/blong-lib/layers.ts`) — a released process takes
                     * them from the `--<realm>.<layer>` flags its plan wrote.
                     */
                    release: {
                        log: {cluster: {enabled: false}, refs: false},
                        resolution: {impl: 'kubernetes'},
                        remote: {canSkipSocket: true},
                    },
                    /**
                     * Brings an existing database up to date, then exits: a schema sync plus the
                     * production seeds are what a *deployed* database needs, and no long-lived
                     * process does that for it. What this block owns is when such a run is over;
                     * what the run *does* is the owning adapter's — `schema.sync` and `schema.seed`
                     * in the `blong-server` realm's `db` adapter — because the same intent may
                     * activate the equivalent work on another adapter.
                     *
                     * It serves nothing, so nothing that would serve is started: no gateway, no
                     * socket to accept a call on, no introspection surface. That is not an
                     * optimisation. The gateway is what asks for the generated validations, and
                     * building them reads every public model through the handler proxy — a
                     * migration process has no gateway to route them to, so what was left was a
                     * call dialling a service that does not exist (`F-653`).
                     */
                    upgrade: {
                        gateway: false,
                        rpcServer: false,
                        apiGateway: false,
                        restFs: false,
                        systemDebug: false,
                        mcp: false,
                        exit: true,
                    },
                    /**
                     * A CLI process does its work in-process and exits: it
                     * serves nothing, watches nothing, and resolves every
                     * dispatch locally.
                     */
                    cli: {
                        gateway: false,
                        rpcServer: false,
                        apiGateway: false,
                        restFs: false,
                        systemDebug: false,
                        mcp: false,
                        resolution: false,
                        // `{enabled: false}`, NOT `false`: the load step that
                        // records handler folders and files still runs (it is
                        // what feeds `Registry.describe()`); only chokidar is
                        // skipped.
                        watch: {enabled: false, logLevel: 'warn'},
                        // Dispatch in-process instead of over HTTP.
                        remote: {canSkipSocket: true},
                        // A command's stdout carries its result and has to stay
                        // parseable, so the framework's own logging is quietened
                        // here rather than by each CLI remembering to do it. The
                        // cluster service is off for the same reason it is a
                        // command: nothing here is long enough to draw, and a
                        // short-lived process must not hold a socket open.
                        log: {level: 'warn', cluster: {enabled: false}},
                        apiSchema: {logLevel: 'warn'},
                        exit: true,
                    },
                    /**
                     * Generating Kubernetes manifests has the `cli` shape: the
                     * process introspects the loaded registry, writes the
                     * artifacts and exits — it serves nothing, watches nothing
                     * and resolves every dispatch in-process. The
                     * `blong-kustomize` realm contributes the generator layer
                     * under this intent (see its `k8s/layer.server.ts`).
                     */
                    k8s: {
                        gateway: false,
                        rpcServer: false,
                        apiGateway: false,
                        restFs: false,
                        systemDebug: false,
                        mcp: false,
                        resolution: false,
                        // `{enabled: false}`, NOT `false`: the load step that
                        // records handler folders and files still runs (it is
                        // what feeds `Registry.describe()`); only chokidar is
                        // skipped.
                        watch: {enabled: false, logLevel: 'warn'},
                        // Dispatch in-process instead of over HTTP.
                        remote: {canSkipSocket: true},
                        // Generated output must stay parseable, so the
                        // framework's own logging is quietened here and the
                        // cluster service is off (nothing here is long enough to
                        // draw, and a short-lived process must not hold a socket).
                        log: {level: 'warn', cluster: {enabled: false}, color: true},
                        apiSchema: {logLevel: 'warn'},
                        exit: true,
                    },
                },
            },
            configNames,
            platformApi.configs,
        );
        loadedConfigs.push(...frameworkConfigs);
        items = topoSort([
            {
                name: 'log',
                deps: [],
                // The implementation is chosen by configuration rather than by
                // the loader. The closure runs long after every source has
                // merged, so `log.impl` is settled by the time it is called; the
                // module is imported lazily either way, so an unselected
                // implementation is never even loaded.
                load: () => {
                    if (rootKind === 'browser' && globalThis.window) {
                        return import('./BrowserLog.ts');
                    }
                    // One implementation, and the switch that used to choose it is gone with the
                    // two it chose between (`@@T-715`). `log.impl` is still read by nothing; a
                    // configuration that names it is ignored rather than refused, because every
                    // deployment in the tree names `semantic` today.
                    return import(/* @vite-ignore */ './LukaotLog' + extension);
                },
            },
            {
                name: 'apiSchema',
                deps: ['log'],
                load: () => import('./ApiSchema.ts'),
            },
            {
                name: 'port',
                deps: ['log'],
                load: () => import('./Port.ts'),
            },
            {
                name: 'error',
                deps: ['log'],
                load: () => import('./ErrorFactory.ts'),
            },
            {
                name: 'watch',
                deps: ['log'],
                load: () => import('./Watch.ts'),
            },
            {
                name: 'local',
                deps: ['log'],
                load: () => import('./Local.ts'),
            },
            {
                name: 'resolution',
                deps: ['log'],
                // Two resolvers share one name: the default assumes every service
                // is a port on this machine, the Kubernetes one resolves a service
                // id to the Service of the same name in the suite's namespace. The
                // suite picks with `resolution.impl: kubernetes`, the same way the
                // `log` component above picks its implementation.
                load: () => {
                    const impl = (mergedConfig as {resolution?: {impl?: string}} | undefined)
                        ?.resolution?.impl;
                    return impl === 'kubernetes'
                        ? import('./ResolutionK8s.ts')
                        : import('./ResolutionLocal.ts');
                },
            },
            ...(rootKind === 'browser'
                ? [
                      {
                          name: 'remote',
                          deps: ['log', 'local'],
                          load: () => import('./Remote.ts'),
                      },
                      {
                          name: 'registry',
                          deps: ['log', 'error', 'remote', 'local', 'watch', 'apiSchema'],
                          load: () => import('./Registry.ts'),
                      },
                      {
                          name: 'codec',
                          deps: ['log'],
                          load: () => import('./codec/browser.ts'),
                      },
                      {
                          name: 'orchestrator',
                          deps: ['log'],
                          load: () => import('./orchestrator/index.ts'),
                      },
                      {
                          name: 'adapter',
                          deps: ['log'],
                          load: () => import('./adapter/browser.ts'),
                      },
                  ]
                : [
                      {
                          name: 'remote',
                          deps: ['log', 'local'],
                          load: () => import(/* @vite-ignore */ './RpcClient' + extension),
                      },
                      {
                          name: 'rpcServer',
                          deps: ['log'],
                          load: () => import(/* @vite-ignore */ './RpcServer' + extension),
                      },
                      {
                          name: 'gateway',
                          deps: ['log'],
                          load: () => import(/* @vite-ignore */ './Gateway' + extension),
                      },
                      {
                          name: 'apiGateway',
                          deps: ['log', 'gateway', 'local'],
                          load: () => import(/* @vite-ignore */ './ApiGateway' + extension),
                      },
                      {
                          name: 'restFs',
                          deps: ['log', 'gateway'],
                          load: () => import(/* @vite-ignore */ './RestFs' + extension),
                      },
                      {
                          name: 'systemDebug',
                          deps: ['log', 'gateway', 'registry', 'rpcServer'],
                          load: () => import(/* @vite-ignore */ './SystemDebug' + extension),
                      },
                      {
                          name: 'mcp',
                          deps: ['log', 'gateway', 'registry', 'remote', 'apiSchema'],
                          load: () => import(/* @vite-ignore */ './Mcp' + extension),
                      },
                      {
                          name: 'registry',
                          deps: [
                              'log',
                              'error',
                              'remote',
                              'rpcServer',
                              'gateway',
                              'local',
                              'watch',
                              'apiSchema',
                          ],
                          load: () => import(/* @vite-ignore */ './Registry' + extension),
                      },
                      {
                          name: 'codec',
                          deps: ['log'],
                          load: () => import(/* @vite-ignore */ './codec/server' + extension),
                      },
                      {
                          name: 'orchestrator',
                          deps: ['log'],
                          load: () => import(/* @vite-ignore */ './orchestrator/index' + extension),
                      },
                      {
                          name: 'adapter',
                          deps: ['log'],
                          load: () => import(/* @vite-ignore */ './adapter/server' + extension),
                      },
                  ]),
        ]).map(({name, load}) => {
            const fn = load;
            Object.defineProperty(fn, 'name', {value: name});
            return fn;
        });
    }
    // The module's own config blocks for the active intents. Captured (rather
    // than inlined into `loadedConfigs`) because the keys they name are what
    // makes the config validation's allow-list: a key the module's own source
    // declares is legitimate, whatever its `validation` schema happens to say.
    const declaredBlocks = activeConfigs(mod, configNames, platformApi.configs);
    loadedConfigs.push(...declaredBlocks);
    const configPromise = platformApi.loadConfig(
        {
            name,
            pkg: {name, version: '0.0.0'},
            children: [],
            url: '',
            base: '',
            server: {
                load: {
                    logLevel: 'warn' as Parameters<ILog['logger']>[0],
                },
                realm: {
                    logLevel: 'warn' as Parameters<ILog['logger']>[0],
                },
            },
            browser: {
                load: {
                    logLevel: 'warn' as Parameters<ILog['logger']>[0],
                },
                realm: {
                    logLevel: 'warn' as Parameters<ILog['logger']>[0],
                },
            },
            configNames,
        },
        parentConfig,
        loadedConfigs.filter(Boolean) as object[],
    );
    // The config is what says how slow a step may be (`log.slowMs`), so it cannot
    // itself be measured against a configured margin — only against the default.
    const {loadedConfig: mergedConfig, configRuntime} = await withProgress(
        bootstrap,
        `config ${name}`,
        configPromise,
        {slowMs: SLOW_STEP_MS},
    );
    // This realm's own slice of the active config, recorded where a planner can reach it by name
    // (`describe().realmConfig`). Per realm rather than merged flat, because realms disagree — one is
    // a companion, another a service — and a flat key would keep only the last one's answer (D-433).
    const apiState = (api ?? {}) as {realmConfig: Record<string, unknown>};
    const realmConfig = (apiState.realmConfig ??= {});
    realmConfig[name] = merge(
        {},
        ...activeConfigs(mod, configNames, platformApi.configs).filter(
            (block): block is object => Boolean(block) && typeof block === 'object',
        ),
    );
 
    // Populate the manifest from config values (e.g. `--manifest.gatewayPort=8080`
    // parsed by blong-config into `mergedConfig.manifest.gatewayPort`).
    if (manifest && mergedConfig.manifest && typeof mergedConfig.manifest === 'object') {
        Object.assign(manifest, mergedConfig.manifest);
    }
 
    // An intent that switches a feature OFF is not overridable by a template's
    // convenience defaults. The standalone-realm wrapper below declares
    // ephemeral `gateway`/`rpcServer` ports in its `default` block; that block is
    // pushed *after* the framework's intent blocks and would otherwise silently
    // re-enable a listener the `cli` intent deliberately disabled.
    for (const config of frameworkConfigs) {
        if (!config || typeof config !== 'object') continue;
        for (const [key, value] of Object.entries(config)) {
            if (value === false) (mergedConfig as Record<string, unknown>)[key] = false;
        }
    }
 
    /**
     * One identity per process: the pair is resolved *here*, once, and both readers are handed the
     * material — the gateway that mints a bearer token and the rpc client that verifies it.
     *
     * Load time is what makes that possible at all. The client builds its MLE crypto when it is
     * constructed, which is before the gateway registers its plugin, so a pair left as a descriptor
     * for each reader to resolve would be resolved twice — and two readers of one `{generate}`
     * descriptor hold two different pairs, which is the defect a value bridge used to patch (T-267).
     * Resolving into both paths here removes the ordering question instead: the client reads material,
     * and the gateway's plugin finds nothing left to resolve.
     *
     * The *raw* snapshot, not `mergedConfig`: reading an object through the config proxy hands back a
     * path proxy rather than the value, and resolving one of those writes the path into itself, so
     * the next read of it recurses until the stack is gone. Writes land on the same object the proxy
     * delegates to, so a component reading through the proxy sees exactly what is resolved here.
     */
    if (
        rootKind === 'server' &&
        (await resolveGatewayPair(configRuntime?.rawSnapshot ?? mergedConfig))
    ) {
        // A generated pair is one a restart invalidates and a second replica does not share, so it is
        // said out loud rather than left to be discovered elsewhere, much later. The `dev` intent's
        // committed pair and a deployment's rc file both spare this line.
        console.warn(GENERATED_PAIR_WARNING);
    }
 
    /**
     * The realms' own slices of the active config are recorded per realm above and published on the
     * registry at the end of the load, not merged into this config.
     *
     * They used to be copied in here, and that copy is the bug it looks like: the root's config is
     * merged before its children load, so a snapshot taken at this point holds the root and nothing
     * else — every realm then read as absent, and a planner quietly fell back to "a service of its
     * own" for realms that had declared themselves companions (D-433). The map is handed over by
     * reference instead, and asked for by name through `describe().realmConfig`.
     */
 
    // Publish the runtime on the shared api, which `layerProxy` reads while the
    // children load. The watcher is attached later, at the end of this load: it is
    // a component of its own and does not exist yet here, so attaching it now was a
    // no-op and a config-file change was answered with "ConfigRuntime not attached;
    // config change ignored" (@@D-548).
    if (configRuntime) {
        api!.configRuntime = configRuntime;
    }
    let logger: ILogger | undefined = api?.log?.logger(
        mergedConfig[rootKind === 'browser' ? 'browser' : 'server']?.load?.logLevel,
        {
            name,
            context: `${defKind}`,
        },
    );
    // From here on every step of the load is measured against the margin the
    // config names, and a step that crosses it is reported at warn level through
    // whichever logger exists — the realm's own, or the bootstrap one while the
    // log component is still being built.
    const slowMs = slowStepMs(mergedConfig.log);
    const stepLog = () => logger ?? bootstrap;
    if (typeof parentConfig === 'string' && mergedConfig.watch)
        mergedConfig.watch.configs = mergedConfig.configs;
 
    // Auto-discover layer folders not already listed in mod.children
    // Use empty base when url is empty (e.g. minimal wrapper) to prevent scanning CWD
    const base = mergedConfig.url
        ? mergedConfig.url.startsWith('file://')
            ? platformApi.dirname(mergedConfig.url.slice(7))
            : platformApi.dirname(mergedConfig.url)
        : '';
    mergedConfig.base = base;
    const children = Array.isArray(mod.children) ? mod.children : [];
    const extraChildren: (
        | string
        | {
              path: string;
              name: string;
              isFile?: () => Promise<unknown>;
              isDirectory?: Record<string, () => Promise<unknown>>;
          }
    )[] = [];
    if (base && platformApi.platform === 'server' && defKind !== 'server') {
        const explicitChildren = new Set(
            children.filter(c => typeof c === 'string').map(c => platformApi.basename(c as string)),
        );
        const discoveredFolders = await withProgress(
            stepLog(),
            `discover layers of ${name}`,
            discoverLayerFolders(platformApi, base, rootKind, explicitChildren),
            {slowMs},
        );
        for (const [folderName, activation] of discoveredFolders) {
            if (!(folderName in mergedConfig))
                merge(mergedConfig, {[platformApi.basename(folderName)]: activation});
            extraChildren.push(`./${folderName}`);
        }
    }
    if (mod.children && !Array.isArray(mod.children)) {
        const globFolders: Record<string, Record<string, () => Promise<unknown>>> = {};
        Object.entries(mod.children)
            .sort(([keyA], [keyB]) => keyA.localeCompare(keyB))
            .forEach(([path, value]) => {
                const segments = path.split('/');
                if (segments[0] === '.') segments.shift();
                if (segments.length >= 2) {
                    if (segments.length === 2) {
                        extraChildren.push({
                            name: segments[0],
                            path,
                            isFile: value,
                        });
                    } else {
                        const target = (globFolders[platformApi.dirname(segments.join('/'))] ||=
                            {});
                        target[segments.join('/')] = value;
                    }
                }
            });
        Object.entries(globFolders).forEach(([path, isDirectory]) => {
            extraChildren.push({
                name: platformApi.dirname(path),
                path,
                isDirectory,
            });
        });
        for (const child of extraChildren) {
            const folderName = typeof child === 'object' && child.name;
            if (!folderName || folderName in mergedConfig) continue;
            const activation = WELL_KNOWN_LAYERS[folderName]?.[rootKind];
            if (activation) merge(mergedConfig, {[folderName]: activation});
        }
    }
 
    /**
     * The realms the framework ships and loads beside a suite that depends on them.
     *
     * A suite gets these without naming them, which is the point: the four lines
     * of imports and the four matching config blocks that every suite used to
     * repeat are the kind of wiring that drifts — a suite that forgot one failed
     * later, somewhere else, with a symptom that did not name the cause.
     *
     * Two properties make that safe:
     *
     * - **The suite's own manifest decides**, so a suite that does not depend on a
     *   realm is not given one. That is why the list may name realms a particular
     *   suite never installs: an undeclared package is skipped, not reported.
     * - **A realm the suite already lists is skipped too.** The suite's own
     *   children load first (they are wrapped to record the realm they produce),
     *   so by the time these are reached the already-loaded realms are known and
     *   are not loaded twice — a doubled realm would register every handler twice.
     *
     * A suite that wants none of it says so by name, in its own config:
     *
     *     config: {default: {framework: {realms: {access: false}}}}
     *
     * Only the server platform is covered: the browser loader resolves children
     * through Vite, which must see the specifier in the source to bundle it, so a
     * browser suite still names its browser realms itself.
     */
    /**
     * The package a specifier names — `@scope/name/sub` → `@scope/name`, `name/sub`
     * → `name` — so that the suite's manifest can be asked about it.
     */
    const packageNameOf = (specifier: string): string => {
        const parts = specifier.split('/');
        return specifier.startsWith('@') ? parts.slice(0, 2).join('/') : (parts[0] as string);
    };
 
    /**
     * The packages the suite declares in its own manifest.
     *
     * The framework realms are loaded because the suite *depends* on them, and the
     * manifest is where a suite says so — `dependencies`, `devDependencies` and
     * `peerDependencies` alike, because a realm a suite uses only from its own tests
     * is still a realm that suite declares. `core/blong-realm/index.ts` is exactly
     * that case: it names its own realm and leaves blong-server, blong-login,
     * blong-core and blong-access to the framework, and declares all four in
     * `devDependencies`.
     *
     * Asking by resolution instead asks a different question, and one the ambient
     * environment answers: `createRequire(...).resolve()` falls back to `NODE_PATH`,
     * which the tap runner points at the pnpm store, so under `blong-dev test` every
     * suite resolved every framework realm. A suite that declares none of them then
     * loaded blong-server's knex adapter — pointed at a database named after the
     * suite — and died on the connection: `demo/blong-cli` exited 1 with `Unknown
     * database 'blong-cli'` and `test/framework/nscfg` with `ER_BAD_DB_ERROR`
     * (F-206). A manifest cannot be reached that way.
     */
    const declaredDependencies: ReadonlySet<string> = (() => {
        const url = mod.url ?? mergedConfig.url;
        const from = typeof url === 'string' && url.length > 0 ? url : undefined;
        /** The names declared in the three maps an installed dependency appears in. */
        const names = (manifest: unknown): string[] =>
            ['dependencies', 'devDependencies', 'peerDependencies'].flatMap(map =>
                Object.keys((manifest as Record<string, object> | null)?.[map] ?? {}),
            );
        // `mod.pkg` is normally the suite's own package.json — the loader reads the
        // file beside the suite when the suite supplies none — but a suite may supply
        // a *trimmed* manifest (`blong-suite/server.ts` passes `{name, version}`), and
        // a trimmed manifest must not be read as a suite that declares nothing. The
        // file beside the suite is the authority, so it is asked as well; only a suite
        // with no manifest at all ends up declaring nothing.
        const manifests: unknown[] = [mod.pkg];
        if (from) {
            try {
                manifests.push(platformApi.createRequire?.(from)?.('./package.json'));
            } catch {
                // No manifest beside the suite — nothing to declare.
            }
        }
        return new Set(manifests.flatMap(names));
    })();
 
    /**
     * Resolve a framework realm from the suite's own location.
     *
     * A suite that does not depend on the package has no such realm, and that is
     * not an error: the framework ships realms for suites that ship them, and asks
     * the suite's manifest which those are. A specifier the manifest does not
     * declare is not resolved at all — resolution on its own is not that question,
     * because `NODE_PATH` can make it succeed for a suite that depends on nothing
     * (see `declaredDependencies`).
     */
    const resolveFromSuite = (specifier: string): string | undefined => {
        if (!declaredDependencies.has(packageNameOf(specifier))) return undefined;
        // The suite's own bootstrap file is the base — `mod.url`. `mergedConfig.url`
        // is the *config* url, which `ConfigRuntime` fills only when a config names
        // one, so falling back to this module's own location would resolve every
        // framework realm from `blong-gogo`, which depends on none of them: each one
        // would be skipped as unresolvable, looking exactly like a suite that ships
        // none of them. That mistake is invisible in the logs, so the base is taken
        // from the module and the impossible case warns (see below).
        const url = mod.url ?? mergedConfig.url;
        const from = typeof url === 'string' && url.length > 0 ? url : import.meta.url;
        try {
            return platformApi.createRequire?.(from)?.resolve(specifier);
        } catch {
            return undefined;
        }
    };
 
    /**
     * The realms the framework ships and loads for a suite that depends on them.
     *
     * A suite gets these without naming them, which is the point: the four lines
     * of imports and the four matching config blocks every suite used to repeat
     * are the kind of wiring that drifts — a suite that forgot one failed later,
     * somewhere else, with a symptom that did not name the cause.
     *
     * Three properties make it safe:
     *
     * - **The suite's own manifest decides**, so a suite that does not depend on a
     *   realm does not get it — the dependency is looked for in `dependencies`,
     *   `devDependencies` and `peerDependencies`, never in whatever the ambient
     *   resolution happens to find (see `declaredDependencies`). That is why the
     *   list may name realms a particular suite never installs: an undeclared
     *   package is skipped, not reported.
     * - **A realm the suite already lists is skipped too.** The suite's own
     *   children are wrapped to record the realm each one produces, and these are
     *   appended after them, so by the time they are reached the already-loaded
     *   realms are known and nothing is loaded twice — a doubled realm would
     *   register every handler twice.
     * - **Only the platform root does this.** `api` is absent exactly when this is
     *   the load the platform was started with; a nested realm load receives it.
     *   Without this the framework would add its realms *inside every realm it
     *   contains*, which is not a bigger list but a different graph.
     *
     * A suite that wants none of it says so by name, in its own config:
     *
     *     config: {default: {framework: {realms: {access: false}}}}
     *
     * And a realm in this list may name the intents it is *meaningful* under, which is how the
     * deployment realm stays out of the processes its own suite deploys: a suite declaring that
     * package means "a `k8s` run needs this", not "every process carries it". `true` is the way a
     * deployment that does want it in a serving process says so:
     *
     *     config: {default: {framework: {realms: {kustomize: true}}}}
     *
     * Only the server platform is covered: the browser loader resolves children
     * through Vite, which has to see the specifier in the source to bundle it, so
     * a browser suite still names its browser realms itself.
     */
    const frameworkRealms: ReadonlyArray<{
        name: string;
        specifier: string;
        /**
         * The intents this realm is meaningful under; absent means every one of them.
         *
         * A realm in this list is loaded because a suite *depends* on it, and a dependency is
         * not an intent: `blong-suite` declares the deployment realm so that a `k8s` run can
         * write a tree, and the gate below then loaded it into every deployed process as well —
         * a business pod carried the realm's layer folders and ports because the suite wanted
         * it for one command line (T-254). A suite that wants it unconditionally names it as a
         * child, which is what the realm's own entry and the operator's do, so narrowing here
         * changes nothing for the two processes that are *about* the realm.
         */
        intents?: readonly string[];
    }> = [
        {name: 'srv', specifier: '@feasibleone/blong-server/server.ts'},
        {name: 'login', specifier: '@feasibleone/blong-login/server.ts'},
        {name: 'core', specifier: '@feasibleone/blong-core/server.ts'},
        {name: 'access', specifier: '@feasibleone/blong-access/server.ts'},
        {name: 'blong', specifier: '@feasibleone/blong-realm/server.ts'},
        {name: 'kustomize', specifier: '@feasibleone/blong-kustomize/server.ts', intents: ['k8s']},
    ];
    // Without a base there is nothing to resolve from, and every framework realm is
    // silently absent — the symptom is a gateway that refuses every unauthenticated
    // route (the login realm is not mounted) rather than anything that names this.
    if (isPlatformRoot && rootKind === 'server' && !mod.url && !mergedConfig.url) {
        console.warn(
            'blong: the suite exposes no url, so no framework realm can be resolved from it ' +
                '(server, login, core, access, blong). Name them as children, or give the suite a url.',
        );
    }
    /**
     * The realms this load tree produced, by the file they came from.
     *
     * Filled where a realm module is created (`loadRealm`), not by the wrapper
     * below: a suite's child answers with the realm *factory*, and only the load
     * that calls it can read the url off the module.
     */
    const loadedRealmUrls = new Set<string>();
    if (isPlatformRoot) api!.loadedRealmUrls = loadedRealmUrls;
    const trackChild = (child: unknown): unknown =>
        typeof child === 'function'
            ? Object.defineProperty(
                  async (): Promise<unknown> => {
                      const value = await (child as () => Promise<unknown>)();
                      const url = (value as {url?: unknown} | undefined)?.url;
                      if (typeof url === 'string') {
                          // Framework realms load first now, so a suite that still names one
                          // as a child reaches this wrapper after the realm is already in the
                          // tree. Returning nothing makes the loop skip it rather than register
                          // every handler twice.
                          const normalised = normaliseUrl(url);
                          if (loadedRealmUrls.has(normalised)) return undefined;
                          loadedRealmUrls.add(normalised);
                      }
                      return value;
                  },
                  'name',
                  {value: (child as {name?: string}).name ?? 'child', configurable: true},
              )
            : child;
    // `rootKind`, not `platformApi.platform`: the latter names the transport
    // implementation, and a *browser* suite loaded in a Node process (the tap runner)
    // gets the server one — which made this load look like the server platform and
    // pull in the framework realms' `server.ts` entries. blong-login's `./orchestrator`
    // came with them and its `token.ts` needs a gateway that does not exist there, so
    // the whole tap process died before a test (T-114). `rootKind` is what the rest of
    // this loader already asks that question with.
    const frameworkChildren =
        isPlatformRoot && rootKind === 'server'
            ? frameworkRealms.map(({name, specifier, intents}) => {
                  // The loop below looks a child's config up by its name and skips
                  // the child when there is none, so a realm loaded this way needs a
                  // block here. A suite that declares its own keeps it: this fills a
                  // gap rather than overriding one.
                  mergedConfig[name] ??= {};
                  return Object.defineProperty(
                      async (): Promise<unknown> => {
                          const realms = (
                              mergedConfig as {framework?: {realms?: Record<string, unknown>}}
                          ).framework?.realms;
                          if (realms?.[name] === false) return undefined;
                          // The realm's own intents, unless the suite asks for it by name: `true`
                          // is how a deployment that *does* want the deployment realm in a process
                          // of its own says so, and it has to be able to.
                          if (
                              intents &&
                              realms?.[name] !== true &&
                              !intents.some(intent => configNames.includes(intent))
                          ) {
                              return undefined;
                          }
                          const resolved = resolveFromSuite(specifier);
                          if (resolved === undefined) return undefined;
                          if (loadedRealmUrls.has(normaliseUrl(resolved))) return undefined;
                          loadedRealmUrls.add(normaliseUrl(resolved));
                          const loaded = await import(/* @vite-ignore */ resolved);
                          return loaded.default ?? loaded;
                      },
                      'name',
                      {value: name},
                  );
              })
            : [];
 
    let realm: IRealm;
    // The keys the block had before the children loaded, so the allow-list can tell
    // a key the loader merged in (a handler group's own `config.ts` becomes a key of
    // its realm's block, under the group's folder name) from one the source or a
    // parent declared (@@D-554).
    const keysOnEntry = new Set(Object.keys(mergedConfig));
    // The framework realms are the foundation: they load before the suite's own
    // children. A suite that names one of them as a child still gets it once —
    // `loadedRealmUrls` skips the duplicate — but the order is the loader's. This
    // matters for a shared namespace such as `test`: the last port to claim it
    // serves the method, and a suite's test runner must load after the framework
    // realms that also contribute test groups.
    for (let item of items
        .concat(frameworkChildren)
        .concat(children.map(trackChild) as [])
        .concat(extraChildren)) {
        // Deliberately `platformApi.platform` here, not `rootKind`: this gate decides how a
        // folder-string child is *resolved*, and browser suites in the tap runner rely on the
        // server-side resolution (their folder layers must still load, or the browser test
        // group's handlers never register and its calls hang). Do not "fix" this to rootKind.
        if (typeof item === 'string' && platformApi.platform !== 'server') continue;
        const itemName = typeof item === 'string' ? platformApi.basename(item) : item.name;
        const config: Record<string, unknown> = mergedConfig[itemName] as Record<string, unknown>;
        // This child's block in a candidate snapshot is the parent's block indexed
        // by the child's name — the getter a reload validator re-runs it with
        // (@@D-548).
        const childBlockOf = (snapshot: object): unknown =>
            (blockOf(snapshot) as Record<string, unknown> | undefined)?.[itemName];
        logger?.debug?.(
            {$meta: {mtid: 'event', method: config ? 'child.load' : 'child.skip'}},
            typeof item === 'string' ? item : item.name + '()',
        );
        if (config) {
            if (typeof item === 'string') {
                switch (defKind) {
                    case 'server':
                    case 'browser': {
                        const folderPath = item;
                        const fileName = folderPath.startsWith('.')
                            ? platformApi.join(base, folderPath, `${defKind}.ts`)
                            : folderPath;
                        // Skip import when file doesn't exist — prevents ts-node
                        // ESM resolve-hook errors that can bypass try/catch.
                        if (!platformApi.existsSync(fileName)) {
                            item = async () => [];
                            break;
                        }
                        item = async () => {
                            try {
                                const mod = await import(/* @vite-ignore */ fileName);
                                return mod.default ?? mod;
                            } catch (error) {
                                if (
                                    !['ERR_MODULE_NOT_FOUND', 'MODULE_NOT_FOUND'].includes(
                                        (error as {code?: string}).code ?? '',
                                    )
                                )
                                    throw error;

                                if (mergedConfig?.kopi?.realm && !(itemName in WELL_KNOWN_LAYERS)) {
                                    let destUrl = import.meta.resolve(fileName);
                                    destUrl = destUrl.startsWith('file://')
                                        ? platformApi.dirname(destUrl.slice(7))
                                        : destUrl;
                                    if (
                                        !platformApi.existsSync(
                                            platformApi.join(destUrl, 'package.json'),
                                        )
                                    ) {
                                        const {createRealm} = await import(
                                            /* @vite-ignore */ './kopi' + extension
                                        );
                                        await createRealm(destUrl, logger);
                                        const mod = await import(/* @vite-ignore */ fileName);
                                        return mod.default ?? mod;
                                    }
                                }
                                return [];
                            }
                        };
                        break;
                    }
                    default:
                        const loaded: unknown[] = [];
                        // `.dev`-suffixed handler groups (e.g. `gateway/vision.dev/`)
                        // load only under the `dev` intent — a general dev-only gating
                        // convention for layers such as gateway/orchestrator.
                        const devActive =
                            configNames.includes('dev') || platformApi.configs.includes('dev');
                        for (const dirEntry of await platformApi.scan(base, item)) {
                            if (
                                dirEntry.isDirectory() &&
                                dirEntry.name.endsWith('.dev') &&
                                !devActive
                            )
                                continue;
                            loaded.push(
                                await api!.watch?.load(
                                    mergedConfig,
                                    dirEntry.isDirectory(),
                                    dirEntry.isFile(),
                                    base,
                                    item,
                                    dirEntry.name.toString(),
                                ),
                            );
                        }
                        // Auto-provision a testDispatch orchestrator when the test/ folder
                        // has no testDispatch.ts and no layer.server.ts — but only where tests run,
                        // because the registration below hands the port straight to the realm and so
                        // bypasses the activation it declares: a serving process carried
                        // `access.testDispatch` and `blong.testDispatch` among the ports it started,
                        // which is what `default: {}` did here and the intent check now prevents.
                        const testsActive =
                            configNames.includes('integration') ||
                            configNames.includes('playwright') ||
                            platformApi.configs.includes('integration') ||
                            platformApi.configs.includes('playwright');
                        if (
                            itemName === 'test' &&
                            platformApi.platform === 'server' &&
                            base &&
                            testsActive
                        ) {
                            const testDir = platformApi.join(base, item as string);
                            const hasTestDispatch = platformApi.existsSync(
                                platformApi.join(testDir, 'testDispatch.ts'),
                            );
                            const hasLayerServer = platformApi.existsSync(
                                platformApi.join(testDir, 'layer.server.ts'),
                            );
                            if (!hasTestDispatch && !hasLayerServer) {
                                const realmName = mergedConfig.name;
                                const syntheticOrchestrator = orchestrator(() => ({
                                    extends: 'orchestrator.dispatch' as const,
                                    // Only where tests run. The port exists to dispatch a realm's test
                                    // groups, and a serving process that carries the realm should not
                                    // register it at all — the deployed suite listed
                                    // `access.testDispatch` and `blong.testDispatch` among its ports,
                                    // which is what `default: {}` did here.
                                    activation: {
                                        integration: {
                                            namespace: ['test'],
                                            imports: [/\.test$/],
                                        },
                                        playwright: {
                                            namespace: ['test'],
                                            imports: [/\.test$/],
                                        },
                                    },
                                }));
                                Object.defineProperty(syntheticOrchestrator, 'name', {
                                    value: 'testDispatch',
                                    configurable: true,
                                });
                                loaded.push(
                                    Object.defineProperty(
                                        (api: unknown) => {
                                            (
                                                api as Record<
                                                    string,
                                                    (...args: unknown[]) => unknown
                                                >
                                            )['testDispatch'](
                                                syntheticOrchestrator,
                                                realmName + '.testDispatch',
                                                'auto-provisioned',
                                            );
                                            return api;
                                        },
                                        'name',
                                        {value: 'testDispatch'},
                                    ),
                                );
                            }
                        }
                        item = async () => loaded.filter(Boolean);
                }
            } else if (platformApi.platform === 'browser' && 'path' in item) {
                const loaded: unknown[] = [];
                loaded.push(
                    await api!.watch?.load(mergedConfig, item.isDirectory, item.isFile, item.path),
                );
                item = async () => loaded.filter(Boolean);
            }
            // The import and the start are separate steps with separate costs: an
            // import is the module graph, which is slow on a cold filesystem, while
            // a start is the component's own init. A delayed start that names only
            // "load log" would not say which of the two to look at, so the two are
            // reported under labels that do.
            const loadedModules = await withProgress(
                stepLog(),
                `import ${itemName}`,
                (item as () => Promise<unknown[]>)(),
                {slowMs},
            );
            const modules = Array.isArray(loadedModules) ? loadedModules : [loadedModules];
            let loadedCount = 0;
            await withProgress(
                stepLog(),
                `start ${itemName}`,
                (async () => {
                    for (const module of modules) {
                        const item = await module;
                        const fn = (item as {default?: unknown})?.default ?? item;
                        // A child may contribute nothing: an optional realm that is not
                        // configured, an adapter whose dependency is absent, a framework
                        // realm a suite does not depend on. Reading a kind off that used
                        // to throw `Symbol(blong:kind)` of undefined — a TypeError that
                        // names the symbol rather than the child that resolved to nothing,
                        // and that killed the whole process at boot (a demo suite that
                        // does not depend on blong-realm never started).
                        if (fn === undefined || fn === null) continue;
                        if (
                            typeof fn === 'function' &&
                            (fn.prototype instanceof Internal ||
                                (fn as unknown as Record<symbol, unknown>)[System])
                        ) {
                            api![itemName] = new (fn as IConstructor)(config, api);
                            await api![itemName].init?.();
                            if (itemName === 'log' && platformApi.platform === 'server') {
                                // A destination, named by configuration rather than by a dependency: the
                                // framework loads the module or builds the sink the config names and
                                // installs what it answers, so a process can send its records to a
                                // viewer without `core/blong-gogo` naming one (`@@D-930`). Installed
                                // before the realms load, which is the first moment the log exists and
                                // the last before anything worth watching happens.
                                //
                                // Imported through the same non-literal specifier every server half
                                // below uses: resolving a module needs `node:module`, and this file is
                                // bundled for a page as well as for a process, where one `node:` import
                                // costs the page its whole module chain (`@@T-732`).
                                const {installDestination} = (await import(
                                    /* @vite-ignore */ './destination' + extension
                                )) as typeof import('./destination.ts');
                                const destination = await installDestination(
                                    (config as {destination?: unknown} | undefined)?.destination,
                                    (message, reason) => {
                                        const warn = api!.log?.logger('warn', {
                                            name,
                                            context: 'log',
                                        });
                                        warn?.warn?.({reason}, message);
                                    },
                                );
                                // Closed with the process, so the last batch is sent rather than lost
                                // in a socket's queue. A process killed by a signal never reaches
                                // `beforeExit`, which is why the writer also flushes on its own timer.
                                if (destination !== undefined)
                                    process.once?.('beforeExit', () => destination.close());
                                // Whether this process was *told* where its records go, published where
                                // a realm can read it. A receiver that rides the process — the viewer's
                                // UDP listener — has to know the difference between "nobody named a
                                // destination" and "one was installed", and neither `getWriter()` nor
                                // the merged config tells it: by the time a realm starts, the log has a
                                // writer either way, and the config it sees is its own slice. Set before
                                // the realms load, like `clusterUrl` below (`@@D-953`).
                                if (destination !== undefined) manifest.logDestination = true;
                                logger = api!.log?.logger(
                                    mergedConfig[rootKind === 'browser' ? 'browser' : 'server']
                                        ?.load?.logLevel,
                                    {
                                        name,
                                        context: `${defKind}`,
                                    },
                                );
                                // Publish the address of the service this process started for
                                // its own records, if it started one. The realm that reads
                                // that service answers on a *port*, and a port needs an
                                // address: the service is bound on one the operating system
                                // chose (`log.cluster.port: 0`), so without this the reader
                                // would fall back to the conventional port and reach
                                // whichever *other* process on the machine holds it. Set
                                // before the realms load — the log is the first component —
                                // so a realm's port reads it as the string it is rather than
                                // as the manifest proxy's pending placeholder.
                                const clusterUrl = (api!.log as {clusterUrl?: string} | undefined)
                                    ?.clusterUrl;
                                if (clusterUrl !== undefined) manifest.clusterUrl = clusterUrl;
                                // The configuration's provenance, in a single line: which rc
                                // files were read, which environment variables supplied values
                                // and which command-line keys were applied. Written once, from
                                // the root load, through the log the config just configured —
                                // `sources` is populated only when a ConfigRuntime exists, which
                                // is the root only. Names, never values, so a secret is not
                                // copied here.
                                const sources = configRuntime?.sources;
                                if (sources) {
                                    const level =
                                        ((mergedConfig as {log?: {level?: unknown}}).log
                                            ?.level as Parameters<ILog['logger']>[0]) ?? 'info';
                                    api!.log?.logger(level, {name, context: 'config'}).info?.({
                                        $meta: {mtid: 'event', method: 'config.load'},
                                        ...sources,
                                    });
                                }
                                // A level is the one config value no port owns, so the reload
                                // path cannot reach it through `applyConfigReload`. Applied
                                // here instead, without restarting anything: `log.level`
                                // re-points the process logger, a `<component>.logLevel`
                                // re-points that component's logger (a port's own level is a
                                // restart, which `applyConfigReload` already does).
                                configRuntime?.subscribe((diff, next) => {
                                    const config = next as Record<string, unknown>;
                                    const levelAt = (...path: string[]): unknown =>
                                        path.reduce<unknown>(
                                            (node, key) =>
                                                node && typeof node === 'object'
                                                    ? (node as Record<string, unknown>)[key]
                                                    : undefined,
                                            config,
                                        );
                                    for (const key of diff.keys()) {
                                        if (key === 'log.level' || key === 'log.logLevel') {
                                            const level = levelAt('log', 'level');
                                            if (level !== undefined)
                                                api!.log?.setLevel?.(
                                                    level as Parameters<ILog['logger']>[0],
                                                );
                                        } else if (key === `${rootKind}.load.logLevel`) {
                                            const level = levelAt(rootKind, 'load', 'logLevel');
                                            if (level !== undefined)
                                                logger = api!.log?.logger(
                                                    level as Parameters<ILog['logger']>[0],
                                                    {name, context: `${defKind}`},
                                                );
                                        } else if (key.endsWith('.logLevel')) {
                                            const componentName = key.slice(0, -'.logLevel'.length);
                                            // A port's own level is a restart, which
                                            // `applyConfigReload` already performs; only a
                                            // top-level framework component is re-pointed here.
                                            if (componentName.includes('.')) continue;
                                            const component = api![componentName] as
                                                | {setLogLevel?: (level: unknown) => void}
                                                | undefined;
                                            const level = levelAt(componentName, 'logLevel');
                                            if (component?.setLogLevel && level !== undefined)
                                                component.setLogLevel(level);
                                        }
                                    }
                                });
                            }
                        } else if (
                            ['solution', 'server', 'browser'].includes(
                                kind(fn as Record<symbol, Kinds>),
                            )
                        ) {
                            realm ||= new RealmImpl(mergedConfig, api!, rootKind);
                            realm.addModule(
                                itemName,
                                await loadRealm(
                                    platformApi,
                                    fn as Parameters<typeof loadRealm>[1],
                                    itemName,
                                    {
                                        [platformApi.platform]: mergedConfig[platformApi.platform],
                                        ...config,
                                    },
                                    configNames,
                                    manifest,
                                    api,
                                    rootKind,
                                    childBlockOf,
                                ),
                            );
                        } else if (typeof fn === 'function') {
                            realm ||= new RealmImpl(mergedConfig, api!, rootKind);
                            realm.addLayer(
                                itemName,
                                fn(
                                    layerProxy(
                                        api?.error,
                                        api?.registry?.objectSchema,
                                        api?.apiSchema,
                                        api?.port,
                                        mergedConfig as unknown as Parameters<typeof layerProxy>[4],
                                        api?.configRuntime,
                                        signalsAttacher,
                                    ),
                                ).result,
                            );
                        }
                        loadedCount += 1;
                    }
                })(),
                {
                    getProgress: () => ({done: loadedCount, total: modules.length}),
                },
            );
        }
    }
    /**
     * The prototypes this realm ships, registered as lazy port entries.
     *
     * A `thunk` folder is scanned, never imported: each `<name>.ts` goes into the registry as
     * `<realm>.<name>` with a proxy in place of the factory, and the proxy is what pulls the module
     * — and the `<name>/` group beside it, which is where a base's methods live — the first time
     * something names it. That is either an instance's `extends: '<realm>.<name>'` or a process
     * that starts the base itself; both await, so a promise-returning entry needs no change at
     * either call site (`@@D-720` `@@T-593`).
     *
     * Nothing is registered under a name another child already claimed, and a folder that does not
     * exist is skipped: a realm may declare the folder its published build carries.
     */
    for (const folder of Array.isArray((mod as {thunk?: unknown}).thunk)
        ? ((mod as {thunk?: string[]}).thunk ?? [])
        : []) {
        const dir = platformApi.join(base, folder);
        if (!platformApi.existsSync(dir)) continue;
        const entries = await platformApi.scan(dir);
        const groups = new Set(
            entries.filter(entry => entry.isDirectory()).map(entry => entry.name),
        );
        const groupNameOf = (name: string): string => name;
        const layerOf = (apply: (api: {result: unknown}) => {result: unknown}): IRealm =>
            (
                apply(
                    layerProxy(
                        api?.error,
                        api?.registry?.objectSchema,
                        api?.apiSchema,
                        api?.port,
                        mergedConfig as unknown as Parameters<typeof layerProxy>[4],
                        api?.configRuntime,
                        signalsAttacher,
                    ),
                ) as {result: IRealm}
            ).result;
        for (const entry of entries) {
            if (!entry.isFile() || !/\.ts$/.test(entry.name) || /\.test\.ts$/.test(entry.name))
                continue;
            const name = entry.name.replace(/\.ts$/, '');
            const id = `${String(mergedConfig.name)}.${name}`;
            if (api!.registry?.ports?.has(id)) continue;
            let factory: unknown;
            api!.registry?.thunks?.set(id, async () => {
                if (factory) return factory;
                realm ||= new RealmImpl(mergedConfig, api!, rootKind);
                // The group first: it is where a base's methods live, and the instance that named
                // this base is attached to them the moment it is created.
                if (groups.has(name)) {
                    const group = await api!.watch!.load(
                        mergedConfig,
                        true,
                        false,
                        base,
                        folder,
                        name,
                    );
                    realm.addLayer(groupNameOf(name), layerOf(group as never));
                }
                // The module itself is imported and its factory kept — deliberately not registered
                // as a layer, because a layer becomes a port and a port is started in every process.
                const module_ = (await import(
                    /* @vite-ignore */ platformApi.join(dir, entry.name)
                )) as {default?: unknown};
                if (typeof module_.default !== 'function') {
                    throw new Error(
                        `${id} is not an adapter: ${entry.name} has no factory to extend`,
                    );
                }
                factory = module_.default;
                return factory;
            });
        }
    }
    realm ||= new RealmImpl(mergedConfig, api!, rootKind);
    /**
     * Validate this module's own config block, now that its children and ports
     * are known.
     *
     * Unknown keys are always judged; the type checks only apply where the module
     * declared a `validation` schema. The allow-list is what the module's
     * structure legitimises: one key per child module (a layer folder, a named
     * realm), one per port it registered (`kustomize.deploy`), the keys its own
     * source config blocks name, the keys its parent declared for it, and the keys
     * the loader itself merged in while the children loaded. It is read here rather
     * than before the loop because a port's name — the key an override addresses it
     * by — and a handler group's config key are only known once the children have
     * loaded (@@F-370 @@D-547 @@D-554).
     *
     * At the platform root the unknown-key check is narrowed to the keys the
     * command line introduced: a shared rc file carries keys for every suite in
     * the repository, and those are the developer's own settings, not a mistake.
     * A nested module is judged on all of its keys, since an override reaches it
     * by name — and a `cli` run judges none of them, because there the command
     * line is the command's interface rather than configuration (@@D-555).
     */
    {
        const allow = new Set<string>();
        const addKey = (key: unknown): void => {
            if (typeof key === 'string' && key) allow.add(key);
        };
        const addChild = (child: unknown): void => {
            const childName =
                typeof child === 'string'
                    ? platformApi.basename(child)
                    : (child as {name?: string} | undefined)?.name;
            addKey(childName);
        };
        for (const child of children) addChild(child);
        for (const child of extraChildren) addChild(child);
        for (const child of frameworkChildren) addChild(child);
        for (const block of declaredBlocks)
            if (block && typeof block === 'object') Object.keys(block).forEach(addKey);
        // The keys the parent declared for this module. The block this module was
        // handed *is* the parent's block for it — `merge` puts `parentConfig`
        // last — so each of its top-level keys was written as `<name>.<key>`: by
        // the parent's own config, or by an rc file or the command line
        // addressing the parent. A suite root configuring a child realm this way
        // (`commander: {showParentRow: true}`) is how a realm is told what its
        // pages render, so the key is legitimate here even though the module's
        // own source never names it (@@D-554). At the platform root this is a
        // string — the entry, not a block — and the module's own declared config
        // is the whole story.
        if (parentConfig && typeof parentConfig === 'object')
            Object.keys(parentConfig).forEach(addKey);
        // Keys the loader merged into the block while the children loaded. A handler
        // group that carries its own `config.ts` gets a key of its realm's block, under
        // the group's folder name (`orchestrator/cfg/config.ts` → `cfg`), and nothing in
        // the realm's source names it — the group is structure, and the key is how the
        // group is configured (@@D-554).
        for (const key of Object.keys(mergedConfig)) if (!keysOnEntry.has(key)) addKey(key);
        // A port registered under this module (`kustomize.deploy`) is addressed by
        // its name, so its name is a legitimate key here.
        const ports = (api?.registry as {ports?: {keys: () => Iterable<string>}} | undefined)
            ?.ports;
        for (const portId of ports?.keys() ?? []) {
            if (typeof portId === 'string' && portId.startsWith(name + '.'))
                addKey(portId.slice(name.length + 1));
        }
        // Which keys the unknown-key check may name. At the platform root that is the
        // command line and only the command line — a shared rc file carries keys for
        // every suite in the repository, and those are the developer's own settings,
        // not a mistake. Under `cli` the set is empty: there the process's command line
        // is the command's interface, `runCli` parses those flags itself and passes them
        // as handler params, so a flag that also lands in the config (`--value`,
        // `--output`) is not an override, and judging it named every command flag an
        // unknown key (@@D-555). A nested module is judged on all of its keys, since an
        // override reaches it by name.
        const rootKeys =
            typeof parentConfig === 'string'
                ? new Set<string>(
                      configNames.includes('cli') ? [] : (configRuntime?.sources?.argv ?? []),
                  )
                : undefined;
        const validateBlock = (block: unknown): void => {
            const issues = validateConfigBlock(
                block,
                mod.validation,
                allow,
                rootKeys ? {onlyUnknownKeys: rootKeys} : {},
            );
            if (issues.length) throw new Error(formatConfigIssues(name, issues));
        };
        // The same check guards a reload: its validator re-reads this module's
        // block from the candidate snapshot with the getter threaded down from the
        // root, so an rc edit that introduces an unknown key is refused rather than
        // applied (@@D-548).
        api!.configValidators?.push((snapshot: object) => validateBlock(blockOf(snapshot)));
        // Startup: fail now, on the block just merged.
        validateBlock(mergedConfig);
    }
    // The reload hook, registered at the platform root — the one load where a
    // `ConfigRuntime` exists. Every module's validator is collected by now: a
    // module validates only after its children have loaded.
    if (isPlatformRoot && configRuntime) {
        configRuntime.setValidator?.(snapshot => {
            for (const validate of api!.configValidators ?? []) validate(snapshot);
        });
        // Attach the runtime to the watcher here rather than at the top of the
        // load: `watch` is one of the components built by the loop above, so it
        // does not exist earlier — a change to a watched rc file used to be
        // answered with "ConfigRuntime not attached; config change ignored"
        // (@@D-548).
        api?.watch?.setConfigRuntime?.(configRuntime);
    }
    if (!api?.registry) throw new Error('Registry not found in loaded modules');
    // What each realm declared about itself, handed to the registry by reference (D-433): a realm
    // loads after the root's config has merged, so nothing that is copied while the config is built
    // can hold the whole tree. By this point every realm has been recorded, and the object the
    // registry now holds keeps growing with any realm a later load adds.
    api.registry.setRealmConfig?.(
        (api as {realmConfig?: Record<string, unknown>}).realmConfig ?? {},
    );
    // The package the suite *is*, for the same reason and by the same route: a planner that writes a
    // deployment names its version, and that version is a fact about the manifest beside the entry
    // rather than a value the entry repeats in its own `kustomize.deploy` config.
    api.registry.setPackage?.((mod as {pkg?: {name?: string; version?: string}}).pkg ?? {});
    // Resolved from the active intents (see the `exit` keys in the synthetic
    // config above). The runner uses it to decide whether this process outlives
    // its work; absent means "keep running". Set here rather than in the
    // constructor so the value is read after every config source has merged.
    api.registry.exit = Boolean(mergedConfig.exit);
    return api.registry;
}