js-component-bindgen 1.16.8

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
//! Intrinsics that represent helpers that enable Stream integration

use crate::{
    intrinsics::{Intrinsic, RenderIntrinsicsArgs, component::ComponentIntrinsic},
    source::Source,
};

use super::async_task::AsyncTaskIntrinsic;

/// This enum contains intrinsics that enable Stream
#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
pub enum AsyncStreamIntrinsic {
    /// Global that stores streams
    ///
    /// ```ts
    /// type i32 = number;
    /// type StreamEnd = StreamWritableEndClass | StreamReadableEndClass;
    /// type GlobalStreamMap<T> = Map<i32, StreamEnd>;
    /// ```
    GlobalStreamMap,

    /// Map of stream tables to component indices
    GlobalStreamTableMap,

    /// The definition of the `StreamEnd` JS superclass
    StreamEndClass,

    /// The definition of the `InternalStream` JS class (which inherits from the `StreamEnd` superclass)
    ///
    /// This class serves as a shared implementation used by writable and readable ends,
    /// that is meant to be used internally to generated code.
    InternalStreamClass,

    /// The definition of the `StreamReadableEnd` JS class
    StreamReadableEndClass,

    /// The definition of the `StreamWritableEnd` JS class
    StreamWritableEndClass,

    /// The definition of the `HostStream` JS class
    ///
    /// This class serves as an implementation for top level host-managed streams,
    /// internal to the bindgen generated logic.
    ///
    /// External code is no expected to work in terms of `HostStream`, but rather deal with `Stream`s
    ///
    HostStreamClass,

    /// The definition of the `Stream` JS class for use with external clients/SDKs
    ///
    /// This class serves as an user-facing implementation of a Preview3 `stream`.
    /// Usually this class is created via `HostStream#createStream()`.
    ///
    ExternalStreamClass,

    /// Create a new stream
    ///
    /// See: https://github.com/WebAssembly/component-model/blob/main/design/mvp/CanonicalABI.md#-canon-streamfuturenew
    ///
    /// # Intrinsic implementation function
    ///
    /// The function that implements this intrinsic has the following definition:
    ///
    /// ```ts
    /// type u32 = number; // >= 0
    /// type u64 = bigint; // >= 0
    /// function streamNew(typeRep: u32): u64;
    /// ```
    StreamNew,

    /// Create a new stream during a lift (`Instruction::StreamLift`).
    ///
    /// This is distinct from plain stream creation, because we are provided more information,
    /// particularly the relevant types to teh stream and lift/lower fns for the stream.
    ///
    /// ```ts
    /// type Ctx = {
    ///     componentIdx: number,
    ///     elemMeta: object,
    /// }
    /// function streamNewFromLift(ctx: Ctx);
    /// ```
    ///
    StreamNewFromLift,

    /// Read from a stream
    ///
    /// See: https://github.com/WebAssembly/component-model/blob/main/design/mvp/CanonicalABI.md#-canon-streamfuturereadwrite
    ///
    /// # Intrinsic implementation function
    ///
    /// The function that implements this intrinsic has the following definition:
    ///
    /// ```ts
    /// type i32 = number;
    /// type u32 = number; // >=0
    /// type i64 = bigint;
    /// type StringEncoding = 'utf8' | 'utf16' | 'compact-utf16'; // see wasmtime_environ::StringEncoding
    ///
    /// function streamRead(
    ///     componentIdx: i32,
    ///     memory: i32,
    ///     realloc: i32,
    ///     encoding: StringEncoding,
    ///     isAsync: bool,
    ///     typeRep: u32,
    ///     streamRep: u32,
    ///     ptr: u32,
    ///     count:u322
    /// ): i64;
    /// ```
    StreamRead,

    /// Write to a stream
    ///
    /// See: https://github.com/WebAssembly/component-model/blob/main/design/mvp/CanonicalABI.md#-canon-streamfuturereadwrite
    ///
    /// # Intrinsic implementation function
    ///
    /// The function that implements this intrinsic has the following definition:
    ///
    /// ```ts
    /// type i32 = number;
    /// type u32 = number; // >=0
    /// type i64 = bigint;
    /// type StringEncoding = 'utf8' | 'utf16' | 'compact-utf16'; // see wasmtime_environ::StringEncoding
    ///
    /// function streamWrite(
    ///     componentIdx: i32,
    ///     memory: i32,
    ///     realloc: i32,
    ///     encoding: StringEncoding,
    ///     isAsync: bool,
    ///     typeRep: u32,
    ///     streamRep: u32,
    ///     ptr: u32,
    ///     count:u322
    /// ): i64;
    /// ```
    StreamWrite,

    /// Cancel a read to a stream
    ///
    /// See: https://github.com/WebAssembly/component-model/blob/main/design/mvp/CanonicalABI.md#-canon-streamfuturecancel-readread
    ///
    /// # Intrinsic implementation function
    ///
    /// The function that implements this intrinsic has the following definition:
    ///
    /// ```ts
    /// type u32 = number; // >=0
    /// type u64 = bigint; // >= 0
    ///
    /// function streamCancelRead(streamRep: u32, isAsync: boolean, readerRep: u32): u64;
    /// ```
    StreamCancelRead,

    /// Cancel a write to a stream
    ///
    /// See: https://github.com/WebAssembly/component-model/blob/main/design/mvp/CanonicalABI.md#-canon-streamfuturecancel-writewrite
    ///
    /// # Intrinsic implementation function
    ///
    /// The function that implements this intrinsic has the following definition:
    ///
    /// ```ts
    /// type u32 = number; // >=0
    /// type u64 = bigint; // >= 0
    ///
    /// function streamCancelWrite(streamRep: u32, isAsync: boolean, writerRep: u32): u64;
    /// ```
    StreamCancelWrite,

    /// Drop a the readable end of a Stream
    ///
    /// See: https://github.com/WebAssembly/component-model/blob/main/design/mvp/CanonicalABI.md#-canon-streamfuturedrop-readablewritable
    ///
    /// # Intrinsic implementation function
    ///
    /// The function that implements this intrinsic has the following definition:
    ///
    /// ```ts
    /// type u32 = number; // >=0
    ///
    /// function streamDropReadable(streamRep: u32, readerRep: u32): bool;
    /// ```
    StreamDropReadable,

    /// Drop a the writable end of a Stream
    ///
    /// See: https://github.com/WebAssembly/component-model/blob/main/design/mvp/CanonicalABI.md#-canon-streamfuturedrop-readablewritable
    ///
    /// # Intrinsic implementation function
    ///
    /// The function that implements this intrinsic has the following definition:
    ///
    /// ```ts
    /// type u32 = number; // >=0
    ///
    /// function streamDropWritable(streamRep: u32, writerRep: u32): bool;
    /// ```
    StreamDropWritable,

    /// Transfer a given stream from one component to another
    ///
    /// Note that all arguments for a stream transfer are provided via arguments at runtime,
    /// and is generally called from the *guest* component (or at least the guest component idx is
    /// discernable via the current task).
    ///
    /// ```ts
    /// type u32 = number;
    ///
    /// function streamTransfer(srcComponentIdx: u32, srcTableIdx: u32, destTableIdx: u32): bool;
    /// ```
    StreamTransfer,

    /// Function to check whether a JS object can be used as a stream
    IsStreamLowerableObject,

    /// Function that generates a host injection function for external streams
    ///
    /// This is usually used when lowering external streams' readable ends into a component,
    /// and the generated function is generally called right when a component attempts to read
    /// (in doing so, "injecting" a write before the component read).
    GenHostInjectFn,

    /// Function that generates a function (the "read function") lowerable stream object
    GenReadFnFromLowerableStream,
}

