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();
87
88    // Determine Zig optimization level: TOML override > Cargo PROFILE auto-detect.
89    let zig_optimize = config.build.zig_optimize.clone().unwrap_or_else(|| {
90        let profile = std::env::var("PROFILE").unwrap_or_else(|_| "debug".into());
91        if profile == "release" {
92            "ReleaseSafe".into()
93        } else {
94            "Debug".into()
95        }
96    });
97
98    let project_config = js2zig_core::ProjectConfig {
99        js_dir,
100        js_files: js_files.clone(),
101        out_dir: cache_dir.clone(),
102        host_config,
103        build: js2zig_core::BuildConfig {
104            force_rebuild: config.build.force_rebuild,
105            run_zig_build: config.build.run_zig_build,
106            zig_optimize: Some(zig_optimize),
107            is_build_script: true, // build.rs context — show progress + emit rerun-if-changed
108        },
109    };
110    match js2zig_core::transpile_project(&project_config) {
111        Ok(result) => {
112            // Emit compile errors as cargo:warning — but only when they CHANGE.
113            // Cargo replays cargo:warning from the previous build script run,
114            // so if we always emit them the user sees the same warnings on every
115            // build.  By tracking the last-emitted set and only emitting new/
116            // changed diagnostics, we produce a clean build script output once
117            // the diagnostics stabilize, and Cargo will replay that clean output
118            // on subsequent cached builds.
119            let compile_errors: Vec<&str> = result
120                .diagnostics
121                .iter()
122                .filter(|d| d.contains("COMPILE_ERROR"))
123                .map(|s| s.as_str())
124                .collect();
125
126            let last_emitted_path = cache_dir.join(".last_emitted_diagnostics.json");
127            let last_emitted: Vec<String> = std::fs::read_to_string(&last_emitted_path)
128                .ok()
129                .and_then(|s| serde_json::from_str(&s).ok())
130                .unwrap_or_default();
131
132            // Only emit warnings for diagnostics that differ from the last emission
133            if !compile_errors.iter().eq(last_emitted.iter()) {
134                for diag in &compile_errors {
135                    println!("cargo:warning=js2zig: {diag}");
136                }
137                // Persist current set so the next build can compare
138                if let Ok(json) = serde_json::to_string_pretty(&compile_errors) {
139                    let _ = std::fs::write(&last_emitted_path, json);
140                }
141            }
142
143            link_from_cache(&cache_dir);
144        }
145        Err(e) => {
146            panic!("js2rust_bridge::build: transpilation/zig build failed: {e}");
147        }
148    }
149}
150
151/// Fallback: scan `.js2zig-cache/` and emit link directives without running
152/// transpilation or zig build.  Used when the proc-macro already did the work.
153///
154/// Emits `cargo:rerun-if-changed` for the cache directory so Cargo re-runs
155/// the build script when the compiled libraries change.
156pub fn link() {
157    let manifest_dir =
158        std::env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR must be set by Cargo");
159    let cache_dir = PathBuf::from(&manifest_dir).join(".js2zig-cache");
160
161    // Re-run when compiled libraries appear or change.
162    if cache_dir.exists() {
163        println!("cargo:rerun-if-changed={}", cache_dir.display());
164    }
165
166    link_from_cache(&cache_dir);
167}
168
169/// Scan `.js2zig-cache/` for compiled static libraries and emit link directives.
170fn link_from_cache(cache_dir: &std::path::Path) {
171    if !cache_dir.exists() {
172        println!(
173            "cargo:warning=js2zig: .js2zig-cache not found. \
174             Run `cargo build` twice on a clean checkout."
175        );
176        return;
177    }
178
179    let mut found = false;
180    if let Ok(entries) = std::fs::read_dir(cache_dir) {
181        for entry in entries.flatten() {
182            let project_dir = entry.path();
183            let lib_dir = project_dir.join("zig-out").join("lib");
184
185            if lib_dir.exists()
186                && let Some(dir_name) = entry.file_name().to_str()
187            {
188                if dir_name == "host_regex.zig"
189                    || dir_name == "host_icu.zig"
190                    || dir_name == "host_regex_stubs.zig"
191                    || dir_name == "host_icu_stubs.zig"
192                {
193                    continue;
194                }
195                println!("cargo:rustc-link-search=native={}", lib_dir.display());
196                println!("cargo:rustc-link-lib=static={}", dir_name);
197                found = true;
198            }
199        }
200    }
201
202    if !found {
203        println!(
204            "cargo:warning=js2zig: no compiled libraries found in {}. \
205             Run `cargo build` twice on a clean checkout.",
206            cache_dir.display()
207        );
208    }
209}