Skip to content

Craft Anything: understand how any software works, and craft your own.

Rust

Minified esbuild modules keep their dependencies (R0.5) (#438)

Afloat89bcd061905d
diff --git a/crates/js/src/bundle.rs b/crates/js/src/bundle.rs
index 82155502..80fa5ccd 100644
--- a/crates/js/src/bundle.rs
+++ b/crates/js/src/bundle.rs
@@ -3,25 +3,28 @@
//! esbuild (`__commonJS` / `__esm` wrappers, minified or not) and browserify. Scope-hoisted
//! bundles (Rollup, Vite production chunks) have no module boundaries left to recover.
+use crate::facts::Key;
use crate::fingerprint::Fingerprint;
use crate::model::{BundleInfo, BundleModule};
use crate::util::{LineIndex, sha256_hex, slice};
use oxc_ast::ast::*;
use oxc_ast_visit::{Visit, walk};
+use oxc_semantic::Scoping;
use oxc_syntax::scope::ScopeFlags;
-use std::collections::HashMap;
+use std::collections::{HashMap, HashSet};
pub const MAX_MODULES: usize = 50_000;
pub(crate) struct BundleVisitor<'s> {
src: &'s str,
lines: &'s LineIndex,
+ scoping: Option<&'s Scoping>,
webpack_hint: bool,
pub info: BundleInfo,
- /// esbuild wrapper variable → module id, for dependency resolution.
- esbuild_vars: HashMap<String, String>,
- /// Raw esbuild deps (wrapper variable names) per module index.
- esbuild_raw: Vec<(usize, Vec<String>)>,
+ /// esbuild wrapper binding → module id, for dependency resolution.
+ esbuild_vars: HashMap<Key, String>,
+ /// Raw esbuild deps (callee bindings) per module index.
+ esbuild_raw: Vec<(usize, Vec<Key>)>,
}
/// A function-ish table value.
@@ -76,8 +79,10 @@ impl Func<'_, '_> {
/// Collects calls to the module's `require` parameter and esbuild wrapper calls.
struct DepVisitor<'n> {
require_name: Option<&'n str>,
+ scoping: Option<&'n Scoping>,
deps: Vec<String>,
- esbuild: Vec<String>,
+ esbuild: Vec<Key>,
+ esbuild_seen: HashSet<Key>,
}
impl<'a> Visit<'a> for DepVisitor<'_> {
@@ -96,8 +101,18 @@ impl<'a> Visit<'a> for DepVisitor<'_> {
{
self.deps.push(d);
}
- } else if (n.starts_with("require_") || n.starts_with("init_")) && it.arguments.is_empty() && self.esbuild.len() < 4096 {
- self.esbuild.push(n.to_string());
+ } else if it.arguments.is_empty() && self.esbuild.len() < 4096 {
+ // Minifiers rename the wrapper. Resolve by binding, not by its spelling, so a
+ // short name also works without confusing a local parameter with the wrapper.
+ let key = match self.scoping {
+ Some(sc) => id.reference_id.get().and_then(|rid| sc.get_reference(rid).symbol_id()).map(Key::Sym),
+ None => Some(Key::Name(n.to_string())),
+ };
+ if let Some(key) = key
+ && self.esbuild_seen.insert(key.clone())
+ {
+ self.esbuild.push(key);
+ }
}
}
walk::walk_call_expression(self, it);
@@ -105,8 +120,8 @@ impl<'a> Visit<'a> for DepVisitor<'_> {
}
impl<'s> BundleVisitor<'s> {
- pub fn new(src: &'s str, lines: &'s LineIndex, webpack_hint: bool) -> Self {
- BundleVisitor { src, lines, webpack_hint, info: BundleInfo::default(), esbuild_vars: HashMap::new(), esbuild_raw: Vec::new() }
+ pub fn new(src: &'s str, lines: &'s LineIndex, webpack_hint: bool, scoping: Option<&'s Scoping>) -> Self {
+ BundleVisitor { src, lines, scoping, webpack_hint, info: BundleInfo::default(), esbuild_vars: HashMap::new(), esbuild_raw: Vec::new() }
}
/// Resolve esbuild wrapper calls to module ids once every wrapper is known.
@@ -136,7 +151,8 @@ impl<'s> BundleVisitor<'s> {
"browserify" => params.first().cloned(),
_ => None,
};
- let mut dv = DepVisitor { require_name: require_name.as_deref(), deps: Vec::new(), esbuild: Vec::new() };
+ let mut dv =
+ DepVisitor { require_name: require_name.as_deref(), scoping: self.scoping, deps: Vec::new(), esbuild: Vec::new(), esbuild_seen: HashSet::new() };
let mut fp = Fingerprint::new();
match f {
Func::Function(func) => {
@@ -301,8 +317,12 @@ impl<'a> Visit<'a> for BundleVisitor<'_> {
if let Some(Expression::CallExpression(call)) = it.init.as_ref().map(|e| e.get_inner_expression())
&& let Some((key, f, kind)) = Self::esbuild_wrapper(call)
{
- if let Some(var) = it.id.get_identifier_name() {
- self.esbuild_vars.insert(var.to_string(), key.clone());
+ if let BindingPattern::BindingIdentifier(var) = &it.id {
+ let binding = match (self.scoping, var.symbol_id.get()) {
+ (Some(_), Some(symbol)) => Key::Sym(symbol),
+ _ => Key::Name(var.name.to_string()),
+ };
+ self.esbuild_vars.insert(binding, key.clone());
}
self.add(key, kind, &[], &f);
return;
diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs
index ca3b76c6..6e79448b 100644
--- a/crates/js/src/lib.rs
+++ b/crates/js/src/lib.rs
@@ -231,7 +231,7 @@ fn parse_and_visit(src: &str, st: SourceType) -> Option<Analysis> {
fp.visit_program(&ret.program);
facts.fingerprint = Some(fp.finish());
let webpack_hint = facts.bundler_markers.keys().any(|k| k.contains("webpack"));
- let mut bv = bundle::BundleVisitor::new(src, &lines, webpack_hint);
+ let mut bv = bundle::BundleVisitor::new(src, &lines, webpack_hint, scoping);
bv.visit_program(&ret.program);
let bundle = bv.finish();
Some(Analysis { facts, bundle })
diff --git a/crates/js/src/tests.rs b/crates/js/src/tests.rs
index bcbf56db..63685f27 100644
--- a/crates/js/src/tests.rs
+++ b/crates/js/src/tests.rs
@@ -130,6 +130,59 @@ fn esbuild_bundle_is_split() {
assert_eq!(main.deps, vec!["src/util.js"]);
}
+#[test]
+fn minified_esbuild_wrappers_keep_dependencies() {
+ let minified = fx::ESBUILD_BUNDLE.replace("require_util", "a").replace("require_main", "b");
+ let a = run("out.js", &minified);
+ assert_eq!(a.facts.parse_errors, 0);
+ assert_eq!(a.bundle.modules.len(), 2);
+ let main = a.bundle.modules.iter().find(|m| m.id == "src/main.js").unwrap();
+ assert_eq!(main.format, "esbuild-cjs");
+ assert_eq!(main.deps, ["src/util.js"]);
+
+ // Resolve after visiting the whole file: an initializer may be declared later.
+ let source = r#"
+var m = h({"src/main.js"(exports, module) { u(); i(); }});
+var u = h({"src/util.js"(exports, module) { module.exports = 7; }});
+var i = h({"src/setup.js"() { globalThis.ready = true; }});
+"#;
+ let a = run("out.js", source);
+ assert_eq!(a.facts.parse_errors, 0);
+ assert_eq!(a.bundle.modules.len(), 3);
+ assert_eq!(a.bundle.modules.iter().find(|m| m.id == "src/main.js").unwrap().deps, ["src/util.js", "src/setup.js"]);
+ assert_eq!(a.bundle.modules.iter().find(|m| m.id == "src/setup.js").unwrap().format, "esbuild-esm");
+}
+
+#[test]
+fn esbuild_wrapper_dependencies_follow_bindings() {
+ let source = r#"
+var a = h({"src/outer.js"(exports, module) { module.exports = 1; }});
+var b = h({"src/main.js"(exports, module) { a(); }});
+function anotherBundle() {
+ var a = h({"src/inner.js"(exports, module) { module.exports = 2; }});
+ var b = h({"src/other.js"(exports, module) { a(); }});
+}
+var s = h({"src/shadow.js"(exports, module) { function local(a) { a(); } }});
+"#;
+ let a = run("out.js", source);
+ assert_eq!(a.facts.parse_errors, 0);
+ let deps = |id| &a.bundle.modules.iter().find(|m| m.id == id).unwrap().deps;
+ assert_eq!(deps("src/main.js"), &["src/outer.js"]);
+ assert_eq!(deps("src/other.js"), &["src/inner.js"]);
+ assert!(deps("src/shadow.js").is_empty(), "a local parameter is not a wrapper call");
+}
+
+#[test]
+fn esbuild_dependencies_ignore_unrecognised_and_repeated_calls() {
+ let source = r#"
+var a = h({"src/util.js"(exports, module) { module.exports = 1; }});
+var b = h({"src/main.js"(exports, module) { a(); a(); unknown(); require_external(); a(1); }});
+"#;
+ let a = run("out.js", source);
+ assert_eq!(a.facts.parse_errors, 0);
+ assert_eq!(a.bundle.modules.iter().find(|m| m.id == "src/main.js").unwrap().deps, ["src/util.js"]);
+}
+
#[test]
fn fingerprints_ignore_names() {
let a = run("a.js", "function f(a, b) { return a + b * 2; }").facts.fingerprint;
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index bf0288cc..bc9ada4a 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -170,6 +170,7 @@ Owner: open · Status: done (branch chore/r0.5-cleanups)
- [x] Class-usage search includes the component class of multidimensional object arrays (#325).
- [x] Missing `database` icon for SQLite in the UI (`kind_icon`)
- [x] Deduplicate the five private `fn spec(` helpers in the tool modules
+- [x] Keep dependencies between recognised esbuild wrappers after identifier minification (#270).
- [x] rustfmt drift on main (11 files)
- [x] Checked arithmetic on file offsets in `fsread/extfs.rs`: an inode offset near `usize::MAX`
overflows `o + 128` (two sites), found by a lint scan of `crates/formats` (#42)
diff --git a/docs/STATUS.md b/docs/STATUS.md
index ef4abed0..771e15b1 100644
--- a/docs/STATUS.md
+++ b/docs/STATUS.md
@@ -14,6 +14,7 @@ workspace clippy, layers, fmt and the secret scan of all history were clean. Chi
| Engine | 298 engine tools (314 with the AI and setup layers') across native, managed, Java, Android, Apple, JS/Electron, web, firmware, packets, databases, game archives and assets; see [tools.md](tools.md) and [tool-status.md](tool-status.md). A saved result can be narrowed without running again (`core_evidence_browse` keeps the rows matching given field values, cut to chosen fields) | A functional audit that ran every tool on real inputs on Windows, plus 600+ unit and integration tests |
| Java class usage | `java_class_users_find` includes the component class of multidimensional object arrays; primitive-array descriptors do not match an unrelated class with the same descriptor letter | Synthetic class files parsed by the built-in reader: one- and two-dimensional allocations, class names beginning with `L`, primitive arrays, hit limits and method filters; formats tests. This correction was not checked with javac output or a JVM |
| Single-file apps and game files | `core_packed_files_list` and `core_packed_files_unpack` read Bun and Node.js single-file programs, .NET single-file apps, PyInstaller and Godot packs through one seam (`formats::packed`); `formats_bytecode_show` reads Python bytecode, `game_unity_code_names_show` Unity IL2CPP metadata, `formats_ai_weights_show` GGUF and safetensors headers. `app_folder_explain` says what an install folder is made with and what to run next | Unit tests with damaged files. Real files: a 279 MB Bun program, Node blobs, PyInstaller programs (Python 3.9, 3.14), .NET 8 single-file apps (macOS, Linux, Windows, compressed), Godot 3.6, 4.3 and 4.5 packs, 214 Python modules against CPython's own reader, a GGUF and a safetensors file, about 25 installed Mac apps. IL2CPP on synthetic files only |
+| esbuild module dependencies | Recognised CommonJS and ESM wrappers keep their dependency edges after identifier minification; semantic bindings distinguish shadowed and reused names, and repeated calls produce one edge | 44 JS unit tests pass. New synthetic regressions cover short names, forward declarations, both wrapper kinds, shadowed parameters, reused names, unrelated calls and duplicates. No real minified application was run for this correction; sources above the existing semantic-analysis size limit retain name-based resolution |
| Program facts across builds | `native_library_calls_list` (delay-load too), `native_offered_symbols_list`, `native_publisher_show` (checks the file hash and the signature, not Windows trust), `app_builds_line_up` pairs functions across two builds and says how, `native_source_folder_write` writes pseudo-C to a folder and picks up where it stopped, `android_components_list` | Unit tests. Real PE, ELF and Mach-O files; two builds of a 276 MB program; a signed Microsoft DLL; Android components from one real APK, spot-checked |
| ARM32 value flow | A32 and Thumb calls define ARM scratch registers, and word results flow through `r0` into returns in `native_value_flow_show` | Synthetic instruction fixtures for leaf results and indirect calls in both modes, with AArch64 and x86-64 controls; disassembler tests. This correction was not checked on real ARM binaries or devices |
| Stand-in backends | `web_standin_build` turns a HAR into `standin.json` (secrets dropped, varying path parts templated); `web_standin_start` answers from it on loopback; `web_standin_show` lists what it had no answer for. Writes replay what was recorded and don't change later reads. App maps list GraphQL and tRPC operations; `web_walkthrough_check` checks a scripted session without a browser | Unit tests, real loopback requests, and a run with curl on a hand-written HAR. No browser-made recording or real front end yet |