wasm-rquickjs-cli 0.5.3

Tool for wrapping JavaScript modules as WebAssembly components using the QuickJS engine
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
use camino::Utf8Path;
use camino::Utf8PathBuf;
use camino_tempfile::Utf8TempDir;
use indoc::indoc;
use std::io::{Read, Write};
use std::net::TcpListener;
use std::process::Command;
use std::sync::{Arc, Condvar, Mutex};
use std::thread;
use std::time::Duration;
use wasm_rquickjs::{
    DependencySpec, EmbeddingMode, GenerationTarget, JsModuleSpec, NativeModuleSpec,
    WrapperCrateOptions, generate_dts_with_target, generate_wrapper_crate_with_options,
    generate_wrapper_crate_with_target,
};

mod p3_build;

/// Starts a minimal single-threaded HTTP/1.1 test server on an ephemeral loopback port and
/// returns the bound port. The server runs on a detached background thread for the lifetime of
/// the test process and serves:
///   * `GET  /hello` -> `200` with body `hello-from-p3`
///   * `POST /echo`  -> `200` echoing the request body
///   * `GET  /redirect` -> `302` with `Location: /hello`
///   * `POST /redirect-307` -> `307` with `Location: /echo-method`
///   * `POST /bad-location-redirect` -> `302` with an invalid `Location` header
///   * `GET  /truncated-redirect` -> malformed `302` with `Content-Length` longer than body
///   * `GET  /legal` -> `451 Unavailable For Legal Reasons`
///   * `GET|POST /truncated` -> malformed response with `Content-Length` longer than body
///   * `POST /content-type` -> `200` with `<content-type-count>:<joined-values>`
///   * `POST /echo-method` -> `200` with `<method>:<body>`
///   * `<any> /method` -> `200` with the received request method as the body
///   * anything else -> `404`
fn spawn_test_http_server() -> u16 {
    let listener = TcpListener::bind("127.0.0.1:0").expect("failed to bind test HTTP server");
    let port = listener.local_addr().unwrap().port();

    thread::spawn(move || {
        for stream in listener.incoming() {
            let Ok(mut stream) = stream else { continue };

            // Read the request head (up to the blank line separating headers from the body).
            let mut buf = Vec::new();
            let mut chunk = [0u8; 1024];
            let header_end = loop {
                if let Some(pos) = find_subsequence(&buf, b"\r\n\r\n") {
                    break pos + 4;
                }
                match stream.read(&mut chunk) {
                    Ok(0) => break buf.len(),
                    Ok(n) => buf.extend_from_slice(&chunk[..n]),
                    Err(_) => break buf.len(),
                }
            };

            let head = String::from_utf8_lossy(&buf[..header_end.min(buf.len())]).to_string();
            let mut lines = head.split("\r\n");
            let request_line = lines.next().unwrap_or("");
            let mut parts = request_line.split_whitespace();
            let method = parts.next().unwrap_or("").to_string();
            let target = parts.next().unwrap_or("").to_string();

            let content_type_values = head
                .lines()
                .filter_map(|l| {
                    let (name, value) = l.split_once(':')?;
                    name.trim()
                        .eq_ignore_ascii_case("content-type")
                        .then(|| value.trim().to_string())
                })
                .collect::<Vec<_>>();

            let content_length = head
                .lines()
                .find_map(|l| {
                    let (name, value) = l.split_once(':')?;
                    name.trim()
                        .eq_ignore_ascii_case("content-length")
                        .then(|| value.trim().parse::<usize>().ok())
                        .flatten()
                })
                .unwrap_or(0);
            let is_chunked = head.lines().any(|l| {
                l.split_once(':').is_some_and(|(name, value)| {
                    name.trim().eq_ignore_ascii_case("transfer-encoding")
                        && value.to_ascii_lowercase().contains("chunked")
                })
            });

            // Read the remaining request body. `wasi:http` streams request bodies with
            // `Transfer-Encoding: chunked` (no known length), so decode chunked framing when
            // present and otherwise honor `Content-Length`.
            let mut raw = buf[header_end.min(buf.len())..].to_vec();
            let body = if is_chunked {
                loop {
                    if let Some(decoded) = decode_chunked(&raw) {
                        break decoded;
                    }
                    match stream.read(&mut chunk) {
                        Ok(0) => break decode_chunked(&raw).unwrap_or_default(),
                        Ok(n) => raw.extend_from_slice(&chunk[..n]),
                        Err(_) => break decode_chunked(&raw).unwrap_or_default(),
                    }
                }
            } else {
                while raw.len() < content_length {
                    match stream.read(&mut chunk) {
                        Ok(0) => break,
                        Ok(n) => raw.extend_from_slice(&chunk[..n]),
                        Err(_) => break,
                    }
                }
                raw
            };

            let response: Vec<u8> = match (method.as_str(), target.as_str()) {
                ("POST", "/echo") => http_response(200, "OK", "text/plain", &body),
                ("POST", "/echo-method") => http_response(
                    200,
                    "OK",
                    "text/plain",
                    format!("{method}:{}", String::from_utf8_lossy(&body)).as_bytes(),
                ),
                ("POST", "/content-type") => http_response(
                    200,
                    "OK",
                    "text/plain",
                    format!(
                        "{}:{}",
                        content_type_values.len(),
                        content_type_values.join("|")
                    )
                    .as_bytes(),
                ),
                (_, "/method") => http_response(200, "OK", "text/plain", method.as_bytes()),
                ("GET", "/hello") => http_response(200, "OK", "text/plain", b"hello-from-p3"),
                ("POST", "/bad-location-redirect") => {
                    b"HTTP/1.1 302 Found\r\nLocation: http://[\r\nContent-Type: text/plain\r\nContent-Length: 17\r\n\r\nbad-location-body"
                        .to_vec()
                }
                ("GET", "/legal") => http_response(
                    451,
                    "Unavailable For Legal Reasons",
                    "text/plain",
                    b"blocked",
                ),
                ("GET", "/truncated") | ("POST", "/truncated") => {
                    b"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 10\r\n\r\nshort"
                        .to_vec()
                }
                ("GET", "/truncated-redirect") => {
                    b"HTTP/1.1 302 Found\r\nLocation: /hello\r\nContent-Type: text/plain\r\nContent-Length: 10\r\n\r\nshort"
                        .to_vec()
                }
                ("GET", "/redirect") => {
                    b"HTTP/1.1 302 Found\r\nLocation: /hello\r\nContent-Length: 0\r\n\r\n".to_vec()
                }
                ("POST", "/redirect-307") => {
                    b"HTTP/1.1 307 Temporary Redirect\r\nLocation: /echo-method\r\nContent-Length: 0\r\n\r\n"
                        .to_vec()
                }
                _ => http_response(404, "Not Found", "text/plain", b"not found"),
            };

            let _ = stream.write_all(&response);
            let _ = stream.flush();
        }
    });

    port
}

fn http_response(status: u16, reason: &str, content_type: &str, body: &[u8]) -> Vec<u8> {
    let mut out = format!(
        "HTTP/1.1 {status} {reason}\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\n\r\n",
        body.len()
    )
    .into_bytes();
    out.extend_from_slice(body);
    out
}

fn find_subsequence(haystack: &[u8], needle: &[u8]) -> Option<usize> {
    haystack
        .windows(needle.len())
        .position(|window| window == needle)
}

/// Decodes an HTTP/1.1 `Transfer-Encoding: chunked` body. Returns `Some(bytes)` once the
/// terminating zero-length chunk has been fully received, or `None` if more bytes are still
/// needed (so the caller keeps reading from the socket).
fn decode_chunked(raw: &[u8]) -> Option<Vec<u8>> {
    let mut out = Vec::new();
    let mut rest = raw;
    loop {
        let line_end = find_subsequence(rest, b"\r\n")?;
        let size_line = std::str::from_utf8(&rest[..line_end]).ok()?;
        // Chunk size may carry extensions after a ';'; ignore them.
        let size_hex = size_line.split(';').next().unwrap_or("").trim();
        let size = usize::from_str_radix(size_hex, 16).ok()?;
        rest = &rest[line_end + 2..];
        if size == 0 {
            // Final chunk; a trailing CRLF (and optional trailers) follows but we don't need it.
            return Some(out);
        }
        if rest.len() < size + 2 {
            return None; // Need more bytes for the chunk data + trailing CRLF.
        }
        out.extend_from_slice(&rest[..size]);
        rest = &rest[size + 2..];
    }
}

#[derive(Default)]
struct SlowStreamingRedirectState {
    redirect_body_open: bool,
    followup_received: bool,
}

/// Starts a test server whose `POST /slow-redirect` responds with a `302` to `/hello` but keeps
/// the (discarded) redirect response body open until the follow-up request arrives or `delay`
/// elapses.
///
/// Each accepted connection is handled on its own thread so the `GET /hello` follow-up can be
/// served while the redirect connection is still open. Its response body reports whether that
/// ordering occurred, avoiding a wall-clock assertion that can fail when the CI runner is busy.
fn spawn_slow_streaming_redirect_server(delay: Duration) -> u16 {
    let listener = TcpListener::bind("127.0.0.1:0").expect("failed to bind test HTTP server");
    let port = listener.local_addr().unwrap().port();
    let redirect_state = Arc::new((
        Mutex::new(SlowStreamingRedirectState::default()),
        Condvar::new(),
    ));

    thread::spawn(move || {
        for stream in listener.incoming() {
            let Ok(mut stream) = stream else { continue };
            let redirect_state = Arc::clone(&redirect_state);

            thread::spawn(move || {
                let mut buf = Vec::new();
                let mut chunk = [0u8; 1024];
                let header_end = loop {
                    if let Some(pos) = find_subsequence(&buf, b"\r\n\r\n") {
                        break pos + 4;
                    }
                    match stream.read(&mut chunk) {
                        Ok(0) => break buf.len(),
                        Ok(n) => buf.extend_from_slice(&chunk[..n]),
                        Err(_) => break buf.len(),
                    }
                };

                let head = String::from_utf8_lossy(&buf[..header_end.min(buf.len())]).to_string();
                let mut lines = head.split("\r\n");
                let request_line = lines.next().unwrap_or("");
                let mut parts = request_line.split_whitespace();
                let method = parts.next().unwrap_or("");
                let target = parts.next().unwrap_or("");

                match (method, target) {
                    ("POST", "/slow-redirect") => {
                        {
                            let (state, _) = &*redirect_state;
                            state.lock().unwrap().redirect_body_open = true;
                        }
                        let _ = stream.write_all(
                            b"HTTP/1.1 302 Found\r\nLocation: /hello\r\nContent-Type: text/plain\r\nContent-Length: 100000000\r\n\r\npartial",
                        );
                        let _ = stream.flush();
                        let (state, followup) = &*redirect_state;
                        let guard = state.lock().unwrap();
                        let (mut guard, _) = followup
                            .wait_timeout_while(guard, delay, |state| !state.followup_received)
                            .unwrap();
                        guard.redirect_body_open = false;
                    }
                    ("GET", "/hello") => {
                        let followed_while_redirect_body_open = {
                            let (state, followup) = &*redirect_state;
                            let mut state = state.lock().unwrap();
                            let redirect_body_open = state.redirect_body_open;
                            state.followup_received = true;
                            followup.notify_one();
                            redirect_body_open
                        };
                        let body: &[u8] = if followed_while_redirect_body_open {
                            b"hello-after-slow-redirect"
                        } else {
                            b"followed-after-redirect-body-closed"
                        };
                        let _ = stream.write_all(&http_response(200, "OK", "text/plain", body));
                        let _ = stream.flush();
                    }
                    _ => {
                        let _ = stream.write_all(&http_response(
                            404,
                            "Not Found",
                            "text/plain",
                            b"not found",
                        ));
                        let _ = stream.flush();
                    }
                }
            });
        }
    });

    port
}

fn write_fixture(root: &Utf8Path, wit: &str, js: &str) -> anyhow::Result<()> {
    let wit_dir = root.join("wit");
    let src_dir = root.join("src");
    std::fs::create_dir_all(&wit_dir)?;
    std::fs::create_dir_all(&src_dir)?;
    std::fs::write(wit_dir.join("world.wit"), wit)?;
    std::fs::write(src_dir.join("module.js"), js)?;
    Ok(())
}

fn write_wit_dep(root: &Utf8Path, name: &str, wit: &str) -> anyhow::Result<()> {
    let deps_dir = root.join("wit").join("deps");
    std::fs::create_dir_all(&deps_dir)?;
    std::fs::write(deps_dir.join(name), wit)?;
    Ok(())
}

fn generate_p3(root: &Utf8Path) -> anyhow::Result<()> {
    generate_wrapper_crate_with_target(
        &root.join("wit"),
        &[JsModuleSpec {
            name: "module".to_string(),
            mode: EmbeddingMode::EmbedFile(root.join("src").join("module.js")),
        }],
        &root.join("out"),
        None,
        GenerationTarget::WasiP3,
    )
}

fn generate_p3_dts(wit: &Utf8Path, output: &Utf8Path) -> anyhow::Result<Vec<Utf8PathBuf>> {
    generate_dts_with_target(wit, output, None, GenerationTarget::WasiP3)
}

fn use_local_golem_websocket(root: &Utf8Path) -> anyhow::Result<()> {
    let manifest = root.join("out").join("Cargo.toml");
    let contents = std::fs::read_to_string(&manifest)?;
    let remote_patch = concat!(
        "golem-websocket = { git = \"https://github.com/golemcloud/wasm-rquickjs\", ",
        "branch = \"gol804-websocket-current-generator\" }"
    );
    let local_crate = Utf8Path::new(env!("CARGO_MANIFEST_DIR")).join("crates/golem-websocket");
    let local_patch = format!("golem-websocket = {{ path = \"{local_crate}\" }}");
    let updated = contents.replace(remote_patch, &local_patch);
    assert_ne!(
        updated, contents,
        "generated Cargo.toml did not contain the expected golem-websocket branch patch"
    );
    std::fs::write(manifest, updated)?;
    // The copied skeleton lockfile still identifies the bridge by its Git source.
    let mut status = Command::new("cargo")
        .args(["update", "--offline", "-p", "golem-websocket"])
        .current_dir(root.join("out"))
        .status()?;
    if !status.success() {
        status = Command::new("cargo")
            .args(["update", "-p", "golem-websocket"])
            .current_dir(root.join("out"))
            .status()?;
    }
    anyhow::ensure!(
        status.success(),
        "failed to lock the local golem-websocket bridge"
    );
    Ok(())
}

