bun_runtime 0.1.2

Bao runtime integration — JS engine + Bun API + event loop
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
// @trace REQ-ENG-006 [api:node:http2]
//
// HTTP/2 module — JS IIFE + Rust uWS bridge.
//
// Architecture:
//   - createServer / createSecureServer: uWS App (non-SSL / SSL) with H2-capable
//     route handler, same pattern as node_http / node_https.
//   - connect / client session: fetch_async::start for async HTTP/2 requests
//     (BoringSSL ALPN negotiates H2 automatically).
//   - Http2Session / Http2Stream / constants: JS IIFE for the bulk of the API
//     surface; Rust native functions only for server creation, settings packing,
//     and async fetch bridging.
use ::std::cell::RefCell;
use ::std::ptr::NonNull;
use ::std::sync::atomic::{AtomicU64, Ordering};
use bun_core::ZBox;

use mozjs::jsapi::*;
use mozjs::jsval::{
    BooleanValue, Int32Value, JSVal, ObjectValue, PrivateValue, StringValue, UndefinedValue,
};
use mozjs::rooted;
use mozjs::rust::wrappers2 as w2;

use bun_uws_sys::app::App;
use bun_uws_sys::request::Request;
use bun_uws_sys::response::Response;
use bun_uws_sys::socket_context::BunSocketContextOptions;

use crate::gc_store::{gc_store_get_ns, gc_store_insert_ns, gc_store_remove_ns};
use crate::require::cache_builtin;

static NEXT_SERVER_ID: AtomicU64 = AtomicU64::new(1);
#[allow(dead_code)]
static NEXT_SESSION_ID: AtomicU64 = AtomicU64::new(1);

thread_local! {
    static ACTIVE_H2_APPS: RefCell<Vec<*mut App<false>>> = const { RefCell::new(Vec::new()) };
    static ACTIVE_H2_SSL_APPS: RefCell<Vec<*mut App<true>>> = const { RefCell::new(Vec::new()) };
}

pub fn has_active_servers() -> bool {
    ACTIVE_H2_APPS.with(|s| !s.borrow().is_empty())
        || ACTIVE_H2_SSL_APPS.with(|s| !s.borrow().is_empty())
}

// BCE-007 registration gap (node_http2 variant): `drain_and_check`
// (timers.rs) keeps the JS-thread uWS `Loop` ticking ONLY while
// `node_http::has_active_servers()` is true — the h2-local registries above
// were never consulted there, so an h2 App's listen socket never `accept()`ed
// (requests connected, then sat unanswered; route handler never invoked).
// Same disease Bun.serve had before the unified `register_active_app` fix
// (bun_api.rs). Close the class: every h2 register/unregister ALSO keeps the
// unified node_http liveness registry in sync, so the single source of truth
// drives the loop tick for h2 Apps too.
//
// The SSL registration passes an `*mut App<true>` through the `App<false>`
// registry API: `App<SSL>` is a `#[repr(C)]` zero-sized opaque token with
// identical layout for both instantiations, and the unified registry uses
// pointers ONLY for liveness bookkeeping (len / ptr-eq / retain — never
// dereferences), so the cast is a representation-preserving token alias.

pub unsafe fn register_active_h2_app(app: *mut App<false>) {
    if app.is_null() {
        return;
    }
    ACTIVE_H2_APPS.with(|s| {
        let mut apps = s.borrow_mut();
        if !apps.iter().any(|&p| ::std::ptr::eq(p, app)) {
            apps.push(app);
        }
    });
    crate::node_http::register_active_app(app);
}

pub unsafe fn unregister_active_h2_app(app: *mut App<false>) {
    if app.is_null() {
        return;
    }
    ACTIVE_H2_APPS.with(|s| {
        s.borrow_mut().retain(|&p| !::std::ptr::eq(p, app));
    });
    crate::node_http::unregister_active_app(app);
}

pub unsafe fn register_active_h2_ssl_app(app: *mut App<true>) {
    if app.is_null() {
        return;
    }
    ACTIVE_H2_SSL_APPS.with(|s| {
        let mut apps = s.borrow_mut();
        if !apps.iter().any(|&p| ::std::ptr::eq(p, app)) {
            apps.push(app);
        }
    });
    // Liveness token only — see the safety note above the register fns.
    crate::node_http::register_active_app(app as *mut App<false>);
}

pub unsafe fn unregister_active_h2_ssl_app(app: *mut App<true>) {
    if app.is_null() {
        return;
    }
    ACTIVE_H2_SSL_APPS.with(|s| {
        s.borrow_mut().retain(|&p| !::std::ptr::eq(p, app));
    });
    // Liveness token only — see the safety note above the register fns.
    crate::node_http::unregister_active_app(app as *mut App<false>);
}

// ──────────────────────────────────────────────────────────────────────
// JS IIFE — Http2Session, Http2Stream, connect, utility functions
// ──────────────────────────────────────────────────────────────────────

const HTTP2_JS: &str = r#"
(function() {
  // ── Minimal EventEmitter ────────────────────────────────────────────
  function EE() { this._events = Object.create(null); }
  EE.prototype.on = function(ev, fn) {
    (this._events[ev] || (this._events[ev] = [])).push(fn);
    return this;
  };
  EE.prototype.once = function(ev, fn) {
    var self = this;
    var g = function() { self.removeListener(ev, g); fn.apply(this, arguments); };
    g.listener = fn;
    this.on(ev, g);
    return this;
  };
  EE.prototype.emit = function(ev) {
    var args = Array.prototype.slice.call(arguments, 1);
    var list = this._events[ev];
    if (list) { for (var i = 0; i < list.length; i++) { list[i].apply(this, args); } }
    return this;
  };
  EE.prototype.removeListener = function(ev, fn) {
    var list = this._events[ev];
    if (!list) return this;
    for (var i = list.length - 1; i >= 0; i--) {
      if (list[i] === fn || list[i].listener === fn) list.splice(i, 1);
    }
    return this;
  };
  EE.prototype.removeAllListeners = function(ev) {
    if (ev) delete this._events[ev];
    else this._events = Object.create(null);
    return this;
  };
  EE.prototype.prependListener = function(ev, fn) {
    (this._events[ev] || (this._events[ev] = [])).unshift(fn);
    return this;
  };

  // ── byte-exact body helpers (same contract as the node:http client) ──
  // Buffers/TypedArrays/ArrayBuffers are byte bodies; the historical
  // `String(data)` coercion turned them into "72,101,108" comma strings.
  function isByteValue(v) {
    return !!v && typeof v === 'object' &&
      (v instanceof ArrayBuffer ||
       (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && ArrayBuffer.isView(v)));
  }
  function pushBodyChunk(stream, data) {
    if (data === undefined || data === null) return;
    if (typeof data === 'string' || isByteValue(data)) {
      (stream._bodyChunks || (stream._bodyChunks = [])).push(data);
      return;
    }
    throw new TypeError('http2: stream chunk must be a string, Buffer, TypedArray or ArrayBuffer');
  }
  // Transport body argument: all-string parts join (fast path, identical
  // bytes); any binary part switches to byte-exact Uint8Array assembly.
  function buildBodyArg(parts) {
    var hasBinary = false;
    for (var i = 0; i < parts.length; i++) {
      if (typeof parts[i] !== 'string') { hasBinary = true; break; }
    }
    if (!hasBinary) return parts.join('');
    var enc = new TextEncoder();
    var chunks = [];
    var total = 0;
    for (var j = 0; j < parts.length; j++) {
      var p = parts[j];
      var u;
      if (typeof p === 'string') u = enc.encode(p);
      else if (p instanceof ArrayBuffer) u = new Uint8Array(p);
      else u = new Uint8Array(p.buffer, p.byteOffset, p.byteLength);
      chunks.push(u);
      total += u.length;
    }
    var out = new Uint8Array(total);
    var off = 0;
    for (var k = 0; k < chunks.length; k++) {
      out.set(chunks[k], off);
      off += chunks[k].length;
    }
    return out;
  }

  // ── Http2Stream ─────────────────────────────────────────────────────
  function Http2Stream(session, id) {
    this._session = session;
    this._id = id;
    this._headers = {};
    this._trailers = {};
    this._ended = false;
    this._closed = false;
    this._events = Object.create(null);
    this.readable = true;
    this.writable = true;
    // Ordered string|byte parts — byte-exact request-body accumulation.
    this._bodyChunks = [];
  }
  Http2Stream.prototype = Object.create(null);
  // Mix in EventEmitter
  Http2Stream.prototype.on = EE.prototype.on;
  Http2Stream.prototype.once = EE.prototype.once;
  Http2Stream.prototype.emit = EE.prototype.emit;
  Http2Stream.prototype.removeListener = EE.prototype.removeListener;
  Http2Stream.prototype.removeAllListeners = EE.prototype.removeAllListeners;
  Http2Stream.prototype.prependListener = EE.prototype.prependListener;

  Object.defineProperty(Http2Stream.prototype, 'id', {
    get: function() { return this._id; },
    enumerable: true
  });
  Object.defineProperty(Http2Stream.prototype, 'session', {
    get: function() { return this._session; },
    enumerable: true
  });
  Object.defineProperty(Http2Stream.prototype, 'closed', {
    get: function() { return this._closed; },
    enumerable: true
  });
  Object.defineProperty(Http2Stream.prototype, 'ended', {
    get: function() { return this._ended; },
    enumerable: true
  });
  Object.defineProperty(Http2Stream.prototype, 'state', {
    get: function() {
      return {
        localWindowSize: 65535,
        state: this._ended ? 4 : 0, // NGHTTP2_STREAM_CLOSED : NGHTTP2_STREAM_IDLE
        weight: 16,
        sumDependencyWeight: 0,
        localClose: this._ended ? 1 : 0,
        remoteClose: 0
      };
    },
    enumerable: true
  });

  Http2Stream.prototype.respond = function(headers, options) {
    if (this._closed || this._ended) return this;
    headers = headers || {};
    this._headers = Object.assign(this._headers, headers);
    if (options && options.endStream) {
      this.end();
    }
    return this;
  };

  Http2Stream.prototype.end = function(data, cb) {
    if (this._ended) return this;
    if (typeof data === 'function') { cb = data; data = undefined; }
    pushBodyChunk(this, data);
    this._ended = true;
    this.writable = false;
    this.emit('end');
    if (cb) cb();
    return this;
  };

  Http2Stream.prototype.close = function(code, cb) {
    if (this._closed) return this;
    if (typeof code === 'function') { cb = code; code = 0; }
    this._closed = true;
    this._ended = true;
    this.readable = false;
    this.writable = false;
    // Upstream f7ad274e3 parity: release the stream from the session's
    // registry as soon as it is fully closed. Node drops a stream when both
    // halves close; without this eviction one Http2Stream per request stays
    // rooted on the session for its whole lifetime (WeakRef never clears).
    if (this._session && this._session._streams) {
      delete this._session._streams[this._id];
    }
    this.emit('close');
    if (cb) cb();
    return this;
  };

  Http2Stream.prototype.priority = function(options) {
    // Priority signaling — no-op in JS-based H2 layer
    return this;
  };

  Http2Stream.prototype.sendTrailers = function(headers) {
    if (this._closed) return this;
    this._trailers = Object.assign(this._trailers, headers || {});
    return this;
  };

  Http2Stream.prototype.pushStream = function(headers, options, callback) {
    // Server push — not supported in JS-based H2 layer
    var err = new Error('HTTP/2 server push is not supported');
    if (callback) callback(err);
    return this;
  };

  Http2Stream.prototype.setTimeout = function(msecs, callback) {
    if (callback) callback();
    return this;
  };

  Http2Stream.prototype.destroy = function(error) {
    if (this._closed) return;
    this._closed = true;
    this._ended = true;
    this.readable = false;
    this.writable = false;
    // Same release-on-close invariant as close() (f7ad274e3 parity).
    if (this._session && this._session._streams) {
      delete this._session._streams[this._id];
    }
    if (error) this.emit('error', error);
    this.emit('close');
  };

  // ── Http2Session ────────────────────────────────────────────────────
  var nextStreamId = 1;

  function Http2Session(mode, authority, options) {
    this._mode = mode; // 'client' or 'server'
    this._authority = authority || '';
    this._options = options || {};
    this._streamId = nextStreamId;
    nextStreamId += 2; // client-initiated streams use odd IDs
    this._streams = Object.create(null);
    this._closed = false;
    this._destroyed = false;
    this._events = Object.create(null);
    this._settings = {
      headerTableSize: 4096,
      enablePush: false,
      initialWindowSize: 65535,
      maxFrameSize: 16384,
      maxConcurrentStreams: 100,
      maxHeaderListSize: 65535
    };
    this._remoteSettings = {
      headerTableSize: 4096,
      enablePush: false,
      initialWindowSize: 65535,
      maxFrameSize: 16384,
      maxConcurrentStreams: 100,
      maxHeaderListSize: 65535
    };
    this._pingCallbacks = Object.create(null);
    this._nextPingId = 0;
  }
  Http2Session.prototype = Object.create(null);
  // Mix in EventEmitter
  Http2Session.prototype.on = EE.prototype.on;
  Http2Session.prototype.once = EE.prototype.once;
  Http2Session.prototype.emit = EE.prototype.emit;
  Http2Session.prototype.removeListener = EE.prototype.removeListener;
  Http2Session.prototype.removeAllListeners = EE.prototype.removeAllListeners;
  Http2Session.prototype.prependListener = EE.prototype.prependListener;

  Object.defineProperty(Http2Session.prototype, 'closed', {
    get: function() { return this._closed; },
    enumerable: true
  });
  Object.defineProperty(Http2Session.prototype, 'destroyed', {
    get: function() { return this._destroyed; },
    enumerable: true
  });
  Object.defineProperty(Http2Session.prototype, 'type', {
    get: function() { return this._mode === 'client' ? 0 : 1; },
    enumerable: true
  });
  Object.defineProperty(Http2Session.prototype, 'encrypted', {
    get: function() { return this._mode === 'client' && this._authority.indexOf('https') === 0; },
    enumerable: true
  });
  Object.defineProperty(Http2Session.prototype, 'alpnProtocol', {
    get: function() { return 'h2'; },
    enumerable: true
  });
  Object.defineProperty(Http2Session.prototype, 'originSet', {
    get: function() {
      if (!this._authority) return [];
      return [this._authority];
    },
    enumerable: true
  });
  Object.defineProperty(Http2Session.prototype, 'localSettings', {
    get: function() { return Object.assign({}, this._settings); },
    enumerable: true
  });
  Object.defineProperty(Http2Session.prototype, 'remoteSettings', {
    get: function() { return Object.assign({}, this._remoteSettings); },
    enumerable: true
  });
  Object.defineProperty(Http2Session.prototype, 'state', {
    get: function() {
      return {
        effectiveLocalWindowSize: 65535,
        effectiveRecvDataLength: 0,
        nextStreamID: this._streamId,
        localWindowSize: 65535,
        lastProcStreamID: 0,
        remoteWindowSize: 65535,
        outboundQueueSize: 0,
        deflateDynamicTableSize: 0,
        inflateDynamicTableSize: 0
      };
    },
    enumerable: true
  });
  Object.defineProperty(Http2Session.prototype, 'pendingSettingsAck', {
    get: function() { return false; },
    enumerable: true
  });
  Object.defineProperty(Http2Session.prototype, 'settings', {
    set: function(s) {
      if (s && typeof s === 'object') {
        for (var k in s) {
          if (s.hasOwnProperty(k)) this._settings[k] = s[k];
        }
        this.emit('localSettings', this._settings);
      }
    }
  });

  Http2Session.prototype.request = function(headers, options) {
    if (this._closed || this._destroyed) {
      throw new Error('Session is closed');
    }
    headers = headers || {};
    options = options || {};

    var streamId = this._streamId;
    this._streamId += 2;

    var stream = new Http2Stream(this, streamId);
    stream._headers = Object.assign({}, headers);

    // If this is a client session, perform the fetch via __http2_fetch.
    // The bridge returns the fetch Promise, which resolves with the realm's
    // real WHATWG Response — response headers become the 'response' event
    // (with ':status'), the body is consumed via arrayBuffer() and delivered
    // as ONE Buffer 'data' chunk (Node http2 stream semantics), then 'end'.
    // (The old bridge returned a statusCode:0 placeholder JSON synchronously
    // — every http2 client response was a silent fake.)
    if (this._mode === 'client' && typeof __http2_fetch === 'function') {
      var method = headers[':method'] || 'GET';
      var path = headers[':path'] || '/';
      var authority = headers[':authority'] || this._authority;
      var scheme = headers[':scheme'] || 'https';
      var url = scheme + '://' + authority + path;

      // Build regular headers (strip pseudo-headers)
      var reqHeaders = {};
      for (var k in headers) {
        if (k.charAt(0) !== ':') {
          reqHeaders[k] = headers[k];
        }
      }

      var headersJSON = '{}';
      try { headersJSON = JSON.stringify(reqHeaders); } catch(e) {}

      // Request body: validated eagerly (string or byte body — anything
      // else throws, never a silent comma-string/empty), then assembled
      // byte-exactly. The fire-once bridge carries the body via options.body
      // only — stream.write/end after request() cannot retro-send (the
      // fetch is already in flight).
      if (options.body !== undefined && options.body !== null &&
          typeof options.body !== 'string' && !isByteValue(options.body)) {
        throw new TypeError('http2: request body must be a string, Buffer, TypedArray or ArrayBuffer');
      }
      var bodyArg = buildBodyArg(
        options.body === undefined || options.body === null ? [] : [options.body]
      );

      var sess = this;
      var settle = function (resp) {
        var respHeaders = {};
        try {
          if (resp && resp.headers && typeof resp.headers.forEach === 'function') {
            resp.headers.forEach(function (v, hk) { respHeaders[hk] = v; });
          }
        } catch (e) {}
        respHeaders[':status'] = String(resp && typeof resp.status === 'number' ? resp.status : 0);
        stream._responseHeaders = respHeaders;
        if (!resp || typeof resp.arrayBuffer !== 'function') {
          failStream(new Error('http2: transport resolved without a Response body'));
          return;
        }
        resp.arrayBuffer().then(function (ab) {
          stream.emit('response', respHeaders);
          // One Buffer chunk over the exact wire bytes (Node 'data'
          // semantics — byte view, never a lossy decoded string).
          var chunk;
          if (typeof Buffer !== 'undefined' && typeof Buffer.from === 'function') {
            chunk = Buffer.from(ab);
          } else {
            chunk = new Uint8Array(ab);
          }
          stream._responseBody = chunk;
          if (chunk.length !== 0) stream.emit('data', chunk);
          stream.end();
          // Release-on-completion (same eviction the synchronous path used).
          if (sess._streams) delete sess._streams[streamId];
        }, failStream);
      };
      var failStream = function (err) {
        var e = err instanceof Error ? err : new Error(String(err && err.message ? err.message : err));
        stream.emit('error', e);
        stream.close();
        if (sess._streams) delete sess._streams[streamId];
      };
      var p;
      try {
        p = __http2_fetch(url, method, headersJSON, bodyArg);
      } catch (e) {
        failStream(e);
      }
      if (p !== undefined && p !== null && typeof p.then === 'function' && !stream._closed) {
        p.then(settle, failStream);
      }
    }

    this._streams[streamId] = stream;
    // Upstream f7ad274e3 parity (its flush_queue release point): when the
    // outbound request already completed synchronously — END_STREAM sent by
    // the fetch bridge above — the finished stream must not sit in the
    // session registry until session teardown.
    if (stream._ended) {
      delete this._streams[streamId];
    }
    this.emit('stream', stream, headers);
    return stream;
  };

  Http2Session.prototype.respondWithFile = function(filePath, headers, options) {
    throw new Error('http2.respondWithFile is not supported');
  };

  Http2Session.prototype.respondWithFD = function(fd, headers, options) {
    throw new Error('http2.respondWithFD is not supported');
  };

  Http2Session.prototype.ping = function(payload, callback) {
    if (this._closed || this._destroyed) {
      if (callback) callback(new Error('Session is closed'));
      return false;
    }
    if (typeof payload === 'function') {
      callback = payload;
      payload = null;
    }
    var pingId = this._nextPingId++;
    this._pingCallbacks[pingId] = callback;
    // Simulate ping response
    if (callback) {
      var duration = 0;
      callback(null, duration, payload || Buffer.alloc(8));
    }
    this.emit('ping', payload || Buffer.alloc(8));
    return true;
  };

  Http2Session.prototype.close = function(callback) {
    if (this._closed) {
      if (callback) callback();
      return;
    }
    this._closed = true;
    // Close all open streams. `_streams` is Object.create(null) — it has no
    // hasOwnProperty (calling it threw TypeError the first time this code
    // was ever reached); for-in over a null-proto object only ever yields
    // own enumerable keys, so the guard was redundant anyway. Each
    // stream.close() evicts itself from the registry (f7ad274e3 parity).
    for (var id in this._streams) {
      var stream = this._streams[id];
      if (stream && !stream._closed) stream.close();
    }
    this.emit('close');
    if (callback) callback();
  };

  Http2Session.prototype.destroy = function(error, callback) {
    if (this._destroyed) {
      if (callback) callback();
      return;
    }
    this._destroyed = true;
    this._closed = true;
    // Destroy all streams (evicts each from the registry — see close()).
    for (var id in this._streams) {
      var stream = this._streams[id];
      if (stream) stream.destroy(error);
    }
    if (error) this.emit('error', error);
    this.emit('close');
    if (callback) callback();
  };

  Http2Session.prototype.goaway = function(code, lastStreamID, opaqueData) {
    if (typeof code === 'undefined') code = 0;
    if (typeof lastStreamID === 'undefined') lastStreamID = 0;
    this.emit('goaway', code, lastStreamID, opaqueData);
    this.close();
  };

  Http2Session.prototype.ref = function() { return this; };
  Http2Session.prototype.unref = function() { return this; };

  Http2Session.prototype.setLocalWindowSize = function(windowSize) {
    this._settings.initialWindowSize = windowSize;
    return this;
  };

  Http2Session.prototype.setTimeout = function(msecs, callback) {
    if (callback) callback();
    return this;
  };

  Http2Session.prototype.sendSettings = function(settings) {
    if (settings && typeof settings === 'object') {
      for (var k in settings) {
        if (settings.hasOwnProperty(k)) this._settings[k] = settings[k];
      }
    }
    this.emit('localSettings', this._settings);
  };

  // ── connect(authority, options, listener) ───────────────────────────
  function connect(authority, options, listener) {
    if (typeof options === 'function') {
      listener = options;
      options = {};
    }
    options = options || {};

    var session = new Http2Session('client', authority, options);

    // Store authority for fetch
    if (typeof authority === 'string') {
      if (authority.indexOf('://') === -1) {
        authority = 'https://' + authority;
      }
      session._authority = authority;
    }

    // Emit 'connect' event (synchronous, matching Node.js behavior)
    session.emit('connect', session, null);

    if (listener) {
      session.on('stream', listener);
    }

    return session;
  }

  // ── Server ──────────────────────────────────────────────────────────
  // Node compat split (verified against node docs): the createServer
  // handler is the COMPAT onRequestHandler — called (request, response) —
  // while session-style 'stream' listeners are separate (stream, headers,
  // flags) listeners. Registering the compat handler on 'stream' made the
  // native dispatcher's emit hit it with the wrong shape (double dispatch
  // of one function), so the compat handler now lives on _onStreamHandler
  // (the property the native listen/route bridge reads) and 'stream' is
  // reserved for real session-style listeners.
  function Http2Server(options, handler) {
    if (typeof options === 'function') {
      handler = options;
      options = {};
    }
    this._options = options || {};
    this._events = Object.create(null);
    this.listening = false;
    this._port = 0;
    if (handler) this._onStreamHandler = handler;
  }
  Http2Server.prototype = Object.create(null);
  Http2Server.prototype.on = EE.prototype.on;
  Http2Server.prototype.once = EE.prototype.once;
  Http2Server.prototype.emit = EE.prototype.emit;
  Http2Server.prototype.removeListener = EE.prototype.removeListener;
  Http2Server.prototype.removeAllListeners = EE.prototype.removeAllListeners;
  Http2Server.prototype.prependListener = EE.prototype.prependListener;

  // Node listen arg forms: (port), (port, cb), (port, host, cb),
  // (port, host, backlog, cb), (port, options, cb). Normalize by type so
  // the historical (port, callback)-only signature stopped dropping the
  // host string into the callback slot — listen(18143, '127.0.0.1', fn)
  // bound fine but fn never ran.
  Http2Server.prototype.listen = function(port) {
    var host = null, backlog, callback = null;
    for (var i = 1; i < arguments.length; i++) {
      var a = arguments[i];
      if (typeof a === 'function') {
        if (!callback) callback = a;
      } else if (typeof a === 'number') {
        if (backlog === undefined) backlog = a;
      } else if (typeof a === 'string') {
        if (host === null) host = a;
      }
    }
    this._port = port;
    this._host = host || '0.0.0.0';
    this.listening = true;
    // Delegate to native __http2_server_listen(serverObj, port, host, cb)
    if (typeof __http2_server_listen === 'function') {
      __http2_server_listen(this, port, this._host, callback);
    } else if (callback) {
      callback();
    }
    return this;
  };

  Http2Server.prototype.close = function(callback) {
    this.listening = false;
    // Delegate to native __http2_server_close
    if (typeof __http2_server_close === 'function') {
      __http2_server_close(this, callback);
    } else {
      if (callback) callback();
    }
    return this;
  };

  Http2Server.prototype.setTimeout = function(msecs, callback) {
    if (callback) callback();
    return this;
  };

  Http2Server.prototype.address = function() {
    return {
      port: this._listeningPort || this._port || 0,
      family: 'IPv4',
      address: this._host || '0.0.0.0'
    };
  };

  // ── SecureServer ────────────────────────────────────────────────────
  function Http2SecureServer(options, handler) {
    if (typeof options === 'function') {
      handler = options;
      options = {};
    }
    this._options = options || {};
    this._events = Object.create(null);
    this.listening = false;
    this._port = 0;
    // Compat handler split — see Http2Server.
    if (handler) this._onStreamHandler = handler;
  }
  Http2SecureServer.prototype = Object.create(null);
  Http2SecureServer.prototype.on = EE.prototype.on;
  Http2SecureServer.prototype.once = EE.prototype.once;
  Http2SecureServer.prototype.emit = EE.prototype.emit;
  Http2SecureServer.prototype.removeListener = EE.prototype.removeListener;
  Http2SecureServer.prototype.removeAllListeners = EE.prototype.removeAllListeners;
  Http2SecureServer.prototype.prependListener = EE.prototype.prependListener;

  Http2SecureServer.prototype.listen = function(port) {
    var host = null, backlog, callback = null;
    for (var i = 1; i < arguments.length; i++) {
      var a = arguments[i];
      if (typeof a === 'function') {
        if (!callback) callback = a;
      } else if (typeof a === 'number') {
        if (backlog === undefined) backlog = a;
      } else if (typeof a === 'string') {
        if (host === null) host = a;
      }
    }
    this._port = port;
    this._host = host || '0.0.0.0';
    this.listening = true;
    // Delegate to native __http2_secure_server_listen(serverObj, port, host, cb)
    if (typeof __http2_secure_server_listen === 'function') {
      __http2_secure_server_listen(this, port, this._host, callback);
    } else if (callback) {
      callback();
    }
    return this;
  };

  Http2SecureServer.prototype.close = function(callback) {
    this.listening = false;
    // Delegate to native __http2_secure_server_close
    if (typeof __http2_secure_server_close === 'function') {
      __http2_secure_server_close(this, callback);
    } else {
      if (callback) callback();
    }
    return this;
  };

  Http2SecureServer.prototype.setTimeout = function(msecs, callback) {
    if (callback) callback();
    return this;
  };

  Http2SecureServer.prototype.address = function() {
    return {
      port: this._listeningPort || this._port || 0,
      family: 'IPv4',
      address: this._host || '0.0.0.0'
    };
  };

  // ── createServer / createSecureServer ───────────────────────────────
  function createServer(options, handler) {
    return new Http2Server(options, handler);
  }

  function createSecureServer(options, handler) {
    return new Http2SecureServer(options, handler);
  }

  // ── Utility functions ───────────────────────────────────────────────
  function getDefaultSettings() {
    return {
      headerTableSize: 4096,
      enablePush: false,
      initialWindowSize: 65535,
      maxFrameSize: 16384,
      maxConcurrentStreams: 100,
      maxHeaderListSize: 65535,
      maxHeaderSize: 16384,
      enableConnectProtocol: false
    };
  }

  function getPackedSettings(settings) {
    // Returns a Buffer containing the serialized SETTINGS frame payload.
    // Each setting is 6 bytes: 2-byte identifier + 4-byte value.
    settings = settings || getDefaultSettings();
    var keys = [
      'headerTableSize',       // 0x01
      'enablePush',            // 0x02
      'maxConcurrentStreams',  // 0x03
      'initialWindowSize',     // 0x04
      'maxFrameSize',          // 0x05
      'maxHeaderListSize'      // 0x06
    ];
    var ids = [0x01, 0x02, 0x03, 0x04, 0x05, 0x06];
    var buf = Buffer.alloc(keys.length * 6);
    for (var i = 0; i < keys.length; i++) {
      var val = settings[keys[i]];
      if (typeof val === 'undefined') {
        var defaults = getDefaultSettings();
        val = defaults[keys[i]];
      }
      var offset = i * 6;
      buf[offset] = (ids[i] >> 8) & 0xff;
      buf[offset + 1] = ids[i] & 0xff;
      buf[offset + 2] = (val >> 24) & 0xff;
      buf[offset + 3] = (val >> 16) & 0xff;
      buf[offset + 4] = (val >> 8) & 0xff;
      buf[offset + 5] = val & 0xff;
    }
    return buf;
  }

  function getUnpackedSettings(buf) {
    // Parse a SETTINGS frame payload Buffer into a settings object.
    if (!buf || !buf.length) return getDefaultSettings();
    var settings = getDefaultSettings();
    var keys = [
      'headerTableSize',       // 0x01
      'enablePush',            // 0x02
      'maxConcurrentStreams',  // 0x03
      'initialWindowSize',     // 0x04
      'maxFrameSize',          // 0x05
      'maxHeaderListSize'      // 0x06
    ];
    var ids = [0x01, 0x02, 0x03, 0x04, 0x05, 0x06];
    for (var i = 0; i < Math.floor(buf.length / 6); i++) {
      var offset = i * 6;
      var id = (buf[offset] << 8) | buf[offset + 1];
      var val = (buf[offset + 2] << 24) | (buf[offset + 3] << 16) |
                (buf[offset + 4] << 8) | buf[offset + 5];
      // Convert signed to unsigned for values > 0x7FFFFFFF
      if (val < 0) val = val >>> 0;
      for (var j = 0; j < ids.length; j++) {
        if (ids[j] === id) {
          settings[keys[j]] = val;
          break;
        }
      }
    }
    return settings;
  }

  function sensitiveHeaders(headers) {
    // Mark headers as sensitive so they are never indexed in HPACK.
    // Returns the same headers object with a hidden _sensitive flag.
    if (headers && typeof headers === 'object') {
      Object.defineProperty(headers, '_sensitive', {
        value: true,
        enumerable: false,
        configurable: true
      });
    }
    return headers;
  }

  // ── Export ──────────────────────────────────────────────────────────
  return {
    connect: connect,
    createServer: createServer,
    createSecureServer: createSecureServer,
    Http2Session: Http2Session,
    Http2Stream: Http2Stream,
    Http2Server: Http2Server,
    Http2SecureServer: Http2SecureServer,
    getDefaultSettings: getDefaultSettings,
    getPackedSettings: getPackedSettings,
    getUnpackedSettings: getUnpackedSettings,
    sensitiveHeaders: sensitiveHeaders,
    // PerformanceEntry stubs
    performance: {
      timerify: function(fn) { return fn; },
      eventLoopUtilization: function() { return { idle: 0, active: 0, utilization: 0 }; }
    }
  };
})();
"#;

