Skip to main content

fallow_graph/resolve/
types.rs

1//! Type definitions and constants for import resolution.
2
3use std::path::{Path, PathBuf};
4use std::sync::Mutex;
5
6use oxc_resolver::Resolver;
7use rustc_hash::{FxHashMap, FxHashSet};
8
9use fallow_types::discover::FileId;
10
11/// Result of resolving an import specifier.
12#[derive(Debug, Clone)]
13pub enum ResolveResult {
14    /// Resolved to a file within the project.
15    InternalModule(FileId),
16    /// Resolved to a file outside the project (`node_modules`, `.json`, etc.).
17    ExternalFile(PathBuf),
18    /// Bare specifier — an npm package.
19    NpmPackage(String),
20    /// Could not resolve.
21    Unresolvable(String),
22}
23
24/// A resolved import with its target.
25#[derive(Debug, Clone)]
26pub struct ResolvedImport {
27    /// The original import information.
28    pub info: fallow_types::extract::ImportInfo,
29    /// Where the import resolved to.
30    pub target: ResolveResult,
31}
32
33/// A resolved re-export with its target.
34#[derive(Debug, Clone)]
35pub struct ResolvedReExport {
36    /// The original re-export information.
37    pub info: fallow_types::extract::ReExportInfo,
38    /// Where the re-export source resolved to.
39    pub target: ResolveResult,
40}
41
42/// Fully resolved module with all imports mapped to targets.
43#[derive(Debug)]
44pub struct ResolvedModule {
45    /// Unique file identifier.
46    pub file_id: FileId,
47    /// Absolute path to the module file.
48    pub path: PathBuf,
49    /// All export declarations in this module.
50    pub exports: Vec<fallow_types::extract::ExportInfo>,
51    /// All re-exports with resolved targets.
52    pub re_exports: Vec<ResolvedReExport>,
53    /// All static imports with resolved targets.
54    pub resolved_imports: Vec<ResolvedImport>,
55    /// All dynamic imports with resolved targets.
56    pub resolved_dynamic_imports: Vec<ResolvedImport>,
57    /// Dynamic import patterns matched against discovered files.
58    pub resolved_dynamic_patterns: Vec<(fallow_types::extract::DynamicImportPattern, Vec<FileId>)>,
59    /// Static member accesses (e.g., `Status.Active`).
60    pub member_accesses: Vec<fallow_types::extract::MemberAccess>,
61    /// Identifiers used as whole objects (Object.values, for..in, spread, etc.).
62    pub whole_object_uses: Vec<String>,
63    /// Whether this module uses `CommonJS` exports.
64    pub has_cjs_exports: bool,
65    /// Local names of import bindings that are never referenced in this file.
66    pub unused_import_bindings: FxHashSet<String>,
67    /// Local import bindings referenced from type positions.
68    pub type_referenced_import_bindings: Vec<String>,
69    /// Local import bindings referenced from runtime/value positions.
70    pub value_referenced_import_bindings: Vec<String>,
71}
72
73impl Default for ResolvedModule {
74    fn default() -> Self {
75        Self {
76            file_id: FileId(0),
77            path: PathBuf::new(),
78            exports: vec![],
79            re_exports: vec![],
80            resolved_imports: vec![],
81            resolved_dynamic_imports: vec![],
82            resolved_dynamic_patterns: vec![],
83            member_accesses: vec![],
84            whole_object_uses: vec![],
85            has_cjs_exports: false,
86            unused_import_bindings: FxHashSet::default(),
87            type_referenced_import_bindings: vec![],
88            value_referenced_import_bindings: vec![],
89        }
90    }
91}
92
93/// Shared context for resolving import specifiers.
94///
95/// Groups the immutable lookup tables and caches that are shared across all
96/// `resolve_specifier` calls within a single `resolve_all_imports` invocation.
97pub(super) struct ResolveContext<'a> {
98    /// The oxc_resolver instance (configured once, shared across threads).
99    pub resolver: &'a Resolver,
100    /// CSS-only resolver with the package.json `style` condition enabled.
101    /// Used only for stylesheet package subpaths so JS/TS imports do not
102    /// accidentally prefer CSS export branches.
103    pub style_resolver: &'a Resolver,
104    /// Ordered extension list used by the resolver.
105    pub extensions: &'a [String],
106    /// Canonical path → FileId lookup (raw paths when root is canonical).
107    pub path_to_id: &'a FxHashMap<&'a Path, FileId>,
108    /// Raw (non-canonical) path → FileId lookup.
109    pub raw_path_to_id: &'a FxHashMap<&'a Path, FileId>,
110    /// Workspace name → canonical root path.
111    pub workspace_roots: &'a FxHashMap<&'a str, &'a Path>,
112    /// Plugin-provided path aliases (prefix, replacement).
113    pub path_aliases: &'a [(String, String)],
114    /// Absolute directories to search when resolving bare SCSS/Sass
115    /// `@import` / `@use` specifiers. Populated from Angular's
116    /// `stylePreprocessorOptions.includePaths` and equivalent settings.
117    pub scss_include_paths: &'a [PathBuf],
118    /// Project root directory.
119    pub root: &'a Path,
120    /// Lazy canonical path → FileId fallback for intra-project symlinks.
121    /// Only initialized on first miss when root is canonical. `None` when
122    /// path_to_id already uses canonical paths (root is not canonical).
123    pub canonical_fallback: Option<&'a CanonicalFallback<'a>>,
124    /// Dedup set for broken-tsconfig warnings. Emits one `tracing::warn!`
125    /// per unique error message instead of spamming the log with one
126    /// warning per affected file. Shared across all parallel resolver
127    /// threads via `Mutex`. Empty and unused when no tsconfig errors occur.
128    pub tsconfig_warned: &'a Mutex<FxHashSet<String>>,
129}
130
131/// Thread-safe lazy canonical path index, built on first access.
132pub(super) struct CanonicalFallback<'a> {
133    files: &'a [fallow_types::discover::DiscoveredFile],
134    map: std::sync::OnceLock<FxHashMap<std::path::PathBuf, FileId>>,
135}
136
137impl<'a> CanonicalFallback<'a> {
138    pub const fn new(files: &'a [fallow_types::discover::DiscoveredFile]) -> Self {
139        Self {
140            files,
141            map: std::sync::OnceLock::new(),
142        }
143    }
144
145    /// Look up a canonical path, lazily building the index on first call.
146    pub fn get(&self, canonical: &Path) -> Option<FileId> {
147        let map = self.map.get_or_init(|| {
148            tracing::debug!(
149                "intra-project symlinks detected, building canonical path index ({} files)",
150                self.files.len()
151            );
152            self.files
153                .iter()
154                .filter_map(|f| {
155                    dunce::canonicalize(&f.path)
156                        .ok()
157                        .map(|canonical| (canonical, f.id))
158                })
159                .collect()
160        });
161        map.get(canonical).copied()
162    }
163}
164
165#[cfg(all(test, not(miri)))]
166mod tests {
167    use super::*;
168    use fallow_types::discover::DiscoveredFile;
169
170    #[test]
171    fn canonical_fallback_returns_none_for_empty_files() {
172        let files: Vec<DiscoveredFile> = vec![];
173        let fallback = CanonicalFallback::new(&files);
174        assert!(fallback.get(Path::new("/nonexistent")).is_none());
175    }
176
177    #[test]
178    fn canonical_fallback_finds_existing_file() {
179        let temp = std::env::temp_dir().join("fallow-test-canonical-fallback");
180        let _ = std::fs::create_dir_all(&temp);
181        let test_file = temp.join("test.ts");
182        std::fs::write(&test_file, "").unwrap();
183
184        let files = vec![DiscoveredFile {
185            id: FileId(42),
186            path: test_file.clone(),
187            size_bytes: 0,
188        }];
189        let fallback = CanonicalFallback::new(&files);
190
191        let canonical = dunce::canonicalize(&test_file).unwrap();
192        assert_eq!(fallback.get(&canonical), Some(FileId(42)));
193
194        // Second call uses cached map (OnceLock)
195        assert_eq!(fallback.get(&canonical), Some(FileId(42)));
196
197        let _ = std::fs::remove_dir_all(&temp);
198    }
199
200    #[test]
201    fn canonical_fallback_returns_none_for_missing_path() {
202        let temp = std::env::temp_dir().join("fallow-test-canonical-miss");
203        let _ = std::fs::create_dir_all(&temp);
204        let test_file = temp.join("exists.ts");
205        std::fs::write(&test_file, "").unwrap();
206
207        let files = vec![DiscoveredFile {
208            id: FileId(1),
209            path: test_file,
210            size_bytes: 0,
211        }];
212        let fallback = CanonicalFallback::new(&files);
213        assert!(fallback.get(Path::new("/nonexistent/file.ts")).is_none());
214
215        let _ = std::fs::remove_dir_all(&temp);
216    }
217}
218
219/// Known output directory names that may appear in exports map targets.
220/// When an exports map points to `./dist/utils.js`, we try replacing these
221/// prefixes with `src/` (the conventional source directory) to find the tracked
222/// source file.
223pub const OUTPUT_DIRS: &[&str] = &["dist", "build", "out", "esm", "cjs"];
224
225/// Source extensions to try when mapping a built output file back to source.
226pub const SOURCE_EXTS: &[&str] = &["ts", "tsx", "mts", "cts", "js", "jsx", "mjs", "cjs"];
227
228/// React Native platform extension prefixes.
229/// Metro resolves platform-specific files (e.g., `./foo` -> `./foo.web.tsx` on web).
230pub const RN_PLATFORM_PREFIXES: &[&str] = &[".web", ".ios", ".android", ".native"];