impl AsyncStreamIntrinsic {
    /// Retrieve dependencies for this intrinsic
    pub fn deps() -> &'static [&'static Intrinsic] {
        &[]
    }

    /// Retrieve global names for this intrinsic
    pub fn get_global_names() -> impl IntoIterator<Item = &'static str> {
        []
    }

    /// Get the name for the intrinsic
    pub fn name(&self) -> &'static str {
        match self {
            Self::GlobalStreamMap => "STREAMS",
            Self::GlobalStreamTableMap => "STREAM_TABLES",
            Self::StreamEndClass => "StreamEnd",
            Self::InternalStreamClass => "InternalStream",
            Self::StreamWritableEndClass => "StreamWritableEnd",
            Self::StreamReadableEndClass => "StreamReadableEnd",
            Self::HostStreamClass => "HostStream",
            Self::ExternalStreamClass => "Stream",
            Self::StreamNew => "streamNew",
            Self::StreamNewFromLift => "streamNewFromLift",
            Self::StreamRead => "streamRead",
            Self::StreamWrite => "streamWrite",
            Self::StreamDropReadable => "streamDropReadable",
            Self::StreamDropWritable => "streamDropWritable",
            Self::StreamTransfer => "streamTransfer",
            Self::StreamCancelRead => "streamCancelRead",
            Self::StreamCancelWrite => "streamCancelWrite",
            Self::IsStreamLowerableObject => "_isStreamLowerableObject",
            Self::GenHostInjectFn => "_genHostInjectFn",
            Self::GenReadFnFromLowerableStream => "_genReadFnFromLowerableStream",
        }
    }

    /// Render an intrinsic to a string
    pub fn render(&self, output: &mut Source, _render_args: &RenderIntrinsicsArgs<'_>) {
        match self {
            Self::StreamEndClass => {
                let debug_log_fn = Intrinsic::DebugLog.name();
                let stream_end_class = Self::StreamEndClass.name();
                output.push_str(&format!(
                    r#"
                    class {stream_end_class} {{
                        static CopyResult = {{
                            COMPLETED: 0,
                            DROPPED: 1,
                            CANCELLED: 2,
                        }};

                        static CopyState = {{
                            IDLE: 1,
                            SYNC_COPYING: 2,
                            ASYNC_COPYING: 3,
                            CANCELLING_COPY: 4,
                            DONE: 5,
                        }};

                        #waitable = null;

                        #tableIdx = null; // stream table that contains the stream end
                        #idx = null; // stream end index in the table

                        #componentIdx = null;

                        #copyState = {stream_end_class}.CopyState.IDLE;

                        #dropped;
                        #setDroppedFn;
                        #isDroppedFn;

                        target;

                        constructor(args) {{
                            const {{ tableIdx, componentIdx }} = args;
                            if (tableIdx === undefined || typeof tableIdx !== 'number') {{
                                throw new TypeError(`missing table idx [${{tableIdx}}]`);
                            }}
                            if (tableIdx < 0 || tableIdx > 2_147_483_647) {{
                                throw new TypeError(`invalid  tableIdx [${{tableIdx}}]`);
                            }}
                            if (!args.waitable) {{ throw new Error('missing/invalid waitable'); }}

                            this.#tableIdx = args.tableIdx;
                            this.#waitable = args.waitable;

                            if (args.setDroppedFn && args.isDroppedFn) {{
                                this.#setDroppedFn = args.setDroppedFn;
                                this.#isDroppedFn = args.isDroppedFn;
                            }} else if (args.setDroppedFn === undefined && args.isDroppedFn === undefined) {{
                                this.#setDroppedFn = (v) => {{ this.#dropped = v; }};
                                this.#isDroppedFn = () => {{ return this.#dropped; }};
                            }} else {{
                                throw new TypeError('setDroppedFn and isDroppedFn must both be specified or neither');
                            }}

                            this.target = args.target;
                        }}

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

                        idx() {{ return this.#idx; }}
                        setIdx(idx) {{ this.#idx = idx; }}

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

                        getWaitable() {{ return this.#waitable; }}
                        setWaitable(w) {{ this.#waitable = w; }}

                        setCopyState(state) {{ this.#copyState = state; }}
                        getCopyState() {{ return this.#copyState; }}

                        isCopying() {{
                            switch (this.#copyState) {{
                                case {stream_end_class}.CopyState.IDLE:
                                case {stream_end_class}.CopyState.DONE:
                                    return false;
                                    break;
                                case {stream_end_class}.CopyState.SYNC_COPYING:
                                case {stream_end_class}.CopyState.ASYNC_COPYING:
                                case {stream_end_class}.CopyState.CANCELLING_COPY:
                                    return true;
                                    break;
                                default:
                                    throw new Error('invalid/unknown copying state');
                            }}
                        }}

                        setPendingEvent(fn) {{
                            if (!this.#waitable) {{ throw new Error('missing/invalid waitable'); }}
                            {debug_log_fn}('[{stream_end_class}#setPendingEvent()]', {{
                                waitable: this.#waitable,
                                waitableinSet: this.#waitable.isInSet(),
                                componentIdx: this.#waitable.componentIdx(),
                            }});
                            this.#waitable.setPendingEvent(fn);
                        }}

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

                        getPendingEvent() {{
                            if (!this.#waitable) {{ throw new Error('missing/invalid waitable'); }}
                            {debug_log_fn}('[{stream_end_class}#getPendingEvent()]', {{
                                waitable: this.#waitable,
                                waitableinSet: this.#waitable.isInSet(),
                                componentIdx: this.#waitable.componentIdx(),
                            }});
                            const event = this.#waitable.getPendingEvent();
                            return event;
                        }}

                        isDropped() {{ return this.#isDroppedFn(); }}
                        setDropped() {{ return this.#setDroppedFn(); }}

                        drop() {{
                            {debug_log_fn}('[{stream_end_class}#drop()]', {{
                                waitable: this.#waitable,
                                waitableinSet: this.#waitable.isInSet(),
                                componentIdx: this.#waitable.componentIdx(),
                            }});

                            if (this.isDropped()) {{
                                {debug_log_fn}('[{stream_end_class}#drop()] already dropped', {{
                                    waitable: this.#waitable,
                                    waitableinSet: this.#waitable.isInSet(),
                                    componentIdx: this.#waitable.componentIdx(),
                                }});
                                return;
                            }}

                            if (this.#waitable) {{
                                const w = this.#waitable;
                                w.drop();
                            }}

                            this.setDropped();
                        }}
                    }}
                "#
                ));
            }

            // Stream Write/Read ends hold on to buffer(s) for the component from which the copy is being performed
            // along with buffers for the component being written to.
            //
            // Depending on whether we're doing a write or a read, different parts of the class itself should be filled out,
            // and the output below will have different members/functions available.
            //
            //
            // TODO(fix): the stream class itself is ONE CLASS/need to share data. The classes don't have to be distinct.
            //
            Self::StreamReadableEndClass | Self::StreamWritableEndClass => {
                let debug_log_fn = Intrinsic::DebugLog.name();
                let (end_class_name, _js_stream_class_name) = match self {
                    Self::StreamReadableEndClass => (self.name(), "ReadableStream"),
                    Self::StreamWritableEndClass => (self.name(), "WritableStream"),
                    _ => unreachable!("impossible stream readable end class intrinsic"),
                };

                let stream_end_class = Self::StreamEndClass.name();
                let managed_buffer_class = Intrinsic::ManagedBufferClass.name();
                let global_buffer_manager = Intrinsic::GlobalBufferManager.name();

                // Internal helper fn that sets up for a `copy()` call
                let copy_setup_impl = format!(
                    r#"
                    setupCopy(args) {{
                        const {{
                            memory,
                            ptr,
                            count,
                            eventCode,
                            componentIdx,
                            skipStateCheck,
                        }} = args;
                        if (eventCode === undefined) {{ throw new Error("missing/invalid event code"); }}

                        let buffer = args.buffer;
                        let bufferID = args.bufferID;

                        // Only check invariants if we are *not* doing a follow-up/post-blocked read
                        if (!skipStateCheck) {{
                            if (this.isCopying()) {{
                                throw new Error('stream is currently undergoing a separate copy');
                            }}
                            if (this.getCopyState() !== {stream_end_class}.CopyState.IDLE) {{
                                throw new Error(`stream copy state is not idle`);
                            }}
                        }}

                        const elemMeta = this.getElemMeta();
                        if (elemMeta.isBorrowed) {{ throw new Error('borrowed types cannot be sent over streams'); }}

                        // If we already have a managed buffer (likely host case), we can use that, otherwise we must
                        // create a buffer (likely in the guest case)
                        if (!buffer) {{
                            const newBufferMeta = {global_buffer_manager}.createBuffer({{
                                componentIdx,
                                memory,
                                start: ptr,
                                count,
                                // If creating a buffer for a write operation, the buffer we are encapsulating
                                // is a *readable* buffer from the view of the component (as it has written to that buffer data that)
                                // should be sent out
                                isReadable: this.isWritable(),
                                // If creating a buffer for a read operation, the buffer we are encapsulating
                                // is a *writable* buffer from the view of the component (as it has prepared space to receive data)
                                isWritable: this.isReadable(),
                                elemMeta,
                            }});
                            bufferID = newBufferMeta.id;
                            buffer = newBufferMeta.buffer;
                            buffer.setTarget(`component [${{componentIdx}}] {end_class_name} buffer (id [${{bufferID}}], count [${{count}}], eventCode [${{eventCode}}])`);
                        }}

                        const streamEnd = this;
                        const processFn = (result, reclaimBufferFn) => {{
                            if (reclaimBufferFn) {{ reclaimBufferFn(); }}

                            if (result === {stream_end_class}.CopyResult.DROPPED) {{
                                streamEnd.setCopyState({stream_end_class}.CopyState.DONE);
                            }} else {{
                                streamEnd.setCopyState({stream_end_class}.CopyState.IDLE);
                            }}

                            if (result < 0 || result >= 16) {{
                                throw new Error(`unsupported stream copy result [${{result}}]`);
                            }}
                            if (buffer.processed >= {managed_buffer_class}.MAX_LENGTH) {{
                                 throw new Error(`processed count [${{buf.length}}] greater than max length`);
                            }}
                            if (buffer.length > 2**28) {{ throw new Error('buffer uses reserved space'); }}

                            const packedResult = (Number(buffer.processed) << 4) | result;
                            const event = {{ code: eventCode, payload0: streamEnd.waitableIdx(), payload1: packedResult }};

                            return event;
                        }};

                        const onCopyFn = (reclaimBufferFn) => {{
                            streamEnd.setPendingEvent(() => {{
                                return processFn({stream_end_class}.CopyResult.COMPLETED, reclaimBufferFn);
                            }});
                        }};

                        const onCopyDoneFn = (result) => {{
                            streamEnd.setPendingEvent(() => {{
                                return processFn(result);
                            }});
                        }};

                        return {{ bufferID, buffer, onCopyFn, onCopyDoneFn }};
                    }}
                    "#
                );

                let (rw_fn_name, inner_rw_impl) = match self {
                    // Internal implementation for writing to internal buffer after reading from a provided managed buffers
                    //
                    // This is called by both the host and the guest
                    Self::StreamWritableEndClass => (
                        "write",
                        format!(
                            r#"
                            _write(args) {{
                                const {{ buffer, onCopyFn, onCopyDoneFn, componentIdx }} = args;
                                if (!buffer) {{ throw new TypeError('missing/invalid buffer'); }}
                                if (!onCopyFn) {{ throw new TypeError("missing/invalid onCopy handler"); }}
                                if (!onCopyDoneFn) {{ throw new TypeError("missing/invalid onCopyDone handler"); }}

                                if (!this.#pendingBufferMeta.buffer) {{
                                    this.setPendingBufferMeta({{ componentIdx, buffer, onCopyFn, onCopyDoneFn }});
                                    return;
                                }}

                                const pendingElemMeta = this.#pendingBufferMeta.buffer.getElemMeta();
                                const newBufferElemMeta = buffer.getElemMeta();
                                if (pendingElemMeta.payloadTypeName !== newBufferElemMeta.payloadTypeName) {{
                                    throw new Error("trap: stream end type does not match internal buffer");
                                }}

                                // If the buffer came from the same component that is currently doing the operation
                                // we're doing a inter-component write, and only unit or numeric types are allowed
                                const pendingElemIsNoneOrNumeric = pendingElemMeta.isNone || pendingElemMeta.isNumeric;
                                if (this.#pendingBufferMeta.componentIdx === buffer.componentIdx() && buffer.componentIdx() !== -1 && !pendingElemIsNoneOrNumeric) {{
                                    throw new Error(`trap: cannot stream non-numeric types within the same component (component [${{buffer.componentIdx()}}], send)`);
                                }}

                                // If original capacities were zero, we're dealing with a unit stream,
                                // a write to the unit stream is instantly copied without any work.
                                if (buffer.capacity === 0 && this.#pendingBufferMeta.buffer.capacity === 0) {{
                                    onCopyDoneFn({stream_end_class}.CopyResult.COMPLETED);
                                    return;
                                }}

                                // If the internal buffer has no space left to take writes,
                                // the write is complete, we must reset and wait for another read
                                // to clear up space in the buffer.
                                if (this.#pendingBufferMeta.buffer.remaining() === 0) {{
                                    this.resetAndNotifyPending({stream_end_class}.CopyResult.COMPLETED);
                                    this.setPendingBufferMeta({{ componentIdx, buffer, onCopyFn, onCopyDoneFn }});
                                    return;
                                }}

                                // At this point it is implied that remaining is > 0,
                                // so if there is still remaining capacity in the incoming buffer, perform copy of values
                                // to the internal buffer from the incoming buffer
                                let transferred = false;
                                if (buffer.remaining() > 0) {{
                                    const numElements = Math.min(buffer.remaining(), this.#pendingBufferMeta.buffer.remaining());
                                    this.#pendingBufferMeta.buffer.write(buffer.read(numElements));
                                    this.#pendingBufferMeta.onCopyFn(() => this.resetPendingBufferMeta());
                                    transferred = true;
                                }}

                                onCopyDoneFn({stream_end_class}.CopyResult.COMPLETED);
                            }}
                        "#,
                        ),
                    ),

                    // Internal implementation for reading from an internal buffer and writing to a provided managed buffer
                    //
                    // This is called by both the host and the guest
                    Self::StreamReadableEndClass => (
                        "read",
                        format!(
                            r#"
                            _read(args) {{
                                const {{ buffer, onCopyDoneFn, onCopyFn, componentIdx }} = args;
                                if (this.isDropped()) {{
                                    onCopyDoneFn({stream_end_class}.CopyResult.DROPPED);
                                    return;
                                }}

                                if (!this.#pendingBufferMeta.buffer) {{
                                    this.setPendingBufferMeta({{
                                        componentIdx,
                                        buffer,
                                        onCopyFn,
                                        onCopyDoneFn,
                                    }});
                                    return;
                                }}

                                const pendingElemMeta = this.#pendingBufferMeta.buffer.getElemMeta();
                                const newBufferElemMeta = buffer.getElemMeta();
                                if (pendingElemMeta.payloadTypeName !== newBufferElemMeta.payloadTypeName) {{
                                    throw new Error("trap: stream end type does not match internal buffer");
                                }}

                                // Since we do not know the string encoding until a write is performed, it is possible that
                                // one end (i.e. the read end) does not yet know the appropriate string encoding to use when
                                // lifting/lowering.
                                if (newBufferElemMeta.stringEncoding === undefined || pendingElemMeta.stringEncoding === undefined) {{
                                    const encoding = pendingElemMeta.stringEncoding ?? newBufferElemMeta.stringEncoding;
                                    if (encoding === undefined) {{ throw new Error('both writer & reader missing string encoding'); }}
                                    newBufferElemMeta.stringEncoding = encoding;
                                    pendingElemMeta.stringEncoding = encoding;
                                }}

                                // If the buffer came from the same component that is currently doing the operation
                                // we're doing a inter-component read, and only unit or numeric types are allowed
                                const pendingElemIsNoneOrNumeric = pendingElemMeta.isNone || pendingElemMeta.isNumeric;
                                if (this.#pendingBufferMeta.componentIdx === buffer.componentIdx() && buffer.componentIdx() !== -1 && !pendingElemIsNoneOrNumeric) {{
                                    throw new Error(`trap: cannot stream non-numeric types within the same component (component [${{buffer.componentIdx()}}] read)`);
                                }}

                                const pendingRemaining = this.#pendingBufferMeta.buffer.remaining();
                                let transferred = false;
                                if (pendingRemaining > 0) {{
                                    const bufferRemaining = buffer.remaining();
                                    if (bufferRemaining > 0) {{
                                        const count = Math.min(pendingRemaining, bufferRemaining);
                                        buffer.write(this.#pendingBufferMeta.buffer.read(count))
                                        this.#pendingBufferMeta.onCopyFn(() => this.resetPendingBufferMeta());
                                        transferred = true;
                                    }}

                                    onCopyDoneFn({stream_end_class}.CopyResult.COMPLETED);

                                    return;
                                }}

                                this.resetAndNotifyPending({stream_end_class}.CopyResult.COMPLETED);
                                this.setPendingBufferMeta({{ componentIdx, buffer, onCopyFn, onCopyDoneFn }});
                            }}
                            "#,
                        ),
                    ),
                    _ => unreachable!("invalid stream end enum"),
                };

                let async_blocked_const =
                    Intrinsic::AsyncTask(AsyncTaskIntrinsic::AsyncBlockedConstant).name();
                let current_task_get_fn =
                    Intrinsic::AsyncTask(AsyncTaskIntrinsic::GetCurrentTask).name();

                // NOTE: This shared copy impl is meant to be called from *outside* the stream end class in question,
                // but internally to the bindgen-generated code (i.e. from `stream.{read,write}` or from a
                // read on an external stream class)
                let copy_impl = format!(
                    r#"
                         async copy(args) {{
                             const {{
                                 isAsync,
                                 memory,
                                 componentIdx,
                                 ptr,
                                 count,
                                 eventCode,
                                 initial,
                                 skipStateCheck,
                                 stringEncoding,
                                 reallocFn,
                             }} = args;
                             if (eventCode === undefined) {{ throw new TypeError('missing/invalid event code'); }}

                             if (this.#elemMeta.stringEncoding === undefined && stringEncoding) {{
                                this.#elemMeta.stringEncoding = stringEncoding;
                             }}
                             if (this.#elemMeta.stringEncoding && stringEncoding && this.#elemMeta.stringEncoding !== stringEncoding) {{
                                 throw new Error(`inconsistent string encoding (previously [${{this.#elemMeta.stringEncoding}}], now [${{stringEncoding}}])`);
                             }}

                             if (this.#elemMeta.reallocFn === undefined && reallocFn) {{
                                this.#elemMeta.reallocFn = reallocFn;
                             }}

                             if (this.isDropped()) {{
                                 if (this.#pendingBufferMeta?.onCopyDoneFn) {{
                                     const f = this.#pendingBufferMeta.onCopyDoneFn;
                                     this.#pendingBufferMeta.onCopyDoneFn = null;
                                     f({stream_end_class}.CopyResult.DROPPED);
                                 }}
                                 return;
                             }}

                             const {{ buffer, onCopyFn, onCopyDoneFn }} = this.setupCopy({{
                                 memory,
                                 eventCode,
                                 componentIdx,
                                 ptr,
                                 count,
                                 buffer: args.buffer,
                                 bufferID: args.bufferID,
                                 initial,
                                 skipStateCheck,
                             }});

                             // If the stream is readable and was lowered from the host,
                             // when the component is doing a read (i.e. `stream.read`),
                             // the writer is host-side and may have already written.
                             //
                             // We effectively do a just-in-time "write" of the external value,
                             // if one is present, because what we got from the outside world
                             // was a reader
                             //
                             let onReadFinishFn;
                             const injectHostWrite = this.isReadable() && !!this.#hostInjectFn;
                             if (injectHostWrite) {{
                                 onReadFinishFn = await this.#hostInjectFn({{ count }});
                             }}

                             // Perform the read/write
                             this._{rw_fn_name}({{
                                 buffer,
                                 onCopyFn,
                                 onCopyDoneFn,
                                 componentIdx,
                             }});

                             // If sync, wait forever but allow task to do other things
                             if (!this.hasPendingEvent()) {{
                                 if (injectHostWrite) {{
                                     throw new Error('reader unexpectedly blocked after injected write');
                                 }}

                                 if (isAsync) {{
                                     this.setCopyState({stream_end_class}.CopyState.ASYNC_COPYING);
                                     {debug_log_fn}('[{stream_end_class}#copy()] blocked', {{ componentIdx, eventCode, self: this }});
                                     return {async_blocked_const};
                                 }} else {{
                                     this.setCopyState({stream_end_class}.CopyState.SYNC_COPYING);

                                     const taskMeta = {current_task_get_fn}(componentIdx);
                                     if (!taskMeta) {{ throw new Error(`missing task meta for component idx [${{componentIdx}}]`); }}

                                     const task = taskMeta.task;
                                     if (!task) {{ throw new Error('missing task task from task meta'); }}

                                     const streamEnd = this;
                                     await task.suspendUntil({{
                                         readyFn: () => streamEnd.hasPendingEvent(),
                                     }});
                                 }}
                             }}

                             // If we injected a write and the read has completed, we should reset
                             // we can skip the rest of the async machinery since there the host controlled
                             // write end does not need to use the pending event machinery
                             if (injectHostWrite) {{
                                 if (!onReadFinishFn) {{ throw new Error('missing read finish fn'); }}
                                 onReadFinishFn();
                             }}

                             const event = this.getPendingEvent();
                             if (!event) {{ throw new Error("unexpectedly missing pending event"); }}
                             if (event.code === undefined || event.payload0 === undefined || event.payload1 === undefined) {{
                                 throw new Error("unexpectedly malformed event");
                             }}

                             const {{ code, payload0: index, payload1: payload }} = event;

                             const waitableIdx = this.getWaitable().idx();
                             if (code !== eventCode  || index !== waitableIdx || payload === {async_blocked_const}) {{
                                 const errMsg = "invalid event code/event during stream operation";
                                 {debug_log_fn}(errMsg, {{
                                     event,
                                     payload,
                                     payloadIsBlockedConst: payload === {async_blocked_const},
                                     code,
                                     eventCode,
                                     codeDoesNotMatchEventCode: code !== eventCode,
                                     index,
                                     internalEndIdx: waitableIdx,
                                     indexDoesNotMatch: index !== waitableIdx,
                                 }});
                                 throw new Error(errMsg);
                             }}

                             return payload;
                         }}
                    "#
                );

                let type_getter_impl = match self {
                    Self::StreamWritableEndClass => "
                         isReadable() { return false; }
                         isWritable() { return true; }
                    "
                    .to_string(),
                    Self::StreamReadableEndClass => "
                         isReadable() { return true; }
                         isWritable() { return false; }
                    "
                    .to_string(),
                    _ => unreachable!("impossible stream readable end class intrinsic"),
                };

                let async_event_code_enum = Intrinsic::AsyncEventCodeEnum.name();
                let promise_with_resolvers_fn = Intrinsic::PromiseWithResolversPonyfill.name();

                // NOTE: these action implementations `write()` and `read()` are normally called
                // from the host -- internally components will use the `stream.{write, read}` intrinsics
                // which call the `copy()` function on the stream end class directly.
                let action_impl = match self {
                    Self::StreamWritableEndClass => format!(
                        r#"
                         async write(v) {{
                            {debug_log_fn}('[{end_class_name}#write()] args', {{ v }});

                            // Wait for an existing write operation to end, if present,
                            // otherwise register this write for any future operations.
                            //
                            // NOTE: this complexity below is an attempt to sequence operations
                            // to ensure consecutive writes only wait on their direct predecessors,
                            // (i.e. write #3 must wait on write #2, *not* write #1)
                            //
                            let newResult = {promise_with_resolvers_fn}();
                            if (this.#result) {{
                                try {{
                                    const p = this.#result.promise;
                                    this.#result = newResult;
                                    await p;
                                }} catch (err) {{
                                    {debug_log_fn}('[{end_class_name}#write()] error waiting for previous write', err);
                                    // If the previous write we were waiting on errors for any reason,
                                    // we can ignore it and attempt to continue with this write
                                    // which may also fail for a similar reason
                                }}
                            }} else {{
                                this.#result = newResult;
                            }}
                            const {{ promise, resolve, reject }} = newResult;

                            const count = 1;
                            if (this.#elemMeta.stringEncoding === undefined) {{
                                this.#elemMeta.string = 'utf8';
                            }}

                            try {{
                                const {{ id: bufferID, buffer }} = {global_buffer_manager}.createBuffer({{
                                    componentIdx: -1,
                                    count,
                                    isReadable: true, // we need to read from this buffer later
                                    isWritable: false,
                                    elemMeta: this.#elemMeta,
                                    data: v,
                                }});
                                buffer.setTarget(`host stream write buffer (id [${{bufferID}}], count [${{count}}], data len [${{v.length}}])`);

                                let packedResult;
                                packedResult = await this.copy({{
                                    isAsync: true,
                                    count,
                                    bufferID,
                                    buffer,
                                    eventCode: {async_event_code_enum}.STREAM_WRITE,
                                    componentIdx: -1,
                                }});

                                // If we are dealing with a blocked component write operation, we do an immedaite wait
                                // on the host side to pause the host until the write can be completed.
                                //
                                // We do not do this if we're dealing with a host injection,
                                // (i.e. a lowered read end into a component does a read() and forces
                                // data to be read from the host side), we must signal the write is completed
                                // and we are waiting for the read.
                                //
                                //  In the host injection case, it is OK that the write is blocked, because we
                                //  know the read is about to occur (we control the writes to the stream to be
                                // just-before reads, no matter what the user does on the other end).
                                //
                                if (packedResult === {async_blocked_const} && !this.#isHostOwned) {{
                                    // If the write was blocked, we can only make progress when
                                    // the read side notifies us of a read, then we must attempt the copy again

                                    await new Promise((resolve) => {{
                                        let waitInterval = setInterval(async () => {{
                                            if (!this.hasPendingEvent()) {{ return; }}
                                            clearInterval(waitInterval);
                                            resolve();
                                        }});
                                    }});

                                    packedResult = await this.copy({{
                                        isAsync: true,
                                        count,
                                        bufferID,
                                        buffer,
                                        eventCode: {async_event_code_enum}.STREAM_WRITE,
                                        // NOTE: we skip state checks only when dealing with a post blocked
                                        // read/write in the host. This enables the host to quickly pick up the
                                        // guest operation on the otherside quickly.
                                        skipStateCheck: true,
                                        componentIdx: -1,
                                    }});

                                    const copied = packedResult >> 4;
                                    if (copied === 0 && this.isDoneState()) {{
                                       reject(new Error("read end dropped during write"));
                                    }}

                                    if (packedResult === {async_blocked_const}) {{
                                        throw new Error("unexpected double block during write");
                                    }}
                                }}


                                // Host owned writes were not necessarily unblocked, but are always blocked
                                // because they happen just-before a component read (via a lowered end).
                                //
                                // In this case, we cant to declare the copy state back to idle
                                // for the next write that is performed, assuming there may be more writes
                                // to do.
                                //
                                // if (this.#hostOwned) {{
                                //    this.setCopyState({stream_end_class}.CopyState.IDLE);
                                // }}

                                // If the write was not blocked, we can resolve right away
                                this.#result = null;
                                resolve();

                            }} catch (err) {{
                                {debug_log_fn}('[{end_class_name}#write()] error', err);
                                reject(err);
                            }}

                            return await promise;
                         }}
                        "#
                    ),

                    // NOTE: Host stream reads typically take this path, via `ExternalStream` class's
                    // `read()` function which calls the underlying stream end's `read()`
                    // fn (below) via an anonymous function.
                    Self::StreamReadableEndClass => format!(
                        r#"
                         async read() {{
                            {debug_log_fn}('[{end_class_name}#read()]');

                            // Wait for an existing read operation to end, if present,
                            // otherwise register this read for any future operations.
                            //
                            // NOTE: this complexity below is an attempt to sequence operations
                            // to ensure consecutive reads only wait on their direct predecessors,
                            // (i.e. read #3 must wait on read #2, *not* read #1)
                            //
                            const newResult = {promise_with_resolvers_fn}();
                            if (this.#result) {{
                                try {{
                                    const p = this.#result.promise;
                                    this.#result = newResult;
                                    await p;
                                }} catch (err) {{
                                    {debug_log_fn}('[{end_class_name}#read()] error waiting for previous read', err);
                                    // If the previous write we were waiting on errors for any reason,
                                    // we can ignore it and attempt to continue with this read
                                    // which may also fail for a similar reason
                                }}
                            }} else {{
                                this.#result = newResult;
                            }}
                            const {{ promise, resolve, reject }} = newResult;

                            // TODO(fix): when we do a read, we need to GET the string encoding from the
                            // other side, via the lift/lower fn?

                            const count = 1;
                            try {{
                                const {{ id: bufferID, buffer }} = {global_buffer_manager}.createBuffer({{
                                    componentIdx: -1, // componentIdx of -1 indicates the host
                                    count,
                                    isReadable: false,
                                    isWritable: true, // we need to write out the pending buffer (if present)
                                    elemMeta: this.#elemMeta,
                                    data: [],
                                }});
                                buffer.setTarget(`host stream read buffer (id [${{bufferID}}], count [${{count}}])`);

                                let packedResult;
                                packedResult = await this.copy({{
                                    isAsync: true,
                                    count,
                                    bufferID,
                                    buffer,
                                    eventCode: {async_event_code_enum}.STREAM_READ,
                                    componentIdx: -1,
                                }});

                                if (packedResult === {async_blocked_const}) {{
                                    // If the read was blocked, we can only make progress when
                                    // the write side notifies us of a write, then we must attempt the copy again

                                    await new Promise((resolve) => {{
                                        let waitInterval = setInterval(() => {{
                                            if (!this.hasPendingEvent()) {{ return; }}
                                            clearInterval(waitInterval);
                                            resolve();
                                        }});
                                    }});

                                    packedResult = await this.copy({{
                                        isAsync: true,
                                        count,
                                        bufferID,
                                        buffer,
                                        eventCode: {async_event_code_enum}.STREAM_READ,
                                        // NOTE: we skip state checks only when dealing with a post blocked
                                        // read/write in the host. This enables the host to quickly pick up the
                                        // guest operation on the otherside quickly.
                                        skipStateCheck: true,
                                        componentIdx: -1,
                                    }});

                                    const copied = packedResult >> 4;
                                    if (copied === 0 && this.isDoneState()) {{
                                       reject(new Error("write end dropped during read"));
                                    }}

                                    if (packedResult === {async_blocked_const}) {{
                                        throw new Error("unexpected double block during read");
                                    }}
                                }}

                                const vs = buffer.read(count);
                                const res = count === 1 ? vs[0] : vs;
                                this.#result = null;
                                resolve(res);

                            }} catch (err) {{
                                {debug_log_fn}('[{end_class_name}#read()] error', err);
                                reject(err);
                            }}

                            const res = await promise;
                            return {{ value: res, done: res === undefined }};
                         }}
                        "#
                    ),
                    _ => unreachable!("impossible stream readable end class intrinsic"),
                };

                output.push_str(&format!(r#"
                    class {end_class_name} extends {stream_end_class} {{
                        #copying = false;
                        #done = false;

                        #elemMeta = null;
                        // held by both write and read ends
                        #pendingBufferMeta = null;

                        // table index that the stream is in (can change after a stream transfer)
                        #streamTableIdx;
                        // handle (index) inside the given table (can change after a stream transfer)
                        #handle;

                        // internal stream (which has both ends) rep
                        #globalStreamMapRep;

                        // only populated for lowered (read) stream ends
                        #hostInjectFn;
                        // only populated for the write side of a lowered read stream end
                        #isHostOwned;

                        #result = null;

                        constructor(args) {{
                            {debug_log_fn}('[{end_class_name}#constructor()] args', args);
                            super(args);

                            if (!args.elemMeta) {{ throw new Error('missing/invalid element meta'); }}
                            this.#elemMeta = args.elemMeta;

                            if (!args.pendingBufferMeta) {{ throw new Error('missing/invalid shared pending buffer meta'); }}
                            this.#pendingBufferMeta = args.pendingBufferMeta;

                            if (args.tableIdx === undefined) {{ throw new Error('missing index for stream table idx'); }}
                            this.#streamTableIdx = args.tableIdx;

                            this.#hostInjectFn = args.hostInjectFn;
                            this.#isHostOwned = args.hostOwned;
                        }}

                        streamTableIdx() {{ return this.#streamTableIdx; }}
                        setStreamTableIdx(idx) {{ this.#streamTableIdx = idx; }}

                        handle() {{ return this.#handle; }}
                        setHandle(h) {{ this.#handle = h; }}

                        globalStreamMapRep() {{ return this.#globalStreamMapRep; }}
                        setGlobalStreamMapRep(rep) {{ this.#globalStreamMapRep = rep; }}

                        waitableIdx() {{ return this.getWaitable().idx(); }}
                        setWaitableIdx(idx) {{
                            const w = this.getWaitable();
                            w.setIdx(idx);
                            w.setTarget(`waitable for {rw_fn_name} end (waitable [${{idx}}])`);
                        }}

                        setHostInjectFn(f) {{
                            if (this.#hostInjectFn) {{ throw new Error('host injection fn is already set'); }}
                            this.#hostInjectFn = f;
                        }}

                        getElemMeta() {{ return {{...this.#elemMeta}}; }}

                        {type_getter_impl}

                        isDoneState() {{ return this.getCopyState() === {stream_end_class}.CopyState.DONE; }}
                        isCancelledState() {{ return this.getCopyState() === {stream_end_class}.CopyState.CANCELLED; }}
                        isIdleState() {{ return this.getCopyState() === {stream_end_class}.CopyState.IDLE; }}

                        {action_impl}
                        {inner_rw_impl}
                        {copy_setup_impl}
                        {copy_impl}

                        setPendingBufferMeta(args) {{
                            const {{ componentIdx, buffer, onCopyFn, onCopyDoneFn }} = args;
                            this.#pendingBufferMeta.componentIdx = componentIdx;
                            this.#pendingBufferMeta.buffer = buffer;
                            this.#pendingBufferMeta.onCopyFn = onCopyFn;
                            this.#pendingBufferMeta.onCopyDoneFn = onCopyDoneFn;
                        }}

                        resetPendingBufferMeta() {{
                            this.setPendingBufferMeta({{ componentIdx: null, buffer: null, onCopyFn: null, onCopyDoneFn: null }});
                        }}

                        getPendingBufferMeta() {{ return this.#pendingBufferMeta; }}

                        resetAndNotifyPending(result) {{
                            const f = this.#pendingBufferMeta.onCopyDoneFn;
                            this.resetPendingBufferMeta();
                            if (f) {{ f(result); }}
                        }}

                        cancel() {{
                            {debug_log_fn}('[{stream_end_class}#cancel()]');
                            this.resetAndNotifyPending({stream_end_class}.CopyResult.CANCELLED);
                        }}

                        drop() {{
                            {debug_log_fn}('[{stream_end_class}#drop()]');
                            if (this.isDropped()) {{ return; }}
                            super.drop();
                            if (this.#pendingBufferMeta) {{
                                this.resetAndNotifyPending({stream_end_class}.CopyResult.DROPPED);
                            }}
                        }}
                    }}
                "#));
            }

            Self::InternalStreamClass => {
                let debug_log_fn = Intrinsic::DebugLog.name();
                let internal_stream_class_name = self.name();
                let read_end_class = Self::StreamReadableEndClass.name();
                let write_end_class = Self::StreamWritableEndClass.name();

                output.push_str(&format!(
                    r#"
                    class {internal_stream_class_name} {{
                        #pendingBufferMeta = {{}}; // shared between read/write ends
                        #elemMeta;

                        #globalStreamMapRep;

                        #readEnd;
                        #writeEnd;

                        constructor(args) {{
                            {debug_log_fn}('[{internal_stream_class_name}#constructor()] args', args);
                            if (!args.elemMeta) {{ throw new Error('missing/invalid stream element metadata'); }}
                            if (args.tableIdx === undefined) {{ throw new Error('missing/invalid stream table idx'); }}
                            if (!args.readWaitable) {{ throw new Error('missing/invalid read waitable'); }}
                            if (!args.writeWaitable) {{ throw new Error('missing/invalid write waitable'); }}
                            const {{ tableIdx, elemMeta, readWaitable, writeWaitable, }} = args;

                            this.#elemMeta = elemMeta;

                            let dropped = false;
                            const setDroppedFn = () => {{ dropped = true }};
                            const isDroppedFn = () => dropped;

                            this.#readEnd = new {read_end_class}({{
                                tableIdx,
                                elemMeta: this.#elemMeta,
                                pendingBufferMeta: this.#pendingBufferMeta,
                                target: "stream read end (@ init)",
                                waitable: readWaitable,
                                // Only in-component read-ends need the host inject fn if provided,
                                // as that function will *inject* a write when a read is performed
                                // from inside the guest.
                                hostInjectFn: args.hostInjectFn,
                                setDroppedFn,
                                isDroppedFn,
                            }});

                            this.#writeEnd = new {write_end_class}({{
                                tableIdx,
                                elemMeta: this.#elemMeta,
                                pendingBufferMeta: this.#pendingBufferMeta,
                                target: "stream write end (@ init)",
                                waitable: writeWaitable,
                                hostOwned: true,
                                setDroppedFn,
                                isDroppedFn,
                            }});
                        }}

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

                        globalStreamMapRep() {{ return this.#globalStreamMapRep; }}
                        setGlobalStreamMapRep(rep) {{
                            this.#globalStreamMapRep = rep;
                            this.#readEnd.setGlobalStreamMapRep(rep);
                            this.#writeEnd.setGlobalStreamMapRep(rep);
                        }}

                        readEnd() {{ return this.#readEnd; }}
                        writeEnd() {{ return this.#writeEnd; }}
                    }}
                    "#
                ));
            }

            // The host stream class is used exclusively *inside* the host implementation,
            // to represent stream that have been lifted (or originated) external to a given
            // component.
            //
            // For example, after a component-internal stream is lifted from a component (normally
            // by way of returning it from a function), that stream will have been made into a host
            // stream, and *may* give actual end users access via the `createUserStream()` function.
            //
            // At present since streams can only give away the read-end, this usually means that the
            // host stream will be used to often give away the *read* end.
            //
            Self::HostStreamClass => {
                let debug_log_fn = Intrinsic::DebugLog.name();
                let host_stream_class_name = self.name();
                let external_stream_class = Self::ExternalStreamClass.name();
                let get_or_create_async_state_fn =
                    Intrinsic::Component(ComponentIntrinsic::GetOrCreateAsyncState).name();

                output.push_str(&format!(
                    r#"
                    class {host_stream_class_name} {{
                        #componentIdx;
                        #streamEndWaitableIdx;
                        #streamTableIdx;

                        #payloadLiftFn;
                        #payloadLowerFn;

                        #userStream;

                        #rep = null;

                        constructor(args) {{
                            {debug_log_fn}('[{host_stream_class_name}#constructor()] args', args);
                            if (args.componentIdx === undefined) {{ throw new TypeError("missing component idx"); }}
                            this.#componentIdx = args.componentIdx;

                            if (!args.payloadLiftFn) {{ throw new TypeError("missing payload lift fn"); }}
                            this.#payloadLiftFn = args.payloadLiftFn;

                            if (!args.payloadLowerFn) {{ throw new TypeError("missing payload lower fn"); }}
                            this.#payloadLowerFn = args.payloadLowerFn;

                            if (args.streamEndWaitableIdx === undefined) {{ throw new Error("missing stream idx"); }}
                            if (args.streamTableIdx === undefined) {{ throw new Error("missing stream table idx"); }}
                            this.#streamEndWaitableIdx = args.streamEndWaitableIdx;
                            this.#streamTableIdx = args.streamTableIdx;
                        }}

                        setRep(rep) {{ this.#rep = rep; }}
                        getStreamEndWaitableIdx() {{ return this.#streamEndWaitableIdx; }}

                        createUserStream() {{
                           if (this.#userStream) {{ return this.#userStream; }}
                           if (this.#rep === null) {{ throw new Error("unexpectedly missing rep for host stream"); }}

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

                           const streamEnd = cstate.getStreamEnd({{
                               tableIdx: this.#streamTableIdx,
                               streamEndWaitableIdx: this.#streamEndWaitableIdx
                           }});
                           if (!streamEnd) {{
                               throw new Error(`missing stream [${{this.#streamEndWaitableIdx}}] (table [${{this.#streamTableIdx}}], component [${{this.#componentIdx}}]`);
                           }}

                            return new {external_stream_class}({{
                                isReadable: streamEnd.isReadable(),
                                isWritable: streamEnd.isWritable(),
                                globalRep: this.#rep,
                                readFn: async () => {{
                                    return await streamEnd.read();
                                }},
                                writeFn: async (v) => {{
                                    await streamEnd.write(v);
                                }},
                            }});
                        }}
                    }}
                    "#
                ));
            }

            // NOTE: this stream class is meant to be given to external users and can be passed along
            // to the outside world.
            //
            // Functions that return streams should return *this* stream class, and functions that accept
            // streams should return this stream class.
            //
            // TODO(fix): move this stream class to an external @bytecodealliance/p3-runtime package for
            // reuse from inside and outside.
            //
            // TODO(fix): remove host stream rep tracking, force this on the host to maintain as metadata.
            //
            Self::ExternalStreamClass => {
                let debug_log_fn = Intrinsic::DebugLog.name();
                let external_stream_class_name = self.name();
                let symbol_dispose = Intrinsic::SymbolDispose.name();
                let symbol_async_iterator = Intrinsic::SymbolAsyncIterator.name();
                let symbol_cabi_rep = Intrinsic::SymbolResourceRep.name();

                output.push_str(&format!(
                    r#"
                    class {external_stream_class_name} {{
                        #globalRep = null;
                        #isReadable;
                        #isWritable;
                        #writeFn;
                        #readFn;
                        #dropFn;

                        constructor(args) {{
                            {debug_log_fn}('[{external_stream_class_name}#constructor()] args', args);

                            if (args.globalRep === undefined) {{ throw new TypeError("missing host stream rep"); }}
                            this[{symbol_cabi_rep}] = args.globalRep;

                            if (args.isReadable === undefined) {{ throw new TypeError("missing readable setting"); }}
                            this.#isReadable = args.isReadable;

                            if (args.isWritable === undefined) {{ throw new TypeError("missing writable setting"); }}
                            this.#isWritable = args.isWritable;

                            if (this.#isWritable && args.writeFn === undefined) {{ throw new TypeError("missing write fn"); }}
                            this.#writeFn = args.writeFn;

                            if (this.#isReadable && args.readFn === undefined) {{ throw new TypeError("missing read fn"); }}
                            this.#readFn = args.readFn;

                            this.#dropFn = args.dropFn;
                        }}

                        [{symbol_async_iterator}]() {{ return this; }}

                        async next() {{
                            {debug_log_fn}('[{external_stream_class_name}#next()]');
                            if (!this.#isReadable) {{ throw new Error("stream is not marked as readable and cannot be written from"); }}
                            return this.#readFn();
                        }}

                        async write() {{
                            {debug_log_fn}('[{external_stream_class_name}#write()]');
                            if (!this.#isWritable) {{ throw new Error("stream is not marked as writable and cannot be written to"); }}

                            const objects = [...arguments];
                            if (!objects.length !== 1) {{
                                throw new Error("only single object writes are currently supported");
                            }}
                            const obj = objects[0];

                            this.#writeFn(obj);
                        }}

                        [{symbol_dispose}]() {{
                            this.#dropFn();
                        }}

                    }}
                    "#
                ));
            }

            Self::GlobalStreamMap => {
                let global_stream_map = Self::GlobalStreamMap.name();
                let rep_table_class = Intrinsic::RepTableClass.name();
                output.push_str(&format!(
                    r#"
                    const {global_stream_map} = new {rep_table_class}({{ target: 'global stream map' }});
                    "#
                ));
            }

            Self::GlobalStreamTableMap => {
                let global_stream_table_map = Self::GlobalStreamTableMap.name();
                output.push_str(&format!(
                    r#"
                    const {global_stream_table_map} = {{}};
                    "#
                ));
            }

            // TODO: allow customizable stream functionality (user should be able to specify a lib/import for a 'stream()' function
            // (this will enable using p3-shim explicitly or any other implementation)
            //
            // NOTE: Unit streams are represented with a streamTypeRep of null
            Self::StreamNew => {
                let debug_log_fn = Intrinsic::DebugLog.name();
                let stream_new_fn = Self::StreamNew.name();
                let current_task_get_fn =
                    Intrinsic::AsyncTask(AsyncTaskIntrinsic::GetCurrentTask).name();
                let get_or_create_async_state_fn =
                    Intrinsic::Component(ComponentIntrinsic::GetOrCreateAsyncState).name();
                output.push_str(&format!(r#"
                    function {stream_new_fn}(ctx) {{
                        {debug_log_fn}('[{stream_new_fn}()] args', {{ ctx }});
                        const {{
                            streamTableIdx,
                            callerComponentIdx,
                            elemMeta,
                        }} = ctx;
                        if (callerComponentIdx === undefined) {{ throw new Error("missing caller component idx during stream.new"); }}

                        const taskMeta = {current_task_get_fn}(callerComponentIdx);
                        if (!taskMeta) {{ throw new Error('missing async task metadata during stream.new'); }}

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

                        if (task.componentIdx() !== callerComponentIdx) {{
                            throw new Error(`task component idx [${{task.componentIdx()}}] does not match stream new intrinsic component idx [${{callerComponentIdx}}]`);
                        }}

                        const cstate = {get_or_create_async_state_fn}(callerComponentIdx);
                        if (!cstate.mayLeave) {{
                            throw new Error('component instance is not marked as may leave during stream.new');
                        }}

                        const {{ writeEndWaitableIdx, readEndWaitableIdx, writeEndHandle, readEndHandle }} = cstate.createStream({{
                            tableIdx: streamTableIdx,
                            elemMeta,
                        }});

                        {debug_log_fn}('[{stream_new_fn}()] created stream ends', {{
                            writeEnd: {{
                                waitableIdx: writeEndWaitableIdx,
                                handle: writeEndHandle,
                            }},
                            readEnd: {{
                                waitableIdx: readEndWaitableIdx,
                                handle: readEndHandle,
                            }},
                            streamTableIdx,
                            callerComponentIdx,
                        }});

                        return (BigInt(writeEndWaitableIdx) << 32n) | BigInt(readEndWaitableIdx);
                    }}
                "#));
            }

            Self::StreamNewFromLift => {
                let debug_log_fn = Intrinsic::DebugLog.name();
                let stream_new_from_lift_fn = self.name();
                let global_stream_map =
                    Intrinsic::AsyncStream(AsyncStreamIntrinsic::GlobalStreamMap).name();
                let host_stream_class =
                    Intrinsic::AsyncStream(AsyncStreamIntrinsic::HostStreamClass).name();

                output.push_str(&format!(
                    r#"
                    function {stream_new_from_lift_fn}(ctx) {{
                        {debug_log_fn}('[{stream_new_from_lift_fn}()] args', {{ ctx }});
                        const {{
                            componentIdx,
                            streamEndWaitableIdx,
                            streamTableIdx,
                            payloadLiftFn,
                            payloadTypeSize32,
                            payloadLowerFn,
                        }} = ctx;

                        const stream = new {host_stream_class}({{
                            componentIdx,
                            streamEndWaitableIdx,
                            streamTableIdx,
                            payloadLiftFn: payloadLiftFn,
                            payloadLowerFn: payloadLowerFn,
                        }});

                        const rep = {global_stream_map}.insert(stream);
                        stream.setRep(rep);

                        return stream.createUserStream();
                    }}
                "#
                ));
            }

            // NOTE: reads/writes are rendezvous based for P3, meaning that every write matches with a read.
            //
            // The pending buffer represents waiting write/read buffer.
            //
            Self::StreamWrite | Self::StreamRead => {
                let debug_log_fn = Intrinsic::DebugLog.name();
                let stream_op_fn = self.name();
                let get_or_create_async_state_fn =
                    Intrinsic::Component(ComponentIntrinsic::GetOrCreateAsyncState).name();
                let may_block = AsyncTaskIntrinsic::CurrentTaskMayBlock.name();
                let async_event_code_enum = Intrinsic::AsyncEventCodeEnum.name();
                let managed_buffer_class = Intrinsic::ManagedBufferClass.name();
                let (event_code, stream_end_class) = match self {
                    Self::StreamWrite => (
                        format!("{async_event_code_enum}.STREAM_WRITE"),
                        &Self::StreamWritableEndClass.name(),
                    ),
                    Self::StreamRead => (
                        format!("{async_event_code_enum}.STREAM_READ"),
                        &Self::StreamReadableEndClass.name(),
                    ),
                    _ => unreachable!("unexpected stream operation"),
                };

                output.push_str(&format!(r#"
                    async function {stream_op_fn}(
                        ctx,
                        streamEndWaitableIdx,
                        ptr,
                        count,
                    ) {{
                        {debug_log_fn}('[{stream_op_fn}()] args', {{ ctx, streamEndWaitableIdx, ptr, count }});
                        const {{
                            componentIdx,
                            memoryIdx,
                            getMemoryFn,
                            reallocIdx,
                            getReallocFn,
                            stringEncoding,
                            isAsync,
                            streamTableIdx,
                        }} = ctx;

                        if (componentIdx === undefined) {{ throw new TypeError("missing/invalid component idx"); }}
                        if (streamTableIdx === undefined) {{ throw new TypeError("missing/invalid stream table idx"); }}
                        if (streamEndWaitableIdx === undefined) {{ throw new TypeError("missing/invalid stream end idx"); }}

                        // count may come in as u32::MAX which is mangled by JS into a negative value
                        count = Math.min(count >>> 0, {managed_buffer_class}.MAX_LENGTH);

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

                        if (!{may_block} && !isAsync) {{
                            throw new Error('trap: only async tasks or otherwise blocking-allowed tasks my stream.{stream_op_fn}');
                        }}

                        const streamEnd = cstate.getStreamEnd({{ tableIdx: streamTableIdx, streamEndWaitableIdx }});
                        if (!streamEnd) {{
                            throw new Error(`missing stream end [${{streamEndWaitableIdx}}] (table [${{streamTableIdx}}], component [${{componentIdx}}])`);
                        }}
                        if (!(streamEnd instanceof {stream_end_class})) {{
                            throw new Error('invalid stream type, expected {stream_end_class}');
                        }}
                        if (streamEnd.streamTableIdx() !== streamTableIdx) {{
                            throw new Error(`stream end table idx [${{streamEnd.streamTableIdx()}}] != operation table idx [${{streamTableIdx}}]`);
                        }}

                        const result = await streamEnd.copy({{
                            isAsync,
                            memory: getMemoryFn(),
                            ptr,
                            count,
                            eventCode: {event_code},
                            componentIdx,
                            stringEncoding,
                            reallocFn: getReallocFn(),
                        }});

                        return result;
                    }}
                "#));
            }

            Self::StreamCancelRead | Self::StreamCancelWrite => {
                let debug_log_fn = Intrinsic::DebugLog.name();
                let stream_cancel_fn = self.name();
                let async_blocked_const =
                    Intrinsic::AsyncTask(AsyncTaskIntrinsic::AsyncBlockedConstant).name();
                let is_cancel_write = matches!(self, Self::StreamCancelWrite);
                let event_code_enum = format!(
                    "{}.STREAM_{}",
                    Intrinsic::AsyncEventCodeEnum.name(),
                    if is_cancel_write { "WRITE" } else { "READ" }
                );
                let stream_end_class = if is_cancel_write {
                    Self::StreamWritableEndClass.name()
                } else {
                    Self::StreamReadableEndClass.name()
                };
                let current_task_get_fn =
                    Intrinsic::AsyncTask(AsyncTaskIntrinsic::GetCurrentTask).name();
                let get_or_create_async_state_fn =
                    Intrinsic::Component(ComponentIntrinsic::GetOrCreateAsyncState).name();
                output.push_str(&format!(r#"
                    async function {stream_cancel_fn}(ctx, streamEndWaitableIdx) {{
                        {debug_log_fn}('[{stream_cancel_fn}()] args', {{ ctx, streamEndWaitableIdx }});
                        const {{ streamTableIdx, isAsync, componentIdx }} = ctx;

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

                        const streamEnd = cstate.getStreamEnd({{ streamEndWaitableIdx, tableIdx: streamTableIdx }});
                        if (!streamEnd) {{ throw new Error('missing stream end with idx [' + streamEndWaitableIdx + ']'); }}
                        if (!(streamEnd instanceof {stream_end_class})) {{ throw new Error('invalid stream end, expected value of type [{stream_end_class}]'); }}

                        if (!streamEnd.isCopying()) {{ throw new Error('stream end is not copying, cannot cancel'); }}

                        streamEnd.setCopyState({stream_end_class}.CopyState.CANCELLING_COPY);

                        if (!streamEnd.hasPendingEvent()) {{

                            streamEnd.cancel();

                            if (!streamEnd.hasPendingEvent()) {{
                                if (isAsync) {{ return {async_blocked_const}; }}

                                const taskMeta = {current_task_get_fn}(componentIdx);
                                if (!taskMeta) {{ throw new Error('missing current task metadata while doing stream transfer'); }}
                                const task = taskMeta.task;
                                if (!task) {{ throw new Error('missing task while doing stream transfer'); }}
                                await task.suspendUntil({{ readyFn: () => streamEnd.hasPendingEvent() }});
                            }}
                        }}

                        const event = streamEnd.getPendingEvent();
                        const {{ code, payload0: index, payload1: payload }} = event;
                        if (streamEnd.isCopying()) {{
                            throw new Error(`stream end (idx [${{streamEndWaitableIdx}}]) is still in copying state`);
                        }}
                        if (code !== {event_code_enum}) {{
                            throw new Error(`unexpected event code [${{code}}], expected [{event_code_enum}]`);
                        }}
                        if (index !== streamEnd.waitableIdx()) {{ throw new Error('event index does not match stream end'); }}

                        {debug_log_fn}('[{stream_cancel_fn}()] successful cancel', {{ ctx, streamEndWaitableIdx, streamEnd, event }});
                        return payload;
                    }}
                "#));
            }

            // NOTE: as writable drops are called from guests, they may happen *after*
            // a host has tried to read off the end (i.e. getting back the async blocked constant),
            // when running non-deterministrically (the default)
            Self::StreamDropReadable | Self::StreamDropWritable => {
                let debug_log_fn = Intrinsic::DebugLog.name();
                let stream_drop_fn = self.name();
                let current_task_get_fn =
                    Intrinsic::AsyncTask(AsyncTaskIntrinsic::GetCurrentTask).name();
                let is_write = matches!(self, Self::StreamDropWritable);
                let stream_end_class = if is_write {
                    Self::StreamWritableEndClass.name()
                } else {
                    Self::StreamReadableEndClass.name()
                };
                let get_or_create_async_state_fn =
                    Intrinsic::Component(ComponentIntrinsic::GetOrCreateAsyncState).name();
                output.push_str(&format!(r#"
                    function {stream_drop_fn}(ctx, streamEndWaitableIdx) {{
                        {debug_log_fn}('[{stream_drop_fn}()] args', {{ ctx, streamEndWaitableIdx }});
                        const {{ streamTableIdx, componentIdx }} = ctx;

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

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

                        const streamEnd = cstate.deleteStreamEnd({{ tableIdx: streamTableIdx, streamEndWaitableIdx }});
                        if (!streamEnd) {{
                            throw new Error(`missing stream (waitable [${{streamEndWaitableIdx}}], table [${{streamTableIdx}}], component [${{componentIdx}}])`);
                        }}

                        if (!(streamEnd instanceof {stream_end_class})) {{
                          throw new Error('invalid stream end class, expected [{stream_end_class}]');
                        }}

                        streamEnd.drop();
                    }}
                "#));
            }

            Self::StreamTransfer => {
                let debug_log_fn = Intrinsic::DebugLog.name();
                let stream_transfer_fn = self.name();
                let get_global_current_task_meta_fn = Intrinsic::GetGlobalCurrentTaskMetaFn.name();
                let current_task_get_fn = AsyncTaskIntrinsic::GetCurrentTask.name();
                let get_or_create_async_state_fn =
                    Intrinsic::Component(ComponentIntrinsic::GetOrCreateAsyncState).name();
                let global_stream_table_map = AsyncStreamIntrinsic::GlobalStreamTableMap.name();

                output.push_str(&format!(
                    r#"
                    function {stream_transfer_fn}(
                        srcStreamWaitableIdx,
                        srcTableIdx,
                        destTableIdx,
                    ) {{
                        {debug_log_fn}('[{stream_transfer_fn}()] args', {{
                            srcStreamWaitableIdx,
                            srcTableIdx,
                            destTableIdx,
                        }});

                        const streamMeta = {global_stream_table_map}[srcTableIdx];
                        if (!streamMeta) {{ throw new Error('missing stream meta during transfer'); }}
                        const componentIdx = streamMeta.componentIdx;

                        const globalTaskMeta = {get_global_current_task_meta_fn}(componentIdx);
                        if (!globalTaskMeta) {{ throw new Error('missing global current task globalTaskMeta'); }}
                        const taskID = globalTaskMeta.taskID;

                        const taskMeta = {current_task_get_fn}(componentIdx, taskID);
                        if (!taskMeta) {{ throw new Error('missing current task metadata while doing stream transfer'); }}

                        const task = taskMeta.task;
                        if (!task) {{ throw new Error('missing task while doing stream transfer'); }}
                        if (componentIdx !== task.componentIdx()) {{
                            throw new Error("task component ID should match current component ID");
                        }}

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

                        const streamEnd = cstate.removeStreamEndFromTable({{ tableIdx: srcTableIdx, streamWaitableIdx: srcStreamWaitableIdx }});
                        if (!streamEnd.isReadable()) {{
                            throw new Error("writable stream ends cannot be moved");
                        }}
                        if (streamEnd.isDoneState()) {{
                            throw new Error('readable ends cannot be moved once writable ends are dropped');
                        }}

                        const {{ handle, waitableIdx }} = cstate.addStreamEndToTable({{ tableIdx: destTableIdx, streamEnd }});
                        streamEnd.setTarget(`stream read end (waitable [${{waitableIdx}}])`);

                        {debug_log_fn}('[{stream_transfer_fn}()] successfully transferred', {{
                            dest: {{
                                streamEndHandle: handle,
                                streamEndWaitableIdx: waitableIdx,
                                tableIdx: destTableIdx,
                            }},
                            src: {{
                                streamEndWaitableIdx: srcStreamWaitableIdx,
                                tableIdx: srcTableIdx,
                            }},
                            componentIdx,
                        }});

                        return waitableIdx;

                      }}
                "#
                ));
            }

            Self::IsStreamLowerableObject => {
                let is_stream_lowerable_object = self.name();
                let external_stream_class = Self::ExternalStreamClass.name();
                let async_iterator_symbol = Intrinsic::SymbolAsyncIterator.name();
                let iterator_symbol = Intrinsic::SymbolIterator.name();
                let external_readable_stream_class = Intrinsic::PlatformReadableStreamClass.name();

                output.push_str(&format!(
                    r#"
                      function {is_stream_lowerable_object}(obj) {{
                          if (typeof obj !== 'object') {{ return false; }}
                          return obj instanceof {external_stream_class}
                               || {async_iterator_symbol} in obj
                               || {iterator_symbol} in obj
                               || obj instanceof {external_readable_stream_class};
                      }}
                    "#
                ));
            }

            Self::GenReadFnFromLowerableStream => {
                let gen_read_fn_from_lowerable_stream = self.name();
                let is_stream_lowerable_object = Self::IsStreamLowerableObject.name();
                let async_iterator_symbol = Intrinsic::SymbolAsyncIterator.name();
                let iterator_symbol = Intrinsic::SymbolIterator.name();
                let external_readable_stream_class = Intrinsic::PlatformReadableStreamClass.name();

                output.push_str(&format!(
                    r#"
                      function {gen_read_fn_from_lowerable_stream}(stream) {{
                          if (!{is_stream_lowerable_object}(stream)) {{
                              throw new Error("cannot generate read fn: object is not a stream lowerable object");
                          }}

                          let readFn;
                          if ({async_iterator_symbol} in stream) {{
                              let asyncIterator = stream[{async_iterator_symbol}]();
                              readFn = () => asyncIterator.next();
                          }} else if ({iterator_symbol} in stream) {{
                              let iterator = stream[{iterator_symbol}]();
                              readFn = async () => iterator.next();
                          }} else if (stream instanceof {external_readable_stream_class}) {{
                              // At this point we're dealing with a readable stream that *somehow *does not*
                              // implement the async iterator protocol.
                              const lockedReader = stream.getReader();
                              readFn = () => lockedReader.read();
                          }} else {{
                              throw new Error("invalid stream object, cannot generate read fn");
                          }}

                          return readFn;
                      }}
                    "#
                ));
            }

            Self::GenHostInjectFn => {
                let gen_host_inject_fn = self.name();

                output.push_str(&format!(
                    r#"
                      function {gen_host_inject_fn}(genArgs) {{
                          const {{ readFn, hostWriteEnd }} = genArgs;
                          const doNothingFn = () => {{}};
                          const resetWriteEndToIdleFn = () => {{
                              // After the write is finished, we consume the event that was generated
                              // by the just-in-time write (and the subsequent read), if one was generated
                              if (hostWriteEnd.hasPendingEvent()) {{ hostWriteEnd.getPendingEvent(); }}
                          }};

                          let done = false;

                          return async (args) => {{
                              let {{ count }} = args;
                              if (count < 0) {{ throw new Error('invalid count'); }}
                              if (count === 0) {{ return doNothingFn; }}

                              // If we get another read when done is already set, that was
                              // the case of a iterator that returned a final value
                              // along with `done: true`
                              if (done) {{
                                  hostWriteEnd.getPendingEvent();
                                  hostWriteEnd.drop();
                                  return doNothingFn;
                              }}

                              if (hostWriteEnd.isDoneState()) {{
                                  return doNothingFn;
                              }}

                              const values = [];
                              while (count > 0 && !done) {{
                                  const res = await readFn();
                                  if (res.value !== undefined) {{ values.push(res.value); }}
                                  done = res.done;
                                  if (done) {{ break; }}
                                  count -= 1;
                              }}

                              // Iterator provided `done: true` with no final value
                              if (done && values.length === 0) {{
                                  hostWriteEnd.getPendingEvent();
                                  hostWriteEnd.drop();
                                  return doNothingFn;
                              }}

                              await hostWriteEnd.write(values);

                              return resetWriteEndToIdleFn;
                          }};
                      }}
                    "#
                ));
            }
        }
    }
}