// ──────────────────────────────────────────────────────────────────────
// Install — register module on the JS global
// ──────────────────────────────────────────────────────────────────────

pub fn install(cx: &mut mozjs::context::JSContext) {
    rooted!(&in(cx) let http2_obj = unsafe { w2::JS_NewPlainObject(cx) });
    if http2_obj.get().is_null() {
        return;
    }

    unsafe {
        // ── Constants ──────────────────────────────────────────────────
        // HTTP/2 header pseudo-header constants
        define_int_prop(cx, http2_obj.get(), "HTTP2_HEADER_STATUS", 0x01);
        define_int_prop(cx, http2_obj.get(), "HTTP2_HEADER_METHOD", 0x02);
        define_int_prop(cx, http2_obj.get(), "HTTP2_HEADER_PATH", 0x04);
        define_int_prop(cx, http2_obj.get(), "HTTP2_HEADER_AUTHORITY", 0x08);
        define_int_prop(cx, http2_obj.get(), "HTTP2_HEADER_SCHEME", 0x10);
        define_int_prop(cx, http2_obj.get(), "HTTP2_HEADER_CONTENT_TYPE", 0x20);
        define_int_prop(cx, http2_obj.get(), "HTTP2_HEADER_CONTENT_LENGTH", 0x40);

        // Legacy aliases (Node.js compat)
        define_int_prop(cx, http2_obj.get(), "HEADER_STATUS", 0x01);
        define_int_prop(cx, http2_obj.get(), "HEADER_METHOD", 0x02);
        define_int_prop(cx, http2_obj.get(), "HEADER_PATH", 0x04);
        define_int_prop(cx, http2_obj.get(), "HEADER_AUTHORITY", 0x08);
        define_int_prop(cx, http2_obj.get(), "HEADER_SCHEME", 0x10);

        // nghttp2 error codes
        define_int_prop(cx, http2_obj.get(), "NGHTTP2_NO_ERROR", 0);
        define_int_prop(cx, http2_obj.get(), "NGHTTP2_PROTOCOL_ERROR", 1);
        define_int_prop(cx, http2_obj.get(), "NGHTTP2_INTERNAL_ERROR", 2);
        define_int_prop(cx, http2_obj.get(), "NGHTTP2_FLOW_CONTROL_ERROR", 3);
        define_int_prop(cx, http2_obj.get(), "NGHTTP2_SETTINGS_TIMEOUT", 4);
        define_int_prop(cx, http2_obj.get(), "NGHTTP2_STREAM_CLOSED", 5);
        define_int_prop(cx, http2_obj.get(), "NGHTTP2_FRAME_SIZE_ERROR", 6);
        define_int_prop(cx, http2_obj.get(), "NGHTTP2_REFUSED_STREAM", 7);
        define_int_prop(cx, http2_obj.get(), "NGHTTP2_CANCEL", 8);
        define_int_prop(cx, http2_obj.get(), "NGHTTP2_COMPRESSION_ERROR", 9);
        define_int_prop(cx, http2_obj.get(), "NGHTTP2_CONNECT_ERROR", 10);
        define_int_prop(cx, http2_obj.get(), "NGHTTP2_ENHANCE_YOUR_CALM", 11);
        define_int_prop(cx, http2_obj.get(), "NGHTTP2_INADEQUATE_SECURITY", 12);
        define_int_prop(cx, http2_obj.get(), "NGHTTP2_HTTP_1_1_REQUIRED", 13);

        // Default settings constants
        define_int_prop(
            cx,
            http2_obj.get(),
            "DEFAULT_SETTINGS_HEADER_TABLE_SIZE",
            4096,
        );
        define_int_prop(cx, http2_obj.get(), "DEFAULT_SETTINGS_ENABLE_PUSH", 0);
        define_int_prop(
            cx,
            http2_obj.get(),
            "DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE",
            65535,
        );
        define_int_prop(
            cx,
            http2_obj.get(),
            "DEFAULT_SETTINGS_MAX_FRAME_SIZE",
            16384,
        );
        define_int_prop(
            cx,
            http2_obj.get(),
            "DEFAULT_SETTINGS_MAX_CONCURRENT_STREAMS",
            100,
        );
        define_int_prop(
            cx,
            http2_obj.get(),
            "DEFAULT_SETTINGS_MAX_HEADER_LIST_SIZE",
            65535,
        );

        // Stream states
        define_int_prop(cx, http2_obj.get(), "NGHTTP2_STREAM_STATE_IDLE", 0);
        define_int_prop(cx, http2_obj.get(), "NGHTTP2_STREAM_STATE_OPEN", 1);
        define_int_prop(
            cx,
            http2_obj.get(),
            "NGHTTP2_STREAM_STATE_RESERVED_LOCAL",
            2,
        );
        define_int_prop(
            cx,
            http2_obj.get(),
            "NGHTTP2_STREAM_STATE_RESERVED_REMOTE",
            3,
        );
        define_int_prop(
            cx,
            http2_obj.get(),
            "NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL",
            4,
        );
        define_int_prop(
            cx,
            http2_obj.get(),
            "NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE",
            5,
        );
        define_int_prop(cx, http2_obj.get(), "NGHTTP2_STREAM_STATE_CLOSED", 6);

        // Frame types
        define_int_prop(cx, http2_obj.get(), "NGHTTP2_DATA", 0);
        define_int_prop(cx, http2_obj.get(), "NGHTTP2_HEADERS", 1);
        define_int_prop(cx, http2_obj.get(), "NGHTTP2_PRIORITY", 2);
        define_int_prop(cx, http2_obj.get(), "NGHTTP2_RST_STREAM", 3);
        define_int_prop(cx, http2_obj.get(), "NGHTTP2_SETTINGS", 4);
        define_int_prop(cx, http2_obj.get(), "NGHTTP2_PUSH_PROMISE", 5);
        define_int_prop(cx, http2_obj.get(), "NGHTTP2_PING", 6);
        define_int_prop(cx, http2_obj.get(), "NGHTTP2_GOAWAY", 7);
        define_int_prop(cx, http2_obj.get(), "NGHTTP2_WINDOW_UPDATE", 8);
        define_int_prop(cx, http2_obj.get(), "NGHTTP2_CONTINUATION", 9);

        // Flags
        define_int_prop(cx, http2_obj.get(), "NGHTTP2_FLAG_NONE", 0);
        define_int_prop(cx, http2_obj.get(), "NGHTTP2_FLAG_END_STREAM", 1);
        define_int_prop(cx, http2_obj.get(), "NGHTTP2_FLAG_END_HEADERS", 4);
        define_int_prop(cx, http2_obj.get(), "NGHTTP2_FLAG_ACK", 1);

        // ── Native functions ───────────────────────────────────────────
        // Server creation (delegates to JS Http2Server/Http2SecureServer
        // but also registers native uWS App for real HTTP serving)
        w2::JS_DefineFunction(
            cx,
            http2_obj.handle(),
            c"createServer".as_ptr(),
            Some(http2_create_server),
            2,
            JSPROP_ENUMERATE as u32,
        );
        w2::JS_DefineFunction(
            cx,
            http2_obj.handle(),
            c"createSecureServer".as_ptr(),
            Some(http2_create_secure_server),
            2,
            JSPROP_ENUMERATE as u32,
        );

        // Client fetch bridge
        w2::JS_DefineFunction(
            cx,
            http2_obj.handle(),
            c"__http2_fetch".as_ptr(),
            Some(http2_fetch),
            4,
            0 as u32,
        );

        // Server listen/close bridges (called from JS)
        w2::JS_DefineFunction(
            cx,
            http2_obj.handle(),
            c"__http2_server_listen".as_ptr(),
            Some(http2_server_listen),
            3,
            0 as u32,
        );
        w2::JS_DefineFunction(
            cx,
            http2_obj.handle(),
            c"__http2_server_close".as_ptr(),
            Some(http2_server_close),
            2,
            0 as u32,
        );
        w2::JS_DefineFunction(
            cx,
            http2_obj.handle(),
            c"__http2_secure_server_listen".as_ptr(),
            Some(http2_secure_server_listen),
            3,
            0 as u32,
        );
        w2::JS_DefineFunction(
            cx,
            http2_obj.handle(),
            c"__http2_secure_server_close".as_ptr(),
            Some(http2_secure_server_close),
            2,
            0 as u32,
        );

        // The JS IIFE resolves these host bridges as FREE variables — the
        // `typeof __http2_server_listen === 'function'` probes inside the
        // IIFE look at the GLOBAL, never at this module object. Defining
        // them only on http2_obj left every probe false: JS-side servers
        // fell back to a no-op listen and the client fetch bridge never
        // ran. Mirror them onto the global (non-enumerable, configurable)
        // so the IIFE sees them.
        rooted!(&in(cx) let global = CurrentGlobalOrNull(cx.raw_cx()));
        if !global.get().is_null() {
            let bridges: &[(&str, JSNative, u32)] = &[
                ("__http2_fetch", Some(http2_fetch), 4),
                ("__http2_server_listen", Some(http2_server_listen), 3),
                ("__http2_server_close", Some(http2_server_close), 2),
                (
                    "__http2_secure_server_listen",
                    Some(http2_secure_server_listen),
                    3,
                ),
                (
                    "__http2_secure_server_close",
                    Some(http2_secure_server_close),
                    2,
                ),
            ];
            for &(name, native, nargs) in bridges {
                let c_name = ZBox::from_bytes(name);
                w2::JS_DefineFunction(
                    cx,
                    global.handle(),
                    c_name.as_ptr(),
                    native,
                    nargs,
                    0 as u32,
                );
            }
        }

        // ── Evaluate JS IIFE ───────────────────────────────────────────
        let opts = mozjs::glue::NewCompileOptions(cx.raw_cx(), c"node:http2".as_ptr(), 1);
        if !opts.is_null() {
            let mut src_text = mozjs::rust::transform_str_to_source_text(HTTP2_JS);
            let mut rval = UndefinedValue();
            if JS::Evaluate2(
                cx.raw_cx(),
                opts,
                &mut src_text,
                MutableHandle::<Value> {
                    _phantom_0: ::std::marker::PhantomData,
                    ptr: &mut rval,
                },
            ) && rval.is_object()
            {
                // HTTP2_JS ends with `})();`, so Evaluate2's completion value
                // IS the exports object already — do NOT call it again. The
                // previous code re-invoked the exports object as a function
                // (TypeError, silently swallowed), which dropped the entire
                // JS API surface (connect / Http2Session / Http2Stream /
                // getDefaultSettings / ...) from the module:
                // require('http2').connect was undefined.
                rooted!(&in(cx) let exports = rval.to_object());
                // Copy JS-defined properties onto http2_obj
                let js_props = [
                    "connect",
                    "Http2Session",
                    "Http2Stream",
                    "Http2Server",
                    "Http2SecureServer",
                    "getDefaultSettings",
                    "getPackedSettings",
                    "getUnpackedSettings",
                    "sensitiveHeaders",
                    "performance",
                ];
                for &prop in &js_props {
                    let c_prop = ZBox::from_bytes(prop.as_bytes());
                    let mut prop_val = UndefinedValue();
                    JS_GetProperty(
                        cx.raw_cx(),
                        exports.handle().into(),
                        c_prop.as_ptr(),
                        MutableHandle::<Value> {
                            _phantom_0: ::std::marker::PhantomData,
                            ptr: &mut prop_val,
                        },
                    );
                    if !prop_val.is_undefined() {
                        rooted!(&in(cx) let pv = prop_val);
                        JS_DefineProperty(
                            cx.raw_cx(),
                            http2_obj.handle().into(),
                            c_prop.as_ptr(),
                            pv.handle().into(),
                            (JSPROP_ENUMERATE | JSPROP_PERMANENT) as u32,
                        );
                    }
                }
            }
            libc::free(opts as *mut _);
        }
    }

    cache_builtin(cx, "http2", http2_obj.get());
}

