Skip to main content

fallow_graph/resolve/
mod.rs

1//! Import specifier resolution using `oxc_resolver`.
2//!
3//! Orchestrates the resolution pipeline: for every extracted module, resolves all
4//! import specifiers in parallel (via rayon) to an [`ResolveResult`], internal file,
5//! npm package, external file, or unresolvable. The entry point is [`resolve_all_imports`].
6//!
7//! Resolution is split into submodules by import kind:
8//! - `static_imports`: ES `import` declarations
9//! - `dynamic_imports`: `import()` expressions and glob-based dynamic patterns
10//! - `require_imports`: CommonJS `require()` calls
11//! - `re_exports`: `export { x } from './y'` re-export sources
12//! - `upgrades`: post-resolution pass fixing non-deterministic bare specifier results
13//!
14//! Handles tsconfig path aliases (auto-discovered per file), pnpm virtual store paths,
15//! React Native platform extensions, and package.json `exports` subpath resolution with
16//! output-to-source directory fallback.
17
18mod auto_imports;
19mod base_url_directory;
20mod dynamic_imports;
21mod extension_alias;
22pub(crate) mod fallbacks;
23mod file_attempt;
24mod inline_loaders;
25mod jsx_runtime;
26mod memo;
27mod output_entry;
28mod package_credit;
29mod package_import_conditions;
30mod path_info;
31mod re_exports;
32mod react_native;
33mod require_imports;
34mod root_relative;
35mod specifier;
36mod static_imports;
37#[cfg(test)]
38mod tests;
39mod tsconfig_scope;
40mod types;
41mod upgrades;
42mod url_suffix;
43mod work;
44mod workspace_alias;
45
46pub use auto_imports::{UnreadableAutoImportRead, unreadable_auto_import_reads};
47pub use fallbacks::extract_package_name_from_node_modules_path;
48pub use inline_loaders::InlineLoaderRequest;
49pub use output_entry::{directory_index_entry, output_entry_to_source_path};
50pub use path_info::{
51    extract_package_name, is_bare_specifier, is_path_alias, is_valid_package_name,
52    normalize_npm_specifier,
53};
54pub use react_native::{PlatformFamilyKey, has_react_native_plugin, platform_family_key};
55pub use types::{
56    MISSING_ONLY_OUTPUT_DIRS, MissingExportTarget, OUTPUT_DIRS, ResolveResult, ResolvedImport,
57    ResolvedModule, ResolvedProject, ResolvedReExport, ResolvedReplacedModuleTarget,
58    ResolvedSourceEdge, ScopedPathAlias,
59};
60pub use work::ResolveWork;
61
62use std::sync::Arc;
63
64use std::path::{Path, PathBuf};
65use std::sync::Mutex;
66
67use rayon::prelude::*;
68use rustc_hash::{FxHashMap, FxHashSet};
69
70use fallow_config::{AutoImportKind, AutoImportRule, JsxImportSourceRule};
71use fallow_types::discover::{DiscoveredFile, FileId};
72use fallow_types::extract::{ImportInfo, ImportedName, ModuleInfo, SemanticFact};
73use oxc_span::Span;
74
75use auto_imports::synthesize_auto_import_edges;
76use dynamic_imports::{GlobMatcherCache, resolve_dynamic_imports, resolve_dynamic_patterns};
77use jsx_runtime::resolve_config_jsx_runtime_imports;
78pub use jsx_runtime::{CompiledJsxRule, compile_jsx_rules};
79use package_import_conditions::synthesize_package_import_condition_edges;
80use re_exports::resolve_re_exports;
81use react_native::{build_condition_names, build_extensions, synthesize_platform_family_edges};
82use require_imports::resolve_require_imports;
83use specifier::{build_resolve_options, create_resolver};
84use static_imports::resolve_static_imports;
85use types::{DenoImportMapEntry, PackageManifestInfo, ResolveContext};
86use upgrades::{ResolvedVitestMockOperation, apply_specifier_upgrades};
87
88/// Inputs used to resolve imports for a complete extracted project.
89pub struct ResolveAllImportsInput<'a> {
90    /// Extracted modules whose imports should be resolved.
91    pub modules: &'a [ModuleInfo],
92    /// Discovered source files indexed by [`FileId`].
93    pub files: &'a [DiscoveredFile],
94    /// Workspace package roots used for package self-resolution.
95    pub workspaces: &'a [fallow_config::WorkspaceInfo],
96    /// Active plugin names that affect extensions and resolver conditions.
97    pub active_plugins: &'a [String],
98    /// Configured TypeScript path alias pairs.
99    pub path_aliases: &'a [(String, String)],
100    /// Plugin path aliases that apply only to the files of one workspace.
101    pub scoped_path_aliases: &'a [ScopedPathAlias],
102    /// Auto-import rules that synthesize implicit graph edges.
103    pub auto_imports: &'a [AutoImportRule],
104    /// JSX import sources from bundler and test configs. Each adds a runtime
105    /// edge to the matching modules that have JSX and no runtime pragma.
106    pub jsx_import_sources: &'a [JsxImportSourceRule],
107    /// Additional Sass and SCSS include directories.
108    pub scss_include_paths: &'a [PathBuf],
109    /// Static directory mappings for framework-specific asset resolution.
110    pub static_dir_mappings: &'a [(PathBuf, String)],
111    /// Mounts a framework serves for the whole project; see `ResolveContext`.
112    pub framework_static_dir_mappings: &'a [(PathBuf, String)],
113    /// Project root used for package manifest and relative-path resolution.
114    pub root: &'a Path,
115    /// Extra resolver conditions supplied by configuration.
116    pub extra_conditions: &'a [String],
117}
118
119/// Reusable per-project resolver state: the resolver instances, package
120/// manifests, and workspace canonicalization that do not depend on the specific
121/// modules being resolved.
122///
123/// Building these is the bulk of `resolve_all_imports`'s non-parallel setup cost
124/// (workspace `dunce::canonicalize`, root + workspace `package.json` loads, and
125/// resolver construction). A caller that resolves many small inputs against the
126/// same project (the external-stylesheet scanner resolves dozens of node_modules
127/// stylesheets one file at a time) builds a session once and reuses it across
128/// every resolution instead of rebuilding this state per call.
129pub struct ResolverSession {
130    resolver: crate::read_trace::Resolver,
131    script_resolver: crate::read_trace::Resolver,
132    style_resolver: crate::read_trace::Resolver,
133    extensions: Vec<String>,
134    condition_names: Vec<String>,
135    package_manifests: Vec<PackageManifestInfo>,
136    has_deno_import_maps: bool,
137    canonical_ws_roots: Vec<PathBuf>,
138    root_is_canonical: bool,
139}
140
141impl ResolverSession {
142    /// Build the reusable resolver state for `input`'s project context (root,
143    /// workspaces, active plugins, and resolver conditions).
144    ///
145    /// The session is valid for any later [`resolve_all_imports_with_session`]
146    /// call whose input shares that project context; in particular the
147    /// `workspaces` slice must be the same (same entries and order) so workspace
148    /// names line up with the cached `canonical_ws_roots`.
149    #[must_use]
150    pub fn new(input: &ResolveAllImportsInput<'_>) -> Self {
151        let canonical_ws_roots: Vec<PathBuf> = input
152            .workspaces
153            .par_iter()
154            .map(|ws| crate::read_trace::canonicalize(&ws.root).unwrap_or_else(|_| ws.root.clone()))
155            .collect();
156        let package_manifests = build_package_manifests(input, &canonical_ws_roots);
157        let has_deno_import_maps = package_manifests
158            .iter()
159            .any(|manifest| !manifest.deno_import_map.is_empty());
160        let root_is_canonical =
161            crate::read_trace::canonicalize(input.root).is_ok_and(|c| c == input.root);
162
163        let extensions = build_extensions(input.active_plugins);
164        let condition_names = build_condition_names(input.active_plugins, input.extra_conditions);
165        let resolver = create_resolver(input.root, input.active_plugins, input.extra_conditions);
166        let script_resolver = specifier::create_script_resolver(&resolver);
167        let mut style_conditions = input.extra_conditions.to_vec();
168        style_conditions.push("sass".to_string());
169        style_conditions.push("style".to_string());
170        // Derived from the main resolver so both share one filesystem cache and,
171        // on Yarn PnP projects, one parsed manifest.
172        let style_resolver = resolver.clone_with_options(build_resolve_options(
173            input.root,
174            input.active_plugins,
175            &style_conditions,
176        ));
177
178        Self {
179            resolver,
180            script_resolver,
181            style_resolver,
182            extensions,
183            condition_names,
184            package_manifests,
185            has_deno_import_maps,
186            canonical_ws_roots,
187            root_is_canonical,
188        }
189    }
190}
191
192/// Resolve all imports across all modules in parallel.
193#[must_use]
194pub fn resolve_all_imports(input: &ResolveAllImportsInput<'_>) -> ResolvedProject {
195    let session = ResolverSession::new(input);
196    resolve_all_imports_with_session(input, &session)
197}
198
199/// Resolve all imports for `input`, reusing a prebuilt [`ResolverSession`].
200///
201/// This is the single resolution code path; [`resolve_all_imports`] is the
202/// convenience wrapper that builds a fresh session first. `session` MUST have
203/// been built from an input with the same project context as `input` (same
204/// `root`, `workspaces` slice and order, `active_plugins`, and
205/// `extra_conditions`); only `modules` and `files` may differ.
206#[must_use]
207pub fn resolve_all_imports_with_session(
208    input: &ResolveAllImportsInput<'_>,
209    session: &ResolverSession,
210) -> ResolvedProject {
211    // `ResolverSession::new` reads only the root, the workspace roots and
212    // their manifests, which the graph cache key covers by name.
213    let missed_probes = crate::missed_probes::MissRecorder::start(input.root);
214    let root_is_canonical = session.root_is_canonical;
215    let workspace_roots = build_workspace_roots(input.workspaces, &session.canonical_ws_roots);
216    let canonical_paths = build_canonical_file_paths(input.files, root_is_canonical);
217    let mut work = ResolveWork {
218        canonicalize_calls: canonical_paths.len() as u64,
219        ..ResolveWork::default()
220    };
221    let path_to_id = build_path_to_id(input.files, &canonical_paths, root_is_canonical);
222    let raw_path_to_id: FxHashMap<&Path, FileId> = input
223        .files
224        .iter()
225        .map(|f| (f.path.as_path(), f.id))
226        .collect();
227
228    let file_paths: Vec<&Path> = input.files.iter().map(|f| f.path.as_path()).collect();
229
230    let canonical_fallback = if root_is_canonical {
231        Some(types::CanonicalFallback::new(input.files))
232    } else {
233        None
234    };
235
236    let tsconfig_warned: Mutex<FxHashSet<String>> = Mutex::new(FxHashSet::default());
237    let tsconfig_cache = types::TsconfigCache::default();
238    let canonicalize_cache = types::CanonicalizeCache::default();
239    let glob_matcher_cache = GlobMatcherCache::with_module_extensions(&session.extensions);
240    // Dynamic import patterns match against canonical file paths when the
241    // root is not canonical, so their root containment check needs the
242    // canonical root too.
243    let pattern_root = if canonical_paths.is_empty() {
244        input.root.to_path_buf()
245    } else {
246        crate::read_trace::canonicalize(input.root).unwrap_or_else(|_| input.root.to_path_buf())
247    };
248    let jsx_rules = compile_jsx_rules(input.jsx_import_sources);
249
250    let ctx = ResolveContext {
251        resolver: &session.resolver,
252        script_resolver: &session.script_resolver,
253        style_resolver: &session.style_resolver,
254        extensions: &session.extensions,
255        path_to_id: &path_to_id,
256        raw_path_to_id: &raw_path_to_id,
257        workspace_roots: &workspace_roots,
258        package_manifests: &session.package_manifests,
259        has_deno_import_maps: session.has_deno_import_maps,
260        condition_names: &session.condition_names,
261        path_aliases: input.path_aliases,
262        scoped_path_aliases: input.scoped_path_aliases,
263        scss_include_paths: input.scss_include_paths,
264        static_dir_mappings: input.static_dir_mappings,
265        framework_static_dir_mappings: input.framework_static_dir_mappings,
266        root: input.root,
267        canonical_fallback: canonical_fallback.as_ref(),
268        tsconfig_warned: &tsconfig_warned,
269        tsconfig_cache: &tsconfig_cache,
270        canonicalize_cache: &canonicalize_cache,
271    };
272
273    let resolved_outputs: Vec<ResolvedModuleOutput> = input
274        .modules
275        .par_iter()
276        .filter_map(|module| {
277            resolve_module_imports(
278                module,
279                &ctx,
280                &ProjectResolveRules {
281                    glob_matcher_cache: &glob_matcher_cache,
282                    pattern_root: &pattern_root,
283                    jsx_rules: &jsx_rules,
284                },
285                &file_paths,
286                &canonical_paths,
287                input.files,
288            )
289        })
290        .collect();
291    let mut resolved = Vec::with_capacity(resolved_outputs.len());
292    let mut vitest_mock_operations = Vec::new();
293    for output in resolved_outputs {
294        resolved.push(output.module);
295        vitest_mock_operations.extend(output.vitest_mock_operations);
296        work += output.work;
297    }
298    work.canonicalize_calls += canonicalize_cache.distinct_paths() as u64;
299
300    apply_specifier_upgrades(&mut resolved, &mut vitest_mock_operations);
301
302    synthesize_platform_family_edges(&mut resolved, input.files, input.active_plugins);
303
304    synthesize_package_import_condition_edges(&mut resolved, &ctx);
305
306    synthesize_auto_import_edges(
307        &mut resolved,
308        input.modules,
309        input.auto_imports,
310        &path_to_id,
311        &raw_path_to_id,
312    );
313
314    let replaced_module_targets = final_replaced_module_targets(vitest_mock_operations);
315    let probes = missed_probes.finish();
316
317    ResolvedProject {
318        modules: resolved,
319        replaced_module_targets,
320        work,
321        missed_probes: probes.missed,
322        package_manifests: probes.package_manifests,
323    }
324}
325
326fn build_workspace_roots<'a>(
327    workspaces: &'a [fallow_config::WorkspaceInfo],
328    canonical_ws_roots: &'a [PathBuf],
329) -> FxHashMap<&'a str, &'a Path> {
330    workspaces
331        .iter()
332        .zip(canonical_ws_roots.iter())
333        .map(|(ws, canonical)| (ws.name.as_str(), canonical.as_path()))
334        .collect()
335}
336
337fn build_canonical_file_paths(files: &[DiscoveredFile], root_is_canonical: bool) -> Vec<PathBuf> {
338    if root_is_canonical {
339        return Vec::new();
340    }
341
342    files
343        .par_iter()
344        .map(|f| crate::read_trace::canonicalize(&f.path).unwrap_or_else(|_| f.path.clone()))
345        .collect()
346}
347
348/// Load the root package manifest plus each workspace manifest into the
349/// `PackageManifestInfo` list used for `exports` / `imports` resolution.
350///
351/// Manifests come from `package.json` when present, otherwise `deno.json` /
352/// `deno.jsonc` (`name` + `exports`), so pure Deno workspaces resolve without
353/// npm bridge files.
354fn build_package_manifests(
355    input: &ResolveAllImportsInput<'_>,
356    canonical_ws_roots: &[PathBuf],
357) -> Vec<PackageManifestInfo> {
358    let root_canonical =
359        crate::read_trace::canonicalize(input.root).unwrap_or_else(|_| input.root.to_path_buf());
360    let root_probe = fallow_config::probe_dir_manifest(input.root);
361    let root_import_map = merge_deno_import_maps(&[], input.root, root_probe.deno_import_map);
362    let mut package_manifests = Vec::new();
363    if let Ok(Some((_name, package_json, _deps))) = root_probe.manifest {
364        package_manifests.push(PackageManifestInfo {
365            root: input.root.to_path_buf(),
366            canonical_root: root_canonical,
367            name: package_json.name.clone(),
368            package_json,
369            deno_import_map: root_import_map.clone(),
370        });
371    }
372    for (ws, canonical_root) in input.workspaces.iter().zip(canonical_ws_roots.iter()) {
373        let ws_probe = fallow_config::probe_dir_manifest(&ws.root);
374        if let Ok(Some((_name, package_json, _deps))) = ws_probe.manifest {
375            package_manifests.push(PackageManifestInfo {
376                root: ws.root.clone(),
377                canonical_root: canonical_root.clone(),
378                name: package_json.name.clone().or_else(|| Some(ws.name.clone())),
379                package_json,
380                deno_import_map: merge_deno_import_maps(
381                    &root_import_map,
382                    &ws.root,
383                    ws_probe.deno_import_map,
384                ),
385            });
386        }
387    }
388    package_manifests
389}
390
391/// Merge inherited and package-local Deno import maps once per resolver
392/// session. Equal local keys replace inherited keys while retaining the
393/// declaring directory needed for relative target resolution. The local map
394/// comes from the caller's single-probe manifest load so the Deno config is
395/// not read and parsed a second time.
396fn merge_deno_import_maps(
397    inherited: &[DenoImportMapEntry],
398    package_root: &Path,
399    local: Option<(PathBuf, Vec<(String, String)>)>,
400) -> Vec<DenoImportMapEntry> {
401    let mut entries: FxHashMap<String, DenoImportMapEntry> = inherited
402        .iter()
403        .cloned()
404        .map(|entry| (entry.key.clone(), entry))
405        .collect();
406
407    if let Some((config_path, local_entries)) = local {
408        let declaring_dir = config_path.parent().unwrap_or(package_root).to_path_buf();
409        for (key, target) in local_entries {
410            entries.insert(
411                key.clone(),
412                DenoImportMapEntry {
413                    key,
414                    target,
415                    declaring_dir: declaring_dir.clone(),
416                },
417            );
418        }
419    }
420
421    let mut entries: Vec<_> = entries.into_values().collect();
422    entries.sort_by(|a, b| a.key.cmp(&b.key));
423    entries
424}
425
426/// Build the path-to-`FileId` index, keyed by canonical paths when the root is
427/// not already canonical and by raw paths otherwise.
428fn build_path_to_id<'a>(
429    files: &'a [DiscoveredFile],
430    canonical_paths: &'a [PathBuf],
431    root_is_canonical: bool,
432) -> FxHashMap<&'a Path, FileId> {
433    if root_is_canonical {
434        files.iter().map(|f| (f.path.as_path(), f.id)).collect()
435    } else {
436        canonical_paths
437            .iter()
438            .enumerate()
439            .map(|(idx, canonical)| (canonical.as_path(), files[idx].id))
440            .collect()
441    }
442}
443
444/// Per-run state that every module resolution reads.
445struct ProjectResolveRules<'a> {
446    glob_matcher_cache: &'a GlobMatcherCache,
447    pattern_root: &'a Path,
448    jsx_rules: &'a [CompiledJsxRule<'a>],
449}
450
451fn resolve_module_imports(
452    module: &ModuleInfo,
453    ctx: &ResolveContext<'_>,
454    rules: &ProjectResolveRules<'_>,
455    file_paths: &[&Path],
456    canonical_paths: &[PathBuf],
457    files: &[DiscoveredFile],
458) -> Option<ResolvedModuleOutput> {
459    let Some(file_path) = file_paths.get(module.file_id.0 as usize) else {
460        tracing::warn!(
461            file_id = module.file_id.0,
462            "Skipping module with unknown file_id during resolution"
463        );
464        return None;
465    };
466
467    let resolve = || {
468        let mut all_imports = resolve_static_imports(ctx, file_path, &module.imports);
469        all_imports.extend(resolve_config_jsx_runtime_imports(
470            ctx,
471            file_path,
472            module,
473            rules.jsx_rules,
474        ));
475        all_imports.extend(resolve_require_imports(
476            ctx,
477            file_path,
478            &module.require_calls,
479        ));
480
481        let from_dir = if canonical_paths.is_empty() {
482            file_path.parent().unwrap_or(file_path)
483        } else {
484            canonical_paths
485                .get(module.file_id.0 as usize)
486                .and_then(|p| p.parent())
487                .unwrap_or(file_path)
488        };
489
490        let vitest_mock_operations =
491            resolve_vitest_mock_operations(module.file_id, &module.semantic_facts, ctx, file_path);
492        let module = build_resolved_module(ResolvedModuleBuildInput {
493            module,
494            ctx,
495            glob_matcher_cache: rules.glob_matcher_cache,
496            pattern_root: rules.pattern_root,
497            file_path,
498            from_dir,
499            canonical_paths,
500            files,
501            all_imports,
502        });
503        (module, vitest_mock_operations)
504    };
505    let ((module, vitest_mock_operations), work) =
506        memo::in_file_scope(file_path, || work::in_module_scope(resolve));
507
508    Some(ResolvedModuleOutput {
509        module,
510        vitest_mock_operations,
511        work,
512    })
513}
514
515struct ResolvedModuleOutput {
516    module: ResolvedModule,
517    vitest_mock_operations: Vec<ResolvedVitestMockOperation>,
518    work: ResolveWork,
519}
520
521fn resolve_vitest_mock_operations(
522    source_file: FileId,
523    semantic_facts: &[SemanticFact],
524    ctx: &ResolveContext<'_>,
525    file_path: &Path,
526) -> Vec<ResolvedVitestMockOperation> {
527    let mut operations: Vec<_> = semantic_facts
528        .iter()
529        .filter_map(|fact| {
530            let SemanticFact::VitestModuleMockOperation(operation) = fact else {
531                return None;
532            };
533            Some(ResolvedVitestMockOperation {
534                source_file,
535                source_specifier: operation.source.clone(),
536                call_start: operation.call_start,
537                action: operation.action,
538                target: specifier::resolve_import_specifier(
539                    ctx,
540                    file_path,
541                    &operation.source,
542                    false,
543                ),
544            })
545        })
546        .collect();
547    operations.sort_unstable_by(|left, right| {
548        left.call_start
549            .cmp(&right.call_start)
550            .then_with(|| left.source_specifier.cmp(&right.source_specifier))
551    });
552    operations
553}
554
555fn final_replaced_module_targets(
556    mut operations: Vec<ResolvedVitestMockOperation>,
557) -> Vec<ResolvedReplacedModuleTarget> {
558    operations.sort_unstable_by(|left, right| {
559        left.source_file
560            .0
561            .cmp(&right.source_file.0)
562            .then_with(|| left.call_start.cmp(&right.call_start))
563            .then_with(|| left.source_specifier.cmp(&right.source_specifier))
564    });
565
566    let mut final_operations = FxHashMap::default();
567    for operation in operations {
568        let Some(target_file) = operation.target.internal_file_id() else {
569            continue;
570        };
571        final_operations.insert((operation.source_file, target_file), operation.action);
572    }
573
574    let mut targets: Vec<_> = final_operations
575        .into_iter()
576        .filter_map(|((source_file, target_file), action)| {
577            action
578                .replaces_original()
579                .then_some(ResolvedReplacedModuleTarget {
580                    source_file,
581                    target_file,
582                })
583        })
584        .collect();
585    targets.sort_unstable_by_key(|target| (target.source_file.0, target.target_file.0));
586    targets
587}
588
589struct ResolvedModuleBuildInput<'a> {
590    module: &'a ModuleInfo,
591    ctx: &'a ResolveContext<'a>,
592    glob_matcher_cache: &'a GlobMatcherCache,
593    pattern_root: &'a Path,
594    file_path: &'a Path,
595    from_dir: &'a Path,
596    canonical_paths: &'a [PathBuf],
597    files: &'a [DiscoveredFile],
598    all_imports: Vec<types::ResolvedImport>,
599}
600
601fn build_resolved_module(input: ResolvedModuleBuildInput<'_>) -> ResolvedModule {
602    let ctx = input.ctx;
603    let mut module = resolved_module_without_export_hints(input);
604    module.missing_export_targets = collect_missing_export_targets(ctx, &module);
605    module
606}
607
608/// Record the missing target paths of each unresolved specifier once: the
609/// `exports` paths of a bare specifier, or else the paths that a matching
610/// path alias substitutes.
611fn collect_missing_export_targets(
612    ctx: &ResolveContext<'_>,
613    module: &ResolvedModule,
614) -> Vec<MissingExportTarget> {
615    let mut seen: FxHashSet<&str> = FxHashSet::default();
616    let mut targets: Vec<MissingExportTarget> = module
617        .all_resolved_source_edges()
618        .filter_map(|edge| match edge.target() {
619            ResolveResult::Unresolvable(specifier) => Some(specifier.as_str()),
620            _ => None,
621        })
622        .filter(|specifier| seen.insert(specifier))
623        .filter_map(|specifier| {
624            let aliased = workspace_alias::aliased_specifier(ctx, &module.path, specifier);
625            fallbacks::missing_package_export_paths(ctx, aliased.as_deref().unwrap_or(specifier))
626                .or_else(|| missing_alias_targets(ctx, &module.path, specifier))
627                .map(|paths| MissingExportTarget {
628                    specifier: specifier.to_string(),
629                    paths,
630                })
631        })
632        .collect();
633    targets.sort_unstable_by(|left, right| left.specifier.cmp(&right.specifier));
634    targets
635}
636
637/// The paths that the nearest tsconfig `paths` entry substitutes for an
638/// unresolved `specifier`, or else the paths that a plugin path alias
639/// substitutes. `None` when no alias matches.
640fn missing_alias_targets(
641    ctx: &ResolveContext<'_>,
642    from_file: &Path,
643    specifier: &str,
644) -> Option<Vec<PathBuf>> {
645    let tsconfig_targets =
646        package_credit::nearest_tsconfig_alias_targets(ctx, from_file, specifier);
647    if tsconfig_targets.is_empty() {
648        return fallbacks::missing_path_alias_targets(ctx, from_file, specifier);
649    }
650    Some(
651        tsconfig_targets
652            .iter()
653            .map(|target| fallbacks::normalize_path_lexically(target))
654            .collect(),
655    )
656}
657
658fn resolved_module_without_export_hints(input: ResolvedModuleBuildInput<'_>) -> ResolvedModule {
659    ResolvedModule {
660        file_id: input.module.file_id,
661        path: input.file_path.to_path_buf(),
662        exports: Arc::clone(&input.module.exports),
663        re_exports: resolve_re_exports(input.ctx, input.file_path, &input.module.re_exports),
664        resolved_imports: input.all_imports,
665        resolved_dynamic_imports: resolve_dynamic_imports(
666            input.ctx,
667            input.file_path,
668            &input.module.dynamic_imports,
669        ),
670        resolved_dynamic_patterns: resolve_dynamic_patterns(
671            input.glob_matcher_cache,
672            input.pattern_root,
673            input.from_dir,
674            &input.module.dynamic_import_patterns,
675            input.canonical_paths,
676            input.files,
677        ),
678        member_accesses: Arc::clone(&input.module.member_accesses),
679        semantic_facts: Arc::clone(&input.module.semantic_facts),
680        whole_object_uses: Arc::clone(&input.module.whole_object_uses),
681        has_cjs_exports: input.module.has_cjs_exports,
682        has_angular_component_template_url: input.module.has_angular_component_template_url,
683        unused_import_bindings: input
684            .module
685            .unused_import_bindings
686            .iter()
687            .cloned()
688            .collect(),
689        type_referenced_import_bindings: input.module.type_referenced_import_bindings.clone(),
690        value_referenced_import_bindings: input.module.value_referenced_import_bindings.clone(),
691        namespace_object_aliases: input.module.namespace_object_aliases.clone(),
692        exported_factory_returns: Arc::clone(&input.module.exported_factory_returns),
693        exported_factory_return_object_shapes: Arc::clone(
694            &input.module.exported_factory_return_object_shapes,
695        ),
696        type_member_types: Arc::clone(&input.module.type_member_types),
697        missing_export_targets: Vec::new(),
698    }
699}
700
701fn is_auto_import_builtin(name: &str) -> bool {
702    is_js_auto_import_builtin(name)
703        || is_vue_auto_import_builtin(name)
704        || is_nuxt_auto_import_builtin(name)
705}
706
707fn is_js_auto_import_builtin(name: &str) -> bool {
708    matches!(
709        name,
710        "AbortController"
711            | "AbortSignal"
712            | "Array"
713            | "ArrayBuffer"
714            | "BigInt"
715            | "Blob"
716            | "Boolean"
717            | "Buffer"
718            | "CSS"
719            | "DOMParser"
720            | "Date"
721            | "Document"
722            | "Error"
723            | "Event"
724            | "EventTarget"
725            | "File"
726            | "FormData"
727            | "Intl"
728            | "JSON"
729            | "Map"
730            | "Math"
731            | "Number"
732            | "Object"
733            | "Promise"
734            | "Reflect"
735            | "RegExp"
736            | "Response"
737            | "Set"
738            | "String"
739            | "Symbol"
740            | "URL"
741            | "URLSearchParams"
742            | "WeakMap"
743            | "WeakSet"
744            | "Window"
745            | "alert"
746            | "clearInterval"
747            | "clearTimeout"
748            | "console"
749            | "document"
750            | "fetch"
751            | "global"
752            | "globalThis"
753            | "localStorage"
754            | "navigator"
755            | "process"
756            | "requestAnimationFrame"
757            | "sessionStorage"
758            | "setInterval"
759            | "setTimeout"
760            | "window"
761    )
762}
763
764fn is_vue_auto_import_builtin(name: &str) -> bool {
765    matches!(name, |"computed"| "customRef"
766        | "defineAsyncComponent"
767        | "defineComponent"
768        | "effectScope"
769        | "getCurrentInstance"
770        | "h"
771        | "inject"
772        | "isProxy"
773        | "isReactive"
774        | "isReadonly"
775        | "isRef"
776        | "markRaw"
777        | "nextTick"
778        | "onActivated"
779        | "onBeforeMount"
780        | "onBeforeUnmount"
781        | "onBeforeUpdate"
782        | "onDeactivated"
783        | "onErrorCaptured"
784        | "onMounted"
785        | "onRenderTracked"
786        | "onRenderTriggered"
787        | "onScopeDispose"
788        | "onServerPrefetch"
789        | "onUnmounted"
790        | "onUpdated"
791        | "provide"
792        | "reactive"
793        | "readonly"
794        | "ref"
795        | "resolveComponent"
796        | "shallowReactive"
797        | "shallowReadonly"
798        | "shallowRef"
799        | "toRaw"
800        | "toRef"
801        | "toRefs"
802        | "triggerRef"
803        | "unref"
804        | "watch"
805        | "watchEffect"
806        | "watchPostEffect"
807        | "watchSyncEffect")
808}
809
810fn is_nuxt_auto_import_builtin(name: &str) -> bool {
811    matches!(name, |"useAsyncData"| "useCookie"
812        | "useError"
813        | "useFetch"
814        | "useHead"
815        | "useLazyAsyncData"
816        | "useLazyFetch"
817        | "useNuxtApp"
818        | "useRequestEvent"
819        | "useRequestHeaders"
820        | "useRoute"
821        | "useRouter"
822        | "useRuntimeConfig"
823        | "useSeoMeta"
824        | "useState")
825}
826
827/// Build a synthetic [`ImportInfo`] for a convention auto-import. Component and
828/// default kinds credit the default export; named kinds credit the named export.
829fn synthetic_auto_import_info(name: &str, kind: AutoImportKind) -> ImportInfo {
830    let imported_name = match kind {
831        AutoImportKind::Named => ImportedName::Named(name.to_string()),
832        AutoImportKind::Default | AutoImportKind::DefaultComponent => ImportedName::Default,
833    };
834    ImportInfo {
835        source: format!("<auto-import:{name}>"),
836        imported_name,
837        local_name: name.to_string(),
838        is_type_only: false,
839        is_type_only_star: false,
840        from_style: false,
841        span: Span::default(),
842        source_span: Span::default(),
843    }
844}