oj_server 0.0.4

Dev server: on-demand compile over HTTP, WebSocket HMR channel, file watcher
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
// SPDX-License-Identifier: MIT
// Copyright (c) 2026 Raphael Amorim

//! Dev server with React Fast Refresh. Compiles TS/TSX/JSX on demand via
//! `oj_compiler`, rewriting relative imports to rooted URLs so each module has
//! one identity; the `oj_graph` propagates changes to the nearest boundary
//! (targeted `update`, else `full-reload`). Unbundled in dev by default.

use std::collections::HashMap;
use std::net::SocketAddr;
use std::path::{Component, Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

use anyhow::Context;
use axum::{
    Router,
    body::Body,
    extract::{Query, State, WebSocketUpgrade, ws::Message},
    http::{HeaderMap, StatusCode, Uri, header},
    response::{IntoResponse, Response},
    routing::get,
};
use oj_cache::{CachedModule, PersistentCache};

pub mod sidecar;
pub mod plugins;
use sidecar::{Sidecar, is_tailwind_css};
use plugins::PluginHost;
use oj_graph::{HmrDecision, ModuleGraph};
use oj_resolver::OjResolver;
use tokio::sync::broadcast;

/// oj's brand cobalt (`#2a33d4`, the docs-site accent) as a bold truecolor ANSI
/// wrap. Applied only to an interactive stdout with `NO_COLOR` unset; otherwise
/// the string is returned unchanged, so piped and CI output stay plain.
pub fn cobalt(s: &str) -> String {
    use std::io::IsTerminal;
    if std::env::var_os("NO_COLOR").is_none() && std::io::stdout().is_terminal() {
        format!("\x1b[1;38;2;42;51;212m{s}\x1b[0m")
    } else {
        s.to_string()
    }
}

/// The colored `oj` brand token followed by a plain `: ` — the prefix on oj's
/// own status lines.
fn oj_tag() -> String {
    format!("{}:", cobalt("oj"))
}

/// Turn freshly-read file bytes into a `String`, validating UTF-8 with SIMD
/// (`simdutf8`) instead of the standard library's scalar check, then reusing the
/// validated buffer directly (no re-validation, no copy). Every module read on
/// the cold-start crawl goes through here. On invalid UTF-8 it returns the same
/// `InvalidData` error `read_to_string` would.
fn bytes_to_string(bytes: Vec<u8>) -> std::io::Result<String> {
    match simdutf8::basic::from_utf8(&bytes) {
        // SAFETY: simdutf8 fully validated `bytes` as UTF-8 on this branch.
        Ok(_) => Ok(unsafe { String::from_utf8_unchecked(bytes) }),
        Err(_) => Err(std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            "stream did not contain valid UTF-8",
        )),
    }
}

const CLIENT_JS: &str = include_str!("assets/client.js");
/// Built-in `virtual:oj-routes` module: a file-based route manifest globbed
/// from `<root>/src/routes`. Shared by the dev server and `oj build`.
pub const OJ_ROUTES_JS: &str = include_str!("assets/oj-routes.js");
/// Client runtime for server functions (the `__ojServerCall` RPC helper).
const SERVER_FN_JS: &str = include_str!("assets/server-fn.js");
const REFRESH_RUNTIME_JS: &str = include_str!("assets/refresh-runtime.js");
const REFRESH_PREAMBLE_JS: &str = include_str!("assets/refresh-preamble.js");
const BUNDLE_RUNTIME_JS: &str = include_str!("assets/bundle-runtime.js");
/// The persistent SSR module-runner script (`oj dev --ssr`), spawned by the
/// `oj` crate under the app root so Node resolves the app's `node_modules`.
pub const SSR_RUNNER_JS: &str = include_str!("assets/ssr-runner.mjs");
const COMPILABLE: &[&str] = &["tsx", "ts", "jsx", "js", "mjs"];

/// TanStack Start adapter assets: a Node loader hook (resolves the framework's
/// four alias specifiers + compiles TS/JSX), the persistent SSR runner, the
/// route-tree generator, and the synthesized server/client/manifest entries.
const START_ASSETS: &[(&str, &str)] = &[
    ("resolve-pkg.mjs", include_str!("assets/start/resolve-pkg.mjs")),
    ("esbuild-assets.mjs", include_str!("assets/start/esbuild-assets.mjs")),
    ("vite-plugin-bridge.mjs", include_str!("assets/start/vite-plugin-bridge.mjs")),
    ("glob-transform.mjs", include_str!("assets/start/glob-transform.mjs")),
    ("cf-server.mjs", include_str!("assets/start/cf-server.mjs")),
    ("css-host.mjs", include_str!("assets/start/css-host.mjs")),
    ("loader.mjs", include_str!("assets/start/loader.mjs")),
    ("loader-util.mjs", include_str!("assets/start/loader-util.mjs")),
    ("runner.mjs", include_str!("assets/start/runner.mjs")),
    ("generate.mjs", include_str!("assets/start/generate.mjs")),
    ("gen-resolver.mjs", include_str!("assets/start/gen-resolver.mjs")),
    ("fn-stubs.mjs", include_str!("assets/start/fn-stubs.mjs")),
    ("bundle-client.mjs", include_str!("assets/start/bundle-client.mjs")),
    ("build.mjs", include_str!("assets/start/build.mjs")),
    ("live-reload.js", include_str!("assets/start/live-reload.js")),
    ("server-entry.tsx", include_str!("assets/start/server-entry.tsx")),
    ("client-entry.tsx", include_str!("assets/start/client-entry.tsx")),
    ("start-entry.ts", include_str!("assets/start/start-entry.ts")),
    ("plugin-adapters.ts", include_str!("assets/start/plugin-adapters.ts")),
    ("manifest.ts", include_str!("assets/start/manifest.ts")),
];

/// Write the TanStack Start adapter assets into `dir` (`.oj-cache/start`).
pub fn write_start_assets(dir: &Path) -> std::io::Result<()> {
    std::fs::create_dir_all(dir)?;
    for (name, content) in START_ASSETS {
        std::fs::write(dir.join(name), content)?;
    }
    Ok(())
}

/// A TanStack Start app: `@tanstack/react-start` in package.json plus a
/// `src/routes/` directory.
pub fn is_tanstack_start_app(root: &Path) -> bool {
    root.join("src/routes").is_dir()
        && std::fs::read_to_string(root.join("package.json"))
            .map(|s| s.contains("@tanstack/react-start"))
            .unwrap_or(false)
}

pub struct DevServer {
    pub root: PathBuf,
    /// CLI `--port`; `None` falls back to config `server.port` then 5199.
    pub port: Option<u16>,
    /// CLI `--bundle`; OR-ed with config `bundle`.
    pub bundle: bool,
}

struct ServerState {
    root: PathBuf,
    /// Where static assets are served from at the URL root (Vite's publicDir);
    /// defaults to `<root>/public`, overridden by config/vite `publicDir`.
    public_dir: PathBuf,
    bundle: bool,
    reload_tx: broadcast::Sender<String>,
    graph: Mutex<ModuleGraph>,
    resolver: Arc<OjResolver>,
    /// Resolver for the "ssr" environment (node conditions), used by the
    /// module-runner endpoint so server modules resolve their node variants.
    ssr_resolver: Arc<OjResolver>,
    cache: PersistentCache,
    /// Maps url to (content key, output). Content key re-checked per request,
    /// so this needs no watcher-driven invalidation to stay correct.
    memory: Mutex<HashMap<String, (String, Arc<CachedModule>)>>,
    /// Per-url compile locks: concurrent requests (or crawl vs request) for
    /// the same module coalesce into one compile.
    compile_locks: Mutex<HashMap<String, Arc<tokio::sync::Mutex<()>>>>,
    /// Flips true when the eager startup crawl has the full graph.
    crawl_done: tokio::sync::watch::Receiver<bool>,
    /// Out-of-root files the resolver legitimately resolved (workspace
    /// packages etc). /@fs/ requests are served only from this set, so the
    /// scheme cannot be used for directory traversal.
    fs_allow: Arc<Mutex<std::collections::HashSet<PathBuf>>>,
    /// Cached directory listings for relative-import resolution (see
    /// `is_file_cached`); cleared wholesale on any watcher burst.
    dir_cache: Arc<Mutex<DirCache>>,
    /// Monotonic patch counter; the client detects a gap in the sequence
    /// (a dropped WS frame after a backgrounded tab / reconnect) and reloads
    /// rather than applying patches onto a diverged module graph.
    patch_seq: std::sync::atomic::AtomicU64,
    /// Assembled bundle-mode chunk: (etag, bytes), memoized until the watcher
    /// sees a change; unchanged reloads answer 304 without re-assembling.
    chunk_cache: Mutex<Option<(String, Arc<String>)>>,
    /// Dedicated disk-cache writer (single thread, bounded queue).
    cache_writes: tokio::sync::mpsc::Sender<(String, Arc<CachedModule>)>,
    /// Lazily-spawned Tailwind v4 Node sidecar + the css urls it owns
    /// (regenerated whenever any source file changes).
    tailwind: tokio::sync::OnceCell<std::sync::Arc<Sidecar>>,
    tailwind_urls: Mutex<std::collections::HashSet<String>>,
    /// The app has a `postcss.config.*`, so all css (not just Tailwind-flagged)
    /// runs through the CSS sidecar (the app's own PostCSS plugin chain) before
    /// Lightning, matching Vite. `false` keeps the pure-Rust Lightning path.
    has_postcss: bool,
    /// Module list persisted by the previous session's crawl: lets a warm
    /// start emit the full modulepreload list immediately, without HTML
    /// ever waiting on the live crawl.
    preload_snapshot: Vec<String>,
    /// `server.proxy` rules: (path prefix, entry). Empty = no proxying.
    proxy: Vec<(String, oj_config::ProxyEntry)>,
    /// Client for forwarding proxied requests.
    http: reqwest::Client,
    /// Author-provided virtual modules: import id maps to module source, served
    /// at `/@virtual/<id>`. The first slice of the plugin pipeline.
    virtual_modules: std::collections::BTreeMap<String, String>,
    /// Node plugin host running Vite/Rollup `transform` hooks (present when the
    /// app has an `oj.plugins.*`).
    plugins: Option<std::sync::Arc<PluginHost>>,
    /// Port of the plugin host's `configureServer` middleware server, if any
    /// plugin registered dev-server middleware. Requests oj can't serve are
    /// forwarded here before the SPA fallback / 404.
    plugin_mw_port: Option<u16>,
    /// A second plugin host running as the "ssr" environment (Vite Environment
    /// API), lazily spawned the first time an SSR module is compiled so plain
    /// `oj dev` doesn't spawn it. Its transform runs on server modules, so
    /// `applyToEnvironment("ssr")` plugins actually execute.
    plugins_ssr: tokio::sync::OnceCell<Option<std::sync::Arc<PluginHost>>>,
    /// Prebuilt config JSON for the "ssr" host (identical to the client host's
    /// but `environment.name` is "ssr").
    ssr_plugin_config: String,
    /// Runtime handle so the sync file-watcher thread can call async plugin
    /// hooks (handleHotUpdate).
    rt: tokio::runtime::Handle,
    /// Configured `base` (e.g. `/riotermjs/`). In dev, requests carrying this
    /// prefix (app fetches built from `import.meta.env.BASE_URL`) have it
    /// stripped before file lookup, so the app serves under `base` like Vite.
    base: Option<String>,
}

/// A fully-configured dev server that hasn't been bound to a socket yet.
/// Returned by [`DevServer::build_app`] so other servers (dev-server SSR) can
/// compose the dev pipeline (Fast Refresh, HMR WebSocket, on-demand module
/// compilation) beneath their own routes.
pub struct BuiltApp {
    pub router: Router,
    pub host: std::net::IpAddr,
    pub port: u16,
    pub proxy_prefixes: Vec<String>,
    pub root: PathBuf,
    pub started: Instant,
}

impl DevServer {
    pub async fn run(self) -> anyhow::Result<()> {
        let built = self.build_app().await?;
        let addr = SocketAddr::from((built.host, built.port));
        let listener = tokio::net::TcpListener::bind(addr)
            .await
            .with_context(|| format!("cannot bind {addr}"))?;
        println!("  {} dev server", cobalt("oj"));
        println!("  root: {}", built.root.display());
        println!("  {}", cobalt(&format!("http://localhost:{}/", built.port)));
        if !built.proxy_prefixes.is_empty() {
            println!("  proxy: {}", built.proxy_prefixes.join(", "));
        }
        println!("  ready in {:?}", built.started.elapsed());
        axum::serve(listener, built.router).await?;
        Ok(())
    }