// ──────────────────────────────────────────────────────────────────────
// ServerUserData — GC-safe per-server state (same pattern as node_http)
// ──────────────────────────────────────────────────────────────────────

struct H2ServerUserData {
    cx: *mut JSContext,
    global_key: String,
    handler_key: String,
    server_key: String,
}

impl H2ServerUserData {
    fn new(
        cx: *mut JSContext,
        global: *mut JSObject,
        handler: *mut JSObject,
        server: *mut JSObject,
    ) -> Self {
        let server_id = NEXT_SERVER_ID.fetch_add(1, Ordering::Relaxed);
        let global_key = format!("http2_server_{}_global", server_id);
        let handler_key = format!("http2_server_{}_handler", server_id);
        let server_key = format!("http2_server_{}_server", server_id);
        gc_store_insert_ns(cx, "http2", &global_key, global);
        gc_store_insert_ns(cx, "http2", &handler_key, handler);
        gc_store_insert_ns(cx, "http2", &server_key, server);
        Self {
            cx,
            global_key,
            handler_key,
            server_key,
        }
    }

    fn global(&self) -> Option<*mut JSObject> {
        gc_store_get_ns(self.cx, "http2", &self.global_key)
    }

    fn handler(&self) -> Option<*mut JSObject> {
        gc_store_get_ns(self.cx, "http2", &self.handler_key)
    }

    fn server_obj(&self) -> Option<*mut JSObject> {
        gc_store_get_ns(self.cx, "http2", &self.server_key)
    }

    fn cleanup(&self) {
        gc_store_remove_ns(self.cx, "http2", &self.global_key);
        gc_store_remove_ns(self.cx, "http2", &self.handler_key);
        gc_store_remove_ns(self.cx, "http2", &self.server_key);
    }
}

// ──────────────────────────────────────────────────────────────────────
// Per-request state — GC-safe lifetime for async bodies/responses
// ──────────────────────────────────────────────────────────────────────
// uWS hands the route handler a `res` that stays valid past handler return
// ONLY under its async contract: attach onAborted (mandatory when not
// responding inline) and onData for body delivery. The JS req/res objects
// outlive the route-handler frame, so they are rooted in the GcStore under
// per-request keys and the uWS callbacks resolve them through this state.
//
// Ownership: the Box lives in H2_LIVE_REQUESTS keyed by id; every finish
// path (res.end, stream.end, fallback 500, body-end fallback, abort) calls
// h2_req_finish, which clears the uWS callbacks FIRST (so a freed state can
// never be dereferenced by a later on_data/on_aborted dispatch — uWS holds
// None after clear) and then drops the Box and its GcStore entries. The
// map-remove makes finish idempotent, which is what makes the reentrant
// case safe: res.end() invoked from inside a req 'data' listener frees the
// state mid-callback, and the pump's post-emit code touches only locals.

struct H2ReqState {
    cx: *mut JSContext,
    id: u64,
    req_key: String,
    res_key: String,
}

static NEXT_H2_REQ_ID: AtomicU64 = AtomicU64::new(1);

thread_local! {
    static H2_LIVE_REQUESTS: RefCell<::std::collections::HashMap<u64, Box<H2ReqState>>> =
        RefCell::new(::std::collections::HashMap::new());
}

/// Idempotent per-request teardown: detach uWS callbacks, drop the state Box
/// and its GcStore roots. `res` is None on the abort path (the connection is
/// dead; touching the res would be a use-after-close).
#[allow(unsafe_op_in_unsafe_fn)]
unsafe fn h2_req_finish(cx: *mut JSContext, id: u64, res: Option<&mut Response<false>>) {
    let state = H2_LIVE_REQUESTS.with(|m| m.borrow_mut().remove(&id));
    match state {
        Some(st) => {
            if let Some(r) = res {
                r.clear_on_data();
                r.clear_aborted();
            }
            gc_store_remove_ns(cx, "http2", &st.req_key);
            gc_store_remove_ns(cx, "http2", &st.res_key);
        }
        None => {}
    }
}

/// Explicit-500 crash-class guard (node:http 4c933019 pattern): a handler
/// that never responded must never fall through to uWS's
/// "Returning from a request handler without responding" std::terminate —
/// answer explicitly. If a status line is already on the wire, complete
/// that response instead of double-writing a status.
#[allow(unsafe_op_in_unsafe_fn)]
unsafe fn h2_respond_500(res: &mut Response<false>, msg: &[u8]) {
    if res.state().is_http_status_called() {
        res.end(&[], true);
        return;
    }
    res.write_status(b"500 Internal Server Error");
    res.write_header(b"Content-Type", b"text/plain");
    res.end(msg, true);
}

/// Emit `event` (with one optional arg) on a JS object through its `emit`
/// method (the native node_events EE — emit reads `this`, so the receiver is
/// the object itself). Returns the EE's had-listeners boolean. Caller must be
/// inside the realm. Pending exceptions from listeners are cleared — a
/// throwing listener must not kill the pump.
#[allow(unsafe_op_in_unsafe_fn)]
unsafe fn h2_emit_event(
    cx: *mut JSContext,
    obj: *mut JSObject,
    event: &str,
    arg: Option<JSVal>,
) -> bool {
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;
    rooted!(&in(cx_ref) let obj_root = obj);

    let mut emit_val = UndefinedValue();
    JS_GetProperty(
        cx,
        obj_root.handle().into(),
        c"emit".as_ptr(),
        MutableHandle::<Value> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut emit_val,
        },
    );
    if !emit_val.is_object() {
        return false;
    }

    let c_event = ZBox::from_bytes(event.as_bytes());
    let event_str = JS_NewStringCopyZ(cx, c_event.as_ptr());
    if event_str.is_null() {
        return false;
    }

    let ev_val = StringValue(&*event_str);
    rooted!(&in(cx_ref) let ev_root = ev_val);
    rooted!(&in(cx_ref) let arg_root = arg.unwrap_or_else(UndefinedValue));

    let args_vals = [ev_root.get(), arg_root.get()];
    let call_args = HandleValueArray {
        length_: 2,
        elements_: args_vals.as_ptr(),
    };

    rooted!(&in(cx_ref) let emit_fn = emit_val.to_object());
    let emit_fn_val = ObjectValue(emit_fn.get());
    rooted!(&in(cx_ref) let emit_fn_root = emit_fn_val);

    let mut rval = UndefinedValue();
    let rval_h = MutableHandle::<Value> {
        _phantom_0: ::std::marker::PhantomData,
        ptr: &mut rval,
    };
    let ok = JS_CallFunctionValue(
        cx,
        obj_root.handle().into(),
        emit_fn_root.handle().into(),
        &call_args,
        rval_h,
    );
    if !ok {
        JS_ClearPendingException(cx);
        return false;
    }
    rval.is_boolean() && rval.to_boolean()
}

/// Read a boolean property off a JS object (missing → false).
#[allow(unsafe_op_in_unsafe_fn)]
unsafe fn h2_get_bool_prop(cx: *mut JSContext, obj: *mut JSObject, name: &str) -> bool {
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;
    rooted!(&in(cx_ref) let obj_root = obj);
    let mut v = UndefinedValue();
    let c_name = ZBox::from_bytes(name.as_bytes());
    JS_GetProperty(
        cx,
        obj_root.handle().into(),
        c_name.as_ptr(),
        MutableHandle::<Value> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut v,
        },
    );
    v.is_boolean() && v.to_boolean()
}

/// Set a boolean property on a JS object.
#[allow(unsafe_op_in_unsafe_fn)]
unsafe fn h2_set_bool_prop(cx: *mut JSContext, obj: *mut JSObject, name: &str, val: bool) {
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;
    rooted!(&in(cx_ref) let obj_root = obj);
    rooted!(&in(cx_ref) let v = mozjs::jsval::BooleanValue(val));
    let c_name = ZBox::from_bytes(name.as_bytes());
    JS_SetProperty(cx, obj_root.handle().into(), c_name.as_ptr(), v.handle().into());
}

/// Append one response-body chunk to the res object's `_bodyChunks` array,
/// byte-exactly (same contract as node_http::res_append_chunk): strings are
/// stored as JS strings, byte views as fresh Uint8Array parts. Anything
/// else is a TypeError — never a silent drop.
#[allow(unsafe_op_in_unsafe_fn)]
unsafe fn h2_res_append_chunk(cx: *mut JSContext, obj: *mut JSObject, v: JSVal) -> bool {
    if v.is_undefined() || v.is_null() {
        return true;
    }
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;
    rooted!(&in(cx_ref) let obj_root = obj);

    let part_val: Value = if v.is_string() {
        v
    } else if let Some(bytes) = crate::node_buffer::collect_byte_view(cx, v) {
        let ta = crate::globals::create_buffer_object(cx, &bytes);
        if ta.is_null() {
            return false;
        }
        ObjectValue(ta)
    } else {
        JS_ReportErrorUTF8(
            cx,
            c"%s".as_ptr(),
            c"http2: stream chunk must be a string, Buffer, TypedArray or ArrayBuffer".as_ptr(),
        );
        return false;
    };
    rooted!(&in(cx_ref) let part_root = part_val);

    // Ensure `_bodyChunks` array exists.
    let mut chunks_val = UndefinedValue();
    JS_GetProperty(
        cx,
        obj_root.handle().into(),
        c"_bodyChunks".as_ptr(),
        MutableHandle::<Value> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut chunks_val,
        },
    );
    if !chunks_val.is_object() {
        rooted!(&in(cx_ref) let arr = w2::NewArrayObject1(cx_ref, 0));
        if arr.get().is_null() {
            return false;
        }
        rooted!(&in(cx_ref) let arr_val = ObjectValue(arr.get()));
        JS_SetProperty(
            cx,
            obj_root.handle().into(),
            c"_bodyChunks".as_ptr(),
            arr_val.handle().into(),
        );
        chunks_val = arr_val.get();
    }
    rooted!(&in(cx_ref) let chunks_obj = chunks_val.to_object());

    let mut len_val = UndefinedValue();
    JS_GetProperty(
        cx,
        chunks_obj.handle().into(),
        c"length".as_ptr(),
        MutableHandle::<Value> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut len_val,
        },
    );
    let next_index: u32 = if len_val.is_int32() {
        len_val.to_int32().max(0) as u32
    } else {
        0
    };
    JS_DefineElement(
        cx,
        chunks_obj.handle().into(),
        next_index,
        part_root.handle().into(),
        JSPROP_ENUMERATE as u32,
    );
    true
}

/// Concatenate `_bodyChunks` into the exact wire bytes (strings encode
/// UTF-8, Uint8Array parts copy verbatim).
#[allow(unsafe_op_in_unsafe_fn)]
unsafe fn h2_res_collect_body(cx: *mut JSContext, obj: *mut JSObject) -> Vec<u8> {
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;
    rooted!(&in(cx_ref) let obj_root = obj);

    let mut chunks_val = UndefinedValue();
    JS_GetProperty(
        cx,
        obj_root.handle().into(),
        c"_bodyChunks".as_ptr(),
        MutableHandle::<Value> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut chunks_val,
        },
    );
    if !chunks_val.is_object() {
        return Vec::new();
    }
    rooted!(&in(cx_ref) let chunks_obj = chunks_val.to_object());

    let mut len_val = UndefinedValue();
    JS_GetProperty(
        cx,
        chunks_obj.handle().into(),
        c"length".as_ptr(),
        MutableHandle::<Value> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut len_val,
        },
    );
    let count: u32 = if len_val.is_int32() {
        len_val.to_int32().max(0) as u32
    } else {
        0
    };

    let mut out: Vec<u8> = Vec::new();
    for i in 0..count {
        let mut elem = UndefinedValue();
        if !JS_GetElement(
            cx,
            chunks_obj.handle().into(),
            i,
            MutableHandle::<Value> {
                _phantom_0: ::std::marker::PhantomData,
                ptr: &mut elem,
            },
        ) {
            break;
        }
        if elem.is_string() {
            out.extend_from_slice(crate::js_to_rust_string(cx, elem).as_bytes());
        } else if elem.is_object() {
            match crate::node_buffer::collect_byte_view(cx, elem) {
                Some(bytes) => out.extend_from_slice(&bytes),
                None => eprintln!("[node:http2] response body chunk {} was not extractable", i),
            }
        }
    }
    out
}

/// Write every own string-keyed property of the headers object as a response
/// header (names lowercased for uWS; ':' pseudo-headers skipped). Iterates
/// ALL keys via IdVector — the fixed common-header list silently dropped
/// every other header a handler sent.
#[allow(unsafe_op_in_unsafe_fn)]
unsafe fn h2_write_headers_obj(
    cx: *mut JSContext,
    hdrs: *mut JSObject,
    res_mut: &mut Response<false>,
) {
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;
    rooted!(&in(cx_ref) let hdrs_obj = hdrs);
    let mut ids = mozjs::rust::IdVector::new(cx);
    if !w2::GetPropertyKeys(
        cx_ref,
        hdrs_obj.handle().into(),
        JSITER_OWNONLY as u32,
        ids.handle_mut(),
    ) {
        return;
    }
    for jsid in &*ids {
        if !jsid.is_string() {
            continue;
        }
        let key_str = jsid.to_string();
        let key = mozjs::conversions::unsafe_jsstr_to_string(
            cx,
            NonNull::new_unchecked(key_str),
        );
        if key.starts_with(':') {
            continue;
        }
        let c_key = ZBox::from_bytes(key.as_bytes());
        let mut hv = UndefinedValue();
        JS_GetProperty(
            cx,
            hdrs_obj.handle().into(),
            c_key.as_ptr(),
            MutableHandle::<Value> {
                _phantom_0: ::std::marker::PhantomData,
                ptr: &mut hv,
            },
        );
        if hv.is_string() {
            let val = crate::js_to_rust_string(cx, hv);
            let key_lower = key.to_ascii_lowercase();
            let c_val = ZBox::from_bytes(val.as_bytes());
            (*res_mut).write_header(key_lower.as_bytes(), c_val.as_bytes());
        }
    }
}

// ──────────────────────────────────────────────────────────────────────
// uWS route handler — bridges C++ HTTP events to JS Http2Stream
// ──────────────────────────────────────────────────────────────────────