fn build_p3(root: &Utf8Path, wasm_name: &str) -> anyhow::Result<Utf8PathBuf> {
    build_p3_with_features(root, wasm_name, Some(P3_NORMAL_NO_LOGGING_FEATURES))
}

/// Builds a generated P3 crate, optionally overriding its default feature set. Passing
/// `features = Some("full-p3")` compiles the heavier capability tier (sqlite, brotli,
/// crypto-full, timezone) that is intentionally left out of the default `normal-p3` tier.
const P3_NORMAL_NO_LOGGING_FEATURES: &str = "p3,crypto,zlib,encoding";
const P3_NORMAL_NO_LOGGING_WITH_WEBSOCKET_FEATURES: &str = "p3,crypto,zlib,encoding,websocket";

fn build_p3_with_features(
    root: &Utf8Path,
    wasm_name: &str,
    features: Option<&str>,
) -> anyhow::Result<Utf8PathBuf> {
    let cache = p3_build::BuildCache::new()?;
    let mut build_cmd = Command::new("cargo");
    cache.configure(&mut build_cmd);
    build_cmd
        .arg("build")
        .arg("--manifest-path")
        .arg(root.join("out").join("Cargo.toml"))
        .arg("--target")
        .arg("wasm32-wasip2");
    if let Some(features) = features {
        build_cmd
            .arg("--no-default-features")
            .arg("--features")
            .arg(features);
    }
    let build = build_cmd.output()?;

    assert!(
        build.status.success(),
        "P3 generated crate should build; stdout:\n{}\nstderr:\n{}",
        String::from_utf8_lossy(&build.stdout),
        String::from_utf8_lossy(&build.stderr)
    );

    let mut metadata_cmd = Command::new("cargo");
    cache.configure(&mut metadata_cmd);
    let metadata = metadata_cmd
        .arg("metadata")
        .arg("--no-deps")
        .arg("--format-version")
        .arg("1")
        .arg("--manifest-path")
        .arg(root.join("out").join("Cargo.toml"))
        .output()?;
    assert!(
        metadata.status.success(),
        "cargo metadata should succeed; stdout:\n{}\nstderr:\n{}",
        String::from_utf8_lossy(&metadata.stdout),
        String::from_utf8_lossy(&metadata.stderr)
    );
    let metadata: serde_json::Value = serde_json::from_slice(&metadata.stdout)?;
    let target_dir = metadata["target_directory"]
        .as_str()
        .ok_or_else(|| anyhow::anyhow!("missing target_directory in cargo metadata"))?;

    let wasm = Utf8PathBuf::from(target_dir)
        .join("wasm32-wasip2")
        .join("debug")
        .join(format!("{wasm_name}.wasm"));
    Ok(Utf8PathBuf::from_path_buf(
        cache.finish(wasm.as_std_path(), root.join("out").as_std_path())?,
    )
    .expect("generated paths are UTF-8"))
}

fn run_p3_string_export(wasm_path: &Utf8Path, export: &str) -> anyhow::Result<String> {
    let output = Command::new("wasmtime")
        .arg("run")
        .arg("-S")
        .arg("p3=y")
        // The default `normal-p3` tier wires the `fetch`/HTTP builtins, so every generated P3
        // component imports `wasi:http`. `-S http=y` provides that host implementation; it is
        // harmless for components that never make a request.
        .arg("-S")
        .arg("http=y")
        .arg("--wasm")
        .arg("component-model=y")
        .arg("--wasm")
        .arg("component-model-async=y")
        .arg("--invoke")
        .arg(format!("{export}()"))
        .arg(wasm_path)
        .output()?;

    assert!(
        output.status.success(),
        "P3 component invocation should succeed; stdout:\n{}\nstderr:\n{}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );

    let stdout = String::from_utf8_lossy(&output.stdout);
    serde_json::from_str(stdout.trim()).map_err(Into::into)
}

fn run_p3_string_export_with_dir(
    wasm_path: &Utf8Path,
    export: &str,
    host_dir: &Utf8Path,
    guest_dir: &str,
) -> anyhow::Result<String> {
    let output = Command::new("wasmtime")
        .arg("run")
        .arg("-S")
        .arg("p3=y")
        .arg("-S")
        .arg("http=y")
        .arg("--wasm")
        .arg("component-model=y")
        .arg("--wasm")
        .arg("component-model-async=y")
        .arg("--dir")
        .arg(format!("{host_dir}::{guest_dir}"))
        .arg("--invoke")
        .arg(format!("{export}()"))
        .arg(wasm_path)
        .output()?;

    assert!(
        output.status.success(),
        "P3 component invocation should succeed; stdout:\n{}\nstderr:\n{}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );

    let stdout = String::from_utf8_lossy(&output.stdout);
    serde_json::from_str(stdout.trim()).map_err(Into::into)
}

#[test]
fn p3_sync_freestanding_export_runs() -> anyhow::Result<()> {
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:p3-sync-export;

            world p3-sync-export {
              export run: func() -> string;
            }
        "#},
        "export function run() { return 'sync-ok'; }\n",
    )?;

    generate_p3(temp.path())?;
    let wasm_path = build_p3(temp.path(), "p3_sync_export")?;
    let result = run_p3_string_export(&wasm_path, "run")?;

    assert_eq!(result, "sync-ok");
    Ok(())
}

/// A plain (synchronous) WIT export implemented by an `async` JavaScript function: a returned
/// Promise that settles without waiting on the host is awaited. (A synchronous task cannot block
/// on host waits such as timers, so those still trap.)
#[test]
fn p3_sync_export_awaits_a_returned_promise() -> anyhow::Result<()> {
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:p3-sync-promise;

            world p3-sync-promise {
              export run: func() -> string;
            }
        "#},
        indoc! {r#"
            async function label() {
              await null;
              return 'awaited';
            }

            export async function run() {
              await Promise.resolve();
              return await label();
            }
        "#},
    )?;

    generate_p3(temp.path())?;
    let wasm_path = build_p3(temp.path(), "p3_sync_promise")?;
    assert_eq!(run_p3_string_export(&wasm_path, "run")?, "awaited");
    Ok(())
}

/// Plugs the exports of `provider` into the matching imports of `socket`.
fn compose_provider(
    socket: &Utf8Path,
    provider: &Utf8Path,
    output: &Utf8Path,
) -> anyhow::Result<()> {
    use wac_graph::types::Package;
    use wac_graph::{CompositionGraph, EncodeOptions, plug};

    let mut graph = CompositionGraph::new();
    let socket = Package::from_file("socket", None, socket, graph.types_mut())?;
    let socket = graph.register_package(socket)?;
    let provider = Package::from_file("provider", None, provider, graph.types_mut())?;
    let provider = graph.register_package(provider)?;
    plug(&mut graph, vec![provider], socket)?;
    std::fs::write(output, graph.encode(EncodeOptions::default())?)?;
    Ok(())
}

/// `@composition` modules are loaded at runtime through the generated synchronous `get-script`
/// import, both as an additional module and as the primary (exporting) module.
#[test]
fn p3_composition_modules_load_through_get_script() -> anyhow::Result<()> {
    let temp = Utf8TempDir::new()?;
    let wit = indoc! {r#"
        package bug:p3-composition;

        world p3-composition {
          export run: func() -> string;
        }
    "#};

    let additional = temp.path().join("additional");
    write_fixture(
        &additional,
        wit,
        indoc! {r#"
            import { label } from 'user-lib';
            export function run() { return `embedded:${label()}`; }
        "#},
    )?;
    generate_wrapper_crate_with_target(
        &additional.join("wit"),
        &[
            JsModuleSpec {
                name: "module".to_string(),
                mode: EmbeddingMode::EmbedFile(additional.join("src").join("module.js")),
            },
            JsModuleSpec {
                name: "user-lib".to_string(),
                mode: EmbeddingMode::Composition,
            },
        ],
        &additional.join("out"),
        None,
        GenerationTarget::WasiP3,
    )?;
    let generated_wit =
        std::fs::read_to_string(additional.join("out").join("wit").join("world.wit"))?;
    assert!(
        generated_wit.contains("import get-script: func() -> string;"),
        "{generated_wit}"
    );

    let primary = temp.path().join("primary");
    write_fixture(&primary, wit, "")?;
    generate_wrapper_crate_with_target(
        &primary.join("wit"),
        &[JsModuleSpec {
            name: "module".to_string(),
            mode: EmbeddingMode::Composition,
        }],
        &primary.join("out"),
        None,
        GenerationTarget::WasiP3,
    )?;

    let mut providers = Vec::new();
    for (name, script) in [
        (
            "additional-provider",
            "export function label() { return 'composed'; }",
        ),
        (
            "primary-provider",
            "export function run() { return 'composed-primary'; }",
        ),
    ] {
        let root = temp.path().join(name);
        write_fixture(
            &root,
            &format!(
                "package bug:{name};\n\nworld {name} {{\n  export get-script: func() -> string;\n}}\n"
            ),
            &format!("export function getScript() {{ return {script:?}; }}\n"),
        )?;
        generate_p3(&root)?;
        providers.push(build_p3(&root, &name.replace('-', "_"))?);
    }

    for (root, provider, expected) in [
        (&additional, &providers[0], "embedded:composed"),
        (&primary, &providers[1], "composed-primary"),
    ] {
        let socket = build_p3(root, "p3_composition")?;
        let composed = root.join("composed.wasm");
        compose_provider(&socket, provider, &composed)?;
        assert_eq!(run_p3_string_export(&composed, "run")?, expected);
    }
    Ok(())
}

#[test]
fn p3_wizer_preinitializes_component_with_async_export() -> anyhow::Result<()> {
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:p3-wizer;

            world p3-wizer {
              export run: async func() -> string;
            }
        "#},
        indoc! {r#"
            globalThis.__p3WizerInitCount = (globalThis.__p3WizerInitCount ?? 0) + 1;
            globalThis.__wasm_rquickjs_new_env = 'user-owned';

            export async function run() {
              return `${globalThis.__p3WizerInitCount}:${globalThis.__wasm_rquickjs_new_env}:${process.env.P3_WIZER_RUNTIME_ENV ?? 'missing'}`;
            }
        "#},
    )?;

    generate_p3(temp.path())?;
    let wasm_path = build_p3(temp.path(), "p3_wizer")?;
    let optimized_path = temp.path().join("p3-wizer-optimized.wasm");
    tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()?
        .block_on(wasm_rquickjs::optimize_component(
            &wasm_path,
            &optimized_path,
            "wizer-initialize",
        ))?;

    let output = Command::new("wasmtime")
        .arg("run")
        .arg("-S")
        .arg("p3=y")
        .arg("-S")
        .arg("http=y")
        .arg("--wasm")
        .arg("component-model=y")
        .arg("--wasm")
        .arg("component-model-async=y")
        .arg("--env")
        .arg("P3_WIZER_RUNTIME_ENV=runtime")
        .arg("--invoke")
        .arg("run()")
        .arg(&optimized_path)
        .output()?;
    assert!(
        output.status.success(),
        "optimized P3 component invocation should succeed; stdout:\n{}\nstderr:\n{}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );
    let result: String = serde_json::from_slice(&output.stdout)?;
    assert_eq!(result, "1:user-owned:runtime");
    Ok(())
}

#[test]
fn p3_wizer_refreshes_named_process_argv0_export() -> anyhow::Result<()> {
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:p3-wizer-argv0;

            world p3-wizer-argv0 {
              export run: async func() -> string;
            }
        "#},
        indoc! {r#"
            import { argv0 } from 'node:process';

            export async function run() {
              return `${argv0}|${process.argv0}`;
            }
        "#},
    )?;

    generate_p3(temp.path())?;
    let wasm_path = build_p3(temp.path(), "p3_wizer_argv0")?;
    let optimized_path = temp.path().join("p3-wizer-argv0-optimized.wasm");
    tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()?
        .block_on(wasm_rquickjs::optimize_component(
            &wasm_path,
            &optimized_path,
            "wizer-initialize",
        ))?;

    let invoke = |component: &Utf8Path| -> anyhow::Result<String> {
        let output = Command::new("wasmtime")
            .arg("run")
            .arg("-S")
            .arg("p3=y")
            .arg("-S")
            .arg("http=y")
            .arg("--wasm")
            .arg("component-model=y")
            .arg("--wasm")
            .arg("component-model-async=y")
            .arg("--invoke")
            .arg("run()")
            .arg(component)
            .output()?;
        assert!(
            output.status.success(),
            "P3 component invocation should succeed; stdout:\n{}\nstderr:\n{}",
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr)
        );
        Ok(serde_json::from_slice(&output.stdout)?)
    };

    for (kind, component) in [
        ("unoptimized", wasm_path.as_path()),
        ("optimized", optimized_path.as_path()),
    ] {
        let result = invoke(component)?;
        let (named_argv0, process_argv0) = result
            .split_once('|')
            .expect("fixture should return both argv0 values");
        assert_eq!(
            named_argv0, process_argv0,
            "the named node:process export must reflect process.argv0 in the {kind} component"
        );
    }
    Ok(())
}

#[test]
fn p3_wizer_restores_runtime_argv_when_user_freezes_argv() -> anyhow::Result<()> {
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:p3-wizer-frozen-argv;

            world p3-wizer-frozen-argv {
              export run: async func() -> string;
            }
        "#},
        indoc! {r#"
            import { argv } from 'node:process';

            Object.freeze(process.argv);

            export async function run() {
              return `${process.argv[0] ?? 'missing'}|${argv[0] ?? 'missing'}`;
            }
        "#},
    )?;

    generate_p3(temp.path())?;
    let wasm_path = build_p3(temp.path(), "p3_wizer_frozen_argv")?;
    let optimized_path = temp.path().join("p3-wizer-frozen-argv-optimized.wasm");
    tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()?
        .block_on(wasm_rquickjs::optimize_component(
            &wasm_path,
            &optimized_path,
            "wizer-initialize",
        ))?;

    let invoke = |component: &Utf8Path| -> anyhow::Result<String> {
        let output = Command::new("wasmtime")
            .arg("run")
            .arg("-S")
            .arg("p3=y")
            .arg("-S")
            .arg("http=y")
            .arg("--wasm")
            .arg("component-model=y")
            .arg("--wasm")
            .arg("component-model-async=y")
            .arg("--argv0")
            .arg("runtime-program")
            .arg("--invoke")
            .arg("run()")
            .arg(component)
            .output()?;
        assert!(
            output.status.success(),
            "P3 component invocation should succeed; stdout:\n{}\nstderr:\n{}",
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr)
        );
        Ok(serde_json::from_slice(&output.stdout)?)
    };

    assert_eq!(invoke(&wasm_path)?, "runtime-program|runtime-program");
    assert_eq!(invoke(&optimized_path)?, "runtime-program|runtime-program");
    Ok(())
}

#[test]
fn p3_wizer_restores_runtime_env_when_user_prevents_extensions() -> anyhow::Result<()> {
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:p3-wizer-nonextensible-env;

            world p3-wizer-nonextensible-env {
              export run: async func() -> string;
            }
        "#},
        indoc! {r#"
            import { env } from 'node:process';

            process.env = Object.preventExtensions({ ...process.env });

            export async function run() {
              return `${process.env.P3_WIZER_RUNTIME_ENV ?? 'missing'}|${env.P3_WIZER_RUNTIME_ENV ?? 'missing'}`;
            }
        "#},
    )?;

    generate_p3(temp.path())?;
    let wasm_path = build_p3(temp.path(), "p3_wizer_nonextensible_env")?;
    let optimized_path = temp
        .path()
        .join("p3-wizer-nonextensible-env-optimized.wasm");
    tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()?
        .block_on(wasm_rquickjs::optimize_component(
            &wasm_path,
            &optimized_path,
            "wizer-initialize",
        ))?;

    let invoke = |component: &Utf8Path| -> anyhow::Result<String> {
        let output = Command::new("wasmtime")
            .arg("run")
            .arg("-S")
            .arg("p3=y")
            .arg("-S")
            .arg("http=y")
            .arg("--wasm")
            .arg("component-model=y")
            .arg("--wasm")
            .arg("component-model-async=y")
            .arg("--env")
            .arg("P3_WIZER_RUNTIME_ENV=runtime")
            .arg("--invoke")
            .arg("run()")
            .arg(component)
            .output()?;
        assert!(
            output.status.success(),
            "P3 component invocation should succeed; stdout:\n{}\nstderr:\n{}",
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr)
        );
        Ok(serde_json::from_slice(&output.stdout)?)
    };

    assert_eq!(invoke(&wasm_path)?, "runtime|runtime");
    assert_eq!(invoke(&optimized_path)?, "runtime|runtime");
    Ok(())
}

#[test]
fn p3_wizer_nonextensible_process_env_retains_string_coercion() -> anyhow::Result<()> {
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:p3-wizer-nonextensible-proxy-env;

            world p3-wizer-nonextensible-proxy-env {
              export run: async func() -> string;
            }
        "#},
        indoc! {r#"
            Object.preventExtensions(process.env);

            export async function run() {
              process.env.P3_WIZER_RUNTIME_ENV = 42;
              return `${typeof process.env.P3_WIZER_RUNTIME_ENV}:${process.env.P3_WIZER_RUNTIME_ENV}`;
            }
        "#},
    )?;

    generate_p3(temp.path())?;
    let wasm_path = build_p3(temp.path(), "p3_wizer_nonextensible_proxy_env")?;
    let optimized_path = temp
        .path()
        .join("p3-wizer-nonextensible-proxy-env-optimized.wasm");
    tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()?
        .block_on(wasm_rquickjs::optimize_component(
            &wasm_path,
            &optimized_path,
            "wizer-initialize",
        ))?;

    let invoke = |component: &Utf8Path| -> anyhow::Result<String> {
        let output = Command::new("wasmtime")
            .arg("run")
            .arg("-S")
            .arg("p3=y")
            .arg("-S")
            .arg("http=y")
            .arg("--wasm")
            .arg("component-model=y")
            .arg("--wasm")
            .arg("component-model-async=y")
            .arg("--env")
            .arg("P3_WIZER_RUNTIME_ENV=runtime")
            .arg("--invoke")
            .arg("run()")
            .arg(component)
            .output()?;
        assert!(
            output.status.success(),
            "P3 component invocation should succeed; stdout:\n{}\nstderr:\n{}",
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr)
        );
        Ok(serde_json::from_slice(&output.stdout)?)
    };

    assert_eq!(invoke(&wasm_path)?, "string:42");
    assert_eq!(invoke(&optimized_path)?, "string:42");
    Ok(())
}

