js-component-bindgen 2.18.0

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

use std::fmt::Write;

use crate::intrinsics::component::ComponentIntrinsic;
use crate::intrinsics::conversion::ConversionIntrinsic;
use crate::intrinsics::p3::async_future::AsyncFutureIntrinsic;
use crate::intrinsics::p3::waitable::WaitableIntrinsic;
use crate::intrinsics::resource::ResourceIntrinsic;
use crate::intrinsics::{Intrinsic, RenderIntrinsicsArgs};
use crate::source::Source;
use crate::uwriteln;

/// This enum contains intrinsics that implement async tasks
#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
pub enum AsyncTaskIntrinsic {
    /// Set the value of a context local storage for the current task/thread
    ///
    /// # Intrinsic implementation function
    ///
    /// The function that implements this intrinsic has the following definition:
    ///
    /// ```ts
    /// type i32 = number;
    /// type SlotIndex = 0 | 1;
    /// function contextSet(slot: SlotIndex, value: number);
    /// ```
    ///
    ContextSet,

    /// Gets the value stored in context local storage for the current task/thread
    ///
    /// Guest code uses this to reference internally stored context local storage,
    /// whether that is task local or thread local.
    ///
    /// # Intrinsic implementation function
    ///
    /// The function that implements this intrinsic has the following definition:
    ///
    /// ```ts
    /// type i32 = number;
    /// type SlotIndex = 0 | 1;
    /// function contextGet(slot: SlotIndex): i32;
    /// ```
    ///
    ContextGet,

    /// Return a value to a caller of an lifted export.
    ///
    /// Consider the following scenario:
    ///   - Some component A is created with a async lifted export
    ///   - A caller of component A (Host/other component) calls the lifted export
    ///   - During component A's execution, component A triggers `task.return` with a (possibly partial) result of computation
    ///   - While processing the `task.return` intrinsic:
    ///     - The host lifts the return values from the partial computation
    ///     - The host pauses execution (if necessary) of component A
    ///     - The host delivers return values to possibly waiting tasks
    ///     - The host continues executing the appropriate next task
    ///
    /// Note that it *is* possible for the lifted export to be sync.
    ///
    /// # Intrinsic implementation function
    ///
    /// The function that implements this intrinsic has the following definition:
    ///
    /// ```ts
    /// type u32 = number;
    /// type usize = bigint;
    /// type ComponentIdx = number;
    /// type TypeIdx = number;
    /// type ValueWithTypeIdx = (ComponentIdx, TypeIdx, any);
    /// type LiftFn = function(ptr: u32, totalLen: usize): ValueWithTypeIndex[];
    ///
    /// function taskReturn(taskId: number, resultLiftFns: LiftFn[], storagePtr: u32, storageLen: usize);
    /// ```
    ///
    TaskReturn,

    /// Remove the subtask (waitable) at the given index, for a given component
    ///
    /// # Intrinsic implementation function
    ///
    /// The function that implements this intrinsic has the following definition:
    ///
    /// ```ts
    /// type i32 = number;
    /// function subtaskDrop(componentIdx: number, taskId: i32);
    /// ```
    ///
    SubtaskDrop,

    /// Suspend the current thread while leaving it ready for another scheduler turn.
    ThreadYield,
    /// Suspend the current thread until an operation explicitly makes it ready.
    ThreadSuspend,
    /// Resume a suspended target and suspend the current thread until it is resumed.
    ThreadSuspendThenResume,
    /// Resume a ready target if possible, leaving the current thread suspended; otherwise suspend normally.
    ThreadSuspendThenPromote,
    /// Resume a suspended target while yielding the current thread.
    ThreadYieldThenResume,
    /// Resume a ready target if possible, leaving the current thread ready; otherwise yield normally.
    ThreadYieldThenPromote,

    /// Return the component-instance-scoped index of the current thread.
    ThreadIndex,
    /// Create a suspended thread whose start function is selected from a table.
    ThreadNewIndirect,
    /// Make a suspended thread ready to run, starting it if it has not run before.
    ThreadResumeLater,

    /// Cancel the current async subtask for a given component instance
    ///
    /// # Intrinsic implementation function
    ///
    /// The function that implements this intrinsic has the following definition:
    ///
    /// ```ts
    /// type i32 = number;
    /// function subtaskCancel(componentIdx: number, isAsync: boolean);
    /// ```
    SubtaskCancel,

    /// Cancel the current task
    ///
    /// # Intrinsic implementation function
    ///
    /// The function that implements this intrinsic has the following definition:
    ///
    /// ```ts
    /// type i32 = number;
    /// function taskCancel(componentIdx: i32);
    /// ```
    TaskCancel,

    /// Function that retrieves the current global async current task
    GetCurrentTask,

    /// Function that retrieves the current global async current thread
    GetCurrentThread,

    /// Function that resolves the thread named by a component instance's ambient
    /// thread-meta register, throwing if there is none (shared `thread.*` prologue)
    CurrentThreadOrThrow,

    /// Function that creates a new implicit thread, and marks it as the current executing thread
    CreateNewCurrentImplicitThread,

    /// Function that stops the current thread
    ClearCurrentThread,

    /// Global that stores the current task for a given invocation.
    ///
    /// This global variable is populated *only* when we are performing a call
    /// that was triggered by an async lifted export.
    ///
    /// You can consider the type of the global variable to be:
    ///
    /// ```ts
    /// type Task = {
    ///     componentIdx: number,
    ///     storage: [number]
    ///     returnCalls: number,
    ///     requested: boolean,
    ///     borrowedHandles: Record<number, boolean>,
    ///     cancelled: boolean,
    /// }
    ///
    /// type GlobalAsyncCurrentTaskMap = Map<number, Task>;
    /// ```
    GlobalAsyncCurrentTaskMap,

    /// Global that stores the current task ID
    ///
    /// This global variable is populated when a task is started, and cleared
    /// (reset to `null` in JS) when a task ends.
    ///
    /// This global is used only when *necessary* -- for canonical builtins that
    /// do not include/cannot access the current task any other way, often because
    /// they have no access to the current component instance index (e.g. `context.get`).
    ///
    /// ```ts
    /// type GlobalAsyncCurrentTaskIds = number[];
    /// ```
    GlobalAsyncCurrentTaskIds,

    /// Global that stores the current component ID (for the current task)
    ///
    /// This global variable is populated when a task is started, and cleared
    /// (reset to `null` in JS) when a task ends.
    ///
    /// ```ts
    /// type GlobalAsyncCurrentTaskIds = number[];
    /// ```
    GlobalAsyncCurrentComponentIdxs,

    /// The definition of the `AsyncTask` JS class
    AsyncTaskClass,

    /// The definition of the `AsyncThread` JS class
    AsyncThreadClass,

    /// The constant that represents that a async task is blocked
    AsyncBlockedConstant,

    /// The definition of the `AsyncSubtask` JS class
    AsyncSubtaskClass,

    /// A utility function used for unpacking results to callbck that mostly contain
    /// a callback code and possibly a waitable set index to be watied on or polled
    ///
    /// # Intrinsic implementation function
    ///
    /// The function that implements this intrinsic has the following definition:
    ///
    /// ```ts
    /// type i32 = number;
    /// function unpackCallbackResult(callbackResult: i32): [i32, i32];
    /// ```
    UnpackCallbackResult,

    /// JS that contains the loop which drives a given async task to completion.
    ///
    /// This intrinsic is not a canon function but instead a reusable JS snippet
    /// that controls
    ///
    /// The Canonical ABI pseudo-code equivalent is `thread_func(thread)` in `canon_lift`.
    ///
    /// Normally, the async driver loop returns a Promise that resolves to the result
    /// of the original async function that was called.
    ///
    /// See `Instruction::CallWasm` for example usage.
    ///
    /// ```ts
    /// interface DriverLoopArgs {
    ///     componentState: ComponentAsyncState,
    ///     task: AsyncTask,
    ///     fnName: string,
    ///     callbackFnName: string,
    ///     isAsync: boolean, // whether using JSPI *or* lifted async function
    ///     callbackResult: number, // initial wasm call result that contains callback code and more metadata
    ///     // Normally, the driver loop is run in a separately executing Promise,
    ///     // so we ensure that the enclosing promise itself can eventually be resolved
    ///     resolve: () => void,
    ///     reject: () => void,
    /// }
    ///
    /// function asyncDriverLoop(args: DriverLoopArgs): Promise<any>;
    /// ```
    DriverLoop,

    /// Intrinsic used when components lower imports to be used
    /// from other components or the host.
    ///
    /// # Component Intrinsic implementation function
    ///
    /// The function that implements this intrinsic has the following definition:
    ///
    /// ```ts
    /// ```
    ///
    LowerImport,

    /// Version of lower import written explicitly for backwards compatibility
    ///
    /// TODO(breaking): remove this when specifying async imports/exports is removed.
    LowerImportBackwardsCompat,

    /// Global variable that represents whether the *current* task my block
    /// see `CoreDef::TaskMayBlock`
    CurrentTaskMayBlock,

    /// Global counter tracking how many blocking (synchronous, non-async) callee
    /// slices are currently executing on the JS stack. While it is non-zero, an
    /// async subtask started by the running callee originates from a blocking
    /// function and must enter synchronously (the caller cannot yield to observe
    /// or cancel it before it runs).
    AsyncBlockingCallDepth,

    /// Called before entering sync-to-sync guest-to-guest call
    EnterSymmetricSyncGuestCall,

    /// Called when exiting a sync-to-sync guest-to-guest call
    ExitSymmetricSyncGuestCall,

    /// Component index that is saved across sync-to-sync guest calls
    SymmetricSyncGuestCallStack,
}

