1pub 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 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 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 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 builder.add_import("serde_json");
128
129 for trait_path in generators::collect_trait_imports(api) {
131 builder.add_import(&trait_path);
132 }
133
134 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 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 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 if !capsule_types.is_empty() {
169 builder.add_import("napi::bindgen_prelude::JsObjectValue");
170 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 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 let adapter_bodies = alef_adapters::build_adapter_bodies(config, Language::Node)?;
210
211 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 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 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 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 for typ in api
372 .types
373 .iter()
374 .filter(|typ| !typ.is_trait && !exclude_types.contains(&typ.name))
375 {
376 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 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 let struct_names: ahash::AHashSet<String> = api.types.iter().map(|t| t.name.clone()).collect();
415
416 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 .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 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 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 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 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: true,
542 option_duration_on_defaults: true,
543 include_cfg_metadata: true,
544 opaque_types: Some(&opaque_types),
548 json_as_value: true,
551 never_skip_cfg_field_names: &never_skip_cfg_field_names,
552 ..Default::default()
553 };
554 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 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 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 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 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 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 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 if let Some(impl_start) = content.find(&impl_marker) {
675 let from_impl_start = impl_start;
677 let impl_body = &content[from_impl_start..];
678
679 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 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 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 let mut type_exports = vec![];
749 let mut function_exports = vec![];
750
751 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 for enum_def in &api.enums {
772 type_exports.push(format!("{prefix}{}", enum_def.name));
773 }
774
775 for func in &api.functions {
780 let js_name = to_node_name(&func.name);
782 function_exports.push(js_name);
783 }
784
785 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 type_exports.sort();
804 function_exports.sort();
805
806 let mut lines = vec![
809 "// This file is auto-generated by alef. DO NOT EDIT.".to_string(),
810 "".to_string(),
811 ];
812
813 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 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 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 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#[cfg(test)]
903mod tests {
904 use super::NapiBackend;
905 use alef_core::backend::Backend;
906 use alef_core::config::Language;
907
908 #[test]
910 fn napi_backend_name_is_napi() {
911 let b = NapiBackend;
912 assert_eq!(b.name(), "napi");
913 }
914
915 #[test]
917 fn napi_backend_language_is_node() {
918 let b = NapiBackend;
919 assert_eq!(b.language(), Language::Node);
920 }
921
922 #[test]
924 fn cfg_gated_field_accepted_when_in_never_skip_list() {
925 let never_skip_cfg_field_names = ["visitor".to_string()];
928 let field_is_target = "visitor";
929
930 let field_has_cfg = Some("feature = \"visitor\"");
932
933 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}