js-component-bindgen 2.17.0

JS component bindgen for transpiling WebAssembly components into JavaScript
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
//! Intrinsics that represent helpers that manage per-component state

use std::fmt::Write as _;

use crate::intrinsics::p3::waitable::WaitableIntrinsic;
use crate::intrinsics::resource::ResourceIntrinsic;
use crate::intrinsics::{Intrinsic, RenderIntrinsicsArgs};
use crate::source::Source;
use crate::uwriteln;
use wasmtime_environ::Trap;

/// This enum contains intrinsics that manage per-component state
#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
pub enum ComponentIntrinsic {
    /// Global that stores the canonical ABI `may_leave` global by component instance.
    GlobalInstanceFlagsMap,

    /// Shared trap state for all component instances in this generated store.
    GlobalStoreTrap,

    /// Shared scheduling state for all component instances in this generated store.
    GlobalStoreAsyncState,

    /// Schedule a store-wide deadlock check after queued guest work has drained.
    CheckForDeadlock,

    /// Track a possibly asynchronous host operation as an external wake source.
    TrackHostOperation,

    /// Normalize engine-specific core WebAssembly trap messages.
    NormalizeCoreTrap,

    /// Convert failed post-return cleanup into a trap of its component.
    PostReturnTrap,

    /// Guard the synchronous post-return imports of fused adapters.
    GuardPostReturn,

    /// Trap if the specified component instance may not currently leave.
    CheckMayLeave,

    /// Wrap a non-suspending canonical ABI trampoline with a `may_leave` check.
    GuardMayLeave,

    /// Record a `WebAssembly.RuntimeError` as the store's trap, synchronously at the throw site
    RecordTrap,

    /// Wrap a non-suspending canonical ABI trampoline so that a trap it throws is recorded
    /// before it propagates (nothing in the store may run after a trap)
    GuardTrap,

    /// Global that stores async state by component instance
    ///
    /// ```ts
    /// type ComponentAsyncState = {
    ///     mayLeave: boolean,
    /// };
    /// type GlobalAsyncStateMap = Map<number, ComponentAsyncState>;
    /// ```
    GlobalAsyncStateMap,

    /// Function that retrieves or creates async state for a given component instance
    GetOrCreateAsyncState,

    /// Increment the backpressure for a given component instance
    ///
    ///
    /// The function that implements this intrinsic has the following definition:
    ///
    /// ```ts
    /// function backpressureInc(componentIdx: number);
    /// ```
    BackpressureInc,

    /// Decrement the backpressure for a given component instance
    ///
    ///
    /// The function that implements this intrinsic has the following definition:
    ///
    /// ```ts
    /// function backpressureDec(componentIdx: number);
    /// ```
    BackpressureDec,

    /// A class that encapsulates component-level async state
    ComponentAsyncStateClass,

    /// Intrinsic used to set all component async states to error.
    ///
    /// Practically, this stops all individual component event loops (`AsyncComponentState#tick()`)
    /// and will usually allow the JS event loop which would otherwise be running `tick()` intervals
    /// forever.
    ///
    ComponentStateSetAllError,
}

