js-component-bindgen 1.16.6

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
//! Intrinsics used from JS

use std::collections::{BTreeSet, HashSet};
use std::fmt::Write;

use crate::source::Source;
use crate::{uwrite, uwriteln};

pub(crate) mod conversion;
use conversion::ConversionIntrinsic;

pub(crate) mod js_helper;
use js_helper::JsHelperIntrinsic;

pub(crate) mod webidl;
use webidl::WebIdlIntrinsic;

pub(crate) mod string;
use string::StringIntrinsic;

pub(crate) mod resource;
use resource::ResourceIntrinsic;

pub(crate) mod lift;
use lift::LiftIntrinsic;

pub(crate) mod lower;
use lower::LowerIntrinsic;

pub(crate) mod component;
use component::ComponentIntrinsic;

pub(crate) mod p3;
use p3::async_future::AsyncFutureIntrinsic;
use p3::async_stream::AsyncStreamIntrinsic;
use p3::async_task::AsyncTaskIntrinsic;
use p3::error_context::ErrCtxIntrinsic;
use p3::host::HostIntrinsic;
use p3::waitable::WaitableIntrinsic;

/// List of all intrinsics that are used by these
///
/// These intrinsics refer to JS code that is included in order to make
/// transpiled WebAssembly components and their imports/exports functional
/// in the relevant JS context.
#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
pub enum Intrinsic {
    JsHelper(JsHelperIntrinsic),
    WebIdl(WebIdlIntrinsic),
    Conversion(ConversionIntrinsic),
    String(StringIntrinsic),
    Resource(ResourceIntrinsic),
    ErrCtx(ErrCtxIntrinsic),
    AsyncTask(AsyncTaskIntrinsic),
    Waitable(WaitableIntrinsic),
    Lift(LiftIntrinsic),
    Lower(LowerIntrinsic),
    AsyncStream(AsyncStreamIntrinsic),
    AsyncFuture(AsyncFutureIntrinsic),
    Component(ComponentIntrinsic),
    Host(HostIntrinsic),

    // Polyfills
    PromiseWithResolversPonyfill,

    /// Enable debug logging
    DebugLog,

    /// Global setting for determinism (used in async)
    GlobalAsyncDeterminism,

    /// Randomly produce a boolean true/false
    CoinFlip,

    // Basic type helpers
    ConstantI32Max,
    ConstantI32Min,
    TypeCheckValidI32,
    TypeCheckAsyncFn,
    AsyncFunctionCtor,

    Base64Compile,
    ClampGuest,
    FetchCompile,

    // Globals
    SymbolCabiDispose,
    SymbolCabiLower,
    SymbolResourceHandle,
    SymbolResourceRep,
    SymbolDispose,
    SymbolAsyncIterator,
    SymbolIterator,
    ScopeId,
    DefinedResourceTables,
    HandleTables,

    /// Class that conforms to a `ReadableStreams`-like interface and is usable externally
    ///
    /// This is normally the `ReadableStream` class provided by the platform itself.
    PlatformReadableStreamClass,

    // Global Initializers
    FinalizationRegistryCreate,

    // Global classes
    ComponentError,

    // WASI object helpers
    GetErrorPayload,
    GetErrorPayloadString,

    /// Class that manages (and synchronizes) writes to managed buffers
    ManagedBufferClass,

    /// Buffer manager that is used to synchronize component writes
    BufferManagerClass,

    /// Global for an instantiated buffer manager singleton
    GlobalBufferManager,

    /// Reusable table structure for holding canonical ABI objects by their representation/identifier of (e.g. resources, waitables, etc)
    ///
    /// Representations of objects stored in one of these tables is a u32 (0 is expected to be an invalid index).
    RepTableClass,

    /// Event codes used for async, as a JS enum
    AsyncEventCodeEnum,

    // JS helper functions
    IsLE,
    ThrowInvalidBool,
    ThrowUninitialized,
    HasOwnProperty,
    InstantiateCore,

    /// Tracking of component memories
    GlobalComponentMemoryMap,

    /// Tracking of component memories
    RegisterGlobalMemoryForComponent,

    /// Tracking of component memories
    LookupMemoriesForComponent,

    /// Global that tracks the current task
    GlobalCurrentTaskMeta,

    /// Gets the current global task state
    GetGlobalCurrentTaskMetaFn,

    /// Gets the current global task state
    SetGlobalCurrentTaskMetaFn,

    /// Execute a closure with a certain set current task
    WithGlobalCurrentTaskMetaFn,

    /// Execute an async closure with a certain set current task
    WithGlobalCurrentTaskMetaFnAsync,

    /// Clear the global task meta
    ClearGlobalCurrentTaskMetaFn,
}

