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