#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn uws_h2_route_handler(
    res: *mut bun_uws_sys::response::c::uws_res,
    req: *mut bun_uws_sys::Request,
    user_data: *mut ::std::ffi::c_void,
) {
    if res.is_null() || req.is_null() || user_data.is_null() {
        return;
    }

    let ud = &*(user_data as *const H2ServerUserData);
    let cx = ud.cx;
    if cx.is_null() {
        return;
    }

    let raw_cx = cx;
    let res_mut = Response::<false>::cast_res(res);

    // Enter the context's persistent realm before any JS resolution (same
    // rationale as node_http::uws_route_handler): async dispatch runs with no
    // realm entered, and the GcStore properties backing ud.global()/handler()
    // live on this realm's global — without the AutoRealm the lookups fail
    // and the handler silently never runs (uWS then std::terminates on the
    // unanswered request). First-principles realm model: one realm per
    // JsContext, held for the context's lifetime.
    let realm_global = match bao_engine::context::thread_realm_global() {
        Some(g) if !g.is_null() => g,
        _ => {
            // No realm on this thread → no JS server should exist here.
            // Explicit 500 (never a silent return → uWS std::terminate).
            eprintln!("[node:http2] no JS realm on this thread — responding 500");
            (*res_mut).write_status(b"500 Internal Server Error");
            (*res_mut).write_header(b"Content-Type", b"text/plain");
            (*res_mut).end(b"no JS realm", true);
            return;
        }
    };

    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;
    rooted!(&in(cx_ref) let realm_global_root = realm_global);
    let mut realm = mozjs::realm::AutoRealm::new_from_handle(cx_ref, realm_global_root.handle());
    let cx_ref: &mut mozjs::context::JSContext = &mut realm;

    // Now inside the realm: CurrentGlobalOrNull = persistent global, so the
    // GcStore lookups resolve the registered server global and stream handler.
    let Some(global) = ud.global() else {
        eprintln!(
            "[node:http2] server global unavailable (key {}) — responding 500",
            ud.global_key
        );
        (*res_mut).write_status(b"500 Internal Server Error");
        (*res_mut).write_header(b"Content-Type", b"text/plain");
        (*res_mut).end(b"no server global", true);
        return;
    };
    if global.is_null() {
        eprintln!("[node:http2] server global null — responding 500");
        (*res_mut).write_status(b"500 Internal Server Error");
        (*res_mut).write_header(b"Content-Type", b"text/plain");
        (*res_mut).end(b"no server global", true);
        return;
    }

    let Some(handler) = ud.handler() else {
        // Registered-but-unresolvable handler must fail explicitly — never a
        // silent return (crash) and never a fake response.
        eprintln!(
            "[node:http2] stream handler unavailable (key {}) — responding 500",
            ud.handler_key
        );
        (*res_mut).write_status(b"500 Internal Server Error");
        (*res_mut).write_header(b"Content-Type", b"text/plain");
        (*res_mut).end(b"no stream handler", true);
        return;
    };
    if handler.is_null() {
        eprintln!("[node:http2] stream handler null — responding 500");
        (*res_mut).write_status(b"500 Internal Server Error");
        (*res_mut).write_header(b"Content-Type", b"text/plain");
        (*res_mut).end(b"no stream handler", true);
        return;
    }

    let req_ref = bun_opaque::opaque_deref_mut(req);
    let method_bytes = req_ref.method();
    let url_bytes = req_ref.url();
    // uWS stores the method token lowercased internally; Node's req.method
    // carries the client-sent uppercase token (same restore as node_http).
    let method_upper = method_bytes.to_ascii_uppercase();
    let method_str = ::std::str::from_utf8_unchecked(&method_upper);
    let url_str = ::std::str::from_utf8_unchecked(url_bytes);

    // Body detection drives the uWS async contract: a request WITH a body
    // keeps the Response alive past handler return (the onData pump delivers
    // 'data'/'end' and enforces respond-or-500 at body end); a bodyless
    // request must be fully decided by the handler's return.
    let has_body = {
        let content_length = req_ref
            .header(b"content-length")
            .and_then(|v| ::std::str::from_utf8(v).ok())
            .and_then(|v| v.trim().parse::<usize>().ok())
            .unwrap_or(0);
        let chunked = req_ref.header(b"transfer-encoding").is_some();
        content_length > 0 || chunked
    };

    // Union stream/request object. arg1 of the compat handler is node's
    // Http2ServerRequest AND carries the session-style Http2Stream method
    // surface (respond/end/close + ':method'/':path') — http_te_parity pins
    // createServer handlers written against the session shape, and node's
    // Http2ServerRequest is itself a stream (req.stream === this surface).
    rooted!(&in(cx_ref) let stream_obj = w2::JS_NewPlainObject(cx_ref));
    if stream_obj.get().is_null() {
        eprintln!("[node:http2] stream object allocation failed — responding 500");
        h2_respond_500(&mut *res_mut, b"stream allocation failed");
        return;
    }

    // Session-shape pseudo-header properties.
    {
        let c_method = ZBox::from_bytes(method_str.as_bytes());
        let js_method = JS_NewStringCopyZ(raw_cx, c_method.as_ptr());
        if !js_method.is_null() {
            let mv = StringValue(&*js_method);
            rooted!(&in(cx_ref) let mvr = mv);
            JS_DefineProperty(
                raw_cx,
                stream_obj.handle().into(),
                c":method".as_ptr(),
                mvr.handle().into(),
                JSPROP_ENUMERATE as u32,
            );
        }
    }
    {
        let c_path = ZBox::from_bytes(url_str.as_bytes());
        let js_path = JS_NewStringCopyZ(raw_cx, c_path.as_ptr());
        if !js_path.is_null() {
            let pv = StringValue(&*js_path);
            rooted!(&in(cx_ref) let pvr = pv);
            JS_DefineProperty(
                raw_cx,
                stream_obj.handle().into(),
                c":path".as_ptr(),
                pvr.handle().into(),
                JSPROP_ENUMERATE as u32,
            );
        }
    }

    // Compat request properties (method/url/httpVersion/stream).
    {
        let c_method = ZBox::from_bytes(method_str.as_bytes());
        let js_method = JS_NewStringCopyZ(raw_cx, c_method.as_ptr());
        if !js_method.is_null() {
            let mv = StringValue(&*js_method);
            rooted!(&in(cx_ref) let mvr = mv);
            JS_DefineProperty(
                raw_cx,
                stream_obj.handle().into(),
                c"method".as_ptr(),
                mvr.handle().into(),
                JSPROP_ENUMERATE as u32,
            );
        }
    }
    {
        let c_url = ZBox::from_bytes(url_str.as_bytes());
        let js_url = JS_NewStringCopyZ(raw_cx, c_url.as_ptr());
        if !js_url.is_null() {
            let uv = StringValue(&*js_url);
            rooted!(&in(cx_ref) let uvr = uv);
            JS_DefineProperty(
                raw_cx,
                stream_obj.handle().into(),
                c"url".as_ptr(),
                uvr.handle().into(),
                JSPROP_ENUMERATE as u32,
            );
        }
    }
    {
        let js_ver = JS_NewStringCopyZ(raw_cx, c"2.0".as_ptr());
        if !js_ver.is_null() {
            let vv = StringValue(&*js_ver);
            rooted!(&in(cx_ref) let vvr = vv);
            JS_DefineProperty(
                raw_cx,
                stream_obj.handle().into(),
                c"httpVersion".as_ptr(),
                vvr.handle().into(),
                JSPROP_ENUMERATE as u32,
            );
        }
    }
    {
        let sv = ObjectValue(stream_obj.get());
        rooted!(&in(cx_ref) let svr = sv);
        JS_DefineProperty(
            raw_cx,
            stream_obj.handle().into(),
            c"stream".as_ptr(),
            svr.handle().into(),
            JSPROP_ENUMERATE as u32,
        );
    }

    // Headers: ALL request headers via for_each_header — the previous fixed
    // common-name list silently dropped every other header the client sent.
    // (HTTP/1.x wire path: no ':authority'/':scheme' pseudo-headers exist,
    // so none are synthesized.)
    rooted!(&in(cx_ref) let headers_obj = w2::JS_NewPlainObject(cx_ref));
    if !headers_obj.get().is_null() {
        let mut header_pairs: Vec<(Vec<u8>, Vec<u8>)> = Vec::new();
        req_ref.for_each_header(
            |pairs: &mut Vec<(Vec<u8>, Vec<u8>)>, name: &[u8], value: &[u8]| {
                pairs.push((name.to_vec(), value.to_vec()));
            },
            &mut header_pairs as *mut Vec<(Vec<u8>, Vec<u8>)>,
        );
        for (name, value) in &header_pairs {
            let c_k = ZBox::from_bytes(name);
            let c_v = ZBox::from_bytes(value);
            let js_v = JS_NewStringCopyZ(raw_cx, c_v.as_ptr());
            if !js_v.is_null() {
                let hv = StringValue(&*js_v);
                rooted!(&in(cx_ref) let hvr = hv);
                JS_DefineProperty(
                    raw_cx,
                    headers_obj.handle().into(),
                    c_k.as_ptr(),
                    hvr.handle().into(),
                    JSPROP_ENUMERATE as u32,
                );
            }
        }
        let hdrs_val = ObjectValue(headers_obj.get());
        rooted!(&in(cx_ref) let hdrs_r = hdrs_val);
        JS_DefineProperty(
            raw_cx,
            stream_obj.handle().into(),
            c"headers".as_ptr(),
            hdrs_r.handle().into(),
            JSPROP_ENUMERATE as u32,
        );
    }

    // Session-shape method surface (respond/end/close).
    w2::JS_DefineFunction(
        cx_ref,
        stream_obj.handle(),
        c"respond".as_ptr(),
        Some(h2_stream_respond),
        2,
        JSPROP_ENUMERATE as u32,
    );
    w2::JS_DefineFunction(
        cx_ref,
        stream_obj.handle(),
        c"end".as_ptr(),
        Some(h2_stream_end),
        1,
        JSPROP_ENUMERATE as u32,
    );
    w2::JS_DefineFunction(
        cx_ref,
        stream_obj.handle(),
        c"close".as_ptr(),
        Some(h2_stream_close),
        0,
        JSPROP_ENUMERATE as u32,
    );

    // EE surface for the request side: 'data'/'end'/'aborted' listeners
    // (node_events natives — the same EE the pump emits through).
    attach_ee_methods(raw_cx, stream_obj.get());

    // Store uWS res pointer on the stream object
    let res_ptr_val = PrivateValue(res as *const core::ffi::c_void);
    rooted!(&in(cx_ref) let rv = res_ptr_val);
    JS_DefineProperty(
        raw_cx,
        stream_obj.handle().into(),
        c"_uwsRes".as_ptr(),
        rv.handle().into(),
        0,
    );

    // Compat response object: writeHead/setHeader/write/end bridging to the
    // uWS Response (node's Http2ServerResponse surface).
    rooted!(&in(cx_ref) let res_obj = w2::JS_NewPlainObject(cx_ref));
    if res_obj.get().is_null() {
        eprintln!("[node:http2] response object allocation failed — responding 500");
        h2_respond_500(&mut *res_mut, b"response allocation failed");
        return;
    }
    let res_methods: &[(&str, u32, unsafe extern "C" fn(*mut JSContext, u32, *mut JSVal) -> bool)] = &[
        ("writeHead", 2, h2_res_write_head),
        ("setHeader", 2, h2_res_set_header),
        ("getHeader", 1, h2_res_get_header),
        ("getHeaders", 0, h2_res_get_headers),
        ("hasHeader", 1, h2_res_has_header),
        ("removeHeader", 1, h2_res_remove_header),
        ("write", 1, h2_res_write),
        ("end", 1, h2_res_end),
        ("setTimeout", 2, h2_res_set_timeout),
    ];
    for (name, nargs, op) in res_methods {
        let c_name = ZBox::from_bytes(name.as_bytes());
        w2::JS_DefineFunction(
            cx_ref,
            res_obj.handle(),
            c_name.as_ptr(),
            Some(*op),
            *nargs,
            JSPROP_ENUMERATE as u32,
        );
    }
    {
        rooted!(&in(cx_ref) let sv = Int32Value(200));
        JS_DefineProperty(
            raw_cx,
            res_obj.handle().into(),
            c"statusCode".as_ptr(),
            sv.handle().into(),
            JSPROP_ENUMERATE as u32,
        );
    }
    {
        rooted!(&in(cx_ref) let hdrs_plain = w2::JS_NewPlainObject(cx_ref));
        rooted!(&in(cx_ref) let hv = ObjectValue(hdrs_plain.get()));
        JS_DefineProperty(
            raw_cx,
            res_obj.handle().into(),
            c"_headers".as_ptr(),
            hv.handle().into(),
            0,
        );
    }
    attach_ee_methods(raw_cx, res_obj.get());
    JS_DefineProperty(
        raw_cx,
        res_obj.handle().into(),
        c"_uwsRes".as_ptr(),
        rv.handle().into(),
        0,
    );

    // Per-request state: root the stream/res objects in the GcStore and
    // register the uWS async contract (onAborted mandatory, onData = body
    // pump) so the response may legally complete after this frame returns.
    let req_id = NEXT_H2_REQ_ID.fetch_add(1, Ordering::Relaxed);
    let req_key = format!("http2_req_{}_stream", req_id);
    let res_key = format!("http2_req_{}_res", req_id);
    gc_store_insert_ns(raw_cx, "http2", &req_key, stream_obj.get());
    gc_store_insert_ns(raw_cx, "http2", &res_key, res_obj.get());
    {
        rooted!(&in(cx_ref) let idv = Int32Value(req_id as i32));
        JS_DefineProperty(
            raw_cx,
            stream_obj.handle().into(),
            c"_stateId".as_ptr(),
            idv.handle().into(),
            0,
        );
        JS_DefineProperty(
            raw_cx,
            res_obj.handle().into(),
            c"_stateId".as_ptr(),
            idv.handle().into(),
            0,
        );
    }
    H2_LIVE_REQUESTS.with(|m| {
        m.borrow_mut().insert(
            req_id,
            Box::new(H2ReqState {
                cx: raw_cx,
                id: req_id,
                req_key: req_key.clone(),
                res_key: res_key.clone(),
            }),
        );
    });
    let state_ptr = H2_LIVE_REQUESTS.with(|m| {
        m.borrow()
            .get(&req_id)
            .map(|b| b.as_ref() as *const H2ReqState as *mut H2ReqState)
    });
    if let Some(state_ptr) = state_ptr {
        (*res_mut).on_aborted(
            |st: *mut H2ReqState, _res: &mut Response<false>| h2_on_aborted(st),
            state_ptr,
        );
        (*res_mut).on_data(
            |st: *mut H2ReqState, res: &mut Response<false>, chunk: &[u8], last: bool| {
                h2_on_data(st, res, chunk, last)
            },
            state_ptr,
        );
    }

    // Compat dispatch: handler(stream, res) — arg1 doubles as the session
    // stream (union object above).
    rooted!(&in(cx_ref) let handler_root = ObjectValue(handler));
    rooted!(&in(cx_ref) let global_root = global);

    let args_vals = [
        ObjectValue(stream_obj.get()),
        ObjectValue(res_obj.get()),
    ];
    let call_args = HandleValueArray {
        length_: 2,
        elements_: args_vals.as_ptr(),
    };

    let mut rval = UndefinedValue();
    let rval_h = MutableHandle::<Value> {
        _phantom_0: ::std::marker::PhantomData,
        ptr: &mut rval,
    };
    let ok = JS_CallFunctionValue(
        raw_cx,
        global_root.handle().into(),
        handler_root.handle().into(),
        &call_args,
        rval_h,
    );
    if !ok {
        // Handler threw — explicit 500 (never silent terminate; the uWS
        // unanswered-request path is std::terminate → mozalloc_abort).
        JS_ClearPendingException(raw_cx);
        eprintln!("[node:http2] request handler threw — responding 500");
        if !(*res_mut).state().is_http_end_called() {
            h2_respond_500(&mut *res_mut, b"request handler threw");
        }
        h2_req_finish(raw_cx, req_id, Some(&mut *res_mut));
        return;
    }

    // Session-style 'stream' event on the server object (node forwards the
    // session stream event alongside the compat handler; the compat handler
    // is NOT registered on 'stream', so no double dispatch).
    if let Some(server_obj) = ud.server_obj() {
        if !server_obj.is_null() {
            h2_emit_server_stream(raw_cx, server_obj, stream_obj.get(), headers_obj.get());
        }
    }

    // Post-dispatch decision. Response already complete → res.end finished
    // the state itself. With a body, the onData pump owns the
    // respond-or-500 deadline. Bodyless requests are decided now: deliver a
    // synthetic 'end' (CL:0 handlers), then enforce respond-or-500.
    if (*res_mut).state().is_http_end_called() {
        return;
    }
    if has_body {
        return;
    }
    h2_set_bool_prop(raw_cx, stream_obj.get(), "_bodyEnded", true);
    h2_emit_event(raw_cx, stream_obj.get(), "end", None);
    if !(*res_mut).state().is_http_end_called() {
        eprintln!("[node:http2] request handler returned without responding — responding 500");
        h2_respond_500(&mut *res_mut, b"handler did not respond");
    }
    h2_req_finish(raw_cx, req_id, Some(&mut *res_mut));
}

/// onData pump: forward request-body chunks to the JS stream's 'data'
/// listeners and 'end' at the final chunk, then enforce respond-or-500.
#[allow(unsafe_op_in_unsafe_fn)]
unsafe fn h2_on_data(
    st: *mut H2ReqState,
    res: &mut Response<false>,
    chunk: &[u8],
    last: bool,
) {
    // Copy everything the post-emit code needs BEFORE any JS call — a
    // reentrant res.end() inside a 'data' listener finishes (and frees) the
    // state mid-callback; after the emit only these locals and the callback
    // param `res` may be touched.
    let cx = (*st).cx;
    let id = (*st).id;
    let req_key = (*st).req_key.clone();

    // Realm entry (same rationale as the route handler: pump dispatch runs
    // with no realm entered, GcStore lookups need the realm's global).
    let realm_global = match bao_engine::context::thread_realm_global() {
        Some(g) if !g.is_null() => g,
        _ => return,
    };
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;
    rooted!(&in(cx_ref) let realm_global_root = realm_global);
    let mut realm = mozjs::realm::AutoRealm::new_from_handle(cx_ref, realm_global_root.handle());
    let _cx_ref: &mut mozjs::context::JSContext = &mut realm;

    let stream_obj = match gc_store_get_ns(cx, "http2", &req_key) {
        Some(o) if !o.is_null() => o,
        _ => return,
    };

    // Synthetic-end guard: a bodyless request already got 'end' inline (and
    // the route handler finished the state).
    if h2_get_bool_prop(cx, stream_obj, "_bodyEnded") {
        return;
    }

    if !chunk.is_empty() {
        let chunk_val = crate::bun_api::bytes_to_js_uint8array(cx, chunk);
        if !chunk_val.is_undefined() {
            h2_emit_event(cx, stream_obj, "data", Some(chunk_val));
        }
    }
    if !last {
        return;
    }
    h2_set_bool_prop(cx, stream_obj, "_bodyEnded", true);
    h2_emit_event(cx, stream_obj, "end", None);
    // Body fully delivered and the handler still has not responded —
    // explicit 500 (never fall through to uWS std::terminate).
    if !res.state().is_http_end_called() {
        eprintln!("[node:http2] request handler returned without responding — responding 500");
        h2_respond_500(res, b"handler did not respond");
        h2_req_finish(cx, id, Some(res));
    }
}

/// onAborted: the connection died before the response completed. Mark the
/// JS objects dead (late write/end calls become no-ops instead of hitting a
/// dead uWS res), notify listeners, drop the per-request state.
#[allow(unsafe_op_in_unsafe_fn)]
unsafe fn h2_on_aborted(st: *mut H2ReqState) {
    // Copy locals first — no reentrancy concerns here, but the state is
    // freed below and must not be touched after.
    let cx = (*st).cx;
    let id = (*st).id;
    let req_key = (*st).req_key.clone();
    let res_key = (*st).res_key.clone();

    let realm_global = bao_engine::context::thread_realm_global().unwrap_or(core::ptr::null_mut());
    if !realm_global.is_null() {
        let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
        let cx_ref = &mut wrapped_cx;
        rooted!(&in(cx_ref) let realm_global_root = realm_global);
        let mut realm = mozjs::realm::AutoRealm::new_from_handle(cx_ref, realm_global_root.handle());
        let _cx_ref: &mut mozjs::context::JSContext = &mut realm;

        if let Some(res_obj) = gc_store_get_ns(cx, "http2", &res_key) {
            if !res_obj.is_null() {
                h2_set_bool_prop(cx, res_obj, "_ended", true);
                h2_emit_event(cx, res_obj, "close", None);
            }
        }
        if let Some(stream_obj) = gc_store_get_ns(cx, "http2", &req_key) {
            if !stream_obj.is_null() {
                h2_emit_event(cx, stream_obj, "aborted", None);
            }
        }
    }

    // The res is dead — do NOT touch it. Drop the state and its roots.
    let state = H2_LIVE_REQUESTS.with(|m| m.borrow_mut().remove(&id));
    drop(state);
    gc_store_remove_ns(cx, "http2", &req_key);
    gc_store_remove_ns(cx, "http2", &res_key);
}

/// Emit the session-style 'stream' event on the server object:
/// server.emit('stream', stream, headers, 0) — node's (stream, headers,
/// flags) listener shape.
#[allow(unsafe_op_in_unsafe_fn)]
unsafe fn h2_emit_server_stream(
    cx: *mut JSContext,
    server_obj: *mut JSObject,
    stream_obj: *mut JSObject,
    headers_obj: *mut JSObject,
) {
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;
    rooted!(&in(cx_ref) let server_root = server_obj);

    let mut emit_val = UndefinedValue();
    JS_GetProperty(
        cx,
        server_root.handle().into(),
        c"emit".as_ptr(),
        MutableHandle::<Value> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut emit_val,
        },
    );
    if !emit_val.is_object() {
        return;
    }

    let ev_str = JS_NewStringCopyZ(cx, c"stream".as_ptr());
    if ev_str.is_null() {
        return;
    }
    let ev_val = StringValue(&*ev_str);
    rooted!(&in(cx_ref) let ev_root = ev_val);
    rooted!(&in(cx_ref) let s_root = ObjectValue(stream_obj));
    rooted!(&in(cx_ref) let h_root = ObjectValue(headers_obj));
    rooted!(&in(cx_ref) let f_root = Int32Value(0));

    let args_vals = [ev_root.get(), s_root.get(), h_root.get(), f_root.get()];
    let call_args = HandleValueArray {
        length_: 4,
        elements_: args_vals.as_ptr(),
    };

    rooted!(&in(cx_ref) let emit_fn = emit_val.to_object());
    rooted!(&in(cx_ref) let emit_fn_root = ObjectValue(emit_fn.get()));
    let mut rval = UndefinedValue();
    let ok = JS_CallFunctionValue(
        cx,
        server_root.handle().into(),
        emit_fn_root.handle().into(),
        &call_args,
        MutableHandle::<Value> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut rval,
        },
    );
    if !ok {
        JS_ClearPendingException(cx);
        eprintln!("[node:http2] server 'stream' listener threw (cleared)");
    }
}

// ──────────────────────────────────────────────────────────────────────
// JS stream methods — bridge to uWS Response::<false>
// ──────────────────────────────────────────────────────────────────────

#[inline]
fn val_is_private(v: &JSVal) -> bool {
    v.is_double() && (v.asBits_ & 0xFFFF000000000000) == 0
}

#[inline]
unsafe fn get_uws_res(
    cx: *mut JSContext,
    obj: *mut JSObject,
) -> *mut bun_uws_sys::response::c::uws_res {
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;
    rooted!(&in(cx_ref) let obj_root = obj);
    let mut ptr_val = UndefinedValue();
    JS_GetProperty(
        cx,
        obj_root.handle().into(),
        c"_uwsRes".as_ptr(),
        MutableHandle::<Value> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut ptr_val,
        },
    );
    if !val_is_private(&ptr_val) {
        return core::ptr::null_mut();
    }
    ptr_val.to_private() as *mut bun_uws_sys::response::c::uws_res
}

#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn h2_stream_respond(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;

    let this = args.thisv();
    rooted!(&in(cx_ref) let obj = this.to_object());

    // Extract :status from headers
    if argc > 0 {
        let hdrs_val = *args.get(0).ptr;
        if hdrs_val.is_object() {
            rooted!(&in(cx_ref) let hdrs_obj = hdrs_val.to_object());

            // Get :status
            let mut status_val = UndefinedValue();
            JS_GetProperty(
                cx,
                hdrs_obj.handle().into(),
                c":status".as_ptr(),
                MutableHandle::<Value> {
                    _phantom_0: ::std::marker::PhantomData,
                    ptr: &mut status_val,
                },
            );

            let status = if status_val.is_string() {
                let s = crate::js_to_rust_string(cx, status_val);
                s.parse::<i32>().unwrap_or(200)
            } else if status_val.is_int32() {
                status_val.to_int32()
            } else {
                200
            };

            let uws_res = get_uws_res(cx, obj.get());
            if !uws_res.is_null() {
                let res_mut = Response::<false>::cast_res(uws_res);
                if (*res_mut).state().is_http_end_called() {
                    // Response already complete — respond() is a no-op, never
                    // a second uWS end (use-after-answer crash class).
                    args.rval().set(UndefinedValue());
                    return true;
                }
                if !(*res_mut).state().is_http_status_called() {
                    let status_str = format!("{} ", status);
                    (*res_mut).write_status(status_str.as_bytes());
                }

                // Write ALL response headers (IdVector iteration; ':'-prefixed
                // pseudo-headers skipped inside) — the fixed common-name list
                // silently dropped every other header.
                h2_write_headers_obj(cx, hdrs_obj.get(), &mut *res_mut);
            }
        }
    }

    // If endStream option, end the response
    if argc > 1 {
        let opts_val = *args.get(1).ptr;
        if opts_val.is_object() {
            rooted!(&in(cx_ref) let opts_obj = opts_val.to_object());
            let mut end_stream_val = UndefinedValue();
            JS_GetProperty(
                cx,
                opts_obj.handle().into(),
                c"endStream".as_ptr(),
                MutableHandle::<Value> {
                    _phantom_0: ::std::marker::PhantomData,
                    ptr: &mut end_stream_val,
                },
            );
            if end_stream_val.is_boolean() && end_stream_val.to_boolean() {
                let uws_res = get_uws_res(cx, obj.get());
                if !uws_res.is_null() {
                    let res_mut = Response::<false>::cast_res(uws_res);
                    if !(*res_mut).state().is_http_end_called() {
                        if !(*res_mut).state().is_http_status_called() {
                            (*res_mut).write_status(b"200 ");
                        }
                        (*res_mut).end(&[], false);
                        h2_finish_state_from_obj(cx, obj.get(), &mut *res_mut);
                    }
                }
            }
        }
    }

    args.rval().set(UndefinedValue());
    true
}