#[test]
fn p3_wizer_links_unused_async_imports() -> anyhow::Result<()> {
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:p3-wizer-async-import;

            interface host {
              unused: async func();
            }

            world p3-wizer-async-import {
              import host;
              export run: async func() -> string;
            }
        "#},
        "export async function run() { return 'ok'; }\n",
    )?;

    generate_p3(temp.path())?;
    let wasm_path = build_p3(temp.path(), "p3_wizer_async_import")?;
    let optimized_path = temp.path().join("p3-wizer-async-import-optimized.wasm");
    tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()?
        .block_on(wasm_rquickjs::optimize_component(
            &wasm_path,
            &optimized_path,
            "wizer-initialize",
        ))?;

    let optimized = std::fs::read(&optimized_path)?;
    wasmparser_encoder::Validator::new_with_features(wasmparser_encoder::WasmFeatures::all())
        .validate_all(&optimized)?;
    Ok(())
}

#[test]
fn p3_generated_crate_builds_with_wasi_system_clock_import() -> anyhow::Result<()> {
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:clock;

            world clock {
              import wasi:clocks/system-clock@0.3.0-rc-2026-03-15;
              export run: async func() -> u64;
            }
        "#},
        "export async function run() { return 1n; }\n",
    )?;
    write_wit_dep(
        temp.path(),
        "clocks.wit",
        indoc! {r#"
            package wasi:clocks@0.3.0-rc-2026-03-15;

            interface types {
              type duration = u64;
            }

            interface system-clock {
              use types.{duration};

              record instant {
                seconds: s64,
                nanoseconds: u32,
              }

              now: func() -> instant;
              get-resolution: func() -> duration;
            }
        "#},
    )?;

    generate_p3(temp.path())?;

    let output = Command::new("cargo")
        .arg("build")
        .arg("--manifest-path")
        .arg(temp.path().join("out").join("Cargo.toml"))
        .arg("--target")
        .arg("wasm32-wasip2")
        .output()?;

    assert!(
        output.status.success(),
        "P3 generated crate with a wasi:clocks/system-clock import should build; stdout:\n{}\nstderr:\n{}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );
    Ok(())
}

#[test]
fn p3_generated_crate_builds_with_multiple_wasi_package_versions() -> anyhow::Result<()> {
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:multiple-wasi-versions;

            world multiple-wasi-versions {
              import wasi:cli/environment@0.3.0;
              export run: async func() -> u64;
            }
        "#},
        "export async function run() { return 1n; }\n",
    )?;
    write_wit_dep(
        temp.path(),
        "cli-p3.wit",
        indoc! {r#"
            package wasi:cli@0.3.0;

            interface environment {
              get-environment: func() -> list<tuple<string, string>>;
              get-arguments: func() -> list<string>;
              get-initial-cwd: func() -> option<string>;
            }
        "#},
    )?;
    write_wit_dep(
        temp.path(),
        "cli-p2.wit",
        indoc! {r#"
            package wasi:cli@0.2.6;

            interface environment {
              get-environment: func() -> list<tuple<string, string>>;
            }
        "#},
    )?;

    generate_p3(temp.path())?;

    let output = Command::new("cargo")
        .arg("build")
        .arg("--manifest-path")
        .arg(temp.path().join("out").join("Cargo.toml"))
        .arg("--target")
        .arg("wasm32-wasip2")
        .output()?;

    assert!(
        output.status.success(),
        "P3 generated crate with multiple versions of a WASI package should build; stdout:\n{}\nstderr:\n{}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );
    Ok(())
}

/// Hardening regression test for the WASI Preview 3 dependency boundary.
///
/// The Preview 3 generation path must not drag in the Preview 2 *runtime* crates. This test
/// resolves the generated P3 crate's dependency graph (for its default `["p3", "normal-p3"]`
/// features, on the `wasm32-wasip2` build target that P3 actually compiles to) and asserts that
/// none of the Preview 2 runtime dependencies are active, while the Preview 3 bindings are.
///
/// Note on scope: the check deliberately targets the P2 *runtime* crates the removed Preview 2
/// skeleton pulled in (`wstd`, `golem-wasi-http`). It does **not** assert the absence of:
/// - the `wasip2` crate: the skeleton binds the synchronous Preview 2 `set-times-at` through it,
///   and it is also `getrandom`'s WASI backend for the `wasm32-wasip2` target — it is not evidence
///   of a Preview 2 runtime leak in our code;
/// - the 0.42 `wit-bindgen-rt` and the target-agnostic binding crates that use it
///   (`wasi-logging`, `golem-context`, `golem-websocket`): they bind fully synchronous
///   interfaces that work on both targets (P3 components legitimately import residual 0.2-style
///   sync interfaces), and `wasi-logging` is part of the default `normal-p3` tier.
#[test]
fn p3_dependency_graph_excludes_preview2_runtime_crates() -> anyhow::Result<()> {
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package test:p3deps;

            world p3deps {
              export run: async func() -> string;
            }
        "#},
        "export async function run() { return \"ok\"; }\n",
    )?;

    generate_p3(temp.path())?;

    // `--prefix none` makes each line start with `<crate> vX.Y.Z ...`; `-e normal` keeps only
    // dependencies that compile into the artifact (no dev/build-only edges).
    let output = Command::new("cargo")
        .arg("tree")
        .arg("--manifest-path")
        .arg(temp.path().join("out").join("Cargo.toml"))
        .arg("--target")
        .arg("wasm32-wasip2")
        .arg("-e")
        .arg("normal")
        .arg("--prefix")
        .arg("none")
        .output()?;

    assert!(
        output.status.success(),
        "cargo tree on the generated P3 crate should succeed; stdout:\n{}\nstderr:\n{}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );

    let stdout = String::from_utf8_lossy(&output.stdout);
    let crate_names: std::collections::BTreeSet<&str> = stdout
        .lines()
        .filter_map(|line| line.split_whitespace().next())
        .filter(|token| !token.is_empty())
        .collect();

    // Preview 2 runtime crates that must never be active in the Preview 3 path.
    for forbidden in ["wstd", "golem-wasi-http"] {
        assert!(
            !crate_names.contains(forbidden),
            "Preview 2 runtime crate `{forbidden}` must not appear in the P3 dependency graph; \
             full graph:\n{stdout}"
        );
    }

    // The Preview 3 bindings must be present.
    assert!(
        crate_names.contains("wasip3"),
        "Preview 3 crate `wasip3` must appear in the P3 dependency graph; full graph:\n{stdout}"
    );

    Ok(())
}

/// Consumers such as Golem's SDK agent templates replace the whole `wit-bindgen-p3` entry with
/// `--dependency` and keep `optional = true` in it. The `p3` feature must still activate the
/// replacement, or the generated bindings cannot find `wit_bindgen_p3`.
#[test]
fn p3_feature_activates_an_optional_wit_bindgen_p3_override() -> anyhow::Result<()> {
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package test:p3-override;

            world p3-override {
              export run: func() -> string;
            }
        "#},
        "export function run() { return \"ok\"; }\n",
    )?;
    generate_p3(temp.path())?;
    let skeleton_manifest = std::fs::read_to_string(temp.path().join("out").join("Cargo.toml"))?;
    let entry = skeleton_manifest
        .lines()
        .find_map(|line| line.strip_prefix("wit-bindgen-p3 = "))
        .expect("the skeleton declares wit-bindgen-p3");
    let replacement = entry
        .replace(", optional = true", "")
        .trim_end()
        .strip_suffix('}')
        .expect("wit-bindgen-p3 is an inline table")
        .trim_end()
        .to_string()
        + ", optional = true }";
    std::fs::remove_dir_all(temp.path().join("out"))?;

    generate_wrapper_crate_with_options(
        &temp.path().join("wit"),
        &[JsModuleSpec {
            name: "module".to_string(),
            mode: EmbeddingMode::EmbedFile(temp.path().join("src").join("module.js")),
        }],
        &temp.path().join("out"),
        None,
        GenerationTarget::WasiP3,
        &WrapperCrateOptions {
            native_modules: vec![],
            dependencies: vec![DependencySpec {
                key: "wit-bindgen-p3".to_string(),
                value: replacement,
            }],
        },
    )?;

    let output = Command::new("cargo")
        .arg("tree")
        .arg("--manifest-path")
        .arg(temp.path().join("out").join("Cargo.toml"))
        .args(["--target", "wasm32-wasip2", "-e", "normal", "--depth", "1"])
        .args(["--prefix", "none"])
        .args(["--no-default-features", "--features", "p3"])
        .output()?;
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        output.status.success(),
        "cargo tree failed; stdout:\n{stdout}\nstderr:\n{}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert!(
        stdout.lines().any(|line| line.starts_with("wit-bindgen v")),
        "the `p3` feature must activate the optional wit-bindgen-p3 override; direct \
         dependencies:\n{stdout}"
    );
    Ok(())
}

#[test]
fn p3_generated_crate_builds_with_async_result_export() -> anyhow::Result<()> {
    // An async export returning `result<T, E>`. Per the documented contract a result-returning
    // JS function returns the bare `ok` value or `throw`s for the `err` arm (the `{ tag, val }`
    // shape is only used for results received as inputs/data, not for result *return* values).
    // This locks in that the P3 result-export glue (`JsResult` + `call_js_export_returning_result`)
    // generates a crate that compiles. The ok/err runtime behavior is validated by the
    // `examples/p3/async-result` host-runner harness.
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:result-export;

            world result-export {
              export run: async func(flag: bool) -> result<u32, string>;
            }
        "#},
        indoc! {r#"
            export async function run(flag) {
              if (flag) {
                return 7;
              }
              throw "nope";
            }
        "#},
    )?;

    generate_p3(temp.path())?;

    let build = Command::new("cargo")
        .arg("build")
        .arg("--manifest-path")
        .arg(temp.path().join("out").join("Cargo.toml"))
        .arg("--target")
        .arg("wasm32-wasip2")
        .output()?;

    assert!(
        build.status.success(),
        "P3 generated crate with an async result export should build; stdout:\n{}\nstderr:\n{}",
        String::from_utf8_lossy(&build.stdout),
        String::from_utf8_lossy(&build.stderr)
    );
    Ok(())
}

#[test]
fn p3_generated_crate_builds_with_node_builtin_imports() -> anyhow::Result<()> {
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:p3-builtins;

            world p3-builtins {
              export run: async func() -> string;
            }
        "#},
        indoc! {r#"
            import { Buffer } from 'node:buffer';
            import process from 'node:process';
            import path from 'node:path';

            export async function run() {
              return `${Buffer.from('p3').toString('utf8')}:${process.platform}:${path.join('a', 'b')}`;
            }
        "#},
    )?;

    generate_p3(temp.path())?;

    let build = Command::new("cargo")
        .arg("build")
        .arg("--manifest-path")
        .arg(temp.path().join("out").join("Cargo.toml"))
        .arg("--target")
        .arg("wasm32-wasip2")
        .output()?;

    assert!(
        build.status.success(),
        "P3 generated crate with Node.js builtin imports should build; stdout:\n{}\nstderr:\n{}",
        String::from_utf8_lossy(&build.stdout),
        String::from_utf8_lossy(&build.stderr)
    );
    Ok(())
}

#[test]
fn p3_fs_named_imports_are_supported() -> anyhow::Result<()> {
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:p3-fs-named;

            world p3-fs-named {
              export run: async func() -> string;
            }
        "#},
        indoc! {r#"
            import { readFile } from 'node:fs';

            export async function run() {
              return typeof readFile;
            }
        "#},
    )?;

    generate_p3(temp.path())?;
    let wasm_path = build_p3(temp.path(), "p3_fs_named")?;
    let result = run_p3_string_export(&wasm_path, "run")?;

    assert_eq!(result, "function");
    Ok(())
}

#[test]
fn p3_fs_read_write_roundtrip_on_wasi_p3() -> anyhow::Result<()> {
    // Strong functional check that node:fs actually *executes* on the Preview 3 path
    // (native filesystem calls driven through `block_on`), not merely that the named
    // exports are importable. A regression back to throwing "not available" stubs would
    // fail here even though the `typeof`-only smoke tests above would still pass.
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:p3-fs-rw;

            world p3-fs-rw {
              export run: async func() -> string;
            }
        "#},
        indoc! {r#"
            import { mkdirSync, writeFileSync, readFileSync, readdirSync, existsSync } from 'node:fs';

            export async function run() {
              mkdirSync('/data/sub', { recursive: true });
              writeFileSync('/data/sub/hello.txt', 'p3-fs-works');
              const back = readFileSync('/data/sub/hello.txt', 'utf8');
              const listed = readdirSync('/data/sub').join(',');
              const ex = existsSync('/data/sub/hello.txt');
              return `${back}|${listed}|${ex}`;
            }
        "#},
    )?;

    let data_dir = temp.path().join("data");
    std::fs::create_dir_all(&data_dir)?;

    generate_p3(temp.path())?;
    let wasm_path = build_p3(temp.path(), "p3_fs_rw")?;
    let result = run_p3_string_export_with_dir(&wasm_path, "run", &data_dir, "/data")?;

    assert_eq!(result, "p3-fs-works|hello.txt|true");
    // Confirm the write really hit the host filesystem through the P3 filesystem bindings.
    let written = std::fs::read_to_string(data_dir.join("sub").join("hello.txt"))?;
    assert_eq!(written, "p3-fs-works");
    Ok(())
}

#[test]
fn p3_fs_dirent_named_import_is_supported() -> anyhow::Result<()> {
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:p3-fs-dirent-named;

            world p3-fs-dirent-named {
              export run: async func() -> string;
            }
        "#},
        indoc! {r#"
            import { Dirent } from 'node:fs';

            export async function run() {
              return typeof Dirent;
            }
        "#},
    )?;

    generate_p3(temp.path())?;
    let wasm_path = build_p3(temp.path(), "p3_fs_dirent_named")?;
    let result = run_p3_string_export(&wasm_path, "run")?;

    assert_eq!(result, "function");
    Ok(())
}

#[test]
fn p3_net_named_imports_are_supported() -> anyhow::Result<()> {
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:p3-net-named;

            world p3-net-named {
              export run: async func() -> string;
            }
        "#},
        indoc! {r#"
            import { createConnection, Socket } from 'node:net';

            export async function run() {
              return `${typeof createConnection}:${typeof Socket}`;
            }
        "#},
    )?;

    generate_p3(temp.path())?;
    let wasm_path = build_p3(temp.path(), "p3_net_named")?;
    let result = run_p3_string_export(&wasm_path, "run")?;

    assert_eq!(result, "function:function");
    Ok(())
}

#[test]
fn p3_dgram_named_import_is_supported() -> anyhow::Result<()> {
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:p3-dgram-named;

            world p3-dgram-named {
              export run: async func() -> string;
            }
        "#},
        indoc! {r#"
            import { createSocket } from 'node:dgram';

            export async function run() {
              return typeof createSocket;
            }
        "#},
    )?;

    generate_p3(temp.path())?;
    let wasm_path = build_p3(temp.path(), "p3_dgram_named")?;
    let result = run_p3_string_export(&wasm_path, "run")?;

    assert_eq!(result, "function");
    Ok(())
}

#[test]
fn p3_dns_named_imports_are_supported() -> anyhow::Result<()> {
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:p3-dns-named;

            world p3-dns-named {
              export run: async func() -> string;
            }
        "#},
        indoc! {r#"
            import { lookup, promises } from 'node:dns';
            import { resolve4 } from 'node:dns/promises';

            export async function run() {
              return `${typeof lookup}:${typeof promises}:${typeof resolve4}`;
            }
        "#},
    )?;

    generate_p3(temp.path())?;
    let wasm_path = build_p3(temp.path(), "p3_dns_named")?;
    let result = run_p3_string_export(&wasm_path, "run")?;

    assert_eq!(result, "function:object:function");
    Ok(())
}

#[test]
fn p3_dns_promises_default_matches_dns_promises_object() -> anyhow::Result<()> {
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:p3-dns-promises-identity;

            world p3-dns-promises-identity {
              export run: async func() -> string;
            }
        "#},
        indoc! {r#"
            import dnsPromises from 'node:dns/promises';
            import { promises } from 'node:dns';

            export async function run() {
              return String(dnsPromises === promises);
            }
        "#},
    )?;

    generate_p3(temp.path())?;
    let wasm_path = build_p3(temp.path(), "p3_dns_promises_identity")?;
    let result = run_p3_string_export(&wasm_path, "run")?;

    assert_eq!(result, "true");
    Ok(())
}

#[test]
fn p3_set_timeout_resolves_promise_on_wasi_p3() -> anyhow::Result<()> {
    // Proves that the Preview 3 async spine actually *drives* rquickjs background tasks:
    // `setTimeout` schedules a Rust future via `ctx.spawn` that awaits
    // `wasip3::clocks::monotonic_clock::wait_for`. If the spawned future were never polled
    // (e.g. because the P3 executor did not wake rquickjs tasks), this `run()` would hang and
    // the invocation would time out instead of returning the resolved value.
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:p3-set-timeout;

            world p3-set-timeout {
              export run: async func() -> string;
            }
        "#},
        indoc! {r#"
            export async function run() {
              return await new Promise((resolve) => {
                setTimeout(() => resolve('timer-ok'), 1);
              });
            }
        "#},
    )?;

    generate_p3(temp.path())?;
    let wasm_path = build_p3(temp.path(), "p3_set_timeout")?;
    let result = run_p3_string_export(&wasm_path, "run")?;

    assert_eq!(result, "timer-ok");
    Ok(())
}

#[test]
fn p3_runtime_idle_wait_uses_export_liveness_boundary() -> anyhow::Result<()> {
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:p3-runtime-idle;

            world p3-runtime-idle {
              export run: async func() -> string;
            }
        "#},
        indoc! {r#"
            export async function run() {
              const events = ['before'];
              setTimeout(() => events.push('timer'), 5);
              const ignored = setInterval(() => events.push('unref'), 1000);
              ignored.unref();
              await process._awaitRuntimeIdle();
              events.push('after');
              return events.join(':');
            }
        "#},
    )?;

    generate_p3(temp.path())?;
    let wasm_path = build_p3(temp.path(), "p3_runtime_idle")?;
    let result = run_p3_string_export(&wasm_path, "run")?;

    assert_eq!(result, "before:timer:after");
    Ok(())
}

#[test]
fn p3_crypto_sha256_matches_known_digest_on_wasi_p3() -> anyhow::Result<()> {
    // The default `normal-p3` tier enables the real `crypto` capability, so `node:crypto`
    // must expose the full hashing surface. The `web_crypto_lite` fallback only provides
    // randomness and has no `createHash`, so computing the well-known SHA-256 digest of "abc"
    // proves the native hash bridge is actually wired and functional on the Preview 3 path.
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:p3-crypto-sha256;

            world p3-crypto-sha256 {
              export run: async func() -> string;
            }
        "#},
        indoc! {r#"
            import { createHash } from 'node:crypto';

            export async function run() {
              return createHash('sha256').update('abc').digest('hex');
            }
        "#},
    )?;

    generate_p3(temp.path())?;
    let wasm_path = build_p3(temp.path(), "p3_crypto_sha256")?;
    let result = run_p3_string_export(&wasm_path, "run")?;

    assert_eq!(
        result,
        "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
    );
    Ok(())
}

#[test]
fn p3_zlib_gzip_roundtrip_on_wasi_p3() -> anyhow::Result<()> {
    // The default `normal-p3` tier enables the real `zlib` capability. The `zlib_disabled`
    // fallback throws for every operation, so a gzip -> gunzip roundtrip that recovers the
    // original text proves the native flate2 bridge is actually wired on the Preview 3 path.
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:p3-zlib-roundtrip;

            world p3-zlib-roundtrip {
              export run: async func() -> string;
            }
        "#},
        indoc! {r#"
            import { Buffer } from 'node:buffer';
            import { gzipSync, gunzipSync } from 'node:zlib';

            export async function run() {
              const original = 'hello zlib on preview 3';
              const restored = gunzipSync(gzipSync(Buffer.from(original))).toString();
              return restored;
            }
        "#},
    )?;

    generate_p3(temp.path())?;
    let wasm_path = build_p3(temp.path(), "p3_zlib_roundtrip")?;
    let result = run_p3_string_export(&wasm_path, "run")?;

    assert_eq!(result, "hello zlib on preview 3");
    Ok(())
}

#[test]
fn p3_sqlite_roundtrip_on_wasi_p3() -> anyhow::Result<()> {
    // `sqlite` is intentionally kept out of the default `normal-p3` tier (it pulls in the
    // heavier rusqlite dependency), so this builds the generated crate with the full tier instead.
    // Use the no-logging variant because this test invokes the component through the `wasmtime`
    // CLI, which does not provide a `wasi:logging/logging` host implementation. An in-memory
    // create/insert/select roundtrip proves the real rusqlite bridge is wired and functional on
    // the Preview 3 path rather than the throwing `sqlite_disabled` stub.
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:p3-sqlite-roundtrip;

            world p3-sqlite-roundtrip {
              export run: async func() -> string;
            }
        "#},
        indoc! {r#"
            import { DatabaseSync } from 'node:sqlite';

            export async function run() {
              const db = new DatabaseSync(':memory:');
              db.exec('CREATE TABLE t (id INTEGER PRIMARY KEY, name TEXT)');
              const insert = db.prepare('INSERT INTO t (name) VALUES (?)');
              insert.run('alice');
              insert.run('bob');
              const rows = db.prepare('SELECT name FROM t ORDER BY id').all();
              db.close();
              return rows.map((r) => r.name).join(',');
            }
        "#},
    )?;

    generate_p3(temp.path())?;
    let wasm_path = build_p3_with_features(
        temp.path(),
        "p3_sqlite_roundtrip",
        Some("full-no-logging-p3"),
    )?;
    let result = run_p3_string_export(&wasm_path, "run")?;

    assert_eq!(result, "alice,bob");
    Ok(())
}

#[test]
fn p3_websocket_builds_on_wasi_p3() -> anyhow::Result<()> {
    // `websocket` is an opt-in capability (like `logging`) intentionally kept out of the default
    // `normal-p3` and `full-p3` tiers because enabling it adds a required `golem:websocket/client`
    // host import that plain WASI hosts (including the wasmtime CLI used here) cannot satisfy. It
    // uses the Preview 3 interface with asynchronous receive operations.
    // There is no `golem:websocket` host in this harness, so this is a build-only check that the
    // websocket builtin compiles and links into a Preview 3 crate (the `WebSocket`/`WebSocketStream`
    // globals it installs are exercised by the P2 runtime tests / a Golem host, not here).
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:p3-websocket;

            world p3-websocket {
              import golem:websocket/client@1.5.0;
              export run: async func() -> string;
            }
        "#},
        indoc! {r#"
            import { WebsocketConnection } from 'golem:websocket/client@1.5.0';

            export async function run() {
              return `${typeof WebSocket},${typeof WebSocketStream},${typeof WebsocketConnection.connect}`;
            }
        "#},
    )?;

    let websocket_deps = temp.path().join("wit/deps/golem-websocket");
    std::fs::create_dir_all(&websocket_deps)?;
    std::fs::write(
        websocket_deps.join("websocket.wit"),
        include_str!("../crates/golem-websocket/wit-p3/deps/golem-websocket/websocket.wit"),
    )?;

    generate_p3(temp.path())?;
    use_local_golem_websocket(temp.path())?;
    // Build only: enabling `websocket` adds an unsatisfiable `golem:websocket` import under the
    // wasmtime CLI, so we assert compilation/linking succeeds rather than invoking the component.
    // Use the no-logging feature set for consistency with the P3 CLI-invoked tests.
    let _wasm_path = build_p3_with_features(
        temp.path(),
        "p3_websocket",
        Some(P3_NORMAL_NO_LOGGING_WITH_WEBSOCKET_FEATURES),
    )?;
    Ok(())
}

#[test]
fn p3_generated_crate_builds_with_exported_resource() -> anyhow::Result<()> {
    // An *exported* WIT resource on the Preview 3 path (Phase 4). It exercises every method shape:
    // a synchronous constructor, synchronous instance/static methods (plain `fn`s driven by
    // `block_on`), and `async func` instance/static methods (`async fn`s awaiting the JS Promise).
    // This locks in that the P3 exported-resource glue generates a crate that compiles. The
    // end-to-end runtime behavior (constructor / method / static / async / drop) is validated by
    // the `tests/p3_exported_resource.rs` harness.
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:exported-resource;

            interface api {
              resource counter {
                constructor(initial: u32);
                increment: func(by: u32) -> u32;
                get: func() -> u32;
                add-other: func(other: borrow<counter>) -> u32;
                %static-zero: static func() -> u32;
                identity: static func(value: own<counter>) -> counter;
                identity-async: static async func(value: own<counter>) -> counter;
                alias: static func(value: borrow<counter>) -> counter;
                stash: static func(value: own<counter>);
                stash-and-fail: static func(value: own<counter>) -> result<_, string>;
                take: static func() -> counter;
                increment-async: async func(by: u32, other: borrow<counter>) -> u32;
                make-async: static async func(initial: u32) -> u32;
              }
            }

            world exported-resource {
              export api;
            }
        "#},
        indoc! {r#"
            class Counter {
              constructor(initial) {
                this.value = initial;
              }
              increment(by) {
                this.value += by;
                return this.value;
              }
              get() {
                return this.value;
              }
              addOther(other) {
                return this.value + other.value;
              }
              static staticZero() {
                return 0;
              }
              static identity(value) {
                return value;
              }
              static async identityAsync(value) {
                await Promise.resolve();
                return value;
              }
              static alias(value) {
                return value;
              }
              static stash(value) {
                Object.freeze(value);
                globalThis.stashedCounter = value;
              }
              static stashAndFail(value) {
                Object.freeze(value);
                globalThis.stashedCounter = value;
                throw "expected failure";
              }
              static take() {
                return globalThis.stashedCounter;
              }
              async incrementAsync(by, other) {
                await Promise.resolve();
                this.value += by + other.value;
                return this.value;
              }
              static async makeAsync(initial) {
                await Promise.resolve();
                return initial;
              }
            }

            export const api = {
              Counter,
            };
        "#},
    )?;

    generate_p3(temp.path())?;
    let _wasm_path = build_p3(temp.path(), "exported_resource")?;
    Ok(())
}

#[test]
fn p3_rejects_methodless_exported_resource() -> anyhow::Result<()> {
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:methodless-resource;

            interface api {
              resource r;
            }

            world methodless-resource {
              export api;
              export run: async func() -> u32;
            }
        "#},
        "export async function run() { return 1; }\n",
    )?;

    let error = generate_p3(temp.path())
        .expect_err("P3 generation must reject interface-owned methodless exported resources");
    assert!(
        format!("{error:#}").contains(
            "Exported resources without any constructor, method, or static function are not supported by the WASI Preview 3 generation path (resource 'r')"
        ),
        "P3 generation must return an actionable error for an interface-owned methodless resource; got: {error:#}"
    );
    Ok(())
}

