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}
68
69impl Default for ResolvedModule {
70    fn default() -> Self {
71        Self {
72            file_id: FileId(0),
73            path: PathBuf::new(),
74            exports: vec![],
75            re_exports: vec![],
76            resolved_imports: vec![],
77            resolved_dynamic_imports: vec![],
78            resolved_dynamic_patterns: vec![],
79            member_accesses: vec![],
80            whole_object_uses: vec![],
81            has_cjs_exports: false,
82            unused_import_bindings: FxHashSet::default(),
83        }
84    }
85}
86
87/// Shared context for resolving import specifiers.
88///
89/// Groups the immutable lookup tables and caches that are shared across all
90/// `resolve_specifier` calls within a single `resolve_all_imports` invocation.
91pub(super) struct ResolveContext<'a> {
92    /// The oxc_resolver instance (configured once, shared across threads).
93    pub resolver: &'a Resolver,
94    /// Canonical path → FileId lookup (raw paths when root is canonical).
95    pub path_to_id: &'a FxHashMap<&'a Path, FileId>,
96    /// Raw (non-canonical) path → FileId lookup.
97    pub raw_path_to_id: &'a FxHashMap<&'a Path, FileId>,
98    /// Workspace name → canonical root path.
99    pub workspace_roots: &'a FxHashMap<&'a str, &'a Path>,
100    /// Plugin-provided path aliases (prefix, replacement).
101    pub path_aliases: &'a [(String, String)],
102    /// Project root directory.
103    pub root: &'a Path,
104    /// Lazy canonical path → FileId fallback for intra-project symlinks.
105    /// Only initialized on first miss when root is canonical. `None` when
106    /// path_to_id already uses canonical paths (root is not canonical).
107    pub canonical_fallback: Option<&'a CanonicalFallback<'a>>,
108    /// Dedup set for broken-tsconfig warnings. Emits one `tracing::warn!`
109    /// per unique error message instead of spamming the log with one
110    /// warning per affected file. Shared across all parallel resolver
111    /// threads via `Mutex`. Empty and unused when no tsconfig errors occur.
112    pub tsconfig_warned: &'a Mutex<FxHashSet<String>>,
113}
114
115/// Thread-safe lazy canonical path index, built on first access.
116pub(super) struct CanonicalFallback<'a> {
117    files: &'a [fallow_types::discover::DiscoveredFile],
118    map: std::sync::OnceLock<FxHashMap<std::path::PathBuf, FileId>>,
119}
120
121impl<'a> CanonicalFallback<'a> {
122    pub const fn new(files: &'a [fallow_types::discover::DiscoveredFile]) -> Self {
123        Self {
124            files,
125            map: std::sync::OnceLock::new(),
126        }
127    }
128
129    /// Look up a canonical path, lazily building the index on first call.
130    pub fn get(&self, canonical: &Path) -> Option<FileId> {
131        let map = self.map.get_or_init(|| {
132            tracing::debug!(
133                "intra-project symlinks detected — building canonical path index ({} files)",
134                self.files.len()
135            );
136            self.files
137                .iter()
138                .filter_map(|f| {
139                    dunce::canonicalize(&f.path)
140                        .ok()
141                        .map(|canonical| (canonical, f.id))
142                })
143                .collect()
144        });
145        map.get(canonical).copied()
146    }
147}
148
149#[cfg(all(test, not(miri)))]
150mod tests {
151    use super::*;
152    use fallow_types::discover::DiscoveredFile;
153
154    #[test]
155    fn canonical_fallback_returns_none_for_empty_files() {
156        let files: Vec<DiscoveredFile> = vec![];
157        let fallback = CanonicalFallback::new(&files);
158        assert!(fallback.get(Path::new("/nonexistent")).is_none());
159    }
160
161    #[test]
162    fn canonical_fallback_finds_existing_file() {
163        let temp = std::env::temp_dir().join("fallow-test-canonical-fallback");
164        let _ = std::fs::create_dir_all(&temp);
165        let test_file = temp.join("test.ts");
166        std::fs::write(&test_file, "").unwrap();
167
168        let files = vec![DiscoveredFile {
169            id: FileId(42),
170            path: test_file.clone(),
171            size_bytes: 0,
172        }];
173        let fallback = CanonicalFallback::new(&files);
174
175        let canonical = dunce::canonicalize(&test_file).unwrap();
176        assert_eq!(fallback.get(&canonical), Some(FileId(42)));
177
178        // Second call uses cached map (OnceLock)
179        assert_eq!(fallback.get(&canonical), Some(FileId(42)));
180
181        let _ = std::fs::remove_dir_all(&temp);
182    }
183
184    #[test]
185    fn canonical_fallback_returns_none_for_missing_path() {
186        let temp = std::env::temp_dir().join("fallow-test-canonical-miss");
187        let _ = std::fs::create_dir_all(&temp);
188        let test_file = temp.join("exists.ts");
189        std::fs::write(&test_file, "").unwrap();
190
191        let files = vec![DiscoveredFile {
192            id: FileId(1),
193            path: test_file,
194            size_bytes: 0,
195        }];
196        let fallback = CanonicalFallback::new(&files);
197        assert!(fallback.get(Path::new("/nonexistent/file.ts")).is_none());
198
199        let _ = std::fs::remove_dir_all(&temp);
200    }
201}
202
203/// Known output directory names that may appear in exports map targets.
204/// When an exports map points to `./dist/utils.js`, we try replacing these
205/// prefixes with `src/` (the conventional source directory) to find the tracked
206/// source file.
207pub const OUTPUT_DIRS: &[&str] = &["dist", "build", "out", "esm", "cjs"];
208
209/// Source extensions to try when mapping a built output file back to source.
210pub const SOURCE_EXTS: &[&str] = &["ts", "tsx", "mts", "cts", "js", "jsx", "mjs", "cjs"];
211
212/// React Native platform extension prefixes.
213/// Metro resolves platform-specific files (e.g., `./foo` -> `./foo.web.tsx` on web).
214pub const RN_PLATFORM_PREFIXES: &[&str] = &[".web", ".ios", ".android", ".native"];