    /// Configure the dev server (config, .env, state, watcher, crawl, routes,
    /// proxy) and return it as a [`BuiltApp`] without binding a listener.
    pub async fn build_app(self) -> anyhow::Result<BuiltApp> {
        let root = self
            .root
            .canonicalize()
            .with_context(|| format!("app root not found: {}", self.root.display()))?;

        // Load oj.config.*: the source for proxy/port/host/bundle/envPrefix.
        let mut config = oj_config::load(&root).map_err(|e| anyhow::anyhow!("{e}"))?;

        // When the app configures itself through a `vite.config` (no
        // `oj.plugins.*`), adopt its `base`, `server.port`/`host`, `define`, and
        // `resolve.alias` for any field oj.config left unset. Shared with the
        // production build so `oj dev` and `oj build` agree.
        plugins::adopt_vite_config_values(&mut config, &root);

        // Load .env files (dev mode) and install the import.meta.env defines
        // before any module compiles. envPrefix from config overrides VITE_.
        let env_prefix = config.env_prefix.as_deref().unwrap_or("VITE_");
        let env_dir = config.env_dir.as_deref().map(|d| root.join(d)).unwrap_or_else(|| root.clone());
        let env = oj_env::load(&env_dir, "development");
        let mut defines = oj_env::import_meta_env_defines(
            &env,
            "development",
            true,
            config.base.as_deref().unwrap_or("/"),
            env_prefix,
        );
        // Config-driven `define`: the top-level `define` plus per-environment
        // overrides (Vite Environment API). The dev server has a single compiler
        // define table, so it holds the union of client + ssr defines; distinct
        // keys coexist (same key across environments resolves to the last).
        defines.extend(oj_config::config_defines(&config));
        defines.extend(oj_config::environment_defines(&config, "client"));
        defines.extend(oj_config::environment_defines(&config, "ssr"));
        oj_compiler::set_import_meta_env(defines);

        // Precedence: CLI flag > config > built-in default.
        let server_cfg = config.server.clone().unwrap_or_default();
        let port = self.port.or(server_cfg.port).unwrap_or(5199);
        let bundle = self.bundle || config.bundle.unwrap_or(false);
        let host: std::net::IpAddr = match server_cfg.host.as_deref() {
            Some("0.0.0.0") | Some("true") => [0, 0, 0, 0].into(),
            Some(h) => h.parse().unwrap_or([127, 0, 0, 1].into()),
            None => [127, 0, 0, 1].into(),
        };
        let proxy: Vec<(String, oj_config::ProxyEntry)> =
            server_cfg.proxy.clone().unwrap_or_default().into_iter().collect();

        // Where plugins come from: oj.plugins.* (array) or a vite.config.*
        // (default export's `plugins`). The host reads them per `pluginsFormat`.
        // A TanStack Start app's vite.config plugins are the framework's (run by
        // the start adapter, not the plugin host), and depend on Vite internals
        // oj does not host, so skip loading them here.
        let plugin_src = if is_tanstack_start_app(&root) {
            None
        } else {
            plugins::plugin_source(&root)
        };
        let (plugins_path, plugins_format, plugins_label) = match plugin_src {
            Some(plugins::PluginSource::OjPlugins(p)) => {
                let label = p.file_name().unwrap().to_string_lossy().into_owned();
                (Some(p), "oj", label)
            }
            Some(plugins::PluginSource::ViteConfig(p)) => (Some(p), "vite", "vite.config".to_string()),
            None => (None, "oj", String::new()),
        };

        // Config the plugin hosts receive in their config()/configResolved()
        // hooks. The client host tags itself the "client" environment; the ssr
        // host (lazily spawned for server modules) flips it to "ssr" so
        // applyToEnvironment("ssr") plugins run there.
        let mut plugin_cfg = serde_json::json!({
            "config": {
                "root": root.display().to_string(),
                "base": config.base.clone().unwrap_or_else(|| "/".into()),
                "mode": "development",
                "command": "serve",
                "define": config.define,
                "server": { "port": port, "host": server_cfg.host },
                "environments": config.environments,
            },
            "env": { "command": "serve", "mode": "development" },
            "environment": { "name": "client", "mode": "development" },
            "pluginsFormat": plugins_format,
        });
        let plugin_config = plugin_cfg.to_string();
        plugin_cfg["environment"]["name"] = serde_json::json!("ssr");
        let ssr_plugin_config = plugin_cfg.to_string();
        let plugin_host = match plugins_path {
            Some(file) => match PluginHost::spawn(&root, &file, &plugin_config).await {
                Ok(host) => {
                    println!("  plugins: {plugins_label}");
                    // buildStart fires once when the dev server starts (Vite
                    // semantics; buildEnd is a prod-build hook, and the dev
                    // server has no close lifecycle to fire it on).
                    if let Err(e) = host.build_start().await {
                        eprintln!("oj: plugin buildStart failed: {e}");
                    }
                    Some(host)
                }
                Err(e) => {
                    eprintln!("oj: plugin host failed to start: {e}");
                    None
                }
            },
            None => None,
        };
        // Ask the host whether any plugin registered configureServer middleware.
        let plugin_mw_port = match &plugin_host {
            Some(host) => host.middleware_port().await,
            None => None,
        };
        if let Some(p) = plugin_mw_port {
            println!("  plugin middleware: forwarding unmatched requests to :{p}");
        }

        let started = Instant::now();
        let (reload_tx, _) = broadcast::channel::<String>(64);
        let (crawl_tx, crawl_rx) = tokio::sync::watch::channel(false);
        let (write_tx, mut write_rx) =
            tokio::sync::mpsc::channel::<(String, Arc<CachedModule>)>(65536);
        // publicDir: config/vite value resolved against root (an absolute value
        // wins), else the default `<root>/public`.
        let public_dir = config
            .public_dir
            .as_ref()
            .map(|p| root.join(p))
            .unwrap_or_else(|| root.join("public"));
        let state = Arc::new(ServerState {
            root: root.clone(),
            public_dir,
            bundle,
            reload_tx,
            graph: Mutex::new(ModuleGraph::new()),
            resolver: Arc::new(OjResolver::with_options(
                &root,
                &oj_config::resolve_conditions(&config, "client"),
                &oj_config::resolve_alias(&config, "client"),
            )),
            ssr_resolver: Arc::new(OjResolver::with_options(
                &root,
                &oj_config::resolve_conditions(&config, "ssr"),
                &oj_config::resolve_alias(&config, "ssr"),
            )),
            cache: PersistentCache::new(
                root.join(".oj-cache"),
                env!("CARGO_PKG_VERSION"),
            ),
            memory: Mutex::new(HashMap::new()),
            compile_locks: Mutex::new(HashMap::new()),
            crawl_done: crawl_rx,
            tailwind: tokio::sync::OnceCell::new(),
            tailwind_urls: Mutex::new(std::collections::HashSet::new()),
            has_postcss: has_postcss_config(&root),
            fs_allow: Arc::new(Mutex::new(std::collections::HashSet::new())),
            dir_cache: Arc::new(Mutex::new(DirCache::new())),
            patch_seq: std::sync::atomic::AtomicU64::new(0),
            chunk_cache: Mutex::new(None),
            cache_writes: write_tx,
            preload_snapshot: load_graph_snapshot(&root),
            proxy,
            http: reqwest::Client::new(),
            virtual_modules: config.virtual_modules.clone().unwrap_or_default(),
            plugins: plugin_host,
            plugin_mw_port,
            plugins_ssr: tokio::sync::OnceCell::new(),
            ssr_plugin_config,
            rt: tokio::runtime::Handle::current(),
            base: config.base.clone().filter(|b| b != "/"),
        });
        {
            let state = Arc::clone(&state);
            std::thread::spawn(move || {
                while let Some((key, module)) = write_rx.blocking_recv() {
                    state.cache.put(&key, &module);
                }
            });
        }
        spawn_watcher(Arc::clone(&state));
        spawn_crawl(Arc::clone(&state), crawl_tx);

        let mut app = Router::new()
            .route("/@oj/client.js", get(|| async { js(CLIENT_JS) }))
            .route("/@oj/refresh-runtime.js", get(|| async { js(REFRESH_RUNTIME_JS) }))
            .route("/@oj/refresh-preamble.js", get(|| async { js(REFRESH_PREAMBLE_JS) }))
            .route("/@oj/bundle-runtime.js", get(|| async { js(BUNDLE_RUNTIME_JS) }))
            .route("/@oj/chunk.js", get(serve_chunk))
            .route("/@oj/patch.js", get(serve_patch))
            .route("/@oj/lazy.js", get(serve_lazy))
            .route("/@oj/routes.js", get(serve_oj_routes))
            .route("/@oj/server-fn.js", get(|| async { js(SERVER_FN_JS) }))
            .route("/@ssr-resolve", get(ssr_resolve))
            .route("/@ssr-module", get(ssr_module))
            .route("/__ws", get(ws_upgrade))
            .fallback(get(serve_path));
        // Configured `server.headers` (COOP/COEP, etc.) applied to every
        // response; needed for e.g. SharedArrayBuffer-based apps.
        let extra_headers: Vec<(header::HeaderName, header::HeaderValue)> = config
            .server
            .as_ref()
            .and_then(|s| s.headers.as_ref())
            .map(|h| {
                h.iter()
                    .filter_map(|(k, v)| Some((k.parse().ok()?, v.parse().ok()?)))
                    .collect()
            })
            .unwrap_or_default();
        if !extra_headers.is_empty() {
            app = app.layer(axum::middleware::from_fn_with_state(
                Arc::new(extra_headers),
                apply_dev_headers,
            ));
        }
        // Proxy runs ahead of routing so configured prefixes (/api, ...) are
        // forwarded before hitting the file fallback.
        if !state.proxy.is_empty() {
            app = app.layer(axum::middleware::from_fn_with_state(
                Arc::clone(&state),
                proxy_middleware,
            ));
        }
        let proxy_prefixes: Vec<String> =
            state.proxy.iter().map(|(p, _)| p.clone()).collect();
        let app = app.with_state(state);

        Ok(BuiltApp { router: app, host, port, proxy_prefixes, root, started })
    }
}

fn js(body: impl IntoResponse) -> Response {
    ([(header::CONTENT_TYPE, "text/javascript")], body).into_response()
}

/// Module-runner endpoint: resolve `spec` as imported from `importer`. Returns
/// `{"external":true,"spec":...}` for anything under node_modules (the runner
/// imports those natively in Node) or `{"id":"<abs>"}` for app source (which
/// the runner fetches from [`ssr_module`]). This plus [`ssr_module`] is the
/// server-side half of dev SSR: a persistent Node runner links the SSR module
/// graph on demand, so edits re-evaluate incrementally with no bundle step.
async fn ssr_resolve(
    State(state): State<Arc<ServerState>>,
    Query(q): Query<HashMap<String, String>>,
) -> Response {
    let (Some(importer), Some(spec)) = (q.get("importer"), q.get("spec")) else {
        return (StatusCode::BAD_REQUEST, "importer and spec required").into_response();
    };
    let importer_dir = Path::new(importer).parent().unwrap_or(&state.root);
    // Resolve with the "ssr" environment's conditions (node), not the client's.
    match state.ssr_resolver.resolve(importer_dir, spec) {
        Ok(p) => {
            let s = p.to_string_lossy();
            let body = if s.contains("/node_modules/") {
                serde_json::json!({ "external": true, "spec": spec })
            } else {
                serde_json::json!({ "id": s })
            };
            js_response_json(body)
        }
        Err(e) => {
            // A plugin (ssr environment) may own this specifier (virtual
            // modules etc). The returned id is fetched from ssr_module, which
            // consults the plugin's load hook for the source.
            if let Some(host) = ssr_plugin_host(&state).await {
                if let Ok(Some(id)) = host.resolve_id(spec, importer).await {
                    return js_response_json(serde_json::json!({ "id": id }));
                }
            }
            // Unresolvable bare specifier (e.g. a Node builtin): let Node try it.
            if !spec.starts_with('.') && !spec.starts_with('/') {
                return js_response_json(serde_json::json!({ "external": true, "spec": spec }));
            }
            (StatusCode::NOT_FOUND, format!("cannot resolve {spec}: {}", e.reason)).into_response()
        }
    }
}

fn js_response_json(v: serde_json::Value) -> Response {
    ([(header::CONTENT_TYPE, "application/json")], v.to_string()).into_response()
}

/// Module-runner endpoint: compile one app-source module for server-side
/// evaluation. Plain TS/JSX prod transform (no Fast Refresh, no browser HMR
/// glue), import specifiers left raw for the runner's linker; CSS Modules
/// become their class-name map (hashed off the root-relative id, matching the
/// client) and JSON becomes an ESM module.
async fn ssr_module(
    State(state): State<Arc<ServerState>>,
    Query(q): Query<HashMap<String, String>>,
) -> Response {
    let Some(id) = q.get("id") else {
        return (StatusCode::BAD_REQUEST, "id required").into_response();
    };
    let path = PathBuf::from(id);
    // Real file, or (for a plugin-resolved id with no file, a virtual module)
    // the "ssr" plugin host's load hook.
    let (source, from_plugin) = match std::fs::read(&path).and_then(bytes_to_string) {
        Ok(s) => (s, false),
        Err(read_err) => match ssr_plugin_host(&state).await {
            Some(host) => match host.load(id).await {
                Ok(Some(code)) => (code, true),
                _ => return (StatusCode::NOT_FOUND, format!("{id}: {read_err}")).into_response(),
            },
            None => return (StatusCode::NOT_FOUND, format!("{id}: {read_err}")).into_response(),
        },
    };
    let ext = path.extension().and_then(|e| e.to_str());
    // CSS/JSON handling is for real files only; virtual modules are JS.
    if !from_plugin && matches!(ext, Some("css") | Some("scss") | Some("sass")) {
        return match ssr_css_module(&state.root, &path, &source) {
            Ok(code) => js(code),
            Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, e).into_response(),
        };
    }
    if !from_plugin && ext == Some("json") {
        return match oj_compiler::json::to_esm(&source, id) {
            Ok(code) => js(code),
            Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, format!("{e}")).into_response(),
        };
    }
    // Run user plugins' transform as the "ssr" environment before compiling, so
    // applyToEnvironment("ssr") plugins execute on server modules (the client
    // host, a different environment, transforms the browser copy separately).
    let source = match ssr_plugin_host(&state).await {
        Some(host) => host.transform(&source, id).await.unwrap_or(source),
        None => source,
    };
    // A virtual id has no usable file extension; compile it as TSX so the JS/TS
    // parser runs (mirrors the client's serve_plugin_id).
    let compile_path: PathBuf =
        if from_plugin { PathBuf::from("virtual.tsx") } else { path };
    match oj_compiler::compile(&compile_path, &source, &oj_compiler::CompileOptions::prod()) {
        Ok(out) => js(out.code),
        Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, format!("{e}")).into_response(),
    }
}