impl ComponentIntrinsic {
    /// Retrieve global names for
    pub fn get_global_names() -> impl IntoIterator<Item = &'static str> {
        ["_postReturnTrap", "_guardPostReturn"]
    }

    /// Get the name for the intrinsic
    pub fn name(&self) -> &'static str {
        match self {
            Self::GlobalInstanceFlagsMap => "INSTANCE_FLAGS",
            Self::GlobalStoreTrap => "STORE_TRAP",
            Self::GlobalStoreAsyncState => "STORE_ASYNC_STATE",
            Self::CheckForDeadlock => "_checkForDeadlock",
            Self::TrackHostOperation => "_trackHostOperation",
            Self::NormalizeCoreTrap => "_normalizeCoreTrap",
            Self::PostReturnTrap => "_postReturnTrap",
            Self::GuardPostReturn => "_guardPostReturn",
            Self::CheckMayLeave => "_checkMayLeave",
            Self::GuardMayLeave => "_guardMayLeave",
            Self::RecordTrap => "_recordTrap",
            Self::GuardTrap => "_guardTrap",
            Self::GlobalAsyncStateMap => "ASYNC_STATE",
            Self::GetOrCreateAsyncState => "getOrCreateAsyncState",
            Self::BackpressureInc => "backpressureInc",
            Self::BackpressureDec => "backpressureDec",
            Self::ComponentAsyncStateClass => "ComponentAsyncState",
            Self::ComponentStateSetAllError => "_ComponentStateSetAllError",
        }
    }

    /// Render an intrinsic to a string
    pub fn render(&self, output: &mut Source, render_args: &RenderIntrinsicsArgs<'_>) {
        match self {
            Self::GlobalInstanceFlagsMap => {
                let var_name = render_args.require_intrinsic(Self::GlobalInstanceFlagsMap);
                uwriteln!(output, r#"const {var_name} = new Map();"#);
            }

            Self::GlobalStoreTrap => {
                let var_name = render_args.require_intrinsic(Self::GlobalStoreTrap);
                uwriteln!(output, r#"const {var_name} = {{ error: null }};"#);
            }

            Self::GlobalStoreAsyncState => {
                let var_name = render_args.require_intrinsic(Self::GlobalStoreAsyncState);
                uwriteln!(
                    output,
                    r#"const {var_name} = {{ deadlockCheck: null, pendingHostOperations: 0 }};"#
                );
            }

            Self::CheckForDeadlock => {
                let check_for_deadlock_fn = render_args.require_intrinsic(Self::CheckForDeadlock);
                let async_state_map = render_args.require_intrinsic(Self::GlobalAsyncStateMap);
                let store_async_state = render_args.require_intrinsic(Self::GlobalStoreAsyncState);
                let store_trap = render_args.require_intrinsic(Self::GlobalStoreTrap);
                let runtime_error_class =
                    render_args.require_intrinsic(Intrinsic::WebAssemblyRuntimeError);
                output.push_str(&format!(
                    r#"
                    function {check_for_deadlock_fn}() {{
                        if ({store_async_state}.deadlockCheck !== null || {store_trap}.error !== null) {{ return; }}
                        {store_async_state}.deadlockCheck = setTimeout(() => {{
                            {store_async_state}.deadlockCheck = null;
                            if ({store_trap}.error !== null || {store_async_state}.pendingHostOperations > 0) {{ return; }}

                            const suspendedTasks = new Set();
                            for (const state of {async_state_map}.values()) {{
                                if (state.hasPendingSchedulerWork()) {{
                                    state.runTickLoop();
                                    return;
                                }}
                                for (const meta of state.suspendedTaskMetas()) {{
                                    suspendedTasks.add(meta.task);
                                }}
                            }}

                            const unresolvedRoots = new Set();
                            for (const task of suspendedTasks) {{
                                const root = task.getRootTask();
                                if (!root.isResolvedState()) {{ unresolvedRoots.add(root); }}
                            }}
                            if (unresolvedRoots.size === 0) {{ return; }}

                            const err = new {runtime_error_class}('wasm trap: deadlock detected: event loop cannot make further progress');
                            // Which tasks were waiting, and on whose behalf. The message stays
                            // exactly what the Canonical ABI calls for, so this rides alongside
                            // it: a deadlock reported from a real program is otherwise a bare
                            // sentence, and the state that produced it is gone by the time
                            // anyone reads the failure.
                            err.deadlockDetail = {{
                                pendingHostOperations: {store_async_state}.pendingHostOperations,
                                suspendedTasks: [...suspendedTasks].map((task) => ({{
                                    taskID: task.id(),
                                    componentIdx: task.componentIdx(),
                                    state: task.taskState(),
                                    rootTaskID: task.getRootTask().id(),
                                }})),
                                unresolvedRootTaskIDs: [...unresolvedRoots].map((root) => root.id()),
                            }};
                            {store_trap}.error = err;
                            for (const root of unresolvedRoots) {{
                                root.setErrored(err);
                                root.reject(err);
                            }}
                            for (const task of suspendedTasks) {{
                                if (!task.isResolvedState() && unresolvedRoots.has(task.getRootTask())) {{
                                    task.setErrored(err);
                                    task.reject(err);
                                }}
                            }}
                            // A deadlock is a trap of the whole store: no instance may be entered again.
                            for (const state of {async_state_map}.values()) {{ state.markTrapped(err); }}
                            for (const state of {async_state_map}.values()) {{ state.abandonLockWaiters(); }}
                            for (const state of {async_state_map}.values()) {{ state.abandonAdmissionWaiters(); }}
                            for (const state of {async_state_map}.values()) {{ state.runTickLoop(); }}
                        }}, 0);
                    }}
                    "#,
                ));
            }

            Self::TrackHostOperation => {
                let track_host_operation_fn =
                    render_args.require_intrinsic(Self::TrackHostOperation);
                let check_for_deadlock_fn = render_args.require_intrinsic(Self::CheckForDeadlock);
                let async_state_map = render_args.require_intrinsic(Self::GlobalAsyncStateMap);
                let store_async_state = render_args.require_intrinsic(Self::GlobalStoreAsyncState);
                let symbol_dispose = render_args.require_intrinsic(Intrinsic::SymbolDispose);
                output.push_str(&format!(
                    r#"
                    function {track_host_operation_fn}(operation) {{
                        const result = operation();
                        if (result === null ||
                            (typeof result !== 'object' && typeof result !== 'function') ||
                            typeof result.then !== 'function') {{
                            return result;
                        }}

                        {store_async_state}.pendingHostOperations++;
                        const tracked = Promise.resolve(result).finally(() => {{
                            {store_async_state}.pendingHostOperations--;
                            if ({store_async_state}.pendingHostOperations < 0) {{
                                throw new Error('negative pending host operation count');
                            }}
                            for (const state of {async_state_map}.values()) {{ state.runTickLoop(); }}
                            {check_for_deadlock_fn}();
                        }});

                        // Forward disposal to the host's value, so it is notified if a guest
                        // discards the value (e.g. a future) produced from this operation
                        for (const sym of [Symbol.asyncDispose, {symbol_dispose}]) {{
                            if (typeof sym === 'symbol' && typeof result[sym] === 'function') {{
                                tracked[sym] = () => result[sym]();
                            }}
                        }}

                        return tracked;
                    }}
                    "#,
                ));
            }

            Self::NormalizeCoreTrap => {
                let normalize_core_trap_fn = render_args.require_intrinsic(Self::NormalizeCoreTrap);
                let runtime_error_class =
                    render_args.require_intrinsic(Intrinsic::WebAssemblyRuntimeError);
                let unreachable = Trap::UnreachableCodeReached.to_string();
                let memory_oob = Trap::MemoryOutOfBounds.to_string();
                let integer_division_by_zero = Trap::IntegerDivisionByZero.to_string();
                let integer_overflow = Trap::IntegerOverflow.to_string();
                let bad_conversion = Trap::BadConversionToInteger.to_string();
                let table_oob = Trap::TableOutOfBounds.to_string();
                let bad_signature = Trap::BadSignature.to_string();
                let stack_overflow = Trap::StackOverflow.to_string();
                output.push_str(&format!(
                    r#"
                    const CORE_TRAP_MESSAGES = new Map([
                        ['unreachable', {unreachable:?}],
                        ['memory access out of bounds', {memory_oob:?}],
                        ['divide by zero', {integer_division_by_zero:?}],
                        ['remainder by zero', {integer_division_by_zero:?}],
                        ['divide result unrepresentable', {integer_overflow:?}],
                        ['float unrepresentable in integer range', {bad_conversion:?}],
                        ['table index is out of bounds', {table_oob:?}],
                        ['function signature mismatch', {bad_signature:?}],
                        ['call stack exhausted', {stack_overflow:?}],
                    ]);
                    function {normalize_core_trap_fn}(err) {{
                        if (!(err instanceof {runtime_error_class})) {{ return err; }}
                        const message = CORE_TRAP_MESSAGES.get(err.message);
                        if (message !== undefined) {{ err.message = message; }}
                        return err;
                    }}
                    "#,
                ));
            }

            Self::PostReturnTrap => {
                let post_return_trap_fn = render_args.require_intrinsic(Self::PostReturnTrap);
                let get_state = render_args.require_intrinsic(Self::GetOrCreateAsyncState);
                let runtime_error_class =
                    render_args.require_intrinsic(Intrinsic::WebAssemblyRuntimeError);
                let stack_overflow = Trap::StackOverflow.to_string();
                let uncaught_exception = Trap::UncaughtException.to_string();
                output.push_str(&format!(
                    r#"
                    function {post_return_trap_fn}(componentIdx, err) {{
                        // Core exceptions and stack exhaustion are fatal during cleanup.
                        if (!(err instanceof {runtime_error_class})) {{
                            const message = /call stack|stack overflow|too much recursion/i.test(err?.message ?? '')
                                ? {stack_overflow:?} : {uncaught_exception:?};
                            err = new {runtime_error_class}(message, {{ cause: err }});
                        }}
                        {get_state}(componentIdx).markTrapped(err);
                        return err;
                    }}
                    "#,
                ));
            }

            Self::GuardPostReturn => {
                let guard = render_args.require_intrinsic(Self::GuardPostReturn);
                let trap = render_args.require_intrinsic(Self::PostReturnTrap);
                output.push_str(&format!(
                    r#"
                    function {guard}(componentIdx, fn) {{
                        return (...args) => {{
                            try {{ return fn(...args); }}
                            catch (err) {{ throw {trap}(componentIdx, err); }}
                        }};
                    }}
                    "#,
                ));
            }

            Self::CheckMayLeave => {
                let check_may_leave_fn = render_args.require_intrinsic(Self::CheckMayLeave);
                let instance_flags = render_args.require_intrinsic(Self::GlobalInstanceFlagsMap);
                let runtime_error_class =
                    render_args.require_intrinsic(Intrinsic::WebAssemblyRuntimeError);
                output.push_str(&format!(
                    r#"
                    function {check_may_leave_fn}(componentIdx) {{
                        if ({instance_flags}.get(componentIdx)?.value !== 1) {{
                            throw new {runtime_error_class}('cannot leave component instance');
                        }}
                    }}
                    "#,
                ));
            }

            Self::GuardMayLeave => {
                let guard_may_leave_fn = render_args.require_intrinsic(Self::GuardMayLeave);
                let check_may_leave_fn = render_args.require_intrinsic(Self::CheckMayLeave);
                output.push_str(&format!(
                    r#"
                    function {guard_may_leave_fn}(componentIdx, fn) {{
                        return function (...args) {{
                            {check_may_leave_fn}(componentIdx);
                            return fn.apply(this, args);
                        }};
                    }}
                    "#,
                ));
            }

            Self::RecordTrap => {
                let record_trap_fn = render_args.require_intrinsic(Self::RecordTrap);
                let get_or_create_async_state_fn =
                    render_args.require_intrinsic(Self::GetOrCreateAsyncState);
                let global_current_thread_meta_obj =
                    render_args.require_intrinsic(Intrinsic::GlobalCurrentThreadMeta);
                let runtime_error_class =
                    render_args.require_intrinsic(Intrinsic::WebAssemblyRuntimeError);
                output.push_str(&format!(
                    r#"
                    function {record_trap_fn}(componentIdx, err, convertsRangeErrors = false) {{
                        // A built-in reading or writing guest memory past its end fails with a
                        // DataView RangeError: that is the Canonical ABI's out-of-bounds trap.
                        if (convertsRangeErrors && err instanceof RangeError) {{
                            err = new {runtime_error_class}('out of bounds memory access');
                        }}
                        if (err instanceof {runtime_error_class}) {{
                            // (a trampoline without a static instance records against the
                            // component whose guest code is running)
                            const idx = componentIdx ?? {global_current_thread_meta_obj}.current?.componentIdx;
                            if (idx !== undefined && idx !== null) {{
                                {get_or_create_async_state_fn}(idx).markTrapped(err);
                            }}
                        }}
                        return err;
                    }}
                    "#,
                ));
            }

            Self::GuardTrap => {
                let guard_trap_fn = render_args.require_intrinsic(Self::GuardTrap);
                let record_trap_fn = render_args.require_intrinsic(Self::RecordTrap);
                output.push_str(&format!(
                    r#"
                    function {guard_trap_fn}(componentIdx, fn, convertsRangeErrors = false) {{
                        return function (...args) {{
                            try {{
                                return fn.apply(this, args);
                            }} catch (err) {{
                                throw {record_trap_fn}(componentIdx, err, convertsRangeErrors);
                            }}
                        }};
                    }}
                    "#,
                ));
            }

            Self::GlobalAsyncStateMap => {
                let var_name = render_args.require_intrinsic(Self::GlobalAsyncStateMap);
                uwriteln!(output, r#"const {var_name} = new Map();"#);
            }

            Self::BackpressureInc => {
                let debug_log_fn = render_args.require_intrinsic(Intrinsic::DebugLog);
                let backpressure_inc_fn = render_args.require_intrinsic(Self::BackpressureInc);
                let get_or_create_async_state_fn =
                    render_args.require_intrinsic(Self::GetOrCreateAsyncState);
                output.push_str(&format!(
                    r#"
                    function {backpressure_inc_fn}(componentIdx) {{
                        {debug_log_fn}('[{backpressure_inc_fn}()] args', {{ componentIdx }});
                        const state = {get_or_create_async_state_fn}(componentIdx);
                        if (!state) {{ throw new Error(`missing component state for component [${{componentIdx}}]`); }}
                        const newValue = state.incrementBackpressure();
                        {debug_log_fn}('[{backpressure_inc_fn}()] incremented', {{ componentIdx, newValue }});
                    }}
                    "#,
                ));
            }

            Self::BackpressureDec => {
                let debug_log_fn = render_args.require_intrinsic(Intrinsic::DebugLog);
                let backpressure_dec_fn = render_args.require_intrinsic(Self::BackpressureDec);
                let get_or_create_async_state_fn =
                    render_args.require_intrinsic(Self::GetOrCreateAsyncState);
                output.push_str(&format!(
                    "
                    function {backpressure_dec_fn}(componentIdx) {{
                        {debug_log_fn}('[{backpressure_dec_fn}()] args', {{ componentIdx }});
                        const state = {get_or_create_async_state_fn}(componentIdx);
                        const newValue = state.decrementBackpressure();
                        {debug_log_fn}('[{backpressure_dec_fn}()] decremented', {{ componentIdx, newValue }});
                    }}
                "
                ));
            }

            Self::ComponentAsyncStateClass => {
                let component_async_state_class = self.name();
                let debug_log_fn = render_args.require_intrinsic(Intrinsic::DebugLog);
                let rep_table_class = render_args.require_intrinsic(Intrinsic::RepTableClass);
                let get_handle_index_space_fn = render_args
                    .require_intrinsic(Intrinsic::Resource(ResourceIntrinsic::GetHandleIndexSpace));
                let waitable_class =
                    render_args.require_intrinsic(WaitableIntrinsic::WaitableClass);
                let promise_with_resolvers_fn =
                    render_args.require_intrinsic(Intrinsic::PromiseWithResolversPonyfill);
                let runtime_error_class =
                    render_args.require_intrinsic(Intrinsic::WebAssemblyRuntimeError);
                let normalize_core_trap_fn = render_args.require_intrinsic(Self::NormalizeCoreTrap);
                let instance_flags = render_args.require_intrinsic(Self::GlobalInstanceFlagsMap);
                let store_trap = render_args.require_intrinsic(Self::GlobalStoreTrap);
                let check_for_deadlock_fn = render_args.require_intrinsic(Self::CheckForDeadlock);
                let cannot_enter_component = Trap::CannotEnterComponent.to_string();

                output.push_str(&format!(
                    r#"
                    class {component_async_state_class} {{
                        static EVENT_HANDLER_EVENTS = [ 'backpressure-change' ];

                        static TickResult = {{
                            // no suspended tasks remain
                            DONE: 'done',
                            // a suspended task was resumed (more may be ready)
                            RESUMED: 'resumed',
                            // suspended tasks remain but none were ready
                            IDLE: 'idle',
                        }};

                        #componentIdx;
                        #callingAsyncImport = false;
                        #syncImportWait = {promise_with_resolvers_fn}();
                        #lockHolderTaskID = null;
                        #lockWaiters = [];
                        #admissionQueue = [];
                        #lockHandoffScheduled = false;
                        #pendingTaskStarts = 0;
                        #parkedTasks = new Map();
                        // Suspended threads, oldest first (a Map iterates in insertion
                        // order, so no separate queue is kept for them).
                        #suspendedThreadsByRef = new Map();
                        #errored = null;
                        #trapped = false;
                        #trapError = null;
                        #backpressure = 0;
                        #backpressureWaiters = 0n;

                        #handlerMap = new Map();
                        #nextHandlerID = 0n;

                        #tickLoop = null;
                        #tickLoopInterval = null;

                        #onExclusiveReleaseHandlers = [];

                        #mayLeave = true;

                        handles;
                        subtasks;
                        threads;

                        constructor(args) {{
                            this.#componentIdx = args.componentIdx;
                            this.handles = new {rep_table_class}({{
                                target: `component [${{this.#componentIdx}}] handles (waitable objects)`,
                                space: {get_handle_index_space_fn}(this.#componentIdx),
                            }});
                            this.subtasks = new {rep_table_class}({{ target: `component [${{this.#componentIdx}}] subtasks` }});
                            this.threads = new {rep_table_class}({{ target: `component [${{this.#componentIdx}}] threads` }});
                        }};

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

                        get mayLeave() {{
                            const flags = {instance_flags}.get(this.#componentIdx);
                            return flags === undefined ? this.#mayLeave : flags.value === 1;
                        }}
                        set mayLeave(value) {{
                            if (typeof value !== 'boolean') {{ throw new TypeError('mayLeave must be a boolean'); }}
                            this.#mayLeave = value;
                            const flags = {instance_flags}.get(this.#componentIdx);
                            if (flags !== undefined) {{ flags.value = value ? 1 : 0; }}
                        }}

                        errored() {{ return this.#errored !== null; }}
                        setErrored(err) {{
                            {debug_log_fn}('[{component_async_state_class}#setErrored()] component errored', {{ err, componentIdx: this.#componentIdx }});
                            if (this.#errored) {{ return; }}
                            if (!err) {{
                                err = new Error('error elswehere (see other component instance error)')
                                err.componentIdx = this.#componentIdx;
                            }}
                            this.#errored = err;
                        }}

                        markTrapped(err) {{
                            if (!(err instanceof {runtime_error_class})) {{
                                return false;
                            }}
                            err = {normalize_core_trap_fn}(err);
                            this.#trapped = true;
                            if (this.#trapError === null) {{ this.#trapError = err; }}
                            {debug_log_fn}('[{component_async_state_class}#markTrapped()] component trapped', {{ err, componentIdx: this.#componentIdx }});
                            if ({store_trap}.error === null) {{ {store_trap}.error = err; }}
                            return true;
                        }}

                        isTrapped() {{ return this.#trapped; }}
                        // For work that was already under way or queued when the instance
                        // trapped: it fails with that trap (nothing runs after a trap).
                        throwIfInterrupted() {{
                            if (this.#trapped) {{
                                throw this.#trapError ?? new {runtime_error_class}({cannot_enter_component:?});
                            }}
                        }}
                        throwIfTrapped() {{
                            if (this.#trapped) {{
                                throw new {runtime_error_class}({cannot_enter_component:?});
                            }}
                        }}

                        callingSyncImport(val) {{
                            if (val === undefined) {{ return this.#callingAsyncImport; }}
                            if (typeof val !== 'boolean') {{ throw new TypeError('invalid setting for async import'); }}
                            const prev = this.#callingAsyncImport;
                            this.#callingAsyncImport = val;
                            if (prev === true && this.#callingAsyncImport === false) {{
                                this.#notifySyncImportEnd();
                            }}
                        }}

                        #notifySyncImportEnd() {{
                            const existing = this.#syncImportWait;
                            this.#syncImportWait = {promise_with_resolvers_fn}();
                            existing.resolve();
                        }}

                        async waitForSyncImportCallEnd() {{
                            await this.#syncImportWait.promise;
                        }}

                        setBackpressure(v) {{
                            this.#backpressure = v;
                            return this.#backpressure
                        }}
                        getBackpressure() {{ return this.#backpressure; }}

                        incrementBackpressure() {{
                            const current = this.#backpressure;
                            if (current < 0 || current > 2**16) {{
                                throw new Error(`invalid current backpressure value [${{current}}]`);
                            }}
                            const newValue = this.getBackpressure() + 1;
                            if (newValue >= 2**16) {{
                                throw new Error(`invalid new backpressure value [${{newValue}}], overflow`);
                            }}
                            return this.setBackpressure(newValue);
                        }}

                        decrementBackpressure() {{
                            const current = this.#backpressure;
                            if (current < 0 || current > 2**16) {{
                                throw new Error(`invalid current backpressure value [${{current}}]`);
                            }}
                            // Canonical ABI `backpressure.dec`: trap if the counter would go
                            // below zero.
                            const newValue = current - 1;
                            if (newValue < 0) {{
                                throw new {runtime_error_class}('backpressure counter underflow');
                            }}
                            return this.setBackpressure(newValue);
                        }}
                        hasBackpressure() {{ return this.#backpressure > 0; }}

                        waitForBackpressure() {{
                            let backpressureCleared = false;
                            const cstate = this;
                            cstate.addBackpressureWaiter();
                            const handlerID = this.registerHandler({{
                                event: 'backpressure-change',
                                fn: (bp) => {{
                                    if (bp === 0) {{
                                        cstate.removeHandler(handlerID);
                                        backpressureCleared = true;
                                    }}
                                }}
                            }});
                            return new Promise((resolve) => {{
                                const interval = setInterval(() => {{
                                    if (backpressureCleared) {{ return; }}
                                    clearInterval(interval);
                                    cstate.removeBackpressureWaiter();
                                    resolve(null);
                                }}, 0);
                            }});
                        }}

                        registerHandler(args) {{
                            const {{ event, fn }} = args;
                            if (!event) {{ throw new Error("missing handler event"); }}
                            if (!fn) {{ throw new Error("missing handler fn"); }}

                            if (!{component_async_state_class}.EVENT_HANDLER_EVENTS.includes(event)) {{
                                throw new Error(`unrecognized event handler [${{event}}]`);
                            }}

                            const handlerID = this.#nextHandlerID++;
                            let handlers = this.#handlerMap.get(event);
                            if (!handlers) {{
                                handlers = [];
                                this.#handlerMap.set(event, handlers)
                            }}

                            handlers.push({{ id: handlerID, fn, event }});
                            return handlerID;
                        }}

                        removeHandler(args) {{
                            const {{ event, handlerID }} = args;
                            const registeredHandlers = this.#handlerMap.get(event);
                            if (!registeredHandlers) {{ return; }}
                            const found = registeredHandlers.find(h => h.id === handlerID);
                            if (!found) {{ return; }}
                            this.#handlerMap.set(event, this.#handlerMap.get(event).filter(h => h.id !== handlerID));
                        }}

                        getBackpressureWaiters() {{ return this.#backpressureWaiters; }}
                        addBackpressureWaiter() {{ this.#backpressureWaiters++; }}
                        removeBackpressureWaiter() {{
                            this.#backpressureWaiters--;
                            if (this.#backpressureWaiters < 0) {{
                                throw new Error("unexepctedly negative number of backpressure waiters");
                            }}
                        }}

                        // The per-slice mutual-exclusion lock for guest execution in this
                        // component instance. Guest slices (callback invocations and
                        // sync-lifted bodies) must be atomic per component even across the
                        // JSPI suspensions jco introduces for host imports: wit-bindgen's
                        // executors publish per-task state in single linear-memory cells
                        // (the wasip3-task pointer, context-local storage discipline) that
                        // an interleaved slice of the same component corrupts
                        //
                        // The lock is *owned*: acquisition records the holder task and
                        // release is a no-op for anyone else, so a task exiting can no
                        // longer drop a hold it does not own (blind acquire/release-any
                        // was the previous discipline). Contended acquisition queues
                        // FIFO; release hands the lock to the next waiter directly.
                        isExclusivelyLocked() {{ return this.#lockHolderTaskID !== null; }}
                        exclusivelyLockedBy(taskID) {{ return this.#lockHolderTaskID === taskID; }}

                        exclusiveLock(taskID) {{
                            {debug_log_fn}('[{component_async_state_class}#exclusiveLock()]', {{
                                holder: this.#lockHolderTaskID,
                                requester: taskID,
                                componentIdx: this.#componentIdx,
                            }});
                            if (taskID === undefined || taskID === null) {{
                                throw new Error('exclusive lock requires the acquiring task id');
                            }}
                            if (this.#lockHolderTaskID !== null) {{
                                throw new Error(`component [${{this.#componentIdx}}] exclusive lock held by task [${{this.#lockHolderTaskID}}], requested by [${{taskID}}]`);
                            }}
                            this.#lockHolderTaskID = taskID;
                        }}

                        // Awaitable acquisition: takes the lock immediately when free,
                        // otherwise queues FIFO behind the current holder and earlier
                        // waiters. The resolved promise implies ownership.
                        acquireExclusiveLock(taskID) {{
                            if (taskID === undefined || taskID === null) {{
                                throw new Error('exclusive lock requires the acquiring task id');
                            }}
                            if (this.#lockHolderTaskID === null) {{
                                this.#lockHolderTaskID = taskID;
                                {debug_log_fn}('[{component_async_state_class}#acquireExclusiveLock()] acquired', {{
                                    holder: taskID,
                                    componentIdx: this.#componentIdx,
                                }});
                                return;
                            }}
                            if (this.#lockHolderTaskID === taskID) {{
                                throw new Error(`task [${{taskID}}] already holds the lock for component [${{this.#componentIdx}}]`);
                            }}
                            {debug_log_fn}('[{component_async_state_class}#acquireExclusiveLock()] waiting', {{
                                holder: this.#lockHolderTaskID,
                                requester: taskID,
                                componentIdx: this.#componentIdx,
                                queued: this.#lockWaiters.length,
                            }});
                            return new Promise((resolve) => {{
                                this.#lockWaiters.push({{ taskID, resolve }});
                            }});
                        }}

                        // Release every queued entry without granting ownership, so that
                        // calls waiting to enter a trapped store fail instead of hanging.
                        // FIFO admission of tasks entering this instance (Canonical ABI
                        // `inst.pending`): a task enters only after every task that asked to
                        // enter before it has entered or given up, so calls enter in the order
                        // they were made, whatever each waits for on the way.
                        takeAdmissionTicket(taskID) {{
                            const ticket = {{ taskID, ...{promise_with_resolvers_fn}() }};
                            this.#admissionQueue.push(ticket);
                            return ticket;
                        }}
                        hasPendingAdmissions() {{ return this.#admissionQueue.length > 0; }}
                        waitForAdmissionTurn(ticket) {{
                            if (this.#admissionQueue[0] === ticket) {{ return; }}
                            return ticket.promise;
                        }}
                        releaseAdmissionTicket(ticket) {{
                            const idx = this.#admissionQueue.indexOf(ticket);
                            if (idx === -1) {{ return; }}
                            this.#admissionQueue.splice(idx, 1);
                            if (idx === 0 && this.#admissionQueue.length > 0) {{
                                this.#admissionQueue[0].resolve();
                            }}
                        }}
                        // Release every queued entry (the instance trapped): each then fails
                        // in `enter()` instead of waiting forever.
                        abandonAdmissionWaiters() {{
                            const tickets = this.#admissionQueue.splice(0);
                            for (const ticket of tickets) {{ ticket.resolve(); }}
                        }}

                        abandonLockWaiters() {{
                            const waiters = this.#lockWaiters.splice(0);
                            for (const waiter of waiters) {{ waiter.resolve(); }}
                        }}

                        cancelExclusiveLockWaiter(taskID) {{
                            const idx = this.#lockWaiters.findIndex(waiter => waiter.taskID === taskID);
                            if (idx === -1) {{ return false; }}
                            const [waiter] = this.#lockWaiters.splice(idx, 1);
                            // Release the awaiting `enter()` continuation without granting
                            // ownership. It observes the task's resolved cancellation state
                            // before attempting to execute guest code.
                            waiter.resolve();
                            return true;
                        }}

                        exclusiveRelease(taskID) {{
                            {debug_log_fn}('[{component_async_state_class}#exclusiveRelease()] args', {{
                                holder: this.#lockHolderTaskID,
                                releaser: taskID,
                                componentIdx: this.#componentIdx,
                            }});
                            if (this.#lockHolderTaskID !== taskID) {{
                                // Ownerless releases were the historical behavior; a foreign
                                // release now leaves the hold intact
                                {debug_log_fn}('[{component_async_state_class}#exclusiveRelease()] ignoring foreign release', {{
                                    holder: this.#lockHolderTaskID,
                                    releaser: taskID,
                                    componentIdx: this.#componentIdx,
                                }});
                                return false;
                            }}

                            // Make the release observable before handing the lock to the next
                            // asynchronous guest slice.
                            //
                            // Release handlers may expose a lifted value whose consumer immediately
                            // performs a synchronous call on the same component; that call must run
                            // while the instance is genuinely unlocked, not via enterSync's
                            // lock-free fallback code.
                            this.#lockHolderTaskID = null;

                            this.#onExclusiveReleaseHandlers = this.#onExclusiveReleaseHandlers.filter(v => !!v);
                            for (const [idx, f] of this.#onExclusiveReleaseHandlers.entries()) {{
                                try {{
                                    this.#onExclusiveReleaseHandlers[idx] = null;
                                    f();
                                }} catch (err) {{
                                    {debug_log_fn}("error while executing handler for next exclusive release", err);
                                    throw err;
                                }}
                            }}
                            this.#scheduleLockHandoff();
                            return true;
                        }}

                        #scheduleLockHandoff() {{
                            if (this.#lockHandoffScheduled || this.#lockWaiters.length === 0) {{ return; }}
                            this.#lockHandoffScheduled = true;
                            queueMicrotask(() => {{
                                this.#lockHandoffScheduled = false;
                                // A synchronous call triggered by a release handler gets the
                                // first opportunity to use the unlocked component. Its own
                                // release schedules the next handoff; re-queueing one here
                                // would spin the microtask queue for as long as the holder
                                // stays blocked (e.g. in a synchronous wait), starving every
                                // timer, the deadlock detector included.
                                if (this.#lockHolderTaskID !== null) {{ return; }}
                                const next = this.#lockWaiters.shift();
                                if (!next) {{ return; }}
                                this.#lockHolderTaskID = next.taskID;
                                next.resolve();
                            }});
                        }}

                        onNextExclusiveRelease(fn) {{
                            {debug_log_fn}('[{component_async_state_class}#()onNextExclusiveRelease] registering');
                            this.#onExclusiveReleaseHandlers.push(fn);
                        }}

                        async waitForExclusiveRelease() {{
                            while (this.isExclusivelyLocked()) {{
                                await new Promise(resolve => this.onNextExclusiveRelease(resolve));
                            }}
                        }}

                        // Callback drivers refer to the implicit thread by task ID.
                        // Stackful built-ins pass their current thread directly.
                        #getSuspendedTaskMeta(taskID) {{
                            const metas = [...this.#suspendedThreadsByRef.values()].filter(meta => meta.thread.taskID() === taskID);
                            return metas.find(meta => meta.cancellable && this.suspendedThreadReady(meta.thread)) ?? metas[0];
                        }}

                        suspendTask(args) {{
                            const {{ task, ...opts }} = args;
                            task.endFirstSlice();
                            return this.suspendThread({{ thread: task.defaultThread(), ...opts }});
                        }}

                        resumeTaskByID(taskID) {{
                            const meta = this.#getSuspendedTaskMeta(taskID);
                            return meta ? this.resumeThread(meta.thread) : false;
                        }}

                        suspendedTaskReady(taskID) {{
                            const meta = this.#getSuspendedTaskMeta(taskID);
                            return meta ? this.suspendedThreadReady(meta.thread) : false;
                        }}

                        suspendedTaskCancellable(taskID) {{
                            return !!this.#getSuspendedTaskMeta(taskID)?.cancellable;
                        }}

                        isTaskSuspended(taskID) {{
                            return !!this.#getSuspendedTaskMeta(taskID);
                        }}

                        *suspendedTaskMetas() {{
                            for (const meta of this.#suspendedThreadsByRef.values()) {{
                                yield {{ ...meta, task: meta.thread.task() }};
                            }}
                        }}

                        #removeSuspendedThreadMeta(thread) {{
                            const meta = this.#suspendedThreadsByRef.get(thread);
                            this.#suspendedThreadsByRef.delete(thread);
                            return meta;
                        }}

                        suspendThread(args) {{
                            const {{ thread, readyFn, cancellable, onResume, suspended = false }} = args;
                            {debug_log_fn}('[{component_async_state_class}#suspendThread()]', {{
                                threadID: thread.id(),
                                taskID: thread.taskID(),
                                componentIdx: this.#componentIdx,
                            }});

                            if (thread.componentIdx() !== this.#componentIdx) {{
                                throw new Error('assert: thread component idx should match async state');
                            }}
                            if (this.#suspendedThreadsByRef.has(thread)) {{
                                throw new Error(`thread [${{thread.id()}}] already suspended`);
                            }}

                            let promise;
                            let resume;
                            if (onResume) {{
                                resume = () => onResume(!thread.isCancelled() && !thread.isRejected() && !this.isTrapped());
                            }} else {{
                                const resolvers = {promise_with_resolvers_fn}();
                                promise = resolvers.promise;
                                resume = () => resolvers.resolve(!thread.isCancelled() && !thread.isRejected() && !this.isTrapped());
                            }}
                            this.#suspendedThreadsByRef.set(thread, {{ thread, cancellable, readyFn, resume, suspended }});

                            thread.notifyProgress();

                            this.runTickLoop();
                            {check_for_deadlock_fn}();

                            return promise;
                        }}

                        resumeThread(thread) {{
                            const meta = this.#removeSuspendedThreadMeta(thread);
                            if (!meta) {{ return false; }}
                            meta.resume();
                            return true;
                        }}

                        markThreadReady(thread) {{
                            const meta = this.#suspendedThreadsByRef.get(thread);
                            if (!meta || !meta.suspended) {{ return false; }}
                            meta.suspended = false;
                            meta.readyFn = () => true;
                            this.runTickLoop();
                            return true;
                        }}

                        isThreadSuspended(thread) {{
                            return this.#suspendedThreadsByRef.get(thread)?.suspended ?? false;
                        }}

                        isThreadReady(thread) {{
                            const meta = this.#suspendedThreadsByRef.get(thread);
                            return !!meta && !meta.suspended && (meta.thread.isRejected() || meta.readyFn());
                        }}

                        suspendedThreadReady(thread) {{
                            const meta = this.#suspendedThreadsByRef.get(thread);
                            if (!meta) {{ return false; }}
                            if (!meta.readyFn) {{
                                throw new Error(`suspended thread [${{thread.id()}}] is missing a readiness function`);
                            }}
                            if (this.isTrapped() || meta.thread.isRejected()) {{ return true; }}
                            if (!meta.readyFn()) {{ return false; }}
                            const task = meta.thread.task();
                            return !task.needsExclusiveLock()
                                || !this.isExclusivelyLocked()
                                || this.exclusivelyLockedBy(task.id());
                        }}

                        addPendingTaskStart() {{ this.#pendingTaskStarts++; }}
                        removePendingTaskStart() {{ this.#pendingTaskStarts--; }}

                        hasPendingSchedulerWork() {{
                            if (this.#pendingTaskStarts > 0) {{ return true; }}
                            if (this.#lockHandoffScheduled) {{ return true; }}
                            for (const meta of this.#suspendedThreadsByRef.values()) {{
                                if (this.suspendedThreadReady(meta.thread)) {{ return true; }}
                            }}
                            return false;
                        }}

                        async runTickLoop() {{
                            if (this.#tickLoop !== null) {{ return; }}
                            this.#tickLoop = 1;
                            setTimeout(async () => {{
                                let result = this.tick();
                                while (result !== {component_async_state_class}.TickResult.DONE) {{
                                    if (result === {component_async_state_class}.TickResult.IDLE) {{
                                        {check_for_deadlock_fn}();
                                    }}
                                    // After resuming a task, re-tick as soon as the resumed
                                    // slice's microtask continuations have drained (timeout 0)
                                    // so queued sibling resumptions aren't charged the idle
                                    // polling interval; otherwise poll at the idle cadence.
                                    const delay = result === {component_async_state_class}.TickResult.RESUMED ? 0 : 10;
                                    await new Promise((resolve) => setTimeout(resolve, delay));
                                    result = this.tick();
                                }}
                                this.#tickLoop = null;
                            }}, 10);
                        }}

                        tick() {{
                            // (resuming returns immediately below, so the map is never
                            // mutated while this loop is still iterating it)
                            for (const [thread, meta] of this.#suspendedThreadsByRef) {{
                                if (!meta || !meta.readyFn) {{
                                    throw new Error(`missing/invalid thread meta despite thread [${{thread.id()}}] being present`);
                                }}

                                if (this.isTrapped() || meta.thread.isRejected()) {{
                                    {debug_log_fn}('[{component_async_state_class}#tick()] detected thread rejection, leaving early', {{ meta }});
                                    this.resumeThread(thread);
                                    return {component_async_state_class}.TickResult.RESUMED;
                                }}

                                if (!this.suspendedThreadReady(thread)) {{ continue; }}

                                {debug_log_fn}('[{component_async_state_class}#tick()] resuming thread via tick', {{
                                    threadID: thread.id(),
                                    componentIdx: this.#componentIdx,
                                }});
                                this.resumeThread(thread);

                                // Resume only one thread per tick so its current-thread
                                // register window closes before another continuation runs.
                                return {component_async_state_class}.TickResult.RESUMED;
                            }}

                            const idle = this.#suspendedThreadsByRef.size > 0;
                            return idle
                                ? {component_async_state_class}.TickResult.IDLE
                                : {component_async_state_class}.TickResult.DONE;
                        }}

                        createWaitable(args) {{
                            return new {waitable_class}({{ target: args?.target, }});
                        }}
                    }}
                    "#,
                ));
            }

            Self::GetOrCreateAsyncState => {
                let get_state_fn = render_args.require_intrinsic(Self::GetOrCreateAsyncState);
                let async_state_map = render_args.require_intrinsic(Self::GlobalAsyncStateMap);
                let component_async_state_class =
                    render_args.require_intrinsic(Self::ComponentAsyncStateClass);
                output.push_str(&format!(
                    r#"
                    function {get_state_fn}(componentIdx, init) {{
                        if (!{async_state_map}.has(componentIdx)) {{
                            const newState = new {component_async_state_class}({{ componentIdx }});
                            {async_state_map}.set(componentIdx, newState);
                        }}
                        return {async_state_map}.get(componentIdx);
                    }}
                   "#
                ));
            }

            Self::ComponentStateSetAllError => {
                let debug_log_fn = render_args.require_intrinsic(Intrinsic::DebugLog);
                let async_state_map = render_args.require_intrinsic(Self::GlobalAsyncStateMap);
                let component_state_set_all_error_fn =
                    render_args.require_intrinsic(Self::ComponentStateSetAllError);
                output.push_str(&format!(
                    r#"
                    function {component_state_set_all_error_fn}() {{
                        {debug_log_fn}('[{component_state_set_all_error_fn}()]');
                        for (const state of {async_state_map}.values()) {{
                            state.setErrored();
                        }}
                    }}
                    "#
                ));
            }
        }
    }
}