#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn h2_stream_end(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;

    let this = args.thisv();
    rooted!(&in(cx_ref) let obj = this.to_object());

    let uws_res = get_uws_res(cx, obj.get());
    if uws_res.is_null() {
        args.rval().set(UndefinedValue());
        return true;
    }
    let res_mut = Response::<false>::cast_res(uws_res);

    // Node contract: end() after end() is a no-op — a second uWS end() on
    // the same response is a use-after-answer crash class (also covers the
    // res.end-first cross-object case: both objects share _uwsRes).
    if (*res_mut).state().is_http_end_called() {
        args.rval().set(UndefinedValue());
        return true;
    }

    // Accumulated body: legacy `_body` string + the final chunk, byte-exact
    // (strings encode UTF-8; Buffer/TypedArray chunks copy verbatim — the
    // previous string-only accumulator dropped every binary body).
    let mut body: Vec<u8> = Vec::new();
    {
        let mut body_val = UndefinedValue();
        JS_GetProperty(
            cx,
            obj.handle().into(),
            c"_body".as_ptr(),
            MutableHandle::<Value> {
                _phantom_0: ::std::marker::PhantomData,
                ptr: &mut body_val,
            },
        );
        if body_val.is_string() {
            body.extend_from_slice(crate::js_to_rust_string(cx, body_val).as_bytes());
        }
    }
    if argc > 0 {
        let v = *args.get(0).ptr;
        if v.is_string() {
            body.extend_from_slice(crate::js_to_rust_string(cx, v).as_bytes());
        } else if let Some(bytes) = crate::node_buffer::collect_byte_view(cx, v) {
            body.extend_from_slice(&bytes);
        }
    }

    // Write default status if not yet written
    if !(*res_mut).state().is_http_status_called() {
        (*res_mut).write_status(b"200 ");
    }

    (*res_mut).end(&body, false);
    h2_finish_state_from_obj(cx, obj.get(), &mut *res_mut);

    args.rval().set(UndefinedValue());
    true
}

#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn h2_stream_close(cx: *mut JSContext, _argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, _argc);
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;

    let this = args.thisv();
    rooted!(&in(cx_ref) let obj = this.to_object());

    let uws_res = get_uws_res(cx, obj.get());
    if !uws_res.is_null() {
        let res_mut = Response::<false>::cast_res(uws_res);
        if !(*res_mut).state().is_http_end_called() {
            if !(*res_mut).state().is_http_status_called() {
                (*res_mut).write_status(b"200 ");
            }
            (*res_mut).end(&[], false);
            h2_finish_state_from_obj(cx, obj.get(), &mut *res_mut);
        }
    }

    args.rval().set(UndefinedValue());
    true
}

// ──────────────────────────────────────────────────────────────────────
// Compat response methods — node's Http2ServerResponse surface
// ──────────────────────────────────────────────────────────────────────

/// Read `_stateId` off a JS object and finish the per-request state (used
/// by every path that completes the uWS response: res.end, stream.end,
/// stream.close, respond{endStream:true}).
#[allow(unsafe_op_in_unsafe_fn)]
unsafe fn h2_finish_state_from_obj(cx: *mut JSContext, obj: *mut JSObject, res: &mut Response<false>) {
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;
    rooted!(&in(cx_ref) let obj_root = obj);
    let mut id_val = UndefinedValue();
    JS_GetProperty(
        cx,
        obj_root.handle().into(),
        c"_stateId".as_ptr(),
        MutableHandle::<Value> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut id_val,
        },
    );
    if id_val.is_int32() {
        h2_req_finish(cx, id_val.to_int32() as u64, Some(res));
    }
}

/// Read the `_headers` bookkeeping object off the res object (missing →
/// None).
#[allow(unsafe_op_in_unsafe_fn)]
unsafe fn h2_get_headers_obj(cx: *mut JSContext, obj: *mut JSObject) -> Option<*mut JSObject> {
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;
    rooted!(&in(cx_ref) let obj_root = obj);
    let mut v = UndefinedValue();
    JS_GetProperty(
        cx,
        obj_root.handle().into(),
        c"_headers".as_ptr(),
        MutableHandle::<Value> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut v,
        },
    );
    if v.is_object() {
        Some(v.to_object())
    } else {
        None
    }
}

/// res.writeHead(status[, statusText][, headers]) — write status + headers
/// to the wire. Second writeHead (or after headers sent) is node's
/// ERR_HTTP_HEADERS_SENT.
#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn h2_res_write_head(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;
    rooted!(&in(cx_ref) let obj = args.thisv().to_object());

    let status: i32 = if argc > 0 {
        let v = *args.get(0).ptr;
        if v.is_int32() {
            v.to_int32()
        } else if v.is_double() {
            v.to_double() as i32
        } else {
            200
        }
    } else {
        200
    };

    // Record statusCode for bookkeeping (end() default uses it too).
    rooted!(&in(cx_ref) let sv = Int32Value(status));
    JS_SetProperty(cx, obj.handle().into(), c"statusCode".as_ptr(), sv.handle().into());

    let uws_res = get_uws_res(cx, obj.get());
    if !uws_res.is_null() {
        let res_mut = Response::<false>::cast_res(uws_res);
        if (*res_mut).state().is_http_end_called() {
            JS_ReportErrorUTF8(cx, c"%s".as_ptr(), c"write after end".as_ptr());
            return false;
        }
        if (*res_mut).state().is_http_status_called() {
            let msg = ZBox::from_bytes("Headers already sent".as_bytes());
            JS_ReportErrorUTF8(cx, c"%s".as_ptr(), msg.as_ptr());
            return false;
        }
        let status_str = format!("{} ", status);
        (*res_mut).write_status(status_str.as_bytes());
    }

    // Headers object: first object arg after status (statusText string is
    // accepted and skipped — headers come from the object arg).
    for i in 1..(argc as usize) {
        let v = *args.get(i as u32).ptr;
        if v.is_object() {
            rooted!(&in(cx_ref) let hdrs_obj = v.to_object());

            // Node merge semantics: setHeader values written first, then the
            // writeHead object's values — same-name writeHead keys override
            // (skipped in the store flush so the wire never carries the
            // header twice).
            let mut arg_keys: Vec<String> = Vec::new();
            {
                let mut ids = mozjs::rust::IdVector::new(cx);
                if w2::GetPropertyKeys(
                    cx_ref,
                    hdrs_obj.handle().into(),
                    JSITER_OWNONLY as u32,
                    ids.handle_mut(),
                ) {
                    for jsid in &*ids {
                        if !jsid.is_string() {
                            continue;
                        }
                        let key_str = jsid.to_string();
                        let key = mozjs::conversions::unsafe_jsstr_to_string(
                            cx,
                            NonNull::new_unchecked(key_str),
                        );
                        arg_keys.push(key);
                    }
                }
            }

            let uws_res = get_uws_res(cx, obj.get());
            if !uws_res.is_null() {
                let res_mut = Response::<false>::cast_res(uws_res);
                // setHeader store first, minus overridden keys.
                if let Some(headers_store) = h2_get_headers_obj(cx, obj.get()) {
                    rooted!(&in(cx_ref) let store_root = headers_store);
                    let mut store_ids = mozjs::rust::IdVector::new(cx);
                    if w2::GetPropertyKeys(
                        cx_ref,
                        store_root.handle().into(),
                        JSITER_OWNONLY as u32,
                        store_ids.handle_mut(),
                    ) {
                        for jsid in &*store_ids {
                            if !jsid.is_string() {
                                continue;
                            }
                            let key_str = jsid.to_string();
                            let key = mozjs::conversions::unsafe_jsstr_to_string(
                                cx,
                                NonNull::new_unchecked(key_str),
                            );
                            if key.starts_with(':') || arg_keys.contains(&key) {
                                continue;
                            }
                            let c_key = ZBox::from_bytes(key.as_bytes());
                            let mut hv = UndefinedValue();
                            JS_GetProperty(
                                cx,
                                store_root.handle().into(),
                                c_key.as_ptr(),
                                MutableHandle::<Value> {
                                    _phantom_0: ::std::marker::PhantomData,
                                    ptr: &mut hv,
                                },
                            );
                            if hv.is_string() {
                                let val = crate::js_to_rust_string(cx, hv);
                                let key_lower = key.to_ascii_lowercase();
                                let c_val = ZBox::from_bytes(val.as_bytes());
                                (*res_mut).write_header(key_lower.as_bytes(), c_val.as_bytes());
                            }
                        }
                    }
                }
                h2_write_headers_obj(cx, hdrs_obj.get(), &mut *res_mut);
            }

            // Mirror the writeHead object into _headers for
            // getHeader/hasHeader truth.
            if let Some(headers_store) = h2_get_headers_obj(cx, obj.get()) {
                rooted!(&in(cx_ref) let store_root = headers_store);
                for key in &arg_keys {
                    let c_key = ZBox::from_bytes(key.as_bytes());
                    let mut hv = UndefinedValue();
                    JS_GetProperty(
                        cx,
                        hdrs_obj.handle().into(),
                        c_key.as_ptr(),
                        MutableHandle::<Value> {
                            _phantom_0: ::std::marker::PhantomData,
                            ptr: &mut hv,
                        },
                    );
                    if hv.is_string() {
                        JS_SetProperty(
                            cx,
                            store_root.handle().into(),
                            c_key.as_ptr(),
                            {
                                rooted!(&in(cx_ref) let hr = hv);
                                hr.handle().into()
                            },
                        );
                    }
                }
            }
            break;
        }
    }

    args.rval().set(ObjectValue(obj.get()));
    true
}

/// res.setHeader(name, value) — pre-send header store (flushed by end()
/// when writeHead was never called). Setting after send is node's
/// ERR_HTTP_HEADERS_SENT.
#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn h2_res_set_header(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;
    rooted!(&in(cx_ref) let obj = args.thisv().to_object());

    if h2_res_headers_sent(cx, obj.get()) {
        let msg = ZBox::from_bytes("Cannot set headers after they are sent to the client".as_bytes());
        JS_ReportErrorUTF8(cx, c"%s".as_ptr(), msg.as_ptr());
        return false;
    }

    if argc < 2 {
        let msg = ZBox::from_bytes("res.setHeader(name, value) requires 2 arguments".as_bytes());
        JS_ReportErrorUTF8(cx, c"%s".as_ptr(), msg.as_ptr());
        return false;
    }
    let name_val = *args.get(0).ptr;
    let value_val = *args.get(1).ptr;
    if !name_val.is_string() {
        let msg = ZBox::from_bytes("res.setHeader name must be a string".as_bytes());
        JS_ReportErrorUTF8(cx, c"%s".as_ptr(), msg.as_ptr());
        return false;
    }
    let name = crate::js_to_rust_string(cx, name_val);
    let value_str = if value_val.is_string() {
        crate::js_to_rust_string(cx, value_val)
    } else if value_val.is_int32() {
        format!("{}", value_val.to_int32())
    } else if value_val.is_double() {
        format!("{}", value_val.to_double())
    } else {
        let msg = ZBox::from_bytes("res.setHeader value must be a string or number".as_bytes());
        JS_ReportErrorUTF8(cx, c"%s".as_ptr(), msg.as_ptr());
        return false;
    };

    if let Some(headers_store) = h2_get_headers_obj(cx, obj.get()) {
        rooted!(&in(cx_ref) let store_root = headers_store);
        let c_name = ZBox::from_bytes(name.as_bytes());
        let c_value = ZBox::from_bytes(value_str.as_bytes());
        let js_v = JS_NewStringCopyZ(cx, c_value.as_ptr());
        if !js_v.is_null() {
            let vv = StringValue(&*js_v);
            rooted!(&in(cx_ref) let vv_root = vv);
            JS_SetProperty(cx, store_root.handle().into(), c_name.as_ptr(), vv_root.handle().into());
        }
    }

    args.rval().set(ObjectValue(obj.get()));
    true
}

/// Headers-sent truth: the uWS status line is out, or the response ended.
#[allow(unsafe_op_in_unsafe_fn)]
unsafe fn h2_res_headers_sent(cx: *mut JSContext, obj: *mut JSObject) -> bool {
    if h2_get_bool_prop(cx, obj, "_ended") {
        return true;
    }
    let uws_res = get_uws_res(cx, obj);
    if uws_res.is_null() {
        return false;
    }
    let res_mut = Response::<false>::cast_res(uws_res);
    (*res_mut).state().is_http_status_called() || (*res_mut).state().is_http_end_called()
}

/// res.getHeader(name) → stored value or undefined.
#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn h2_res_get_header(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;
    rooted!(&in(cx_ref) let obj = args.thisv().to_object());

    args.rval().set(UndefinedValue());
    if argc < 1 || !(*args.get(0).ptr).is_string() {
        return true;
    }
    let name = crate::js_to_rust_string(cx, *args.get(0).ptr);
    if let Some(headers_store) = h2_get_headers_obj(cx, obj.get()) {
        rooted!(&in(cx_ref) let store_root = headers_store);
        let c_name = ZBox::from_bytes(name.as_bytes());
        let mut v = UndefinedValue();
        JS_GetProperty(
            cx,
            store_root.handle().into(),
            c_name.as_ptr(),
            MutableHandle::<Value> {
                _phantom_0: ::std::marker::PhantomData,
                ptr: &mut v,
            },
        );
        args.rval().set(v);
    }
    true
}

/// res.getHeaders() → shallow copy of the store.
#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn h2_res_get_headers(cx: *mut JSContext, _argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, _argc);
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;
    rooted!(&in(cx_ref) let obj = args.thisv().to_object());

    rooted!(&in(cx_ref) let out = w2::JS_NewPlainObject(cx_ref));
    args.rval().set(ObjectValue(out.get()));
    if let Some(headers_store) = h2_get_headers_obj(cx, obj.get()) {
        rooted!(&in(cx_ref) let store_root = headers_store);
        let mut ids = mozjs::rust::IdVector::new(cx);
        if w2::GetPropertyKeys(
            cx_ref,
            store_root.handle().into(),
            JSITER_OWNONLY as u32,
            ids.handle_mut(),
        ) {
            for jsid in &*ids {
                if !jsid.is_string() {
                    continue;
                }
                let key_str = jsid.to_string();
                let key = mozjs::conversions::unsafe_jsstr_to_string(
                    cx,
                    NonNull::new_unchecked(key_str),
                );
                let c_key = ZBox::from_bytes(key.as_bytes());
                let mut hv = UndefinedValue();
                JS_GetProperty(
                    cx,
                    store_root.handle().into(),
                    c_key.as_ptr(),
                    MutableHandle::<Value> {
                        _phantom_0: ::std::marker::PhantomData,
                        ptr: &mut hv,
                    },
                );
                JS_DefineProperty(
                    cx,
                    out.handle().into(),
                    c_key.as_ptr(),
                    {
                        rooted!(&in(cx_ref) let hr = hv);
                        hr.handle().into()
                    },
                    JSPROP_ENUMERATE as u32,
                );
            }
        }
    }
    true
}

/// res.hasHeader(name) → boolean.
#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn h2_res_has_header(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;
    rooted!(&in(cx_ref) let obj = args.thisv().to_object());

    let mut found = false;
    if argc >= 1 && (*args.get(0).ptr).is_string() {
        let name = crate::js_to_rust_string(cx, *args.get(0).ptr);
        if let Some(headers_store) = h2_get_headers_obj(cx, obj.get()) {
            rooted!(&in(cx_ref) let store_root = headers_store);
            let c_name = ZBox::from_bytes(name.as_bytes());
            let mut v = UndefinedValue();
            JS_GetProperty(
                cx,
                store_root.handle().into(),
                c_name.as_ptr(),
                MutableHandle::<Value> {
                    _phantom_0: ::std::marker::PhantomData,
                    ptr: &mut v,
                },
            );
            found = !v.is_undefined();
        }
    }
    args.rval().set(mozjs::jsval::BooleanValue(found));
    true
}

/// res.removeHeader(name) — pre-send only (node throws after send).
#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn h2_res_remove_header(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;
    rooted!(&in(cx_ref) let obj = args.thisv().to_object());

    if h2_res_headers_sent(cx, obj.get()) {
        let msg = ZBox::from_bytes("Cannot remove headers after they are sent to the client".as_bytes());
        JS_ReportErrorUTF8(cx, c"%s".as_ptr(), msg.as_ptr());
        return false;
    }
    if argc >= 1 && (*args.get(0).ptr).is_string() {
        let name = crate::js_to_rust_string(cx, *args.get(0).ptr);
        if let Some(headers_store) = h2_get_headers_obj(cx, obj.get()) {
            rooted!(&in(cx_ref) let store_root = headers_store);
            let c_name = ZBox::from_bytes(name.as_bytes());
            rooted!(&in(cx_ref) let uv = UndefinedValue());
            // JS_DeleteProperty1 would be cleaner; UndefinedValue assignment
            // reads as "missing" for every consumer of the store.
            JS_SetProperty(cx, store_root.handle().into(), c_name.as_ptr(), uv.handle().into());
        }
    }
    args.rval().set(ObjectValue(obj.get()));
    true
}

/// res.write(chunk) — buffer byte-exactly; the whole body flushes once in
/// end() (same single-flush model as node:http — write() streaming plus a
/// later end() re-send duplicated every chunk on the wire).
#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn h2_res_write(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;
    rooted!(&in(cx_ref) let obj = args.thisv().to_object());

    // Node contract: write() after end() throws ERR_STREAM_WRITE_AFTER_END.
    if h2_get_bool_prop(cx, obj.get(), "_ended") {
        JS_ReportErrorUTF8(cx, c"%s".as_ptr(), c"write after end".as_ptr());
        return false;
    }

    if argc > 0 {
        let v = *args.get(0).ptr;
        if !h2_res_append_chunk(cx, obj.get(), v) {
            return false;
        }
    }
    args.rval().set(ObjectValue(obj.get()));
    true
}

/// res.end([chunk]) — flush status (statusCode default or writeHead's),
/// pending setHeader store, then the exact accumulated body. Idempotent;
/// finishes the per-request state and emits 'finish' + 'close'.
#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn h2_res_end(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;
    rooted!(&in(cx_ref) let obj = args.thisv().to_object());

    // Node contract: end() after end() is a no-op (second uWS end() on the
    // same response is a use-after-answer crash class).
    if h2_get_bool_prop(cx, obj.get(), "_ended") {
        args.rval().set(ObjectValue(obj.get()));
        return true;
    }

    if argc > 0 {
        let v = *args.get(0).ptr;
        if !h2_res_append_chunk(cx, obj.get(), v) {
            return false;
        }
    }

    let body = h2_res_collect_body(cx, obj.get());

    let uws_res = get_uws_res(cx, obj.get());
    if !uws_res.is_null() {
        let res_mut = Response::<false>::cast_res(uws_res);
        if !(*res_mut).state().is_http_end_called() {
            // Status: writeHead's line may already be out; otherwise default
            // from the statusCode property (node's implicit 200).
            if !(*res_mut).state().is_http_status_called() {
                let mut status_val = Int32Value(200);
                JS_GetProperty(
                    cx,
                    obj.handle().into(),
                    c"statusCode".as_ptr(),
                    MutableHandle::<Value> {
                        _phantom_0: ::std::marker::PhantomData,
                        ptr: &mut status_val,
                    },
                );
                let status = if status_val.is_int32() {
                    status_val.to_int32()
                } else {
                    200
                };
                let status_str = format!("{} ", status);
                (*res_mut).write_status(status_str.as_bytes());

                // setHeader store flushes only when writeHead never ran.
                if let Some(headers_store) = h2_get_headers_obj(cx, obj.get()) {
                    rooted!(&in(cx_ref) let store_root = headers_store);
                    h2_write_headers_obj(cx, store_root.get(), &mut *res_mut);
                }
            }

            // uWS computes Content-Length from data.len() — binary bodies
            // hit the wire byte-for-byte.
            (*res_mut).end(&body, false);
            h2_finish_state_from_obj(cx, obj.get(), &mut *res_mut);
        }
    }

    h2_set_bool_prop(cx, obj.get(), "_ended", true);

    // Lifecycle events (node emits 'finish' then 'close' on the response).
    h2_emit_event(cx, obj.get(), "finish", None);
    h2_emit_event(cx, obj.get(), "close", None);

    args.rval().set(ObjectValue(obj.get()));
    true
}

/// res.setTimeout(msecs, callback) — arm the callback on the real timer
/// wheel via global setTimeout (node invokes it with no args on timeout).
#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn h2_res_set_timeout(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;
    rooted!(&in(cx_ref) let obj = args.thisv().to_object());

    if argc >= 2 && (*args.get(1).ptr).is_object() {
        let msecs = if (*args.get(0).ptr).is_int32() {
            (*args.get(0).ptr).to_int32().max(0)
        } else {
            0
        };
        rooted!(&in(cx_ref) let global = CurrentGlobalOrNull(cx));
        if !global.get().is_null() {
            let c_set_timeout = ZBox::from_bytes("setTimeout".as_bytes());
            let mut st_val = UndefinedValue();
            JS_GetProperty(
                cx,
                global.handle().into(),
                c_set_timeout.as_ptr(),
                MutableHandle::<Value> {
                    _phantom_0: ::std::marker::PhantomData,
                    ptr: &mut st_val,
                },
            );
            if st_val.is_object() {
                rooted!(&in(cx_ref) let st_fn = st_val.to_object());
                rooted!(&in(cx_ref) let st_root = ObjectValue(st_fn.get()));
                rooted!(&in(cx_ref) let cb_root = *args.get(1).ptr);
                rooted!(&in(cx_ref) let ms_root = Int32Value(msecs));
                let call_vals = [cb_root.get(), ms_root.get()];
                let call_args = HandleValueArray {
                    length_: 2,
                    elements_: call_vals.as_ptr(),
                };
                let mut rval = UndefinedValue();
                JS_CallFunctionValue(
                    cx,
                    global.handle().into(),
                    st_root.handle().into(),
                    &call_args,
                    MutableHandle::<Value> {
                        _phantom_0: ::std::marker::PhantomData,
                        ptr: &mut rval,
                    },
                );
                JS_ClearPendingException(cx);
            }
        }
    }

    args.rval().set(ObjectValue(obj.get()));
    true
}