/// The lazily-spawned "ssr" environment plugin host (spawned on first use so
/// plain `oj dev` never starts it). `None` if the app has no plugins.
async fn ssr_plugin_host(state: &Arc<ServerState>) -> Option<std::sync::Arc<PluginHost>> {
    state
        .plugins_ssr
        .get_or_init(|| async {
            let file = match plugins::plugin_source(&state.root)? {
                plugins::PluginSource::OjPlugins(p) | plugins::PluginSource::ViteConfig(p) => p,
            };
            match PluginHost::spawn(&state.root, &file, &state.ssr_plugin_config).await {
                Ok(host) => {
                    eprintln!("oj ssr: plugins (ssr environment) from {}", file.display());
                    Some(host)
                }
                Err(e) => {
                    eprintln!("oj ssr: plugin host failed to start: {e}");
                    None
                }
            }
        })
        .await
        .clone()
}

/// Compile a (possibly CSS-module / Sass) stylesheet into an ESM module for the
/// runner: `export default <class map>`. Class names hash off the root-relative
/// id, so they match the dev pipeline and the SSR markup hydrates cleanly.
fn ssr_css_module(root: &Path, path: &Path, source: &str) -> Result<String, String> {
    let css_src = if oj_css::is_sass(&path.to_string_lossy()) {
        oj_css::compile_sass(source, path.parent())?
    } else {
        source.to_string()
    };
    let css_id = match path.strip_prefix(root) {
        Ok(rel) => format!("/{}", rel.display()),
        Err(_) => path.to_string_lossy().to_string(),
    };
    let output = oj_css::compile_css(&css_id, &css_src, true)?;
    Ok(match output.exports {
        Some(exports) => {
            let map: serde_json::Map<String, serde_json::Value> =
                exports.into_iter().map(|(k, v)| (k, serde_json::Value::String(v))).collect();
            format!("export default {};", serde_json::Value::Object(map))
        }
        None => "export default {};".to_string(),
    })
}

/// Static server for a production build (`oj preview`). Serves `dir`,
/// strips `base`, refuses traversal, and falls back to `index.html` for
/// extensionless routes (SPA client routing).
pub async fn preview(
    dir: PathBuf,
    port: u16,
    base: String,
    headers: Vec<(String, String)>,
) -> anyhow::Result<()> {
    let dir = dir
        .canonicalize()
        .with_context(|| format!("build dir not found: {} (run `oj build` first)", dir.display()))?;
    let headers: Vec<(header::HeaderName, header::HeaderValue)> = headers
        .iter()
        .filter_map(|(k, v)| Some((k.parse().ok()?, v.parse().ok()?)))
        .collect();
    let state = Arc::new((dir.clone(), base, headers));
    let app = Router::new().fallback(get(preview_serve)).with_state(state);
    let addr = SocketAddr::from(([127, 0, 0, 1], port));
    let listener = tokio::net::TcpListener::bind(addr)
        .await
        .with_context(|| format!("cannot bind {addr}"))?;
    println!("  {} preview", cobalt("oj"));
    println!("  serving: {}", dir.display());
    println!("  {}", cobalt(&format!("http://localhost:{port}/")));
    axum::serve(listener, app).await?;
    Ok(())
}

/// Map a request path (with the base stripped) to a file under the build
/// dir, or `None` for a traversal attempt. Empty becomes `index.html`.
fn preview_rel<'a>(path: &'a str, base: &str) -> Option<String> {
    let trimmed = path.strip_prefix(base.trim_end_matches('/')).unwrap_or(path);
    let rel = trimmed.trim_start_matches('/');
    if rel.split('/').any(|seg| seg == "..") {
        return None;
    }
    Some(if rel.is_empty() { "index.html".to_string() } else { rel.to_string() })
}

async fn preview_serve(
    State(state): State<Arc<(PathBuf, String, Vec<(header::HeaderName, header::HeaderValue)>)>>,
    uri: Uri,
) -> Response {
    let (dir, base, extra_headers) = &*state;
    let Some(rel) = preview_rel(uri.path(), base) else {
        return (StatusCode::FORBIDDEN, "oj: path traversal denied").into_response();
    };
    let file = dir.join(&rel);
    let ext = Path::new(&rel).extension().and_then(|e| e.to_str()).unwrap_or("");

    // Existing file: serve it. Otherwise, extensionless routes fall back to
    // index.html so client-side routing works on deep links.
    let (target, ctype) = if file.is_file() {
        (file, content_type(ext))
    } else if ext.is_empty() {
        (dir.join("index.html"), "text/html; charset=utf-8")
    } else {
        return (StatusCode::NOT_FOUND, format!("oj: not found: {rel}")).into_response();
    };

    match tokio::fs::read(&target).await {
        Ok(bytes) => {
            let mut resp = ([(header::CONTENT_TYPE, ctype)], bytes).into_response();
            let h = resp.headers_mut();
            for (name, value) in extra_headers {
                h.insert(name.clone(), value.clone());
            }
            resp
        }
        Err(_) => (StatusCode::NOT_FOUND, "oj: not found").into_response(),
    }
}

async fn ws_upgrade(
    State(state): State<Arc<ServerState>>,
    upgrade: WebSocketUpgrade,
) -> impl IntoResponse {
    upgrade.on_upgrade(move |mut socket| async move {
        let mut rx = state.reload_tx.subscribe();
        loop {
            tokio::select! {
                msg = rx.recv() => match msg {
                    Ok(text) => {
                        if socket.send(Message::Text(text.into())).await.is_err() {
                            break;
                        }
                    }
                    Err(broadcast::error::RecvError::Lagged(_)) => continue,
                    Err(broadcast::error::RecvError::Closed) => break,
                },
                incoming = socket.recv() => match incoming {
                    None | Some(Err(_)) => break,
                    Some(Ok(Message::Text(text))) => handle_client_message(&state, &text),
                    Some(Ok(_)) => {}
                },
            }
        }
    })
}

/// Forward requests whose path matches a `server.proxy` prefix to the
/// configured target (longest prefix wins), otherwise pass through. Supports
/// `changeOrigin`, `ws` (marker only for now), and `^from -> to` rewrite.
/// Add the app's configured `server.headers` (e.g. COOP/COEP for
/// SharedArrayBuffer) to every dev response.
async fn apply_dev_headers(
    State(headers): State<Arc<Vec<(header::HeaderName, header::HeaderValue)>>>,
    req: axum::extract::Request,
    next: axum::middleware::Next,
) -> Response {
    let mut resp = next.run(req).await;
    let h = resp.headers_mut();
    for (name, value) in headers.iter() {
        h.insert(name.clone(), value.clone());
    }
    resp
}

async fn proxy_middleware(
    State(state): State<Arc<ServerState>>,
    req: axum::extract::Request,
    next: axum::middleware::Next,
) -> Response {
    let path = req.uri().path().to_string();
    let matched = state
        .proxy
        .iter()
        .filter(|(prefix, _)| path.starts_with(prefix.as_str()))
        .max_by_key(|(prefix, _)| prefix.len());
    let Some((prefix, entry)) = matched else {
        return next.run(req).await;
    };

    // Compose the target URL: target + (rewritten) path + query.
    let mut fwd_path = path.clone();
    if let Some((from, to)) = entry.rewrite() {
        if let Some(stripped) = from.strip_prefix('^') {
            if let Some(rest) = fwd_path.strip_prefix(stripped) {
                fwd_path = format!("{to}{rest}");
            }
        } else {
            fwd_path = fwd_path.replacen(from, to, 1);
        }
    }
    let query = req.uri().query().map(|q| format!("?{q}")).unwrap_or_default();
    let target = format!("{}{}{}", entry.target().trim_end_matches('/'), fwd_path, query);

    let method = req.method().clone();
    let req_headers = req.headers().clone();
    let body_bytes = match axum::body::to_bytes(req.into_body(), 100 * 1024 * 1024).await {
        Ok(b) => b,
        Err(e) => {
            return (StatusCode::BAD_GATEWAY, format!("oj proxy: body read: {e}")).into_response()
        }
    };

    let mut out = state.http.request(method, &target).body(body_bytes.to_vec());
    for (name, value) in req_headers.iter() {
        // Host is set by reqwest per target when changeOrigin; else forward.
        if entry.change_origin() && name == header::HOST {
            continue;
        }
        out = out.header(name, value);
    }

    match out.send().await {
        Ok(resp) => {
            let status = resp.status();
            let headers = resp.headers().clone();
            let bytes = resp.bytes().await.unwrap_or_default();
            let mut response = Response::new(Body::from(bytes));
            *response.status_mut() = status;
            for (name, value) in headers.iter() {
                // reqwest already decompressed; drop framing headers that
                // would now be wrong.
                if name == header::TRANSFER_ENCODING || name == header::CONTENT_LENGTH {
                    continue;
                }
                response.headers_mut().insert(name, value.clone());
            }
            response
        }
        Err(e) => {
            let via = if entry.ws() { " (ws proxying not yet supported)" } else { "" };
            (StatusCode::BAD_GATEWAY, format!("oj proxy to {}{} failed: {e}", prefix, via))
                .into_response()
        }
    }
}

/// Serve an index.html body: run plugin transformIndexHtml, then inject oj's
/// dev scripts / bundle scripts. Shared by the direct `/` route and the SPA
/// history fallback.
async fn serve_html(state: &ServerState, bytes: Vec<u8>) -> Response {
    let mut raw = String::from_utf8_lossy(&bytes).into_owned();
    if let Some(host) = &state.plugins {
        if let Ok(out) = host.transform_index_html(&raw).await {
            raw = out;
        }
    }
    let html = if state.bundle {
        inject_bundle_scripts(raw)
    } else {
        inject_module_preloads(inject_dev_scripts(raw), state)
    };
    ([(header::CONTENT_TYPE, "text/html; charset=utf-8")], html).into_response()
}

/// Serve the app's root index.html (the SPA fallback target).
async fn serve_index_html(state: &ServerState) -> Response {
    match tokio::fs::read(state.root.join("index.html")).await {
        Ok(bytes) => serve_html(state, bytes).await,
        Err(_) => (StatusCode::NOT_FOUND, "oj: index.html not found").into_response(),
    }
}

/// Whether an unresolved path should fall back to index.html (client-side
/// routing) rather than 404. True for extension-less paths and browser HTML
/// navigations; false for oj-internal namespaces, source, and missing assets.
fn is_spa_navigation(rel: &str, headers: &HeaderMap) -> bool {
    if rel.starts_with('@')
        || rel.starts_with("__")
        || rel.starts_with("src/")
        || rel.starts_with("node_modules/")
    {
        return false;
    }
    let last = rel.rsplit('/').next().unwrap_or("");
    let no_extension = !last.contains('.');
    let accepts_html = headers
        .get(header::ACCEPT)
        .and_then(|v| v.to_str().ok())
        .is_some_and(|a| a.contains("text/html"));
    no_extension || accepts_html
}

/// Forward an unmatched GET to the plugin `configureServer` middleware server.
/// Returns `Some(response)` if a middleware handled it, `None` if there's no
/// middleware or it fell through (so oj resumes its own SPA-fallback / 404).
async fn forward_to_plugin_middleware(
    state: &ServerState,
    uri: &Uri,
    headers: &HeaderMap,
) -> Option<Response> {
    let port = state.plugin_mw_port?;
    let pq = uri.path_and_query().map(|p| p.as_str()).unwrap_or(uri.path());
    let target = format!("http://127.0.0.1:{port}{pq}");
    let mut out = state.http.get(&target);
    for (name, value) in headers.iter() {
        if name == header::HOST {
            continue;
        }
        out = out.header(name, value);
    }
    let resp = out.send().await.ok()?;
    // The sentinel means no middleware claimed the request: fall through.
    if resp.headers().contains_key("x-oj-fallthrough") {
        return None;
    }
    let status = resp.status();
    let resp_headers = resp.headers().clone();
    let bytes = resp.bytes().await.unwrap_or_default();
    let mut response = Response::new(Body::from(bytes));
    *response.status_mut() = status;
    for (name, value) in resp_headers.iter() {
        if name == header::TRANSFER_ENCODING || name == header::CONTENT_LENGTH {
            continue;
        }
        response.headers_mut().insert(name, value.clone());
    }
    Some(response)
}

