mod dynamic_imports;
pub(crate) mod fallbacks;
mod path_info;
mod re_exports;
mod react_native;
mod require_imports;
mod specifier;
mod static_imports;
#[cfg(test)]
mod tests;
mod types;
mod upgrades;
pub use fallbacks::extract_package_name_from_node_modules_path;
pub use path_info::{
extract_package_name, is_bare_specifier, is_path_alias, is_valid_package_name,
};
pub use react_native::{PlatformFamilyKey, has_react_native_plugin, platform_family_key};
pub use types::{
OUTPUT_DIRS, ResolveResult, ResolvedImport, ResolvedModule, ResolvedProject, ResolvedReExport,
ResolvedReplacedModuleTarget, ResolvedSourceEdge,
};
use std::sync::Arc;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use rayon::prelude::*;
use rustc_hash::{FxHashMap, FxHashSet};
use fallow_config::{AutoImportKind, AutoImportRule};
use fallow_types::discover::{DiscoveredFile, FileId};
use fallow_types::extract::{ImportInfo, ImportedName, ModuleInfo, SemanticFact};
use oxc_span::Span;
use dynamic_imports::{GlobMatcherCache, resolve_dynamic_imports, resolve_dynamic_patterns};
use re_exports::resolve_re_exports;
use react_native::{build_condition_names, build_extensions, synthesize_platform_family_edges};
use require_imports::resolve_require_imports;
use specifier::{build_resolve_options, create_resolver};
use static_imports::resolve_static_imports;
use types::{DenoImportMapEntry, PackageManifestInfo, ResolveContext};
use upgrades::{ResolvedVitestMockOperation, apply_specifier_upgrades};
pub struct ResolveAllImportsInput<'a> {
pub modules: &'a [ModuleInfo],
pub files: &'a [DiscoveredFile],
pub workspaces: &'a [fallow_config::WorkspaceInfo],
pub active_plugins: &'a [String],
pub path_aliases: &'a [(String, String)],
pub auto_imports: &'a [AutoImportRule],
pub scss_include_paths: &'a [PathBuf],
pub static_dir_mappings: &'a [(PathBuf, String)],
pub framework_static_dir_mappings: &'a [(PathBuf, String)],
pub root: &'a Path,
pub extra_conditions: &'a [String],
}
pub struct ResolverSession {
resolver: oxc_resolver::Resolver,
style_resolver: oxc_resolver::Resolver,
extensions: Vec<String>,
condition_names: Vec<String>,
package_manifests: Vec<PackageManifestInfo>,
has_deno_import_maps: bool,
canonical_ws_roots: Vec<PathBuf>,
root_is_canonical: bool,
}
impl ResolverSession {
#[must_use]
pub fn new(input: &ResolveAllImportsInput<'_>) -> Self {
let canonical_ws_roots: Vec<PathBuf> = input
.workspaces
.par_iter()
.map(|ws| dunce::canonicalize(&ws.root).unwrap_or_else(|_| ws.root.clone()))
.collect();
let package_manifests = build_package_manifests(input, &canonical_ws_roots);
let has_deno_import_maps = package_manifests
.iter()
.any(|manifest| !manifest.deno_import_map.is_empty());
let root_is_canonical = dunce::canonicalize(input.root).is_ok_and(|c| c == input.root);
let extensions = build_extensions(input.active_plugins);
let condition_names = build_condition_names(input.active_plugins, input.extra_conditions);
let resolver = create_resolver(input.root, input.active_plugins, input.extra_conditions);
let mut style_conditions = input.extra_conditions.to_vec();
style_conditions.push("sass".to_string());
style_conditions.push("style".to_string());
let style_resolver = resolver.clone_with_options(build_resolve_options(
input.root,
input.active_plugins,
&style_conditions,
));
Self {
resolver,
style_resolver,
extensions,
condition_names,
package_manifests,
has_deno_import_maps,
canonical_ws_roots,
root_is_canonical,
}
}
}
#[must_use]
pub fn resolve_all_imports(input: &ResolveAllImportsInput<'_>) -> ResolvedProject {
let session = ResolverSession::new(input);
resolve_all_imports_with_session(input, &session)
}
#[must_use]
pub fn resolve_all_imports_with_session(
input: &ResolveAllImportsInput<'_>,
session: &ResolverSession,
) -> ResolvedProject {
let root_is_canonical = session.root_is_canonical;
let workspace_roots = build_workspace_roots(input.workspaces, &session.canonical_ws_roots);
let canonical_paths = build_canonical_file_paths(input.files, root_is_canonical);
let path_to_id = build_path_to_id(input.files, &canonical_paths, root_is_canonical);
let raw_path_to_id: FxHashMap<&Path, FileId> = input
.files
.iter()
.map(|f| (f.path.as_path(), f.id))
.collect();
let file_paths: Vec<&Path> = input.files.iter().map(|f| f.path.as_path()).collect();
let canonical_fallback = if root_is_canonical {
Some(types::CanonicalFallback::new(input.files))
} else {
None
};
let tsconfig_warned: Mutex<FxHashSet<String>> = Mutex::new(FxHashSet::default());
let tsconfig_cache = types::TsconfigCache::default();
let canonicalize_cache = types::CanonicalizeCache::default();
let glob_matcher_cache = GlobMatcherCache::default();
let ctx = ResolveContext {
resolver: &session.resolver,
style_resolver: &session.style_resolver,
extensions: &session.extensions,
path_to_id: &path_to_id,
raw_path_to_id: &raw_path_to_id,
workspace_roots: &workspace_roots,
package_manifests: &session.package_manifests,
has_deno_import_maps: session.has_deno_import_maps,
condition_names: &session.condition_names,
path_aliases: input.path_aliases,
scss_include_paths: input.scss_include_paths,
static_dir_mappings: input.static_dir_mappings,
framework_static_dir_mappings: input.framework_static_dir_mappings,
root: input.root,
canonical_fallback: canonical_fallback.as_ref(),
tsconfig_warned: &tsconfig_warned,
tsconfig_cache: &tsconfig_cache,
canonicalize_cache: &canonicalize_cache,
};
let resolved_outputs: Vec<ResolvedModuleOutput> = input
.modules
.par_iter()
.filter_map(|module| {
resolve_module_imports(
module,
&ctx,
&glob_matcher_cache,
&file_paths,
&canonical_paths,
input.files,
)
})
.collect();
let mut resolved = Vec::with_capacity(resolved_outputs.len());
let mut vitest_mock_operations = Vec::new();
for output in resolved_outputs {
resolved.push(output.module);
vitest_mock_operations.extend(output.vitest_mock_operations);
}
apply_specifier_upgrades(&mut resolved, &mut vitest_mock_operations);
synthesize_platform_family_edges(&mut resolved, input.files, input.active_plugins);
synthesize_auto_import_edges(
&mut resolved,
input.modules,
input.auto_imports,
&path_to_id,
&raw_path_to_id,
);
let replaced_module_targets = final_replaced_module_targets(vitest_mock_operations);
ResolvedProject {
modules: resolved,
replaced_module_targets,
}
}
fn build_workspace_roots<'a>(
workspaces: &'a [fallow_config::WorkspaceInfo],
canonical_ws_roots: &'a [PathBuf],
) -> FxHashMap<&'a str, &'a Path> {
workspaces
.iter()
.zip(canonical_ws_roots.iter())
.map(|(ws, canonical)| (ws.name.as_str(), canonical.as_path()))
.collect()
}
fn build_canonical_file_paths(files: &[DiscoveredFile], root_is_canonical: bool) -> Vec<PathBuf> {
if root_is_canonical {
return Vec::new();
}
files
.par_iter()
.map(|f| dunce::canonicalize(&f.path).unwrap_or_else(|_| f.path.clone()))
.collect()
}
fn build_package_manifests(
input: &ResolveAllImportsInput<'_>,
canonical_ws_roots: &[PathBuf],
) -> Vec<PackageManifestInfo> {
let root_canonical =
dunce::canonicalize(input.root).unwrap_or_else(|_| input.root.to_path_buf());
let root_probe = fallow_config::probe_dir_manifest(input.root);
let root_import_map = merge_deno_import_maps(&[], input.root, root_probe.deno_import_map);
let mut package_manifests = Vec::new();
if let Ok(Some((_name, package_json, _deps))) = root_probe.manifest {
package_manifests.push(PackageManifestInfo {
root: input.root.to_path_buf(),
canonical_root: root_canonical,
name: package_json.name.clone(),
package_json,
deno_import_map: root_import_map.clone(),
});
}
for (ws, canonical_root) in input.workspaces.iter().zip(canonical_ws_roots.iter()) {
let ws_probe = fallow_config::probe_dir_manifest(&ws.root);
if let Ok(Some((_name, package_json, _deps))) = ws_probe.manifest {
package_manifests.push(PackageManifestInfo {
root: ws.root.clone(),
canonical_root: canonical_root.clone(),
name: package_json.name.clone().or_else(|| Some(ws.name.clone())),
package_json,
deno_import_map: merge_deno_import_maps(
&root_import_map,
&ws.root,
ws_probe.deno_import_map,
),
});
}
}
package_manifests
}
fn merge_deno_import_maps(
inherited: &[DenoImportMapEntry],
package_root: &Path,
local: Option<(PathBuf, Vec<(String, String)>)>,
) -> Vec<DenoImportMapEntry> {
let mut entries: FxHashMap<String, DenoImportMapEntry> = inherited
.iter()
.cloned()
.map(|entry| (entry.key.clone(), entry))
.collect();
if let Some((config_path, local_entries)) = local {
let declaring_dir = config_path.parent().unwrap_or(package_root).to_path_buf();
for (key, target) in local_entries {
entries.insert(
key.clone(),
DenoImportMapEntry {
key,
target,
declaring_dir: declaring_dir.clone(),
},
);
}
}
let mut entries: Vec<_> = entries.into_values().collect();
entries.sort_by(|a, b| a.key.cmp(&b.key));
entries
}
fn build_path_to_id<'a>(
files: &'a [DiscoveredFile],
canonical_paths: &'a [PathBuf],
root_is_canonical: bool,
) -> FxHashMap<&'a Path, FileId> {
if root_is_canonical {
files.iter().map(|f| (f.path.as_path(), f.id)).collect()
} else {
canonical_paths
.iter()
.enumerate()
.map(|(idx, canonical)| (canonical.as_path(), files[idx].id))
.collect()
}
}
fn resolve_module_imports(
module: &ModuleInfo,
ctx: &ResolveContext<'_>,
glob_matcher_cache: &GlobMatcherCache,
file_paths: &[&Path],
canonical_paths: &[PathBuf],
files: &[DiscoveredFile],
) -> Option<ResolvedModuleOutput> {
let Some(file_path) = file_paths.get(module.file_id.0 as usize) else {
tracing::warn!(
file_id = module.file_id.0,
"Skipping module with unknown file_id during resolution"
);
return None;
};
let mut all_imports = resolve_static_imports(ctx, file_path, &module.imports);
all_imports.extend(resolve_require_imports(
ctx,
file_path,
&module.require_calls,
));
let from_dir = if canonical_paths.is_empty() {
file_path.parent().unwrap_or(file_path)
} else {
canonical_paths
.get(module.file_id.0 as usize)
.and_then(|p| p.parent())
.unwrap_or(file_path)
};
let vitest_mock_operations =
resolve_vitest_mock_operations(module.file_id, &module.semantic_facts, ctx, file_path);
let module = build_resolved_module(ResolvedModuleBuildInput {
module,
ctx,
glob_matcher_cache,
file_path,
from_dir,
canonical_paths,
files,
all_imports,
});
Some(ResolvedModuleOutput {
module,
vitest_mock_operations,
})
}
struct ResolvedModuleOutput {
module: ResolvedModule,
vitest_mock_operations: Vec<ResolvedVitestMockOperation>,
}
fn resolve_vitest_mock_operations(
source_file: FileId,
semantic_facts: &[SemanticFact],
ctx: &ResolveContext<'_>,
file_path: &Path,
) -> Vec<ResolvedVitestMockOperation> {
let mut operations: Vec<_> = semantic_facts
.iter()
.filter_map(|fact| {
let SemanticFact::VitestModuleMockOperation(operation) = fact else {
return None;
};
Some(ResolvedVitestMockOperation {
source_file,
source_specifier: operation.source.clone(),
call_start: operation.call_start,
action: operation.action,
target: specifier::resolve_specifier(ctx, file_path, &operation.source, false),
})
})
.collect();
operations.sort_unstable_by(|left, right| {
left.call_start
.cmp(&right.call_start)
.then_with(|| left.source_specifier.cmp(&right.source_specifier))
});
operations
}
fn final_replaced_module_targets(
mut operations: Vec<ResolvedVitestMockOperation>,
) -> Vec<ResolvedReplacedModuleTarget> {
operations.sort_unstable_by(|left, right| {
left.source_file
.0
.cmp(&right.source_file.0)
.then_with(|| left.call_start.cmp(&right.call_start))
.then_with(|| left.source_specifier.cmp(&right.source_specifier))
});
let mut final_operations = FxHashMap::default();
for operation in operations {
let Some(target_file) = operation.target.internal_file_id() else {
continue;
};
final_operations.insert((operation.source_file, target_file), operation.action);
}
let mut targets: Vec<_> = final_operations
.into_iter()
.filter_map(|((source_file, target_file), action)| {
action
.replaces_original()
.then_some(ResolvedReplacedModuleTarget {
source_file,
target_file,
})
})
.collect();
targets.sort_unstable_by_key(|target| (target.source_file.0, target.target_file.0));
targets
}
struct ResolvedModuleBuildInput<'a> {
module: &'a ModuleInfo,
ctx: &'a ResolveContext<'a>,
glob_matcher_cache: &'a GlobMatcherCache,
file_path: &'a Path,
from_dir: &'a Path,
canonical_paths: &'a [PathBuf],
files: &'a [DiscoveredFile],
all_imports: Vec<types::ResolvedImport>,
}
fn build_resolved_module(input: ResolvedModuleBuildInput<'_>) -> ResolvedModule {
ResolvedModule {
file_id: input.module.file_id,
path: input.file_path.to_path_buf(),
exports: Arc::clone(&input.module.exports),
re_exports: resolve_re_exports(input.ctx, input.file_path, &input.module.re_exports),
resolved_imports: input.all_imports,
resolved_dynamic_imports: resolve_dynamic_imports(
input.ctx,
input.file_path,
&input.module.dynamic_imports,
),
resolved_dynamic_patterns: resolve_dynamic_patterns(
input.glob_matcher_cache,
input.from_dir,
&input.module.dynamic_import_patterns,
input.canonical_paths,
input.files,
),
member_accesses: Arc::clone(&input.module.member_accesses),
semantic_facts: Arc::clone(&input.module.semantic_facts),
whole_object_uses: Arc::clone(&input.module.whole_object_uses),
has_cjs_exports: input.module.has_cjs_exports,
has_angular_component_template_url: input.module.has_angular_component_template_url,
unused_import_bindings: input
.module
.unused_import_bindings
.iter()
.cloned()
.collect(),
type_referenced_import_bindings: input.module.type_referenced_import_bindings.clone(),
value_referenced_import_bindings: input.module.value_referenced_import_bindings.clone(),
namespace_object_aliases: input.module.namespace_object_aliases.clone(),
exported_factory_returns: Arc::clone(&input.module.exported_factory_returns),
exported_factory_return_object_shapes: Arc::clone(
&input.module.exported_factory_return_object_shapes,
),
type_member_types: Arc::clone(&input.module.type_member_types),
}
}
fn synthesize_auto_import_edges(
resolved: &mut [ResolvedModule],
modules: &[ModuleInfo],
auto_imports: &[AutoImportRule],
path_to_id: &FxHashMap<&Path, FileId>,
raw_path_to_id: &FxHashMap<&Path, FileId>,
) {
if auto_imports.is_empty() {
return;
}
let mut table: FxHashMap<&str, Vec<(FileId, AutoImportKind)>> = FxHashMap::default();
for rule in auto_imports {
let source = rule.source.as_path();
let Some(file_id) = raw_path_to_id
.get(source)
.or_else(|| path_to_id.get(source))
.copied()
else {
continue;
};
table
.entry(rule.name.as_str())
.or_default()
.push((file_id, rule.kind));
}
if table.is_empty() {
return;
}
let candidates: FxHashMap<FileId, &[String]> = modules
.iter()
.filter(|module| !module.auto_import_candidates.is_empty())
.map(|module| (module.file_id, module.auto_import_candidates.as_slice()))
.collect();
if candidates.is_empty() {
return;
}
for module in resolved.iter_mut() {
let Some(names) = candidates.get(&module.file_id) else {
continue;
};
for name in *names {
if is_auto_import_builtin(name) {
continue;
}
let Some(targets) = table.get(name.as_str()) else {
continue;
};
for (target_id, kind) in targets {
if *target_id == module.file_id {
continue;
}
module.resolved_imports.push(ResolvedImport {
info: synthetic_auto_import_info(name, *kind),
target: ResolveResult::SyntheticAutoImport(*target_id),
});
}
}
}
}
fn is_auto_import_builtin(name: &str) -> bool {
is_js_auto_import_builtin(name)
|| is_vue_auto_import_builtin(name)
|| is_nuxt_auto_import_builtin(name)
}
fn is_js_auto_import_builtin(name: &str) -> bool {
matches!(
name,
"AbortController"
| "AbortSignal"
| "Array"
| "ArrayBuffer"
| "BigInt"
| "Blob"
| "Boolean"
| "Buffer"
| "CSS"
| "DOMParser"
| "Date"
| "Document"
| "Error"
| "Event"
| "EventTarget"
| "File"
| "FormData"
| "Intl"
| "JSON"
| "Map"
| "Math"
| "Number"
| "Object"
| "Promise"
| "Reflect"
| "RegExp"
| "Response"
| "Set"
| "String"
| "Symbol"
| "URL"
| "URLSearchParams"
| "WeakMap"
| "WeakSet"
| "Window"
| "alert"
| "clearInterval"
| "clearTimeout"
| "console"
| "document"
| "fetch"
| "global"
| "globalThis"
| "localStorage"
| "navigator"
| "process"
| "requestAnimationFrame"
| "sessionStorage"
| "setInterval"
| "setTimeout"
| "window"
)
}
fn is_vue_auto_import_builtin(name: &str) -> bool {
matches!(name, |"computed"| "customRef"
| "defineAsyncComponent"
| "defineComponent"
| "effectScope"
| "getCurrentInstance"
| "h"
| "inject"
| "isProxy"
| "isReactive"
| "isReadonly"
| "isRef"
| "markRaw"
| "nextTick"
| "onActivated"
| "onBeforeMount"
| "onBeforeUnmount"
| "onBeforeUpdate"
| "onDeactivated"
| "onErrorCaptured"
| "onMounted"
| "onRenderTracked"
| "onRenderTriggered"
| "onScopeDispose"
| "onServerPrefetch"
| "onUnmounted"
| "onUpdated"
| "provide"
| "reactive"
| "readonly"
| "ref"
| "resolveComponent"
| "shallowReactive"
| "shallowReadonly"
| "shallowRef"
| "toRaw"
| "toRef"
| "toRefs"
| "triggerRef"
| "unref"
| "watch"
| "watchEffect"
| "watchPostEffect"
| "watchSyncEffect")
}
fn is_nuxt_auto_import_builtin(name: &str) -> bool {
matches!(name, |"useAsyncData"| "useCookie"
| "useError"
| "useFetch"
| "useHead"
| "useLazyAsyncData"
| "useLazyFetch"
| "useNuxtApp"
| "useRequestEvent"
| "useRequestHeaders"
| "useRoute"
| "useRouter"
| "useRuntimeConfig"
| "useSeoMeta"
| "useState")
}
fn synthetic_auto_import_info(name: &str, kind: AutoImportKind) -> ImportInfo {
let imported_name = match kind {
AutoImportKind::Named => ImportedName::Named(name.to_string()),
AutoImportKind::Default | AutoImportKind::DefaultComponent => ImportedName::Default,
};
ImportInfo {
source: format!("<auto-import:{name}>"),
imported_name,
local_name: name.to_string(),
is_type_only: false,
is_type_only_star: false,
from_style: false,
span: Span::default(),
source_span: Span::default(),
}
}