wasm-rquickjs 0.4.4

Tool for wrapping JavaScript modules as WebAssembly components using the QuickJS engine
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
use crate::javascript::escape_js_ident;
use crate::rust_bindgen::RustWitFunction;
use crate::types::{
    ProcessedParameter, ReturnTypeInformation, WrappedType, get_function_name, get_return_type,
    ident_in_exported_interface, ident_in_exported_interface_or_global, param_refs_as_tuple,
    process_parameter, to_original_func_arg_list, to_wrapped_param_refs, type_borrows_resource,
};
use crate::{EmbeddingMode, GeneratorContext, JsModuleSpec};
use anyhow::{Context, anyhow};
use heck::{ToLowerCamelCase, ToUpperCamelCase};
use proc_macro2::{Ident, Span, TokenStream};
use quote::quote;
use std::collections::BTreeMap;
use syn::{Lit, LitStr};
use wit_parser::{
    Function, FunctionKind, Interface, InterfaceId, TypeDefKind, TypeId, TypeOwner, WorldItem,
    WorldKey,
};

/// Generates the `<output>/src/lib.rs` file for the wrapper crate, implementing the component exports
/// and providing the general Rust module declarations.
pub fn generate_export_impls(
    context: &GeneratorContext<'_>,
    js_modules: &[JsModuleSpec],
) -> anyhow::Result<()> {
    let guest_impls = generate_guest_impls(context)?;
    let module_defs = generate_module_defs(js_modules)?;

    let world_name_lit = LitStr::new(&context.world_name, Span::call_site());
    let with_block = generate_wasi_remaps(context);

    // The Preview 3 path enables the component-model async ABI. It uses a renamed
    // `wit-bindgen` dependency (`wit-bindgen-p3`, compiled with the
    // `async`/`macros`/`inter-task-wakeup` features) so that it can coexist with the Preview 2
    // `wit-bindgen` in the single shared skeleton; `runtime_path` points the generated bindings
    // at that renamed crate's runtime module.
    //
    // `ownership: Owning` and `generate_all` match the Preview 2 invocation below.
    // `ownership: Owning` keeps generated ADTs owned (no lifetime-parameterized borrowed
    // variants), which is what the import/export codegen in this crate models. `generate_all`
    // is required so that interfaces without a `with:` remap entry — user-defined imports and
    // WASI interfaces whose version does not match the `wasip3` crate (e.g.
    // `wasi:io/poll@0.2.3`) — get bindings generated instead of making the macro fail.
    let bindings_module = if context.target.is_p3() {
        quote! {
            #[allow(unsafe_op_in_unsafe_fn)]
            pub(crate) mod bindings {
                wit_bindgen_p3::generate!({
                    path: "wit",
                    world: #world_name_lit,
                    runtime_path: "wit_bindgen_p3::rt",
                    ownership: Owning,
                    generate_all,
                    #with_block
                });
            }
        }
    } else {
        quote! {
            #[allow(unsafe_op_in_unsafe_fn)]
            pub(crate) mod bindings {
                wit_bindgen::generate!({
                    path: "wit",
                    world: #world_name_lit,
                    ownership: Owning,
                    generate_all,
                    #with_block
                });
            }
        }
    };

    // In the Preview 3 path the Node.js builtin tree (`builtin/`) is not compiled at all;
    // `mod builtin` is bound to the minimal `builtin_p3.rs` stub instead, so none of the
    // P2-only builtin dependencies are pulled in. See `builtin_p3.rs`.
    let builtin_module = if context.target.is_p3() {
        quote! {
            #[path = "builtin_p3.rs"]
            mod builtin;
        }
    } else {
        quote! { mod builtin; }
    };

    let lib_tokens = quote! {
        #bindings_module
        #builtin_module
        mod conversions;
        #[allow(unused)]
        mod internal;
        #[allow(unused)]
        mod modules;
        mod wrappers;

        #module_defs

        struct Component;

        #(#guest_impls)*

        bindings::export!(Component with_types_in bindings);
    };

    let lib_ast: syn::File =
        syn::parse2(lib_tokens).context("failed to parse generated lib.rs tokens")?;

    let lib_path = context.output.join("src").join("lib.rs");
    let lib_src = prettier_please::unparse(&lib_ast);

    crate::write_if_changed(&lib_path, lib_src)?;

    Ok(())
}

/// Generates a list of code snippets, each implementing one of the `Guest` traits generated by
/// wit-bindgen-rust for the component's exports.
fn generate_guest_impls(context: &GeneratorContext<'_>) -> anyhow::Result<Vec<TokenStream>> {
    let mut result = Vec::new();

    let world = &context.resolve.worlds[context.world];

    let mut global_exports = Vec::new();
    let mut interface_exports = Vec::new();

    // Enumerating all exports and separating them into global exports and interface exports.
    for (name, export) in &world.exports {
        let name = match name {
            WorldKey::Name(name) => name.clone(),
            WorldKey::Interface(id) => {
                let interface = &context.resolve.interfaces[*id];
                interface
                    .name
                    .clone()
                    .ok_or_else(|| anyhow!("Interface export does not have a name"))?
            }
        };
        match export {
            WorldItem::Interface { id, .. } => {
                let interface = &context.resolve.interfaces[*id];
                interface_exports.push((name, interface, *id));
            }
            WorldItem::Function(function) => {
                global_exports.push((name, function));
            }
            WorldItem::Type { .. } => {}
        }
    }

    // Implementing a single Guest trait containing all the global exported functions
    if !global_exports.is_empty() {
        result.extend(generate_guest_impl(
            context,
            quote! { crate::bindings::Guest },
            None,
            &global_exports,
        )?);
    }

    // Implementing a Guest trait per exported interface
    for (name, interface, interface_id) in interface_exports {
        let interface_exports: Vec<_> = interface
            .functions
            .iter()
            .map(|(name, function)| (name.clone(), function))
            .collect();

        result.extend(generate_guest_impl(
            context,
            ident_in_exported_interface(
                context,
                Ident::new("Guest", Span::call_site()),
                &name,
                interface,
            ),
            Some((&name, interface, interface_id)),
            &interface_exports,
        )?);
    }

    Ok(result)
}