impl AsyncTaskIntrinsic {
    /// Retrieve global names for this intrinsic
    pub fn get_global_names() -> impl IntoIterator<Item = &'static str> {
        [
            Self::CurrentTaskMayBlock.name(),
            Self::AsyncBlockingCallDepth.name(),
            Self::AsyncBlockedConstant.name(),
            Self::AsyncSubtaskClass.name(),
            Self::AsyncTaskClass.name(),
            Self::AsyncThreadClass.name(),
            Self::ContextGet.name(),
            Self::ContextSet.name(),
            Self::GetCurrentTask.name(),
            Self::GetCurrentThread.name(),
            Self::CurrentThreadOrThrow.name(),
            Self::CreateNewCurrentImplicitThread.name(),
            Self::ClearCurrentThread.name(),
            Self::GlobalAsyncCurrentTaskMap.name(),
            Self::GlobalAsyncCurrentTaskIds.name(),
            Self::GlobalAsyncCurrentComponentIdxs.name(),
            Self::SubtaskCancel.name(),
            Self::SubtaskDrop.name(),
            Self::TaskCancel.name(),
            Self::TaskReturn.name(),
            Self::ThreadYield.name(),
            Self::ThreadSuspend.name(),
            Self::ThreadSuspendThenResume.name(),
            Self::ThreadSuspendThenPromote.name(),
            Self::ThreadYieldThenResume.name(),
            Self::ThreadYieldThenPromote.name(),
            Self::ThreadIndex.name(),
            Self::ThreadNewIndirect.name(),
            Self::ThreadResumeLater.name(),
            Self::UnpackCallbackResult.name(),
            Self::DriverLoop.name(),
            Self::LowerImport.name(),
            Self::LowerImportBackwardsCompat.name(),
            Self::EnterSymmetricSyncGuestCall.name(),
            Self::ExitSymmetricSyncGuestCall.name(),
            Self::SymmetricSyncGuestCallStack.name(),
        ]
    }

    /// Get the name for the intrinsic
    pub fn name(&self) -> &'static str {
        match self {
            Self::CurrentTaskMayBlock => "CURRENT_TASK_MAY_BLOCK",
            Self::AsyncBlockingCallDepth => "ASYNC_BLOCKING_CALL_DEPTH",
            Self::AsyncBlockedConstant => "ASYNC_BLOCKED_CODE",
            Self::AsyncSubtaskClass => "AsyncSubtask",
            Self::AsyncTaskClass => "AsyncTask",
            Self::AsyncThreadClass => "AsyncThread",
            Self::ContextGet => "contextGet",
            Self::ContextSet => "contextSet",
            Self::GetCurrentTask => "getCurrentTask",
            Self::GetCurrentThread => "getCurrentThread",
            Self::CurrentThreadOrThrow => "currentThreadOrThrow",
            Self::CreateNewCurrentImplicitThread => "createNewCurrentImplicitThread",
            Self::ClearCurrentThread => "clearCurrentThread",
            Self::GlobalAsyncCurrentTaskMap => "ASYNC_TASKS_BY_COMPONENT_IDX",
            Self::GlobalAsyncCurrentTaskIds => "ASYNC_CURRENT_TASK_IDS",
            Self::GlobalAsyncCurrentComponentIdxs => "ASYNC_CURRENT_COMPONENT_IDXS",
            Self::SubtaskCancel => "subtaskCancel",
            Self::SubtaskDrop => "subtaskDrop",
            Self::TaskCancel => "taskCancel",
            Self::TaskReturn => "taskReturn",
            Self::ThreadYield => "asyncYield",
            Self::ThreadSuspend => "threadSuspend",
            Self::ThreadSuspendThenResume => "threadSuspendThenResume",
            Self::ThreadSuspendThenPromote => "threadSuspendThenPromote",
            Self::ThreadYieldThenResume => "threadYieldThenResume",
            Self::ThreadYieldThenPromote => "threadYieldThenPromote",
            Self::ThreadIndex => "threadIndex",
            Self::ThreadNewIndirect => "threadNewIndirect",
            Self::ThreadResumeLater => "threadResumeLater",
            Self::UnpackCallbackResult => "unpackCallbackResult",
            Self::DriverLoop => "_driverLoop",
            Self::LowerImport => "_lowerImport",
            Self::LowerImportBackwardsCompat => "_lowerImportBackwardsCompat",
            Self::EnterSymmetricSyncGuestCall => "_symmetricSyncGuestCallEnter",
            Self::ExitSymmetricSyncGuestCall => "_symmetricSyncGuestCallExit",
            Self::SymmetricSyncGuestCallStack => "SYMMETRIC_SYNC_GUEST_CALL_STACK",
        }
    }

    /// Render an intrinsic to a string
    pub fn render(&self, output: &mut Source, render_args: &RenderIntrinsicsArgs<'_>) {
        match self {
            Self::CurrentTaskMayBlock => {
                let var_name = self.name();
                uwriteln!(
                    output,
                    r#"
                      const {var_name} = typeof WebAssembly !== 'undefined' ? new WebAssembly.Global({{ value: 'i32', mutable: true }}, 0) : false;
                    "#
                );
            }

            Self::AsyncBlockingCallDepth => {
                let var_name = self.name();
                uwriteln!(
                    output,
                    r#"
                      const {var_name} = typeof WebAssembly !== 'undefined' ? new WebAssembly.Global({{ value: 'i32', mutable: true }}, 0) : {{ value: 0 }};
                    "#
                );
            }

            Self::GlobalAsyncCurrentTaskMap => {
                let var_name = render_args.require_intrinsic(Self::GlobalAsyncCurrentTaskMap);
                output.push_str(&format!("const {var_name} = new Map();\n"));
            }

            Self::GlobalAsyncCurrentTaskIds => {
                output.push_str(&format!("const {var_name} = [];\n", var_name = self.name(),));
            }

            Self::GlobalAsyncCurrentComponentIdxs => {
                output.push_str(&format!("const {var_name} = [];\n", var_name = self.name(),));
            }

            Self::AsyncBlockedConstant => {
                let name = render_args.require_intrinsic(Self::AsyncBlockedConstant);
                output.push_str(&format!("const {name} = 0xFFFF_FFFF;"));
            }

            Self::ContextSet => {
                let debug_log_fn = render_args.require_intrinsic(Intrinsic::DebugLog);
                let context_set_fn = render_args.require_intrinsic(Self::ContextSet);
                let current_thread_get_fn = render_args.require_intrinsic(Self::GetCurrentThread);
                let type_check_i32 = render_args.require_intrinsic(Intrinsic::TypeCheckValidI32);
                let get_global_current_thread_meta_fn =
                    render_args.require_intrinsic(Intrinsic::GetGlobalCurrentThreadMetaFn);

                uwriteln!(
                    output,
                    r#"
                      function {context_set_fn}(ctx, value) {{
                          const {{ slot }} = ctx;
                          if (slot === undefined) {{ throw new TypeError("missing slot"); }}
                          if (!({type_check_i32}(value))) {{ throw new Error('invalid value for context set (not valid i32)'); }}

                          // Guest callbacks use their component's task register. FACT
                          // adapters have no component index; post-return also runs
                          // after the callee register is cleared. Both use the executing
                          // task, whose context FACT temporarily saves and restores.
                          let currentThreadMeta = {get_global_current_thread_meta_fn}(ctx.componentIdx);
                          let threadMeta = currentThreadMeta
                              ? {current_thread_get_fn}(currentThreadMeta.componentIdx, currentThreadMeta.threadID, currentThreadMeta.taskID)
                              : undefined;

                          // A post-return may run after the callee has exited. Its
                          // per-component register can therefore name a task which is
                          // no longer live; fall back to FACT's executing task.
                          if (!threadMeta) {{
                              currentThreadMeta = {get_global_current_thread_meta_fn}();
                              threadMeta = currentThreadMeta
                                  ? {current_thread_get_fn}(currentThreadMeta.componentIdx, currentThreadMeta.threadID, currentThreadMeta.taskID)
                                  : undefined;
                          }}
                          if (!threadMeta) {{
                              throw new Error(`missing/incomplete global current thread meta for component idx [${{ctx.componentIdx}}] during context set`);
                          }}

                          const thread = threadMeta.thread;
                          if (!thread) {{ throw new Error('invalid/missing current thread in metadata while setting context'); }}

                          {debug_log_fn}('[{context_set_fn}()] args', {{
                              slot,
                              value,
                              storage: thread.storage,
                              threadID: thread.id(),
                              taskID: threadMeta.task.id(),
                              componentIdx: thread.componentIdx(),
                          }});

                          if (slot < 0 || slot >= thread.storage.length) {{ throw new Error('invalid slot for current thread'); }}
                          thread.storage[slot] = value;
                      }}
                    "#
                );
            }

            Self::ContextGet => {
                let debug_log_fn = render_args.require_intrinsic(Intrinsic::DebugLog);
                let context_get_fn = render_args.require_intrinsic(Self::ContextGet);
                let current_thread_get_fn = render_args.require_intrinsic(Self::GetCurrentThread);
                let get_global_current_thread_meta_fn =
                    render_args.require_intrinsic(Intrinsic::GetGlobalCurrentThreadMetaFn);

                uwriteln!(
                    output,
                    r#"
                      function {context_get_fn}(ctx) {{
                          const {{ slot }} = ctx;
                          if (slot === undefined) {{ throw new TypeError("missing slot"); }}

                          // Guest callbacks use their component's task register. FACT
                          // adapters have no component index; post-return also runs
                          // after the callee register is cleared. Both use the executing
                          // task, whose context FACT temporarily saves and restores.
                          let currentThreadMeta = {get_global_current_thread_meta_fn}(ctx.componentIdx);
                          let threadMeta = currentThreadMeta
                              ? {current_thread_get_fn}(currentThreadMeta.componentIdx, currentThreadMeta.threadID, currentThreadMeta.taskID)
                              : undefined;

                          // A post-return may run after the callee has exited. Its
                          // per-component register can therefore name a task which is
                          // no longer live; fall back to FACT's executing task.
                          if (!threadMeta) {{
                              currentThreadMeta = {get_global_current_thread_meta_fn}();
                              threadMeta = currentThreadMeta
                                  ? {current_thread_get_fn}(currentThreadMeta.componentIdx, currentThreadMeta.threadID, currentThreadMeta.taskID)
                                  : undefined;
                          }}
                          if (!threadMeta) {{
                              throw new Error(`missing/incomplete global current thread meta for component idx [${{ctx.componentIdx}}] during context get`);
                          }}

                          const thread = threadMeta.thread;
                          if (!thread) {{ throw new Error('invalid/missing current thread in metadata while getting context'); }}

                          {debug_log_fn}('[{context_get_fn}()] args', {{
                              slot,
                              storage: thread.storage,
                              threadID: thread.id(),
                              taskID: threadMeta.task.id(),
                              componentIdx: thread.componentIdx(),
                          }});

                          if (slot < 0 || slot >= thread.storage.length) {{ throw new Error('invalid slot for current thread'); }}

                          return thread.storage[slot];
                      }}
                    "#
                );
            }

            // Equivalent of `task.return`
            Self::TaskReturn => {
                let debug_log_fn = render_args.require_intrinsic(Intrinsic::DebugLog);
                let task_return_fn = render_args.require_intrinsic(Self::TaskReturn);
                let runtime_error_class =
                    render_args.require_intrinsic(Intrinsic::WebAssemblyRuntimeError);
                let get_global_current_thread_meta_fn =
                    render_args.require_intrinsic(Intrinsic::GetGlobalCurrentThreadMetaFn);
                let current_task_get_fn = render_args.require_intrinsic(Self::GetCurrentTask);
                let with_global_current_thread_meta_fn =
                    render_args.require_intrinsic(Intrinsic::WithGlobalCurrentThreadMetaFn);

                output.push_str(&format!(r#"
                    function {task_return_fn}(ctx) {{
                        const {{
                            componentIdx,
                            getMemoryFn,
                            memoryIdx,
                            callbackFnIdx,
                            liftFns,
                            lowerFns,
                            stringEncoding,
                        }} = ctx;
                        const params = [...arguments].slice(1);
                        const memory = getMemoryFn();
                        let useDirectParams = ctx.useDirectParams;

                        const {{ taskID }} = {get_global_current_thread_meta_fn}(componentIdx);

                        const taskMeta = {current_task_get_fn}(componentIdx, taskID);
                        if (!taskMeta) {{ throw new Error('failed to retrieve current task metadata'); }}

                        const task = taskMeta.task;
                        if (!task) {{ throw new Error('invalid/missing current task in metadata'); }}
                        // JSPI wrapping does not change the canonical lift option.
                        if (!task.calleeIsAsync()) {{
                            throw new {runtime_error_class}('task.return requires an async canonical lift');
                        }}
                        task.validateResourceBorrowScope();

                        // Canonical ABI `canon_task_return`: the result type must be the one of
                        // the task's function type.
                        const expectedResultType = task.returnResultTypeIdx();
                        if (expectedResultType !== null && ctx.resultTypeIdx !== undefined && ctx.resultTypeIdx !== expectedResultType) {{
                            throw new {runtime_error_class}('task.return result type does not match the function type');
                        }}

                        {debug_log_fn}('[{task_return_fn}()] args', {{
                            componentIdx,
                            taskID: task.id(),
                            subtaskID: task.getParentSubtask()?.id(),
                            callbackFnIdx,
                            memoryIdx,
                            liftFns,
                            lowerFns,
                            params,
                        }});

                        // If we are in a subtask, and have a fused helper function provided to use
                        // via PrepareCall, we can use that function rather than performing lifting manually.
                        //
                        // See also documentation on `HostIntrinsic::PrepareCall`
                        const subtaskCallMetadata = task.getParentSubtask()?.getCallMetadata();
                        if (subtaskCallMetadata?.returnFn && !subtaskCallMetadata.returnFnCalled) {{
                            {debug_log_fn}('[{task_return_fn}()] calling return fn on subtask', {{
                                componentIdx,
                                taskID: task.id(),
                                subtaskID: task.getParentSubtask()?.id(),
                                returnFnParams: [...params, subtaskCallMetadata.resultPtr],
                            }});
                            const callerTask = task.getParentSubtask().getParentTask();
                            const res = {with_global_current_thread_meta_fn}({{
                                taskID: callerTask.id(),
                                threadID: subtaskCallMetadata.callerThreadID,
                                componentIdx: callerTask.componentIdx(),
                                fn: () => subtaskCallMetadata.returnFn.apply(null, [...params, subtaskCallMetadata.resultPtr]),
                            }});
                            // For sync-lowered calls the fused [return-call] helper returns
                            // the lowering's flat result directly; stash it for
                            // _syncStartCall to return to the blocked caller.
                            subtaskCallMetadata.returnFnResult = res;
                            subtaskCallMetadata.returnFnCalled = true;
                            task.resolve([]);
                            return;
                        }}

                        const expectedMemoryIdx = task.getReturnMemoryIdx();
                        if (expectedMemoryIdx !== null && memoryIdx !== null && expectedMemoryIdx !== memoryIdx) {{
                            {debug_log_fn}("[{task_return_fn}()] mismatched memory indices", {{ expectedMemoryIdx, memoryIdx }});
                            throw new Error('task.return memory [' + memoryIdx + '] does not match task [' + expectedMemoryIdx + ']');
                        }}

                        task.callbackFnIdx = callbackFnIdx;

                        if (!memory && liftFns.length > 4) {{
                            {debug_log_fn}("[{task_return_fn}()] memory not present for max async flat lifts");
                            throw new Error('memory must be present if more than max async flat lifts are performed');
                        }}

                        let liftCtx = {{ memory, useDirectParams, params, componentIdx, stringEncoding }};
                        if (!useDirectParams) {{
                            if (!memory) {{
                                {debug_log_fn}('missing memory despite indirect param usage', {{ useDirectParams, liftCtx, ctx }});
                                throw new Error('missing memory despite indirect param usage');
                            }}
                            liftCtx.storagePtr = params[0] >>> 0;
                            liftCtx.storageLen = params[1];
                        }}

                        const liftedResults = [];
                        {debug_log_fn}('[{task_return_fn}()] lifting results out of memory', {{ liftCtx }});
                        for (const liftFn of liftFns) {{
                            if (liftCtx.storageLen !== undefined && liftCtx.storageLen <= 0) {{
                                {debug_log_fn}(`[{task_return_fn}()] ran out of range while writing storageLen = [${{liftCtx.storageLen}}]`);
                                throw new Error('ran out of storage while writing');
                            }}
                            const [ val, newLiftCtx ] = liftFn(liftCtx);
                            liftCtx = newLiftCtx;
                            liftedResults.push(val);
                        }}

                        task.resolve(liftedResults);
                    }}
                "#));
            }

            Self::SubtaskDrop => {
                let runtime_error_class =
                    render_args.require_intrinsic(Intrinsic::WebAssemblyRuntimeError);
                let subtask_class = render_args.require_intrinsic(Self::AsyncSubtaskClass);
                let debug_log_fn = render_args.require_intrinsic(Intrinsic::DebugLog);
                let subtask_drop_fn = render_args.require_intrinsic(Self::SubtaskDrop);
                let get_or_create_async_state_fn = render_args.require_intrinsic(
                    Intrinsic::Component(ComponentIntrinsic::GetOrCreateAsyncState),
                );
                uwriteln!(
                    output,
                    r#"
                    function {subtask_drop_fn}(componentIdx, subtaskWaitableRep) {{
                        {debug_log_fn}('[{subtask_drop_fn}()] args', {{ componentIdx, subtaskWaitableRep }});

                        const cstate = {get_or_create_async_state_fn}(componentIdx);
                        if (!cstate.mayLeave) {{ throw new {runtime_error_class}('component is not marked as may leave, cannot drop subtask'); }}

                        const subtask = cstate.handles.get(subtaskWaitableRep);
                        if (!(subtask instanceof {subtask_class})) {{
                            throw new {runtime_error_class}('invalid subtask handle for drop');
                        }}

                        cstate.handles.remove(subtaskWaitableRep);
                        subtask.drop();
                    }}
                "#
                );
            }

            Self::ThreadYield => {
                let debug_log_fn = render_args.require_intrinsic(Intrinsic::DebugLog);
                let thread_yield_fn = self.name();
                let current_thread_or_throw_fn =
                    render_args.require_intrinsic(Self::CurrentThreadOrThrow);
                let get_or_create_async_state_fn = render_args.require_intrinsic(
                    Intrinsic::Component(ComponentIntrinsic::GetOrCreateAsyncState),
                );
                output.push_str(&format!(
                    "
                    function {thread_yield_fn}(ctx) {{
                        {debug_log_fn}('[{thread_yield_fn}()] args', {{ ctx }});
                        const {{ componentIdx, isCancellable }} = ctx;
                        const {{ thread, task }} = {current_thread_or_throw_fn}(componentIdx);

                        // A nonblocking task cannot suspend its Wasm stack. The
                        // Canonical ABI permits yield to complete without scheduling
                        // another thread, so take that synchronous fast path here.
                        if (!task.mayBlock()) {{
                            {get_or_create_async_state_fn}(componentIdx).runTickLoop();
                            return isCancellable && thread.isCancelled() ? 1 : 0;
                        }}

                        // A canonical thread.yield must give the scheduler a chance to
                        // run other work before reporting NOT_CANCELLED. Unlike an
                        // ordinary ready wait, it cannot take the immediate-completion
                        // shortcut.
                        return thread.suspend({{
                            // Cancellation is delivered only while an implicit
                            // callback thread is parked in its event loop.
                            cancellable: false,
                            readyFn: () => true,
                        }}).then(keepGoing => keepGoing ? 0 : 1);
                    }}
                "
                ));
            }

            // Thread indices are scoped to the component instance. The ambient
            // thread-meta register already stores the current thread's index.
            Self::ThreadIndex => {
                let thread_index_fn = self.name();
                let get_global_current_thread_meta_fn =
                    render_args.require_intrinsic(Intrinsic::GetGlobalCurrentThreadMetaFn);
                output.push_str(&format!(
                    "
                    function {thread_index_fn}(componentIdx) {{
                        const meta = {get_global_current_thread_meta_fn}(componentIdx);
                        if (!meta) {{ throw new Error('missing/incomplete global current thread meta for component idx [' + componentIdx + ']'); }}
                        return meta.threadID;
                    }}
                    "
                ))
            }

            // Suspends the current thread until something else explicitly
            // targets it via `thread.resume-later` -- unlike `thread.yield`,
            // it is never spontaneously ready on its own.
            Self::ThreadSuspend => {
                let debug_log_fn = render_args.require_intrinsic(Intrinsic::DebugLog);
                let thread_suspend_fn = self.name();
                let current_thread_or_throw_fn =
                    render_args.require_intrinsic(Self::CurrentThreadOrThrow);
                output.push_str(&format!(
                    "
                    async function {thread_suspend_fn}(ctx) {{
                        {debug_log_fn}('[{thread_suspend_fn}()] args', {{ ctx }});
                        const {{ componentIdx, isCancellable }} = ctx;
                        const {{ thread }} = {current_thread_or_throw_fn}(componentIdx);

                        const keepGoing = await thread.suspend({{
                            cancellable: isCancellable,
                            suspended: true,
                            readyFn: () => false,
                        }});
                        return keepGoing ? 0 : 1;
                    }}
                "
                ));
            }

            // Implements `thread.new-indirect`: creates a new thread on the
            // *current* task whose body is the function at `startFuncIdx` in
            // the given table, and whose signature is always
            // `(context: i32) -> ()`.
            //
            // Per the canonical ABI, a freshly created thread starts out
            // *suspended* (not running) -- Core Wasm must separately call
            // `thread.resume-later` (or another `thread.*` builtin) to make
            // it actually run. So this registers the thread as suspended
            // immediately, with `onResume` wired to kick off its body; it
            // does not run anything itself.
            //
            // The returned id is allocated from the component instance's thread
            // table, so it can be targeted by another task in that instance.
            //
            // An out-of-range or uninitialized table index is a trap (the
            // trampoline is installed under `guardTrap`, so the trap is also
            // recorded against the instance).
            Self::ThreadNewIndirect => {
                let debug_log_fn = render_args.require_intrinsic(Intrinsic::DebugLog);
                let thread_new_indirect_fn = self.name();
                let current_thread_or_throw_fn =
                    render_args.require_intrinsic(Self::CurrentThreadOrThrow);
                let thread_class = render_args.require_intrinsic(Self::AsyncThreadClass);
                let get_or_create_async_state_fn = render_args.require_intrinsic(
                    Intrinsic::Component(ComponentIntrinsic::GetOrCreateAsyncState),
                );
                let runtime_error_class =
                    render_args.require_intrinsic(Intrinsic::WebAssemblyRuntimeError);
                output.push_str(&format!(
                    "
                    // Component validation requires the start type to be (func (param i32)).
                    // Import matching checks a Wasm function's actual type without running it.
                    const {thread_new_indirect_fn}TypeCheck = new WebAssembly.Module(new Uint8Array([
                        0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00,
                        0x01, 0x05, 0x01, 0x60, 0x01, 0x7f, 0x00,
                        0x02, 0x06, 0x01, 0x00, 0x01, 0x66, 0x00, 0x00,
                    ]));
                    const {thread_new_indirect_fn}Checked = new WeakSet();
                    function {thread_new_indirect_fn}(ctx, startFuncIdx, context) {{
                        const {{ componentIdx, getStartFuncTableFn }} = ctx;
                        {debug_log_fn}('[{thread_new_indirect_fn}()] args', {{ componentIdx, startFuncIdx, context }});

                        const table = getStartFuncTableFn();
                        if (!table) {{ throw new Error('missing start function table for thread.new-indirect'); }}

                        // (the index is a core i32; an out-of-range index traps like `call_indirect`)
                        const tableIdx = startFuncIdx >>> 0;
                        if (tableIdx >= table.length) {{
                            throw new {runtime_error_class}('thread.new-indirect: table index out of bounds');
                        }}
                        const startFuncRef = table.get(tableIdx);
                        if (typeof startFuncRef !== 'function') {{
                            throw new {runtime_error_class}('thread.new-indirect: uninitialized table element');
                        }}
                        if (!{thread_new_indirect_fn}Checked.has(startFuncRef)) {{
                            try {{
                                new WebAssembly.Instance({thread_new_indirect_fn}TypeCheck, {{ '': {{ f: startFuncRef }} }});
                            }} catch (err) {{
                                if (!(err instanceof WebAssembly.LinkError)) {{ throw err; }}
                                throw new {runtime_error_class}('thread.new-indirect: start function type mismatch');
                            }}
                            {thread_new_indirect_fn}Checked.add(startFuncRef);
                        }}
                        const promisingStartFuncRef = WebAssembly.promising(startFuncRef);

                        const {{ task }} = {current_thread_or_throw_fn}(componentIdx);

                        const newThread = task.addThread(new {thread_class}({{
                            componentIdx,
                            task,
                            startFn: () => promisingStartFuncRef(context),
                        }}));

                        // Suspended, not ready: only an explicit `thread.resume-later`
                        // (never the tick loop's own readiness polling) may wake it.
                        {get_or_create_async_state_fn}(componentIdx).suspendThread({{
                            thread: newThread,
                            cancellable: false,
                            suspended: true,
                            readyFn: () => false,
                            onResume: () => newThread.start(),
                        }});

                        return newThread.id();
                    }}
                "
                ));
            }

            // Implements `thread.resume-later`: marks a suspended thread of this
            // component instance ready to run. An index that names no live thread,
            // or a thread that is not suspended, traps (the trampoline is installed
            // under `guardTrap`, so the trap is also recorded against the instance).
            Self::ThreadResumeLater => {
                let debug_log_fn = render_args.require_intrinsic(Intrinsic::DebugLog);
                let thread_resume_later_fn = self.name();
                let get_or_create_async_state_fn = render_args.require_intrinsic(
                    Intrinsic::Component(ComponentIntrinsic::GetOrCreateAsyncState),
                );
                let runtime_error_class =
                    render_args.require_intrinsic(Intrinsic::WebAssemblyRuntimeError);
                output.push_str(&format!(
                    "
                    function {thread_resume_later_fn}(ctx, threadHandle) {{
                        const {{ componentIdx }} = ctx;
                        {debug_log_fn}('[{thread_resume_later_fn}()] args', {{ componentIdx, threadHandle }});

                        const cstate = {get_or_create_async_state_fn}(componentIdx);
                        if (!cstate) {{ throw new Error(`missing async state for component idx [${{componentIdx}}]`); }}
                        const thread = threadHandle === 0 ? undefined : cstate.threads.get(threadHandle >>> 0);
                        if (!thread) {{
                            throw new {runtime_error_class}(`unknown handle index ${{threadHandle}}`);
                        }}

                        if (!cstate.markThreadReady(thread)) {{
                            throw new {runtime_error_class}(`thread [${{threadHandle}}] is not suspended, cannot resume-later`);
                        }}
                    }}
                "
                ));
            }

            // Implements `thread.suspend-then-resume`/`thread.yield-then-resume`:
            // switches to `other` (which must already be suspended), leaving
            // the current thread suspended (resume variant) or ready (yield
            // variant). Register the current suspension before resuming the
            // target so its continuation cannot race ahead and observe this
            // thread as still running.
            Self::ThreadSuspendThenResume | Self::ThreadYieldThenResume => {
                let debug_log_fn = render_args.require_intrinsic(Intrinsic::DebugLog);
                let fn_name = self.name();
                let current_thread_or_throw_fn =
                    render_args.require_intrinsic(Self::CurrentThreadOrThrow);
                let get_or_create_async_state_fn = render_args.require_intrinsic(
                    Intrinsic::Component(ComponentIntrinsic::GetOrCreateAsyncState),
                );
                let runtime_error_class =
                    render_args.require_intrinsic(Intrinsic::WebAssemblyRuntimeError);
                // The resume variant leaves self merely suspended (only an
                // explicit resume-later/suspend-then-resume/promote wakes it);
                // the yield variant leaves self ready, same as plain `thread.yield`.
                let (self_ready_fn, self_suspended) = match self {
                    Self::ThreadYieldThenResume => ("() => true", false),
                    Self::ThreadSuspendThenResume => ("() => false", true),
                    _ => unreachable!(),
                };
                output.push_str(&format!(
                    "
                    function {fn_name}(ctx, threadIdx) {{
                        const {{ componentIdx, isCancellable }} = ctx;
                        {debug_log_fn}('[{fn_name}()] args', {{ componentIdx, isCancellable, threadIdx }});
                        const {{ thread }} = {current_thread_or_throw_fn}(componentIdx);

                        const cstate = {get_or_create_async_state_fn}(componentIdx);
                        const other = threadIdx === 0 ? undefined : cstate.threads.get(threadIdx >>> 0);
                        if (!other || other === thread || !cstate.isThreadSuspended(other)) {{
                            throw new {runtime_error_class}('cannot resume thread which is not suspended');
                        }}

                        const suspension = thread.suspend({{
                            cancellable: isCancellable,
                            suspended: {self_suspended},
                            readyFn: {self_ready_fn},
                        }});
                        cstate.resumeThread(other);

                        return suspension.then(keepGoing => keepGoing ? 0 : 1);
                    }}
                "
                ));
            }

            // Implements `thread.suspend-then-promote`/`thread.yield-then-promote`:
            // if `other` is currently suspended *and* ready (its readiness
            // condition is already met, just not yet picked up by the tick
            // loop), switch to it exactly like the `*-then-resume` builtins
            // above; otherwise ignore `other` entirely and fall back to a
            // plain `thread.suspend`/`thread.yield`.
            Self::ThreadSuspendThenPromote | Self::ThreadYieldThenPromote => {
                let debug_log_fn = render_args.require_intrinsic(Intrinsic::DebugLog);
                let fn_name = self.name();
                let current_thread_or_throw_fn =
                    render_args.require_intrinsic(Self::CurrentThreadOrThrow);
                let get_or_create_async_state_fn = render_args.require_intrinsic(
                    Intrinsic::Component(ComponentIntrinsic::GetOrCreateAsyncState),
                );
                let runtime_error_class =
                    render_args.require_intrinsic(Intrinsic::WebAssemblyRuntimeError);
                let fallback_fn = match self {
                    Self::ThreadSuspendThenPromote => {
                        render_args.require_intrinsic(Self::ThreadSuspend)
                    }
                    _ => render_args.require_intrinsic(Self::ThreadYield),
                };
                let self_ready_fn = match self {
                    Self::ThreadSuspendThenPromote => "() => false",
                    _ => "() => true",
                };
                let self_suspended = matches!(self, Self::ThreadSuspendThenPromote);
                output.push_str(&format!(
                    "
                    function {fn_name}(ctx, threadIdx) {{
                        const {{ componentIdx, isCancellable }} = ctx;
                        {debug_log_fn}('[{fn_name}()] args', {{ componentIdx, isCancellable, threadIdx }});
                        const {{ thread }} = {current_thread_or_throw_fn}(componentIdx);

                        const cstate = {get_or_create_async_state_fn}(componentIdx);
                        const other = threadIdx === 0 ? undefined : cstate.threads.get(threadIdx >>> 0);
                        // An index that names no live thread traps; so does a self
                        // switch (the same check as the `*-then-resume` built-ins).
                        if (!other) {{
                            throw new {runtime_error_class}('invalid thread handle');
                        }}
                        if (other === thread) {{
                            throw new {runtime_error_class}('cannot resume thread which is not suspended');
                        }}

                        if (cstate.isThreadReady(other)) {{
                            const suspension = thread.suspend({{
                                cancellable: isCancellable,
                                suspended: {self_suspended},
                                readyFn: {self_ready_fn},
                            }});
                            cstate.resumeThread(other);
                            return suspension.then(keepGoing => keepGoing ? 0 : 1);
                        }}

                        return {fallback_fn}(ctx);
                    }}
                "
                ));
            }
            Self::SubtaskCancel => {
                let runtime_error_class =
                    render_args.require_intrinsic(Intrinsic::WebAssemblyRuntimeError);
                let debug_log_fn = render_args.require_intrinsic(Intrinsic::DebugLog);
                let subtask_cancel_fn = render_args.require_intrinsic(Self::SubtaskCancel);
                let subtask_class = render_args.require_intrinsic(Self::AsyncSubtaskClass);
                let current_task_get_fn = render_args.require_intrinsic(Self::GetCurrentTask);
                let get_or_create_async_state_fn = render_args.require_intrinsic(
                    Intrinsic::Component(ComponentIntrinsic::GetOrCreateAsyncState),
                );
                let get_global_current_thread_meta_fn =
                    render_args.require_intrinsic(Intrinsic::GetGlobalCurrentThreadMetaFn);

                // Implements `canon subtask.cancel` -- the *supertask*-side request to
                // cancel a pending subtask (in contrast to `canon task.cancel`, which is
                // the *callee*-side acknowledgement that cancellation was delivered).
                //
                // See: https://github.com/WebAssembly/component-model/blob/main/design/mvp/CanonicalABI.md#-canon-subtaskcancel
                output.push_str(&format!("
                    function {subtask_cancel_fn}(componentIdx, isAsync, subtaskRep, slowOnly = false) {{
                        {debug_log_fn}('[{subtask_cancel_fn}()] args', {{ componentIdx, isAsync, subtaskRep }});

                        const state = {get_or_create_async_state_fn}(componentIdx);
                        if (!state.mayLeave) {{ throw new {runtime_error_class}('component instance is not marked as may leave, cannot cancel subtask'); }}

                        const subtask = state.handles.get(subtaskRep);
                        if (!(subtask instanceof {subtask_class})) {{
                            throw new {runtime_error_class}('missing/invalid subtask [' + subtaskRep + '] specified for cancel in component instance');
                        }}
                        if (subtask.resolveDelivered()) {{
                            throw new {runtime_error_class}('`subtask.cancel` called after terminal status delivered');
                        }}
                        if (!isAsync && subtask.getWaitable().isInSet()) {{
                            throw new {runtime_error_class}('cannot synchronously cancel a subtask that is in a waitable set');
                        }}

                        const finishCancel = () => {{
                            // Consume the subtask's pending resolution event (which also marks the
                            // resolution as delivered), then hand the final state back to core wasm.
                            // Legal states here: RETURNED, CANCELLED_BEFORE_STARTED, CANCELLED_BEFORE_RETURNED.
                            if (subtask.hasPendingEvent()) {{ subtask.getPendingEvent(); }}
                            if (!subtask.resolveDelivered()) {{ subtask.deliverResolve(); }}

                            return subtask.getStateNumber();
                        }};

                        if (subtask.cancellationRequested()) {{
                            if (!slowOnly) {{
                                throw new {runtime_error_class}('cancellation has already been requested for this subtask');
                            }}
                            if (subtask.isResolved()) {{ return finishCancel(); }}

                            if (subtask.cancelProgress) {{
                                const progress = subtask.cancelProgress;
                                subtask.cancelProgress = null;
                                return progress.then(() => {{
                                    if (subtask.isResolved()) {{ return finishCancel(); }}
                                    if (isAsync) {{ return 0xFFFFFFFF; }}
                                    const {{ taskID }} = {get_global_current_thread_meta_fn}(componentIdx);
                                    const taskMeta = {current_task_get_fn}(componentIdx, taskID);
                                    if (!taskMeta || !taskMeta.task) {{ throw new Error('invalid/missing async task'); }}
                                    return taskMeta.task.waitUntil({{
                                        cancellable: false,
                                        readyFn: () => subtask.isResolved(),
                                    }}).then(finishCancel);
                                }});
                            }}

                            const {{ taskID }} = {get_global_current_thread_meta_fn}(componentIdx);
                            const taskMeta = {current_task_get_fn}(componentIdx, taskID);
                            if (!taskMeta || !taskMeta.task) {{ throw new Error('invalid/missing async task'); }}
                            return taskMeta.task.waitUntil({{
                                cancellable: false,
                                readyFn: () => subtask.isResolved(),
                            }}).then(finishCancel);
                        }}

                        let cancellationWillCompleteAsync = false;

                        if (!subtask.isResolved()) {{
                            const childTask = subtask.getChildTask();
                            subtask.requestCancellation();

                            if (!subtask.isResolved()) {{
                                // Cancellation may resume only the cancelled task's
                                // implicit callback thread, and only while that thread is
                                // parked cancellably in its event loop. No other ready
                                // thread in the component instance may run here.
                                if (childTask?.hasCallback()) {{
                                    const childState = {get_or_create_async_state_fn}(childTask.componentIdx());
                                    if (childState.suspendedTaskCancellable(childTask.id()) &&
                                        childState.suspendedTaskReady(childTask.id())) {{
                                        const progress = childTask.waitForProgress();
                                        if (!childState.resumeTaskByID(childTask.id())) {{
                                            throw new Error('failed to resume cancelled callback task');
                                        }}
                                        cancellationWillCompleteAsync = true;
                                        subtask.cancelProgress = progress;
                                    }}
                                }}
                            }}

                            if (!subtask.isResolved()) {{
                                // The resumed callee blocked again: async-lowered cancels
                                // report BLOCKED (resolution will arrive via a later SUBTASK event),
                                // while sync-lowered cancels block the current task until the
                                // subtask resolves.
                                if (isAsync) {{
                                    // -1 is the canonical BLOCKED status. -2 is an
                                    // internal signal consumed by the conditional JSPI
                                    // trampoline when a cancellable child was resumed but
                                    // its suspended Wasm stack must finish in a microtask.
                                    return cancellationWillCompleteAsync ? 0xFFFFFFFE : 0xFFFFFFFF;
                                }}

                                // The fast half of the conditional JSPI trampoline
                                // cannot return a Promise. Signal that the slow,
                                // suspending half must finish the synchronous cancel.
                                if (!slowOnly) {{ return 0xFFFFFFFE; }}

                                const {{ taskID }} = {get_global_current_thread_meta_fn}(componentIdx);
                                const taskMeta = {current_task_get_fn}(componentIdx, taskID);
                                if (!taskMeta || !taskMeta.task) {{ throw new Error('invalid/missing async task'); }}
                                return taskMeta.task.waitUntil({{
                                    cancellable: false,
                                    readyFn: () => subtask.isResolved(),
                                }}).then(finishCancel);
                            }}
                        }}

                        return finishCancel();
                    }}
                "));
            }

            Self::TaskCancel => {
                let debug_log_fn = render_args.require_intrinsic(Intrinsic::DebugLog);
                let task_cancel_fn = render_args.require_intrinsic(Self::TaskCancel);
                let current_task_get_fn = render_args.require_intrinsic(Self::GetCurrentTask);
                let get_or_create_async_state_fn = render_args.require_intrinsic(
                    Intrinsic::Component(ComponentIntrinsic::GetOrCreateAsyncState),
                );
                let get_global_current_thread_meta_fn =
                    render_args.require_intrinsic(Intrinsic::GetGlobalCurrentThreadMetaFn);

                output.push_str(&format!("
                    function {task_cancel_fn}(componentIdx) {{
                        {debug_log_fn}('[{task_cancel_fn}()] args', {{ componentIdx }});

                        const state = {get_or_create_async_state_fn}(componentIdx);
                        if (!state.mayLeave) {{ throw new Error('component instance is not marked as may leave, cannot be cancelled'); }}

                        const {{ taskID }} = {get_global_current_thread_meta_fn}(componentIdx);

                        const taskMeta = {current_task_get_fn}(componentIdx, taskID);
                        if (!taskMeta) {{ throw new Error('invalid/missing async task meta'); }}

                        const task = taskMeta.task;
                        if (!task) {{ throw new Error('invalid/missing async task'); }}

                        if (task.sync && !task.alwaysTaskReturn) {{
                            throw new Error('cannot cancel sync tasks without always task return set');
                        }}

                        task.cancel();
                    }}
                "));
            }

            Self::CreateNewCurrentImplicitThread => {
                let debug_log_fn = render_args.require_intrinsic(Intrinsic::DebugLog);
                let task_class = render_args.require_intrinsic(Self::AsyncTaskClass);
                let thread_class = render_args.require_intrinsic(Self::AsyncThreadClass);
                let global_task_map =
                    render_args.require_intrinsic(Self::GlobalAsyncCurrentTaskMap);
                let task_id_globals =
                    render_args.require_intrinsic(Self::GlobalAsyncCurrentTaskIds);
                let component_idx_globals =
                    render_args.require_intrinsic(Self::GlobalAsyncCurrentComponentIdxs);

                output.push_str(&format!(
                    r#"
                    function {fn_name}(args) {{
                        {debug_log_fn}('[{fn_name}()] args', args);
                        const {{
                            componentIdx,
                            isAsync,
                            isManualAsync,
                            preserveFutureResult,
                            entryFnName,
                            parentSubtaskID,
                            callbackFnName,
                            getCallbackFn,
                            getParamsFn,
                            stringEncoding,
                            errHandling,
                            getCalleeParamsFn,
                            resultPtr,
                            callingWasmExport,
                        }} = args;
                        if (componentIdx === undefined || componentIdx === null) {{
                            throw new Error('missing/invalid component instance index while starting task');
                        }}
                        let taskMetas = {global_task_map}.get(componentIdx);
                        const callbackFn = getCallbackFn ? getCallbackFn() : null;

                        const newTask = new {task_class}({{
                            componentIdx,
                            isAsync,
                            isManualAsync,
                            preserveFutureResult,
                            entryFnName,
                            callbackFn,
                            callbackFnName,
                            stringEncoding,
                            getCalleeParamsFn,
                            resultPtr,
                            errHandling,
                            callingWasmExport,
                        }});

                        const newTaskID = newTask.id();
                        const newTaskMeta = {{ id: newTaskID, componentIdx, task: newTask }};

                        // Every task starts with a single implicit thread, registered
                        // the same way as explicitly spawned ones (`thread.new-indirect`):
                        // `addThread` assigns its real, instance-scoped id.
                        const newThread = newTask.addThread(new {thread_class}({{
                            componentIdx,
                            task: newTask,
                        }}));
                        const newThreadID = newThread.id();

                        // NOTE: do not track host tasks
                        {task_id_globals}.push(newTaskID);
                        {component_idx_globals}.push(componentIdx);

                        if (!taskMetas) {{
                            taskMetas = [newTaskMeta];
                            {global_task_map}.set(componentIdx, [newTaskMeta]);
                        }} else {{
                            taskMetas.push(newTaskMeta);
                        }}

                        return {{ task: newTask, thread: newThread, taskID: newTaskID, threadID: newThreadID }};
                    }}
                "#,
                    fn_name = self.name(),
                ));
            }

            // Debug log for this is disabled since it is fairly noisy
            Self::GetCurrentTask => {
                let global_task_map =
                    render_args.require_intrinsic(Self::GlobalAsyncCurrentTaskMap);
                let current_component_idx_globals = render_args
                    .require_intrinsic(AsyncTaskIntrinsic::GlobalAsyncCurrentComponentIdxs);
                let global_current_thread_meta_obj =
                    render_args.require_intrinsic(Intrinsic::GlobalCurrentThreadMeta);
                output.push_str(&format!(
                    r#"
                    function {fn_name}(componentIdx, taskID) {{
                        let usedGlobal = false;
                        if (componentIdx === undefined || componentIdx === null) {{
                            throw new Error('missing component idx'); // TODO(fix)
                            // componentIdx = {current_component_idx_globals}.at(-1);
                            // usedGlobal = true;
                        }}

                        const taskMetas = {global_task_map}.get(componentIdx);
                        if (taskMetas === undefined || taskMetas.length === 0) {{ return undefined; }}

                        if (taskID) {{
                            return taskMetas.find(meta => meta.task.id() === taskID);
                        }}

                        // The task whose guest code is running is the one the metadata
                        // wrappers record for the component (and restore when a suspended
                        // stack resumes). The component's most recently created task may
                        // be another one, e.g. a prepared callee that has not entered yet
                        // while an earlier task of the component is suspended.
                        const current = {global_current_thread_meta_obj}[componentIdx];
                        if (current && current.taskID !== undefined) {{
                            const currentMeta = taskMetas.find(meta => meta.task.id() === current.taskID);
                            if (currentMeta) {{ return currentMeta; }}
                        }}

                        const taskMeta = taskMetas[taskMetas.length - 1];
                        if (!taskMeta || !taskMeta.task) {{ return undefined; }}

                        return taskMeta;
                    }}
                "#,
                    fn_name = self.name(),
                ));
            }

            // Looks up a thread by its component-instance-scoped id (the
            // canonical ABI's `inst.threads.get(i)`) -- *not* scoped through
            // any particular task, since threads are addressed instance-wide.
            Self::GetCurrentThread => {
                let get_or_create_async_state_fn = render_args.require_intrinsic(
                    Intrinsic::Component(ComponentIntrinsic::GetOrCreateAsyncState),
                );
                output.push_str(&format!(
                    r#"
                    function {fn_name}(componentIdx, threadID, taskID) {{
                        // Host (-1) tasks have no component instance, and so no thread table.
                        if (componentIdx === -1) {{ return undefined; }}
                        if (threadID === undefined || threadID === null || threadID === 0) {{ return undefined; }}

                        const cstate = {get_or_create_async_state_fn}(componentIdx);
                        const thread = cstate.threads.get(threadID);
                        if (!thread) {{ return undefined; }}

                        // Thread indices are recycled once a thread exits (the thread table
                        // reuses freed slots) but task ids never are. A register that still
                        // names an exited thread, e.g. during a post-return that runs after
                        // its task exited, must not resolve to whichever newer thread took
                        // the slot; callers then fall back as for a missing thread.
                        if (taskID !== undefined && thread.taskID() !== taskID) {{ return undefined; }}

                        return {{ id: threadID, componentIdx, taskID: thread.taskID(), task: thread.task(), thread }};
                    }}
                "#,
                    fn_name = self.name(),
                ));
            }

            // The prologue shared by every `thread.*` built-in: the thread whose
            // guest code is running is the one the component's ambient register
            // names. Missing or stale register contents are an internal error
            // here (the built-ins only run from guest code of a live thread).
            Self::CurrentThreadOrThrow => {
                let fn_name = self.name();
                let get_current_thread_fn = render_args.require_intrinsic(Self::GetCurrentThread);
                let get_global_current_thread_meta_fn =
                    render_args.require_intrinsic(Intrinsic::GetGlobalCurrentThreadMetaFn);
                output.push_str(&format!(
                    r#"
                    function {fn_name}(componentIdx) {{
                        const meta = {get_global_current_thread_meta_fn}(componentIdx);
                        if (!meta) {{
                            throw new Error(`missing/incomplete global current thread meta for component idx [${{componentIdx}}]`);
                        }}
                        const threadMeta = {get_current_thread_fn}(meta.componentIdx, meta.threadID, meta.taskID);
                        if (!threadMeta || !threadMeta.thread) {{
                            throw new Error(`invalid/missing async thread [${{meta.threadID}}] for component idx [${{componentIdx}}]`);
                        }}
                        return threadMeta;
                    }}
                "#
                ));
            }

            Self::ClearCurrentThread => {
                let debug_log_fn = render_args.require_intrinsic(Intrinsic::DebugLog);
                let fn_name = self.name();
                let global_task_map =
                    render_args.require_intrinsic(Self::GlobalAsyncCurrentTaskMap);
                let task_id_globals =
                    render_args.require_intrinsic(Self::GlobalAsyncCurrentTaskIds);
                let component_idx_globals =
                    render_args.require_intrinsic(Self::GlobalAsyncCurrentComponentIdxs);

                output.push_str(&format!(
                    r#"
                    function {fn_name}(componentIdx, taskID, opts = {{}}) {{
                        {debug_log_fn}('[{fn_name}()] args', {{ componentIdx, taskID }});

                        if (componentIdx === undefined || componentIdx === null) {{
                            throw new Error('missing/invalid component instance index while ending current task');
                        }}

                        const tasks = {global_task_map}.get(componentIdx);
                        if (!tasks || !Array.isArray(tasks)) {{
                            throw new Error('missing/invalid tasks for component instance while ending task');
                        }}
                        if (tasks.length == 0) {{
                            throw new Error(`no current tasks for component instance [${{componentIdx}}] while ending task`);
                        }}

                        const taskIdx = taskID === undefined
                            ? tasks.length - 1
                            : tasks.findIndex(meta => meta.id === taskID);
                        if (taskIdx === -1) {{ return; }}

                        const taskMeta = tasks[taskIdx];
                        if (!opts.preserveTask) {{
                            tasks.splice(taskIdx, 1);
                        }}
                        const globalTaskIdx = {task_id_globals}.lastIndexOf(taskMeta.id);
                        if (globalTaskIdx !== -1) {{
                            {task_id_globals}.splice(globalTaskIdx, 1);
                            {component_idx_globals}.splice(globalTaskIdx, 1);
                        }}
                        return taskMeta.task;
                    }}
                "#,
                ));
            }

            Self::AsyncTaskClass => {
                let debug_log_fn = render_args.require_intrinsic(Intrinsic::DebugLog);
                let get_or_create_async_state_fn = render_args.require_intrinsic(
                    Intrinsic::Component(ComponentIntrinsic::GetOrCreateAsyncState),
                );
                let event_code_enum = render_args.require_intrinsic(Intrinsic::AsyncEventCodeEnum);
                let task_class = render_args.require_intrinsic(Self::AsyncTaskClass);
                let subtask_class = render_args.require_intrinsic(Self::AsyncSubtaskClass);
                let global_async_determinism =
                    render_args.require_intrinsic(Intrinsic::GlobalAsyncDeterminism);
                let coin_flip_fn = render_args.require_intrinsic(Intrinsic::CoinFlip);
                let waitable_class = render_args
                    .require_intrinsic(Intrinsic::Waitable(WaitableIntrinsic::WaitableClass));
                let clear_current_task_fn = render_args.require_intrinsic(Intrinsic::AsyncTask(
                    AsyncTaskIntrinsic::ClearCurrentThread,
                ));
                let with_global_current_thread_meta_async_fn =
                    render_args.require_intrinsic(Intrinsic::WithGlobalCurrentThreadMetaFnAsync);
                let with_global_current_thread_meta_fn =
                    render_args.require_intrinsic(Intrinsic::WithGlobalCurrentThreadMetaFn);
                let promise_with_resolvers_fn =
                    render_args.require_intrinsic(Intrinsic::PromiseWithResolversPonyfill);
                let post_return_trap_fn = render_args
                    .require_intrinsic(Intrinsic::Component(ComponentIntrinsic::PostReturnTrap));
                let record_trap_fn = render_args
                    .require_intrinsic(Intrinsic::Component(ComponentIntrinsic::RecordTrap));
                let future_value_class = render_args.require_intrinsic(Intrinsic::AsyncFuture(
                    AsyncFutureIntrinsic::FutureValueClass,
                ));
                let resource_scope_counter = render_args.require_intrinsic(Intrinsic::Resource(
                    ResourceIntrinsic::ResourceScopeCounter,
                ));
                let resource_scope_tasks = render_args
                    .require_intrinsic(Intrinsic::Resource(ResourceIntrinsic::ResourceScopeTasks));
                let runtime_error_class =
                    render_args.require_intrinsic(Intrinsic::WebAssemblyRuntimeError);

                let get_global_current_thread_meta_fn =
                    render_args.require_intrinsic(Intrinsic::GetGlobalCurrentThreadMetaFn);

                output.push_str(&format!(r#"
                    class {task_class} {{
                        static _ID = 0n;
                        // Ids for the implicit threads of host (-1) tasks, which have no
                        // component instance thread table (see `addThread`).
                        static _HOST_THREAD_ID = 0;

                        static State = {{
                            INITIAL: 'initial',
                            CANCELLED: 'cancelled',
                            CANCEL_PENDING: 'cancel-pending',
                            CANCEL_DELIVERED: 'cancel-delivered',
                            RESOLVED: 'resolved',
                        }}

                        static BlockResult = {{
                            CANCELLED: 'block.cancelled',
                            NOT_CANCELLED: 'block.not-cancelled',
                        }}

                        #id;
                        #componentIdx;
                        #state;
                        #isAsync;
                        #isManualAsync;
                        #callingWasmExport = true;
                        #lockFreeEntry = false;
                        #preserveFutureResult;
                        #entryFnName = null;

                        #onResolveHandlers = [];
                        #progressWaiters = [];
                        #completionPromise = null;
                        #completionValue;
                        #completionReady = false;
                        #settleCompletionPromise;
                        #rejected = false;

                        #exitPromise = null;
                        #onExitHandlers = [];

                        #memoryIdx = null;
                        #memory = null;

                        #callbackFn = null;
                        #callbackFnName = null;

                        #postReturnFn = null;

                        #getCalleeParamsFn = null;
                        #calleeIsAsync = null;
                        #admissionTicket = null;
                        #funcTypeIsAsync = false;
                        #returnResultTypeIdx = null;

                        #stringEncoding = null;

                        #parentSubtask = null;

                        #errHandling;

                        #backpressurePromise;
                        #backpressureWaiters = 0n;

                        #returnLowerFns = null;

                        #resourceScopeId;
                        #resourceBorrowCount = 0;
                        #resourceLenders = [];
                        #resourceScopeExited = false;

                        #subtasks = [];

                        // Threads owned by this task, indexed by their task-scoped
                        // thread id (see AsyncThread -- index 0 is always the task's
                        // implicit thread, created alongside it).
                        #threads = [];

                        #entered = false;
                        #exited = false;
                        #errored = null;

                        cancelled = false;
                        cancelRequested = false;
                        alwaysTaskReturn = false;

                        returnCalls =  0;
                        tmpRetI64HighBits = 0|0;

                        constructor(opts) {{
                           this.#id = ++{task_class}._ID;
                           this.#resourceScopeId = ++{resource_scope_counter};
                           {resource_scope_tasks}.set(this.#resourceScopeId, this);

                           if (opts?.componentIdx === undefined) {{
                               throw new TypeError('missing component id during task creation');
                           }}
                           this.#componentIdx = opts.componentIdx;

                           this.#state = {task_class}.State.INITIAL;
                           this.#isAsync = opts?.isAsync ?? false;
                           this.#isManualAsync = opts?.isManualAsync ?? false;
                           this.#preserveFutureResult = opts?.preserveFutureResult ?? false;
                           this.#entryFnName = opts.entryFnName;
                           // Tasks that execute guest slices (export calls, fused
                           // callees) default to true; import-handler tasks pass false
                           // explicitly (they run host code nested inside the caller's
                           // already-locked slice).
                           this.#callingWasmExport = opts?.callingWasmExport !== false;

                           const {{
                               promise: completionPromise,
                               resolve: resolveCompletionPromise,
                               reject: rejectCompletionPromise,
                           }} = {promise_with_resolvers_fn}();
                           this.#completionPromise = completionPromise;
                           // A nested rejection can reach the root task while its Wasm
                           // entrypoint is still suspended, before the export wrapper awaits
                           // this promise. Mark it handled immediately while preserving the
                           // original rejected promise for the eventual caller.
                           completionPromise.catch(() => {{}});

                           let completionSettled = false;
                           const settleCompletionPromise = () => {{
                               if (completionSettled || !this.#completionReady) {{ return; }}
                               completionSettled = true;
                               if (this.#errored !== null) {{
                                   rejectCompletionPromise(this.#errored);
                               }} else if (this.#rejected) {{
                                   rejectCompletionPromise(this.#completionValue);
                               }} else if (
                                   this.#preserveFutureResult
                                   && this.#completionValue instanceof {future_value_class}
                               ) {{
                                   this.#completionValue.resolveAsValue(resolveCompletionPromise);
                               }} else {{
                                   resolveCompletionPromise(this.#completionValue);
                               }}
                           }};

                           this.#settleCompletionPromise = settleCompletionPromise;
                           this.#onResolveHandlers.push((results) => {{
                               if (this.#parentSubtask !== null) {{ return; }}
                               if (!this.#isAsync && !this.#isManualAsync) {{ return; }}
                               this.#completionValue = results;
                               this.#completionReady = true;
                               // Publish after the current guest slice returns, so a trap
                               // in that slice can still reject the call. Do not wait for
                               // task exit: detached work may require further host calls
                               // or consumption of a returned resource's stream.
                           }});

                           const {{
                               promise: exitPromise,
                               resolve: resolveExitPromise,
                               reject: rejectExitPromise,
                           }} = {promise_with_resolvers_fn}();
                           this.#exitPromise = exitPromise;

                           this.#onExitHandlers.push(() => {{
                               if (this.#parentSubtask === null && (this.#isAsync || this.#isManualAsync)) {{
                                   settleCompletionPromise();
                               }}
                               resolveExitPromise();
                           }});

                           if (opts.callbackFn) {{ this.#callbackFn = opts.callbackFn; }}
                           if (opts.callbackFnName) {{ this.#callbackFnName = opts.callbackFnName; }}

                           if (opts.getCalleeParamsFn) {{ this.#getCalleeParamsFn = opts.getCalleeParamsFn; }}
                           if (opts.stringEncoding) {{ this.#stringEncoding = opts.stringEncoding; }}

                           if (opts.parentSubtask) {{ this.#parentSubtask = opts.parentSubtask; }}


                           if (opts.errHandling) {{ this.#errHandling = opts.errHandling; }}
                        }}

                        taskState() {{ return this.#state; }}
                        id() {{ return this.#id; }}
                        componentIdx() {{ return this.#componentIdx; }}
                        entryFnName() {{ return this.#entryFnName; }}

                        resourceScopeId() {{ return this.#resourceScopeId; }}

                        addBorrowedHandle() {{
                            if (this.#resourceScopeExited) {{
                                throw new Error('cannot add a borrow to an exited resource scope');
                            }}
                            this.#resourceBorrowCount++;
                        }}

                        removeBorrowedHandle() {{
                            if (this.#resourceBorrowCount === 0) {{
                                throw new Error('resource borrow count underflow');
                            }}
                            this.#resourceBorrowCount--;
                        }}

                        addResourceLender(table, handle) {{
                            if (this.#resourceScopeExited) {{
                                throw new Error('cannot add a lender to an exited resource scope');
                            }}
                            this.#resourceLenders.push({{ table, handle }});
                        }}

                        validateResourceBorrowScope() {{
                            if (this.#resourceScopeExited) {{ return; }}
                            if (this.#resourceBorrowCount !== 0) {{
                                throw new {runtime_error_class}('borrow handles still remain at the end of the call');
                            }}
                            for (const {{ table, handle }} of this.#resourceLenders) {{
                                const idx = handle << 1;
                                const lendCount = table[idx];
                                if (!Number.isInteger(lendCount) || lendCount <= 0 || lendCount >= 2**30) {{
                                    throw new Error('invalid resource lender state at scope exit');
                                }}
                                table[idx] = lendCount - 1;
                            }}
                            this.#resourceLenders = [];
                            this.#resourceScopeExited = true;
                            {resource_scope_tasks}.delete(this.#resourceScopeId);
                        }}

                        completionPromise() {{ return this.#completionPromise; }}
                        settleCompletion() {{ this.#settleCompletionPromise(); }}
                        exitPromise() {{ return this.#exitPromise; }}

                        waitForProgress() {{
                            const {{ promise, resolve }} = {promise_with_resolvers_fn}();
                            this.#progressWaiters.push(resolve);
                            return promise;
                        }}

                        notifyProgress() {{
                            const waiters = this.#progressWaiters;
                            this.#progressWaiters = [];
                            for (const resolve of waiters) {{ resolve(); }}
                        }}

                        isAsync() {{ return this.#isAsync; }}
                        isManualAsync() {{ return this.#isManualAsync; }}
                        isSync() {{ return !this.isAsync(); }}

                        getErrHandling() {{ return this.#errHandling; }}

                        hasCallback() {{ return this.#callbackFn !== null; }}

                        getReturnMemoryIdx() {{ return this.#memoryIdx; }}
                        setReturnMemoryIdx(idx) {{
                            if (idx === null) {{ return; }}
                            this.#memoryIdx = idx;
                        }}

                        getReturnMemory() {{ return this.#memory; }}
                        setReturnMemory(m) {{
                            if (m === null) {{ return; }}
                            this.#memory = m;
                        }}

                        setReturnLowerFns(fns) {{ this.#returnLowerFns = fns; }}
                        getReturnLowerFns() {{ return this.#returnLowerFns; }}

                        calleeIsAsync() {{ return this.#calleeIsAsync === true; }}

                        setCalleeIsAsync(value) {{
                            if (typeof value !== 'boolean') {{ throw new TypeError('callee async state must be a boolean'); }}
                            this.#calleeIsAsync = value;
                        }}

                        setParentSubtask(subtask) {{
                            if (!subtask || !(subtask instanceof {subtask_class})) {{ return }}
                            if (this.#parentSubtask) {{ throw new Error('parent subtask can only be set once'); }}
                            this.#parentSubtask = subtask;
                        }}

                        getParentSubtask() {{ return this.#parentSubtask; }}

                        // Registers a newly-created thread as belonging to this task
                        // and assigns it its real, *component-instance-scoped* id
                        // (`Task.register_thread` in the canonical ABI) -- threads
                        // are addressed instance-wide (not per-task) so that a
                        // thread of one task can target a thread of another, e.g.
                        // via `thread.resume-later`.
                        addThread(thread) {{
                            // Host (-1) tasks model host-side import handling: there is no
                            // component instance behind them, so no instance thread table to
                            // register with (and none may be materialised on their behalf).
                            if (this.#componentIdx === -1) {{
                                thread.setId(++{task_class}._HOST_THREAD_ID);
                                this.#threads.push(thread);
                                return thread;
                            }}
                            const cstate = {get_or_create_async_state_fn}(this.#componentIdx);
                            thread.setId(cstate.threads.insert(thread));
                            this.#threads.push(thread);
                            return thread;
                        }}

                        #checkThreadExit() {{
                            if (this.#threads.length === 1 && !this.isResolvedState() && !this.isRejected()) {{
                                const err = new {runtime_error_class}(`(component [${{this.#componentIdx}}]) task [${{this.#id}}] exited without resolution`);
                                throw this.#componentIdx === -1 ? err : {record_trap_fn}(this.#componentIdx, err);
                            }}
                        }}

                        // Unregisters a thread that has finished running
                        // (`Task.unregister_thread`), freeing its instance-scoped id.
                        removeThread(thread) {{
                            this.#checkThreadExit();
                            this.settleCompletion();
                            if (this.#componentIdx !== -1) {{
                                const cstate = {get_or_create_async_state_fn}(this.#componentIdx);
                                cstate.threads.remove(thread.id());
                            }}
                            this.#threads = this.#threads.filter(t => t !== thread);
                            if (this.#exited && this.#threads.length === 0) {{
                                {clear_current_task_fn}(this.#componentIdx, this.#id);
                            }}
                        }}

                        // The thread created alongside this task (always the first
                        // one registered). Used by task-level callback dispatch and
                        // exit cleanup, which operate on the task rather than an
                        // explicitly identified thread.
                        defaultThread() {{ return this.#threads[0]; }}

                        // TODO(threads): this is very inefficient, we can pass along a root task,
                        // and ideally do not need this once thread support is in place
                        getRootTask() {{
                            let currentSubtask = this.getParentSubtask();
                            let task = this;
                            while (currentSubtask) {{
                                task = currentSubtask.getParentTask();
                                currentSubtask = task.getParentSubtask();
                            }}
                            return task;
                        }}

                        setPostReturnFn(f) {{
                            if (!f) {{ return; }}
                            if (this.#postReturnFn) {{ throw new Error('postReturn fn can only be set once'); }}
                            this.#postReturnFn = f;
                        }}

                        setCallbackFn(f, name) {{
                            if (!f) {{ return; }}
                            if (this.#callbackFn) {{ throw new Error('callback fn can only be set once'); }}
                            this.#callbackFn = f;
                            this.#callbackFnName = name;
                        }}

                        getCallbackFnName() {{
                            if (!this.#callbackFnName) {{ return undefined; }}
                            return this.#callbackFnName;
                        }}

                        runCallbackFn(...args) {{
                            if (!this.#callbackFn) {{ throw new Error('no callback function has been set for task'); }}
                            if (this.#callbackFn._jcoMaySuspend === false) {{
                                return {with_global_current_thread_meta_fn}({{
                                    taskID: this.#id,
                                    threadID: this.defaultThread().id(),
                                    componentIdx: this.#componentIdx,
                                    fn: () => this.#callbackFn.apply(null, args),
                                }});
                            }}
                            return {with_global_current_thread_meta_async_fn}({{
                                taskID: this.#id,
                                threadID: this.defaultThread().id(),
                                componentIdx: this.#componentIdx,
                                fn: () => {{ return this.#callbackFn.apply(null, args); }}
                            }});
                        }}

                        getCalleeParams() {{
                            if (!this.#getCalleeParamsFn) {{ throw new Error('missing/invalid getCalleeParamsFn'); }}
                            return this.#getCalleeParamsFn();
                        }}

                        // Legacy manually-async exports are sync-typed in the component
                        // but use JSPI precisely so their guest stack may suspend.
                        // Canonical ABI: only sync-typed callees may not block (`canon_lift`);
                        // an async-lifted callee may, even when called through a sync lowering.
                        mayBlock() {{ return this.isAsync() || this.isManualAsync() || this.isResolvedState() || this.#funcTypeIsAsync }}
                        // (an async-typed function may block however it was lifted)
                        setFuncTypeIsAsync(v) {{ this.#funcTypeIsAsync = v; }}
                        // The interned result type of the task's function (checked by `task.return`)
                        setReturnResultTypeIdx(v) {{ this.#returnResultTypeIdx = v; }}
                        returnResultTypeIdx() {{ return this.#returnResultTypeIdx; }}

                        mayEnter(task) {{
                            const cstate = {get_or_create_async_state_fn}(this.#componentIdx);
                            if (cstate.hasBackpressure()) {{
                                {debug_log_fn}('[{task_class}#mayEnter()] disallowed due to backpressure', {{ taskID: this.#id }});
                                return false;
                            }}
                            if (!cstate.callingSyncImport()) {{
                                {debug_log_fn}('[{task_class}#mayEnter()] disallowed due to sync import call', {{ taskID: this.#id }});
                                return false;
                            }}
                            const callingSyncExportWithSyncPending = cstate.callingSyncExport && !task.isAsync;
                            if (!callingSyncExportWithSyncPending) {{
                                {debug_log_fn}('[{task_class}#mayEnter()] disallowed due to sync export w/ sync pending', {{ taskID: this.#id }});
                                return false;
                            }}
                            return true;
                        }}

                        enterSync() {{
                            if (this.needsExclusiveLock()) {{
                                const cstate = {get_or_create_async_state_fn}(this.#componentIdx);
                                if (!cstate.isExclusivelyLocked()) {{
                                    cstate.exclusiveLock(this.#id);
                                }} else {{
                                    // A host-called sync export arriving while another
                                    // task's slice holds the lock: synchronous entry
                                    // cannot wait, and historically this entry silently
                                    // stole the hold. Run without the lock instead --
                                    // the holder's bookkeeping stays intact and its
                                    // release still pairs
                                    this.#lockFreeEntry = true;
                                    {debug_log_fn}('[{task_class}#enterSync()] entering without exclusive lock', {{
                                        taskID: this.#id,
                                        componentIdx: this.#componentIdx,
                                    }});
                                }}
                            }}
                            return true;
                        }}

                        tryEnter() {{
                            if (this.#entered) {{
                                throw new Error(`task with ID [${{this.#id}}] should not be entered twice`);
                            }}

                            if (this.deliverPendingCancel({{ cancellable: true }})) {{
                                this.cancel();
                                return false;
                            }}

                            const cstate = {get_or_create_async_state_fn}(this.#componentIdx);
                            if (this.isSync()) {{
                                this.#entered = true;
                                return true;
                            }}
                            if (cstate.hasBackpressure()) {{ return null; }}
                            // Entries already queued for this instance go first.
                            if (cstate.hasPendingAdmissions()) {{ return null; }}
                            if (this.needsExclusiveLock()) {{
                                if (cstate.isExclusivelyLocked()) {{ return null; }}
                                cstate.exclusiveLock(this.#id);
                            }}

                            if (this.deliverPendingCancel({{ cancellable: true }})) {{
                                cstate.exclusiveRelease(this.#id);
                                this.cancel();
                                return false;
                            }}

                            this.#entered = true;
                            return true;
                        }}

                        enterHost() {{
                            if (this.#entered) {{
                                throw new Error(`task with ID [${{this.#id}}] should not be entered twice`);
                            }}

                            // If cancellation was requested before the task was entered, resolve
                            // as cancelled without ever running host code
                            if (this.deliverPendingCancel({{ cancellable: true }})) {{
                                this.cancel();
                                return false;
                            }}

                            {get_or_create_async_state_fn}(this.#componentIdx);

                            this.#entered = true;
                            // A guest task may be synchronously blocked in this
                            // host entry. Propagate that boundary so an async
                            // cancellation driver can yield BLOCKED while the host
                            // operation is outstanding.
                            const parentTask = this.#parentSubtask?.getParentTask();
                            if (
                                parentTask?.taskState() === {task_class}.State.CANCEL_DELIVERED
                                || (parentTask && !parentTask.hasCallback())
                            ) {{
                                parentTask.notifyProgress();
                            }}
                            return this.#entered;
                        }}

                        async enter(opts) {{
                            {debug_log_fn}('[{task_class}#enter()] args', {{
                                taskID: this.#id,
                                componentIdx: this.#componentIdx,
                                subtaskID: this.getParentSubtask()?.id(),
                                args: opts,
                                entryFnName: this.#entryFnName,
                            }});

                            if (opts?.isHost) {{ return this.enterHost(); }}

                            if (this.#entered) {{
                                throw new Error(`task with ID [${{this.#id}}] should not be entered twice`);
                            }}

                            // If cancellation was requested before the task was entered, resolve
                            // as cancelled without ever running guest code
                            if (this.deliverPendingCancel({{ cancellable: true }})) {{
                                this.cancel();
                                return false;
                            }}

                            const cstate = {get_or_create_async_state_fn}(this.#componentIdx);

                            // NOTE: concurrent task lifetimes within one component instance are
                            // permitted by the Component Model: entry is governed by the
                            // backpressure and exclusive-lock checks below (the lock is held per
                            // execution slice, not for the task's lifetime).
                            //
                            // Serializing entire task lifetimes here (the former "execution slot" queue)
                            // deadlocks pipelines where a parked long-lived task's progress depends on a
                            // later entry into the same component.

                            // If a task is synchronous then we can avoid component-relevant
                            // tracking and immediately enter.
                            if (this.isSync()) {{
                                this.#entered = true;

                                // TODO(breaking): remove once manually-specifying async fns is removed
                                // It is currently possible for an actually sync export to be specified
                                // as async via JSPI
                                if (this.#isManualAsync) {{
                                    if (this.needsExclusiveLock()) {{ await cstate.acquireExclusiveLock(this.#id); }}
                                }}

                                return this.#entered;
                            }}

                            // Enter in the order the calls were made: queue behind every
                            // earlier entry into this instance, whatever it waits for.
                            const ticket = cstate.takeAdmissionTicket(this.#id);
                            this.#admissionTicket = ticket;
                            let entered = false;
                            try {{
                                entered = await this.#enterQueued(cstate, ticket);
                                return entered;
                            }} finally {{
                                // An entered task keeps the slot until its first slice ends
                                // (`endFirstSlice`): the next call is admitted once this one
                                // returned, blocked or trapped, as `Store.invoke` runs a call.
                                if (!entered) {{ this.endFirstSlice(); }}
                            }}
                        }}

                        // The first slice of this task ended (it returned, blocked or trapped):
                        // the next entry into the instance may be admitted (Canonical ABI
                        // `Store.invoke` runs a call until it first blocks or returns).
                        endFirstSlice() {{
                            const ticket = this.#admissionTicket;
                            if (ticket === null) {{ return; }}
                            this.#admissionTicket = null;
                            {get_or_create_async_state_fn}(this.#componentIdx).releaseAdmissionTicket(ticket);
                        }}

                        async #enterQueued(cstate, ticket) {{
                            await cstate.waitForAdmissionTurn(ticket);
                            // Cancelled before it started while it was queued: the task was
                            // retired already and must not park in a wait as a dead entry.
                            if (this.isResolvedState() || this.isCancelled()) {{ return false; }}

                            // Wait until there is no backpressure *and* the exclusive lock (if
                            // needed) is ours. Backpressure can be set while we wait for the
                            // lock (by the task holding it), so it's checked again once the lock
                            // is acquired, as the Canonical ABI's `enter_implicit_thread` waits
                            // for both together.
                            while (true) {{
                                if (cstate.hasBackpressure()) {{
                                    cstate.addBackpressureWaiter();

                                    const result = await this.waitUntil({{
                                        readyFn: () => {{
                                            return !cstate.hasBackpressure();
                                        }},
                                        cancellable: true,
                                    }});

                                    cstate.removeBackpressureWaiter();

                                    if (!result || this.isCancelled()) {{
                                        if (!this.isResolvedState()) {{ this.cancel(); }}
                                        return false;
                                    }}
                                }}

                                // Acquire the per-slice exclusive lock (FIFO-queued when
                                // contended); the first slice runs under this hold and the
                                // driver loop releases/re-acquires it per slice thereafter.
                                if (this.needsExclusiveLock()) {{
                                    await cstate.acquireExclusiveLock(this.#id);
                                    if (cstate.hasBackpressure()) {{
                                        cstate.exclusiveRelease(this.#id);
                                        continue;
                                    }}
                                }}
                                break;
                            }}

                            // The store may have trapped (e.g. a deadlock was detected) while
                            // this task waited to enter: it must not run, and its call fails
                            // with that trap.
                            try {{
                                cstate.throwIfInterrupted();
                            }} catch (err) {{
                                cstate.exclusiveRelease(this.#id);
                                this.setErrored(err);
                                return false;
                            }}

                            // Cancellation-before-start may resolve this task while its
                            // queued lock acquisition is still pending. Acquiring the lock
                            // does not make the already-resolved task runnable again.
                            if (this.isResolvedState() || this.isCancelled()) {{
                                cstate.exclusiveRelease(this.#id);
                                return false;
                            }}

                            // Cancellation can be requested while entry is waiting for
                            // backpressure or its exclusive lock. Do not execute the guest
                            // after acquiring a lock for a task that should no longer start.
                            if (this.deliverPendingCancel({{ cancellable: true }})) {{
                                cstate.exclusiveRelease(this.#id);
                                this.cancel();
                                return false;
                            }}

                            this.#entered = true;
                            return this.#entered;
                        }}

                        isRunningState() {{ return this.#state !== {task_class}.State.RESOLVED; }}
                        isResolvedState() {{ return this.#state === {task_class}.State.RESOLVED; }}
                        isResolved() {{ return this.#state === {task_class}.State.RESOLVED; }}
                        isExited() {{ return this.#exited; }}

                        async waitUntil(opts) {{
                            const {{ readyFn, cancellable }} = opts;
                            {debug_log_fn}('[{task_class}#waitUntil()] args', {{ taskID: this.#id, args: {{ cancellable }} }});

                            // TODO(fix): check for cancel
                            // TODO(fix): determinism

                            const keepGoing = await this.suspendUntil({{
                                readyFn,
                                cancellable,
                            }});

                            return keepGoing;
                        }}

                        async yieldUntil(opts) {{
                            const {{ readyFn, cancellable }} = opts;
                            {debug_log_fn}('[{task_class}#yieldUntil()]', {{
                                taskID: this.#id,
                                args: {{
                                    cancellable,
                                }},
                                componentIdx: this.#componentIdx,
                            }});

                            // A callback YIELD is an explicit request to let other work run.
                            // Unlike waits whose condition is already ready, it must always
                            // suspend for at least one scheduler turn.
                            const keepGoing = await this.immediateSuspend({{ readyFn, cancellable }});
                            if (keepGoing) {{
                                return {{
                                    code: {event_code_enum}.NONE,
                                    payload0: 0,
                                    payload1: 0,
                                }};
                            }}

                            return {{
                                code: {event_code_enum}.TASK_CANCELLED,
                                payload0: 0,
                                payload1: 0,
                            }};
                        }}

                        async suspendUntil(opts) {{
                            const {{ cancellable, readyFn }} = opts;
                            {debug_log_fn}('[{task_class}#suspendUntil()] args', {{
                                taskID: this.#id,
                                args: {{
                                    cancellable,
                                }},
                                componentIdx: this.#componentIdx,
                            }});

                            const pendingCancelled = this.deliverPendingCancel({{ cancellable }});
                            if (pendingCancelled) {{ return false; }}

                            const completed = await this.immediateSuspendUntil({{ readyFn, cancellable }});
                            return completed;
                        }}

                        suspendUntilCallback(opts, onResume) {{
                            const {{ cancellable, readyFn }} = opts;
                            if (this.deliverPendingCancel({{ cancellable }})) {{
                                onResume(false);
                                return;
                            }}

                            const cstate = {get_or_create_async_state_fn}(this.#componentIdx);
                            cstate.suspendTask({{
                                task: this,
                                cancellable,
                                readyFn: () => {{
                                    if (cancellable && this.#state === {task_class}.State.CANCEL_PENDING) {{
                                        return true;
                                    }}
                                    return readyFn();
                                }},
                                onResume: (keepGoing) => {{
                                    if (keepGoing && this.deliverPendingCancel({{ cancellable }})) {{
                                        keepGoing = false;
                                    }}
                                    onResume(keepGoing);
                                }},
                            }});
                        }}

                        // TODO(threads): equivalent to thread.suspend_until()
                        async immediateSuspendUntil(opts) {{
                            const {{ cancellable, readyFn }} = opts;
                            {debug_log_fn}('[{task_class}#immediateSuspendUntil()] args', {{
                                args: {{
                                    cancellable,
                                    readyFn,
                                }},
                                taskID: this.#id,
                                componentIdx: this.#componentIdx,
                            }});

                            const ready = readyFn();
                            if (ready && {global_async_determinism} === 'random') {{
                                const coinFlip = {coin_flip_fn}();
                                if (coinFlip) {{ return true }}
                            }}

                            const keepGoing = await this.immediateSuspend({{ cancellable, readyFn }});
                            return keepGoing;
                        }}

                        async immediateSuspend(opts) {{
                            // Entry can wait on backpressure before a guest register window exists.
                            const cstate = {get_or_create_async_state_fn}(this.#componentIdx);
                            const thread = this.#entered
                                ? cstate.threads.get({get_global_current_thread_meta_fn}(this.#componentIdx).threadID)
                                : this.defaultThread();
                            if (!thread || thread.task() !== this) {{ throw new Error('invalid current thread for wait'); }}
                            // Suspending a core Wasm stack retains the task's exclusive
                            // lock. Only a callback return releases it between slices.
                            return thread.suspend({{ ...opts, releaseLock: false }});
                        }}

                        deliverPendingCancel(opts) {{
                            const {{ cancellable }} = opts;
                            {debug_log_fn}('[{task_class}#deliverPendingCancel()]', {{
                                args: {{ cancellable }},
                                taskID: this.#id,
                                componentIdx: this.#componentIdx,
                            }});

                            if (cancellable && this.#state === {task_class}.State.CANCEL_PENDING) {{
                                this.#state = {task_class}.State.CANCEL_DELIVERED;
                                return true;
                            }}

                            return false;
                        }}

                        isCancelled() {{ return this.cancelled }}
                        cancellationRequested() {{ return this.cancelRequested; }}
                        cancellationPending() {{ return this.#state === {task_class}.State.CANCEL_PENDING; }}

                        // Request cooperative cancellation of this task, called on behalf of a
                        // supertask performing `subtask.cancel` on the subtask this task backs.
                        //
                        // The request is delivered at this task's next cancellable wait
                        // (see suspendUntil/immediateSuspend), at which point the task is
                        // expected to acknowledge via `task.cancel` or still resolve via
                        // `task.return`.
                        requestCancellation() {{
                            {debug_log_fn}('[{task_class}#requestCancellation()] args', {{
                                taskID: this.#id,
                                componentIdx: this.#componentIdx,
                                state: this.#state,
                            }});
                            if (this.isResolvedState() || this.cancelRequested) {{ return; }}
                            this.cancelRequested = true;
                            if (this.#state === {task_class}.State.INITIAL) {{
                                this.#state = {task_class}.State.CANCEL_PENDING;
                                // A task still waiting for backpressure or its
                                // initial instance lock has no guest thread to
                                // resume. Cancellation is therefore delivered
                                // and acknowledged eagerly as
                                // CANCELLED_BEFORE_STARTED.
                                if (!this.#entered) {{
                                    this.deliverPendingCancel({{ cancellable: true }});
                                    this.cancel();

                                    const cstate = {get_or_create_async_state_fn}(this.#componentIdx);
                                    // `enter()` may already be parked either in the scheduler's
                                    // explicit-backpressure wait or in the exclusive-lock FIFO.
                                    // Wake/remove that entry work now so it cannot retain a timer,
                                    // waiter count, or lock-queue slot after cancellation.
                                    cstate.resumeTaskByID(this.#id);
                                    cstate.cancelExclusiveLockWaiter(this.#id);

                                    // No guest thread was registered, so no driver loop will call
                                    // `exit()`. Retire the task's JS bookkeeping explicitly.
                                    this.exit({{ skipExclusiveLockCheck: true }});
                                    return;
                                }}
                            }}
                            // Nudge the component's tick loop so that any suspended cancellable
                            // wait observes the pending cancellation promptly
                            {get_or_create_async_state_fn}(this.#componentIdx).runTickLoop();
                        }}

                        cancel(args) {{
                            {debug_log_fn}('[{task_class}#cancel()] args', {{ }});
                            if (this.taskState() !== {task_class}.State.CANCEL_DELIVERED) {{
                                throw new Error('`task.cancel` called by task which has not been cancelled');
                            }}
                            this.validateResourceBorrowScope();
                            this.cancelled = true;
                            // Cancelled tasks resolve with no value (spec: `Task.cancel` calls
                            // `on_resolve(None)`); an explicit error is only present on the
                            // host-driven rejection path (see `reject()`).
                            this.onResolve(args?.error ?? null);
                            this.#state = {task_class}.State.RESOLVED;
                            // A task cancelled before entry has no driver loop that can
                            // report its exit. Entered tasks notify after releasing their
                            // component slice in `exit()`.
                            if (!this.#entered) {{ this.notifyProgress(); }}
                        }}

                        onResolve(taskValue) {{
                            const handlers = this.#onResolveHandlers;
                            this.#onResolveHandlers = [];
                            for (const f of handlers) {{
                                try {{
                                    f(taskValue);
                                }} catch (err) {{
                                    {debug_log_fn}("[{task_class}#onResolve] error during task resolve handler", err);
                                    throw err;
                                }}
                            }}

                            // Rejections are control-flow failures, not canonical ABI results.
                            // Propagate them through the subtask chain without running return
                            // lowering or post-return hooks for a successful result.
                            if (this.#rejected) {{
                                this.#parentSubtask?.reject(taskValue);
                                return;
                            }}

                            // NOTE: if the parent subtask has already been resolved (e.g. it was
                            // cancelled via `subtask.cancel` while this task was still pending),
                            // this task's resolution must be discarded rather than delivered.
                            const parentSubtaskPending = this.#parentSubtask && !this.#parentSubtask.isResolved();
                            const taskReturned = !this.isCancelled();

                            if (parentSubtaskPending && taskReturned) {{
                                const meta = this.#parentSubtask.getCallMetadata();
                                // Run the rturn fn if it has not already been called -- this *should* have happened in
                                // `task.return`, but some paths do not go through task.return (e.g. async lower of sync fn
                                // which goes through prepare + async-start-call)
                                if (meta.returnFn && !meta.returnFnCalled) {{
                                    {debug_log_fn}('[{task_class}#onResolve()] running returnFn', {{
                                        componentIdx: this.#componentIdx,
                                        taskID: this.#id,
                                        subtaskID: this.#parentSubtask.id(),
                                    }});
                                    const callerTask = this.#parentSubtask.getParentTask();
                                    {with_global_current_thread_meta_fn}({{
                                        taskID: callerTask.id(),
                                        threadID: meta.callerThreadID,
                                        componentIdx: callerTask.componentIdx(),
                                        fn: () => meta.returnFn.apply(null, [taskValue, meta.resultPtr]),
                                    }});
                                    meta.returnFnCalled = true;
                                }}
                            }}

                            if (this.#postReturnFn && taskReturned) {{
                                {debug_log_fn}('[{task_class}#onResolve()] running post return ', {{
                                    componentIdx: this.#componentIdx,
                                    taskID: this.#id,
                                }});
                                try {{
                                    {with_global_current_thread_meta_fn}({{
                                        taskID: this.#id,
                                        threadID: this.defaultThread().id(),
                                        componentIdx: this.#componentIdx,
                                        fn: () => this.#postReturnFn(taskValue),
                                    }});
                                }} catch (err) {{
                                    err = {post_return_trap_fn}(this.#componentIdx, err);
                                    this.reject(err);
                                    throw err;
                                }}
                            }}

                            if (parentSubtaskPending) {{
                                this.#parentSubtask.onResolve(taskValue);
                            }}
                        }}

                        registerOnResolveHandler(f) {{
                            this.#onResolveHandlers.push(f);
                        }}

                        isRejected() {{ return this.#rejected; }}

                        isErrored() {{ return this.#errored; }}
                        setErrored(err) {{
                            // Preserve the originating trap when unwinding through
                            // additional guest frames produces secondary traps (often
                            // an `unreachable` after a call which was expected to trap).
                            if (this.#errored === null) {{ this.#errored = err; }}
                        }}

                        reject(taskErr) {{
                            {debug_log_fn}('[{task_class}#reject()] args', {{
                                componentIdx: this.#componentIdx,
                                taskID: this.#id,
                                parentSubtask: this.#parentSubtask,
                                parentSubtaskID: this.#parentSubtask?.id(),
                                entryFnName: this.entryFnName(),
                                callbackFnName: this.#callbackFnName,
                                errMsg: taskErr.message,
                            }});

                            this.setErrored(taskErr);
                            if (this.#rejected) {{ return; }}

                            // A task may call `task.return` before its callback exits.
                            // A trap in cleanup or spawned work must still reject the
                            // host call and poison the enclosing task chain.
                            if (this.isResolvedState()) {{
                                this.#rejected = true;
                                this.#errored = taskErr;
                                const parentTask = this.#parentSubtask?.getParentTask();
                                if (parentTask) {{ parentTask.reject(taskErr); }}
                                return;
                            }}

                            this.#rejected = true;
                            this.cancelRequested = true;
                            this.#state = {task_class}.State.CANCEL_PENDING;
                            const cancelled = this.deliverPendingCancel({{ cancellable: true }});

                            // TODO: do cleanup here to reset the machinery so we can run again?

                            this.cancel({{ error: taskErr }});
                        }}

                        resolve(results) {{
                            {debug_log_fn}('[{task_class}#resolve()] args', {{
                                componentIdx: this.#componentIdx,
                                taskID: this.#id,
                                entryFnName: this.entryFnName(),
                                callbackFnName: this.#callbackFnName,
                            }});

                            if (this.#state === {task_class}.State.RESOLVED) {{
                                if (this.#errored !== null) {{ throw this.#errored; }}
                                throw new Error(`(component [${{this.#componentIdx}}]) task [${{this.#id}}]  is already resolved (did you forget to wait for an import?)`);
                            }}

                            this.validateResourceBorrowScope();

                            this.#state = {task_class}.State.RESOLVED;

                            switch (results.length) {{
                                case 0:
                                    this.onResolve(undefined);
                                    break;
                                case 1:
                                    this.onResolve(results[0]);
                                    break;
                                default:
                                    {debug_log_fn}('[{task_class}#resolve()] unexpected number of results', {{
                                        componentIdx: this.#componentIdx,
                                        results,
                                        taskID: this.#id,
                                        subtaskID: this.#parentSubtask?.id(),
                                        entryFnName: this.#entryFnName,
                                        callbackFnName: this.#callbackFnName,
                                    }});
                                    throw new Error('unexpected number of results');
                            }}
                        }}

                        exit(args) {{
                            {debug_log_fn}('[{task_class}#exit()]', {{
                                componentIdx: this.#componentIdx,
                                taskID: this.#id,
                            }});

                            this.endFirstSlice();
                            if (this.#exited)  {{ throw new Error("task has already exited"); }}

                            // Validate before publishing exit or running its handlers.
                            // Otherwise a failed exit leaves #exited true, so the driver
                            // cannot finish rejection cleanup and settle the host call.
                            this.#checkThreadExit();
                            this.validateResourceBorrowScope();

                            // Host (-1) tasks have no component instance (and so no async
                            // state or exclusive lock); do not materialise one for them.
                            const state = this.#componentIdx === -1
                                ? null
                                : {get_or_create_async_state_fn}(this.#componentIdx);
                            if (!state && this.#componentIdx !== -1) {{
                                throw new Error('missing async state for component [' + this.#componentIdx + ']');
                            }}

                            if (state && !args?.skipExclusiveLockCheck && !this.#lockFreeEntry) {{
                                if (this.needsExclusiveLock() && !state.exclusivelyLockedBy(this.#id)) {{
                                    throw new Error(`task [${{this.#id}}] exit: component [${{this.#componentIdx}}] should have been exclusively locked by it`);
                                }}
                            }}

                            // Ownership-checked: releases only this task's own hold (a
                            // task exiting while another task's slice holds the lock no
                            // longer clears the foreign hold).
                            if (state) {{ state.exclusiveRelease(this.#id); }}
                            this.notifyProgress();

                            for (const f of this.#onExitHandlers) {{
                                try {{
                                    f();
                                }} catch (err) {{
                                    console.error("error during task exit handler", err);
                                    throw err;
                                }}
                            }}

                            this.#exited = true;
                            this.removeThread(this.defaultThread());
                            if (this.#threads.length > 0) {{
                                {clear_current_task_fn}(this.#componentIdx, this.#id, {{ preserveTask: true }});
                            }}
                        }}

                        needsExclusiveLock() {{
                            // Host (-1) tasks model host-side import handling: there is no
                            // guest linear memory or executor state to protect, and host
                            // calls from unrelated guest components would contend spuriously.
                            if (this.#componentIdx === -1) {{ return false; }}
                            // Import-handler tasks (CallInterface) run host code nested
                            // inside the calling guest slice, which already holds the
                            // lock; only tasks that execute guest slices need it.
                            if (!this.#callingWasmExport) {{ return false; }}
                            // Automatic backpressure only applies to async function
                            // types. A sync-typed call may run ready callback threads
                            // before returning, so holding this lock would deadlock it.
                            if (!this.#funcTypeIsAsync) {{ return false; }}
                            // A sync-lifted callee cannot be reentered until the whole
                            // stackful call returns. This is the Component Model's
                            // automatic-backpressure rule for async-lowered calls.
                            return !this.#isAsync || this.hasCallback() || this.#calleeIsAsync === false;
                        }}

                        createSubtask(args) {{
                            {debug_log_fn}('[{task_class}#createSubtask()] args', args);
                            const {{ componentIdx, childTask, callMetadata, fnName, isAsync, isManualAsync }} = args;

                            const cstate = {get_or_create_async_state_fn}(this.#componentIdx);
                            if (!cstate) {{
                                throw new Error(`invalid/missing async state for component idx [${{componentIdx}}]`);
                            }}

                            const waitable = new {waitable_class}({{
                                componentIdx: this.#componentIdx,
                                target: `subtask (internal ID [${{this.#id}}])`,
                            }});

                            const newSubtask = new {subtask_class}({{
                                componentIdx,
                                childTask,
                                parentTask: this,
                                callMetadata,
                                isAsync,
                                isManualAsync,
                                fnName,
                                waitable,
                            }});
                            this.#subtasks.push(newSubtask);
                            newSubtask.setTarget(`subtask (internal ID [${{newSubtask.id()}}], waitable [${{waitable.idx()}}], component [${{componentIdx}}])`);
                            // The subtask gets a handle index in this task's table only once the
                            // guest is given it (see `AsyncSubtask#ensureHandle`).
                            return newSubtask;
                        }}

                        getLatestSubtask() {{
                            return this.#subtasks.at(-1);
                        }}

                        getSubtaskByWaitableRep(rep) {{
                            if (rep === undefined) {{ throw new TypeError('missing rep'); }}
                            return this.#subtasks.find(s => s.waitableRep() === rep);
                        }}

                        currentSubtask() {{
                            {debug_log_fn}('[{task_class}#currentSubtask()]');
                            if (this.#subtasks.length === 0) {{ return undefined; }}
                            return this.#subtasks.at(-1);
                        }}

                        removeSubtask(subtask) {{
                            if (this.#subtasks.length === 0) {{
                                throw new Error('cannot end current subtask: no current subtask');
                            }}
                            this.#subtasks = this.#subtasks.filter(t => t !== subtask);
                            return subtask;
                        }}
                    }}
                "#));
            }

            Self::AsyncThreadClass => {
                let debug_log_fn = render_args.require_intrinsic(Intrinsic::DebugLog);
                let thread_class = render_args.require_intrinsic(Self::AsyncThreadClass);
                let get_or_create_async_state_fn = render_args.require_intrinsic(
                    Intrinsic::Component(ComponentIntrinsic::GetOrCreateAsyncState),
                );
                let with_global_current_thread_meta_async_fn =
                    render_args.require_intrinsic(Intrinsic::WithGlobalCurrentThreadMetaFnAsync);

                let record_trap_fn = render_args
                    .require_intrinsic(Intrinsic::Component(ComponentIntrinsic::RecordTrap));

                output.push_str(&format!(r#"
                    class {thread_class} {{
                        static State = {{
                            // Explicitly spawned (`thread.new-indirect`) threads start
                            // here; the implicit thread of a task skips straight to
                            // RUNNING since it is the task's own entry.
                            NOT_STARTED: 'not-started',
                            RUNNING: 'running',
                            COMPLETED: 'completed',
                        }}

                        // Component-instance-scoped id (the canonical ABI's
                        // `Thread.index`) -- globally unique within the instance,
                        // *not* per task, since a thread of one task may be
                        // targeted (e.g. by `thread.resume-later`) by code
                        // running in a different task of the same instance.
                        // Assigned post-construction by `Task#addThread()`, which
                        // is the only code allowed to insert into the instance's
                        // thread table.
                        #id = null;
                        #componentIdx;
                        #task;
                        #state;
                        #startFn = null;
                        storage = [0, 0];

                        constructor (opts) {{
                           if (opts?.componentIdx === undefined) {{
                               throw new TypeError('missing component id during thread creation');
                           }}
                           this.#componentIdx = opts.componentIdx;

                           if (!opts?.task) {{
                               throw new TypeError('missing task during thread creation');
                           }}
                           this.#task = opts.task;

                           // Explicitly spawned threads provide a `startFn` and begin
                           // NOT_STARTED; the task's own implicit thread has none and
                           // is already running by the time it's constructed.
                           if (opts.startFn) {{
                               this.#startFn = opts.startFn;
                               this.#state = {thread_class}.State.NOT_STARTED;
                           }} else {{
                               this.#state = {thread_class}.State.RUNNING;
                           }}
                        }}

                        id() {{ return this.#id; }}
                        setId(id) {{
                            if (this.#id !== null) {{ throw new Error('thread id can only be assigned once'); }}
                            this.#id = id;
                        }}
                        componentIdx() {{ return this.#componentIdx; }}
                        task() {{ return this.#task; }}
                        taskID() {{ return this.#task.id(); }}
                        state() {{ return this.#state; }}

                        // Delegate task-scoped bookkeeping that doesn't yet have a
                        // thread-specific notion (cancellation, progress waiters,
                        // the subtask this task is answering) to the owning task.
                        isCancelled() {{ return this.#task.isCancelled(); }}
                        isRejected() {{ return this.#task.isRejected(); }}
                        notifyProgress() {{ return this.#task.notifyProgress(); }}
                        entryFnName() {{ return this.#task.entryFnName(); }}
                        getParentSubtask() {{ return this.#task.getParentSubtask(); }}

                        async suspend(opts) {{
                            const cstate = {get_or_create_async_state_fn}(this.#componentIdx);
                            const task = this.#task;
                            task.endFirstSlice();
                            task.settleCompletion();
                            const {{ cancellable, readyFn, releaseLock = false }} = opts;
                            if (task.deliverPendingCancel({{ cancellable }})) {{ return false; }}
                            const reacquireLock = releaseLock && task.needsExclusiveLock() && cstate.exclusivelyLockedBy(task.id());
                            if (reacquireLock) {{ cstate.exclusiveRelease(task.id()); }}
                            try {{
                                const keepGoing = await cstate.suspendThread({{
                                    ...opts,
                                    thread: this,
                                    readyFn: () => (cancellable && task.cancellationPending()) || readyFn(),
                                }});
                                cstate.throwIfInterrupted();
                                if (keepGoing && task.deliverPendingCancel({{ cancellable }})) {{ return false; }}
                                return keepGoing;
                            }} finally {{
                                if (reacquireLock && !cstate.exclusivelyLockedBy(task.id())) {{
                                    await cstate.acquireExclusiveLock(task.id());
                                }}
                            }}
                        }}

                        // Begins running a NOT_STARTED (explicitly spawned) thread's
                        // start function. Runs detached -- the caller (`thread.resume-later`)
                        // does not wait for the thread to finish or even reach its first
                        // suspension point.
                        start() {{
                            if (this.#state !== {thread_class}.State.NOT_STARTED) {{
                                throw new Error(`cannot start thread [${{this.#id}}] in state [${{this.#state}}]`);
                            }}
                            this.#state = {thread_class}.State.RUNNING;
                            const startFn = this.#startFn;
                            this.#startFn = null;

                            {with_global_current_thread_meta_async_fn}({{
                                threadID: this.#id,
                                taskID: this.#task.id(),
                                componentIdx: this.#componentIdx,
                                fn: () => {{
                                    {get_or_create_async_state_fn}(this.#componentIdx).throwIfInterrupted();
                                    return startFn();
                                }},
                            }}).then(() => {{
                                this.#state = {thread_class}.State.COMPLETED;
                                this.#task.removeThread(this);
                            }}).catch((err) => {{
                                err = {record_trap_fn}(this.#componentIdx, err);
                                this.#state = {thread_class}.State.COMPLETED;
                                {debug_log_fn}('[{thread_class}#start()] spawned thread errored', {{
                                    threadID: this.#id,
                                    taskID: this.#task.id(),
                                    componentIdx: this.#componentIdx,
                                    err,
                                }});
                                this.#task.setErrored(err);
                                this.#task.reject(err);
                                this.#task.removeThread(this);
                            }});
                        }}
                    }}
                "#));
            }

            Self::AsyncSubtaskClass => {
                let runtime_error_class =
                    render_args.require_intrinsic(Intrinsic::WebAssemblyRuntimeError);
                let debug_log_fn = render_args.require_intrinsic(Intrinsic::DebugLog);
                let subtask_class = render_args.require_intrinsic(Self::AsyncSubtaskClass);
                let get_or_create_async_state_fn = render_args.require_intrinsic(
                    Intrinsic::Component(ComponentIntrinsic::GetOrCreateAsyncState),
                );
                let lookup_memories_for_component =
                    render_args.require_intrinsic(Intrinsic::LookupMemoriesForComponent);
                let dispose_host_value = render_args.require_intrinsic(Intrinsic::DisposeHostValue);

                output.push_str(&format!(r#"
                    class {subtask_class} {{
                        static _ID = 0n;

                        static State = {{
                            STARTING: 0,
                            STARTED: 1,
                            RETURNED: 2,
                            CANCELLED_BEFORE_STARTED: 3,
                            CANCELLED_BEFORE_RETURNED: 4,
                        }};

                        #id;
                        #state = {subtask_class}.State.STARTING;
                        #componentIdx;

                        #parentTask;
                        #childTask = null;

                        #dropped = false;
                        #cancelRequested = false;

                        #memoryIdx = null;
                        #lenders = null;

                        #waitable = null;

                        #callbackFn = null;
                        #callbackFnName = null;

                        #postReturnFn = null;
                        #onProgressFn = null;
                        #pendingEventFn = null;

                        #callMetadata = {{}};

                        #resolved = false;

                        #onResolveHandlers = [];
                        #onStartHandlers = [];

                        #result = null;
                        #resultSet = false;

                        // Pending value returned by a host implementation of this (async import)
                        // subtask, held so it can be disposed if the guest discards the call
                        #hostPendingResult = null;

                        fnName;
                        target;
                        isAsync;
                        isManualAsync;
                        // One execution slice awaited by the conditional cancel trampoline.
                        cancelProgress = null;

                        constructor(args) {{
                            if (typeof args.componentIdx !== 'number') {{
                                throw new Error('invalid componentIdx for subtask creation');
                            }}
                            this.#componentIdx = args.componentIdx;

                            this.#id = ++{subtask_class}._ID;
                            this.fnName = args.fnName;

                            if (!args.parentTask) {{ throw new Error('missing parent task during subtask creation'); }}
                            this.#parentTask = args.parentTask;

                            if (args.childTask) {{ this.#childTask = args.childTask; }}

                            if (args.memoryIdx) {{ this.#memoryIdx = args.memoryIdx; }}

                            if (!args.waitable) {{ throw new Error("missing/invalid waitable"); }}
                            this.#waitable = args.waitable;

                            if (args.callMetadata) {{ this.#callMetadata = args.callMetadata; }}

                            this.#lenders = [];
                            this.target = args.target;
                            this.isAsync = args.isAsync;
                            this.isManualAsync = args.isManualAsync;
                        }}

                        id() {{ return this.#id; }}
                        parentTaskID() {{ return this.#parentTask?.id(); }}
                        childTaskID() {{ return this.#childTask?.id(); }}
                        state() {{ return this.#state; }}

                        getWaitable() {{ return this.#waitable; }}
                        waitableRep() {{ return this.#waitable.idx(); }}
                        // The handle index is allocated only when the guest gets to see the
                        // subtask (an async lower that did not complete at once), and after the
                        // lifted arguments have freed theirs (Canonical ABI `canon_lower`).
                        ensureHandle() {{
                            const existing = this.#waitable.idx();
                            if (existing !== null && existing !== undefined) {{ return existing; }}
                            const idx = this.#getComponentState().handles.insert(this);
                            this.#waitable.setIdx(idx);
                            this.#waitable.setTarget(`waitable for subtask (waitable id [${{idx}}], subtask internal ID [${{this.id()}}])`);
                            return idx;
                        }}

                        join() {{ return this.#waitable.join(...arguments); }}
                        getPendingEvent() {{ return this.#waitable.getPendingEvent(...arguments); }}
                        hasPendingEvent() {{ return this.#waitable.hasPendingEvent(...arguments); }}
                        setPendingEvent() {{ return this.#waitable.setPendingEvent(...arguments); }}

                        setTarget(tgt) {{ this.target = tgt; }}

                        getResult() {{
                            if (!this.#resultSet) {{ throw new Error("subtask result has not been set") }}
                            return this.#result;
                        }}
                        setResult(v) {{
                            if (this.#resultSet) {{ throw new Error("subtask result has already been set"); }}
                            this.#result = v;
                            this.#resultSet = true;
                        }}

                        componentIdx() {{ return this.#componentIdx; }}

                        setChildTask(t) {{
                            if (!t) {{ throw new Error('cannot set missing/invalid child task on subtask'); }}
                            if (this.#childTask) {{ throw new Error('child task is already set on subtask'); }}
                            if (this.#parentTask === t) {{ throw new Error("parent cannot be child"); }}
                            this.#childTask = t;
                        }}
                        getChildTask(t) {{ return this.#childTask; }}

                        getParentTask() {{ return this.#parentTask; }}

                        setCallbackFn(f, name) {{
                            if (!f) {{ return; }}
                            if (this.#callbackFn) {{ throw new Error('callback fn can only be set once'); }}
                            this.#callbackFn = f;
                            this.#callbackFnName = name;
                        }}

                        getCallbackFnName() {{
                            if (!this.#callbackFn) {{ return undefined; }}
                            return this.#callbackFn.name;
                        }}

                        setPostReturnFn(f) {{
                            if (!f) {{ return; }}
                            if (this.#postReturnFn) {{ throw new Error('postReturn fn can only be set once'); }}
                            this.#postReturnFn = f;
                        }}

                        setOnProgressFn(f) {{
                            if (this.#onProgressFn) {{ throw new Error('on progress fn can only be set once'); }}
                            this.#onProgressFn = f;
                        }}

                        isNotStarted() {{
                            return this.#state == {subtask_class}.State.STARTING;
                        }}

                        cancellationRequested() {{ return this.#cancelRequested; }}

                        // Request cooperative cancellation of this subtask, on behalf of the
                        // supertask (i.e. `canon subtask.cancel`).
                        //
                        // If the callee is another guest task, the request is delivered to it and
                        // the callee confirms via `task.cancel` (or still resolves via `task.return`).
                        //
                        // If the callee is a host function, the pending call is treated as
                        // immediately cancelled -- consistent with hosts being expected to resolve
                        // cancellation promptly -- and any later host resolution is discarded
                        // (see `AsyncTask#onResolve`). The host is notified of the discard by
                        // disposing the pending value it returned (see `setHostPendingResult`).
                        requestCancellation() {{
                            {debug_log_fn}('[{subtask_class}#requestCancellation()] args', {{
                                componentIdx: this.#componentIdx,
                                subtaskID: this.#id,
                                state: this.#state,
                                childTaskID: this.childTaskID(),
                                fnName: this.fnName,
                            }});
                            if (this.#cancelRequested) {{
                                throw new Error('cancellation has already been requested for this subtask');
                            }}
                            this.#cancelRequested = true;

                            if (this.#resolved) {{ return; }}

                            if (this.#childTask) {{
                                this.#childTask.requestCancellation();
                                return;
                            }}

                            this.onResolve(null);
                            this.#disposeHostPendingResult();
                        }}

                        // Record the value returned by the host implementation of this subtask.
                        //
                        // Host imports may return a thenable that implements `Symbol.asyncDispose`
                        // or `Symbol.dispose`. If the guest cancels the call before its result is
                        // delivered, the result is discarded and the thenable is disposed so the
                        // host can stop pending work and release anything it produced.
                        setHostPendingResult(v) {{
                            if (v === null || (typeof v !== 'object' && typeof v !== 'function') || typeof v.then !== 'function') {{
                                return;
                            }}
                            this.#hostPendingResult = v;
                            if (this.#resolved && this.#state !== {subtask_class}.State.RETURNED) {{
                                this.#disposeHostPendingResult();
                            }}
                        }}

                        #disposeHostPendingResult() {{
                            const pending = this.#hostPendingResult;
                            if (!pending) {{ return; }}
                            this.#hostPendingResult = null;
                            {dispose_host_value}(pending);
                        }}

                        registerOnStartHandler(f) {{
                            this.#onStartHandlers.push(f);
                        }}

                        onStart(args) {{
                            {debug_log_fn}('[{subtask_class}#onStart()] args', {{
                                componentIdx: this.#componentIdx,
                                subtaskID: this.#id,
                                parentTaskID: this.parentTaskID(),
                                fnName: this.fnName,
                                args,
                            }});

                            if (this.#onProgressFn) {{ this.#onProgressFn(); }}

                            // Starting a nested operation is a task execution boundary.
                            // In particular, a cancellation handler may synchronously
                            // enter an import which then suspends in the host.  Wake a
                            // supertask that is driving one cancellation slice so an
                            // async `subtask.cancel` can report BLOCKED without waiting
                            // for that nested operation to finish.
                            this.#parentTask.notifyProgress();

                            this.#state = {subtask_class}.State.STARTED;

                            let result;

                            // If we have been provided a helper start function as a result of
                            // component fusion performed by wasmtime tooling, then we can call that helper and lifts/lowers will
                            // be performed for us.
                            //
                            // See also documentation on `HostIntrinsic::PrepareCall`
                            //
                            if (this.#callMetadata.startFn) {{
                                result = this.#callMetadata.startFn.apply(null, args?.startFnParams ?? []);
                            }}

                            return result;
                        }}


                        registerOnResolveHandler(f) {{
                            this.#onResolveHandlers.push(f);
                        }}

                        reject(subtaskErr) {{
                            if (this.#resolved) {{ return; }}

                            if (this.#onProgressFn) {{ this.#onProgressFn(); }}

                            if (this.#state === {subtask_class}.State.STARTING) {{
                                this.#state = {subtask_class}.State.CANCELLED_BEFORE_STARTED;
                            }} else if (this.#state === {subtask_class}.State.STARTED) {{
                                this.#state = {subtask_class}.State.CANCELLED_BEFORE_RETURNED;
                            }} else {{
                                throw new Error('cannot reject a completed subtask');
                            }}

                            this.#resolved = true;
                            this.#hostPendingResult = null;
                            this.#parentTask.removeSubtask(this);
                            this.#parentTask.reject(subtaskErr);
                        }}

                        onResolve(subtaskValue) {{
                            {debug_log_fn}('[{subtask_class}#onResolve()] args', {{
                                componentIdx: this.#componentIdx,
                                subtaskID: this.#id,
                                isAsync: this.isAsync,
                                childTaskID: this.childTaskID(),
                                parentTaskID: this.parentTaskID(),
                                parentTaskFnName: this.#parentTask?.entryFnName(),
                                fnName: this.fnName,
                            }});

                            if (this.#resolved) {{
                                throw new Error('subtask has already been resolved');
                            }}

                            if (this.#onProgressFn) {{ this.#onProgressFn(); }}

                            if (subtaskValue === null && this.#cancelRequested) {{
                                if (this.#state === {subtask_class}.State.STARTING) {{
                                    this.#state = {subtask_class}.State.CANCELLED_BEFORE_STARTED;
                                }} else {{
                                    if (this.#state !== {subtask_class}.State.STARTED) {{
                                        throw new Error('resolved subtask must have been started before cancellation');
                                    }}
                                    this.#state = {subtask_class}.State.CANCELLED_BEFORE_RETURNED;
                                }}
                            }} else {{
                                if (this.#state !== {subtask_class}.State.STARTED) {{
                                    throw new Error('resolved subtask must have been started before completion');
                                }}
                                this.#state = {subtask_class}.State.RETURNED;
                                // The host result is delivered to the guest, so it is no longer ours to dispose
                                this.#hostPendingResult = null;
                            }}

                            this.setResult(subtaskValue);

                            for (const f of this.#onResolveHandlers) {{
                                try {{
                                    f(subtaskValue);
                                }} catch (err) {{
                                    console.error("error during subtask resolve handler", err);
                                    throw err;
                                }}
                            }}

                            const callMetadata = this.getCallMetadata();

                            // TODO(fix): we should be able to easily have the caller's meomry
                            // to lower into here, but it's not present in PrepareCall
                            const memory = callMetadata.memory ?? this.#parentTask?.getReturnMemory() ?? {lookup_memories_for_component}({{ componentIdx: this.#parentTask?.componentIdx() }})[0];
                            // NOTE: cancelled resolutions carry no value, so nothing is lowered
                            const returned = this.#state === {subtask_class}.State.RETURNED;
                            if (returned && callMetadata && !callMetadata.returnFn && (this.isAsync || callMetadata.funcTypeIsAsync) && callMetadata.resultPtr && memory) {{
                                const {{ resultPtr, realloc }} = callMetadata;
                                const lowers = callMetadata.lowers; // may have been updated in task.return of the child
                                if (lowers && lowers.length > 0) {{
                                    lowers[0]({{
                                        componentIdx: this.#componentIdx,
                                        memory,
                                        realloc,
                                        vals: [subtaskValue],
                                        storagePtr: resultPtr,
                                        stringEncoding: callMetadata.stringEncoding,
                                    }});
                                }}
                            }}

                            this.#resolved = true;
                            this.#parentTask.removeSubtask(this);

                            if (!this.isAsync) {{
                                this.deliverResolve();
                                const rep = this.waitableRep();
                                if (rep) {{
                                    try {{
                                        const removed = this.#getComponentState().handles.remove(rep);
                                        if (removed !== this) {{
                                            throw new Error("unexpectedly received non-self Subtask from handle removal");
                                        }}
                                        this.drop();
                                    }} catch (err) {{
                                        {debug_log_fn}('[{subtask_class}#onResolve()] failed to remove subtask after sync subtask completion', err);
                                    }}
                                }}
                            }}
                        }}

                        getStateNumber() {{ return this.#state; }}
                        isReturned() {{ return this.#state === {subtask_class}.State.RETURNED; }}

                        getCallMetadata() {{ return this.#callMetadata; }}

                        isResolved() {{
                            if (this.#state === {subtask_class}.State.STARTING
                                || this.#state === {subtask_class}.State.STARTED) {{
                                return false;
                            }}
                            if (this.#state === {subtask_class}.State.RETURNED
                                || this.#state === {subtask_class}.State.CANCELLED_BEFORE_STARTED
                                || this.#state === {subtask_class}.State.CANCELLED_BEFORE_RETURNED) {{
                                return true;
                            }}
                            throw new Error('unrecognized internal Subtask state [' + this.#state + ']');
                        }}

                        addLender(handle) {{
                            {debug_log_fn}('[{subtask_class}#addLender()] args', {{ handle }});
                            if (!Number.isNumber(handle)) {{ throw new Error('missing/invalid lender handle [' + handle + ']'); }}

                            if (this.#lenders.length === 0 || this.isResolved()) {{
                                throw new Error('subtask has no lendors or has already been resolved');
                            }}

                            handle.lends++;
                            this.#lenders.push(handle);
                        }}

                        deliverResolve() {{
                            {debug_log_fn}('[{subtask_class}#deliverResolve()] args', {{
                                lenders: this.#lenders,
                                parentTaskID: this.parentTaskID(),
                                subtaskID: this.#id,
                                childTaskID: this.childTaskID(),
                                resolved: this.isResolved(),
                                resolveDelivered: this.resolveDelivered(),
                            }});

                            const cannotDeliverResolve = this.resolveDelivered() || !this.isResolved();
                            if (cannotDeliverResolve) {{
                                throw new Error('subtask cannot deliver resolution twice, and the subtask must be resolved');
                            }}

                            for (const lender of this.#lenders) {{
                                lender.lends--;
                            }}

                            this.#lenders = null;
                        }}

                        resolveDelivered() {{
                            {debug_log_fn}('[{subtask_class}#resolveDelivered()] args', {{ }});
                            if (this.#lenders === null && !this.isResolved()) {{
                                throw new Error('invalid subtask state, lenders missing and subtask has not been resolved');
                            }}
                            return this.#lenders === null;
                        }}

                        drop() {{
                            {debug_log_fn}('[{subtask_class}#drop()] args', {{
                                componentIdx: this.#componentIdx,
                                parentTaskID: this.#parentTask?.id(),
                                parentTaskFnName: this.#parentTask?.entryFnName(),
                                childTaskID: this.#childTask?.id(),
                                childTaskFnName: this.#childTask?.entryFnName(),
                                subtaskFnName: this.fnName,
                            }});
                            if (!this.#waitable) {{ throw new Error('missing/invalid inner waitable'); }}
                            if (!this.resolveDelivered()) {{
                                throw new {runtime_error_class}('cannot drop a subtask which has not yet resolved');
                            }}
                            if (this.#waitable) {{ this.#waitable.drop() }}
                            this.#dropped = true;
                        }}

                        #getComponentState() {{
                            const state = {get_or_create_async_state_fn}(this.#componentIdx);
                            if (!state) {{
                                throw new Error('invalid/missing async state for component [' + componentIdx + ']');
                            }}
                            return state;
                        }}

                        getWaitableHandleIdx() {{
                            {debug_log_fn}('[{subtask_class}#getWaitableHandleIdx()] args', {{ }});
                            if (!this.#waitable) {{ throw new Error('missing/invalid waitable'); }}
                            return this.waitableRep();
                        }}
                    }}
                "#));
            }

            Self::UnpackCallbackResult => {
                let runtime_error_class =
                    render_args.require_intrinsic(Intrinsic::WebAssemblyRuntimeError);
                let unpack_callback_result_fn =
                    render_args.require_intrinsic(Self::UnpackCallbackResult);
                let i32_typecheck_fn = render_args.require_intrinsic(Intrinsic::TypeCheckValidI32);
                output.push_str(&format!("
                    function {unpack_callback_result_fn}(result) {{
                        if (!({i32_typecheck_fn}(result))) {{ throw new Error('invalid callback return value [' + result + '], not a valid i32'); }}
                        const eventCode = result & 0xF;
                        if (eventCode < 0 || eventCode > 3) {{
                            throw new {runtime_error_class}('invalid async return value [' + eventCode + '], outside callback code range');
                        }}
                        if (result < 0 || result >= 2**32) {{ throw new {runtime_error_class}('invalid callback result'); }}
                        // TODO: table max length check?
                        const waitableSetRep = result >> 4;
                        return [eventCode, waitableSetRep];
                    }}
                ",
                ));
            }

            Self::DriverLoop => {
                let debug_log_fn = render_args.require_intrinsic(Intrinsic::DebugLog);
                let driver_loop_fn = render_args.require_intrinsic(Self::DriverLoop);
                let i32_typecheck = render_args.require_intrinsic(Intrinsic::TypeCheckValidI32);
                let to_int32_fn = render_args
                    .require_intrinsic(Intrinsic::Conversion(ConversionIntrinsic::ToInt32));
                let unpack_callback_result_fn =
                    render_args.require_intrinsic(Self::UnpackCallbackResult);
                let get_or_create_async_state_fn = render_args.require_intrinsic(
                    Intrinsic::Component(ComponentIntrinsic::GetOrCreateAsyncState),
                );
                let waitable_set_class = render_args
                    .require_intrinsic(Intrinsic::Waitable(WaitableIntrinsic::WaitableSetClass));
                let async_event_code_enum =
                    render_args.require_intrinsic(Intrinsic::AsyncEventCodeEnum);
                let runtime_error_class =
                    render_args.require_intrinsic(Intrinsic::WebAssemblyRuntimeError);

                output.push_str(&format!(r#"
                    function {driver_loop_fn}(args) {{
                        {debug_log_fn}('[{driver_loop_fn}()] args', args);
                        const {{
                            componentState,
                            task,
                            fnName,
                            isAsync,
                        }} = args;
                        let callbackResult = args.callbackResult;

                        const callbackFnName = task.getCallbackFnName();
                        const componentIdx = task.componentIdx();

                        if (callbackResult instanceof Promise) {{
                            throw new Error("callbackResult should be a value, not a promise");
                        }}

                        if (callbackResult === undefined) {{
                            throw new Error("callback result should never be undefined");
                        }}

                        let callbackCode;
                        let waitableSetRep;
                        let unpacked;
                        const unpackCallback = (value) => {{
                            if (!({i32_typecheck}(value))) {{
                                throw new {runtime_error_class}('invalid callback result [' + value + '], not a number');
                            }}

                            unpacked = {unpack_callback_result_fn}(value);
                            callbackCode = unpacked[0];
                            waitableSetRep = unpacked[1];
                            if (callbackCode < 0 || callbackCode > 3) {{
                                throw new {runtime_error_class}('invalid async return value, outside callback code range');
                            }}
                        }};

                        const cstate = {get_or_create_async_state_fn}(componentIdx);

                        let eventCode;
                        let index;
                        let result;
                        let asyncRes;
                        let wset;

                        const handleError = (err) => {{
                            {debug_log_fn}('[{driver_loop_fn}()] error during async driver loop', {{
                                fnName,
                                callbackFnName,
                                componentIdx,
                                taskID: task.id(),
                                subtaskID: task.getParentSubtask()?.id(),
                                parentTaskID: task.getParentSubtask()?.getParentTask()?.id(),
                                event: {{
                                    eventCode,
                                    index,
                                    result,
                                }},
                                err,
                            }});
                            task.setErrored(err);
                            task.reject(err);
                            if (!task.isExited()) {{
                                task.exit({{ skipExclusiveLockCheck: true }});
                            }}
                        }};

                        const drive = () => {{
                            try {{
                                if (callbackCode !== 0) {{ componentState.exclusiveRelease(task.id()); }}

                                switch (callbackCode) {{
                                    case 0: // EXIT
                                        {debug_log_fn}('[{driver_loop_fn}()] async exit indicated', {{
                                            fnName,
                                            componentIdx,
                                            callbackFnName,
                                            taskID: task.id()
                                        }});
                                        task.exit({{ skipExclusiveLockCheck: true }});
                                        return;

                                    case 1: // YIELD
                                        {debug_log_fn}('[{driver_loop_fn}()] yield', {{
                                            fnName,
                                            componentIdx,
                                            callbackFnName,
                                            taskID: task.id()
                                        }});
                                        task.suspendUntilCallback({{
                                            cancellable: true,
                                            readyFn: () => true,
                                        }}, (keepGoing) => {{
                                            continueWithEvent(keepGoing
                                                ? {{
                                                    code: {async_event_code_enum}.NONE,
                                                    payload0: 0,
                                                    payload1: 0,
                                                }}
                                                : {{
                                                    code: {async_event_code_enum}.TASK_CANCELLED,
                                                    payload0: 0,
                                                    payload1: 0,
                                                }});
                                        }});
                                        task.settleCompletion();
                                        return;

                                    case 2: // WAIT for a given waitable set
                                        // (an invalid index traps, like `waitable-set.wait`)
                                        wset = waitableSetRep === 0 ? undefined : cstate.handles.get(waitableSetRep);
                                        if (!(wset instanceof {waitable_set_class})) {{
                                            throw new {runtime_error_class}(`unknown handle index ${{waitableSetRep}}`);
                                        }}

                                        {debug_log_fn}('[{driver_loop_fn}()] waiting for event', {{
                                            fnName,
                                            componentIdx,
                                            callbackFnName,
                                            taskID: task.id(),
                                            waitableSetRep,
                                            waitableSetTargets: wset.targets(),
                                        }});

                                        wset.waitUntilCallback({{
                                            readyFn: () => true,
                                            task,
                                            cancellable: true,
                                        }}, continueWithEvent);
                                        task.settleCompletion();
                                        return;

                                    default:
                                        throw new Error(`Unrecognized async function result [${{callbackCode}}]`);
                                }}
                            }} catch (err) {{
                                handleError(err);
                            }}
                        }};

                        const continueWithCallbackResult = (callbackRes) => {{
                            try {{
                                unpackCallback(callbackRes);

                                {debug_log_fn}('[{driver_loop_fn}()] callback result unpacked', {{
                                    fnName,
                                    componentIdx,
                                    callbackFnName,
                                    callbackRes,
                                    callbackCode,
                                    waitableSetRep,
                                }});
                                return drive();
                            }} catch (err) {{
                                handleError(err);
                            }}
                        }};

                        const runCallback = () => {{
                            try {{
                                // No callback runs once the component instance has trapped.
                                if (!task.isRejected()) {{
                                    try {{
                                        componentState.throwIfInterrupted();
                                    }} catch (err) {{
                                        task.setErrored(err);
                                        task.reject(err);
                                    }}
                                }}
                                if (task.isRejected()) {{
                                    {debug_log_fn}('[{driver_loop_fn}()] detected task rejection, leaving early');
                                    componentState.exclusiveRelease(task.id());
                                    if (!task.isExited()) {{
                                        task.exit({{ skipExclusiveLockCheck: true }});
                                    }}
                                    return;
                                }}
                                if (asyncRes.code === undefined) {{ throw new Error("missing event code from event"); }}
                                if (asyncRes.payload0 === undefined) {{ throw new Error("missing payload0 from event"); }}
                                if (asyncRes.payload1 === undefined) {{ throw new Error("missing payload1 from event"); }}

                                eventCode = asyncRes.code; // async event enum code
                                index = asyncRes.payload0; // varies (e.g. idx of related waitable set)
                                result = asyncRes.payload1; // varies (e.g. task state)
                                asyncRes = null;

                                {debug_log_fn}('[{driver_loop_fn}()] performing callback', {{
                                    fnName,
                                    componentIdx,
                                    taskID: task.id(),
                                    callbackFnName,
                                    eventCode,
                                    index,
                                    result
                                }});

                                const callbackRes = task.runCallbackFn(
                                    {to_int32_fn}(eventCode),
                                    {to_int32_fn}(index),
                                    {to_int32_fn}(result),
                                );
                                if (callbackRes && typeof callbackRes.then === 'function') {{
                                    return callbackRes.then(continueWithCallbackResult, handleError);
                                }}
                                return continueWithCallbackResult(callbackRes);
                            }} catch (err) {{
                                handleError(err);
                            }}
                        }};

                        function continueWithEvent(event) {{
                            asyncRes = event;
                            const lock = componentState.acquireExclusiveLock(task.id());
                            if (lock && typeof lock.then === 'function') {{
                                return lock.then(runCallback, handleError);
                            }}
                            return runCallback();
                        }}

                        try {{
                            unpackCallback(callbackResult);
                            return drive();
                        }} catch (err) {{
                            handleError(err);
                        }}
                    }}
                "#,
                ));
            }

            // NOTE: the function that is output by this intrinsic also receives the
            // function that *should* be called (i.e. a trampoline to CallWasm, etc)
            //
            // LowerImport serves as the calling point of a lowered import that is *not*
            // a guest->guest async call.
            //
            // For example, consider a scenario where the host calls a guest that calls a host
            // import. The following entities are created:
            //
            // 1. A Task for the "entrypoint" exported guest fn
            // 2. A Subtask that wraps the component call to the imported host fn
            // 3. A Task for execution of the imported host fn
            //
            // Between (2) and (3), this LowerImport intrinsic should be called, serving a role
            // similar to PrepareCall/AsyncStartCall in guest->guest async lowered import calls.
            //
            Self::LowerImport => {
                let debug_log_fn = render_args.require_intrinsic(Intrinsic::DebugLog);
                let task_class = render_args.require_intrinsic(Self::AsyncTaskClass);
                let lower_import_fn = render_args.require_intrinsic(Self::LowerImport);
                let current_task_get_fn = render_args.require_intrinsic(Self::GetCurrentTask);
                let get_or_create_async_state_fn = render_args.require_intrinsic(
                    Intrinsic::Component(ComponentIntrinsic::GetOrCreateAsyncState),
                );
                let async_event_code_enum =
                    render_args.require_intrinsic(Intrinsic::AsyncEventCodeEnum);
                let get_global_current_thread_meta_fn =
                    render_args.require_intrinsic(Intrinsic::GetGlobalCurrentThreadMetaFn);
                let with_global_current_thread_meta_async_fn =
                    render_args.require_intrinsic(Intrinsic::WithGlobalCurrentThreadMetaFnAsync);
                let with_global_current_thread_meta_fn =
                    render_args.require_intrinsic(Intrinsic::WithGlobalCurrentThreadMetaFn);
                let promise_with_resolvers_fn =
                    render_args.require_intrinsic(Intrinsic::PromiseWithResolversPonyfill);
                let check_may_leave_fn = render_args
                    .require_intrinsic(Intrinsic::Component(ComponentIntrinsic::CheckMayLeave));

                output.push_str(&format!(
                    r#"
                    function {lower_import_fn}(args) {{
                        const params = [...arguments].slice(1);
                        {debug_log_fn}('[{lower_import_fn}()] args', {{ args, params }});
                        const {{
                            functionIdx,
                            componentIdx,
                            isAsync,
                            isManualAsync,
                            paramLiftFns,
                            resultLowerFns,
                            hasResultPointer,
                            funcTypeIsAsync,
                            metadata,
                            memoryIdx,
                            getMemoryFn,
                            getReallocFn,
                            stringEncoding,
                            importFn,
                        }} = args;

                        {check_may_leave_fn}(componentIdx);

                        const {{ taskID, threadID }} = {get_global_current_thread_meta_fn}(componentIdx);

                        const taskMeta = {current_task_get_fn}(componentIdx, taskID);
                        if (!taskMeta) {{ throw new Error('invalid/missing async task meta'); }}

                        const task = taskMeta.task;
                        if (!task) {{ throw new Error('invalid/missing async task'); }}

                        const cstate = {get_or_create_async_state_fn}(componentIdx);

                        if (!task.mayBlock() && funcTypeIsAsync && !isAsync) {{
                            throw new Error("non async exports cannot synchronously call async functions");
                        }}

                        // If there is an existing task, this should be part of a subtask
                        const memory = getMemoryFn();
                        // Canonical ABI lower appends result storage as a trailing
                        // param when async lower has any flat result, or sync lower
                        // has more than one flat result.
                        const resultPtr = hasResultPointer ? params[params.length - 1] >>> 0 : undefined;
                        const subtask = task.createSubtask({{
                           componentIdx,
                           parentTask: task,
                           fnName: importFn.fnName,
                           isAsync,
                           isManualAsync,
                           callMetadata: {{
                               memoryIdx,
                               memory,
                               realloc: getReallocFn?.(),
                               getReallocFn,
                               resultPtr,
                               lowers: resultLowerFns,
                               funcTypeIsAsync,
                               stringEncoding,
                           }}
                        }});
                        task.setReturnMemoryIdx(memoryIdx);
                        task.setReturnMemory(getMemoryFn());

                        subtask.onStart();

                        // If dealing with a sync lowered sync function, we can directly return results
                        //
                        // TODO(breaking): remove once we get rid of manual async import specification,
                        // as func types cannot be detected in that case only (and we don't need that w/ p3)
                        if (!isManualAsync && !isAsync && !funcTypeIsAsync) {{
                            const res = importFn(...params);
                            // TODO(breaking): remove once we get rid of manual async import specification,
                            // as func types cannot be detected in that case only (and we don't need that w/ p3)
                            if (!funcTypeIsAsync && !subtask.isReturned()) {{
                                throw new Error('post-execution subtasks must either be async or returned');
                            }}
                            return subtask.getResult();
                        }}

                        // Sync-lowered async functions requires async behavior because the callee *can* block,
                        // but this call must *act* synchronously and return immediately with the result
                        // (i.e. not returning until the work is done)
                        //
                        // TODO(breaking): remove checking for manual async specification here, once we can go p3-only
                        //
                        if (!isManualAsync && !isAsync && funcTypeIsAsync) {{
                            const {{ promise, resolve, reject }} = {promise_with_resolvers_fn}();
                            queueMicrotask(async () => {{
                                try {{
                                    await {with_global_current_thread_meta_async_fn}({{
                                        taskID: task.id(),
                                        threadID,
                                        componentIdx: task.componentIdx(),
                                        fn: () => importFn(...params),
                                    }});
                                    if (!subtask.isResolved()) {{
                                        await task.suspendUntil({{ readyFn: () => subtask.isResolved() }});
                                    }}
                                    resolve(subtask.getResult());
                                }} catch (err) {{
                                    reject(err);
                                }}
                            }});
                            return promise;
                        }}

                        // NOTE: at this point we know that we are working with an async lowered import

                        subtask.setOnProgressFn(() => {{
                            subtask.setPendingEvent(() => {{
                                if (subtask.isResolved()) {{ subtask.deliverResolve(); }}
                                const event = {{
                                    code: {async_event_code_enum}.SUBTASK,
                                    payload0: subtask.waitableRep(),
                                    payload1: subtask.getStateNumber(),
                                }}
                                return event;
                            }});
                        }});

                        // This is a hack to maintain backwards compatibility with
                        // manually-specified async imports, used in wasm exports that are
                        // not actually async (but are specified as so).
                        //
                        // This is not normal p3 sync behavior but instead anticipating that
                        // the caller that is doing manual async will be waiting for a promise that
                        // resolves to the *actual* result.
                        //
                        // TODO(breaking): remove once manually specified async is removed
                        //
                        // There are a few cases:
                        // 1. sync function with async types (e.g. `f: func() -> stream<u32>`)
                        // 2. async function with async types (e.g. `f: async func() -> stream<u32>`)
                        // 3. async function with sync types (e.g. `f: async func() -> list<u32>`)
                        // 4. sync function with non-async types (e.g. `f: func() -> list<u32>`)
                        //
                        // This hack *only* applies to 4 -- the case where an async JS host function
                        // is supplied to a Wasm export which does *not* need to do any async abi
                        // lifting/lowering (async ABI did not exist when JSPI integratiton was
                        // initially merged to enable asynchronously returning values from the host)
                        //
                        const requiresManualAsyncResult = !isAsync && !funcTypeIsAsync && isManualAsync;
                        let manualAsyncResult;
                        if (requiresManualAsyncResult) {{
                            manualAsyncResult = {promise_with_resolvers_fn}();
                        }}

                        const finishAsyncLower = () => {{
                            const subtaskState = subtask.getStateNumber();
                            if (subtaskState < 0 || subtaskState >= 2**4) {{
                                throw new Error('invalid subtask state, out of valid range');
                            }}
                            let res;
                            // An async-lowered import whose callee resolved synchronously returns
                            // [Subtask.State.RETURNED] only and no subtask handle is exposed.
                            if (subtask.isReturned()) {{
                                // The on-progress handler parked a pending SUBTASK event on the
                                // waitable when the import settled. The guest never learns this
                                // waitable's rep (we return a bare RETURNED state), so consume the
                                // event now -- otherwise a stale event is left parked forever (and
                                // the waitable can never be dropped).
                                if (subtask.hasPendingEvent()) {{
                                    subtask.getPendingEvent();
                                }}
                                if (!subtask.resolveDelivered()) {{
                                    subtask.deliverResolve();
                                }}
                                if (subtask.waitableRep() !== null) {{
                                    const removed = cstate.handles.remove(subtask.waitableRep());
                                    if (removed !== subtask) {{
                                        throw new Error('subtask handle cleanup removed unexpected entry');
                                    }}
                                }}
                                subtask.drop();
                                res = subtaskState;
                            }} else {{
                                res = Number(subtask.ensureHandle()) << 4 | subtaskState;
                            }}
                            {debug_log_fn}('[{lower_import_fn}()] async-lowered import return', {{
                                fnName: importFn.fnName,
                                componentIdx,
                                subtaskID: subtask.id(),
                                waitableRep: subtask.waitableRep(),
                                subtaskState,
                                eagerReturn: subtask.isReturned(),
                                packedResult: res,
                            }});
                            return res;
                        }};

                        // Canonical async lowering returns a status in the current guest
                        // slice. Start the trampoline now so it captures this subtask
                        // before another import is issued; only its host result is async.
                        if (isAsync) {{
                            try {{
                                if (!subtask.cancellationRequested() && task.taskState() !== {task_class}.State.CANCEL_PENDING) {{
                                    const pending = {with_global_current_thread_meta_fn}({{
                                        taskID: task.id(),
                                        threadID,
                                        componentIdx: task.componentIdx(),
                                        fn: () => importFn(...params),
                                    }});
                                    Promise.resolve(pending).catch((err) => {{
                                        task.setErrored(err);
                                        task.reject(err);
                                    }});
                                }}
                                return finishAsyncLower();
                            }} catch (err) {{
                                task.setErrored(err);
                                task.reject(err);
                                throw err;
                            }}
                        }}

                        // Build a response that *may* resolve quickly

                        queueMicrotask(async () => {{
                            try {{
                                // The async host call has not started yet. If the
                                // enclosing guest task has pending cancellation,
                                // leave this subtask for the guest cancellation callback
                                // to retire without invoking host code after cancellation.
                                // Imports issued by the cancellation callback itself
                                // must still run so the guest can finish its cleanup.
                                if (subtask.cancellationRequested() || task.taskState() === {task_class}.State.CANCEL_PENDING) {{ return; }}
                                {debug_log_fn}('[{lower_import_fn}()] calling lowered import', {{ importFn, params }});
                                await {with_global_current_thread_meta_async_fn}({{
                                    taskID: task.id(),
                                    threadID,
                                    componentIdx: task.componentIdx(),
                                    fn: () => importFn(...params),
                                }});
                                if (requiresManualAsyncResult) {{
                                    manualAsyncResult.resolve(subtask.getResult());
                                }}
                            }} catch (err) {{
                                {debug_log_fn}("[{lower_import_fn}()] import fn error:", err);
                                if (requiresManualAsyncResult) {{
                                    manualAsyncResult.reject(err);
                                    return;
                                }}
                                task.setErrored(err);
                                task.reject(err);
                            }}
                        }});

                        if (requiresManualAsyncResult) {{ return manualAsyncResult.promise; }}

                        return new Promise((resolve, reject) => {{
                            setTimeout(() => {{
                                // NOTE: whether the import settled before this timer fires is a race
                                // between the import's settlement (microtask + any host timers), this
                                // setTimeout(0), and JSPI resume scheduling -- engines order these
                                // differently (e.g. V8 13.6 vs 14.x). Either outcome is CABI-legal,
                                // but the invariants of each branch must hold independently, and this
                                // promise must *always* settle (an unhandled throw here would leave a
                                // JSPI-suspended guest suspended forever).
                                try {{
                                    resolve(finishAsyncLower());
                                }} catch (err) {{
                                    reject(err);
                                }}
                            }}, 0);
                        }});
                    }}
                    "#
                ));
            }

            // This version of lower import is sync, doing any requried work in the background,
            // explicitly for older P2 components targeted by jco transpile. We need this because
            // JSPI will not allow calling suspending imports from regular functions, which
            // means that a sync export will not be able to call a 'manually async' import.
            //
            // TODO(breaking): remove when manually specifying async imports/expors is removed.
            //
            Self::LowerImportBackwardsCompat => {
                let debug_log_fn = render_args.require_intrinsic(Intrinsic::DebugLog);
                let lower_import_backwards_compat_fn =
                    render_args.require_intrinsic(Self::LowerImportBackwardsCompat);
                let current_task_get_fn = render_args.require_intrinsic(Self::GetCurrentTask);
                let create_new_current_thread_fn =
                    render_args.require_intrinsic(Self::CreateNewCurrentImplicitThread);
                let get_or_create_async_state_fn = render_args.require_intrinsic(
                    Intrinsic::Component(ComponentIntrinsic::GetOrCreateAsyncState),
                );
                let async_event_code_enum =
                    render_args.require_intrinsic(Intrinsic::AsyncEventCodeEnum);
                let get_global_current_thread_meta_fn =
                    render_args.require_intrinsic(Intrinsic::GetGlobalCurrentThreadMetaFn);
                let set_global_current_thread_meta_fn =
                    render_args.require_intrinsic(Intrinsic::SetGlobalCurrentThreadMetaFn);
                let clear_global_current_thread_meta_fn =
                    render_args.require_intrinsic(Intrinsic::ClearGlobalCurrentThreadMetaFn);
                let promise_with_resolvers_fn =
                    render_args.require_intrinsic(Intrinsic::PromiseWithResolversPonyfill);
                let check_may_leave_fn = render_args
                    .require_intrinsic(Intrinsic::Component(ComponentIntrinsic::CheckMayLeave));

                output.push_str(&format!(
                    r#"
                    function {lower_import_backwards_compat_fn}(args) {{
                        const params = [...arguments].slice(1);
                        {debug_log_fn}('[{lower_import_backwards_compat_fn}()] args', {{ args, params }});
                        const {{
                            functionIdx,
                            componentIdx,
                            isAsync,
                            isManualAsync,
                            paramLiftFns,
                            resultLowerFns,
                            hasResultPointer,
                            funcTypeIsAsync,
                            metadata,
                            memoryIdx,
                            getMemoryFn,
                            getReallocFn,
                            importFn,
                            stringEncoding,
                        }} = args;

                        {check_may_leave_fn}(componentIdx);

                        const meta = {get_global_current_thread_meta_fn}(componentIdx);
                        let taskMeta = meta && {current_task_get_fn}(componentIdx, meta.taskID);
                        let createdTask;

                        // Some components depend on initialization logic (i.e. `_initialize` or some such
                        // core wasm export) that is embedded in the component, but is not executed or wizer'd
                        // away before the transpiled component is attempted to be used.
                        //
                        // These components execut their initialization logic *when they are imported* in the
                        // transpiled context -- so we may get a call to an export that is lowered without going
                        // through `CallWasm` or `CallInterface`.
                        //
                        // A nested synchronous call can leave global metadata for a task
                        // that has already exited. Treat it like a call with no current task.
                        if (!taskMeta) {{
                           if (funcTypeIsAsync || (isAsync && !isManualAsync)) {{
                               throw new Error('p3 async wasm exports cannot use backwards compat auto-task init');
                           }}

                            const {{ task: newTask, taskID: newTaskID, threadID: newThreadID }} = {create_new_current_thread_fn}({{
                                componentIdx,
                                isAsync,
                                isManualAsync,
                                callingWasmExport: false,
                            }});
                            createdTask = newTask;

                            // Since we're managing the task creation ourselves we must clear ourselves
                            createdTask.registerOnResolveHandler(() => {{
                                {clear_global_current_thread_meta_fn}({{
                                    taskID: task.id(),
                                    threadID: newThreadID,
                                    componentIdx: task.componentIdx(),
                                }});
                            }});

                            {set_global_current_thread_meta_fn}({{
                                componentIdx,
                                taskID: newTaskID,
                                threadID: newThreadID,
                            }});

                            taskMeta = {current_task_get_fn}(componentIdx, newTaskID);
                        }}
                        if (!taskMeta) {{
                            throw new Error('invalid/missing async task meta');
                        }}

                        const task = taskMeta.task;
                        if (!task) {{ throw new Error('invalid/missing async task'); }}

                        const cstate = {get_or_create_async_state_fn}(componentIdx);

                        if (!task.mayBlock() && funcTypeIsAsync && !isAsync) {{
                            throw new Error("non async exports cannot synchronously call async functions");
                        }}

                        // If there is an existing task, this should be part of a subtask
                        const memory = getMemoryFn();
                        // Canonical ABI lower appends result storage as a trailing
                        // param when async lower has any flat result, or sync lower
                        // has more than one flat result.
                        const resultPtr = hasResultPointer ? params[params.length - 1] >>> 0 : undefined;
                        const subtask = task.createSubtask({{
                           componentIdx,
                           parentTask: task,
                           fnName: importFn.fnName,
                           isAsync,
                           isManualAsync,
                           callMetadata: {{
                               memoryIdx,
                               memory,
                               realloc: getReallocFn?.(),
                               getReallocFn,
                               resultPtr,
                               lowers: resultLowerFns,
                               funcTypeIsAsync,
                               stringEncoding,
                           }}
                        }});
                        task.setReturnMemoryIdx(memoryIdx);
                        task.setReturnMemory(getMemoryFn());

                        subtask.onStart();

                        // If dealing with a sync lowered sync function, we can directly return results
                        //
                        // TODO(breaking): remove once we get rid of manual async import specification,
                        // as func types cannot be detected in that case only (and we don't need that w/ p3)
                        if (!isManualAsync && !isAsync && !funcTypeIsAsync) {{
                            if (createdTask) {{ createdTask.enterSync(); }}

                            const res = importFn(...params);

                            // TODO(breaking): remove once we get rid of manual async import specification,
                            // as func types cannot be detected in that case only (and we don't need that w/ p3)
                            if (!funcTypeIsAsync && !subtask.isReturned()) {{
                                throw new Error('post-execution subtasks must either be async or returned');
                            }}

                            const syncRes = subtask.getResult();
                            if (createdTask) {{ createdTask.resolve([syncRes]); }}

                            return syncRes;
                        }}

                        // Sync-lowered async functions requires async behavior because the callee *can* block,
                        // but this call must *act* synchronously and return immediately with the result
                        // (i.e. not returning until the work is done)
                        //
                        // TODO(breaking): remove checking for manual async specification here, once we can go p3-only
                        //
                        if (!isManualAsync && !isAsync && funcTypeIsAsync) {{
                            const {{ promise, resolve, reject }} = {promise_with_resolvers_fn}();
                            queueMicrotask(async () => {{
                                try {{
                                    await importFn(...params);
                                    if (!subtask.isResolved()) {{
                                        await task.suspendUntil({{ readyFn: () => subtask.isResolved() }});
                                    }}
                                    resolve(subtask.getResult());
                                }} catch (err) {{
                                    reject(err);
                                }}
                            }});
                            return promise;
                        }}

                        // NOTE: at this point we know that we are working with an async lowered import

                        const subtaskState = subtask.getStateNumber();
                        if (subtaskState < 0 || subtaskState >= 2**4) {{
                            throw new Error('invalid subtask state, out of valid range');
                        }}

                        subtask.setOnProgressFn(() => {{
                            subtask.setPendingEvent(() => {{
                                if (subtask.isResolved()) {{ subtask.deliverResolve(); }}
                                const event = {{
                                    code: {async_event_code_enum}.SUBTASK,
                                    payload0: subtask.waitableRep(),
                                    payload1: subtask.getStateNumber(),
                                }}
                                return event;
                            }});
                        }});

                        // This is a hack to maintain backwards compatibility with
                        // manually-specified async imports, used in wasm exports that are
                        // not actually async (but are specified as so).
                        //
                        // This is not normal p3 sync behavior but instead anticipating that
                        // the caller that is doing manual async will be given the *actual* result,
                        // or a promise that resolves to it.
                        //
                        // TODO(breaking): remove once manually specified async is removed
                        //
                        // There are a few cases:
                        // 1. sync function with async types (e.g. `f: func() -> stream<u32>`)
                        // 2. async function with async types (e.g. `f: async func() -> stream<u32>`)
                        // 3. async function with sync types (e.g. `f: async func() -> list<u32>`)
                        // 4. sync function with non-async types (e.g. `f: func() -> list<u32>`)
                        //
                        // This hack *only* applies to 4 -- the case where an async JS host function
                        // is supplied to a Wasm export which does *not* need to do any async abi
                        // lifting/lowering (async ABI did not exist when JSPI integratiton was
                        // initially merged to enable asynchronously returning values from the host)
                        //
                        // The host is called now rather than in a microtask, so that a host which
                        // answers synchronously is answered synchronously: a task that cannot block
                        // (e.g. a resource destructor) traps on a promise.
                        if (!isAsync && !funcTypeIsAsync && isManualAsync) {{
                            {debug_log_fn}('[{lower_import_backwards_compat_fn}()] calling lowered import', {{ importFn, params }});
                            if (createdTask) {{ createdTask.enterSync(); }}
                            try {{
                                const res = importFn(...params);
                                const isPromise = res !== null &&
                                    (typeof res === 'object' || typeof res === 'function') &&
                                    typeof res.then === 'function';
                                // Without a current task the call cannot block, and its caller
                                // traps on a promise, so a task created for it ends now.
                                if (createdTask) {{ createdTask.resolve([isPromise ? undefined : res]); }}
                                if (!isPromise) {{ return subtask.getResult(); }}
                                return Promise.resolve(res).then(() => subtask.getResult());
                            }} catch (err) {{
                                if (createdTask) {{ createdTask.reject(err); }}
                                throw err;
                            }} finally {{
                                // Resolution delivers the result; exit retires the implicit
                                // thread and removes the task from the component's registry.
                                if (createdTask) {{ createdTask.exit(); }}
                            }}
                        }}

                        queueMicrotask(async () => {{
                            try {{
                                {debug_log_fn}('[{lower_import_backwards_compat_fn}()] calling lowered import', {{ importFn, params }});
                                if (createdTask) {{ await createdTask.enter(); }}

                                const asyncRes = await importFn(...params);
                                if (createdTask) {{ createdTask.resolve([asyncRes]); }}
                            }} catch (err) {{
                                {debug_log_fn}("[{lower_import_backwards_compat_fn}()] import fn error:", err);
                                task.setErrored(err);
                                task.reject(err);
                            }}
                        }});

                        {debug_log_fn}('[{lower_import_backwards_compat_fn}()] async-lowered import return', {{
                            fnName: importFn.fnName,
                            componentIdx,
                            subtaskID: subtask.id(),
                            waitableRep: subtask.waitableRep(),
                            subtaskState,
                            packedResult: Number(subtask.waitableRep()) << 4 | subtaskState,
                        }});

                        return Number(subtask.ensureHandle()) << 4 | subtaskState;
                    }}
                    "#
                ));
            }

            // This call receives the following params:
            // - caller instance
            // - callee async (0 for sync)
            // - callee instance
            //
            // Note that symmetric guest calls are may be called before lowered import calls as well.
            //
            // Symmentric guest enters are marked as as async because they must possibly wait for
            // the availability (unlock) of component instances that they run on.
            //
            Self::EnterSymmetricSyncGuestCall => {
                let debug_log_fn = render_args.require_intrinsic(Intrinsic::DebugLog);
                let enter_symmetric_sync_guest_call_fn = self.name();
                let get_current_task_fn = render_args
                    .require_intrinsic(Intrinsic::AsyncTask(AsyncTaskIntrinsic::GetCurrentTask));
                let get_global_current_thread_meta_fn =
                    render_args.require_intrinsic(Intrinsic::GetGlobalCurrentThreadMetaFn);
                let create_new_current_thread_fn = render_args.require_intrinsic(
                    Intrinsic::AsyncTask(AsyncTaskIntrinsic::CreateNewCurrentImplicitThread),
                );
                let get_or_create_async_state_fn = render_args.require_intrinsic(
                    Intrinsic::Component(ComponentIntrinsic::GetOrCreateAsyncState),
                );
                let set_global_current_thread_meta_fn =
                    render_args.require_intrinsic(Intrinsic::SetGlobalCurrentThreadMetaFn);
                let symmetric_sync_guest_call_stack =
                    render_args.require_intrinsic(Self::SymmetricSyncGuestCallStack);
                let current_task_may_block =
                    render_args.require_intrinsic(Self::CurrentTaskMayBlock);

                // TODO: find a way to get the callee function/export name for the executing symmetric call,
                // at present we only have the current executing task which is far outside
                // (ex. 'run()' that was executing in the caller when the callee is 'set_value()' in the callee)
                output.push_str(&format!(
                    r#"
                    function {enter_symmetric_sync_guest_call_fn}(callerComponentIdx, calleeIsAsync, calleeComponentIdx, syncOnly = false) {{
                        {debug_log_fn}('[{enter_symmetric_sync_guest_call_fn}()] args', {{
                            callerComponentIdx,
                            calleeIsAsync,
                            calleeComponentIdx
                        }});

                        const cstate = {get_or_create_async_state_fn}(calleeComponentIdx);

                        // The conditional JSPI trampoline probes this path before
                        // invoking its Suspending fallback. Avoid creating either
                        // task until the probe knows that entry can complete in the
                        // current Wasm slice.
                        if (syncOnly && calleeIsAsync && cstate.isExclusivelyLocked()) {{
                            return 0;
                        }}

                        const callerThreadMeta = {get_global_current_thread_meta_fn}(callerComponentIdx);
                        if (!callerThreadMeta) {{ throw new Error('missing current caller thread metadata'); }}
                        const callerTaskMeta = {get_current_task_fn}(callerComponentIdx, callerThreadMeta.taskID);
                        if (!callerTaskMeta) {{ throw new Error('missing current caller task metadata'); }}
                        const callerTask = callerTaskMeta.task;
                        if (!callerTask) {{ throw new Error('missing current caller task'); }}
                        if (callerThreadMeta.taskID !== callerTask.id()) {{
                            throw new Error('missing current caller thread metadata');
                        }}
                        const callerThreadID = callerThreadMeta.threadID;

                        const subtask = callerTask.createSubtask({{
                           componentIdx: callerComponentIdx,
                           parentTask: callerTask,
                           // This adapter is a synchronous lowering even when
                           // the callee's component function is async. Its
                           // bookkeeping subtask is never exposed to the guest.
                           isAsync: false,
                        }});

                        const {{ task: newTask, taskID: newTaskID, threadID: newThreadID }} = {create_new_current_thread_fn}({{
                            componentIdx: calleeComponentIdx,
                            isAsync: !!calleeIsAsync,
                            // A manually-async root uses one JSPI stack through any
                            // sync-typed component adapters on the way to its configured
                            // async import, so preserve that compatibility mode here.
                            isManualAsync: callerTask.isManualAsync(),
                            entryFnName: [
                                'task',
                                callerTask.id(),
                                'subtask',
                                subtask.id(),
                                'task',
                                'new-sync-guest-task',
                            ].join("/"),
                            // Sync-typed functions do not participate in an
                            // instance's async exclusive-lock protocol. This is
                            // what permits ordinary synchronous reentrance.
                            callingWasmExport: !!calleeIsAsync,
                        }});
                        newTask.setFuncTypeIsAsync(!!calleeIsAsync);

                        // This symmetric adapter uses a synchronous canonical lift,
                        // even when the component function type itself is async.
                        newTask.setCalleeIsAsync(false);
                        subtask.setChildTask(newTask);
                        newTask.setParentSubtask(subtask);

                        subtask.onStart();

                        const finishEnter = () => {{
                            {set_global_current_thread_meta_fn}({{
                                threadID: newThreadID,
                                taskID: newTask.id(),
                                componentIdx: newTask.componentIdx(),
                            }});
                            {symmetric_sync_guest_call_stack}.push({{
                                componentIdx: newTask.componentIdx(),
                                threadID: newThreadID,
                                callerThreadID,
                                previousTaskMayBlock: {current_task_may_block}.value,
                            }});
                            {current_task_may_block}.value = newTask.mayBlock() ? 1 : 0;

                            {debug_log_fn}('[{enter_symmetric_sync_guest_call_fn}()] finished preparing', {{
                                callerComponentIdx,
                                calleeComponentIdx,
                                subtaskID: subtask.id(),
                                newTaskID: newTask.id(),
                            }});
                        }};

                        // Take the callee's per-slice exclusive lock. Uncontended entry
                        // stays fully synchronous (returning a non-promise means the
                        // Suspending-wrapped trampoline does not suspend, so pure-sync
                        // compositions keep working without WebAssembly.promising).
                        // Contended entry queues FIFO on the holder instead of silently
                        // stealing the hold; the returned
                        // promise suspends the caller's (JSPI) stack until ownership.
                        if (!newTask.needsExclusiveLock()) {{
                            finishEnter();
                            return 1;
                        }}
                        if (!cstate.isExclusivelyLocked()) {{
                            cstate.exclusiveLock(newTask.id());
                            finishEnter();
                            return 1;
                        }}
                        return cstate.acquireExclusiveLock(newTask.id()).then(() => {{
                            finishEnter();
                            return 1;
                        }});
                    }}
                    "#,
                ));
            }

            Self::ExitSymmetricSyncGuestCall => {
                let debug_log_fn = render_args.require_intrinsic(Intrinsic::DebugLog);
                let exit_symmetric_sync_guest_call_fn = self.name();
                let get_or_create_async_state_fn = render_args.require_intrinsic(
                    Intrinsic::Component(ComponentIntrinsic::GetOrCreateAsyncState),
                );
                let get_current_task_fn = render_args
                    .require_intrinsic(Intrinsic::AsyncTask(AsyncTaskIntrinsic::GetCurrentTask));
                let set_global_current_thread_meta_fn =
                    render_args.require_intrinsic(Intrinsic::SetGlobalCurrentThreadMetaFn);
                let symmetric_sync_guest_call_stack =
                    render_args.require_intrinsic(Self::SymmetricSyncGuestCallStack);
                let current_task_may_block =
                    render_args.require_intrinsic(Self::CurrentTaskMayBlock);

                // NOTE: we need to end the task (and clear task machinery/set relevant state)
                // for sync->sync guest calls here because normal task machinery does not work
                // *at all* during the guest sync execution (i.e. there is no call to `CallWasm`).
                //
                output.push_str(&format!(
                    r#"
                    function {exit_symmetric_sync_guest_call_fn}() {{
                        const {{ componentIdx, threadID, callerThreadID, previousTaskMayBlock }} = {symmetric_sync_guest_call_stack}.pop();
                        const cstate = {get_or_create_async_state_fn}(componentIdx);

                        const taskMeta = {get_current_task_fn}(componentIdx);
                        if (!taskMeta) {{ throw new Error('missing current caller task metadata'); }}
                        const task = taskMeta.task;
                        if (!task) {{ throw new Error('missing current caller task'); }}

                        {debug_log_fn}('[{exit_symmetric_sync_guest_call_fn}()] exiting', {{
                            componentIdx,
                            taskID: task.id(),
                            subtask: task.getParentSubtask(),
                            subtaskID: task.getParentSubtask()?.id(),
                            parent: task.getParentSubtask()?.getParentTask(),
                        }});

                        const callerTask = task.getParentSubtask().getParentTask();
                        task.resolve([]);
                        task.exit();

                        {current_task_may_block}.value = previousTaskMayBlock;

                        // Restoring the caller directly is important for recursive
                        // calls into the same component: an enclosing synchronous
                        // metadata wrapper may already have restored its task before
                        // this exit trampoline runs.
                        {set_global_current_thread_meta_fn}({{
                            taskID: callerTask.id(),
                            threadID: callerThreadID,
                            componentIdx: callerTask.componentIdx(),
                        }});
                    }}
                    "#,
                ));
            }

            Self::SymmetricSyncGuestCallStack => {
                let var_name = self.name();
                output.push_str(&format!("let {var_name} = [];\n"));
            }
        }
    }
}