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 react_native::{build_condition_names, build_extensions};
47use require_imports::resolve_require_imports;
48use specifier::create_resolver;
49use static_imports::resolve_static_imports;
50use types::{PackageManifestInfo, ResolveContext};
51use upgrades::apply_specifier_upgrades;
52
53/// Resolve all imports across all modules in parallel.
54#[must_use]
55#[expect(
56    clippy::too_many_arguments,
57    reason = "resolver inputs come from disjoint sources (config, plugins, workspace, filesystem); \
58              bundling them into a struct would be a cross-cutting refactor outside this task"
59)]
60pub fn resolve_all_imports(
61    modules: &[ModuleInfo],
62    files: &[DiscoveredFile],
63    workspaces: &[fallow_config::WorkspaceInfo],
64    active_plugins: &[String],
65    path_aliases: &[(String, String)],
66    scss_include_paths: &[PathBuf],
67    root: &Path,
68    extra_conditions: &[String],
69) -> Vec<ResolvedModule> {
70    // Build workspace name → root index for pnpm store fallback.
71    // Canonicalize roots to match path_to_id (which uses canonical paths).
72    // Without this, macOS /var → /private/var and similar platform symlinks
73    // cause workspace roots to mismatch canonical file paths.
74    let canonical_ws_roots: Vec<PathBuf> = workspaces
75        .par_iter()
76        .map(|ws| dunce::canonicalize(&ws.root).unwrap_or_else(|_| ws.root.clone()))
77        .collect();
78    let workspace_roots: FxHashMap<&str, &Path> = workspaces
79        .iter()
80        .zip(canonical_ws_roots.iter())
81        .map(|(ws, canonical)| (ws.name.as_str(), canonical.as_path()))
82        .collect();
83    let root_canonical = dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
84    let mut package_manifests = Vec::new();
85    if let Ok(package_json) = fallow_config::PackageJson::load(&root.join("package.json")) {
86        package_manifests.push(PackageManifestInfo {
87            root: root.to_path_buf(),
88            canonical_root: root_canonical,
89            name: package_json.name.clone(),
90            package_json,
91        });
92    }
93    for (ws, canonical_root) in workspaces.iter().zip(canonical_ws_roots.iter()) {
94        if let Ok(package_json) = fallow_config::PackageJson::load(&ws.root.join("package.json")) {
95            package_manifests.push(PackageManifestInfo {
96                root: ws.root.clone(),
97                canonical_root: canonical_root.clone(),
98                name: package_json.name.clone().or_else(|| Some(ws.name.clone())),
99                package_json,
100            });
101        }
102    }
103
104    // Check if project root is already canonical (no symlinks in path).
105    // When true, raw paths == canonical paths for files under root, so we can skip
106    // the upfront bulk canonicalize() of all source files (21k+ syscalls on large projects).
107    // A lazy CanonicalFallback handles the rare intra-project symlink case.
108    let root_is_canonical = dunce::canonicalize(root).is_ok_and(|c| c == root);
109
110    // Pre-compute canonical paths ONCE for all files in parallel (avoiding repeated syscalls).
111    // Skipped when root is canonical — the lazy fallback below handles edge cases.
112    let canonical_paths: Vec<PathBuf> = if root_is_canonical {
113        Vec::new()
114    } else {
115        files
116            .par_iter()
117            .map(|f| dunce::canonicalize(&f.path).unwrap_or_else(|_| f.path.clone()))
118            .collect()
119    };
120
121    // Primary path → FileId index. When root is canonical, uses raw paths (fast).
122    // Otherwise uses pre-computed canonical paths (correct for all symlink configurations).
123    let path_to_id: FxHashMap<&Path, FileId> = if root_is_canonical {
124        files.iter().map(|f| (f.path.as_path(), f.id)).collect()
125    } else {
126        canonical_paths
127            .iter()
128            .enumerate()
129            .map(|(idx, canonical)| (canonical.as_path(), files[idx].id))
130            .collect()
131    };
132
133    // Also index by non-canonical path for fallback lookups
134    let raw_path_to_id: FxHashMap<&Path, FileId> =
135        files.iter().map(|f| (f.path.as_path(), f.id)).collect();
136
137    // FileIds are sequential 0..n, so direct array indexing is faster than FxHashMap.
138    let file_paths: Vec<&Path> = files.iter().map(|f| f.path.as_path()).collect();
139
140    // Create resolvers ONCE and share across threads (oxc_resolver::Resolver is Send + Sync).
141    let extensions = build_extensions(active_plugins);
142    let condition_names = build_condition_names(active_plugins, extra_conditions);
143    let resolver = create_resolver(active_plugins, extra_conditions);
144    let mut style_conditions = extra_conditions.to_vec();
145    style_conditions.push("style".to_string());
146    let style_resolver = create_resolver(active_plugins, &style_conditions);
147
148    // Lazy canonical fallback — only needed when root is canonical (path_to_id uses raw paths).
149    // When root is NOT canonical, path_to_id already uses canonical paths, no fallback needed.
150    let canonical_fallback = if root_is_canonical {
151        Some(types::CanonicalFallback::new(files))
152    } else {
153        None
154    };
155
156    // Dedup set for broken-tsconfig warnings. See `ResolveContext::tsconfig_warned`.
157    let tsconfig_warned: Mutex<FxHashSet<String>> = Mutex::new(FxHashSet::default());
158
159    // Shared resolution context — avoids passing 6 arguments to every resolve_specifier call
160    let ctx = ResolveContext {
161        resolver: &resolver,
162        style_resolver: &style_resolver,
163        extensions: &extensions,
164        path_to_id: &path_to_id,
165        raw_path_to_id: &raw_path_to_id,
166        workspace_roots: &workspace_roots,
167        package_manifests: &package_manifests,
168        condition_names: &condition_names,
169        path_aliases,
170        scss_include_paths,
171        root,
172        canonical_fallback: canonical_fallback.as_ref(),
173        tsconfig_warned: &tsconfig_warned,
174    };
175
176    // Resolve in parallel — shared resolver instance.
177    // Each file resolves its own imports independently (no shared bare specifier cache).
178    // oxc_resolver's internal caches (package.json, tsconfig, directory entries) are
179    // shared across threads for performance.
180    let mut resolved: Vec<ResolvedModule> = modules
181        .par_iter()
182        .filter_map(|module| {
183            let Some(file_path) = file_paths.get(module.file_id.0 as usize) else {
184                tracing::warn!(
185                    file_id = module.file_id.0,
186                    "Skipping module with unknown file_id during resolution"
187                );
188                return None;
189            };
190
191            let mut all_imports = resolve_static_imports(&ctx, file_path, &module.imports);
192            all_imports.extend(resolve_require_imports(
193                &ctx,
194                file_path,
195                &module.require_calls,
196            ));
197
198            let from_dir = if canonical_paths.is_empty() {
199                // Root is canonical — raw paths are canonical
200                file_path.parent().unwrap_or(file_path)
201            } else {
202                canonical_paths
203                    .get(module.file_id.0 as usize)
204                    .and_then(|p| p.parent())
205                    .unwrap_or(file_path)
206            };
207
208            Some(ResolvedModule {
209                file_id: module.file_id,
210                path: file_path.to_path_buf(),
211                exports: module.exports.clone(),
212                re_exports: resolve_re_exports(&ctx, file_path, &module.re_exports),
213                resolved_imports: all_imports,
214                resolved_dynamic_imports: resolve_dynamic_imports(
215                    &ctx,
216                    file_path,
217                    &module.dynamic_imports,
218                ),
219                resolved_dynamic_patterns: resolve_dynamic_patterns(
220                    from_dir,
221                    &module.dynamic_import_patterns,
222                    &canonical_paths,
223                    files,
224                ),
225                member_accesses: module.member_accesses.clone(),
226                whole_object_uses: module.whole_object_uses.clone(),
227                has_cjs_exports: module.has_cjs_exports,
228                has_angular_component_template_url: module.has_angular_component_template_url,
229                unused_import_bindings: module.unused_import_bindings.iter().cloned().collect(),
230                type_referenced_import_bindings: module.type_referenced_import_bindings.clone(),
231                value_referenced_import_bindings: module.value_referenced_import_bindings.clone(),
232                namespace_object_aliases: module.namespace_object_aliases.clone(),
233            })
234        })
235        .collect();
236
237    apply_specifier_upgrades(&mut resolved);
238
239    resolved
240}