/// Returns the terminal resource type ID when `type_id` denotes a resource, following `use`
/// re-exports and type aliases (`TypeDefKind::Type(Type::Id(..))`) to their target. A direct
/// resource has its kind set to `Resource`, but an interface that re-exports a resource via
/// `use other.{r};` stores it as an alias, so a naive `kind == Resource` check would miss it.
fn resolve_resource_type_id(
    context: &GeneratorContext<'_>,
    type_id: TypeId,
) -> anyhow::Result<Option<TypeId>> {
    let mut current = type_id;
    loop {
        let typ = context
            .resolve
            .types
            .get(current)
            .ok_or_else(|| anyhow!("Unknown type id {current:?}"))?;
        match &typ.kind {
            TypeDefKind::Resource => return Ok(Some(current)),
            TypeDefKind::Type(wit_parser::Type::Id(next)) => current = *next,
            _ => return Ok(None),
        }
    }
}

/// Generates the implementation of a `Guest` trait for the component, implementing the exported functions.
///
/// The `guest_trait` parameter is a Rust snippet containing the fully-qualified path to the `Guest` trait to
/// be implemented.
///
/// If there are resources in the interface, the return contains all the trait implementations, for the interface
/// and the resources as well.
fn generate_guest_impl(
    context: &GeneratorContext<'_>,
    guest_trait: TokenStream,
    interface: Option<(&str, &Interface, InterfaceId)>,
    exports: &[(String, &Function)],
) -> anyhow::Result<Vec<TokenStream>> {
    let mut func_impls = Vec::new();
    let mut resource_impls = Vec::new();
    let mut resource_functions = BTreeMap::new();

    let is_p3 = context.target.is_p3();

    // The Preview 3 path supports exported resources that have at least one
    // constructor/method/static function. A resource with no functions produces no entries in
    // `exports` (so no `GuestX` impl would be generated — the same limitation exists on the P2
    // path), which would surface as an obscure compile error. Reject such methodless exported
    // resources at the type level here with an actionable message.
    if is_p3 && let Some((_, iface, interface_id)) = interface {
        let mut resource_ids_with_functions = std::collections::HashSet::new();
        for (_, function) in exports {
            match &function.kind {
                FunctionKind::Method(type_id)
                | FunctionKind::Static(type_id)
                | FunctionKind::Constructor(type_id)
                | FunctionKind::AsyncMethod(type_id)
                | FunctionKind::AsyncStatic(type_id) => {
                    resource_ids_with_functions.insert(*type_id);
                }
                _ => {}
            }
        }

        for (_, type_id) in &iface.types {
            let Some(resource_type_id) = resolve_resource_type_id(context, *type_id)? else {
                continue;
            };
            let resource = context.typ(resource_type_id)?;

            if !matches!(
                &resource.owner,
                TypeOwner::Interface(owner) if *owner == interface_id
            ) {
                continue;
            }
            if !resource_ids_with_functions.contains(type_id)
                && !resource_ids_with_functions.contains(&resource_type_id)
            {
                let resource_name = resource.name.as_deref().unwrap_or("<anonymous>");
                return Err(anyhow!(
                    "Exported resources without any constructor, method, or static function are not supported by the WASI Preview 3 generation path (resource '{resource_name}')"
                ));
            }
        }
    }

    for (name, function) in exports {
        match &function.kind {
            FunctionKind::Freestanding => {
                if name == "wizer-initialize" {
                    // wizer-initialize calls directly into the skeleton's
                    // pre-init function instead of dispatching to JS
                    func_impls.push(quote! {
                        fn wizer_initialize() {
                            crate::internal::wizer_initialize();
                        }
                    });
                } else {
                    let func_impl =
                        generate_exported_function_impl(context, interface, name, function)?;
                    func_impls.push(func_impl);
                }
            }
            FunctionKind::AsyncFreestanding => {
                if is_p3 && name == "wizer-initialize" {
                    func_impls.push(quote! {
                        async fn wizer_initialize() {
                            crate::internal::wizer_initialize().await;
                        }
                    });
                } else if is_p3 {
                    let func_impl =
                        generate_exported_function_impl(context, interface, name, function)?;
                    func_impls.push(func_impl);
                } else {
                    return Err(anyhow!("Async exported functions are not supported yet"));
                }
            }
            FunctionKind::AsyncMethod(type_id) | FunctionKind::AsyncStatic(type_id) => {
                if is_p3 {
                    resource_functions
                        .entry(type_id)
                        .or_insert_with(Vec::new)
                        .push((name, function));
                } else {
                    return Err(anyhow!("Async exported functions are not supported yet"));
                }
            }
            FunctionKind::Method(type_id)
            | FunctionKind::Static(type_id)
            | FunctionKind::Constructor(type_id) => {
                resource_functions
                    .entry(type_id)
                    .or_insert_with(Vec::new)
                    .push((name, function));
            }
        }
    }

    let mut resource_types = Vec::new();
    for (resource_type_id, resource_funcs) in resource_functions {
        let typ = context
            .resolve
            .types
            .get(*resource_type_id)
            .ok_or_else(|| anyhow!("Unknown resource type id"))?;

        let resource_name = typ
            .name
            .as_ref()
            .ok_or_else(|| anyhow!("Resource type has no name"))?;
        let resource_name_ident =
            Ident::new(&resource_name.to_upper_camel_case(), Span::call_site());
        let resource_name_borrow_ident = Ident::new(
            &format!("{}Borrow", resource_name.to_upper_camel_case()),
            Span::call_site(),
        );
        let guest_name_ident = Ident::new(
            &format!("Guest{}", resource_name.to_upper_camel_case()),
            Span::call_site(),
        );
        let interface_name_and_def = interface.map(|(name, interface, _)| (name, interface));
        let guest_trait = ident_in_exported_interface_or_global(
            context,
            guest_name_ident,
            interface_name_and_def,
        );

        let borrow_wrapper = ident_in_exported_interface_or_global(
            context,
            resource_name_borrow_ident,
            interface_name_and_def,
        );
        let owned_wrapper = ident_in_exported_interface_or_global(
            context,
            resource_name_ident.clone(),
            interface_name_and_def,
        );

        let mut resource_func_impls = Vec::new();
        for (name, resource_function) in resource_funcs {
            let func_impl = generate_exported_resource_function_impl(
                context,
                interface,
                resource_type_id,
                name,
                resource_function,
            )?;
            resource_func_impls.push(func_impl);
        }

        resource_impls.push(quote! {
            struct #resource_name_ident {
                resource_id: usize
            }

            impl #guest_trait for #resource_name_ident {
                #(#resource_func_impls)*
            }

            impl Drop for #resource_name_ident {
                fn drop(&mut self) {
                    crate::internal::enqueue_drop_js_resource(self.resource_id);
                }
            }

            impl<'js> rquickjs::IntoJs<'js> for #borrow_wrapper<'_> {
                fn into_js(self, ctx: &rquickjs::Ctx<'js>) -> rquickjs::Result<rquickjs::Value<'js>> {
                    let inner: &#resource_name_ident = self.get();
                    let resource_table: rquickjs::Object = ctx.globals().get(crate::internal::RESOURCE_TABLE_NAME)
                        .expect("Failed to get the resource table");
                    let resource_instance: rquickjs::Object = resource_table.get(inner.resource_id.to_string())
                        .expect(&format!("Failed to get resource instance with id {}", inner.resource_id));
                    Ok(resource_instance.into_value())
                }
            }

            impl<'js> rquickjs::IntoJs<'js> for #owned_wrapper {
                fn into_js(self, ctx: &rquickjs::Ctx<'js>) -> rquickjs::Result<rquickjs::Value<'js>> {
                    let inner: &#resource_name_ident = self.get();
                    let resource_table: rquickjs::Object = ctx.globals().get(crate::internal::RESOURCE_TABLE_NAME)
                        .expect("Failed to get the resource table");
                    let resource_instance: rquickjs::Object = resource_table.get(inner.resource_id.to_string())
                        .expect(&format!("Failed to get resource instance with id {}", inner.resource_id));
                    Ok(resource_instance.into_value())
                }
            }

            impl<'js> rquickjs::FromJs<'js> for #owned_wrapper {
                fn from_js(ctx: &rquickjs::Ctx<'js>, value: rquickjs::Value<'js>) -> rquickjs::Result<Self> {
                    let resource = value.into_object().ok_or_else(|| {
                        rquickjs::Error::new_from_js_message(
                            "JS Resource instance",
                            "WASM resource instance",
                            "The value is not an object",
                        )
                    })?;

                    let already_registered = resource.contains_key(crate::internal::RESOURCE_ID_KEY)?;
                    let resource_id: usize = if already_registered {
                        // This resource instance is already registered in the resource table
                        resource.get(crate::internal::RESOURCE_ID_KEY)?
                    } else {
                        // This is a new resource instance, we need to store it in the resource table
                        let resource_table: rquickjs::Object = ctx.globals().get(crate::internal::RESOURCE_TABLE_NAME)?;
                        let resource_id = crate::internal::get_free_resource_id();
                        resource_table.set(resource_id.to_string(), resource)?;
                        resource_id
                    };

                    Ok(#owned_wrapper::new(#resource_name_ident { resource_id }))
                }
            }
        });

        resource_types.push(quote! {
            type #resource_name_ident = #resource_name_ident;
        })
    }

    let mut guest_impls = Vec::new();
    guest_impls.extend(resource_impls);
    guest_impls.push(quote! {
        impl #guest_trait for Component {
            #(#resource_types)*
            #(#func_impls)*
        }
    });

    Ok(guest_impls)
}