#[test]
fn p3_builds_with_foreign_resource_alias_in_async_export() -> anyhow::Result<()> {
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:foreign-resource-alias;

            interface common {
              resource context {
                get-value: async func() -> string;
              }
            }

            interface api {
              use common.{context};
              run: async func(ctx: own<context>);
            }

            world foreign-resource-alias {
              import common;
              export api;
            }
        "#},
        "export const api = { async run(_ctx) {} };\n",
    )?;

    generate_p3(temp.path())?;
    let _wasm_path = build_p3(temp.path(), "foreign_resource_alias")?;
    Ok(())
}

#[test]
fn p3_rejects_methodless_world_level_resource() -> anyhow::Result<()> {
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:methodless-world-resource;

            world methodless-world-resource {
              resource r;
              export run: async func() -> u32;
            }
        "#},
        "export async function run() { return 1; }\n",
    )?;

    assert!(
        generate_p3(temp.path()).is_err(),
        "P3 generation must reject resources declared directly in the world even when the resource has no functions"
    );
    Ok(())
}

#[test]
fn p3_rejects_world_level_imported_resource() -> anyhow::Result<()> {
    // A resource declared directly in the world (rather than inside an interface) is a documented
    // limitation. The Preview 3 path must reject it instead of emitting a crate that fails to
    // compile.
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:world-resource;

            world world-resource {
              resource r;

              import make: func() -> r;
              import take: func(x: r);
              export run: async func() -> u32;
            }
        "#},
        "export async function run() { return 1; }\n",
    )?;

    assert!(
        generate_p3(temp.path()).is_err(),
        "P3 generation must reject resources imported directly into the world"
    );
    Ok(())
}