async fn serve_path(
    State(state): State<Arc<ServerState>>,
    headers: HeaderMap,
    uri: Uri,
) -> Response {
    // Serve under `base` like Vite: strip the configured base prefix from app
    // requests (built from `import.meta.env.BASE_URL`). oj's own root-relative
    // URLs (/@fs, /@id, /@oj, /src) don't carry the prefix, so this is a no-op
    // for them.
    let path = state
        .base
        .as_deref()
        .and_then(|b| uri.path().strip_prefix(b.trim_end_matches('/')))
        .unwrap_or_else(|| uri.path());
    let rel = path.trim_start_matches('/');
    let rel = if rel.is_empty() { "index.html" } else { rel };

    // Virtual modules: serve author-provided source at /@virtual/<id>.
    if let Some(id) = uri.path().strip_prefix("/@virtual/") {
        return match state.virtual_modules.get(id) {
            Some(code) => (
                [(header::CONTENT_TYPE, "text/javascript"), (header::CACHE_CONTROL, "no-cache")],
                code.clone(),
            )
                .into_response(),
            None => (StatusCode::NOT_FOUND, format!("oj: no virtual module {id}")).into_response(),
        };
    }

    // Plugin-resolved modules: `/@id/<hex spec>?importer=<hex>`, a specifier
    // oj couldn't resolve, handed to plugin resolveId + load.
    if let Some(hex) = uri.path().strip_prefix("/@id/") {
        let spec = hex_decode(hex).unwrap_or_default();
        let importer = uri
            .query()
            .and_then(|q| q.strip_prefix("importer="))
            .and_then(hex_decode)
            .unwrap_or_default();
        return serve_plugin_id(&state, &spec, &importer).await;
    }

    let file = if let Some(abs) = uri.path().strip_prefix("/@fs") {
        let candidate = PathBuf::from(abs);
        let allowed = {
            let allow = state.fs_allow.lock().unwrap();
            allow.iter().any(|root| candidate.starts_with(root))
        };
        if !allowed {
            return (StatusCode::FORBIDDEN, "oj: /@fs path not allow-listed").into_response();
        }
        candidate
    } else {
        match locate(&state.root, &state.public_dir, rel) {
            Some(file) => file,
            None => {
                // A plugin's configureServer middleware may own this route
                // (dev endpoints: health checks, secrets, api stubs). Consulted
                // only on a miss, so served modules/assets skip the round-trip.
                if let Some(resp) = forward_to_plugin_middleware(&state, &uri, &headers).await {
                    return resp;
                }
                // SPA history fallback: a navigation to a client-router path
                // (no file extension, or an HTML navigation) serves index.html
                // so BrowserRouter/etc. can take over. Missing assets and
                // oj-internal namespaces still 404.
                if is_spa_navigation(rel, &headers) {
                    return serve_index_html(&state).await;
                }
                return (StatusCode::NOT_FOUND, format!("oj: no such file: /{rel}"))
                    .into_response();
            }
        }
    };

    let ext = file.extension().and_then(|e| e.to_str()).unwrap_or("");
    if let Some(kind) = query_asset_kind(uri.query()) {
        let url = url_of(&state.root, &file);
        return match asset_module(&file, &url, kind).await {
            Ok(js) => (
                [(header::CONTENT_TYPE, "text/javascript"), (header::CACHE_CONTROL, "no-cache")],
                js,
            )
                .into_response(),
            Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, format!("oj: {e}")).into_response(),
        };
    }
    if matches!(ext, "css" | "scss" | "sass")
        && uri.query().is_some_and(|q| q.contains("import"))
    {
        let url = url_of(&state.root, &file);
        return serve_css_wrapper(&state, &file, &url).await;
    }
    if COMPILABLE.contains(&ext) {
        let url = url_of(&state.root, &file);
        return serve_compiled(&state, &file, &url, uri.query(), &headers).await;
    }
    // JSON imported from JS becomes a module; JSON under publicDir stays raw.
    if ext == "json" && !file.starts_with(&state.public_dir) {
        let url = url_of(&state.root, &file);
        return serve_compiled(&state, &file, &url, uri.query(), &headers).await;
    }

    match tokio::fs::read(&file).await {
        Ok(bytes) if ext == "html" => serve_html(&state, bytes).await,
        Ok(bytes) if ext == "css" => {
            let source = String::from_utf8_lossy(&bytes).into_owned();
            if is_tailwind_css(&source) {
                let url = url_of(&state.root, &file);
                return match compile_tailwind(&state, &url, &source).await {
                    Ok(css) => {
                        ([(header::CONTENT_TYPE, "text/css"), (header::CACHE_CONTROL, "no-cache")], css)
                            .into_response()
                    }
                    Err(err) => {
                        let _ = state.reload_tx.send(
                            serde_json::json!({ "type": "error", "message": err.clone() })
                                .to_string(),
                        );
                        (StatusCode::INTERNAL_SERVER_ERROR, format!("oj: {err}")).into_response()
                    }
                };
            }
            ([(header::CONTENT_TYPE, "text/css")], source).into_response()
        }
        Ok(bytes) => {
            let mut response = Response::new(Body::from(bytes));
            response
                .headers_mut()
                .insert(header::CONTENT_TYPE, content_type(ext).parse().unwrap());
            response
        }
        Err(err) => {
            (StatusCode::INTERNAL_SERVER_ERROR, format!("oj: read error: {err}"))
                .into_response()
        }
    }
}

/// The preamble must be the first module script in the document: module
/// scripts execute in document order, and injectIntoGlobalHook has to run
/// before any module pulls in React.
fn inject_dev_scripts(html: String) -> String {
    let tags = "<script type=\"module\" src=\"/@oj/refresh-preamble.js\"></script>\n\
                <script type=\"module\" src=\"/@oj/client.js\"></script>";
    match html.find("<head>") {
        Some(idx) => {
            let insert_at = idx + "<head>".len();
            format!("{}\n{}{}", &html[..insert_at], tags, &html[insert_at..])
        }
        None => format!("{tags}\n{html}"),
    }
}

async fn serve_compiled(
    state: &Arc<ServerState>,
    file: &Path,
    url: &str,
    query: Option<&str>,
    headers: &HeaderMap,
) -> Response {
    let (key, module) = match ensure_module(state, file, url).await {
        Ok(pair) => pair,
        Err(err) => {
            // Push to the overlay too: during a hot update the failed module
            // is fetched via dynamic import and the 500 body is never shown.
            let _ = state.reload_tx.send(
                serde_json::json!({ "type": "error", "message": err.clone() }).to_string(),
            );
            return (StatusCode::INTERNAL_SERVER_ERROR, format!("oj: {err}")).into_response();
        }
    };

    // The content key is the etag: reloads revalidate modules as 304s instead
    // of re-downloading bodies. ?t= requests are one-shot HMR fetches, no etag.
    let etag = format!("\"{key}\"");
    if query.is_none() {
        if let Some(inm) = headers.get(header::IF_NONE_MATCH).and_then(|v| v.to_str().ok()) {
            if inm == etag {
                return (
                    StatusCode::NOT_MODIFIED,
                    [(header::ETAG, etag), (header::CACHE_CONTROL, "no-cache".to_string())],
                )
                    .into_response();
            }
        }
    }

    let mut body = module.code.clone();
    if !state.bundle {
        body.push_str(&hot_glue(url, query, module.is_boundary));
    }
    if let Some(map_url) = &module.map_data_url {
        // Glue is append-only, so original line mappings stay exact.
        body.push_str(&format!("\n//# sourceMappingURL={map_url}\n"));
    }

    (
        [
            (header::CONTENT_TYPE, "text/javascript".to_string()),
            (header::CACHE_CONTROL, "no-cache".to_string()),
            (header::ETAG, etag),
        ],
        body,
    )
        .into_response()
}

/// Compile-or-cache one module: memory, then disk, then compile, coalescing
/// concurrent callers (HTTP requests and the startup crawl) per url.
/// Also re-applies the module's graph edges: the graph is in-memory only
/// and empty after a restart, cache hits included.
async fn ensure_module(
    state: &Arc<ServerState>,
    file: &Path,
    url: &str,
) -> Result<(String, Arc<CachedModule>), String> {
    let source = bytes_to_string(
        tokio::fs::read(file).await.map_err(|err| format!("read error for {url}: {err}"))?,
    )
    .map_err(|err| format!("read error for {url}: {err}"))?;
    if file.extension().and_then(|e| e.to_str()) == Some("css") && is_tailwind_css(&source) {
        let css = compile_tailwind(state, url, &source).await?;
        let module = Arc::new(CachedModule {
            is_boundary: true,
            kind: "css".into(),
            code: css,
            map_data_url: None,
            imports: Vec::new(),
            require_map: Vec::new(),
            css_exports: Vec::new(),
            fs_allow: Vec::new(),
        });
        register_in_graph(state, url, &module);
        return Ok((String::new(), module));
    }

    // Server functions: a `*.server.*` module never reaches the client; it is
    // replaced by stubs that RPC to /__oj_fn (served by the SSR dev server).
    // The stub is a pure function of the source, so it rides the same
    // content-addressed cache as every other module (its own `server` mode)
    // rather than being re-derived — re-parsing exports included — per request.
    let is_dep_early = url.contains("/node_modules/") || url.starts_with("/@fs/");
    let is_server = is_server_module(file) && !is_dep_early && !state.bundle;

    let mode = if state.bundle {
        "bundle"
    } else if is_server {
        "server"
    } else {
        "dev"
    };
    let key = state.cache.key(source.as_bytes(), url, mode);

    if let Some(module) = memory_get(state, url, &key) {
        register_in_graph(state, url, &module);
        return Ok((key, module));
    }

    let lock = {
        let mut locks = state.compile_locks.lock().unwrap();
        Arc::clone(locks.entry(url.to_string()).or_default())
    };
    let _guard = lock.lock().await;

    // A coalesced waiter arrives here after the winner finished: re-check.
    if let Some(module) = memory_get(state, url, &key) {
        register_in_graph(state, url, &module);
        return Ok((key, module));
    }
    if let Some(module) = state.cache.get(&key) {
        let module = Arc::new(module);
        memory_put(state, url, &key, &module);
        register_in_graph(state, url, &module);
        return Ok((key, module));
    }

    // Server-fn stub (cache miss): build once, then persist + memoize like a
    // compiled module so repeat requests and restarts skip the export parse.
    if is_server {
        let code = server_fn_stub(&oj_compiler::exports(&source, file), url);
        let module = Arc::new(CachedModule {
            is_boundary: false,
            kind: String::new(),
            code,
            map_data_url: None,
            imports: Vec::new(),
            require_map: Vec::new(),
            css_exports: Vec::new(),
            fs_allow: Vec::new(),
        });
        let _ = state.cache_writes.try_send((key.clone(), Arc::clone(&module)));
        memory_put(state, url, &key, &module);
        register_in_graph(state, url, &module);
        return Ok((key, module));
    }

    let is_dep = url.contains("/node_modules/") || url.starts_with("/@fs/");
    // Plugin `transform` hooks run on app source before oj compiles it (deps
    // are skipped to avoid a per-node_modules-module round trip). The `id` is
    // the absolute file path (Rollup convention, and what prod passes), so a
    // plugin's this.resolve gets a usable importer in both dev and prod.
    let source = match &state.plugins {
        Some(host) if !is_dep => {
            host.transform(&source, &file.to_string_lossy()).await.unwrap_or(source)
        }
        _ => source,
    };

    // Arbitrary PostCSS: with a postcss.config, non-Tailwind .css runs through
    // the app's PostCSS chain (sidecar) before Lightning below. Tailwind css
    // already went through the sidecar above and returned; .scss keeps the
    // sass-to-Lightning path. Only reached on a cache miss (key is on the raw
    // source), so cache hits skip the round-trip.
    let source = if state.has_postcss && file.extension().and_then(|e| e.to_str()) == Some("css") {
        run_css_sidecar(state, url, &source).await.unwrap_or(source)
    } else {
        source
    };

    let root = state.root.clone();
    let resolver = Arc::clone(&state.resolver);
    let fs_allow = Arc::clone(&state.fs_allow);
    let dir_cache = Arc::clone(&state.dir_cache);
    let virtual_ids: std::collections::BTreeSet<String> =
        state.virtual_modules.keys().cloned().collect();
    let dir = file.parent().map(Path::to_path_buf).unwrap_or_default();
    let file_owned = file.to_path_buf();
    let url_owned = url.to_string();
    let bundle = state.bundle;
    // A bare specifier oj can't resolve, when plugins are present (dev only),
    // is deferred to plugin resolveId/load via a `/@id/` URL served lazily.
    let plugin_fallback = state.plugins.is_some() && !bundle;
    let importer_abs = file.to_string_lossy().into_owned();
    let ext = file.extension().and_then(|e| e.to_str());
    let is_css = matches!(ext, Some("css") | Some("scss") | Some("sass"));
    let is_json = ext == Some("json");
    let compiled = tokio::task::spawn_blocking(move || -> Result<CachedModule, String> {
        if is_json {
            // JSON as a module: a JS body exporting default + named keys.
            let code = if bundle {
                oj_compiler::json::to_factory_body(&source, &url_owned)
            } else {
                oj_compiler::json::to_esm(&source, &url_owned)
            }
            .map_err(|err| format!("compile error:\n{err}"))?;
            return Ok(CachedModule {
                is_boundary: false,
                kind: if bundle { "esm".into() } else { String::new() },
                code,
                map_data_url: None,
                imports: Vec::new(),
                require_map: Vec::new(),
                css_exports: Vec::new(),
                fs_allow: Vec::new(),
            });
        }
        if is_css {
            // Sass/SCSS to CSS first (sibling @use/@import resolve from dir).
            let css_src = if oj_css::is_sass(&url_owned) {
                oj_css::compile_sass(&source, Some(&dir))?
            } else {
                source.clone()
            };
            let output = oj_css::compile_css(&url_owned, &css_src, false)?;
            return Ok(CachedModule {
                is_boundary: true, // JS-imported css self-accepts its updates
                kind: "css".into(),
                code: output.css,
                map_data_url: None,
                imports: Vec::new(),
                require_map: Vec::new(),
                css_exports: output.exports.unwrap_or_default(),
                fs_allow: Vec::new(),
            });
        }
        let mut rewrite = |spec: &str| {
            // Built-in file-based route manifest.
            if spec == "virtual:oj-routes" {
                return Some("/@oj/routes.js".to_string());
            }
            // Virtual modules resolve to /@virtual/<id> instead of the FS.
            if virtual_ids.contains(spec) {
                return Some(format!("/@virtual/{spec}"));
            }
            if let Some(url) = rewrite_specifier(&root, &dir, &resolver, &fs_allow, &dir_cache, spec, !bundle) {
                return Some(url);
            }
            // Unresolvable bare specifier: defer to plugin resolveId/load.
            if plugin_fallback && is_bare_specifier(spec) {
                return Some(format!("/@id/{}?importer={}", hex_encode(spec), hex_encode(&importer_abs)));
            }
            None
        };
        if bundle {
            let factory =
                oj_compiler::bundle::compile_factory(&file_owned, &url_owned, &source, &mut rewrite)
                    .map_err(|err| format!("compile error:\n{err}"))?;
            Ok(CachedModule {
                is_boundary: factory.is_boundary(),
                kind: match factory.kind {
                    oj_compiler::bundle::FactoryKind::Esm => "esm".into(),
                    oj_compiler::bundle::FactoryKind::Cjs => "cjs".into(),
                },
                code: factory.code,
                map_data_url: None,
                fs_allow: fs_allow_from(&factory.imports),
                imports: factory.imports,
                require_map: factory.require_map,
                css_exports: Vec::new(),
            })
        } else {
            let output = if is_dep {
                oj_compiler::cjs::compile_dep(&file_owned, &url_owned, &source, &mut rewrite)
            } else {
                oj_compiler::compile_module(
                    &file_owned,
                    &source,
                    &oj_compiler::CompileOptions::dev(),
                    Some(&mut rewrite),
                )
            }
            .map_err(|err| format!("compile error:\n{err}"))?;
            Ok(CachedModule {
                is_boundary: !is_dep && output.has_refresh_registrations(),
                code: output.code,
                map_data_url: output.map_data_url,
                fs_allow: fs_allow_from(&output.imports),
                imports: output.imports,
                kind: String::new(),
                require_map: Vec::new(),
                css_exports: Vec::new(),
            })
        }
    })
    .await;

    let module = match compiled {
        Ok(Ok(module)) => Arc::new(module),
        Ok(Err(err)) => return Err(err),
        Err(join_err) => return Err(format!("compiler task failed: {join_err}")),
    };
    // Disk-cache writes go through one dedicated writer thread: keeps
    // serialize+write+rename off the compile tasks without flooding the
    // blocking pool (per-write spawn_blocking regressed cold start).
    // Best-effort: a full queue just drops the write.
    let _ = state.cache_writes.try_send((key.clone(), Arc::clone(&module)));
    memory_put(state, url, &key, &module);
    register_in_graph(state, url, &module);
    Ok((key, module))
}

