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