/// Functions imported directly into the world are importable from a JavaScript module named after
/// the world, both synchronous and `async` ones.
#[test]
fn p3_world_level_function_imports_are_importable() -> anyhow::Result<()> {
    let temp = Utf8TempDir::new()?;
    let consumer = temp.path().join("consumer");
    write_fixture(
        &consumer,
        indoc! {r#"
            package bug:world-imports;

            world world-imports {
              import get-number: func() -> u32;
              import get-label: async func() -> string;
              export run: async func() -> string;
            }
        "#},
        indoc! {r#"
            import { getNumber, getLabel } from 'world-imports';

            export async function run() {
              return `${getNumber() + 1}:${await getLabel()}`;
            }
        "#},
    )?;
    generate_p3(&consumer)?;

    let provider = temp.path().join("provider");
    write_fixture(
        &provider,
        indoc! {r#"
            package bug:world-imports-provider;

            world world-imports-provider {
              export get-number: func() -> u32;
              export get-label: async func() -> string;
            }
        "#},
        indoc! {r#"
            export function getNumber() { return 41; }
            export async function getLabel() { return 'label'; }
        "#},
    )?;
    generate_p3(&provider)?;
    let provider = build_p3(&provider, "world_imports_provider")?;

    let socket = build_p3(&consumer, "world_imports")?;
    let composed = consumer.join("composed.wasm");
    compose_provider(&socket, &provider, &composed)?;
    assert_eq!(run_p3_string_export(&composed, "run")?, "42:label");
    Ok(())
}

#[test]
fn p3_fetch_get_returns_body_on_wasi_p3() -> anyhow::Result<()> {
    // Strong functional check that `fetch`/HTTP actually *executes* on the Preview 3 path: the
    // request is driven through `wasip3::http::client::send` (Component Model async bodies), not
    // through P2 pollables. A regression to a disabled HTTP stub (which throws for every call)
    // would fail this test.
    let port = spawn_test_http_server();
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:p3-fetch-get;

            world p3-fetch-get {
              export run: async func() -> string;
            }
        "#},
        &indoc! {r#"
            export async function run() {
              const res = await fetch('http://127.0.0.1:__PORT__/hello');
              const text = await res.text();
              return `${res.status}:${text}`;
            }
        "#}
        .replace("__PORT__", &port.to_string()),
    )?;

    generate_p3(temp.path())?;
    let wasm_path = build_p3(temp.path(), "p3_fetch_get")?;
    let result = run_p3_string_export(&wasm_path, "run")?;

    assert_eq!(result, "200:hello-from-p3");
    Ok(())
}

#[test]
fn p3_fetch_post_echoes_body_on_wasi_p3() -> anyhow::Result<()> {
    // Validates buffered *request* bodies on the Preview 3 path: the POST body is streamed to the
    // server through the async `stream<u8>` request body, and the server echoes it back.
    let port = spawn_test_http_server();
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:p3-fetch-post;

            world p3-fetch-post {
              export run: async func() -> string;
            }
        "#},
        &indoc! {r#"
            export async function run() {
              const res = await fetch('http://127.0.0.1:__PORT__/echo', {
                method: 'POST',
                body: 'ping-p3',
              });
              const text = await res.text();
              return `${res.status}:${text}`;
            }
        "#}
        .replace("__PORT__", &port.to_string()),
    )?;

    generate_p3(temp.path())?;
    let wasm_path = build_p3(temp.path(), "p3_fetch_post")?;
    let result = run_p3_string_export(&wasm_path, "run")?;

    assert_eq!(result, "200:ping-p3");
    Ok(())
}

#[test]
fn p3_fetch_follows_redirect_on_wasi_p3() -> anyhow::Result<()> {
    // Validates the redirect-following logic in `builtin/http.rs`: `GET /redirect` returns a 302 to
    // `/hello`, and the default `redirect: 'follow'` policy must transparently follow it and
    // surface `redirected === true` plus the final body.
    let port = spawn_test_http_server();
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:p3-fetch-redirect;

            world p3-fetch-redirect {
              export run: async func() -> string;
            }
        "#},
        &indoc! {r#"
            export async function run() {
              const res = await fetch('http://127.0.0.1:__PORT__/redirect');
              const text = await res.text();
              return `${res.status}:${res.redirected}:${text}`;
            }
        "#}
        .replace("__PORT__", &port.to_string()),
    )?;

    generate_p3(temp.path())?;
    let wasm_path = build_p3(temp.path(), "p3_fetch_redirect")?;
    let result = run_p3_string_export(&wasm_path, "run")?;

    assert_eq!(result, "200:true:hello-from-p3");
    Ok(())
}

#[test]
fn p3_fetch_manual_redirect_returns_opaqueredirect_filtered_response() -> anyhow::Result<()> {
    // Fetch's manual redirect mode returns an opaque-redirect filtered response: status/statusText,
    // headers, and body are hidden from JavaScript, and the response type is `opaqueredirect`.
    let port = spawn_test_http_server();
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:p3-fetch-manual-redirect;

            world p3-fetch-manual-redirect {
              export run: async func() -> string;
            }
        "#},
        &indoc! {r#"
            export async function run() {
              const res = await fetch('http://127.0.0.1:__PORT__/redirect', {
                redirect: 'manual',
              });
              return `${res.status}:${res.statusText}:${res.type}:${res.headers.get('location')}:${await res.text()}`;
            }
        "#}
        .replace("__PORT__", &port.to_string()),
    )?;

    generate_p3(temp.path())?;
    let wasm_path = build_p3(temp.path(), "p3_fetch_manual_redirect")?;
    let result = run_p3_string_export(&wasm_path, "run")?;

    assert_eq!(result, "0::opaqueredirect:null:");
    Ok(())
}

#[test]
fn p3_request_clone_preserves_replayable_body_without_disturbing_original() -> anyhow::Result<()> {
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:p3-request-clone-body;

            world p3-request-clone-body {
              export run: async func() -> string;
            }
        "#},
        indoc! {r#"
            export async function run() {
              const req = new Request('http://example.com/echo', {
                method: 'POST',
                body: 'clone-body',
              });

              try {
                const clone = req.clone();
                return `not-thrown:${clone.method}:${await clone.text()}:originalUsed=${req.bodyUsed}`;
              } catch (err) {
                return `thrown:${String(err && (err.message || err))}:originalUsed=${req.bodyUsed}`;
              }
            }
        "#},
    )?;

    generate_p3(temp.path())?;
    let wasm_path = build_p3(temp.path(), "p3_request_clone_body")?;
    let result = run_p3_string_export(&wasm_path, "run")?;

    assert_eq!(result, "not-thrown:POST:clone-body:originalUsed=false");
    Ok(())
}

#[test]
fn p3_fetch_rejects_invalid_http_version() -> anyhow::Result<()> {
    let port = spawn_test_http_server();
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:p3-fetch-invalid-version;

            world p3-fetch-invalid-version {
              export run: async func() -> string;
            }
        "#},
        &indoc! {r#"
            export async function run() {
              try {
                const res = await fetch('http://127.0.0.1:__PORT__/hello', {
                  version: 'HTTP/9.9',
                });
                return `not-thrown:${res.status}:${await res.text()}`;
              } catch (err) {
                return String(err && (err.message || err));
              }
            }
        "#}
        .replace("__PORT__", &port.to_string()),
    )?;

    generate_p3(temp.path())?;
    let wasm_path = build_p3(temp.path(), "p3_fetch_invalid_version")?;
    let result = run_p3_string_export(&wasm_path, "run")?;

    assert!(
        result.contains("Unsupported HTTP version: HTTP/9.9"),
        "invalid HTTP version should be rejected before sending; got {result:?}"
    );
    Ok(())
}

#[test]
fn p3_fetch_rejects_invalid_header_value() -> anyhow::Result<()> {
    let port = spawn_test_http_server();
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:p3-fetch-invalid-header-value;

            world p3-fetch-invalid-header-value {
              export run: async func() -> string;
            }
        "#},
        &indoc! {r#"
            export async function run() {
              try {
                const res = await fetch('http://127.0.0.1:__PORT__/hello', {
                  headers: { 'x-bad': 'a\r\nb' },
                });
                return `not-thrown:${res.status}:${await res.text()}`;
              } catch (err) {
                return String(err && (err.message || err));
              }
            }
        "#}
        .replace("__PORT__", &port.to_string()),
    )?;

    generate_p3(temp.path())?;
    let wasm_path = build_p3(temp.path(), "p3_fetch_invalid_header_value")?;
    let result = run_p3_string_export(&wasm_path, "run")?;

    assert!(
        result.contains("failed to parse header value"),
        "invalid header value should be rejected before sending; got {result:?}"
    );
    Ok(())
}

#[test]
fn p3_fetch_rejects_invalid_method() -> anyhow::Result<()> {
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:p3-fetch-invalid-method;

            world p3-fetch-invalid-method {
              export run: async func() -> string;
            }
        "#},
        indoc! {r#"
            export async function run() {
              try {
                await fetch('http://example.com/hello', {
                  method: 'bad method',
                });
                return 'not-thrown';
              } catch (err) {
                return String(err && (err.message || err));
              }
            }
        "#},
    )?;

    generate_p3(temp.path())?;
    let wasm_path = build_p3(temp.path(), "p3_fetch_invalid_method")?;
    let result = run_p3_string_export(&wasm_path, "run")?;

    assert!(
        result.contains("failed to parse method"),
        "invalid method syntax should be rejected by the native request constructor like P2; got {result:?}"
    );
    Ok(())
}

#[test]
fn p3_fetch_preserves_custom_method_case() -> anyhow::Result<()> {
    let port = spawn_test_http_server();
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:p3-fetch-custom-method-case;

            world p3-fetch-custom-method-case {
              export run: async func() -> string;
            }
        "#},
        &indoc! {r#"
            export async function run() {
              const res = await fetch('http://127.0.0.1:__PORT__/method', {
                method: 'foo',
              });
              return await res.text();
            }
        "#}
        .replace("__PORT__", &port.to_string()),
    )?;

    generate_p3(temp.path())?;
    let wasm_path = build_p3(temp.path(), "p3_fetch_custom_method_case")?;
    let result = run_p3_string_export(&wasm_path, "run")?;

    assert_eq!(result, "foo");
    Ok(())
}

#[test]
fn p3_fetch_status_text_uses_canonical_reason() -> anyhow::Result<()> {
    let port = spawn_test_http_server();
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:p3-fetch-status-text;

            world p3-fetch-status-text {
              export run: async func() -> string;
            }
        "#},
        &indoc! {r#"
            export async function run() {
              const res = await fetch('http://127.0.0.1:__PORT__/legal');
              return `${res.status}:${res.statusText}`;
            }
        "#}
        .replace("__PORT__", &port.to_string()),
    )?;

    generate_p3(temp.path())?;
    let wasm_path = build_p3(temp.path(), "p3_fetch_status_text")?;
    let result = run_p3_string_export(&wasm_path, "run")?;

    assert_eq!(result, "451:Unavailable For Legal Reasons");
    Ok(())
}

#[test]
fn p3_fetch_rejects_truncated_response_body() -> anyhow::Result<()> {
    let port = spawn_test_http_server();
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:p3-fetch-truncated-body;

            world p3-fetch-truncated-body {
              export run: async func() -> string;
            }
        "#},
        &indoc! {r#"
            export async function run() {
              try {
                const res = await fetch('http://127.0.0.1:__PORT__/truncated');
                return `not-thrown:${res.status}:${await res.text()}`;
              } catch (err) {
                return `thrown:${String(err && (err.message || err))}`;
              }
            }
        "#}
        .replace("__PORT__", &port.to_string()),
    )?;

    generate_p3(temp.path())?;
    let wasm_path = build_p3(temp.path(), "p3_fetch_truncated_body")?;
    let result = run_p3_string_export(&wasm_path, "run")?;

    assert!(
        result.starts_with("thrown:"),
        "fetch should reject instead of returning a partial response body; got {result:?}"
    );
    Ok(())
}

#[test]
fn p3_fetch_follows_redirect_even_when_redirect_body_is_truncated() -> anyhow::Result<()> {
    let port = spawn_test_http_server();
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:p3-fetch-truncated-redirect-body;

            world p3-fetch-truncated-redirect-body {
              export run: async func() -> string;
            }
        "#},
        &indoc! {r#"
            export async function run() {
              try {
                const res = await fetch('http://127.0.0.1:__PORT__/truncated-redirect');
                return `${res.status}:${res.redirected}:${await res.text()}`;
              } catch (err) {
                return `thrown:${String(err && (err.message || err))}`;
              }
            }
        "#}
        .replace("__PORT__", &port.to_string()),
    )?;

    generate_p3(temp.path())?;
    let wasm_path = build_p3(temp.path(), "p3_fetch_truncated_redirect_body")?;
    let result = run_p3_string_export(&wasm_path, "run")?;

    assert_eq!(result, "200:true:hello-from-p3");
    Ok(())
}

#[test]
fn p3_response_json_invalid_status_matches_p2_fallback() -> anyhow::Result<()> {
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:p3-response-json-invalid-status;

            world p3-response-json-invalid-status {
              export run: async func() -> string;
            }
        "#},
        indoc! {r#"
            export async function run() {
              const res = Response.json({ ok: true }, { status: 42 });
              return `${res.status}:${res.statusText}:${await res.text()}`;
            }
        "#},
    )?;

    generate_p3(temp.path())?;
    let wasm_path = build_p3(temp.path(), "p3_response_json_invalid_status")?;
    let result = run_p3_string_export(&wasm_path, "run")?;

    assert_eq!(result, "200:OK:{\"ok\":true}");
    Ok(())
}

#[test]
fn p3_url_search_params_body_replaces_existing_content_type() -> anyhow::Result<()> {
    let port = spawn_test_http_server();
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:p3-url-search-params-content-type;

            world p3-url-search-params-content-type {
              export run: async func() -> string;
            }
        "#},
        &indoc! {r#"
            export async function run() {
              const res = await fetch('http://127.0.0.1:__PORT__/content-type', {
                method: 'POST',
                headers: { 'Content-Type': 'text/plain' },
                body: new URLSearchParams([['a', 'b']]),
              });
              return await res.text();
            }
        "#}
        .replace("__PORT__", &port.to_string()),
    )?;

    generate_p3(temp.path())?;
    let wasm_path = build_p3(temp.path(), "p3_url_search_params_content_type")?;
    let result = run_p3_string_export(&wasm_path, "run")?;

    assert_eq!(result, "1:application/x-www-form-urlencoded");
    Ok(())
}

#[test]
fn p3_fetch_streams_readable_stream_request_body_on_wasi_p3() -> anyhow::Result<()> {
    // Validates *streaming* request bodies on the Preview 3 path: a `ReadableStream` POST body is
    // uploaded chunk-by-chunk through the Component Model `stream<u8>` request body while the
    // `wasi:http/client.send` future is in flight, and the server echoes the concatenated body.
    let port = spawn_test_http_server();
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:p3-fetch-stream-body;

            world p3-fetch-stream-body {
              export run: async func() -> string;
            }
        "#},
        &indoc! {r#"
            export async function run() {
              const chunks = ['strea', 'ming-', 'p3-', 'upload'];
              const body = new ReadableStream({
                start(controller) {
                  const enc = new TextEncoder();
                  for (const c of chunks) {
                    controller.enqueue(enc.encode(c));
                  }
                  controller.close();
                },
              });
              const res = await fetch('http://127.0.0.1:__PORT__/echo', {
                method: 'POST',
                body,
                duplex: 'half',
              });
              const text = await res.text();
              return `${res.status}:${text}`;
            }
        "#}
        .replace("__PORT__", &port.to_string()),
    )?;

    generate_p3(temp.path())?;
    let wasm_path = build_p3(temp.path(), "p3_fetch_stream_body")?;
    let result = run_p3_string_export(&wasm_path, "run")?;

    assert_eq!(result, "200:streaming-p3-upload");
    Ok(())
}

#[test]
fn p3_fetch_streams_large_readable_stream_request_body_on_wasi_p3() -> anyhow::Result<()> {
    // Validates that a large streamed request body (many chunks, larger than a single stream
    // write) is uploaded and echoed back intact, exercising the write loop / backpressure.
    let port = spawn_test_http_server();
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:p3-fetch-stream-body-large;

            world p3-fetch-stream-body-large {
              export run: async func() -> string;
            }
        "#},
        &indoc! {r#"
            export async function run() {
              const chunkCount = 64;
              const chunkSize = 1024;
              const body = new ReadableStream({
                start(controller) {
                  for (let i = 0; i < chunkCount; i++) {
                    const chunk = new Uint8Array(chunkSize);
                    chunk.fill(65 + (i % 26));
                    controller.enqueue(chunk);
                  }
                  controller.close();
                },
              });
              const res = await fetch('http://127.0.0.1:__PORT__/echo', {
                method: 'POST',
                body,
                duplex: 'half',
              });
              const buf = await res.arrayBuffer();
              return `${res.status}:${buf.byteLength}`;
            }
        "#}
        .replace("__PORT__", &port.to_string()),
    )?;

    generate_p3(temp.path())?;
    let wasm_path = build_p3(temp.path(), "p3_fetch_stream_body_large")?;
    let result = run_p3_string_export(&wasm_path, "run")?;

    assert_eq!(result, "200:65536");
    Ok(())
}

#[test]
fn p3_streaming_fetch_invalid_redirect_location_matches_buffered_path() -> anyhow::Result<()> {
    // A malformed Location cannot be followed. The buffered P3 path falls back to returning the
    // 302 response as the final visible response; the public fetch result must not depend on
    // whether the request body is buffered or a ReadableStream.
    let port = spawn_test_http_server();
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:p3-fetch-stream-invalid-redirect-location;

            world p3-fetch-stream-invalid-redirect-location {
              export run: async func() -> string;
            }
        "#},
        &indoc! {r#"
            export async function run() {
              const url = 'http://127.0.0.1:__PORT__/bad-location-redirect';

              const buffered = await fetch(url, { method: 'POST', body: 'buffered' });
              const bufferedResult = `${buffered.status}:${await buffered.text()}`;

              const body = new ReadableStream({
                start(controller) {
                  controller.enqueue(new TextEncoder().encode('streamed'));
                  controller.close();
                },
              });
              try {
                const streamed = await fetch(url, {
                  method: 'POST',
                  body,
                  duplex: 'half',
                });
                return `buffered=${bufferedResult};streaming=${streamed.status}:${await streamed.text()}`;
              } catch (err) {
                return `buffered=${bufferedResult};streaming=thrown:${String(err && (err.message || err))}`;
              }
            }
        "#}
        .replace("__PORT__", &port.to_string()),
    )?;

    generate_p3(temp.path())?;
    let wasm_path = build_p3(temp.path(), "p3_fetch_stream_invalid_redirect_location")?;
    let result = run_p3_string_export(&wasm_path, "run")?;

    assert_eq!(
        result,
        "buffered=302:bad-location-body;streaming=302:bad-location-body"
    );
    Ok(())
}

#[test]
fn p3_streaming_fetch_stream_body_307_redirect_fails_per_fetch_spec() -> anyhow::Result<()> {
    // A 307 redirect preserves the original method and request body. A *buffered* body has a
    // replayable source, so buffered fetch re-sends it and succeeds. A *streaming* (ReadableStream)
    // body has a null source and per the Fetch standard's HTTP-redirect fetch ("If ... status is
    // not 303, request's body is non-null, and request's body's source is null, then return a
    // network error") cannot be replayed, so streaming fetch must fail. This spec-mandated
    // divergence is the correct behavior; the two paths are NOT expected to match here.
    let port = spawn_test_http_server();
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:p3-fetch-stream-307-redirect;

            world p3-fetch-stream-307-redirect {
              export run: async func() -> string;
            }
        "#},
        &indoc! {r#"
            export async function run() {
              const url = 'http://127.0.0.1:__PORT__/redirect-307';

              const buffered = await fetch(url, { method: 'POST', body: 'redirect-body' });
              const bufferedResult = `${buffered.status}:${buffered.redirected}:${await buffered.text()}`;

              const body = new ReadableStream({
                start(controller) {
                  controller.enqueue(new TextEncoder().encode('redirect-body'));
                  controller.close();
                },
              });
              try {
                const streamed = await fetch(url, {
                  method: 'POST',
                  body,
                  duplex: 'half',
                });
                return `buffered=${bufferedResult};streaming=${streamed.status}:${streamed.redirected}:${await streamed.text()}`;
              } catch (err) {
                return `buffered=${bufferedResult};streaming=thrown:${String(err && (err.message || err))}`;
              }
            }
        "#}
        .replace("__PORT__", &port.to_string()),
    )?;

    generate_p3(temp.path())?;
    let wasm_path = build_p3(temp.path(), "p3_fetch_stream_307_redirect")?;
    let result = run_p3_string_export(&wasm_path, "run")?;

    // The buffered arm replays its body and succeeds; the streaming arm must fail (network error)
    // because a ReadableStream body has no replayable source.
    assert!(
        result.starts_with("buffered=200:true:POST:redirect-body;streaming=thrown:"),
        "buffered fetch should replay the body across 307 while streaming fetch fails; got {result:?}"
    );
    assert!(
        result.contains("streaming=thrown:")
            && result.contains(
                "streaming request body cannot be resent across a body-preserving redirect"
            ),
        "streaming fetch should fail with the spec-mandated network error for a stream body across a 307; got {result:?}"
    );
    Ok(())
}

#[test]
fn p3_streaming_fetch_no_cors_response_is_opaque() -> anyhow::Result<()> {
    // The public fetch contract should not depend on whether the request body is buffered or a
    // ReadableStream. Buffered P3 fetch makes no-cors responses opaque in native simple_send; the
    // streaming path must do the same instead of exposing status/body/headers.
    let port = spawn_test_http_server();
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:p3-fetch-stream-no-cors-opaque;

            world p3-fetch-stream-no-cors-opaque {
              export run: async func() -> string;
            }
        "#},
        &indoc! {r#"
            export async function run() {
              const body = new ReadableStream({
                start(controller) {
                  controller.enqueue(new TextEncoder().encode('visible-if-not-opaque'));
                  controller.close();
                },
              });
              const res = await fetch('http://127.0.0.1:__PORT__/echo', {
                method: 'POST',
                mode: 'no-cors',
                body,
                duplex: 'half',
              });
              const text = await res.text();
              return `${res.status}:${res.type}:${text}`;
            }
        "#}
        .replace("__PORT__", &port.to_string()),
    )?;

    generate_p3(temp.path())?;
    let wasm_path = build_p3(temp.path(), "p3_fetch_stream_no_cors_opaque")?;
    let result = run_p3_string_export(&wasm_path, "run")?;

    assert_eq!(result, "0:opaque:");
    Ok(())
}

#[test]
fn p3_streaming_fetch_no_cors_rejects_unsafe_method() -> anyhow::Result<()> {
    // Buffered P3 fetch enforces no-cors method restrictions before sending. A ReadableStream body
    // takes a separate streaming path and must reject the same public fetch input instead of
    // issuing the unsafe method.
    let port = spawn_test_http_server();
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:p3-fetch-stream-no-cors-method;

            world p3-fetch-stream-no-cors-method {
              export run: async func() -> string;
            }
        "#},
        &indoc! {r#"
            export async function run() {
              const body = new ReadableStream({
                start(controller) {
                  controller.enqueue(new TextEncoder().encode('body'));
                  controller.close();
                },
              });
              try {
                const res = await fetch('http://127.0.0.1:__PORT__/method', {
                  method: 'PUT',
                  mode: 'no-cors',
                  body,
                  duplex: 'half',
                });
                return `not-thrown:${res.status}:${await res.text()}`;
              } catch (err) {
                return `thrown:${String(err && (err.message || err))}`;
              }
            }
        "#}
        .replace("__PORT__", &port.to_string()),
    )?;

    generate_p3(temp.path())?;
    let wasm_path = build_p3(temp.path(), "p3_fetch_stream_no_cors_method")?;
    let result = run_p3_string_export(&wasm_path, "run")?;

    assert!(
        result.contains("thrown:no-cors mode only allows GET, HEAD, or POST methods"),
        "streaming no-cors fetch should reject unsafe methods before sending; got {result:?}"
    );
    Ok(())
}

#[test]
fn p3_streaming_redirect_does_not_wait_for_redirect_response_body() -> anyhow::Result<()> {
    // The shared streaming redirect loop must be able to inspect a 302 response head and follow it
    // without waiting for the discarded redirect response body. A slow or never-ending redirect
    // body is not observable to JS and must not delay redirect handling.
    let port = spawn_slow_streaming_redirect_server(Duration::from_secs(10));
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:p3-fetch-stream-slow-redirect-body;

            world p3-fetch-stream-slow-redirect-body {
              export run: async func() -> string;
            }
        "#},
        &indoc! {r#"
            export async function run() {
              const body = new ReadableStream({
                start(controller) {
                  controller.enqueue(new TextEncoder().encode('streamed-upload'));
                  controller.close();
                },
              });
              const res = await fetch('http://127.0.0.1:__PORT__/slow-redirect', {
                method: 'POST',
                body,
                duplex: 'half',
              });
              return `${res.status}:${res.redirected}:${await res.text()}`;
            }
        "#}
        .replace("__PORT__", &port.to_string()),
    )?;

    generate_p3(temp.path())?;
    let wasm_path = build_p3(temp.path(), "p3_fetch_stream_slow_redirect_body")?;

    let result = run_p3_string_export(&wasm_path, "run")?;

    assert_eq!(result, "200:true:hello-after-slow-redirect");
    Ok(())
}

#[test]
fn p3_streaming_fetch_manual_redirect_returns_opaqueredirect_filtered_response()
-> anyhow::Result<()> {
    let port = spawn_test_http_server();
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:p3-fetch-stream-manual-redirect;

            world p3-fetch-stream-manual-redirect {
              export run: async func() -> string;
            }
        "#},
        &indoc! {r#"
            export async function run() {
              const body = new ReadableStream({
                start(controller) {
                  controller.enqueue(new TextEncoder().encode('streamed-manual'));
                  controller.close();
                },
              });
              const res = await fetch('http://127.0.0.1:__PORT__/redirect-307', {
                method: 'POST',
                body,
                duplex: 'half',
                redirect: 'manual',
              });
              return `${res.status}:${res.statusText}:${res.type}:${res.headers.get('location')}:${await res.text()}`;
            }
        "#}
        .replace("__PORT__", &port.to_string()),
    )?;

    generate_p3(temp.path())?;
    let wasm_path = build_p3(temp.path(), "p3_fetch_stream_manual_redirect")?;
    let result = run_p3_string_export(&wasm_path, "run")?;

    assert_eq!(result, "0::opaqueredirect:null:");
    Ok(())
}

#[test]
fn p3_streaming_fetch_truncated_final_body_resolves_headers_then_rejects_body() -> anyhow::Result<()>
{
    let port = spawn_test_http_server();
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:p3-fetch-stream-truncated-final-body;

            world p3-fetch-stream-truncated-final-body {
              export run: async func() -> string;
            }
        "#},
        &indoc! {r#"
            export async function run() {
              const url = 'http://127.0.0.1:__PORT__/truncated';
              let bufferedResult;
              try {
                const buffered = await fetch(url, { method: 'POST', body: 'buffered' });
                bufferedResult = `resolved:${buffered.status}:${await buffered.text()}`;
              } catch (err) {
                bufferedResult = 'rejected';
              }

              const body = new ReadableStream({
                start(controller) {
                  controller.enqueue(new TextEncoder().encode('streamed'));
                  controller.close();
                },
              });
              let streamingResult;
              try {
                const streamed = await fetch(url, {
                  method: 'POST',
                  body,
                  duplex: 'half',
                });
                let bodyResult;
                try {
                  bodyResult = `body-resolved:${await streamed.text()}`;
                } catch (err) {
                  bodyResult = 'body-rejected';
                }
                streamingResult = `resolved:${streamed.status}:${bodyResult}`;
              } catch (err) {
                streamingResult = 'rejected';
              }

              return `buffered=${bufferedResult};streaming=${streamingResult}`;
            }
        "#}
        .replace("__PORT__", &port.to_string()),
    )?;

    generate_p3(temp.path())?;
    let wasm_path = build_p3(temp.path(), "p3_fetch_stream_truncated_final_body")?;
    let result = run_p3_string_export(&wasm_path, "run")?;

    assert_eq!(
        result,
        "buffered=rejected;streaming=resolved:200:body-rejected"
    );
    Ok(())
}

#[test]
fn p3_generated_crate_builds_with_nested_future_in_export_record() -> anyhow::Result<()> {
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:nested-future;

            interface types {
              record wrap { f: future<u32> }
            }

            world nested-future {
              use types.{wrap};
              export run: async func() -> wrap;
            }
        "#},
        "export async function run() { return { f: Promise.resolve(1) }; }\n",
    )?;

    generate_p3(temp.path())?;
    build_p3(temp.path(), "nested_future")?;
    Ok(())
}

#[test]
fn p3_generated_crate_builds_with_nested_stream_in_export_list() -> anyhow::Result<()> {
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:nested-stream;

            world nested-stream {
              export run: async func() -> list<stream<u8>>;
            }
        "#},
        "export async function run() { return []; }\n",
    )?;

    generate_p3(temp.path())?;
    build_p3(temp.path(), "nested_stream")?;
    Ok(())
}

#[test]
fn p3_rejects_async_value_results_from_sync_exports() -> anyhow::Result<()> {
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:sync-stream;

            world sync-stream {
              export run: func() -> stream<u8>;
            }
        "#},
        "export function run() { return (async function* () {})(); }\n",
    )?;

    let err = generate_p3(temp.path())
        .expect_err("a sync export must not return an async value directly or recursively");
    assert!(
        format!("{err:#}").contains("require an `async func`"),
        "unexpected error: {err:#}"
    );
    Ok(())
}

#[test]
fn p3_rejects_async_values_in_export_result_errors() -> anyhow::Result<()> {
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:async-error-stream;

            world async-error-stream {
              export run: async func() -> result<u32, stream<u8>>;
            }
        "#},
        "export async function run() { return 1; }\n",
    )?;

    let err = generate_p3(temp.path())
        .expect_err("an export result error must not contain an async value");
    assert!(
        format!("{err:#}").contains("error arm of an exported function result"),
        "unexpected error: {err:#}"
    );
    Ok(())
}

