1use std::path::{Path, PathBuf};
4use std::sync::{Arc, Mutex};
5
6use dashmap::DashMap;
7use rustc_hash::{FxBuildHasher, FxHashMap, FxHashSet};
8use serde_json::Value;
9
10use fallow_config::TsconfigOutputMap;
11use fallow_types::discover::FileId;
12
13use crate::read_trace::Resolver;
14
15#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
17pub enum ResolveResult {
18 InternalModule(FileId),
20 CommonJsInternalModule(FileId),
22 SyntheticAutoImport(FileId),
24 InternalPackageModule {
27 file_id: FileId,
29 package_name: String,
31 },
32 CommonJsInternalPackageModule {
34 file_id: FileId,
36 package_name: String,
38 },
39 ExternalFile(PathBuf),
41 NpmPackage(String),
43 CommonJsNpmPackage(String),
45 Unresolvable(String),
47}
48
49impl ResolveResult {
50 #[must_use]
52 pub const fn internal_file_id(&self) -> Option<FileId> {
53 match self {
54 Self::InternalModule(file_id)
55 | Self::CommonJsInternalModule(file_id)
56 | Self::SyntheticAutoImport(file_id)
57 | Self::InternalPackageModule { file_id, .. }
58 | Self::CommonJsInternalPackageModule { file_id, .. } => Some(*file_id),
59 Self::ExternalFile(_)
60 | Self::NpmPackage(_)
61 | Self::CommonJsNpmPackage(_)
62 | Self::Unresolvable(_) => None,
63 }
64 }
65
66 #[must_use]
68 pub const fn is_synthetic_auto_import(&self) -> bool {
69 matches!(self, Self::SyntheticAutoImport(_))
70 }
71
72 #[must_use]
74 pub(crate) const fn is_commonjs_require(&self) -> bool {
75 matches!(
76 self,
77 Self::CommonJsInternalModule(_)
78 | Self::CommonJsInternalPackageModule { .. }
79 | Self::CommonJsNpmPackage(_)
80 )
81 }
82
83 #[must_use]
85 pub const fn is_bare_package(&self) -> bool {
86 matches!(self, Self::NpmPackage(_) | Self::CommonJsNpmPackage(_))
87 }
88
89 #[must_use]
91 pub(crate) fn into_commonjs_require(self) -> Self {
92 match self {
93 Self::InternalModule(file_id) => Self::CommonJsInternalModule(file_id),
94 Self::InternalPackageModule {
95 file_id,
96 package_name,
97 } => Self::CommonJsInternalPackageModule {
98 file_id,
99 package_name,
100 },
101 Self::NpmPackage(package_name) => Self::CommonJsNpmPackage(package_name),
102 other => other,
103 }
104 }
105
106 #[must_use]
108 pub fn package_usage_name(&self) -> Option<&str> {
109 match self {
110 Self::InternalPackageModule { package_name, .. }
111 | Self::CommonJsInternalPackageModule { package_name, .. }
112 | Self::NpmPackage(package_name)
113 | Self::CommonJsNpmPackage(package_name) => Some(package_name),
114 Self::InternalModule(_)
115 | Self::CommonJsInternalModule(_)
116 | Self::SyntheticAutoImport(_)
117 | Self::ExternalFile(_)
118 | Self::Unresolvable(_) => None,
119 }
120 }
121}
122
123#[derive(Debug, Default)]
125pub struct ResolvedProject {
126 pub modules: Vec<ResolvedModule>,
128 pub replaced_module_targets: Vec<ResolvedReplacedModuleTarget>,
130 pub work: super::ResolveWork,
133 pub missed_probes: crate::missed_probes::MissedProbes,
137 pub package_manifests: Vec<String>,
143}
144
145#[derive(Debug, Clone, Copy, PartialEq, Eq)]
147pub struct ResolvedReplacedModuleTarget {
148 pub source_file: FileId,
150 pub target_file: FileId,
152}
153
154#[derive(Debug, Clone)]
156pub struct ResolvedImport {
157 pub info: fallow_types::extract::ImportInfo,
159 pub target: ResolveResult,
161}
162
163#[derive(Debug, Clone)]
165pub struct ResolvedReExport {
166 pub info: fallow_types::extract::ReExportInfo,
168 pub target: ResolveResult,
170}
171
172pub enum ResolvedSourceEdge<'a> {
174 Import(&'a ResolvedImport),
176 ReExport(&'a ResolvedReExport),
178}
179
180impl<'a> ResolvedSourceEdge<'a> {
181 #[must_use]
183 pub fn source_specifier(&self) -> &'a str {
184 match self {
185 Self::Import(import) => &import.info.source,
186 Self::ReExport(re_export) => &re_export.info.source,
187 }
188 }
189
190 #[must_use]
192 pub const fn target(&self) -> &'a ResolveResult {
193 match self {
194 Self::Import(import) => &import.target,
195 Self::ReExport(re_export) => &re_export.target,
196 }
197 }
198
199 #[must_use]
201 pub const fn is_type_only(&self) -> bool {
202 match self {
203 Self::Import(import) => import.info.is_type_only,
204 Self::ReExport(re_export) => re_export.info.is_type_only,
205 }
206 }
207
208 #[must_use]
210 pub const fn span(&self) -> oxc_span::Span {
211 match self {
212 Self::Import(import) => import.info.span,
213 Self::ReExport(re_export) => re_export.info.span,
214 }
215 }
216
217 #[must_use]
219 pub const fn source_span(&self) -> oxc_span::Span {
220 match self {
221 Self::Import(import) => import.info.source_span,
222 Self::ReExport(re_export) => re_export.info.source_span,
223 }
224 }
225
226 #[must_use]
231 pub const fn statement_span(&self) -> oxc_span::Span {
232 match self {
233 Self::Import(import) => import.info.span,
234 Self::ReExport(re_export) => re_export.info.statement_span,
235 }
236 }
237}
238
239#[derive(Debug, Clone)]
245pub struct ResolvedModule {
246 pub file_id: FileId,
248 pub path: PathBuf,
250 pub exports: Arc<[fallow_types::extract::ExportInfo]>,
252 pub re_exports: Vec<ResolvedReExport>,
254 pub resolved_imports: Vec<ResolvedImport>,
256 pub resolved_dynamic_imports: Vec<ResolvedImport>,
258 pub resolved_dynamic_patterns: Vec<(fallow_types::extract::DynamicImportPattern, Vec<FileId>)>,
260 pub member_accesses: Arc<[fallow_types::extract::MemberAccess]>,
262 pub semantic_facts: Arc<[fallow_types::extract::SemanticFact]>,
264 pub whole_object_uses: Arc<[String]>,
266 pub has_cjs_exports: bool,
268 pub has_angular_component_template_url: bool,
272 pub unused_import_bindings: FxHashSet<String>,
274 pub type_referenced_import_bindings: Vec<String>,
276 pub value_referenced_import_bindings: Vec<String>,
278 pub namespace_object_aliases: Vec<fallow_types::extract::NamespaceObjectAlias>,
281 pub exported_factory_returns: Arc<[fallow_types::extract::FactoryReturnExport]>,
284 pub exported_factory_return_object_shapes:
288 Arc<[fallow_types::extract::FactoryReturnObjectShapeExport]>,
289 pub type_member_types: Arc<[fallow_types::extract::TypeMemberTypeEntry]>,
293 pub missing_export_targets: Vec<MissingExportTarget>,
298}
299
300#[derive(Debug, Clone, PartialEq, Eq)]
307pub struct ScopedPathAlias {
308 pub scope: String,
311 pub prefix: String,
313 pub replacement: String,
315}
316
317#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
320pub struct MissingExportTarget {
321 pub specifier: String,
323 pub paths: Vec<PathBuf>,
325}
326
327impl Default for ResolvedModule {
328 fn default() -> Self {
329 Self {
330 file_id: FileId(0),
331 path: PathBuf::new(),
332 exports: Arc::default(),
333 re_exports: vec![],
334 resolved_imports: vec![],
335 resolved_dynamic_imports: vec![],
336 resolved_dynamic_patterns: vec![],
337 member_accesses: Arc::default(),
338 semantic_facts: Arc::default(),
339 whole_object_uses: Arc::default(),
340 has_cjs_exports: false,
341 has_angular_component_template_url: false,
342 unused_import_bindings: FxHashSet::default(),
343 type_referenced_import_bindings: vec![],
344 value_referenced_import_bindings: vec![],
345 namespace_object_aliases: vec![],
346 exported_factory_returns: Arc::default(),
347 exported_factory_return_object_shapes: Arc::default(),
348 type_member_types: Arc::default(),
349 missing_export_targets: vec![],
350 }
351 }
352}
353
354impl ResolvedModule {
355 pub fn all_resolved_imports(&self) -> impl Iterator<Item = &ResolvedImport> {
361 self.resolved_imports
362 .iter()
363 .chain(self.resolved_dynamic_imports.iter())
364 }
365
366 pub fn all_resolved_source_edges(&self) -> impl Iterator<Item = ResolvedSourceEdge<'_>> {
372 self.resolved_imports
373 .iter()
374 .map(ResolvedSourceEdge::Import)
375 .chain(
376 self.resolved_dynamic_imports
377 .iter()
378 .map(ResolvedSourceEdge::Import),
379 )
380 .chain(self.re_exports.iter().map(ResolvedSourceEdge::ReExport))
381 }
382}
383
384pub(super) struct ResolveContext<'a> {
389 pub resolver: &'a Resolver,
391 pub script_resolver: &'a Resolver,
394 pub style_resolver: &'a Resolver,
398 pub extensions: &'a [String],
400 pub path_to_id: &'a FxHashMap<&'a Path, FileId>,
402 pub raw_path_to_id: &'a FxHashMap<&'a Path, FileId>,
404 pub workspace_roots: &'a FxHashMap<&'a str, &'a Path>,
406 pub package_manifests: &'a [PackageManifestInfo],
408 pub has_deno_import_maps: bool,
411 pub condition_names: &'a [String],
413 pub path_aliases: &'a [(String, String)],
415 pub scoped_path_aliases: &'a [ScopedPathAlias],
417 pub scss_include_paths: &'a [PathBuf],
421 pub static_dir_mappings: &'a [(PathBuf, String)],
424 pub framework_static_dir_mappings: &'a [(PathBuf, String)],
428 pub root: &'a Path,
430 pub canonical_fallback: Option<&'a CanonicalFallback<'a>>,
434 pub tsconfig_warned: &'a Mutex<FxHashSet<String>>,
439 pub tsconfig_cache: &'a TsconfigCache,
444 pub canonicalize_cache: &'a CanonicalizeCache,
451}
452
453#[derive(Default)]
455pub(super) struct CanonicalizeCache {
456 map: DashMap<PathBuf, Option<PathBuf>, FxBuildHasher>,
457}
458
459impl CanonicalizeCache {
460 pub fn get(&self, path: &Path) -> Option<PathBuf> {
464 if let Some(value) = self.map.get(path) {
465 return value.clone();
466 }
467 let value = crate::read_trace::canonicalize(path).ok();
468 self.map.insert(path.to_path_buf(), value.clone());
469 value
470 }
471
472 pub fn distinct_paths(&self) -> usize {
476 self.map.len()
477 }
478}
479
480#[derive(Default)]
482pub(super) struct TsconfigCache {
483 json: DashMap<PathBuf, Option<Arc<Value>>, FxBuildHasher>,
484 chains: DashMap<PathBuf, Arc<[PathBuf]>, FxBuildHasher>,
485 output_maps: DashMap<PathBuf, Arc<TsconfigOutputMap>, FxBuildHasher>,
486}
487
488impl TsconfigCache {
489 pub fn json(
496 &self,
497 path: &Path,
498 load: impl FnOnce(&Path) -> Option<Value>,
499 ) -> Option<Arc<Value>> {
500 if let Some(value) = self.json.get(path) {
501 return value.clone();
502 }
503
504 let value = load(path).map(Arc::new);
505 self.json.insert(path.to_path_buf(), value.clone());
506 value
507 }
508
509 pub fn chain(&self, from_file: &Path) -> Option<Arc<[PathBuf]>> {
511 self.chains.get(from_file).map(|entry| Arc::clone(&entry))
512 }
513
514 pub fn store_chain(&self, from_file: &Path, chain: Arc<[PathBuf]>) {
516 self.chains.insert(from_file.to_path_buf(), chain);
517 }
518
519 pub fn output_map(&self, package_root: &Path) -> Arc<TsconfigOutputMap> {
522 if let Some(map) = self.output_maps.get(package_root) {
523 return Arc::clone(&map);
524 }
525 let map = Arc::new(TsconfigOutputMap::from_project(package_root));
526 self.output_maps
527 .insert(package_root.to_path_buf(), Arc::clone(&map));
528 map
529 }
530}
531
532#[derive(Debug, Clone)]
534pub(super) struct PackageManifestInfo {
535 pub root: PathBuf,
537 pub canonical_root: PathBuf,
539 pub name: Option<String>,
541 pub package_json: fallow_config::PackageJson,
543 pub deno_import_map: Vec<DenoImportMapEntry>,
545}
546
547#[derive(Debug, Clone)]
549pub(super) struct DenoImportMapEntry {
550 pub key: String,
551 pub target: String,
552 pub declaring_dir: PathBuf,
553}
554
555pub(super) struct CanonicalFallback<'a> {
557 files: &'a [fallow_types::discover::DiscoveredFile],
558 map: std::sync::OnceLock<FxHashMap<std::path::PathBuf, FileId>>,
559}
560
561impl<'a> CanonicalFallback<'a> {
562 pub const fn new(files: &'a [fallow_types::discover::DiscoveredFile]) -> Self {
563 Self {
564 files,
565 map: std::sync::OnceLock::new(),
566 }
567 }
568
569 pub fn get(&self, canonical: &Path) -> Option<FileId> {
571 let map = self.map.get_or_init(|| {
572 super::work::note_canonicalize(self.files.len() as u64);
573 tracing::debug!(
574 "intra-project symlinks detected, building canonical path index ({} files)",
575 self.files.len()
576 );
577 self.files
578 .iter()
579 .filter_map(|f| {
580 crate::read_trace::canonicalize(&f.path)
581 .ok()
582 .map(|canonical| (canonical, f.id))
583 })
584 .collect()
585 });
586 map.get(canonical).copied()
587 }
588}
589
590#[cfg(all(test, not(miri)))]
591mod tests {
592 use super::*;
593 use fallow_types::discover::DiscoveredFile;
594
595 #[test]
596 fn canonical_fallback_returns_none_for_empty_files() {
597 let files: Vec<DiscoveredFile> = vec![];
598 let fallback = CanonicalFallback::new(&files);
599 assert!(fallback.get(Path::new("/nonexistent")).is_none());
600 }
601
602 #[test]
603 fn canonical_fallback_finds_existing_file() {
604 let temp = std::env::temp_dir().join("fallow-test-canonical-fallback");
605 let _ = std::fs::create_dir_all(&temp);
606 let test_file = temp.join("test.ts");
607 std::fs::write(&test_file, "").unwrap();
608
609 let files = vec![DiscoveredFile {
610 id: FileId(42),
611 path: test_file.clone(),
612 size_bytes: 0,
613 }];
614 let fallback = CanonicalFallback::new(&files);
615
616 let canonical = dunce::canonicalize(&test_file).unwrap();
617 assert_eq!(fallback.get(&canonical), Some(FileId(42)));
618
619 assert_eq!(fallback.get(&canonical), Some(FileId(42)));
620
621 let _ = std::fs::remove_dir_all(&temp);
622 }
623
624 #[test]
625 fn canonical_fallback_returns_none_for_missing_path() {
626 let temp = std::env::temp_dir().join("fallow-test-canonical-miss");
627 let _ = std::fs::create_dir_all(&temp);
628 let test_file = temp.join("exists.ts");
629 std::fs::write(&test_file, "").unwrap();
630
631 let files = vec![DiscoveredFile {
632 id: FileId(1),
633 path: test_file,
634 size_bytes: 0,
635 }];
636 let fallback = CanonicalFallback::new(&files);
637 assert!(fallback.get(Path::new("/nonexistent/file.ts")).is_none());
638
639 let _ = std::fs::remove_dir_all(&temp);
640 }
641
642 #[test]
643 fn tsconfig_cache_loads_once_and_shares_the_parsed_document() {
644 let cache = TsconfigCache::default();
645 let path = Path::new("/project/tsconfig.json");
646 let loads = std::sync::atomic::AtomicUsize::new(0);
647 let load = |_: &Path| {
648 loads.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
649 Some(serde_json::json!({ "compilerOptions": {} }))
650 };
651
652 let first = cache.json(path, load).unwrap();
653 let second = cache.json(path, load).unwrap();
654
655 assert_eq!(loads.load(std::sync::atomic::Ordering::SeqCst), 1);
656 assert!(
657 Arc::ptr_eq(&first, &second),
658 "repeat reads must share one allocation rather than deep-copy"
659 );
660 }
661
662 #[test]
664 fn tsconfig_cache_caches_a_failed_load() {
665 let cache = TsconfigCache::default();
666 let path = Path::new("/project/missing.json");
667 let loads = std::sync::atomic::AtomicUsize::new(0);
668 let load = |_: &Path| {
669 loads.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
670 None
671 };
672
673 assert!(cache.json(path, load).is_none());
674 assert!(cache.json(path, load).is_none());
675 assert_eq!(loads.load(std::sync::atomic::Ordering::SeqCst), 1);
676 }
677
678 #[test]
679 fn tsconfig_cache_round_trips_a_chain() {
680 let cache = TsconfigCache::default();
681 let from_file = Path::new("/project/src/index.ts");
682 assert!(cache.chain(from_file).is_none());
683
684 let chain: Arc<[PathBuf]> = vec![PathBuf::from("/project/tsconfig.json")].into();
685 cache.store_chain(from_file, Arc::clone(&chain));
686
687 assert!(Arc::ptr_eq(&cache.chain(from_file).unwrap(), &chain));
688 }
689
690 #[test]
692 fn tsconfig_cache_is_consistent_under_concurrent_access() {
693 const THREADS: usize = 8;
694 const PATHS: usize = 32;
695
696 let cache = TsconfigCache::default();
697 std::thread::scope(|scope| {
698 for _ in 0..THREADS {
699 scope.spawn(|| {
700 for index in 0..PATHS {
701 let path = PathBuf::from(format!("/project/{index}/tsconfig.json"));
702 let json = cache
703 .json(&path, |_| Some(serde_json::json!({ "index": index })))
704 .unwrap();
705 assert_eq!(json["index"], index);
706 }
707 });
708 }
709 });
710 }
711
712 #[test]
713 fn canonicalize_cache_returns_the_same_result_on_repeat_lookups() {
714 let temp = tempfile::tempdir().expect("create temp dir");
715 let file = temp.path().join("file.ts");
716 std::fs::write(&file, "").unwrap();
717
718 let cache = CanonicalizeCache::default();
719 let expected = dunce::canonicalize(&file).ok();
720 assert_eq!(cache.get(&file), expected);
721 assert_eq!(cache.get(&file), expected);
722 assert!(cache.get(&temp.path().join("missing.ts")).is_none());
723 }
724
725 #[test]
726 fn commonjs_provenance_wraps_internal_and_bare_package_targets() {
727 assert!(matches!(
728 ResolveResult::InternalModule(FileId(4)).into_commonjs_require(),
729 ResolveResult::CommonJsInternalModule(FileId(4))
730 ));
731 assert!(matches!(
732 ResolveResult::InternalPackageModule {
733 file_id: FileId(5),
734 package_name: "pkg".to_string(),
735 }
736 .into_commonjs_require(),
737 ResolveResult::CommonJsInternalPackageModule {
738 file_id: FileId(5),
739 package_name,
740 } if package_name == "pkg"
741 ));
742 assert!(matches!(
743 ResolveResult::NpmPackage("pkg".to_string()).into_commonjs_require(),
744 ResolveResult::CommonJsNpmPackage(package_name) if package_name == "pkg"
745 ));
746 }
747}
748
749pub const OUTPUT_DIRS: &[&str] = &["dist", "build", "out", "esm", "cjs"];
754
755pub const MISSING_ONLY_OUTPUT_DIRS: &[&str] = &["lib"];
764
765pub const SOURCE_EXTS: &[&str] = &["ts", "tsx", "mts", "cts", "js", "jsx", "mjs", "cjs"];
767
768pub const RN_PLATFORM_PREFIXES: &[&str] = &[".web", ".ios", ".android", ".native"];