alef 0.58.3

Opinionated polyglot binding generator for Rust libraries
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
//! WASM (wasm-bindgen) backend: orchestration and `Backend` trait implementation.

mod cfg;
pub mod enums;
pub mod errors;
pub mod functions;
pub mod methods;
pub mod service_api;
pub mod types;

mod cargo;

use crate::backends::wasm::type_map::WasmMapper;
use crate::codegen::builder::RustFileBuilder;
use crate::codegen::{generators, shared};
use crate::core::backend::{Backend, BuildConfig, BuildDependency, Capabilities, GeneratedFile};
use crate::core::config::{Language, ResolvedCrateConfig, resolve_output_dir};
use crate::core::ir::{ApiSurface, ReceiverKind, TypeRef};
use ahash::{AHashMap, AHashSet};
use regex::Regex;
use std::path::PathBuf;

use cargo::gen_cargo_toml;
use cfg::{
    cfg_condition_enabled, collect_cfg_features, field_references_excluded_type, first_unknown_named_type,
    is_gated_behind_disabled_feature,
};
use enums::gen_enum;
use errors::{gen_error_converter, gen_error_methods};
use functions::{gen_env_shims, gen_function_with_emitted_dtos};
use types::{
    filter_cfg_fields_for_features, gen_opaque_struct, gen_opaque_struct_methods, gen_struct, gen_struct_methods,
};

/// Prepend `#[cfg(<pred>)]` to a code item when the source symbol carries a cfg predicate.
fn prepend_cfg(cfg: Option<&str>, item: String) -> String {
    match cfg {
        Some(pred) if !pred.is_empty() => format!("#[cfg({pred})]\n{item}"),
        _ => item,
    }
}

/// Prepend a visible marker comment listing fields dropped from `item` because they reference a
/// type with no generated wasm binding (see `first_unknown_named_type` in `cfg.rs`).
///
/// The comment is emitted directly above the struct so the omission is discoverable by reading
/// the generated source, not just by grepping build logs for the accompanying `tracing::warn!`
/// (nothing may be silently omitted from a binding).
fn prepend_unknown_type_omission_marker(omissions: Option<&Vec<(String, String)>>, item: String) -> String {
    let Some(omissions) = omissions else {
        return item;
    };
    let mut marker = String::from(
        "// ALEF-OMITTED: the field(s) below were dropped from this WASM binding\n\
         // because their Rust type has no generated wasm-bindgen representation.\n",
    );
    for (field_name, type_name) in omissions {
        marker.push_str(&format!(
            "//   - field `{field_name}`: type `{type_name}` is not part of the bound wasm API surface\n"
        ));
    }
    format!("{marker}{item}")
}

/// Types for which `methods::gen_method` emits a self-delegating
/// `{core_import}::{type_name}::from(self.clone()).{method}(..)` call for at least one method.
///
/// That delegation form is a hard requirement on `impl From<Wasm{Type}> for {core}::{Type}`
/// existing (see `methods.rs`). The reverse (`binding -> core`) conversion is otherwise only
/// emitted for types in `input_type_names(api)` — types reachable as a function/method
/// parameter, directly or transitively through struct fields. A struct that is only ever
/// *returned* (never taken as a parameter, directly or transitively) but that also has an
/// auto-delegated instance method — e.g. `PageRange::page_count(&self)` — falls through that
/// gap: `input_type_names` has no reason to include it, yet `gen_method` still needs the
/// reverse impl to compile the delegation. Mirrors the exact branching `gen_method` uses to
/// decide between self-delegation and the opaque mutex-lock path, so the two stay in sync.
fn types_needing_self_delegation_reverse_impl(api: &ApiSurface, opaque_types: &AHashSet<String>) -> AHashSet<String> {
    let mut needed = AHashSet::default();
    for typ in api.types.iter().filter(|t| !t.is_trait) {
        let has_mut_methods = typ
            .methods
            .iter()
            .any(|m| matches!(m.receiver.as_ref(), Some(ReceiverKind::RefMut)));
        let is_opaque_type = opaque_types.contains(&typ.name);

        for method in &typ.methods {
            if method.is_static {
                continue;
            }
            let is_ref_mut_receiver = matches!(method.receiver.as_ref(), Some(ReceiverKind::RefMut));
            // Mirrors gen_method: this path calls `self.inner.lock().unwrap().{method}(..)`
            // directly on the core value held by the opaque wrapper — no `From` impl needed.
            if is_opaque_type && has_mut_methods && !is_ref_mut_receiver {
                continue;
            }

            let delegates_via_self_conversion = if method.is_async {
                // gen_method's async branch always builds `core_call` via self-delegation
                // (or the mutex path excluded above), regardless of `can_delegate`.
                true
            } else if is_ref_mut_receiver && has_mut_methods {
                !method.sanitized
                    && method
                        .params
                        .iter()
                        .all(|p| !p.sanitized && shared::is_delegatable_param(&p.ty, opaque_types))
                    && shared::is_opaque_delegatable_type(&method.return_type)
            } else {
                shared::can_auto_delegate(method, opaque_types)
            };

            if delegates_via_self_conversion {
                needed.insert(typ.name.clone());
                break;
            }
        }
    }
    needed
}

