nsh-js 0.8.0

QuickJS host: runtime setup, host APIs, op decoding and bytecode.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
use std::{
    cell::{Cell, RefCell},
    rc::Rc,
    sync::{
        Arc,
        atomic::{AtomicBool, Ordering},
    },
    time::Duration,
};

use nsh_core::{
    EventKind, EventPayload, NodeId, Op, PayloadValue, TouchPhase, js::Limits,
    platform::Environment, selection::ListItemKey, time::Instant,
};
use rquickjs::{
    AsyncRuntime, CatchResultExt, Ctx, Function, Module, Persistent, Promise, Value, function::Opt,
    qjs,
};

use crate::{
    console,
    error::JsError,
    net::{FetchEvent, NetworkQueue, RequestId},
    protocol::Warnings,
    rejections::Rejections,
    sandbox::{self, Budget, Phase},
    standard::scheduler::{Context, Scheduler},
    timers::Timers,
    web,
};

/// Receives JS errors: uncaught exceptions ([`Host::set_error_handler`])
/// or unhandled promise rejections ([`Host::set_rejection_handler`]).
pub type ErrorHandler = Box<dyn Fn(&JsError)>;
type ExitHandler = Rc<dyn Fn(i32)>;

/// State shared between the host and the native functions installed in JS.
/// Only touched on the JS thread.
#[derive(Default)]
pub(crate) struct Shared {
    pub(crate) ops: RefCell<Vec<Op>>,
    /// Native nodes collected since the last [`Host::take_ops`] (their
    /// finalizers queue here: the op queue may be borrowed meanwhile).
    pub(crate) releases: RefCell<Vec<NodeId>>,
    /// Native animation nodes and composites collected meanwhile.
    pub(crate) animation_releases: RefCell<Vec<nsh_core::animation::AnimationOp>>,
    timers: RefCell<Timers>,
    /// Per-VM host delegate for capability-gated exit requests.
    pub(crate) system_exit_handler: RefCell<Option<ExitHandler>>,
    /// The embedding app's side of `nsh/host` (the engine's bridge).
    pub(crate) host_bridge: RefCell<Option<Rc<dyn nsh_core::host_channel::HostBridge>>>,
    pub(crate) system_websocket:
        RefCell<Option<std::sync::Arc<dyn nsh_core::websocket::WebSocketTransport>>>,
    /// What the host refuses the app's sockets and WebSockets with (a
    /// test's network); `None`: they connect.
    pub(crate) system_refuse_connections: RefCell<Option<nsh_core::element::RefuseConnections>>,
    /// Permissions and host-selected app directory for native system operations.
    pub(crate) system_access: RefCell<nsh_core::access::Access>,
    pub(crate) system_filesystem:
        RefCell<Option<std::sync::Arc<dyn nsh_core::filesystem::FileSystem>>>,
    pub(crate) system_updater: RefCell<Option<std::sync::Arc<dyn nsh_core::runtime::UpdaterHost>>>,
    /// The core's address (`UrlScheme.url()`).
    pub(crate) system_app_url: RefCell<nsh_core::url_scheme::AppUrlCell>,
    pub(crate) system_data_dir: RefCell<Option<std::path::PathBuf>>,
    /// Where the app's bundled (`asset:/…`) files are on disk: a packaged
    /// desktop app's own. `process.run` of an `asset:/…` program resolves
    /// it through this.
    pub(crate) system_asset_base: RefCell<Option<nsh_core::image::AssetBase>>,
    pub(crate) system_paths: RefCell<nsh_core::access::TrustedPaths>,
    /// The VM's counts of limited resources for Rust modules (`net`'s
    /// sockets), handed to their calls' `System`.
    pub(crate) system_quotas: nsh_core::element::Quotas,
    /// The VM's scheduler, for native transports that start its I/O runtime.
    #[cfg_attr(
        not(all(not(target_arch = "wasm32"), feature = "websocket")),
        allow(dead_code)
    )]
    pub(crate) scheduler: std::rc::Weak<Scheduler>,
    /// The VM's state of the runtime's Rust modules (`process`'s
    /// children), closed when the VM goes.
    pub(crate) system_locals: nsh_core::element::Locals,
    /// The lazy standard globals installed so far (bits of `standard::LAZY`).
    pub(crate) lazy_globals: Cell<u8>,
    /// Worker completion wakes the owning engine without polling.
    pub(crate) system_wake: RefCell<Option<Arc<dyn Fn() + Send + Sync>>>,
    pub(crate) warnings: RefCell<Warnings>,
    pub(crate) net: RefCell<NetworkQueue>,
    /// Requests whose response bodies were collected unread (finalizers
    /// queue them here; the next [`Host::take_network`] cancels them).
    pub(crate) dropped_fetches: RefCell<Vec<RequestId>>,
    /// Font assets imported by the app, not yet registered.
    pub(crate) fonts: RefCell<Vec<String>>,
    /// `requestAnimationFrame` callbacks waiting for the next frame.
    frames: RefCell<Vec<(u32, Persistent<Function<'static>>)>>,
    next_frame_id: std::cell::Cell<u32>,
    /// Measures one line of text for `measureText` (the engine's text
    /// engine).
    pub(crate) measurer: RefCell<Option<TextMeasurer>>,
    /// Lays one line out for `measureText`'s font extent.
    pub(crate) line_measurer: RefCell<Option<LineExtentMeasurer>>,
    /// The VM's limits.
    pub(crate) limits: Limits,
    /// Why the VM was stopped (out of memory, over a quota): no JS runs
    /// after that.
    pub(crate) fatal: RefCell<Option<String>>,
    /// Rejected promises without a handler, until the end of the turn.
    rejections: RefCell<Rejections>,
}

impl Shared {
    /// Stops the VM for `reason` (the first reason wins).
    pub(crate) fn stop(&self, reason: String) {
        self.fatal.borrow_mut().get_or_insert(reason);
    }
}

/// Measures the width of one line of `text` in `font`, in points.
pub type TextMeasurer =
    Box<dyn Fn(&nsh_core::canvas::CanvasFont, &str) -> nsh_core::geometry::Points>;

/// Lays one line of `text` in `font` out: the font's ascent and descent on
/// it, in points.
pub type LineExtentMeasurer = Box<
    dyn Fn(
        &nsh_core::canvas::CanvasFont,
        &str,
    ) -> (nsh_core::geometry::Points, nsh_core::geometry::Points),
>;

/// One QuickJS runtime + context with the nsh host APIs installed.
pub struct Host {
    // Field order matters: the context must drop before the runtime.
    cx: Context,
    rt: RefCell<Option<AsyncRuntime>>,
    scheduler: Rc<Scheduler>,
    /// Set by the heap's allocator when it refuses an allocation.
    exhausted: Arc<AtomicBool>,
    shared: Rc<Shared>,
    on_error: Option<ErrorHandler>,
    on_rejection: Option<ErrorHandler>,
    budget: Budget,
    evaluations: RefCell<Vec<Persistent<Promise<'static>>>>,
    entry_depth: Cell<usize>,
}

/// How a VM is set up.
#[derive(Debug, Clone, Default)]
pub struct HostOptions {
    /// Resource limits.
    pub limits: Limits,
    /// Removes `eval` and the function constructors and freezes the shared
    /// prototypes (see `sandbox`). Off for development bundles.
    pub harden: bool,
    /// The UI sets apps import as native modules
    /// (`nsh_base::registry()`, served as `nsh/base`, and an app's own).
    pub ui_sets: Vec<nsh_core::element::Registry>,
    /// The queue of the JS calls Rust posts (`Callback::post`,
    /// `call_async`): the engine hands the core the same one
    /// ([`nsh_core::Core::set_posts`]), which releases the calls posted
    /// during a synchronous call in order with the ops.
    pub posts: nsh_core::element::Posts,
    /// The URL relative request URLs (`fetch("/api")`, `new Request("x")`)
    /// resolve against: the page's on the web. `None` (native hosts):
    /// they are invalid, as there is no document they belong to.
    pub base_url: Option<String>,
}

impl Host {
    /// Creates a runtime with the default limits, not hardened, and installs
    /// `console`, timers and the op bridge.
    pub fn new() -> Result<Host, JsError> {
        Self::with_options(HostOptions::default())
    }

    /// Creates a runtime set up by `options` and installs `console`, timers
    /// and the op bridge.
    pub fn with_options(options: HostOptions) -> Result<Host, JsError> {
        let limits = options.limits;
        // The allocator enforces the heap limit (`set_memory_limit` does
        // nothing with one) and tells when it was reached.
        let (allocator, exhausted) = sandbox::HeapAllocator::new(limits.memory_bytes);
        let scheduler = Scheduler::new();
        let rt = AsyncRuntime::new_with_alloc(allocator)?;
        scheduler.ready(rt.set_loader(crate::modules::Resolver, crate::modules::Loader));
        // The engine thread is spawned with a larger stack; keep a margin.
        scheduler.ready(rt.set_max_stack_size(limits.stack_bytes));
        let budget = Budget::new(limits);
        scheduler.ready(rt.set_interrupt_handler(Some(budget.interrupt_handler(None))));
        let cx = Context::full(&rt, scheduler.clone())?;
        let shared = Rc::new(Shared {
            limits,
            scheduler: Rc::downgrade(&scheduler),
            ..Shared::default()
        });
        let tracked = shared.clone();
        scheduler.ready(rt.set_host_promise_rejection_tracker(Some(Box::new(
            move |cx, promise, reason, handled| {
                tracked
                    .rejections
                    .borrow_mut()
                    .track(&cx, promise, reason, handled);
            },
        ))));
        cx.with(|cx| {
            crate::state::install(&cx, shared.clone(), &options.ui_sets, options.posts.clone());
            web::web(cx.as_raw().as_ptr()).base_url = options
                .base_url
                .as_deref()
                .and_then(|u| url::Url::parse(u).ok());
            install(&cx, &shared)?;
            crate::standard::install(&cx)?;
            // Before hardening freezes the globals.
            crate::clock::install(&cx)?;
            if options.harden {
                sandbox::harden(&cx)?;
            }
            Ok(())
        })
        .map_err(|e| cx.with(|cx| JsError::from_engine(&cx, e)))?;
        Ok(Host {
            cx,
            rt: RefCell::new(Some(rt)),
            scheduler,
            exhausted,
            shared,
            on_error: None,
            on_rejection: None,
            budget,
            evaluations: RefCell::new(Vec::new()),
            entry_depth: Cell::new(0),
        })
    }

    /// Aborts running JS (with an uncatchable exception) once `stop` is
    /// set: an engine shutting down never waits for a long-running script.
    pub fn set_stop_flag(&self, stop: std::sync::Arc<std::sync::atomic::AtomicBool>) {
        if let Some(rt) = self.rt.borrow().as_ref() {
            self.scheduler
                .ready(rt.set_interrupt_handler(Some(self.budget.interrupt_handler(Some(stop)))));
        }
    }

    /// Why the VM was stopped, if it was: it ran out of memory, or the app
    /// went over a quota. No JS runs after that; the views stay as they are.
    pub fn fatal(&self) -> Option<String> {
        self.shared.fatal.borrow().clone()
    }

    /// Stops the VM (e.g. the core refused an op over a quota).
    pub fn stop(&self, reason: String) {
        self.shared.stop(reason);
        if self.entry_depth.get() == 0 {
            self.stop_work();
        }
    }

    /// The VM's limits.
    pub fn limits(&self) -> &Limits {
        self.budget.limits()
    }

    /// Runs `f` (a call into JS) within the budget of `phase`; `None` once
    /// the VM was stopped.
    fn guarded<R>(&self, phase: Phase, f: impl FnOnce() -> R) -> Option<R> {
        if self.shared.fatal.borrow().is_some() {
            if self.entry_depth.get() == 0 {
                self.stop_work();
            }
            return None;
        }
        self.entry_depth.set(self.entry_depth.get() + 1);
        let running = self.budget.run(phase);
        let result = f();
        drop(running);
        // The app may have caught running out (it is an `InternalError`):
        // the VM stops all the same.
        if self.exhausted.load(Ordering::Relaxed) && self.shared.fatal.borrow().is_none() {
            self.uncaught(&JsError::new("out of memory".to_owned()));
        }
        self.entry_depth.set(self.entry_depth.get() - 1);
        if self.entry_depth.get() == 0 && self.fatal().is_some() {
            self.stop_work();
        }
        Some(result)
    }

    /// Retire native work and JS together while retaining the core's rendered
    /// snapshot and already queued operations. Never called under a JS entry.
    fn stop_work(&self) {
        self.scheduler.disable();
        self.shared.system_wake.borrow_mut().take();
        self.shared.system_exit_handler.borrow_mut().take();
        self.evaluations.borrow_mut().clear();
        self.shared.timers.borrow_mut().clear();
        self.shared.frames.borrow_mut().clear();
        if self.cx.is_live() {
            self.cx.with(|cx| crate::state::uninstall(&cx));
            self.cx.retire();
        }
        // After the state, whose freeing may reject what waits on it;
        // the rejections' values go before the runtime.
        if let Some(rt) = self.rt.borrow().as_ref() {
            self.scheduler
                .ready(rt.set_host_promise_rejection_tracker(None));
        }
        self.shared.rejections.borrow_mut().clear();
        self.rt.borrow_mut().take();
    }

    /// What an error from a call means: an overrun budget or exhausted
    /// memory get a message saying so (exhausted memory also stops the VM).
    fn classify(&self, mut err: JsError) -> JsError {
        if let Some(trip) = self.budget.take_trip() {
            err.message = format!("{trip}\n{}", err.message);
        } else if self.exhausted.load(Ordering::Relaxed) {
            let reason = format!(
                "the script ran out of memory (the JS heap is limited to {} MB) and was stopped. \
                 Keep large data out of JS: load it in pages, or keep it on the native side \
                 (a server, a native module) and hand JS only what it shows.",
                self.budget.limits().memory_bytes >> 20
            );
            self.shared.stop(reason.clone());
            err.message = format!("{reason}\n{}", err.message);
        }
        err
    }

    /// The error for a call refused because the VM was stopped.
    fn stopped(&self) -> JsError {
        JsError::new(self.fatal().unwrap_or_default())
    }

    /// Sets what canvas `measureText` measures with.
    pub fn set_text_measurer(&mut self, measurer: TextMeasurer) {
        *self.shared.measurer.borrow_mut() = Some(measurer);
    }

    /// Sets what canvas `measureText`'s `fontBoundingBoxAscent` /
    /// `fontBoundingBoxDescent` lay the line out with (without it they are 0).
    pub fn set_line_extent_measurer(&mut self, measurer: LineExtentMeasurer) {
        *self.shared.line_measurer.borrow_mut() = Some(measurer);
    }

    /// Sets the handler for uncaught exceptions (in event handlers, timers and
    /// promise jobs). Without a handler they are logged.
    pub fn set_error_handler(&mut self, handler: ErrorHandler) {
        self.on_error = Some(handler);
    }

    /// Actual native module exports for declaration generation. This evaluates
    /// trusted module initializers only, without running user bundles or jobs.
    pub(crate) fn standard_exports(&self) -> Result<Vec<(String, Vec<String>)>, JsError> {
        self.guarded(Phase::Load, || {
            self.cx
                .with(|cx| {
                    crate::standard::NAMES
                        .iter()
                        .map(|name| {
                            let module = crate::modules::load_module(&cx, name)
                                .catch(&cx)
                                .map_err(JsError::caught)?;
                            let (module, promise) =
                                module.eval().catch(&cx).map_err(JsError::caught)?;
                            if let Some(result) = promise.result::<()>() {
                                result.catch(&cx).map_err(JsError::caught)?;
                            }
                            let namespace =
                                module.namespace().catch(&cx).map_err(JsError::caught)?;
                            let mut exports = namespace
                                .keys::<String>()
                                .collect::<rquickjs::Result<Vec<_>>>()
                                .catch(&cx)
                                .map_err(JsError::caught)?;
                            exports.sort();
                            Ok(((*name).to_owned(), exports))
                        })
                        .collect::<Result<Vec<(String, Vec<String>)>, JsError>>()
                })
                .map_err(|error| self.classify(error))
        })
        .unwrap_or_else(|| Err(self.stopped()))
    }

    /// Sets the handler for unhandled promise rejections: promises still
    /// rejected without a handler once a turn's jobs ran (as browsers
    /// report them). Without a handler they are logged (target `js`, level
    /// error), as `unhandled rejection: <reason>`.
    pub fn set_rejection_handler(&mut self, handler: ErrorHandler) {
        self.on_rejection = Some(handler);
    }

    /// Evaluates a bundle given as source.
    pub fn eval_source(&self, source: &str) -> Result<(), JsError> {
        self.guarded(Phase::Load, || {
            let promise = self
                .cx
                .with(|cx| -> Result<_, JsError> {
                    let module = Module::declare(cx.clone(), crate::BUNDLE_NAME, source)
                        .catch(&cx)
                        .map_err(JsError::caught)?;
                    let (_, promise) = module.eval().catch(&cx).map_err(JsError::caught)?;
                    // Its failure is the bundle's, reported as such.
                    mark_handled(&cx, &promise);
                    Ok(Persistent::save(&cx, promise))
                })
                .map_err(|e| self.classify(e))?;
            self.finish_evaluation(promise)
        })
        .unwrap_or_else(|| Err(self.stopped()))
    }

    /// Poll native work outside the context lock. A module awaiting I/O remains
    /// owned by the VM and resumes on its engine wake, without blocking input.
    fn finish_evaluation(&self, promise: Persistent<Promise<'static>>) -> Result<(), JsError> {
        self.run_jobs();
        let result = self.cx.with(|cx| {
            let restored = promise
                .clone()
                .restore(&cx)
                .map_err(|e| JsError::from_engine(&cx, e))?;
            Ok::<_, JsError>(
                restored
                    .result::<()>()
                    .map(|r| r.catch(&cx).map_err(JsError::caught)),
            )
        })?;
        match result {
            Some(result) => result.map_err(|e| self.classify(e)),
            None => {
                self.evaluations.borrow_mut().push(promise);
                Ok(())
            }
        }
    }

    fn settle_evaluations(&self) {
        let pending = self.evaluations.take();
        for promise in pending {
            let result = self.cx.with(|cx| match promise.clone().restore(&cx) {
                Ok(promise) => promise
                    .result::<()>()
                    .map(|r| r.catch(&cx).map_err(JsError::caught)),
                Err(error) => Some(Err(JsError::from_engine(&cx, error))),
            });
            match result {
                Some(Err(error)) => self.uncaught(&error),
                Some(Ok(())) => {}
                None => self.evaluations.borrow_mut().push(promise),
            }
        }
    }

    /// Evaluates a classic script named `name` (for stack traces) and
    /// returns whether its completion value is `true`: development updates
    /// report whether they could be applied.
    pub fn eval_script(&self, name: &str, source: &str) -> Result<bool, JsError> {
        self.guarded(Phase::Load, || self.eval_script_unguarded(name, source))
            .unwrap_or_else(|| Err(self.stopped()))
    }

    fn eval_script_unguarded(&self, name: &str, source: &str) -> Result<bool, JsError> {
        let applied = self.cx.with(|cx| -> Result<bool, JsError> {
            let mut options = rquickjs::context::EvalOptions::default();
            options.global = true;
            options.strict = false;
            options.filename = Some(name.to_owned());
            let value: rquickjs::Value<'_> = cx
                .eval_with_options(source, options)
                .catch(&cx)
                .map_err(JsError::caught)?;
            Ok(value.as_bool() == Some(true))
        });
        let applied = applied.map_err(|e| self.classify(e))?;
        self.run_jobs();
        Ok(applied)
    }