fn memory_get(state: &ServerState, url: &str, key: &str) -> Option<Arc<CachedModule>> {
    let memory = state.memory.lock().unwrap();
    memory.get(url).filter(|(k, _)| k == key).map(|(_, m)| Arc::clone(m))
}

fn memory_put(state: &ServerState, url: &str, key: &str, module: &Arc<CachedModule>) {
    state
        .memory
        .lock()
        .unwrap()
        .insert(url.to_string(), (key.to_string(), Arc::clone(module)));
}

/// The package a file belongs to: nearest ancestor with a package.json
/// (fallback: the file's own directory). This is the /@fs trust boundary:
/// pulling in one file from a resolved dependency trusts that package's
/// shipped assets (e.g. a wasm loaded at runtime via new URL(import.meta.url)).
fn package_root(path: &Path) -> PathBuf {
    let mut dir = path.parent();
    while let Some(d) = dir {
        if d.join("package.json").is_file() {
            return d.to_path_buf();
        }
        dir = d.parent();
    }
    path.parent().unwrap_or(path).to_path_buf()
}

/// Package-root prefixes for a module's /@fs/ imports (query stripped).
fn fs_allow_from(imports: &[String]) -> Vec<String> {
    imports
        .iter()
        .filter_map(|i| i.split('?').next().unwrap_or(i).strip_prefix("/@fs"))
        .map(|p| package_root(Path::new(p)).display().to_string())
        .collect()
}

fn register_in_graph(state: &ServerState, url: &str, module: &CachedModule) {
    if !module.fs_allow.is_empty() {
        let mut allow = state.fs_allow.lock().unwrap();
        for p in &module.fs_allow {
            allow.insert(PathBuf::from(p));
        }
    }
    let mut graph = state.graph.lock().unwrap();
    let local_imports: Vec<PathBuf> = module
        .imports
        .iter()
        .filter(|s| s.starts_with('/') && !s.starts_with("/@oj/"))
        .map(|s| PathBuf::from(s.split('?').next().unwrap_or(s)))
        .collect();
    graph.set_imports(Path::new(url), &local_imports);
    graph.set_self_accepting(Path::new(url), module.is_boundary);
}

/// JS-imported css: a style-injecting ES module with the scoped class map
/// as its default export. Self-accepting, so edits hot-swap through the
/// normal module-update flow with React state intact.
async fn serve_css_wrapper(state: &Arc<ServerState>, file: &Path, url: &str) -> Response {
    let (_, module) = match ensure_module(state, file, url).await {
        Ok(pair) => pair,
        Err(err) => {
            let _ = state.reload_tx.send(
                serde_json::json!({ "type": "error", "message": err.clone() }).to_string(),
            );
            return (StatusCode::INTERNAL_SERVER_ERROR, format!("oj: {err}")).into_response();
        }
    };
    let exports = if module.css_exports.is_empty() {
        "void 0".to_string()
    } else {
        let map: serde_json::Map<String, serde_json::Value> = module
            .css_exports
            .iter()
            .map(|(k, v)| (k.clone(), serde_json::Value::String(v.clone())))
            .collect();
        serde_json::Value::Object(map).to_string()
    };
    let body = format!(
        "import {{ createHotContext as __oj_hot, updateStyle as __oj_updateStyle }} from \"/@oj/client.js\";\n\
         import.meta.hot = __oj_hot({url:?});\n\
         __oj_updateStyle({url:?}, {css});\n\
         export default {exports};\n\
         import.meta.hot.accept(() => {{}});\n",
        css = serde_json::Value::String(module.code.clone()),
    );
    (
        [(header::CONTENT_TYPE, "text/javascript"), (header::CACHE_CONTROL, "no-cache")],
        body,
    )
        .into_response()
}

/// Whether the app has a PostCSS config (so all css goes through the sidecar).
pub fn has_postcss_config(root: &Path) -> bool {
    ["postcss.config.js", "postcss.config.cjs", "postcss.config.mjs"]
        .iter()
        .any(|f| root.join(f).is_file())
}

/// Run css through the (lazily-spawned) CSS sidecar: the app's PostCSS chain,
/// or the Tailwind v4 API when there's no postcss config.
async fn run_css_sidecar(state: &Arc<ServerState>, url: &str, source: &str) -> Result<String, String> {
    let sidecar = state
        .tailwind
        .get_or_try_init(|| Sidecar::spawn(&state.root))
        .await
        .map_err(|e| e.to_string())?;
    sidecar.compile(source, url).await
}

/// Compile tailwind-flavored css through the Node sidecar. Never cached:
/// the output depends on class candidates across the whole app, not on the
/// css file's own content.
async fn compile_tailwind(
    state: &Arc<ServerState>,
    url: &str,
    source: &str,
) -> Result<String, String> {
    let css = run_css_sidecar(state, url, source).await?;
    state.tailwind_urls.lock().unwrap().insert(url.to_string());
    Ok(css)
}

/// Handle messages from the dev client (currently only `invalidate`).
fn handle_client_message(state: &Arc<ServerState>, text: &str) {
    let Ok(msg) = serde_json::from_str::<serde_json::Value>(text) else { return };
    if msg["type"] == "invalidate" {
        let Some(path) = msg["path"].as_str() else { return };
        // Bundle mode escalates as a patch (re-execute the importer boundaries
        // with the already-registered factory); unbundled as an update (re-import
        // the boundary module urls). Both replace the old full-reload fallback.
        let reply = if state.bundle {
            match state.graph.lock().unwrap().update_plan_from_importers(Path::new(path)) {
                Ok(plan) => {
                    println!("oj: invalidate {path} -> patch {:?}", plan.boundaries);
                    let seq =
                        state.patch_seq.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
                    let to_urls =
                        |v: &[PathBuf]| -> Vec<String> { v.iter().map(|p| p.display().to_string()).collect() };
                    serde_json::json!({
                        "type": "patch",
                        "changed": [],
                        "dirty": to_urls(&plan.dirty),
                        "boundaries": to_urls(&plan.boundaries),
                        "timestamp": now_millis() as u64,
                        "seq": seq,
                    })
                }
                Err(reason) => {
                    println!("oj: invalidate {path} -> full-reload ({reason})");
                    serde_json::json!({ "type": "full-reload", "reason": reason })
                }
            }
        } else {
            match state.graph.lock().unwrap().propagate_update_from_importers(Path::new(path)) {
                HmrDecision::Update { boundaries } => {
                    println!("oj: invalidate {path} -> update {boundaries:?}");
                    let timestamp = now_millis() as u64;
                    let updates: Vec<_> = boundaries
                        .iter()
                        .map(|b| {
                            serde_json::json!({
                                "path": format!("{}", b.display()),
                                "timestamp": timestamp,
                            })
                        })
                        .collect();
                    serde_json::json!({ "type": "update", "updates": updates })
                }
                HmrDecision::FullReload { reason } => {
                    println!("oj: invalidate {path} -> full-reload ({reason})");
                    serde_json::json!({ "type": "full-reload", "reason": reason })
                }
            }
        };
        let _ = state.reload_tx.send(reply.to_string());
    } else if msg["type"] == "custom" {
        // A client `import.meta.hot.send(event, data)`. With no plugin system
        // yet, broadcast it to all clients so hot.on(event) listeners (this
        // tab and others) receive it: enough for round-trip messaging.
        if msg["event"].is_string() {
            let _ = state.reload_tx.send(
                serde_json::json!({
                    "type": "custom",
                    "event": msg["event"],
                    "data": msg["data"],
                })
                .to_string(),
            );
        }
    }
}

/// The per-module HMR/Fast Refresh glue, following @vitejs/plugin-react's
/// current append-only wrapper: `$RefreshReg$`/`$RefreshSig$` are hoisted
/// function declarations, so the transform's module-body calls resolve to
/// these locals instead of the window stubs; the module imports itself
/// (with the same ?t query when hot-updated) to hand its export namespace
/// to the boundary validator.
fn hot_glue(url: &str, query: Option<&str>, is_boundary: bool) -> String {
    if !is_boundary {
        return String::new();
    }
    let self_specifier = match query {
        Some(q) if !q.is_empty() => format!("{url}?{q}"),
        _ => url.to_string(),
    };
    format!(
        r#"
import {{ createHotContext as __oj_createHotContext }} from "/@oj/client.js";
import.meta.hot = __oj_createHotContext({url:?});
import * as RefreshRuntime from "/@oj/refresh-runtime.js";
import * as __oj_currentExports from {self_specifier:?};
if (import.meta.hot) {{
  if (!window.__oj_refresh_installed__) {{
    throw new Error("oj: Fast Refresh preamble missing; was index.html served by oj?");
  }}
  const currentExports = __oj_currentExports;
  // Register synchronously during module evaluation (NOT in a microtask):
  // a fast second edit must find the accept callback the instant the first
  // edit's dynamic import resolves, or it snapshots an empty list and is
  // silently dropped. This mirrors Vite's shared/hmr.ts.
  RefreshRuntime.registerExportsForReactRefresh({url:?}, currentExports);
  import.meta.hot.accept((nextExports) => {{
    if (!nextExports) return;
    const invalidateMessage = RefreshRuntime.validateRefreshBoundaryAndEnqueueUpdate({url:?}, currentExports, nextExports);
    if (invalidateMessage) import.meta.hot.invalidate(invalidateMessage);
  }});
}}
function $RefreshReg$(type, id) {{ return RefreshRuntime.register(type, {url:?} + " " + id); }}
function $RefreshSig$() {{ return RefreshRuntime.createSignatureFunctionForTransform(); }}
"#
    )
}

/// Per-directory listing cache: `dir -> { filename -> is_regular_file }`.
/// Collapses the relative-import extension probe (up to ~6 `is_file` syscalls
/// per extensionless import) into one `read_dir` per directory, amortized
/// across every sibling import during the cold-start crawl. Cleared wholesale
/// on any watcher burst (see `spawn_watcher`), so a newly created/removed file
/// is picked up on the next resolve.
type DirCache = std::collections::HashMap<PathBuf, std::sync::Arc<std::collections::HashMap<std::ffi::OsString, bool>>>;

/// `path.is_file()`, answered from a cached directory listing. Falls back to a
/// direct stat only for symlinked entries (rare in app source; node_modules
/// goes through the resolver, not this path).
fn is_file_cached(cache: &Mutex<DirCache>, path: &Path) -> bool {
    let (Some(dir), Some(name)) = (path.parent(), path.file_name()) else {
        return path.is_file();
    };
    if let Some(entries) = cache.lock().unwrap().get(dir) {
        return entries.get(name).copied().unwrap_or(false);
    }
    let mut map = std::collections::HashMap::new();
    if let Ok(rd) = std::fs::read_dir(dir) {
        for e in rd.flatten() {
            let is_file = match e.file_type() {
                Ok(ft) if ft.is_file() => true,
                Ok(ft) if ft.is_symlink() => e.path().is_file(), // follow the link
                _ => false,
            };
            map.insert(e.file_name(), is_file);
        }
    }
    let arc = std::sync::Arc::new(map);
    let result = arc.get(name).copied().unwrap_or(false);
    cache.lock().unwrap().insert(dir.to_path_buf(), arc);
    result
}