// ──────────────────────────────────────────────────────────────────────
// createServer / createSecureServer — JS host functions
// ──────────────────────────────────────────────────────────────────────

#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn http2_create_server(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;

    // Create a JS Http2Server instance via the IIFE's constructor
    // First, get the Http2Server constructor from the http2 module object
    let this_val = args.thisv();
    rooted!(&in(cx_ref) let http2_obj = if this_val.is_object() {
        this_val.to_object()
    } else {
        core::ptr::null_mut()
    });

    if http2_obj.get().is_null() {
        args.rval().set(UndefinedValue());
        return true;
    }

    // Get Http2Server constructor
    let mut ctor_val = UndefinedValue();
    JS_GetProperty(
        cx,
        http2_obj.handle().into(),
        c"Http2Server".as_ptr(),
        MutableHandle::<Value> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut ctor_val,
        },
    );

    if !ctor_val.is_object() {
        // Fallback: create a plain object with EE methods
        rooted!(&in(cx_ref) let server_obj = w2::JS_NewPlainObject(cx_ref));
        if server_obj.get().is_null() {
            args.rval().set(UndefinedValue());
            return true;
        }
        attach_ee_methods(cx, server_obj.get());
        w2::JS_DefineFunction(
            cx_ref,
            server_obj.handle(),
            c"listen".as_ptr(),
            Some(http2_server_listen_js),
            3,
            JSPROP_ENUMERATE as u32,
        );
        w2::JS_DefineFunction(
            cx_ref,
            server_obj.handle(),
            c"close".as_ptr(),
            Some(http2_server_close_js),
            1,
            JSPROP_ENUMERATE as u32,
        );
        store_handler(cx, cx_ref, server_obj.get(), argc, &args);
        args.rval().set(ObjectValue(server_obj.get()));
        return true;
    }

    // new Http2Server(options, handler): build the instance off the ctor's
    // prototype and run the ctor body with the instance as `this`. A bare
    // JS_CallFunctionValue against the global runs the sloppy-mode ctor on
    // the global and returns undefined (the ctor has no return statement),
    // which made createServer() yield undefined.
    rooted!(&in(cx_ref) let ctor = ctor_val.to_object());

    let mut proto_val = UndefinedValue();
    JS_GetProperty(
        cx,
        ctor.handle().into(),
        c"prototype".as_ptr(),
        MutableHandle::<Value> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut proto_val,
        },
    );
    rooted!(&in(cx_ref) let proto_obj = if proto_val.is_object() {
        proto_val.to_object()
    } else {
        ::std::ptr::null_mut::<JSObject>()
    });
    rooted!(&in(cx_ref) let server_obj = w2::JS_NewObjectWithGivenProto(
        cx_ref,
        ::std::ptr::null(),
        proto_obj.handle()
    ));
    if server_obj.get().is_null() {
        args.rval().set(UndefinedValue());
        return true;
    }

    // Prepare args: (options, handler)
    let opts_arg = if argc > 0 && (*args.get(0).ptr).is_object() {
        *args.get(0).ptr
    } else {
        UndefinedValue()
    };
    let handler_arg = if argc > 1 && (*args.get(1).ptr).is_object() {
        *args.get(1).ptr
    } else {
        UndefinedValue()
    };

    let call_args_vals = [opts_arg, handler_arg];
    let call_args = HandleValueArray {
        length_: if argc > 1 {
            2
        } else if argc > 0 {
            1
        } else {
            0
        },
        elements_: call_args_vals.as_ptr(),
    };

    rooted!(&in(cx_ref) let ctor_fn = ObjectValue(ctor.get()));
    let mut ctor_rval = UndefinedValue();
    JS_CallFunctionValue(
        cx,
        server_obj.handle().into(),
        ctor_fn.handle().into(),
        &call_args,
        MutableHandle::<Value> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut ctor_rval,
        },
    );

    // Store handler on the server object for native listen
    store_handler(cx, cx_ref, server_obj.get(), argc, &args);
    args.rval().set(ObjectValue(server_obj.get()));

    true
}

#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn http2_create_secure_server(
    cx: *mut JSContext,
    argc: u32,
    vp: *mut JSVal,
) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;

    let this_val = args.thisv();
    rooted!(&in(cx_ref) let http2_obj = if this_val.is_object() {
        this_val.to_object()
    } else {
        core::ptr::null_mut()
    });

    if http2_obj.get().is_null() {
        args.rval().set(UndefinedValue());
        return true;
    }

    // Get Http2SecureServer constructor
    let mut ctor_val = UndefinedValue();
    JS_GetProperty(
        cx,
        http2_obj.handle().into(),
        c"Http2SecureServer".as_ptr(),
        MutableHandle::<Value> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut ctor_val,
        },
    );

    if !ctor_val.is_object() {
        // Fallback: create a plain object with EE methods
        rooted!(&in(cx_ref) let server_obj = w2::JS_NewPlainObject(cx_ref));
        if server_obj.get().is_null() {
            args.rval().set(UndefinedValue());
            return true;
        }
        attach_ee_methods(cx, server_obj.get());
        w2::JS_DefineFunction(
            cx_ref,
            server_obj.handle(),
            c"listen".as_ptr(),
            Some(http2_secure_server_listen_js),
            3,
            JSPROP_ENUMERATE as u32,
        );
        w2::JS_DefineFunction(
            cx_ref,
            server_obj.handle(),
            c"close".as_ptr(),
            Some(http2_secure_server_close_js),
            1,
            JSPROP_ENUMERATE as u32,
        );
        store_handler(cx, cx_ref, server_obj.get(), argc, &args);
        // Mark as secure
        rooted!(&in(cx_ref) let secure_val = BooleanValue(true));
        JS_DefineProperty(
            cx,
            server_obj.handle().into(),
            c"_secure".as_ptr(),
            secure_val.handle().into(),
            0,
        );
        args.rval().set(ObjectValue(server_obj.get()));
        return true;
    }

    // new Http2SecureServer(options, handler): construct via the ctor's
    // prototype with the instance as `this` (see http2_create_server — a
    // bare call against the global returns undefined).
    rooted!(&in(cx_ref) let ctor = ctor_val.to_object());

    let mut proto_val = UndefinedValue();
    JS_GetProperty(
        cx,
        ctor.handle().into(),
        c"prototype".as_ptr(),
        MutableHandle::<Value> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut proto_val,
        },
    );
    rooted!(&in(cx_ref) let proto_obj = if proto_val.is_object() {
        proto_val.to_object()
    } else {
        ::std::ptr::null_mut::<JSObject>()
    });
    rooted!(&in(cx_ref) let server_obj = w2::JS_NewObjectWithGivenProto(
        cx_ref,
        ::std::ptr::null(),
        proto_obj.handle()
    ));
    if server_obj.get().is_null() {
        args.rval().set(UndefinedValue());
        return true;
    }

    let opts_arg = if argc > 0 && (*args.get(0).ptr).is_object() {
        *args.get(0).ptr
    } else {
        UndefinedValue()
    };
    let handler_arg = if argc > 1 && (*args.get(1).ptr).is_object() {
        *args.get(1).ptr
    } else {
        UndefinedValue()
    };

    let call_args_vals = [opts_arg, handler_arg];
    let call_args = HandleValueArray {
        length_: if argc > 1 {
            2
        } else if argc > 0 {
            1
        } else {
            0
        },
        elements_: call_args_vals.as_ptr(),
    };

    rooted!(&in(cx_ref) let ctor_fn = ObjectValue(ctor.get()));
    let mut ctor_rval = UndefinedValue();
    JS_CallFunctionValue(
        cx,
        server_obj.handle().into(),
        ctor_fn.handle().into(),
        &call_args,
        MutableHandle::<Value> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut ctor_rval,
        },
    );

    store_handler(cx, cx_ref, server_obj.get(), argc, &args);
    // Mark as secure
    rooted!(&in(cx_ref) let secure_val = BooleanValue(true));
    JS_DefineProperty(
        cx,
        server_obj.handle().into(),
        c"_secure".as_ptr(),
        secure_val.handle().into(),
        0,
    );
    args.rval().set(ObjectValue(server_obj.get()));

    true
}

/// Store the stream handler on the server JS object as `_onStreamHandler`.
#[allow(unsafe_op_in_unsafe_fn)]
unsafe fn store_handler(
    cx: *mut JSContext,
    cx_ref: &mut mozjs::context::JSContext,
    server_obj: *mut JSObject,
    argc: u32,
    args: &CallArgs,
) {
    // The handler can be arg[1] (options, handler) or arg[0] (handler only)
    let handler_val = if argc > 1 {
        *args.get(1).ptr
    } else if argc > 0 {
        *args.get(0).ptr
    } else {
        UndefinedValue()
    };

    if handler_val.is_object() {
        rooted!(&in(cx_ref) let cb = handler_val.to_object());
        let cb_val = ObjectValue(cb.get());
        rooted!(&in(cx_ref) let cb_root = cb_val);
        rooted!(&in(cx_ref) let server_root = server_obj);
        JS_DefineProperty(
            cx,
            server_root.handle().into(),
            c"_onStreamHandler".as_ptr(),
            cb_root.handle().into(),
            0,
        );
    }
}

/// Attach EventEmitter methods to a plain server object.
#[allow(unsafe_op_in_unsafe_fn)]
unsafe fn attach_ee_methods(cx: *mut JSContext, obj: *mut JSObject) {
    let ee_on: JSNative = Some(crate::node_events::ee_on);
    let ee_emit: JSNative = Some(crate::node_events::ee_emit);
    let ee_once: JSNative = Some(crate::node_events::ee_once);
    let ee_off: JSNative = Some(crate::node_events::ee_off);
    let ee_prepend: JSNative = Some(crate::node_events::ee_prepend);
    let ee_remove_all: JSNative = Some(crate::node_events::ee_remove_all);

    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;

    rooted!(&in(cx_ref) let obj_root = obj);
    for (name, op) in [
        ("on", ee_on),
        ("once", ee_once),
        ("emit", ee_emit),
        ("off", ee_off),
        ("addListener", ee_on),
        ("removeListener", ee_off),
        ("prependListener", ee_prepend),
        ("removeAllListeners", ee_remove_all),
    ] {
        let c_name = ZBox::from_bytes(name.as_bytes());
        mozjs_sys::jsapi::JS_DefineFunction(
            cx,
            obj_root.handle().into(),
            c_name.as_ptr(),
            op,
            2,
            JSPROP_ENUMERATE as u32,
        );
    }
}

// ──────────────────────────────────────────────────────────────────────
// Server listen / close — native uWS App bridge
// ──────────────────────────────────────────────────────────────────────

/// Per-listen state handed to uWS: the listen callback fires when the
/// socket actually binds (or fails), which is where node semantics place the
/// 'listening' event and the user callback — calling the callback eagerly at
/// listen() time was the "listen 回调不触发"/premature-fire class.
struct H2ListenState {
    cx: *mut JSContext,
    cb_key: String,
    server_key: String,
}

/// uWS listen callback: socket non-null = listening confirmed; null = bind
/// failed (EADDRINUSE etc). Emits 'listening'/'error' on the server object
/// and invokes the user callback (no args on success, an error carrier on
/// failure), then frees the state (uWS fires this exactly once per listen).
#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn uws_h2_listen_callback(
    listen_socket: *mut bun_uws_sys::listen_socket::ListenSocket,
    user_data: *mut ::std::ffi::c_void,
) {
    if user_data.is_null() {
        // Legacy js-bridge listen sites pass null — nothing deferred there.
        return;
    }
    let st = Box::from_raw(user_data as *mut H2ListenState);
    let cx = st.cx;
    let cb_key = st.cb_key.clone();
    let server_key = st.server_key.clone();

    let realm_global = match bao_engine::context::thread_realm_global() {
        Some(g) if !g.is_null() => g,
        _ => {
            eprintln!("[node:http2] listen callback: no JS realm — cannot fire JS callback");
            gc_store_remove_ns(cx, "http2", &cb_key);
            gc_store_remove_ns(cx, "http2", &server_key);
            return;
        }
    };
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;
    rooted!(&in(cx_ref) let realm_global_root = realm_global);
    let mut realm = mozjs::realm::AutoRealm::new_from_handle(cx_ref, realm_global_root.handle());
    let cx_ref: &mut mozjs::context::JSContext = &mut realm;

    let cb = gc_store_get_ns(cx, "http2", &cb_key);
    let server_obj = gc_store_get_ns(cx, "http2", &server_key);

    if listen_socket.is_null() {
        // Bind failed: node calls cb(err) and emits 'error' on the server.
        eprintln!("[node:http2] listen failed (bind error)");
        rooted!(&in(cx_ref) let err_obj = w2::JS_NewPlainObject(cx_ref));
        if !err_obj.get().is_null() {
            let c_code = ZBox::from_bytes("EADDRINUSE".as_bytes());
            let c_code_v = JS_NewStringCopyZ(cx, c_code.as_ptr());
            if !c_code_v.is_null() {
                let cv = StringValue(&*c_code_v);
                rooted!(&in(cx_ref) let cvr = cv);
                JS_DefineProperty(
                    cx,
                    err_obj.handle().into(),
                    c"code".as_ptr(),
                    cvr.handle().into(),
                    JSPROP_ENUMERATE as u32,
                );
            }
            let c_msg = ZBox::from_bytes("listen EADDRINUSE: address already in use".as_bytes());
            let c_msg_v = JS_NewStringCopyZ(cx, c_msg.as_ptr());
            if !c_msg_v.is_null() {
                let mv = StringValue(&*c_msg_v);
                rooted!(&in(cx_ref) let mvr = mv);
                JS_DefineProperty(
                    cx,
                    err_obj.handle().into(),
                    c"message".as_ptr(),
                    mvr.handle().into(),
                    JSPROP_ENUMERATE as u32,
                );
            }
            if let Some(server) = server_obj {
                if !server.is_null() {
                    h2_emit_event(cx, server, "error", Some(ObjectValue(err_obj.get())));
                }
            }
            if let Some(cb) = cb {
                if !cb.is_null() {
                    rooted!(&in(cx_ref) let cb_root = ObjectValue(cb));
                    rooted!(&in(cx_ref) let arg_root = ObjectValue(err_obj.get()));
                    let call_vals = [arg_root.get()];
                    let call_args = HandleValueArray {
                        length_: 1,
                        elements_: call_vals.as_ptr(),
                    };
                    let mut rval = UndefinedValue();
                    JS_CallFunctionValue(
                        cx,
                        realm_global_root.handle().into(),
                        cb_root.handle().into(),
                        &call_args,
                        MutableHandle::<Value> {
                            _phantom_0: ::std::marker::PhantomData,
                            ptr: &mut rval,
                        },
                    );
                    JS_ClearPendingException(cx);
                }
            }
        }
    } else {
        if let Some(server) = server_obj {
            if !server.is_null() {
                h2_emit_event(cx, server, "listening", None);
            }
        }
        if let Some(cb) = cb {
            if !cb.is_null() {
                rooted!(&in(cx_ref) let cb_root = ObjectValue(cb));
                let mut rval = UndefinedValue();
                JS_CallFunctionValue(
                    cx,
                    realm_global_root.handle().into(),
                    cb_root.handle().into(),
                    &HandleValueArray::empty(),
                    MutableHandle::<Value> {
                        _phantom_0: ::std::marker::PhantomData,
                        ptr: &mut rval,
                    },
                );
                JS_ClearPendingException(cx);
            }
        }
    }

    gc_store_remove_ns(cx, "http2", &cb_key);
    gc_store_remove_ns(cx, "http2", &server_key);
}

/// __http2_server_listen(serverObj, port[, host][, callback]) — called from
/// JS. The JS wrapper normalizes node's listen arg forms; here host and
/// callback are picked by type so the historical (serverObj, port, callback)
/// shape keeps working too.
#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn http2_server_listen(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;

    // args: serverObj, port, [host | callback], [callback]
    if argc < 2 || !(*args.get(0).ptr).is_object() {
        args.rval().set(UndefinedValue());
        return true;
    }

    let server_obj_val = *args.get(0).ptr;
    rooted!(&in(cx_ref) let server_obj = server_obj_val.to_object());

    let port: u16 = if (*args.get(1).ptr).is_int32() {
        (*args.get(1).ptr).to_int32() as u16
    } else if (*args.get(1).ptr).is_double() {
        (*args.get(1).ptr).to_double() as u16
    } else {
        3000
    };

    let mut host: Option<String> = None;
    let mut callback: Option<*mut JSObject> = None;
    for i in 2..(argc as usize) {
        let v = *args.get(i as u32).ptr;
        if v.is_string() && host.is_none() {
            host = Some(crate::js_to_rust_string(cx, v));
        } else if v.is_object() && callback.is_none() {
            rooted!(&in(cx_ref) let cb = v.to_object());
            callback = Some(cb.get());
        }
    }

    // Create uWS App<false>
    let opts = BunSocketContextOptions::default();
    let app_ptr = match App::<false>::create(&opts) {
        Some(p) => p,
        None => {
            let msg = format!("Failed to create HTTP/2 server on port {}", port);
            let c_msg = ZBox::from_bytes(msg.as_bytes());
            JS_ReportErrorUTF8(cx, c"%s".as_ptr(), c_msg.as_ptr());
            return false;
        }
    };

    // node:http2 rides the same uWS HTTP/1.x parser as node:http, so it
    // keeps node-family framing parity (upstream `IsNodeHttp` split, BCE
    // bdb738222): an HTTP/1.0 request bearing Transfer-Encoding is
    // dispatched and the connection closed after (ancientHttp already
    // marks close), not 400-rejected as Bun.serve does per RFC 9112 6.1.
    // Real-Node http2 would GOAWAY any HTTP/1.x text outright, but this
    // surface is an HTTP/1.x-adapted compat server by design — rejecting
    // only the 1.0+TE pair would match neither Node shape. Must be set
    // before any traffic reaches the app.
    // Safety: app_ptr is a live `*mut App<false>` from `App::create` above,
    // valid until `App::<false>::destroy`.
    unsafe { (*app_ptr).set_is_node_http(true) };

    // Get the JS stream handler from the server object
    let mut handler_val = UndefinedValue();
    let handler_mh = MutableHandle::<Value> {
        _phantom_0: ::std::marker::PhantomData,
        ptr: &mut handler_val,
    };
    JS_GetProperty(
        cx,
        server_obj.handle().into(),
        c"_onStreamHandler".as_ptr(),
        handler_mh,
    );

    rooted!(&in(cx_ref) let global = CurrentGlobalOrNull(cx));
    if global.get().is_null() || !handler_val.is_object() {
        App::<false>::destroy(app_ptr);
        let msg = ZBox::from_bytes("http2.createServer requires a stream handler".as_bytes());
        JS_ReportErrorUTF8(cx, c"%s".as_ptr(), msg.as_ptr());
        return false;
    }

    // Allocate H2ServerUserData (server object registered for the
    // session-style 'stream' event emission from the route handler).
    rooted!(&in(cx_ref) let handler_root = handler_val.to_object());
    let ud = Box::new(H2ServerUserData::new(
        cx,
        global.get(),
        handler_root.get(),
        server_obj.get(),
    ));
    let ud_ptr = Box::into_raw(ud) as *mut ::std::ffi::c_void;

    // Register catch-all route
    let safe_handler: Option<
        extern "C" fn(
            *mut bun_uws_sys::response::c::uws_res,
            *mut bun_uws_sys::Request,
            *mut ::std::ffi::c_void,
        ),
    > = unsafe {
        ::std::mem::transmute(Some(
            uws_h2_route_handler
                as unsafe extern "C" fn(
                    *mut bun_uws_sys::response::c::uws_res,
                    *mut bun_uws_sys::Request,
                    *mut ::std::ffi::c_void,
                ),
        ))
    };
    (*app_ptr).any(b"/*", safe_handler, ud_ptr);

    // Store ud pointer on server object
    {
        let ud_val = PrivateValue(ud_ptr as *const core::ffi::c_void);
        rooted!(&in(cx_ref) let udv = ud_val);
        JS_DefineProperty(
            cx,
            server_obj.handle().into(),
            c"_udPtr".as_ptr(),
            udv.handle().into(),
            0,
        );
    }

    // Listen. Host binding honored through listen_with_config (the plain
    // listen() call bound 0.0.0.0 unconditionally). The JS-facing 'listening'
    // event + user callback fire from uws_h2_listen_callback when the socket
    // actually binds — not eagerly here.
    let listen_id = NEXT_SERVER_ID.fetch_add(1, Ordering::Relaxed);
    let cb_key = format!("http2_listen_{}_cb", listen_id);
    let listen_server_key = format!("http2_listen_{}_server", listen_id);
    if let Some(cb) = callback {
        gc_store_insert_ns(cx, "http2", &cb_key, cb);
    }
    gc_store_insert_ns(cx, "http2", &listen_server_key, server_obj.get());
    let listen_state = Box::new(H2ListenState {
        cx,
        cb_key,
        server_key: listen_server_key,
    });
    let listen_state_ptr = Box::into_raw(listen_state) as *mut ::std::ffi::c_void;

    let safe_listen_cb: extern "C" fn(
        *mut bun_uws_sys::listen_socket::ListenSocket,
        *mut ::std::ffi::c_void,
    ) = unsafe {
        ::std::mem::transmute(
            uws_h2_listen_callback
                as unsafe extern "C" fn(
                    *mut bun_uws_sys::listen_socket::ListenSocket,
                    *mut ::std::ffi::c_void,
                ),
        )
    };
    match &host {
        Some(h) if !h.is_empty() => {
            let host_cstr = ::std::ffi::CString::new(h.clone()).unwrap_or_default();
            let mut config = bun_uws_sys::app::c::uws_app_listen_config_t::new(port as i32);
            config.host = host_cstr.as_ptr();
            (*app_ptr).listen_with_config(Some(safe_listen_cb), listen_state_ptr, config);
        }
        _ => {
            (*app_ptr).listen(port as i32, safe_listen_cb, listen_state_ptr);
        }
    }

    // Store app pointer on server object
    {
        let app_ptr_val = PrivateValue(app_ptr as *const core::ffi::c_void);
        rooted!(&in(cx_ref) let apv = app_ptr_val);
        JS_DefineProperty(
            cx,
            server_obj.handle().into(),
            c"_appPtr".as_ptr(),
            apv.handle().into(),
            0,
        );
    }

    rooted!(&in(cx_ref) let port_root = Int32Value(port as i32));
    JS_DefineProperty(
        cx,
        server_obj.handle().into(),
        c"_listeningPort".as_ptr(),
        port_root.handle().into(),
        JSPROP_ENUMERATE as u32,
    );

    rooted!(&in(cx_ref) let listening_root = BooleanValue(true));
    JS_DefineProperty(
        cx,
        server_obj.handle().into(),
        c"listening".as_ptr(),
        listening_root.handle().into(),
        JSPROP_ENUMERATE as u32,
    );

    register_active_h2_app(app_ptr);

    args.rval().set(UndefinedValue());
    true
}