    /// Evaluates a bundle compiled with [`crate::compile_bytecode`].
    pub fn eval_bytecode(&self, bytecode: &[u8]) -> Result<(), JsError> {
        self.guarded(Phase::Load, || {
            let promise = self
                .cx
                .with(|cx| -> Result<_, JsError> {
                    // SAFETY: bytecode comes from `compile_bytecode` with the same
                    // QuickJS build; QuickJS does not validate arbitrary input.
                    let module = unsafe { Module::load(cx.clone(), bytecode) }
                        .catch(&cx)
                        .map_err(JsError::caught)?;
                    let (_, promise) = module.eval().catch(&cx).map_err(JsError::caught)?;
                    // Its failure is the bundle's, reported as such.
                    mark_handled(&cx, &promise);
                    Ok(Persistent::save(&cx, promise))
                })
                .map_err(|e| self.classify(e))?;
            self.finish_evaluation(promise)
        })
        .unwrap_or_else(|| Err(self.stopped()))
    }

    /// Gives the VM chunk `id` of a split bundle (an ES module as
    /// `nsh-bundler` makes it), before the bundle is evaluated or when it
    /// was asked for ([`Host::take_chunk_requests`]); the imports waiting
    /// for it continue.
    pub fn add_chunk_source(&self, id: &str, source: String) {
        self.add_chunk(id, crate::modules::ChunkCode::Source(source));
    }

    /// [`Host::add_chunk_source`] for a chunk compiled with
    /// [`crate::compile_chunk_bytecode`].
    ///
    /// # Safety
    ///
    /// As [`Host::eval_bytecode`]: bytecode from this QuickJS build, from a
    /// trusted source (QuickJS does not validate it).
    pub unsafe fn add_chunk_bytecode(&self, id: &str, bytecode: Vec<u8>) {
        self.add_chunk(id, crate::modules::ChunkCode::Bytecode(bytecode));
    }

    fn add_chunk(&self, id: &str, code: crate::modules::ChunkCode) {
        self.guarded(Phase::Call, || {
            self.cx
                .with(|cx| crate::chunks::add(cx.as_raw().as_ptr(), id, code));
            self.run_jobs();
        });
    }

    /// Chunk `id` could not be loaded: the imports waiting for it reject
    /// with `message`. A later import asks for it again.
    pub fn chunk_failed(&self, id: &str, message: &str) {
        self.guarded(Phase::Call, || {
            self.cx
                .with(|cx| crate::chunks::failed(cx.as_raw().as_ptr(), id, message));
            self.run_jobs();
        });
    }

    /// Moves the ids of the chunks the app imports and the VM does not have
    /// (since the last call) into `out`: the host loads each and hands it
    /// over with [`Host::add_chunk_source`] or [`Host::chunk_failed`].
    pub fn take_chunk_requests(&self, out: &mut Vec<String>) {
        if !self.cx.is_live() {
            return;
        }
        self.cx.with(|cx| {
            // SAFETY: the context's state, for this call.
            unsafe { &(*crate::state::state(cx.as_raw().as_ptr())).chunks }.take_requests(out)
        });
    }

    /// Delivers what the core hands JS after a commit
    /// ([`nsh_core::Core::take_events`]): a node's event to its handler, a
    /// Rust component's event to its `on<Event>` prop, a call's result to
    /// its promise (converted now).
    pub fn deliver(&self, event: nsh_core::element::JsEvent) {
        if let nsh_core::element::JsEvent::Event(id, kind, payload) = &event {
            self.dispatch_event(*id, *kind, payload);
            return;
        }
        // What it carries is the app's (a result, an event): dropped
        // unused (JS stopped), its `Drop` must not unwind into the engine.
        let delivered = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            self.guarded(Phase::Call, || {
                self.cx.with(|cx| {
                    let raw = cx.as_raw().as_ptr();
                    if crate::components::deliver(raw, event).is_err() {
                        self.report::<()>(&cx, Err(rquickjs::Error::Exception));
                    }
                });
                self.run_jobs();
            })
        }));
        if delivered.is_err() {
            log::error!(target: "js", "a value for JS panicked as it dropped");
        }
    }

    /// Delivers a native event (and its data) to the node's JS handler.
    pub fn dispatch_event(&self, id: NodeId, event: EventKind, payload: &EventPayload) {
        let payload_in = payload;
        self.guarded(Phase::Call, || {
            self.cx.with(|cx| {
                // Touches: the responder system is native.
                if let (EventKind::Touch, EventPayload::Touch(touch)) = (event, payload) {
                    if crate::touch::dispatch(cx.as_raw().as_ptr(), touch).is_err() {
                        self.report::<()>(&cx, Err(rquickjs::Error::Exception));
                    }
                    return;
                }
                // Windows: their handles and listeners are native.
                if let (EventKind::Window, EventPayload::Window(window)) = (event, payload) {
                    crate::window::platform_event(cx.as_raw().as_ptr(), id, window);
                    return;
                }
                let payload = match (event, payload) {
                    // `onChange({ value })`: the text, in one object as every
                    // event (`api-naming.md` "Payloads").
                    (EventKind::ChangeText, EventPayload::Text { text, .. }) => {
                        rquickjs::Object::new(cx.clone()).and_then(|o| {
                            o.set("value", text.as_str())?;
                            Ok(o.into_value())
                        })
                    }
                    (_, EventPayload::Value(value)) => payload_value(&cx, value),
                    // `onContentSizeChange({ size })`.
                    (EventKind::ContentSizeChange, EventPayload::Map(fields)) => {
                        rquickjs::Object::new(cx.clone()).and_then(|o| {
                            o.set(
                                "size",
                                payload_object(&cx, &EventPayload::Map(fields.clone()))?,
                            )?;
                            Ok(o.into_value())
                        })
                    }
                    // Presses always pass their event: where the backend
                    // does not know the pointer (a keyboard or assistive
                    // technology activation), at the view's origin with
                    // no clicks, as the DOM's `detail` of 0.
                    (
                        EventKind::Press
                        | EventKind::LongPress
                        | EventKind::PressDown
                        | EventKind::PressUp,
                        EventPayload::None,
                    ) => payload_object(&cx, &EventPayload::Press(nsh_core::PressEvent::default())),
                    // A selectable view's `onSelectionChange`: the ends of
                    // the selection in the list items, each `{ key, offset }`.
                    (EventKind::SelectionChange, EventPayload::Map(fields))
                        if fields.iter().any(|(k, _)| *k == "text") =>
                    {
                        text_selection(&cx, fields)
                    }
                    // A video's `onLoad`: `{ duration, size }` of the
                    // platforms' `duration`, `width` and `height`.
                    (EventKind::Load, EventPayload::Map(fields))
                        if fields.iter().any(|(k, _)| *k == "duration") =>
                    {
                        video_load(&cx, fields)
                    }
                    _ => payload_object(&cx, payload),
                };
                let raw = cx.as_raw().as_ptr();
                let result = payload.and_then(|payload| {
                    // Nodes hold their handlers natively.
                    let Some(handler) = crate::dom::handler(raw, id, event) else {
                        return Ok(());
                    };
                    grant_user_files(raw, event, payload_in);
                    // SAFETY: an owned function value of this context.
                    let handler = unsafe { Value::from_raw(cx.clone(), handler) };
                    match handler.into_function() {
                        Some(f) => f.call::<_, ()>((payload,)),
                        None => Ok(()),
                    }
                });
                // A listener made under an error boundary fails into it.
                let result = match result {
                    Err(rquickjs::Error::Exception)
                        if crate::dom::catch_listener_failure(raw, id) =>
                    {
                        Ok(())
                    }
                    other => other,
                };
                self.report(&cx, result);
            });
            self.run_jobs();
        });
    }

    /// Whether `<Each>` leaves the rows the core may cull unrendered, as
    /// placeholders, until the core asks for them (`content_culling`);
    /// off by default. Set before evaluating the bundle.
    pub fn set_lazy_rows(&self, lazy: bool) {
        self.cx.with(|cx| {
            // SAFETY: the state of this host's context.
            unsafe { &(*crate::state::state(cx.as_raw().as_ptr())).dom }
                .lazy_rows
                .set(lazy);
        });
    }

    /// Asks a `List` to render items into cells: `(slot, item index)`
    /// pairs.
    pub fn bind_list(&self, list: NodeId, binds: &[(u32, u32)]) {
        self.guarded(Phase::Call, || {
            self.cx.with(|cx| {
                if let Some(Err(_)) = crate::list::bind(cx.as_raw().as_ptr(), list, binds) {
                    self.report::<()>(&cx, Err(rquickjs::Error::Exception));
                }
            });
            self.run_jobs();
        });
    }

    /// What row `index` of virtual list `list` is called: the key of a
    /// `List`'s item (`keyExtractor`, else the item's `key` or `id`, else
    /// its index), where a selection across the list starts and ends
    /// (`onSelectionChange`'s `anchor` and `focus`).
    /// [`ListItemKey::NotMine`] for a list that is not the runtime's;
    /// [`ListItemKey::Failed`] when the list has no key for the row: a
    /// `keyExtractor` that throws (reported as an uncaught exception) or
    /// gives neither a string nor a number, a row past the items, or a VM
    /// that stopped.
    pub fn list_item_key(&self, list: NodeId, index: u32) -> ListItemKey {
        self.guarded(Phase::Call, || {
            self.cx.with(|cx| {
                crate::list::row_key(cx.as_raw().as_ptr(), list, index).unwrap_or_else(|()| {
                    self.report::<()>(&cx, Err(rquickjs::Error::Exception));
                    ListItemKey::Failed
                })
            })
        })
        .unwrap_or(ListItemKey::Failed)
    }

    /// Resolves the promises of finished (or interrupted) native animations.
    pub fn animations_finished(&self, finished: &[nsh_core::animation::Finished]) {
        self.guarded(Phase::Call, || {
            if finished.is_empty() {
                return;
            }
            self.cx.with(|cx| {
                let raw = cx.as_raw().as_ptr();
                for f in finished {
                    if crate::animated::finished(raw, f).is_err() {
                        self.report::<()>(&cx, Err(rquickjs::Error::Exception));
                    }
                }
            });
            self.run_jobs();
        });
    }

    /// Moves the ops committed by JS since the last call into `out`.
    pub fn take_ops(&self, out: &mut Vec<Op>) {
        let mut ops = self.shared.ops.borrow_mut();
        if out.is_empty() {
            std::mem::swap(out, &mut ops);
        } else {
            out.append(&mut ops);
        }
        drop(ops);
        let mut releases = self.shared.releases.borrow_mut();
        out.extend(releases.drain(..).map(|id| Op::Release { id }));
        drop(releases);
        out.extend(
            self.shared
                .animation_releases
                .borrow_mut()
                .drain(..)
                .map(Op::Animation),
        );
    }

    /// Sets native system permissions and the app-specific trusted data directory.
    /// Process and file access require explicit grants, including in standalone apps.
    pub fn set_system_access(
        &self,
        access: nsh_core::access::Access,
        data_dir: Option<std::path::PathBuf>,
    ) {
        *self.shared.system_access.borrow_mut() = access;
        *self.shared.system_data_dir.borrow_mut() = data_dir;
    }

    /// Sets where the app's bundled (`asset:/…`) files are on disk: a
    /// packaged desktop app's own, beside the running runner (`process.run`
    /// of an `asset:/…` program resolves it through this).
    pub fn set_system_asset_base(&self, base: Option<nsh_core::image::AssetBase>) {
        *self.shared.system_asset_base.borrow_mut() = base;
    }

    /// Sets trusted application and home directory anchors for manifest grants.
    pub fn set_system_paths(&self, paths: nsh_core::access::TrustedPaths) {
        *self.shared.system_paths.borrow_mut() = paths;
    }

    /// Installs an app-private virtual filesystem. Capability checks stay in Rust.
    pub fn set_filesystem(
        &self,
        filesystem: Option<std::sync::Arc<dyn nsh_core::filesystem::FileSystem>>,
    ) {
        *self.shared.system_filesystem.borrow_mut() = filesystem;
    }

    /// Installs what `nsh/updater` runs on.
    pub fn set_updater(&self, updater: Option<std::sync::Arc<dyn nsh_core::runtime::UpdaterHost>>) {
        *self.shared.system_updater.borrow_mut() = updater;
    }

    /// Shares the core's address with the VM's modules (`UrlScheme.url()`).
    pub fn set_app_url(&self, app_url: nsh_core::url_scheme::AppUrlCell) {
        *self.shared.system_app_url.borrow_mut() = app_url;
    }

    /// Installs the host WebSocket transport.
    pub fn set_websocket_transport(
        &self,
        transport: Option<std::sync::Arc<dyn nsh_core::websocket::WebSocketTransport>>,
    ) {
        *self.shared.system_websocket.borrow_mut() = transport;
    }

    /// Refuses the app's connections (`net` sockets and both WebSocket
    /// APIs) with what `refuse` gives, before they reach the network: a
    /// test's (`nsh_core::element::System::refuse_connections`).
    pub fn set_refuse_connections(&self, refuse: Option<nsh_core::element::RefuseConnections>) {
        *self.shared.system_refuse_connections.borrow_mut() = refuse;
    }

    /// Connects `nsh/host` to the embedding app: its launch parameters, and
    /// where the app's calls and posts go. Call before evaluating the bundle
    /// (`host.params` is read when the module is first imported).
    pub fn set_host_bridge(&self, bridge: Rc<dyn nsh_core::host_channel::HostBridge>) {
        *self.shared.host_bridge.borrow_mut() = Some(bridge);
    }

    /// Delivers the embedding app's event `name` (`host.on`): to the
    /// listeners of its name, or kept until one is added.
    pub fn host_event(&self, name: &str, data: nsh_core::JsonValue) {
        if !self.cx.is_live() {
            return;
        }
        self.guarded(Phase::Call, || {
            self.cx.with(|cx| {
                crate::host_channel::deliver(cx.as_raw().as_ptr(), name, data);
            });
            self.run_jobs();
        });
    }

    /// Settles call `id` (`host.call`) with the embedding app's answer, or
    /// rejects it with the message.
    pub fn host_reply(&self, id: u64, result: Result<nsh_core::JsonValue, String>) {
        if !self.cx.is_live() {
            return;
        }
        self.guarded(Phase::Call, || {
            self.cx.with(|cx| {
                crate::host_channel::settle(cx.as_raw().as_ptr(), id, result);
            });
            self.run_jobs();
        });
    }

    /// Installs the meaning of `process.exit(code)` for this VM. The callback
    /// runs on the owning engine thread after the app's exit capability check.
    /// NSH never terminates the embedding process itself.
    pub fn set_exit_handler(&self, handler: Rc<dyn Fn(i32)>) {
        if self.fatal().is_some() {
            return;
        }
        *self.shared.system_exit_handler.borrow_mut() = Some(handler);
    }

    /// Wakes this host's engine when a process worker produces an event.
    pub fn set_system_wake(&self, wake: Arc<dyn Fn() + Send + Sync>) {
        if self.fatal().is_some() {
            return;
        }
        self.scheduler.set_wake(wake.clone());
        *self.shared.system_wake.borrow_mut() = Some(wake);
    }

    /// Drains pending promise jobs (the runtime modules' work runs as core
    /// tasks, whose results arrive through the core).
    pub fn run_system(&self) {
        self.guarded(Phase::Call, || self.run_jobs());
    }

    /// Whether JS work is still pending in this VM: evaluations, timers or
    /// jobs. Workers wake the engine; this predicate does not schedule
    /// polling.
    pub fn has_system_tasks(&self) -> bool {
        if self.fatal().is_some() {
            return false;
        }
        !self.evaluations.borrow().is_empty()
            || self
                .scheduler
                .ready(self.rt.borrow().as_ref().expect("live VM").is_job_pending())
    }

    /// Earliest timer deadline, if any timer is pending.
    pub fn next_timer(&self) -> Option<Instant> {
        let timer = self.shared.timers.borrow_mut().next_deadline();
        let host = self
            .cx
            .is_live()
            .then(|| {
                self.cx
                    .with(|cx| crate::host_channel::next_deadline(cx.as_raw().as_ptr()))
            })
            .flatten();
        timer.into_iter().chain(host).min()
    }

    /// Runs all timers due at `now`.
    pub fn run_timers(&self, now: Instant) {
        if self.cx.is_live() {
            self.guarded(Phase::Call, || {
                self.cx
                    .with(|cx| crate::host_channel::expire(cx.as_raw().as_ptr(), now));
                self.run_jobs();
            });
        }
        loop {
            // Release the borrow before calling into JS: callbacks may add timers.
            let Some(callback) = self.shared.timers.borrow_mut().pop_due(now) else {
                break;
            };
            // Each callback, with the microtasks it queues, has a budget of its own.
            let ran = self.guarded(Phase::Call, || {
                self.cx.with(|cx| {
                    let result = callback.restore(&cx).and_then(|f| f.call::<_, ()>(()));
                    self.report(&cx, result);
                });
                self.run_jobs();
            });
            if ran.is_none() {
                break;
            }
        }
    }

    /// Runs pending promise jobs and microtasks until the queue is empty,
    /// then reports the promises rejected meanwhile that are still without
    /// a handler ([`Host::set_rejection_handler`]). Every call from Rust
    /// into JS ends with it: it is the end of the turn.
    pub fn run_jobs(&self) {
        self.guarded(Phase::Call, || {
            loop {
                loop {
                    match self
                        .scheduler
                        .poll_job(self.rt.borrow().as_ref().expect("live VM"))
                    {
                        std::task::Poll::Ready(Ok(true)) => {}
                        std::task::Poll::Ready(Ok(false)) | std::task::Poll::Pending => break,
                        std::task::Poll::Ready(Err(err)) => {
                            let err = self.scheduler.ready(err.with(|cx| {
                                let caught = cx.catch();
                                let mut err = JsError::new(describe(caught.clone()));
                                err.null = caught.is_null();
                                err
                            }));
                            self.uncaught(&err);
                            if self.fatal().is_some() {
                                break;
                            }
                        }
                    }
                }
                if self.fatal().is_some() {
                    break;
                }
                self.settle_evaluations();
                // Rendering a reason may run JS (a getter) and queue jobs.
                if !self.report_rejections() {
                    break;
                }
            }
        });
    }

    /// Reports the rejections still unhandled; whether there were any.
    fn report_rejections(&self) -> bool {
        // Taken first: rendering a reason may run JS, which may reject.
        let rejections = self.shared.rejections.borrow_mut().take();
        if rejections.is_empty() {
            return false;
        }
        // A VM out of memory stops with that report; what failed for it is
        // not the app's to handle.
        if self.exhausted.load(Ordering::Relaxed) || self.shared.fatal.borrow().is_some() {
            return false;
        }
        self.cx.with(|cx| {
            for rejection in rejections {
                let mut text = String::new();
                if let Ok(reason) = rejection.reason(&cx) {
                    console::format_value(&reason, &mut text);
                }
                // An error without a stack ends with its empty line.
                text.truncate(text.trim_end().len());
                let err = JsError::new(text);
                match &self.on_rejection {
                    Some(handler) => handler(&err),
                    None => log::error!(target: "js", "unhandled rejection: {err}"),
                }
            }
        });
        true
    }

    /// How many rejections wait for the end of the turn (tests).
    #[cfg(test)]
    pub(crate) fn pending_rejections(&self) -> usize {
        self.shared.rejections.borrow().len()
    }

    /// Whether warning `message` was logged (tests).
    #[cfg(test)]
    pub(crate) fn warned(&self, message: &str) -> bool {
        self.shared.warnings.borrow().reported(message)
    }

    /// Runs `f` with the raw context (tests).
    #[cfg(test)]
    pub(crate) fn with_raw<R>(&self, f: impl FnOnce(*mut qjs::JSContext) -> R) -> R {
        self.cx.with(|cx| f(cx.as_raw().as_ptr()))
    }

    /// Whether an exception is pending outside any call (none should be).
    #[cfg(test)]
    pub(crate) fn has_exception(&self) -> bool {
        if !self.cx.is_live() {
            return false;
        }
        // SAFETY: a check on the live context.
        self.cx
            .with(|cx| unsafe { qjs::JS_HasException(cx.as_raw().as_ptr()) })
    }

    /// Runs the calls of JS functions Rust queued (`Callback::post`,
    /// `Callback::call_async`), in order; those queued meanwhile wait for
    /// the next call. The engine calls it each turn, after the core's work.
    pub fn run_posted(&self) {
        if self.fatal().is_some() {
            // Stopped for good: what waits for these calls is told so.
            if self.cx.is_live() {
                self.cx
                    .with(|cx| crate::classes::close(cx.as_raw().as_ptr()));
            }
            return;
        }
        self.guarded(Phase::Call, || {
            self.cx.with(|cx| {
                let ran = crate::classes::run_posted(cx.as_raw().as_ptr());
                self.report(&cx, ran.map_err(|_| rquickjs::Error::Exception));
            });
            self.run_jobs();
        });
    }

    /// Releases the posts JS's ops park (as the core does) and runs the
    /// posted calls: for tests without a core.
    #[cfg(test)]
    pub(crate) fn run_posted_without_core(&self) {
        let mut ops = Vec::new();
        self.take_ops(&mut ops);
        self.apply_posts(&mut ops);
        self.run_posted();
    }

    /// Applies the posts' ops among `ops` (as the core does: dropped, they
    /// release their places): for tests without a core.
    #[cfg(test)]
    pub(crate) fn apply_posts(&self, ops: &mut Vec<Op>) {
        ops.retain(|op| {
            !matches!(
                op,
                Op::Rust(nsh_core::element::RustOp {
                    run: nsh_core::element::RustCall::Post(_),
                    ..
                })
            )
        });
    }

    /// Whether calls Rust queued wait for [`Host::run_posted`].
    pub fn has_posted(&self) -> bool {
        if !self.cx.is_live() {
            return false;
        }
        self.cx
            .with(|cx| crate::classes::has_posted(cx.as_raw().as_ptr()))
    }

    /// Moves the network requests and cancellations made since the last
    /// call into `out`.
    pub fn take_network(&self, out: &mut NetworkQueue) {
        if self.cx.is_live() && !self.shared.dropped_fetches.borrow().is_empty() {
            self.cx
                .with(|cx| crate::web::forget_dropped_fetches(cx.as_raw().as_ptr()));
        }
        out.ops.append(&mut self.shared.net.borrow_mut().ops);
    }

    /// Publishes the surface's environment to JS. Call once before
    /// evaluating the bundle (the runtime reads the initial value), then on
    /// every change.
    pub fn set_environment(&self, env: &Environment) {
        self.guarded(Phase::Call, || {
            self.cx.with(|cx| {
                let result = (|| {
                    let raw = cx.as_raw().as_ptr();
                    // SAFETY: the state of this host's context.
                    unsafe { &(*crate::state::state(raw)).dom }.set_platform(env.os, env.desktop());
                    if crate::env::set_environment(raw, env).is_err() {
                        return Err(rquickjs::Error::Exception);
                    }
                    Ok(())
                })();
                self.report(&cx, result);
            });
            self.run_jobs();
        });
    }

    /// Publishes the displays to JS (`nsh/desktop`'s `displays()`). Call
    /// before evaluating the bundle where there are displays, then on every
    /// change; without a call they are none.
    pub fn set_displays(&self, displays: &[nsh_core::desktop::Display]) {
        self.guarded(Phase::Call, || {
            self.cx.with(|cx| {
                let raw = cx.as_raw().as_ptr();
                let result = match crate::env::set_displays(raw, displays) {
                    Ok(()) => Ok(()),
                    Err(()) => Err(rquickjs::Error::Exception),
                };
                self.report(&cx, result);
            });
            self.run_jobs();
        });
    }

    /// Publishes whether the platform's performance monitor measures to JS
    /// (`nsh`'s `fpsEnabled()`). Call on every change; without a call it is
    /// off.
    pub fn set_fps_enabled(&self, enabled: bool) {
        self.guarded(Phase::Call, || {
            self.cx.with(|cx| {
                let raw = cx.as_raw().as_ptr();
                let result = match crate::env::set_fps_enabled(raw, enabled) {
                    Ok(()) => Ok(()),
                    Err(()) => Err(rquickjs::Error::Exception),
                };
                self.report(&cx, result);
            });
            self.run_jobs();
        });
    }

    /// Publishes what the performance monitor measured last to JS (`nsh`'s
    /// `perfStats()`): `None` while it does not measure.
    pub fn set_perf_stats(&self, stats: Option<&nsh_core::platform::PerfStats>) {
        self.guarded(Phase::Call, || {
            self.cx.with(|cx| {
                let raw = cx.as_raw().as_ptr();
                let result = match crate::env::set_perf_stats(raw, stats) {
                    Ok(()) => Ok(()),
                    Err(()) => Err(rquickjs::Error::Exception),
                };
                self.report(&cx, result);
            });
            self.run_jobs();
        });
    }

    /// Publishes the design tokens the app is drawn with to JS (`token()`
    /// of `nsh`). Call before evaluating the bundle, then on every change.
    pub fn set_tokens(&self, tokens: std::sync::Arc<nsh_core::element::Tokens>) {
        self.guarded(Phase::Call, || {
            self.cx.with(|cx| {
                crate::env::set_tokens(cx.as_raw().as_ptr(), tokens);
            });
            self.run_jobs();
        });
    }

    /// Sets how the app's theme file makes the tokens it is drawn with
    /// ([`nsh_core::Core::theme_tokens`]): `token()` reads them from the
    /// entry's first statement on, before the theme reaches the core. Call
    /// before evaluating the bundle, then when the embedding app's tokens
    /// change.
    pub fn set_theme_tokens(&self, theme: nsh_core::element::ThemeTokens) {
        self.cx.with(|cx| {
            crate::env::set_theme_tokens(cx.as_raw().as_ptr(), theme);
        });
    }

    /// Sets what `appInfo()` reports for a bundle that came from a verified
    /// package: the app as its signed header names it. Its known fields
    /// (`id`, `name`, `version`, `build`) win over what the build wrote into
    /// the bundle, which a bundle signed again under a new build number
    /// still carries; `development` stays the build's. Call before
    /// evaluating the bundle, and only for a verified package.
    pub fn set_package_app_info(&self, info: nsh_core::platform::AppInfo) {
        self.cx.with(|cx| {
            crate::env::set_package_app_info(cx.as_raw().as_ptr(), info);
        });
    }

    /// The release of NSH the evaluated bundle was built for (`target`
    /// of `nsh:rt`); [`Release::FIRST_COMPATIBLE`] for one that names none.
    /// A behavior change applies to bundles built for its release or later.
    ///
    /// [`Release::FIRST_COMPATIBLE`]: crate::Release::FIRST_COMPATIBLE
    pub fn target(&self) -> crate::Release {
        self.cx.with(|cx| crate::env::target(cx.as_raw().as_ptr()))
    }

    /// True if JS asked for a display frame (`requestAnimationFrame`).
    pub fn wants_frame(&self) -> bool {
        !self.shared.frames.borrow().is_empty()
    }

    /// Runs the `requestAnimationFrame` callbacks queued so far, with the
    /// current `performance.now()`. Callbacks requested meanwhile wait for
    /// the next frame.
    pub fn run_frame(&self) {
        self.guarded(Phase::Call, || {
            let callbacks = std::mem::take(&mut *self.shared.frames.borrow_mut());
            if callbacks.is_empty() {
                return;
            }
            self.cx.with(|cx| {
                let now = (|| -> rquickjs::Result<f64> {
                    let performance: rquickjs::Object = cx.globals().get("performance")?;
                    performance.get::<_, Function>("now")?.call(())
                })()
                .unwrap_or(0.0);
                for (_, callback) in callbacks {
                    let result = callback.restore(&cx).and_then(|f| f.call::<_, ()>((now,)));
                    self.report(&cx, result);
                }
            });
            self.run_jobs();
        });
    }

    /// Moves the font assets (`asset:/…` URIs) imported since the last call
    /// into `out`. They must be registered before the next layout.
    pub fn take_fonts(&self, out: &mut Vec<String>) {
        out.append(&mut self.shared.fonts.borrow_mut());
    }

    /// Delivers an event of request `id` (what the network stack reported).
    pub fn fetch_event(&self, id: RequestId, event: FetchEvent) {
        self.guarded(Phase::Call, || {
            self.cx.with(|cx| {
                let raw = cx.as_raw().as_ptr();
                let result =
                    crate::web::fetch_event(raw, id, event).map_err(|_| rquickjs::Error::Exception);
                self.report(&cx, result);
            });
            self.run_jobs();
        });
    }

    /// Fails request `id`, which the app's capabilities do not grant:
    /// `message` says why, `url` is the URL refused (the request's, or a
    /// redirect's). `fetch` rejects with a `TypeError` whose `code` is
    /// `ERR_ACCESS_DENIED`, `permission` `"network"` and `resource` `url`.
    pub fn fetch_refused(&self, id: RequestId, message: &str, url: &str) {
        self.guarded(Phase::Call, || {
            self.cx.with(|cx| {
                let raw = cx.as_raw().as_ptr();
                let result = crate::web::fetch_refused(raw, id, message, url)
                    .map_err(|_| rquickjs::Error::Exception);
                self.report(&cx, result);
            });
            self.run_jobs();
        });
    }

    /// The number of live JS objects (diagnostics: leak checks).
    pub fn object_count(&self) -> i64 {
        self.rt
            .borrow()
            .as_ref()
            .map_or(0, |rt| self.scheduler.ready(rt.memory_usage()).obj_count)
    }

    /// The JS heap's size in bytes and its live objects (diagnostics: a
    /// walk of the heap, so not for every frame).
    pub fn heap_usage(&self) -> (u64, u64) {
        self.rt.borrow().as_ref().map_or((0, 0), |rt| {
            let m = self.scheduler.ready(rt.memory_usage());
            (m.malloc_size.max(0) as u64, m.obj_count.max(0) as u64)
        })
    }

    /// Runs the cycle collector. Call when idle so released nodes are
    /// reported promptly.
    pub fn collect_garbage(&self) {
        self.guarded(Phase::Call, || {
            self.scheduler
                .ready(self.rt.borrow().as_ref().expect("live VM").run_gc());
            // What the collection released: the graph gives back the slots
            // of nodes that are gone.
            self.cx.with(|cx| {
                // SAFETY: the state of this host's context; no other borrow
                // of the graph is live between calls into JS.
                unsafe { crate::reactive::graph(cx.as_raw().as_ptr()) }.compact();
            });
            self.run_jobs();
        });
    }
}