/// Generates one trait method implementation for an exported freestanding function
fn generate_exported_function_impl(
    context: &GeneratorContext<'_>,
    interface: Option<(&str, &Interface, InterfaceId)>,
    name: &str,
    function: &Function,
) -> anyhow::Result<TokenStream> {
    let rust_fn = RustWitFunction::new(context, name, function);
    let func_name = rust_fn.function_name_ident();

    if context.target.is_p3()
        && matches!(function.kind, FunctionKind::Freestanding)
        && function
            .result
            .as_ref()
            .map(|result| crate::async_values::contains(context, result))
            .transpose()?
            .unwrap_or(false)
    {
        return Err(anyhow!(
            "future<T> and stream<T> in exported function results require an `async func` on the WASI Preview 3 generation path"
        ));
    }
    if function
        .result
        .as_ref()
        .map(|result| crate::async_values::top_level_result_error_contains(context, result))
        .transpose()?
        .unwrap_or(false)
    {
        return Err(anyhow!(
            "future<T> and stream<T> in the error arm of an exported function result are not supported"
        ));
    }

    // Build the guest-trait argument list and the arguments forwarded to the JS export. A
    // `future<T>` / `stream<T>` parameter is special-cased: the guest receives a component reader
    // and the JS export is handed a lazily-created `Promise` / async-iterable
    // (`reader_to_js_expr`). All other parameters flow through the normal `WrappedType` pipeline.
    let mut func_arg_list: Vec<TokenStream> = Vec::new();
    let mut param_refs: Vec<TokenStream> = Vec::new();
    for ((param, export_parameter), import_parameter) in function
        .params
        .iter()
        .zip(rust_fn.export_parameters.clone())
        .zip(rust_fn.import_parameters.clone())
    {
        if let Some(async_value) = crate::async_values::detect(context, &param.ty)? {
            let ident = Ident::new(&export_parameter.name, Span::call_site());
            let reader_type = crate::async_values::reader_type(context, &async_value)?;
            func_arg_list.push(quote! { #ident: #reader_type });
            param_refs.push(crate::async_values::reader_to_js_expr(
                context,
                &async_value,
                quote! { #ident },
            )?);
        } else {
            let processed = process_parameter(
                context,
                &param.name,
                &param.ty,
                &export_parameter,
                &import_parameter,
            )?;
            let slice = std::slice::from_ref(&processed);
            func_arg_list.extend(to_original_func_arg_list(slice));
            param_refs.extend(to_wrapped_param_refs(slice));
        }
    }

    let param_refs_tuple = param_refs_as_tuple(&param_refs);

    let js_func_name_str = Lit::Str(LitStr::new(
        &escape_js_ident(name.to_lower_camel_case()),
        func_name.span(),
    ));
    let (js_func_path, wit_package_lit) = match interface {
        Some((iface_name, iface, interface_id)) => {
            let if_name_str = LitStr::new(
                &context.exported_interface_js_name(interface_id, iface_name)?,
                func_name.span(),
            );
            let owner_package_name = match iface.package {
                Some(package_id) => {
                    let package = context.resolve.packages.get(package_id).ok_or_else(|| {
                        anyhow!("Unknown owner package of interface: {iface_name}")
                    })?;
                    package.name.to_string()
                }
                None => context.root_package_name().to_string(),
            };

            (
                quote! { &[#if_name_str, #js_func_name_str] },
                Lit::Str(LitStr::new(&owner_package_name, Span::call_site())),
            )
        }
        None => (
            quote! { &[#js_func_name_str] },
            Lit::Str(LitStr::new(&context.root_package_name(), Span::call_site())),
        ),
    };

    // A `future<T>` / `stream<T>` return type is special-cased: the JS export's raw return value
    // (a `Promise` / async-iterable) is captured without awaiting it, a component future/stream
    // is created, and a background writer task resolves the JS value and writes it into the
    // component reader that is handed back to the host immediately (`js_to_reader_expr`).
    if let Some(async_value) = function
        .result
        .as_ref()
        .map(|typ| crate::async_values::detect(context, typ))
        .transpose()?
        .flatten()
    {
        let reader_type = crate::async_values::reader_type(context, &async_value)?;
        let build_reader =
            crate::async_values::js_to_reader_expr(context, &async_value, quote! { __js_result })?;
        let body = quote! {
                let __js_result = crate::internal::call_js_export_raw(
                    #wit_package_lit,
                    #js_func_path,
                    #param_refs_tuple
                ).await;
                #build_reader
        };
        return if context.target.is_p3() && matches!(function.kind, FunctionKind::Freestanding) {
            Ok(quote! {
                fn #func_name(#(#func_arg_list),*) -> #reader_type {
                    crate::internal::run_sync(async move { #body })
                }
            })
        } else {
            Ok(quote! {
                async fn #func_name(#(#func_arg_list),*) -> #reader_type {
                    #body
                }
            })
        };
    }

    let return_types = get_return_type(context, function, name, &rust_fn)?;

    let original_result = &return_types.wit_level_ret.original_type_ref;
    let wrapped_result = &return_types.wit_level_ret.wrapped_type_ref;
    let unwrap = &return_types.wit_level_ret.unwrap;
    let unwrap_result = unwrap.run(quote! { result });
    let has_exception = return_types.expected_exception.is_some();
    let is_p3 = context.target.is_p3();
    let is_async = matches!(function.kind, FunctionKind::AsyncFreestanding);
    let call = match (is_p3, is_async, has_exception) {
        (true, true, true) => quote! { call_js_export_returning_result },
        (true, true, false) => quote! { call_js_export },
        (true, false, true) => quote! { call_js_export_sync_returning_result },
        (true, false, false) => quote! { call_js_export_sync },
        (false, _, true) => quote! { call_js_export_returning_result },
        (false, _, false) => quote! { call_js_export },
    };
    let body = quote! {
        let result: #wrapped_result = crate::internal::#call(
            #wit_package_lit,
            #js_func_path,
            #param_refs_tuple
        ).await;
        #unwrap_result
    };
    let func_impl = if is_p3 && is_async {
        quote! {
           async fn #func_name(#(#func_arg_list),*) -> #original_result {
               #body
            }
        }
    } else if is_p3 {
        quote! {
           fn #func_name(#(#func_arg_list),*) -> #original_result {
               crate::internal::run_sync(async move { #body })
           }
        }
    } else {
        quote! {
           fn #func_name(#(#func_arg_list),*) -> #original_result {
               crate::internal::async_exported_function(async move {
                   #body
               })
           }
        }
    };
    Ok(func_impl)
}

/// Generates one trait method implementation for an exported freestanding function
fn generate_exported_resource_function_impl(
    context: &GeneratorContext<'_>,
    interface: Option<(&str, &Interface, InterfaceId)>,
    resource_type_id: &TypeId,
    name: &str,
    function: &Function,
) -> anyhow::Result<TokenStream> {
    let func_name = get_function_name(name, function)?;

    let rust_fn = RustWitFunction::new(context, &func_name, function);
    let func_name_ident = rust_fn.function_name_ident();

    if context.target.is_p3()
        && !matches!(
            function.kind,
            FunctionKind::AsyncMethod(_) | FunctionKind::AsyncStatic(_)
        )
        && function
            .result
            .as_ref()
            .map(|result| crate::async_values::contains(context, result))
            .transpose()?
            .unwrap_or(false)
    {
        return Err(anyhow!(
            "future<T> and stream<T> in exported resource function results require an `async func` on the WASI Preview 3 generation path"
        ));
    }
    if function
        .result
        .as_ref()
        .map(|result| crate::async_values::top_level_result_error_contains(context, result))
        .transpose()?
        .unwrap_or(false)
    {
        return Err(anyhow!(
            "future<T> and stream<T> in the error arm of an exported resource function result are not supported"
        ));
    }

    let param_ident_type: Vec<_> = function
        .params
        .iter()
        .zip(rust_fn.export_parameters.clone())
        .zip(rust_fn.import_parameters.clone())
        .map(|((param, export_param), import_param)| {
            let param_name = &param.name;
            let param_type = &param.ty;
            if matches!(
                function.kind,
                FunctionKind::Method(_) | FunctionKind::AsyncMethod(_)
            ) && type_borrows_resource(context, param_type, resource_type_id)?
            {
                Ok(ProcessedParameter {
                    ident: Ident::new(param_name, Span::call_site()),
                    wrapped_type: None,
                    export_parameter: export_param,
                    import_parameter: import_param,
                })
            } else {
                process_parameter(
                    context,
                    param_name,
                    param_type,
                    &export_param,
                    &import_param,
                )
            }
        })
        .collect::<anyhow::Result<Vec<_>>>()?;

    let func_arg_list = to_original_func_arg_list(&param_ident_type);
    let return_types = if matches!(function.kind, FunctionKind::Constructor(_)) {
        ReturnTypeInformation {
            wit_level_ret: WrappedType::no_wrapping(quote! { Self }),
            func_ret: WrappedType::no_wrapping(quote! { Self }),
            expected_exception: None,
        }
    } else {
        get_return_type(context, function, name, &rust_fn)?
    };

    let param_refs = to_wrapped_param_refs(&param_ident_type);

    let resource_name = context
        .resolve
        .types
        .get(*resource_type_id)
        .ok_or_else(|| anyhow::anyhow!("Unknown resource type id"))?
        .name
        .as_ref()
        .ok_or_else(|| anyhow::anyhow!("Resource type has no name"))?;

    let js_resource_name_str = Lit::Str(LitStr::new(
        &resource_name.to_upper_camel_case(),
        Span::call_site(),
    ));
    let (js_resource_path, wit_package_lit) = match interface {
        Some((iface_name, iface, interface_id)) => {
            let if_name_str = LitStr::new(
                &context.exported_interface_js_name(interface_id, iface_name)?,
                Span::call_site(),
            );
            let owner_package_name = match iface.package {
                Some(package_id) => {
                    let package = context.resolve.packages.get(package_id).ok_or_else(|| {
                        anyhow!("Unknown owner package of interface: {iface_name}")
                    })?;
                    package.name.to_string()
                }
                None => context.root_package_name().to_string(),
            };

            (
                quote! { &[#if_name_str, #js_resource_name_str] },
                Lit::Str(LitStr::new(&owner_package_name, Span::call_site())),
            )
        }
        None => (
            quote! { &[#js_resource_name_str] },
            Lit::Str(LitStr::new(&context.root_package_name(), Span::call_site())),
        ),
    };

    let js_func_name_str = Lit::Str(LitStr::new(
        &escape_js_ident(func_name.to_lower_camel_case()),
        Span::call_site(),
    ));
    let js_static_func_path = match interface {
        Some((iface_name, _, interface_id)) => {
            let if_name_str = LitStr::new(
                &context.exported_interface_js_name(interface_id, iface_name)?,
                Span::call_site(),
            );
            quote! { &[#if_name_str, #js_resource_name_str, #js_func_name_str] }
        }
        None => quote! { &[#js_func_name_str] },
    };

    // On the Preview 3 path the generated Guest trait methods mirror the shape wit-bindgen-p3
    // emits: constructors and *synchronous* methods/statics are plain `fn`s (their component-model
    // exports are not `start_task`-wrapped), so they drive the async JS helpers to completion with
    // `crate::internal::run_sync` (a self-contained `block_on`); `async` methods/statics are
    // `async fn`s that `.await` the helpers directly. On the Preview 2 path everything is a
    // synchronous `fn` driven by `async_exported_function`, and `async` resource functions are
    // rejected.
    let is_p3 = context.target.is_p3();

    let func_impl = match &function.kind {
        FunctionKind::Constructor(_) => {
            let param_refs_tuple = param_refs_as_tuple(&param_refs);
            let body = quote! {
                let resource_id = crate::internal::call_js_resource_constructor(
                     #wit_package_lit,
                     #js_resource_path,
                     #param_refs_tuple,
                ).await;
                Self {
                    resource_id
                }
            };
            let driver = if is_p3 {
                quote! { crate::internal::run_sync }
            } else {
                quote! { crate::internal::async_exported_function }
            };
            quote! {
              fn #func_name_ident(#(#func_arg_list),*) -> Self {
                  #driver(async move { #body })
              }
            }
        }
        FunctionKind::Method(_) | FunctionKind::AsyncMethod(_) => {
            let is_async = matches!(function.kind, FunctionKind::AsyncMethod(_));
            if is_async && !is_p3 {
                return Err(anyhow::anyhow!(
                    "Async exported functions are not supported yet"
                ));
            }
            let param_refs = param_refs[1..].to_vec();
            let param_refs_tuple = param_refs_as_tuple(&param_refs);
            let original_result = &return_types.func_ret.original_type_ref;
            let wrapped_result = &return_types.func_ret.wrapped_type_ref;
            let unwrap = &return_types.func_ret.unwrap;
            let unwrap_result = unwrap.run(quote! { result });
            let has_exception = return_types.expected_exception.is_some();
            let call = match (is_p3, is_async, has_exception) {
                // Preview 3, async method: await the async helper directly.
                (true, true, true) => quote! { call_js_resource_method_returning_result },
                (true, true, false) => quote! { call_js_resource_method },
                // Preview 3, sync method: driven by `block_on`, traps on a returned Promise.
                (true, false, true) => quote! { call_js_resource_method_sync_returning_result },
                (true, false, false) => quote! { call_js_resource_method_sync },
                // Preview 2: only synchronous methods, driven by `async_exported_function`.
                (false, _, true) => quote! { call_js_resource_method_returning_result },
                (false, _, false) => quote! { call_js_resource_method },
            };
            let body = quote! {
                let result: #wrapped_result = crate::internal::#call(
                     #wit_package_lit,
                     #js_resource_path,
                     self.resource_id,
                     #js_func_name_str,
                     #param_refs_tuple,
                ).await;
                #unwrap_result
            };
            if is_p3 && is_async {
                quote! {
                   async fn #func_name_ident(#(#func_arg_list),*) -> #original_result {
                       #body
                   }
                }
            } else {
                let driver = if is_p3 {
                    quote! { crate::internal::run_sync }
                } else {
                    quote! { crate::internal::async_exported_function }
                };
                quote! {
                   fn #func_name_ident(#(#func_arg_list),*) -> #original_result {
                       #driver(async move { #body })
                   }
                }
            }
        }
        FunctionKind::Static(_) | FunctionKind::AsyncStatic(_) => {
            let is_async = matches!(function.kind, FunctionKind::AsyncStatic(_));
            if is_async && !is_p3 {
                return Err(anyhow::anyhow!(
                    "Async exported functions are not supported yet"
                ));
            }
            let param_refs_tuple = param_refs_as_tuple(&param_refs);
            let original_result = &return_types.wit_level_ret.original_type_ref;
            let wrapped_result = &return_types.wit_level_ret.wrapped_type_ref;
            let unwrap = &return_types.wit_level_ret.unwrap;
            let unwrap_result = unwrap.run(quote! { result });
            let has_exception = return_types.expected_exception.is_some();
            let call = match (is_p3, is_async, has_exception) {
                // Preview 3, async static: await the async helper directly.
                (true, true, true) => quote! { call_js_export_returning_result },
                (true, true, false) => quote! { call_js_export },
                // Preview 3, sync static: driven by `block_on`, traps on a returned Promise.
                (true, false, true) => quote! { call_js_export_sync_returning_result },
                (true, false, false) => quote! { call_js_export_sync },
                // Preview 2: only synchronous statics, driven by `async_exported_function`.
                (false, _, true) => quote! { call_js_export_returning_result },
                (false, _, false) => quote! { call_js_export },
            };
            let body = quote! {
                let result: #wrapped_result = crate::internal::#call(
                    #wit_package_lit,
                    #js_static_func_path,
                    #param_refs_tuple,
                ).await;
                #unwrap_result
            };
            if is_p3 && is_async {
                quote! {
                   async fn #func_name_ident(#(#func_arg_list),*) -> #original_result {
                       #body
                   }
                }
            } else {
                let driver = if is_p3 {
                    quote! { crate::internal::run_sync }
                } else {
                    quote! { crate::internal::async_exported_function }
                };
                quote! {
                   fn #func_name_ident(#(#func_arg_list),*) -> #original_result {
                       #driver(async move { #body })
                   }
                }
            }
        }
        FunctionKind::Freestanding | FunctionKind::AsyncFreestanding => Err(anyhow::anyhow!(
            "Freestanding functions are not expected in resource methods",
        ))?,
    };

    Ok(func_impl)
}

fn generate_module_defs(js_modules: &[JsModuleSpec]) -> anyhow::Result<TokenStream> {
    if let Some((export_module, additional_modules)) = js_modules.split_first() {
        let export_module_name = LitStr::new(&export_module.name, Span::call_site());

        let any_binary_slot = export_module.mode.is_binary_slot()
            || additional_modules.iter().any(|m| m.mode.is_binary_slot());

        let slot_helper = if any_binary_slot {
            quote! {
                /// Reads JS source from a binary slot marker using volatile reads to prevent
                /// the optimizer from constant-folding the slot contents at compile time.
                /// This is essential because the slot is patched post-compilation.
                ///
                /// The marker layout is: MAGIC(16) + MODULE_INDEX(4) + JS_OFFSET(4) + END_MAGIC(16) = 40 bytes.
                /// JS_OFFSET is a pointer into linear memory where LEN(4) + JS(LEN) is stored.
                /// A JS_OFFSET of 0 means no JS has been injected.
                fn read_js_from_slot_bytes(slot: &[u8]) -> String {
                    const MAGIC: &[u8; 16] = b"WASM_RQJS_SLOT\x01\x00";
                    const END_MAGIC: &[u8; 16] = b"WASM_RQJS_SLTND\x00";
                    assert!(slot.len() >= 40, "JS injection marker is too small");

                    let slot_ptr = slot.as_ptr();
                    unsafe {
                        // Validate magic
                        let mut magic_buf = [0u8; 16];
                        for i in 0..16 {
                            magic_buf[i] = core::ptr::read_volatile(slot_ptr.add(i));
                        }
                        assert_eq!(&magic_buf, MAGIC, "invalid JS injection marker header");

                        // Skip MODULE_INDEX (4 bytes at offset 16), read JS_OFFSET (4 bytes at offset 20)
                        let mut offset_bytes = [0u8; 4];
                        for i in 0..4 {
                            offset_bytes[i] = core::ptr::read_volatile(slot_ptr.add(20 + i));
                        }
                        let js_offset = u32::from_le_bytes(offset_bytes) as usize;

                        assert!(js_offset > 0, "JS injection slot is empty — no JS has been injected. \
                            Use wasm-rquickjs inject-js to inject JavaScript source into the template.");

                        // Validate end magic
                        let mut end_magic_buf = [0u8; 16];
                        for i in 0..16 {
                            end_magic_buf[i] = core::ptr::read_volatile(slot_ptr.add(24 + i));
                        }
                        assert_eq!(&end_magic_buf, END_MAGIC, "JS injection marker footer is corrupted");

                        // Read JS length from linear memory at js_offset
                        let mem_ptr = js_offset as *const u8;
                        let mut len_bytes = [0u8; 4];
                        for i in 0..4 {
                            len_bytes[i] = core::ptr::read_volatile(mem_ptr.add(i));
                        }
                        let len = u32::from_le_bytes(len_bytes) as usize;

                        // Read JS bytes from linear memory at js_offset + 4
                        let js_ptr = mem_ptr.add(4);
                        let mut payload = Vec::with_capacity(len);
                        for i in 0..len {
                            payload.push(core::ptr::read_volatile(js_ptr.add(i)));
                        }
                        String::from_utf8(payload)
                            .expect("injected JS source is not valid UTF-8")
                    }
                }
            }
        } else {
            quote! {}
        };

        let export_module_def = match &export_module.mode {
            EmbeddingMode::BinarySlot => {
                let slot_file_name = LitStr::new(
                    &(export_module.name.replace('/', "_") + ".slot"),
                    Span::call_site(),
                );
                quote! {
                    static JS_EXPORT_MODULE_NAME: &str = #export_module_name;
                    static JS_EXPORT_MODULE_SLOT: &[u8] = include_bytes!(#slot_file_name);

                    fn js_export_module() -> &'static str {
                        static SOURCE: std::sync::LazyLock<String> =
                            std::sync::LazyLock::new(|| read_js_from_slot_bytes(JS_EXPORT_MODULE_SLOT));
                        SOURCE.as_str()
                    }
                }
            }
            _ => {
                let export_module_file_name =
                    LitStr::new(&export_module.file_name(), Span::call_site());
                quote! {
                    static JS_EXPORT_MODULE_NAME: &str = #export_module_name;
                    static JS_EXPORT_MODULE_SOURCE: &str = include_str!(#export_module_file_name);

                    fn js_export_module() -> &'static str {
                        JS_EXPORT_MODULE_SOURCE
                    }
                }
            }
        };

        let mut additional_module_pairs = Vec::new();
        let mut additional_slot_defs = Vec::new();
        for module in additional_modules {
            match &module.mode {
                EmbeddingMode::EmbedFile(_) => {
                    let name = LitStr::new(&module.name, Span::call_site());
                    let file_name = LitStr::new(&module.file_name(), Span::call_site());
                    additional_module_pairs.push(
                        quote! { (#name, Box::new(|| { include_str!(#file_name).to_string() })) },
                    );
                }
                EmbeddingMode::Composition => {
                    let name = LitStr::new(&module.name, Span::call_site());
                    additional_module_pairs.push(
                        quote! { (#name, Box::new(|| { crate::bindings::get_script().to_string() })) },
                    );
                }
                EmbeddingMode::BinarySlot => {
                    let name = LitStr::new(&module.name, Span::call_site());
                    let slot_file_name = LitStr::new(
                        &(module.name.replace('/', "_") + ".slot"),
                        Span::call_site(),
                    );
                    let sanitized = module.name.replace(['/', '-'], "_");
                    let static_name = Ident::new(
                        &format!("JS_SLOT_{}", sanitized.to_uppercase()),
                        Span::call_site(),
                    );
                    let fn_name =
                        Ident::new(&format!("read_js_from_slot_{sanitized}"), Span::call_site());
                    let source_name = Ident::new(
                        &format!("JS_SLOT_SOURCE_{}", sanitized.to_uppercase()),
                        Span::call_site(),
                    );

                    additional_slot_defs.push(quote! {
                        static #static_name: &[u8] = include_bytes!(#slot_file_name);

                        fn #fn_name() -> String {
                            read_js_from_slot_bytes(#static_name)
                        }
                    });

                    additional_module_pairs.push(quote! {
                        (#name, Box::new(|| {
                            static #source_name: std::sync::LazyLock<String> =
                                std::sync::LazyLock::new(#fn_name);
                            #source_name.clone()
                        }))
                    });
                }
            }
        }

        Ok(quote! {
            #slot_helper

            #export_module_def

            #(#additional_slot_defs)*

            static JS_ADDITIONAL_MODULES: std::sync::LazyLock<Vec<(&str, Box<dyn (Fn() -> String) + Send + Sync>)>> =
              std::sync::LazyLock::new(|| { vec![
                 #(#additional_module_pairs),*
              ]});
        })
    } else {
        Err(anyhow!("No JS modules provided."))?
    }
}

/// Generates the `with: { ... }` entries for `wit_bindgen::generate!` to remap
/// standard WASI interfaces to the `wasip2` crate, avoiding duplicate bindings.
///
/// Only interfaces that are actually used by the resolved world are included,
/// because unused `with:` entries cause compilation errors.
fn generate_wasi_remaps(context: &GeneratorContext<'_>) -> TokenStream {
    // Preview 3 remaps: only the clock interfaces are remapped to the `wasip3` crate for now
    // (Phase 1). Any other WASI interface present in the world keeps the bindings generated by
    // `wit_bindgen::generate!`. The actual `with:` entries use the fully-versioned names from the
    // resolved world, so the exact `@0.3.0-rc-...` snapshot is picked up automatically.
    // The WASI Preview 3 `clocks` package (`wasi:clocks@0.3.x`) exposes `types`,
    // `monotonic-clock` and `system-clock` (there is no `wall-clock`; that was the Preview 2
    // name). Each maps to the corresponding `wasip3::clocks::*` module. Only interfaces that
    // are actually used by the world get a `with:` entry, so listing all of them is safe.
    static WASI_REMAPS_P3: &[(&str, &str)] = &[
        ("wasi:clocks/types", "wasip3::clocks::types"),
        (
            "wasi:clocks/monotonic-clock",
            "wasip3::clocks::monotonic_clock",
        ),
        ("wasi:clocks/system-clock", "wasip3::clocks::system_clock"),
    ];

    // Static mapping from unversioned WIT interface names to wasip2 Rust module paths.
    // The actual `with:` entries use the fully-versioned names from the resolved world.
    static WASI_REMAPS: &[(&str, &str)] = &[
        ("wasi:cli/environment", "wasip2::cli::environment"),
        ("wasi:cli/exit", "wasip2::cli::exit"),
        ("wasi:cli/stderr", "wasip2::cli::stderr"),
        ("wasi:cli/stdin", "wasip2::cli::stdin"),
        ("wasi:cli/stdout", "wasip2::cli::stdout"),
        ("wasi:cli/terminal-input", "wasip2::cli::terminal_input"),
        ("wasi:cli/terminal-output", "wasip2::cli::terminal_output"),
        ("wasi:cli/terminal-stderr", "wasip2::cli::terminal_stderr"),
        ("wasi:cli/terminal-stdin", "wasip2::cli::terminal_stdin"),
        ("wasi:cli/terminal-stdout", "wasip2::cli::terminal_stdout"),
        (
            "wasi:clocks/monotonic-clock",
            "wasip2::clocks::monotonic_clock",
        ),
        ("wasi:clocks/wall-clock", "wasip2::clocks::wall_clock"),
        ("wasi:filesystem/preopens", "wasip2::filesystem::preopens"),
        ("wasi:filesystem/types", "wasip2::filesystem::types"),
        (
            "wasi:http/outgoing-handler",
            "wasip2::http::outgoing_handler",
        ),
        ("wasi:http/types", "wasip2::http::types"),
        ("wasi:io/error", "wasip2::io::error"),
        ("wasi:io/poll", "wasip2::io::poll"),
        ("wasi:io/streams", "wasip2::io::streams"),
        ("wasi:random/insecure", "wasip2::random::insecure"),
        ("wasi:random/insecure-seed", "wasip2::random::insecure_seed"),
        ("wasi:random/random", "wasip2::random::random"),
        (
            "wasi:sockets/instance-network",
            "wasip2::sockets::instance_network",
        ),
        (
            "wasi:sockets/ip-name-lookup",
            "wasip2::sockets::ip_name_lookup",
        ),
        ("wasi:sockets/network", "wasip2::sockets::network"),
        ("wasi:sockets/tcp", "wasip2::sockets::tcp"),
        (
            "wasi:sockets/tcp-create-socket",
            "wasip2::sockets::tcp_create_socket",
        ),
        ("wasi:sockets/udp", "wasip2::sockets::udp"),
        (
            "wasi:sockets/udp-create-socket",
            "wasip2::sockets::udp_create_socket",
        ),
    ];

    // Collect all interfaces used in the world, with their fully-qualified versioned names
    let world = &context.resolve.worlds[context.world];
    let mut used_interfaces = std::collections::BTreeMap::<String, String>::new();

    for (key, _) in world.imports.iter().chain(world.exports.iter()) {
        if let WorldKey::Interface(id) = key {
            let interface = &context.resolve.interfaces[*id];
            if let Some(ref name) = interface.name
                && let Some(package_id) = interface.package
            {
                // Only packages accepted by `is_wasi_remapped_package` may get a `with:`
                // entry; the check is version-aware, so e.g. `wasi:clocks/...@0.2.3` in a
                // Preview 3 world is not remapped to the (API-incompatible) `wasip3` crate
                // and keeps its generated bindings instead.
                if !context.is_wasi_remapped_package(package_id) {
                    continue;
                }
                let package = &context.resolve.packages[package_id];
                let unversioned =
                    format!("{}:{}/{}", package.name.namespace, package.name.name, name);
                let versioned = package.name.interface_id(name);
                used_interfaces.insert(unversioned, versioned);
            }
        }
    }

    let remaps: &[(&str, &str)] = if context.target.is_p3() {
        WASI_REMAPS_P3
    } else {
        WASI_REMAPS
    };

    // Build with: entries only for WASI interfaces that are actually used,
    // using the fully-versioned WIT name as the key
    let mut entries = Vec::new();
    for (wit_name, rust_path) in remaps {
        if let Some(versioned_name) = used_interfaces.get(*wit_name) {
            let wit_lit = LitStr::new(versioned_name, Span::call_site());
            let rust_path: syn::Path = syn::parse_str(rust_path)
                .unwrap_or_else(|_| panic!("Invalid Rust path: {rust_path}"));
            entries.push(quote! { #wit_lit: #rust_path });
        }
    }

    if entries.is_empty() {
        quote! {}
    } else {
        quote! {
            with: {
                #(#entries),*
            },
        }
    }
}