/// `./App` from `<root>/src` becomes `/src/App.tsx`; `react` becomes the
/// resolved node_modules entry as a rooted URL. Rooted/virtual/absolute-URL
/// specifiers pass through untouched.
fn rewrite_specifier(
    root: &Path,
    dir: &Path,
    resolver: &OjResolver,
    fs_allow: &Mutex<std::collections::HashSet<PathBuf>>,
    dir_cache: &Mutex<DirCache>,
    spec: &str,
    css_import_marker: bool,
) -> Option<String> {
    if spec.starts_with('/') || spec.contains("://") {
        return None;
    }

    // Query-suffixed imports (`./x.wasm?url`, `./x.txt?raw`, `./x.png?inline`,
    // `./w.ts?worker`): resolve the base file, keep the marker; the server
    // answers with a JS module (url string / contents / data URI / Worker
    // factory).
    if let Some((base, query)) = spec.split_once('?') {
        if matches!(query, "url" | "raw" | "inline" | "worker" | "sharedworker") {
            let resolved = rewrite_specifier(root, dir, resolver, fs_allow, dir_cache, base, false)
                .or_else(|| {
                    resolver.resolve(dir, base).ok().map(|p| {
                        fs_allow.lock().unwrap().insert(package_root(&p));
                        url_of(root, &p)
                    })
                })?;
            return Some(format!("{resolved}?{query}"));
        }
    }

    if spec.starts_with("./") || spec.starts_with("../") {
        let mut joined = normalize(&dir.join(spec));
        // TS convention: `import "./x.js"` resolves the sibling `./x.ts`
        // (also .tsx/.jsx). If the literal .js/.jsx target is absent, retarget.
        if !is_file_cached(dir_cache, &joined) {
            if let Some(ext) = joined.extension().and_then(|e| e.to_str()) {
                if ext == "js" || ext == "jsx" {
                    for cand in ["ts", "tsx"] {
                        let alt = joined.with_extension(cand);
                        if is_file_cached(dir_cache, &alt) {
                            joined = alt;
                            break;
                        }
                    }
                }
            }
        }
        let quick = if is_file_cached(dir_cache, &joined) {
            Some(joined)
        } else if joined.extension().is_none() {
            COMPILABLE.iter().map(|ext| joined.with_extension(ext)).find(|c| is_file_cached(dir_cache, c))
        } else {
            None
        };
        if let Some(p) = quick {
            let url = url_of(root, &p);
            // JS-imported css is served as a style-injecting JS module; the
            // ?import marker distinguishes it from <link> requests.
            if css_import_marker
                && (url.ends_with(".css") || url.ends_with(".scss") || url.ends_with(".sass"))
            {
                return Some(format!("{url}?import"));
            }
            return Some(url);
        }
        // Directories, `./x.js` to `x.ts`, etc.: let the real resolver try.
    }

    match resolver.resolve(dir, spec) {
        Ok(resolved) if resolved.starts_with(root) => Some(url_of(root, &resolved)),
        Ok(resolved) => {
            // Outside the served root (workspace packages, hoisted installs):
            // trust the whole package and serve it under /@fs/.
            fs_allow.lock().unwrap().insert(package_root(&resolved));
            Some(url_of(root, &resolved))
        }
        Err(err) => {
            if !(spec.starts_with("./") || spec.starts_with("../")) {
                eprintln!("oj: cannot resolve '{spec}': {err}");
            }
            None
        }
    }
}

fn url_of(root: &Path, file: &Path) -> String {
    match file.strip_prefix(root) {
        Ok(rel) => format!("/{}", rel.display()),
        Err(_) => format!("/@fs{}", file.display()),
    }
}

fn normalize(path: &Path) -> PathBuf {
    let mut out = PathBuf::new();
    for component in path.components() {
        match component {
            Component::ParentDir => {
                out.pop();
            }
            Component::CurDir => {}
            other => out.push(other.as_os_str()),
        }
    }
    out
}

/// Map a URL path to a file under root, refusing traversal and probing
/// TS-first extensions for extensionless imports (`/src/App` finds `App.tsx`).
fn locate(root: &Path, public_dir: &Path, rel: &str) -> Option<PathBuf> {
    if rel.split('/').any(|seg| seg == "..") {
        return None;
    }
    let base = root.join(rel);
    if base.is_file() {
        return Some(base);
    }
    if base.extension().is_none() {
        for ext in COMPILABLE {
            let candidate = base.with_extension(ext);
            if candidate.is_file() {
                return Some(candidate);
            }
        }
    }
    // Vite-style publicDir: assets under the public dir are served at root.
    let public = public_dir.join(rel);
    if public.is_file() {
        return Some(public);
    }
    None
}

/// Which query-suffix asset module a request wants, if any.
fn query_asset_kind(query: Option<&str>) -> Option<&'static str> {
    let q = query?;
    for kind in ["url", "raw", "inline", "worker", "sharedworker"] {
        if q.split('&').any(|kv| kv == kind) {
            return Some(kind);
        }
    }
    None
}

/// Build the JS module for a `?url` / `?raw` / `?inline` asset import.
async fn asset_module(file: &Path, url: &str, kind: &str) -> Result<String, String> {
    let clean_url = url.split('?').next().unwrap_or(url);
    match kind {
        "url" => Ok(format!("export default {clean_url:?};\n")),
        "raw" => {
            let text = tokio::fs::read_to_string(file)
                .await
                .map_err(|e| format!("read {}: {e}", file.display()))?;
            Ok(format!("export default {};\n", serde_json::Value::String(text)))
        }
        "inline" => {
            let bytes = tokio::fs::read(file).await.map_err(|e| format!("read: {e}"))?;
            let ext = file.extension().and_then(|e| e.to_str()).unwrap_or("");
            let mime = content_type(ext).split(';').next().unwrap_or("application/octet-stream");
            let data_uri = format!("data:{mime};base64,{}", base64_encode(&bytes));
            Ok(format!("export default {data_uri:?};\n"))
        }
        // `?worker` / `?sharedworker`: a factory that constructs a module
        // Worker over the (separately compiled+served) worker script.
        "worker" | "sharedworker" => {
            let ctor = if kind == "sharedworker" { "SharedWorker" } else { "Worker" };
            Ok(format!(
                "export default function () {{ return new {ctor}({clean_url:?}, {{ type: \"module\" }}); }}\n"
            ))
        }
        _ => Err(format!("unknown asset query: {kind}")),
    }
}

fn base64_encode(bytes: &[u8]) -> String {
    const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
    for chunk in bytes.chunks(3) {
        let b = [chunk[0], *chunk.get(1).unwrap_or(&0), *chunk.get(2).unwrap_or(&0)];
        let n = (b[0] as u32) << 16 | (b[1] as u32) << 8 | b[2] as u32;
        out.push(T[(n >> 18 & 63) as usize] as char);
        out.push(T[(n >> 12 & 63) as usize] as char);
        out.push(if chunk.len() > 1 { T[(n >> 6 & 63) as usize] as char } else { '=' });
        out.push(if chunk.len() > 2 { T[(n & 63) as usize] as char } else { '=' });
    }
    out
}

/// A `*.server.{ts,tsx,js,jsx}` module: its exports run only on the server and
/// are replaced by client stubs.
fn is_server_module(file: &Path) -> bool {
    file.file_name()
        .and_then(|n| n.to_str())
        .map(|n| {
            [".server.ts", ".server.tsx", ".server.js", ".server.jsx"]
                .iter()
                .any(|s| n.ends_with(s))
        })
        .unwrap_or(false)
}

/// Client stub module for a server-function module: each export becomes a call
/// that RPCs to /__oj_fn via the server-fn runtime.
fn server_fn_stub(exports: &[String], url: &str) -> String {
    let mut out = String::from("import { __ojServerCall } from \"/@oj/server-fn.js\";\n");
    for name in exports {
        if name == "default" {
            out.push_str(&format!(
                "export default (...a) => __ojServerCall({url:?}, \"default\", a);\n"
            ));
        } else {
            out.push_str(&format!(
                "export const {name} = (...a) => __ojServerCall({url:?}, {name:?}, a);\n"
            ));
        }
    }
    out
}

/// Serve the built-in `virtual:oj-routes` manifest, compiled at the app root so
/// its `./src/routes/**` glob resolves there (and each route becomes a
/// code-split lazy import).
async fn serve_oj_routes(State(state): State<Arc<ServerState>>) -> Response {
    let root = state.root.clone();
    let resolver = Arc::clone(&state.resolver);
    let fs_allow = Arc::clone(&state.fs_allow);
    let dir_cache = Arc::clone(&state.dir_cache);
    let synthetic = root.join("oj-routes.tsx");
    let compiled = tokio::task::spawn_blocking(move || {
        let dir = root.clone();
        let mut rewrite = |s: &str| rewrite_specifier(&root, &dir, &resolver, &fs_allow, &dir_cache, s, true);
        oj_compiler::compile_module(
            &synthetic,
            OJ_ROUTES_JS,
            &oj_compiler::CompileOptions::dev(),
            Some(&mut rewrite),
        )
        .map(|o| o.code_with_inline_map())
        .map_err(|e| format!("{e}"))
    })
    .await;
    match compiled {
        Ok(Ok(code)) => (
            [(header::CONTENT_TYPE, "text/javascript"), (header::CACHE_CONTROL, "no-cache")],
            code,
        )
            .into_response(),
        Ok(Err(e)) => (StatusCode::INTERNAL_SERVER_ERROR, format!("oj: routes manifest: {e}")).into_response(),
        Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, format!("compile task failed: {e}")).into_response(),
    }
}

/// Serve a plugin-resolved module: run `resolveId(spec, importer)` then
/// `load(id)`, compile the returned source (TS/JSX strip + import rewrite), and
/// serve it as a JS module. This is how plugin virtual modules reach the browser.
async fn serve_plugin_id(state: &Arc<ServerState>, spec: &str, importer: &str) -> Response {
    let Some(host) = &state.plugins else {
        return (StatusCode::NOT_FOUND, "oj: no plugin host").into_response();
    };
    let id = match host.resolve_id(spec, importer).await {
        Ok(Some(id)) => id,
        Ok(None) => {
            return (StatusCode::NOT_FOUND, format!("oj: no plugin resolved {spec}")).into_response();
        }
        Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, e).into_response(),
    };
    let source = match host.load(&id).await {
        Ok(Some(src)) => src,
        Ok(None) => {
            return (StatusCode::NOT_FOUND, format!("oj: no plugin loaded {id}")).into_response();
        }
        Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, e).into_response(),
    };
    let root = state.root.clone();
    let resolver = Arc::clone(&state.resolver);
    let fs_allow = Arc::clone(&state.fs_allow);
    let dir_cache = Arc::clone(&state.dir_cache);
    let compiled = tokio::task::spawn_blocking(move || {
        let mut rewrite = |s: &str| rewrite_specifier(&root, &root, &resolver, &fs_allow, &dir_cache, s, true);
        oj_compiler::compile_module(
            Path::new("plugin.tsx"),
            &source,
            &oj_compiler::CompileOptions::dev(),
            Some(&mut rewrite),
        )
        .map(|o| o.code_with_inline_map())
        .map_err(|e| format!("{e}"))
    })
    .await;
    match compiled {
        Ok(Ok(code)) => (
            [(header::CONTENT_TYPE, "text/javascript"), (header::CACHE_CONTROL, "no-cache")],
            code,
        )
            .into_response(),
        Ok(Err(e)) => (StatusCode::INTERNAL_SERVER_ERROR, e).into_response(),
        Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, format!("compile task failed: {e}")).into_response(),
    }
}

/// A bare import specifier (not relative/absolute/URL), e.g. `virtual:foo`,
/// `react`. Used to decide whether an unresolved import can defer to plugins.
fn is_bare_specifier(spec: &str) -> bool {
    !spec.starts_with('.') && !spec.starts_with('/') && !spec.contains("://")
}

/// Hex encode/decode for stuffing a specifier + importer into a `/@id/` URL
/// (path-safe, no dependency).
fn hex_encode(s: &str) -> String {
    let mut out = String::with_capacity(s.len() * 2);
    for b in s.bytes() {
        out.push(char::from_digit((b >> 4) as u32, 16).unwrap());
        out.push(char::from_digit((b & 0xf) as u32, 16).unwrap());
    }
    out
}

fn hex_decode(s: &str) -> Option<String> {
    let bytes = s.as_bytes();
    if bytes.len() % 2 != 0 {
        return None;
    }
    let mut out = Vec::with_capacity(bytes.len() / 2);
    for pair in bytes.chunks(2) {
        let hi = (pair[0] as char).to_digit(16)?;
        let lo = (pair[1] as char).to_digit(16)?;
        out.push((hi * 16 + lo) as u8);
    }
    String::from_utf8(out).ok()
}

fn content_type(ext: &str) -> &'static str {
    match ext {
        "html" => "text/html; charset=utf-8",
        "js" | "mjs" | "cjs" => "text/javascript",
        "css" => "text/css",
        "json" | "map" => "application/json",
        "svg" => "image/svg+xml",
        "png" => "image/png",
        "jpg" | "jpeg" => "image/jpeg",
        "ico" => "image/x-icon",
        "wasm" => "application/wasm",
        "woff2" => "font/woff2",
        "woff" => "font/woff",
        "ttf" => "font/ttf",
        "otf" => "font/otf",
        "eot" => "application/vnd.ms-fontobject",
        "webp" => "image/webp",
        "gif" => "image/gif",
        "txt" | "map2" => "text/plain; charset=utf-8",
        _ => "application/octet-stream",
    }
}

fn now_millis() -> u128 {
    SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_millis()
}

/// `<link rel="modulepreload">` for every known module, so the browser
/// fetches the whole graph in parallel instead of discovering it one
/// import-depth round trip at a time. This is what replaces bundling while
/// dev stays native-ESM.
fn inject_module_preloads(html: String, state: &ServerState) -> String {
    // Live graph once the crawl finished; last session's snapshot before
    // that. Never block HTML on compilation: a stale snapshot just means a
    // few extra or missing preloads, and imports still resolve normally.
    let paths: Vec<String> = if *state.crawl_done.borrow() {
        state
            .graph
            .lock()
            .unwrap()
            .module_paths()
            .iter()
            .map(|p| p.display().to_string())
            .collect()
    } else {
        state.preload_snapshot.clone()
    };
    if paths.is_empty() {
        return html;
    }
    let links: String = paths
        .iter()
        .map(|p| {
            // Stylesheets live in the graph under their clean url but are
            // served as JS only with the ?import marker.
            if p.ends_with(".css") || p.ends_with(".scss") || p.ends_with(".sass") {
                format!("<link rel=\"modulepreload\" href=\"{p}?import\" />\n")
            } else {
                format!("<link rel=\"modulepreload\" href=\"{p}\" />\n")
            }
        })
        .collect();
    match html.find("</head>") {
        Some(idx) => format!("{}{links}{}", &html[..idx], &html[idx..]),
        None => format!("{html}\n{links}"),
    }
}