impl Host {
    fn report<T>(&self, cx: &Ctx<'_>, result: rquickjs::Result<T>) {
        if let Err(err) = result.catch(cx) {
            self.uncaught(&JsError::caught(err));
        }
    }

    fn uncaught(&self, err: &JsError) {
        let err = self.classify(err.clone());
        match &self.on_error {
            Some(handler) => handler(&err),
            None => log::error!(target: "js", "uncaught exception: {err}"),
        }
    }
}

impl Drop for Host {
    fn drop(&mut self) {
        self.stop_work();
    }
}

/// Marks `promise` handled: it is not reported as an unhandled rejection.
fn mark_handled(cx: &Ctx<'_>, promise: &rquickjs::Promise<'_>) {
    // SAFETY: a live promise of this context.
    unsafe { qjs::JS_PromiseMarkAsHandled(cx.as_raw().as_ptr(), promise.as_raw()) };
}

/// A video's `onLoad` payload: `{ duration, size: { width, height } }`.
fn video_load<'js>(
    cx: &Ctx<'js>,
    fields: &[(&'static str, PayloadValue)],
) -> rquickjs::Result<Value<'js>> {
    let obj = rquickjs::Object::new(cx.clone())?;
    let size = rquickjs::Object::new(cx.clone())?;
    for (key, value) in fields {
        match *key {
            "width" | "height" => size.set(*key, payload_value(cx, value)?)?,
            _ => obj.set(*key, payload_value(cx, value)?)?,
        }
    }
    obj.set("size", size)?;
    Ok(obj.into_value())
}

/// Lets the app read the files the user pasted or dropped, as its handler
/// gets them (`fs/promises` at their exact paths): not a drag that only
/// entered.
fn grant_user_files(raw: *mut qjs::JSContext, event: EventKind, payload: &EventPayload) {
    let uris = match (event, payload) {
        (EventKind::Paste, EventPayload::Paste(paste)) => &paste.uris,
        (
            EventKind::FileDrop,
            EventPayload::FileDrop(uris) | EventPayload::FileDropAt { uris, .. },
        ) => uris,
        _ => return,
    };
    nsh_core::runtime::grant_user_files(&crate::dom::shared(raw).system_locals, uris);
}

/// A selectable view's `onSelectionChange` event: the payload's fields,
/// the ends' keys and offsets ([`nsh_core::selection::ITEM_FIELDS`]) as
/// `anchor` and `focus` objects (`{ key, offset }`).
fn text_selection<'js>(
    cx: &Ctx<'js>,
    fields: &[(&'static str, nsh_core::PayloadValue)],
) -> rquickjs::Result<Value<'js>> {
    let ends = nsh_core::selection::ITEM_FIELDS;
    let obj = rquickjs::Object::new(cx.clone())?;
    for (key, value) in fields {
        if !ends.iter().any(|(k, o)| key == k || key == o) {
            obj.set(*key, payload_value(cx, value)?)?;
        }
    }
    let field = |name: &str| fields.iter().find(|(k, _)| *k == name).map(|(_, v)| v);
    for ((key, offset), name) in ends.into_iter().zip(["anchor", "focus"]) {
        if let (Some(key), Some(offset)) = (field(key), field(offset)) {
            let end = rquickjs::Object::new(cx.clone())?;
            end.set("key", payload_value(cx, key)?)?;
            end.set("offset", payload_value(cx, offset)?)?;
            obj.set(name, end)?;
        }
    }
    Ok(obj.into_value())
}