/// Fix up `<field>: Default::default().map(Box::new),` lines left behind by the shared
/// binding->core `From` conversion generator (`crate::codegen::conversions`, shared with every
/// other backend) when a field's type is a payload-carrying enum (a `#[serde(tag = "type")]`
/// enum with struct variants).
///
/// wasm_bindgen only supports fieldless, C-style enums, so `gen_struct` (this backend, see
/// `types.rs`) drops any field referencing such an enum from the generated Wasm struct entirely.
/// The shared conversion generator does not know the field was dropped: it still emits a value
/// for it and falls back to `Default::default()`. For an `Option<Box<T>>` field the generic
/// Option<Box<_>> wrapper then unconditionally appends `.map(Box::new)`, producing
/// `Default::default().map(Box::new)` -- a value that is always `None` (`Option::default()` is
/// `None` for every `T`, and `None.map(Box::new)` is `None`), but whose type `T` rustc cannot
/// infer (E0282), since nothing in the expression pins it down.
///
/// Replacing the whole expression with the equivalent literal `None` is behavior-preserving and
/// compiles; the comment documents *why* the field is always `None` on wasm for anyone reading
/// the generated binding.
fn fix_dropped_payload_enum_option_fields(content: String) -> String {
    let Ok(dropped_boxed_option_field) =
        Regex::new(r"(?m)^(?P<indent>[ \t]*)(?P<field>\w+): Default::default\(\)\.map\(Box::new\),$")
    else {
        return content;
    };
    dropped_boxed_option_field
        .replace_all(&content, |caps: &regex::Captures<'_>| {
            format!(
                "{indent}// ALEF-OMITTED: `{field}` is always None on wasm -- its Rust type is a \
                 payload-carrying enum, which wasm_bindgen cannot represent.\n\
                 {indent}{field}: None,",
                indent = &caps["indent"],
                field = &caps["field"],
            )
        })
        .into_owned()
}

pub struct WasmBackend;

impl Backend for WasmBackend {
    fn name(&self) -> &str {
        "wasm"
    }

    fn language(&self) -> Language {
        Language::Wasm
    }

    fn capabilities(&self) -> Capabilities {
        Capabilities {
            supports_async: true,
            supports_classes: true,
            supports_enums: true,
            supports_option: true,
            supports_result: true,
            ..Capabilities::default()
        }
    }