/// Bundle mode: runtime + chunk replace the app's own module script tags.
fn inject_bundle_scripts(html: String) -> String {
    let mut out = String::with_capacity(html.len());
    let mut rest = html.as_str();
    // Drop every `<script type="module" src="/...">...</script>` tag; the
    // chunk executes those entries via __oj_start.
    while let Some(start) = rest.find("<script") {
        let Some(tag_close) = rest[start..].find('>') else { break };
        let tag = &rest[start..start + tag_close];
        if tag.contains("type=\"module\"") && tag.contains("src=\"/") {
            out.push_str(&rest[..start]);
            let after_tag = &rest[start + tag_close + 1..];
            rest = match after_tag.find("</script>") {
                Some(end) => &after_tag[end + "</script>".len()..],
                None => after_tag,
            };
        } else {
            out.push_str(&rest[..start + tag_close + 1]);
            rest = &rest[start + tag_close + 1..];
        }
    }
    out.push_str(rest);

    let tags = "<script type=\"module\" src=\"/@oj/bundle-runtime.js\"></script>\n\
                <script type=\"module\" src=\"/@oj/chunk.js\"></script>";
    match out.find("<head>") {
        Some(idx) => {
            let insert_at = idx + "<head>".len();
            format!("{}\n{}{}", &out[..insert_at], tags, &out[insert_at..])
        }
        None => format!("{tags}\n{out}"),
    }
}

async fn serve_chunk(State(state): State<Arc<ServerState>>, headers: HeaderMap) -> Response {
    // Fresh case: cached bytes + etag, so an unchanged reload is a 304 and
    // never re-assembles.
    if let Some((etag, body)) = state.chunk_cache.lock().unwrap().clone() {
        return chunk_response(&headers, etag, body);
    }

    // The chunk needs the full graph: wait for the eager crawl.
    let mut crawl_done = state.crawl_done.clone();
    if !*crawl_done.borrow() {
        let _ = crawl_done.wait_for(|done| *done).await;
    }
    let urls: Vec<String> = state
        .graph
        .lock()
        .unwrap()
        .module_paths()
        .iter()
        .map(|p| p.display().to_string())
        .collect();

    // Single-flight assembly: coalesce concurrent cold reloads.
    let lock = {
        let mut locks = state.compile_locks.lock().unwrap();
        Arc::clone(locks.entry("/@oj/chunk.js".into()).or_default())
    };
    let _guard = lock.lock().await;
    if let Some((etag, body)) = state.chunk_cache.lock().unwrap().clone() {
        return chunk_response(&headers, etag, body);
    }

    let mut chunk = String::new();
    for url in &urls {
        match registration_for(&state, url).await {
            Ok(registration) => chunk.push_str(&registration),
            Err(err) => {
                return (StatusCode::INTERNAL_SERVER_ERROR, format!("oj: chunk: {err}"))
                    .into_response();
            }
        }
    }
    for entry in html_entries(&state.root) {
        chunk.push_str(&format!("__oj_start({entry:?});\n"));
    }
    let etag = format!("\"{}\"", state.cache.key(chunk.as_bytes(), "/@oj/chunk.js", "chunk"));
    let body = Arc::new(chunk);
    *state.chunk_cache.lock().unwrap() = Some((etag.clone(), Arc::clone(&body)));
    chunk_response(&headers, etag, body)
}

fn chunk_response(headers: &HeaderMap, etag: String, body: Arc<String>) -> Response {
    if headers.get(header::IF_NONE_MATCH).and_then(|v| v.to_str().ok()) == Some(etag.as_str()) {
        return (
            StatusCode::NOT_MODIFIED,
            [(header::ETAG, etag), (header::CACHE_CONTROL, "no-cache".to_string())],
        )
            .into_response();
    }
    (
        [
            (header::CONTENT_TYPE, "text/javascript".to_string()),
            (header::CACHE_CONTROL, "no-cache".to_string()),
            (header::ETAG, etag),
        ],
        body.as_str().to_string(),
    )
        .into_response()}

/// `?m=url1,url2&t=...`: re-registrations for the changed modules.
async fn serve_patch(State(state): State<Arc<ServerState>>, uri: Uri) -> Response {
    let query = uri.query().unwrap_or("");
    let modules = query
        .split('&')
        .find_map(|kv| kv.strip_prefix("m="))
        .map(|v| urldecode(v))
        .unwrap_or_default();

    let mut patch = String::new();
    for url in modules.split(',').filter(|u| !u.is_empty()) {
        match registration_for(&state, url).await {
            Ok(registration) => patch.push_str(&registration),
            Err(err) => {
                let _ = state.reload_tx.send(
                    serde_json::json!({ "type": "error", "message": err.clone() }).to_string(),
                );
                return (StatusCode::INTERNAL_SERVER_ERROR, format!("oj: patch: {err}"))
                    .into_response();
            }
        }
    }
    (
        [(header::CONTENT_TYPE, "text/javascript"), (header::CACHE_CONTROL, "no-cache")],
        patch,
    )
        .into_response()
}

/// Resolve a module url to its file path (shared by chunk + lazy assembly).
fn locate_url(state: &ServerState, url: &str) -> Result<PathBuf, String> {
    if let Some(abs) = url.strip_prefix("/@fs") {
        Ok(PathBuf::from(abs))
    } else {
        let rel = url.trim_start_matches('/');
        locate(&state.root, &state.public_dir, rel).ok_or_else(|| format!("no such module: {url}"))
    }
}

/// Render a module's `__oj_register(...)` statement from its compiled form.
fn render_registration(url: &str, module: &CachedModule) -> String {
    let deps: serde_json::Map<String, serde_json::Value> = module
        .require_map
        .iter()
        .map(|(spec, target)| (spec.clone(), serde_json::Value::String(target.clone())))
        .collect();
    if module.kind == "css" {
        let exports = if module.css_exports.is_empty() {
            "void 0".to_string()
        } else {
            let map: serde_json::Map<String, serde_json::Value> = module
                .css_exports
                .iter()
                .map(|(k, v)| (k.clone(), serde_json::Value::String(v.clone())))
                .collect();
            serde_json::Value::Object(map).to_string()
        };
        return format!(
            "__oj_register({url:?}, \"esm\", {{}}, function(module, __oj_exports, __oj_require) {{\n             __oj_esm(__oj_exports, {{ \"default\": () => __oj_css_default }});\n             var __oj_css_default = {exports};\n             __oj_inject_css({url:?}, {css});\n             }});\n",
            css = serde_json::Value::String(module.code.clone()),
        );
    }
    // Parameter names are kind-specific: CJS bodies reference
    // `exports`/`require` directly, ESM factories the __oj_* forms.
    let params = if module.kind == "cjs" {
        "module, exports, require"
    } else {
        "module, __oj_exports, __oj_require"
    };
    format!(
        "__oj_register({url:?}, {kind:?}, {deps}, function({params}) {{\n{body}\n}});\n",
        kind = module.kind,
        deps = serde_json::Value::Object(deps),
        body = module.code,
    )
}

/// One `__oj_register(...)` statement for a module, compiling if needed.
async fn registration_for(state: &Arc<ServerState>, url: &str) -> Result<String, String> {
    let file = locate_url(state, url)?;
    let (_, module) = ensure_module(state, &file, url).await?;
    Ok(render_registration(url, &module))
}

/// `?id=<url>&have=<csv>`: register the target's static-import closure (minus
/// the modules this client already holds) so a lazy `import()` compiled to
/// `__oj_import_lazy` resolves on demand. Nested dynamic imports inside the
/// subtree stay their own lazy boundaries. Compiles subtrees the eager crawl
/// deliberately skipped.
async fn serve_lazy(State(state): State<Arc<ServerState>>, uri: Uri) -> Response {
    let query = uri.query().unwrap_or("");
    let field = |k: &str| query.split('&').find_map(|kv| kv.strip_prefix(k)).map(urldecode);
    let Some(id) = field("id=").filter(|s| !s.is_empty()) else {
        return (StatusCode::BAD_REQUEST, "oj: lazy: id required").into_response();
    };
    // Modules the client already registered: never re-ship (shared React etc.).
    let mut visited: std::collections::HashSet<String> = field("have=")
        .map(|v| v.split(',').filter(|s| !s.is_empty()).map(str::to_string).collect())
        .unwrap_or_default();

    let mut chunk = String::new();
    let mut queue = vec![id.split('?').next().unwrap_or(&id).to_string()];
    while let Some(url) = queue.pop() {
        if url.starts_with("/@oj/") || !visited.insert(url.clone()) {
            continue;
        }
        let Ok(file) = locate_url(&state, &url) else { continue };
        let module = match ensure_module(&state, &file, &url).await {
            Ok((_, module)) => module,
            Err(err) => return (StatusCode::INTERNAL_SERVER_ERROR, format!("oj: lazy: {err}")).into_response(),
        };
        chunk.push_str(&render_registration(&url, &module));
        for imp in &module.imports {
            let clean = imp.split('?').next().unwrap_or(imp);
            if clean.starts_with('/') && !clean.starts_with("/@oj/") && !visited.contains(clean) {
                queue.push(clean.to_string());
            }
        }
    }
    (
        [(header::CONTENT_TYPE, "text/javascript"), (header::CACHE_CONTROL, "no-cache")],
        chunk,
    )
        .into_response()
}

fn urldecode(input: &str) -> String {
    // Only %2F and %2C realistically appear in oj's module lists.
    input.replace("%2F", "/").replace("%2f", "/").replace("%2C", ",").replace("%2c", ",")
}

/// Module-script entry URLs from the app's index.html.
fn html_entries(root: &Path) -> Vec<String> {
    let Ok(html) = std::fs::read_to_string(root.join("index.html")) else {
        return Vec::new();
    };
    let mut entries = Vec::new();
    for tag_start in html.match_indices("<script").map(|(i, _)| i) {
        let Some(tag_end) = html[tag_start..].find('>') else { continue };
        let tag = &html[tag_start..tag_start + tag_end];
        if !tag.contains("type=\"module\"") {
            continue;
        }
        if let Some(src_at) = tag.find("src=\"") {
            let rest = &tag[src_at + 5..];
            if let Some(end) = rest.find('"') {
                let src = &rest[..end];
                if src.starts_with('/') {
                    entries.push(src.to_string());
                }
            }
        }
    }
    entries
}

/// Startup crawl: compile the entire entry-reachable graph in parallel so
/// first paint never waits on request-driven, depth-serialized discovery.
fn spawn_crawl(state: Arc<ServerState>, done_tx: tokio::sync::watch::Sender<bool>) {
    tokio::spawn(async move {
        let started = Instant::now();
        let mut visited: std::collections::HashSet<String> = std::collections::HashSet::new();
        let mut queue: Vec<String> = html_entries(&state.root);
        let mut tasks = tokio::task::JoinSet::new();

        loop {
            for url in queue.drain(..) {
                if !visited.insert(url.clone()) {
                    continue;
                }
                let file = if let Some(abs) = url.strip_prefix("/@fs") {
                    let f = PathBuf::from(abs);
                    let ok = { let a = state.fs_allow.lock().unwrap();
                        a.iter().any(|r| f.starts_with(r)) };
                    if !ok { continue; }
                    f
                } else {
                    let rel = url.trim_start_matches('/').to_string();
                    match locate(&state.root, &state.public_dir, &rel) { Some(f) => f, None => continue }
                };
                let ext = file.extension().and_then(|e| e.to_str()).unwrap_or("");
                if !COMPILABLE.contains(&ext) && !matches!(ext, "css" | "scss" | "sass" | "json") {
                    continue;
                }
                let state = Arc::clone(&state);
                tasks.spawn(async move {
                    match ensure_module(&state, &file, &url).await {
                        Ok((_, module)) => module.imports.clone(),
                        Err(err) => {
                            eprintln!("oj: crawl: {err}");
                            Vec::new()
                        }
                    }
                });
            }
            match tasks.join_next().await {
                None => break,
                Some(imports) => {
                    for import in imports.unwrap_or_default() {
                        let import =
                            import.split('?').next().unwrap_or(&import).to_string();
                        if import.starts_with('/')
                            && !import.starts_with("/@oj/")
                            && !visited.contains(&import)
                        {
                            queue.push(import);
                        }
                    }
                }
            }
        }

        let paths = state.graph.lock().unwrap().module_paths();
        println!("{} eager graph ready: {} modules in {:?}", oj_tag(), paths.len(), started.elapsed());
        save_graph_snapshot(&state.root, &paths);
        let _ = done_tx.send(true);
    });
}

fn snapshot_path(root: &Path) -> PathBuf {
    root.join(".oj-cache").join("graph-snapshot.json")
}

fn load_graph_snapshot(root: &Path) -> Vec<String> {
    std::fs::read(snapshot_path(root))
        .ok()
        .and_then(|bytes| serde_json::from_slice(&bytes).ok())
        .unwrap_or_default()
}

fn save_graph_snapshot(root: &Path, paths: &[PathBuf]) {
    let urls: Vec<String> = paths.iter().map(|p| p.display().to_string()).collect();
    let path = snapshot_path(root);
    if let Some(parent) = path.parent() {
        let _ = std::fs::create_dir_all(parent);
    }
    let _ = std::fs::write(path, serde_json::to_vec(&urls).unwrap_or_default());
}