/// The JS object handed to event handlers.
fn payload_object<'js>(cx: &Ctx<'js>, payload: &EventPayload) -> rquickjs::Result<Value<'js>> {
    let obj = rquickjs::Object::new(cx.clone())?;
    match payload {
        EventPayload::None => return Ok(Value::new_undefined(cx.clone())),
        EventPayload::Value(value) => return payload_value(cx, value),
        EventPayload::Map(fields) => {
            for (key, value) in fields {
                obj.set(*key, payload_value(cx, value)?)?;
            }
        }
        EventPayload::Press(nsh_core::PressEvent {
            position,
            page_position,
            modifiers,
            clicks,
        }) => {
            obj.set("position", point_object(cx, *position)?)?;
            obj.set("pagePosition", point_object(cx, *page_position)?)?;
            obj.set("modifiers", modifiers_object(cx, modifiers)?)?;
            obj.set("clickCount", *clicks)?;
        }
        EventPayload::Mouse(e) => {
            obj.set("position", point_object(cx, e.position)?)?;
            obj.set("pagePosition", point_object(cx, e.page_position)?)?;
            obj.set("modifiers", modifiers_object(cx, &e.modifiers)?)?;
            // `null` with no button down, as declared (an absent field
            // would read `undefined`).
            match e.pressed_button {
                Some(button) => obj.set("pressedButton", button.name())?,
                None => obj.set("pressedButton", Value::new_null(cx.clone()))?,
            }
            // The button that changed here (`onMouseUp`'s), or `null` on a
            // move.
            match e.button {
                Some(button) => obj.set("button", button.name())?,
                None => obj.set("button", Value::new_null(cx.clone()))?,
            }
            obj.set("pointerType", e.pointer_type.name())?;
            obj.set("pressure", e.pressure)?;
            obj.set("tiltX", e.tilt_x)?;
            obj.set("tiltY", e.tilt_y)?;
        }
        EventPayload::Key(event) => {
            obj.set("key", event.key.as_str())?;
            obj.set("code", event.code.as_str())?;
            obj.set("modifiers", modifiers_object(cx, &event.modifiers)?)?;
            obj.set("repeat", event.repeat)?;
            obj.set("defaultPrevented", event.default_prevented)?;
        }
        EventPayload::Wheel(e) => {
            obj.set("position", point_object(cx, e.position)?)?;
            obj.set("pagePosition", point_object(cx, e.page_position)?)?;
            let (x, y) = e.delta.xy();
            let delta = rquickjs::Object::new(cx.clone())?;
            delta.set("x", x)?;
            delta.set("y", y)?;
            obj.set("delta", delta)?;
            obj.set("deltaMode", e.delta.mode_name())?;
            obj.set("modifiers", modifiers_object(cx, &e.modifiers)?)?;
        }
        EventPayload::Pinch(e) => {
            obj.set("position", point_object(cx, e.position)?)?;
            obj.set("pagePosition", point_object(cx, e.page_position)?)?;
            obj.set("delta", e.delta.0)?;
            obj.set("phase", e.phase.name())?;
            obj.set("modifiers", modifiers_object(cx, &e.modifiers)?)?;
        }
        EventPayload::ContextMenu(e) => {
            obj.set("position", point_object(cx, e.position)?)?;
            obj.set("pagePosition", point_object(cx, e.page_position)?)?;
            obj.set("modifiers", modifiers_object(cx, &e.modifiers)?)?;
            // `null` when no pointer asked, as declared.
            match e.pointer_type {
                Some(pointer) => obj.set("pointerType", pointer.name())?,
                None => obj.set("pointerType", Value::new_null(cx.clone()))?,
            }
        }
        EventPayload::FileDrop(uris) | EventPayload::FileDropAt { uris, .. } => {
            let list = rquickjs::Array::new(cx.clone())?;
            let types = rquickjs::Array::new(cx.clone())?;
            for (index, uri) in uris.iter().enumerate() {
                list.set(index, uri.as_str())?;
                types.set(index, nsh_core::platform::file_mime_type(uri))?;
            }
            obj.set("uris", list)?;
            obj.set("mimeTypes", types)?;
            // Contents come only where there are no paths (the Web, macOS file promises).
            obj.set("files", rquickjs::Array::new(cx.clone())?)?;
            if let EventPayload::FileDropAt { page_position, .. } = payload {
                obj.set("pagePosition", point_object(cx, *page_position)?)?;
            }
        }
        // `PickedFile`s: each read one's `File` shares the dropped bytes.
        EventPayload::FileContents(drop) => {
            obj.set("uris", rquickjs::Array::new(cx.clone())?)?;
            let types = rquickjs::Array::new(cx.clone())?;
            for (index, mime) in drop.mime_types.iter().enumerate() {
                types.set(index, mime.as_str())?;
            }
            obj.set("mimeTypes", types)?;
            let files = rquickjs::Array::new(cx.clone())?;
            for (index, file) in drop.files.iter().enumerate() {
                let entry = rquickjs::Object::new(cx.clone())?;
                if file.status == nsh_core::picker::PickedStatus::TooLarge {
                    entry.set("file", Value::new_null(cx.clone()))?;
                    entry.set("status", "tooLarge")?;
                } else {
                    let blob = crate::web::blob::Blob::shared(file.data.clone(), file.mime.clone());
                    let modified = file
                        .last_modified
                        .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
                        .map_or_else(crate::web::blob::now_ms, |d| d.as_millis() as f64);
                    let made = crate::web::blob::new_file(
                        cx.as_raw().as_ptr(),
                        blob,
                        file.name.clone(),
                        modified,
                    )
                    .map_err(|_| rquickjs::Error::Exception)?;
                    // SAFETY: an owned value of this context, handed over.
                    let value = unsafe { Value::from_raw(cx.clone(), made.take()) };
                    entry.set("file", value)?;
                    entry.set("status", "read")?;
                }
                entry.set("name", file.name.as_str())?;
                entry.set("type", file.mime.as_str())?;
                entry.set("size", file.len as f64)?;
                files.set(index, entry)?;
            }
            obj.set("files", files)?;
            if let Some(at) = drop.page_position {
                obj.set("pagePosition", point_object(cx, at)?)?;
            }
        }
        EventPayload::TextDrop(drop) => {
            obj.set("text", drop.text.as_str())?;
            obj.set("html", drop.html.as_str())?;
            obj.set("pagePosition", point_object(cx, drop.page_position)?)?;
        }
        // The bytes cross natively: each file is a `File` over them.
        EventPayload::Paste(paste) => {
            obj.set("text", paste.text.as_str())?;
            obj.set("html", paste.html.as_str())?;
            let files = rquickjs::Array::new(cx.clone())?;
            for (index, file) in paste.files.iter().enumerate() {
                let blob = crate::web::blob::Blob::new(file.data.clone(), file.mime.clone());
                let made = crate::web::blob::new_file(
                    cx.as_raw().as_ptr(),
                    blob,
                    file.name.clone(),
                    crate::web::blob::now_ms(),
                )
                .map_err(|_| rquickjs::Error::Exception)?;
                // SAFETY: an owned value of this context, handed over.
                let value = unsafe { Value::from_raw(cx.clone(), made.take()) };
                files.set(index, value)?;
            }
            obj.set("files", files)?;
            let too_large = rquickjs::Array::new(cx.clone())?;
            for (index, file) in paste.too_large.iter().enumerate() {
                let unread = rquickjs::Object::new(cx.clone())?;
                unread.set("name", file.name.as_str())?;
                unread.set("type", file.mime.as_str())?;
                unread.set("size", file.len as f64)?;
                too_large.set(index, unread)?;
            }
            obj.set("tooLarge", too_large)?;
            let uris = rquickjs::Array::new(cx.clone())?;
            for (index, uri) in paste.uris.iter().enumerate() {
                uris.set(index, uri.as_str())?;
            }
            obj.set("uris", uris)?;
        }
        // The core answers picks; JS never gets their files this way.
        EventPayload::Picked { id, .. } => obj.set("id", *id)?,
        // The core answers these too.
        EventPayload::FileRequest { id, .. } => obj.set("id", *id)?,
        // And offscreen canvas renders.
        EventPayload::CanvasImage { id, .. } => obj.set("id", *id)?,
        // And sounds' and players' events (their objects' listeners).
        EventPayload::Audio { id, .. } => obj.set("id", *id)?,
        // Handled natively (`crate::window`).
        EventPayload::Window(_) => return Ok(Value::new_undefined(cx.clone())),
        EventPayload::Native { name, data } => {
            obj.set("name", &**name)?;
            obj.set("data", json_value(cx, data)?)?;
        }
        EventPayload::Json(value) => return json_value(cx, value),
        EventPayload::TextLayout(lines) => {
            let list = rquickjs::Array::new(cx.clone())?;
            for (i, l) in lines.iter().enumerate() {
                let line = rquickjs::Object::new(cx.clone())?;
                line.set("text", l.text.as_str())?;
                let bounds = nsh_core::geometry::Bounds {
                    origin: nsh_core::geometry::point(l.x, l.y),
                    size: nsh_core::geometry::Size::new(l.width, l.height),
                };
                line.set("bounds", bounds_object(cx, bounds)?)?;
                line.set("ascender", l.ascender.0)?;
                line.set("descender", l.descender.0)?;
                line.set("capHeight", l.cap_height.0)?;
                line.set("xHeight", l.x_height.0)?;
                list.set(i, line)?;
            }
            obj.set("lines", list)?;
        }
        EventPayload::Layout(frame) => obj.set("bounds", bounds_object(cx, *frame)?)?,
        EventPayload::Pan {
            origin,
            translation,
            velocity_x,
            velocity_y,
            value_x,
            value_y,
        }
        | EventPayload::PanCancelled {
            origin,
            translation,
            velocity_x,
            velocity_y,
            value_x,
            value_y,
        } => {
            obj.set(
                "cancelled",
                matches!(payload, EventPayload::PanCancelled { .. }),
            )?;
            obj.set("origin", point_object(cx, *origin)?)?;
            obj.set("translation", point_object(cx, *translation)?)?;
            let velocity = rquickjs::Object::new(cx.clone())?;
            velocity.set("x", *velocity_x)?;
            velocity.set("y", *velocity_y)?;
            obj.set("velocity", velocity)?;
            // The bound values, those of the axes `pan` binds.
            if value_x.is_some() || value_y.is_some() {
                let value = rquickjs::Object::new(cx.clone())?;
                if let Some(v) = value_x {
                    value.set("x", v.0)?;
                }
                if let Some(v) = value_y {
                    value.set("y", v.0)?;
                }
                obj.set("value", value)?;
            }
        }
        EventPayload::Scroll(offset) => obj.set("offset", point_object(cx, *offset)?)?,
        // The numbers JS always got (pixels are whole).
        EventPayload::Image(size) => {
            let pixels = rquickjs::Object::new(cx.clone())?;
            pixels.set("width", size.width.0 as f32)?;
            pixels.set("height", size.height.0 as f32)?;
            obj.set("size", pixels)?;
        }
        EventPayload::Error { message } => obj.set("message", message.as_str())?,
        EventPayload::Text { text, .. } => obj.set("text", text.as_str())?,
        EventPayload::Touch(touch) => {
            obj.set(
                "phase",
                match touch.phase {
                    TouchPhase::Start => "start",
                    TouchPhase::Move => "move",
                    TouchPhase::End => "end",
                    TouchPhase::Cancel => "cancel",
                },
            )?;
            obj.set("timestamp", touch.timestamp)?;
            let points = rquickjs::Array::new(cx.clone())?;
            for (i, p) in touch.points.iter().enumerate() {
                let o = rquickjs::Object::new(cx.clone())?;
                o.set("identifier", p.id)?;
                o.set("target", p.target)?;
                let path = rquickjs::Array::new(cx.clone())?;
                for (j, id) in p.path.iter().enumerate() {
                    path.set(j, *id)?;
                }
                o.set("path", path)?;
                o.set("pageX", p.page.x.0)?;
                o.set("pageY", p.page.y.0)?;
                o.set("locationX", p.location.x.0)?;
                o.set("locationY", p.location.y.0)?;
                o.set("changed", p.changed)?;
                o.set("pointerType", p.pointer_type.name())?;
                o.set("pressure", p.pressure)?;
                o.set("tiltX", p.tilt_x)?;
                o.set("tiltY", p.tilt_y)?;
                o.set("eraser", p.eraser)?;
                o.set("barrel", p.barrel)?;
                let coalesced = rquickjs::Array::new(cx.clone())?;
                for (j, c) in p.coalesced.iter().enumerate() {
                    let s = rquickjs::Object::new(cx.clone())?;
                    s.set("pageX", c.page.x.0)?;
                    s.set("pageY", c.page.y.0)?;
                    s.set("locationX", c.location.x.0)?;
                    s.set("locationY", c.location.y.0)?;
                    s.set("pressure", c.pressure)?;
                    s.set("tiltX", c.tilt_x)?;
                    s.set("tiltY", c.tilt_y)?;
                    s.set("timestamp", c.timestamp)?;
                    coalesced.set(j, s)?;
                }
                o.set("coalesced", coalesced)?;
                o.set("timestamp", touch.timestamp)?;
                points.set(i, o)?;
            }
            obj.set("points", points)?;
        }
    }
    Ok(obj.into_value())
}

/// JSON as a JS value (owned), for natives.
pub(crate) fn json_to_js(raw: *mut qjs::JSContext, json: &nsh_core::JsonValue) -> qjs::JSValue {
    // SAFETY: a context reference; the value's ownership moves out.
    let cx = unsafe { Ctx::from_raw(std::ptr::NonNull::new_unchecked(raw)) };
    match json_value(&cx, json) {
        // A value of our own; the wrapper (and its context reference) go.
        Ok(v) => unsafe { qjs::JS_DupValue(raw, v.as_raw()) },
        Err(_) => qjs::JS_UNDEFINED,
    }
}

/// JSON (a native component's event data) as a JS value.
fn json_value<'js>(cx: &Ctx<'js>, value: &nsh_core::JsonValue) -> rquickjs::Result<Value<'js>> {
    use nsh_core::JsonValue as J;
    Ok(match value {
        J::Null => Value::new_null(cx.clone()),
        J::Bool(b) => Value::new_bool(cx.clone(), *b),
        J::Number(n) => Value::new_float(cx.clone(), n.as_f64().unwrap_or(0.0)),
        J::String(s) => rquickjs::String::from_str(cx.clone(), s)?.into_value(),
        J::Array(items) => {
            let array = rquickjs::Array::new(cx.clone())?;
            for (i, item) in items.iter().enumerate() {
                array.set(i, json_value(cx, item)?)?;
            }
            array.into_value()
        }
        J::Object(fields) => {
            let object = rquickjs::Object::new(cx.clone())?;
            for (key, item) in fields {
                object.set(key.as_str(), json_value(cx, item)?)?;
            }
            object.into_value()
        }
    })
}

/// A `Point` (`{ x, y }`).
fn point_object<'js>(
    cx: &Ctx<'js>,
    p: nsh_core::geometry::Point<nsh_core::geometry::Points>,
) -> rquickjs::Result<rquickjs::Object<'js>> {
    let obj = rquickjs::Object::new(cx.clone())?;
    obj.set("x", p.x.0)?;
    obj.set("y", p.y.0)?;
    Ok(obj)
}

/// A `Size` (`{ width, height }`).
fn size_object<'js>(
    cx: &Ctx<'js>,
    s: nsh_core::geometry::Size<nsh_core::geometry::Points>,
) -> rquickjs::Result<rquickjs::Object<'js>> {
    let obj = rquickjs::Object::new(cx.clone())?;
    obj.set("width", s.width.0)?;
    obj.set("height", s.height.0)?;
    Ok(obj)
}

/// A `Bounds` (`{ origin, size }`).
fn bounds_object<'js>(
    cx: &Ctx<'js>,
    b: nsh_core::geometry::Bounds<nsh_core::geometry::Points>,
) -> rquickjs::Result<rquickjs::Object<'js>> {
    let obj = rquickjs::Object::new(cx.clone())?;
    obj.set("origin", point_object(cx, b.origin)?)?;
    obj.set("size", size_object(cx, b.size)?)?;
    Ok(obj)
}

/// `Modifiers` (`{ control, alt, shift, platform, altGraph }`, GPUI's names).
fn modifiers_object<'js>(
    cx: &Ctx<'js>,
    m: &nsh_core::keymap::Modifiers,
) -> rquickjs::Result<rquickjs::Object<'js>> {
    let obj = rquickjs::Object::new(cx.clone())?;
    obj.set("control", m.ctrl)?;
    obj.set("alt", m.alt)?;
    obj.set("shift", m.shift)?;
    obj.set("platform", m.cmd)?;
    obj.set("altGraph", m.alt_graph)?;
    Ok(obj)
}

fn payload_value<'js>(cx: &Ctx<'js>, value: &PayloadValue) -> rquickjs::Result<Value<'js>> {
    Ok(match value {
        PayloadValue::Number(n) => Value::new_float(cx.clone(), *n),
        PayloadValue::Bool(b) => Value::new_bool(cx.clone(), *b),
        PayloadValue::Str(s) => rquickjs::String::from_str(cx.clone(), s)?.into_value(),
        PayloadValue::Null => Value::new_null(cx.clone()),
        PayloadValue::Point(p) => point_object(cx, *p)?.into_value(),
        PayloadValue::Size(s) => size_object(cx, *s)?.into_value(),
        PayloadValue::Bounds(b) => bounds_object(cx, *b)?.into_value(),
    })
}

fn describe(value: Value<'_>) -> String {
    match value.as_exception() {
        Some(e) => e.to_string(),
        None => format!("{value:?}"),
    }
}

/// The declarations of the globals besides the web classes and functions
/// (`web/`): the host's (console, timers, frames, below) and QuickJS-NG's
/// that apps use. A test checks that each exists, and that every global
/// the host adds is declared.
pub(crate) const GLOBALS: &str = r#"declare var console: {
  log(...data: unknown[]): void;
  info(...data: unknown[]): void;
  debug(...data: unknown[]): void;
  warn(...data: unknown[]): void;
  error(...data: unknown[]): void;
};

declare var performance: {
  /** Milliseconds since the JS context started, with sub-millisecond precision. */
  now(): number;
};

interface ImportMeta {
  /** The module's own URL: `file:` in the app's directory on desktop hosts,
   * the page's on the web, `asset:/` in packaged mobile apps, so
   * `new URL("./data.json", import.meta.url)` names a file beside it. */
  readonly url: string;
}

declare function setTimeout(handler: (...args: any[]) => void, timeout?: number, ...args: any[]): number;
declare function setInterval(handler: (...args: any[]) => void, timeout?: number, ...args: any[]): number;
declare function clearTimeout(id: number | undefined): void;
declare function clearInterval(id: number | undefined): void;
declare function queueMicrotask(callback: () => void): void;
/** Runs `callback` at the next display frame with its time in milliseconds. */
declare function requestAnimationFrame(callback: (time: number) => void): number;
declare function cancelAnimationFrame(id: number | undefined): void;
declare function atob(data: string): string;
declare function btoa(data: string): string;

/** `<If when={…} else={…}>…</If>`: renders its children while `when` is
 * truthy, else `else`. A function child gets an accessor of `when`'s value,
 * which is set while it shows: `<If when={user()}>{(u) => <Text>{u().name}</Text>}</If>`.
 * A global (no import), like `Each`. */
declare function If<T>(props: {
  when: T;
  else?: import("./types").JSX.Element;
  children?: import("./types").JSX.Element | ((value: () => NonNullable<T>) => import("./types").JSX.Element);
}): import("./types").JSX.Element;
declare function If(props: {
  when: unknown;
  else?: import("./types").JSX.Element;
  children?: import("./types").JSX.Element;
}): import("./types").JSX.Element;
/** `<Each of={items} key={…}>{(item, index) => …}</Each>`: renders
 * `children(item, index)` for each item of `of` (`item()` and `index()`
 * follow the row); rows are kept by `key` (default: the item; objects by
 * identity, other values by value). `key="index"` keeps rows by position:
 * a changed item updates its row's `item()` instead of making a new row
 * (a list of strings streamed in, edited in place). A global. */
declare function Each<T>(props: {
  of: readonly T[] | null | undefined;
  key?: "index" | ((item: T, index: number) => unknown);
  children: (item: () => T, index: () => number) => import("./types").JSX.Element;
}): import("./types").JSX.Element;

declare class DOMException extends Error {
  constructor(message?: string, name?: string);
  readonly name: string;
  readonly message: string;
  readonly code: number;
}
"#;

fn install(cx: &Ctx<'_>, shared: &Rc<Shared>) -> rquickjs::Result<()> {
    let globals = cx.globals();
    console::install(cx)?;
    web::install(cx.as_raw().as_ptr())?;
    crate::chunks::install(cx.as_raw().as_ptr()).map_err(|_| rquickjs::Error::Exception)?;
    crate::dom::install_globals(cx.as_raw().as_ptr());

    for (name, repeat) in [("setTimeout", false), ("setInterval", true)] {
        let s = shared.clone();
        globals.set(
            name,
            Function::new(
                cx.clone(),
                move |callback: Function<'_>, delay: Opt<f64>| -> u32 {
                    let ms = delay.0.unwrap_or(0.0);
                    let delay = Duration::from_secs_f64(if ms.is_finite() && ms > 0.0 {
                        ms / 1000.0
                    } else {
                        0.0
                    });
                    let callback = Persistent::save(&callback.ctx().clone(), callback);
                    s.timers.borrow_mut().add(callback, delay, repeat)
                },
            )?,
        )?;
    }
    let s = shared.clone();
    globals.set(
        "requestAnimationFrame",
        Function::new(cx.clone(), move |callback: Function<'_>| -> u32 {
            let id = s.next_frame_id.get().wrapping_add(1).max(1);
            s.next_frame_id.set(id);
            let callback = Persistent::save(&callback.ctx().clone(), callback);
            s.frames.borrow_mut().push((id, callback));
            id
        })?,
    )?;
    let s = shared.clone();
    globals.set(
        "cancelAnimationFrame",
        Function::new(cx.clone(), move |id: Opt<Value<'_>>| {
            if let Some(id) = handle_id(id) {
                s.frames.borrow_mut().retain(|(i, _)| *i != id);
            }
        })?,
    )?;
    for name in ["clearTimeout", "clearInterval"] {
        let s = shared.clone();
        globals.set(
            name,
            Function::new(cx.clone(), move |id: Opt<Value<'_>>| {
                if let Some(id) = handle_id(id) {
                    s.timers.borrow_mut().cancel(id);
                }
            })?,
        )?;
    }
    Ok(())
}

/// The id `clearTimeout`, `clearInterval` and `cancelAnimationFrame` were
/// given, read as the web reads it (a number, truncated; a numeric string);
/// anything else (`undefined`, `null`, objects) names no timer and is ignored,
/// never thrown at: libraries call these with ids they never got.
fn handle_id(id: Opt<Value<'_>>) -> Option<u32> {
    let id = id.0?;
    let n = match id.as_number() {
        Some(n) => n,
        None => id
            .as_string()?
            .to_string()
            .ok()?
            .trim()
            .parse::<f64>()
            .ok()?,
    };
    let n = n.trunc();
    (n.is_finite() && n >= 1.0 && n <= f64::from(u32::MAX)).then_some(n as u32)
}

#[cfg(test)]
mod tests {
    use std::time::Duration;

    use nsh_core::{
        EventKind, Op,
        geometry::{point, px},
    };

    use super::*;

