Skip to main content

fallow_graph/resolve/
mod.rs

1//! Import specifier resolution using `oxc_resolver`.
2//!
3//! Orchestrates the resolution pipeline: for every extracted module, resolves all
4//! import specifiers in parallel (via rayon) to an [`ResolveResult`] — internal file,
5//! npm package, external file, or unresolvable. The entry point is [`resolve_all_imports`].
6//!
7//! Resolution is split into submodules by import kind:
8//! - `static_imports` — ES `import` declarations
9//! - `dynamic_imports` — `import()` expressions and glob-based dynamic patterns
10//! - `require_imports` — CommonJS `require()` calls
11//! - `re_exports` — `export { x } from './y'` re-export sources
12//! - `upgrades` — post-resolution pass fixing non-deterministic bare specifier results
13//!
14//! Handles tsconfig path aliases (auto-discovered per file), pnpm virtual store paths,
15//! React Native platform extensions, and package.json `exports` subpath resolution with
16//! output-to-source directory fallback.
17
18mod dynamic_imports;
19pub(crate) mod fallbacks;
20mod path_info;
21mod re_exports;
22mod react_native;
23mod require_imports;
24mod specifier;
25mod static_imports;
26#[cfg(test)]
27mod tests;
28mod types;
29mod upgrades;
30
31pub use fallbacks::extract_package_name_from_node_modules_path;
32pub use path_info::{extract_package_name, is_bare_specifier, is_path_alias};
33pub use types::{ResolveResult, ResolvedImport, ResolvedModule, ResolvedReExport};
34
35use std::path::{Path, PathBuf};
36use std::sync::Mutex;
37
38use rayon::prelude::*;
39use rustc_hash::{FxHashMap, FxHashSet};
40
41use fallow_types::discover::{DiscoveredFile, FileId};
42use fallow_types::extract::ModuleInfo;
43
44use dynamic_imports::{resolve_dynamic_imports, resolve_dynamic_patterns};
45use re_exports::resolve_re_exports;
46use require_imports::resolve_require_imports;
47use specifier::create_resolver;
48use static_imports::resolve_static_imports;
49use types::ResolveContext;
50use upgrades::apply_specifier_upgrades;
51
52/// Resolve all imports across all modules in parallel.
53#[must_use]
54#[expect(
55    clippy::too_many_arguments,
56    reason = "resolver inputs come from disjoint sources (config, plugins, workspace, filesystem); \
57              bundling them into a struct would be a cross-cutting refactor outside this task"
58)]
59pub fn resolve_all_imports(
60    modules: &[ModuleInfo],
61    files: &[DiscoveredFile],
62    workspaces: &[fallow_config::WorkspaceInfo],
63    active_plugins: &[String],
64    path_aliases: &[(String, String)],
65    scss_include_paths: &[PathBuf],
66    root: &Path,
67    extra_conditions: &[String],
68) -> Vec<ResolvedModule> {
69    // Build workspace name → root index for pnpm store fallback.
70    // Canonicalize roots to match path_to_id (which uses canonical paths).
71    // Without this, macOS /var → /private/var and similar platform symlinks
72    // cause workspace roots to mismatch canonical file paths.
73    let canonical_ws_roots: Vec<PathBuf> = workspaces
74        .par_iter()
75        .map(|ws| dunce::canonicalize(&ws.root).unwrap_or_else(|_| ws.root.clone()))
76        .collect();
77    let workspace_roots: FxHashMap<&str, &Path> = workspaces
78        .iter()
79        .zip(canonical_ws_roots.iter())
80        .map(|(ws, canonical)| (ws.name.as_str(), canonical.as_path()))
81        .collect();
82
83    // Check if project root is already canonical (no symlinks in path).
84    // When true, raw paths == canonical paths for files under root, so we can skip
85    // the upfront bulk canonicalize() of all source files (21k+ syscalls on large projects).
86    // A lazy CanonicalFallback handles the rare intra-project symlink case.
87    let root_is_canonical = dunce::canonicalize(root).is_ok_and(|c| c == root);
88
89    // Pre-compute canonical paths ONCE for all files in parallel (avoiding repeated syscalls).
90    // Skipped when root is canonical — the lazy fallback below handles edge cases.
91    let canonical_paths: Vec<PathBuf> = if root_is_canonical {
92        Vec::new()
93    } else {
94        files
95            .par_iter()
96            .map(|f| dunce::canonicalize(&f.path).unwrap_or_else(|_| f.path.clone()))
97            .collect()
98    };
99
100    // Primary path → FileId index. When root is canonical, uses raw paths (fast).
101    // Otherwise uses pre-computed canonical paths (correct for all symlink configurations).
102    let path_to_id: FxHashMap<&Path, FileId> = if root_is_canonical {
103        files.iter().map(|f| (f.path.as_path(), f.id)).collect()
104    } else {
105        canonical_paths
106            .iter()
107            .enumerate()
108            .map(|(idx, canonical)| (canonical.as_path(), files[idx].id))
109            .collect()
110    };
111
112    // Also index by non-canonical path for fallback lookups
113    let raw_path_to_id: FxHashMap<&Path, FileId> =
114        files.iter().map(|f| (f.path.as_path(), f.id)).collect();
115
116    // FileIds are sequential 0..n, so direct array indexing is faster than FxHashMap.
117    let file_paths: Vec<&Path> = files.iter().map(|f| f.path.as_path()).collect();
118
119    // Create resolver ONCE and share across threads (oxc_resolver::Resolver is Send + Sync)
120    let resolver = create_resolver(active_plugins, extra_conditions);
121
122    // Lazy canonical fallback — only needed when root is canonical (path_to_id uses raw paths).
123    // When root is NOT canonical, path_to_id already uses canonical paths, no fallback needed.
124    let canonical_fallback = if root_is_canonical {
125        Some(types::CanonicalFallback::new(files))
126    } else {
127        None
128    };
129
130    // Dedup set for broken-tsconfig warnings. See `ResolveContext::tsconfig_warned`.
131    let tsconfig_warned: Mutex<FxHashSet<String>> = Mutex::new(FxHashSet::default());
132
133    // Shared resolution context — avoids passing 6 arguments to every resolve_specifier call
134    let ctx = ResolveContext {
135        resolver: &resolver,
136        path_to_id: &path_to_id,
137        raw_path_to_id: &raw_path_to_id,
138        workspace_roots: &workspace_roots,
139        path_aliases,
140        scss_include_paths,
141        root,
142        canonical_fallback: canonical_fallback.as_ref(),
143        tsconfig_warned: &tsconfig_warned,
144    };
145
146    // Resolve in parallel — shared resolver instance.
147    // Each file resolves its own imports independently (no shared bare specifier cache).
148    // oxc_resolver's internal caches (package.json, tsconfig, directory entries) are
149    // shared across threads for performance.
150    let mut resolved: Vec<ResolvedModule> = modules
151        .par_iter()
152        .filter_map(|module| {
153            let Some(file_path) = file_paths.get(module.file_id.0 as usize) else {
154                tracing::warn!(
155                    file_id = module.file_id.0,
156                    "Skipping module with unknown file_id during resolution"
157                );
158                return None;
159            };
160
161            let mut all_imports = resolve_static_imports(&ctx, file_path, &module.imports);
162            all_imports.extend(resolve_require_imports(
163                &ctx,
164                file_path,
165                &module.require_calls,
166            ));
167
168            let from_dir = if canonical_paths.is_empty() {
169                // Root is canonical — raw paths are canonical
170                file_path.parent().unwrap_or(file_path)
171            } else {
172                canonical_paths
173                    .get(module.file_id.0 as usize)
174                    .and_then(|p| p.parent())
175                    .unwrap_or(file_path)
176            };
177
178            Some(ResolvedModule {
179                file_id: module.file_id,
180                path: file_path.to_path_buf(),
181                exports: module.exports.clone(),
182                re_exports: resolve_re_exports(&ctx, file_path, &module.re_exports),
183                resolved_imports: all_imports,
184                resolved_dynamic_imports: resolve_dynamic_imports(
185                    &ctx,
186                    file_path,
187                    &module.dynamic_imports,
188                ),
189                resolved_dynamic_patterns: resolve_dynamic_patterns(
190                    from_dir,
191                    &module.dynamic_import_patterns,
192                    &canonical_paths,
193                    files,
194                ),
195                member_accesses: module.member_accesses.clone(),
196                whole_object_uses: module.whole_object_uses.clone(),
197                has_cjs_exports: module.has_cjs_exports,
198                unused_import_bindings: module.unused_import_bindings.iter().cloned().collect(),
199                type_referenced_import_bindings: module.type_referenced_import_bindings.clone(),
200                value_referenced_import_bindings: module.value_referenced_import_bindings.clone(),
201            })
202        })
203        .collect();
204
205    apply_specifier_upgrades(&mut resolved);
206
207    resolved
208}