fn spawn_watcher(state: Arc<ServerState>) {
    std::thread::spawn(move || {
        use notify::{RecursiveMode, Watcher};

        let (tx, rx) = std::sync::mpsc::channel();
        let mut watcher = match notify::recommended_watcher(tx) {
            Ok(w) => w,
            Err(err) => {
                eprintln!("oj: file watcher failed to start: {err}");
                return;
            }
        };
        if let Err(err) = watcher.watch(&state.root, RecursiveMode::Recursive) {
            eprintln!("oj: cannot watch {}: {err}", state.root.display());
            return;
        }

        // Trailing/coalescing debounce. Editor and OS writes fire several
        // events per save; collect a burst and process it once after a short
        // quiet gap. Never drops an event: a leading "skip if within Nms of
        // the last send" debounce loses a second edit whose event lands in
        // the shadow of the first's trailing event.
        use std::sync::mpsc::RecvTimeoutError;
        // Trailing-drain window: after the last event of a save's burst, wait
        // this long for the next before processing. It sits directly on the HMR
        // critical path (a single-event save waits exactly this long before the
        // recompile even starts), so it is kept just long enough to coalesce a
        // burst — editor writes land within ~1-2ms, so 10ms coalesces reliably
        // while shaving ~20ms off save-to-paint versus the old 30ms. Tunable via
        // OJ_HMR_DEBOUNCE_MS. Never drops an event: any event resets the timer.
        let debounce_ms: u64 = std::env::var("OJ_HMR_DEBOUNCE_MS")
            .ok()
            .and_then(|v| v.parse().ok())
            .unwrap_or(10);
        loop {
            // Block for the first event of a burst.
            let first = match rx.recv() {
                Ok(Ok(ev)) => ev,
                Ok(Err(_)) => continue,
                Err(_) => break, // channel closed
            };
            let mut paths: std::collections::HashSet<PathBuf> =
                first.paths.into_iter().collect();
            // Drain the rest of the burst until things go quiet.
            loop {
                match rx.recv_timeout(Duration::from_millis(debounce_ms)) {
                    Ok(Ok(ev)) => paths.extend(ev.paths),
                    Ok(Err(_)) => {}
                    Err(RecvTimeoutError::Timeout) => break,
                    Err(RecvTimeoutError::Disconnected) => return,
                }
            }
            let paths: Vec<PathBuf> = paths.into_iter().collect();
            let messages = decide(&state, &paths);
            if messages.is_empty() {
                continue;
            }
            // Anything changed: the assembled chunk is stale, and a created or
            // removed file may change how relative imports resolve.
            *state.chunk_cache.lock().unwrap() = None;
            state.dir_cache.lock().unwrap().clear();
            for message in messages {
                let _ = state.reload_tx.send(message);
            }
        }
    });
}

/// Turn a batch of changed paths into HMR messages (empty if irrelevant).
fn decide(state: &ServerState, paths: &[PathBuf]) -> Vec<String> {
    let mut messages: Vec<String> = Vec::new();
    let mut updates: Vec<serde_json::Value> = Vec::new();

    // Files plugins registered via this.addWatchFile: a change to one forces a
    // full reload even if oj would otherwise ignore the file. Fetched once per
    // burst (canonicalized so /tmp vs /private/tmp style aliases still match).
    let plugin_watched: std::collections::HashSet<PathBuf> = match &state.plugins {
        Some(host) => state
            .rt
            .block_on(host.watch_files())
            .unwrap_or_default()
            .into_iter()
            .map(|p| std::fs::canonicalize(&p).unwrap_or_else(|_| PathBuf::from(p)))
            .collect(),
        None => Default::default(),
    };

    // Any source change can mint new utility classes: refresh tailwind css.
    let source_changed = paths.iter().any(|p| {
        !p.components().any(|c| {
            let c = c.as_os_str();
            c == "node_modules" || c == ".oj-cache" || c == "dist"
        })
            && p.extension()
                .and_then(|e| e.to_str())
                .is_some_and(|e| COMPILABLE.contains(&e))
    });
    if source_changed {
        let timestamp = now_millis() as u64;
        for url in state.tailwind_urls.lock().unwrap().iter() {
            messages.push(
                serde_json::json!({ "type": "css-update", "path": url, "timestamp": timestamp })
                    .to_string(),
            );
        }
    }

    for path in paths {
        // Deps change via installs, not saves; watching them is pure noise.
        // .oj-cache and dist are oj's own outputs.
        if path.components().any(|c| {
            let c = c.as_os_str();
            c == "node_modules" || c == ".oj-cache" || c == "dist"
        }) {
            continue;
        }

        // Notify plugins the file changed (Rollup watchChange), then let them
        // customize HMR (handleHotUpdate).
        if let Some(host) = &state.plugins {
            let file = path.display().to_string();
            let ts = now_millis() as u64;
            let _ = state.rt.block_on(host.watch_change(&file, "update"));
            match state.rt.block_on(host.handle_hot_update(&file, ts)) {
                Ok(Some(d)) if d == "skip" => {
                    println!("oj: change {file} -> HMR suppressed by plugin");
                    continue;
                }
                Ok(Some(d)) if d == "full-reload" => {
                    println!("oj: change {file} -> full-reload (plugin)");
                    messages.push(
                        serde_json::json!({ "type": "full-reload", "reason": "plugin" }).to_string(),
                    );
                    return messages;
                }
                _ => {}
            }
        }

        // A plugin-watched file (this.addWatchFile): force a full reload.
        if !plugin_watched.is_empty() {
            let canon = std::fs::canonicalize(path).unwrap_or_else(|_| path.clone());
            if plugin_watched.contains(&canon) {
                println!("oj: change {} -> full-reload (plugin watch)", path.display());
                messages.push(
                    serde_json::json!({ "type": "full-reload", "reason": "plugin-watch" }).to_string(),
                );
                return messages;
            }
        }

        let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
        if ext == "css" {
            let url = url_of(&state.root, path);
            if !state.graph.lock().unwrap().contains(Path::new(&url)) {
                // Only referenced via <link>: hot-swap the stylesheet.
                println!("oj: change {url} -> css-update");
                messages.push(
                    serde_json::json!({
                        "type": "css-update",
                        "path": url,
                        "timestamp": now_millis() as u64,
                    })
                    .to_string(),
                );
                continue;
            }
            // JS-imported css: falls through to module propagation below.
        }
        if ext == "html" {
            println!("oj: change {} -> full-reload", path.display());
            messages.push(
                serde_json::json!({ "type": "full-reload", "reason": path.display().to_string() })
                    .to_string(),
            );
            return messages;
        }
        if !COMPILABLE.contains(&ext) && !matches!(ext, "css" | "scss" | "sass" | "json") {
            continue;
        }

        let url = url_of(&state.root, path);
        if state.bundle {
            let plan = state.graph.lock().unwrap().update_plan(Path::new(&url));
            match plan {
                Ok(plan) => {
                    println!("oj: change {url} -> patch {:?}", plan.boundaries);
                    let to_urls = |v: &[PathBuf]| -> Vec<String> {
                        v.iter().map(|p| p.display().to_string()).collect()
                    };
                    let seq = state
                        .patch_seq
                        .fetch_add(1, std::sync::atomic::Ordering::Relaxed)
                        + 1;
                    messages.push(
                        serde_json::json!({
                            "type": "patch",
                            "changed": [url],
                            "dirty": to_urls(&plan.dirty),
                            "boundaries": to_urls(&plan.boundaries),
                            "timestamp": now_millis() as u64,
                            "seq": seq,
                        })
                        .to_string(),
                    );
                    continue;
                }
                Err(reason) => {
                    println!("oj: change {url} -> full-reload ({reason})");
                    messages.push(
                        serde_json::json!({ "type": "full-reload", "reason": reason }).to_string(),
                    );
                    return messages;
                }
            }
        }
        let decision = state.graph.lock().unwrap().propagate_update(Path::new(&url));
        match decision {
            HmrDecision::Update { boundaries } => {
                println!("oj: change {url} -> update {boundaries:?}");
                let timestamp = now_millis() as u64;
                updates.extend(boundaries.iter().map(|b| {
                    let mut path = format!("{}", b.display());
                    if path.ends_with(".css") {
                        path.push_str("?import");
                    }
                    serde_json::json!({ "path": path, "timestamp": timestamp })
                }));
            }
            HmrDecision::FullReload { reason } => {
                println!("oj: change {url} -> full-reload ({reason})");
                messages.push(
                    serde_json::json!({ "type": "full-reload", "reason": reason }).to_string(),
                );
                return messages;
            }
        }
    }

    if !updates.is_empty() {
        messages.push(serde_json::json!({ "type": "update", "updates": updates }).to_string());
    }
    messages
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn html_injection_puts_preamble_first_in_head() {
        let out = inject_dev_scripts("<html><head><title>x</title></head></html>".into());
        let preamble = out.find("refresh-preamble").unwrap();
        let title = out.find("<title>").unwrap();
        assert!(preamble < title);
    }

    #[test]
    fn glue_only_added_for_boundary_modules() {
        assert!(hot_glue("/src/util.ts", None, false).is_empty());
        let glue = hot_glue("/src/App.tsx", Some("t=123"), true);
        assert!(glue.contains(r#"createHotContext("/src/App.tsx")"#));
        assert!(glue.contains(r#"from "/src/App.tsx?t=123""#), "{glue}");
        assert!(glue.contains("validateRefreshBoundaryAndEnqueueUpdate"));
        assert!(glue.contains("function $RefreshReg$"));
    }

    #[test]
    fn normalize_resolves_parent_components() {
        assert_eq!(
            normalize(Path::new("/a/b/../c/./d.ts")),
            PathBuf::from("/a/c/d.ts")
        );
    }

    #[test]
    fn preview_rel_maps_base_and_guards_traversal() {
        assert_eq!(preview_rel("/", "/").as_deref(), Some("index.html"));
        assert_eq!(preview_rel("/assets/x.js", "/").as_deref(), Some("assets/x.js"));
        // base stripping
        assert_eq!(preview_rel("/app/assets/x.js", "/app/").as_deref(), Some("assets/x.js"));
        assert_eq!(preview_rel("/app/", "/app/").as_deref(), Some("index.html"));
        // traversal denied
        assert_eq!(preview_rel("/../etc/passwd", "/"), None);
    }

    #[test]
    fn spa_navigation_falls_back_only_for_routes() {
        let html = {
            let mut h = HeaderMap::new();
            h.insert(header::ACCEPT, "text/html,application/xhtml+xml".parse().unwrap());
            h
        };
        let empty = HeaderMap::new();
        // Extension-less client routes fall back to index.html.
        assert!(is_spa_navigation("dashboard", &empty));
        assert!(is_spa_navigation("users/123/edit", &empty));
        // A browser HTML navigation falls back even with dots in the path.
        assert!(is_spa_navigation("report.v2", &html));
        // Missing assets (has extension, not an HTML nav) stay 404.
        assert!(!is_spa_navigation("missing.png", &empty));
        assert!(!is_spa_navigation("assets/app.js", &empty));
        // oj-internal namespaces and source never fall back.
        assert!(!is_spa_navigation("@vite/client", &html));
        assert!(!is_spa_navigation("src/does-not-exist.tsx", &html));
        assert!(!is_spa_navigation("node_modules/react/missing.js", &html));
    }
}

#[cfg(test)]
mod adapter_tests {
    use super::*;

    fn tmp(label: &str) -> std::path::PathBuf {
        let d = std::env::temp_dir().join(format!("oj-srv-{}-{label}", std::process::id()));
        let _ = std::fs::remove_dir_all(&d);
        std::fs::create_dir_all(&d).unwrap();
        d
    }

    #[test]
    fn is_tanstack_start_app_requires_routes_and_dep() {
        let base = tmp("ts");
        let app = base.join("app");
        std::fs::create_dir_all(app.join("src").join("routes")).unwrap();
        // routes dir present but no react-start dep -> not a start app
        std::fs::write(app.join("package.json"), r#"{"dependencies":{"react":"19"}}"#).unwrap();
        assert!(!is_tanstack_start_app(&app));
        // add the dep -> detected
        std::fs::write(app.join("package.json"), r#"{"dependencies":{"@tanstack/react-start":"1"}}"#).unwrap();
        assert!(is_tanstack_start_app(&app));
        // dep but no src/routes -> not a start app
        let app2 = base.join("app2");
        std::fs::create_dir_all(app2.join("src")).unwrap();
        std::fs::write(app2.join("package.json"), r#"{"dependencies":{"@tanstack/react-start":"1"}}"#).unwrap();
        assert!(!is_tanstack_start_app(&app2));
        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn locate_prefers_root_then_public_dir() {
        let base = tmp("locate");
        let root = base.join("root");
        let public = base.join("shared-public");
        std::fs::create_dir_all(root.join("src")).unwrap();
        std::fs::create_dir_all(public.join("img")).unwrap();
        std::fs::write(root.join("src").join("App.tsx"), "x").unwrap();
        std::fs::write(public.join("img").join("logo.webp"), "y").unwrap();

        // extensionless import resolves TS-first under root
        assert_eq!(locate(&root, &public, "src/App"), Some(root.join("src/App.tsx")));
        // a public asset resolves from the configured public dir
        assert_eq!(locate(&root, &public, "img/logo.webp"), Some(public.join("img/logo.webp")));
        // missing -> None; traversal refused
        assert_eq!(locate(&root, &public, "img/missing.webp"), None);
        assert_eq!(locate(&root, &public, "../secret"), None);
        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn is_spa_navigation_rules() {
        let empty = HeaderMap::new();
        // extensionless client routes fall back to index.html
        assert!(is_spa_navigation("dashboard", &empty));
        assert!(is_spa_navigation("projects/abc", &empty));
        // assets and oj-internal namespaces do not
        assert!(!is_spa_navigation("main.js", &empty));
        assert!(!is_spa_navigation("@vite/client", &empty));
        assert!(!is_spa_navigation("src/App.tsx", &empty));
        assert!(!is_spa_navigation("node_modules/react/index.js", &empty));
        // an html navigation with an extension still falls back (accept header)
        let mut html = HeaderMap::new();
        html.insert(header::ACCEPT, "text/html,*/*".parse().unwrap());
        assert!(is_spa_navigation("some.thing", &html));
    }
}