    fn generate_bindings(&self, api: &ApiSurface, config: &ResolvedCrateConfig) -> anyhow::Result<Vec<GeneratedFile>> {
        // wrapper delegates to the core crate (which resolves the cfg) and emits no `#[cfg]` gate,
        // so two same-named entries would otherwise produce duplicate `#[wasm_bindgen]` fns.
        let deduped_api = api.with_deduped_functions();
        let api = &deduped_api;

        let wasm_config = config.wasm.as_ref();
        let mut exclude_functions = wasm_config.map(|c| c.exclude_functions.clone()).unwrap_or_default();
        let mut exclude_types = wasm_config.map(|c| c.exclude_types.clone()).unwrap_or_default();
        // Simple newtype opaques (no generics in the path) DO wrap as `#[wasm_bindgen]` classes
        exclude_types.extend(
            config
                .opaque_types
                .iter()
                .filter(|(_, path)| path.contains('<'))
                .map(|(name, _)| name.clone()),
        );
        let text_field_enum_names: AHashSet<String> = config.untagged_union_text_types.iter().cloned().collect();
        let mut type_overrides = wasm_config.map(|c| c.type_overrides.clone()).unwrap_or_default();
        for name in &text_field_enum_names {
            type_overrides
                .entry(name.clone())
                .or_insert_with(|| "String".to_string());
        }
        let env_shims = wasm_config.map(|c| c.env_shims.clone()).unwrap_or_default();
        let prefix = config.wasm_type_prefix();

        let enabled_features = config.features_for_language(Language::Wasm).to_vec();
        for typ in &api.types {
            if is_gated_behind_disabled_feature(&typ.cfg, &enabled_features) {
                exclude_types.push(typ.name.clone());
            }
        }
        for enum_def in &api.enums {
            if is_gated_behind_disabled_feature(&enum_def.cfg, &enabled_features) {
                exclude_types.push(enum_def.name.clone());
            }
        }
        for func in &api.functions {
            if is_gated_behind_disabled_feature(&func.cfg, &enabled_features) {
                exclude_functions.push(func.name.clone());
            }
        }

        // Captured before the move: `known_type_names` below needs the override keys, and
        // `WasmMapper::new` takes the map by value.
        let override_type_names: Vec<String> = type_overrides.keys().cloned().collect();
        let mapper = WasmMapper::new(type_overrides, prefix.clone());
        let core_import = config.core_import_for_language(Language::Wasm);

        let source_remap_pairs: Vec<(String, String)> = wasm_config
            .map(|c| c.source_crate_remaps.clone())
            .unwrap_or_default()
            .into_iter()
            .map(|orig| (orig.replace('-', "_"), core_import.clone()))
            .collect();
        let source_remaps_borrowed: Vec<(&str, &str)> = source_remap_pairs
            .iter()
            .map(|(o, n)| (o.as_str(), n.as_str()))
            .collect();
        let dropped_crates: AHashSet<String> = wasm_config
            .map(|c| c.exclude_extra_dependencies.clone())
            .unwrap_or_default()
            .into_iter()
            .map(|name| name.replace('-', "_"))
            .filter(|underscored| {
                underscored != &core_import && !source_remap_pairs.iter().any(|(orig, _)| orig == underscored)
            })
            .collect();
        for typ in &api.types {
            let crate_seg = typ.rust_path.split("::").next().unwrap_or("").replace('-', "_");
            if dropped_crates.contains(&crate_seg) && !exclude_types.contains(&typ.name) {
                exclude_types.push(typ.name.clone());
            }
        }
        for enum_def in &api.enums {
            let crate_seg = enum_def.rust_path.split("::").next().unwrap_or("").replace('-', "_");
            if dropped_crates.contains(&crate_seg) && !exclude_types.contains(&enum_def.name) {
                exclude_types.push(enum_def.name.clone());
            }
        }
        for func in &api.functions {
            let crate_seg = func.rust_path.split("::").next().unwrap_or("").replace('-', "_");
            if dropped_crates.contains(&crate_seg) && !exclude_functions.contains(&func.name) {
                exclude_functions.push(func.name.clone());
            }
        }
        let dropped_error_names: Vec<String> = api
            .errors
            .iter()
            .filter(|e| {
                let crate_seg = e.rust_path.split("::").next().unwrap_or("").replace('-', "_");
                dropped_crates.contains(&crate_seg)
            })
            .map(|e| e.name.clone())
            .collect();
        for name in dropped_error_names {
            if !exclude_types.contains(&name) {
                exclude_types.push(name);
            }
        }

        // is treated as if it were `#[cfg]`-gated, so the binding struct omits it and
        let exclude_fields_map = wasm_config.map(|c| c.exclude_fields.clone()).unwrap_or_default();
        let api_owned;
        let api: &ApiSurface = if exclude_fields_map.is_empty() {
            api
        } else {
            api_owned = {
                let mut cloned = api.clone();
                for typ in &mut cloned.types {
                    if let Some(skip_list) = exclude_fields_map.get(&typ.name) {
                        let before = typ.fields.len();
                        typ.fields.retain(|field| !skip_list.iter().any(|s| s == &field.name));
                        if typ.fields.len() != before {
                            typ.has_stripped_cfg_fields = true;
                        }
                    }
                }
                cloned
            };
            &api_owned
        };
        let cfg_filtered_api = filter_cfg_fields_for_features(api, &enabled_features);
        let api = &cfg_filtered_api;

        // Detect fields that reference a type with no generated wasm binding: neither a
        // `TypeDef`/`EnumDef` present in the (already cfg-filtered) API surface nor an explicit
        // `type_overrides` entry. `WasmMapper::named` (see `type_map.rs`) maps every
        // `TypeRef::Named` unconditionally to `"{prefix}{name}"` with no existence check, so
        // left alone this would silently emit a reference to a `Wasm*` struct that is never
        // generated — a dangling-type compile failure the consumer only discovers by running
        // `wasm-pack build`, not by reading the generated source. Route such fields through the
        // same exclusion machinery as cfg-gated fields, but warn loudly and mark the omission in
        // the generated source instead of dropping it in silence.
        let mut known_type_names: AHashSet<String> = api.types.iter().map(|t| t.name.clone()).collect();
        known_type_names.extend(api.enums.iter().map(|e| e.name.clone()));
        known_type_names.extend(override_type_names.iter().cloned());
        let mut unknown_type_omissions: AHashMap<String, Vec<(String, String)>> = AHashMap::default();
        for typ in api.types.iter().filter(|t| !t.is_opaque && !t.is_trait) {
            if exclude_types.contains(&typ.name) {
                continue;
            }
            for field in shared::binding_fields(&typ.fields) {
                if field_references_excluded_type(&field.ty, &exclude_types) {
                    continue;
                }
                let Some(unknown_name) = first_unknown_named_type(&field.ty, &known_type_names) else {
                    continue;
                };
                let unknown_name = unknown_name.to_string();
                tracing::warn!(
                    struct_name = %typ.name,
                    field_name = %field.name,
                    referenced_type = %unknown_name,
                    "wasm backend: field references a type with no generated wasm binding; omitting field"
                );
                if !exclude_types.contains(&unknown_name) {
                    exclude_types.push(unknown_name.clone());
                }
                unknown_type_omissions
                    .entry(typ.name.clone())
                    .or_default()
                    .push((field.name.clone(), unknown_name));
            }
        }

        let mut builder = RustFileBuilder::new().with_generated_header();
        builder.add_inner_attribute(
            "allow(dead_code, unused_imports, unused_variables, unreachable_patterns, missing_docs)",
        );
        builder.add_inner_attribute("allow(clippy::too_many_arguments, clippy::let_unit_value, clippy::needless_borrow, clippy::map_identity, clippy::just_underscores_and_digits, clippy::unused_unit, clippy::unnecessary_cast, clippy::unwrap_or_default, clippy::derivable_impls, clippy::redundant_field_names, clippy::needless_borrows_for_generic_args, clippy::unnecessary_fallible_conversions, clippy::useless_conversion, clippy::arc_with_non_send_sync, clippy::collapsible_if, clippy::clone_on_copy, clippy::should_implement_trait, clippy::await_holding_refcell_ref, clippy::new_without_default)");
        if let Some(extra_attr) = crate::codegen::shared::format_extra_clippy_allows(
            &config.extra_clippy_allows,
            builder.inner_attributes_text(),
        ) {
            builder.add_inner_attribute(&extra_attr);
        }
        for attribute in crate::codegen::shared::format_crate_attributes(&config.crate_attributes) {
            builder.add_inner_attribute(&attribute);
        }
        builder.add_import("wasm_bindgen::prelude::*");

        if let Some(modules) = wasm_config.map(|c| c.custom_rust_modules.as_slice()) {
            for module in modules {
                builder.add_item(&format!("pub mod {module};"));
                builder.add_item(&format!("pub use {module}::*;"));
            }
        }

        // so no explicit `use js_sys;` import is needed (clippy::single_component_path_imports).

        for trait_path in generators::collect_trait_imports(api) {
            builder.add_import(&trait_path);
        }

        if !env_shims.is_empty() {
            builder.add_item(&gen_env_shims(&env_shims));
        }

        let opaque_types: AHashSet<String> = api
            .types
            .iter()
            .filter(|t| t.is_opaque && !exclude_types.contains(&t.name))
            .map(|t| t.name.clone())
            .collect();
        let mutex_types: AHashSet<String> = api
            .types
            .iter()
            .filter(|t| t.is_opaque && !exclude_types.contains(&t.name) && generators::type_needs_mutex(t))
            .map(|t| t.name.clone())
            .collect();
        if !opaque_types.is_empty() {
            builder.add_import("std::sync::Arc");
            if !mutex_types.is_empty() {
                builder.add_import("std::sync::Mutex");
            }
        }

        let bridge_type_aliases: AHashSet<String> = config
            .trait_bridges
            .iter()
            .filter_map(|b| b.type_alias.clone())
            .collect();
        let mut opaque_names_vec: Vec<String> = opaque_types.iter().cloned().collect();
        opaque_names_vec.extend(bridge_type_aliases.iter().cloned());
        let opaque_names_set: AHashSet<String> = opaque_names_vec.iter().cloned().collect();

        let adapter_bodies = crate::adapters::build_adapter_bodies(config, Language::Wasm)?;

        let streaming_item_types: ahash::AHashMap<String, String> = config
            .adapters
            .iter()
            .filter(|a| matches!(a.pattern, crate::core::config::AdapterPattern::Streaming))
            .filter(|a| !a.skip_languages.iter().any(|l| l == "wasm"))
            .filter_map(|a| {
                let owner = a.owner_type.as_deref()?;
                let item = a.item_type.as_deref()?;
                Some((format!("{owner}.{}", a.name), item.to_string()))
            })
            .collect();

        let wasm_skipped_methods: AHashSet<String> = config
            .adapters
            .iter()
            .filter(|a| matches!(a.pattern, crate::core::config::AdapterPattern::Streaming))
            .filter(|a| a.skip_languages.iter().any(|l| l == "wasm"))
            .filter_map(|a| {
                let owner = a.owner_type.as_deref()?;
                Some(format!("{owner}.{}", a.name))
            })
            .collect();

        for adapter in &config.adapters {
            match adapter.pattern {
                crate::core::config::AdapterPattern::Streaming => {
                    let key = crate::adapters::stream_struct_key(adapter);
                    if let Some(struct_code) = adapter_bodies.get(&key) {
                        builder.add_item(struct_code);
                    }
                }
                crate::core::config::AdapterPattern::CallbackBridge => {
                    let struct_key = format!("{}.__bridge_struct__", adapter.name);
                    let impl_key = format!("{}.__bridge_impl__", adapter.name);
                    if let Some(struct_code) = adapter_bodies.get(&struct_key) {
                        builder.add_item(struct_code);
                    }
                    if let Some(impl_code) = adapter_bodies.get(&impl_key) {
                        builder.add_item(impl_code);
                    }
                }
                _ => {}
            }
        }

        // `#[wasm_bindgen]` entrypoints (e.g. `app_run`) are compiled and exported.
        let has_wasm_services = api.services.iter().any(|svc| {
            !config
                .services
                .iter()
                .any(|sc| sc.owner_type == svc.name && sc.skip_languages.iter().any(|l| l == "wasm"))
        });
        if has_wasm_services {
            builder.add_item("pub mod service;");
        }

        let tagged_data_enum_names: AHashSet<String> = api
            .enums
            .iter()
            .filter(|e| !exclude_types.contains(&e.name) && enums::is_tagged_data_enum(e))
            .map(|e| e.name.clone())
            .collect();

        let methods_enums: Vec<_> = api
            .enums
            .iter()
            .filter(|e| !text_field_enum_names.contains(&e.name))
            .cloned()
            .collect();

        let core_to_binding_convertible_for_structs =
            crate::codegen::conversions::core_to_binding_convertible_types(api, &exclude_types);

        for typ in api.types.iter().filter(|typ| !typ.is_trait) {
            if exclude_types.contains(&typ.name) {
                continue;
            }
            if typ.is_opaque {
                builder.add_item(&gen_opaque_struct(typ, &core_import, &prefix));
                builder.add_item(&gen_opaque_struct_methods(
                    typ,
                    &mapper,
                    &opaque_types,
                    &core_import,
                    &prefix,
                    &adapter_bodies,
                    &mutex_types,
                    &streaming_item_types,
                    &wasm_skipped_methods,
                    &config.trait_bridges,
                ));
                // Client constructor — emit a #[wasm_bindgen(constructor)] impl
                if let Some(ctor) = config.client_constructors.get(&typ.name) {
                    let struct_name = format!("{prefix}{}", typ.name);
                    let ctor_body = generators::gen_opaque_constructor(
                        ctor,
                        &typ.name,
                        &core_import,
                        "#[wasm_bindgen(constructor)]",
                    );
                    let ctor_impl = format!("#[wasm_bindgen]\nimpl {struct_name} {{\n{}}}", ctor_body);
                    builder.add_item(&ctor_impl);
                }
            } else {
                // A type that dropped a field is NOT core-to-binding convertible: the
                // delegating `Default` impl is `<core::T as Default>::default().into()`, which
                // needs a `From<core::T>` that can carry every field across. The omitted field has
                // no binding representation to carry it into, so the conversion cannot exist and
                // the struct must fall back to `#[derive(Default)]` on the fields that remain.
                let is_core_to_binding_convertible = core_to_binding_convertible_for_structs.contains(&typ.name)
                    && !unknown_type_omissions.contains_key(&typ.name);
                // gen_struct gates #[derive(Default)] and the delegating Default impl on
                let struct_code = gen_struct(
                    typ,
                    &mapper,
                    &exclude_types,
                    &core_import,
                    &prefix,
                    &tagged_data_enum_names,
                    &source_remaps_borrowed,
                    is_core_to_binding_convertible,
                );
                builder.add_item(&prepend_unknown_type_omission_marker(
                    unknown_type_omissions.get(&typ.name),
                    struct_code,
                ));
                builder.add_item(&gen_struct_methods(
                    typ,
                    &mapper,
                    &exclude_types,
                    &core_import,
                    &opaque_types,
                    &methods_enums,
                    &prefix,
                    &mutex_types,
                    &streaming_item_types,
                ));
            }
        }

        for enum_def in &api.enums {
            if !exclude_types.contains(&enum_def.name) {
                builder.add_item(&gen_enum(enum_def, &prefix));
            }
        }

        let mut emitted_input_dtos = AHashSet::new();
        let mut input_dto_code = String::new();

        for func in &api.functions {
            if !exclude_functions.contains(&func.name)
                && !crate::codegen::generators::trait_bridge::is_trait_bridge_managed_fn(
                    &func.name,
                    &config.trait_bridges,
                )
            {
                let refs_excluded = func
                    .params
                    .iter()
                    .any(|p| field_references_excluded_type(&p.ty, &exclude_types))
                    || field_references_excluded_type(&func.return_type, &exclude_types);
                if !refs_excluded {
                    for p in &func.params {
                        if let TypeRef::Named(name) = &p.ty
                            && !opaque_types.contains(name.as_str())
                            && !emitted_input_dtos.contains(name.as_str())
                            && let Some(type_def) = api.types.iter().find(|t| t.name == name.as_str())
                            && functions::should_have_input_dto(type_def)
                        {
                            let non_deserializable_type_names: std::collections::HashSet<String> = api
                                .types
                                .iter()
                                .filter(|t| !t.has_serde || t.is_trait || t.is_opaque)
                                .map(|t| t.name.clone())
                                .collect();
                            let (dto_code, _dto_name) = functions::gen_input_dto_for_type_with_cfg(
                                name.as_str(),
                                &core_import,
                                type_def,
                                &exclude_types,
                                &enabled_features,
                                &non_deserializable_type_names,
                            );
                            if !dto_code.is_empty() {
                                input_dto_code.push_str(&dto_code);
                                input_dto_code.push_str("\n\n");
                                emitted_input_dtos.insert(name.clone());
                            }
                        }
                    }
                }
            }
        }
        if !input_dto_code.is_empty() {
            builder.add_item(&input_dto_code);
        }

        for func in &api.functions {
            if !exclude_functions.contains(&func.name) {
                if crate::codegen::generators::trait_bridge::is_trait_bridge_managed_fn(
                    &func.name,
                    &config.trait_bridges,
                ) {
                    continue;
                }
                let refs_excluded = func
                    .params
                    .iter()
                    .any(|p| field_references_excluded_type(&p.ty, &exclude_types))
                    || field_references_excluded_type(&func.return_type, &exclude_types);
                if refs_excluded {
                    continue;
                }
                let bridge_param = crate::backends::wasm::trait_bridge::find_bridge_param(func, &config.trait_bridges);
                let options_field_bridge =
                    crate::backends::wasm::trait_bridge::find_options_field_binding(func, &config.trait_bridges)
                        .filter(|(_, bridge_cfg)| {
                            let Some(field_name) = bridge_cfg.resolved_options_field() else {
                                return false;
                            };
                            let Some(options_type) = bridge_cfg.options_type.as_deref() else {
                                return false;
                            };
                            api.types
                                .iter()
                                .filter(|t| t.name == options_type)
                                .flat_map(|t| t.fields.iter())
                                .any(|f| f.cfg.is_none() && f.name == field_name)
                        });
                if let Some((param_idx, bridge_cfg)) = bridge_param {
                    let item = crate::backends::wasm::trait_bridge::gen_bridge_function(
                        api,
                        func,
                        param_idx,
                        bridge_cfg,
                        &mapper,
                        &opaque_types,
                        &core_import,
                        &prefix,
                    );
                    let item = prepend_cfg(func.cfg.as_deref(), item);
                    builder.add_item(&item);
                } else if let Some((param_idx, bridge_cfg)) = options_field_bridge {
                    let item = crate::backends::wasm::trait_bridge::gen_options_field_bridge_function(
                        api,
                        func,
                        param_idx,
                        bridge_cfg,
                        &mapper,
                        &opaque_types,
                        &core_import,
                        &prefix,
                    );
                    let item = prepend_cfg(func.cfg.as_deref(), item);
                    builder.add_item(&item);
                } else {
                    let item = gen_function_with_emitted_dtos(
                        func,
                        &mapper,
                        &core_import,
                        &opaque_types,
                        &prefix,
                        &mutex_types,
                        api,
                        &emitted_input_dtos,
                    );
                    let item = prepend_cfg(func.cfg.as_deref(), item);
                    builder.add_item(&item);
                }
            }
        }

        for bridge_cfg in &config.trait_bridges {
            if let Some(trait_type) = api.types.iter().find(|t| t.is_trait && t.name == bridge_cfg.trait_name) {
                let bridge = crate::backends::wasm::trait_bridge::gen_trait_bridge(
                    trait_type,
                    bridge_cfg,
                    &core_import,
                    &config.error_type_name(),
                    &config.error_constructor_expr(),
                    api,
                )?;
                for imp in &bridge.imports {
                    builder.add_import(imp);
                }
                builder.add_item(&bridge.code);
            }
        }

        let trait_bridge_arc_wrapper_field_names: Vec<String> = config
            .trait_bridges
            .iter()
            .filter(|b| b.bind_via == crate::core::config::BridgeBinding::OptionsField)
            .filter_map(|b| b.resolved_options_field().map(String::from))
            .collect();
        let wasm_conv_config = crate::codegen::conversions::ConversionConfig {
            type_name_prefix: &prefix,
            map_uses_jsvalue: true,
            option_duration_on_defaults: true,
            optionalize_defaults: false,
            exclude_types: &exclude_types,
            source_crate_remaps: &source_remaps_borrowed,
            opaque_types: if opaque_names_set.is_empty() {
                None
            } else {
                Some(&opaque_names_set)
            },
            trait_bridge_arc_wrapper_field_names: &trait_bridge_arc_wrapper_field_names,
            tagged_data_enum_names: if tagged_data_enum_names.is_empty() {
                None
            } else {
                Some(&tagged_data_enum_names)
            },
            text_field_enum_names: if text_field_enum_names.is_empty() {
                None
            } else {
                Some(&text_field_enum_names)
            },
            ..Default::default()
        };
        let convertible = crate::codegen::conversions::convertible_types(api);
        let core_to_binding_convertible =
            crate::codegen::conversions::core_to_binding_convertible_types(api, &exclude_types);
        let input_types = crate::codegen::conversions::input_type_names(api);
        let self_delegating_types = types_needing_self_delegation_reverse_impl(api, &opaque_types);
        for typ in api.types.iter().filter(|typ| !typ.is_trait) {
            if exclude_types.contains(&typ.name) {
                continue;
            }
            let is_strict = crate::codegen::conversions::can_generate_conversion(typ, &convertible);
            let is_relaxed = crate::codegen::conversions::can_generate_conversion(typ, &core_to_binding_convertible);
            if is_strict {
                if input_types.contains(&typ.name) || self_delegating_types.contains(&typ.name) {
                    builder.add_item(&crate::codegen::conversions::gen_from_binding_to_core_cfg(
                        typ,
                        &core_import,
                        &wasm_conv_config,
                    ));
                }
                builder.add_item(&crate::codegen::conversions::gen_from_core_to_binding_cfg(
                    typ,
                    &core_import,
                    &opaque_types,
                    &wasm_conv_config,
                ));
            } else if is_relaxed {
                builder.add_item(&crate::codegen::conversions::gen_from_core_to_binding_cfg(
                    typ,
                    &core_import,
                    &opaque_types,
                    &wasm_conv_config,
                ));
            }
        }
        for e in &api.enums {
            if !exclude_types.contains(&e.name) {
                if enums::is_tagged_data_enum(e) {
                    if input_types.contains(&e.name) {
                        builder.add_item(&enums::gen_tagged_enum_binding_to_core(e, &core_import, &prefix));
                    }
                    builder.add_item(&enums::gen_tagged_enum_core_to_binding(e, &core_import, &prefix));
                } else {
                    if input_types.contains(&e.name) && crate::codegen::conversions::can_generate_enum_conversion(e) {
                        builder.add_item(&crate::codegen::conversions::gen_enum_from_binding_to_core_cfg(
                            e,
                            &core_import,
                            &wasm_conv_config,
                        ));
                    }
                    if crate::codegen::conversions::can_generate_enum_conversion_from_core(e) {
                        builder.add_item(&crate::codegen::conversions::gen_enum_from_core_to_binding_cfg(
                            e,
                            &core_import,
                            &wasm_conv_config,
                        ));
                    }
                }
            }
        }

        for error in &api.errors {
            if exclude_types.contains(&error.name) {
                continue;
            }
            builder.add_item(&gen_error_converter(error, &core_import, &source_remaps_borrowed));
            let methods_block = gen_error_methods(error, &core_import, &prefix);
            if !methods_block.is_empty() {
                builder.add_item(&methods_block);
            }
        }

        let mut content = builder.build();
        content = fix_dropped_payload_enum_option_fields(content);

        for bridge in &config.trait_bridges {
            if let Some(field_name) = bridge.resolved_options_field() {
                let param_name = bridge.param_name.as_deref().unwrap_or(field_name);
                let pattern = format!(".{}({}.as_ref().map(|v| &v.inner))", field_name, param_name);
                let replacement = format!(".{}(None)", field_name);
                content = content.replace(&pattern, &replacement);
            }
        }

        for bridge in &config.trait_bridges {
            if bridge.bind_via != crate::core::config::BridgeBinding::OptionsField {
                continue;
            }
            let (Some(options_type), Some(field_name)) =
                (bridge.options_type.as_deref(), bridge.resolved_options_field())
            else {
                continue;
            };
            for variant in ["", "Update"] {
                let binding_name = format!("Wasm{options_type}{variant}");
                let core_path = format!("{core_import}::options::{options_type}{variant}");
                let impl_header = format!("impl From<{binding_name}> for {core_path} {{");
                if !content.contains(&impl_header) {
                    continue;
                }
                let patterns = &[
                    ("            ", "\n            "),
                    ("        ", "\n        "),
                    ("  ", "\n  "),
                ];
                for (indent, newline_indent) in patterns {
                    let old_pattern =
                        format!("{indent}{field_name}: Default::default(),{newline_indent}..Default::default()");
                    let new_pattern = format!(
                        "{indent}{field_name}: val.{field_name}.map(|v| (*v.inner).clone()),{newline_indent}..Default::default()"
                    );
                    if content.contains(&old_pattern) {
                        content = content.replace(&old_pattern, &new_pattern);
                    }
                }
            }
        }

        let output_dir = resolve_output_dir(config.output_paths.get("wasm"), &config.name, "crates/{name}-wasm/src/");

        let cargo_toml_path = PathBuf::from(&output_dir)
            .parent()
            .map(|p| p.join("Cargo.toml"))
            .unwrap_or_else(|| PathBuf::from("Cargo.toml"));

        Ok(vec![
            GeneratedFile {
                path: PathBuf::from(&output_dir).join("lib.rs"),
                content,
                generated_header: false,
            },
            GeneratedFile {
                path: cargo_toml_path,
                content: gen_cargo_toml(api, config),
                generated_header: true,
            },
        ])
    }

    fn generate_service_api(
        &self,
        api: &ApiSurface,
        config: &ResolvedCrateConfig,
    ) -> anyhow::Result<Vec<GeneratedFile>> {
        Ok(service_api::gen_service_files(api, config))
    }

    fn build_config(&self) -> Option<BuildConfig> {
        Some(BuildConfig {
            tool: "wasm-pack",
            crate_suffix: "-wasm",
            build_dep: BuildDependency::None,
            post_build: vec![],
        })
    }
}

#[cfg(test)]
mod tests;