#[test]
fn p3_generated_crate_builds_with_nested_async_import_values() -> anyhow::Result<()> {
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:nested-async-imports;

            interface host {
              type byte-stream = stream<u8>;
              record request { data: byte-stream }

              resource transfer {
                send: func(data: byte-stream) -> future<result<_, string>>;
                send-request: async func(request: request) -> result<_, string>;
                receive: func() -> result<byte-stream, string>;
              }
            }

            world nested-async-imports {
              import host;
              export run: async func() -> string;
            }
        "#},
        "export async function run() { return 'ok'; }\n",
    )?;

    generate_p3(temp.path())?;
    build_p3(temp.path(), "nested_async_imports")?;
    Ok(())
}

#[test]
fn p3_dts_maps_nested_async_import_values() -> anyhow::Result<()> {
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:dts-nested-async-imports;

            interface host {
              type byte-stream = stream<u8>;
              record request { data: byte-stream }

              resource transfer {
                send: func(data: byte-stream) -> future<result<_, string>>;
                send-request: async func(request: request) -> result<_, string>;
                receive: func() -> result<byte-stream, string>;
              }
            }

            world dts-nested-async-imports {
              import host;
            }
        "#},
        "",
    )?;

    let generated = generate_p3_dts(&temp.path().join("wit"), &temp.path().join("dts"))?;
    let host_path = generated
        .iter()
        .find(|path| path.file_name().is_some_and(|name| name.contains("host")))
        .expect("host import interface .d.ts should be generated");
    let host = std::fs::read_to_string(host_path)?;

    for expected in [
        "data: AsyncIterable<number>",
        "send(data: AsyncIterable<number>): Promise<Result<void, string>>;",
        "sendRequest(request: Request): Promise<void>;",
        "receive(): AsyncIterable<number>;",
    ] {
        assert!(
            host.contains(expected),
            "missing `{expected}` in generated declarations:\n{host}"
        );
    }
    Ok(())
}

