1mod auto_imports;
19mod dynamic_imports;
20pub(crate) mod fallbacks;
21pub(crate) mod inline_loaders;
22mod memo;
23mod path_info;
24mod re_exports;
25mod react_native;
26mod require_imports;
27mod specifier;
28mod static_imports;
29#[cfg(test)]
30mod tests;
31mod types;
32mod upgrades;
33mod work;
34
35pub use auto_imports::{UnreadableAutoImportRead, unreadable_auto_import_reads};
36pub use fallbacks::extract_package_name_from_node_modules_path;
37pub use inline_loaders::InlineLoaderRequest;
38pub use path_info::{
39 extract_package_name, is_bare_specifier, is_path_alias, is_valid_package_name,
40};
41pub use react_native::{PlatformFamilyKey, has_react_native_plugin, platform_family_key};
42pub use types::{
43 OUTPUT_DIRS, ResolveResult, ResolvedImport, ResolvedModule, ResolvedProject, ResolvedReExport,
44 ResolvedReplacedModuleTarget, ResolvedSourceEdge,
45};
46pub use work::ResolveWork;
47
48use std::sync::Arc;
49
50use std::path::{Path, PathBuf};
51use std::sync::Mutex;
52
53use rayon::prelude::*;
54use rustc_hash::{FxHashMap, FxHashSet};
55
56use fallow_config::{AutoImportKind, AutoImportRule};
57use fallow_types::discover::{DiscoveredFile, FileId};
58use fallow_types::extract::{ImportInfo, ImportedName, ModuleInfo, SemanticFact};
59use oxc_span::Span;
60
61use auto_imports::synthesize_auto_import_edges;
62use dynamic_imports::{GlobMatcherCache, resolve_dynamic_imports, resolve_dynamic_patterns};
63use re_exports::resolve_re_exports;
64use react_native::{build_condition_names, build_extensions, synthesize_platform_family_edges};
65use require_imports::resolve_require_imports;
66use specifier::{build_resolve_options, create_resolver};
67use static_imports::resolve_static_imports;
68use types::{DenoImportMapEntry, PackageManifestInfo, ResolveContext};
69use upgrades::{ResolvedVitestMockOperation, apply_specifier_upgrades};
70
71pub struct ResolveAllImportsInput<'a> {
73 pub modules: &'a [ModuleInfo],
75 pub files: &'a [DiscoveredFile],
77 pub workspaces: &'a [fallow_config::WorkspaceInfo],
79 pub active_plugins: &'a [String],
81 pub path_aliases: &'a [(String, String)],
83 pub auto_imports: &'a [AutoImportRule],
85 pub scss_include_paths: &'a [PathBuf],
87 pub static_dir_mappings: &'a [(PathBuf, String)],
89 pub framework_static_dir_mappings: &'a [(PathBuf, String)],
91 pub root: &'a Path,
93 pub extra_conditions: &'a [String],
95}
96
97pub struct ResolverSession {
108 resolver: oxc_resolver::Resolver,
109 style_resolver: oxc_resolver::Resolver,
110 extensions: Vec<String>,
111 condition_names: Vec<String>,
112 package_manifests: Vec<PackageManifestInfo>,
113 has_deno_import_maps: bool,
114 canonical_ws_roots: Vec<PathBuf>,
115 root_is_canonical: bool,
116}
117
118impl ResolverSession {
119 #[must_use]
127 pub fn new(input: &ResolveAllImportsInput<'_>) -> Self {
128 let canonical_ws_roots: Vec<PathBuf> = input
129 .workspaces
130 .par_iter()
131 .map(|ws| dunce::canonicalize(&ws.root).unwrap_or_else(|_| ws.root.clone()))
132 .collect();
133 let package_manifests = build_package_manifests(input, &canonical_ws_roots);
134 let has_deno_import_maps = package_manifests
135 .iter()
136 .any(|manifest| !manifest.deno_import_map.is_empty());
137 let root_is_canonical = dunce::canonicalize(input.root).is_ok_and(|c| c == input.root);
138
139 let extensions = build_extensions(input.active_plugins);
140 let condition_names = build_condition_names(input.active_plugins, input.extra_conditions);
141 let resolver = create_resolver(input.root, input.active_plugins, input.extra_conditions);
142 let mut style_conditions = input.extra_conditions.to_vec();
143 style_conditions.push("sass".to_string());
144 style_conditions.push("style".to_string());
145 let style_resolver = resolver.clone_with_options(build_resolve_options(
148 input.root,
149 input.active_plugins,
150 &style_conditions,
151 ));
152
153 Self {
154 resolver,
155 style_resolver,
156 extensions,
157 condition_names,
158 package_manifests,
159 has_deno_import_maps,
160 canonical_ws_roots,
161 root_is_canonical,
162 }
163 }
164}
165
166#[must_use]
168pub fn resolve_all_imports(input: &ResolveAllImportsInput<'_>) -> ResolvedProject {
169 let session = ResolverSession::new(input);
170 resolve_all_imports_with_session(input, &session)
171}
172
173#[must_use]
181pub fn resolve_all_imports_with_session(
182 input: &ResolveAllImportsInput<'_>,
183 session: &ResolverSession,
184) -> ResolvedProject {
185 let root_is_canonical = session.root_is_canonical;
186 let workspace_roots = build_workspace_roots(input.workspaces, &session.canonical_ws_roots);
187 let canonical_paths = build_canonical_file_paths(input.files, root_is_canonical);
188 let mut work = ResolveWork {
189 canonicalize_calls: canonical_paths.len() as u64,
190 ..ResolveWork::default()
191 };
192 let path_to_id = build_path_to_id(input.files, &canonical_paths, root_is_canonical);
193 let raw_path_to_id: FxHashMap<&Path, FileId> = input
194 .files
195 .iter()
196 .map(|f| (f.path.as_path(), f.id))
197 .collect();
198
199 let file_paths: Vec<&Path> = input.files.iter().map(|f| f.path.as_path()).collect();
200
201 let canonical_fallback = if root_is_canonical {
202 Some(types::CanonicalFallback::new(input.files))
203 } else {
204 None
205 };
206
207 let tsconfig_warned: Mutex<FxHashSet<String>> = Mutex::new(FxHashSet::default());
208 let tsconfig_cache = types::TsconfigCache::default();
209 let canonicalize_cache = types::CanonicalizeCache::default();
210 let glob_matcher_cache = GlobMatcherCache::default();
211
212 let ctx = ResolveContext {
213 resolver: &session.resolver,
214 style_resolver: &session.style_resolver,
215 extensions: &session.extensions,
216 path_to_id: &path_to_id,
217 raw_path_to_id: &raw_path_to_id,
218 workspace_roots: &workspace_roots,
219 package_manifests: &session.package_manifests,
220 has_deno_import_maps: session.has_deno_import_maps,
221 condition_names: &session.condition_names,
222 path_aliases: input.path_aliases,
223 scss_include_paths: input.scss_include_paths,
224 static_dir_mappings: input.static_dir_mappings,
225 framework_static_dir_mappings: input.framework_static_dir_mappings,
226 root: input.root,
227 canonical_fallback: canonical_fallback.as_ref(),
228 tsconfig_warned: &tsconfig_warned,
229 tsconfig_cache: &tsconfig_cache,
230 canonicalize_cache: &canonicalize_cache,
231 };
232
233 let resolved_outputs: Vec<ResolvedModuleOutput> = input
234 .modules
235 .par_iter()
236 .filter_map(|module| {
237 resolve_module_imports(
238 module,
239 &ctx,
240 &glob_matcher_cache,
241 &file_paths,
242 &canonical_paths,
243 input.files,
244 )
245 })
246 .collect();
247 let mut resolved = Vec::with_capacity(resolved_outputs.len());
248 let mut vitest_mock_operations = Vec::new();
249 for output in resolved_outputs {
250 resolved.push(output.module);
251 vitest_mock_operations.extend(output.vitest_mock_operations);
252 work += output.work;
253 }
254 work.canonicalize_calls += canonicalize_cache.distinct_paths() as u64;
255
256 apply_specifier_upgrades(&mut resolved, &mut vitest_mock_operations);
257
258 synthesize_platform_family_edges(&mut resolved, input.files, input.active_plugins);
259
260 synthesize_auto_import_edges(
261 &mut resolved,
262 input.modules,
263 input.auto_imports,
264 &path_to_id,
265 &raw_path_to_id,
266 );
267
268 let replaced_module_targets = final_replaced_module_targets(vitest_mock_operations);
269
270 ResolvedProject {
271 modules: resolved,
272 replaced_module_targets,
273 work,
274 }
275}
276
277fn build_workspace_roots<'a>(
278 workspaces: &'a [fallow_config::WorkspaceInfo],
279 canonical_ws_roots: &'a [PathBuf],
280) -> FxHashMap<&'a str, &'a Path> {
281 workspaces
282 .iter()
283 .zip(canonical_ws_roots.iter())
284 .map(|(ws, canonical)| (ws.name.as_str(), canonical.as_path()))
285 .collect()
286}
287
288fn build_canonical_file_paths(files: &[DiscoveredFile], root_is_canonical: bool) -> Vec<PathBuf> {
289 if root_is_canonical {
290 return Vec::new();
291 }
292
293 files
294 .par_iter()
295 .map(|f| dunce::canonicalize(&f.path).unwrap_or_else(|_| f.path.clone()))
296 .collect()
297}
298
299fn build_package_manifests(
306 input: &ResolveAllImportsInput<'_>,
307 canonical_ws_roots: &[PathBuf],
308) -> Vec<PackageManifestInfo> {
309 let root_canonical =
310 dunce::canonicalize(input.root).unwrap_or_else(|_| input.root.to_path_buf());
311 let root_probe = fallow_config::probe_dir_manifest(input.root);
312 let root_import_map = merge_deno_import_maps(&[], input.root, root_probe.deno_import_map);
313 let mut package_manifests = Vec::new();
314 if let Ok(Some((_name, package_json, _deps))) = root_probe.manifest {
315 package_manifests.push(PackageManifestInfo {
316 root: input.root.to_path_buf(),
317 canonical_root: root_canonical,
318 name: package_json.name.clone(),
319 package_json,
320 deno_import_map: root_import_map.clone(),
321 });
322 }
323 for (ws, canonical_root) in input.workspaces.iter().zip(canonical_ws_roots.iter()) {
324 let ws_probe = fallow_config::probe_dir_manifest(&ws.root);
325 if let Ok(Some((_name, package_json, _deps))) = ws_probe.manifest {
326 package_manifests.push(PackageManifestInfo {
327 root: ws.root.clone(),
328 canonical_root: canonical_root.clone(),
329 name: package_json.name.clone().or_else(|| Some(ws.name.clone())),
330 package_json,
331 deno_import_map: merge_deno_import_maps(
332 &root_import_map,
333 &ws.root,
334 ws_probe.deno_import_map,
335 ),
336 });
337 }
338 }
339 package_manifests
340}
341
342fn merge_deno_import_maps(
348 inherited: &[DenoImportMapEntry],
349 package_root: &Path,
350 local: Option<(PathBuf, Vec<(String, String)>)>,
351) -> Vec<DenoImportMapEntry> {
352 let mut entries: FxHashMap<String, DenoImportMapEntry> = inherited
353 .iter()
354 .cloned()
355 .map(|entry| (entry.key.clone(), entry))
356 .collect();
357
358 if let Some((config_path, local_entries)) = local {
359 let declaring_dir = config_path.parent().unwrap_or(package_root).to_path_buf();
360 for (key, target) in local_entries {
361 entries.insert(
362 key.clone(),
363 DenoImportMapEntry {
364 key,
365 target,
366 declaring_dir: declaring_dir.clone(),
367 },
368 );
369 }
370 }
371
372 let mut entries: Vec<_> = entries.into_values().collect();
373 entries.sort_by(|a, b| a.key.cmp(&b.key));
374 entries
375}
376
377fn build_path_to_id<'a>(
380 files: &'a [DiscoveredFile],
381 canonical_paths: &'a [PathBuf],
382 root_is_canonical: bool,
383) -> FxHashMap<&'a Path, FileId> {
384 if root_is_canonical {
385 files.iter().map(|f| (f.path.as_path(), f.id)).collect()
386 } else {
387 canonical_paths
388 .iter()
389 .enumerate()
390 .map(|(idx, canonical)| (canonical.as_path(), files[idx].id))
391 .collect()
392 }
393}
394
395fn resolve_module_imports(
396 module: &ModuleInfo,
397 ctx: &ResolveContext<'_>,
398 glob_matcher_cache: &GlobMatcherCache,
399 file_paths: &[&Path],
400 canonical_paths: &[PathBuf],
401 files: &[DiscoveredFile],
402) -> Option<ResolvedModuleOutput> {
403 let Some(file_path) = file_paths.get(module.file_id.0 as usize) else {
404 tracing::warn!(
405 file_id = module.file_id.0,
406 "Skipping module with unknown file_id during resolution"
407 );
408 return None;
409 };
410
411 let resolve = || {
412 let mut all_imports = resolve_static_imports(ctx, file_path, &module.imports);
413 all_imports.extend(resolve_require_imports(
414 ctx,
415 file_path,
416 &module.require_calls,
417 ));
418
419 let from_dir = if canonical_paths.is_empty() {
420 file_path.parent().unwrap_or(file_path)
421 } else {
422 canonical_paths
423 .get(module.file_id.0 as usize)
424 .and_then(|p| p.parent())
425 .unwrap_or(file_path)
426 };
427
428 let vitest_mock_operations =
429 resolve_vitest_mock_operations(module.file_id, &module.semantic_facts, ctx, file_path);
430 let module = build_resolved_module(ResolvedModuleBuildInput {
431 module,
432 ctx,
433 glob_matcher_cache,
434 file_path,
435 from_dir,
436 canonical_paths,
437 files,
438 all_imports,
439 });
440 (module, vitest_mock_operations)
441 };
442 let ((module, vitest_mock_operations), work) =
443 memo::in_file_scope(file_path, || work::in_module_scope(resolve));
444
445 Some(ResolvedModuleOutput {
446 module,
447 vitest_mock_operations,
448 work,
449 })
450}
451
452struct ResolvedModuleOutput {
453 module: ResolvedModule,
454 vitest_mock_operations: Vec<ResolvedVitestMockOperation>,
455 work: ResolveWork,
456}
457
458fn resolve_vitest_mock_operations(
459 source_file: FileId,
460 semantic_facts: &[SemanticFact],
461 ctx: &ResolveContext<'_>,
462 file_path: &Path,
463) -> Vec<ResolvedVitestMockOperation> {
464 let mut operations: Vec<_> = semantic_facts
465 .iter()
466 .filter_map(|fact| {
467 let SemanticFact::VitestModuleMockOperation(operation) = fact else {
468 return None;
469 };
470 Some(ResolvedVitestMockOperation {
471 source_file,
472 source_specifier: operation.source.clone(),
473 call_start: operation.call_start,
474 action: operation.action,
475 target: specifier::resolve_import_specifier(
476 ctx,
477 file_path,
478 &operation.source,
479 false,
480 ),
481 })
482 })
483 .collect();
484 operations.sort_unstable_by(|left, right| {
485 left.call_start
486 .cmp(&right.call_start)
487 .then_with(|| left.source_specifier.cmp(&right.source_specifier))
488 });
489 operations
490}
491
492fn final_replaced_module_targets(
493 mut operations: Vec<ResolvedVitestMockOperation>,
494) -> Vec<ResolvedReplacedModuleTarget> {
495 operations.sort_unstable_by(|left, right| {
496 left.source_file
497 .0
498 .cmp(&right.source_file.0)
499 .then_with(|| left.call_start.cmp(&right.call_start))
500 .then_with(|| left.source_specifier.cmp(&right.source_specifier))
501 });
502
503 let mut final_operations = FxHashMap::default();
504 for operation in operations {
505 let Some(target_file) = operation.target.internal_file_id() else {
506 continue;
507 };
508 final_operations.insert((operation.source_file, target_file), operation.action);
509 }
510
511 let mut targets: Vec<_> = final_operations
512 .into_iter()
513 .filter_map(|((source_file, target_file), action)| {
514 action
515 .replaces_original()
516 .then_some(ResolvedReplacedModuleTarget {
517 source_file,
518 target_file,
519 })
520 })
521 .collect();
522 targets.sort_unstable_by_key(|target| (target.source_file.0, target.target_file.0));
523 targets
524}
525
526struct ResolvedModuleBuildInput<'a> {
527 module: &'a ModuleInfo,
528 ctx: &'a ResolveContext<'a>,
529 glob_matcher_cache: &'a GlobMatcherCache,
530 file_path: &'a Path,
531 from_dir: &'a Path,
532 canonical_paths: &'a [PathBuf],
533 files: &'a [DiscoveredFile],
534 all_imports: Vec<types::ResolvedImport>,
535}
536
537fn build_resolved_module(input: ResolvedModuleBuildInput<'_>) -> ResolvedModule {
538 ResolvedModule {
539 file_id: input.module.file_id,
540 path: input.file_path.to_path_buf(),
541 exports: Arc::clone(&input.module.exports),
542 re_exports: resolve_re_exports(input.ctx, input.file_path, &input.module.re_exports),
543 resolved_imports: input.all_imports,
544 resolved_dynamic_imports: resolve_dynamic_imports(
545 input.ctx,
546 input.file_path,
547 &input.module.dynamic_imports,
548 ),
549 resolved_dynamic_patterns: resolve_dynamic_patterns(
550 input.glob_matcher_cache,
551 input.from_dir,
552 &input.module.dynamic_import_patterns,
553 input.canonical_paths,
554 input.files,
555 ),
556 member_accesses: Arc::clone(&input.module.member_accesses),
557 semantic_facts: Arc::clone(&input.module.semantic_facts),
558 whole_object_uses: Arc::clone(&input.module.whole_object_uses),
559 has_cjs_exports: input.module.has_cjs_exports,
560 has_angular_component_template_url: input.module.has_angular_component_template_url,
561 unused_import_bindings: input
562 .module
563 .unused_import_bindings
564 .iter()
565 .cloned()
566 .collect(),
567 type_referenced_import_bindings: input.module.type_referenced_import_bindings.clone(),
568 value_referenced_import_bindings: input.module.value_referenced_import_bindings.clone(),
569 namespace_object_aliases: input.module.namespace_object_aliases.clone(),
570 exported_factory_returns: Arc::clone(&input.module.exported_factory_returns),
571 exported_factory_return_object_shapes: Arc::clone(
572 &input.module.exported_factory_return_object_shapes,
573 ),
574 type_member_types: Arc::clone(&input.module.type_member_types),
575 }
576}
577
578fn is_auto_import_builtin(name: &str) -> bool {
579 is_js_auto_import_builtin(name)
580 || is_vue_auto_import_builtin(name)
581 || is_nuxt_auto_import_builtin(name)
582}
583
584fn is_js_auto_import_builtin(name: &str) -> bool {
585 matches!(
586 name,
587 "AbortController"
588 | "AbortSignal"
589 | "Array"
590 | "ArrayBuffer"
591 | "BigInt"
592 | "Blob"
593 | "Boolean"
594 | "Buffer"
595 | "CSS"
596 | "DOMParser"
597 | "Date"
598 | "Document"
599 | "Error"
600 | "Event"
601 | "EventTarget"
602 | "File"
603 | "FormData"
604 | "Intl"
605 | "JSON"
606 | "Map"
607 | "Math"
608 | "Number"
609 | "Object"
610 | "Promise"
611 | "Reflect"
612 | "RegExp"
613 | "Response"
614 | "Set"
615 | "String"
616 | "Symbol"
617 | "URL"
618 | "URLSearchParams"
619 | "WeakMap"
620 | "WeakSet"
621 | "Window"
622 | "alert"
623 | "clearInterval"
624 | "clearTimeout"
625 | "console"
626 | "document"
627 | "fetch"
628 | "global"
629 | "globalThis"
630 | "localStorage"
631 | "navigator"
632 | "process"
633 | "requestAnimationFrame"
634 | "sessionStorage"
635 | "setInterval"
636 | "setTimeout"
637 | "window"
638 )
639}
640
641fn is_vue_auto_import_builtin(name: &str) -> bool {
642 matches!(name, |"computed"| "customRef"
643 | "defineAsyncComponent"
644 | "defineComponent"
645 | "effectScope"
646 | "getCurrentInstance"
647 | "h"
648 | "inject"
649 | "isProxy"
650 | "isReactive"
651 | "isReadonly"
652 | "isRef"
653 | "markRaw"
654 | "nextTick"
655 | "onActivated"
656 | "onBeforeMount"
657 | "onBeforeUnmount"
658 | "onBeforeUpdate"
659 | "onDeactivated"
660 | "onErrorCaptured"
661 | "onMounted"
662 | "onRenderTracked"
663 | "onRenderTriggered"
664 | "onScopeDispose"
665 | "onServerPrefetch"
666 | "onUnmounted"
667 | "onUpdated"
668 | "provide"
669 | "reactive"
670 | "readonly"
671 | "ref"
672 | "resolveComponent"
673 | "shallowReactive"
674 | "shallowReadonly"
675 | "shallowRef"
676 | "toRaw"
677 | "toRef"
678 | "toRefs"
679 | "triggerRef"
680 | "unref"
681 | "watch"
682 | "watchEffect"
683 | "watchPostEffect"
684 | "watchSyncEffect")
685}
686
687fn is_nuxt_auto_import_builtin(name: &str) -> bool {
688 matches!(name, |"useAsyncData"| "useCookie"
689 | "useError"
690 | "useFetch"
691 | "useHead"
692 | "useLazyAsyncData"
693 | "useLazyFetch"
694 | "useNuxtApp"
695 | "useRequestEvent"
696 | "useRequestHeaders"
697 | "useRoute"
698 | "useRouter"
699 | "useRuntimeConfig"
700 | "useSeoMeta"
701 | "useState")
702}
703
704fn synthetic_auto_import_info(name: &str, kind: AutoImportKind) -> ImportInfo {
707 let imported_name = match kind {
708 AutoImportKind::Named => ImportedName::Named(name.to_string()),
709 AutoImportKind::Default | AutoImportKind::DefaultComponent => ImportedName::Default,
710 };
711 ImportInfo {
712 source: format!("<auto-import:{name}>"),
713 imported_name,
714 local_name: name.to_string(),
715 is_type_only: false,
716 is_type_only_star: false,
717 from_style: false,
718 span: Span::default(),
719 source_span: Span::default(),
720 }
721}