Skip to main content

js2rust_bridge/
lib.rs

1// js2rust-bridge: Facade crate for the js2rust_bridge! proc-macro.
2//
3// Users only need to depend on this single crate:
4//
5// ```toml
6// [dependencies]
7// js2rust-bridge = "0.3"
8// [build-dependencies]
9// js2rust-bridge = "0.3"
10// ```
11//
12// The macro transpiles JS to Zig and generates Rust FFI bindings in one step.
13// Call `js2rust_bridge::build()` from your `build.rs` to transpile, compile,
14// and link the Zig static libraries.  The proc-macro detects an up-to-date cache
15// and skips re-transpilation automatically.
16//
17// Both `js2rust_bridge!()` and `build()` read from a single `js2rust.toml`
18// in the crate root — no duplicated configuration.
19//
20// `build()` emits `cargo:rerun-if-changed` directives for every JS source
21// file, the `js2rust.toml` config, and the build cache, so Cargo automatically
22// re-runs the build script when any input changes.
23
24mod config;
25#[cfg(feature = "icu")]
26pub mod native_icu;
27#[cfg(feature = "regex")]
28pub mod native_regex;
29pub mod sdk;
30
31pub use js2rust_bridge_macro::{host_fn, js2rust_bridge};
32
33// Re-export types needed for host function configuration from js2zig-core
34// so users only need `js2rust-bridge` in their `[build-dependencies]`.
35pub use js2zig_core::{HostConfig, HostFunction, HostType};
36
37// Re-export config types for programmatic use.
38pub use config::{BuildSection, HostFnToml, Js2rustConfig, ProjectSection};
39
40use std::path::PathBuf;
41
42/// Build: transpile JS → Zig, compile Zig static library, and emit linker directives.
43///
44/// Reads configuration from `js2rust.toml` in the crate root.  Call this from
45/// your `build.rs` with zero arguments:
46///
47/// ```rust,ignore
48/// fn main() {
49///     js2rust_bridge::build();
50/// }
51/// ```
52///
53/// The project name is derived automatically from the file stem of the first
54/// entry in `project.js_files`. Build behavior (force_rebuild, run_zig_build)
55/// is read from the `[build]` section of `js2rust.toml`.
56pub fn build() {
57    let config = Js2rustConfig::from_manifest_dir();
58    let manifest_dir =
59        std::env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR must be set by Cargo");
60    let cache_dir = PathBuf::from(&manifest_dir).join(".js2zig-cache");
61
62    // All JS files are resolved from config (js_dir + js_files)
63    let js_dir: PathBuf = PathBuf::from(&manifest_dir).join(&config.project.js_dir);
64    let js_files = &config.project.js_files;
65
66    // Emit cargo:rerun-if-changed for explicitly listed JS files and config.
67    // Note: js2zig-core::transpile_project() additionally emits rerun-if-changed
68    // for every JS file it discovers via import analysis (including transitive
69    // dependencies like helpers.js).  Those directives take effect in subsequent
70    // builds because Cargo stores all rerun-if-changed paths from the previous
71    // build script run.
72    for f in js_files {
73        let p = js_dir.join(f);
74        println!("cargo:rerun-if-changed={}", p.display());
75    }
76    let config_toml = PathBuf::from(&manifest_dir).join("js2rust.toml");
77    println!("cargo:rerun-if-changed={}", config_toml.display());
78    // Watch the diagnostics tracking file so Cargo re-runs the build script
79    // when it is first created or changes.  This ensures the build script
80    // produces a CLEAN output (no cargo:warning) on the next run after the
81    // initial diagnostic emission, preventing Cargo from replaying stale
82    // warnings on cached builds.
83    let diagnostics_file = cache_dir.join(".last_emitted_diagnostics.json");
84    println!("cargo:rerun-if-changed={}", diagnostics_file.display());
85
86    let host_config = config.to_host_config().unwrap_or_else(|e| {
87        panic!("js2rust.toml configuration error: {}", e);
88    });
89
90    // Determine Zig optimization level: TOML override > Cargo PROFILE auto-detect.
91    let zig_optimize = config.build.zig_optimize.clone().unwrap_or_else(|| {
92        let profile = std::env::var("PROFILE").unwrap_or_else(|_| "debug".into());
93        if profile == "release" {
94            "ReleaseSafe".into()
95        } else {
96            "Debug".into()
97        }
98    });
99
100    let project_config = js2zig_core::ProjectConfig {
101        js_dir,
102        js_files: js_files.clone(),
103        out_dir: cache_dir.clone(),
104        host_config,
105        build: js2zig_core::BuildConfig {
106            force_rebuild: config.build.force_rebuild,
107            run_zig_build: config.build.run_zig_build,
108            zig_optimize: Some(zig_optimize),
109            is_build_script: true, // build.rs context — show progress + emit rerun-if-changed
110        },
111    };
112    match js2zig_core::transpile_project(&project_config) {
113        Ok(result) => {
114            // Emit compile errors as cargo:warning — but only when they CHANGE.
115            // Cargo replays cargo:warning from the previous build script run,
116            // so if we always emit them the user sees the same warnings on every
117            // build.  By tracking the last-emitted set and only emitting new/
118            // changed diagnostics, we produce a clean build script output once
119            // the diagnostics stabilize, and Cargo will replay that clean output
120            // on subsequent cached builds.
121            let compile_errors: Vec<&str> = result
122                .diagnostics
123                .iter()
124                .filter(|d| d.contains("COMPILE_ERROR"))
125                .map(|s| s.as_str())
126                .collect();
127
128            let last_emitted_path = cache_dir.join(".last_emitted_diagnostics.json");
129            let last_emitted: Vec<String> = std::fs::read_to_string(&last_emitted_path)
130                .ok()
131                .and_then(|s| serde_json::from_str(&s).ok())
132                .unwrap_or_default();
133
134            // Only emit warnings for diagnostics that differ from the last emission
135            if !compile_errors.iter().eq(last_emitted.iter()) {
136                for diag in &compile_errors {
137                    println!("cargo:warning=js2zig: {diag}");
138                }
139                // Persist current set so the next build can compare
140                if let Ok(json) = serde_json::to_string_pretty(&compile_errors) {
141                    let _ = std::fs::write(&last_emitted_path, json);
142                }
143            }
144
145            link_from_cache(&cache_dir);
146        }
147        Err(e) => {
148            panic!("js2rust_bridge::build: transpilation/zig build failed: {e}");
149        }
150    }
151}
152
153/// Fallback: scan `.js2zig-cache/` and emit link directives without running
154/// transpilation or zig build.  Used when the proc-macro already did the work.
155///
156/// Emits `cargo:rerun-if-changed` for the cache directory so Cargo re-runs
157/// the build script when the compiled libraries change.
158pub fn link() {
159    let manifest_dir =
160        std::env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR must be set by Cargo");
161    let cache_dir = PathBuf::from(&manifest_dir).join(".js2zig-cache");
162
163    // Re-run when compiled libraries appear or change.
164    if cache_dir.exists() {
165        println!("cargo:rerun-if-changed={}", cache_dir.display());
166    }
167
168    link_from_cache(&cache_dir);
169}
170
171/// Scan `.js2zig-cache/` for compiled static libraries and emit link directives.
172fn link_from_cache(cache_dir: &std::path::Path) {
173    if !cache_dir.exists() {
174        println!(
175            "cargo:warning=js2zig: .js2zig-cache not found. \
176             Run `cargo build` twice on a clean checkout."
177        );
178        return;
179    }
180
181    let mut found = false;
182    if let Ok(entries) = std::fs::read_dir(cache_dir) {
183        for entry in entries.flatten() {
184            let project_dir = entry.path();
185            let lib_dir = project_dir.join("zig-out").join("lib");
186
187            if lib_dir.exists()
188                && let Some(dir_name) = entry.file_name().to_str()
189            {
190                if dir_name == "host_regex.zig"
191                    || dir_name == "host_icu.zig"
192                    || dir_name == "host_regex_stubs.zig"
193                    || dir_name == "host_icu_stubs.zig"
194                {
195                    continue;
196                }
197                println!("cargo:rustc-link-search=native={}", lib_dir.display());
198                println!("cargo:rustc-link-lib=static={}", dir_name);
199                found = true;
200            }
201        }
202    }
203
204    if !found {
205        println!(
206            "cargo:warning=js2zig: no compiled libraries found in {}. \
207             Run `cargo build` twice on a clean checkout.",
208            cache_dir.display()
209        );
210    }
211}