#[test]
fn p3_dts_maps_nested_future_in_export_record() -> anyhow::Result<()> {
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:dts-nested-future;

            world dts-nested-future {
              record wrap { f: future<u32> }
              export run: async func() -> wrap;
            }
        "#},
        "export function run() { return { f: Promise.resolve(1) }; }\n",
    )?;

    let generated = generate_p3_dts(&temp.path().join("wit"), &temp.path().join("dts"))?;
    let exports_path = generated
        .iter()
        .find(|path| path.file_name() == Some("exports.d.ts"))
        .expect("exports.d.ts should be generated");
    let exports = std::fs::read_to_string(exports_path)?;
    assert!(
        exports.contains("f: Promise<number>;"),
        "nested future should map to Promise<number>; generated:\n{exports}"
    );
    Ok(())
}

#[test]
fn p3_dts_maps_nested_future_alias_in_export_record() -> anyhow::Result<()> {
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:dts-nested-future-alias;

            world dts-nested-future-alias {
              type aliased-future = future<u32>;
              record wrap { f: aliased-future }
              export run: async func() -> wrap;
            }
        "#},
        "export function run() { return { f: Promise.resolve(1) }; }\n",
    )?;

    let generated = generate_p3_dts(&temp.path().join("wit"), &temp.path().join("dts"))?;
    let exports_path = generated
        .iter()
        .find(|path| path.file_name() == Some("exports.d.ts"))
        .expect("exports.d.ts should be generated");
    let exports = std::fs::read_to_string(exports_path)?;
    assert!(
        exports.contains("f: Promise<number>;"),
        "nested aliased future should map to Promise<number>; generated:\n{exports}"
    );
    Ok(())
}

#[test]
fn p3_dts_maps_direct_future_and_stream_boundaries() -> anyhow::Result<()> {
    // A `future<T>` / `stream<T>` used directly as a function parameter or return type must be
    // reflected in the generated `.d.ts` as `Promise<T>` / `AsyncIterable<T>`. This is checked for
    // all four boundaries — export param/return and import param/return.
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:dts-async-values;

            interface host {
              make-future: func(x: u32) -> future<u32>;
              consume-stream: func(s: stream<u8>) -> u32;
            }

            world dts-async-values {
              import host;
              export run-future: async func() -> future<u32>;
              export take-stream: async func(s: stream<u8>) -> u32;
            }
        "#},
        "export function runFuture() { return Promise.resolve(1); }\n\
         export function takeStream() { return 0; }\n",
    )?;

    let generated = generate_p3_dts(&temp.path().join("wit"), &temp.path().join("dts"))?;
    let mut combined = String::new();
    for path in &generated {
        combined.push_str(&std::fs::read_to_string(path)?);
        combined.push('\n');
    }

    // export return `future<u32>` and import return `future<u32>` -> `Promise<number>`
    assert!(
        combined.contains("Promise<number>"),
        "expected a direct future<u32> boundary to map to Promise<number>; generated:\n{combined}"
    );
    // export param `stream<u8>` and import param `stream<u8>` -> `AsyncIterable<number>`
    assert!(
        combined.contains("AsyncIterable<number>"),
        "expected a direct stream<u8> boundary to map to AsyncIterable<number>; \
         generated:\n{combined}"
    );
    Ok(())
}

#[test]
fn p3_dts_exported_future_return_is_not_double_wrapped() -> anyhow::Result<()> {
    // Exported JS functions are already declared as Promise-returning by the DTS writer. A direct
    // component `future<T>` export return is implemented by returning a `T`/`Promise<T>` payload
    // from JS, so the declaration must expose `Promise<T>`, not `Promise<Promise<T>>`.
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:dts-export-future-return;

            world dts-export-future-return {
              export run-future: async func() -> future<u32>;
            }
        "#},
        "export function runFuture() { return Promise.resolve(1); }\n",
    )?;

    let generated = generate_p3_dts(&temp.path().join("wit"), &temp.path().join("dts"))?;
    let exports_path = generated
        .iter()
        .find(|path| path.file_name() == Some("exports.d.ts"))
        .expect("exports.d.ts should be generated");
    let exports = std::fs::read_to_string(exports_path)?;

    assert!(
        exports.contains("export function runFuture(): Promise<number>;"),
        "expected exported future<T> return to be declared as Promise<T>; generated:\n{exports}"
    );
    Ok(())
}

#[test]
fn p3_dts_maps_direct_future_and_stream_alias_boundaries() -> anyhow::Result<()> {
    // Direct function-boundary async values remain direct even when named through a WIT alias.
    // DTS generation should follow those aliases and emit Promise<T> / AsyncIterable<T> at the
    // function boundary rather than treating the alias declaration as a forbidden nested use.
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:dts-async-value-aliases;

            interface host {
              type aliased-future = future<u32>;
              type aliased-stream = stream<u8>;

              make-future: func() -> aliased-future;
              consume-stream: func(s: aliased-stream) -> u32;
            }

            world dts-async-value-aliases {
              import host;

              type exported-future = future<u32>;
              type exported-stream = stream<u8>;

              export run-future: async func() -> exported-future;
              export take-stream: async func(s: exported-stream) -> u32;
            }
        "#},
        "export function runFuture() { return Promise.resolve(1); }\n\
         export function takeStream() { return 0; }\n",
    )?;

    let generated = generate_p3_dts(&temp.path().join("wit"), &temp.path().join("dts"))?;
    let mut combined = String::new();
    for path in &generated {
        combined.push_str(&std::fs::read_to_string(path)?);
        combined.push('\n');
    }

    assert!(
        combined.contains("Promise<number>"),
        "expected a direct future<u32> alias boundary to map to Promise<number>; \
         generated:\n{combined}"
    );
    assert!(
        combined.contains("AsyncIterable<number>"),
        "expected a direct stream<u8> alias boundary to map to AsyncIterable<number>; \
         generated:\n{combined}"
    );
    Ok(())
}

