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 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 | 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 469x 469x 469x 4x 4x 4x 4x 469x 469x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 1046x 1046x 1046x 1046x 1046x 1046x 1x 1x 1x 1x 1x 1x 1046x 1046x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 4227x 4227x 1726x 4227x 50x 50x 50x 50x 50x 50x 50x 1726x 4227x 3616x 3616x 4227x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 482x 482x 482x 482x 482x 149x 149x 148x 148x 148x 148x 149x 149x 149x 149x 148x 140x 140x 148x 148x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 149x 482x 482x 482x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 4769x 4769x 4389x 4389x 380x 380x 380x 4769x 1677x 1677x 231x 231x 231x 231x 231x 1446x 1677x 149x 149x 1297x 1297x 380x 380x 380x 4769x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 4252x 4252x 41x 41x 4211x 4211x 4252x 4211x 4211x 4252x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 469x 469x 469x 469x 469x 469x 50x 50x 50x 50x 50x 50x 469x 469x 322x 322x 322x 322x 322x 322x 322x 482x 482x 482x 482x 482x 482x 482x 482x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 509x 509x 17x 17x 17x 17x 509x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 24x 24x 1x 1x 1x 1x 1x 1x 1x 1x 1x 24x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 470x 470x 470x 470x 470x 470x 470x 470x 470x 470x 24x 24x 24x 24x 446x 446x 457x 446x 446x 470x 322x 322x 322x 322x 322x 322x 322x 322x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 322x 322x 322x 322x 322x 322x 322x 196x 196x 322x 322x 322x 322x 322x 322x 322x 196x 196x 196x 322x 322x 322x 322x 322x 322x 322x 191x 191x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 200x 200x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 483x 483x 127x 127x 127x 1x 1x 1x 1x 127x 127x 1x 1x 126x 126x 126x 482x 483x 322x 322x 322x 322x 322x 322x 322x 322x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 225x 225x 225x 16x 16x 16x 16x 45x 45x 16x 225x 225x 225x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 130x 130x 473x 473x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 2x 2x 471x 471x 471x 471x 471x 471x 471x 471x 471x 471x 471x 471x 471x 471x 471x 471x 471x 482x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 471x 471x 471x 471x 471x 471x 471x 471x 471x 471x 471x 471x 482x 1x 1x 470x 470x 470x 470x 470x 470x 470x 470x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 22x 22x 22x 22x 469x 486x 486x 486x 486x 22x 22x 480x 2x 2x 482x 25x 25x 469x 469x 469x 469x 469x 469x 469x 469x 469x 469x 469x 469x 470x 446x 446x 446x 446x 446x 446x 3x 3x 3x 3x 3x 3x 446x 443x 443x 443x 443x 443x 443x 443x 443x 443x 443x 443x 443x 443x 443x 107x 89x 89x 107x 27x 27x 107x 443x 443x 446x 469x 469x 469x 469x 469x 469x 469x 469x 469x 469x 469x 469x 469x 469x 469x 469x 486x 3x 3x 3x 3x 4x 4x 3x 3x 3x 3x 3x 3x 3x 3x 469x 469x 469x 469x 469x 469x 469x 469x 469x 469x 469x 469x 264x 264x 469x 469x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 486x 121x 121x 121x 121x 121x 121x 121x 121x 121x 121x 121x 121x 121x 121x 121x 121x 348x 348x 348x 348x 348x 348x 348x 348x 348x 348x 348x 348x 348x 348x 348x 486x 322x 322x 322x 322x 322x 322x 322x 322x 322x 230x 230x 230x 20x 20x 20x 20x 20x 20x 20x 47x 47x 20x 20x 20x 20x 20x 17x 17x 20x 2x 2x 20x 230x 230x 230x 211x 211x 211x 211x 211x 211x 211x 211x 211x 211x 211x 211x 211x 211x 211x 24845x 24845x 1681x 1681x 24845x 24845x 46x 2x 2x 2x 46x 46x 24799x 24845x 2x 2x 2x 2x 24797x 24845x 4x 4x 4x 4x 2x 2x 4x 4x 4x 24845x 24793x 2x 2x 2x 2x 24793x 625x 625x 625x 625x 625x 625x 24791x 2x 2x 24166x 627x 627x 625x 625x 625x 523x 523x 523x 523x 523x 523x 625x 625x 211x 211x 211x 211x 211x 211x 211x 625x 625x 625x 625x 625x 625x 625x 625x 627x 2x 2x 24164x 17736x 17736x 24793x 24845x 211x 230x 322x 322x 322x 322x 322x 322x 322x 322x 483x 483x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 485x 485x 485x 485x 485x 485x 322x 322x 322x 322x 322x 322x 322x 322x 488x 488x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 490x 490x 490x 490x 269x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 269x 490x 490x 490x 322x 322x 322x 322x 322x 322x 322x 322x 482x 482x 322x 322x 322x 322x 322x 322x 322x 322x 322x 510x 510x 510x 510x 143x 143x 367x 367x 367x 367x 367x 367x 367x 510x 2x 2x 2x 367x 367x 367x 375x 1x 375x 366x 2x 2x 366x 364x 364x 366x 366x 367x 375x 3x 3x 3x 3x 3x 3x 3x 3x 364x 364x 510x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 509x 509x 509x 509x 509x 509x 509x 509x 509x 509x 509x 509x 509x 509x 509x 509x 509x 509x 509x 509x 509x 509x 509x 509x 509x 509x 496x 496x 496x 509x 509x 509x 509x 509x 509x 509x 509x 509x 509x 494x 494x 494x 494x 494x 494x 494x 494x 494x 494x 494x 504x 504x 504x 504x 504x 504x 504x 504x 504x 504x 504x 504x 504x 504x 504x 504x 504x 504x 504x 504x 504x 504x 504x 504x 509x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 486x 486x 3x 3x 3x 3x 3x 3x 3x 3x 486x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 504x 504x 504x 380x 97x 380x 380x 130x 130x 130x 130x 130x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 1x 1x 1x 130x 130x 130x 130x 130x 91x 504x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 509x 509x 5832x 2x 2x 85x 5832x 5832x 5832x 5832x 5832x 5832x 509x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 507x 507x 507x 20x 20x 20x 20x 20x 20x 8x 8x 20x 2x 2x 18x 18x 507x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 505x 505x 5778x 1720x 5778x 5778x 1720x 1720x 1720x 40x 1720x 1720x 505x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 15x 15x 15x 15x 15x 322x 322x 322x 322x 322x 322x 322x 322x 322x 500x 500x 500x 500x 500x 500x 4205x 1735x 1735x 1563x 296x 296x 296x 294x 294x 294x 296x 1563x 1735x 293x 293x 1735x 1735x 1735x 1735x 500x 500x 500x 500x 500x 322x 322x 322x 322x 322x 322x 322x 322x 515x 509x 509x 509x 509x 509x 509x 509x 509x 509x 509x 515x 85421x 24026x 16x 16x 21573x 15x 15x 15x 15x 15x 15x 15x 21573x 6x 6x 6x 15x 15x 85421x 85421x 85421x 515x 322x 322x 322x 322x 322x 322x 322x 322x 508x 503x 503x 503x 503x 503x 503x 503x 503x 503x 503x 503x 503x 508x 96x 96x 96x 96x 96x 96x 90x 90x 90x 6x 6x 6x 6x 6x 6x 6x 6x 7x 460x 460x 460x 460x 6x 6x 6x 6x 6x 460x 454x 454x 454x 460x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 96x 503x 508x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 611x 611x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 511x 1035x 1035x 1096x 55x 55x 1095x 89x 89x 1095x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 1096x 511x 511x 511x 1109x 50x 50x 50x 1109x 50x 50x 1059x 24x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 24x 1009x 985x 985x 985x 15x 985x 985x 985x 985x 985x 1109x 508x 508x 511x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 521x 521x 521x 521x 678x 678x 673x 673x 673x 673x 673x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 521x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 508x 165x 165x 508x 343x 508x 508x 508x 508x 508x 508x 508x 508x 508x 508x 508x 508x 343x 343x 343x 343x 1459x 3348x 1280x 1280x 1280x 1280x 1280x 1280x 1280x 1280x 1280x 1280x 1280x 1280x 1280x 1280x 1280x 1280x 1280x 117x 1280x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1280x 3348x 3348x 1116x 1116x 3348x 343x 343x 343x 508x 322x 322x 322x 322x 322x 322x 322x 322x 1046x 1046x 1046x 1046x 1046x 4486x 4486x 4486x 4486x 4486x 4486x 4486x 30x 30x 111x 111x 111x 30x 30x 30x 4456x 4486x 17x 17x 99x 99x 99x 17x 17x 17x 4439x 4486x 3x 3x 12x 12x 1x 1x 1x 5x 5x 5x 5x 1x 1x 1x 1x 12x 12x 3x 3x 3x 4436x 4436x 4436x 4436x 4486x 1518x 1518x 1518x 1518x 1518x 740x 740x 1518x 360x 1517x 1518x 1518x 1518x 725x 725x 1518x 1518x 6x 6x 6x 6x 1518x 1518x 1152x 1152x 1518x 1518x 1518x 1518x 2918x 4483x 32x 3x 3x 3x 29x 29x 2915x 4486x 329x 329x 2915x 2915x 2915x 1046x 1046x 1046x 1046x 1046x 1046x 1046x 1046x 1046x 1046x 1046x 1046x 1046x 322x 322x 322x 322x 322x 322x 322x 322x 515x 515x 322x 322x 322x 322x 322x 322x 322x 322x 322x 500x 500x 500x 553x 553x 553x 553x 118x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 118x 58x 58x 58x 58x 58x 60x 2x 2x 2x 2x 2x 2x 118x 553x 553x 500x 500x 53x 53x 53x 53x 53x 553x 111x 111x 56x 56x 70x 2x 2x 2x 55x 53x 53x 53x 53x 53x 53x 53x 53x 111x 53x 261x 53x 53x 53x 53x 53x 53x 53x 53x 261x 2x 2x 243x 51x 51x 53x 53x 53x 53x 53x 244x 15x 15x 53x 53x 261x 2x 2x 2x 53x 53x 500x 500x 500x 322x 322x 322x 322x 322x 322x 322x 322x 500x 500x 511x 511x 11x 11x 11x 11x 11x 11x 11x 11x 28x 10x 10x 10x 11x 11x 11x 11x 500x 500x 322x 322x 322x 322x 322x 322x 322x 322x 500x 500x 507x 507x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 500x 500x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 505x 505x 505x 505x 517x 517x 12x 12x 517x 517x 517x 517x 517x 517x 517x 517x 517x 517x 517x 517x 517x 517x 517x 517x 517x 517x 7x 7x 7x 7x 7x 7x 12x 12x 12x 12x 12x 12x 17x 7x 7x 7x 7x 12x 12x 17x 517x 517x 517x 517x 517x 505x 505x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 505x 505x 518x 518x 13x 13x 518x 518x 518x 518x 518x 518x 518x 518x 518x 8x 8x 8x 13x 13x 55x 1x 1x 1x 13x 13x 13x 518x 518x 518x 518x 518x 518x 518x 505x 505x 322x 322x 322x 322x 322x 322x 322x 322x 504x 504x 504x 504x 504x 656x 656x 656x 504x 504x 152x 152x 152x 152x 152x 152x 152x 152x 152x 152x 656x 845x 845x 259x 21x 21x 845x 21x 586x 152x 152x 136x 136x 152x 152x 152x 693x 693x 152x 425x 152x 152x 152x 656x 136x 136x 152x 152x 152x 152x 152x 152x 152x 152x 424x 21x 4x 2x 2x 2x 2x 21x 2x 16x 15x 15x 4x 14x 11x 11x 11x 11x 11x 9x 11x 4x 10x 7x 7x 11x 15x 15x 21x 656x 656x 656x 656x 656x 656x 136x 136x 136x 425x 16x 16x 16x 16x 16x 16x 16x 1150x 1150x 1150x 1150x 16x 16x 16x 16x 16x 16x 1150x 1134x 1134x 1134x 1150x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 656x 504x 504x 322x 322x 322x 322x 322x 322x 322x 322x 322x 500x 500x 500x 500x 500x 500x 500x 322x 322x 322x 322x 322x 322x 322x 2235x 2235x 4205x 1735x 1735x 1735x 1735x 1735x 4205x 2470x 2470x 4205x 2235x 2235x 322x 322x 322x 322x 322x 322x 322x 322x 322x 948x 948x 948x 948x 948x 948x 948x 322x 322x 322x 322x 322x 322x 322x 322x 4298x 8217x 3350x 3350x 3350x 3350x 3350x 3350x 3350x 3350x 3350x 3350x 3350x 1x 1x 3350x 3349x 3349x 3350x 3350x 3350x 3350x 3350x 3350x 3350x 3350x 3350x 3350x 2x 2x 3350x 3350x 378x 378x 3350x 3350x 8217x 4298x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 322x 14571x 14571x 8123x 8123x 14571x 14x 14x 6434x 14571x 322x 322x 322x 322x 322x 322x 6905x 6905x 2906x 1455x 1455x 1451x 1451x 3999x 6905x 3999x 3999x 3999x 3999x 108x 108x 3891x 3891x 3891x 3891x 3891x 3891x 3891x 3999x 185x 185x 3706x 3706x 3706x 3706x 3706x 3999x 14x 14x 3692x 3999x 31x 31x 3661x 3999x 3008x 294x 294x 3008x 383x 383x 3008x 120x 120x 3008x 2864x 3807x 3844x 2157x 2157x 3844x 707x 707x 707x 6905x 322x 322x 322x 322x | import fs from 'fs';
import path from 'path';
import ExpressionParser, { readDeclarations } from './expressionParser.js';
import { analyzeBridgeFile, findBridgeImports } from './BridgeParser.js';
import ContractValidator from './ContractValidator.js';
import { logger } from '../core/runtime/AvenxLogger.js';
import { AvenxErrorCodes } from '../core/runtime/AvenxError.js';
import { RESERVED_INSTANCE_METHOD_KEYS } from '../core/runtime/AvenxComponent.js';
import { TemplateValidationError, BuildError } from './errors/index.js';
import { reportWarning } from './utils/warningReporter.js';
import { replaceEnvVariables } from '../env.js';
import { processBindDirectives, escapeTemplateMarkers } from '../core/utils/templateUtils.js';
import { tokenizeMarkup, applyEdits } from '../core/utils/markupLexer.js';
import { isEventHandlerAttribute } from '../core/security/eventAttributes.js';
import loadConfig, { resolvePathAlias, getClosestKey } from '../config.js';
import { collectLocations } from './sourceMapTrace.js';
import { addCachedComponentUnit } from './atlas/cache.js';
import { collectTemplateEvents } from './templateEvents.js';
import { interpolationEnd } from '../core/utils/markupLexer.js';
import { getLineAndColumn, parseAttributes, parseHTML, scanTagEnd, serializeHTML } from './parser/htmlTree.js';
import { buildTemplateIR, parseForHeader } from './ir/build.js';
import { lowerToProgram } from './ir/lower.js';
import { validateComponentExpressions } from './validateExpressions.js';
import { collectImportStatements } from './modules.js';
/**
* The executable source of each declared resource, keyed by name.
*
* A resource is emitted either as a bare handler string or as
* `{ handler, pollInterval }`, and the runtime prefixes a bare expression with
* `return`. Both shapes are normalised here so the generator sees exactly the
* text the runtime will execute -- otherwise a polling resource would compile
* against a string that is not what runs, and quietly miss.
* @param {object} resources - The parsed resource declarations.
* @returns {Object<string, string>} Handler sources by resource name.
*/
function resourceBodies(resources) {
const bodies = {};
for (const [name, definition] of Object.entries(resources || {})) {
const handler = definition && typeof definition === 'object' ? definition.handler : definition;
if (typeof handler !== 'string' || handler.trim() === '') continue;
bodies[name] = handler.trim().startsWith('return') ? handler : `return ${handler}`;
}
return bodies;
}
import { collectExpressions } from './codegen/collect.js';
import { buildExpressionTable, buildProgramTables } from './codegen/table.js';
/**
* Framework tags the compiler understands directly. These are never real
* components, so a reference to one must not be reported as an unresolved
* component (see {@link ComponentParser#validateComponentTags} / AVX_W46).
*
* The `@`-prefixed directives (`@for`, `@if`, `@suspense`, …) are handled
* separately: any tag beginning with `@` is skipped unconditionally, so it is
* enough to list the non-prefixed framework tags here.
* @type {Set<string>}
*/
const BUILTIN_TAGS = new Set([
'slot',
'resource',
'state',
'action',
'transition',
'template',
'component',
'script',
'style',
]);
/**
* The parameter names bound by arrow functions in an expression.
*
* Covers `x => …` and `(x, y) => …`, which is the whole of what the template
* expression language admits -- a destructuring parameter is not an expression
* and is refused before it reaches here.
* @param {string} code - The expression source.
* @returns {Set<string>} The bound names.
*/
function arrowParameters(code) {
const names = new Set();
const arrow = /(?:\(([^)]*)\)|([A-Za-z_$][\w$]*))\s*=>/g;
let match;
while ((match = arrow.exec(code)) !== null) {
const list = match[1] !== undefined ? match[1] : match[2];
for (const part of list.split(',')) {
const name = part.trim();
if (/^[A-Za-z_$][\w$]*$/.test(name)) names.add(name);
}
}
return names;
}
/**
* Adds every name a `<@for>` header binds to the declared set.
*
* `index` is included for every loop, named or not, because that is how the
* loop index has always been reached -- and reporting it as undeclared was a
* warning on correct code, which is worse than no warning at all.
* @param {object} node - A parsed template node.
* @param {Set<string>} declared - The set to add to.
*/
function collectLoopBindings(node, declared) {
if (!node || node.type !== 'element') return;
if ((node.tagName || '').toLowerCase() === '@for') {
declared.add('index');
try {
const parts = parseForHeader(node.rawAttrs);
if (parts.item) declared.add(parts.item);
for (const name of parts.destructure || []) declared.add(name);
} catch {
// A malformed header is reported by the IR builder, with a location and
// a reason. Adding a second, vaguer complaint here would not help.
}
}
for (const child of node.children || []) {
collectLoopBindings(child, declared);
}
}
/**
* A conservative set of known HTML and SVG element names. Element names are
* lowercase, so a PascalCase tag can practically never collide with one; this
* set exists only as a defensive net for an element written with an unusual
* case. It is deliberately not exhaustive — anything lowercase is treated as an
* ordinary element regardless of membership (see {@link ComponentParser#validateComponentTags}).
* @type {Set<string>}
*/
const KNOWN_ELEMENTS = new Set([
// Common HTML
'a', 'abbr', 'address', 'article', 'aside', 'audio', 'b', 'bdi', 'bdo',
'blockquote', 'body', 'button', 'canvas', 'caption', 'cite', 'code',
'colgroup', 'data', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog',
'div', 'dl', 'dt', 'em', 'fieldset', 'figcaption', 'figure', 'footer',
'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup',
'html', 'i', 'iframe', 'ins', 'kbd', 'label', 'legend', 'li', 'main', 'map',
'mark', 'menu', 'meter', 'nav', 'noscript', 'object', 'ol', 'optgroup',
'option', 'output', 'p', 'picture', 'pre', 'progress', 'q', 'rp', 'rt',
'ruby', 's', 'samp', 'section', 'select', 'small', 'span', 'strong', 'sub',
'summary', 'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead',
'time', 'tr', 'u', 'ul', 'var', 'video',
// SVG
'svg', 'circle', 'clippath', 'defs', 'ellipse', 'foreignobject', 'g',
'image', 'line', 'lineargradient', 'marker', 'mask', 'path', 'pattern',
'polygon', 'polyline', 'radialgradient', 'rect', 'stop', 'symbol', 'text',
'tspan', 'use',
]);
/**
* The local names a component's own imports bind, excluding bridges and the
* runtime entry.
*
* A bridge already reaches the template through the bridges argument, and the
* runtime import binds the base class the generated module extends. Everything
* else -- an npm package, a local helper -- is a value the developer expects to
* be able to name, so it becomes part of the component's evaluation scope.
* @param {string} source - The component source.
* @param {string[]} bridgeLocals - Local names already bound as bridges.
* @returns {string[]} Local binding names, in source order.
*/
function collectImportBindings(source, bridgeLocals) {
const bridges = new Set(bridgeLocals);
const names = [];
for (const statement of collectImportStatements(source)) {
const match = statement.match(/^import\s+([\s\S]*?)\s+from\s*['"]([^'"]*)['"]/);
if (!match) continue;
if (/^(avenx-core(\/(runtime|core))?)$/.test(match[2])) continue;
const clause = match[1].trim();
const braceStart = clause.indexOf('{');
const head = (braceStart === -1 ? clause : clause.slice(0, braceStart)).replace(/,\s*$/, '').trim();
const star = head.match(/^(?:([A-Za-z_$][\w$]*)\s*,\s*)?\*\s+as\s+([A-Za-z_$][\w$]*)$/);
if (star) {
if (star[1]) names.push(star[1]);
names.push(star[2]);
} else if (/^[A-Za-z_$][\w$]*$/.test(head)) {
names.push(head);
}
if (braceStart !== -1) {
const close = clause.indexOf('}', braceStart);
const inner = close === -1 ? clause.slice(braceStart + 1) : clause.slice(braceStart + 1, close);
for (const part of inner.split(',')) {
const trimmed = part.trim();
if (!trimmed) continue;
const aliased = trimmed.split(/\s+as\s+/);
const local = (aliased[1] || aliased[0]).trim();
if (/^[A-Za-z_$][\w$]*$/.test(local)) names.push(local);
}
}
}
return names.filter((name) => !bridges.has(name) && !names.includes(name, names.indexOf(name) + 1));
}
/**
* Cache of resolved `avenx.config.json` contents, keyed by the directory
* the search started from, so each component file doesn't re-read and
* re-parse the config from disk.
* @type {Map<string, object|null>}
*/
const configCache = new Map();
/**
* Walks up the directory tree from `startDir` looking for an
* `avenx.config.json` file, and returns its parsed contents (or `null` if
* none is found, or if it fails to parse).
* @param {string} startDir - Absolute directory to start searching from.
* @returns {object|null}
*/
function loadAvenxConfig(startDir) {
if (configCache.has(startDir)) {
return configCache.get(startDir);
}
let config = null;
let currentDir = startDir;
while (currentDir) {
const configPath = path.join(currentDir, 'avenx.config.json');
if (fs.existsSync(configPath)) {
try {
config = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
} catch (err) {
reportWarning(AvenxErrorCodes.COMPILER_INVALID_CONFIG, new BuildError(AvenxErrorCodes.COMPILER_INVALID_CONFIG, configPath, err.message));
config = null;
}
break;
}
const parent = path.dirname(currentDir);
if (parent === currentDir) {
break;
}
currentDir = parent;
}
configCache.set(startDir, config);
return config;
}
/**
* Resolves the list of project-specific void tags declared in
* `avenx.config.json` (via a `voidTags` array) for the given component
* file, e.g.:
* ```json
* { "voidTags": ["my-video", "my-icon"] }
* ```
* @param {string} [filePath] - Absolute path of the component file being compiled.
* @returns {string[]} Lowercased, trimmed custom void tag names. Empty if none configured.
*/
function getCustomVoidTags(filePath) {
if (!filePath) {
return [];
}
const startDir = path.resolve(path.dirname(filePath));
const config = loadAvenxConfig(startDir);
if (!config || !Array.isArray(config.voidTags)) {
return [];
}
return config.voidTags
.filter((tag) => typeof tag === 'string' && tag.trim() !== '')
.map((tag) => tag.trim().toLowerCase());
}
/**
* Builds the atomic descriptor the generated constructor carries.
*
* Only the runtime-relevant half of a modifier reaches the bundle. The write
* set, the boundedness flag and the irreversible-effect list are compile-time
* findings: they exist to be reported before the application ships, and the
* journal does not need them because it observes the reactive proxies rather
* than a prediction of what they will do.
*
* A modifier naming an action the component does not declare is dropped. The
* generated code would otherwise reference a method that is not there, and a
* typo in `name=` is already reported by the action itself being missing.
* @param {Object<string, {atomic: boolean, onConflict: string=}>} modifiers - Parsed modifiers.
* @param {Object<string, string>} methods - The component's action bodies.
* @returns {Object<string, object>|null} The descriptor, or null when there is nothing to emit.
*/
function buildAtomicSpec(modifiers, methods) {
if (!modifiers) return null;
/** @type {Object<string, object>} */
const spec = {};
let found = false;
for (const name of Object.keys(modifiers).sort()) {
if (!Object.prototype.hasOwnProperty.call(methods || {}, name)) continue;
const modifier = modifiers[name];
if (!modifier || !modifier.atomic) continue;
spec[name] = modifier.onConflict ? { onConflict: modifier.onConflict } : {};
found = true;
}
return found ? spec : null;
}
/**
* The component class name a file compiles to: `user-profile.component.js`
* becomes `UserProfile`.
* @param {string} filePath - The component or page path.
* @returns {string} The class name.
*/
function classNameFromPath(filePath) {
return path
.basename(filePath)
.replace(/\.(component|page)?\.(js|html|avx)$/i, '')
.split(/[-_]/)
.map((part) => part.charAt(0).toUpperCase() + part.slice(1))
.join('');
}
/**
* Removes HTML comments from a template by lexer span.
*
* Only real comments are removed. `title="<!-- x -->"` is an attribute value,
* and an unterminated `<!--` is left for {@link ComponentParser#assertWellFormedTemplate}
* to report rather than silently deleting the rest of the template.
* @param {string} template - The template.
* @returns {string} The template without comments.
*/
function stripTemplateComments(template) {
if (typeof template !== 'string' || !template.includes('<!--')) return template;
const edits = tokenizeMarkup(template)
.filter((token) => token.type === 'comment' && !token.unterminated)
.map((token) => ({ start: token.start, end: token.end, text: '' }));
return applyEdits(template, edits);
}
/**
* ComponentParser handles the parsing of Avenx component files (.js and .css).
* It extracts component state, computed properties, methods, and templates,
* and coordinates with the StyleProcessor to handle styles.
*/
class ComponentParser {
/**
* Fails the build when a refused template uses a compiled-only construct.
*
* Falling back is safe for a construct both renderers implement: the template
* renders, more slowly, and the build says so. `<@if>` is not such a
* construct. It only ever existed on the compiled path, so the string
* renderer has no rewrite for it -- a refused template containing one would
* render `<@if cond>` into the document as a literal element, wrapping the
* branch it was supposed to choose between.
*
* That is exactly the silent miscompile the compile-or-refuse rule exists to
* prevent, so it is an error with a location rather than a warning. The fix
* is always the same: get the template compiling, by moving the construct
* that refused into a child component.
* @param {string} name - The component class name.
* @param {string} filePath - The component's path.
* @param {string} template - The semantic template.
* @param {{reason: string, detail: string}} refusal - Why it refused.
* @throws {TemplateValidationError} When the template cannot fall back safely.
*/
assertNoCompiledOnlyConstruct(name, filePath, template, refusal) {
const match = template.match(/<@(if|elseif|elif|else)\b/i);
if (!match) return;
const error = new TemplateValidationError(
AvenxErrorCodes.COMPILER_COMPILED_ONLY_CONSTRUCT,
name,
match[1],
`${refusal.reason} (${refusal.detail})`,
);
error.setLocation({ source: template, index: match.index, filePath });
throw error;
}
/**
* Compiles this component's template to a render program.
*
* Runs on {@link ComponentParser#lastSemanticTemplate} -- the template after
* styles and two-way bindings and before any directive rewrite -- so the IR
* reads `<@for>` and `<@if>` as the constructs they are rather than as the
* markup they used to be turned into.
*
* Either half may refuse. The IR refuses a construct it does not model yet;
* the lowering refuses an IR node it cannot emit. Either way the component
* keeps the string renderer and the reason is recorded for the build to
* report, which is the same compile-or-refuse rule that has always applied.
* @param {string} name - The component class name.
* @param {string} filePath - The component's path, for diagnostics.
* @param {string[]} voidTags - The effective void tag set.
* @returns {{program: object|null, expressions: string[], statements: string[]}}
* The program and the sources its indices address.
*/
compileRenderProgram(name, filePath, voidTags) {
const source = this.lastSemanticTemplate;
if (typeof source !== 'string' || source.trim() === '') {
return { program: null, expressions: [], statements: [] };
}
// Static marking runs on the semantic template rather than on the rewritten
// one, because the IR is built from the semantic template and a mark
// applied after it would never be seen.
const marked = this.optimizeStaticSubtrees(source, filePath);
const built = buildTemplateIR(marked, { voidTags });
if (built.refusal) {
this.assertNoCompiledOnlyConstruct(name, filePath, source, built.refusal);
this.renderFallbacks.push({ name, reason: built.refusal.reason, detail: built.refusal.detail });
return { program: null, expressions: [], statements: [] };
}
const lowered = lowerToProgram(built.ir, { voidTags });
if (lowered.refusal) {
this.assertNoCompiledOnlyConstruct(name, filePath, source, lowered.refusal);
this.renderFallbacks.push({ name, reason: lowered.refusal.reason, detail: lowered.refusal.detail });
return { program: null, expressions: [], statements: [] };
}
return { program: lowered.program, expressions: lowered.expressions, statements: lowered.statements };
}
/**
* @param {StyleProcessor} styleProcessor - An instance of StyleProcessor to handle styles.
* @param {string[]} [customVoidTags] - Additional void tag names (lowercase).
* @param {object} [config] - Project configuration object.
*/
constructor(styleProcessor, customVoidTags = [], config = null) {
/** @type {StyleProcessor} */
this.styleProcessor = styleProcessor;
/** @type {object|null} */
this.config = config;
/** @type {ExpressionParser} */
this.expressionParser = new ExpressionParser(config);
/** @type {string[]} */
this.customVoidTags = customVoidTags || [];
/**
* Bridges discovered by the compiler, keyed by absolute path. Set by
* AvenxCompiler before components are parsed; when a component is parsed
* standalone (tests, the Vite plugin) bridges are analysed on demand.
* @type {Map<string, object>}
*/
this.bridges = new Map();
/**
* Source locations of every declaration parsed so far, keyed by class name.
*
* Collected as a by-product of parsing and written beside the bundle rather
* than into it, so `avenx trace view` can turn a recorded action name into
* a file and a line without an application paying for the mapping.
* @type {Map<string, object>}
*/
this.locations = new Map();
/**
* The Atlas model being populated, or null when Atlas is not being built.
*
* Set by AvenxCompiler. When it is null, `parse` does no Atlas work at
* all, so a caller that only wants a compiled class — the Vite plugin, a
* unit test, `loadComponent` — pays nothing for it.
* @type {AppModel|null}
*/
this.model = null;
/**
* The units handed to Atlas so far, so render edges can be resolved once
* every component name is known.
* @type {Array<{name: string, filePath: string, content: string, kind: string}>}
*/
this.__atlasUnits = [];
/**
* Every registered component and page name in the project, supplied by the
* compiler through {@link ComponentParser#setComponentNames} before any
* file is parsed. Used by the unresolved-component check (AVX_W46). Empty
* when a component is parsed standalone, which disables that check.
* @type {Set<string>}
*/
this.__componentNames = new Set();
/**
* Components whose template could not be compiled to a render program, and
* why.
*
* A component without a program renders through the string path: correct,
* and proportional to the whole template on every update. That is a real
* cost, so it is reported rather than absorbed silently -- the same house
* rule Atlas follows when its analysis is incomplete.
* @type {Array<{name: string, reason: string, detail: string}>}
*/
/**
* Per-unit information the module generator needs, keyed by absolute
* source path. Filled by {@link ComponentParser#parse}.
* @type {Map<string, object>}
*/
this.moduleMeta = new Map();
this.renderFallbacks = [];
/**
* Component tag names referenced by any template in this build.
*
* Populated as templates compile, so by the time the entry module is built
* the answer is exact rather than a guess from the source text.
* @type {Set<string>}
*/
this.referencedComponents = new Set();
/**
* What the expression generator could not compile, per unit.
*
* A security refusal fails the build; a language gap is reported as a
* warning and leaves that one expression on the runtime path. Recorded
* here rather than thrown at the point of generation so a build reports
* every unit's problems at once instead of the first one's.
* @type {Array<{name: string, refusals: object[], gaps: object[]}>}
*/
this.expressionGaps = [];
/**
* The project root, when the compiler has told the parser what it is.
*
* `findProjectRoot` walks up from a component looking for a project
* marker, which lands somewhere arbitrary in a directory that has none —
* a scratch project in a temp directory, for instance — and every reported
* path is then relative to the wrong place. The compiler resolved the root
* once and authoritatively, so it is preferred when available.
* @type {string|null}
*/
this.rootDir = null;
}
/**
* Tells the parser which directory reported paths are relative to.
* @param {string} rootDir - The project root.
* @returns {void}
*/
setRootDir(rootDir) {
this.rootDir = rootDir || null;
}
/**
* Attaches an Atlas model for `parse` to populate.
* @param {AppModel|null} model - The model.
* @returns {void}
*/
setModel(model) {
this.model = model || null;
this.__atlasUnits = [];
}
/**
* Supplies the project's bridge descriptors, so imports can be resolved
* without re-reading each bridge module for every component.
* @param {Map<string, object>} bridges - Descriptors keyed by absolute path.
*/
setBridges(bridges) {
this.bridges = bridges instanceof Map ? bridges : new Map();
}
/**
* Supplies the full set of registered component and page names, so a template
* tag can be validated against every name in the project rather than only the
* ones parsed so far.
*
* The compiler discovers all names by filename before it parses any file, and
* hands them over here. When it is never called — a component parsed
* standalone in a test or the Vite plugin — the set stays empty and the
* unresolved-component check does nothing, so a lone component is never
* flagged for referencing a sibling the parser could not see.
* @param {Iterable<string>} names - Registered component and page names.
* @returns {void}
*/
setComponentNames(names) {
this.__componentNames = names ? new Set(names) : new Set();
}
/**
* Resolves the bridges a component imports into template scope bindings.
*
* The import is the declaration: a component sees exactly the bridges it
* imported, under the local name it chose. Nothing is ambient, so the
* compiler knows every consumer of every bridge.
* @param {string} filePath - Absolute path to the component file.
* @param {string} content - The component source.
* @param {string} name - The component class name, for diagnostics.
* @param {Set<string>} contracts - The component's declared contracts.
* @returns {Array<{local: string, binding: string, bridge: string}>} The bindings.
* @private
*/
resolveBridgeBindings(filePath, content, name, contracts) {
const bindings = [];
for (const entry of findBridgeImports(filePath, content)) {
const key = path.resolve(entry.resolved);
let descriptor = this.bridges.get(key);
if (!descriptor) {
descriptor = analyzeBridgeFile(key, replaceEnvVariables);
if (!descriptor) {
continue;
}
this.bridges.set(key, descriptor);
}
if (contracts && contracts.has('isolated')) {
throw new BuildError(AvenxErrorCodes.COMPILER_BRIDGE_ISOLATED_IMPORT, name, descriptor.name);
}
bindings.push({ local: entry.local, binding: descriptor.binding, bridge: descriptor.name });
}
return bindings;
}
/**
* Parses a .component.js or .page.js file and its corresponding CSS file.
* @param {string} filePath - The absolute path to the file.
* @param {'component'|'page'} [type] - The type of file being parsed.
* @returns {string} The generated JavaScript class.
*/
parse(filePath, type = 'component') {
const config = this.config || (filePath ? loadAvenxConfig(path.dirname(filePath)) : null);
const rootDir = this.rootDir || (filePath ? loadConfig.findProjectRoot(path.dirname(filePath)) : process.cwd());
filePath = resolvePathAlias(filePath, config, rootDir);
const isPage = type === 'page';
const content = replaceEnvVariables(fs.readFileSync(filePath, 'utf-8'));
const fileName = path.basename(filePath).replace(/\.(component|page)?\.(js|html|avx)$/i, '');
// Convert user-profile or user_profile to UserProfile
const name = fileName
.split(/[-_]/)
.map((part) => part.charAt(0).toUpperCase() + part.slice(1))
.join('');
const desPath = filePath.replace(/\.(component|page)?\.(js|html|avx)$/i, isPage ? '.page.css' : '.component.css');
const desBlocks = {};
const styles = {};
if (fs.existsSync(desPath)) {
const desContent = fs.readFileSync(desPath, 'utf-8');
const globalMatch = desContent.match(/<@global>([\s\S]*?)<\/ ?@global>/i);
if (globalMatch) {
const inner = globalMatch[1];
const defRegex = /@def\s+([\w-]+)\s+([^;]+);/g;
let defMatch;
while ((defMatch = defRegex.exec(inner)) !== null) {
styles[defMatch[1]] = defMatch[2].trim();
}
}
this.styleProcessor.registerSourceFile(desPath, desContent);
this.extractStylesAndVars(desContent, desBlocks, desPath);
}
this.assertDeclarationsTerminated(content, filePath, name);
const contracts = this.extractContracts(content);
const bridgeBindings = this.resolveBridgeBindings(filePath, content, name, contracts);
// Everything else the file imports. Bridges are excluded because they reach
// the template through the bridges argument already, and the runtime entry
// is excluded because those names are the base class the module extends.
const importedLocals = collectImportBindings(content, bridgeBindings.map((entry) => entry.local));
const state = this.extractState(content, filePath, config);
const computed = this.extractComputed(content);
const methods = this.extractMethods(content, name, filePath, config);
const actionModifiers = this.extractActionModifiers(content);
const resources = this.expressionParser.parseResources(content);
let template = this.extractTemplate(
content,
desBlocks,
name,
filePath,
state,
computed,
methods,
resources,
[...bridgeBindings.map((entry) => entry.local), ...importedLocals],
);
// Handle declarative tags: <MyComponent /> or <MyComponent>...</MyComponent> -> <div data-avenx-comp="MyComponent">...</div>
// Only if it looks like a component (starts with uppercase)
template = this.processComponentTags(template);
// Which components this build actually references. The compiler uses it to
// decide whether a built-in's registering module joins the graph, so an
// application that never writes `<VirtualList>` does not carry it.
for (const match of template.matchAll(/data-avenx-comp="([A-Za-z0-9_]+)"/g)) {
this.referencedComponents.add(match[1]);
}
// Validate compiler contracts (static, pure, deterministic, isolated)
const customVoidTags = [...(this.customVoidTags || []), ...getCustomVoidTags(filePath)];
const astNodes = parseHTML(template, customVoidTags);
const validation = ContractValidator.validate(astNodes, {
name,
filePath,
contracts,
state,
computed,
methods,
resources,
config,
});
if (!validation.valid && validation.errors.length > 0) {
throw validation.errors[0];
}
this.locations.set(name, collectLocations({
name,
filePath,
rootDir,
content,
computed,
methods,
resources,
contracts,
}));
// Atlas is retention, not a second pass: everything it needs was produced
// above on the way to generating this class, and is handed over rather
// than recomputed. The original `content` goes with it because the
// template below has already been rewritten past the point where its
// offsets point at anything a developer can open.
if (this.model) {
const atlasUnit = addCachedComponentUnit(this.model, {
name,
kind: isPage ? 'page' : 'component',
filePath,
rootDir,
content,
state,
computed,
methods,
resources,
contracts,
actionModifiers,
bridgeBindings,
bridges: this.bridges,
});
this.__atlasUnits.push({
name,
filePath,
content,
kind: isPage ? 'page' : 'component',
// The mask is the expensive half of reading a template; the render
// pass reuses the one the relationship pass already built.
masked: atlasUnit.masked,
starts: atlasUnit.starts,
});
}
// Template expressions are evaluated by Avenx's expression evaluator, which
// refuses anything outside the expression language. Checking here means an
// unsupported expression fails the build with a file and a line, rather
// than becoming an AVX_R32 the first time that component renders.
const expressionErrors = validateComponentExpressions({
name,
filePath,
content,
template,
computed,
});
if (expressionErrors.length > 0) {
throw expressionErrors[0];
}
// Identify and mark static subtrees for patcher performance optimization
template = this.optimizeStaticSubtrees(template, filePath);
// The render program is compiled from the *semantic* template -- the one
// the author wrote, before any directive was rewritten into markup. That
// ordering is the point of the IR: `<@for item in items>` still says what
// it means at that stage, and after the rewrites above it does not.
const customVoidTagsForProgram = [...(this.customVoidTags || []), ...getCustomVoidTags(filePath)];
const rendered = this.compileRenderProgram(name, filePath, customVoidTagsForProgram);
// Templates and method bodies are emitted as JSON string literals rather
// than backtick-wrapped template literals: a `${...}` sequence in component
// HTML (or a legitimate template literal inside an <action> body) would
// otherwise be interpolated by the generated bundle instead of being
// preserved verbatim.
let optionImports = '';
// A compiled component does not render from the template, so a production
// build does not carry it. That is the larger half of what the previous
// design shipped twice: the whole template travelled beside the program,
// with its `{{ }}` and its JSON-encoded handlers still in it, for a runtime
// that never looked at it.
//
// Development keeps it. `__getTemplate()` is the seam renderer benchmarks
// and the render-path parity test use to drive the same class through both
// renderers, and a suspense or error-boundary fallback is still read out of
// the template by regex -- neither of which a compiled component can have,
// because both refuse to compile, but both of which a *fallback* component
// in the same build still needs.
const shipTemplate = !rendered.program || !this.production;
const templateLiteral = JSON.stringify(shipTemplate ? template : '');
// The options argument stays absent unless something needs it, so a
// component that declares neither contracts nor atomic actions compiles to
// exactly the same constructor call it did before either feature existed.
if (importedLocals.length > 0) {
// Emitted as shorthand properties, so the object references the module's
// own bindings and the bundler sees them used.
optionImports = `imports: { ${importedLocals.join(', ')} }`;
}
const contractsList = Array.from(contracts || []);
const atomicSpec = buildAtomicSpec(actionModifiers, methods);
const optionParts = [];
if (optionImports) {
optionParts.push(optionImports);
}
if (contractsList.length > 0) {
optionParts.push(`contracts: ${JSON.stringify(contractsList)}`);
}
if (atomicSpec) {
optionParts.push(`atomic: ${JSON.stringify(atomicSpec)}`);
}
// The program travels in the options object rather than as another
// positional argument. The constructor already takes nine, and the options
// argument is the extension point that exists precisely so it does not have
// to take ten. A component compiled before render programs existed simply
// has no `program` key and takes the string path.
//
// It is referenced as a static rather than written inline, because the
// runtime caches one parsed skeleton per program *object*. An object
// literal inside the constructor is a fresh object on every `new`, so the
// cache would never hit and every instance would reparse the template --
// which is most of the cost this whole mechanism exists to remove.
let programStatic = '';
if (rendered.program) {
// The expression and statement closures the program's indices address.
// Built here rather than in the source-keyed table below because an
// indexed entry that will not compile leaves nothing behind for the
// runtime to fall back to, so the whole program has to be withdrawn.
const programTables = buildProgramTables(name, rendered.expressions, rendered.statements);
if (programTables.failure) {
this.renderFallbacks.push({
name,
reason: 'an expression the code generator could not compile',
detail: `${programTables.failure.source} (${programTables.failure.reason})`,
});
rendered.program = null;
} else {
optionParts.push(`program: ${name}.__axProgram`);
// The handler sources, for Trace only, and only in a development
// build. A causal tree reads better with "@click=\"inc()\"" on the
// event node than with "handler #2", and Trace is a development
// feature -- the recorder is not reachable from a production bundle at
// all. Gating it here is what keeps the source out of shipped output
// while leaving the tool that wants it fully served.
// Development-only debug tables. Trace names a woken binding by the
// expression it evaluates and an event node by the handler that fired,
// and both of those are source. A production bundle cannot start a
// recording at all, so carrying the source there would be weight
// nothing can read.
let debugStatic = '';
if (!this.production) {
if (rendered.expressions.length > 0) {
debugStatic += `${name}.__axProgramExprSrc = ${JSON.stringify(rendered.expressions)};\n`;
}
if (rendered.statements.length > 0) {
debugStatic += `${name}.__axProgramStmtSrc = ${JSON.stringify(rendered.statements)};\n`;
}
}
programStatic = `\n${name}.__axProgram = ${JSON.stringify(rendered.program)};\n${programTables.source}${debugStatic}`;
}
}
// Every expression this unit will evaluate, compiled to a closure the
// engine itself will parse. The table is attached as a static beside the
// program so the runtime can find it from the class, and so it is created
// once per class rather than once per instance.
const collected = collectExpressions({
template,
computed,
program: rendered.program,
voidTags: customVoidTagsForProgram,
});
// Actions and resources are addressed by name at run time, so they are
// compiled into their own tables rather than into the source-keyed one.
collected.actions = methods;
collected.resources = resourceBodies(resources);
const table = buildExpressionTable(name, collected);
if (table.refusals.length > 0 || table.gaps.length > 0) {
// The line is where the expression's text first appears in the file. The
// table is keyed by source text, so this is exact for every expression
// written once and names the first use of one written more than once.
const lineOf = (source) => {
const index = typeof source === 'string' ? content.indexOf(source) : -1;
return index >= 0 ? content.slice(0, index).split('\n').length : null;
};
this.expressionGaps.push({
name,
filePath,
refusals: table.refusals,
gaps: table.gaps.map((gap) => ({ ...gap, line: lineOf(gap.source) })),
});
}
const expressionStatic = table.source;
// An action whose body compiled is reached through `__axActions`, keyed by
// name, so the body text is no longer needed to *run* it. It is still
// emitted in a development build because Trace records it and
// `avenx trace view` prints it; a production bundle cannot start a
// recording, so carrying the text there is weight nothing can read. The
// name still has to be emitted -- it is what tells the runtime the action
// exists.
const keepBodies = !this.production;
const methodStrings = Object.entries(methods)
.map(([key, body]) => {
const drop = !keepBodies && table.compiledActions && table.compiledActions.has(key);
return `${JSON.stringify(key)}: ${JSON.stringify(drop ? '' : body)}`;
})
.join(',\n ');
const contractsParam = optionParts.length > 0 ? `, { ${optionParts.join(', ')} }` : '';
// What the compiler needs in order to frame this class as an ES module: the
// class name, the import statements the developer wrote, and the bridge
// bindings the class body refers to. Recorded on the parser rather than
// returned, so `parse()` keeps the bare-class output shape that
// avenx-core/testing, the Vite plugin and the render-path tests consume.
this.moduleMeta.set(path.resolve(filePath), {
importedLocals,
className: name,
isPage,
imports: collectImportStatements(content),
bridgeBindings,
});
// Imported bridges join the component's template scope under their local
// name, on top of the bridges the app registered.
const bridgesExpr =
bridgeBindings.length > 0
? `{ ...bridges, ${bridgeBindings.map((entry) => `${JSON.stringify(entry.local)}: ${entry.binding}`).join(', ')} }`
: 'bridges';
if (isPage) {
return `
/**
* Page component representing ${name}.
*/
class ${name} extends AvenxPage {
/**
* @param {Object} bridges - Mapped bridges.
* @param {Object} componentRegistry - Registry of components.
* @param {Object} props - Page properties.
*/
constructor(bridges, componentRegistry, props) {
super(${JSON.stringify(state)}, ${JSON.stringify(computed)}, ${bridgesExpr}, ${templateLiteral}, { ${methodStrings} }, componentRegistry, props, ${JSON.stringify(styles)}, ${JSON.stringify(resources)}${contractsParam});
}
}
${programStatic}${expressionStatic}`;
}
return `
/**
* Component representing ${name}.
*/
class ${name} extends AvenxComponent {
/**
* @param {Object} bridges - Mapped bridges.
* @param {Object} props - Component properties.
*/
constructor(bridges, props) {
super(${JSON.stringify(state)}, ${JSON.stringify(computed)}, ${bridgesExpr}, ${templateLiteral}, { ${methodStrings} }, props, ${JSON.stringify(styles)}, ${JSON.stringify(resources)}${contractsParam});
}
}
${programStatic}${expressionStatic}`;
}
/**
* Extracts global CSS variables and component-specific style blocks from CSS content.
* @param {string} desContent - The content of the .component.css file.
* @param {object} desBlocks - An object to store the extracted style blocks.
* @param {string} [desPath] - The original CSS file path.
* @private
*/
extractStylesAndVars(desContent, desBlocks, desPath = '') {
const globalMatch = desContent.match(/<@global>([\s\S]*?)<\/ ?@global>/i);
let rawGlobalCss = '';
if (globalMatch) {
const idx = desContent.indexOf(globalMatch[0]);
const globalStartLine = desContent.substring(0, idx).split('\n').length;
const inner = globalMatch[1];
const defRegex = /@def\s+([\w-]+)\s+([^;]+);/g;
let defMatch;
while ((defMatch = defRegex.exec(inner)) !== null) {
this.styleProcessor.addVariable(defMatch[1], defMatch[2].trim());
}
// Remove @def lines and add the rest as global CSS
rawGlobalCss = inner.replace(/@def\s+[\w-]+\s+[^;]+;/g, '').trim();
let compiledGlobalCss = rawGlobalCss;
if (this.styleProcessor.options && this.styleProcessor.options.preprocessor) {
compiledGlobalCss = this.styleProcessor.preprocessCss(rawGlobalCss, this.styleProcessor.options.preprocessor);
}
if (compiledGlobalCss) {
this.styleProcessor.addGlobalCSS(compiledGlobalCss, desPath, globalStartLine);
}
}
const cssBlockMatch = desContent.match(/<@css>([\s\S]*?)<\/ ?@css>/i);
if (cssBlockMatch) {
const cssContentOffset = desContent.indexOf(cssBlockMatch[0]);
const cssStartLine = desContent.substring(0, cssContentOffset).split('\n').length;
const inner = cssBlockMatch[1];
let depth = 0,
currentName = '',
currentBody = '',
inBlock = false;
let inString = null;
let inComment = false;
let blockStartLineOffset = 0;
let currentLineOffset = 0;
for (let i = 0; i < inner.length; i++) {
const char = inner[i];
if (char === '\n') {
currentLineOffset++;
}
if (inComment) {
if (char === '*' && inner[i + 1] === '/') {
inComment = false;
i++; // skip '/'
}
continue;
}
if (char === '/' && inner[i + 1] === '*') {
inComment = true;
i++; // skip '*'
continue;
}
if (inString) {
const toAppend = char;
let nextToAppend = '';
if (char === '\\') {
if (i + 1 < inner.length) {
nextToAppend = inner[i + 1];
if (inner[i + 1] === '\n') currentLineOffset++;
i++;
}
} else if (char === inString) {
inString = null;
}
if (inBlock) {
currentBody += toAppend + nextToAppend;
}
} else {
if (char === '"' || char === "'") {
inString = char;
if (inBlock) {
currentBody += char;
}
} else if (char === '{' && depth === 0) {
const namePart = inner.substring(0, i).trim().split('}').pop().trim();
currentName = namePart.replace(/\/\*[\s\S]*?\*\//g, '').trim();
blockStartLineOffset = currentLineOffset;
inBlock = true;
depth++;
} else if (char === '{') {
depth++;
currentBody += char;
} else if (char === '}') {
depth--;
if (depth === 0) {
if (currentName) {
let finalBody = currentBody.trim();
if (this.styleProcessor.options && this.styleProcessor.options.preprocessor) {
finalBody = this.styleProcessor.preprocessBlock(
rawGlobalCss,
finalBody,
this.styleProcessor.options.preprocessor,
);
}
desBlocks[currentName] = finalBody;
if (!desBlocks._sourceMapInfo) {
Object.defineProperty(desBlocks, '_sourceMapInfo', {
value: {},
writable: true,
enumerable: false,
configurable: true,
});
}
desBlocks._sourceMapInfo[currentName] = {
startLine: cssStartLine + blockStartLineOffset,
sourceFile: desPath,
};
}
currentBody = '';
currentName = '';
inBlock = false;
} else {
currentBody += char;
}
} else if (inBlock) {
currentBody += char;
}
}
}
}
}
/**
* Extracts compiler contracts from the component's <contract /> tags.
* @param {string} content - The content of the .component.js file.
* @returns {Set<string>} The set of declared contracts.
* @private
*/
extractContracts(content) {
return this.expressionParser.parseContracts(content);
}
/**
* Extracts the initial state from the component's <state /> tags.
* @param {string} content - The content of the .component.js file.
* @param {string} [filePath] - The component file path.
* @param {object} [config] - Project configuration object.
* @returns {object} The extracted state object.
* @private
*/
extractState(content, filePath = '', config = null) {
const activeConfig = config || this.config || (filePath ? loadAvenxConfig(path.dirname(filePath)) : null);
return this.expressionParser.parseState(content, activeConfig, {
name: filePath ? classNameFromPath(filePath) : undefined,
filePath,
});
}
/**
* Extracts computed properties from the component's <computed /> tags.
* @param {string} content - The content of the .component.js file.
* @returns {object} A map of property names to their expression strings.
* @private
*/
extractComputed(content) {
return this.expressionParser.parseComputed(content);
}
/**
* Extracts actions (methods) from the component's <action /> tags and validates method names.
* @param {string} content - The content of the .component.js file.
* @param {string} [name] - Component name.
* @param {string} [filePath] - Component file path.
* @param {object} [config] - Project configuration object.
* @returns {Object<string, string>} A map of method names to their stringified bodies.
* @private
*/
extractMethods(content, name = '', filePath = '', config = null) {
const methods = this.expressionParser.parseMethods(content);
const activeConfig = config || this.config || (filePath ? loadAvenxConfig(path.dirname(filePath)) : null);
if (methods && typeof methods === 'object') {
for (const methodName of Object.keys(methods)) {
if (RESERVED_INSTANCE_METHOD_KEYS.includes(methodName)) {
const actionMatchIdx = content.search(new RegExp(`<action\\s+[^>]*name=["']${methodName}["']`));
const err = new TemplateValidationError(
AvenxErrorCodes.COMPONENT_METHOD_RESERVED_KEY_COLLISION,
methodName,
name || (filePath ? path.basename(filePath) : 'Component'),
);
if (actionMatchIdx >= 0) {
err.setLocation({ source: content, index: actionMatchIdx, filename: filePath });
}
reportWarning(
AvenxErrorCodes.COMPONENT_METHOD_RESERVED_KEY_COLLISION,
err,
activeConfig,
);
}
}
}
return methods;
}
/**
* Extracts Avenx Rewind modifiers declared on the component's `<action>` tags.
* @param {string} content - The content of the .component.js file.
* @returns {Object<string, {atomic: boolean, onConflict: string=}>} Modifiers by action name.
* @private
*/
extractActionModifiers(content) {
return this.expressionParser.parseActionModifiers(content);
}
/**
* Preprocesses a raw template string using configured template preprocessor hooks.
* Supports custom filter functions (e.g. Pug -> HTML) before ComponentParser parses HTML.
* @param {string} rawTemplate - The raw template content.
* @param {string} [filePath] - Absolute path to component file.
* @returns {string} Preprocessed template string.
*/
preprocessTemplate(rawTemplate, filePath = '') {
if (!rawTemplate || typeof rawTemplate !== 'string') return rawTemplate;
const config = this.config || (filePath ? loadAvenxConfig(path.dirname(filePath)) : null);
if (!config || !config.preprocessors) {
return rawTemplate;
}
const preprocessors = config.preprocessors;
let templateContent = rawTemplate;
let lang = null;
// Check if the template is wrapped in <template lang="...">...</template> or <template>...</template>
const templateTagMatch = rawTemplate.match(/^<template(?:\s+lang=['"]?([\w-]+)['"]?)?\s*>([\s\S]*?)<\/template>$/i);
if (templateTagMatch) {
lang = templateTagMatch[1] ? templateTagMatch[1].toLowerCase() : null;
templateContent = templateTagMatch[2];
}
let filterFn = null;
if (typeof preprocessors === 'function') {
filterFn = preprocessors;
} else if (typeof preprocessors === 'object' && preprocessors !== null) {
if (lang) {
filterFn = preprocessors[lang] || preprocessors['.' + lang];
}
if (!filterFn) {
filterFn = preprocessors.template || preprocessors.html || preprocessors.default;
}
if (!filterFn && Object.keys(preprocessors).length === 1) {
filterFn = Object.values(preprocessors)[0];
}
}
if (typeof filterFn === 'function') {
try {
const meta = { filePath, lang };
const result = filterFn(templateContent, meta);
if (typeof result === 'string') {
return result;
}
} catch (err) {
reportWarning(
AvenxErrorCodes.COMPILER_INVALID_CONFIG,
new BuildError(AvenxErrorCodes.COMPILER_INVALID_CONFIG, filePath || 'template', `Preprocessor execution error: ${err.message}`)
);
}
}
return templateContent;
}
/**
* Extracts the HTML template and processes internal styles.
* @param {string} content - The content of the .component.js file.
* @param {object} desBlocks - The previously extracted design blocks.
* @param {string} name - The name of the component for style hashing.
* @param {string} [filePath] - The component file path.
* @param {object} [state] - The extracted state keys.
* @param {object} [computed] - The extracted computed keys.
* @param {object} [methods] - The extracted method keys.
* @param {object} [resources] - The extracted resources.
* @param {string[]} [bridgeLocals] - Local names of imported bridges, which are in template scope.
* @returns {string} The cleaned and processed HTML template.
* @private
*/
extractTemplate(content, desBlocks, name, filePath, state, computed, methods, resources = {}, bridgeLocals = []) {
// Declarations are removed by the exact source ranges the scanner
// reported, not by re-matching them with a second pattern. The old code
// read a declaration with one regex and stripped it with another, and the
// two disagreed about multi-line tags: `/<state.*? \/>/` cannot match
// across a newline, so a JSDoc-annotated `<state>` survived into the
// template and was rendered as a literal element. One scan now decides
// both, so the reader and the remover cannot drift apart again.
let template = readDeclarations(content).template;
// ES imports are declarations, not markup. They resolve child components
// and bridges at compile time and must not survive into the template,
// where they would render as a stray text node.
template = template
.replace(/^[ \t]*import\s+(?:[\s\w$,{}*]*?\s+from\s+)?['"][^'"]*['"];?[ \t]*\r?\n?/gm, '');
// Comments are removed by the spans the markup lexer reports, so text that
// merely looks like a comment inside an attribute value survives. An
// unterminated comment is left in place for the malformed-template check.
template = stripTemplateComments(template).trim();
template = this.preprocessTemplate(template, filePath);
this.assertWellFormedTemplate(template, content, filePath, name);
const isPage = filePath && filePath.endsWith('.page.js');
const desPath = filePath
? filePath.replace(
isPage ? '.page.js' : '.component.js',
isPage ? '.page.css' : '.component.css'
)
: '';
const voidTags = [...(this.customVoidTags || []), ...getCustomVoidTags(filePath)];
template = this.styleProcessor.process(template, desBlocks, name, desPath, voidTags);
this.reportFrontEndDiagnostics(this.styleProcessor.lastDiagnostics, template, content, filePath);
template = this.processBindDirectives(template);
this.assertFrontEndComplete(template, content, filePath, name);
if (filePath && state && computed && methods) {
this.validateTemplate(
template,
state,
computed,
methods,
resources,
filePath,
name,
bridgeLocals
);
}
// The template as the author wrote it, with styles resolved and two-way
// bindings expanded but no directive rewritten. This is what the IR is
// built from: `<@for item in items>` still says what it means here, and
// one line further down it will not.
//
// Recorded on the parser rather than returned, because `extractTemplate`
// has nine parameters already and every caller of it wants the rewritten
// string. The one caller that wants both reads this immediately after.
this.lastSemanticTemplate = template;
this.validateEventHandlerAttributes(template, content, filePath, name);
template = this.processForLoops(template);
template = this.processSuspense(template);
template = this.processErrorBoundary(template);
template = this.processDeadlock(template, filePath);
template = this.processDefer(template);
template = this.processTransitionTags(template, filePath);
template = this.processEventDelegation(template, filePath);
return template
.split('\n')
.filter((line) => line.trim() !== '')
.join('\n');
}
/**
* Fails the build when an `<action>` or `<resource>` is never closed.
*
* Its body would otherwise be read as template markup: the JavaScript would
* render as text, and the declaration would silently not exist.
* @param {string} content - The component source.
* @param {string} filePath - The component path.
* @param {string} name - The component class name.
* @throws {TemplateValidationError} AVX_C26 for the first unclosed declaration.
*/
assertDeclarationsTerminated(content, filePath, name) {
const [first] = readDeclarations(content).unterminated;
if (!first) return;
const error = new TemplateValidationError(
AvenxErrorCodes.COMPILER_MALFORMED_TEMPLATE,
name,
`the <${first.name}> declaration is never closed with </${first.name}>`,
content.slice(first.offset).split('\n')[0],
);
error.setLocation({ source: content, index: first.offset, filename: filePath });
throw error;
}
/**
* Refuses a bound inline event handler, and warns on a static one.
*
* An `on*` attribute on an HTML element runs its value as JavaScript. Bound to
* an interpolation (`onclick="{{ handler }}"`), that executes application state
* as code, so it is a build error (AVX_C28) with the `@event` form as the
* fix. Written as a literal (`onclick="doThing()"`), it is the developer's own
* code -- kept, but warned (AVX_W52), because it bypasses the event system and
* a strict CSP.
*
* Only lowercase HTML element tags are checked. An `on*` attribute on a
* PascalCase component tag is a prop passed to the child, never set as a DOM
* handler, so it is left alone.
* @param {string} template - The semantic template (component tags intact).
* @param {string} content - The component source, for locations.
* @param {string} filePath - The component path.
* @param {string} name - The component class name.
* @throws {TemplateValidationError} AVX_C28 for a bound handler.
*/
validateEventHandlerAttributes(template, content, filePath, name) {
if (typeof template !== 'string' || !/\bon/i.test(template)) return;
const config = this.config || (filePath ? loadAvenxConfig(path.dirname(filePath)) : null);
for (const token of tokenizeMarkup(template)) {
if (token.type !== 'open' || token.unterminated || token.directive) continue;
// A component reference is PascalCase; its attributes are props.
if (/^[A-Z]/.test(token.name)) continue;
for (const attr of token.attrs) {
if (!isEventHandlerAttribute(attr.name)) continue;
const value = attr.value || '';
const eventName = attr.name.toLowerCase().slice(2);
const snippet = template.slice(token.start, Math.min(token.end, token.start + 100)).split('\n')[0];
if (value.includes('{{') || value.includes('{%')) {
const error = new TemplateValidationError(
AvenxErrorCodes.COMPILER_BOUND_EVENT_ATTRIBUTE,
name,
attr.name,
snippet,
eventName,
);
error.setLocation(this.frontEndLocation(content, template, attr.start, `${attr.name}=`, filePath));
throw error;
}
const warning = new TemplateValidationError(
AvenxErrorCodes.COMPILER_INLINE_EVENT_ATTRIBUTE,
name,
attr.name,
eventName,
filePath ? path.basename(filePath) : 'this component',
);
warning.setLocation(this.frontEndLocation(content, template, attr.start, `${attr.name}=`, filePath));
reportWarning(AvenxErrorCodes.COMPILER_INLINE_EVENT_ATTRIBUTE, warning, config);
}
}
}
/**
* Fails the build when the template contains a tag or comment that never ends.
*
* Everything after an unterminated construct would be read as part of it:
* an unclosed attribute quote swallows the rest of the template into one
* attribute value. The tree parser has always read such input leniently, as
* text, and emitted a program for it; the build now stops instead.
* @param {string} template - The template, after preprocessing.
* @param {string} content - The component source, for locations.
* @param {string} filePath - The component path.
* @param {string} name - The component class name.
* @throws {TemplateValidationError} AVX_C26 when a construct is unterminated.
*/
assertWellFormedTemplate(template, content, filePath, name) {
if (typeof template !== 'string' || template === '') return;
for (const token of tokenizeMarkup(template)) {
if (!token.unterminated || (token.type !== 'open' && token.type !== 'comment' && token.type !== 'close')) continue;
const what =
token.type === 'comment'
? 'a comment is opened with "<!--" and never closed with "-->"'
: `the tag <${token.type === 'close' ? '/' : ''}${token.name}> is never closed with ">"`;
const snippet = template.slice(token.start, Math.min(token.end, token.start + 80)).split('\n')[0];
const error = new TemplateValidationError(AvenxErrorCodes.COMPILER_MALFORMED_TEMPLATE, name, what, snippet);
error.setLocation(this.frontEndLocation(content, template, token.start, snippet, filePath));
throw error;
}
}
/**
* Reports the diagnostics the style front-end recorded, with locations.
* @param {Array<{severity: string, code: string, args: string[], offset: number, snippet: string}>} diagnostics
* What {@link StyleProcessor#process} recorded.
* @param {string} template - The template those offsets refer to.
* @param {string} content - The component source.
* @param {string} filePath - The component path.
* @throws {TemplateValidationError} For an error-severity diagnostic, or a
* warning escalated to an error in avenx.config.json.
*/
reportFrontEndDiagnostics(diagnostics, template, content, filePath) {
if (!Array.isArray(diagnostics)) return;
const config = this.config || (filePath ? loadAvenxConfig(path.dirname(filePath)) : null);
for (const diagnostic of diagnostics) {
const args = diagnostic.severity === 'error' ? [...diagnostic.args, diagnostic.snippet] : diagnostic.args;
const error = new TemplateValidationError(diagnostic.code, ...args);
// A negative offset means the finding is not at a point in the template:
// an unused style block lives in the stylesheet, and a code frame cut
// from line one of the template would point at the wrong file entirely.
if (diagnostic.offset >= 0) {
error.setLocation(this.frontEndLocation(content, template, diagnostic.offset, diagnostic.snippet, filePath));
}
if (diagnostic.severity === 'error') {
throw error;
}
reportWarning(diagnostic.code, error, config);
}
}
/**
* Fails the build if a directive the front-end rewrites is still present.
*
* `@css`, `<@css />` and `data-ax-bind` have no meaning to either renderer:
* the IR would read `@css` as an event handler named "css" and `data-ax-bind`
* as an inert attribute, and the component would build and silently lose its
* styling or its binding. After the front-end has run none of them may remain,
* so finding one is a compiler defect and the build stops rather than emit it.
* @param {string} template - The rewritten template.
* @param {string} content - The component source.
* @param {string} filePath - The component path.
* @param {string} name - The component class name.
* @throws {TemplateValidationError} AVX_C25 when a directive survived.
*/
assertFrontEndComplete(template, content, filePath, name) {
if (typeof template !== 'string') return;
for (const token of tokenizeMarkup(template)) {
if (token.type !== 'open' || token.unterminated) continue;
let leftover = null;
if (token.name === '@css') {
leftover = 'a <@css /> tag';
} else if (token.attrs.some((attr) => attr.name === '@css')) {
leftover = 'an @css attribute';
} else if (
!token.directive &&
/^(input|textarea|select)$/i.test(token.name) &&
token.attrs.some((attr) => attr.name.toLowerCase() === 'data-ax-bind')
) {
leftover = 'a data-ax-bind attribute';
}
if (!leftover) continue;
const snippet = template.slice(token.start, token.end);
const error = new TemplateValidationError(AvenxErrorCodes.COMPILER_TEMPLATE_REWRITE_INCOMPLETE, name, leftover, snippet);
error.setLocation(this.frontEndLocation(content, template, token.start, snippet, filePath));
throw error;
}
}
/**
* Maps a template offset back to the component file where possible.
*
* Declarations are removed from the source before the template is processed,
* so a template offset is not a file offset. The tag's own text is searched
* for in the file first; when a rewrite has already changed it, the location
* falls back to the template itself.
* @param {string} content - The component source.
* @param {string} template - The template the offset refers to.
* @param {number} offset - Offset into the template.
* @param {string} snippet - The text at that offset.
* @param {string} filePath - The component path.
* @returns {{source: string, index: number, filename: string}} A location.
*/
frontEndLocation(content, template, offset, snippet, filePath) {
const index = typeof content === 'string' && snippet ? content.indexOf(snippet) : -1;
return index >= 0
? { source: content, index, filename: filePath }
: { source: template, index: offset, filename: filePath };
}
/**
* Translates common event handler attributes (@click, @input, etc.)
* to a single data-ax-event JSON-encoded attribute for centralized delegation.
* @param {string} template - The HTML template string.
* @param {string} filePath - The component file path.
* @returns {string} The transformed template string.
*/
processEventDelegation(template, filePath) {
if (!template) return template;
const customVoidTags = [...(this.customVoidTags || []), ...getCustomVoidTags(filePath)];
const nodes = parseHTML(template, customVoidTags);
const COMMON_EVENTS = ['click', 'input', 'change', 'keydown'];
const transformNode = (node) => {
if (node.type === 'element') {
const eventMap = {};
for (const [name, val] of Object.entries(node.attrs)) {
if (name.startsWith('@')) {
const fullEventName = name.substring(1);
const baseEventName = fullEventName.split('.')[0];
if (COMMON_EVENTS.includes(baseEventName)) {
delete node.attrs[name];
eventMap[fullEventName] = val;
}
}
}
if (Object.keys(eventMap).length > 0) {
node.attrs['data-ax-event'] = JSON.stringify(eventMap);
}
if (node.children) {
node.children.forEach(transformNode);
}
}
};
nodes.forEach(transformNode);
return serializeHTML(nodes, customVoidTags);
}
/**
* Processes slot elements in the template, converting dynamic props starting
* with `:` to `data-props-` attributes.
* @param {string} template - The template string.
* @returns {string} The processed template.
*/
processSlotProps(template) {
if (!template) return template;
// The tag is bounded by the shared lexer rather than by `/<slot\b([^>]*?)>/`,
// which ends a tag at the first `>` wherever it appears. Two shapes failed
// silently: `<slot name="a > b" :item="row">`, and -- the one that matters --
// `<slot :label="a > b ? x : y">`, a conditional passed to a scoped slot.
// In both, the `:prop` was never rewritten to `data-props-*`, so the slot
// received nothing and the raw directive was left in the markup.
const out = [];
let cursor = 0;
for (let i = 0; i < template.length; i++) {
if (template[i] !== '<') continue;
if (!/^<slot\b/i.test(template.slice(i, i + 6))) continue;
const end = scanTagEnd(template, i);
if (end === -1) continue;
const attrsStr = template.slice(i + '<slot'.length, end);
const replacedAttrs = attrsStr.replace(
/\s+:([\w\d.-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g,
(m, name, dquote, squote) => ` data-props-${name}="${dquote !== undefined ? dquote : squote}"`,
);
if (replacedAttrs !== attrsStr) {
out.push(template.slice(cursor, i), `<slot${replacedAttrs}>`);
cursor = end + 1;
}
i = end;
}
out.push(template.slice(cursor));
return out.join('');
}
/**
* Encodes interpolations inside `<template data-slot-props="...">` tags
* to avoid premature evaluation by the parent component.
* @param {string} template - The template string.
* @returns {string} The processed template.
*/
escapeScopedSlots(template) {
if (!template) return template;
let currentTemplate = template;
// The opening tag is located by scanning for `<template`, then bounded with
// the shared tag scanner, and only then searched for `data-slot-props`.
// Matching the whole tag with `/<template\s+[^>]*\bdata-slot-props=.../` put
// `[^>]*` before the attribute, so any earlier attribute containing a `>`
// -- `<template title="a > b" data-slot-props="row">` -- ended the match
// early and the tag was not recognised as a scoped slot at all. Its
// interpolations were then left unescaped for the parent to evaluate, which
// is exactly what this pass exists to prevent.
const startRegex = /<template\b/gi;
let match;
while ((match = startRegex.exec(currentTemplate)) !== null) {
const startIndex = match.index;
const tagEnd = scanTagEnd(currentTemplate, startIndex);
if (tagEnd === -1) break;
const openTag = currentTemplate.slice(startIndex, tagEnd + 1);
if (!/\bdata-slot-props\s*=\s*"/i.test(openTag)) {
startRegex.lastIndex = tagEnd + 1;
continue;
}
const tagOpenLength = openTag.length;
// Find the matching </template> tag by tracking depth
let searchIndex = startIndex + tagOpenLength;
let depth = 1;
let closingIndex = -1;
while (searchIndex < currentTemplate.length) {
const nextOpen = currentTemplate.substring(searchIndex).match(/^<template\b/i);
const nextClose = currentTemplate.substring(searchIndex).match(/^<\/template>/i);
if (nextClose) {
depth--;
if (depth === 0) {
closingIndex = searchIndex;
break;
}
searchIndex += nextClose[0].length;
} else if (nextOpen) {
depth++;
searchIndex += nextOpen[0].length;
} else {
searchIndex++;
}
}
if (closingIndex !== -1) {
const contentStart = startIndex + tagOpenLength;
const content = currentTemplate.substring(contentStart, closingIndex);
// Escape interpolations in the content
// [\s\S] rather than . so a multi-line expression inside a scoped slot
// is escaped as a whole instead of being left half-encoded.
const escapedContent = content
.replace(/\{\{\{\s*([\s\S]*?)\s*\}\}\}/g, (m, g) => `_AX_LBRACE3_${g}_AX_RBRACE3_`)
.replace(/\{\{\s*([\s\S]*?)\s*\}\}/g, (m, g) => `_AX_LBRACE_${g}_AX_RBRACE_`);
currentTemplate = currentTemplate.substring(0, contentStart) + escapedContent + currentTemplate.substring(closingIndex);
// Advance regex lastIndex past the modified template block
startRegex.lastIndex = contentStart + escapedContent.length + 11; // 11 is length of </template>
}
}
return currentTemplate;
}
/**
* Performs compile-time validation on template expressions to ensure
* all referenced variables and methods are declared.
* @param {string} template - The template string (after data-ax-bind translation).
* @param {object} state - The extracted state keys.
* @param {object} computed - The extracted computed keys.
* @param {object} methods - The extracted method keys.
* @param {object} [resources] - The extracted resources.
* @param {string} filePath - The component file path.
* @param {string} [name] - The component name, used for warning messages.
* @param {string[]} [bridgeLocals] - Local names of imported bridges, which are in template scope.
* @private
*/
validateTemplate(template, state, computed, methods, resources, filePath, name, bridgeLocals = []) {
const config = this.config || (filePath ? loadAvenxConfig(path.dirname(filePath)) : null);
if (!template || template.trim() === '') {
reportWarning(
AvenxErrorCodes.COMPILER_EMPTY_TEMPLATE,
new TemplateValidationError(AvenxErrorCodes.COMPILER_EMPTY_TEMPLATE, name),
config,
);
}
const declared = new Set([
...Object.keys(state),
...Object.keys(computed),
...Object.keys(methods),
...Object.keys(resources || {}),
...bridgeLocals,
// Names a plugin puts into every component's scope through app.mixin().
// The compiler cannot see a runtime installation, so the project declares
// them once in avenx.config.json — `@avenx/i18n`, for instance, publishes
// t, tHtml, n, d, rel, locale and $i18n.
...((config && config.templateGlobals) || []),
]);
// Loop bindings. The header is read with the same parser the IR uses, so
// the validator and the compiler agree about what a loop declares -- a
// regex here disagreed with the IR about `[a, b] in pairs` and about any
// list expression containing a `>`.
for (const node of parseHTML(template, [...(this.customVoidTags || []), ...getCustomVoidTags(filePath)])) {
collectLoopBindings(node, declared);
}
const slotPropsRegex = /data-slot-props="([^"]*)"/gi;
let slotPropsMatch;
while ((slotPropsMatch = slotPropsRegex.exec(template)) !== null) {
declared.add(slotPropsMatch[1].trim());
}
const EXCLUDED_IDENTIFIERS = new Set([
'true',
'false',
'null',
'undefined',
'NaN',
'Infinity',
'this',
'let',
'const',
'var',
'function',
'return',
'if',
'else',
'for',
'in',
'of',
'new',
'typeof',
'instanceof',
'class',
'extends',
'try',
'catch',
'finally',
'throw',
'await',
'async',
'import',
'export',
'default',
'delete',
'void',
'do',
'while',
'switch',
'case',
'break',
'continue',
'debugger',
'yield',
'with',
'arguments',
'console',
'Math',
'JSON',
'window',
'document',
'Array',
'Object',
'String',
'Number',
'Boolean',
'Date',
'Error',
'Map',
'Set',
'Promise',
'props',
'styles',
'event',
'args',
]);
this.reportUnterminatedInterpolations(template, filePath, name, config);
const events = collectTemplateEvents(template);
const currentLoopVars = [];
const seenIds = new Set();
let loopDepth = 0;
const filename = path.basename(filePath);
const checkIdentifiers = (expr, eventIndex = -1) => {
const ids = this.extractRootIdentifiers(expr);
for (const id of ids) {
if (EXCLUDED_IDENTIFIERS.has(id)) {
continue;
}
if (currentLoopVars.includes(id)) {
continue;
}
if (!declared.has(id)) {
const idx = eventIndex >= 0 ? eventIndex : template.indexOf(expr);
const err = new TemplateValidationError(AvenxErrorCodes.COMPILER_UNDECLARED_REFERENCE, id, filename);
if (idx >= 0) {
err.setLocation({ source: template, index: idx, filename, length: id.length });
}
reportWarning(
AvenxErrorCodes.COMPILER_UNDECLARED_REFERENCE,
err,
config,
);
}
}
};
for (const ev of events) {
if (ev.type === 'loop_start') {
checkIdentifiers(ev.list, ev.index);
currentLoopVars.push(ev.item);
loopDepth++;
} else if (ev.type === 'loop_end') {
currentLoopVars.pop();
loopDepth = Math.max(0, loopDepth - 1);
} else if (ev.type === 'id_attribute') {
if (seenIds.has(ev.idValue) || loopDepth > 0) {
const idx = ev.index >= 0 ? ev.index : template.indexOf(`id="${ev.idValue}"`);
const err = new TemplateValidationError(
AvenxErrorCodes.COMPILER_DUPLICATE_ID_ATTRIBUTE,
ev.idValue,
name || filename,
);
if (idx >= 0) {
err.setLocation({ source: template, index: idx, filename });
}
reportWarning(
AvenxErrorCodes.COMPILER_DUPLICATE_ID_ATTRIBUTE,
err,
config,
);
}
seenIds.add(ev.idValue);
} else if (
ev.type === 'interpolation' ||
ev.type === 'event' ||
ev.type === 'directive' ||
ev.type === 'condition'
) {
// 'condition' is the <@if>/<@elseif> header. It was never collected, so
// a typo in a condition compiled silently and failed in the browser.
checkIdentifiers(ev.expr, ev.index);
}
}
this.validateComponentTags(template, filePath, name, config);
}
/**
* Reports an interpolation that is opened and never closed (AVX_W54).
*
* An unterminated `{{` is not a parse failure: the lexer treats the braces as
* ordinary text, so the template compiles, the build exits 0, and the page
* shows the braces and the expression source to a visitor. Forgetting one
* `}}` therefore looked exactly like working code until someone loaded the
* page, and the misread state was reported a second time -- as AVX_W40,
* claiming the state the broken interpolation meant to read is read nowhere.
*
* A warning rather than an error, because a template may legitimately contain
* literal `{{` in prose, and refusing to build such a template would be worse
* than describing it.
* @param {string} template - The template being validated.
* @param {string} filePath - Absolute path of the file being compiled.
* @param {string} name - The component or page name, for the diagnostic.
* @param {object|null} config - Resolved project configuration.
* @returns {void}
* @private
*/
reportUnterminatedInterpolations(template, filePath, name, config) {
if (!template) return;
const filename = filePath ? path.basename(filePath) : (name || 'template');
for (let index = template.indexOf('{{'); index !== -1; index = template.indexOf('{{', index + 2)) {
const end = interpolationEnd(template, index);
if (end !== -1) {
// Terminated: skip past it, so a `{{` inside a closed interpolation's
// body is not examined on its own.
index = end - 2;
continue;
}
const excerpt = template.slice(index, index + 40).split('\n')[0];
// The file, not the component name: the phrasing "in template of <file>"
// is what `avenx check --json` reads a location out of, and it is what
// AVX_W03 already uses for the same kind of finding.
const err = new TemplateValidationError(
AvenxErrorCodes.COMPILER_UNTERMINATED_INTERPOLATION,
filename,
JSON.stringify(excerpt),
);
err.setLocation({ source: template, index, filename });
reportWarning(AvenxErrorCodes.COMPILER_UNTERMINATED_INTERPOLATION, err, config);
}
}
/**
* Reports PascalCase template tags that resolve to no registered component,
* built-in tag, or known HTML/SVG element (AVX_W46).
*
* A misspelled or unimported component name is the most common template
* mistake and, unlike an undeclared identifier, it currently escapes every
* compile-time check — it surfaces only at runtime as AVX_R03 (or AVX_W13
* inside a page). This walks the parsed node tree the other passes use, so no
* new parse is added, and reports each unresolved tag with the file, the
* line, the tag and the closest registered name when one is near enough.
*
* It is a warning, not an error: a component may legitimately be registered
* at runtime through `app.register()`, which the compiler cannot see. The
* check is skipped entirely when the registry is empty (a component parsed
* standalone), so it never fires on a project the compiler did not scan whole.
* @param {string} template - The processed template HTML.
* @param {string} filePath - Absolute path of the file being compiled.
* @param {string} name - The component/page name, for the diagnostic.
* @param {object|null} config - Resolved project configuration.
* @returns {void}
* @private
*/
validateComponentTags(template, filePath, name, config) {
if (!this.__componentNames || this.__componentNames.size === 0) {
return;
}
if (!template || template.trim() === '') {
return;
}
const filename = filePath ? path.basename(filePath) : (name || 'template');
// The project's void tags share the identifier check's escape hatch: a tag
// the project has declared as its own element is never reported as an
// unresolved component, whatever its casing.
const customVoidTags = [...(this.customVoidTags || []), ...getCustomVoidTags(filePath)];
const voidTagSet = new Set(customVoidTags.map((t) => String(t).toLowerCase()));
let nodes;
try {
nodes = parseHTML(template, customVoidTags);
} catch {
// A template that will not even parse is a different problem, reported by
// the passes that transform it. This check simply steps aside.
return;
}
const isPascalCase = (tag) => /^[A-Z][A-Za-z0-9]*$/.test(tag);
const walk = (list) => {
for (const node of list) {
if (node && node.type === 'element' && typeof node.tagName === 'string') {
const tag = node.tagName;
// A dash marks a Web Component custom element; the framework never
// owns it, so it is never flagged (matches the identifier check's
// escape hatch).
const isCustomElement = tag.includes('-');
// `<Component is="...">` is the dynamic-component built-in.
const isDynamic = tag === 'Component';
if (
isPascalCase(tag) &&
!isCustomElement &&
!isDynamic &&
!tag.startsWith('@') &&
!BUILTIN_TAGS.has(tag.toLowerCase()) &&
!KNOWN_ELEMENTS.has(tag.toLowerCase()) &&
!voidTagSet.has(tag.toLowerCase()) &&
!this.__componentNames.has(tag)
) {
const suggestion = getClosestKey(tag, [...this.__componentNames]);
const hint = suggestion ? `\n\nDid you mean "<${suggestion}>"?` : '';
const err = new TemplateValidationError(
AvenxErrorCodes.COMPILER_UNRESOLVED_COMPONENT_REFERENCE,
tag,
filename,
hint,
);
if (node.line) {
err.setLocation({
source: template,
line: node.line,
column: node.column || 1,
filename,
length: tag.length,
});
}
reportWarning(
AvenxErrorCodes.COMPILER_UNRESOLVED_COMPONENT_REFERENCE,
err,
config,
);
}
}
if (node && Array.isArray(node.children) && node.children.length > 0) {
walk(node.children);
}
}
};
walk(nodes);
}
/**
* Extracts root variable and method identifiers from a JS expression string.
* @param {string} code - The Javascript expression/statement.
* @returns {string[]} The list of root identifiers.
* @private
*/
extractRootIdentifiers(code) {
const identifiers = new Set();
let i = 0;
let hasQuestionMark = false;
while (i < code.length) {
const char = code[i];
if (char === '/' && code[i + 1] === '/') {
i += 2;
while (i < code.length && code[i] !== '\n') i++;
continue;
}
if (char === '/' && code[i + 1] === '*') {
i += 2;
while (i < code.length && !(code[i] === '*' && code[i + 1] === '/')) i++;
i += 2;
continue;
}
if (char === "'") {
i++;
while (i < code.length && code[i] !== "'") {
if (code[i] === '\\') i++;
i++;
}
i++;
continue;
}
if (char === '"') {
i++;
while (i < code.length && code[i] !== '"') {
if (code[i] === '\\') i++;
i++;
}
i++;
continue;
}
if (char === '`') {
i++;
while (i < code.length && code[i] !== '`') {
if (code[i] === '\\') i++;
if (code[i] === '$' && code[i + 1] === '{') {
let depth = 1;
let j = i + 2;
while (j < code.length && depth > 0) {
if (code[j] === '{') depth++;
else if (code[j] === '}') depth--;
j++;
}
const subExpr = code.substring(i + 2, j - 1);
this.extractRootIdentifiers(subExpr).forEach((id) => identifiers.add(id));
i = j - 1;
}
i++;
}
i++;
continue;
}
const idRegex = /^[A-Za-z_$][\w$]*/;
const sub = code.substring(i);
const match = sub.match(idRegex);
if (match) {
const name = match[0];
let isProperty = false;
let checkIdx = i - 1;
while (checkIdx >= 0 && /\s/.test(code[checkIdx])) {
checkIdx--;
}
if (checkIdx >= 0 && code[checkIdx] === '.') {
isProperty = true;
} else if (checkIdx >= 1 && code[checkIdx] === '.' && code[checkIdx - 1] === '?') {
isProperty = true;
}
let nextIdx = i + name.length;
while (nextIdx < code.length && /\s/.test(code[nextIdx])) {
nextIdx++;
}
let isObjectKey = false;
if (nextIdx < code.length && code[nextIdx] === ':') {
if (!hasQuestionMark) {
isObjectKey = true;
} else {
hasQuestionMark = false;
}
}
if (!isProperty && !isObjectKey) {
identifiers.add(name);
}
i += name.length;
continue;
}
if (char === '?') {
if (code[i + 1] === '.') {
i += 2;
continue;
}
hasQuestionMark = true;
}
if (char === ';' || char === ',' || char === '{' || char === '(' || char === '[') {
hasQuestionMark = false;
}
i++;
}
// An arrow function's parameters are bound by the arrow, not by the
// component. `rows.filter(r => r.done)` declares `r`, and reporting it as
// undeclared is a warning on correct code -- which is worse than no
// warning, because it teaches people to ignore the category.
//
// Previously invisible: a `<@for>` header containing an arrow never reached
// this function intact, because the header was truncated at the arrow
// before it got here.
for (const name of arrowParameters(code)) {
identifiers.delete(name);
}
return Array.from(identifiers);
}
/**
* Processes data-ax-bind attributes on input, textarea, and select elements.
* Converts data-ax-bind="expr" to value="{{ expr }}" and event listener.
* @param {string} template - The template string.
* @returns {string} The processed template.
*/
processBindDirectives(template) {
return processBindDirectives(template);
}
/**
* Processes <@for> loops in the template, converting them to <template> tags
* that can be handled by the runtime for efficient list rendering.
* @param {string} template - The HTML template string.
* @returns {string} The processed template.
* @private
*/
processForLoops(template) {
let currentTemplate = template;
while (true) {
const tagRegex = /(<@for\b)|(<\/ ?@for>)|(<@empty>)/gi;
let match;
const tags = [];
while ((match = tagRegex.exec(currentTemplate)) !== null) {
if (match[1]) {
// The header is scanned and parsed by the same code the IR uses.
// This loop used to carry its own pattern for it, and the two
// disagreed: `([^>]+?)` ends the header at the first `>`, so
// `<@for r in rows.filter(x => x.n > 2)>` was truncated to
// `rows.filter(x =` and reported as a malformed expression. One
// parser means the fallback template and the compiled program
// describe the same loop.
const end = scanTagEnd(currentTemplate, match.index);
if (end === -1) break;
const header = currentTemplate.slice(match.index + '<@for'.length, end).trim();
let parts;
try {
parts = parseForHeader(header);
} catch {
// Reported by the IR builder with a location and a reason; a
// second, vaguer complaint from here would not help.
tagRegex.lastIndex = end + 1;
continue;
}
tags.push({
type: 'start',
index: match.index,
length: end + 1 - match.index,
item: parts.destructure ? `[${parts.destructure.join(', ')}]` : parts.item,
list: parts.list,
key: parts.key,
});
tagRegex.lastIndex = end + 1;
} else if (match[2]) {
tags.push({
type: 'end',
index: match.index,
length: match[0].length,
});
} else if (match[3]) {
tags.push({
type: 'empty',
index: match.index,
length: match[0].length,
});
}
}
if (tags.length === 0) {
break;
}
let innerPair = null;
let innerEmpty = null;
const stack = [];
const emptyStack = [];
for (let i = 0; i < tags.length; i++) {
const tag = tags[i];
if (tag.type === 'start') {
stack.push(tag);
emptyStack.push(null);
} else if (tag.type === 'empty') {
if (emptyStack.length > 0) {
emptyStack[emptyStack.length - 1] = tag;
}
} else {
const startTag = stack.pop();
const emptyTag = emptyStack.pop();
if (startTag) {
innerPair = { start: startTag, end: tag };
innerEmpty = emptyTag;
break; // Found innermost loop!
}
}
}
if (!innerPair) {
const unmatchedIdx = (stack.length > 0 && stack[0].index !== undefined) ? stack[0].index : currentTemplate.indexOf('<@for');
const err = new TemplateValidationError(AvenxErrorCodes.COMPILER_UNMATCHED_FOR_TAG);
if (unmatchedIdx >= 0) {
err.setLocation({ source: currentTemplate, index: unmatchedIdx });
}
logger.warn(err.message);
break;
}
const startIdx = innerPair.start.index;
const endIdx = innerPair.end.index + innerPair.end.length;
let body, emptyBody = '';
const bodyStart = startIdx + innerPair.start.length;
const bodyEnd = innerPair.end.index;
if (innerEmpty) {
body = currentTemplate.substring(bodyStart, innerEmpty.index);
emptyBody = currentTemplate.substring(innerEmpty.index + innerEmpty.length, bodyEnd);
} else {
body = currentTemplate.substring(bodyStart, bodyEnd);
}
// Escape inner interpolation tags to prevent them from being processed
// by the initial template render. They will be processed per-item at runtime.
const escapedBody = escapeTemplateMarkers(body);
let attrs = `data-ax-for="${innerPair.start.list.trim()}" data-ax-as="${innerPair.start.item.trim()}"`;
if (innerPair.start.key) {
attrs += ` data-ax-key="${innerPair.start.key.trim()}"`;
}
let replacement = `<template ${attrs}>${escapedBody}</template>`;
if (innerEmpty) {
const escapedEmptyBody = escapeTemplateMarkers(emptyBody);
replacement += `<template data-ax-empty>${escapedEmptyBody}</template>`;
}
currentTemplate = currentTemplate.substring(0, startIdx) + replacement + currentTemplate.substring(endIdx);
}
return currentTemplate;
}
/**
* Processes <@suspense> tags, converting them to DOM markers.
* @param {string} template - The template string.
* @returns {string} The processed template.
* @private
*/
processSuspense(template) {
let currentTemplate = template;
while (true) {
const match = currentTemplate.match(/<@suspense>([\s\S]*?)<\/ ?@suspense>/i);
if (!match) break;
const fullMatch = match[0];
const inner = match[1];
// Extract <@fallback>
let fallbackContent = '';
let suspenseContent = inner;
const fallbackMatch = inner.match(/<@fallback>([\s\S]*?)<\/ ?@fallback>/i);
if (fallbackMatch) {
fallbackContent = escapeTemplateMarkers(fallbackMatch[1]); // Escape fallback template logic
suspenseContent = inner.replace(fallbackMatch[0], '');
}
const replacement = `<div data-ax-suspense="true"><template data-ax-fallback>${fallbackContent}</template>${suspenseContent}</div>`;
currentTemplate = currentTemplate.replace(fullMatch, replacement);
}
return currentTemplate;
}
/**
* Processes <@errorBoundary> tags, converting them to DOM markers.
* @param {string} template - The template string.
* @returns {string} The processed template.
* @private
*/
processErrorBoundary(template) {
let currentTemplate = template;
while (true) {
const match = currentTemplate.match(/<@errorBoundary>([\s\S]*?)<\/ ?@errorBoundary>/i);
if (!match) break;
const fullMatch = match[0];
const inner = match[1];
// Extract <@fallback as="...">
let fallbackContent = '';
let errorAs = 'error';
let boundaryContent = inner;
const fallbackMatch = inner.match(/<@fallback(?:\s+as="([^"]*)")?>([\s\S]*?)<\/ ?@fallback>/i);
if (fallbackMatch) {
errorAs = fallbackMatch[1] || 'error';
fallbackContent = escapeTemplateMarkers(fallbackMatch[2]); // Escape fallback logic
boundaryContent = inner.replace(fallbackMatch[0], '');
}
const replacement = `<div data-ax-error-boundary="true" data-ax-error-as="${errorAs}"><template data-ax-error-fallback><div class="ax-error-boundary">${fallbackContent}</div></template>${boundaryContent}</div>`;
currentTemplate = currentTemplate.replace(fullMatch, replacement);
}
return currentTemplate;
}
/**
* Processes <@deadlock> tags, converting them to DOM boundary markers.
* Supports attributes: name="...", maxDepth="...", action="abort|fallback|throw", isolated="true|false",
* and optional inner <@fallback as="..."> tags for error recovery.
* @param {string} template - The template string.
* @param {string} [filePath] - The component file path for source location tracking.
* @returns {string} The processed template.
* @private
*/
processDeadlock(template, filePath = '') {
let currentTemplate = template;
const deadlockRegex = /<@deadlock\b([^>]*)>((?:(?!<@deadlock\b)[\s\S])*?)<\/ ?@deadlock>/i;
while (true) {
const match = currentTemplate.match(deadlockRegex);
if (!match) break;
const fullMatch = match[0];
const attrsStr = match[1] || '';
const inner = match[2];
const nameMatch = attrsStr.match(/\bname=["']([^"']*)["']/i);
const name = nameMatch ? nameMatch[1].trim() : 'anonymous';
const depthMatch = attrsStr.match(/\bmaxDepth=["']([^"']*)["']/i);
const depthAttr = depthMatch ? ` data-ax-deadlock-depth="${depthMatch[1].trim()}"` : '';
const actionMatch = attrsStr.match(/\baction=["']([^"']*)["']/i);
const actionAttr = actionMatch ? ` data-ax-deadlock-action="${actionMatch[1].trim().toLowerCase()}"` : '';
const isolatedMatch = attrsStr.match(/\bisolated=["']([^"']*)["']/i);
const isolatedAttr = isolatedMatch ? ` data-ax-deadlock-isolated="${isolatedMatch[1].trim().toLowerCase()}"` : '';
// Compute location if possible
let locAttr = '';
if (filePath) {
const matchIdx = currentTemplate.indexOf(fullMatch);
if (matchIdx !== -1) {
const pos = getLineAndColumn(currentTemplate, matchIdx);
locAttr = ` data-ax-deadlock-loc="${filePath}:${pos.line}:${pos.column}"`;
}
}
// Extract <@fallback as="...">
let fallbackContent = '';
let errorAs = 'error';
let boundaryContent = inner;
const fallbackMatch = inner.match(/<@fallback(?:\s+as="([^"]*)")?>([\s\S]*?)<\/ ?@fallback>/i);
if (fallbackMatch) {
errorAs = fallbackMatch[1] || 'error';
fallbackContent = escapeTemplateMarkers(fallbackMatch[2]);
boundaryContent = inner.replace(fallbackMatch[0], '');
}
const fallbackTpl = fallbackMatch
? `<template data-ax-deadlock-fallback="true" data-ax-error-as="${errorAs}"><div class="ax-deadlock-fallback">${fallbackContent}</div></template>`
: '';
const replacement = `<div data-ax-deadlock="true" data-ax-deadlock-name="${name}"${depthAttr}${actionAttr}${isolatedAttr}${locAttr}>${fallbackTpl}${boundaryContent}</div>`;
currentTemplate = currentTemplate.replace(fullMatch, replacement);
}
return currentTemplate;
}
/**
* Processes <@defer> tags, converting them to DOM markers with templates for deferred loading.
* Supports triggers via when="<trigger>" (idle, visible, interaction, timer, expression)
* and optional <@placeholder> and <@loading> sub-tags.
* @param {string} template - The template string.
* @returns {string} The processed template.
* @private
*/
processDefer(template) {
let currentTemplate = template;
while (true) {
const match = currentTemplate.match(/<@defer(?:\s+when=["']([^"']*)["'])?\s*>([\s\S]*?)<\/ ?@defer>/i);
if (!match) break;
const fullMatch = match[0];
const whenCondition = (match[1] || 'idle').trim();
const inner = match[2];
let placeholderContent = '';
let loadingContent = '';
let deferredContent = inner;
const placeholderMatch = inner.match(/<@placeholder>([\s\S]*?)<\/ ?@placeholder>/i);
if (placeholderMatch) {
placeholderContent = escapeTemplateMarkers(placeholderMatch[1]).trim();
deferredContent = deferredContent.replace(placeholderMatch[0], '');
}
const loadingMatch = inner.match(/<@loading>([\s\S]*?)<\/ ?@loading>/i);
if (loadingMatch) {
loadingContent = escapeTemplateMarkers(loadingMatch[1]).trim();
deferredContent = deferredContent.replace(loadingMatch[0], '');
}
deferredContent = escapeTemplateMarkers(deferredContent).trim();
const placeholderTpl = placeholderContent ? `<template data-ax-defer-placeholder>${placeholderContent}</template>` : '';
const loadingTpl = loadingContent ? `<template data-ax-defer-loading>${loadingContent}</template>` : '';
const contentTpl = `<template data-ax-defer-content>${deferredContent}</template>`;
const replacement = `<div data-ax-defer="true" data-ax-defer-when="${whenCondition}">${placeholderTpl}${loadingTpl}${contentTpl}</div>`;
currentTemplate = currentTemplate.replace(fullMatch, replacement);
}
return currentTemplate;
}
/**
* Processes component tags recursively to handle transclusion slots.
* Maps `<CompName ...>...</CompName>` to `<div data-avenx-comp="CompName">...</div>`.
* @param {string} template - The template string.
* @returns {string} The processed template.
*/
processComponentTags(template) {
let currentTemplate = template;
currentTemplate = this.processSlotProps(currentTemplate);
currentTemplate = this.escapeScopedSlots(currentTemplate);
while (true) {
// Find the first occurrence of < followed by an uppercase letter
const match = currentTemplate.match(/<([A-Z][a-zA-Z0-9]*)\b/);
if (!match) {
break;
}
const compName = match[1];
const startIndex = match.index;
// Find the end of this opening/self-closing tag
let i = startIndex + 1 + compName.length;
let inQuote = null;
let isSelfClosing = false;
let tagEndIndex = -1;
while (i < currentTemplate.length) {
const char = currentTemplate[i];
if (inQuote) {
if (char === inQuote) {
inQuote = null;
}
} else if (char === '"' || char === "'") {
inQuote = char;
} else if (char === '>') {
const trimmedBefore = currentTemplate.substring(startIndex + 1 + compName.length, i).trim();
if (trimmedBefore.endsWith('/')) {
isSelfClosing = true;
}
tagEndIndex = i + 1;
break;
}
i++;
}
if (tagEndIndex === -1) {
break; // Malformed tag, stop parsing to prevent infinite loops
}
// Extract the attributes string
let attrsStr = currentTemplate.substring(startIndex + 1 + compName.length, tagEndIndex - 1).trim();
if (isSelfClosing && attrsStr.endsWith('/')) {
attrsStr = attrsStr.slice(0, -1).trim();
}
let isExpr = '';
const isDynamic = compName === 'Component';
// Parse attributes
const props = [];
const others = [];
const attrs = parseAttributes(attrsStr);
for (const [attrName, attrVal] of Object.entries(attrs)) {
if (isDynamic && (attrName === 'is' || attrName === ':is')) {
if (attrVal.startsWith('{{') && attrVal.endsWith('}}')) {
isExpr = attrVal.slice(2, -2).trim();
} else {
isExpr = attrVal.trim();
}
} else if (attrName.startsWith('@')) {
others.push(`${attrName}="${attrVal.replace(/"/g, '"')}"`);
} else {
let propExpr;
if (attrVal.startsWith('{{') && attrVal.endsWith('}}')) {
propExpr = attrVal.slice(2, -2).trim();
} else {
const trimmed = attrVal.trim();
if (
trimmed === 'true' ||
trimmed === 'false' ||
trimmed === 'null' ||
(trimmed !== '' && !isNaN(trimmed))
) {
propExpr = trimmed;
} else {
propExpr = `'${trimmed.replace(/'/g, "\\'")}'`;
}
}
props.push(`data-props-${attrName}="${propExpr}"`);
}
}
const propsAttr = props.length > 0 ? ` ${props.join(' ')}` : '';
const othersAttr = others.length > 0 ? ` ${others.join(' ')}` : '';
const replacementTag = isDynamic ? `data-avenx-comp-dynamic="${isExpr}"` : `data-avenx-comp="${compName}"`;
if (isSelfClosing) {
const replacement = `<div ${replacementTag}${propsAttr}${othersAttr}></div>`;
currentTemplate =
currentTemplate.substring(0, startIndex) + replacement + currentTemplate.substring(tagEndIndex);
} else {
// Find matching closing tag </CompName>
let searchIndex = tagEndIndex;
let depth = 1;
let closingTagIndex = -1;
let closingTagLength = 0;
while (searchIndex < currentTemplate.length) {
const nextOpen = currentTemplate.substring(searchIndex).match(new RegExp(`^<${compName}\\b`));
const nextClose = currentTemplate.substring(searchIndex).match(new RegExp(`^</\\s*${compName}\\s*>`));
if (nextClose) {
depth--;
if (depth === 0) {
closingTagIndex = searchIndex;
closingTagLength = nextClose[0].length;
break;
}
searchIndex += nextClose[0].length;
} else if (nextOpen) {
// Scan to end of this open tag to see if it is self-closing
let tempIdx = searchIndex + nextOpen[0].length;
let tempInQuote = null;
let tempIsSelfClosing = false;
while (tempIdx < currentTemplate.length) {
const tc = currentTemplate[tempIdx];
if (tempInQuote) {
if (tc === tempInQuote) tempInQuote = null;
} else if (tc === '"' || tc === "'") {
tempInQuote = tc;
} else if (tc === '>') {
const trimmedBefore = currentTemplate.substring(searchIndex + nextOpen[0].length, tempIdx).trim();
if (trimmedBefore.endsWith('/')) {
tempIsSelfClosing = true;
}
tempIdx++;
break;
}
tempIdx++;
}
if (!tempIsSelfClosing) {
depth++;
}
searchIndex = tempIdx;
} else {
searchIndex++;
}
}
if (closingTagIndex === -1) {
// No matching closing tag, treat as self-closing
const replacement = `<div ${replacementTag}${propsAttr}${othersAttr}></div>`;
currentTemplate =
currentTemplate.substring(0, startIndex) + replacement + currentTemplate.substring(tagEndIndex);
} else {
const innerContent = currentTemplate.substring(tagEndIndex, closingTagIndex);
// Recursively process tags inside innerContent
const processedInner = this.processComponentTags(innerContent);
const replacement = `<div ${replacementTag}${propsAttr}${othersAttr}>${processedInner}</div>`;
currentTemplate =
currentTemplate.substring(0, startIndex) +
replacement +
currentTemplate.substring(closingTagIndex + closingTagLength);
}
}
}
return currentTemplate;
}
/**
* Processes transition tags in the template, converting them to data-ax-transition attributes.
* @param {string} template - The HTML template string.
* @param {string} [filePath] - The component file path, used to resolve project-specific
* void tags from `avenx.config.json` (see {@link getCustomVoidTags}).
* @returns {string} The processed template.
*/
processTransitionTags(template, filePath) {
try {
const customVoidTags = [...(this.customVoidTags || []), ...getCustomVoidTags(filePath)];
const nodes = parseHTML(template, customVoidTags);
const processed = this.processTransitionTagsInTree(nodes);
return serializeHTML(processed, customVoidTags);
} catch (err) {
logger.warn(new TemplateValidationError(AvenxErrorCodes.COMPILER_TRANSITION_PARSE_FAILED, err).message);
return template;
}
}
/**
* Recursively processes transition tags in the node tree.
* @param {HTMLNode[]} nodes
* @returns {HTMLNode[]}
*/
processTransitionTagsInTree(nodes) {
const result = [];
for (const node of nodes) {
if (node.type === 'element') {
if (node.tagName.toLowerCase() === 'transition') {
const nameAttr = node.attrs['name'];
let transitionValue = "'ax'";
if (nameAttr) {
if (nameAttr.startsWith('{{') && nameAttr.endsWith('}}')) {
transitionValue = nameAttr.slice(2, -2).trim();
} else {
transitionValue = `'${nameAttr.replace(/'/g, "\\'")}'`;
}
}
const processedChildren = this.processTransitionTagsInTree(node.children);
for (const child of processedChildren) {
if (child.type === 'element') {
child.attrs['data-ax-transition'] = transitionValue;
}
result.push(child);
}
} else {
node.children = this.processTransitionTagsInTree(node.children);
result.push(node);
}
} else {
result.push(node);
}
}
return result;
}
/**
* Identifies static elements/subtrees and marks them with data-ax-static="true".
* @param {string} template - The compiled HTML template.
* @param {string} [filePath] - The component file path, used to resolve project-specific
* void tags from `avenx.config.json` (see {@link getCustomVoidTags}).
* @returns {string} The optimized template.
*/
optimizeStaticSubtrees(template, filePath) {
try {
const customVoidTags = [...(this.customVoidTags || []), ...getCustomVoidTags(filePath)];
const nodes = parseHTML(template, customVoidTags);
this.markStaticNodes(nodes, false);
return serializeHTML(nodes, customVoidTags);
} catch (err) {
logger.warn(new TemplateValidationError(AvenxErrorCodes.COMPILER_STATIC_SUBTREE_OPTIMIZATION_FAILED, err).message);
return template;
}
}
/**
* Recursively traverses nodes to find and mark the root of static subtrees.
* @param {HTMLNode[]} nodes
* @param {boolean} [parentIsStatic]
* @param {boolean} [inSlot] - Indicates if the current node is inside a slot or component transclusion boundary.
*/
markStaticNodes(nodes, parentIsStatic = false, inSlot = false) {
for (const node of nodes) {
if (node.type === 'element') {
const lowerTag = node.tagName.toLowerCase();
const isSlot = lowerTag === 'slot';
const isComponent = Boolean(
node.attrs['data-avenx-comp'] || node.attrs['data-ax-comp'] || /^[A-Z]/.test(node.tagName)
);
const currentInSlot = inSlot || isSlot || isComponent;
const hasStaticContract = node.contracts && node.contracts.has('static');
const nodeStatic = !currentInSlot && (hasStaticContract || isStaticNode(node));
// Convert contract block directives to div wrappers with respective data attributes
if (lowerTag === '@static') {
node.tagName = 'div';
node.attrs['data-ax-static'] = 'true';
} else if (lowerTag === '@isolated') {
node.tagName = 'div';
node.attrs['data-ax-isolated'] = 'true';
} else if (lowerTag === '@pure') {
node.tagName = 'div';
node.attrs['data-ax-pure'] = 'true';
} else if (lowerTag === '@deterministic') {
node.tagName = 'div';
node.attrs['data-ax-deterministic'] = 'true';
}
// Clean up raw contract attributes from DOM element output
if (node.attrs) {
if (node.attrs['static'] !== undefined) delete node.attrs['static'];
if (node.attrs['pure'] !== undefined) delete node.attrs['pure'];
if (node.attrs['deterministic'] !== undefined) delete node.attrs['deterministic'];
if (node.attrs['isolated'] !== undefined) delete node.attrs['isolated'];
}
if (node.contracts && node.contracts.has('pure') && node.contracts.has('deterministic') && !nodeStatic) {
node.attrs['data-ax-memo'] = 'true';
}
if (nodeStatic && !parentIsStatic) {
node.attrs['data-ax-static'] = 'true';
}
this.markStaticNodes(node.children, nodeStatic, currentInSlot);
}
}
}
}
/**
* Parses an HTML string into a tree of HTMLNode elements.
* @param {string} html
* @param {string[]} [customVoidTags] - Additional project-specific void tag
* names (lowercase), loaded from `avenx.config.json`. Merged on top of
* {@link DEFAULT_VOID_TAGS}. Regardless of this list, any tag that is
* written with a self-closing slash (e.g. `<my-video />`) is always
* treated as void so it never requires a matching closing tag.
* @returns {HTMLNode[]}
*/
/**
* Recursively checks whether a node is a <slot> tag, or has a <slot>
* anywhere among its descendants. Used to disqualify a subtree from the
* static-optimization pass, since slots are dynamic transclusion points
* that DomPatcher must always be able to patch (see issue #200).
* @param {HTMLNode} node
* @returns {boolean}
*/
function containsSlot(node) {
if (node.type !== 'element') {
return false;
}
if (node.tagName.toLowerCase() === 'slot') {
return true;
}
return node.children.some((child) => containsSlot(child));
}
/**
* Recursively determines if a node (and all its descendants) are completely static.
* @param {HTMLNode} node
* @returns {boolean}
*/
function isStaticNode(node) {
if (node.type === 'text') {
if (node.content.includes('{{') || node.content.includes('{%')) {
return false;
}
return true;
}
if (node.type === 'comment') {
return true;
}
if (node.type === 'element') {
const lowerTag = node.tagName.toLowerCase();
if (lowerTag === 'template' || lowerTag === 'slot') {
return false;
}
// A directive is control flow, and control flow is never static however
// little its body interpolates. `<@defer>` with literal content reads as
// static to every other test here -- no `{{ }}`, no component tag, no
// bound attribute -- and marking it so told the render compiler to emit
// the subtree verbatim, which would have rendered the deferred content
// immediately and dropped the trigger.
if (lowerTag.startsWith('@')) {
return false;
}
// A wrapper that contains a <slot> anywhere beneath it must never be
// marked static: slot content is transcluded dynamically per-instance,
// so a static-tagged ancestor would cause DomPatcher to skip patching
// it entirely and slot updates would be silently dropped.
if (containsSlot(node)) {
return false;
}
if (/^[A-Z]/.test(node.tagName)) {
return false;
}
for (const [name, val] of Object.entries(node.attrs)) {
if (name.startsWith('@') || name.startsWith(':[')) {
return false;
}
if ((name.startsWith('data-ax-') && name !== 'data-ax-static') || name.startsWith('data-avenx-')) {
return false;
}
if (val && (val.includes('{{') || val.includes('{%'))) {
return false;
}
}
for (const child of node.children) {
if (!isStaticNode(child)) {
return false;
}
}
return true;
}
return false;
}
ComponentParser.parseHTML = parseHTML;
export default ComponentParser;
|