/// __http2_server_close(serverObj, callback) — called from JS
#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn http2_server_close(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;

    if argc < 1 || !(*args.get(0).ptr).is_object() {
        args.rval().set(UndefinedValue());
        return true;
    }

    let server_obj_val = *args.get(0).ptr;
    rooted!(&in(cx_ref) let server_obj = server_obj_val.to_object());

    let callback = if argc > 1 && (*args.get(1).ptr).is_object() {
        rooted!(&in(cx_ref) let cb = (*args.get(1).ptr).to_object());
        Some(cb.get())
    } else {
        None
    };

    close_h2_server(cx, cx_ref, server_obj.get(), false);

    if let Some(cb) = callback {
        rooted!(&in(cx_ref) let global = CurrentGlobalOrNull(cx));
        if !global.get().is_null() {
            rooted!(&in(cx_ref) let fval_root = ObjectValue(cb));
            let mut rval = UndefinedValue();
            let rval_h = MutableHandle::<Value> {
                _phantom_0: ::std::marker::PhantomData,
                ptr: &mut rval,
            };
            JS_CallFunctionValue(
                cx,
                global.handle().into(),
                fval_root.handle().into(),
                &HandleValueArray::empty(),
                rval_h,
            );
            JS_ClearPendingException(cx);
        }
    }

    args.rval().set(UndefinedValue());
    true
}

/// Close an H2 server — shared by plain and secure close paths.
#[allow(unsafe_op_in_unsafe_fn)]
unsafe fn close_h2_server(
    cx: *mut JSContext,
    cx_ref: &mut mozjs::context::JSContext,
    server_obj: *mut JSObject,
    _is_secure: bool,
) {
    rooted!(&in(cx_ref) let obj = server_obj);

    // Destroy the uWS App
    let mut app_ptr_val = UndefinedValue();
    JS_GetProperty(
        cx,
        obj.handle().into(),
        c"_appPtr".as_ptr(),
        MutableHandle::<Value> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut app_ptr_val,
        },
    );
    let app_ptr = if val_is_private(&app_ptr_val) {
        app_ptr_val.to_private() as *mut App<false>
    } else {
        core::ptr::null_mut()
    };
    if !app_ptr.is_null() {
        (*app_ptr).close();
        App::<false>::destroy(app_ptr);
        unregister_active_h2_app(app_ptr);
        rooted!(&in(cx_ref) let undef_root = UndefinedValue());
        JS_SetProperty(
            cx,
            obj.handle().into(),
            c"_appPtr".as_ptr(),
            undef_root.handle().into(),
        );
    }

    // Cleanup H2ServerUserData
    let mut ud_ptr_val = UndefinedValue();
    JS_GetProperty(
        cx,
        obj.handle().into(),
        c"_udPtr".as_ptr(),
        MutableHandle::<Value> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut ud_ptr_val,
        },
    );
    let ud_ptr = if val_is_private(&ud_ptr_val) {
        ud_ptr_val.to_private() as *mut H2ServerUserData
    } else {
        core::ptr::null_mut()
    };
    if !ud_ptr.is_null() {
        let ud = Box::from_raw(ud_ptr);
        ud.cleanup();
        rooted!(&in(cx_ref) let undef_root2 = UndefinedValue());
        JS_SetProperty(
            cx,
            obj.handle().into(),
            c"_udPtr".as_ptr(),
            undef_root2.handle().into(),
        );
    }
}

// ──────────────────────────────────────────────────────────────────────
// Secure server listen / close — uWS App<true> (SSL)
// ──────────────────────────────────────────────────────────────────────

#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn http2_secure_server_listen(
    cx: *mut JSContext,
    argc: u32,
    vp: *mut JSVal,
) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;

    if argc < 2 || !(*args.get(0).ptr).is_object() {
        args.rval().set(UndefinedValue());
        return true;
    }

    let server_obj_val = *args.get(0).ptr;
    rooted!(&in(cx_ref) let server_obj = server_obj_val.to_object());

    let port: u16 = if (*args.get(1).ptr).is_int32() {
        (*args.get(1).ptr).to_int32() as u16
    } else if (*args.get(1).ptr).is_double() {
        (*args.get(1).ptr).to_double() as u16
    } else {
        3000
    };

    // host + callback picked by type (see http2_server_listen).
    let mut _host: Option<String> = None;
    let mut callback: Option<*mut JSObject> = None;
    for i in 2..(argc as usize) {
        let v = *args.get(i as u32).ptr;
        if v.is_string() && _host.is_none() {
            _host = Some(crate::js_to_rust_string(cx, v));
        } else if v.is_object() && callback.is_none() {
            rooted!(&in(cx_ref) let cb = v.to_object());
            callback = Some(cb.get());
        }
    }

    // Extract TLS options from server._options
    let mut pem_key = String::new();
    let mut pem_cert = String::new();

    let mut opts_val = UndefinedValue();
    JS_GetProperty(
        cx,
        server_obj.handle().into(),
        c"_options".as_ptr(),
        MutableHandle::<Value> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut opts_val,
        },
    );
    if opts_val.is_object() {
        rooted!(&in(cx_ref) let opts_root = opts_val.to_object());

        // Extract key
        let mut key_val = UndefinedValue();
        JS_GetProperty(
            cx,
            opts_root.handle().into(),
            c"key".as_ptr(),
            MutableHandle::<Value> {
                _phantom_0: ::std::marker::PhantomData,
                ptr: &mut key_val,
            },
        );
        if key_val.is_string() {
            pem_key = crate::js_to_rust_string(cx, key_val);
        }

        // Extract cert
        let mut cert_val = UndefinedValue();
        JS_GetProperty(
            cx,
            opts_root.handle().into(),
            c"cert".as_ptr(),
            MutableHandle::<Value> {
                _phantom_0: ::std::marker::PhantomData,
                ptr: &mut cert_val,
            },
        );
        if cert_val.is_string() {
            pem_cert = crate::js_to_rust_string(cx, cert_val);
        }
    }

    // Get the JS stream handler
    let mut handler_val = UndefinedValue();
    let handler_mh = MutableHandle::<Value> {
        _phantom_0: ::std::marker::PhantomData,
        ptr: &mut handler_val,
    };
    JS_GetProperty(
        cx,
        server_obj.handle().into(),
        c"_onStreamHandler".as_ptr(),
        handler_mh,
    );

    rooted!(&in(cx_ref) let global = CurrentGlobalOrNull(cx));
    if global.get().is_null() || !handler_val.is_object() {
        let msg = ZBox::from_bytes("http2.createSecureServer requires a stream handler".as_bytes());
        JS_ReportErrorUTF8(cx, c"%s".as_ptr(), msg.as_ptr());
        return false;
    }

    // Create uWS App<true> (SSL) with TLS options
    let mut ssl_opts = BunSocketContextOptions::default();
    let key_cstr;
    let cert_cstr;
    let key_ptr;
    let cert_ptr;
    if !pem_key.is_empty() && !pem_cert.is_empty() {
        key_cstr = ::std::ffi::CString::new(pem_key).unwrap_or_default();
        cert_cstr = ::std::ffi::CString::new(pem_cert).unwrap_or_default();
        key_ptr = key_cstr.as_ptr();
        cert_ptr = cert_cstr.as_ptr();
        ssl_opts.key = &key_ptr as *const *const i8;
        ssl_opts.key_count = 1;
        ssl_opts.cert = &cert_ptr as *const *const i8;
        ssl_opts.cert_count = 1;
    }

    let app_ptr = match App::<true>::create(&ssl_opts) {
        Some(p) => p,
        None => {
            let msg = format!("Failed to create HTTP/2 secure server on port {}", port);
            let c_msg = ZBox::from_bytes(msg.as_bytes());
            JS_ReportErrorUTF8(cx, c"%s".as_ptr(), c_msg.as_ptr());
            return false;
        }
    };

    // node:http2 framing parity — see the matching comment at the
    // `App::<false>` listen site (node-family `IsNodeHttp` semantics).
    // Safety: app_ptr is a live `*mut App<true>` from `App::create` above,
    // valid until `App::<true>::destroy`.
    unsafe { (*app_ptr).set_is_node_http(true) };

    // Allocate H2ServerUserData (reuse same struct for SSL; server object
    // registered for the session-style 'stream' emission).
    rooted!(&in(cx_ref) let handler_root = handler_val.to_object());
    let ud = Box::new(H2ServerUserData::new(
        cx,
        global.get(),
        handler_root.get(),
        server_obj.get(),
    ));
    let ud_ptr = Box::into_raw(ud) as *mut ::std::ffi::c_void;

    // Register catch-all route — use the same handler (uWS handles TLS transparently)
    let safe_handler: Option<
        extern "C" fn(
            *mut bun_uws_sys::response::c::uws_res,
            *mut bun_uws_sys::Request,
            *mut ::std::ffi::c_void,
        ),
    > = unsafe {
        ::std::mem::transmute(Some(
            uws_h2_route_handler
                as unsafe extern "C" fn(
                    *mut bun_uws_sys::response::c::uws_res,
                    *mut bun_uws_sys::Request,
                    *mut ::std::ffi::c_void,
                ),
        ))
    };
    (*app_ptr).any(b"/*", safe_handler, ud_ptr);

    // Store ud pointer
    {
        let ud_val = PrivateValue(ud_ptr as *const core::ffi::c_void);
        rooted!(&in(cx_ref) let udv = ud_val);
        JS_DefineProperty(
            cx,
            server_obj.handle().into(),
            c"_udPtr".as_ptr(),
            udv.handle().into(),
            0,
        );
    }

    // Listen — the JS-facing 'listening' event + user callback fire from
    // uws_h2_listen_callback when the socket actually binds.
    let listen_id = NEXT_SERVER_ID.fetch_add(1, Ordering::Relaxed);
    let cb_key = format!("http2_listen_{}_cb", listen_id);
    let listen_server_key = format!("http2_listen_{}_server", listen_id);
    if let Some(cb) = callback {
        gc_store_insert_ns(cx, "http2", &cb_key, cb);
    }
    gc_store_insert_ns(cx, "http2", &listen_server_key, server_obj.get());
    let listen_state = Box::new(H2ListenState {
        cx,
        cb_key,
        server_key: listen_server_key,
    });
    let listen_state_ptr = Box::into_raw(listen_state) as *mut ::std::ffi::c_void;

    let safe_listen_cb: extern "C" fn(
        *mut bun_uws_sys::listen_socket::ListenSocket,
        *mut ::std::ffi::c_void,
    ) = unsafe {
        ::std::mem::transmute(
            uws_h2_listen_callback
                as unsafe extern "C" fn(
                    *mut bun_uws_sys::listen_socket::ListenSocket,
                    *mut ::std::ffi::c_void,
                ),
        )
    };
    (*app_ptr).listen(port as i32, safe_listen_cb, listen_state_ptr);

    // Store app pointer (as App<true>)
    {
        let app_ptr_val = PrivateValue(app_ptr as *const core::ffi::c_void);
        rooted!(&in(cx_ref) let apv = app_ptr_val);
        JS_DefineProperty(
            cx,
            server_obj.handle().into(),
            c"_sslAppPtr".as_ptr(),
            apv.handle().into(),
            0,
        );
    }

    rooted!(&in(cx_ref) let port_root = Int32Value(port as i32));
    JS_DefineProperty(
        cx,
        server_obj.handle().into(),
        c"_listeningPort".as_ptr(),
        port_root.handle().into(),
        JSPROP_ENUMERATE as u32,
    );

    rooted!(&in(cx_ref) let listening_root = BooleanValue(true));
    JS_DefineProperty(
        cx,
        server_obj.handle().into(),
        c"listening".as_ptr(),
        listening_root.handle().into(),
        JSPROP_ENUMERATE as u32,
    );

    register_active_h2_ssl_app(app_ptr);

    args.rval().set(UndefinedValue());
    true
}

#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn http2_secure_server_close(
    cx: *mut JSContext,
    argc: u32,
    vp: *mut JSVal,
) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;

    if argc < 1 || !(*args.get(0).ptr).is_object() {
        args.rval().set(UndefinedValue());
        return true;
    }

    let server_obj_val = *args.get(0).ptr;
    rooted!(&in(cx_ref) let server_obj = server_obj_val.to_object());

    let callback = if argc > 1 && (*args.get(1).ptr).is_object() {
        rooted!(&in(cx_ref) let cb = (*args.get(1).ptr).to_object());
        Some(cb.get())
    } else {
        None
    };

    // Close the SSL App
    {
        rooted!(&in(cx_ref) let obj = server_obj.get());
        let mut app_ptr_val = UndefinedValue();
        JS_GetProperty(
            cx,
            obj.handle().into(),
            c"_sslAppPtr".as_ptr(),
            MutableHandle::<Value> {
                _phantom_0: ::std::marker::PhantomData,
                ptr: &mut app_ptr_val,
            },
        );
        let app_ptr = if val_is_private(&app_ptr_val) {
            app_ptr_val.to_private() as *mut App<true>
        } else {
            core::ptr::null_mut()
        };
        if !app_ptr.is_null() {
            (*app_ptr).close();
            App::<true>::destroy(app_ptr);
            unregister_active_h2_ssl_app(app_ptr);
            rooted!(&in(cx_ref) let undef_root = UndefinedValue());
            JS_SetProperty(
                cx,
                obj.handle().into(),
                c"_sslAppPtr".as_ptr(),
                undef_root.handle().into(),
            );
        }
    }

    // Cleanup H2ServerUserData
    {
        rooted!(&in(cx_ref) let obj = server_obj.get());
        let mut ud_ptr_val = UndefinedValue();
        JS_GetProperty(
            cx,
            obj.handle().into(),
            c"_udPtr".as_ptr(),
            MutableHandle::<Value> {
                _phantom_0: ::std::marker::PhantomData,
                ptr: &mut ud_ptr_val,
            },
        );
        let ud_ptr = if val_is_private(&ud_ptr_val) {
            ud_ptr_val.to_private() as *mut H2ServerUserData
        } else {
            core::ptr::null_mut()
        };
        if !ud_ptr.is_null() {
            let ud = Box::from_raw(ud_ptr);
            ud.cleanup();
            rooted!(&in(cx_ref) let undef_root2 = UndefinedValue());
            JS_SetProperty(
                cx,
                obj.handle().into(),
                c"_udPtr".as_ptr(),
                undef_root2.handle().into(),
            );
        }
    }

    if let Some(cb) = callback {
        rooted!(&in(cx_ref) let global = CurrentGlobalOrNull(cx));
        if !global.get().is_null() {
            rooted!(&in(cx_ref) let fval_root = ObjectValue(cb));
            let mut rval = UndefinedValue();
            let rval_h = MutableHandle::<Value> {
                _phantom_0: ::std::marker::PhantomData,
                ptr: &mut rval,
            };
            JS_CallFunctionValue(
                cx,
                global.handle().into(),
                fval_root.handle().into(),
                &HandleValueArray::empty(),
                rval_h,
            );
            JS_ClearPendingException(cx);
        }
    }

    args.rval().set(UndefinedValue());
    true
}

// ──────────────────────────────────────────────────────────────────────
// JS-facing server listen/close (called when IIFE constructors are not
// available — fallback path)
// ──────────────────────────────────────────────────────────────────────

#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn http2_server_listen_js(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    // Delegate to the native __http2_server_listen
    let args = CallArgs::from_vp(vp, argc);
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;

    let this = args.thisv();
    rooted!(&in(cx_ref) let server_obj = this.to_object());

    let port: u16 = if argc > 0 {
        let v = *args.get(0).ptr;
        if v.is_int32() {
            v.to_int32() as u16
        } else if v.is_double() {
            v.to_double() as u16
        } else {
            3000
        }
    } else {
        3000
    };

    let callback = if argc > 1 && (*args.get(1).ptr).is_object() {
        rooted!(&in(cx_ref) let cb = (*args.get(1).ptr).to_object());
        Some(cb.get())
    } else if argc > 0 && (*args.get(0).ptr).is_object() {
        rooted!(&in(cx_ref) let cb = (*args.get(0).ptr).to_object());
        Some(cb.get())
    } else {
        None
    };

    // Create uWS App<false>
    let opts = BunSocketContextOptions::default();
    let app_ptr = match App::<false>::create(&opts) {
        Some(p) => p,
        None => {
            let msg = format!("Failed to create HTTP/2 server on port {}", port);
            let c_msg = ZBox::from_bytes(msg.as_bytes());
            JS_ReportErrorUTF8(cx, c"%s".as_ptr(), c_msg.as_ptr());
            return false;
        }
    };

    // node:http2 framing parity — see the matching comment at the
    // `App::<false>` listen site (node-family `IsNodeHttp` semantics).
    // Safety: app_ptr is a live `*mut App<false>` from `App::create` above,
    // valid until `App::<false>::destroy`.
    unsafe { (*app_ptr).set_is_node_http(true) };

    // Get handler
    let mut handler_val = UndefinedValue();
    JS_GetProperty(
        cx,
        server_obj.handle().into(),
        c"_onStreamHandler".as_ptr(),
        MutableHandle::<Value> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut handler_val,
        },
    );

    rooted!(&in(cx_ref) let global = CurrentGlobalOrNull(cx));
    if global.get().is_null() || !handler_val.is_object() {
        App::<false>::destroy(app_ptr);
        args.rval().set(ObjectValue(server_obj.get()));
        return true;
    }

    rooted!(&in(cx_ref) let handler_root = handler_val.to_object());
    let ud = Box::new(H2ServerUserData::new(cx, global.get(), handler_root.get(), server_obj.get()));
    let ud_ptr = Box::into_raw(ud) as *mut ::std::ffi::c_void;

    let safe_handler: Option<
        extern "C" fn(
            *mut bun_uws_sys::response::c::uws_res,
            *mut bun_uws_sys::Request,
            *mut ::std::ffi::c_void,
        ),
    > = unsafe {
        ::std::mem::transmute(Some(
            uws_h2_route_handler
                as unsafe extern "C" fn(
                    *mut bun_uws_sys::response::c::uws_res,
                    *mut bun_uws_sys::Request,
                    *mut ::std::ffi::c_void,
                ),
        ))
    };
    (*app_ptr).any(b"/*", safe_handler, ud_ptr);

    {
        let ud_val = PrivateValue(ud_ptr as *const core::ffi::c_void);
        rooted!(&in(cx_ref) let udv = ud_val);
        JS_DefineProperty(
            cx,
            server_obj.handle().into(),
            c"_udPtr".as_ptr(),
            udv.handle().into(),
            0,
        );
    }

    let safe_listen_cb: extern "C" fn(
        *mut bun_uws_sys::listen_socket::ListenSocket,
        *mut ::std::ffi::c_void,
    ) = unsafe {
        ::std::mem::transmute(
            uws_h2_listen_callback
                as unsafe extern "C" fn(
                    *mut bun_uws_sys::listen_socket::ListenSocket,
                    *mut ::std::ffi::c_void,
                ),
        )
    };
    (*app_ptr).listen(port as i32, safe_listen_cb, core::ptr::null_mut());

    {
        let app_ptr_val = PrivateValue(app_ptr as *const core::ffi::c_void);
        rooted!(&in(cx_ref) let apv = app_ptr_val);
        JS_DefineProperty(
            cx,
            server_obj.handle().into(),
            c"_appPtr".as_ptr(),
            apv.handle().into(),
            0,
        );
    }

    rooted!(&in(cx_ref) let port_root = Int32Value(port as i32));
    JS_DefineProperty(
        cx,
        server_obj.handle().into(),
        c"_listeningPort".as_ptr(),
        port_root.handle().into(),
        JSPROP_ENUMERATE as u32,
    );

    rooted!(&in(cx_ref) let listening_root = BooleanValue(true));
    JS_DefineProperty(
        cx,
        server_obj.handle().into(),
        c"listening".as_ptr(),
        listening_root.handle().into(),
        JSPROP_ENUMERATE as u32,
    );

    register_active_h2_app(app_ptr);

    if let Some(cb) = callback {
        rooted!(&in(cx_ref) let fval_root = ObjectValue(cb));
        let mut rval = UndefinedValue();
        let rval_h = MutableHandle::<Value> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut rval,
        };
        JS_CallFunctionValue(
            cx,
            global.handle().into(),
            fval_root.handle().into(),
            &HandleValueArray::empty(),
            rval_h,
        );
        JS_ClearPendingException(cx);
    }

    args.rval().set(ObjectValue(server_obj.get()));
    true
}

