Skip to main content

alef_backend_napi/gen_bindings/
mod.rs

1//! NAPI-RS (Node.js) backend: orchestration and `Backend` trait implementation.
2
3pub mod capsule;
4pub mod enums;
5pub mod errors;
6pub mod functions;
7pub mod methods;
8pub mod types;
9
10use crate::type_map::NapiMapper;
11use ahash::AHashSet;
12use alef_codegen::builder::RustFileBuilder;
13use alef_codegen::generators::{self, AsyncPattern, RustBindingConfig};
14use alef_core::backend::{Backend, BuildConfig, BuildDependency, Capabilities, GeneratedFile, PostBuildStep};
15use alef_core::config::{Language, NodeCapsuleTypeConfig, ResolvedCrateConfig, resolve_output_dir};
16use alef_core::ir::{ApiSurface, TypeRef};
17use std::collections::HashMap;
18use std::path::PathBuf;
19
20pub struct NapiBackend;
21
22impl NapiBackend {
23    fn binding_config<'a>(core_import: &'a str, prefix: &'a str, has_serde: bool) -> RustBindingConfig<'a> {
24        RustBindingConfig {
25            struct_attrs: &["napi"],
26            field_attrs: &[],
27            struct_derives: &["Clone"],
28            method_block_attr: Some("napi"),
29            constructor_attr: "#[napi(constructor)]",
30            static_attr: None,
31            function_attr: "#[napi]",
32            enum_attrs: &["napi(string_enum)"],
33            enum_derives: &["Clone"],
34            needs_signature: false,
35            signature_prefix: "",
36            signature_suffix: "",
37            core_import,
38            async_pattern: AsyncPattern::NapiNativeAsync,
39            has_serde,
40            // NAPI napi(object) structs don't derive Serialize — disable serde bridge
41            type_name_prefix: prefix,
42            option_duration_on_defaults: true,
43            opaque_type_names: &[],
44            skip_impl_constructor: false,
45            cast_uints_to_i32: false,
46            cast_large_ints_to_f64: false,
47            named_non_opaque_params_by_ref: false,
48            lossy_skip_types: &[],
49            serializable_opaque_type_names: &[],
50            never_skip_cfg_field_names: &[],
51        }
52    }
53}
54
55impl Backend for NapiBackend {
56    fn name(&self) -> &str {
57        "napi"
58    }
59
60    fn language(&self) -> Language {
61        Language::Node
62    }
63
64    fn capabilities(&self) -> Capabilities {
65        Capabilities {
66            supports_async: true,
67            supports_classes: true,
68            supports_enums: true,
69            supports_option: true,
70            supports_result: true,
71            ..Capabilities::default()
72        }
73    }
74
75    fn generate_bindings(&self, api: &ApiSurface, config: &ResolvedCrateConfig) -> anyhow::Result<Vec<GeneratedFile>> {
76        let prefix = config.node_type_prefix();
77        let trait_type_names: AHashSet<String> = api
78            .types
79            .iter()
80            .filter(|t| t.is_trait)
81            .map(|t| t.name.clone())
82            .collect();
83        let capsule_type_names_for_mapper: AHashSet<String> = config
84            .node
85            .as_ref()
86            .map(|c| c.capsule_types.keys().cloned().collect())
87            .unwrap_or_default();
88        let mapper =
89            NapiMapper::with_traits_and_capsules(prefix.clone(), trait_type_names, capsule_type_names_for_mapper);
90        let core_import = config.core_import_name();
91
92        // Detect serde availability from the output crate's Cargo.toml
93        let output_dir = resolve_output_dir(config.output_paths.get("node"), &config.name, "crates/{name}-node/src/");
94        let has_serde = alef_core::config::detect_serde_available(&output_dir);
95        let mut cfg = Self::binding_config(&core_import, &prefix, has_serde);
96        let never_skip_cfg_field_names: Vec<String> = config
97            .trait_bridges
98            .iter()
99            .filter_map(|b| {
100                if b.bind_via == alef_core::config::BridgeBinding::OptionsField {
101                    b.resolved_options_field().map(|s| s.to_string())
102                } else {
103                    None
104                }
105            })
106            .collect();
107        cfg.never_skip_cfg_field_names = &never_skip_cfg_field_names;
108
109        let mut builder = RustFileBuilder::new().with_generated_header();
110        builder.add_inner_attribute("allow(dead_code, unused_imports, unused_variables)");
111        builder.add_inner_attribute("allow(unsafe_code)");
112        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::unnecessary_cast, clippy::unused_unit, clippy::unwrap_or_default, clippy::derivable_impls, clippy::needless_borrows_for_generic_args, clippy::unnecessary_fallible_conversions, clippy::arc_with_non_send_sync, clippy::collapsible_if, clippy::clone_on_copy, clippy::should_implement_trait)");
113        // Cast lints fire heavily on the JS u32/i64/Number bridge — these are
114        // intentional, deliberate at the FFI boundary. Pedantic/nursery noise
115        // (must_use_candidate, use_self, missing_const_for_fn, etc.) is
116        // suppressed for the same reasons documented in the pyo3 backend.
117        builder.add_inner_attribute(
118            "allow(clippy::cast_possible_wrap, clippy::cast_possible_truncation, clippy::cast_sign_loss, clippy::default_trait_access, clippy::useless_conversion, clippy::unsafe_derive_deserialize, clippy::must_use_candidate, clippy::return_self_not_must_use, clippy::use_self, clippy::missing_const_for_fn, clippy::missing_errors_doc, clippy::needless_pass_by_value, clippy::doc_markdown, clippy::derive_partial_eq_without_eq, clippy::uninlined_format_args, clippy::redundant_clone, clippy::implicit_clone, clippy::redundant_closure_for_method_calls, clippy::wildcard_imports, clippy::option_if_let_else, clippy::too_many_lines)",
119        );
120        builder.add_import("napi::*");
121        builder.add_import("napi_derive::napi");
122
123        // Always import serde_json for type conversion in From/Into impls,
124        // even if the binding crate doesn't explicitly list it as a dependency.
125        // serde_json is needed for conversions of types with serde-serializable fields.
126        builder.add_import("serde_json");
127
128        // Import traits needed for trait method dispatch
129        for trait_path in generators::collect_trait_imports(api) {
130            builder.add_import(&trait_path);
131        }
132
133        // Only import HashMap when Map-typed fields or returns are present
134        let has_maps = api
135            .types
136            .iter()
137            .any(|t| t.fields.iter().any(|f| matches!(&f.ty, TypeRef::Map(_, _))))
138            || api
139                .functions
140                .iter()
141                .any(|f| matches!(&f.return_type, TypeRef::Map(_, _)));
142        if has_maps {
143            builder.add_import("std::collections::HashMap");
144        }
145
146        // Check if any function or method is async
147        let has_async =
148            api.functions.iter().any(|f| f.is_async) || api.types.iter().any(|t| t.methods.iter().any(|m| m.is_async));
149
150        if has_async {
151            builder.add_item(&functions::gen_tokio_runtime());
152        }
153
154        // Extract capsule_types from NodeConfig. Types listed here skip #[napi] opaque-class
155        // emission; functions returning them produce a JsObject with __parser External<T>.
156        let capsule_types: HashMap<String, NodeCapsuleTypeConfig> = config
157            .node
158            .as_ref()
159            .map(|c| c.capsule_types.clone())
160            .unwrap_or_default();
161
162        // When capsule types are present, generated shims call set_named_property which
163        // requires the JsObjectValue trait to be in scope.
164        if !capsule_types.is_empty() {
165            builder.add_import("napi::bindgen_prelude::JsObjectValue");
166            // Emit the FFI declarations for napi_create_external and napi_type_tag_object,
167            // and any per-capsule type tag constants. Done once per crate.
168            builder.add_item(&capsule::gen_ffi_declarations());
169            let constants = capsule::gen_type_tag_constants(&capsule_types);
170            if !constants.is_empty() {
171                builder.add_item(&constants);
172            }
173        }
174
175        // Check if we have opaque types and trait types (visitors)
176        // Exclude trait types from opaque_types since they use JsVisitorRef instead of Object<'static>
177        // Also exclude capsule types — they do not get #[napi] class wrappers.
178        let opaque_types: AHashSet<String> = api
179            .types
180            .iter()
181            .filter(|t| t.is_opaque && !t.is_trait && !capsule_types.contains_key(&t.name))
182            .map(|t| t.name.clone())
183            .collect();
184        let mutex_types: AHashSet<String> = api
185            .types
186            .iter()
187            .filter(|t| t.is_opaque && generators::type_needs_mutex(t))
188            .map(|t| t.name.clone())
189            .collect();
190        let has_traits = api.types.iter().any(|t| t.is_trait);
191        if !opaque_types.is_empty() || has_traits {
192            builder.add_import("std::sync::Arc");
193        }
194        if !mutex_types.is_empty() {
195            builder.add_import("std::sync::Mutex");
196        }
197
198        let exclude_types: ahash::AHashSet<String> = config
199            .node
200            .as_ref()
201            .map(|c| c.exclude_types.iter().cloned().collect())
202            .unwrap_or_default();
203
204        // Build adapter body map before type iteration so bodies are available for method generation.
205        let adapter_bodies = alef_adapters::build_adapter_bodies(config, Language::Node)?;
206
207        // Map "OwnerType.method" -> streaming item type. The napi backend needs to
208        // override the IR-declared `String` return type with `Vec<{prefix}{item}>`
209        // for streaming adapters, since the generated body returns chunks directly
210        // as a JS array instead of a serialized JSON string.
211        let streaming_item_types: ahash::AHashMap<String, String> = config
212            .adapters
213            .iter()
214            .filter(|a| matches!(a.pattern, alef_core::config::AdapterPattern::Streaming))
215            .filter_map(|a| {
216                let owner = a.owner_type.as_deref()?;
217                let item = a.item_type.as_deref()?;
218                Some((format!("{owner}.{}", a.name), item.to_string()))
219            })
220            .collect();
221
222        // JsBytes: a newtype wrapper for Vec<u8> with custom FromNapiValue that accepts
223        // Buffer.from(...) from JavaScript. Fixes NAPI v3 macro-derived deserialization
224        // of Vec<u8> fields in #[napi(object)] structs, which normally expect Array[number].
225        let js_bytes_def = r#"
226/// Wrapper for byte arrays that implements custom FromNapiValue to accept Buffer.from(...).
227///
228/// NAPI v3's default FromNapiValue for Vec<u8> expects Array[number], not Buffer.
229/// This wrapper provides custom deserialization that accepts Buffer, Uint8Array, or Array,
230/// converting them to Vec<u8>. Implements Clone and serde traits for use in struct fields.
231#[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)]
232pub struct JsBytes(pub Vec<u8>);
233
234impl From<Vec<u8>> for JsBytes {
235    fn from(v: Vec<u8>) -> Self {
236        JsBytes(v)
237    }
238}
239
240impl From<JsBytes> for Vec<u8> {
241    fn from(js_bytes: JsBytes) -> Self {
242        js_bytes.0
243    }
244}
245
246impl AsRef<[u8]> for JsBytes {
247    fn as_ref(&self) -> &[u8] {
248        &self.0
249    }
250}
251
252impl std::ops::Deref for JsBytes {
253    type Target = Vec<u8>;
254    fn deref(&self) -> &Self::Target {
255        &self.0
256    }
257}
258
259impl std::ops::DerefMut for JsBytes {
260    fn deref_mut(&mut self) -> &mut Self::Target {
261        &mut self.0
262    }
263}
264
265impl napi::bindgen_prelude::FromNapiValue for JsBytes {
266    unsafe fn from_napi_value(env: napi::sys::napi_env, napi_val: napi::sys::napi_value) -> napi::Result<Self> {
267        use napi::bindgen_prelude::FromNapiValue;
268
269        // Try Buffer first (most common for binary data in JS)
270        if let Ok(buffer) = unsafe { napi::bindgen_prelude::Buffer::from_napi_value(env, napi_val) } {
271            return Ok(JsBytes(buffer.as_ref().to_vec()));
272        }
273
274        // Try Uint8Array
275        if let Ok(ua) = unsafe { napi::bindgen_prelude::Uint8Array::from_napi_value(env, napi_val) } {
276            return Ok(JsBytes(ua.to_vec()));
277        }
278
279        // Fall back to Array[number]
280        if let Ok(vec) = unsafe { Vec::<u8>::from_napi_value(env, napi_val) } {
281            return Ok(JsBytes(vec));
282        }
283
284        Err(napi::Error::new(
285            napi::Status::InvalidArg,
286            "Expected Buffer, Uint8Array, or Array<number> for bytes field",
287        ))
288    }
289}
290
291impl napi::bindgen_prelude::ToNapiValue for JsBytes {
292    unsafe fn to_napi_value(env: napi::sys::napi_env, val: Self) -> napi::Result<napi::sys::napi_value> {
293        // Delegate to Vec<u8>'s implementation (which returns an Uint8Array/Buffer).
294        unsafe { <Vec<u8> as napi::bindgen_prelude::ToNapiValue>::to_napi_value(env, val.0) }
295    }
296}
297"#;
298        builder.add_item(js_bytes_def);
299
300        // JsVisitorRef: a thin wrapper around napi::Object that implements Clone.
301        // This newtype makes Object<'static> work with napi(object) field derivations,
302        // which require Clone. Uses std::sync::Arc to make the handle cheaply cloneable.
303        if has_traits {
304            let js_visitor_ref_def = r#"
305/// Wrapper for trait visitor types (napi::Object<'static>) that implements Clone.
306///
307/// Object is not Clone. This wrapper uses Arc<Object<'static>> internally for cheap cloning.
308/// The .inner field is public for compatibility with generated code that needs to access
309/// the underlying Object for trait dispatch.
310pub struct JsVisitorRef {
311    pub inner: std::sync::Arc<napi::bindgen_prelude::Object<'static>>,
312}
313
314impl Clone for JsVisitorRef {
315    fn clone(&self) -> Self {
316        JsVisitorRef {
317            inner: std::sync::Arc::clone(&self.inner),
318        }
319    }
320}
321
322#[allow(clippy::arc_with_non_send_sync)]
323impl From<napi::bindgen_prelude::Object<'static>> for JsVisitorRef {
324    fn from(visitor: napi::bindgen_prelude::Object<'static>) -> Self {
325        JsVisitorRef {
326            inner: std::sync::Arc::new(visitor),
327        }
328    }
329}
330
331impl From<JsVisitorRef> for napi::bindgen_prelude::Object<'static> {
332    fn from(visitor_ref: JsVisitorRef) -> Self {
333        // Object<'static> is Copy (it just holds an env+handle pair), so deref directly.
334        *visitor_ref.inner
335    }
336}
337"#;
338            builder.add_item(js_visitor_ref_def);
339        }
340
341        // Emit adapter-generated standalone items (streaming iterators, callback bridges).
342        for adapter in &config.adapters {
343            match adapter.pattern {
344                alef_core::config::AdapterPattern::Streaming => {
345                    let key = format!("{}.__stream_struct__", adapter.item_type.as_deref().unwrap_or(""));
346                    if let Some(struct_code) = adapter_bodies.get(&key) {
347                        builder.add_item(struct_code);
348                    }
349                }
350                alef_core::config::AdapterPattern::CallbackBridge => {
351                    let struct_key = format!("{}.__bridge_struct__", adapter.name);
352                    let impl_key = format!("{}.__bridge_impl__", adapter.name);
353                    if let Some(struct_code) = adapter_bodies.get(&struct_key) {
354                        builder.add_item(struct_code);
355                    }
356                    if let Some(impl_code) = adapter_bodies.get(&impl_key) {
357                        builder.add_item(impl_code);
358                    }
359                }
360                _ => {}
361            }
362        }
363
364        // NAPI has some unique patterns: Js-prefixed names, Option-wrapped fields,
365        // and custom constructor. Use shared generators for enums and functions,
366        // but keep struct/method generation custom.
367        for typ in api
368            .types
369            .iter()
370            .filter(|typ| !typ.is_trait && !exclude_types.contains(&typ.name))
371        {
372            // Capsule types bypass #[napi] class emission entirely — they are exposed
373            // as raw External<T> pointers in JsObject wrappers from functions that return them.
374            if capsule_types.contains_key(&typ.name) {
375                continue;
376            }
377            if typ.is_opaque {
378                // gen_opaque_struct_prefixed emits `#[napi]` from cfg.struct_attrs.
379                // Replace with `#[napi(js_name = "Foo")]` so NAPI-RS exports the
380                // unprefixed name while the Rust struct stays JsFoo internally.
381                // Prepend `///` rustdoc so napi-derive forwards it to JSDoc on
382                // the corresponding `export declare class` in index.d.ts.
383                let opaque_struct_code = {
384                    let raw = alef_codegen::generators::gen_opaque_struct_prefixed(typ, &cfg, &prefix);
385                    let struct_name = format!("{prefix}{}", typ.name);
386                    let body = raw.replace(
387                        &format!("#[napi]pub struct {struct_name}"),
388                        &format!("#[napi(js_name = \"{}\")]pub struct {struct_name}", typ.name),
389                    );
390                    let mut out = String::new();
391                    alef_codegen::doc_emission::emit_rustdoc(&mut out, &typ.doc, "");
392                    out.push_str(&body);
393                    out
394                };
395                builder.add_item(&opaque_struct_code);
396                let capsule_type_names: AHashSet<String> = capsule_types.keys().cloned().collect();
397                builder.add_item(&types::gen_opaque_struct_methods(
398                    typ,
399                    &mapper,
400                    &cfg,
401                    &opaque_types,
402                    &prefix,
403                    &adapter_bodies,
404                    &streaming_item_types,
405                    &capsule_type_names,
406                    &mutex_types,
407                    &capsule_types,
408                ));
409            } else {
410                // Non-opaque structs use #[napi(object)] — plain JS objects without methods.
411                // napi(object) structs cannot have #[napi] impl blocks.
412                // gen_struct adds Default to derives when typ.has_default is true.
413                builder.add_item(&types::gen_struct(
414                    typ,
415                    &mapper,
416                    &prefix,
417                    has_serde,
418                    &opaque_types,
419                    &never_skip_cfg_field_names,
420                ));
421            }
422        }
423
424        // Collect struct names so tagged enum codegen knows which Named types have binding structs
425        let struct_names: ahash::AHashSet<String> = api.types.iter().map(|t| t.name.clone()).collect();
426
427        // Collect Named types that have a Default impl. These are eligible to be
428        // promoted to Option<T> in binding signatures so JS callers may pass
429        // `undefined` to fall back to a default-constructed instance.
430        let default_types: ahash::AHashSet<String> = api
431            .types
432            .iter()
433            .filter(|t| t.has_default)
434            .map(|t| t.name.clone())
435            .collect();
436
437        for enum_def in &api.enums {
438            builder.add_item(&enums::gen_enum(enum_def, &prefix, has_serde));
439        }
440
441        let exclude_functions: ahash::AHashSet<String> = config
442            .node
443            .as_ref()
444            .map(|c| c.exclude_functions.iter().cloned().collect())
445            .unwrap_or_default();
446
447        for func in &api.functions {
448            if exclude_functions.contains(&func.name) {
449                continue;
450            }
451            let bridge_param = crate::trait_bridge::find_bridge_param(func, &config.trait_bridges);
452            let options_field_bridge = crate::trait_bridge::find_options_field_binding(func, &config.trait_bridges)
453                // Only use the options-field path when the bridge field actually survives
454                // into the binding struct. If the core field is `#[cfg(...)]`-gated, the
455                // struct generator strips it and the generated bridge code would reference
456                // a missing field, producing `E0609 no field` at compile time.
457                // Exception: fields listed in never_skip_cfg_field_names are cfg-gated but
458                // preserved by the struct generator, so they are valid for bridge codegen.
459                .filter(|(_, bridge_cfg)| {
460                    let Some(field_name) = bridge_cfg.resolved_options_field() else { return false; };
461                    let Some(options_type) = bridge_cfg.options_type.as_deref() else { return false; };
462                    api.types
463                        .iter()
464                        .filter(|t| t.name == options_type)
465                        .flat_map(|t| t.fields.iter())
466                        .any(|f| f.name == field_name && (f.cfg.is_none() || never_skip_cfg_field_names.iter().any(|n| n == field_name)))
467                });
468            // Skip sanitized functions when there's no trait bridge that can replace the
469            // sanitized parameter — such functions cannot be auto-delegated. Functions
470            // whose only "sanitized" param is a configured trait_bridge param (e.g.
471            // Option<VisitorHandle> in html-to-markdown) are emitted via gen_bridge_function.
472            if func.sanitized && bridge_param.is_none() && options_field_bridge.is_none() {
473                continue;
474            }
475            if let Some((param_idx, bridge_cfg)) = bridge_param {
476                builder.add_item(&crate::trait_bridge::gen_bridge_function(
477                    func,
478                    param_idx,
479                    bridge_cfg,
480                    &mapper,
481                    &cfg,
482                    &Default::default(),
483                    &opaque_types,
484                    &core_import,
485                ));
486            } else if let Some((param_idx, bridge_cfg)) = options_field_bridge {
487                builder.add_item(&crate::trait_bridge::gen_options_field_bridge_function(
488                    func,
489                    param_idx,
490                    bridge_cfg,
491                    &mapper,
492                    &cfg,
493                    &opaque_types,
494                    &core_import,
495                ));
496            } else if !capsule_types.is_empty() && capsule::function_involves_capsule(func, &capsule_types) {
497                // Function returns a capsule type — emit a napi shim that returns JsObject
498                // with __parser = External<T>(ptr from value.into_raw()).
499                // JsObjectValue provides set_named_property; imported once below.
500                builder.add_item(&capsule::gen_capsule_function(func, &capsule_types, &core_import));
501            } else {
502                builder.add_item(&functions::gen_function(
503                    func,
504                    &mapper,
505                    &cfg,
506                    &opaque_types,
507                    &default_types,
508                    &prefix,
509                    &capsule_types,
510                    &mutex_types,
511                ));
512            }
513        }
514
515        // Trait bridge wrappers — generate NAPI bridge structs that delegate to JS objects
516        for bridge_cfg in &config.trait_bridges {
517            if let Some(trait_type) = api.types.iter().find(|t| t.is_trait && t.name == bridge_cfg.trait_name) {
518                let bridge = crate::trait_bridge::gen_trait_bridge(
519                    trait_type,
520                    bridge_cfg,
521                    &core_import,
522                    &config.error_type_name(),
523                    &config.error_constructor_expr(),
524                    api,
525                );
526                for imp in &bridge.imports {
527                    builder.add_import(imp);
528                }
529                builder.add_item(&bridge.code);
530            }
531        }
532
533        let binding_to_core = alef_codegen::conversions::convertible_types(api);
534        let core_to_binding = alef_codegen::conversions::core_to_binding_convertible_types(api);
535        let input_types = alef_codegen::conversions::input_type_names(api);
536        // NOTE: NAPI does NOT populate `trait_bridge_arc_wrapper_field_names`. Unlike
537        // PHP/WASM which wrap their visitor handle as `WrapperType { inner: Arc<...> }`,
538        // the NAPI binding stores the raw JS `napi::bindgen_prelude::Object` directly on
539        // `JsConversionOptions.visitor`. There is no `.inner` field to dereference, so
540        // the `(*v.inner).clone()` substitution would emit code that fails to compile.
541        // Instead, the NAPI `convert` codegen attaches the visitor in a post-process
542        // step after the `From<JsConversionOptions>` impl runs (`o.visitor = None;`
543        // then `result.visitor = visitor_handle.clone()`), so the From impl harmlessly
544        // emits `Default::default()` for the visitor field.
545        let napi_conv_config = alef_codegen::conversions::ConversionConfig {
546            type_name_prefix: &prefix,
547            cast_large_ints_to_i64: true,
548            cast_f32_to_f64: true,
549            // optionalize_defaults: For types with has_default, conversion generators
550            // make all fields Option<T> and apply defaults via FromNapiValue,
551            // enabling JS users to pass partial objects and omit fields they want defaults for.
552            optionalize_defaults: true,
553            option_duration_on_defaults: true,
554            include_cfg_metadata: true,
555            // Pass opaque_types so the conversion generator can emit `Default::default()`
556            // for opaque-type fields (e.g. visitor: Object<'static>) instead of trying to
557            // convert them via Into — these fields are handled separately via bridge code.
558            opaque_types: Some(&opaque_types),
559            // Json fields are stored as serde_json::Value in the binding so JS
560            // callers can pass objects/arrays/scalars directly.
561            json_as_value: true,
562            never_skip_cfg_field_names: &never_skip_cfg_field_names,
563            ..Default::default()
564        };
565        // From/Into conversions using shared parameterized generators
566        for typ in api.types.iter().filter(|typ| !typ.is_trait) {
567            if input_types.contains(&typ.name)
568                && alef_codegen::conversions::can_generate_conversion(typ, &binding_to_core)
569            {
570                builder.add_item(&alef_codegen::conversions::gen_from_binding_to_core_cfg(
571                    typ,
572                    &core_import,
573                    &napi_conv_config,
574                ));
575            }
576            if alef_codegen::conversions::can_generate_conversion(typ, &core_to_binding) {
577                builder.add_item(&alef_codegen::conversions::gen_from_core_to_binding_cfg(
578                    typ,
579                    &core_import,
580                    &opaque_types,
581                    &napi_conv_config,
582                ));
583            }
584        }
585        for e in &api.enums {
586            let has_data_variants = e.variants.iter().any(|v| !v.fields.is_empty());
587            let is_tagged_data_enum = e.serde_tag.is_some() && has_data_variants;
588            let is_untagged_data_enum = e.serde_untagged && has_data_variants;
589            if is_tagged_data_enum {
590                // Tagged data enums use flattened struct — generate custom conversions
591                builder.add_item(&methods::gen_tagged_enum_binding_to_core(
592                    e,
593                    &core_import,
594                    &prefix,
595                    &struct_names,
596                ));
597                builder.add_item(&methods::gen_tagged_enum_core_to_binding(
598                    e,
599                    &core_import,
600                    &prefix,
601                    &struct_names,
602                ));
603            } else if is_untagged_data_enum {
604                // Untagged data enums are wrapped around serde_json::Value — bridge via serde.
605                let binding_name = format!("{prefix}{}", e.name);
606                let core_path = alef_codegen::conversions::core_enum_path_remapped(
607                    e,
608                    &core_import,
609                    napi_conv_config.source_crate_remaps,
610                );
611                builder.add_item(&format!(
612                    "impl From<{binding_name}> for {core_path} {{\n    \
613                         fn from(val: {binding_name}) -> Self {{\n        \
614                             serde_json::from_value(val.0).unwrap_or_default()\n    \
615                         }}\n\
616                     }}\n"
617                ));
618                builder.add_item(&format!(
619                    "impl From<{core_path}> for {binding_name} {{\n    \
620                         fn from(val: {core_path}) -> Self {{\n        \
621                             Self(serde_json::to_value(val).unwrap_or_default())\n    \
622                         }}\n\
623                     }}\n"
624                ));
625            } else {
626                if input_types.contains(&e.name) && alef_codegen::conversions::can_generate_enum_conversion(e) {
627                    builder.add_item(&alef_codegen::conversions::gen_enum_from_binding_to_core_cfg(
628                        e,
629                        &core_import,
630                        &napi_conv_config,
631                    ));
632                }
633                if alef_codegen::conversions::can_generate_enum_conversion_from_core(e) {
634                    builder.add_item(&alef_codegen::conversions::gen_enum_from_core_to_binding_cfg(
635                        e,
636                        &core_import,
637                        &napi_conv_config,
638                    ));
639                }
640            }
641        }
642
643        // Error types (variant name constants + converter functions)
644        for error in &api.errors {
645            builder.add_item(&alef_codegen::error_gen::gen_napi_error_types(error));
646            builder.add_item(&alef_codegen::error_gen::gen_napi_error_converter(error, &core_import));
647        }
648
649        let mut content = builder.build();
650
651        // Post-process: Fix From<JsXxx> (binding to core) impls to forward visitor field.
652        // The conversion generator emits `__result.visitor = Default::default();` in binding→core
653        // conversions because the raw JS napi::bindgen_prelude::Object is not Clone-able.
654        // This post-process detects that pattern in the JS→Rust direction and replaces it with
655        // code that wraps val.visitor into a JsHtmlVisitorBridge and then into the core Rc<RefCell<>> type.
656        //
657        // Key: only fix `impl From<Js{type}>` (binding→core), NOT `impl From<core_type>` (core→binding).
658        // The core→binding direction correctly uses Default because the Rc<RefCell<>> is opaque to JS.
659        for bridge in &config.trait_bridges {
660            if bridge.bind_via != alef_core::config::BridgeBinding::OptionsField {
661                continue;
662            }
663            if let Some(field_name) = bridge.resolved_options_field() {
664                // Verify the field is present in the binding struct (not cfg-gated away)
665                let Some(options_type) = bridge.options_type.as_deref() else {
666                    continue;
667                };
668                let field_in_binding = api
669                    .types
670                    .iter()
671                    .filter(|t| t.name == options_type)
672                    .flat_map(|t| t.fields.iter())
673                    .any(|f| f.cfg.is_none() && f.name == field_name);
674                if !field_in_binding {
675                    continue;
676                }
677
678                // Find the binding→core conversion impl: `impl From<Js{options_type}> for core...`
679                let prefix = config.node_type_prefix();
680                let js_type_name = format!("{prefix}{options_type}");
681                let impl_marker = format!("impl From<{js_type_name}> for {core_import}");
682
683                // Search forward from the impl marker to find its closing brace and visitor wipe.
684                // We only fix the impl that converts FROM the JS binding type.
685                if let Some(impl_start) = content.find(&impl_marker) {
686                    // Find the matching closing brace for this impl block
687                    let from_impl_start = impl_start;
688                    let impl_body = &content[from_impl_start..];
689
690                    // Find the next `}` that closes this impl — being careful to count braces
691                    let mut brace_depth = 0;
692                    let mut impl_end = 0;
693                    let mut found_fn_from = false;
694                    for (i, ch) in impl_body.char_indices() {
695                        if ch == '{' {
696                            brace_depth += 1;
697                            // Once we see the opening brace of `fn from(...) {`, mark it
698                            if impl_body[..i].contains("fn from") {
699                                found_fn_from = true;
700                            }
701                        } else if ch == '}' {
702                            brace_depth -= 1;
703                            if brace_depth == 0 && found_fn_from {
704                                impl_end = i;
705                                break;
706                            }
707                        }
708                    }
709
710                    if impl_end > 0 {
711                        let impl_block = &impl_body[..impl_end];
712                        let pattern = "__result.visitor = Default::default();";
713
714                        if let Some(rel_pos) = impl_block.find(pattern) {
715                            let pos = from_impl_start + rel_pos;
716                            let before = &content[..pos];
717                            let after = &content[pos + pattern.len()..];
718
719                            // Build the replacement that wraps val.visitor into JsHtmlVisitorBridge
720                            // and then into the core Arc<Mutex<...>> type.
721                            let type_alias = bridge.type_alias.as_deref().unwrap_or("VisitorHandle");
722                            let handle_path = format!("{core_import}::visitor::{type_alias}");
723                            let replacement = format!(
724                                "__result.visitor = val.{field_name}.map(|obj| {{\n            \
725                                    let bridge = JsHtmlVisitorBridge::new(obj);\n            \
726                                    std::sync::Arc::new(std::sync::Mutex::new(bridge)) as {handle_path}\n        \
727                                }});"
728                            );
729
730                            content = format!("{}{}{}", before, replacement, after);
731                        }
732                    }
733                }
734            }
735        }
736
737        let output_dir = resolve_output_dir(config.output_paths.get("node"), &config.name, "crates/{name}-node/src/");
738
739        Ok(vec![GeneratedFile {
740            path: PathBuf::from(&output_dir).join("lib.rs"),
741            content,
742            generated_header: false,
743        }])
744    }
745
746    fn generate_type_stubs(
747        &self,
748        api: &ApiSurface,
749        config: &ResolvedCrateConfig,
750    ) -> anyhow::Result<Vec<GeneratedFile>> {
751        let prefix = config.node_type_prefix();
752        let exclude_functions: ahash::AHashSet<String> = config
753            .node
754            .as_ref()
755            .map(|c| c.exclude_functions.iter().cloned().collect())
756            .unwrap_or_default();
757        let capsule_types: HashMap<String, NodeCapsuleTypeConfig> = config
758            .node
759            .as_ref()
760            .map(|c| c.capsule_types.clone())
761            .unwrap_or_default();
762        let content = errors::gen_dts(api, &prefix, &exclude_functions, &config.trait_bridges, &capsule_types);
763
764        // `output_for("node")` points to the `src/` directory (e.g., `crates/{name}-node/src/`).
765        // `index.d.ts` belongs at the crate root, one level up from `src/`.
766        // When the configured path ends in `src/` or `src`, strip that suffix to get the crate root.
767        // Falls back to `crates/{name}-node/` if no node output is configured.
768        let src_dir = resolve_output_dir(config.output_paths.get("node"), &config.name, "crates/{name}-node/src/");
769        let crate_root = {
770            let p = PathBuf::from(&src_dir);
771            match p.file_name().and_then(|n| n.to_str()) {
772                Some("src") => p.parent().map(|parent| parent.to_path_buf()).unwrap_or(p),
773                _ => p,
774            }
775        };
776
777        Ok(vec![GeneratedFile {
778            path: crate_root.join("index.d.ts"),
779            content,
780            generated_header: false,
781        }])
782    }
783
784    fn build_config(&self) -> Option<BuildConfig> {
785        Some(BuildConfig {
786            tool: "napi",
787            crate_suffix: "-node",
788            build_dep: BuildDependency::None,
789            post_build: vec![PostBuildStep::PatchFile {
790                path: "index.d.ts",
791                find: "export declare const enum",
792                replace: "export declare enum",
793            }],
794        })
795    }
796}
797
798/// Generate a NAPI struct with Js-prefixed name and fields wrapped in Option only if optional.
799#[cfg(test)]
800mod tests {
801    use super::NapiBackend;
802    use alef_core::backend::Backend;
803    use alef_core::config::Language;
804
805    /// NapiBackend::name returns "napi".
806    #[test]
807    fn napi_backend_name_is_napi() {
808        let b = NapiBackend;
809        assert_eq!(b.name(), "napi");
810    }
811
812    /// NapiBackend::language returns Language::Node.
813    #[test]
814    fn napi_backend_language_is_node() {
815        let b = NapiBackend;
816        assert_eq!(b.language(), Language::Node);
817    }
818
819    /// Test that cfg-gated fields in never_skip_cfg_field_names pass the options-field-bridge filter.
820    #[test]
821    fn cfg_gated_field_accepted_when_in_never_skip_list() {
822        // Test the predicate logic: a cfg-gated field "visitor" should be accepted
823        // when it appears in never_skip_cfg_field_names.
824        let never_skip_cfg_field_names = ["visitor".to_string()];
825        let field_is_target = "visitor";
826
827        // Simulate a field with cfg = Some(...)
828        let field_has_cfg = Some("feature = \"visitor\"");
829
830        // Predicate: f.cfg.is_none() || never_skip_cfg_field_names.iter().any(|n| n == field_name)
831        let accepted = field_has_cfg.is_none() || never_skip_cfg_field_names.iter().any(|n| n == field_is_target);
832
833        assert!(
834            accepted,
835            "cfg-gated field 'visitor' should pass filter when in never_skip_cfg_field_names"
836        );
837    }
838}