Keep module roles when dependency imports repeat (R3.12) (#1617)

A package with 52 reachable modules loses the final module's role when each hop repeats the same `require()` 2,000 times. The graph resolves those imports, but role propagation charges its 100,000-step limit for duplicate queue entries, eventually leaving reachable modules as `unknown`. Mark modules in the existing role map before enqueueing them. Repeated imports, cycles and shared dependencies then use one queue entry per newly discovered module. The limit remains 100,000 newly discovered modules per assignment, and the existing main/preload/renderer/page/worker precedence stays intact. Inline scripts continue to inherit their page's role.
This commit is contained in:
Afloat authored and GitHub committed 2026-11-11 13:42:34 +07:00
1 parent 0757863ece
commit 439dae070e
4 files changed
+84 -9

No files matched your search

+17 -9
View File
@@ -511,22 +511,30 @@ pub fn analyze_application(input: &AppInput, opts: &AppOptions, cancelled: &dyn
let pages: Vec<String> = if has_electron { Vec::new() } else { analysed.iter().filter(|a| a.html.is_some()).map(|a| a.path.clone()).collect() };
let assign = |roots: &[String], role: &str, roles: &mut HashMap<String, String>| {
let mut q: VecDeque<String> = roots.iter().cloned().collect();
let mut seen = 0usize;
while let Some(p) = q.pop_front() {
seen += 1;
if seen > 100_000 || roles.contains_key(&p) {
continue;
let mut q = VecDeque::new();
let mut remaining = 100_000usize;
let mut enqueue = |p: &str, q: &mut VecDeque<String>, roles: &mut HashMap<String, String>| {
if remaining == 0 || roles.contains_key(p) {
return;
}
roles.insert(p.clone(), role.to_string());
remaining -= 1;
// Mark discovered modules before enqueueing: repeated imports must not
// consume the traversal budget or grow the queue with duplicate paths.
roles.insert(p.to_string(), role.to_string());
q.push_back(p.to_string());
};
for p in roots {
enqueue(p, &mut q, roles);
}
while let Some(p) = q.pop_front() {
for imp in resolved_imports.get(&p).into_iter().flatten() {
if let Some(r) = &imp.resolved {
q.push_back(r.clone());
enqueue(r, &mut q, roles);
}
}
// Inline scripts of a page share its role.
for a in analysed.iter().filter(|a| a.host.as_deref() == Some(p.as_str())) {
q.push_back(a.path.clone());
enqueue(&a.path, &mut q, roles);
}
}
};
@@ -0,0 +1,64 @@
use craft_anything_analysis::js_app::{AppFile, AppInput, AppOptions, analyze_application};
fn graph_of(files: Vec<(&str, String)>) -> craft_anything_analysis::js_app::AppGraph {
let files: Vec<_> = files.into_iter().map(|(path, source)| AppFile { path: path.into(), bytes: source.into_bytes() }).collect();
let listing = files.iter().map(|file| (file.path.clone(), file.bytes.len() as u64)).collect();
let input = AppInput { label: "role-fixture".into(), format: "directory".into(), files, listing, notes: vec![] };
analyze_application(&input, &AppOptions::default(), &|| false).unwrap()
}
#[test]
fn repeated_imports_do_not_exhaust_role_propagation_before_reachable_modules() {
let paths: Vec<_> = (0..52).map(|index| format!("module{index}.js")).collect();
let mut files = vec![("package.json", r#"{"name":"role-fixture","main":"module0.js"}"#.to_string())];
for (index, path) in paths.iter().enumerate() {
let source = if let Some(next) = paths.get(index + 1) { format!("require('./{next}');\n").repeat(2_000) } else { "module.exports = 1;".to_string() };
files.push((path, source));
}
let graph = graph_of(files);
assert_eq!(graph.modules.len(), paths.len());
assert_eq!(graph.module("module50.js").unwrap().imports.len(), 2_000);
for path in paths {
assert_eq!(graph.module(&path).unwrap().role, "package", "reachable module {path}");
}
}
#[test]
fn cycles_and_shared_children_keep_reachable_roles_without_claiming_orphans() {
let graph = graph_of(vec![
("package.json", r#"{"name":"roles","main":"main.js"}"#.into()),
("main.js", "require('./left.js'); require('./right.js');".into()),
("left.js", "require('./shared.js'); require('./main.js');".into()),
("right.js", "require('./shared.js');".into()),
("shared.js", "module.exports = 1;".into()),
("orphan.js", "module.exports = 2;".into()),
]);
for path in ["main.js", "left.js", "right.js", "shared.js"] {
assert_eq!(graph.module(path).unwrap().role, "package");
}
assert_eq!(graph.module("orphan.js").unwrap().role, "unknown");
}
#[test]
fn main_preload_and_renderer_roles_keep_their_existing_precedence() {
let graph = graph_of(vec![
("package.json", r#"{"name":"roles","main":"main.js","dependencies":{"electron":"1"}}"#.into()),
("main.js", "const { BrowserWindow } = require('electron'); require('./shared.js'); const win = new BrowserWindow({webPreferences:{preload:'preload.js'}}); win.loadFile('page.html');".into()),
("preload.js", "require('./shared.js'); require('./preload-only.js');".into()),
("preload-only.js", "module.exports = 1;".into()),
("shared.js", "module.exports = 2;".into()),
("page.html", "<script>require('./renderer-only.js');</script>".into()),
("renderer-only.js", "module.exports = 3;".into()),
]);
for (path, role) in [
("main.js", "main"),
("shared.js", "main"),
("preload.js", "preload"),
("preload-only.js", "preload"),
("page.html", "renderer"),
("page.html#inline-0", "renderer"),
("renderer-only.js", "renderer"),
] {
assert_eq!(graph.module(path).unwrap().role, role, "module {path}");
}
}
+2
View File
@@ -1595,6 +1595,8 @@ Owner: open · Status: in progress
- [x] Read the explicit module-format byte in current Node SEA blobs while retaining the older layouts;
report the stored format and recover the main script, assets and execution arguments at their real offsets.
— claimed: Afloat16, branch bugfix/r3.12-node-sea-module-format-20261110
- [x] Deduplicate modules before queueing role propagation, so repeated imports do not exhaust the application graph's traversal limit before reachable modules receive their roles.
— claimed: Afloat16, branch bugfix/r3.12-module-role-queue
- [x] Resolve webpack module-loader calls by the wrapper parameter's binding, so nested parameters and local variables with the same name do not create dependency edges.
— claimed: Afloat16, branch bugfix/r3.12-webpack-require-bindings
- [x] Keep sequence splitting from introducing JavaScript strict-mode directives.
+1
View File
@@ -250,6 +250,7 @@ coverage and secrets passed. The companion CLI was built with locked dependencie
| Source map lookup on long lines | Binary-search sorted section starts and segment columns. A lookup examines only the matching positions, while preserving duplicates and unmapped boundaries. | Regression cases added: A repeated lookup fixture and equal-column and unmapped boundary cases. |
| Numeric bundle identities | Recovered numeric module keys, loader references, browserify dependency mappings and chunk IDs use JavaScript number spelling. Equivalent numeric literals connect to one module identity, while string IDs retain their exact spelling. | Synthetic hexadecimal, binary, octal, separator and exponent literals, array tables, browserify maps, chunk IDs and downstream application-graph edges. Decimal and repeated-load controls, existing JS unit tests and esbuild-budget tests pass; no real application was run for this correction. |
| Webpack module-loader bindings | Module dependencies and application-graph edges follow the wrapper's loader binding. Nested parameters, block variables and catch bindings with the same name do not become module loads; closures that capture the loader keep their dependencies. | Synthetic function, arrow and chunk wrappers, destructured parameters, duplicate calls and application-graph edges. Existing JS unit and esbuild-budget tests also pass. Sources above the existing 16 MiB semantic-analysis limit retain name-based resolution; no real application was run for this correction. |
| App-map role traversal | Reachable modules keep their inferred role when many imports repeat the same dependency. The traversal and queue are bounded by distinct newly discovered modules, with the existing role precedence. | Public application-graph fixtures cover 52 modules with 2,000 repeated imports per hop, cycles, shared children, orphans, and main/preload/renderer/inline-script roles. Synthetic inputs 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. Ordinary calls do not consume the 4096-wrapper dependency budget, including when the wrapper is declared later | 50 JS tests pass. Synthetic regressions cover short names, forward declarations, both wrapper kinds and function/arrow bodies, shadowed parameters, reused names, unrelated calls and duplicates. Public analysis fixtures include 4096 distinct ordinary calls before a wrapper dependency and 4097 real wrapper dependencies to check the cap and first-seen order. 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 (Rust names across toolchains too, with the crate hash left out), `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 |
| Native function body evidence | Reference listings and function dossiers include code blocks below the entry while excluding unrelated code in gaps. Pseudo-C infers its entry-block arguments from the actual entry, not the lowest-address block. | Real engine calls on an ELF fixture with a backward conditional branch, a referenced string and import, an unrelated function in the gap, and a forward-layout control. Three checks fail before the correction; the control passes. |