#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn http2_server_close_js(cx: *mut JSContext, _argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, _argc);
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;

    let this = args.thisv();
    rooted!(&in(cx_ref) let server_obj = this.to_object());

    close_h2_server(cx, cx_ref, server_obj.get(), false);

    args.rval().set(ObjectValue(server_obj.get()));
    true
}

#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn http2_secure_server_listen_js(
    cx: *mut JSContext,
    argc: u32,
    vp: *mut JSVal,
) -> bool {
    // Delegate to the native __http2_secure_server_listen
    let args = CallArgs::from_vp(vp, argc);
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;

    let this = args.thisv();
    rooted!(&in(cx_ref) let server_obj = this.to_object());

    let port: u16 = if argc > 0 {
        let v = *args.get(0).ptr;
        if v.is_int32() {
            v.to_int32() as u16
        } else if v.is_double() {
            v.to_double() as u16
        } else {
            3000
        }
    } else {
        3000
    };

    let callback = if argc > 1 && (*args.get(1).ptr).is_object() {
        rooted!(&in(cx_ref) let cb = (*args.get(1).ptr).to_object());
        Some(cb.get())
    } else {
        None
    };

    // Extract TLS options
    let mut pem_key = String::new();
    let mut pem_cert = String::new();
    let mut opts_val = UndefinedValue();
    JS_GetProperty(
        cx,
        server_obj.handle().into(),
        c"_options".as_ptr(),
        MutableHandle::<Value> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut opts_val,
        },
    );
    if opts_val.is_object() {
        rooted!(&in(cx_ref) let opts_root = opts_val.to_object());
        let mut key_val = UndefinedValue();
        JS_GetProperty(
            cx,
            opts_root.handle().into(),
            c"key".as_ptr(),
            MutableHandle::<Value> {
                _phantom_0: ::std::marker::PhantomData,
                ptr: &mut key_val,
            },
        );
        if key_val.is_string() {
            pem_key = crate::js_to_rust_string(cx, key_val);
        }
        let mut cert_val = UndefinedValue();
        JS_GetProperty(
            cx,
            opts_root.handle().into(),
            c"cert".as_ptr(),
            MutableHandle::<Value> {
                _phantom_0: ::std::marker::PhantomData,
                ptr: &mut cert_val,
            },
        );
        if cert_val.is_string() {
            pem_cert = crate::js_to_rust_string(cx, cert_val);
        }
    }

    // Get handler
    let mut handler_val = UndefinedValue();
    JS_GetProperty(
        cx,
        server_obj.handle().into(),
        c"_onStreamHandler".as_ptr(),
        MutableHandle::<Value> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut handler_val,
        },
    );

    rooted!(&in(cx_ref) let global = CurrentGlobalOrNull(cx));
    if global.get().is_null() || !handler_val.is_object() {
        args.rval().set(ObjectValue(server_obj.get()));
        return true;
    }

    // Create uWS App<true>
    let mut ssl_opts = BunSocketContextOptions::default();
    let key_cstr;
    let cert_cstr;
    let key_ptr;
    let cert_ptr;
    if !pem_key.is_empty() && !pem_cert.is_empty() {
        key_cstr = ::std::ffi::CString::new(pem_key).unwrap_or_default();
        cert_cstr = ::std::ffi::CString::new(pem_cert).unwrap_or_default();
        key_ptr = key_cstr.as_ptr();
        cert_ptr = cert_cstr.as_ptr();
        ssl_opts.key = &key_ptr as *const *const i8;
        ssl_opts.key_count = 1;
        ssl_opts.cert = &cert_ptr as *const *const i8;
        ssl_opts.cert_count = 1;
    }

    let app_ptr = match App::<true>::create(&ssl_opts) {
        Some(p) => p,
        None => {
            let msg = format!("Failed to create HTTP/2 secure server on port {}", port);
            let c_msg = ZBox::from_bytes(msg.as_bytes());
            JS_ReportErrorUTF8(cx, c"%s".as_ptr(), c_msg.as_ptr());
            return false;
        }
    };

    // node:http2 framing parity — see the matching comment at the
    // `App::<false>` listen site (node-family `IsNodeHttp` semantics).
    // Safety: app_ptr is a live `*mut App<true>` from `App::create` above,
    // valid until `App::<true>::destroy`.
    unsafe { (*app_ptr).set_is_node_http(true) };

    rooted!(&in(cx_ref) let handler_root = handler_val.to_object());
    let ud = Box::new(H2ServerUserData::new(cx, global.get(), handler_root.get(), server_obj.get()));
    let ud_ptr = Box::into_raw(ud) as *mut ::std::ffi::c_void;

    let safe_handler: Option<
        extern "C" fn(
            *mut bun_uws_sys::response::c::uws_res,
            *mut bun_uws_sys::Request,
            *mut ::std::ffi::c_void,
        ),
    > = unsafe {
        ::std::mem::transmute(Some(
            uws_h2_route_handler
                as unsafe extern "C" fn(
                    *mut bun_uws_sys::response::c::uws_res,
                    *mut bun_uws_sys::Request,
                    *mut ::std::ffi::c_void,
                ),
        ))
    };
    (*app_ptr).any(b"/*", safe_handler, ud_ptr);

    {
        let ud_val = PrivateValue(ud_ptr as *const core::ffi::c_void);
        rooted!(&in(cx_ref) let udv = ud_val);
        JS_DefineProperty(
            cx,
            server_obj.handle().into(),
            c"_udPtr".as_ptr(),
            udv.handle().into(),
            0,
        );
    }

    let safe_listen_cb: extern "C" fn(
        *mut bun_uws_sys::listen_socket::ListenSocket,
        *mut ::std::ffi::c_void,
    ) = unsafe {
        ::std::mem::transmute(
            uws_h2_listen_callback
                as unsafe extern "C" fn(
                    *mut bun_uws_sys::listen_socket::ListenSocket,
                    *mut ::std::ffi::c_void,
                ),
        )
    };
    (*app_ptr).listen(port as i32, safe_listen_cb, core::ptr::null_mut());

    {
        let app_ptr_val = PrivateValue(app_ptr as *const core::ffi::c_void);
        rooted!(&in(cx_ref) let apv = app_ptr_val);
        JS_DefineProperty(
            cx,
            server_obj.handle().into(),
            c"_sslAppPtr".as_ptr(),
            apv.handle().into(),
            0,
        );
    }

    rooted!(&in(cx_ref) let port_root = Int32Value(port as i32));
    JS_DefineProperty(
        cx,
        server_obj.handle().into(),
        c"_listeningPort".as_ptr(),
        port_root.handle().into(),
        JSPROP_ENUMERATE as u32,
    );

    rooted!(&in(cx_ref) let listening_root = BooleanValue(true));
    JS_DefineProperty(
        cx,
        server_obj.handle().into(),
        c"listening".as_ptr(),
        listening_root.handle().into(),
        JSPROP_ENUMERATE as u32,
    );

    register_active_h2_ssl_app(app_ptr);

    if let Some(cb) = callback {
        rooted!(&in(cx_ref) let fval_root = ObjectValue(cb));
        let mut rval = UndefinedValue();
        let rval_h = MutableHandle::<Value> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut rval,
        };
        JS_CallFunctionValue(
            cx,
            global.handle().into(),
            fval_root.handle().into(),
            &HandleValueArray::empty(),
            rval_h,
        );
        JS_ClearPendingException(cx);
    }

    args.rval().set(ObjectValue(server_obj.get()));
    true
}

#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn http2_secure_server_close_js(
    cx: *mut JSContext,
    _argc: u32,
    vp: *mut JSVal,
) -> bool {
    let args = CallArgs::from_vp(vp, _argc);
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;

    let this = args.thisv();
    rooted!(&in(cx_ref) let server_obj = this.to_object());

    // Close the SSL App
    {
        let mut app_ptr_val = UndefinedValue();
        JS_GetProperty(
            cx,
            server_obj.handle().into(),
            c"_sslAppPtr".as_ptr(),
            MutableHandle::<Value> {
                _phantom_0: ::std::marker::PhantomData,
                ptr: &mut app_ptr_val,
            },
        );
        let app_ptr = if val_is_private(&app_ptr_val) {
            app_ptr_val.to_private() as *mut App<true>
        } else {
            core::ptr::null_mut()
        };
        if !app_ptr.is_null() {
            (*app_ptr).close();
            App::<true>::destroy(app_ptr);
            unregister_active_h2_ssl_app(app_ptr);
            rooted!(&in(cx_ref) let undef_root = UndefinedValue());
            JS_SetProperty(
                cx,
                server_obj.handle().into(),
                c"_sslAppPtr".as_ptr(),
                undef_root.handle().into(),
            );
        }
    }

    // Cleanup H2ServerUserData
    {
        let mut ud_ptr_val = UndefinedValue();
        JS_GetProperty(
            cx,
            server_obj.handle().into(),
            c"_udPtr".as_ptr(),
            MutableHandle::<Value> {
                _phantom_0: ::std::marker::PhantomData,
                ptr: &mut ud_ptr_val,
            },
        );
        let ud_ptr = if val_is_private(&ud_ptr_val) {
            ud_ptr_val.to_private() as *mut H2ServerUserData
        } else {
            core::ptr::null_mut()
        };
        if !ud_ptr.is_null() {
            let ud = Box::from_raw(ud_ptr);
            ud.cleanup();
            rooted!(&in(cx_ref) let undef_root2 = UndefinedValue());
            JS_SetProperty(
                cx,
                server_obj.handle().into(),
                c"_udPtr".as_ptr(),
                undef_root2.handle().into(),
            );
        }
    }

    args.rval().set(ObjectValue(server_obj.get()));
    true
}

// ──────────────────────────────────────────────────────────────────────
// __http2_fetch — client-side fetch bridge (called from JS IIFE)
// ──────────────────────────────────────────────────────────────────────

#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn http2_fetch(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);

    let url = if argc > 0 && (*args.get(0).ptr).is_string() {
        crate::js_to_rust_string(cx, *args.get(0).ptr)
    } else {
        String::new()
    };

    let method = if argc > 1 && (*args.get(1).ptr).is_string() {
        crate::js_to_rust_string(cx, *args.get(1).ptr)
    } else {
        "GET".to_string()
    };

    let headers_json = if argc > 2 && (*args.get(2).ptr).is_string() {
        crate::js_to_rust_string(cx, *args.get(2).ptr)
    } else {
        "{}".to_string()
    };

    // Body (arg 3): string (UTF-8) or Buffer/TypedArray/DataView/ArrayBuffer —
    // byte-exact via the house extractor (same contract as node_http's
    // http_request / node_https's https_request). The previous string-only
    // read silently emptied every binary request body; the JS layer's
    // `String(body)` coercion also turned Buffers into "72,101,108".
    // Unrecognized objects fail loudly.
    let body_bytes: Option<Vec<u8>> = if argc > 3 {
        let v = *args.get(3).ptr;
        if v.is_undefined() || v.is_null() {
            None
        } else if v.is_string() {
            let s = crate::js_to_rust_string(cx, v);
            (!s.is_empty()).then(|| s.into_bytes())
        } else if v.is_object() {
            match crate::node_buffer::collect_byte_view(cx, v) {
                Some(bytes) => (!bytes.is_empty()).then_some(bytes),
                None => {
                    JS_ReportErrorUTF8(
                        cx,
                        c"%s".as_ptr(),
                        c"http2: request body must be a string, Buffer, TypedArray or ArrayBuffer"
                            .as_ptr(),
                    );
                    return false;
                }
            }
        } else {
            JS_ReportErrorUTF8(
                cx,
                c"%s".as_ptr(),
                c"http2: request body must be a string, Buffer, TypedArray or ArrayBuffer".as_ptr(),
            );
            return false;
        }
    } else {
        None
    };

    // Parse headers from JSON
    let headers_map: ::std::collections::HashMap<String, String> =
        serde_json::from_str(&headers_json).unwrap_or_default();
    let headers: Vec<(String, String)> = headers_map
        .into_iter()
        .filter(|(k, _)| !k.starts_with(':')) // Strip pseudo-headers
        .collect();

    // Resolve method
    let bun_method = match method.as_str() {
        "POST" => bun_http::Method::POST,
        "PUT" => bun_http::Method::PUT,
        "DELETE" => bun_http::Method::DELETE,
        "PATCH" => bun_http::Method::PATCH,
        "HEAD" => bun_http::Method::HEAD,
        "OPTIONS" => bun_http::Method::OPTIONS,
        _ => bun_http::Method::GET,
    };

    // Create a pending Promise and schedule async fetch
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;

    rooted!(&in(cx_ref) let null_global = ::std::ptr::null_mut::<JSObject>());
    rooted!(&in(cx_ref) let promise = unsafe {
        mozjs_sys::jsapi::JS::NewPromiseObject(cx, null_global.handle().into())
    });
    if promise.get().is_null() {
        // Fail closed: without the Promise there is no honest result shape.
        // (The old path returned a statusCode:0 placeholder JSON here — a
        // silent-fake the JS layer then delivered as a real response.)
        JS_ReportErrorUTF8(
            cx,
            c"%s".as_ptr(),
            c"http2: failed to create fetch promise".as_ptr(),
        );
        return false;
    }

    let promise_obj = promise.get();
    let promise_val = ObjectValue(promise_obj);

    // Schedule async fetch — the returned Promise resolves with the realm's
    // real WHATWG Response (status/headers/arrayBuffer), exactly like the
    // node:http / node:https client transports. The JS layer consumes it
    // (response headers → 'response', arrayBuffer → Buffer 'data' chunk).
    unsafe {
        crate::fetch_async::start(
            cx,
            promise_val,
            None, // No stealth profile for plain http2
            bun_method,
            url,
            headers,
            body_bytes,
        );
    }

    args.rval().set(promise_val);
    true
}

// ──────────────────────────────────────────────────────────────────────
// Property helpers
// ──────────────────────────────────────────────────────────────────────

#[allow(unsafe_op_in_unsafe_fn)]
unsafe fn define_int_prop(
    cx: &mut mozjs::context::JSContext,
    obj_ptr: *mut JSObject,
    name: &str,
    val: i32,
) {
    let c_name = ZBox::from_bytes(name.as_bytes());
    let raw_cx = cx.raw_cx();
    rooted!(&in(cx) let obj = obj_ptr);
    rooted!(&in(cx) let v = Int32Value(val));
    JS_DefineProperty(
        raw_cx,
        obj.handle().into(),
        c_name.as_ptr(),
        v.handle().into(),
        JSPROP_ENUMERATE as u32,
    );
}

// ──────────────────────────────────────────────────────────────────────
// Unit tests
// ──────────────────────────────────────────────────────────────────────

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

    #[test]
    fn has_active_servers_false_initially() {
        ACTIVE_H2_APPS.with(|s| s.borrow_mut().clear());
        ACTIVE_H2_SSL_APPS.with(|s| s.borrow_mut().clear());
        assert!(!has_active_servers());
    }

    #[test]
    fn register_unregister_h2_app() {
        ACTIVE_H2_APPS.with(|s| s.borrow_mut().clear());
        let sentinel: *mut App<false> = 0x1000 as *mut App<false>;
        unsafe {
            register_active_h2_app(sentinel);
            assert!(has_active_servers());
            register_active_h2_app(sentinel); // idempotent
            let count = ACTIVE_H2_APPS.with(|s| s.borrow().len());
            assert_eq!(count, 1);
            unregister_active_h2_app(sentinel);
            assert!(!has_active_servers());
        }
    }

    #[test]
    fn register_unregister_h2_ssl_app() {
        ACTIVE_H2_SSL_APPS.with(|s| s.borrow_mut().clear());
        let sentinel: *mut App<true> = 0x2000 as *mut App<true>;
        unsafe {
            register_active_h2_ssl_app(sentinel);
            assert!(has_active_servers());
            unregister_active_h2_ssl_app(sentinel);
            assert!(!has_active_servers());
        }
    }

    #[test]
    fn null_app_is_noop() {
        ACTIVE_H2_APPS.with(|s| s.borrow_mut().clear());
        ACTIVE_H2_SSL_APPS.with(|s| s.borrow_mut().clear());
        unsafe {
            register_active_h2_app(core::ptr::null_mut());
            register_active_h2_ssl_app(core::ptr::null_mut());
            assert!(!has_active_servers());
            unregister_active_h2_app(core::ptr::null_mut());
            unregister_active_h2_ssl_app(core::ptr::null_mut());
            assert!(!has_active_servers());
        }
    }

    #[test]
    fn next_session_id_monotonic() {
        let id1 = NEXT_SESSION_ID.fetch_add(1, Ordering::SeqCst);
        let id2 = NEXT_SESSION_ID.fetch_add(1, Ordering::SeqCst);
        assert!(id2 > id1);
    }

    #[test]
    fn next_server_id_monotonic() {
        let id1 = NEXT_SERVER_ID.fetch_add(1, Ordering::Relaxed);
        let id2 = NEXT_SERVER_ID.fetch_add(1, Ordering::Relaxed);
        assert!(id2 > id1);
    }

    #[test]
    fn h2_server_user_data_keys_namespaced() {
        let key1 = format!("http2_server_{}_global", 1);
        let key2 = format!("http2_server_{}_handler", 1);
        assert!(key1.starts_with("http2_server_"));
        assert!(key1.ends_with("_global"));
        assert!(key2.starts_with("http2_server_"));
        assert!(key2.ends_with("_handler"));
        assert_ne!(key1, key2);
    }

    #[test]
    fn h2_server_user_data_null_cx_returns_none() {
        let ud = H2ServerUserData {
            cx: ::std::ptr::null_mut(),
            global_key: "http2_server_999_global".to_string(),
            handler_key: "http2_server_999_handler".to_string(),
            server_key: "http2_server_999_server".to_string(),
        };
        assert!(ud.global().is_none());
        assert!(ud.handler().is_none());
        assert!(ud.server_obj().is_none());
    }

    #[test]
    fn h2_server_user_data_cleanup_no_panic() {
        let ud = H2ServerUserData {
            cx: ::std::ptr::null_mut(),
            global_key: "http2_server_998_global".to_string(),
            handler_key: "http2_server_998_handler".to_string(),
            server_key: "http2_server_998_server".to_string(),
        };
        ud.cleanup(); // Must not panic
    }

    #[test]
    fn val_is_private_undefined() {
        let v = UndefinedValue();
        assert!(!val_is_private(&v));
    }

    #[test]
    fn val_is_private_int32() {
        let v = Int32Value(42);
        assert!(!val_is_private(&v));
    }

    // HTTP/2 constants verification
    #[test]
    fn nghttp2_error_codes() {
        assert_eq!(NGHTTP2_NO_ERROR, 0);
        assert_eq!(NGHTTP2_PROTOCOL_ERROR, 1);
        assert_eq!(NGHTTP2_INTERNAL_ERROR, 2);
        assert_eq!(NGHTTP2_CANCEL, 8);
        assert_eq!(NGHTTP2_HTTP_1_1_REQUIRED, 13);
    }

    #[test]
    fn default_settings_values() {
        assert_eq!(DEFAULT_SETTINGS_HEADER_TABLE_SIZE, 4096);
        assert_eq!(DEFAULT_SETTINGS_ENABLE_PUSH, 0);
        assert_eq!(DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE, 65535);
        assert_eq!(DEFAULT_SETTINGS_MAX_FRAME_SIZE, 16384);
    }

    // Use constants as const values for test access
    const NGHTTP2_NO_ERROR: i32 = 0;
    const NGHTTP2_PROTOCOL_ERROR: i32 = 1;
    const NGHTTP2_INTERNAL_ERROR: i32 = 2;
    const NGHTTP2_CANCEL: i32 = 8;
    const NGHTTP2_HTTP_1_1_REQUIRED: i32 = 13;
    const DEFAULT_SETTINGS_HEADER_TABLE_SIZE: i32 = 4096;
    const DEFAULT_SETTINGS_ENABLE_PUSH: i32 = 0;
    const DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE: i32 = 65535;
    const DEFAULT_SETTINGS_MAX_FRAME_SIZE: i32 = 16384;
}