microsoft-webui 3.0.3

Programmatic API for the WebUI build-time rendering framework
Documentation
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
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

//! Programmatic API for the WebUI build-time rendering framework.
//!
//! This crate provides the core build, render, and inspection APIs
//! that power the `webui` CLI, Node.js bindings, and WASM module.
//!
//! # Example
//!
//! ```rust,no_run
//! use webui::{build, BuildOptions};
//! use std::path::PathBuf;
//!
//! let result = build(BuildOptions {
//!     app_dir: PathBuf::from("./src"),
//!     ..BuildOptions::default()
//! }).unwrap();
//!
//! println!("Built {} fragments in {:?}", result.stats.fragment_count, result.stats.duration);
//! ```

mod chunking;
pub mod component_asset_output;
mod component_assets;
mod error;
mod module_preload;
mod projection;
pub mod server;
pub mod streaming;
mod style_bundle;

pub use component_assets::{render_component_assets, ComponentAssetFile, ComponentAssetGraph};
pub use error::WebUIError;

// Re-export core types from downstream crates
pub use webui_handler::route_handler::{encode_inventory, get_needed_components, parse_inventory};
pub use webui_handler::Result as HandlerResult;
pub use webui_handler::{
    plugin::HandlerPlugin, BoundaryDescriptor, BoundaryInstanceId, BoundaryKey, BoundaryMode,
    FlushWriter, HandlerError, Protocol, RenderOptions, ResponseWriter, SessionOptions,
    SpanInstanceId, StreamStatus, StreamStep, StreamingResponse, StreamingSession, StreamingState,
    WebUIHandler,
};
pub use webui_parser::plugin::{ComponentTemplateArtifact, StateSurface};
pub use webui_parser::CssStrategy;
pub use webui_parser::DomStrategy;
pub use webui_parser::LegalComments;
pub use webui_parser::ParserError;
pub use webui_parser::ParserOptions;
pub use webui_parser::Plugin;
pub use webui_parser::DEFAULT_CSS_FILE_NAME_TEMPLATE;
pub use webui_parser::{
    AssetFileNameTemplate, AssetFileNameTemplateError, DEFAULT_ASSET_FILE_NAME_TEMPLATE,
};
pub use webui_parser::{CssFallbackChain, CssTokenAnalysis};
pub use webui_parser::{Diagnostic, Severity};
pub use webui_protocol::WebUIProtocol;
pub use webui_tokens::{load_token_file, resolve_theme_path, TokenFile};

use std::collections::HashSet;
use std::ffi::{OsStr, OsString};
use std::fs;
use std::path::Path;
use std::time::Instant;
use webui_discovery::{DiscoveryPlugin, FastDiscoveryPlugin, WebUIDiscoveryPlugin};
use webui_parser::plugin::fast_v2::FastV2ParserPlugin;
use webui_parser::plugin::fast_v3::FastV3ParserPlugin;
use webui_parser::plugin::webui::WebUIParserPlugin;
use webui_parser::plugin::ParserPluginArtifacts;
use webui_parser::HtmlParser;

/// Projection metadata validated once for reuse across many protocol builds.
#[derive(Debug, Clone)]
pub struct PreparedProjectionManifests {
    snapshot: std::sync::Arc<projection::ProjectionSnapshot>,
}

#[derive(Debug)]
enum ProjectionBarrierState {
    Waiting,
    Ready(PreparedProjectionManifests),
    Failed(String),
}

/// A reusable projection source that waits for an orchestrated client build.
#[doc(hidden)]
#[derive(Debug, Clone)]
pub struct PendingProjectionManifests {
    state: std::sync::Arc<(std::sync::Mutex<ProjectionBarrierState>, std::sync::Condvar)>,
}

/// Completes a pending projection source exactly once.
#[doc(hidden)]
pub struct ProjectionManifestCompleter {
    state: std::sync::Arc<(std::sync::Mutex<ProjectionBarrierState>, std::sync::Condvar)>,
    completed: bool,
}

/// One projection manifest supplied to a build.
#[derive(Debug, Clone)]
pub enum ProjectionManifestSource {
    /// Read and validate a manifest from disk.
    Path(std::path::PathBuf),
    /// Validate an already parsed/transported manifest JSON object.
    ///
    /// `manifest_path` is its logical disk location and anchors the manifest's
    /// relative `root` plus stale input/output checks.
    Inline {
        /// Logical path the manifest would occupy on disk.
        manifest_path: std::path::PathBuf,
        /// Canonical manifest JSON.
        json: String,
    },
    /// Reuse metadata that has already passed schema, hash, merge, and stale
    /// validation.
    Prepared(PreparedProjectionManifests),
    /// Wait for an orchestrator to validate the completed client bundle.
    #[doc(hidden)]
    Pending(PendingProjectionManifests),
}

impl From<std::path::PathBuf> for ProjectionManifestSource {
    fn from(path: std::path::PathBuf) -> Self {
        Self::Path(path)
    }
}

/// Validate and merge projection sources once for repeated builds.
///
/// This is intended for orchestrators such as `webui-press` that build many
/// page protocols against one completed client bundle.
pub fn prepare_projection_manifests(
    sources: &[ProjectionManifestSource],
) -> Result<PreparedProjectionManifests, WebUIError> {
    let snapshot = projection::load_and_merge(sources)?
        .unwrap_or_else(|| std::sync::Arc::new(projection::ProjectionSnapshot::default()));
    Ok(PreparedProjectionManifests { snapshot })
}

/// Resolve preload hints for compiler-generated entries using exact output
/// identities and host-provided served URLs.
///
/// This is an internal orchestration hook for hosts such as `webui-press`.
/// Resolution consumes the manifest's pre-sorted closures and performs no
/// graph traversal or sorting.
#[doc(hidden)]
#[must_use]
pub fn resolve_generated_module_preloads(
    projection: &PreparedProjectionManifests,
    existing_hrefs: &[String],
    entry_outputs: &[&Path],
    output_urls: &std::collections::BTreeMap<std::path::PathBuf, String>,
) -> (Vec<String>, Vec<Diagnostic>) {
    let mut resolved = module_preload::resolve_exact(
        &projection.snapshot.entry_closures,
        existing_hrefs,
        entry_outputs,
        output_urls,
    );
    (
        std::mem::take(&mut resolved.hrefs),
        std::mem::take(&mut resolved.warnings),
    )
}

/// Return the exact physical outputs needed to map generated preload URLs.
#[doc(hidden)]
#[must_use]
pub fn generated_module_preload_outputs(
    projection: &PreparedProjectionManifests,
    entry_outputs: &[&Path],
) -> Vec<std::path::PathBuf> {
    module_preload::exact_output_identities(&projection.snapshot.entry_closures, entry_outputs)
}

/// Create a pending projection source and its one-shot completer.
#[doc(hidden)]
#[must_use]
pub fn projection_manifest_barrier() -> (ProjectionManifestSource, ProjectionManifestCompleter) {
    let state = std::sync::Arc::new((
        std::sync::Mutex::new(ProjectionBarrierState::Waiting),
        std::sync::Condvar::new(),
    ));
    (
        ProjectionManifestSource::Pending(PendingProjectionManifests {
            state: std::sync::Arc::clone(&state),
        }),
        ProjectionManifestCompleter {
            state,
            completed: false,
        },
    )
}

impl PendingProjectionManifests {
    fn wait(&self) -> Result<PreparedProjectionManifests, WebUIError> {
        let (lock, ready) = self.state.as_ref();
        let mut state = lock.lock().map_err(|_| {
            WebUIError::InvalidBuildOptions("projection synchronization lock poisoned".to_string())
        })?;
        loop {
            match &*state {
                ProjectionBarrierState::Waiting => {
                    state = ready.wait(state).map_err(|_| {
                        WebUIError::InvalidBuildOptions(
                            "projection synchronization lock poisoned".to_string(),
                        )
                    })?;
                }
                ProjectionBarrierState::Ready(projection) => {
                    return Ok(projection.clone());
                }
                ProjectionBarrierState::Failed(message) => {
                    return Err(WebUIError::InvalidBuildOptions(message.clone()));
                }
            }
        }
    }
}

impl ProjectionManifestCompleter {
    /// Wake waiting builds with validated metadata or a producer failure.
    pub fn complete(mut self, result: std::result::Result<PreparedProjectionManifests, String>) {
        let (lock, ready) = self.state.as_ref();
        if let Ok(mut state) = lock.lock() {
            *state = match result {
                Ok(projection) => ProjectionBarrierState::Ready(projection),
                Err(message) => ProjectionBarrierState::Failed(message),
            };
            self.completed = true;
            ready.notify_all();
        }
    }
}

impl Drop for ProjectionManifestCompleter {
    fn drop(&mut self) {
        if self.completed {
            return;
        }
        let (lock, ready) = self.state.as_ref();
        if let Ok(mut state) = lock.lock() {
            *state = ProjectionBarrierState::Failed(
                "projection producer terminated before completing metadata".to_string(),
            );
            ready.notify_all();
        }
    }
}

/// Options for building a WebUI application.
#[derive(Debug, Clone)]
pub struct BuildOptions {
    /// Path to the application folder containing templates.
    pub app_dir: std::path::PathBuf,
    /// Entry HTML file name (e.g., `"index.html"`).
    pub entry: String,
    /// CSS delivery strategy for component stylesheets.
    pub css: CssStrategy,
    /// Fallback DOM strategy for components without an authored Shadow root.
    pub dom: DomStrategy,
    /// Whether to merge component stylesheets into bundled chunks.
    ///
    /// Composes with [`BuildOptions::css`] instead of replacing it: bundling
    /// decides how stylesheets are grouped, the strategy decides how they reach
    /// the page. Stylesheets reached from more than one CSS tree are split into
    /// their own chunk so they are downloaded and cached once.
    pub css_bundle: bool,
    /// Framework plugin to load.
    pub plugin: Option<Plugin>,
    /// Additional component sources (npm packages or local paths).
    pub components: Vec<String>,
    /// Additional root components to compile for static component asset emission.
    ///
    /// These roots are parsed into the protocol so their templates, styles, and
    /// dependency closures can be emitted later, but they are not connected to
    /// the entry fragment and therefore are not rendered during initial SSR.
    pub component_asset_roots: Vec<String>,
    /// Whether to serialize an esbuild-compatible component asset metafile.
    pub metafile: bool,
    /// Emitted Link-mode CSS filename template using `[name]`, `[hash]`, and `[ext]`.
    pub css_file_name_template: String,
    /// Optional URL/base-path prefix for Link-mode `css_href` values.
    /// When set, emitted protocol hrefs become `<base>/<filename>`.
    pub css_public_base: Option<String>,
    /// Legal comment preservation strategy.
    pub legal_comments: LegalComments,
    /// Optional loaded design-token theme used to validate discovered CSS tokens.
    ///
    /// When present, every discovered CSS token that remains unresolved after
    /// local and ancestor CSS definitions are removed must exist in every theme,
    /// unless the `var()` usage supplies a literal CSS fallback (e.g.
    /// `var(--x, 16px)`), which provides its own value. Missing required tokens
    /// fail the build as parser diagnostics.
    pub theme: Option<TokenFile>,
    /// Bundler-neutral state projection manifest fragments supplied as disk
    /// paths or inline JSON with a logical manifest path.
    ///
    /// Empty (the default) means projection is disabled: the build emits
    /// [`webui_protocol::InitialStateStrategy::Full`] and every scripted
    /// component keeps a full-state (`All`) partial-navigation surface. No
    /// JavaScript/TypeScript analysis ever runs in Rust.
    ///
    /// When non-empty, every manifest is loaded, hash-validated against the
    /// files it declares, merged by component tag, and used to narrow each
    /// scripted component that is actually compiled into the protocol down to
    /// an exact hydration/navigation key surface. Every such scripted
    /// component must have exactly one manifest entry, or the build fails
    /// with [`WebUIError::Projection`] (`PROJ-B001`). Supplying manifests with
    /// a `plugin` other than [`Plugin::WebUI`] fails the build immediately
    /// (`PROJ-B002`): only the WebUI plugin produces protocol fields
    /// compatible with per-component key encoding.
    ///
    /// Manifests are read only at build time. The runtime handler never
    /// opens a manifest file; the compiled protocol is fully self-contained.
    pub projection_manifests: Vec<ProjectionManifestSource>,
}

impl Default for BuildOptions {
    fn default() -> Self {
        Self {
            app_dir: std::path::PathBuf::from("."),
            entry: "index.html".to_string(),
            css: CssStrategy::Link,
            dom: DomStrategy::Shadow,
            css_bundle: false,
            plugin: None,
            components: Vec::new(),
            component_asset_roots: Vec::new(),
            metafile: false,
            css_file_name_template: DEFAULT_CSS_FILE_NAME_TEMPLATE.to_string(),
            css_public_base: None,
            legal_comments: LegalComments::default(),
            theme: None,
            projection_manifests: Vec::new(),
        }
    }
}

/// Statistics about a completed build.
#[derive(Debug, Clone)]
pub struct BuildStats {
    /// Total wall-clock build time.
    pub duration: std::time::Duration,
    /// Total number of protocol fragments.
    pub fragment_count: usize,
    /// Number of registered components.
    pub component_count: usize,
    /// Number of CSS files produced.
    pub css_file_count: usize,
    /// Size of the serialized protocol in bytes.
    pub protocol_size_bytes: usize,
    /// Number of unique CSS tokens discovered.
    pub token_count: usize,
}

/// Result of a successful build.
#[derive(Debug)]
pub struct BuildResult {
    /// The compiled WebUI protocol.
    pub protocol: WebUIProtocol,
    /// Serialized protocol bytes (protobuf binary).
    pub protocol_bytes: Vec<u8>,
    /// Component CSS files: `(filename, content)` — only components referenced in the protocol.
    pub css_files: Vec<(String, String)>,
    /// Static component asset files: `(filename, ESM module content)`.
    ///
    /// Populated when [`BuildOptions::component_asset_roots`] is non-empty.
    pub component_asset_files: Vec<ComponentAssetFile>,
    /// Esbuild-compatible component asset metafile JSON when requested.
    pub metafile: Option<String>,
    /// Component client template payloads.
    /// Includes templates for all components encountered during parsing,
    /// including route-referenced components.
    pub component_templates: Vec<ComponentTemplateArtifact>,
    /// Non-fatal build advisories as warning-severity [`Diagnostic`]s.
    ///
    /// Includes parser advisories and CSS token warnings. Carries the same
    /// structured location/snippet/`help:` data as errors; the entry point
    /// decides how to present (and color) them.
    pub warnings: Vec<Diagnostic>,
    /// Build statistics.
    pub stats: BuildStats,
}

/// Advisory for a streaming entry compiled without a state-projection
/// manifest.
///
/// Cold: constructed at most once per build, and only for streaming entries.
#[cold]
#[inline(never)]
fn streaming_without_projection_warning(entry: &str, boundary_count: usize) -> Diagnostic {
    let plural = if boundary_count == 1 { "" } else { "s" };
    Diagnostic::warning(format!(
        "{entry} declares {boundary_count} streaming boundary checkpoint{plural} \
         but this build has no state-projection manifest"
    ))
    .code(webui_parser::codes::STREAMING_WITHOUT_PROJECTION)
    .help(
        "every checkpoint will serialize the whole state object instead of its own \
         components' keys; pass the client build's `webui-projection.json` through \
         `BuildOptions::projection_manifests` to send boundary-local state only",
    )
}

/// Build a WebUI application from an app directory.
///
/// Parses templates, discovers components, and produces a compiled protocol
/// with build statistics.
///
/// # Errors
///
/// Returns [`WebUIError`] if the app directory is invalid, templates fail
/// to parse, theme tokens are incomplete, or the protocol cannot be serialized.
#[must_use = "BuildResult contains the compiled protocol and statistics"]
pub fn build(options: BuildOptions) -> Result<BuildResult, WebUIError> {
    let started = Instant::now();

    let raw = build_protocol_inner(&options)?;

    let protocol_bytes = raw.protocol.to_protobuf()?;

    let stats = BuildStats {
        duration: started.elapsed(),
        fragment_count: raw.fragment_count,
        component_count: raw.component_count,
        css_file_count: raw.css_files.len(),
        protocol_size_bytes: protocol_bytes.len(),
        token_count: raw.token_count,
    };

    Ok(BuildResult {
        protocol: raw.protocol,
        protocol_bytes,
        css_files: raw.css_files,
        component_asset_files: raw.component_asset_files,
        metafile: raw.metafile,
        component_templates: raw.component_templates,
        warnings: raw.warnings,
        stats,
    })
}

/// Build a WebUI application and write output files to disk.
///
/// Writes `protocol.bin`, any external CSS files, and static component assets
/// to `out_dir`.
/// Creates `out_dir` if it does not exist. Component dependencies publish before
/// roots, unchanged component inputs keep their modification times, and existing
/// files outside the current build are left alone.
///
/// # Errors
///
/// Returns [`WebUIError`] on build failure or if output files cannot be written.
pub fn build_to_disk(options: BuildOptions, out_dir: &Path) -> Result<BuildStats, WebUIError> {
    let result = build(options)?;
    validate_output_file_names(OsStr::new("protocol.bin"), &result)?;

    fs::create_dir_all(out_dir).map_err(|source| WebUIError::Io {
        context: format!("Failed to create {}", out_dir.display()),
        source,
    })?;

    fs::write(out_dir.join("protocol.bin"), &result.protocol_bytes).map_err(|source| {
        WebUIError::Io {
            context: format!("Failed to write protocol.bin to {}", out_dir.display()),
            source,
        }
    })?;

    for (name, content) in &result.css_files {
        fs::write(out_dir.join(name), content).map_err(|source| WebUIError::Io {
            context: format!("Failed to write {name} to {}", out_dir.display()),
            source,
        })?;
    }
    if !result.component_asset_files.is_empty() {
        component_asset_output::publish(out_dir, &result.component_asset_files)?;
    }

    Ok(result.stats)
}

/// Inspect a compiled WebUI protocol file and return its JSON representation.
pub fn inspect(protocol_path: &Path) -> Result<String, WebUIError> {
    let bytes = fs::read(protocol_path).map_err(|source| WebUIError::Io {
        context: format!("Failed to read {}", protocol_path.display()),
        source,
    })?;
    inspect_bytes(&bytes)
}

/// Inspect raw protocol bytes and return their JSON representation.
pub fn inspect_bytes(protocol_bytes: &[u8]) -> Result<String, WebUIError> {
    let protocol = WebUIProtocol::from_protobuf(protocol_bytes)?;
    protocol
        .to_json_pretty()
        .map_err(|e| WebUIError::Serialization(e.to_string()))
}

/// Internal intermediate build output before stats are computed.
struct RawBuildOutput {
    protocol: WebUIProtocol,
    css_files: Vec<(String, String)>,
    component_asset_files: Vec<ComponentAssetFile>,
    metafile: Option<String>,
    component_templates: Vec<ComponentTemplateArtifact>,
    warnings: Vec<Diagnostic>,
    fragment_count: usize,
    component_count: usize,
    token_count: usize,
}