#[test]
fn p3_dts_emits_payload_type_definitions_for_async_value_boundaries() -> anyhow::Result<()> {
    // Named payload types used only inside direct `future<T>` / `stream<T>` function boundaries are
    // still part of the public TypeScript surface. The generated declarations must define them;
    // otherwise the boundary signatures reference undeclared `Rec` / `Result` types.
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:dts-async-payload-types;

            interface host {
              record rec { n: u32 }

              make-result: func() -> future<result<u32, string>>;
              take-result: func(s: stream<result<u32, string>>);

              resource thing {
                get-result: func() -> future<result<u32, string>>;
              }
            }

            world dts-async-payload-types {
              import host;

              record rec { n: u32 }

              export run-future: async func() -> future<rec>;
              export take-stream: async func(s: stream<rec>);
              export run-result: async func() -> future<result<u32, string>>;
              export take-result: async func(s: stream<result<u32, string>>);
            }
        "#},
        "export function runFuture() { return Promise.resolve({ n: 1 }); }\n\
         export function takeStream() {}\n\
         export function runResult() { return Promise.resolve({ tag: 'ok', val: 1 }); }\n\
         export function takeResult() {}\n",
    )?;

    let generated = generate_p3_dts(&temp.path().join("wit"), &temp.path().join("dts"))?;
    let exports_path = generated
        .iter()
        .find(|path| path.file_name() == Some("exports.d.ts"))
        .expect("exports.d.ts should be generated");
    let exports = std::fs::read_to_string(exports_path)?;
    let host_path = generated
        .iter()
        .find(|path| path.file_name() != Some("exports.d.ts"))
        .expect("import interface .d.ts should be generated");
    let host = std::fs::read_to_string(host_path)?;

    let expected = [
        (
            "future<rec> return boundary signature",
            "export function runFuture(): Promise<Rec>;",
        ),
        (
            "stream<rec> parameter boundary signature",
            "export function takeStream(s: AsyncIterable<Rec>): Promise<void>;",
        ),
        (
            "future<result<_, _>> return boundary signature",
            "export function runResult(): Promise<Result<number, string>>;",
        ),
        (
            "stream<result<_, _>> parameter boundary signature",
            "export function takeResult(s: AsyncIterable<Result<number, string>>): Promise<void>;",
        ),
        (
            "named async-value payload type declaration",
            "export type Rec =",
        ),
        (
            "async-value result payload helper",
            "export type Result<T, E> =",
        ),
    ];
    let missing = expected
        .iter()
        .filter_map(|(description, needle)| (!exports.contains(needle)).then_some(*description))
        .collect::<Vec<_>>();
    assert!(
        missing.is_empty(),
        "missing expected DTS entries for {}; generated:\n{exports}",
        missing.join(", ")
    );
    assert!(
        host.contains("export type Result<T, E> ="),
        "expected the Result helper for result payloads used by import functions/resource methods; \
         generated:\n{host}"
    );
    Ok(())
}

#[test]
fn p3_dts_accepts_async_func_async_value_boundaries() -> anyhow::Result<()> {
    // The Preview 3 generation path supports `async func` exports/imports, and `future<T>` /
    // `stream<T>` are supported as direct async-value function boundaries. DTS generation should
    // therefore be able to describe the same valid P3 surface instead of accepting only the sync
    // `func() -> future<T>` spelling used by some host-side helpers.
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:dts-async-func-async-values;

            interface host {
              make-future: async func() -> future<u32>;
              consume-stream: async func(s: stream<u8>);
            }

            world dts-async-func-async-values {
              import host;

              export run-future: async func() -> future<u32>;
              export take-stream: async func(s: stream<u8>);
            }
        "#},
        "export async function runFuture() { return 1; }\n\
         export async function takeStream() {}\n",
    )?;

    let generated = generate_p3_dts(&temp.path().join("wit"), &temp.path().join("dts"))?;
    let exports_path = generated
        .iter()
        .find(|path| path.file_name() == Some("exports.d.ts"))
        .expect("exports.d.ts should be generated");
    let exports = std::fs::read_to_string(exports_path)?;

    assert!(
        exports.contains("export function runFuture(): Promise<number>;"),
        "expected exported async future<T> return to be declared as Promise<T>; generated:\n{exports}"
    );
    assert!(
        exports.contains("export function takeStream(s: AsyncIterable<number>): Promise<void>;"),
        "expected exported async stream<T> parameter to be declared as AsyncIterable<T>; generated:\n{exports}"
    );
    Ok(())
}

#[test]
fn p3_dts_generates_async_resource_methods() -> anyhow::Result<()> {
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:dts-async-resource;

            interface host {
              resource pending-value {
                get: async func() -> u32;
                %get-default: static async func() -> u32;
              }
            }

            world dts-async-resource {
              import host;
            }
        "#},
        "",
    )?;

    let generated = generate_p3_dts(&temp.path().join("wit"), &temp.path().join("dts"))?;
    let host_path = generated
        .iter()
        .find(|path| path.file_name().is_some_and(|name| name.contains("host")))
        .expect("host import interface .d.ts should be generated");
    let host = std::fs::read_to_string(host_path)?;

    assert!(
        host.contains("get(): Promise<number>;"),
        "expected an async resource method to return a Promise; generated:\n{host}"
    );
    assert!(
        host.contains("static getDefault(): Promise<number>;"),
        "expected an async static resource method to return a Promise; generated:\n{host}"
    );
    Ok(())
}

#[test]
fn p3_dts_preserves_sync_and_async_export_kinds() -> anyhow::Result<()> {
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:dts-p3-export-kinds;

            world dts-p3-export-kinds {
              export sync-value: func() -> string;
              export async-value: async func() -> string;
            }
        "#},
        "",
    )?;

    let generated = generate_dts_with_target(
        &temp.path().join("wit"),
        &temp.path().join("dts"),
        None,
        GenerationTarget::WasiP3,
    )?;
    let exports_path = generated
        .iter()
        .find(|path| path.file_name() == Some("exports.d.ts"))
        .expect("exports.d.ts should be generated");
    let exports = std::fs::read_to_string(exports_path)?;

    assert!(
        exports.contains("export function syncValue(): string;"),
        "expected a P3 synchronous export to have a synchronous declaration; generated:\n{exports}"
    );
    assert!(
        exports.contains("export function asyncValue(): Promise<string>;"),
        "expected a P3 async export to return a Promise; generated:\n{exports}"
    );
    Ok(())
}

#[test]
fn p3_dts_collects_dependencies_through_imported_async_value_aliases() -> anyhow::Result<()> {
    // An async function boundary remains direct when the boundary type is a world-local `use`
    // alias of an imported interface's alias-to-future. The generated signature references the
    // imported payload type and Result helper, so dependency collection must not stop at the
    // async alias.
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package bug:dts-imported-async-alias;

            interface host {
              record rec { n: u32 }
              type fut-rec = future<rec>;
              type fut-result = future<result<u32, string>>;
            }

            world dts-imported-async-alias {
              import host;
              use host.{fut-rec, fut-result};

              export get-rec: async func() -> fut-rec;
              export get-result: async func() -> fut-result;
            }
        "#},
        "export function getRec() { return Promise.resolve({ n: 1 }); }\n\
         export function getResult() { return Promise.resolve({ tag: 'ok', val: 1 }); }\n",
    )?;

    let generated = generate_p3_dts(&temp.path().join("wit"), &temp.path().join("dts"))?;
    let exports_path = generated
        .iter()
        .find(|path| path.file_name() == Some("exports.d.ts"))
        .expect("exports.d.ts should be generated");
    let exports = std::fs::read_to_string(exports_path)?;

    assert!(
        exports.contains(
            "import * as bugDtsImportedAsyncAliasHost from 'bug:dts-imported-async-alias/host';"
        ),
        "expected an import for the host namespace referenced by the async-value payload; \
         generated:\n{exports}"
    );
    assert!(
        exports.contains("export function getRec(): Promise<bugDtsImportedAsyncAliasHost.Rec>;"),
        "expected imported record payload type to be qualified in the future<T> boundary; \
         generated:\n{exports}"
    );
    assert!(
        exports.contains("export function getResult(): Promise<Result<number, string>>;"),
        "expected imported async alias with result payload to use the Result helper; \
         generated:\n{exports}"
    );
    assert!(
        exports.contains("export type Result<T, E> ="),
        "expected Result helper to be emitted for result payload behind imported async alias; \
         generated:\n{exports}"
    );
    Ok(())
}

#[test]
fn p3_dts_generates_for_async_values_examples() -> anyhow::Result<()> {
    // End-to-end ground truth for Phase 3 part 2: the committed async-value examples use real P3
    // `async func` boundaries. DTS generation must succeed on them and produce the settled
    // `Promise<T>` / `AsyncIterable<T>` mappings (this is the surface a real user would consume).
    let out = Utf8TempDir::new()?;

    // Export-side example: future/stream at both export return and export parameter positions.
    let export_dts = out.path().join("export");
    generate_p3_dts(Utf8Path::new("examples/p3/async-values/wit"), &export_dts)?;
    let exports = std::fs::read_to_string(export_dts.join("exports.d.ts"))?;
    for needle in [
        "export function runFuture(): Promise<number>;",
        "export function runStream(): Promise<AsyncIterable<number>>;",
        "export function takeFuture(f: Promise<number>): Promise<number>;",
        "export function takeStream(s: AsyncIterable<number>): Promise<number>;",
    ] {
        assert!(
            exports.contains(needle),
            "missing `{needle}` in generated exports.d.ts:\n{exports}"
        );
    }

    // Import-side example: future/stream at both import return and import parameter positions,
    // across sync `func` and `async func` imports.
    let import_dts = out.path().join("import");
    let generated = generate_p3_dts(
        Utf8Path::new("examples/p3/async-values-import/wit"),
        &import_dts,
    )?;
    let host_path = generated
        .iter()
        .find(|path| path.file_name().is_some_and(|name| name.contains("host")))
        .expect("host import interface .d.ts should be generated");
    let host = std::fs::read_to_string(host_path)?;
    for needle in [
        // sync `func` import returning future/stream: no outer Promise wrapper
        "export function makeFuture(x: number): Promise<number>;",
        "export function makeStream(n: number): AsyncIterable<number>;",
        // `async func` import: Promise-wrapped return, future param stays Promise<T>
        "export function consumeFuture(f: Promise<number>): Promise<number>;",
        "export function consumeStream(s: AsyncIterable<number>): Promise<number>;",
        "export function storeFuture(f: Promise<number>): Promise<void>;",
        "export function readStoredFuture(): Promise<number>;",
    ] {
        assert!(
            host.contains(needle),
            "missing `{needle}` in generated host.d.ts:\n{host}"
        );
    }
    Ok(())
}

#[test]
fn p3_javascript_imports_a_native_module_from_a_dependency() -> anyhow::Result<()> {
    let temp = Utf8TempDir::new()?;
    write_fixture(
        temp.path(),
        indoc! {r#"
            package test:p3-native-module;

            world p3-native-module {
              export run: func() -> string;
            }
        "#},
        indoc! {r#"
            import { greet } from 'test-native-greeting';
            // A native module named like a schemeless builtin alias takes precedence.
            import { greet as viaAlias } from 'fs';
            export function run() { return `${greet('ok')},${viaAlias('fs')}`; }
        "#},
    )?;
    let native = temp.path().join("native");
    std::fs::create_dir_all(native.join("src"))?;
    std::fs::write(
        native.join("Cargo.toml"),
        indoc! {r#"
            [package]
            name = "test-native-greeting"
            version = "0.0.0"
            edition = "2024"

            [dependencies]
            rquickjs = { version = "0.14.0", default-features = false, features = ["std"] }
        "#},
    )?;
    std::fs::write(
        native.join("src").join("lib.rs"),
        indoc! {r#"
            use rquickjs::module::{Declarations, Exports, ModuleDef};
            use rquickjs::{Ctx, Function};

            pub struct Greeting;

            impl ModuleDef for Greeting {
                fn declare(decl: &Declarations) -> rquickjs::Result<()> {
                    decl.declare("greet")?;
                    Ok(())
                }

                fn evaluate<'js>(ctx: &Ctx<'js>, exports: &Exports<'js>) -> rquickjs::Result<()> {
                    let greet = Function::new(ctx.clone(), |name: String| format!("native:{name}"))?;
                    exports.export("greet", greet)?;
                    Ok(())
                }
            }
        "#},
    )?;

    generate_wrapper_crate_with_options(
        &temp.path().join("wit"),
        &[JsModuleSpec {
            name: "module".to_string(),
            mode: EmbeddingMode::EmbedFile(temp.path().join("src").join("module.js")),
        }],
        &temp.path().join("out"),
        None,
        GenerationTarget::WasiP3,
        &WrapperCrateOptions {
            native_modules: vec![
                NativeModuleSpec {
                    name: "test-native-greeting".to_string(),
                    module_def: "test_native_greeting::Greeting".to_string(),
                },
                NativeModuleSpec {
                    name: "fs".to_string(),
                    module_def: "test_native_greeting::Greeting".to_string(),
                },
            ],
            dependencies: vec![DependencySpec {
                key: "test-native-greeting".to_string(),
                value: format!("{{ path = {:?} }}", native.as_str()),
            }],
        },
    )?;

    let cargo_toml = std::fs::read_to_string(temp.path().join("out").join("Cargo.toml"))?;
    assert!(
        cargo_toml.contains(r#"test-native-greeting = { path = "../native" }"#),
        "the dependency path is relative to the generated crate:\n{cargo_toml}"
    );
    assert!(
        !temp.path().join("out").join("Cargo.lock").exists(),
        "custom dependencies change the dependency graph, so the skeleton lock is not copied"
    );

    let wasm_path = build_p3(temp.path(), "p3_native_module")?;
    assert_eq!(
        run_p3_string_export(&wasm_path, "run")?,
        "native:ok,native:fs"
    );
    Ok(())
}