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    /// Namespace-import aliases re-exported through an object literal.
72    /// See `fallow_types::extract::NamespaceObjectAlias` for the shape.
73    pub namespace_object_aliases: Vec<fallow_types::extract::NamespaceObjectAlias>,
74}
75
76impl Default for ResolvedModule {
77    fn default() -> Self {
78        Self {
79            file_id: FileId(0),
80            path: PathBuf::new(),
81            exports: vec![],
82            re_exports: vec![],
83            resolved_imports: vec![],
84            resolved_dynamic_imports: vec![],
85            resolved_dynamic_patterns: vec![],
86            member_accesses: vec![],
87            whole_object_uses: vec![],
88            has_cjs_exports: false,
89            unused_import_bindings: FxHashSet::default(),
90            type_referenced_import_bindings: vec![],
91            value_referenced_import_bindings: vec![],
92            namespace_object_aliases: vec![],
93        }
94    }
95}
96
97impl ResolvedModule {
98    /// Iterate over all concrete resolved imports in source order buckets.
99    ///
100    /// Includes static `import`/`require` edges and literal dynamic `import()`
101    /// edges. Dynamic import patterns are intentionally excluded because they
102    /// resolve to sets of files rather than single import specifiers.
103    pub fn all_resolved_imports(&self) -> impl Iterator<Item = &ResolvedImport> {
104        self.resolved_imports
105            .iter()
106            .chain(self.resolved_dynamic_imports.iter())
107    }
108}
109
110/// Shared context for resolving import specifiers.
111///
112/// Groups the immutable lookup tables and caches that are shared across all
113/// `resolve_specifier` calls within a single `resolve_all_imports` invocation.
114pub(super) struct ResolveContext<'a> {
115    /// The oxc_resolver instance (configured once, shared across threads).
116    pub resolver: &'a Resolver,
117    /// CSS-only resolver with the package.json `style` condition enabled.
118    /// Used only for stylesheet package subpaths so JS/TS imports do not
119    /// accidentally prefer CSS export branches.
120    pub style_resolver: &'a Resolver,
121    /// Ordered extension list used by the resolver.
122    pub extensions: &'a [String],
123    /// Canonical path → FileId lookup (raw paths when root is canonical).
124    pub path_to_id: &'a FxHashMap<&'a Path, FileId>,
125    /// Raw (non-canonical) path → FileId lookup.
126    pub raw_path_to_id: &'a FxHashMap<&'a Path, FileId>,
127    /// Workspace name → canonical root path.
128    pub workspace_roots: &'a FxHashMap<&'a str, &'a Path>,
129    /// Plugin-provided path aliases (prefix, replacement).
130    pub path_aliases: &'a [(String, String)],
131    /// Absolute directories to search when resolving bare SCSS/Sass
132    /// `@import` / `@use` specifiers. Populated from Angular's
133    /// `stylePreprocessorOptions.includePaths` and equivalent settings.
134    pub scss_include_paths: &'a [PathBuf],
135    /// Project root directory.
136    pub root: &'a Path,
137    /// Lazy canonical path → FileId fallback for intra-project symlinks.
138    /// Only initialized on first miss when root is canonical. `None` when
139    /// path_to_id already uses canonical paths (root is not canonical).
140    pub canonical_fallback: Option<&'a CanonicalFallback<'a>>,
141    /// Dedup set for broken-tsconfig warnings. Emits one `tracing::warn!`
142    /// per unique error message instead of spamming the log with one
143    /// warning per affected file. Shared across all parallel resolver
144    /// threads via `Mutex`. Empty and unused when no tsconfig errors occur.
145    pub tsconfig_warned: &'a Mutex<FxHashSet<String>>,
146}
147
148/// Thread-safe lazy canonical path index, built on first access.
149pub(super) struct CanonicalFallback<'a> {
150    files: &'a [fallow_types::discover::DiscoveredFile],
151    map: std::sync::OnceLock<FxHashMap<std::path::PathBuf, FileId>>,
152}
153
154impl<'a> CanonicalFallback<'a> {
155    pub const fn new(files: &'a [fallow_types::discover::DiscoveredFile]) -> Self {
156        Self {
157            files,
158            map: std::sync::OnceLock::new(),
159        }
160    }
161
162    /// Look up a canonical path, lazily building the index on first call.
163    pub fn get(&self, canonical: &Path) -> Option<FileId> {
164        let map = self.map.get_or_init(|| {
165            tracing::debug!(
166                "intra-project symlinks detected, building canonical path index ({} files)",
167                self.files.len()
168            );
169            self.files
170                .iter()
171                .filter_map(|f| {
172                    dunce::canonicalize(&f.path)
173                        .ok()
174                        .map(|canonical| (canonical, f.id))
175                })
176                .collect()
177        });
178        map.get(canonical).copied()
179    }
180}
181
182#[cfg(all(test, not(miri)))]
183mod tests {
184    use super::*;
185    use fallow_types::discover::DiscoveredFile;
186
187    #[test]
188    fn canonical_fallback_returns_none_for_empty_files() {
189        let files: Vec<DiscoveredFile> = vec![];
190        let fallback = CanonicalFallback::new(&files);
191        assert!(fallback.get(Path::new("/nonexistent")).is_none());
192    }
193
194    #[test]
195    fn canonical_fallback_finds_existing_file() {
196        let temp = std::env::temp_dir().join("fallow-test-canonical-fallback");
197        let _ = std::fs::create_dir_all(&temp);
198        let test_file = temp.join("test.ts");
199        std::fs::write(&test_file, "").unwrap();
200
201        let files = vec![DiscoveredFile {
202            id: FileId(42),
203            path: test_file.clone(),
204            size_bytes: 0,
205        }];
206        let fallback = CanonicalFallback::new(&files);
207
208        let canonical = dunce::canonicalize(&test_file).unwrap();
209        assert_eq!(fallback.get(&canonical), Some(FileId(42)));
210
211        // Second call uses cached map (OnceLock)
212        assert_eq!(fallback.get(&canonical), Some(FileId(42)));
213
214        let _ = std::fs::remove_dir_all(&temp);
215    }
216
217    #[test]
218    fn canonical_fallback_returns_none_for_missing_path() {
219        let temp = std::env::temp_dir().join("fallow-test-canonical-miss");
220        let _ = std::fs::create_dir_all(&temp);
221        let test_file = temp.join("exists.ts");
222        std::fs::write(&test_file, "").unwrap();
223
224        let files = vec![DiscoveredFile {
225            id: FileId(1),
226            path: test_file,
227            size_bytes: 0,
228        }];
229        let fallback = CanonicalFallback::new(&files);
230        assert!(fallback.get(Path::new("/nonexistent/file.ts")).is_none());
231
232        let _ = std::fs::remove_dir_all(&temp);
233    }
234}
235
236/// Known output directory names that may appear in exports map targets.
237/// When an exports map points to `./dist/utils.js`, we try replacing these
238/// prefixes with `src/` (the conventional source directory) to find the tracked
239/// source file.
240pub const OUTPUT_DIRS: &[&str] = &["dist", "build", "out", "esm", "cjs"];
241
242/// Source extensions to try when mapping a built output file back to source.
243pub const SOURCE_EXTS: &[&str] = &["ts", "tsx", "mts", "cts", "js", "jsx", "mjs", "cjs"];
244
245/// React Native platform extension prefixes.
246/// Metro resolves platform-specific files (e.g., `./foo` -> `./foo.web.tsx` on web).
247pub const RN_PLATFORM_PREFIXES: &[&str] = &[".web", ".ios", ".android", ".native"];