    /// A bundle names the release it is built for; one that names none, or
    /// one the runtime cannot read, is the first compatible release's.
    #[test]
    fn the_bundle_names_the_release_it_is_built_for() {
        use crate::Release;
        assert_eq!(Release::parse("0.10.2"), Some(Release(0, 10, 2)));
        assert_eq!(Release::parse("1.0.0-beta.1"), Some(Release(1, 0, 0)));
        for text in ["", "1.0", "1.0.0.0", "x.1.2"] {
            assert_eq!(Release::parse(text), None, "{text}");
        }
        assert!(Release(0, 10, 0) > Release::FIRST_COMPATIBLE);

        let host = Host::new().unwrap();
        assert_eq!(host.target(), Release::FIRST_COMPATIBLE);
        host.eval_source(r#"import { target } from "nsh:rt"; target("not a release");"#)
            .unwrap();
        assert_eq!(host.target(), Release::FIRST_COMPATIBLE);
        host.eval_source(r#"import { target } from "nsh:rt"; target("0.11.3");"#)
            .unwrap();
        assert_eq!(host.target(), Release(0, 11, 3));
        // Per VM: another host keeps its own.
        assert_eq!(Host::new().unwrap().target(), Release::FIRST_COMPATIBLE);
    }

    #[test]
    fn strings_outside_a_text_are_reported_once_per_element() {
        let host = Host::new().unwrap();
        host.eval_source(
            r#"import { append, element, insert, prop, text } from "nsh:rt";
            const view = element("view");
            insert(view, () => "a");
            insert(view, () => "b");
            const label = element("text");
            insert(label, () => "shown");
            // A Rust component places what is put in it.
            const card = element("view");
            prop(card, "component", "Card");
            insert(card, () => "placed");
            const scroll = element("scroll");
            append(scroll, text("c"));"#,
        )
        .unwrap();
        let tags = host
            .cx
            .with(|cx| crate::dom::unshown_text_tags(cx.as_raw().as_ptr()));
        let bit = |t: nsh_core::Tag| 1u64 << t as u32;
        assert_eq!(tags, bit(nsh_core::Tag::View) | bit(nsh_core::Tag::Scroll));
    }

    #[test]
    fn resources_follow_their_source_and_count_the_latest_load_only() {
        let host = Host::new().unwrap();
        host.eval_source(&format!(
            r#"{REPORT}
import {{ effect, resource, signal }} from "nsh";
const id = signal(1);
const loads = [];
globalThis.report = report;
globalThis.id = id;
globalThis.loads = loads;
globalThis.user = resource(id, (n, info) => new Promise((resolve, reject) => {{
  loads.push({{ n, resolve, reject, info }});
  info.signal.addEventListener("abort", () => report(`aborted ${{n}}`));
}}));
effect(() => report(`${{user.state()}}|${{user() ?? ""}}|${{user.error() ?? ""}}|${{user.loading()}}`));"#
        ))
        .unwrap();
        assert_eq!(reported(&host), ["pending|||true"]);
        let step = |code: &str| {
            host.eval_source(code).unwrap();
            reported(&host)
        };
        // A new source aborts the running load; the old one ending later
        // changes nothing.
        assert_eq!(step("id.set(2);"), ["aborted 1"]);
        assert_eq!(step(r#"loads[0].resolve("one");"#), Vec::<String>::new());
        assert_eq!(step(r#"loads[1].resolve("two");"#), ["ready|two||false"]);
        // A refetch keeps the value and says so to the fetcher.
        assert_eq!(
            step("user.refetch(); report(`refetching ${loads[2].info.refetching}`);"),
            ["refreshing|two||true", "refetching true"]
        );
        // A failure keeps the value too.
        assert_eq!(
            step(r#"loads[2].reject(new Error("boom"));"#),
            ["errored|two|Error: boom|false"]
        );
        // A value set here clears the error; no source loads nothing.
        assert_eq!(step(r#"user.mutate("local");"#), ["ready|local||false"]);
        assert!(step("id.set(null);").is_empty());
        // Three loads in all: none for the unset source.
        host.eval_source("if (loads.length !== 3) throw new Error(`${loads.length} loads`);")
            .unwrap();
    }

    #[test]
    fn resources_without_a_source_with_values_and_throws() {
        let host = Host::new().unwrap();
        host.eval_source(&format!(
            r#"{REPORT}
import {{ effect, resource }} from "nsh";
const now = resource(() => 42);
const kept = resource(() => new Promise(() => {{}}), {{ initialValue: "first" }});
const thrown = resource(() => {{ throw new Error("no"); }});
effect(() => report(`${{now.state()}} ${{now()}} | ${{kept.state()}} ${{kept()}} | ${{thrown.state()}} ${{thrown.error()}}`));
// The methods are bound: they work taken off their resource.
const {{ loading, state }} = kept;
report(`${{loading()}} ${{state()}}`);"#
        ))
        .unwrap();
        assert_eq!(
            reported(&host),
            [
                "ready 42 | refreshing first | errored Error: no",
                "true refreshing"
            ]
        );
    }

    #[test]
    fn a_resource_going_with_its_owner_aborts_its_load() {
        let host = Host::new().unwrap();
        host.eval_source(&format!(
            r#"{REPORT}
import {{ cond, component, element, insert }} from "nsh:rt";
import {{ effect, resource, signal }} from "nsh";
const shown = signal(true);
globalThis.shown = shown;
function Card() {{
  const r = resource((info) => new Promise((resolve) => {{
    globalThis.later = resolve;
    info.signal.addEventListener("abort", () => report("aborted"));
  }}));
  effect(() => report(r.state()));
  return element("view");
}}
const root = element("view");
insert(root, cond(() => shown(), () => component(Card, {{}})));"#
        ))
        .unwrap();
        assert_eq!(reported(&host), ["pending"]);
        host.eval_source("shown.set(false);").unwrap();
        assert_eq!(reported(&host), ["aborted"]);
        // Its load ending later finds nothing to change.
        host.eval_source(r#"later("late");"#).unwrap();
        assert!(reported(&host).is_empty());
    }

    #[test]
    fn a_function_an_effect_returns_is_its_cleanup() {
        let host = Host::new().unwrap();
        host.eval_source(&format!(
            r#"{REPORT}
import {{ cond, component, element, insert }} from "nsh:rt";
import {{ effect, signal }} from "nsh";
const n = signal(0);
const shown = signal(true);
globalThis.n = n;
globalThis.shown = shown;
function Ticker() {{
  effect(() => {{
    const v = n();
    report(`run ${{v}}`);
    return () => report(`cleanup ${{v}}`);
  }});
  // An async effect's promise is not a cleanup.
  effect(async () => {{ n(); }});
  return element("view");
}}
const root = element("view");
insert(root, cond(() => shown(), () => component(Ticker, {{}})));"#
        ))
        .unwrap();
        assert_eq!(reported(&host), ["run 0"]);
        host.eval_source("n.set(1);").unwrap();
        assert_eq!(reported(&host), ["cleanup 0", "run 1"]);
        host.eval_source("shown.set(false);").unwrap();
        assert_eq!(reported(&host), ["cleanup 1"]);
    }

    fn ops(host: &Host) -> Vec<Op> {
        let mut out = Vec::new();
        host.take_ops(&mut out);
        out
    }

    /// Reports `v` as a text node (`report(v)`; the native renderer's ops
    /// are what tests observe).
    const REPORT: &str = r#"import { text } from "nsh:rt";
const report = (v) => text(String(v));
"#;

    /// The text nodes created since the last call.
    fn reported(host: &Host) -> Vec<String> {
        ops(host)
            .into_iter()
            .filter_map(|op| match op {
                Op::CreateText { text, .. } => Some(text),
                _ => None,
            })
            .collect()
    }

    #[cfg(all(not(target_arch = "wasm32"), feature = "websocket"))]
    #[test]
    fn native_future_wakes_engine_and_resumes_without_idle_polling() {
        let host = Host::new().unwrap();
        host.scheduler.start_io().unwrap();
        let (send, receive) = std::sync::mpsc::channel();
        host.set_system_wake(Arc::new(move || {
            let _ = send.send(());
        }));
        host.cx.with(|cx| {
            cx.globals().set("nativeFutureDone", false).unwrap();
            let owned = cx.clone();
            cx.spawn(async move {
                tokio::time::sleep(Duration::from_millis(25)).await;
                owned.globals().set("nativeFutureDone", true).unwrap();
            });
        });
        host.run_jobs();
        assert!(host.has_system_tasks());
        assert!(
            !host
                .cx
                .with(|cx| cx.globals().get::<_, bool>("nativeFutureDone").unwrap())
        );
        receive
            .recv_timeout(Duration::from_secs(2))
            .expect("native timer wakes owning engine");
        host.run_system();
        assert!(
            host.cx
                .with(|cx| cx.globals().get::<_, bool>("nativeFutureDone").unwrap())
        );
        assert!(!host.has_system_tasks());
    }

    #[cfg(all(not(target_arch = "wasm32"), feature = "websocket"))]
    #[test]
    fn dropping_host_cancels_pending_native_future_and_wake_callback() {
        struct Dropped(Arc<AtomicBool>);
        impl Drop for Dropped {
            fn drop(&mut self) {
                self.0.store(true, Ordering::SeqCst);
            }
        }
        let dropped = Arc::new(AtomicBool::new(false));
        let callback_dropped = Arc::new(AtomicBool::new(false));
        let host = Host::new().unwrap();
        host.scheduler.start_io().unwrap();
        let callback_guard = Dropped(callback_dropped.clone());
        host.set_system_wake(Arc::new(move || {
            let _ = &callback_guard;
        }));
        let guard = Dropped(dropped.clone());
        host.cx.with(|cx| {
            let owned = cx.clone();
            cx.spawn(async move {
                let (_guard, _owned) = (guard, owned);
                tokio::time::sleep(Duration::from_secs(60)).await;
            });
        });
        host.run_jobs();
        assert!(host.has_system_tasks());
        drop(host);
        assert!(
            dropped.load(Ordering::SeqCst),
            "pending future must be destroyed with VM"
        );
        assert!(
            callback_dropped.load(Ordering::SeqCst),
            "engine callback must not retain old generation"
        );
    }

    #[cfg(all(not(target_arch = "wasm32"), feature = "websocket"))]
    #[test]
    fn stopping_host_cancels_native_work_without_dropping_snapshot() {
        struct Dropped(Arc<AtomicBool>);
        impl Drop for Dropped {
            fn drop(&mut self) {
                self.0.store(true, Ordering::SeqCst);
            }
        }
        let dropped = Arc::new(AtomicBool::new(false));
        let callback_dropped = Arc::new(AtomicBool::new(false));
        let host = Host::new().unwrap();
        host.scheduler.start_io().unwrap();
        let callback_guard = Dropped(callback_dropped.clone());
        host.set_system_wake(Arc::new(move || {
            let _ = &callback_guard;
        }));
        let guard = Dropped(dropped.clone());
        host.cx.with(|cx| {
            let owned = cx.clone();
            cx.spawn(async move {
                let (_guard, _owned) = (guard, owned);
                tokio::time::sleep(Duration::from_secs(60)).await;
            });
        });
        host.run_jobs();
        assert!(host.has_system_tasks());
        host.eval_source(&format!("{REPORT}report('frozen UI');"))
            .unwrap();
        host.stop("test stop".into());
        assert!(!host.cx.is_live());
        assert!(host.rt.borrow().is_none());
        assert_eq!(reported(&host), ["frozen UI"]);
        assert!(!host.has_system_tasks());
        assert!(!host.has_posted());
        assert!(!host.wants_frame());
        assert!(host.next_timer().is_none());
        assert_eq!(host.object_count(), 0);
        host.run_jobs();
        host.run_system();
        host.run_posted();
        host.run_frame();
        host.collect_garbage();
        host.set_stop_flag(Arc::new(AtomicBool::new(false)));
        host.take_chunk_requests(&mut Vec::new());
        assert!(host.eval_source("throw 1").is_err());
        host.stop("repeated stop".into());
        assert!(
            dropped.load(Ordering::SeqCst),
            "pending future must be destroyed with VM"
        );
        assert!(
            callback_dropped.load(Ordering::SeqCst),
            "engine callback must not retain old generation"
        );
    }

    #[cfg(all(not(target_arch = "wasm32"), feature = "websocket"))]
    #[test]
    fn top_level_await_resumes_and_reports_rejection_on_native_wake() {
        let mut host = Host::new().unwrap();
        host.scheduler.start_io().unwrap();
        let errors = Rc::new(RefCell::new(Vec::new()));
        let captured = errors.clone();
        host.set_error_handler(Box::new(move |error| {
            captured.borrow_mut().push(error.message.clone())
        }));
        let (send, receive) = std::sync::mpsc::channel();
        host.set_system_wake(Arc::new(move || {
            let _ = send.send(());
        }));
        host.cx.with(|cx| {
            let promise = Promise::wrap_future(&cx, async {
                tokio::time::sleep(Duration::from_millis(25)).await;
                7
            })
            .unwrap();
            cx.globals().set("nativePending", promise).unwrap();
        });
        host.eval_source("await nativePending; throw new Error('native TLA rejected');")
            .unwrap();
        assert_eq!(host.evaluations.borrow().len(), 1);
        receive.recv_timeout(Duration::from_secs(2)).unwrap();
        host.run_system();
        assert!(host.evaluations.borrow().is_empty());
        assert!(
            errors
                .borrow()
                .iter()
                .any(|error| error.contains("native TLA rejected"))
        );
    }

    #[cfg(all(not(target_arch = "wasm32"), feature = "websocket"))]
    #[test]
    fn oom_retires_pending_native_future_without_dropping_host() {
        struct Dropped(Arc<AtomicBool>);
        impl Drop for Dropped {
            fn drop(&mut self) {
                self.0.store(true, Ordering::SeqCst);
            }
        }
        let dropped = Arc::new(AtomicBool::new(false));
        let host = sandboxed(Limits {
            memory_bytes: 16 << 20,
            ..Limits::default()
        });
        host.scheduler.start_io().unwrap();
        let guard = Dropped(dropped.clone());
        host.cx.with(|cx| {
            cx.spawn(async move {
                let _guard = guard;
                tokio::time::sleep(Duration::from_secs(60)).await;
            })
        });
        host.run_jobs();
        let _ = host.eval_source(
            "try { const keep=[]; for (;;) keep.push(new Array(100000).fill(1)); } catch (_) {}",
        );
        assert!(host.fatal().is_some());
        assert!(!host.cx.is_live());
        assert!(host.rt.borrow().is_none());
        assert!(dropped.load(Ordering::SeqCst));
        assert!(!host.has_system_tasks());
    }

    #[test]
    fn stopping_host_releases_exit_delegate_and_refuses_replacement() {
        let host = Host::new().unwrap();
        let captured = Rc::new(());
        let retained = captured.clone();
        host.set_exit_handler(Rc::new(move |_| {
            let _ = &retained;
        }));
        assert_eq!(Rc::strong_count(&captured), 2);
        host.stop("test exit delegate lifetime".into());
        assert_eq!(Rc::strong_count(&captured), 1);
        assert!(host.shared.system_exit_handler.borrow().is_none());
        let retained = captured.clone();
        host.set_exit_handler(Rc::new(move |_| {
            let _ = &retained;
        }));
        assert_eq!(Rc::strong_count(&captured), 1);
        assert!(host.shared.system_exit_handler.borrow().is_none());
        host.stop("idempotent stop".into());
    }

    #[test]
    fn press_payload_has_both_positions() {
        let host = Host::new().unwrap();
        let event = nsh_core::PressEvent {
            position: point(px(3.0), px(4.5)),
            page_position: point(px(30.0), px(40.5)),
            modifiers: nsh_core::keymap::Modifiers {
                ctrl: true,
                ..Default::default()
            },
            clicks: 2,
        };
        host.cx.with(|cx| {
            let value = payload_object(&cx, &EventPayload::Press(event)).unwrap();
            let obj = value.as_object().unwrap();
            let num = |o: &str, k: &str| {
                let o: rquickjs::Object = obj.get(o).unwrap();
                o.get::<_, f64>(k).unwrap()
            };
            assert_eq!(
                (
                    num("position", "x"),
                    num("position", "y"),
                    num("pagePosition", "x"),
                    num("pagePosition", "y")
                ),
                (3.0, 4.5, 30.0, 40.5)
            );
            let modifiers: rquickjs::Object = obj.get("modifiers").unwrap();
            assert!(modifiers.get::<_, bool>("control").unwrap());
            assert!(!modifiers.get::<_, bool>("shift").unwrap());
            assert!(!modifiers.get::<_, bool>("altGraph").unwrap());
            assert_eq!(obj.get::<_, u32>("clickCount").unwrap(), 2);
        });
    }

    #[test]
    fn a_pointerless_press_has_no_clicks() {
        // A keyboard or assistive technology activation (#2506) must not
        // read as a click at the origin: `clickCount` 0, as the DOM's
        // `detail`, while a real click keeps 1.
        let host = Host::new().unwrap();
        host.eval_source(
            r#"import { element, prop } from "nsh:rt";
            globalThis.counts = [];
            const view = element("view");
            prop(view, "onPress", (e) => globalThis.counts.push(e.clickCount));"#,
        )
        .unwrap();
        host.dispatch_event(2, EventKind::Press, &EventPayload::None);
        host.dispatch_event(
            2,
            EventKind::Press,
            &EventPayload::Press(nsh_core::PressEvent {
                clicks: 1,
                ..Default::default()
            }),
        );
        let counts: Vec<u32> = host.cx.with(|cx| cx.eval("globalThis.counts").unwrap());
        assert_eq!(counts, vec![0, 1]);
    }

    #[test]
    fn mouse_payload_has_both_positions_the_modifiers_and_the_button() {
        let host = Host::new().unwrap();
        let event = nsh_core::MouseEvent::new(
            point(px(3.0), px(4.5)),
            point(px(30.0), px(40.5)),
            nsh_core::keymap::Modifiers {
                shift: true,
                cmd: true,
                ..Default::default()
            },
            Some(nsh_core::MouseButton::Left),
        );
        host.cx.with(|cx| {
            let value = payload_object(&cx, &EventPayload::Mouse(event)).unwrap();
            let obj = value.as_object().unwrap();
            let num = |o: &str, k: &str| {
                let o: rquickjs::Object = obj.get(o).unwrap();
                o.get::<_, f64>(k).unwrap()
            };
            let flag = |k: &str| {
                let m: rquickjs::Object = obj.get("modifiers").unwrap();
                m.get::<_, bool>(k).unwrap()
            };
            assert_eq!(
                (
                    num("position", "x"),
                    num("position", "y"),
                    num("pagePosition", "x"),
                    num("pagePosition", "y")
                ),
                (3.0, 4.5, 30.0, 40.5)
            );
            assert!(flag("shift") && flag("platform"));
            assert!(!flag("alt") && !flag("control"));
            assert_eq!(obj.get::<_, String>("pressedButton").unwrap(), "left");
            let none = nsh_core::MouseEvent::default();
            let value = payload_object(&cx, &EventPayload::Mouse(none)).unwrap();
            let pressed: Value = value.as_object().unwrap().get("pressedButton").unwrap();
            assert!(pressed.is_null());
            let changed: Value = value.as_object().unwrap().get("button").unwrap();
            assert!(changed.is_null());
        });
    }

    #[test]
    fn released_mouse_payload_has_its_button() {
        let host = Host::new().unwrap();
        let event = nsh_core::MouseEvent::released(
            point(px(5.0), px(6.5)),
            point(px(50.0), px(60.5)),
            nsh_core::keymap::Modifiers {
                shift: true,
                ..Default::default()
            },
            nsh_core::MouseButton::Right,
        );
        host.cx.with(|cx| {
            let value = payload_object(&cx, &EventPayload::Mouse(event)).unwrap();
            let obj = value.as_object().unwrap();
            let num = |o: &str, k: &str| {
                let o: rquickjs::Object = obj.get(o).unwrap();
                o.get::<_, f64>(k).unwrap()
            };
            let flag = |k: &str| {
                let m: rquickjs::Object = obj.get("modifiers").unwrap();
                m.get::<_, bool>(k).unwrap()
            };
            assert_eq!(
                (
                    num("position", "x"),
                    num("position", "y"),
                    num("pagePosition", "x"),
                    num("pagePosition", "y")
                ),
                (5.0, 6.5, 50.0, 60.5)
            );
            assert!(flag("shift"));
            assert_eq!(obj.get::<_, String>("button").unwrap(), "right");
            let pressed: Value = obj.get("pressedButton").unwrap();
            assert!(pressed.is_null());
        });
    }

    #[test]
    fn pinch_payload_is_as_declared() {
        let host = Host::new().unwrap();
        let event = nsh_core::PinchEvent::new(
            point(px(1.0), px(2.0)),
            point(px(11.0), px(22.0)),
            nsh_core::geometry::Percentage(0.25),
            nsh_core::PinchPhase::Start,
            Default::default(),
        );
        host.cx.with(|cx| {
            let value = payload_object(&cx, &EventPayload::Pinch(event)).unwrap();
            let obj = value.as_object().unwrap();
            assert_eq!(obj.get::<_, f64>("delta").unwrap(), 0.25);
            assert_eq!(obj.get::<_, String>("phase").unwrap(), "start");
            let page: rquickjs::Object = obj.get("pagePosition").unwrap();
            assert_eq!(page.get::<_, f64>("y").unwrap(), 22.0);
            let modifiers: rquickjs::Object = obj.get("modifiers").unwrap();
            assert!(!modifiers.get::<_, bool>("shift").unwrap());
        });
    }

    #[test]
    fn mouse_payload_has_pen_fields() {
        let host = Host::new().unwrap();
        let mouse = nsh_core::MouseEvent::new(
            point(px(1.0), px(2.0)),
            point(px(1.0), px(2.0)),
            Default::default(),
            Some(nsh_core::MouseButton::Left),
        );
        let pen = mouse.with_pointer(nsh_core::PointerType::Pen, 0.75, 30.0, -15.0);
        host.cx.with(|cx| {
            let value = payload_object(&cx, &EventPayload::Mouse(mouse)).unwrap();
            let obj = value.as_object().unwrap();
            assert_eq!(obj.get::<_, String>("pointerType").unwrap(), "mouse");
            // A device without pressure: the DOM's 0.5 with a button down.
            assert_eq!(obj.get::<_, f64>("pressure").unwrap(), 0.5);
            assert_eq!(obj.get::<_, f64>("tiltX").unwrap(), 0.0);
            let value = payload_object(&cx, &EventPayload::Mouse(pen)).unwrap();
            let obj = value.as_object().unwrap();
            assert_eq!(obj.get::<_, String>("pointerType").unwrap(), "pen");
            assert_eq!(obj.get::<_, f64>("pressure").unwrap(), 0.75);
            assert_eq!(obj.get::<_, f64>("tiltX").unwrap(), 30.0);
            assert_eq!(obj.get::<_, f64>("tiltY").unwrap(), -15.0);
        });
    }

    #[test]
    fn context_menu_payload_has_both_positions() {
        let host = Host::new().unwrap();
        let event = nsh_core::ContextMenuEvent::new(
            point(px(1.0), px(2.0)),
            point(px(11.0), px(22.0)),
            nsh_core::keymap::Modifiers {
                ctrl: true,
                ..Default::default()
            },
            Some(nsh_core::PointerType::Mouse),
        );
        host.cx.with(|cx| {
            let value = payload_object(&cx, &EventPayload::ContextMenu(event)).unwrap();
            let obj = value.as_object().unwrap();
            let num = |o: &str, k: &str| {
                let o: rquickjs::Object = obj.get(o).unwrap();
                o.get::<_, f64>(k).unwrap()
            };
            assert_eq!(
                (
                    num("position", "x"),
                    num("position", "y"),
                    num("pagePosition", "x"),
                    num("pagePosition", "y")
                ),
                (1.0, 2.0, 11.0, 22.0)
            );
            let m: rquickjs::Object = obj.get("modifiers").unwrap();
            assert!(m.get::<_, bool>("control").unwrap());
            assert!(!m.get::<_, bool>("platform").unwrap());
            assert_eq!(obj.get::<_, String>("pointerType").unwrap(), "mouse");
            let keyboard = nsh_core::ContextMenuEvent::new(
                event.position,
                event.page_position,
                event.modifiers,
                None,
            );
            let value = payload_object(&cx, &EventPayload::ContextMenu(keyboard)).unwrap();
            let pointer: Value = value.as_object().unwrap().get("pointerType").unwrap();
            assert!(pointer.is_null());
        });
    }

    #[test]
    fn file_drag_entry_delivers_metadata_before_drop_and_keeps_no_argument_handlers() {
        let host = Host::new().unwrap();
        host.eval_source(
            r#"
            import { element, prop } from "nsh:rt";
            globalThis.seen = [];
            const target = element("view");
            prop(target, "onFileDragEnter", (e) => seen.push("enter " + e.uris.join(";") + " " + e.mimeTypes.join(";")));
            prop(target, "onFileDragLeave", () => seen.push("leave"));
            prop(target, "onFileDrop", (e) => seen.push("drop " + e.uris.join(";")));
            const old = element("view");
            prop(old, "onFileDragEnter", () => seen.push("old"));
        "#,
        )
        .unwrap();
        let first = EventPayload::FileDrop(vec![
            "file:///tmp/a%20b.png".into(),
            "file:///tmp/%E4%B8%AD.txt".into(),
        ]);
        let next = EventPayload::FileDrop(vec!["file:///tmp/next.png".into()]);
        host.dispatch_event(2, EventKind::FileDragEnter, &first);
        host.dispatch_event(2, EventKind::FileDragLeave, &EventPayload::None);
        host.dispatch_event(2, EventKind::FileDragEnter, &next);
        host.dispatch_event(2, EventKind::FileDrop, &next);
        host.dispatch_event(4, EventKind::FileDragEnter, &first);
        host.cx.with(|cx| {
            let seen: Vec<String> = cx.globals().get("seen").unwrap();
            assert_eq!(
                seen,
                [
                    "enter file:///tmp/a%20b.png;file:///tmp/%E4%B8%AD.txt image/png;text/plain",
                    "leave",
                    "enter file:///tmp/next.png image/png",
                    "drop file:///tmp/next.png",
                    "old"
                ]
            );
        });
    }

    #[test]
    fn file_drop_payload_keeps_the_native_uri_list() {
        let host = Host::new().unwrap();
        let uris = vec![
            "file:///tmp/a%20b.txt".into(),
            "file:///tmp/%E4%B8%AD%E6%96%87/".into(),
        ];
        host.cx.with(|cx| {
            let value = payload_object(&cx, &EventPayload::FileDrop(uris.clone())).unwrap();
            let actual: Vec<String> = value.as_object().unwrap().get("uris").unwrap();
            assert_eq!(actual, uris);
            let types: Vec<String> = value.as_object().unwrap().get("mimeTypes").unwrap();
            assert_eq!(types, ["text/plain", ""]);
        });
    }

    #[test]
    fn paste_payload_hands_files_over_as_file_objects() {
        let host = Host::new().unwrap();
        let mut paste = nsh_core::PasteEvent::new("hi");
        paste.files.push(nsh_core::PastedFile::image(vec![
            0x89, b'P', b'N', b'G', 1, 2,
        ]));
        paste.uris.push("file:///tmp/a.txt".into());
        host.cx.with(|cx| {
            let value = payload_object(&cx, &EventPayload::Paste(Box::new(paste))).unwrap();
            cx.globals().set("pasted", value).unwrap();
            let summary: String = cx
                .eval(
                    "const f = pasted.files[0]; \
                     `${pasted.text} ${f instanceof File} ${f.name} ${f.type} ${f.size} ${pasted.uris[0]}`",
                )
                .unwrap();
            assert_eq!(summary, "hi true image.png image/png 6 file:///tmp/a.txt");
        });
    }

    #[test]
    fn styles_decode_shadows_and_corners() {
        let host = Host::new().unwrap();
        host.eval_source(
            r##"import { element, prop } from "nsh:rt";
            prop(element("view"), "style", {
                flexDirection: "row", backgroundColor: "#ff0000", bogus: 1,
                boxShadow: "2px 6px 10px rgb(0 0 0 / 0.25)", textShadow: "0 1px 4px #000",
                borderRadius: 12, borderBottomLeftRadius: 0,
            });"##,
        )
        .unwrap();
        let style = ops(&host)
            .into_iter()
            .find_map(|op| match op {
                Op::SetStyle { style, .. } => Some(style),
                _ => None,
            })
            .unwrap();
        assert_eq!(format!("{:?}", style.layout.flex_direction), "Row");
        assert_eq!(style.view.background_color, nsh_core::Color(0xff00_00ff));
        let shadow = style.view.effects.as_ref().unwrap().box_shadows[0];
        assert_eq!(
            (shadow.offset_x.0, shadow.offset_y.0, shadow.blur.0),
            (2.0, 6.0, 10.0)
        );
        assert_eq!(style.text.shadow_radius.map(|r| r.0), Some(4.0));
        assert_eq!(
            style.view.radii().to_array().map(|r| r.0),
            [12.0, 12.0, 12.0, 0.0]
        );
    }

    /// `style={[base, props.style]}` where `props.style` is itself a list:
    /// nested lists merge left to right, falsy entries skipped.
    #[test]
    fn styles_flatten_nested_lists() {
        let host = Host::new().unwrap();
        host.eval_source(
            r##"import { element, prop } from "nsh:rt";
            const inner = [{ opacity: 0.5 }, false, [null, { backgroundColor: "#00ff00" }]];
            prop(element("view"), "style", [
                { flexDirection: "row", backgroundColor: "#ff0000", opacity: 1 },
                inner,
                undefined,
            ]);"##,
        )
        .unwrap();
        let style = ops(&host)
            .into_iter()
            .find_map(|op| match op {
                Op::SetStyle { style, .. } => Some(style),
                _ => None,
            })
            .unwrap();
        assert_eq!(format!("{:?}", style.layout.flex_direction), "Row");
        assert_eq!(style.view.background_color, nsh_core::Color(0x00ff_00ff));
        assert_eq!(style.view.opacity, 0.5);
    }

    /// `Intl` names local time by the zone it formats it in, whichever the
    /// environment reports (a test's, which moves no local time): the
    /// zone `resolvedOptions()` gives formats as local time does, at any
    /// instant. On a machine outside UTC the reported `UTC` is not local
    /// time; on one in UTC, `+08:00` is not. It holds under any `TZ`:
    /// `Asia/Singapore` (+07:30 at epoch 0), `JST-9`, and
    /// `CET-1CEST,M3.5.0,M10.5.0/3`, whose summer instant shows a zone
    /// named by one offset.
    #[test]
    fn names_the_zone_it_formats_local_time_in() {
        let host = Host::new().unwrap();
        let script = format!(
            r#"{REPORT}
            const options = {{
              year: "numeric", month: "2-digit", day: "2-digit",
              hour: "2-digit", minute: "2-digit", hourCycle: "h23",
            }};
            const local = new Intl.DateTimeFormat("en-US", options);
            const zone = local.resolvedOptions().timeZone;
            const named = new Intl.DateTimeFormat("en-US", {{ ...options, timeZone: zone }});
            // 1970 (Singapore at +07:30), a northern summer and winter.
            const instants = [0, 1720000000000, 1736000000000];
            const differ = instants.filter((t) => named.format(t) !== local.format(t));
            report(differ.length === 0 ? "agrees" : `${{zone}}: ${{differ.map((t) => named.format(t) + " vs " + local.format(t))}}`);
            "#
        );
        for zone in ["UTC", "+08:00", "Asia/Tokyo"] {
            let mut env = Environment::default();
            env.locale_settings.time_zone = nsh_core::platform::TimeZone::parse(zone).unwrap();
            host.set_environment(&env);
            host.eval_source(&script).unwrap();
        }
        assert_eq!(reported(&host), ["agrees", "agrees", "agrees"]);
    }

    /// `Intl` and the `toLocaleString`s format natively, in the device's
    /// locale by default.
    #[test]
    fn formats_numbers_and_dates() {
        let host = Host::new().unwrap();
        // What a bundle listing these languages registers (`nsh:rt`'s
        // `i18n`): the runtime has English only.
        let mut languages = serde_json::Map::new();
        for lang in ["de", "fr", "ja", "ko"] {
            let data = nsh_i18n::language_data(lang).unwrap();
            languages.insert(lang.into(), serde_json::from_str(data).unwrap());
        }
        host.cx
            .with(|cx| crate::web::add_languages(cx.as_raw().as_ptr(), languages));
        host.eval_source(&format!(
            r#"{REPORT}
            report((1234567.891).toLocaleString());
            report((1234.5).toLocaleString("de-DE", {{ style: "currency", currency: "EUR" }}));
            report((0.256).toLocaleString("en-US", {{ style: "percent", maximumFractionDigits: 1 }}));
            report(12345678901234567890n.toLocaleString("en-US"));
            const compact = new Intl.NumberFormat("en", {{ notation: "compact" }});
            report([1234, 1500000, 999999].map(compact.format).join(" "));
            report(new Intl.NumberFormat("en", {{ signDisplay: "always", minimumFractionDigits: 2 }}).format(3));
            report(new Intl.NumberFormat("en", {{ useGrouping: false }}).format(12345));
            report(JSON.stringify(new Intl.NumberFormat("en", {{ style: "currency", currency: "USD" }}).formatToParts(-1.5)));
            report(new Intl.NumberFormat("fr").resolvedOptions().locale);
            const at = Date.UTC(2026, 9, 16, 15, 4, 5);
            const utc = {{ timeZone: "UTC" }};
            report(new Intl.DateTimeFormat("en-US", {{ ...utc, hour: "2-digit", minute: "2-digit", hour12: false }}).format(at));
            report(new Date(at).toLocaleString("en-US", utc));
            report(new Date(at).toLocaleDateString("en-US", {{ ...utc, dateStyle: "full" }}));
            report(new Date(at).toLocaleTimeString("ko-KR", {{ timeZone: "+09:00" }}));
            report(new Intl.DateTimeFormat("en-US", {{ timeZone: "UTC", dateStyle: "medium", timeStyle: "short" }}).format(new Date(at)));
            report(new Intl.DateTimeFormat().resolvedOptions().locale);
            report(new Date(NaN).toLocaleString());
            try {{ new Intl.NumberFormat("en", {{ style: "currency" }}); }} catch (e) {{ report(e.name); }}
            try {{ new Intl.DateTimeFormat("en", {{ timeZone: "Mars/Olympus" }}); }} catch (e) {{ report(e.name); }}
            report(Intl.NumberFormat.supportedLocalesOf(["xx", "ja-jp"]).join());
            report(Object.prototype.toString.call(Intl));
            "#
        ))
        .unwrap();
        assert_eq!(
            reported(&host),
            [
                "1,234,567.891",
                "1.234,50\u{a0}€",
                "25.6%",
                "12,345,678,901,234,567,890",
                "1.2K 1.5M 1M",
                "+3.00",
                "12345",
                r#"[{"type":"minusSign","value":"-"},{"type":"currency","value":"$"},{"type":"integer","value":"1"},{"type":"decimal","value":"."},{"type":"fraction","value":"50"}]"#,
                "fr",
                "15:04",
                "10/16/2026, 3:04:05 PM",
                "Friday, October 16, 2026",
                "오전 12:04:05",
                "Oct 16, 2026, 3:04 PM",
                "en-US",
                "Invalid Date",
                "TypeError",
                "RangeError",
                "ja-JP",
                "[object Intl]",
            ]
        );
    }

    /// `Intl.ListFormat` joins a list by its count with the language's
    /// conjunction, disjunction or unit pattern, and reports the type and
    /// style it resolved.
    #[test]
    fn formats_lists() {
        let host = Host::new().unwrap();
        let mut languages = serde_json::Map::new();
        for lang in ["de", "ja", "tr"] {
            let data = nsh_i18n::language_data(lang).unwrap();
            languages.insert(lang.into(), serde_json::from_str(data).unwrap());
        }
        host.cx
            .with(|cx| crate::web::add_languages(cx.as_raw().as_ptr(), languages));
        host.eval_source(&format!(
            r#"{REPORT}
            const en = (options) => new Intl.ListFormat("en", options);
            report(JSON.stringify(en().format([])));
            report(en().format(["apples"]));
            report(en().format(["apples", "oranges"]));
            report(en().format(["apples", "oranges", "pears"]));
            report([
              en({{ type: "conjunction", style: "long" }}),
              en({{ type: "conjunction", style: "short" }}),
              en({{ type: "conjunction", style: "narrow" }}),
              en({{ type: "disjunction", style: "long" }}),
              en({{ type: "disjunction", style: "short" }}),
              en({{ type: "disjunction", style: "narrow" }}),
              en({{ type: "unit", style: "long" }}),
              en({{ type: "unit", style: "short" }}),
              en({{ type: "unit", style: "narrow" }}),
            ].map((f, i) => f.format(i < 6 ? ["apples", "oranges", "pears"] : ["10", "m", "s"])).join(" | "));
            report(new Intl.ListFormat("tr").format(["Ali", "Ayşe", "Mehmet"]));
            report(new Intl.ListFormat("de").format(["Ali", "Ayşe", "Mehmet"]));
            report(new Intl.ListFormat("ja").format(["Ali", "Ayşe", "Mehmet"]));
            report(JSON.stringify(new Intl.ListFormat("en", {{ type: "disjunction" }}).formatToParts(["tea", "coffee"])));
            report(JSON.stringify(new Intl.ListFormat("en", {{ type: "unit", style: "narrow" }}).formatToParts(["10", "m", "s"])));
            try {{ en().format(["a", 1]); }} catch (e) {{ report(e.name); }}
            try {{ en({{ type: "and" }}); }} catch (e) {{ report(e.name); }}
            try {{ en({{ style: "wide" }}); }} catch (e) {{ report(e.name); }}
            report(JSON.stringify(new Intl.ListFormat("tr", {{ type: "disjunction", style: "short" }}).resolvedOptions()));
            report(new Intl.ListFormat("xx").resolvedOptions().locale);
            "#
        ))
        .unwrap();
        assert_eq!(
            reported(&host),
            [
                r#""""#,
                "apples",
                "apples and oranges",
                "apples, oranges, and pears",
                "apples, oranges, and pears | apples, oranges, & pears | apples, oranges, pears | apples, oranges, or pears | apples, oranges, or pears | apples, oranges, or pears | 10, m, s | 10, m, s | 10 m s",
                "Ali, Ayşe ve Mehmet",
                "Ali, Ayşe und Mehmet",
                "Ali、Ayşe、Mehmet",
                r#"[{"type":"element","value":"tea"},{"type":"literal","value":" or "},{"type":"element","value":"coffee"}]"#,
                r#"[{"type":"element","value":"10"},{"type":"literal","value":" "},{"type":"element","value":"m"},{"type":"literal","value":" "},{"type":"element","value":"s"}]"#,
                "TypeError",
                "RangeError",
                "RangeError",
                r#"{"locale":"tr","type":"disjunction","style":"short"}"#,
                "en-US",
            ]
        );
    }

    /// A host with the language data of `languages`, registered as the
    /// bundle's `i18n` registers it (`nsh-i18n`).
    fn host_with_languages(languages: &[&str]) -> Host {
        let host = Host::new().unwrap();
        let mut data = serde_json::Map::new();
        for lang in languages {
            let value = nsh_i18n::language_data(lang).unwrap();
            data.insert((*lang).into(), serde_json::from_str(value).unwrap());
        }
        host.cx
            .with(|cx| crate::web::add_languages(cx.as_raw().as_ptr(), data));
        host
    }

    /// `Intl.RelativeTimeFormat` writes past and future counts for every
    /// unit, with the unit's plural.
    #[test]
    fn relative_times_format_past_and_future_for_every_unit() {
        let host = Host::new().unwrap();
        host.eval_source(&format!(
            r#"{REPORT}
            const f = new Intl.RelativeTimeFormat("en");
            const cases = [
              ["second", -3, 2], ["minute", -3, 2], ["hour", -3, 2],
              ["day", -3, 2], ["week", -3, 2], ["month", -3, 2],
              ["quarter", -3, 2], ["year", -3, 2],
            ];
            for (const [unit, past, future] of cases) {{
              report(f.format(past, unit) + " / " + f.format(future, unit));
            }}
            "#
        ))
        .unwrap();
        assert_eq!(
            reported(&host),
            [
                "3 seconds ago / in 2 seconds",
                "3 minutes ago / in 2 minutes",
                "3 hours ago / in 2 hours",
                "3 days ago / in 2 days",
                "3 weeks ago / in 2 weeks",
                "3 months ago / in 2 months",
                "3 quarters ago / in 2 quarters",
                "3 years ago / in 2 years",
            ]
        );
    }

    /// `numeric: "auto"` writes the named times a language has, and the
    /// count where it has none.
    #[test]
    fn relative_times_auto_uses_the_named_times() {
        let host = Host::new().unwrap();
        host.eval_source(&format!(
            r#"{REPORT}
            const f = new Intl.RelativeTimeFormat("en", {{ numeric: "auto" }});
            report(f.format(-1, "day"));
            report(f.format(1, "day"));
            report(f.format(0, "day"));
            report(f.format(-0, "day"));
            report(f.format(0, "second"));
            report(f.format(0, "minute"));
            report(f.format(-1, "minute"));
            "#
        ))
        .unwrap();
        assert_eq!(
            reported(&host),
            [
                "yesterday",
                "tomorrow",
                "today",
                "today",
                "now",
                "this minute",
                "1 minute ago",
            ]
        );
    }

    /// Each `style` writes its own pattern.
    #[test]
    fn relative_times_write_every_style() {
        let host = Host::new().unwrap();
        host.eval_source(&format!(
            r#"{REPORT}
            for (const style of ["long", "short", "narrow"]) {{
              const f = new Intl.RelativeTimeFormat("en", {{ style }});
              report(style + ": " + f.format(-3, "second") + " / " + f.format(2, "day"));
            }}
            "#
        ))
        .unwrap();
        assert_eq!(
            reported(&host),
            [
                "long: 3 seconds ago / in 2 days",
                "short: 3 sec. ago / in 2 days",
                "narrow: 3s ago / in 2d",
            ]
        );
    }

    /// The shipped languages write their own patterns and plural forms.
    #[test]
    fn relative_times_use_other_languages() {
        let host = host_with_languages(&["de", "ja", "pl", "ru", "tr"]);
        host.eval_source(&format!(
            r#"{REPORT}
            const f = (locale, options) => new Intl.RelativeTimeFormat(locale, options);
            report(f("tr").format(-5, "minute"));
            report(f("de").format(-3, "day"));
            report(f("de", {{ numeric: "auto" }}).format(2, "day"));
            report(f("ru").format(-1, "minute"));
            report(f("ru").format(-2, "minute"));
            report(f("ru").format(-5, "minute"));
            report(f("pl").format(-5, "minute"));
            report(f("ja").format(-2, "week"));
            report(f("ja", {{ numeric: "auto" }}).format(0, "day"));
            "#
        ))
        .unwrap();
        assert_eq!(
            reported(&host),
            [
                "5 dakika önce",
                "vor 3 Tagen",
                "übermorgen",
                "1 минуту назад",
                "2 минуты назад",
                "5 минут назад",
                "5 minut temu",
                "2 週間前",
                "今日",
            ]
        );
    }

    /// `formatToParts` gives the number and literal parts in order, the
    /// number parts naming their unit; `resolvedOptions` reports the
    /// style, numeric and numbering system.
    #[test]
    fn relative_times_report_their_parts_and_options() {
        let host = Host::new().unwrap();
        host.eval_source(&format!(
            r#"{REPORT}
            const en = new Intl.RelativeTimeFormat("en");
            report(JSON.stringify(en.formatToParts(-1000, "day")));
            report(JSON.stringify(en.formatToParts(-1, "day")));
            const auto = new Intl.RelativeTimeFormat("en", {{ numeric: "auto" }});
            report(JSON.stringify(auto.formatToParts(-1, "day")));
            const options = new Intl.RelativeTimeFormat("en", {{ style: "short", numeric: "auto" }}).resolvedOptions();
            report([options.locale, options.style, options.numeric, options.numberingSystem].join());
            report(en.format(-0, "day") + " / " + en.format(0, "day") + " / " + en.format(1.5, "day"));
            "#
        ))
        .unwrap();
        assert_eq!(
            reported(&host),
            [
                r#"[{"type":"integer","value":"1","unit":"day"},{"type":"group","value":",","unit":"day"},{"type":"integer","value":"000","unit":"day"},{"type":"literal","value":" days ago"}]"#,
                r#"[{"type":"integer","value":"1","unit":"day"},{"type":"literal","value":" day ago"}]"#,
                r#"[{"type":"literal","value":"yesterday"}]"#,
                "en,short,auto,latn",
                "0 days ago / in 0 days / in 1.5 days",
            ]
        );
    }

    /// An invalid value, unit, style or numeric option throws, and
    /// `format` needs a `RelativeTimeFormat`.
    #[test]
    fn relative_times_reject_invalid_arguments() {
        let host = Host::new().unwrap();
        host.eval_source(&format!(
            r#"{REPORT}
            const en = new Intl.RelativeTimeFormat("en");
            try {{ en.format(NaN, "day"); }} catch (e) {{ report(e.name); }}
            try {{ en.format(Infinity, "day"); }} catch (e) {{ report(e.name); }}
            try {{ en.format(undefined, "day"); }} catch (e) {{ report(e.name); }}
            try {{ en.format(-1, "fortnight"); }} catch (e) {{ report(e.name); }}
            try {{ en.format(-1, "DAY"); }} catch (e) {{ report(e.name); }}
            try {{ en.format(1n, "day"); }} catch (e) {{ report(e.name); }}
            try {{ new Intl.RelativeTimeFormat("en", {{ style: "wide" }}); }} catch (e) {{ report(e.name); }}
            try {{ new Intl.RelativeTimeFormat("en", {{ numeric: "sometimes" }}); }} catch (e) {{ report(e.name); }}
            try {{ Intl.RelativeTimeFormat("en"); }} catch (e) {{ report(e.name); }}
            "#
        ))
        .unwrap();
        assert_eq!(
            reported(&host),
            [
                "RangeError",
                "RangeError",
                "RangeError",
                "RangeError",
                "RangeError",
                "TypeError",
                "RangeError",
                "RangeError",
                "TypeError",
            ]
        );
    }

    /// A locale without data resolves to English, as the other formats do.
    #[test]
    fn relative_times_fall_back_to_english() {
        let host = Host::new().unwrap();
        host.eval_source(&format!(
            r#"{REPORT}
            const f = new Intl.RelativeTimeFormat("xx");
            report(f.resolvedOptions().locale);
            report(f.format(2, "day"));
            "#
        ))
        .unwrap();
        assert_eq!(reported(&host), ["en-US", "in 2 days"]);
    }

    /// A named zone the app ships (nsh.json `timeZones`, packed into the
    /// bundle's `i18n` by `nsh-i18n`) formats at its offset at each
    /// instant: across daylight saving time in New York, at half an hour
    /// in Kolkata, with Lord Howe's half-hour daylight saving time, and
    /// by its rule after its last transition. A zone the app does not
    /// ship still throws.
    #[test]
    fn formats_in_the_named_zones_the_app_ships() {
        let host = Host::new().unwrap();
        let zones = ["America/New_York", "Asia/Kolkata", "Australia/Lord_Howe"].map(String::from);
        let bundle =
            nsh_i18n::bundle_json(&Default::default(), Some(&["de".to_owned()]), &zones, |w| {
                panic!("{w}")
            })
            .unwrap();
        host.eval_source(&format!(
            r#"{REPORT}
            import {{ i18n }} from "nsh:rt";
            i18n({bundle:?});
            const time = (timeZone) => new Intl.DateTimeFormat("en-US", {{
              timeZone, year: "numeric", month: "2-digit", day: "2-digit",
              hour: "2-digit", minute: "2-digit", hourCycle: "h23", timeZoneName: "short",
            }});
            const ny = time("america/new_york");
            report(ny.resolvedOptions().timeZone);
            // Daylight saving time starts at 2:00 EST on March 8, 2026 and
            // ends at 2:00 EDT on November 1.
            for (const at of [Date.UTC(2026, 2, 8, 6, 59), Date.UTC(2026, 2, 8, 7, 0),
                              Date.UTC(2026, 10, 1, 5, 59), Date.UTC(2026, 10, 1, 6, 0)]) {{
              report(ny.format(at));
            }}
            report(time("Asia/Kolkata").format(Date.UTC(2026, 0, 1, 0, 0)));
            // Lord Howe: +10:30, and +11 from 2:00 on October 4, 2026.
            const howe = time("Australia/Lord_Howe");
            report(howe.format(Date.UTC(2026, 9, 3, 15, 29)));
            report(howe.format(Date.UTC(2026, 9, 3, 15, 30)));
            // Past the last transition: the zone's rule.
            report(ny.format(Date.UTC(2200, 6, 1, 12, 0)));
            report(ny.format(Date.UTC(2200, 11, 1, 12, 0)));
            report(new Date(Date.UTC(2026, 6, 4, 16, 0)).toLocaleTimeString("en-US", {{ timeZone: "America/New_York" }}));
            report(new Intl.DateTimeFormat("en-US", {{ timeZone: "America/New_York", timeStyle: "long" }}).format(Date.UTC(2026, 6, 4, 16, 0)));
            report(new Intl.DateTimeFormat("de", {{ timeZone: "America/New_York", timeStyle: "long" }}).format(Date.UTC(2026, 0, 1)));
            // A zone the app doesn't ship is a RangeError, unless it is the
            // machine's own: local time is always there to name.
            const local = new Intl.DateTimeFormat().resolvedOptions().timeZone;
            const unshipped = ["Pacific/Chatham", "America/Sao_Paulo"].find((zone) => zone !== local);
            try {{ new Intl.DateTimeFormat("en", {{ timeZone: unshipped }}); }} catch (e) {{ report(e.name); }}
            "#
        ))
        .unwrap();
        assert_eq!(
            reported(&host),
            [
                "America/New_York",
                "03/08/2026, 01:59 EST",
                "03/08/2026, 03:00 EDT",
                "11/01/2026, 01:59 EDT",
                "11/01/2026, 01:00 EST",
                "01/01/2026, 05:30 GMT+5:30",
                "10/04/2026, 01:59 GMT+10:30",
                "10/04/2026, 02:30 GMT+11",
                "07/01/2200, 08:00 EDT",
                "12/01/2200, 07:00 EST",
                "12:00:00 PM",
                "12:00:00 PM EDT",
                "19:00:00 GMT-5",
                "RangeError",
            ]
        );
    }

    /// A host with `zones` shipped and `time(zone, name)` formatting an
    /// hour and minute in `en`.
    fn host_with_zones(zones: &[&str]) -> Host {
        let host = Host::new().unwrap();
        let zones = zones
            .iter()
            .map(|zone| (*zone).to_owned())
            .collect::<Vec<_>>();
        let bundle =
            nsh_i18n::bundle_json(&Default::default(), None, &zones, |w| panic!("{w}")).unwrap();
        host.eval_source(&format!(
            r#"{REPORT}
            import {{ i18n }} from "nsh:rt";
            i18n({bundle:?});
            globalThis.time = (timeZone, timeZoneName) => new Intl.DateTimeFormat("en", {{
              timeZone, timeZoneName, hour: "2-digit", minute: "2-digit", hourCycle: "h23",
            }});
            "#
        ))
        .unwrap();
        host
    }

    /// `timeZoneName: "long"` writes the English long name for a North
    /// American zone by the instant's daylight saving time.
    #[test]
    fn long_zone_names_follow_daylight_saving_time() {
        let host = host_with_zones(&["America/New_York"]);
        host.eval_source(&format!(
            r#"{REPORT}
            report(time("America/New_York", "long").format(Date.UTC(2026, 0, 15, 17, 0)));
            report(time("America/New_York", "long").format(Date.UTC(2026, 6, 15, 16, 0)));
            report(time("America/New_York", "long").resolvedOptions().timeZoneName);
            "#
        ))
        .unwrap();
        assert_eq!(
            reported(&host),
            [
                "12:00 Eastern Standard Time",
                "12:00 Eastern Daylight Time",
                "long",
            ]
        );
    }

    /// A zone without a bundled long name writes its long offset, and the
    /// offset forms ignore the abbreviation.
    #[test]
    fn long_zone_names_fall_back_to_the_long_offset() {
        let host = host_with_zones(&["Asia/Kolkata"]);
        host.eval_source(&format!(
            r#"{REPORT}
            report(time("Asia/Kolkata", "long").format(Date.UTC(2026, 0, 15, 0, 0)));
            report(time("Asia/Kolkata", "longOffset").format(Date.UTC(2026, 0, 15, 0, 0)));
            report(time("Asia/Kolkata", "shortOffset").format(Date.UTC(2026, 0, 15, 0, 0)));
            "#
        ))
        .unwrap();
        assert_eq!(
            reported(&host),
            ["05:30 GMT+05:30", "05:30 GMT+05:30", "05:30 GMT+5:30",]
        );
    }

    /// `timeZoneName: "short"` writes what it did before long names.
    #[test]
    fn short_zone_names_are_unchanged() {
        let host = host_with_zones(&["America/New_York", "Asia/Kolkata"]);
        host.eval_source(&format!(
            r#"{REPORT}
            report(time("America/New_York", "short").format(Date.UTC(2026, 0, 15, 17, 0)));
            report(time("America/New_York", "short").format(Date.UTC(2026, 6, 15, 16, 0)));
            report(time("Asia/Kolkata", "short").format(Date.UTC(2026, 0, 15, 0, 0)));
            "#
        ))
        .unwrap();
        assert_eq!(
            reported(&host),
            ["12:00 EST", "12:00 EDT", "05:30 GMT+5:30"]
        );
    }

    /// `Intl.supportedValuesOf("timeZone")` lists the shipped zones,
    /// sorted, as a new array.
    #[test]
    fn supported_values_of_lists_the_shipped_zones_sorted() {
        let host = host_with_zones(&[
            "America/New_York",
            "Asia/Kolkata",
            "Australia/Lord_Howe",
            "Europe/Istanbul",
        ]);
        host.eval_source(&format!(
            r#"{REPORT}
            const list = Intl.supportedValuesOf("timeZone");
            report(list.join(","));
            report([list.includes("America/New_York"), list.includes("Europe/Istanbul")].join());
            report([...list].sort().join(",") === list.join(","));
            report(list.length);
            report(Intl.supportedValuesOf("timeZone") !== list);
            try {{ Intl.supportedValuesOf("calendar"); }} catch (e) {{ report(e.name); }}
            "#
        ))
        .unwrap();
        assert_eq!(
            reported(&host),
            [
                "America/New_York,Asia/Kolkata,Australia/Lord_Howe,Europe/Istanbul",
                "true,true",
                "true",
                "4",
                "true",
                "RangeError",
            ]
        );
    }

    #[test]
    fn timers_fire_in_order_and_cancel() {
        let host = Host::new().unwrap();
        host.eval_source(
            r#"
            globalThis.log = [];
            setTimeout(() => log.push("b"), 20);
            setTimeout(() => log.push("a"), 0);
            const c = setTimeout(() => log.push("cancelled"), 10);
            clearTimeout(c);
            Promise.resolve().then(() => log.push("micro"));
            "#,
        )
        .unwrap();
        let deadline = Instant::now() + Duration::from_millis(30);
        while let Some(next) = host.next_timer() {
            std::thread::sleep(next.saturating_duration_since(Instant::now()));
            host.run_timers(Instant::now());
            assert!(Instant::now() < deadline + Duration::from_secs(1));
        }
        host.eval_source(&format!("{REPORT}report(log.join(\",\"));"))
            .unwrap();
        assert_eq!(reported(&host), ["micro,a,b"]);
    }

    #[test]
    fn clearing_ids_that_name_no_timer_is_ignored() {
        let host = Host::new().unwrap();
        host.eval_source(
            r#"
            globalThis.log = [];
            const t = setTimeout(() => log.push("timeout"), 0);
            const i = setInterval(() => { log.push("interval"); clearInterval(i); }, 0);
            const f = requestAnimationFrame(() => log.push("frame"));
            for (const clear of [clearTimeout, clearInterval, cancelAnimationFrame]) {
                clear();
                for (const id of [undefined, null, 0, -1, NaN, Infinity, 1e12, 0.5, 99999, "x", "", {}, [], true, Symbol()])
                    clear(id);
            }
            const gone = setTimeout(() => log.push("cancelled by string"), 0);
            clearTimeout(String(gone));
            const gone2 = setTimeout(() => log.push("cancelled by fraction"), 0);
            clearTimeout(gone2 + 0.7);
            const gone3 = requestAnimationFrame(() => log.push("cancelled frame"));
            cancelAnimationFrame(gone3);
            "#,
        )
        .unwrap();
        host.run_frame();
        while let Some(next) = host.next_timer() {
            std::thread::sleep(next.saturating_duration_since(Instant::now()));
            host.run_timers(Instant::now());
        }
        host.eval_source(&format!("{REPORT}report(log.join(\",\"));"))
            .unwrap();
        assert_eq!(reported(&host), ["frame,timeout,interval"]);
    }

    fn sandboxed(limits: Limits) -> Host {
        Host::with_options(HostOptions {
            limits,
            harden: true,
            ..HostOptions::default()
        })
        .unwrap()
    }

    #[test]
    fn calls_over_budget_are_interrupted_and_the_vm_goes_on() {
        let mut host = sandboxed(Limits {
            call_budget: Duration::from_millis(50),
            ..Limits::default()
        });
        let errors = Rc::new(RefCell::new(Vec::new()));
        let seen = errors.clone();
        host.set_error_handler(Box::new(move |e| seen.borrow_mut().push(e.message.clone())));
        // Views 2 and 4: the first loops when pressed.
        host.eval_source(
            r#"import { element, prop } from "nsh:rt";
            globalThis.views = [true, false].map((loops) => {
                const view = element("view");
                prop(view, "onPress", () => {
                    // try/catch cannot swallow the interrupt.
                    try { if (loops) for (;;) {} } catch (e) {}
                    element("view");
                });
                return view;
            });"#,
        )
        .unwrap();
        ops(&host);
        let start = Instant::now();
        host.dispatch_event(2, EventKind::Press, &EventPayload::None);
        assert!(start.elapsed() < Duration::from_secs(2));
        let errors = errors.borrow().clone();
        assert_eq!(errors.len(), 1, "{errors:?}");
        assert!(errors[0].contains("budget of 50 ms"), "{}", errors[0]);
        assert!(ops(&host).is_empty());
        // The next call runs normally.
        host.dispatch_event(4, EventKind::Press, &EventPayload::None);
        let created = ops(&host)
            .into_iter()
            .filter(|op| matches!(op, Op::Create { .. }))
            .count();
        assert_eq!(created, 1);
        assert!(host.fatal().is_none());
    }

    #[test]
    fn an_event_for_a_components_node_never_reaches_the_js_node_below_its_id() {
        // A Rust component's nodes have odd ids; once the component let go
        // of one (a sheet closed), its late `Dismiss` comes to JS. Node 3 is
        // not JS's node 2: a closed sheet's dismissal ran the handler of the
        // page under it and popped that page.
        let host = Host::new().unwrap();
        host.eval_source(
            r#"import { element, prop } from "nsh:rt";
            globalThis.view = element("view");
            prop(globalThis.view, "onPress", () => element("view"));"#,
        )
        .unwrap();
        ops(&host);
        host.dispatch_event(3, EventKind::Press, &EventPayload::None);
        host.dispatch_event(3, EventKind::Dismiss, &EventPayload::None);
        assert!(ops(&host).is_empty());
        // Its own id still reaches it.
        host.dispatch_event(2, EventKind::Press, &EventPayload::None);
        let created = ops(&host)
            .into_iter()
            .filter(|op| matches!(op, Op::Create { .. }))
            .count();
        assert_eq!(created, 1);
    }

    #[test]
    fn an_interrupt_inside_find_keeps_the_elements_alive() {
        // An interrupt inside QuickJS's `find` family must not free the
        // arrays' elements (quickjs-ng #1826), or a later call crashes the
        // VM. `views[0]` and the second, offset run of each method make the
        // interrupt land in the method itself.
        let mut host = sandboxed(Limits {
            call_budget: Duration::ZERO,
            ..Limits::default()
        });
        let errors = Rc::new(RefCell::new(Vec::new()));
        let seen = errors.clone();
        host.set_error_handler(Box::new(move |e| seen.borrow_mut().push(e.message.clone())));
        host.eval_source(
            r#"import { element, prop } from "nsh:rt";
            const methods = ["find", "findIndex", "findLast", "findLastIndex"];
            globalThis.kept = methods.map(() => ({}));
            globalThis.weak = kept.map((element) => new WeakRef(element));
            globalThis.items = kept.map((element) => new Array(100000).fill(element));
            const press = (handler) => {
                const view = element("view");
                prop(view, "onPress", handler);
                return view;
            };
            const nothing = () => {};
            globalThis.views = [press(() => { for (;;) {} })];
            methods.forEach((method, i) => {
                views.push(press(() => items[i][method](() => false)));
                views.push(press(() => (nothing(), items[i][method](() => false))));
            });"#,
        )
        .unwrap();
        ops(&host);
        // Views 2 (the loop), then 4 to 18: two per method.
        for view in (4..=18).step_by(2) {
            host.dispatch_event(2, EventKind::Press, &EventPayload::None);
            host.dispatch_event(view, EventKind::Press, &EventPayload::None);
        }
        let errors = errors.borrow().clone();
        assert_eq!(errors.len(), 16, "{errors:?}");
        assert!(
            errors.iter().all(|e| e.contains("budget of 0 ms")),
            "{errors:?}"
        );
        // The arrays let their elements go; `kept` still holds them.
        host.eval_source("items = null;").unwrap();
        host.collect_garbage();
        host.eval_source(&format!(
            "{REPORT}report(weak.map((w, i) => w.deref() === kept[i]).join());"
        ))
        .unwrap();
        assert_eq!(reported(&host), ["true,true,true,true"]);
        assert!(host.fatal().is_none());
    }

    #[test]
    fn running_out_of_memory_stops_the_vm() {
        let host = sandboxed(Limits {
            memory_bytes: 16 << 20,
            ..Limits::default()
        });
        let err = host
            .eval_source("const keep = []; for (;;) keep.push(new Array(100000).fill(1));")
            .unwrap_err();
        assert!(err.message.contains("limited to 16 MB"), "{}", err.message);
        assert!(host.fatal().is_some());
        // Nothing runs any more.
        assert!(
            host.eval_source(r#"import { element } from "nsh:rt"; element("view");"#)
                .is_err()
        );
        assert!(ops(&host).is_empty());
    }

    #[test]
    fn running_out_of_memory_in_a_timer_stops_the_vm() {
        let mut host = sandboxed(Limits {
            memory_bytes: 16 << 20,
            ..Limits::default()
        });
        let errors = Rc::new(RefCell::new(Vec::new()));
        let seen = errors.clone();
        host.set_error_handler(Box::new(move |e| seen.borrow_mut().push(e.message.clone())));
        // JSON.parse running out throws a null exception, not the usual
        // InternalError.
        host.eval_source(
            r#"const keep = [];
            setTimeout(() => {
                for (let n = 0; ; n++) {
                    const parts = [];
                    for (let i = 0; i < 1000; i++) parts.push(`{"path":"/a/b/c-${n}-${i}","children":[]}`);
                    keep.push(JSON.parse("[" + parts.join(",") + "]"));
                }
            }, 0);"#,
        )
        .unwrap();
        host.run_timers(Instant::now() + Duration::from_millis(1));
        let errors = errors.borrow().clone();
        assert_eq!(errors.len(), 1, "{errors:?}");
        assert!(errors[0].contains("limited to 16 MB"), "{}", errors[0]);
        assert!(host.fatal().is_some());
    }

    #[test]
    fn running_out_of_memory_stops_the_vm_even_when_caught() {
        let mut host = sandboxed(Limits {
            memory_bytes: 16 << 20,
            ..Limits::default()
        });
        let errors = Rc::new(RefCell::new(Vec::new()));
        let seen = errors.clone();
        host.set_error_handler(Box::new(move |e| seen.borrow_mut().push(e.message.clone())));
        host.eval_source(
            r#"setTimeout(() => {
                try {
                    const keep = [];
                    for (;;) keep.push(new Array(100000).fill(1));
                } catch (e) {}
            }, 0);"#,
        )
        .unwrap();
        host.run_timers(Instant::now() + Duration::from_millis(1));
        let errors = errors.borrow().clone();
        assert_eq!(errors.len(), 1, "{errors:?}");
        assert!(
            errors[0].contains("limited to 16 MB") && errors[0].contains("in pages"),
            "{}",
            errors[0]
        );
        assert!(host.fatal().is_some());
    }

    #[test]
    fn too_many_changes_at_once_stop_the_vm() {
        let host = sandboxed(Limits {
            max_op_values: 1000,
            ..Limits::default()
        });
        assert!(
            host.eval_source(
                r#"import { element } from "nsh:rt"; for (let i = 0; i < 2000; i++) element("view");"#
            )
            .is_err()
        );
        assert!(host.fatal().unwrap().contains("more than 1000 changes"));
    }

    #[test]
    fn hardened_vms_run_no_code_from_strings() {
        hardened_vm_runs_no_code_from_strings(&sandboxed(Limits::default()));
    }

    fn hardened_vm_runs_no_code_from_strings(host: &Host) {
        host.eval_source(&(REPORT.to_owned()
            + r#"
            const results = [];
            const attempt = (f) => { try { f(); results.push("ran"); } catch (e) { results.push(e.constructor.name); } };
            attempt(() => eval("1"));
            attempt(() => new Function("return 1")());
            attempt(() => (function () {}).constructor("return 1")());
            attempt(() => (async function () {}).constructor("return 1"));
            attempt(() => (function* () {}).constructor("yield 1"));
            attempt(() => { "use strict"; Array.prototype.map = null; });
            attempt(() => { "use strict"; Object.prototype.polluted = 1; });
            // Ordinary code is unaffected.
            class MyError extends Error { constructor() { super("x"); this.name = "MyError"; } }
            attempt(() => { const e = new MyError(); if (e.name !== "MyError") throw new Error(); });
            attempt(() => [1, 2].map((x) => x * 2));
            // Members of the frozen prototypes can still be overridden on
            // other objects (no override mistake), not on the prototypes.
            attempt(() => {
                "use strict";
                function A() {}
                A.prototype = Object.create(Object.prototype);
                A.prototype.constructor = A;
                const o = { toString: undefined };
                o.toString = () => "mine";
                const d = new Date(0);
                d.toJSON = () => "j";
                if (new A().constructor !== A || String(o) !== "mine" || JSON.stringify(d) !== '"j"') throw new Error();
                if (({}).constructor !== Object || [].toString() !== "") throw new Error();
            });
            attempt(() => { "use strict"; Object.prototype.toString = null; });
            // Functions take an own `constructor` (libraries such as axios copy
            // a prototype's members onto a function), while the shared one
            // stays blocked.
            attempt(() => {
                "use strict";
                const f = function () {};
                f.constructor = Object;
                if (f.constructor !== Object || (function () {}).constructor === Object) throw new Error();
            });
            attempt(() => { "use strict"; Function.prototype.constructor = Object; });
            attempt(() => Object.getPrototypeOf(function () {}).constructor("return 1")());
            report(results.join(","));
            "#))
        .unwrap();
        assert_eq!(
            reported(host),
            [
                "ReferenceError,TypeError,TypeError,TypeError,TypeError,TypeError,TypeError,ran,ran,ran,TypeError,ran,TypeError,TypeError"
            ]
        );
    }

    #[test]
    fn development_vms_keep_eval() {
        let host = Host::new().unwrap();
        host.eval_source(&format!("{REPORT}report(eval(\"1 + 1\"));"))
            .unwrap();
        assert_eq!(reported(&host), ["2"]);
    }

    /// Captures the `js` errors logged on this thread (each test runs on
    /// a thread of its own, its host too).
    mod logs {
        use std::cell::RefCell;

        struct Capture;

        thread_local! {
            static LINES: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
        }

        impl log::Log for Capture {
            fn enabled(&self, metadata: &log::Metadata<'_>) -> bool {
                metadata.target() == "js" && metadata.level() == log::Level::Error
            }

            fn log(&self, record: &log::Record<'_>) {
                if self.enabled(record.metadata()) {
                    LINES.with_borrow_mut(|lines| lines.push(record.args().to_string()));
                }
            }

            fn flush(&self) {}
        }

        static CAPTURE: Capture = Capture;

        /// Captures from here on (the logger is the process's: installed
        /// once).
        pub(super) fn capture() {
            static INSTALL: std::sync::Once = std::sync::Once::new();
            INSTALL.call_once(|| {
                if log::set_logger(&CAPTURE).is_ok() {
                    log::set_max_level(log::LevelFilter::Error);
                }
            });
            LINES.with_borrow_mut(Vec::clear);
        }

        /// The lines logged since the last call.
        pub(super) fn take() -> Vec<String> {
            LINES.with_borrow_mut(std::mem::take)
        }
    }

    /// Lines about unhandled rejections among `lines`.
    fn rejections(lines: &[String]) -> Vec<&String> {
        lines
            .iter()
            .filter(|l| l.contains("unhandled rejection"))
            .collect()
    }

    #[test]
    fn unhandled_rejections_are_logged_once_the_turn_ends() {
        logs::capture();
        let host = Host::new().unwrap();
        host.eval_source(
            r#"function fail() { return Promise.reject(new Error("boom")); }
            fail();
            Promise.reject("plain");"#,
        )
        .unwrap();
        let lines = logs::take();
        assert_eq!(lines.len(), 2, "{lines:?}");
        assert!(
            lines[0].starts_with("unhandled rejection: Error: boom")
                && lines[0].contains("at fail"),
            "{}",
            lines[0]
        );
        assert_eq!(lines[1], "unhandled rejection: plain");
        // Reported once: the next turns have nothing left.
        host.run_jobs();
        host.collect_garbage();
        assert!(logs::take().is_empty());
        assert_eq!(host.pending_rejections(), 0);
    }

    #[test]
    fn rejections_handled_in_the_same_turn_are_not_logged() {
        logs::capture();
        let host = Host::new().unwrap();
        host.eval_source(
            r#"// A handler attached later in the same code.
            const p = Promise.reject(new Error("later"));
            const other = 1 + 1;
            p.catch(() => {});
            // One attached by a microtask of the same turn.
            const q = Promise.reject(new Error("micro"));
            Promise.resolve().then(() => Promise.resolve()).then(() => q.catch(() => {}));
            // Handled the usual ways.
            Promise.reject(new Error("caught")).catch(() => {});
            Promise.reject(new Error("then")).then(undefined, () => {});
            Promise.reject(new Error("chain")).then(() => 1).catch(() => {});
            (async () => { try { await Promise.reject(new Error("awaited")); } catch (e) {} })();
            Promise.allSettled([Promise.reject(new Error("settled"))]);"#,
        )
        .unwrap();
        assert_eq!(logs::take(), Vec::<String>::new());
        assert_eq!(host.pending_rejections(), 0);
    }

    #[test]
    fn a_rejection_left_by_a_chain_is_logged_once() {
        logs::capture();
        let host = Host::new().unwrap();
        // The first promise is handled by `then`, which rejects in turn.
        host.eval_source(r#"Promise.reject(new Error("chained")).then(() => 1);"#)
            .unwrap();
        let lines = logs::take();
        assert_eq!(rejections(&lines).len(), 1, "{lines:?}");
        assert!(lines[0].contains("chained"), "{}", lines[0]);
    }

    #[test]
    fn async_functions_that_throw_unawaited_are_logged() {
        logs::capture();
        let host = Host::new().unwrap();
        host.eval_source(
            r#"async function now() { throw new Error("at once"); }
            async function later() { await null; throw new TypeError("after await"); }
            setTimeout(() => { now(); later(); }, 0);"#,
        )
        .unwrap();
        assert!(logs::take().is_empty());
        host.run_timers(Instant::now() + Duration::from_millis(1));
        let lines = logs::take();
        assert_eq!(lines.len(), 2, "{lines:?}");
        assert!(
            lines[0].contains("at once") && lines[0].contains("at now"),
            "{}",
            lines[0]
        );
        assert!(lines[1].contains("after await"), "{}", lines[1]);
    }

    #[test]
    fn a_rejection_handled_in_a_later_turn_is_logged_once() {
        logs::capture();
        let host = Host::new().unwrap();
        host.eval_source(
            r#"const p = Promise.reject(new Error("too late"));
            setTimeout(() => p.catch(() => {}), 0);"#,
        )
        .unwrap();
        assert_eq!(rejections(&logs::take()).len(), 1);
        host.run_timers(Instant::now() + Duration::from_millis(1));
        assert!(logs::take().is_empty());
        assert_eq!(host.pending_rejections(), 0);
    }

    #[test]
    fn rejections_go_to_the_handler_not_the_error_handler() {
        logs::capture();
        let mut host = Host::new().unwrap();
        let (errors, rejected) = (
            Rc::new(RefCell::new(Vec::new())),
            Rc::new(RefCell::new(Vec::new())),
        );
        let seen = errors.clone();
        host.set_error_handler(Box::new(move |e| seen.borrow_mut().push(e.message.clone())));
        let seen = rejected.clone();
        host.set_rejection_handler(Box::new(move |e| seen.borrow_mut().push(e.message.clone())));
        host.eval_source(r#"Promise.reject(new Error("to the handler"));"#)
            .unwrap();
        assert!(errors.borrow().is_empty());
        assert_eq!(rejected.borrow().len(), 1);
        assert!(rejected.borrow()[0].starts_with("Error: to the handler"));
        assert!(logs::take().is_empty());
    }

    #[test]
    fn a_failing_bundle_is_not_an_unhandled_rejection() {
        logs::capture();
        let host = Host::new().unwrap();
        let err = host
            .eval_source(r#"throw new Error("top level");"#)
            .unwrap_err();
        assert!(err.message.contains("top level"), "{}", err.message);
        assert!(rejections(&logs::take()).is_empty());
        assert_eq!(host.pending_rejections(), 0);
    }

    #[test]
    fn collecting_gives_back_the_graph_slots_of_a_tree_that_is_gone() {
        let host = Host::new().unwrap();
        let slots = |host: &Host| {
            host.cx.with(|cx| {
                // SAFETY: the host's state; no JS runs meanwhile.
                unsafe { crate::reactive::graph(cx.as_raw().as_ptr()) }.slots()
            })
        };
        host.collect_garbage();
        let (_, before) = slots(&host);
        host.eval_source(
            r#"import { cond } from "nsh:rt";
            import { computed, signal } from "nsh";
            const shown = signal(true);
            const branch = cond(() => shown(), () => {
                for (let i = 0; i < 20000; i++) computed(() => i)();
                return null;
            });
            branch();
            globalThis.hide = () => { shown.set(false); branch(); };"#,
        )
        .unwrap();
        assert!(slots(&host).1 >= before + 20000);
        host.eval_script("hide.js", "hide();").unwrap();
        host.collect_garbage();
        let (_, after) = slots(&host);
        assert!(after < before + 100, "{before} → {after} slots");
    }

    #[test]
    fn many_rejections_leave_nothing_behind() {
        logs::capture();
        let host = Host::new().unwrap();
        host.eval_source(
            r#"globalThis.reject = (n) => {
                for (let i = 0; i < n; i++) {
                    Promise.reject(new Error("unhandled " + i));
                    Promise.reject(new Error("handled " + i)).catch(() => {});
                    (async () => { throw new Error("async " + i); })();
                }
            };
            setTimeout(() => reject(1), 0);"#,
        )
        .unwrap();
        host.run_timers(Instant::now() + Duration::from_millis(1));
        logs::take();
        host.collect_garbage();
        let before = host.object_count();
        host.eval_script(
            "rounds.js",
            "for (let i = 0; i < 20; i++) setTimeout(() => reject(50), 0);",
        )
        .unwrap();
        host.run_timers(Instant::now() + Duration::from_millis(1));
        assert_eq!(rejections(&logs::take()).len(), 20 * 50 * 2);
        assert_eq!(host.pending_rejections(), 0);
        host.collect_garbage();
        // The 3000 promises and their errors are gone.
        assert!(
            host.object_count() < before + 100,
            "{} → {}",
            before,
            host.object_count()
        );
    }

    #[test]
    fn interrupts_and_running_out_of_memory_are_not_rejections() {
        logs::capture();
        let mut host = sandboxed(Limits {
            call_budget: Duration::from_millis(50),
            ..Limits::default()
        });
        let errors = Rc::new(RefCell::new(Vec::new()));
        let seen = errors.clone();
        host.set_error_handler(Box::new(move |e| seen.borrow_mut().push(e.message.clone())));
        host.eval_source(
            r#"setTimeout(async () => { await null; for (;;) {} }, 0);
            setTimeout(async () => { try { for (;;) {} } catch (e) {} }, 0);"#,
        )
        .unwrap();
        host.run_timers(Instant::now() + Duration::from_millis(1));
        assert_eq!(errors.borrow().len(), 2, "{:?}", errors.borrow());
        assert!(
            errors
                .borrow()
                .iter()
                .all(|e| e.contains("budget of 50 ms"))
        );
        assert_eq!(rejections(&logs::take()), Vec::<&String>::new());
        assert_eq!(host.pending_rejections(), 0);

        let mut host = sandboxed(Limits {
            memory_bytes: 16 << 20,
            ..Limits::default()
        });
        let errors = Rc::new(RefCell::new(Vec::new()));
        let seen = errors.clone();
        host.set_error_handler(Box::new(move |e| seen.borrow_mut().push(e.message.clone())));
        host.eval_source(
            r#"setTimeout(async () => {
                const keep = [];
                for (;;) keep.push(new Array(100000).fill(1));
            }, 0);"#,
        )
        .unwrap();
        host.run_timers(Instant::now() + Duration::from_millis(1));
        assert_eq!(errors.borrow().len(), 1, "{:?}", errors.borrow());
        assert!(errors.borrow()[0].contains("limited to 16 MB"));
        assert_eq!(rejections(&logs::take()), Vec::<&String>::new());
    }
}