impl Intrinsic {
    pub fn render(&self, output: &mut Source, args: &RenderIntrinsicsArgs) {
        match self {
            Intrinsic::JsHelper(i) => i.render(output),
            Intrinsic::Conversion(i) => i.render(output),
            Intrinsic::String(i) => i.render(output),
            Intrinsic::ErrCtx(i) => i.render(output),
            Intrinsic::Resource(i) => i.render(output),
            Intrinsic::AsyncTask(i) => i.render(output),
            Intrinsic::Waitable(i) => i.render(output, args),
            Intrinsic::Lift(i) => i.render(output),
            Intrinsic::Lower(i) => i.render(output),
            Intrinsic::AsyncStream(i) => i.render(output),
            Intrinsic::AsyncFuture(i) => i.render(output),
            Intrinsic::Component(i) => i.render(output),
            Intrinsic::Host(i) => i.render(output),

            Intrinsic::GlobalAsyncDeterminism => {
                output.push_str(&format!(
                    "const {var_name} = '{determinism}';\n",
                    var_name = self.name(),
                    determinism = args.determinism,
                ));
            }

            Intrinsic::CoinFlip => {
                output.push_str(&format!(
                    "const {var_name} = () => {{ return Math.random() > 0.5; }};\n",
                    var_name = self.name(),
                ));
            }

            Intrinsic::ConstantI32Min => output.push_str(&format!(
                "const {const_name} = -2_147_483_648;\n",
                const_name = self.name()
            )),
            Intrinsic::ConstantI32Max => output.push_str(&format!(
                "const {const_name} = 2_147_483_647;\n",
                const_name = self.name()
            )),
            Intrinsic::TypeCheckValidI32 => {
                let i32_const_min = Intrinsic::ConstantI32Min.name();
                let i32_const_max = Intrinsic::ConstantI32Max.name();
                output.push_str(&format!("const {fn_name} = (n) => typeof n === 'number' && n >= {i32_const_min} && n <= {i32_const_max};\n", fn_name = self.name()))
            }

            Intrinsic::AsyncFunctionCtor => {
                let async_fn_type = Intrinsic::AsyncFunctionCtor.name();
                uwriteln!(
                    output,
                    "const {async_fn_type} = (async () => {{}}).constructor;"
                );
            }

            Intrinsic::TypeCheckAsyncFn => {
                let async_fn_check = Intrinsic::TypeCheckAsyncFn.name();
                let async_fn_ctor = Intrinsic::AsyncFunctionCtor.name();
                uwriteln!(
                    output,
                    r#"
                    const {async_fn_check} = (f) => {{
                        return f instanceof {async_fn_ctor};
                    }};
                    "#,
                );
            }

            Intrinsic::Base64Compile => {
                if !args.no_nodejs_compat {
                    output.push_str("
                    const base64Compile = str => WebAssembly.compile(typeof Buffer !== 'undefined' ? Buffer.from(str, 'base64') : Uint8Array.from(atob(str), b => b.charCodeAt(0)));
                ")
                } else {
                    output.push_str("
                    const base64Compile = str => WebAssembly.compile(Uint8Array.from(atob(str), b => b.charCodeAt(0)));
                ")
                }
            }

            Intrinsic::ClampGuest => output.push_str(
                "
                function clampGuest(i, min, max) {
                    if (i < min || i > max) \
                    throw new TypeError(`must be between ${min} and ${max}`);
                    return i;
                }
            ",
            ),

            Intrinsic::ComponentError => output.push_str(
                "
                class ComponentError extends Error {
                    constructor (value) {
                        const enumerable = typeof value !== 'string';
                        super(enumerable ? `${String(value)} (see error.payload)` : value);
                        Object.defineProperty(this, 'payload', { value, enumerable });
                    }
                }
            ",
            ),

            Intrinsic::DefinedResourceTables => {}

            Intrinsic::FinalizationRegistryCreate => output.push_str(
                "
                function finalizationRegistryCreate (unregister) {
                    if (typeof FinalizationRegistry === 'undefined') {
                        return { unregister () {} };
                    }
                    return new FinalizationRegistry(unregister);
                }
            ",
            ),

            Intrinsic::FetchCompile => {
                if !args.no_nodejs_compat {
                    output.push_str("
                    const isNode = typeof process !== 'undefined' && process.versions && process.versions.node;
                    let _fs;
                    async function fetchCompile (url) {
                        if (isNode) {
                            _fs = _fs || await import('node:fs/promises');
                            return WebAssembly.compile(await _fs.readFile(url));
                        }
                        return fetch(url).then(WebAssembly.compileStreaming);
                    }
                ")
                } else {
                    output.push_str(
                        "
                    const fetchCompile = url => fetch(url).then(WebAssembly.compileStreaming);
                ",
                    )
                }
            }

            Intrinsic::GetErrorPayload => {
                let hop = Intrinsic::HasOwnProperty.name();
                uwrite!(
                    output,
                    "
                    function getErrorPayload(e) {{
                        if (e && {hop}.call(e, 'payload')) return e.payload;
                        if (e instanceof Error) throw e;
                        return e;
                    }}
                "
                )
            }

            Intrinsic::GetErrorPayloadString => {
                let hop = Intrinsic::HasOwnProperty.name();
                uwrite!(
                    output,
                    "
                    function getErrorPayloadString(e) {{
                        if (e && {hop}.call(e, 'payload')) return e.payload;
                        if (e instanceof Error) return e.message;
                        return e;
                    }}
                "
                )
            }

            Intrinsic::WebIdl(w) => w.render(output),

            Intrinsic::HandleTables => output.push_str(
                "
                const handleTables = [];
            ",
            ),

            Intrinsic::HasOwnProperty => output.push_str(
                "
                const hasOwnProperty = Object.prototype.hasOwnProperty;
            ",
            ),

            Intrinsic::InstantiateCore => {
                if !args.instantiation {
                    output.push_str(
                        "
                    const instantiateCore = WebAssembly.instantiate;
                ",
                    )
                }
            }

            Intrinsic::IsLE => output.push_str(
                "
                const isLE = new Uint8Array(new Uint16Array([1]).buffer)[0] === 1;
            ",
            ),

            Intrinsic::SymbolCabiDispose => output.push_str(
                "
                const symbolCabiDispose = Symbol.for('cabiDispose');
            ",
            ),

            Intrinsic::SymbolCabiLower => output.push_str(
                "
                const symbolCabiLower = Symbol.for('cabiLower');
            ",
            ),

            Intrinsic::ScopeId => {
                let name = self.name();
                uwriteln!(output, "let {name} = 0;");
            }

            Intrinsic::SymbolResourceHandle => output.push_str(
                "
                const symbolRscHandle = Symbol('handle');
            ",
            ),

            Intrinsic::SymbolResourceRep => output.push_str(
                "
                const symbolRscRep = Symbol.for('cabiRep');
            ",
            ),

            Intrinsic::SymbolDispose => {
                let var_name = self.name();
                uwriteln!(
                    output,
                    "const {var_name} = Symbol.dispose || Symbol.for('dispose');"
                );
            }

            Intrinsic::SymbolAsyncIterator => {
                let var_name = self.name();
                uwriteln!(output, "const {var_name} = Symbol.asyncIterator;");
            }

            Intrinsic::SymbolIterator => {
                let var_name = self.name();
                uwriteln!(output, "const {var_name} = Symbol.iterator;");
            }

            Intrinsic::ThrowInvalidBool => output.push_str(
                "
                function throwInvalidBool() {
                    throw new TypeError('invalid variant discriminant for bool');
                }
            ",
            ),

            Intrinsic::ThrowUninitialized => output.push_str(
                "
                function throwUninitialized() {
                    throw new TypeError('Wasm uninitialized use `await $init` first');
                }
            ",
            ),

            Intrinsic::DebugLog => {
                let fn_name = Intrinsic::DebugLog.name();
                output.push_str(&format!(
                    "
                    const {fn_name} = (...args) => {{
                        if (!globalThis?.process?.env?.JCO_DEBUG) {{ return; }}
                        console.debug(...args);
                    }};
                "
                ));
            }

            Intrinsic::PromiseWithResolversPonyfill => {
                let fn_name = self.name();
                output.push_str(&format!(
                    r#"
                    function {fn_name}() {{
                        if (Promise.withResolvers) {{
                            return Promise.withResolvers();
                        }} else {{
                            let resolve;
                            let reject;
                            const promise = new Promise((res, rej) => {{
                                resolve = res;
                                reject = rej;
                            }});
                            return {{ promise, resolve, reject }};
                        }}
                    }}
                "#
                ));
            }

            Intrinsic::AsyncEventCodeEnum => {
                let name = Intrinsic::AsyncEventCodeEnum.name();
                output.push_str(&format!(
                    "
                    const {name} = {{
                        NONE: 0,
                        SUBTASK: 1,
                        STREAM_READ: 2,
                        STREAM_WRITE: 3,
                        FUTURE_READ: 4,
                        FUTURE_WRITE: 5,
                        TASK_CANCELLED: 6,
                    }};
                "
                ));
            }

            Intrinsic::ManagedBufferClass => {
                let debug_log_fn = Intrinsic::DebugLog.name();
                let managed_buffer_class = Intrinsic::ManagedBufferClass.name();
                output.push_str(&format!(
                    r#"
                    class {managed_buffer_class} {{
                        static MAX_LENGTH = 2**28 - 1;
                        #componentIdx;
                        #memory;

                        #elemMeta = null;

                        #start;
                        #ptr;
                        capacity;
                        processed = 0;

                        #hostOnlyData; // initial data (only filled out for host-owned)

                        target;

                        constructor(args) {{
                            if (args.capacity > {managed_buffer_class}.MAX_LENGTH) {{
                                 throw new Error(`buffer size [${{args.capacity}}] greater than max length`);
                            }}
                            if (args.componentIdx === undefined) {{ throw new TypeError('missing/invalid component idx'); }}
                            if (args.capacity === undefined) {{ throw new TypeError('missing/invalid capacity'); }}
                            if (!args.elemMeta || typeof args.elemMeta.align32 !== 'number') {{
                                throw new TypeError('missing/invalid element metadata');
                            }}

                            if (!args.memory && args.start === undefined && args.data === undefined) {{
                                throw new TypeError('either memory and start ptr or data must be provided for managed buffers');
                            }}

                            if (args.memory && args.start == undefined) {{
                                throw new TypeError('missing/invalid start ptr, depsite memory being present');
                            }}

                            if (!args.elemMeta.isNone && args.capacity > 0) {{
                                if (args.start && args.start % args.elemMeta.align32 !== 0) {{
                                    throw new Error(`invalid alignment: type with 32bit alignment [${{args.elemMeta.align32}}] at starting pointer [${{args.start}}]`);
                                }}
                                // TODO: memory lenght bounds check
                            }}

                            this.#componentIdx = args.componentIdx;
                            this.#memory = args.memory;
                            this.#start = args.start;
                            this.#ptr = this.#start;
                            this.capacity = args.capacity;
                            this.#elemMeta = args.elemMeta;

                            if (args.data !== undefined && !Array.isArray(args.data)) {{
                                throw new TypeError('host-only data must be an array');
                            }}
                            this.#hostOnlyData = args.data;

                            this.target = args.target;
                        }}

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

                        remaining() {{
                            return this.capacity - this.processed;
                        }}

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

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

                        isHostOwned() {{ return !this.#memory; }}

                        read(count) {{
                            {debug_log_fn}('[{managed_buffer_class}#read()] args', {{ count }});
                            if (count === undefined || count <= 0) {{
                                throw new TypeError(`missing/invalid count [${{count}}]`);
                            }}

                            const cap = this.capacity;
                            if (count > cap) {{
                                throw new Error(`cannot read [${{count}}] elements from buffer with capacity [${{cap}}]`);
                            }}

                            let values = [];
                            if (this.#elemMeta.isNone) {{
                                values = [...new Array(count)].map(() => null);
                            }} else {{
                                if (this.isHostOwned()) {{
                                    const remainingItems = this.#hostOnlyData.slice(count);
                                    values.push(...this.#hostOnlyData.slice(0, count));
                                    this.#hostOnlyData = remainingItems;
                                }} else {{
                                    let currentCount = count;
                                    let startPtr = this.#ptr;
                                    if (this.#elemMeta.stringEncoding === undefined) {{
                                        throw new Error('string encoding unknown during read');
                                    }}
                                    let liftCtx = {{
                                        storagePtr: startPtr,
                                        memory: this.#memory,
                                        componentIdx: this.#componentIdx,
                                        stringEncoding: this.#elemMeta.stringEncoding,
                                    }};
                                    if (currentCount < 0) {{ throw new Error('unexpectedly invalid count'); }}
                                    while (currentCount > 0) {{
                                        const [value, _ctx] = this.#elemMeta.liftFn(liftCtx);
                                        values.push(value);
                                        currentCount -= 1;
                                    }}
                                    this.#ptr = liftCtx.storagePtr;
                                }}
                            }}

                            this.processed += count;
                            return values;
                        }}

                        write(values) {{
                            {debug_log_fn}('[{managed_buffer_class}#write()] args', {{ values }});

                            if (!Array.isArray(values)) {{ throw new TypeError('values input to write() must be an array'); }}
                            let rc = this.remaining();
                            if (values.length > rc) {{
                                throw new Error(`cannot write [${{values.length}}] elements to managed buffer with remaining capacity [${{rc}}]`);
                            }}

                            if (this.#elemMeta.isNone) {{
                                if (!values.every(v => v === null)) {{
                                    throw new Error('non-null values in write() to unit managed buffer');
                                }}
                            }} else {{
                                if (this.isHostOwned()) {{
                                    this.#hostOnlyData.push(...values);
                                }} else {{
                                    let startPtr = this.#ptr;
                                    if (this.#elemMeta.stringEncoding === undefined) {{
                                        throw new Error('string encoding unknown during write');
                                    }}

                                    const lowerCtx = {{
                                        memory: this.#memory,
                                        storagePtr: startPtr,
                                        componentIdx: this.#componentIdx,
                                        stringEncoding: this.#elemMeta.stringEncoding,
                                        realloc: this.#elemMeta.reallocFn,
                                    }}
                                    for (const v of values) {{
                                        lowerCtx.vals = [v];
                                        this.#elemMeta.lowerFn(lowerCtx);
                                    }}

                                    this.#ptr = lowerCtx.storagePtr;
                                }}
                            }}

                            this.processed += values.length;
                        }}

                    }}
                "#
                ));
            }

            Intrinsic::BufferManagerClass => {
                let debug_log_fn = Intrinsic::DebugLog.name();
                let buffer_manager_class = Intrinsic::BufferManagerClass.name();
                let managed_buffer_class = Intrinsic::ManagedBufferClass.name();

                output.push_str(&format!(r#"
                    class {buffer_manager_class} {{
                        #buffers = new Map();
                        #bufferIDs = new Map();

                        // NOTE: componentIdx === -1 indicates the host
                        getNextBufferID(componentIdx) {{
                            const current = this.#bufferIDs.get(componentIdx);
                            if (current === undefined) {{
                                this.#bufferIDs.set(componentIdx, 1n);
                                return 1n;
                            }}
                            const next = current + 1n;
                            this.#bufferIDs.set(componentIdx, next);
                            return next;
                        }}

                        getBuffer(componentIdx, bufferID) {{
                            {debug_log_fn}('[{buffer_manager_class}#getBuffer()] args', {{ componentIdx, bufferID }});
                            return this.#buffers.get(componentIdx)?.get(bufferID);
                        }}

                        createBuffer(args) {{
                            {debug_log_fn}('[{buffer_manager_class}#createBuffer()] args', args);
                            if (!args || typeof args !== 'object') {{ throw new TypeError('missing/invalid argument object'); }}

                            if (args.start === undefined && args.data === undefined) {{
                                throw new  TypeError('either a starting pointer or initial values must be provided');
                            }}

                            if (args.start !== undefined && args.componentIdx === undefined) {{ throw new TypeError('missing/invalid component idx'); }}
                            if (args.count === undefined) {{ throw new TypeError('missing/invalid obj count'); }}
                            if (!args.elemMeta) {{ throw new TypeError('missing/invalid element metadata for use with managed buffer'); }}

                            const {{ componentIdx, data, start, count }} = args;

                            if (!this.#buffers.has(componentIdx)) {{ this.#buffers.set(componentIdx, new Map()); }}
                            const instanceBuffers = this.#buffers.get(componentIdx);

                            const nextBufID = this.getNextBufferID(componentIdx);

                            const buffer = new {managed_buffer_class}({{
                                componentIdx,
                                memory: args.memory,
                                start: args.start,
                                capacity: args.count,
                                elemMeta: args.elemMeta,
                                data: args.data,
                                target: args.target,
                                stringEncoding: args.stringEncoding,
                            }});

                            if (instanceBuffers.has(nextBufID)) {{
                                throw new Error(`managed buffer with ID [${{nextBufID}}] already exists`);
                            }}
                            instanceBuffers.set(nextBufID, buffer);

                            return {{ id: nextBufID, buffer }};
                        }}

                        deleteBuffer(componentIdx, bufferID) {{
                            {debug_log_fn}('[{buffer_manager_class}#deleteBuffer()] args', {{ componentIdx, bufferID }});
                            return this.#buffers.get(componentIdx)?.delete(bufferID);
                        }}

                    }}
                "#));
            }

            Intrinsic::GlobalBufferManager => {
                let global_buffer_manager = Intrinsic::GlobalBufferManager.name();
                let buffer_manager_class = Intrinsic::BufferManagerClass.name();
                output.push_str(&format!(
                    "const {global_buffer_manager} = new {buffer_manager_class}();"
                ));
            }

            Intrinsic::RepTableClass => {
                let debug_log_fn = Intrinsic::DebugLog.name();
                let rep_table_class = Intrinsic::RepTableClass.name();
                output.push_str(&format!(r#"
                    class {rep_table_class} {{
                        #data = [0, null];
                        #target;

                        constructor(args) {{
                            this.target = args?.target;
                        }}

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

                        insert(val) {{
                            {debug_log_fn}('[{rep_table_class}#insert()] args', {{ val, target: this.target }});
                            const freeIdx = this.#data[0];
                            if (freeIdx === 0) {{
                                this.#data.push(val);
                                this.#data.push(null);
                                const rep = (this.#data.length >> 1) - 1;
                                {debug_log_fn}('[{rep_table_class}#insert()] inserted', {{ val, target: this.target, rep }});
                                return rep;
                            }}
                            this.#data[0] = this.#data[freeIdx << 1];
                            const placementIdx = freeIdx << 1;
                            this.#data[placementIdx] = val;
                            this.#data[placementIdx + 1] = null;
                            {debug_log_fn}('[{rep_table_class}#insert()] inserted', {{ val, target: this.target, rep: freeIdx }});
                            return freeIdx;
                        }}

                        get(rep) {{
                            {debug_log_fn}('[{rep_table_class}#get()] args', {{ rep, target: this.target }});
                            if (rep === 0) {{ throw new Error('invalid resource rep during get, (cannot be 0)'); }}

                            const baseIdx = rep << 1;
                            const val = this.#data[baseIdx];
                            return val;
                        }}

                        contains(rep) {{
                            {debug_log_fn}('[{rep_table_class}#contains()] args', {{ rep, target: this.target }});
                            if (rep === 0) {{ throw new Error('invalid resource rep during contains, (cannot be 0)'); }}

                            const baseIdx = rep << 1;
                            return !!this.#data[baseIdx];
                        }}

                        remove(rep) {{
                            {debug_log_fn}('[{rep_table_class}#remove()] args', {{ rep, target: this.target }});
                            if (rep === 0) {{ throw new Error('invalid resource rep during remove, (cannot be 0)'); }}
                            if (this.#data.length === 2) {{ throw new Error('invalid'); }}

                            const baseIdx = rep << 1;
                            const val = this.#data[baseIdx];

                            this.#data[baseIdx] = this.#data[0];
                            this.#data[0] = rep;

                            return val;
                        }}

                        clear() {{
                            {debug_log_fn}('[{rep_table_class}#clear()] args', {{ rep, target: this.target }});
                            this.#data = [0, null];
                        }}
                    }}
                "#));
            }

            Intrinsic::GlobalComponentMemoryMap => {
                let global_component_memory_map = Intrinsic::GlobalComponentMemoryMap.name();
                output.push_str(&format!(
                    "const {global_component_memory_map} = new Map();\n"
                ));
            }

            Intrinsic::RegisterGlobalMemoryForComponent => {
                let global_component_memory_map = Intrinsic::GlobalComponentMemoryMap.name();
                let register_global_component_memory =
                    Intrinsic::RegisterGlobalMemoryForComponent.name();
                output.push_str(&format!(
                    r#"
                      function {register_global_component_memory}(args) {{
                          const {{ componentIdx, memory, memoryIdx }} = args ?? {{}};
                          if (componentIdx === undefined) {{ throw new TypeError('missing component idx'); }}
                          if (memory === undefined && memoryIdx === undefined) {{ throw new TypeError('missing both memory & memory idx'); }}
                          let inner = {global_component_memory_map}.get(componentIdx);
                          if (!inner) {{
                              inner = {{}};
                              {global_component_memory_map}.set(componentIdx, inner);
                          }}

                          inner[memoryIdx] = {{ memory, memoryIdx, componentIdx }};
                      }}
                    "#)
                );
            }

            Intrinsic::LookupMemoriesForComponent => {
                let global_component_memory_map = Intrinsic::GlobalComponentMemoryMap.name();
                let lookup_global_memories_for_component =
                    Intrinsic::LookupMemoriesForComponent.name();
                output.push_str(&format!(
                    r#"
                      function {lookup_global_memories_for_component}(args) {{
                          const {{ componentIdx }} = args ?? {{}};
                          if (args.componentIdx === undefined) {{ throw new TypeError("missing component idx"); }}

                          const metas = {global_component_memory_map}.get(componentIdx);
                          if (!metas) {{ return []; }}

                          if (args.memoryIdx === undefined) {{
                              return Object.values(metas);
                          }}

                          const meta = metas[args.memoryIdx];
                          return meta?.memory;
                      }}
                    "#)
                );
            }

            Self::GlobalCurrentTaskMeta => {
                let name = self.name();
                output.push_str(&format!("const {name} = {{}};\n"));
            }

            Self::GetGlobalCurrentTaskMetaFn => {
                let get_current_global_task_meta_fn = Self::GetGlobalCurrentTaskMetaFn.name();
                let global_current_task_meta_obj = Self::GlobalCurrentTaskMeta.name();
                output.push_str(&format!(
                    r#"
                      function {get_current_global_task_meta_fn}(componentIdx) {{
                          const v = {global_current_task_meta_obj}[componentIdx];
                          if (v === undefined) {{ return v; }}
                          return {{ ...v }};
                      }}
                    "#,
                ));
            }

            Self::SetGlobalCurrentTaskMetaFn => {
                let set_global_current_task_meta_fn = Self::SetGlobalCurrentTaskMetaFn.name();
                let global_current_task_meta_obj = Self::GlobalCurrentTaskMeta.name();
                output.push_str(&format!(
                    r#"
                      function {set_global_current_task_meta_fn}(args) {{
                          if (!args) {{ throw new TypeError('args missing'); }}
                          if (args.taskID === undefined) {{ throw new TypeError('missing task ID'); }}
                          if (args.componentIdx === undefined) {{ throw new TypeError('missing component idx'); }}
                          const {{ taskID, componentIdx }} = args;
                          return {global_current_task_meta_obj}[componentIdx] = {{ taskID, componentIdx }};
                      }}
                    "#,
                ));
            }

            Self::WithGlobalCurrentTaskMetaFn => {
                let debug_log_fn = Intrinsic::DebugLog.name();
                let with_global_current_task_meta_fn = Self::WithGlobalCurrentTaskMetaFn.name();
                let global_current_task_meta_obj = Self::GlobalCurrentTaskMeta.name();

                output.push_str(&format!(
                    r#"
                      function {with_global_current_task_meta_fn}(args) {{
                          {debug_log_fn}('[{with_global_current_task_meta_fn}()] args', args);
                          if (!args) {{ throw new TypeError('args missing'); }}
                          if (args.taskID === undefined) {{ throw new TypeError('missing task ID'); }}
                          if (args.componentIdx === undefined) {{ throw new TypeError('missing component idx'); }}
                          if (!args.fn) {{ throw new TypeError('missing fn'); }}
                          const {{ taskID, componentIdx, fn }} = args;

                          try {{
                              {global_current_task_meta_obj}[componentIdx] = {{ taskID, componentIdx }};
                              return fn();
                          }} catch (err) {{
                              {debug_log_fn}("error while executing sync callee/callback", {{
                                  ...args,
                                  err,
                              }});
                              throw err;
                          }} finally {{
                              {global_current_task_meta_obj}[componentIdx] = null;
                          }}
                      }}
                    "#,
                ));
            }

            Self::WithGlobalCurrentTaskMetaFnAsync => {
                let debug_log_fn = Intrinsic::DebugLog.name();
                let with_global_current_task_meta_async_fn =
                    Self::WithGlobalCurrentTaskMetaFnAsync.name();
                let global_current_task_meta_obj = Self::GlobalCurrentTaskMeta.name();
                let get_or_create_async_state_fn = ComponentIntrinsic::GetOrCreateAsyncState.name();

                output.push_str(&format!(
                    r#"
                      async function {with_global_current_task_meta_async_fn}(args) {{
                          {debug_log_fn}('[{with_global_current_task_meta_async_fn}()] args', args);
                          if (!args) {{ throw new TypeError('args missing'); }}
                          if (args.taskID === undefined) {{ throw new TypeError('missing task ID'); }}
                          if (args.componentIdx === undefined) {{ throw new TypeError('missing component idx'); }}
                          if (!args.fn) {{ throw new TypeError('missing fn'); }}
                          const {{ taskID, componentIdx, fn }} = args;

                          // If there is already an async task executing, we must wait for it
                          // to complete before we can can run the closure we were given
                          //
                          let current = {global_current_task_meta_obj}[componentIdx];
                          let cstate;
                          if (current && current.taskID !== taskID) {{
                              cstate = {get_or_create_async_state_fn}(componentIdx);
                              while (current && current.taskID !== taskID) {{
                                  const {{ promise, resolve }} = Promise.withResolvers();
                                  cstate.onNextExclusiveRelease(resolve);
                                  await promise;
                                  current = {global_current_task_meta_obj}[componentIdx];
                              }}

                              // Since we've just waited for the component to not be locked, re-lock
                              // exclusivity so we can run the fn below (likely a callee/callback)
                              cstate.exclusiveLock();
                          }}

                          try {{
                              {global_current_task_meta_obj}[componentIdx] = {{ taskID, componentIdx }};
                              return await fn();
                          }} catch (err) {{
                              {debug_log_fn}("error while executing async callee/callback", {{
                                  ...args,
                                  err,
                              }});
                              throw err;
                          }} finally {{
                              {global_current_task_meta_obj}[componentIdx] = null;
                          }}
                      }}
                    "#,
                ));
            }

            Self::ClearGlobalCurrentTaskMetaFn => {
                let debug_log_fn = Intrinsic::DebugLog.name();
                let clear_global_current_task_meta_fn = Self::ClearGlobalCurrentTaskMetaFn.name();
                let global_current_task_meta_obj = Self::GlobalCurrentTaskMeta.name();

                output.push_str(&format!(
                    r#"
                      async function {clear_global_current_task_meta_fn}(args) {{
                          {debug_log_fn}('[{clear_global_current_task_meta_fn}()] args', args);
                          if (!args) {{ throw new TypeError('args missing'); }}
                          if (args.taskID === undefined) {{ throw new TypeError('missing task ID'); }}
                          if (args.componentIdx === undefined) {{ throw new TypeError('missing component idx'); }}
                          const {{ taskID, componentIdx }} = args;

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

                          if (meta.taskID !== taskID) {{
                              throw new Error(`task ID [${{meta.taskID}}] != requested ID [${{taskID}}]`);
                          }}
                          if (meta.componentIdx !== componentIdx) {{
                              throw new Error(`component idx [${{meta.componentIdx}}] != requested idx [${{componentIdx}}]`);
                          }}

                          {global_current_task_meta_obj}[componentIdx] = null;
                      }}
                    "#,
                ));
            }

            // TODO(feat): customizable stream classes
            Intrinsic::PlatformReadableStreamClass => {
                let name = self.name();
                uwriteln!(
                    output,
                    r#"
                        if (!ReadableStream) {{
                            throw new Error('builtin stream class [ReadableStream] is not available');
                        }}
                        const {name} = ReadableStream;
                    "#
                );
            }
        }
    }
}

/// Profile for determinism to be used by async implementation
#[derive(Debug, Default, PartialEq, Eq)]
pub(crate) enum AsyncDeterminismProfile {
    /// Allow random ordering non-determinism
    #[default]
    Random,

    /// Require determinism
    #[allow(unused)]
    Deterministic,
}

impl std::fmt::Display for AsyncDeterminismProfile {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}",
            match self {
                Self::Deterministic => "deterministic",
                Self::Random => "random",
            }
        )
    }
}

/// Arguments to `render_intrinsics`
pub struct RenderIntrinsicsArgs<'a> {
    /// List of intrinsics being built for use
    pub(crate) intrinsics: &'a mut BTreeSet<Intrinsic>,
    /// Whether to use NodeJS compat
    pub(crate) no_nodejs_compat: bool,
    /// Whether instantiation has occurred
    pub(crate) instantiation: bool,
    /// The kind of determinism to use
    pub(crate) determinism: AsyncDeterminismProfile,
}

/// Intrinsics that should be rendered as early as possible
const EARLY_INTRINSICS: [Intrinsic; 37] = [
    Intrinsic::PromiseWithResolversPonyfill,
    Intrinsic::SymbolDispose,
    Intrinsic::SymbolAsyncIterator,
    Intrinsic::SymbolIterator,
    Intrinsic::DebugLog,
    Intrinsic::GlobalAsyncDeterminism,
    Intrinsic::GlobalComponentMemoryMap,
    Intrinsic::GlobalCurrentTaskMeta,
    Intrinsic::GetGlobalCurrentTaskMetaFn,
    Intrinsic::SetGlobalCurrentTaskMetaFn,
    Intrinsic::WithGlobalCurrentTaskMetaFn,
    Intrinsic::WithGlobalCurrentTaskMetaFnAsync,
    Intrinsic::ClearGlobalCurrentTaskMetaFn,
    Intrinsic::LookupMemoriesForComponent,
    Intrinsic::RegisterGlobalMemoryForComponent,
    Intrinsic::RepTableClass,
    Intrinsic::CoinFlip,
    Intrinsic::ScopeId,
    // Type checking helpers
    Intrinsic::ConstantI32Min,
    Intrinsic::ConstantI32Max,
    Intrinsic::Conversion(ConversionIntrinsic::IsValidNumericPrimitive),
    Intrinsic::Conversion(ConversionIntrinsic::RequireValidNumericPrimitive),
    Intrinsic::TypeCheckValidI32,
    Intrinsic::TypeCheckAsyncFn,
    // Resources
    Intrinsic::Resource(ResourceIntrinsic::ResourceCallBorrows),
    // Async helpers
    Intrinsic::AsyncFunctionCtor,
    Intrinsic::AsyncTask(AsyncTaskIntrinsic::ClearCurrentTask),
    Intrinsic::AsyncTask(AsyncTaskIntrinsic::CurrentTaskMayBlock),
    Intrinsic::AsyncTask(AsyncTaskIntrinsic::GlobalAsyncCurrentTaskIds),
    Intrinsic::AsyncTask(AsyncTaskIntrinsic::GlobalAsyncCurrentComponentIdxs),
    Intrinsic::AsyncTask(AsyncTaskIntrinsic::UnpackCallbackResult),
    Intrinsic::AsyncTask(AsyncTaskIntrinsic::AsyncSubtaskClass),
    // Host helpers
    Intrinsic::Host(HostIntrinsic::PrepareCall),
    Intrinsic::Host(HostIntrinsic::AsyncStartCall),
    Intrinsic::Host(HostIntrinsic::SyncStartCall),
    // Waitable helpers
    Intrinsic::Waitable(WaitableIntrinsic::WaitableClass),
    // Error context helpers
    Intrinsic::ErrCtx(ErrCtxIntrinsic::GlobalErrCtxTableMap),
];

/// Emits the intrinsic `i` to this file and then returns the name of the
/// intrinsic.
pub fn render_intrinsics(args: RenderIntrinsicsArgs) -> Source {
    let mut output = Source::default();
    let mut rendered_intrinsics = HashSet::new();

    // Render some early intrinsics
    for intrinsic in EARLY_INTRINSICS {
        intrinsic.render(&mut output, &args);
        rendered_intrinsics.insert(intrinsic.name());
    }

    // Add intrinsics to the list we must render
    if args.intrinsics.contains(&Intrinsic::GetErrorPayload)
        || args.intrinsics.contains(&Intrinsic::GetErrorPayloadString)
    {
        args.intrinsics.insert(Intrinsic::HasOwnProperty);
    }
    if args
        .intrinsics
        .contains(&Intrinsic::String(StringIntrinsic::Utf16Encode))
    {
        args.intrinsics.insert(Intrinsic::IsLE);
    }

    if args
        .intrinsics
        .contains(&Intrinsic::Conversion(ConversionIntrinsic::F32ToI32))
        || args
            .intrinsics
            .contains(&Intrinsic::Conversion(ConversionIntrinsic::I32ToF32))
    {
        output.push_str(
            "
            const i32ToF32I = new Int32Array(1);
            const i32ToF32F = new Float32Array(i32ToF32I.buffer);
        ",
        );
    }

    if args
        .intrinsics
        .contains(&Intrinsic::Conversion(ConversionIntrinsic::F64ToI64))
        || args
            .intrinsics
            .contains(&Intrinsic::Conversion(ConversionIntrinsic::I64ToF64))
    {
        output.push_str(
            "
            const i64ToF64I = new BigInt64Array(1);
            const i64ToF64F = new Float64Array(i64ToF64I.buffer);
        ",
        );
    }

    if args.intrinsics.contains(&Intrinsic::Resource(
        ResourceIntrinsic::ResourceTransferBorrow,
    )) || args.intrinsics.contains(&Intrinsic::Resource(
        ResourceIntrinsic::ResourceTransferBorrowValidLifting,
    )) {
        args.intrinsics.insert(Intrinsic::Resource(
            ResourceIntrinsic::ResourceTableCreateBorrow,
        ));
    }

    if args
        .intrinsics
        .contains(&Intrinsic::String(StringIntrinsic::Utf8Encode))
        || args
            .intrinsics
            .contains(&Intrinsic::String(StringIntrinsic::Utf8EncodeAsync))
    {
        args.intrinsics.extend([
            &Intrinsic::IsLE,
            &Intrinsic::String(StringIntrinsic::GlobalTextEncoderUtf8),
        ]);
    }

    if args
        .intrinsics
        .contains(&Intrinsic::String(StringIntrinsic::Utf16Encode))
        || args
            .intrinsics
            .contains(&Intrinsic::String(StringIntrinsic::Utf16EncodeAsync))
    {
        args.intrinsics.extend([&Intrinsic::IsLE]);
    }

    // Attempting to perform a debug message hoist will require string encoding to memory
    if args.intrinsics.contains(&Intrinsic::ErrCtx(
        ErrCtxIntrinsic::ErrorContextDebugMessage,
    )) {
        args.intrinsics.extend([
            &Intrinsic::String(StringIntrinsic::Utf8Encode),
            &Intrinsic::String(StringIntrinsic::Utf16Encode),
            &Intrinsic::ErrCtx(ErrCtxIntrinsic::GetLocalTable),
        ]);
    }

    if args
        .intrinsics
        .contains(&Intrinsic::ErrCtx(ErrCtxIntrinsic::ErrorContextNew))
    {
        args.intrinsics.extend([
            &Intrinsic::ErrCtx(ErrCtxIntrinsic::ComponentGlobalTable),
            &Intrinsic::ErrCtx(ErrCtxIntrinsic::GlobalRefCountAdd),
            &Intrinsic::ErrCtx(ErrCtxIntrinsic::ReserveGlobalRep),
            &Intrinsic::ErrCtx(ErrCtxIntrinsic::CreateLocalHandle),
            &Intrinsic::ErrCtx(ErrCtxIntrinsic::GetLocalTable),
        ]);
    }

    if args.intrinsics.contains(&Intrinsic::ErrCtx(
        ErrCtxIntrinsic::ErrorContextDebugMessage,
    )) {
        args.intrinsics.extend([
            &Intrinsic::ErrCtx(ErrCtxIntrinsic::GlobalRefCountAdd),
            &Intrinsic::ErrCtx(ErrCtxIntrinsic::ErrorContextDrop),
            &Intrinsic::ErrCtx(ErrCtxIntrinsic::GetLocalTable),
        ]);
    }

    if args
        .intrinsics
        .contains(&Intrinsic::AsyncTask(AsyncTaskIntrinsic::ContextGet))
        || args
            .intrinsics
            .contains(&Intrinsic::AsyncTask(AsyncTaskIntrinsic::ContextSet))
    {
        args.intrinsics.extend([
            &Intrinsic::AsyncTask(AsyncTaskIntrinsic::GlobalAsyncCurrentTaskMap),
            &Intrinsic::AsyncTask(AsyncTaskIntrinsic::AsyncTaskClass),
            &Intrinsic::AsyncEventCodeEnum,
            &Intrinsic::AsyncTask(AsyncTaskIntrinsic::GetCurrentTask),
        ]);
    }

    if args
        .intrinsics
        .contains(&Intrinsic::AsyncTask(AsyncTaskIntrinsic::DriverLoop))
    {
        args.intrinsics.extend([
            &Intrinsic::TypeCheckValidI32,
            &Intrinsic::Conversion(ConversionIntrinsic::ToInt32),
            &Intrinsic::Component(ComponentIntrinsic::ComponentStateSetAllError),
        ]);
    }

    if args.intrinsics.contains(&Intrinsic::Component(
        ComponentIntrinsic::GetOrCreateAsyncState,
    )) {
        args.intrinsics.extend([&Intrinsic::RepTableClass]);
    }

    if args
        .intrinsics
        .contains(&Intrinsic::AsyncTask(AsyncTaskIntrinsic::AsyncTaskClass))
    {
        args.intrinsics.extend([
            &Intrinsic::Component(ComponentIntrinsic::GetOrCreateAsyncState),
            &Intrinsic::Component(ComponentIntrinsic::GlobalAsyncStateMap),
            &Intrinsic::RepTableClass,
            &Intrinsic::AsyncTask(AsyncTaskIntrinsic::AsyncSubtaskClass),
            &Intrinsic::Waitable(WaitableIntrinsic::WaitableClass),
        ]);
    }

    if args
        .intrinsics
        .contains(&Intrinsic::Waitable(WaitableIntrinsic::WaitableSetNew))
    {
        args.intrinsics
            .extend([&Intrinsic::Waitable(WaitableIntrinsic::WaitableSetClass)]);
    }

    if args
        .intrinsics
        .contains(&Intrinsic::Waitable(WaitableIntrinsic::WaitableSetPoll))
        || args
            .intrinsics
            .contains(&Intrinsic::Waitable(WaitableIntrinsic::WaitableSetWait))
    {
        args.intrinsics
            .extend([&Intrinsic::Host(HostIntrinsic::StoreEventInComponentMemory)]);
    }

    if args
        .intrinsics
        .contains(&Intrinsic::Waitable(WaitableIntrinsic::WaitableSetDrop))
    {
        args.intrinsics
            .extend([&Intrinsic::Waitable(WaitableIntrinsic::RemoveWaitableSet)]);
    }

    if args.intrinsics.contains(&Intrinsic::Component(
        ComponentIntrinsic::GetOrCreateAsyncState,
    )) {
        args.intrinsics.extend([
            &Intrinsic::Component(ComponentIntrinsic::ComponentAsyncStateClass),
            &Intrinsic::Component(ComponentIntrinsic::GlobalAsyncStateMap),
        ]);
    }

    if args.intrinsics.contains(&Intrinsic::Component(
        ComponentIntrinsic::ComponentAsyncStateClass,
    )) {
        args.intrinsics.extend([&Intrinsic::AsyncStream(
            AsyncStreamIntrinsic::GlobalStreamMap,
        )]);
    }

    if args
        .intrinsics
        .contains(&Intrinsic::Lift(LiftIntrinsic::LiftFlatResult))
        | args
            .intrinsics
            .contains(&Intrinsic::Lift(LiftIntrinsic::LiftFlatOption))
        | args
            .intrinsics
            .contains(&Intrinsic::Lift(LiftIntrinsic::LiftFlatOption))
    {
        args.intrinsics
            .extend([&Intrinsic::Lift(LiftIntrinsic::LiftFlatVariant)]);
    }

    if args
        .intrinsics
        .contains(&Intrinsic::Lift(LiftIntrinsic::LiftFlatVariant))
    {
        args.intrinsics.extend([
            &Intrinsic::Lift(LiftIntrinsic::LiftFlatU8),
            &Intrinsic::Lift(LiftIntrinsic::LiftFlatU16),
            &Intrinsic::Lift(LiftIntrinsic::LiftFlatU32),
        ]);
    }

    if args
        .intrinsics
        .contains(&Intrinsic::Lower(LowerIntrinsic::LowerFlatResult))
    {
        args.intrinsics
            .insert(Intrinsic::Lower(LowerIntrinsic::LowerFlatVariant));
    }

    if args
        .intrinsics
        .contains(&Intrinsic::Lower(LowerIntrinsic::LowerFlatOption))
    {
        args.intrinsics
            .insert(Intrinsic::Lower(LowerIntrinsic::LowerFlatVariant));
    }

    if args
        .intrinsics
        .contains(&Intrinsic::Lower(LowerIntrinsic::LowerFlatVariant))
    {
        args.intrinsics.extend([
            &Intrinsic::Lower(LowerIntrinsic::LowerFlatU8),
            &Intrinsic::Lower(LowerIntrinsic::LowerFlatU16),
            &Intrinsic::Lower(LowerIntrinsic::LowerFlatU32),
        ]);
    }

    if args
        .intrinsics
        .contains(&Intrinsic::Lower(LowerIntrinsic::LowerFlatStream))
    {
        args.intrinsics.extend([
            &Intrinsic::AsyncStream(AsyncStreamIntrinsic::GlobalStreamMap),
            &Intrinsic::AsyncStream(AsyncStreamIntrinsic::ExternalStreamClass),
            &Intrinsic::AsyncStream(AsyncStreamIntrinsic::InternalStreamClass),
            &Intrinsic::AsyncStream(AsyncStreamIntrinsic::IsStreamLowerableObject),
            &Intrinsic::SymbolResourceRep,
            &Intrinsic::Component(ComponentIntrinsic::GetOrCreateAsyncState),
            &Intrinsic::AsyncStream(AsyncStreamIntrinsic::GenReadFnFromLowerableStream),
            &Intrinsic::AsyncStream(AsyncStreamIntrinsic::GenHostInjectFn),
            &Intrinsic::Lower(LowerIntrinsic::LowerFlatU32),
        ])
    }

    if args
        .intrinsics
        .contains(&Intrinsic::Lift(LiftIntrinsic::LiftFlatStringAny))
    {
        args.intrinsics.extend([
            &Intrinsic::Lift(LiftIntrinsic::LiftFlatStringUtf8),
            &Intrinsic::Lift(LiftIntrinsic::LiftFlatStringUtf16),
        ]);
    }

    if args
        .intrinsics
        .contains(&Intrinsic::Lift(LiftIntrinsic::LiftFlatStringUtf8))
    {
        args.intrinsics
            .insert(Intrinsic::String(StringIntrinsic::GlobalTextDecoderUtf8));
    }

    if args
        .intrinsics
        .contains(&Intrinsic::Lower(LowerIntrinsic::LowerFlatStringAny))
    {
        args.intrinsics.extend([
            &Intrinsic::Lower(LowerIntrinsic::LowerFlatStringUtf8),
            &Intrinsic::Lower(LowerIntrinsic::LowerFlatStringUtf16),
        ]);
    }

    if args
        .intrinsics
        .contains(&Intrinsic::Lower(LowerIntrinsic::LowerFlatStringUtf8))
    {
        args.intrinsics
            .insert(Intrinsic::String(StringIntrinsic::GlobalTextEncoderUtf8));
    }

    if args
        .intrinsics
        .contains(&Intrinsic::Lift(LiftIntrinsic::LiftFlatStringUtf16))
    {
        args.intrinsics
            .insert(Intrinsic::String(StringIntrinsic::Utf16Decoder));
    }

    if args
        .intrinsics
        .contains(&Intrinsic::Lift(LiftIntrinsic::LiftFlatStream))
    {
        args.intrinsics.insert(Intrinsic::AsyncStream(
            AsyncStreamIntrinsic::ExternalStreamClass,
        ));
    }

    if args.intrinsics.contains(&Intrinsic::AsyncTask(
        AsyncTaskIntrinsic::CreateNewCurrentTask,
    )) || args
        .intrinsics
        .contains(&Intrinsic::AsyncTask(AsyncTaskIntrinsic::GetCurrentTask))
        || args
            .intrinsics
            .contains(&Intrinsic::AsyncTask(AsyncTaskIntrinsic::ClearCurrentTask))
    {
        args.intrinsics.extend([
            &Intrinsic::AsyncTask(AsyncTaskIntrinsic::AsyncTaskClass),
            &Intrinsic::AsyncTask(AsyncTaskIntrinsic::GlobalAsyncCurrentTaskMap),
        ]);
    }

    if args
        .intrinsics
        .contains(&Intrinsic::AsyncStream(AsyncStreamIntrinsic::StreamNew))
    {
        args.intrinsics.extend([
            &Intrinsic::AsyncStream(AsyncStreamIntrinsic::GlobalStreamMap),
            &Intrinsic::AsyncStream(AsyncStreamIntrinsic::GlobalStreamTableMap),
            &Intrinsic::AsyncStream(AsyncStreamIntrinsic::StreamWritableEndClass),
            &Intrinsic::AsyncStream(AsyncStreamIntrinsic::StreamReadableEndClass),
        ]);
    }

    if args.intrinsics.contains(&Intrinsic::AsyncStream(
        AsyncStreamIntrinsic::StreamWritableEndClass,
    )) || args.intrinsics.contains(&Intrinsic::AsyncStream(
        AsyncStreamIntrinsic::StreamReadableEndClass,
    )) {
        args.intrinsics.extend([
            &Intrinsic::AsyncStream(AsyncStreamIntrinsic::InternalStreamClass),
            &Intrinsic::AsyncStream(AsyncStreamIntrinsic::StreamEndClass),
            &Intrinsic::AsyncEventCodeEnum,
        ]);
    }

    if args.intrinsics.contains(&Intrinsic::AsyncStream(
        AsyncStreamIntrinsic::StreamNewFromLift,
    )) {
        args.intrinsics.extend([
            &Intrinsic::AsyncStream(AsyncStreamIntrinsic::GlobalStreamMap),
            &Intrinsic::AsyncStream(AsyncStreamIntrinsic::GlobalStreamTableMap),
            &Intrinsic::AsyncStream(AsyncStreamIntrinsic::HostStreamClass),
            &Intrinsic::AsyncStream(AsyncStreamIntrinsic::ExternalStreamClass),
        ]);
    }

    if args
        .intrinsics
        .contains(&Intrinsic::AsyncStream(AsyncStreamIntrinsic::StreamWrite))
        || args
            .intrinsics
            .contains(&Intrinsic::AsyncStream(AsyncStreamIntrinsic::StreamRead))
    {
        args.intrinsics.extend([
            &Intrinsic::GlobalBufferManager,
            &Intrinsic::AsyncTask(AsyncTaskIntrinsic::AsyncBlockedConstant),
            &Intrinsic::AsyncEventCodeEnum,
        ]);
    }

    if args
        .intrinsics
        .contains(&Intrinsic::AsyncFuture(AsyncFutureIntrinsic::FutureNew))
    {
        args.intrinsics.extend([
            &Intrinsic::AsyncFuture(AsyncFutureIntrinsic::GlobalFutureMap),
            &Intrinsic::AsyncFuture(AsyncFutureIntrinsic::GlobalFutureTableMap),
            &Intrinsic::AsyncFuture(AsyncFutureIntrinsic::FutureWritableEndClass),
            &Intrinsic::AsyncFuture(AsyncFutureIntrinsic::FutureReadableEndClass),
        ]);
    }

    if args.intrinsics.contains(&Intrinsic::AsyncFuture(
        AsyncFutureIntrinsic::FutureWritableEndClass,
    )) || args.intrinsics.contains(&Intrinsic::AsyncFuture(
        AsyncFutureIntrinsic::FutureReadableEndClass,
    )) {
        args.intrinsics.extend([
            &Intrinsic::AsyncFuture(AsyncFutureIntrinsic::InternalFutureClass),
            &Intrinsic::AsyncFuture(AsyncFutureIntrinsic::FutureEndClass),
            &Intrinsic::AsyncEventCodeEnum,
        ]);
    }

    if args.intrinsics.contains(&Intrinsic::GlobalBufferManager) {
        args.intrinsics.extend([&Intrinsic::BufferManagerClass]);
    }

    if args.intrinsics.contains(&Intrinsic::BufferManagerClass) {
        args.intrinsics.extend([&Intrinsic::ManagedBufferClass]);
    }

    if args.intrinsics.contains(&Intrinsic::AsyncTask(
        AsyncTaskIntrinsic::EnterSymmetricSyncGuestCall,
    )) || args.intrinsics.contains(&Intrinsic::AsyncTask(
        AsyncTaskIntrinsic::ExitSymmetricSyncGuestCall,
    )) {
        args.intrinsics.extend([
            &Intrinsic::AsyncTask(AsyncTaskIntrinsic::GlobalAsyncCurrentComponentIdxs),
            &Intrinsic::Component(ComponentIntrinsic::GetOrCreateAsyncState),
            &Intrinsic::AsyncTask(AsyncTaskIntrinsic::GetCurrentTask),
            &Intrinsic::AsyncTask(AsyncTaskIntrinsic::GlobalAsyncCurrentTaskIds),
            &Intrinsic::ClearGlobalCurrentTaskMetaFn,
            &Intrinsic::AsyncTask(AsyncTaskIntrinsic::SymmetricSyncGuestCallStack),
        ]);
    }

    for current_intrinsic in args.intrinsics.iter() {
        // Skip already rendered intrinsics (i.e. the early intrinsics)
        if rendered_intrinsics.contains(current_intrinsic.name()) {
            continue;
        }

        current_intrinsic.render(&mut output, &args);
    }

    output
}

impl Intrinsic {
    pub fn get_global_names() -> impl IntoIterator<Item = &'static str> {
        JsHelperIntrinsic::get_global_names()
            .into_iter()
            .chain(vec![
                // Intrinsic list exactly as below
                "base64Compile",
                "clampGuest",
                "ComponentError",
                "definedResourceTables",
                "fetchCompile",
                "finalizationRegistryCreate",
                "getErrorPayload",
                "handleTables",
                "hasOwnProperty",
                "imports",
                "instantiateCore",
                "isLE",
                "scopeId",
                "symbolCabiDispose",
                "symbolCabiLower",
                "symbolDispose",
                "symbolAsyncIterator",
                "symbolIterator",
                "symbolRscHandle",
                "symbolRscRep",
                "T_FLAG",
                "throwInvalidBool",
                "throwUninitialized",
                // JS Globals / non intrinsic names
                "ArrayBuffer",
                "BigInt",
                "BigInt64Array",
                "DataView",
                "dv",
                "emptyFunc",
                "Error",
                "fetch",
                "Float32Array",
                "Float64Array",
                "Int32Array",
                "Object",
                "process",
                "String",
                "TextDecoder",
                "TextEncoder",
                "TypeError",
                "Uint16Array",
                "Uint8Array",
                "URL",
                "WebAssembly",
                "GlobalComponentMemories",
            ])
    }

    pub fn name(&self) -> &'static str {
        match self {
            Intrinsic::JsHelper(i) => i.name(),
            Intrinsic::Conversion(i) => i.name(),
            Intrinsic::WebIdl(i) => i.name(),
            Intrinsic::String(i) => i.name(),
            Intrinsic::ErrCtx(i) => i.name(),
            Intrinsic::AsyncTask(i) => i.name(),
            Intrinsic::Waitable(i) => i.name(),
            Intrinsic::Resource(i) => i.name(),
            Intrinsic::Lift(i) => i.name(),
            Intrinsic::Lower(i) => i.name(),
            Intrinsic::AsyncStream(i) => i.name(),
            Intrinsic::AsyncFuture(i) => i.name(),
            Intrinsic::Component(i) => i.name(),
            Intrinsic::Host(i) => i.name(),

            Intrinsic::Base64Compile => "base64Compile",
            Intrinsic::ClampGuest => "clampGuest",
            Intrinsic::ComponentError => "ComponentError",
            Intrinsic::DefinedResourceTables => "definedResourceTables",
            Intrinsic::FetchCompile => "fetchCompile",
            Intrinsic::FinalizationRegistryCreate => "finalizationRegistryCreate",
            Intrinsic::GetErrorPayload => "getErrorPayload",
            Intrinsic::GetErrorPayloadString => "getErrorPayloadString",
            Intrinsic::HandleTables => "handleTables",
            Intrinsic::HasOwnProperty => "hasOwnProperty",
            Intrinsic::InstantiateCore => "instantiateCore",
            Intrinsic::IsLE => "isLE",
            Intrinsic::ScopeId => "SCOPE_ID",

            Intrinsic::SymbolCabiDispose => "symbolCabiDispose",
            Intrinsic::SymbolCabiLower => "symbolCabiLower",
            Intrinsic::SymbolDispose => "symbolDispose",
            Intrinsic::SymbolAsyncIterator => "symbolAsyncIterator",
            Intrinsic::SymbolIterator => "symbolIterator",
            Intrinsic::SymbolResourceHandle => "symbolRscHandle",
            Intrinsic::SymbolResourceRep => "symbolRscRep",

            Intrinsic::ThrowInvalidBool => "throwInvalidBool",
            Intrinsic::ThrowUninitialized => "throwUninitialized",

            // Debugging
            Intrinsic::DebugLog => "_debugLog",
            Intrinsic::PromiseWithResolversPonyfill => "promiseWithResolvers",

            // Types
            Intrinsic::ConstantI32Min => "I32_MIN",
            Intrinsic::ConstantI32Max => "I32_MAX",
            Intrinsic::TypeCheckValidI32 => "_typeCheckValidI32",
            Intrinsic::TypeCheckAsyncFn => "_typeCheckAsyncFn",
            Intrinsic::AsyncFunctionCtor => "ASYNC_FN_CTOR",

            // Streams
            Intrinsic::PlatformReadableStreamClass => "_PlatformReadableStream",

            // Async
            Intrinsic::GlobalAsyncDeterminism => "ASYNC_DETERMINISM",
            Intrinsic::CoinFlip => "_coinFlip",

            // Global current task tracking machinery
            Self::GlobalCurrentTaskMeta => "CURRENT_TASK_META",
            Self::GetGlobalCurrentTaskMetaFn => "_getGlobalCurrentTaskMeta",
            Self::SetGlobalCurrentTaskMetaFn => "_setGlobalCurrentTaskMeta",
            Self::WithGlobalCurrentTaskMetaFn => "_withGlobalCurrentTaskMeta",
            Self::WithGlobalCurrentTaskMetaFnAsync => "_withGlobalCurrentTaskMetaAsync",
            Self::ClearGlobalCurrentTaskMetaFn => "_clearCurrentTask",

            // Iteratively saved metadata
            Intrinsic::GlobalComponentMemoryMap => "GLOBAL_COMPONENT_MEMORY_MAP",
            Intrinsic::RegisterGlobalMemoryForComponent => "registerGlobalMemoryForComponent",
            Intrinsic::LookupMemoriesForComponent => "lookupMemoriesForComponent",

            // Data structures
            Intrinsic::RepTableClass => "RepTable",

            // Buffers for managed/synchronized writing to/from component memory
            Intrinsic::ManagedBufferClass => "ManagedBuffer",
            Intrinsic::BufferManagerClass => "BufferManager",
            Intrinsic::GlobalBufferManager => "BUFFER_MGR",

            // Helpers for working with async state
            Intrinsic::AsyncEventCodeEnum => "ASYNC_EVENT_CODE",
        }
    }
}