/// Internal build logic shared by `build()` and `build_to_disk()`.
fn build_protocol_inner(options: &BuildOptions) -> Result<RawBuildOutput, WebUIError> {
    let projection_enabled = !options.projection_manifests.is_empty();
    if projection_enabled && options.plugin != Some(Plugin::WebUI) {
        return Err(projection::incompatible_plugin_error());
    }
    if !options.component_asset_roots.is_empty() && options.plugin != Some(Plugin::WebUI) {
        return Err(WebUIError::InvalidBuildOptions(
            "component assets require --plugin webui because generated entries use the WebUI Framework registration runtime"
                .to_string(),
        ));
    }
    if options.css_bundle && options.css == CssStrategy::Module {
        return Err(css_bundle_module_error());
    }
    let parser_options = ParserOptions::try_new(
        options.css,
        options.dom,
        &options.css_file_name_template,
        options.css_public_base.as_deref(),
        options.legal_comments,
    )
    .map_err(|e| WebUIError::InvalidBuildOptions(e.to_string()))?;
    let css_link_options = parser_options.css_link_options.clone();

    let mut parser = match options.plugin {
        Some(Plugin::Fast | Plugin::FastV2) => {
            HtmlParser::with_plugin_options(Box::new(FastV2ParserPlugin::new()), parser_options)
        }
        Some(Plugin::FastV3) => {
            HtmlParser::with_plugin_options(Box::new(FastV3ParserPlugin::new()), parser_options)
        }
        Some(Plugin::WebUI) => {
            HtmlParser::with_plugin_options(Box::new(WebUIParserPlugin::new()), parser_options)
        }
        None => HtmlParser::with_options(parser_options),
    };
    let discovery_plugin: Box<dyn DiscoveryPlugin> = match options.plugin {
        Some(Plugin::Fast | Plugin::FastV2 | Plugin::FastV3) => {
            Box::new(FastDiscoveryPlugin::new())
        }
        Some(Plugin::WebUI) | None => Box::new(WebUIDiscoveryPlugin::new()),
    };

    let app_components = discovery_plugin
        .discover_local(&options.app_dir)
        .map_err(|error| {
            WebUIError::ComponentDiscovery(format!(
                "Failed to discover components from {}: {error}",
                options.app_dir.display()
            ))
        })?;
    for component in &app_components {
        parser
            .component_registry_mut()
            .register_component(webui_parser::ComponentRegistration {
                tag_name: &component.tag_name,
                html_content: &component.html_content,
                css_content: component.css_content.as_deref(),
                is_client_owned: component.is_client_owned,
            })
            .map_err(|source| WebUIError::ComponentRegistration {
                context: format!(
                    "Failed to register component '{}' from {}",
                    component.tag_name, component.source
                ),
                source,
            })?;
    }

    // Discover and register external component sources
    for source in &options.components {
        let result = webui_discovery::discover_source_with_plugin(
            source,
            &options.app_dir,
            discovery_plugin.as_ref(),
        )
        .map_err(|e| {
            WebUIError::ComponentDiscovery(format!(
                "Failed to discover components from {source}: {e}"
            ))
        })?;
        for comp in &result.components {
            // Script presence marks client ownership. Rust never analyzes the
            // source; exact state surfaces come from projection manifests.
            parser
                .component_registry_mut()
                .register_component(webui_parser::ComponentRegistration {
                    tag_name: &comp.tag_name,
                    html_content: &comp.html_content,
                    css_content: comp.css_content.as_deref(),
                    is_client_owned: comp.is_client_owned,
                })
                .map_err(|source| WebUIError::ComponentRegistration {
                    context: format!(
                        "Failed to register component '{}' from {}",
                        comp.tag_name, comp.source
                    ),
                    source,
                })?;
        }
    }

    let component_count = parser.component_registry().len();

    // Parse entry HTML
    let entry_path = options.app_dir.join(&options.entry);
    let html_content = fs::read_to_string(&entry_path).map_err(|source| WebUIError::Io {
        context: format!("Failed to read {}", entry_path.display()),
        source,
    })?;
    parser
        .parse(&options.entry, &html_content)
        .map_err(|source| WebUIError::Parse {
            context: format!("Failed to parse {}", options.entry),
            source,
        })?;

    // Read before synthetic asset roots parse because module entry sources are
    // entry-local. Boundary declarations live in the fragment graph itself.
    let module_entry_srcs = parser.module_entry_srcs().to_vec();

    let synthetic_asset_fragments =
        parse_component_asset_roots(&mut parser, &options.component_asset_roots)?;

    let component_render_css = parser.component_registry().render_policy_css(
        parser
            .component_registry()
            .get_all()
            .filter(|component| parser.has_fragment(&component.tag_name))
            .map(|component| component.tag_name.as_str()),
    );
    let css_snapshot: Vec<(String, String)> = parser
        .component_registry()
        .get_all()
        .filter(|component| parser.has_fragment(&component.tag_name))
        .filter_map(|component| {
            component
                .css_content
                .as_ref()
                .map(|css| (component.tag_name.clone(), css.clone()))
        })
        .collect();
    let component_shadow_dom_usage: Vec<(String, bool)> = parser
        .component_shadow_dom_usage()
        .map(|(tag_name, uses_shadow_dom)| (tag_name.to_string(), uses_shadow_dom))
        .collect();
    let component_work_policies: Vec<(String, u8)> = parser
        .component_work_policies()
        .map(|(tag_name, policy)| (tag_name.to_string(), policy))
        .collect();

    // Collect CSS token analysis before consuming the parser.
    let token_analysis = parser.token_analysis();
    let mut warnings: Vec<Diagnostic> = parser.take_warnings();
    if let Some(theme) = options.theme.as_ref() {
        token_analysis
            .validate_theme_tokens(theme)
            .map_err(|source| WebUIError::Parse {
                context: "Failed to validate theme tokens".to_string(),
                source,
            })?;
        // Advisory: a token used only as `var(--x, <literal>)` and absent from
        // every theme is often a misspelling. The literal keeps the build green,
        // so this is a warning (with a "did you mean …?" suggestion), not an
        // error.
        warnings.extend(token_analysis.theme_token_warnings(theme));
    }
    let token_count = token_analysis.protocol_tokens.len();

    let component_templates =
        match parser
            .take_plugin_artifacts()
            .map_err(|source| WebUIError::Parse {
                context: format!(
                    "Failed to compile component templates for {}",
                    options.entry
                ),
                source,
            })? {
            ParserPluginArtifacts::None => Vec::new(),
            ParserPluginArtifacts::ComponentTemplates(templates) => templates,
        };
    // Build protocol (consumes parser)
    let mut fragment_records = parser.into_fragment_records();
    for fragment_id in synthetic_asset_fragments {
        fragment_records.remove(&fragment_id);
    }
    let boundary_count = fragment_records
        .values()
        .flat_map(|list| list.fragments.iter())
        .filter(|fragment| {
            matches!(
                fragment.fragment.as_ref(),
                Some(webui_protocol::web_ui_fragment::Fragment::Boundary(boundary))
                    if boundary.phase() == webui_protocol::BoundaryPhase::Start
            )
        })
        .count();
    // Resolve projection only after template compilation. Ordinary path/inline
    // builds pay the same validation cost, while orchestrators can overlap
    // parser work with an in-flight client bundle through a pending source.
    let merged_manifest = projection::load_and_merge(&options.projection_manifests)?;
    let mut protocol = WebUIProtocol::with_tokens(fragment_records, token_analysis.protocol_tokens);
    protocol.initial_state_strategy = if merged_manifest.is_some() {
        webui_protocol::InitialStateStrategy::Components as i32
    } else {
        webui_protocol::InitialStateStrategy::Full as i32
    };

    // Advisory: without a projection manifest every streaming checkpoint falls
    // back to serializing the entire state object, so the cost is
    // O(boundaries x full state) rather than O(boundaries x that boundary's
    // own keys). The build still works, so this is a warning.
    if boundary_count > 0 && merged_manifest.is_none() {
        warnings.push(streaming_without_projection_warning(
            &options.entry,
            boundary_count,
        ));
    }

    // Resolve `modulepreload` hints once, at build time. The shared chunks an
    // entry statically imports are named only inside that entry's bytes, so
    // the preload scanner cannot find them; hinting them removes a serialized
    // round trip. The handler writes the result verbatim.
    if let Some(merged) = &merged_manifest {
        let mut preloads = module_preload::resolve(&merged.entry_closures, &module_entry_srcs);
        protocol.module_preloads = std::mem::take(&mut preloads.hrefs);
        warnings.append(&mut preloads.warnings);
    }

    // Record CSS delivery and per-component Shadow DOM ownership.
    protocol.set_css_strategy(match options.css {
        CssStrategy::Link => webui_protocol::CssStrategy::Link,
        CssStrategy::Style => webui_protocol::CssStrategy::Style,
        CssStrategy::Module => webui_protocol::CssStrategy::Module,
    });
    for (tag_name, uses_shadow_dom) in component_shadow_dom_usage {
        if !protocol.fragments.contains_key(&tag_name) {
            continue;
        }
        protocol
            .components
            .entry(tag_name)
            .or_default()
            .uses_shadow_dom = uses_shadow_dom;
    }
    for (tag_name, work_policy) in component_work_policies {
        if protocol.fragments.contains_key(&tag_name) {
            protocol.components.entry(tag_name).or_default().work_policy = i32::from(work_policy);
        }
    }
    protocol.component_render_css = component_render_css;

    // Process component CSS in a single pass: retain compiled Style/Module CSS,
    // set Link-strategy css_href, and collect external CSS files.
    let stores_css = options.css != CssStrategy::Link;
    let mut css_files: Vec<(String, String)> = Vec::new();
    let mut emitted_names: HashSet<String> = HashSet::new();
    let mut bundle_inputs: Vec<(String, String)> = Vec::new();
    for (tag, css) in css_snapshot {
        if !protocol.fragments.contains_key(&tag) {
            continue;
        }
        if options.css_bundle {
            bundle_inputs.push((tag.clone(), css.clone()));
        }
        if stores_css {
            protocol.components.entry(tag).or_default().css = css;
        } else {
            let resolved = css_link_options.resolve(&tag, &css);
            if !emitted_names.insert(resolved.filename.clone()) {
                return Err(WebUIError::InvalidBuildOptions(format!(
                    "CSS filename collision for Link strategy: '{}'. Adjust the asset filename template to include [name] or another unique component-specific segment.",
                    resolved.filename
                )));
            }
            protocol.components.entry(tag).or_default().css_href = resolved.href;
            css_files.push((resolved.filename, css));
        }
    }

    // CSS order is load-bearing, so compute this independently from the sorted
    // component-asset reachability sets.
    protocol.populate_style_closures(&[options.entry.as_str()]);

    if options.css_bundle {
        // Chunks are planned from the closures above, so this has to run after
        // them and after per-component resources exist to plan over.
        let by_tag = bundle_inputs
            .iter()
            .map(|(tag, css)| (tag.as_str(), css.as_str()))
            .collect();
        let chunk_files = style_bundle::bundle_style_chunks(
            &mut protocol,
            options.entry.as_str(),
            &by_tag,
            &css_link_options,
        )?;
        if !stores_css {
            // Keep component files as compatibility and independently-loaded
            // component fallbacks. Current handlers render chunk links, so these
            // files add no requests to the normal bundled path.
            for (filename, css) in chunk_files {
                if emitted_names.insert(filename.clone()) {
                    css_files.push((filename, css));
                    continue;
                }
                // A single-component chunk resolves to that component's own
                // filename and bytes, so the file is already written.
                let identical = css_files
                    .iter()
                    .any(|(name, existing)| *name == filename && *existing == css);
                if !identical {
                    return Err(WebUIError::InvalidBuildOptions(format!(
                        "CSS filename collision between bundled chunk '{filename}' and a component stylesheet of the same name. Adjust the asset filename template to include [hash] or another unique segment."
                    )));
                }
            }
        }
    }

    // Store compiled client templates in the protocol so any host server can
    // query them. Scriptless templates retain navigation metadata but contribute
    // no initial hydration state.
    for artifact in &component_templates {
        let component = protocol
            .components
            .entry(artifact.tag_name.clone())
            .or_default();
        component.template = artifact.template.clone();
        component.template_json = artifact.template_json.clone();
        component.template_functions = artifact.template_functions.clone();
        // Manifest keys are the initial hydration surface. Navigation is the
        // union of manifest client keys and Rust-compiled template roots.
        // Scriptless components are never governed by a manifest: they keep
        // their Rust-derived surface regardless of projection.
        let manifest_entry = if artifact.is_scripted {
            merged_manifest
                .as_ref()
                .and_then(|merged| merged.components.get(&artifact.tag_name))
        } else {
            None
        };
        let (hydration_mode, hydration_keys) = match manifest_entry {
            Some(entry) => encode_state_surface(&StateSurface::Keys(entry.hydration_keys.clone())),
            None => encode_state_surface(&artifact.hydration),
        };
        component.hydration_mode = hydration_mode;
        component.hydration_keys = hydration_keys;
        let (navigation_mode, navigation_keys) = match manifest_entry {
            Some(entry) => {
                let union =
                    projection::union_keys(&entry.navigation_keys, &artifact.template_roots);
                encode_state_surface(&StateSurface::Keys(union))
            }
            None => encode_state_surface(&artifact.navigation),
        };
        component.navigation_mode = Some(navigation_mode);
        component.navigation_keys = navigation_keys;
    }

    let mut component_asset_graph = component_assets::render_component_assets(
        &protocol,
        &options.entry,
        &options.component_asset_roots,
        options.metafile,
    )?;
    component_asset_graph.retain_entry_protocol(&mut protocol)?;
    // Strict projection coverage applies to scripted components retained in the
    // entry protocol. Asset-only roots use their static template payloads and
    // never participate in protocol projection.
    if let Some(merged) = &merged_manifest {
        let entry_scripted_tags: Vec<&str> = component_templates
            .iter()
            .filter(|artifact| {
                artifact.is_scripted && protocol.fragments.contains_key(&artifact.tag_name)
            })
            .map(|artifact| artifact.tag_name.as_str())
            .collect();
        projection::validate_coverage(&merged.components, &entry_scripted_tags)?;
    }
    let fragment_count = protocol
        .fragments
        .values()
        .map(|fragments| fragments.fragments.len())
        .sum();
    let component_asset_files = component_asset_graph.files;
    validate_generated_file_names(&css_files, &component_asset_files)?;

    Ok(RawBuildOutput {
        protocol,
        css_files,
        component_asset_files,
        metafile: component_asset_graph.metafile,
        component_templates,
        warnings,
        fragment_count,
        component_count,
        token_count,
    })
}

fn encode_state_surface(surface: &StateSurface) -> (i32, Vec<String>) {
    match surface {
        StateSurface::None => (webui_protocol::StateProjectionMode::None as i32, Vec::new()),
        StateSurface::Keys(keys) => (
            webui_protocol::StateProjectionMode::Keys as i32,
            keys.clone(),
        ),
        StateSurface::All => (webui_protocol::StateProjectionMode::All as i32, Vec::new()),
    }
}

fn parse_component_asset_roots(
    parser: &mut HtmlParser,
    roots: &[String],
) -> Result<Vec<String>, WebUIError> {
    let mut synthetic_fragments = Vec::with_capacity(roots.len());
    for (index, root) in roots.iter().enumerate() {
        let root = root.trim();
        if parser.has_fragment(root) {
            continue;
        }
        // Compile the requested lazy root without connecting it to the entry
        // graph, so it can be emitted as a static asset but stays out of SSR.
        let mut synthetic = String::with_capacity(root.len() * 2 + 5);
        synthetic.push('<');
        synthetic.push_str(root);
        synthetic.push_str("></");
        synthetic.push_str(root);
        synthetic.push('>');

        let fragment_id = format!("__webui_asset_root_{index}");
        parser
            .parse(&fragment_id, &synthetic)
            .map_err(|source| WebUIError::Parse {
                context: format!("Failed to parse component asset root <{root}>"),
                source,
            })?;
        synthetic_fragments.push(fragment_id);
    }
    Ok(synthetic_fragments)
}

fn validate_generated_file_names(
    css_files: &[(String, String)],
    component_asset_files: &[ComponentAssetFile],
) -> Result<(), WebUIError> {
    let mut names = HashSet::with_capacity(css_files.len() + component_asset_files.len());
    for (name, _) in css_files {
        names.insert(name.as_str());
    }
    for file in component_asset_files {
        if !names.insert(file.name.as_str()) {
            return Err(WebUIError::InvalidBuildOptions(format!(
                "output filename collision for '{}'. Adjust the asset filename template to include [ext] or another unique asset-type segment.",
                file.name
            )));
        }
    }
    Ok(())
}

fn validate_output_file_names(
    protocol_name: &OsStr,
    result: &BuildResult,
) -> Result<(), WebUIError> {
    let mut names =
        HashSet::with_capacity(1 + result.css_files.len() + result.component_asset_files.len());
    names.insert(protocol_name.to_os_string());
    for (name, _) in &result.css_files {
        let file_name = OsString::from(name);
        if !names.insert(file_name.clone()) {
            return Err(output_file_collision_error(&file_name));
        }
    }
    for file in &result.component_asset_files {
        let file_name = OsString::from(&file.name);
        if !names.insert(file_name.clone()) {
            return Err(output_file_collision_error(&file_name));
        }
    }
    Ok(())
}

fn output_file_collision_error(name: &OsStr) -> WebUIError {
    WebUIError::InvalidBuildOptions(format!(
        "output filename collision for '{}'. Adjust the asset filename template to include [ext] or another unique asset-type segment.",
        name.to_string_lossy()
    ))
}

#[cold]
#[inline(never)]
fn css_bundle_module_error() -> WebUIError {
    WebUIError::InvalidBuildOptions(
        "CSS bundling is not supported with the Module strategy. Module builds already inline every stylesheet as a data URI, so there are no requests to merge, and their import-map specifiers are resolved per component before chunks exist. Use --css link (or --css style) with --css-bundle, or drop --css-bundle.".to_string(),
    )
}

#[cfg(test)]
#[allow(clippy::disallowed_methods)]
mod tests {
    use super::*;
    use std::collections::HashMap;
    use std::path::PathBuf;
    use tempfile::TempDir;
    use webui_handler::plugin::webui::WebUIHydrationPlugin;
    use webui_protocol::web_ui_fragment::Fragment;

    struct StringWriter {
        buf: String,
    }

    impl ResponseWriter for StringWriter {
        fn write(&mut self, content: &str) -> webui_handler::Result<()> {
            self.buf.push_str(content);
            Ok(())
        }

        fn end(&mut self) -> webui_handler::Result<()> {
            Ok(())
        }
    }

    fn create_app_dir(files: &[(&str, &str)]) -> TempDir {
        let dir = TempDir::new().unwrap();
        for (name, content) in files {
            let path = dir.path().join(name);
            if let Some(parent) = path.parent() {
                fs::create_dir_all(parent).unwrap();
            }
            fs::write(&path, content).unwrap();
        }
        dir
    }

    fn default_options(app_dir: &Path) -> BuildOptions {
        BuildOptions {
            app_dir: app_dir.to_path_buf(),
            ..BuildOptions::default()
        }
    }

    fn component_payload<'a>(files: &'a [ComponentAssetFile], tag: &str) -> &'a ComponentAssetFile {
        let mut prefix = String::with_capacity(tag.len() + 12);
        prefix.push_str("components/");
        prefix.push_str(tag);
        prefix.push('.');
        files
            .iter()
            .find(|file| file.name.starts_with(&prefix))
            .unwrap()
    }

    fn light_options(app_dir: &Path) -> BuildOptions {
        BuildOptions {
            dom: DomStrategy::Light,
            ..default_options(app_dir)
        }
    }

    mod fast;

    #[test]
    fn test_build_simple_html() {
        let app = create_app_dir(&[("index.html", "<h1>Hello</h1>")]);
        let result = build(default_options(app.path())).unwrap();

        assert!(result.protocol.fragments.contains_key("index.html"));
        assert!(result.stats.fragment_count > 0);
        assert!(result.stats.protocol_size_bytes > 0);
        assert!(!result.stats.duration.is_zero());
        assert_eq!(
            result.protocol.initial_state_strategy,
            webui_protocol::InitialStateStrategy::Full as i32
        );
    }

    #[test]
    fn light_build_uses_light_unless_component_authors_shadow() {
        let app = create_app_dir(&[
            (
                "index.html",
                "<my-card></my-card><shadow-card></shadow-card>",
            ),
            ("my-card.html", "<p>content</p>"),
            (
                "shadow-card.html",
                r#"<template shadowrootmode="open"><p>shadow</p></template>"#,
            ),
        ]);

        let result = build(BuildOptions {
            app_dir: app.path().to_path_buf(),
            dom: DomStrategy::Light,
            ..BuildOptions::default()
        })
        .unwrap();
        assert!(!result.protocol.component_uses_shadow_dom("my-card"));
        assert!(result.protocol.component_uses_shadow_dom("shadow-card"));
        let light_html: String = result.protocol.fragments["my-card"]
            .fragments
            .iter()
            .filter_map(|fragment| match fragment.fragment.as_ref() {
                Some(Fragment::Raw(raw)) => Some(raw.value.as_str()),
                _ => None,
            })
            .collect();
        assert!(!light_html.contains("shadowrootmode"));

        let shadow_html: String = result.protocol.fragments["shadow-card"]
            .fragments
            .iter()
            .filter_map(|fragment| match fragment.fragment.as_ref() {
                Some(Fragment::Raw(raw)) => Some(raw.value.as_str()),
                _ => None,
            })
            .collect();
        assert!(shadow_html.contains(r#"<template shadowrootmode="open">"#));
    }

    #[test]
    fn build_defaults_unwrapped_components_to_shadow() {
        let app = create_app_dir(&[
            ("index.html", "<my-card></my-card>"),
            ("my-card.html", "<p>content</p>"),
        ]);

        let result = build(default_options(app.path())).unwrap();
        assert!(result.protocol.component_uses_shadow_dom("my-card"));
        let html: String = result.protocol.fragments["my-card"]
            .fragments
            .iter()
            .filter_map(|fragment| match fragment.fragment.as_ref() {
                Some(Fragment::Raw(raw)) => Some(raw.value.as_str()),
                _ => None,
            })
            .collect();
        assert!(html.contains(r#"<template shadowrootmode="open">"#));
    }

    #[test]
    fn build_rejects_slot_in_unwrapped_light_component() {
        let app = create_app_dir(&[
            ("index.html", "<my-card></my-card>"),
            ("my-card.html", "<div><slot></slot></div>"),
        ]);

        let error = build(BuildOptions {
            app_dir: app.path().to_path_buf(),
            dom: DomStrategy::Light,
            ..BuildOptions::default()
        })
        .expect_err("unwrapped Light DOM slot must fail the build");

        assert!(
            error.chain_message().contains("[light-dom-slot]"),
            "unexpected build error: {}",
            error.chain_message()
        );
    }

    #[test]
    fn pending_projection_unblocks_after_template_compilation() {
        let app = create_app_dir(&[("index.html", "<h1>Hello</h1>")]);
        let (source, completer) = projection_manifest_barrier();
        let options = BuildOptions {
            app_dir: app.path().to_path_buf(),
            plugin: Some(Plugin::WebUI),
            projection_manifests: vec![source],
            ..BuildOptions::default()
        };
        let handle = std::thread::spawn(move || build(options));
        let prepared = prepare_projection_manifests(&[]).unwrap();
        completer.complete(Ok(prepared));
        let result = handle.join().unwrap().unwrap();
        assert_eq!(
            result.protocol.initial_state_strategy,
            webui_protocol::InitialStateStrategy::Components as i32
        );
    }

    /// Streaming entries pay O(boundaries x full state) without a projection
    /// manifest, so the build must say so.
    #[test]
    fn streaming_entry_without_projection_manifest_warns() {
        let app = create_app_dir(&[(
            "index.html",
            concat!(
                "<html><body>",
                r#"<boundary name="a"><p>{{one}}</p></boundary>"#,
                r#"<boundary name="b"><p>{{two}}</p></boundary>"#,
                "</body></html>",
            ),
        )]);
        let mut options = default_options(app.path());
        options.plugin = Some(Plugin::WebUI);

        let result = build(options).unwrap();

        assert_eq!(
            result.protocol.initial_state_strategy,
            webui_protocol::InitialStateStrategy::Full as i32
        );
        let boundary_names = |protocol: &WebUIProtocol| {
            protocol.fragments["index.html"]
                .fragments
                .iter()
                .filter_map(|fragment| match fragment.fragment.as_ref() {
                    Some(webui_protocol::web_ui_fragment::Fragment::Boundary(boundary))
                        if boundary.phase() == webui_protocol::BoundaryPhase::Start =>
                    {
                        Some(boundary.name.clone())
                    }
                    _ => None,
                })
                .collect::<Vec<_>>()
        };
        assert_eq!(boundary_names(&result.protocol), ["a", "b"]);
        let decoded = WebUIProtocol::from_protobuf(&result.protocol_bytes).unwrap();
        assert_eq!(boundary_names(&decoded), ["a", "b"]);
        let warning = result
            .warnings
            .iter()
            .find(|diag| {
                diag.error_code() == Some(webui_parser::codes::STREAMING_WITHOUT_PROJECTION)
            })
            .expect("a streaming build without projection must warn");
        assert_eq!(warning.severity(), webui_parser::Severity::Warning);
        assert!(
            warning.to_string().contains("2 streaming boundary"),
            "warning should report the boundary count: {warning}"
        );
        assert!(
            warning
                .help_text()
                .is_some_and(|help| help.contains("projection_manifests")),
            "warning should point at the fix: {warning}"
        );
    }

    #[test]
    fn streaming_entry_with_projection_manifest_does_not_warn() {
        let app = create_app_dir(&[(
            "index.html",
            concat!(
                "<html><body>",
                r#"<boundary name="a"><p>{{one}}</p></boundary>"#,
                "</body></html>",
            ),
        )]);
        let manifest_json =
            projection::test_support::build_valid_manifest_json(app.path(), &[], &[], &[]);
        let manifest = projection::test_support::write_manifest(
            app.path(),
            "webui-projection.json",
            &manifest_json,
        );
        let mut options = default_options(app.path());
        options.plugin = Some(Plugin::WebUI);
        options.projection_manifests = vec![manifest.into()];

        let result = build(options).unwrap();

        assert_eq!(
            result.protocol.initial_state_strategy,
            webui_protocol::InitialStateStrategy::Components as i32
        );
        assert!(
            !result
                .warnings
                .iter()
                .any(|diag| diag.error_code()
                    == Some(webui_parser::codes::STREAMING_WITHOUT_PROJECTION)),
            "a projected streaming build must not warn"
        );
    }

    /// The advisory is streaming-specific: ordinary entries emit one bootstrap
    /// block, so full state there is not a per-checkpoint multiplier.
    #[test]
    fn non_streaming_entry_without_projection_manifest_does_not_warn() {
        let app = create_app_dir(&[("index.html", "<html><body><p>{{one}}</p></body></html>")]);
        let mut options = default_options(app.path());
        options.plugin = Some(Plugin::WebUI);

        let result = build(options).unwrap();

        assert!(
            !result
                .warnings
                .iter()
                .any(|diag| diag.error_code()
                    == Some(webui_parser::codes::STREAMING_WITHOUT_PROJECTION)),
            "a non-streaming build must not warn about projection"
        );
    }

    #[test]
    fn test_build_keeps_scriptless_component_dormant_until_client_use() {
        let app = create_app_dir(&[
            (
                "index.html",
                "<html><body><demo-card></demo-card></body></html>",
            ),
            ("demo-card.html", "<p>{{name}} {{serverTitle}}</p>"),
        ]);
        // An empty manifest fragment (no scripted components exist in this
        // app, so strict coverage trivially passes) still turns on
        // `InitialStateStrategy::Components`, letting scriptless components'
        // Rust-derived dormant surface (`None` hydration) take effect.
        let manifest_json =
            projection::test_support::build_valid_manifest_json(app.path(), &[], &[], &[]);
        let manifest = projection::test_support::write_manifest(
            app.path(),
            "webui-projection.json",
            &manifest_json,
        );
        let mut options = default_options(app.path());
        options.plugin = Some(Plugin::WebUI);
        options.projection_manifests = vec![manifest.into()];
        let result = build(options).unwrap();
        assert_eq!(
            result.protocol.initial_state_strategy,
            webui_protocol::InitialStateStrategy::Components as i32
        );

        assert!(result
            .component_templates
            .iter()
            .any(|template| template.tag_name == "demo-card"));
        let component = result
            .protocol
            .components
            .get("demo-card")
            .expect("scriptless component metadata should be retained");
        assert!(component.hydration_keys.is_empty());
        assert_eq!(component.navigation_keys, ["name", "serverTitle"]);
        assert!(component.template_json.contains(r#""th":1"#));

        let handler = WebUIHandler::with_plugin(|| Box::new(WebUIHydrationPlugin::new()));
        let state = serde_json::json!({ "name": "Server rendered" });
        let protocol = Protocol::new(result.protocol.clone());
        let mut writer = StringWriter { buf: String::new() };
        handler
            .render(
                &protocol,
                &state,
                &RenderOptions::new("index.html", "/"),
                &mut writer,
            )
            .unwrap();
        assert!(writer.buf.contains("Server rendered"));
        assert!(writer.buf.contains(r#""state":{}"#));
        assert!(writer.buf.contains(r#""templates":{"demo-card":"#));
    }

    #[test]
    fn test_build_treats_sibling_component_script_as_scripted() {
        let app = create_app_dir(&[
            ("index.html", "<demo-card></demo-card>"),
            (
                "demo-card.html",
                r#"<button @click="{onClick()}">{{name}}</button>"#,
            ),
            (
                "demo-card.ts",
                "import { WebUIElement } from '@microsoft/webui-framework';\n\
                 class DemoCard extends WebUIElement { onClick() {} }\n\
                 DemoCard.define('demo-card');",
            ),
        ]);
        let mut options = default_options(app.path());
        options.plugin = Some(Plugin::WebUI);
        let result = build(options).unwrap();

        let template = result
            .component_templates
            .iter()
            .find(|template| template.tag_name == "demo-card")
            .unwrap();
        assert!(template.template_json.contains(r#""eg":[["click""#));
    }

    #[test]
    fn test_build_populates_component_hydration_keys_from_script() {
        let app = create_app_dir(&[
            ("index.html", "<demo-card></demo-card>"),
            ("demo-card.html", "<p>{{name}}</p>"),
            (
                "demo-card.ts",
                "import { WebUIElement, attr, observable } from '@microsoft/webui-framework';\n\
                 class DemoCard extends WebUIElement {\n\
                 @observable name = '';\n\
                 @attr({ attribute: 'cta-href' }) ctaHref = '/x';\n\
                 @observable count = 0;\n\
                 }\n\
                 DemoCard.define('demo-card');",
            ),
        ]);
        // Rust performs no JavaScript/TypeScript analysis: the exact keys
        // come from a bundler-produced projection manifest, not from
        // scanning `demo-card.ts`.
        let manifest_json = projection::test_support::build_valid_manifest_json(
            app.path(),
            &[("demo-card.ts", "source")],
            &[("demo-card.js", "output")],
            &[(
                "demo-card",
                "demo-card.ts",
                &["demo-card.js"],
                &["count", "ctaHref", "name"],
                &["count", "ctaHref", "name"],
            )],
        );
        let manifest = projection::test_support::write_manifest(
            app.path(),
            "webui-projection.json",
            &manifest_json,
        );
        let mut options = default_options(app.path());
        options.plugin = Some(Plugin::WebUI);
        options.projection_manifests = vec![manifest.into()];
        let result = build(options).unwrap();

        assert_eq!(
            result.protocol.initial_state_strategy,
            webui_protocol::InitialStateStrategy::Components as i32
        );
        let component = result.protocol.components.get("demo-card").unwrap();
        assert_eq!(
            component.hydration_mode,
            webui_protocol::StateProjectionMode::Keys as i32
        );
        assert_eq!(component.hydration_keys, vec!["count", "ctaHref", "name"]);
        assert_eq!(
            component.navigation_mode,
            Some(webui_protocol::StateProjectionMode::Keys as i32)
        );
        assert_eq!(component.navigation_keys, vec!["count", "ctaHref", "name"]);
    }

    #[test]
    fn test_build_scripted_component_without_manifest_falls_back_to_full_state() {
        let app = create_app_dir(&[
            (
                "index.html",
                "<html><body><demo-card></demo-card></body></html>",
            ),
            ("demo-card.html", "<p>{{name}}</p>"),
            (
                "demo-card.ts",
                "import { WebUIElement, observable } from '@microsoft/webui-framework';\n\
                 class DemoCard extends WebUIElement {\n\
                 @observable name = '';\n\
                 }\n\
                 DemoCard.define('demo-card');",
            ),
        ]);
        let mut options = default_options(app.path());
        options.plugin = Some(Plugin::WebUI);
        // No `projection_manifests` supplied: without a manifest, Rust never
        // analyzes `demo-card.ts` and must assume the full, unproven surface.
        let result = build(options).unwrap();

        assert_eq!(
            result.protocol.initial_state_strategy,
            webui_protocol::InitialStateStrategy::Full as i32
        );
        let component = result.protocol.components.get("demo-card").unwrap();
        assert_eq!(
            component.hydration_mode,
            webui_protocol::StateProjectionMode::All as i32
        );
        assert!(component.hydration_keys.is_empty());
        assert_eq!(
            component.navigation_mode,
            Some(webui_protocol::StateProjectionMode::All as i32)
        );

        let handler = WebUIHandler::with_plugin(|| Box::new(WebUIHydrationPlugin::new()));
        let state = serde_json::json!({ "name": "Visible" });
        let protocol = Protocol::new(result.protocol.clone());
        let mut writer = StringWriter { buf: String::new() };
        handler
            .render(
                &protocol,
                &state,
                &RenderOptions::new("index.html", "/"),
                &mut writer,
            )
            .unwrap();
        assert!(writer.buf.contains("Visible"));
        // Full-state fallback serializes the entire supplied state object,
        // not a narrowed key subset.
        assert!(writer.buf.contains(r#""state":{"name":"Visible"}"#));
    }

    #[test]
    fn test_build_rejects_scriptless_event_component() {
        let app = create_app_dir(&[
            ("index.html", "<demo-card></demo-card>"),
            (
                "demo-card.html",
                r#"<button @click="{onClick()}">Click</button>"#,
            ),
        ]);
        let mut options = default_options(app.path());
        options.plugin = Some(Plugin::WebUI);
        let err = build(options).expect_err("scriptless events should fail");

        let message = err.chain_message();
        assert!(
            message.contains("scriptless-event-handler"),
            "msg: {message}"
        );
    }

    #[test]
    fn test_build_returns_actionable_error_for_invalid_w_ref() {
        let app = create_app_dir(&[
            ("index.html", "<my-card>Hello</my-card>"),
            ("my-card.html", r#"<div><input w-ref="myInput" /></div>"#),
        ]);
        let mut options = default_options(app.path());
        options.plugin = Some(Plugin::WebUI);

        // Authoring mistakes are returned (not panicked) so every consumer —
        // CLI, Node, FFI, WASM — can surface the message its own way.
        let Err(err) = build(options) else {
            panic!("non-braced w-ref must fail the build");
        };
        let msg = err.chain_message();
        assert!(msg.contains("invalid w-ref binding"), "msg: {msg}");
        assert!(
            msg.contains("component <my-card> · element <input>"),
            "msg: {msg}"
        );
        assert!(msg.contains("help:"), "msg: {msg}");
    }

    #[test]
    fn test_build_returns_actionable_error_for_invalid_event_handler() {
        let app = create_app_dir(&[
            ("index.html", "<my-btn>x</my-btn>"),
            (
                "my-btn.html",
                r#"<div><button @click="e.preventDefault()">x</button></div>"#,
            ),
        ]);
        let mut options = default_options(app.path());
        options.plugin = Some(Plugin::WebUI);

        let Err(err) = build(options) else {
            panic!("invalid @event handler must fail the build");
        };
        let msg = err.chain_message();
        assert!(msg.contains("invalid @click handler"), "msg: {msg}");
        assert!(
            msg.contains("component <my-btn> · element <button>"),
            "msg: {msg}"
        );
    }

    #[test]
    fn test_error_chain_message_has_no_duplicate_source() {
        let err = WebUIError::Parse {
            context: "Failed to parse index.html".to_string(),
            source: webui_parser::ParserError::Directive("Invalid for each: x".to_string()),
        };
        // Each layer's Display describes only its own level — the source is not
        // embedded — so anyhow's `{:#}` / chain walks never repeat it.
        assert_eq!(err.to_string(), "Failed to parse index.html");
        // The flat message includes the source exactly once (no repetition).
        assert_eq!(
            err.chain_message(),
            "Failed to parse index.html: Directive error: Invalid for each: x"
        );
    }

    #[test]
    fn test_build_with_directives() {
        let html = r#"<h1>Hello</h1>
<for each="item in items">
    <p>{{item.name}}</p>
</for>
<if condition="show">
    <p>Visible</p>
</if>"#;
        let app = create_app_dir(&[("index.html", html)]);
        let result = build(default_options(app.path())).unwrap();

        let index = &result.protocol.fragments["index.html"].fragments;
        assert!(index
            .iter()
            .any(|f| matches!(f.fragment.as_ref(), Some(Fragment::ForLoop(_)))));
        assert!(index
            .iter()
            .any(|f| matches!(f.fragment.as_ref(), Some(Fragment::IfCond(_)))));
    }

    #[test]
    fn named_for_builds_recursive_component_assets_and_styles() {
        for (css, expected_tokens) in [
            (":root { --accent: red; }", &[][..]),
            ("tree-view { --accent: red; }", &["accent"][..]),
        ] {
            let app = create_app_dir(&[
                ("index.html", "<tree-view></tree-view>"),
                (
                    "tree-view.html",
                    r#"<for id="tree-item" each="child in items"><span>{{child.name}}</span><token-leaf></token-leaf><for id="tree-item" each="child in child.children" /></for>"#,
                ),
                ("tree-view.css", css),
                ("token-leaf.html", "<b>leaf</b>"),
                ("token-leaf.css", "b { color: var(--accent); }"),
            ]);
            let result = build(BuildOptions {
                plugin: Some(Plugin::WebUI),
                css_bundle: true,
                component_asset_roots: vec!["tree-view".to_string()],
                ..light_options(app.path())
            })
            .unwrap();
            assert_eq!(result.protocol.tokens, expected_tokens, "{css}");
            assert!(!result.component_asset_files.is_empty());
            assert_eq!(
                result.protocol.style_closures["tree-view"].component_tags,
                ["tree-view", "token-leaf"]
            );
            let meta: serde_json::Value =
                serde_json::from_str(&result.protocol.components["tree-view"].template_json)
                    .unwrap();
            let blocks = meta["b"].as_array().unwrap();
            assert_eq!(
                blocks.len(),
                1,
                "recursive depth does not expand compiled metadata"
            );
            assert_eq!(meta["r"][0][2], blocks[0]["r"][0][2]);
            assert!(result.protocol_bytes.len() < 16_384);
        }
    }

    #[test]
    fn test_build_with_component_css() {
        let app = create_app_dir(&[
            ("index.html", "<my-card>Hello</my-card>"),
            (
                "my-card.html",
                r#"<template shadowrootmode="open"><div><slot></slot></div></template>"#,
            ),
            ("my-card.css", ".card { color: red; }"),
            ("my-card.ts", "export {};"),
        ]);
        let result = build(default_options(app.path())).unwrap();

        assert_eq!(result.css_files.len(), 1);
        assert_eq!(result.css_files[0].0, "my-card.css");
        assert!(result.css_files[0].1.contains("color: red"));
        assert_eq!(result.stats.css_file_count, 1);
    }

    #[test]
    fn light_css_bytes_align_across_link_style_and_module() {
        let authored = " \n.ready{color:red}\n ";
        let expected = authored;

        for strategy in [CssStrategy::Link, CssStrategy::Style, CssStrategy::Module] {
            let app = create_app_dir(&[
                ("index.html", "<my-card></my-card>"),
                ("my-card.html", "<p>content</p>"),
                ("my-card.css", authored),
            ]);
            let mut options = light_options(app.path());
            options.css = strategy;
            if strategy == CssStrategy::Link {
                options.css_file_name_template = "[name]-[hash].[ext]".to_string();
            }
            let result = build(options).unwrap();

            let actual = match strategy {
                CssStrategy::Link => {
                    let expected_name = webui_parser::CssLinkOptions::try_new(
                        "[name]-[hash].[ext]".to_string(),
                        None,
                    )
                    .unwrap()
                    .resolve("my-card", expected)
                    .filename;
                    assert_eq!(result.css_files[0].0, expected_name);
                    result.css_files[0].1.clone()
                }
                CssStrategy::Module => result.protocol.components["my-card"].css.clone(),
                CssStrategy::Style => {
                    assert_eq!(result.protocol.components["my-card"].css, expected);
                    result.protocol.components["my-card"].css.clone()
                }
            };
            assert_eq!(actual, expected, "mismatch for {strategy:?}");
            if strategy != CssStrategy::Link {
                assert_eq!(
                    result.protocol.component_style_resource("my-card"),
                    Some(expected)
                );
            }
            assert_eq!(
                result
                    .protocol
                    .style_closure("index.html")
                    .expect("entry closure"),
                ["my-card"],
                "Light CSS must be installed by the Document closure"
            );

            let protocol = Protocol::new(result.protocol.clone());
            let mut writer = StringWriter { buf: String::new() };
            WebUIHandler::new()
                .render(
                    &protocol,
                    &serde_json::json!({}),
                    &RenderOptions::new("index.html", "/"),
                    &mut writer,
                )
                .unwrap();
            match strategy {
                CssStrategy::Link => {
                    let href = &result.protocol.components["my-card"].css_href;
                    assert!(writer.buf.contains(&format!(
                        r#"<link rel="stylesheet" href="{href}" data-webui-resource="my-card" data-webui-strategy="link">"#
                    )));
                }
                CssStrategy::Style | CssStrategy::Module => {
                    let kind = if strategy == CssStrategy::Module {
                        "module"
                    } else {
                        "style"
                    };
                    assert!(writer.buf.contains(&format!(
                        r#"<style data-webui-resource="my-card" data-webui-strategy="{kind}">{expected}</style>"#
                    )));
                }
            }
        }
    }

    #[test]
    fn build_precomputes_style_closures_with_authored_shadow_cut() {
        let app = create_app_dir(&[
            (
                "index.html",
                "<light-card></light-card><shadow-card><after-card></after-card></shadow-card>",
            ),
            ("light-card.html", "<nested-card></nested-card>"),
            ("light-card.css", ".light{}"),
            (
                "shadow-card.html",
                r#"<template shadowrootmode="open"><nested-card></nested-card></template>"#,
            ),
            ("shadow-card.css", ".shadow{}"),
            ("nested-card.html", "<span>nested</span>"),
            ("nested-card.css", ".nested{}"),
            ("after-card.html", "<span>after</span>"),
            ("after-card.css", ".after{}"),
        ]);
        let mut options = light_options(app.path());
        options.css = CssStrategy::Style;
        let result = build(options).unwrap();

        assert_eq!(
            result
                .protocol
                .style_closure("index.html")
                .expect("entry closure"),
            ["light-card", "nested-card", "after-card"]
        );
        assert_eq!(
            result
                .protocol
                .style_closure("shadow-card")
                .expect("Shadow closure"),
            ["shadow-card", "nested-card"]
        );
    }

    /// A fixture that exercises both bundling outcomes at once: two components
    /// used only by the entry merge, and one reached from a second CSS tree is
    /// split out so neither tree over-delivers.
    fn bundling_app() -> tempfile::TempDir {
        create_app_dir(&[
            (
                "index.html",
                "<a-card></a-card><b-card></b-card><shared-card></shared-card>\
                 <shadow-card></shadow-card>",
            ),
            ("a-card.html", "<span>a</span>"),
            ("a-card.css", ".a{color:red}"),
            ("b-card.html", "<span>b</span>"),
            ("b-card.css", ".b{color:green}"),
            ("shared-card.html", "<span>shared</span>"),
            ("shared-card.css", ".shared{color:blue}"),
            (
                "shadow-card.html",
                r#"<template shadowrootmode="open"><shared-card></shared-card></template>"#,
            ),
            ("shadow-card.css", ".shadow{color:black}"),
        ])
    }

    /// Concatenate a closure's CSS the way the browser cascade sees it, once
    /// per component and once per chunk.
    fn closure_css(protocol: &WebUIProtocol, root: &str) -> (String, String) {
        let closure = protocol.style_closures.get(root).expect("closure");
        let unbundled = closure
            .component_tags
            .iter()
            .filter_map(|tag| protocol.components.get(tag))
            .map(|component| component.css.as_str())
            .collect::<Vec<_>>()
            .join("\n");
        let bundled = closure
            .style_chunks
            .iter()
            .filter_map(|index| protocol.style_chunk_resource(*index))
            .map(|(_, css)| css)
            .collect::<Vec<_>>()
            .join("\n");
        (unbundled, bundled)
    }

    #[test]
    fn bundling_preserves_the_cascade_of_every_closure() {
        let app = bundling_app();
        let mut options = light_options(app.path());
        options.css = CssStrategy::Style;
        options.css_bundle = true;
        let result = build(options).unwrap();

        let roots: Vec<String> = result.protocol.style_closures.keys().cloned().collect();
        assert!(roots.len() >= 2, "fixture must produce several CSS trees");
        let mut chunked = 0usize;
        for root in roots {
            let (unbundled, bundled) = closure_css(&result.protocol, &root);
            // A closure the runtime never installs as a unit keeps no chunks and
            // falls back to per-component delivery, which is the unbundled path.
            if bundled.is_empty() && !unbundled.is_empty() {
                continue;
            }
            chunked += 1;
            assert_eq!(
                bundled, unbundled,
                "chunked cascade diverged from the per-component cascade for `{root}`"
            );
        }
        assert!(chunked >= 2, "fixture must chunk several CSS trees");
    }

    #[test]
    fn bundling_merges_entry_local_styles_and_splits_shared_ones() {
        let app = bundling_app();
        let mut options = light_options(app.path());
        options.css = CssStrategy::Style;
        options.css_bundle = true;
        let result = build(options).unwrap();

        let members: Vec<&[String]> = result
            .protocol
            .style_chunks
            .iter()
            .map(|chunk| chunk.component_tags.as_slice())
            .collect();
        assert!(
            members.contains(&["a-card".to_string(), "b-card".to_string()].as_slice()),
            "entry-local components should merge: {members:?}"
        );
        assert!(
            members.contains(&["shared-card".to_string()].as_slice()),
            "a component reached from two CSS trees must stay alone: {members:?}"
        );

        // The shared chunk is the same index in both trees, so it is fetched and
        // cached once.
        let entry = result.protocol.style_closure_chunks("index.html").unwrap();
        let shadow = result.protocol.style_closure_chunks("shadow-card").unwrap();
        let shared = entry
            .iter()
            .find(|index| shadow.contains(index))
            .expect("both trees should share a chunk");
        assert_eq!(
            result.protocol.style_chunk_members(*shared).unwrap(),
            ["shared-card"]
        );
    }

    #[test]
    fn bundling_is_off_by_default_and_leaves_the_protocol_unchanged() {
        let app = bundling_app();
        let mut options = default_options(app.path());
        options.css = CssStrategy::Style;
        let result = build(options).unwrap();

        assert!(result.protocol.style_chunks.is_empty());
        for closure in result.protocol.style_closures.values() {
            assert!(closure.style_chunks.is_empty());
        }
    }

    #[test]
    fn bundling_link_emits_chunks_and_component_fallback_files() {
        let app = bundling_app();
        let mut options = light_options(app.path());
        options.css_bundle = true;
        let result = build(options).unwrap();

        let names: Vec<&str> = result
            .css_files
            .iter()
            .map(|(name, _)| name.as_str())
            .collect();
        for (tag, component) in &result.protocol.components {
            if component.css_href.is_empty() {
                continue;
            }
            assert!(
                names.contains(&component.css_href.as_str()),
                "`{tag}` needs its independently loaded fallback file: {names:?}"
            );
        }
        for chunk in &result.protocol.style_chunks {
            assert!(!chunk.css_href.is_empty(), "Link chunks need an href");
            assert!(
                names.contains(&chunk.css_href.as_str()),
                "every rendered chunk needs an emitted file: {names:?}"
            );
            assert!(
                chunk.css.is_empty(),
                "Link chunks ship their CSS as a file, not inline"
            );
        }
    }

    #[test]
    fn bundling_keeps_component_files_when_component_assets_need_them() {
        let app = create_app_dir(&[
            (
                "index.html",
                "<a-card></a-card><b-card></b-card><shared-card></shared-card>",
            ),
            ("a-card.html", "<span>a</span>"),
            ("a-card.css", ".a{color:red}"),
            ("b-card.html", "<span>b</span>"),
            ("b-card.css", ".b{color:green}"),
            ("shared-card.html", "<span>shared</span>"),
            ("shared-card.css", ".shared{color:blue}"),
            ("lazy-panel.html", "<a-card></a-card><p>lazy</p>"),
            ("lazy-panel.css", ".lazy{color:gray}"),
            ("lazy-panel.ts", "export {};"),
        ]);
        let mut options = light_options(app.path());
        options.plugin = Some(Plugin::WebUI);
        options.css_bundle = true;
        options.component_asset_roots = vec!["lazy-panel".to_string()];
        let result = build(options).unwrap();

        let names: Vec<&str> = result
            .css_files
            .iter()
            .map(|(name, _)| name.as_str())
            .collect();
        assert!(
            names.iter().any(|name| name.starts_with("lazy-panel")),
            "static assets fetch a component's own stylesheet: {names:?}"
        );
        assert!(
            names.iter().any(|name| name.starts_with("_chunk-")),
            "bundled chunks are still emitted: {names:?}"
        );
        assert!(
            result.component_asset_files[0]
                .content
                .contains(r#""a-card":{"kind":"link","href":"a-card.css"}"#),
            "a deferred CSS tree needs the exact external component resource even when the entry Document uses a bundle: {}",
            result.component_asset_files[0].content
        );
    }

    /// Render a built protocol and return the emitted HTML.
    fn render_html(protocol: &WebUIProtocol, route: &str) -> String {
        let protocol = Protocol::new(protocol.clone());
        let mut writer = StringWriter { buf: String::new() };
        WebUIHandler::new()
            .render(
                &protocol,
                &serde_json::json!({}),
                &RenderOptions::new("index.html", route),
                &mut writer,
            )
            .unwrap();
        writer.buf
    }

    /// Every stylesheet URL the rendered page tells the browser to fetch.
    fn linked_stylesheets(html: &str) -> Vec<&str> {
        let mut hrefs = Vec::new();
        let mut rest = html;
        while let Some(start) = rest.find("href=\"") {
            rest = &rest[start + "href=\"".len()..];
            let Some(end) = rest.find('"') else { break };
            let href = &rest[..end];
            if href.ends_with(".css") {
                hrefs.push(href);
            }
            rest = &rest[end..];
        }
        hrefs
    }

    /// The `data-webui-resource` values in emitted order.
    fn emitted_resources(html: &str) -> Vec<&str> {
        let mut resources = Vec::new();
        let mut rest = html;
        while let Some(start) = rest.find("data-webui-resource=\"") {
            rest = &rest[start + "data-webui-resource=\"".len()..];
            match rest.find('"') {
                Some(end) => {
                    resources.push(&rest[..end]);
                    rest = &rest[end..];
                }
                None => break,
            }
        }
        resources
    }

    #[test]
    fn bundled_rendering_emits_one_resource_per_chunk() {
        for strategy in [CssStrategy::Link, CssStrategy::Style] {
            let app = bundling_app();
            let mut options = light_options(app.path());
            options.css = strategy;
            options.css_bundle = true;
            let result = build(options).unwrap();

            let html = render_html(&result.protocol, "/");
            let resources = emitted_resources(&html);
            assert!(
                resources.contains(&"_chunk-a-card-2"),
                "{strategy:?} should deliver the merged chunk once: {resources:?}"
            );
            assert!(
                !resources.contains(&"a-card") && !resources.contains(&"b-card"),
                "{strategy:?} must not also deliver merged members: {resources:?}"
            );
        }
    }

    #[test]
    fn bundling_never_merges_an_authored_shadow_stylesheet() {
        // `shadow-card` sits between two Light components that share its exact
        // consumer set, so ordering alone would let all three merge.
        let app = create_app_dir(&[
            (
                "index.html",
                "<a-card></a-card><shadow-card></shadow-card><b-card></b-card>",
            ),
            ("a-card.html", "<span>a</span>"),
            ("a-card.css", ".a{color:red}"),
            ("b-card.html", "<span>b</span>"),
            ("b-card.css", ".b{color:green}"),
            (
                "shadow-card.html",
                r#"<template shadowrootmode="open"><span>s</span></template>"#,
            ),
            ("shadow-card.css", ".shadow{color:black}"),
        ]);
        let mut options = light_options(app.path());
        options.css = CssStrategy::Style;
        options.css_bundle = true;
        let result = build(options).unwrap();

        let chunk = result
            .protocol
            .style_chunks
            .iter()
            .find(|chunk| chunk.component_tags.iter().any(|tag| tag == "shadow-card"))
            .expect("shadow-card is styled, so it belongs to a chunk");
        // A single-member chunk is named after its member and carries its exact
        // bytes, which is what keeps the parse-time `css_href` and
        // `shadowrootadoptedstylesheets` references valid under bundling.
        assert_eq!(
            chunk.component_tags,
            vec!["shadow-card".to_string()],
            "an authored-Shadow stylesheet must stay in a chunk of its own"
        );
        assert_eq!(chunk.name, "shadow-card");
        assert_eq!(
            chunk.css, result.protocol.components["shadow-card"].css,
            "its chunk must carry the component's own bytes unchanged"
        );
    }

    #[test]
    fn bundling_never_links_a_stylesheet_the_build_did_not_write() {
        // The rendered page is the contract: every stylesheet URL the browser is
        // told to fetch — document links and declarative Shadow roots alike —
        // must name a file the bundled build actually emitted.
        let app = bundling_app();
        let mut options = light_options(app.path());
        options.css = CssStrategy::Link;
        options.css_bundle = true;
        let result = build(options).unwrap();

        let emitted: HashSet<&str> = result
            .css_files
            .iter()
            .map(|(name, _)| name.as_str())
            .collect();
        let html = render_html(&result.protocol, "/");
        let linked = linked_stylesheets(&html);
        assert!(
            !linked.is_empty(),
            "the page should link at least one stylesheet: {html}"
        );
        for href in &linked {
            let name = href.rsplit('/').next().unwrap_or(href);
            assert!(
                emitted.contains(name),
                "page links `{href}`, which the bundled build did not write: {emitted:?}"
            );
        }
    }

    #[test]
    fn bundling_is_rejected_for_the_module_strategy() {
        let app = bundling_app();
        let mut options = light_options(app.path());
        options.css = CssStrategy::Module;
        options.css_bundle = true;

        let Err(WebUIError::InvalidBuildOptions(message)) = build(options) else {
            panic!("Module builds resolve import-map specifiers per component");
        };
        assert!(
            message.contains("--css link"),
            "the error should name a strategy that works: {message}"
        );
    }

    #[test]
    fn bundled_rendering_delivers_the_same_css_in_the_same_order() {
        // Style mode inlines the CSS, so the rendered document carries the whole
        // cascade and the two builds can be compared rule for rule.
        let extract = |html: &str| -> Vec<String> {
            let mut blocks = Vec::new();
            let mut rest = html;
            while let Some(start) = rest.find("data-webui-strategy=\"style\">") {
                rest = &rest[start + "data-webui-strategy=\"style\">".len()..];
                match rest.find("</style>") {
                    Some(end) => {
                        blocks.push(rest[..end].to_string());
                        rest = &rest[end..];
                    }
                    None => break,
                }
            }
            blocks
        };

        let mut plan = Vec::new();
        for bundle in [false, true] {
            let app = bundling_app();
            let mut options = light_options(app.path());
            options.css = CssStrategy::Style;
            options.css_bundle = bundle;
            let result = build(options).unwrap();
            let html = render_html(&result.protocol, "/");
            plan.push(extract(&html).join("\n"));
        }

        assert_eq!(
            plan[1], plan[0],
            "bundling must not change the delivered cascade"
        );
        assert!(!plan[0].is_empty(), "fixture must deliver CSS");
    }

    #[test]
    fn bundled_rendering_never_repeats_a_chunk_across_css_trees() {
        let app = bundling_app();
        let mut options = light_options(app.path());
        options.css = CssStrategy::Style;
        options.css_bundle = true;
        let result = build(options).unwrap();

        let html = render_html(&result.protocol, "/");
        let resources = emitted_resources(&html);
        // `shared-card` is reached by the document tree and by `shadow-card`'s
        // ShadowRoot. Each tree scopes styles separately, so it is delivered once
        // per tree and never twice within one.
        let mut counts: HashMap<&str, usize> = HashMap::new();
        for resource in &resources {
            *counts.entry(*resource).or_insert(0) += 1;
        }
        let shadow_start = html
            .find(r#"<template shadowrootmode="open""#)
            .expect("declarative Shadow root");
        let document_resources = emitted_resources(&html[..shadow_start]);
        let mut document_counts: HashMap<&str, usize> = HashMap::new();
        for resource in &document_resources {
            *document_counts.entry(*resource).or_insert(0) += 1;
        }
        for (resource, count) in &document_counts {
            assert_eq!(
                *count, 1,
                "`{resource}` was delivered {count} times in the document tree: {resources:?}"
            );
        }
    }

    #[test]
    fn authored_shadow_css_bytes_are_not_lowered_or_trimmed() {
        let authored =
            " \n:host(.ready){color:red}:host-context(body){color:blue}::slotted(*){color:green}\n ";

        for strategy in [CssStrategy::Link, CssStrategy::Style, CssStrategy::Module] {
            let app = create_app_dir(&[
                ("index.html", "<my-card></my-card>"),
                (
                    "my-card.html",
                    r#"<template shadowrootmode="open"><p>content</p></template>"#,
                ),
                ("my-card.css", authored),
            ]);
            let mut options = default_options(app.path());
            options.css = strategy;
            let result = build(options).unwrap();

            match strategy {
                CssStrategy::Link => assert_eq!(result.css_files[0].1, authored),
                CssStrategy::Style | CssStrategy::Module => {
                    assert_eq!(result.protocol.components["my-card"].css, authored);
                    assert_eq!(
                        result.protocol.component_style_resource("my-card"),
                        Some(authored)
                    );
                }
            }
            assert_eq!(
                result
                    .protocol
                    .style_closure("my-card")
                    .expect("component closure"),
                ["my-card"],
                "the authored Shadow root owns its exact CSS resource"
            );

            let protocol = Protocol::new(result.protocol.clone());
            let mut writer = StringWriter { buf: String::new() };
            WebUIHandler::new()
                .render(
                    &protocol,
                    &serde_json::json!({}),
                    &RenderOptions::new("index.html", "/"),
                    &mut writer,
                )
                .unwrap();
            match strategy {
                CssStrategy::Link => {
                    let href = &result.protocol.components["my-card"].css_href;
                    assert!(writer.buf.contains(&format!(
                        r#"<template shadowrootmode="open"><link rel="stylesheet" href="{href}" data-webui-resource="my-card" data-webui-strategy="link">"#
                    )));
                }
                CssStrategy::Style | CssStrategy::Module => {
                    let kind = if strategy == CssStrategy::Module {
                        "module"
                    } else {
                        "style"
                    };
                    assert!(writer.buf.contains(&format!(
                        r#"<style data-webui-resource="my-card" data-webui-strategy="{kind}">{authored}</style>"#
                    )));
                    let template_start = writer
                        .buf
                        .find(r#"<template shadowrootmode="open""#)
                        .expect("declarative Shadow root");
                    let style_start = writer
                        .buf
                        .find(&format!(
                            r#"<style data-webui-resource="my-card" data-webui-strategy="{kind}">"#
                        ))
                        .expect("tree-local style");
                    let content_start = writer.buf.find("<p>content</p>").expect("component body");
                    assert!(template_start < style_start && style_start < content_start);
                }
            }
        }
    }

    #[test]
    fn test_build_strips_non_legal_css_comments_from_output_file() {
        let app = create_app_dir(&[
            ("index.html", "<my-card>Hello</my-card>"),
            (
                "my-card.html",
                r#"<template shadowrootmode="open"><div><slot></slot></div></template>"#,
            ),
            (
                "my-card.css",
                "/* remove var(--ignored) */ .card { color: var(--textColor); }",
            ),
        ]);
        let result = build(default_options(app.path())).unwrap();

        assert_eq!(result.css_files[0].1, " .card { color: var(--textColor); }");
        assert_eq!(result.protocol.tokens, vec!["textColor"]);
    }

    #[test]
    fn test_build_preserves_legal_css_comments_by_default() {
        let app = create_app_dir(&[
            ("index.html", "<my-card>Hello</my-card>"),
            (
                "my-card.html",
                r#"<template shadowrootmode="open"><div><slot></slot></div></template>"#,
            ),
            (
                "my-card.css",
                "/*! @license MIT */ .card { color: red; } /* remove */",
            ),
        ]);
        let result = build(default_options(app.path())).unwrap();

        assert_eq!(
            result.css_files[0].1,
            "/*! @license MIT */ .card { color: red; } "
        );
    }

    #[test]
    fn test_build_legal_comments_none_strips_legal_css_comments() {
        let app = create_app_dir(&[
            ("index.html", "<my-card>Hello</my-card>"),
            (
                "my-card.html",
                r#"<template shadowrootmode="open"><div><slot></slot></div></template>"#,
            ),
            ("my-card.css", "/*! @license MIT */ .card { color: red; }"),
        ]);
        let mut options = default_options(app.path());
        options.legal_comments = LegalComments::None;
        let result = build(options).unwrap();

        assert_eq!(result.css_files[0].1, " .card { color: red; }");
    }

    #[test]
    fn test_build_with_css_hashed_filename_template() {
        let app = create_app_dir(&[
            ("index.html", "<my-card>Hello</my-card>"),
            (
                "my-card.html",
                r#"<template shadowrootmode="open"><div><slot></slot></div></template>"#,
            ),
            ("my-card.css", ".card { color: red; }"),
        ]);
        let mut options = default_options(app.path());
        options.css_file_name_template = "[name]-[hash].[ext]".to_string();
        let result = build(options).unwrap();

        assert_eq!(result.css_files.len(), 1);
        let generated = &result.css_files[0].0;
        assert!(generated.starts_with("my-card-"));
        assert!(generated.ends_with(".css"));
        assert_eq!(generated.len(), "my-card-".len() + 8 + ".css".len());
        assert_eq!(
            result
                .protocol
                .components
                .get("my-card")
                .map(|c| c.css_href.as_str()),
            Some(generated.as_str())
        );
    }

    #[test]
    fn test_css_public_base_prefixes_css_href_only() {
        let app = create_app_dir(&[
            ("index.html", "<my-card>Hello</my-card>"),
            (
                "my-card.html",
                r#"<template shadowrootmode="open"><div><slot></slot></div></template>"#,
            ),
            ("my-card.css", ".card { color: red; }"),
        ]);
        let mut options = default_options(app.path());
        options.css_file_name_template = "[name]-[hash].[ext]".to_string();
        options.css_public_base = Some("https://cdn.example.com/assets".to_string());
        let result = build(options).unwrap();

        let filename = &result.css_files[0].0;
        assert!(filename.starts_with("my-card-"));
        let expected_href = format!("https://cdn.example.com/assets/{filename}");
        assert_eq!(
            result
                .protocol
                .components
                .get("my-card")
                .map(|c| c.css_href.as_str()),
            Some(expected_href.as_str())
        );
    }

    #[test]
    fn test_css_public_base_emits_protocol_handler_and_payload_resources() {
        let app = create_app_dir(&[
            (
                "index.html",
                "<html><head></head><body><my-card>Hello</my-card></body></html>",
            ),
            (
                "my-card.html",
                r#"<template shadowrootmode="open"><div><slot></slot></div></template>"#,
            ),
            ("my-card.css", ".card { color: red; }"),
        ]);
        let mut options = default_options(app.path());
        options.css_file_name_template = "[name]-[hash].[ext]".to_string();
        options.css_public_base = Some("https://cdn.example.com/assets".to_string());
        let result = build(options).unwrap();

        let filename = &result.css_files[0].0;
        let expected_href = format!("https://cdn.example.com/assets/{filename}");
        assert_eq!(
            result.protocol.component_style_resource("my-card"),
            Some(expected_href.as_str())
        );
        assert_eq!(
            result
                .protocol
                .style_closure("my-card")
                .expect("component closure"),
            ["my-card"]
        );

        let handler = WebUIHandler::new();
        let protocol = Protocol::new(result.protocol.clone());
        let mut writer = StringWriter { buf: String::new() };
        handler
            .render(
                &protocol,
                &serde_json::json!({}),
                &RenderOptions::new("index.html", "/"),
                &mut writer,
            )
            .unwrap();
        assert!(
            writer.buf.contains(&format!(
                r#"<link rel="stylesheet" href="{}" data-webui-resource="my-card" data-webui-strategy="link">"#,
                expected_href.replace('/', "&#x2F;")
            )),
            "handler Shadow-root resource should use CDN href: {}",
            writer.buf
        );
        let payload = protocol
            .render_component_templates(&["my-card"], "")
            .expect("component resource payload");
        assert_eq!(
            payload["componentStyles"]["resources"]["my-card"]["href"],
            expected_href
        );
    }

    #[test]
    fn test_css_public_base_keeps_webui_template_style_free() {
        let app = create_app_dir(&[
            ("index.html", "<my-card>Hello</my-card>"),
            (
                "my-card.html",
                r#"<template shadowrootmode="open"><div><slot></slot></div></template>"#,
            ),
            ("my-card.css", ".card { color: red; }"),
            ("my-card.ts", "export {};"),
        ]);
        let mut options = default_options(app.path());
        options.plugin = Some(Plugin::WebUI);
        options.css_file_name_template = "[name]-[hash].[ext]".to_string();
        options.css_public_base = Some("https://cdn.example.com/assets".to_string());
        let result = build(options).unwrap();

        let filename = &result.css_files[0].0;
        let expected_href = format!("https://cdn.example.com/assets/{filename}");
        let template = &result.protocol.components["my-card"].template_json;
        assert_eq!(
            result.protocol.component_style_resource("my-card"),
            Some(expected_href.as_str())
        );
        assert!(
            !template.contains(&expected_href),
            "WebUI templates must not duplicate handler-owned CSS links: {template}"
        );
    }

    #[test]
    fn test_invalid_css_template_is_rejected() {
        let app = create_app_dir(&[
            ("index.html", "<my-card>Hello</my-card>"),
            (
                "my-card.html",
                r#"<template shadowrootmode="open"><div><slot></slot></div></template>"#,
            ),
            ("my-card.css", ".card { color: red; }"),
        ]);
        let mut options = default_options(app.path());
        options.css_file_name_template = "[name]-[bogus].[ext]".to_string();
        let result = build(options);

        assert!(matches!(result, Err(WebUIError::InvalidBuildOptions(_))));
    }

    #[test]
    fn test_css_filename_collision_is_rejected() {
        let app = create_app_dir(&[
            ("index.html", "<card-a>A</card-a><card-b>B</card-b>"),
            (
                "card-a.html",
                r#"<template shadowrootmode="open"><div><slot></slot></div></template>"#,
            ),
            ("card-a.css", ".x { color: red; }"),
            (
                "card-b.html",
                r#"<template shadowrootmode="open"><div><slot></slot></div></template>"#,
            ),
            ("card-b.css", ".x { color: red; }"),
        ]);
        let mut options = default_options(app.path());
        options.css_file_name_template = "[hash].[ext]".to_string();
        let result = build(options);

        assert!(matches!(result, Err(WebUIError::InvalidBuildOptions(_))));
    }

    #[test]
    fn test_build_returns_static_component_asset_files() {
        let app = create_app_dir(&[
            ("index.html", "<app-shell></app-shell>"),
            ("app-shell.html", "<div></div>"),
            (
                "lazy-panel.html",
                r#"<if condition="ready"><p>{{title}}</p></if>"#,
            ),
            ("lazy-panel.ts", "export {};"),
        ]);
        let mut options = default_options(app.path());
        options.plugin = Some(Plugin::WebUI);
        options.component_asset_roots = vec!["lazy-panel".to_string()];

        let result = build(options).unwrap();

        assert_eq!(result.component_asset_files.len(), 2);
        assert_eq!(result.component_asset_files[0].name, "lazy-panel.webui.js");
        assert!(result.component_asset_files[0]
            .content
            .contains(r#""type":"webui-component-asset""#));
        assert!(result.component_asset_files[0]
            .content
            .contains(r#""version":4"#));
        assert!(result.component_asset_files[0]
            .content
            .contains(r#""root":"lazy-panel""#));
        assert!(result.component_asset_files[1]
            .content
            .contains(r#""templateFunctions":{"lazy-panel":"#));
        let root = &result.component_asset_files[0].content;
        let payload = &result.component_asset_files[1].content;
        for field in ["kind", "components", "requiredComponents"] {
            assert!(!root.contains(&format!("\"{field}\":")));
            assert!(!payload.contains(&format!("\"{field}\":")));
        }
        for field in ["type", "version\":4", "externalComponents", "imports"] {
            assert!(!payload.contains(&format!("\"{field}")));
        }
        assert!(!root.contains("\"templates\":"));
        assert!(!result.protocol.fragments.contains_key("lazy-panel"));
        assert!(
            !result
                .protocol
                .fragments
                .keys()
                .any(|key| key.starts_with("__webui_asset_root_")),
            "synthetic asset root fragments must not be serialized"
        );
    }

    #[test]
    fn component_assets_emit_enhanced_style_catalog_for_all_strategies() {
        for (strategy, kind) in [
            (CssStrategy::Link, "link"),
            (CssStrategy::Style, "style"),
            (CssStrategy::Module, "module"),
        ] {
            let app = create_app_dir(&[
                ("index.html", "<app-shell></app-shell>"),
                ("app-shell.html", "<p>Entry</p>"),
                ("lazy-panel.html", "<p>Lazy</p>"),
                ("lazy-panel.css", ".lazy{color:red}"),
            ]);
            let mut options = default_options(app.path());
            options.plugin = Some(Plugin::WebUI);
            options.css = strategy;
            options.component_asset_roots = vec!["lazy-panel".to_string()];

            let result = build(options).unwrap();
            let root = &result.component_asset_files[0].content;
            let component = &result.component_asset_files[1].content;
            assert!(root.contains(r#""version":4"#));
            assert!(component.contains(&format!(
                r#""componentStyles":{{"version":1,"strategy":"{kind}""#
            )));
            assert!(component.contains(&format!(r#""lazy-panel":{{"kind":"{kind}""#)));
            assert!(component.contains(r#""closures":{"lazy-panel":["lazy-panel"]}"#));
            if strategy == CssStrategy::Module {
                assert!(component
                    .contains(r#""lazy-panel":{"kind":"module","specifier":"lazy-panel","css":"#,));
            }
            if strategy == CssStrategy::Link {
                assert!(component.contains(r#""href":"lazy-panel.css""#));
                assert!(!component.contains("import.meta.url"));
            }
        }
    }

    #[test]
    fn test_build_emits_semantic_component_modules_and_keeps_them_out_of_protocol() {
        let app = create_app_dir(&[
            ("index.html", "<app-shell></app-shell>"),
            ("app-shell.html", "<entry-badge></entry-badge>"),
            ("entry-badge.html", "<span>Entry</span>"),
            ("entry-badge.css", ":host { display: inline-block; }"),
            (
                "lazy-panel.html",
                "<entry-badge></entry-badge><shared-detail></shared-detail><panel-only></panel-only>",
            ),
            (
                "secondary-panel.html",
                "<entry-badge></entry-badge><shared-detail></shared-detail><secondary-only></secondary-only>",
            ),
            ("shared-detail.html", "<p>Shared</p>"),
            ("shared-detail.css", ":host { display: block; }"),
            ("lazy-panel.css", ":host { color: green; }"),
            ("secondary-panel.css", ":host { color: blue; }"),
            ("panel-only.html", "<p>Panel</p>"),
            ("secondary-only.html", "<p>Secondary</p>"),
        ]);
        let mut options = default_options(app.path());
        options.plugin = Some(Plugin::WebUI);
        options.component_asset_roots =
            vec!["lazy-panel".to_string(), "secondary-panel".to_string()];

        let result = build(options).unwrap();

        for tag in [
            "lazy-panel",
            "secondary-panel",
            "shared-detail",
            "panel-only",
            "secondary-only",
        ] {
            assert!(
                !result.protocol.fragments.contains_key(tag),
                "asset-only fragment <{tag}> must not be serialized"
            );
            assert!(
                !result.protocol.components.contains_key(tag),
                "asset-only component <{tag}> must not be serialized"
            );
        }

        assert!(result.protocol.fragments.contains_key("app-shell"));
        assert!(result.protocol.components.contains_key("entry-badge"));
        assert_eq!(
            result.protocol.component_asset_style_preloads,
            vec![
                webui_protocol::ComponentAssetStylePreload {
                    root: "lazy-panel".to_string(),
                    style_hrefs: vec![
                        "lazy-panel.css".to_string(),
                        "shared-detail.css".to_string(),
                    ],
                },
                webui_protocol::ComponentAssetStylePreload {
                    root: "secondary-panel".to_string(),
                    style_hrefs: vec![
                        "secondary-panel.css".to_string(),
                        "shared-detail.css".to_string(),
                    ],
                },
            ]
        );

        assert_eq!(result.component_asset_files.len(), 7);
        assert_eq!(result.component_asset_files[0].name, "lazy-panel.webui.js");
        assert_eq!(
            result.component_asset_files[1].name,
            "secondary-panel.webui.js"
        );
        let lazy = &result.component_asset_files[0].content;
        assert!(lazy.contains(r#""version":4"#));
        assert!(lazy.contains(r#""root":"lazy-panel""#));
        assert!(lazy.contains(r#""externalComponents":["entry-badge"]"#));
        assert!(lazy.contains(r#""entry-badge":{"kind":"link","href":"entry-badge.css"}"#));
        assert!(!lazy.contains(
            r#""entry-badge":{"kind":"link","href":new URL("entry-badge.css",import.meta.url).href}"#
        ));
        for tag in ["lazy-panel", "panel-only", "shared-detail"] {
            let payload = component_payload(&result.component_asset_files, tag);
            assert!(lazy.contains(&payload.name));
        }
        assert!(!lazy.contains("@microsoft/webui-framework/component-asset-runtime.js"));
        assert!(!lazy.contains("export const preload"));
        assert!(!lazy.contains("export const create"));
        assert!(!lazy.contains(r#""templates":{"entry-badge":"#));
        assert!(!lazy.contains(r#""templates":{"shared-detail":"#));

        let shared = component_payload(&result.component_asset_files, "shared-detail");
        assert!(!shared.content.contains(r#""kind":"component""#));
        assert!(shared.content.contains(r#""templates":{"shared-detail":"#));
        assert!(shared.content.contains(r#""href":"shared-detail.css""#));
        assert!(!shared.content.contains("import.meta.url"));
    }

    #[test]
    fn build_to_disk_creates_component_asset_parent_directories() {
        let app = create_app_dir(&[
            ("index.html", "<app-shell></app-shell>"),
            ("app-shell.html", "<p>Entry</p>"),
            ("lazy-panel.html", "<p>Lazy</p>"),
        ]);
        let out = tempfile::tempdir().unwrap();
        let mut options = default_options(app.path());
        options.plugin = Some(Plugin::WebUI);
        options.component_asset_roots = vec!["lazy-panel".to_string()];

        build_to_disk(options, out.path()).unwrap();

        assert!(out.path().join("lazy-panel.webui.js").is_file());
        assert!(fs::read_dir(out.path().join("components"))
            .unwrap()
            .any(|entry| entry
                .unwrap()
                .file_name()
                .to_string_lossy()
                .starts_with("lazy-panel.")));
    }

    #[test]
    fn build_to_disk_preserves_noop_inputs_and_leaves_older_payloads() {
        let app = create_app_dir(&[
            ("index.html", "<main>Entry</main>"),
            ("lazy-panel.html", "<p>Initial</p>"),
        ]);
        let out = tempfile::tempdir().unwrap();
        let options = || {
            let mut options = default_options(app.path());
            options.plugin = Some(Plugin::WebUI);
            options.component_asset_roots = vec!["lazy-panel".to_string()];
            options
        };
        build_to_disk(options(), out.path()).unwrap();
        let root = out.path().join("lazy-panel.webui.js");
        let before = fs::metadata(&root).unwrap().modified().unwrap();
        build_to_disk(options(), out.path()).unwrap();
        assert_eq!(before, fs::metadata(&root).unwrap().modified().unwrap());

        for generation in 0..5 {
            fs::write(
                app.path().join("lazy-panel.html"),
                format!("<p>{generation}</p>"),
            )
            .unwrap();
            build_to_disk(options(), out.path()).unwrap();
        }
        assert_eq!(
            fs::read_dir(out.path().join("components")).unwrap().count(),
            6
        );
    }

    #[test]
    fn test_component_asset_graph_emits_each_component_once() {
        let app = create_app_dir(&[
            ("index.html", "<app-shell></app-shell>"),
            ("app-shell.html", "<p>Entry</p>"),
            (
                "root-a.html",
                "<shared-ab></shared-ab><shared-all></shared-all><only-a></only-a>",
            ),
            (
                "root-b.html",
                "<shared-ab></shared-ab><shared-all></shared-all><only-b></only-b>",
            ),
            ("root-c.html", "<shared-all></shared-all><only-c></only-c>"),
            ("shared-ab.html", "<p>AB</p>"),
            ("shared-all.html", "<p>All</p>"),
            ("only-a.html", "<p>A</p>"),
            ("only-b.html", "<p>B</p>"),
            ("only-c.html", "<p>C</p>"),
        ]);
        let mut options = default_options(app.path());
        options.plugin = Some(Plugin::WebUI);
        options.component_asset_roots = vec![
            "root-a".to_string(),
            "root-b".to_string(),
            "root-c".to_string(),
        ];

        let result = build(options).unwrap();
        assert_eq!(result.component_asset_files.len(), 11);
        assert_eq!(result.component_asset_files[0].name, "root-a.webui.js");
        assert_eq!(result.component_asset_files[1].name, "root-b.webui.js");
        assert_eq!(result.component_asset_files[2].name, "root-c.webui.js");
        let only_a = component_payload(&result.component_asset_files, "only-a");
        assert!(result.component_asset_files[0]
            .content
            .contains(&only_a.name));
        assert!(
            component_payload(&result.component_asset_files, "shared-ab")
                .content
                .contains(r#""templates":{"shared-ab":"#)
        );
        assert!(
            component_payload(&result.component_asset_files, "shared-all")
                .content
                .contains(r#""templates":{"shared-all":"#)
        );
    }

    #[test]
    fn test_component_asset_graph_is_root_order_independent_with_stable_imports() {
        let app = create_app_dir(&[
            ("index.html", "<app-shell></app-shell>"),
            ("app-shell.html", "<p>Entry</p>"),
            ("root-a.html", "<shared-detail></shared-detail>"),
            ("root-b.html", "<shared-detail></shared-detail>"),
            ("shared-detail.html", "<p>Shared</p>"),
        ]);
        let build_files = |roots: Vec<String>| {
            let mut options = default_options(app.path());
            options.plugin = Some(Plugin::WebUI);
            options.component_asset_roots = roots;
            options.css_file_name_template = "[name]-[hash].[ext]".to_string();
            build(options).unwrap().component_asset_files
        };

        let forward = build_files(vec!["root-a".to_string(), "root-b".to_string()]);
        let reverse = build_files(vec!["root-b".to_string(), "root-a".to_string()]);

        assert_eq!(forward, reverse);
        let shared_name = &component_payload(&forward, "shared-detail").name;
        assert!(forward[0].content.contains(shared_name));
        assert!(forward[1].content.contains(shared_name));
    }

    #[test]
    fn test_component_asset_style_preloads_use_final_css_hrefs() {
        let app = create_app_dir(&[
            ("index.html", "<app-shell></app-shell>"),
            ("app-shell.html", "<p>Entry</p>"),
            ("lazy-panel.html", "<p>Lazy</p>"),
            ("lazy-panel.css", ":host { display: block; }"),
        ]);
        let mut options = default_options(app.path());
        options.plugin = Some(Plugin::WebUI);
        options.component_asset_roots = vec!["lazy-panel".to_string()];
        options.css_file_name_template = "[name]-[hash].[ext]".to_string();
        options.css_public_base = Some("https://cdn.example.com/webui".to_string());

        let result = build(options).unwrap();
        let preload = &result.protocol.component_asset_style_preloads[0];

        assert_eq!(preload.root, "lazy-panel");
        assert_eq!(preload.style_hrefs.len(), 1);
        assert!(preload.style_hrefs[0].starts_with("https://cdn.example.com/webui/lazy-panel-"));
        assert!(preload.style_hrefs[0].ends_with(".css"));
    }

    #[test]
    fn test_light_component_asset_styles_are_retained_for_document_links() {
        let app = create_app_dir(&[
            ("index.html", "<app-shell></app-shell>"),
            ("app-shell.html", "<p>Entry</p>"),
            ("z-lazy-panel.html", "<a-lazy-child></a-lazy-child>"),
            ("z-lazy-panel.css", ".z-lazy-panel { display: block; }"),
            ("a-lazy-child.html", "<p>Child</p>"),
            ("a-lazy-child.css", ".a-lazy-child { color: green; }"),
        ]);
        let mut options = default_options(app.path());
        options.plugin = Some(Plugin::WebUI);
        options.dom = DomStrategy::Light;
        options.component_asset_roots = vec!["z-lazy-panel".to_string()];

        let result = build(options).unwrap();

        assert_eq!(
            result.protocol.component_asset_style_preloads,
            vec![webui_protocol::ComponentAssetStylePreload {
                root: "z-lazy-panel".to_string(),
                style_hrefs: vec![
                    "z-lazy-panel.css".to_string(),
                    "a-lazy-child.css".to_string(),
                ],
            }]
        );
    }

    #[test]
    fn test_metafile_describes_static_import_graph() {
        let app = create_app_dir(&[
            ("index.html", "<app-shell></app-shell>"),
            ("app-shell.html", "<p>Entry</p>"),
            ("root-a.html", "<shared-detail></shared-detail>"),
            ("root-b.html", "<shared-detail></shared-detail>"),
            ("shared-detail.html", "<p>Shared</p>"),
        ]);
        let mut options = default_options(app.path());
        options.plugin = Some(Plugin::WebUI);
        options.component_asset_roots = vec!["root-a".to_string(), "root-b".to_string()];
        options.metafile = true;

        let result = build(options).unwrap();
        let metafile = result.metafile.as_deref().unwrap();
        let value: serde_json::Value = serde_json::from_str(metafile).unwrap();
        assert!(value["inputs"]
            .get("webui:component/shared-detail")
            .is_some());
        assert_eq!(
            value["outputs"]["root-a.webui.js"]["entryPoint"],
            "webui:component/root-a"
        );
        let shared = component_payload(&result.component_asset_files, "shared-detail");
        assert_eq!(
            value["outputs"]["root-a.webui.js"]["imports"][1]["path"],
            shared.name
        );
        assert_eq!(
            value["outputs"]["root-a.webui.js"]["imports"][1]["kind"],
            "import-statement"
        );
        assert_eq!(
            value["inputs"]["webui:component/root-a"]["imports"][0]["kind"],
            "import-statement"
        );
        assert_eq!(
            value["outputs"]["root-a.webui.js"]["exports"],
            serde_json::json!(["default"])
        );
        assert_eq!(
            value["outputs"][&shared.name]["bytes"],
            shared.content.len()
        );
    }

    #[test]
    fn test_component_assets_reject_routes_with_stable_diagnostic() {
        let app = create_app_dir(&[
            (
                "index.html",
                r#"<route path="/" component="app-shell" exact />"#,
            ),
            ("app-shell.html", "<p>Entry</p>"),
            ("lazy-panel.html", "<p>Lazy</p>"),
        ]);
        let mut options = default_options(app.path());
        options.plugin = Some(Plugin::WebUI);
        options.component_asset_roots = vec!["lazy-panel".to_string()];

        let error = build(options).unwrap_err();
        match error {
            WebUIError::ComponentAssets(diagnostic) => {
                assert_eq!(
                    diagnostic.error_code(),
                    Some(webui_parser::codes::COMPONENT_ASSETS_WITH_ROUTES)
                );
                assert!(diagnostic.help_text().is_some());
            }
            other => panic!("expected route diagnostic, received {other}"),
        }
    }

    #[test]
    fn test_component_asset_input_name_is_independent_from_css_template() {
        let app = create_app_dir(&[
            ("index.html", "<app-shell></app-shell>"),
            ("app-shell.html", "<div></div>"),
            ("lazy-panel.html", "<p>Lazy</p>"),
            ("lazy-panel.css", ".panel { color: red; }"),
        ]);
        let mut options = default_options(app.path());
        options.plugin = Some(Plugin::WebUI);
        options.component_asset_roots = vec!["lazy-panel".to_string()];
        options.css_file_name_template = "[name]".to_string();

        let result = build(options).unwrap();

        assert!(result
            .component_asset_files
            .iter()
            .any(|file| file.name == "lazy-panel.webui.js"));
        assert!(result
            .css_files
            .iter()
            .any(|(name, _)| name == "lazy-panel"));
    }

    #[test]
    fn test_build_to_disk_rejects_protocol_name_collision_before_writing() {
        let app = create_app_dir(&[
            ("index.html", "<app-shell></app-shell>"),
            ("app-shell.html", "<div></div>"),
            ("lazy-panel.html", "<p>Lazy</p>"),
            ("lazy-panel.css", ".panel { color: red; }"),
        ]);
        let out = TempDir::new().unwrap();
        let mut options = default_options(app.path());
        options.plugin = Some(Plugin::WebUI);
        options.component_asset_roots = vec!["lazy-panel".to_string()];
        options.css_file_name_template = "protocol.bin".to_string();

        let result = build_to_disk(options, out.path());

        assert!(matches!(result, Err(WebUIError::InvalidBuildOptions(_))));
        assert!(!out.path().join("protocol.bin").exists());
    }

    #[test]
    fn test_css_href_set_for_light_dom_link_strategy() {
        let app = create_app_dir(&[
            ("index.html", "<has-css>A</has-css><no-css>B</no-css>"),
            ("has-css.html", "<p>styled</p>"),
            ("has-css.css", ".yes { color: green; }"),
            ("no-css.html", "<p>plain</p>"),
        ]);
        let options = default_options(app.path());
        let result = build(options).unwrap();

        let href = result
            .protocol
            .components
            .get("has-css")
            .map(|c| c.css_href.as_str())
            .unwrap_or("");
        assert_eq!(
            href, "has-css.css",
            "Light×Link component with CSS should have css_href"
        );

        let no_href = result
            .protocol
            .components
            .get("no-css")
            .map(|c| c.css_href.as_str())
            .unwrap_or("");
        assert!(
            no_href.is_empty(),
            "Component without CSS should have empty css_href"
        );
    }

    #[test]
    fn test_plugin_free_build_persists_component_shadow_usage() {
        let app = create_app_dir(&[
            (
                "index.html",
                "<light-card></light-card><shadow-card></shadow-card>",
            ),
            ("light-card.html", "<p>light</p>"),
            (
                "shadow-card.html",
                "<template shadowrootmode=\"open\"><slot></slot></template>",
            ),
        ]);
        let mut options = default_options(app.path());
        options.dom = DomStrategy::Light;
        options.plugin = None;
        let result = build(options).unwrap();

        assert!(!result.protocol.component_uses_shadow_dom("light-card"));
        assert!(result.protocol.component_uses_shadow_dom("shadow-card"));
        assert!(!result.protocol.components["light-card"].uses_shadow_dom);
        assert!(result.protocol.components["shadow-card"].uses_shadow_dom);

        let entry_html: String = result.protocol.fragments["index.html"]
            .fragments
            .iter()
            .filter_map(|fragment| match fragment.fragment.as_ref() {
                Some(Fragment::Raw(raw)) => Some(raw.value.as_str()),
                _ => None,
            })
            .collect();
        assert!(entry_html.contains("<light-card>"));
        assert!(entry_html.contains("<shadow-card>"));
        assert!(!entry_html.contains("<shadow-card data-wl"));
    }

    #[test]
    fn test_authored_shadow_under_light_matches_ssr_protocol_and_webui_metadata() {
        let app = create_app_dir(&[
            ("index.html", "<shadow-card>projected</shadow-card>"),
            (
                "shadow-card.html",
                "<!-- lead --><template shadowrootmode=\"open\"><slot></slot></template><!-- tail -->",
            ),
        ]);
        let mut options = default_options(app.path());
        options.plugin = Some(Plugin::WebUI);
        let result = build(options).unwrap();

        assert!(result.protocol.component_uses_shadow_dom("shadow-card"));
        assert!(result.protocol.components["shadow-card"]
            .template_json
            .contains("\"sd\":1"));

        let component_html: String = result.protocol.fragments["shadow-card"]
            .fragments
            .iter()
            .filter_map(|fragment| match fragment.fragment.as_ref() {
                Some(Fragment::Raw(raw)) => Some(raw.value.as_str()),
                _ => None,
            })
            .collect();
        assert_eq!(
            component_html,
            "<template shadowrootmode=\"open\"><slot></slot></template>"
        );
        let entry_html: String = result.protocol.fragments["index.html"]
            .fragments
            .iter()
            .filter_map(|fragment| match fragment.fragment.as_ref() {
                Some(Fragment::Raw(raw)) => Some(raw.value.as_str()),
                _ => None,
            })
            .collect();
        assert!(!entry_html.contains("data-wl"));
    }

    #[test]
    fn test_shadow_dom_link_strategy_sets_css_href() {
        // Shadow×Link: css_href is always set for Link-strategy components.
        // The handler uses protocol.css_strategy + component Shadow metadata
        // to decide preload (Shadow) vs stylesheet (Light) in <head>.
        let app = create_app_dir(&[
            ("index.html", "<my-card>A</my-card>"),
            (
                "my-card.html",
                r#"<template shadowrootmode="open"><p><slot></slot></p></template>"#,
            ),
            ("my-card.css", ".card { color: red; }"),
        ]);
        let result = build(default_options(app.path())).unwrap();

        let comp = result.protocol.components.get("my-card").unwrap();
        assert_eq!(
            comp.css_href, "my-card.css",
            "Shadow×Link should set css_href"
        );

        // Strategy fields on protocol
        assert_eq!(
            result.protocol.css_strategy(),
            webui_protocol::CssStrategy::Link,
        );

        // CSS file should still be emitted for the server to serve
        assert_eq!(
            result.css_files.len(),
            1,
            "CSS file should still be produced"
        );
    }

    #[test]
    fn test_css_href_empty_for_style_strategy() {
        let app = create_app_dir(&[
            ("index.html", "<my-card>A</my-card>"),
            (
                "my-card.html",
                r#"<template shadowrootmode="open"><p><slot></slot></p></template>"#,
            ),
            ("my-card.css", ".card { color: red; }"),
        ]);
        let mut options = default_options(app.path());
        options.css = CssStrategy::Style;
        let result = build(options).unwrap();

        let href = result
            .protocol
            .components
            .get("my-card")
            .map(|c| c.css_href.as_str())
            .unwrap_or("");
        assert!(href.is_empty(), "Style-strategy should not set css_href");
    }

    #[test]
    fn test_css_href_empty_for_module_strategy() {
        let app = create_app_dir(&[
            ("index.html", "<my-card>A</my-card>"),
            (
                "my-card.html",
                r#"<template shadowrootmode="open"><p><slot></slot></p></template>"#,
            ),
            ("my-card.css", ".card { color: red; }"),
        ]);
        let mut options = default_options(app.path());
        options.css = CssStrategy::Module;
        let result = build(options).unwrap();

        let href = result
            .protocol
            .components
            .get("my-card")
            .map(|c| c.css_href.as_str())
            .unwrap_or("");
        assert!(href.is_empty(), "Module-strategy should not set css_href");
        assert!(
            !result.protocol.components["my-card"].css.is_empty(),
            "Module-strategy should still populate css content"
        );
    }

    #[test]
    fn test_build_to_disk_writes_files() {
        let app = create_app_dir(&[
            ("index.html", "<my-card>Hello</my-card>"),
            (
                "my-card.html",
                r#"<template shadowrootmode="open"><div><slot></slot></div></template>"#,
            ),
            ("my-card.css", ".card { color: red; }"),
            ("my-card.ts", "export {};"),
        ]);
        let out = TempDir::new().unwrap();

        let stats = build_to_disk(default_options(app.path()), out.path()).unwrap();

        assert!(out.path().join("protocol.bin").exists());
        assert!(out.path().join("my-card.css").exists());
        assert_eq!(stats.css_file_count, 1);
        assert!(stats.fragment_count > 0);
    }

    #[test]
    fn test_build_to_disk_creates_nested_output_dir() {
        let app = create_app_dir(&[("index.html", "<h1>Hello</h1>")]);
        let out = TempDir::new().unwrap();
        let nested = out.path().join("nested").join("output");

        let stats = build_to_disk(default_options(app.path()), &nested).unwrap();
        assert!(nested.join("protocol.bin").exists());
        assert!(stats.fragment_count > 0);
    }

    #[test]
    fn test_build_missing_entry() {
        let app = create_app_dir(&[("other.html", "<h1>Not index</h1>")]);
        let result = build(default_options(app.path()));

        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(matches!(err, WebUIError::Io { .. }));
    }

    #[test]
    fn test_build_stats_populated() {
        let app = create_app_dir(&[("index.html", "<h1>{{title}}</h1>")]);
        let result = build(default_options(app.path())).unwrap();

        assert!(result.stats.fragment_count > 0);
        assert!(result.stats.protocol_size_bytes > 0);
        assert_eq!(result.stats.css_file_count, 0);
    }

    #[test]
    fn test_build_inline_css() {
        let app = create_app_dir(&[
            ("index.html", "<my-card>Hello</my-card>"),
            (
                "my-card.html",
                r#"<template shadowrootmode="open"><div><slot></slot></div></template>"#,
            ),
            ("my-card.css", ".card { color: red; }"),
        ]);
        let mut options = default_options(app.path());
        options.css = CssStrategy::Style;

        let result = build(options).unwrap();
        // Inline mode embeds CSS in <style> tags — no external CSS files
        assert!(result.css_files.is_empty());
        assert_eq!(result.stats.css_file_count, 0);
        assert!(result.stats.fragment_count > 0);
    }

    #[test]
    fn test_build_module_css() {
        let app = create_app_dir(&[
            ("index.html", "<my-card>Hello</my-card>"),
            (
                "my-card.html",
                r#"<template shadowrootmode="open"><div><slot></slot></div></template>"#,
            ),
            ("my-card.css", ".card { color: red; }"),
        ]);
        let mut options = default_options(app.path());
        options.css = CssStrategy::Module;

        let result = build(options).unwrap();
        // Module mode emits <script type="importmap"> data URIs — no external CSS files
        assert!(result.css_files.is_empty());
        assert_eq!(result.stats.css_file_count, 0);
        assert!(result.stats.fragment_count > 0);
    }

    #[test]
    fn test_build_custom_entry() {
        let app = create_app_dir(&[("page.html", "<h1>Custom</h1>")]);
        let mut options = default_options(app.path());
        options.entry = "page.html".to_string();

        let result = build(options).unwrap();
        assert!(result.protocol.fragments.contains_key("page.html"));
        assert!(!result.protocol.fragments.contains_key("index.html"));
    }

    #[test]
    fn test_build_protocol_roundtrip() {
        let app = create_app_dir(&[("index.html", "<h1>{{title}}</h1>")]);
        let result = build(default_options(app.path())).unwrap();

        let restored = WebUIProtocol::from_protobuf(&result.protocol_bytes).unwrap();
        assert!(restored.fragments.contains_key("index.html"));
    }

    #[test]
    fn protocol_is_available_from_facade() {
        let protocol = Protocol::new(WebUIProtocol::new(HashMap::new()));
        assert!(protocol.tokens().is_empty());
    }

    #[test]
    fn test_inspect_bytes_valid() {
        let app = create_app_dir(&[("index.html", "<h1>Hello</h1>")]);
        let result = build(default_options(app.path())).unwrap();

        let json_str = inspect_bytes(&result.protocol_bytes).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&json_str).unwrap();
        assert!(parsed.get("fragments").is_some());
    }

    #[test]
    fn test_inspect_bytes_invalid() {
        let result = inspect_bytes(b"not a protobuf");
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), WebUIError::Protocol(_)));
    }

    #[test]
    fn test_inspect_file() {
        let app = create_app_dir(&[("index.html", "<h1>Hello</h1>")]);
        let out = TempDir::new().unwrap();
        build_to_disk(default_options(app.path()), out.path()).unwrap();

        let json_str = inspect(&out.path().join("protocol.bin")).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&json_str).unwrap();
        assert!(parsed["fragments"]["index.html"]["fragments"].is_array());
    }

    #[test]
    fn test_inspect_missing_file() {
        let result = inspect(Path::new("/nonexistent/protocol.bin"));
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), WebUIError::Io { .. }));
    }

    #[test]
    fn test_build_with_components_local_path() {
        let app = create_app_dir(&[("index.html", "<ext-card>Hello</ext-card>")]);
        let ext_dir = TempDir::new().unwrap();
        fs::write(
            ext_dir.path().join("ext-card.html"),
            r#"<template shadowrootmode="open"><div class="card"><slot></slot></div></template>"#,
        )
        .unwrap();
        fs::write(
            ext_dir.path().join("ext-card.css"),
            ".card { border: 1px solid #ccc; }",
        )
        .unwrap();

        let mut options = default_options(app.path());
        options.components = vec![ext_dir.path().to_string_lossy().to_string()];

        let result = build(options).unwrap();
        assert!(result.protocol.fragments.contains_key("index.html"));
        assert_eq!(result.css_files.len(), 1);
        assert!(result.css_files[0].1.contains("border"));
    }

    #[test]
    fn test_build_with_scriptless_component_path_emits_dormant_template() {
        let app = create_app_dir(&[("index.html", "<ext-card></ext-card>")]);
        let ext_dir = TempDir::new().unwrap();
        fs::write(ext_dir.path().join("ext-card.html"), "<p>{{title}}</p>").unwrap();

        let mut options = default_options(app.path());
        options.plugin = Some(Plugin::WebUI);
        options.components = vec![ext_dir.path().to_string_lossy().to_string()];

        let result = build(options).unwrap();
        assert!(result
            .component_templates
            .iter()
            .any(|template| template.tag_name == "ext-card"));
        let component = result
            .protocol
            .components
            .get("ext-card")
            .expect("external scriptless component metadata should be retained");
        assert!(component.hydration_keys.is_empty());
        assert_eq!(component.navigation_keys, ["title"]);
        assert!(component.template_json.contains(r#""th":1"#));
    }

    #[test]
    fn test_build_with_scripted_component_path_emits_client_artifact() {
        let app = create_app_dir(&[("index.html", "<ext-card></ext-card>")]);
        let ext_dir = TempDir::new().unwrap();
        fs::write(ext_dir.path().join("ext-card.html"), "<p>{{title}}</p>").unwrap();
        fs::write(ext_dir.path().join("ext-card.ts"), "export {};").unwrap();

        let mut options = default_options(app.path());
        options.plugin = Some(Plugin::WebUI);
        options.components = vec![ext_dir.path().to_string_lossy().to_string()];

        let result = build(options).unwrap();
        let template = &result.protocol.components["ext-card"].template_json;
        assert!(!template.is_empty(), "template should be emitted");
    }

    #[test]
    fn test_build_rejects_projection_manifest_with_non_webui_plugin() {
        let app = create_app_dir(&[
            ("index.html", "<demo-card></demo-card>"),
            ("demo-card.html", "<p>{{name}}</p>"),
            ("demo-card.ts", "export {};"),
        ]);
        let manifest_json = projection::test_support::build_valid_manifest_json(
            app.path(),
            &[("demo-card.ts", "export {};")],
            &[("projection-bundle.js", "output")],
            &[(
                "demo-card",
                "demo-card.ts",
                &["projection-bundle.js"],
                &["name"],
                &["name"],
            )],
        );
        let manifest = projection::test_support::write_manifest(
            app.path(),
            "webui-projection.json",
            &manifest_json,
        );
        let mut options = default_options(app.path());
        // No plugin selected: default/FAST builds are incompatible with
        // projection manifests (`PROJ-B002`).
        options.projection_manifests = vec![manifest.into()];
        let err = build(options).expect_err("non-WebUI plugin + manifest should be rejected");
        assert!(
            err.chain_message().contains("PROJ-B002"),
            "msg: {}",
            err.chain_message()
        );
    }

    #[test]
    fn test_build_rejects_missing_scripted_component_coverage() {
        let app = create_app_dir(&[
            ("index.html", "<demo-card></demo-card>"),
            ("demo-card.html", "<p>{{name}}</p>"),
            ("demo-card.ts", "export {};"),
        ]);
        // Manifest is valid but never mentions `demo-card`, the only
        // compiled scripted component in this build.
        let manifest_json =
            projection::test_support::build_valid_manifest_json(app.path(), &[], &[], &[]);
        let manifest = projection::test_support::write_manifest(
            app.path(),
            "webui-projection.json",
            &manifest_json,
        );
        let mut options = default_options(app.path());
        options.plugin = Some(Plugin::WebUI);
        options.projection_manifests = vec![manifest.into()];
        let err = build(options).expect_err("missing coverage should fail the build");
        let message = err.chain_message();
        assert!(message.contains("PROJ-B001"), "msg: {message}");
        assert!(message.contains("demo-card"), "msg: {message}");
    }

    #[test]
    fn test_build_allows_unused_discovered_scripted_component_without_coverage() {
        let app = create_app_dir(&[
            ("index.html", "<demo-card></demo-card>"),
            ("demo-card.html", "<p>{{name}}</p>"),
            ("demo-card.ts", "export {};"),
            // `unused-card` is a scripted component discovered on disk but
            // never referenced from `index.html`, so it is not compiled
            // into the protocol and does not require manifest coverage.
            ("unused-card.html", "<p>{{title}}</p>"),
            ("unused-card.ts", "export {};"),
        ]);
        let manifest_json = projection::test_support::build_valid_manifest_json(
            app.path(),
            &[("demo-card.ts", "export {};")],
            &[("projection-bundle.js", "output")],
            &[(
                "demo-card",
                "demo-card.ts",
                &["projection-bundle.js"],
                &["name"],
                &["name"],
            )],
        );
        let manifest = projection::test_support::write_manifest(
            app.path(),
            "webui-projection.json",
            &manifest_json,
        );
        let mut options = default_options(app.path());
        options.plugin = Some(Plugin::WebUI);
        options.projection_manifests = vec![manifest.into()];
        let result = build(options).unwrap();

        assert!(!result.protocol.fragments.contains_key("unused-card"));
        let component = result.protocol.components.get("demo-card").unwrap();
        assert_eq!(component.hydration_keys, vec!["name"]);
    }

    #[test]
    fn test_build_allows_asset_only_scripted_component_without_projection_coverage() {
        let app = create_app_dir(&[
            ("index.html", "<app-shell></app-shell>"),
            ("app-shell.html", "<p>Entry</p>"),
            ("lazy-panel.html", "<p>{{title}}</p>"),
            ("lazy-panel.ts", "export {};"),
        ]);
        let manifest_json =
            projection::test_support::build_valid_manifest_json(app.path(), &[], &[], &[]);
        let manifest = projection::test_support::write_manifest(
            app.path(),
            "webui-projection.json",
            &manifest_json,
        );
        let mut options = default_options(app.path());
        options.plugin = Some(Plugin::WebUI);
        options.component_asset_roots = vec!["lazy-panel".to_string()];
        options.projection_manifests = vec![manifest.into()];

        let result = build(options).unwrap();

        assert_eq!(result.component_asset_files.len(), 2);
        assert!(!result.protocol.fragments.contains_key("lazy-panel"));
        assert!(!result.protocol.components.contains_key("lazy-panel"));
    }

    #[test]
    fn test_build_merges_multiple_projection_manifest_fragments() {
        let app = create_app_dir(&[
            (
                "index.html",
                "<html><body><card-a></card-a><card-b></card-b></body></html>",
            ),
            ("card-a.html", "<p>{{alpha}}</p>"),
            ("card-a.ts", "export {};"),
            ("card-b.html", "<p>{{beta}}</p>"),
            ("card-b.ts", "export {};"),
        ]);
        let json_a = projection::test_support::build_valid_manifest_json(
            app.path(),
            &[("card-a.ts", "export {};")],
            &[("card-a.js", "output-a")],
            &[(
                "card-a",
                "card-a.ts",
                &["card-a.js"],
                &["alpha"],
                &["alpha"],
            )],
        );
        let manifest_a =
            projection::test_support::write_manifest(app.path(), "fragment-a.json", &json_a);
        let json_b = projection::test_support::build_valid_manifest_json(
            app.path(),
            &[("card-b.ts", "export {};")],
            &[("card-b.js", "output-b")],
            &[("card-b", "card-b.ts", &["card-b.js"], &["beta"], &["beta"])],
        );
        let manifest_b =
            projection::test_support::write_manifest(app.path(), "fragment-b.json", &json_b);

        let mut options = default_options(app.path());
        options.plugin = Some(Plugin::WebUI);
        options.projection_manifests = vec![manifest_a.into(), manifest_b.into()];
        let result = build(options).unwrap();

        assert_eq!(
            result.protocol.initial_state_strategy,
            webui_protocol::InitialStateStrategy::Components as i32
        );
        let card_a = result.protocol.components.get("card-a").unwrap();
        assert_eq!(card_a.hydration_keys, vec!["alpha"]);
        let card_b = result.protocol.components.get("card-b").unwrap();
        assert_eq!(card_b.hydration_keys, vec!["beta"]);
    }

    #[test]
    fn test_build_hello_world_example() {
        let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        let app_dir = manifest_dir.join("../../examples/app/hello-world/src");

        let result = build(BuildOptions {
            app_dir,
            entry: "index.html".to_string(),
            ..BuildOptions::default()
        })
        .unwrap();

        let index = &result.protocol.fragments["index.html"].fragments;
        assert!(index.iter().any(
            |f| matches!(f.fragment.as_ref(), Some(Fragment::ForLoop(fl)) if fl.collection == "people")
        ));
        assert!(index
            .iter()
            .any(|f| matches!(f.fragment.as_ref(), Some(Fragment::IfCond(_)))));
    }

    // ── Security tests ───────────────────────────────────────────────

    #[test]
    fn test_css_filename_sanitizes_path_separators() {
        // Even if a component tag somehow contains path separators,
        // the filename should be sanitized to prevent directory traversal.
        let app = create_app_dir(&[("index.html", "<h1>Hello</h1>")]);
        let result = build(default_options(app.path())).unwrap();

        // Verify all CSS filenames are plain file names (no path separators)
        for (filename, _) in &result.css_files {
            assert!(
                !filename.contains('/') && !filename.contains('\\'),
                "CSS filename contains path separator: {filename}"
            );
        }
    }

    #[test]
    fn test_build_to_disk_css_stays_in_output_dir() {
        let app = create_app_dir(&[
            ("index.html", "<my-card>Hello</my-card>"),
            (
                "my-card.html",
                r#"<template shadowrootmode="open"><div><slot></slot></div></template>"#,
            ),
            ("my-card.css", ".card { color: red; }"),
        ]);
        let out = TempDir::new().unwrap();

        build_to_disk(default_options(app.path()), out.path()).unwrap();

        // Verify CSS file is written inside out_dir
        let css_path = out.path().join("my-card.css");
        assert!(css_path.exists());
        let canonical = css_path.canonicalize().unwrap();
        let out_canonical = out.path().canonicalize().unwrap();
        assert!(
            canonical.starts_with(&out_canonical),
            "CSS file escaped output directory"
        );
    }

    // ── Performance / edge case tests ────────────────────────────────

    #[test]
    fn test_build_empty_html() {
        let app = create_app_dir(&[("index.html", "")]);
        let result = build(default_options(app.path())).unwrap();

        assert!(result.protocol.fragments.contains_key("index.html"));
        assert_eq!(result.stats.fragment_count, 0);
        assert!(result.stats.protocol_size_bytes > 0);
    }

    #[test]
    fn test_build_large_fragment_count() {
        // Verify stats are accurate with many fragments
        let mut html = String::with_capacity(2000);
        for i in 0..50 {
            html.push_str(&format!("<p>Item {i}</p>\n"));
        }
        let app = create_app_dir(&[("index.html", &html)]);
        let result = build(default_options(app.path())).unwrap();

        assert!(result.stats.fragment_count > 0);
        assert_eq!(result.stats.css_file_count, 0);
    }

    #[test]
    fn test_build_to_disk_inline_mode_no_css_files() {
        let app = create_app_dir(&[
            ("index.html", "<my-card>Hello</my-card>"),
            (
                "my-card.html",
                r#"<template shadowrootmode="open"><div><slot></slot></div></template>"#,
            ),
            ("my-card.css", ".card { color: red; }"),
        ]);
        let out = TempDir::new().unwrap();
        let mut options = default_options(app.path());
        options.css = CssStrategy::Style;

        let stats = build_to_disk(options, out.path()).unwrap();

        assert!(out.path().join("protocol.bin").exists());
        assert!(!out.path().join("my-card.css").exists());
        assert_eq!(stats.css_file_count, 0);
    }

    #[test]
    fn test_build_stats_duration_is_nonzero() {
        let app = create_app_dir(&[("index.html", "<h1>Hello {{name}}</h1>")]);
        let result = build(default_options(app.path())).unwrap();

        assert!(!result.stats.duration.is_zero());
    }

    #[test]
    fn test_build_multiple_components_css() {
        let app = create_app_dir(&[
            ("index.html", "<card-a>A</card-a><card-b>B</card-b>"),
            (
                "card-a.html",
                r#"<template shadowrootmode="open"><div><slot></slot></div></template>"#,
            ),
            ("card-a.css", ".a { color: red; }"),
            (
                "card-b.html",
                r#"<template shadowrootmode="open"><span><slot></slot></span></template>"#,
            ),
            ("card-b.css", ".b { color: blue; }"),
        ]);
        let result = build(default_options(app.path())).unwrap();

        assert_eq!(result.css_files.len(), 2);
        assert_eq!(result.stats.css_file_count, 2);
        let filenames: Vec<&str> = result.css_files.iter().map(|(n, _)| n.as_str()).collect();
        assert!(filenames.contains(&"card-a.css"));
        assert!(filenames.contains(&"card-b.css"));
    }

    #[test]
    fn test_build_unused_component_css_not_emitted() {
        // card-b is registered but not referenced in index.html
        let app = create_app_dir(&[
            ("index.html", "<card-a>A</card-a>"),
            (
                "card-a.html",
                r#"<template shadowrootmode="open"><div><slot></slot></div></template>"#,
            ),
            ("card-a.css", ".a { color: red; }"),
            (
                "card-b.html",
                r#"<template shadowrootmode="open"><span><slot></slot></span></template>"#,
            ),
            ("card-b.css", ".b { color: blue; }"),
        ]);
        let result = build(default_options(app.path())).unwrap();

        assert_eq!(result.css_files.len(), 1);
        assert_eq!(result.css_files[0].0, "card-a.css");
    }

    #[test]
    fn test_build_unused_component_render_policy_not_emitted() {
        let app = create_app_dir(&[
            ("index.html", "<card-a>A</card-a>"),
            (
                "card-a.html",
                r#"<template w-render="lazy" w-reserve-block-size="10px"><div>a</div></template>"#,
            ),
            (
                "card-b.html",
                r#"<template w-render="lazy" w-reserve-block-size="20px"><div>b</div></template>"#,
            ),
        ]);
        let result = build(default_options(app.path())).unwrap();

        assert!(result.protocol.component_render_css.contains("card-a"));
        assert!(!result.protocol.component_render_css.contains("card-b"));
    }

    #[test]
    fn test_build_persists_interaction_work_policy() {
        let app = create_app_dir(&[
            ("index.html", "<interaction-shell></interaction-shell>"),
            (
                "interaction-shell.html",
                r#"<template w-hydrate="interaction"><button>Open</button></template>"#,
            ),
            (
                "interaction-shell.ts",
                "customElements.define('interaction-shell', class extends HTMLElement {});",
            ),
        ]);
        for plugin in [Plugin::WebUI, Plugin::FastV3] {
            let is_webui = matches!(plugin, Plugin::WebUI);
            let mut options = default_options(app.path());
            options.plugin = Some(plugin);
            let result = build(options).expect("interaction policy build");
            let component = &result.protocol.components["interaction-shell"];
            assert_eq!(
                component.work_policy,
                webui_protocol::ComponentWorkPolicy::Interaction as i32
            );
            if is_webui {
                assert!(component.template_json.contains(r#""wp":3"#));
            }
        }
    }

    #[test]
    fn test_build_persists_combined_render_interaction_policy() {
        let app = create_app_dir(&[
            ("index.html", "<interaction-panel></interaction-panel>"),
            (
                "interaction-panel.html",
                concat!(
                    r#"<template w-render="lazy" w-reserve-block-size="18rem" "#,
                    r#"w-hydrate="interaction"><button>Open</button></template>"#,
                ),
            ),
            (
                "interaction-panel.ts",
                "customElements.define('interaction-panel', class extends HTMLElement {});",
            ),
        ]);
        for plugin in [Plugin::WebUI, Plugin::FastV3] {
            let is_webui = matches!(plugin, Plugin::WebUI);
            let mut options = default_options(app.path());
            options.plugin = Some(plugin);
            let result = build(options).expect("combined interaction policy build");
            let component = &result.protocol.components["interaction-panel"];
            assert_eq!(
                component.work_policy,
                webui_protocol::ComponentWorkPolicy::LazyRenderInteraction as i32
            );
            assert!(result
                .protocol
                .component_render_css
                .contains("interaction-panel"));
            if is_webui {
                assert!(component.template_json.contains(r#""wp":4"#));
            }
        }
    }

    #[test]
    fn test_inspect_roundtrip_preserves_content() {
        let app = create_app_dir(&[("index.html", "<h1>{{title}}</h1>")]);
        let result = build(default_options(app.path())).unwrap();

        let json_str = inspect_bytes(&result.protocol_bytes).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&json_str).unwrap();

        let fragments = &parsed["fragments"]["index.html"]["fragments"];
        assert!(fragments.is_array());
        assert!(!fragments.as_array().unwrap().is_empty());
    }

    #[test]
    fn test_build_nonexistent_app_dir() {
        let options = BuildOptions {
            app_dir: PathBuf::from("/nonexistent/path/that/does/not/exist"),
            ..BuildOptions::default()
        };
        let result = build(options);
        assert!(result.is_err());
    }

    #[test]
    fn test_build_allows_fallback_chain_when_all_theme_tokens_exist() {
        let app = create_app_dir(&[
            ("index.html", "<my-card></my-card>"),
            ("my-card.html", "<div>Card</div>"),
            (
                "my-card.css",
                ":host { color: var(--token-a, var(--token-b, var(--token-c))); }",
            ),
        ]);
        let mut options = default_options(app.path());
        options.theme = Some(TokenFile {
            themes: HashMap::from([(
                "light".to_string(),
                HashMap::from([
                    ("token-a".to_string(), "red".to_string()),
                    ("token-b".to_string(), "blue".to_string()),
                    ("token-c".to_string(), "green".to_string()),
                ]),
            )]),
        });

        let result = build(options).expect("all fallback tokens are defined");
        assert!(result.protocol.tokens.contains(&"token-a".to_string()));
        assert!(result.protocol.tokens.contains(&"token-b".to_string()));
        assert!(result.protocol.tokens.contains(&"token-c".to_string()));
    }

    #[test]
    fn test_build_allows_literal_fallback_token_absent_from_theme() {
        let app = create_app_dir(&[
            ("index.html", "<my-card></my-card>"),
            ("my-card.html", "<div>Card</div>"),
            ("my-card.css", ":host { color: var(--brand, #000); }"),
        ]);
        let mut options = default_options(app.path());
        options.theme = Some(TokenFile {
            themes: HashMap::from([("light".to_string(), HashMap::new())]),
        });

        // The CSS literal fallback (`#000`) means `--brand` is not required from
        // the theme, so the build must succeed — but the token is still hoisted
        // so the runtime resolves it when a theme provides it.
        let result = build(options).expect("literal fallback should not fail the build");
        assert!(result.protocol.tokens.contains(&"brand".to_string()));
        // `--brand` is absent from every theme and only used with a literal
        // fallback, so it is surfaced as a non-fatal typo advisory.
        assert_eq!(result.warnings.len(), 1, "warnings: {:?}", result.warnings);
        assert!(result.warnings[0].body().contains("--brand"));
    }

    #[test]
    fn test_build_ancestor_inline_style_definition_after_comment_satisfies_descendant() {
        // `--foo-bar` is defined in the entry's inline <style> after a signal
        // comment and consumed inside a component. Custom properties inherit
        // through Shadow DOM, so the ancestor definition must satisfy the
        // descendant and the token must not be required from the theme.
        let app = create_app_dir(&[
            (
                "index.html",
                "<html><head><style>:root {\n  /*{{{tokens.light}}}*/\n  --foo-bar: 100px;\n}</style></head><body><my-card></my-card></body></html>",
            ),
            ("my-card.html", "<div>Card</div>"),
            ("my-card.css", ":host { padding: var(--foo-bar); }"),
        ]);
        let mut options = default_options(app.path());
        options.theme = Some(TokenFile {
            themes: HashMap::from([("light".to_string(), HashMap::new())]),
        });

        let result = build(options)
            .expect("ancestor inline-style definition (after a comment) should satisfy the child");
        assert!(
            !result.protocol.tokens.contains(&"foo-bar".to_string()),
            "ancestor-defined token should not be hoisted: {:?}",
            result.protocol.tokens
        );
    }

    #[test]
    fn test_build_no_warning_when_literal_fallback_token_is_themed() {
        let app = create_app_dir(&[
            ("index.html", "<my-card></my-card>"),
            ("my-card.html", "<div>Card</div>"),
            ("my-card.css", ":host { color: var(--brand, #000); }"),
        ]);
        let mut options = default_options(app.path());
        options.theme = Some(TokenFile {
            themes: HashMap::from([(
                "light".to_string(),
                HashMap::from([("brand".to_string(), "#123456".to_string())]),
            )]),
        });

        let result = build(options).expect("themed literal-fallback token builds");
        assert!(
            result.warnings.is_empty(),
            "a themed token must not warn: {:?}",
            result.warnings
        );
    }

    #[test]
    fn test_build_without_theme_produces_no_warnings() {
        let app = create_app_dir(&[
            ("index.html", "<my-card></my-card>"),
            ("my-card.html", "<div>Card</div>"),
            ("my-card.css", ":host { color: var(--brand, #000); }"),
        ]);
        let result = build(default_options(app.path())).unwrap();
        assert!(result.warnings.is_empty());
    }

    #[test]
    fn test_build_warns_for_multiple_outlets_in_route_component() {
        let app = create_app_dir(&[
            (
                "index.html",
                r#"<route path="/" component="app-shell"><route path="child" component="child-page" exact /></route>"#,
            ),
            (
                "app-shell.html",
                r#"<main><outlet /></main><aside><outlet /></aside>"#,
            ),
            ("child-page.html", "<p>Child</p>"),
        ]);

        let result = build(default_options(app.path())).unwrap();
        assert_eq!(result.warnings.len(), 1, "warnings: {:?}", result.warnings);
        let warning = &result.warnings[0];
        assert_eq!(warning.severity(), Severity::Warning);
        assert_eq!(
            warning.error_code(),
            Some(webui_parser::codes::MULTIPLE_OUTLETS)
        );
        assert_eq!(warning.component_name(), Some("app-shell"));
        assert!(warning.help_text().is_some());
    }

    #[test]
    fn test_build_warns_for_outlets_across_component_templates() {
        let app = create_app_dir(&[
            (
                "index.html",
                r#"<route path="/" component="app-shell"><route path="child" component="child-page" exact /></route>"#,
            ),
            (
                "app-shell.html",
                r#"<nested-layout></nested-layout><aside><outlet /></aside>"#,
            ),
            ("nested-layout.html", "<main><outlet /></main>"),
            ("child-page.html", "<p>Matched child</p>"),
        ]);

        let result = build(default_options(app.path())).unwrap();
        let html = render_html(&result.protocol, "/child");
        assert_eq!(html.matches("<p>Matched child</p>").count(), 1, "{html}");
        assert!(html.contains("<aside></aside>"), "{html}");
        assert_eq!(result.warnings.len(), 1, "warnings: {:?}", result.warnings);
        assert_eq!(
            result.warnings[0].error_code(),
            Some(webui_parser::codes::MULTIPLE_OUTLETS)
        );
        assert_eq!(result.warnings[0].component_name(), Some("app-shell"));
    }

    #[test]
    fn test_build_excludes_tokens_defined_by_ancestor_component_css() {
        let app = create_app_dir(&[
            ("index.html", "<component-a></component-a>"),
            ("component-a.html", "<component-b></component-b>"),
            ("component-a.css", ":host { --brand-color: red; }"),
            ("component-b.html", "<div>Child</div>"),
            ("component-b.css", ":host { color: var(--brand-color); }"),
        ]);
        let mut options = default_options(app.path());
        options.theme = Some(TokenFile {
            themes: HashMap::from([("light".to_string(), HashMap::new())]),
        });

        let result =
            build(options).expect("ancestor component custom property should satisfy child");
        assert!(
            !result.protocol.tokens.contains(&"brand-color".to_string()),
            "ancestor-defined token should not be exposed: {:?}",
            result.protocol.tokens
        );
    }

    #[test]
    fn test_build_scoped_parent_overrides_preserve_theme_defaults() {
        for selector in [
            ".green",
            ":host([split]) plain-control",
            ":host([active])",
            "@media (width > 10000px) { :host",
            "@supports (display: unknown) { :host",
            "@container (width > 10000px) { :host",
        ] {
            let mut css = format!("{selector} {{ --brand: var(--green); }}");
            if selector.starts_with('@') {
                css.push('}');
            }
            let app = create_app_dir(&[
                ("index.html", "<layout-container></layout-container>"),
                (
                    "layout-container.html",
                    "<plain-control></plain-control><div class=\"green\"><plain-control></plain-control></div>",
                ),
                ("layout-container.css", &css),
                ("plain-control.html", "<button>Primary</button>"),
                ("plain-control.css", "button { color: var(--brand); }"),
            ]);
            let mut options = default_options(app.path());
            options.theme = Some(TokenFile {
                themes: HashMap::from([(
                    "light".to_string(),
                    HashMap::from([
                        ("brand".to_string(), "black".to_string()),
                        ("green".to_string(), "green".to_string()),
                    ]),
                )]),
            });
            let result = build(options).expect("scoped overrides should build");
            assert_eq!(result.protocol.tokens, ["brand", "green"], "{selector}");

            let mut options = default_options(app.path());
            options.theme = Some(TokenFile {
                themes: HashMap::from([(
                    "light".to_string(),
                    HashMap::from([("green".to_string(), "green".to_string())]),
                )]),
            });
            let error = build(options).expect_err("uncovered child still requires --brand");
            assert!(error.chain_message().contains("missing-theme-token"));
        }
    }

    #[test]
    fn test_build_scoped_inline_overrides_preserve_theme_defaults() {
        let app = create_app_dir(&[
            (
                "index.html",
                "<style>.green { --brand: var(--green); }</style><plain-control></plain-control><div class=\"green\"><plain-control></plain-control></div>",
            ),
            ("plain-control.html", "<button>Primary</button>"),
            ("plain-control.css", "button { color: var(--brand); }"),
        ]);
        let result = build(default_options(app.path())).expect("build");
        assert_eq!(result.protocol.tokens, ["brand", "green"]);
    }

    #[test]
    fn test_build_does_not_use_sibling_component_definitions_for_theme_validation() {
        let app = create_app_dir(&[
            (
                "index.html",
                "<component-a></component-a><component-b></component-b>",
            ),
            ("component-a.html", "<div>A</div>"),
            ("component-a.css", ":host { --brand-color: red; }"),
            ("component-b.html", "<div>B</div>"),
            ("component-b.css", ":host { color: var(--brand-color); }"),
        ]);
        let mut options = default_options(app.path());
        options.theme = Some(TokenFile {
            themes: HashMap::from([("light".to_string(), HashMap::new())]),
        });

        let Err(err) = build(options) else {
            panic!("sibling custom property must not satisfy component-b");
        };
        let message = err.chain_message();
        assert!(message.contains("missing theme token"), "msg: {message}");
        assert!(message.contains("missing-theme-token"), "msg: {message}");
        assert!(message.contains("--brand-color"), "msg: {message}");
    }

    #[test]
    fn test_build_rejects_missing_theme_token_after_local_definition_filter() {
        let app = create_app_dir(&[
            ("index.html", "<my-card></my-card>"),
            ("my-card.html", "<div>Card</div>"),
            (
                "my-card.css",
                ":host { --token-a: red; --foo-bar: var(--token-a, var(--token-b, var(--token-c))); }",
            ),
        ]);
        let mut options = default_options(app.path());
        options.theme = Some(TokenFile {
            themes: HashMap::from([(
                "light".to_string(),
                HashMap::from([("token-b".to_string(), "green".to_string())]),
            )]),
        });

        let Err(err) = build(options) else {
            panic!("missing --token-c in the theme must fail the build");
        };
        let message = err.chain_message();
        assert!(message.contains("missing-theme-token"), "msg: {message}");
        assert!(message.contains("--token-c"), "msg: {message}");
        // The error demands the missing `--token-c`, never the locally-defined
        // `--token-a` (which only appears in the source snippet as context).
        assert!(!message.contains("add --token-a"), "msg: {message}");
    }

    mod package_discovery {
        use super::*;

        type TestResult = Result<(), Box<dyn std::error::Error>>;

        fn write(root: &Path, name: &str, content: &str) -> TestResult {
            let path = root.join(name);
            if let Some(parent) = path.parent() {
                fs::create_dir_all(parent)?;
            }
            fs::write(path, content)?;
            Ok(())
        }

        fn package_fixture(package: &Path, catalog: Option<&str>) -> TestResult {
            let mut metadata = serde_json::json!({
                "name": "@fixture/catalog", "customElements": "custom-elements.json"
            });
            if let Some(catalog) = catalog {
                metadata["webui"] = serde_json::json!({"components": [catalog]});
            }
            write(package, "package.json", &metadata.to_string())?;
            let catalog = package.join(catalog.unwrap_or("components"));
            write(&catalog, "fixture-card.html", "<p>Package component</p>")?;
            write(&catalog, "fixture-card.css", "p { color: blue; }")?;
            write(
                &catalog,
                "fixture-card.v2.html",
                "<span>Dotted component</span>",
            )?;
            write(
                package,
                "custom-elements.json",
                r#"{"modules":[{"path":"dist/manifest-card.js","declarations":[{"name":"ManifestCard","tagName":"manifest-card"}]}]}"#,
            )?;
            write(package, "dist/manifest-card.js", "export {};")?;
            write(
                package,
                "dist/manifest-card.template-webui.html",
                r#"<f-template name="manifest-card"><template><p>Manifest component</p></template></f-template>"#,
            )?;
            for report in [
                "test_results/coverage/lcov-report/core/initial-state.ts.html",
                "test_results/coverage/lcov-report/initial-state.ts.html",
            ] {
                write(
                    package,
                    report,
                    "<!doctype html><html><body>Generated coverage report</body></html>",
                )?;
            }
            Ok(())
        }

        fn assert_build(root: &Path, plugin: Option<Plugin>) -> TestResult {
            let manifest = matches!(plugin, Some(Plugin::FastV2 | Plugin::FastV3));
            let app = root.join("app/src");
            write(&app, "app-local.html", "<span>App component</span>")?;
            write(
                &app,
                "index.html",
                "<app-local></app-local><fixture-card></fixture-card><fixture-card.v2></fixture-card.v2><manifest-card></manifest-card>",
            )?;
            let options = BuildOptions {
                app_dir: app,
                components: vec!["@fixture/catalog".to_string()],
                plugin,
                css: CssStrategy::Style,
                ..BuildOptions::default()
            };
            for _ in 0..2 {
                let result = build(options.clone())?;
                assert_eq!(result.stats.component_count, if manifest { 4 } else { 3 });
                assert!(!result.protocol.fragments.contains_key("initial-state.ts"));
                let mut writer = StringWriter { buf: String::new() };
                WebUIHandler::new().render(
                    &Protocol::new(result.protocol),
                    &serde_json::json!({}),
                    &RenderOptions::new("index.html", "/"),
                    &mut writer,
                )?;
                for text in ["App component", "Package component", "Dotted component"] {
                    assert!(writer.buf.contains(text), "Missing rendered {text}");
                }
                assert!(writer.buf.contains("color: blue"));
                assert!(!writer.buf.contains("Generated coverage report"));
                assert_eq!(writer.buf.contains("Manifest component"), manifest);
            }
            Ok(())
        }

        #[test]
        fn package_build_excludes_reports_for_default_and_explicit_catalogs() -> TestResult {
            for (plugin, catalog) in [
                (None, None),
                (Some(Plugin::WebUI), Some("./src/components")),
                (Some(Plugin::FastV2), None),
                (Some(Plugin::FastV3), Some("./src/components")),
            ] {
                let root = tempfile::tempdir()?;
                package_fixture(&root.path().join("node_modules/@fixture/catalog"), catalog)?;
                assert_build(root.path(), plugin)?;
            }
            Ok(())
        }

        #[cfg(unix)]
        #[test]
        fn symlinked_workspace_package_build_excludes_generated_reports() -> TestResult {
            let root = tempfile::tempdir()?;
            let package = root.path().join("packages/catalog");
            package_fixture(&package, Some("./src/components"))?;
            fs::create_dir_all(root.path().join("node_modules/@fixture"))?;
            std::os::unix::fs::symlink(
                &package,
                root.path().join("node_modules/@fixture/catalog"),
            )?;
            assert_build(root.path(), Some(Plugin::FastV3))
        }

        #[test]
        fn distinct_files_and_overlapping_roots_preserve_duplicate_errors() -> TestResult {
            for (roots, second_file) in [
                (["./a", "./b"], Some("b/fixture-card.html")),
                (["./a", "./a"], None),
                (["./", "./a"], None),
                (["./a", "./"], None),
            ] {
                let root = tempfile::tempdir()?;
                let package = root.path().join("node_modules/@fixture/catalog");
                write(
                    &package,
                    "package.json",
                    &serde_json::json!({"webui":{"components":roots}}).to_string(),
                )?;
                write(&package, "a/fixture-card.html", "<p>First</p>")?;
                if let Some(path) = second_file {
                    write(&package, path, "<p>Second</p>")?;
                }
                let app = root.path().join("app");
                write(&app, "index.html", "<fixture-card></fixture-card>")?;
                let error = build(BuildOptions {
                    app_dir: app,
                    components: vec!["@fixture/catalog".to_string()],
                    ..BuildOptions::default()
                })
                .expect_err("Duplicate component names must remain errors");
                let message = error.chain_message();
                assert!(message.contains("fixture-card"), "{message}");
                assert!(message.contains("already registered"), "{message}");
            }
            Ok(())
        }
    }

    #[test]
    fn test_build_to_disk_returns_accurate_stats() {
        let app = create_app_dir(&[
            ("index.html", "<my-card>Hello</my-card><p>{{name}}</p>"),
            (
                "my-card.html",
                r#"<template shadowrootmode="open"><div><slot></slot></div></template>"#,
            ),
            ("my-card.css", ".card { color: red; }"),
        ]);
        let out = TempDir::new().unwrap();

        let stats = build_to_disk(default_options(app.path()), out.path()).unwrap();

        assert!(stats.fragment_count > 0);
        assert_eq!(stats.css_file_count, 1);
        assert!(stats.component_count > 0);
        assert!(stats.protocol_size_bytes > 0);
        assert!(!stats.duration.is_zero());
    }
}