Skip to main content

fallow_graph/resolve/
fallbacks.rs

1//! Resolution fallback strategies for import specifiers.
2//!
3//! Handles path alias fallbacks, output-to-source directory mapping, pnpm virtual
4//! store detection, node_modules package extraction, and dynamic import glob patterns.
5
6use std::path::{Path, PathBuf};
7
8use fallow_types::discover::FileId;
9use rustc_hash::FxHashMap;
10
11use super::path_info::{extract_package_name, is_bare_specifier, is_valid_package_name};
12use super::types::{
13    MISSING_ONLY_OUTPUT_DIRS, OUTPUT_DIRS, PackageManifestInfo, ResolveContext, ResolveResult,
14    SOURCE_EXTS,
15};
16use crate::read_trace::TracedPath;
17
18#[path = "fallbacks_package_map.rs"]
19mod package_map;
20#[path = "fallbacks_path_aliases.rs"]
21mod path_aliases;
22#[path = "fallbacks_relative_package_root.rs"]
23mod relative_package_root;
24#[path = "fallbacks_scss_paths.rs"]
25mod scss_paths;
26#[path = "fallbacks_tsconfig_output.rs"]
27mod tsconfig_output;
28#[path = "fallbacks_workspace_package_asset.rs"]
29mod workspace_package_asset;
30
31pub(super) use package_map::{PackageMapTarget, package_map_target};
32pub(super) use path_aliases::{
33    alias_match_remainder, applicable_path_aliases, matches_plugin_path_alias,
34    missing_path_alias_targets, try_path_alias_fallback,
35};
36pub(super) use relative_package_root::try_relative_package_root_source_fallback;
37use scss_paths::{find_scss_through_path_alias, lookup_scss_path};
38pub(super) use tsconfig_output::{
39    try_canonical_source_fallbacks, try_relative_output_source_fallbacks,
40};
41use tsconfig_output::{try_package_source_or_output, try_tsconfig_output_source};
42use workspace_package_asset::{exports_target_asset, workspace_package_asset};
43
44/// Try SCSS partial resolution: `_filename` and `_index` conventions.
45///
46/// SCSS resolves imports in this order:
47/// 1. `@use 'variables'` → `_variables.scss` (partial convention)
48/// 2. `@use 'components'` → `components/_index.scss` or `components/index.scss` (directory index)
49///
50/// Handles both relative (`../styles/variables`) and bare (`variables`) specifiers
51/// that were normalized to `./variables` during extraction.
52pub(super) fn try_scss_partial_fallback(
53    ctx: &ResolveContext<'_>,
54    from_file: &Path,
55    specifier: &str,
56) -> Option<ResolveResult> {
57    if specifier.contains(':') {
58        return None;
59    }
60
61    let spec_path = Path::new(specifier);
62    let filename = spec_path.file_name()?.to_str()?;
63
64    if filename.starts_with('_') {
65        return None;
66    }
67
68    let partial_filename = format!("_{filename}");
69    let partial_specifier = if let Some(parent) = spec_path.parent()
70        && !parent.as_os_str().is_empty()
71    {
72        format!("{}/{partial_filename}", parent.display())
73    } else {
74        partial_filename
75    };
76
77    if let Some(result) = try_resolve_scss(ctx, from_file, &partial_specifier) {
78        return Some(result);
79    }
80
81    let index_partial = format!("{specifier}/_index");
82    if let Some(result) = try_resolve_scss(ctx, from_file, &index_partial) {
83        return Some(result);
84    }
85
86    let index_plain = format!("{specifier}/index");
87    try_resolve_scss(ctx, from_file, &index_plain)
88}
89
90/// Try non-partial CSS-extension resolution: `<spec>.scss`, `<spec>.sass`,
91/// `<spec>.css` from the importing file's parent.
92///
93/// This is needed when the standard resolver's extension list contains both
94/// `.vue` / `.svelte` / `.astro` AND CSS extensions. For an SFC `<style>` block
95/// importing `./Foo`, the standard resolver picks `Foo.vue` (the SFC itself!)
96/// before `Foo.scss` because `.vue` comes earlier in the extension list. SCSS
97/// imports must restrict resolution to CSS-family extensions to avoid this
98/// self-import collision. Only invoked when `from_style = true`. See issue #195.
99pub(super) fn try_css_extension_fallback(
100    ctx: &ResolveContext<'_>,
101    from_file: &Path,
102    specifier: &str,
103) -> Option<ResolveResult> {
104    if specifier.contains(':') {
105        return None;
106    }
107    let spec_path = Path::new(specifier);
108    let already_css_ext = spec_path
109        .extension()
110        .and_then(|e| e.to_str())
111        .is_some_and(|e| {
112            e.eq_ignore_ascii_case("css")
113                || e.eq_ignore_ascii_case("scss")
114                || e.eq_ignore_ascii_case("sass")
115        });
116    if already_css_ext {
117        return try_resolve_scss(ctx, from_file, specifier);
118    }
119    for ext in ["scss", "sass", "css"] {
120        let candidate = format!("{specifier}.{ext}");
121        if let Some(result) = try_resolve_scss(ctx, from_file, &candidate) {
122            return Some(result);
123        }
124    }
125    None
126}
127
128/// Attempt to resolve a single SCSS specifier and map to an internal module.
129fn try_resolve_scss(
130    ctx: &ResolveContext<'_>,
131    from_file: &Path,
132    specifier: &str,
133) -> Option<ResolveResult> {
134    super::work::note_oxc_resolve();
135    let resolved = ctx.resolver.resolve_file(from_file, specifier).ok()?;
136    let resolved_path = resolved.path();
137
138    if let Some(&file_id) = ctx.raw_path_to_id.get(resolved_path) {
139        return Some(ResolveResult::InternalModule(file_id));
140    }
141    if let Some(canonical) = ctx.canonicalize_cache.get(resolved_path)
142        && let Some(&file_id) = ctx.path_to_id.get(canonical.as_path())
143    {
144        return Some(ResolveResult::InternalModule(file_id));
145    }
146    None
147}
148
149/// Try SCSS `includePaths` fallback: resolve the specifier against each
150/// framework-contributed include directory.
151///
152/// Angular's `stylePreprocessorOptions.includePaths` (and Nx's equivalent via
153/// project.json) adds extra search paths that SCSS resolves against before
154/// falling back to node_modules. Bare `@use 'variables'` statements that were
155/// normalized to `./variables` at extraction time fail the usual file-local
156/// resolution, so when the importing file is `.scss`/`.sass` and the spec
157/// originated from such a bare specifier, we retry against each include path,
158/// applying the SCSS partial (`_variables`) and directory-index conventions.
159/// SFC `<style lang="scss">` imports pass `from_style = true` because their
160/// filesystem importer is `.vue` / `.svelte`, not `.scss` / `.sass`.
161///
162/// The specifier arrives with a `./` prefix because `normalize_css_import_path`
163/// rewrites bare extensionless SCSS specifiers to relative ones. We strip that
164/// prefix here to re-enter the include-path search from the root of each
165/// directory. Relative specifiers that already escape the importing file
166/// (e.g. `../shared/variables`) are left untouched — include paths only
167/// disambiguate bare specifiers, not explicit relative paths.
168pub(super) fn try_scss_include_path_fallback(
169    ctx: &ResolveContext<'_>,
170    from_file: &Path,
171    specifier: &str,
172    from_style: bool,
173) -> Option<ResolveResult> {
174    if ctx.scss_include_paths.is_empty()
175        && ctx.path_aliases.is_empty()
176        && ctx.scoped_path_aliases.is_empty()
177    {
178        return None;
179    }
180    let is_scss_importer = from_file
181        .extension()
182        .is_some_and(|e| e == "scss" || e == "sass");
183    if !is_scss_importer && !from_style {
184        return None;
185    }
186    if specifier.contains(':') {
187        return None;
188    }
189    let bare = specifier.strip_prefix("./")?;
190    if bare.starts_with("..") || bare.starts_with('/') {
191        return None;
192    }
193
194    for include_dir in ctx.scss_include_paths {
195        if let Some(file_id) = find_scss_in_dir(include_dir, bare, ctx) {
196            return Some(ResolveResult::InternalModule(file_id));
197        }
198    }
199    find_scss_through_path_alias(ctx, from_file, bare).map(ResolveResult::InternalModule)
200}
201
202/// Probe an SCSS include directory for a bare specifier, applying the standard
203/// SCSS resolution order: exact file, `_`-prefixed partial, `_index` / `index`
204/// directory conventions. Supports `.scss` and `.sass` extensions.
205fn find_scss_in_dir(include_dir: &Path, bare: &str, ctx: &ResolveContext<'_>) -> Option<FileId> {
206    let bare_path = Path::new(bare);
207    let has_scss_ext = matches!(
208        bare_path.extension().and_then(|e| e.to_str()),
209        Some(ext) if ext.eq_ignore_ascii_case("scss") || ext.eq_ignore_ascii_case("sass")
210    );
211
212    let parent = bare_path.parent();
213    let stem_with_ext = bare_path.file_name()?.to_str()?;
214    let stem_without_ext = bare_path.file_stem().and_then(|s| s.to_str())?;
215
216    let build = |rel: &Path| -> std::path::PathBuf { include_dir.join(rel) };
217    let join_with_parent = |name: &str| -> std::path::PathBuf {
218        parent.map_or_else(|| build(Path::new(name)), |p| build(&p.join(name)))
219    };
220
221    let exts: &[&str] = if has_scss_ext {
222        &[""]
223    } else {
224        &["scss", "sass"]
225    };
226
227    for ext in exts {
228        let suffix = if ext.is_empty() {
229            String::new()
230        } else {
231            format!(".{ext}")
232        };
233        let direct = if ext.is_empty() {
234            build(bare_path)
235        } else {
236            join_with_parent(&format!("{stem_with_ext}{suffix}"))
237        };
238        if let Some(fid) = lookup_scss_path(&direct, ctx) {
239            return Some(fid);
240        }
241        let partial_name = if ext.is_empty() {
242            format!("_{stem_with_ext}")
243        } else {
244            format!("_{stem_without_ext}{suffix}")
245        };
246        let partial = join_with_parent(&partial_name);
247        if let Some(fid) = lookup_scss_path(&partial, ctx) {
248            return Some(fid);
249        }
250        if ext.is_empty() {
251            continue;
252        }
253        let idx_partial = build(bare_path).join(format!("_index{suffix}"));
254        if let Some(fid) = lookup_scss_path(&idx_partial, ctx) {
255            return Some(fid);
256        }
257        let idx_plain = build(bare_path).join(format!("index{suffix}"));
258        if let Some(fid) = lookup_scss_path(&idx_plain, ctx) {
259            return Some(fid);
260        }
261    }
262    None
263}
264
265/// Try SCSS `node_modules` fallback: resolve a bare specifier by walking up
266/// from the importing file and probing each ancestor's `node_modules/` dir.
267///
268/// Sass's `@import` / `@use` resolution algorithm searches `node_modules/` for
269/// bare specifiers after the file-local and `includePaths` searches fail.
270/// `@import 'bootstrap/scss/functions'` resolves to
271/// `node_modules/bootstrap/scss/_functions.scss` via the standard partial
272/// convention; `@import 'animate.css/animate.min'` resolves to
273/// `node_modules/animate.css/animate.min.css` via the CSS-extension fallback.
274///
275/// Files inside `node_modules/` are not in fallow's file index (the default
276/// ignore patterns exclude them), so this function returns
277/// `ResolveResult::NpmPackage` when a candidate exists on disk. That ensures
278/// (1) the `@import` is not reported as unresolved and (2) the npm package is
279/// marked as a used dependency so `unused-dependencies` / `unlisted-dependencies`
280/// stay accurate.
281///
282/// The specifier arrives with a `./` prefix because `normalize_css_import_path`
283/// rewrites bare extensionless SCSS specifiers to relative ones. Parent-relative
284/// specifiers are skipped — they explicitly escape the importing file and must
285/// not be silently redirected to `node_modules`. See issue #125.
286pub(super) fn try_scss_node_modules_fallback(
287    _ctx: &ResolveContext<'_>,
288    from_file: &Path,
289    specifier: &str,
290    from_style: bool,
291) -> Option<ResolveResult> {
292    if specifier.contains(':') {
293        return None;
294    }
295    let is_scss_importer = from_file
296        .extension()
297        .is_some_and(|e| e == "scss" || e == "sass");
298    if !is_scss_importer && !from_style {
299        return None;
300    }
301    let bare = specifier.strip_prefix("./")?;
302    if bare.starts_with("..") || bare.starts_with('/') {
303        return None;
304    }
305    if bare.is_empty() {
306        return None;
307    }
308
309    let mut dir = from_file.parent()?;
310    loop {
311        let nm_dir = dir.join("node_modules");
312        if nm_dir.traced_is_dir()
313            && let Some(path) = find_scss_in_node_modules(&nm_dir, bare)
314            && let Some(pkg_name) = extract_package_name_from_node_modules_path(&path)
315        {
316            return Some(ResolveResult::NpmPackage(pkg_name));
317        }
318        let Some(parent) = dir.parent() else {
319            break;
320        };
321        dir = parent;
322    }
323    None
324}
325
326/// Probe candidate filesystem paths for a bare SCSS specifier inside a single
327/// `node_modules/` directory, applying Sass resolution conventions.
328///
329/// Candidate order:
330/// 1. `<bare>.scss` / `<bare>.sass` / `<bare>.css` (extension append)
331/// 2. `<parent>/_<stem>.scss` / `<parent>/_<stem>.sass` (partial convention)
332/// 3. `<bare>/_index.scss` / `<bare>/index.scss` (and `.sass` variants)
333/// 4. `<bare>` (exact, for specifiers that already carry an extension)
334fn find_scss_in_node_modules(nm_dir: &Path, bare: &str) -> Option<PathBuf> {
335    let bare_path = Path::new(bare);
336    let file_name = bare_path.file_name()?.to_str()?;
337    let parent = bare_path.parent();
338    let join_with_parent = |name: &str| -> PathBuf {
339        parent.map_or_else(|| nm_dir.join(name), |p| nm_dir.join(p).join(name))
340    };
341
342    for ext in &["scss", "sass", "css"] {
343        let candidate = join_with_parent(&format!("{file_name}.{ext}"));
344        if candidate.traced_is_file() {
345            return Some(candidate);
346        }
347    }
348    for ext in &["scss", "sass"] {
349        let candidate = join_with_parent(&format!("_{file_name}.{ext}"));
350        if candidate.traced_is_file() {
351            return Some(candidate);
352        }
353    }
354    for ext in &["scss", "sass"] {
355        let idx_partial = nm_dir.join(bare).join(format!("_index.{ext}"));
356        if idx_partial.traced_is_file() {
357            return Some(idx_partial);
358        }
359        let idx_plain = nm_dir.join(bare).join(format!("index.{ext}"));
360        if idx_plain.traced_is_file() {
361            return Some(idx_plain);
362        }
363    }
364    let exact = nm_dir.join(bare);
365    if exact.traced_is_file() {
366        return Some(exact);
367    }
368    None
369}
370
371/// Try to map a resolved output path (e.g., `packages/ui/dist/utils.js`) back to
372/// the corresponding source file (e.g., `packages/ui/src/utils.ts`).
373///
374/// This handles cross-workspace imports that go through `exports` maps pointing to
375/// built output directories. Since fallow ignores `dist/`, `build/`, etc. by default,
376/// the resolved path won't be in the file set, but the source file will be.
377///
378/// Nested output subdirectories (e.g., `dist/esm/utils.mjs`, `build/cjs/index.cjs`)
379/// are handled by finding the last output directory component (closest to the file,
380/// avoiding false matches on parent directories) and then walking backwards to collect
381/// all consecutive output directory components before it.
382pub(super) fn try_source_fallback(
383    resolved: &Path,
384    path_to_id: &FxHashMap<&Path, FileId>,
385) -> Option<FileId> {
386    try_source_fallback_with(Path::new(""), resolved, path_to_id, &[OUTPUT_DIRS])
387}
388
389/// Map a package manifest target below `lib/` to `src/`.
390///
391/// Callers run this only after the target is absent from the file set and
392/// after [`try_source_fallback`] found no match. `lib` (from
393/// `MISSING_ONLY_OUTPUT_DIRS`) applies only to the path below `package_root`,
394/// so a package directory named `lib` does not change the result. Generic
395/// relative imports never use this function.
396fn try_missing_only_source_fallback(
397    package_root: &Path,
398    resolved: &Path,
399    path_to_id: &FxHashMap<&Path, FileId>,
400) -> Option<FileId> {
401    let relative = resolved.strip_prefix(package_root).ok()?;
402    try_source_fallback_with(
403        package_root,
404        relative,
405        path_to_id,
406        &[OUTPUT_DIRS, MISSING_ONLY_OUTPUT_DIRS],
407    )
408}
409
410/// Map the last output directory component of `relative` (any name in
411/// `dir_lists`) to `src/`, and look up the result below `base` in `path_to_id`.
412fn try_source_fallback_with(
413    base: &Path,
414    relative: &Path,
415    path_to_id: &FxHashMap<&Path, FileId>,
416    dir_lists: &[&[&str]],
417) -> Option<FileId> {
418    let components: Vec<_> = relative.components().collect();
419
420    let is_output_dir = |c: &std::path::Component| -> bool {
421        if let std::path::Component::Normal(s) = c
422            && let Some(name) = s.to_str()
423        {
424            return dir_lists.iter().any(|dirs| dirs.contains(&name));
425        }
426        false
427    };
428
429    let last_output_pos = components.iter().rposition(&is_output_dir)?;
430
431    let mut first_output_pos = last_output_pos;
432    while first_output_pos > 0 && is_output_dir(&components[first_output_pos - 1]) {
433        first_output_pos -= 1;
434    }
435
436    let relative_prefix: PathBuf = components[..first_output_pos].iter().collect();
437    let prefix = if base.as_os_str().is_empty() {
438        relative_prefix
439    } else {
440        base.join(relative_prefix)
441    };
442
443    let suffix: PathBuf = components[last_output_pos + 1..].iter().collect();
444    let file_name = suffix.file_name()?.to_str()?;
445    let stem = output_source_stem(file_name);
446    let source_dir = match suffix.parent() {
447        Some(parent) => prefix.join("src").join(parent),
448        None => prefix.join("src"),
449    };
450
451    for ext in SOURCE_EXTS {
452        let source_candidate = source_dir.join(format!("{stem}.{ext}"));
453        if let Some(&file_id) = path_to_id.get(source_candidate.as_path()) {
454            return Some(file_id);
455        }
456    }
457
458    // A package can copy a hand-written declaration file from `src/` to the
459    // output directory unchanged.
460    if is_declaration_file_name(file_name) {
461        return path_to_id
462            .get(source_dir.join(file_name).as_path())
463            .copied();
464    }
465
466    None
467}
468
469/// Declaration suffixes that build tools emit next to the output files.
470const DECLARATION_SUFFIXES: &[&str] = &[".d.ts", ".d.mts", ".d.cts"];
471
472fn declaration_stem(file_name: &str) -> Option<&str> {
473    DECLARATION_SUFFIXES
474        .iter()
475        .find_map(|suffix| file_name.strip_suffix(suffix))
476        .filter(|stem| !stem.is_empty())
477}
478
479pub(super) fn is_declaration_file_name(file_name: &str) -> bool {
480    declaration_stem(file_name).is_some()
481}
482
483/// Return the source stem of a build output file name.
484///
485/// The stem keeps every dot in the base name. `feature.port.d.ts` and
486/// `feature.port.js` both give `feature.port`. `Path::with_extension` removes
487/// only the last extension, so it keeps `.d` in a declaration file name.
488pub(super) fn output_source_stem(file_name: &str) -> &str {
489    if let Some(stem) = declaration_stem(file_name) {
490        return stem;
491    }
492    match file_name.rsplit_once('.') {
493        Some((stem, _)) if !stem.is_empty() => stem,
494        _ => file_name,
495    }
496}
497
498/// Try to resolve a package `imports` entry from the nearest owning package.
499///
500/// `#...` specifiers are package-local by definition, so this fallback is only
501/// allowed when the importing file's nearest package manifest has a matching
502/// `imports` key. That keeps unrelated hash-prefixed path aliases unresolved.
503pub(super) fn try_package_imports_fallback(
504    ctx: &ResolveContext<'_>,
505    from_file: &Path,
506    specifier: &str,
507) -> Option<ResolveResult> {
508    if !specifier.starts_with('#') {
509        return None;
510    }
511    let manifest = nearest_package_manifest(ctx.package_manifests, from_file)?;
512    let imports = manifest.package_json.imports.as_ref()?;
513    let PackageMapTarget::Targets(targets) =
514        package_map_target(imports, specifier, ctx.condition_names)
515    else {
516        return None;
517    };
518    let source_subpath = package_import_source_subpath(manifest, specifier);
519    resolve_package_import_targets(ctx, manifest, &targets, source_subpath.as_deref()).map(
520        |target| match target {
521            PackageImportTarget::Internal(file_id) => match &manifest.name {
522                Some(package_name) => ResolveResult::InternalPackageModule {
523                    file_id,
524                    package_name: package_name.clone(),
525                },
526                None => ResolveResult::InternalModule(file_id),
527            },
528            PackageImportTarget::ExternalPackage(package_name) => {
529                ResolveResult::NpmPackage(package_name)
530            }
531        },
532    )
533}
534
535/// Return the workspace package that a package `imports` alias reached.
536///
537/// An alias such as `"#lib/*": "@acme/lib/*"` can resolve through the install
538/// symlink straight to the workspace source file. The file edge is correct, but
539/// the dependency on `@acme/lib` must still receive usage credit, the same as a
540/// direct `@acme/lib/...` import.
541///
542/// Only the package that owns `resolved_file` can receive the credit, and only
543/// when an alias target names it. Node.js resolves a fallback array such as
544/// `["./src/x.ts", "@acme/lib/x"]` to the local file, so `@acme/lib` receives
545/// no credit for it. A target that names a package outside the known package
546/// manifests also returns `None`.
547pub(super) fn package_imports_workspace_target(
548    ctx: &ResolveContext<'_>,
549    from_file: &Path,
550    specifier: &str,
551    resolved_file: &Path,
552) -> Option<String> {
553    if !specifier.starts_with('#') {
554        return None;
555    }
556    let manifest = nearest_package_manifest(ctx.package_manifests, from_file)?;
557    let imports = manifest.package_json.imports.as_ref()?;
558    let PackageMapTarget::Targets(targets) =
559        package_map_target(imports, specifier, ctx.condition_names)
560    else {
561        return None;
562    };
563    let owner = nearest_package_manifest(ctx.package_manifests, resolved_file)?
564        .name
565        .as_deref()?;
566    targets
567        .iter()
568        .filter(|target| !target.starts_with('#'))
569        .filter_map(|target| package_import_external_target(target))
570        .find(|package_name| package_name == owner)
571}
572
573/// Return the workspace package that a direct bare import reached through its
574/// install link.
575///
576/// npm, yarn and pnpm link a workspace package into `node_modules`, so an
577/// import such as `@acme/lib/x` resolves to the source file of the package.
578/// Node.js uses the first `node_modules/@acme/lib` in the ancestor directories
579/// of the importing file. The package receives the credit only when that link
580/// points at the workspace package root and the resolved file is inside it. An
581/// import that only a tsconfig `paths` alias or a bundler alias resolves has no
582/// such link, so it keeps its plain internal edge.
583pub(super) fn installed_workspace_package_target(
584    ctx: &ResolveContext<'_>,
585    from_file: &Path,
586    specifier: &str,
587    resolved_file: &Path,
588) -> Option<String> {
589    let name = super::package_credit::package_usage_name_for_external_bare_specifier(specifier)?;
590    let workspace_root = *ctx.workspace_roots.get(name.as_str())?;
591    let resolved = ctx
592        .canonicalize_cache
593        .get(resolved_file)
594        .unwrap_or_else(|| resolved_file.to_path_buf());
595    if !resolved.starts_with(workspace_root) {
596        return None;
597    }
598    let installed = from_file.ancestors().skip(1).find_map(|dir| {
599        ctx.canonicalize_cache
600            .get(&dir.join("node_modules").join(&name))
601    })?;
602    (installed == workspace_root).then_some(name)
603}
604
605pub(super) fn normalize_path_lexically(path: &Path) -> PathBuf {
606    let mut normalized = PathBuf::new();
607    for component in path.components() {
608        match component {
609            std::path::Component::CurDir => {}
610            std::path::Component::ParentDir => {
611                if !normalized.pop() {
612                    normalized.push(component.as_os_str());
613                }
614            }
615            std::path::Component::Prefix(_)
616            | std::path::Component::RootDir
617            | std::path::Component::Normal(_) => normalized.push(component.as_os_str()),
618        }
619    }
620    normalized
621}
622
623enum PackageImportTarget {
624    Internal(FileId),
625    ExternalPackage(String),
626}
627
628fn package_import_source_subpath(
629    manifest: &PackageManifestInfo,
630    specifier: &str,
631) -> Option<PathBuf> {
632    let stripped = specifier.strip_prefix('#')?;
633    let without_package_name = manifest
634        .name
635        .as_deref()
636        .and_then(|name| stripped.strip_prefix(name))
637        .and_then(|rest| rest.strip_prefix('/'))
638        .unwrap_or(stripped);
639    if without_package_name.is_empty() {
640        None
641    } else {
642        Some(PathBuf::from(without_package_name))
643    }
644}
645
646pub(super) fn nearest_package_manifest<'a>(
647    manifests: &'a [PackageManifestInfo],
648    from_file: &Path,
649) -> Option<&'a PackageManifestInfo> {
650    manifests
651        .iter()
652        .filter(|manifest| {
653            from_file.starts_with(&manifest.root) || from_file.starts_with(&manifest.canonical_root)
654        })
655        .max_by_key(|manifest| manifest.root.components().count())
656}
657
658fn find_package_manifest<'a>(
659    manifests: &'a [PackageManifestInfo],
660    package_name: &str,
661) -> Option<&'a PackageManifestInfo> {
662    manifests
663        .iter()
664        .find(|manifest| manifest.name.as_deref() == Some(package_name))
665}
666
667pub(super) fn resolve_package_map_target(
668    ctx: &ResolveContext<'_>,
669    manifest: &PackageManifestInfo,
670    target: &str,
671    source_subpath: Option<&Path>,
672) -> Option<FileId> {
673    let target_path = package_map_target_path(manifest, target)?;
674
675    lookup_internal_file_id(ctx, &target_path)
676        .or_else(|| try_source_fallback(&target_path, ctx.raw_path_to_id))
677        .or_else(|| try_source_fallback(&target_path, ctx.path_to_id))
678        .or_else(|| {
679            try_missing_only_source_fallback(&manifest.root, &target_path, ctx.raw_path_to_id)
680        })
681        .or_else(|| try_missing_only_source_fallback(&manifest.root, &target_path, ctx.path_to_id))
682        .or_else(|| try_tsconfig_output_source(ctx, &target_path))
683        .or_else(|| source_subpath.and_then(|subpath| try_source_subpath(ctx, manifest, subpath)))
684}
685
686/// Join a package map target (`./src/index.ts`) to the package root. A target
687/// that leaves the package root is not a package path.
688fn package_map_target_path(manifest: &PackageManifestInfo, target: &str) -> Option<PathBuf> {
689    let target = target.strip_prefix("./")?;
690    if target.starts_with("../") || target.starts_with('/') {
691        return None;
692    }
693    Some(manifest.root.join(target))
694}
695
696fn resolve_package_map_targets(
697    ctx: &ResolveContext<'_>,
698    manifest: &PackageManifestInfo,
699    targets: &[String],
700    source_subpath: Option<&Path>,
701) -> Option<FileId> {
702    targets
703        .iter()
704        .find_map(|target| resolve_package_map_target(ctx, manifest, target, source_subpath))
705}
706
707fn resolve_package_import_targets(
708    ctx: &ResolveContext<'_>,
709    manifest: &PackageManifestInfo,
710    targets: &[String],
711    source_subpath: Option<&Path>,
712) -> Option<PackageImportTarget> {
713    targets.iter().find_map(|target| {
714        resolve_package_map_target(ctx, manifest, target, source_subpath)
715            .map(PackageImportTarget::Internal)
716            .or_else(|| {
717                package_import_external_target(target).map(PackageImportTarget::ExternalPackage)
718            })
719    })
720}
721
722fn package_import_external_target(target: &str) -> Option<String> {
723    if is_bare_specifier(target) && is_valid_package_name(target) {
724        Some(extract_package_name(target))
725    } else {
726        None
727    }
728}
729
730fn try_source_subpath(
731    ctx: &ResolveContext<'_>,
732    manifest: &PackageManifestInfo,
733    subpath: &Path,
734) -> Option<FileId> {
735    if subpath.as_os_str().is_empty()
736        && let Some(source) = manifest.package_json.source.as_deref()
737        && let Some(source_path) = safe_relative_package_source_path(source)
738        && let Some(file_id) = lookup_internal_file_id(ctx, &manifest.root.join(source_path))
739    {
740        return Some(file_id);
741    }
742
743    for ext in SOURCE_EXTS {
744        let direct = if subpath.as_os_str().is_empty() {
745            manifest.root.join("src").join(format!("index.{ext}"))
746        } else {
747            manifest.root.join("src").join(subpath).with_extension(ext)
748        };
749        if let Some(file_id) = lookup_internal_file_id(ctx, &direct) {
750            return Some(file_id);
751        }
752
753        if !subpath.as_os_str().is_empty() {
754            let index = manifest
755                .root
756                .join("src")
757                .join(subpath)
758                .join(format!("index.{ext}"));
759            if let Some(file_id) = lookup_internal_file_id(ctx, &index) {
760                return Some(file_id);
761            }
762        }
763
764        if subpath.as_os_str().is_empty() {
765            let root_index = manifest.root.join(format!("index.{ext}"));
766            if let Some(file_id) = lookup_internal_file_id(ctx, &root_index) {
767                return Some(file_id);
768            }
769        }
770    }
771
772    None
773}
774
775fn safe_relative_package_source_path(source: &str) -> Option<&Path> {
776    let source = source.strip_prefix("./").unwrap_or(source);
777    let path = Path::new(source);
778    if path.as_os_str().is_empty()
779        || path.components().any(|component| {
780            matches!(
781                component,
782                std::path::Component::ParentDir
783                    | std::path::Component::RootDir
784                    | std::path::Component::Prefix(_)
785            )
786        })
787    {
788        None
789    } else {
790        Some(path)
791    }
792}
793
794pub(super) fn lookup_internal_file_id(
795    ctx: &ResolveContext<'_>,
796    candidate: &Path,
797) -> Option<FileId> {
798    if let Some(&file_id) = ctx.raw_path_to_id.get(candidate) {
799        return Some(file_id);
800    }
801    if let Some(&file_id) = ctx.path_to_id.get(candidate) {
802        return Some(file_id);
803    }
804    #[cfg(not(miri))]
805    if let Some(canonical) = ctx.canonicalize_cache.get(candidate) {
806        if let Some(&file_id) = ctx.path_to_id.get(canonical.as_path()) {
807            return Some(file_id);
808        }
809        if let Some(fallback) = ctx.canonical_fallback
810            && let Some(file_id) = fallback.get(&canonical)
811        {
812            return Some(file_id);
813        }
814    }
815    None
816}
817
818/// Extract npm package name from a resolved path inside `node_modules`.
819///
820/// Given a path like `/project/node_modules/react/index.js`, returns `Some("react")`.
821/// Given a path like `/project/node_modules/@scope/pkg/dist/index.js`, returns `Some("@scope/pkg")`.
822/// Returns `None` if the path doesn't contain a `node_modules` segment.
823pub fn extract_package_name_from_node_modules_path(path: &Path) -> Option<String> {
824    let components: Vec<&str> = path
825        .components()
826        .filter_map(|c| match c {
827            std::path::Component::Normal(s) => s.to_str(),
828            _ => None,
829        })
830        .collect();
831
832    let nm_idx = components.iter().rposition(|&c| c == "node_modules")?;
833
834    let after = &components[nm_idx + 1..];
835    if after.is_empty() {
836        return None;
837    }
838
839    if after[0].starts_with('@') {
840        if after.len() >= 2 {
841            Some(format!("{}/{}", after[0], after[1]))
842        } else {
843            Some(after[0].to_string())
844        }
845    } else {
846        Some(after[0].to_string())
847    }
848}
849
850/// Try to map a pnpm virtual store path back to a workspace source file.
851///
852/// When pnpm uses injected dependencies or certain linking strategies, canonical
853/// paths go through `.pnpm`:
854///   `/project/node_modules/.pnpm/@myorg+ui@1.0.0/node_modules/@myorg/ui/dist/index.js`
855///
856/// This function detects such paths, extracts the package name, checks if it
857/// matches a workspace package, and tries to find the source file in that workspace.
858pub(super) fn try_pnpm_workspace_fallback(
859    path: &Path,
860    path_to_id: &FxHashMap<&Path, FileId>,
861    workspace_roots: &FxHashMap<&str, &Path>,
862) -> Option<FileId> {
863    let components: Vec<&str> = path
864        .components()
865        .filter_map(|c| match c {
866            std::path::Component::Normal(s) => s.to_str(),
867            _ => None,
868        })
869        .collect();
870
871    let pnpm_idx = components.iter().position(|&c| c == ".pnpm")?;
872
873    let after_pnpm = &components[pnpm_idx + 1..];
874
875    let inner_nm_idx = after_pnpm.iter().position(|&c| c == "node_modules")?;
876    let after_inner_nm = &after_pnpm[inner_nm_idx + 1..];
877
878    if after_inner_nm.is_empty() {
879        return None;
880    }
881
882    let (pkg_name, pkg_name_components) = if after_inner_nm[0].starts_with('@') {
883        if after_inner_nm.len() >= 2 {
884            (format!("{}/{}", after_inner_nm[0], after_inner_nm[1]), 2)
885        } else {
886            return None;
887        }
888    } else {
889        (after_inner_nm[0].to_string(), 1)
890    };
891
892    let ws_root = workspace_roots.get(pkg_name.as_str())?;
893
894    let relative_parts = &after_inner_nm[pkg_name_components..];
895    if relative_parts.is_empty() {
896        return None;
897    }
898
899    let relative_path: PathBuf = relative_parts.iter().collect();
900
901    let direct = ws_root.join(&relative_path);
902    if let Some(&file_id) = path_to_id.get(direct.as_path()) {
903        return Some(file_id);
904    }
905
906    try_source_fallback(&direct, path_to_id)
907}
908
909/// Try to resolve a bare specifier as a workspace package reference.
910///
911/// When the specifier's package name matches a workspace package, resolve the
912/// subpath against that package's root directory directly instead of going
913/// through `node_modules`. Covers two cases:
914///
915/// 1. **Self-referencing package imports**: Node.js v12+ lets a package import
916///    itself via its own name (`import { X } from '@org/pkg/subentry'` from
917///    inside `@org/pkg`). Angular libraries built with `ng-packagr` rely on
918///    this to declare secondary entry points.
919/// 2. **Cross-workspace imports without `node_modules` symlinks**: monorepos
920///    that have not been installed yet, or bundlers that bypass `node_modules`
921///    entirely, still need to resolve `@org/other-pkg/sub` to the sibling
922///    workspace's source file.
923///
924/// Strategy: prefer a matching package `exports` target when the manifest has
925/// one, then try the package source layout directly when no `exports` map exists,
926/// and finally resolve the stripped subpath as a relative path from inside the
927/// package root. The manifest branches cover source-only workspaces whose
928/// package metadata points at missing `dist` output.
929///
930/// See issues #106, #641, and #725.
931pub(super) fn try_workspace_package_fallback(
932    ctx: &ResolveContext<'_>,
933    specifier: &str,
934    style_context: bool,
935) -> Option<ResolveResult> {
936    if !super::path_info::is_bare_specifier(specifier) {
937        return None;
938    }
939    let pkg_name = super::path_info::extract_package_name(specifier);
940
941    let subpath = specifier
942        .strip_prefix(pkg_name.as_str())
943        .and_then(|s| s.strip_prefix('/'))
944        .unwrap_or("");
945    let source_subpath = PathBuf::from(subpath);
946
947    match try_manifest_workspace_resolution(ctx, &pkg_name, subpath, &source_subpath) {
948        ManifestWorkspaceResolution::Resolved(result) => return Some(result),
949        ManifestWorkspaceResolution::Blocked => return None,
950        ManifestWorkspaceResolution::Continue => {}
951    }
952
953    let ws_root =
954        if let Some(manifest) = find_package_manifest(ctx.package_manifests, pkg_name.as_str()) {
955            manifest.root.as_path()
956        } else {
957            *ctx.workspace_roots.get(pkg_name.as_str())?
958        };
959
960    resolve_workspace_self_reference(ctx, ws_root, subpath, pkg_name, style_context)
961}
962
963/// Outcome of attempting workspace resolution through a matching package
964/// manifest's `exports` map or source layout.
965enum ManifestWorkspaceResolution {
966    /// A target was resolved.
967    Resolved(ResolveResult),
968    /// An `exports` map exists but the subpath is unmatched or null-blocked.
969    Blocked,
970    /// No manifest matched, or it had no usable resolution; keep trying.
971    Continue,
972}
973
974/// Try resolving via the package manifest: `exports` map first, then the source
975/// layout for manifests without an `exports` map.
976fn try_manifest_workspace_resolution(
977    ctx: &ResolveContext<'_>,
978    pkg_name: &str,
979    subpath: &str,
980    source_subpath: &Path,
981) -> ManifestWorkspaceResolution {
982    let Some(manifest) = find_package_manifest(ctx.package_manifests, pkg_name) else {
983        return ManifestWorkspaceResolution::Continue;
984    };
985
986    if let Some(exports) = manifest.package_json.exports.as_ref() {
987        return match package_map_target(exports, &export_key(subpath), ctx.condition_names) {
988            PackageMapTarget::Targets(targets) => {
989                if let Some(file_id) =
990                    resolve_package_map_targets(ctx, manifest, &targets, Some(source_subpath))
991                {
992                    return ManifestWorkspaceResolution::Resolved(
993                        ResolveResult::InternalPackageModule {
994                            file_id,
995                            package_name: pkg_name.to_string(),
996                        },
997                    );
998                }
999                exports_target_asset(manifest, &targets, pkg_name).map_or(
1000                    ManifestWorkspaceResolution::Continue,
1001                    ManifestWorkspaceResolution::Resolved,
1002                )
1003            }
1004            PackageMapTarget::NoMatch | PackageMapTarget::Blocked => {
1005                ManifestWorkspaceResolution::Blocked
1006            }
1007        };
1008    }
1009
1010    if let Some(file_id) = try_package_source_or_output(ctx, manifest, subpath) {
1011        return ManifestWorkspaceResolution::Resolved(ResolveResult::InternalPackageModule {
1012            file_id,
1013            package_name: pkg_name.to_string(),
1014        });
1015    }
1016
1017    ManifestWorkspaceResolution::Continue
1018}
1019
1020/// The `exports` key that a package subpath matches: `.` for the package
1021/// root, else `./<subpath>`.
1022fn export_key(subpath: &str) -> String {
1023    if subpath.is_empty() {
1024        ".".to_string()
1025    } else {
1026        format!("./{subpath}")
1027    }
1028}
1029
1030/// Return the paths that the `exports` map of a project package names for a
1031/// bare `specifier` and that do not exist on disk.
1032///
1033/// Generated code (`./src/generated/enums.ts`) does not exist before the
1034/// generator runs, so such an import does not resolve. The unresolved-import
1035/// check uses these paths to find out if the repository ignores the target.
1036/// The result is `None` when the specifier does not name a project package,
1037/// when the package has no `exports` map, when no `exports` key matches the
1038/// subpath, or when no target inside the package root is missing.
1039pub(super) fn missing_package_export_paths(
1040    ctx: &ResolveContext<'_>,
1041    specifier: &str,
1042) -> Option<Vec<PathBuf>> {
1043    if !is_bare_specifier(specifier) {
1044        return None;
1045    }
1046    let pkg_name = extract_package_name(specifier);
1047    let manifest = find_package_manifest(ctx.package_manifests, &pkg_name)?;
1048    let exports = manifest.package_json.exports.as_ref()?;
1049    let subpath = specifier
1050        .strip_prefix(pkg_name.as_str())
1051        .and_then(|s| s.strip_prefix('/'))
1052        .unwrap_or("");
1053    let PackageMapTarget::Targets(targets) =
1054        package_map_target(exports, &export_key(subpath), ctx.condition_names)
1055    else {
1056        return None;
1057    };
1058    let paths: Vec<PathBuf> = targets
1059        .iter()
1060        .filter_map(|target| package_map_target_path(manifest, target))
1061        .filter(|path| !path.traced_exists())
1062        .collect();
1063    (!paths.is_empty()).then_some(paths)
1064}
1065
1066/// Resolve the stripped subpath as a relative import from inside the package
1067/// root, mapping the resolved path back to an internal module via the id maps
1068/// and source fallback.
1069fn resolve_workspace_self_reference(
1070    ctx: &ResolveContext<'_>,
1071    ws_root: &Path,
1072    subpath: &str,
1073    package_name: String,
1074    style_context: bool,
1075) -> Option<ResolveResult> {
1076    let rel_spec = if subpath.is_empty() {
1077        "./".to_string()
1078    } else {
1079        format!("./{subpath}")
1080    };
1081
1082    let root_file = ws_root.join("__fallow_ws_self_resolve__");
1083    let super::file_attempt::ResolveFileAttempt::Resolved {
1084        resolution: resolved,
1085        ..
1086    } = super::file_attempt::resolve_file_with_tsconfig_fallback(
1087        ctx,
1088        &root_file,
1089        &rel_spec,
1090        style_context,
1091    )
1092    else {
1093        return None;
1094    };
1095    let resolved_path = resolved.path();
1096
1097    if let Some(&file_id) = ctx.raw_path_to_id.get(resolved_path) {
1098        return Some(ResolveResult::InternalPackageModule {
1099            file_id,
1100            package_name,
1101        });
1102    }
1103    if let Some(canonical) = ctx.canonicalize_cache.get(resolved_path) {
1104        if let Some(&file_id) = ctx.path_to_id.get(canonical.as_path()) {
1105            return Some(ResolveResult::InternalPackageModule {
1106                file_id,
1107                package_name,
1108            });
1109        }
1110        if let Some(fallback) = ctx.canonical_fallback
1111            && let Some(file_id) = fallback.get(&canonical)
1112        {
1113            return Some(ResolveResult::InternalPackageModule {
1114                file_id,
1115                package_name,
1116            });
1117        }
1118        if let Some(file_id) = try_source_fallback(&canonical, ctx.path_to_id) {
1119            return Some(ResolveResult::InternalPackageModule {
1120                file_id,
1121                package_name,
1122            });
1123        }
1124    }
1125    workspace_package_asset(resolved_path, &package_name)
1126}
1127
1128/// Convert a `DynamicImportPattern` to a glob string for file matching.
1129pub(super) fn make_glob_from_pattern(
1130    pattern: &fallow_types::extract::DynamicImportPattern,
1131) -> String {
1132    if has_wildcard_or_alternates(&pattern.prefix)
1133        || fallow_config::extglob::has_extglob_group(&pattern.prefix)
1134    {
1135        return pattern.prefix.clone();
1136    }
1137    pattern.suffix.as_ref().map_or_else(
1138        || format!("{}*", pattern.prefix),
1139        |suffix| format!("{}*{}", pattern.prefix, suffix),
1140    )
1141}
1142
1143/// Whether `prefix` has a `*` or a `{` outside a one-character class. The
1144/// extractor escapes a literal metacharacter as a one-character class, such
1145/// as `[*]`, so an escaped character is not glob syntax.
1146pub(super) fn has_wildcard_or_alternates(prefix: &str) -> bool {
1147    let bytes = prefix.as_bytes();
1148    let mut index = 0;
1149    while index < bytes.len() {
1150        match bytes[index] {
1151            b'[' if bytes.get(index + 2) == Some(&b']') => index += 3,
1152            b'*' | b'{' => return true,
1153            _ => index += 1,
1154        }
1155    }
1156    false
1157}
1158
1159#[cfg(test)]
1160mod tests {
1161    use super::package_map::{package_map_pattern_capture, resolve_package_map_value};
1162    use super::*;
1163    use crate::resolve::types::{CanonicalizeCache, TsconfigCache};
1164    use fallow_types::extract::ModuleLoadMechanism;
1165    use rustc_hash::FxHashSet;
1166
1167    pub(super) fn with_package_map_ctx(
1168        root: PathBuf,
1169        name: Option<&str>,
1170        package_json: fallow_config::PackageJson,
1171        raw_files: &[(PathBuf, FileId)],
1172        f: impl FnOnce(&ResolveContext<'_>, &PackageManifestInfo, &Path),
1173    ) {
1174        let manifest = PackageManifestInfo {
1175            root: root.clone(),
1176            canonical_root: root,
1177            name: name.map(str::to_string),
1178            package_json,
1179            deno_import_map: Vec::new(),
1180        };
1181        let manifests = [manifest];
1182        let mut raw_path_to_id = FxHashMap::default();
1183        for (path, file_id) in raw_files {
1184            raw_path_to_id.insert(path.as_path(), *file_id);
1185        }
1186        let path_to_id: FxHashMap<&Path, FileId> = FxHashMap::default();
1187        let workspace_roots: FxHashMap<&str, &Path> = FxHashMap::default();
1188        let condition_names = conditions();
1189        let resolver = crate::read_trace::Resolver::new(oxc_resolver::ResolveOptions::default());
1190        let tsconfig_warned = std::sync::Mutex::new(FxHashSet::default());
1191        let tsconfig_cache = TsconfigCache::default();
1192        let canonicalize_cache = CanonicalizeCache::default();
1193        let script_resolver = crate::resolve::specifier::create_script_resolver(&resolver);
1194        let ctx = ResolveContext {
1195            resolver: &resolver,
1196            script_resolver: &script_resolver,
1197            style_resolver: &resolver,
1198            extensions: &[],
1199            path_to_id: &path_to_id,
1200            raw_path_to_id: &raw_path_to_id,
1201            workspace_roots: &workspace_roots,
1202            package_manifests: &manifests,
1203            has_deno_import_maps: false,
1204            condition_names: &condition_names,
1205            path_aliases: &[],
1206            scoped_path_aliases: &[],
1207            scss_include_paths: &[],
1208            static_dir_mappings: &[],
1209            framework_static_dir_mappings: &[],
1210            root: &manifests[0].root,
1211            canonical_fallback: None,
1212            tsconfig_warned: &tsconfig_warned,
1213            tsconfig_cache: &tsconfig_cache,
1214            canonicalize_cache: &canonicalize_cache,
1215        };
1216
1217        f(&ctx, &manifests[0], &manifests[0].root);
1218    }
1219
1220    #[test]
1221    fn alias_match_remainder_exact_key() {
1222        assert_eq!(alias_match_remainder("vscode", "vscode"), Some(""));
1223        assert_eq!(alias_match_remainder("@scope/sdk", "@scope/sdk"), Some(""));
1224    }
1225
1226    #[test]
1227    fn alias_match_remainder_slash_continuation() {
1228        assert_eq!(
1229            alias_match_remainder("@scope/sdk/sub", "@scope/sdk"),
1230            Some("/sub")
1231        );
1232        assert_eq!(alias_match_remainder("@/foo", "@/"), Some("foo"));
1233        assert_eq!(
1234            alias_match_remainder("~/components/x", "~/"),
1235            Some("components/x")
1236        );
1237        assert_eq!(alias_match_remainder("$lib/util", "$lib/"), Some("util"));
1238    }
1239
1240    #[test]
1241    fn alias_match_remainder_rejects_prefix_collision() {
1242        assert_eq!(
1243            alias_match_remainder("@scope/sdk-extra", "@scope/sdk"),
1244            None
1245        );
1246        assert_eq!(
1247            alias_match_remainder("vscode-languageserver", "vscode"),
1248            None
1249        );
1250        assert_eq!(alias_match_remainder("#shared-utils", "#shared"), None);
1251    }
1252
1253    #[test]
1254    fn alias_match_remainder_non_match() {
1255        assert_eq!(alias_match_remainder("react", "vscode"), None);
1256    }
1257
1258    #[test]
1259    fn test_extract_package_name_from_node_modules_path_regular() {
1260        let path = PathBuf::from("/project/node_modules/react/index.js");
1261        assert_eq!(
1262            extract_package_name_from_node_modules_path(&path),
1263            Some("react".to_string())
1264        );
1265    }
1266
1267    #[test]
1268    fn test_extract_package_name_from_node_modules_path_scoped() {
1269        let path = PathBuf::from("/project/node_modules/@babel/core/lib/index.js");
1270        assert_eq!(
1271            extract_package_name_from_node_modules_path(&path),
1272            Some("@babel/core".to_string())
1273        );
1274    }
1275
1276    #[test]
1277    fn test_extract_package_name_from_node_modules_path_nested() {
1278        let path = PathBuf::from("/project/node_modules/pkg-a/node_modules/pkg-b/dist/index.js");
1279        assert_eq!(
1280            extract_package_name_from_node_modules_path(&path),
1281            Some("pkg-b".to_string())
1282        );
1283    }
1284
1285    #[test]
1286    fn test_extract_package_name_from_node_modules_path_deep_subpath() {
1287        let path = PathBuf::from("/project/node_modules/react-dom/cjs/react-dom.production.min.js");
1288        assert_eq!(
1289            extract_package_name_from_node_modules_path(&path),
1290            Some("react-dom".to_string())
1291        );
1292    }
1293
1294    #[test]
1295    fn test_extract_package_name_from_node_modules_path_no_node_modules() {
1296        let path = PathBuf::from("/project/src/components/Button.tsx");
1297        assert_eq!(extract_package_name_from_node_modules_path(&path), None);
1298    }
1299
1300    #[test]
1301    fn test_extract_package_name_from_node_modules_path_just_node_modules() {
1302        let path = PathBuf::from("/project/node_modules");
1303        assert_eq!(extract_package_name_from_node_modules_path(&path), None);
1304    }
1305
1306    #[test]
1307    fn test_extract_package_name_from_node_modules_path_scoped_only_scope() {
1308        let path = PathBuf::from("/project/node_modules/@scope");
1309        assert_eq!(
1310            extract_package_name_from_node_modules_path(&path),
1311            Some("@scope".to_string())
1312        );
1313    }
1314
1315    #[test]
1316    fn test_resolve_specifier_node_modules_returns_npm_package() {
1317        let path =
1318            PathBuf::from("/project/node_modules/styled-components/dist/styled-components.esm.js");
1319        assert_eq!(
1320            extract_package_name_from_node_modules_path(&path),
1321            Some("styled-components".to_string())
1322        );
1323
1324        let path = PathBuf::from("/project/node_modules/next/dist/server/next.js");
1325        assert_eq!(
1326            extract_package_name_from_node_modules_path(&path),
1327            Some("next".to_string())
1328        );
1329    }
1330
1331    #[test]
1332    fn test_try_source_fallback_dist_to_src() {
1333        let src_path = PathBuf::from("/project/packages/ui/src/utils.ts");
1334        let mut path_to_id = FxHashMap::default();
1335        path_to_id.insert(src_path.as_path(), FileId(0));
1336
1337        let dist_path = PathBuf::from("/project/packages/ui/dist/utils.js");
1338        assert_eq!(
1339            try_source_fallback(&dist_path, &path_to_id),
1340            Some(FileId(0)),
1341            "dist/utils.js should fall back to src/utils.ts"
1342        );
1343    }
1344
1345    #[test]
1346    fn test_try_source_fallback_build_to_src() {
1347        let src_path = PathBuf::from("/project/packages/core/src/index.tsx");
1348        let mut path_to_id = FxHashMap::default();
1349        path_to_id.insert(src_path.as_path(), FileId(1));
1350
1351        let build_path = PathBuf::from("/project/packages/core/build/index.js");
1352        assert_eq!(
1353            try_source_fallback(&build_path, &path_to_id),
1354            Some(FileId(1)),
1355            "build/index.js should fall back to src/index.tsx"
1356        );
1357    }
1358
1359    #[test]
1360    fn test_try_source_fallback_no_match() {
1361        let path_to_id: FxHashMap<&Path, FileId> = FxHashMap::default();
1362
1363        let dist_path = PathBuf::from("/project/packages/ui/dist/utils.js");
1364        assert_eq!(
1365            try_source_fallback(&dist_path, &path_to_id),
1366            None,
1367            "should return None when no source file exists"
1368        );
1369    }
1370
1371    #[test]
1372    fn test_try_source_fallback_non_output_dir() {
1373        let src_path = PathBuf::from("/project/packages/ui/src/utils.ts");
1374        let mut path_to_id = FxHashMap::default();
1375        path_to_id.insert(src_path.as_path(), FileId(0));
1376
1377        let normal_path = PathBuf::from("/project/packages/ui/scripts/utils.js");
1378        assert_eq!(
1379            try_source_fallback(&normal_path, &path_to_id),
1380            None,
1381            "non-output directory path should not trigger fallback"
1382        );
1383    }
1384
1385    #[test]
1386    fn test_try_source_fallback_nested_path() {
1387        let src_path = PathBuf::from("/project/packages/ui/src/components/Button.ts");
1388        let mut path_to_id = FxHashMap::default();
1389        path_to_id.insert(src_path.as_path(), FileId(2));
1390
1391        let dist_path = PathBuf::from("/project/packages/ui/dist/components/Button.js");
1392        assert_eq!(
1393            try_source_fallback(&dist_path, &path_to_id),
1394            Some(FileId(2)),
1395            "nested dist path should fall back to nested src path"
1396        );
1397    }
1398
1399    #[test]
1400    fn test_try_source_fallback_nested_dist_esm() {
1401        let src_path = PathBuf::from("/project/packages/ui/src/utils.ts");
1402        let mut path_to_id = FxHashMap::default();
1403        path_to_id.insert(src_path.as_path(), FileId(0));
1404
1405        let dist_path = PathBuf::from("/project/packages/ui/dist/esm/utils.mjs");
1406        assert_eq!(
1407            try_source_fallback(&dist_path, &path_to_id),
1408            Some(FileId(0)),
1409            "dist/esm/utils.mjs should fall back to src/utils.ts"
1410        );
1411    }
1412
1413    #[test]
1414    fn test_try_source_fallback_nested_build_cjs() {
1415        let src_path = PathBuf::from("/project/packages/core/src/index.ts");
1416        let mut path_to_id = FxHashMap::default();
1417        path_to_id.insert(src_path.as_path(), FileId(1));
1418
1419        let build_path = PathBuf::from("/project/packages/core/build/cjs/index.cjs");
1420        assert_eq!(
1421            try_source_fallback(&build_path, &path_to_id),
1422            Some(FileId(1)),
1423            "build/cjs/index.cjs should fall back to src/index.ts"
1424        );
1425    }
1426
1427    #[test]
1428    fn test_try_source_fallback_nested_dist_esm_deep_path() {
1429        let src_path = PathBuf::from("/project/packages/ui/src/components/Button.ts");
1430        let mut path_to_id = FxHashMap::default();
1431        path_to_id.insert(src_path.as_path(), FileId(2));
1432
1433        let dist_path = PathBuf::from("/project/packages/ui/dist/esm/components/Button.mjs");
1434        assert_eq!(
1435            try_source_fallback(&dist_path, &path_to_id),
1436            Some(FileId(2)),
1437            "dist/esm/components/Button.mjs should fall back to src/components/Button.ts"
1438        );
1439    }
1440
1441    #[test]
1442    fn test_try_source_fallback_triple_nested_output_dirs() {
1443        let src_path = PathBuf::from("/project/packages/ui/src/utils.ts");
1444        let mut path_to_id = FxHashMap::default();
1445        path_to_id.insert(src_path.as_path(), FileId(0));
1446
1447        let dist_path = PathBuf::from("/project/packages/ui/out/dist/esm/utils.mjs");
1448        assert_eq!(
1449            try_source_fallback(&dist_path, &path_to_id),
1450            Some(FileId(0)),
1451            "out/dist/esm/utils.mjs should fall back to src/utils.ts"
1452        );
1453    }
1454
1455    #[test]
1456    fn test_try_source_fallback_parent_dir_named_build() {
1457        let src_path = PathBuf::from("/home/user/build/my-project/src/utils.ts");
1458        let mut path_to_id = FxHashMap::default();
1459        path_to_id.insert(src_path.as_path(), FileId(0));
1460
1461        let dist_path = PathBuf::from("/home/user/build/my-project/dist/utils.js");
1462        assert_eq!(
1463            try_source_fallback(&dist_path, &path_to_id),
1464            Some(FileId(0)),
1465            "should resolve dist/ within project, not match parent 'build' dir"
1466        );
1467    }
1468
1469    #[test]
1470    fn package_map_non_relative_target_does_not_trigger_source_fallback() {
1471        with_package_map_ctx(
1472            PathBuf::from("/project"),
1473            Some("pkg"),
1474            fallow_config::PackageJson::default(),
1475            &[],
1476            |ctx, manifest, _| {
1477                assert!(resolve_package_map_target(ctx, manifest, "lodash", None).is_none());
1478                assert!(
1479                    resolve_package_map_target(ctx, manifest, "../dist/index.js", None).is_none()
1480                );
1481            },
1482        );
1483    }
1484
1485    #[test]
1486    fn package_map_lib_target_maps_to_source_when_absent() {
1487        let root = PathBuf::from("/project/packages/uses-lib");
1488        let feature = root.join("src/features/feature.ts");
1489        let index = root.join("src/index.ts");
1490
1491        with_package_map_ctx(
1492            root,
1493            Some("@repro/uses-lib"),
1494            fallow_config::PackageJson::default(),
1495            &[(feature, FileId(3)), (index, FileId(4))],
1496            |ctx, manifest, _| {
1497                assert_eq!(
1498                    resolve_package_map_target(ctx, manifest, "./lib/features/feature.mjs", None),
1499                    Some(FileId(3))
1500                );
1501                assert_eq!(
1502                    resolve_package_map_target(ctx, manifest, "./lib/index.d.ts", None),
1503                    Some(FileId(4))
1504                );
1505            },
1506        );
1507    }
1508
1509    #[test]
1510    fn package_map_tracked_lib_target_wins_over_source() {
1511        let root = PathBuf::from("/project");
1512        let lib_path = root.join("lib/index.js");
1513        let src_path = root.join("src/index.ts");
1514
1515        with_package_map_ctx(
1516            root,
1517            Some("pkg"),
1518            fallow_config::PackageJson::default(),
1519            &[(lib_path, FileId(1)), (src_path, FileId(2))],
1520            |ctx, manifest, _| {
1521                assert_eq!(
1522                    resolve_package_map_target(ctx, manifest, "./lib/index.js", None),
1523                    Some(FileId(1))
1524                );
1525            },
1526        );
1527    }
1528
1529    #[test]
1530    fn generic_source_fallback_does_not_map_lib() {
1531        let src_path = PathBuf::from("/project/src/x.ts");
1532        let mut path_to_id = FxHashMap::default();
1533        path_to_id.insert(src_path.as_path(), FileId(0));
1534
1535        assert_eq!(
1536            try_source_fallback(Path::new("/project/lib/x.js"), &path_to_id),
1537            None
1538        );
1539    }
1540
1541    #[test]
1542    fn package_map_dist_lib_target_prefers_output_dirs_mapping() {
1543        let root = PathBuf::from("/project");
1544        let nested = root.join("src/lib/x.ts");
1545        let flat = root.join("src/x.ts");
1546
1547        with_package_map_ctx(
1548            root,
1549            Some("pkg"),
1550            fallow_config::PackageJson::default(),
1551            &[(nested, FileId(6)), (flat, FileId(7))],
1552            |ctx, manifest, _| {
1553                assert_eq!(
1554                    resolve_package_map_target(ctx, manifest, "./dist/lib/x.js", None),
1555                    Some(FileId(6))
1556                );
1557            },
1558        );
1559    }
1560
1561    #[test]
1562    fn package_imports_fallback_supports_external_package_targets() {
1563        let root = PathBuf::from("/project");
1564        with_package_map_ctx(
1565            root,
1566            Some("pkg"),
1567            fallow_config::PackageJson {
1568                imports: Some(serde_json::json!({
1569                    "#pad": "left-pad",
1570                    "#scoped": "@scope/pkg/subpath"
1571                })),
1572                ..Default::default()
1573            },
1574            &[],
1575            |ctx, _, root| {
1576                let pad = try_package_imports_fallback(ctx, &root.join("src/index.ts"), "#pad");
1577                assert!(matches!(pad, Some(ResolveResult::NpmPackage(pkg)) if pkg == "left-pad"));
1578
1579                let scoped =
1580                    try_package_imports_fallback(ctx, &root.join("src/index.ts"), "#scoped");
1581                assert!(
1582                    matches!(scoped, Some(ResolveResult::NpmPackage(pkg)) if pkg == "@scope/pkg")
1583                );
1584            },
1585        );
1586    }
1587
1588    #[test]
1589    fn package_imports_workspace_target_names_only_known_packages() {
1590        let root = PathBuf::from("/project");
1591        with_package_map_ctx(
1592            root,
1593            Some("pkg"),
1594            fallow_config::PackageJson {
1595                imports: Some(serde_json::json!({
1596                    "#self/*": "pkg/*",
1597                    "#pad": "left-pad",
1598                    "#local/*": "./src/*.ts"
1599                })),
1600                ..Default::default()
1601            },
1602            &[],
1603            |ctx, _, root| {
1604                let from = root.join("src/index.ts");
1605                let feature = root.join("src/feature.ts");
1606                assert_eq!(
1607                    package_imports_workspace_target(ctx, &from, "#self/feature", &feature),
1608                    Some("pkg".to_string())
1609                );
1610                assert_eq!(
1611                    package_imports_workspace_target(
1612                        ctx,
1613                        &from,
1614                        "#self/feature",
1615                        Path::new("/elsewhere/feature.ts")
1616                    ),
1617                    None,
1618                    "a file outside the named package must not credit it"
1619                );
1620                assert_eq!(
1621                    package_imports_workspace_target(
1622                        ctx,
1623                        &from,
1624                        "#pad",
1625                        &root.join("node_modules/left-pad/index.js")
1626                    ),
1627                    None
1628                );
1629                assert_eq!(
1630                    package_imports_workspace_target(ctx, &from, "#local/feature", &feature),
1631                    None
1632                );
1633                assert_eq!(
1634                    package_imports_workspace_target(ctx, &from, "pkg/feature", &feature),
1635                    None
1636                );
1637            },
1638        );
1639    }
1640
1641    #[test]
1642    fn package_imports_fallback_supports_unnamed_packages() {
1643        let root = PathBuf::from("/project");
1644        let src_path = root.join("src/runtime/task.ts");
1645        with_package_map_ctx(
1646            root,
1647            None,
1648            fallow_config::PackageJson {
1649                imports: Some(serde_json::json!({
1650                    "#runtime/*": "./dist/runtime/*.mjs"
1651                })),
1652                ..Default::default()
1653            },
1654            &[(src_path, FileId(7))],
1655            |ctx, _, root| {
1656                let result =
1657                    try_package_imports_fallback(ctx, &root.join("src/index.ts"), "#runtime/task");
1658                assert!(matches!(
1659                    result,
1660                    Some(ResolveResult::InternalModule(FileId(7)))
1661                ));
1662            },
1663        );
1664    }
1665
1666    #[test]
1667    fn package_source_path_accepts_relative_source_entries() {
1668        assert_eq!(
1669            safe_relative_package_source_path("src/index.js"),
1670            Some(Path::new("src/index.js"))
1671        );
1672        assert_eq!(
1673            safe_relative_package_source_path("./custom/entry.ts"),
1674            Some(Path::new("custom/entry.ts"))
1675        );
1676    }
1677
1678    #[test]
1679    fn package_source_path_rejects_unsafe_entries() {
1680        assert_eq!(safe_relative_package_source_path(""), None);
1681        assert_eq!(safe_relative_package_source_path("./"), None);
1682        assert_eq!(safe_relative_package_source_path("../src/index.js"), None);
1683        assert_eq!(safe_relative_package_source_path("src/../index.js"), None);
1684        assert_eq!(safe_relative_package_source_path("/src/index.js"), None);
1685
1686        #[cfg(windows)]
1687        assert_eq!(safe_relative_package_source_path("C:\\src\\index.js"), None);
1688    }
1689
1690    #[test]
1691    fn test_pnpm_store_path_extract_package_name() {
1692        let path =
1693            PathBuf::from("/project/node_modules/.pnpm/react@18.2.0/node_modules/react/index.js");
1694        assert_eq!(
1695            extract_package_name_from_node_modules_path(&path),
1696            Some("react".to_string())
1697        );
1698    }
1699
1700    #[test]
1701    fn test_pnpm_store_path_scoped_package() {
1702        let path = PathBuf::from(
1703            "/project/node_modules/.pnpm/@babel+core@7.24.0/node_modules/@babel/core/lib/index.js",
1704        );
1705        assert_eq!(
1706            extract_package_name_from_node_modules_path(&path),
1707            Some("@babel/core".to_string())
1708        );
1709    }
1710
1711    fn conditions() -> Vec<String> {
1712        vec![
1713            "development".to_string(),
1714            "import".to_string(),
1715            "require".to_string(),
1716            "default".to_string(),
1717            "types".to_string(),
1718            "node".to_string(),
1719        ]
1720    }
1721
1722    #[test]
1723    fn test_pnpm_store_path_with_peer_deps() {
1724        let path = PathBuf::from(
1725            "/project/node_modules/.pnpm/webpack@5.0.0_esbuild@0.19.0/node_modules/webpack/lib/index.js",
1726        );
1727        assert_eq!(
1728            extract_package_name_from_node_modules_path(&path),
1729            Some("webpack".to_string())
1730        );
1731    }
1732
1733    #[test]
1734    fn test_try_pnpm_workspace_fallback_dist_to_src() {
1735        let src_path = PathBuf::from("/project/packages/ui/src/utils.ts");
1736        let mut path_to_id = FxHashMap::default();
1737        path_to_id.insert(src_path.as_path(), FileId(0));
1738
1739        let mut workspace_roots = FxHashMap::default();
1740        let ws_root = PathBuf::from("/project/packages/ui");
1741        workspace_roots.insert("@myorg/ui", ws_root.as_path());
1742
1743        let pnpm_path = PathBuf::from(
1744            "/project/node_modules/.pnpm/@myorg+ui@1.0.0/node_modules/@myorg/ui/dist/utils.js",
1745        );
1746        assert_eq!(
1747            try_pnpm_workspace_fallback(&pnpm_path, &path_to_id, &workspace_roots),
1748            Some(FileId(0)),
1749            ".pnpm workspace path should fall back to src/utils.ts"
1750        );
1751    }
1752
1753    #[test]
1754    fn test_try_pnpm_workspace_fallback_direct_source() {
1755        let src_path = PathBuf::from("/project/packages/core/src/index.ts");
1756        let mut path_to_id = FxHashMap::default();
1757        path_to_id.insert(src_path.as_path(), FileId(1));
1758
1759        let mut workspace_roots = FxHashMap::default();
1760        let ws_root = PathBuf::from("/project/packages/core");
1761        workspace_roots.insert("@myorg/core", ws_root.as_path());
1762
1763        let pnpm_path = PathBuf::from(
1764            "/project/node_modules/.pnpm/@myorg+core@workspace/node_modules/@myorg/core/src/index.ts",
1765        );
1766        assert_eq!(
1767            try_pnpm_workspace_fallback(&pnpm_path, &path_to_id, &workspace_roots),
1768            Some(FileId(1)),
1769            ".pnpm workspace path with src/ should resolve directly"
1770        );
1771    }
1772
1773    #[test]
1774    fn test_try_pnpm_workspace_fallback_non_workspace_package() {
1775        let path_to_id: FxHashMap<&Path, FileId> = FxHashMap::default();
1776
1777        let mut workspace_roots = FxHashMap::default();
1778        let ws_root = PathBuf::from("/project/packages/ui");
1779        workspace_roots.insert("@myorg/ui", ws_root.as_path());
1780
1781        let pnpm_path =
1782            PathBuf::from("/project/node_modules/.pnpm/react@18.2.0/node_modules/react/index.js");
1783        assert_eq!(
1784            try_pnpm_workspace_fallback(&pnpm_path, &path_to_id, &workspace_roots),
1785            None,
1786            "non-workspace package in .pnpm should return None"
1787        );
1788    }
1789
1790    #[test]
1791    fn test_try_pnpm_workspace_fallback_unscoped_package() {
1792        let src_path = PathBuf::from("/project/packages/utils/src/index.ts");
1793        let mut path_to_id = FxHashMap::default();
1794        path_to_id.insert(src_path.as_path(), FileId(2));
1795
1796        let mut workspace_roots = FxHashMap::default();
1797        let ws_root = PathBuf::from("/project/packages/utils");
1798        workspace_roots.insert("my-utils", ws_root.as_path());
1799
1800        let pnpm_path = PathBuf::from(
1801            "/project/node_modules/.pnpm/my-utils@1.0.0/node_modules/my-utils/dist/index.js",
1802        );
1803        assert_eq!(
1804            try_pnpm_workspace_fallback(&pnpm_path, &path_to_id, &workspace_roots),
1805            Some(FileId(2)),
1806            "unscoped workspace package in .pnpm should resolve"
1807        );
1808    }
1809
1810    #[test]
1811    fn test_try_pnpm_workspace_fallback_nested_path() {
1812        let src_path = PathBuf::from("/project/packages/ui/src/components/Button.ts");
1813        let mut path_to_id = FxHashMap::default();
1814        path_to_id.insert(src_path.as_path(), FileId(3));
1815
1816        let mut workspace_roots = FxHashMap::default();
1817        let ws_root = PathBuf::from("/project/packages/ui");
1818        workspace_roots.insert("@myorg/ui", ws_root.as_path());
1819
1820        let pnpm_path = PathBuf::from(
1821            "/project/node_modules/.pnpm/@myorg+ui@1.0.0/node_modules/@myorg/ui/dist/components/Button.js",
1822        );
1823        assert_eq!(
1824            try_pnpm_workspace_fallback(&pnpm_path, &path_to_id, &workspace_roots),
1825            Some(FileId(3)),
1826            "nested .pnpm workspace path should resolve through source fallback"
1827        );
1828    }
1829
1830    #[test]
1831    fn test_try_pnpm_workspace_fallback_no_pnpm() {
1832        let path_to_id: FxHashMap<&Path, FileId> = FxHashMap::default();
1833        let workspace_roots: FxHashMap<&str, &Path> = FxHashMap::default();
1834
1835        let regular_path = PathBuf::from("/project/node_modules/react/index.js");
1836        assert_eq!(
1837            try_pnpm_workspace_fallback(&regular_path, &path_to_id, &workspace_roots),
1838            None,
1839        );
1840    }
1841
1842    #[test]
1843    fn test_try_pnpm_workspace_fallback_with_peer_deps() {
1844        let src_path = PathBuf::from("/project/packages/ui/src/index.ts");
1845        let mut path_to_id = FxHashMap::default();
1846        path_to_id.insert(src_path.as_path(), FileId(4));
1847
1848        let mut workspace_roots = FxHashMap::default();
1849        let ws_root = PathBuf::from("/project/packages/ui");
1850        workspace_roots.insert("@myorg/ui", ws_root.as_path());
1851
1852        let pnpm_path = PathBuf::from(
1853            "/project/node_modules/.pnpm/@myorg+ui@1.0.0_react@18.2.0/node_modules/@myorg/ui/dist/index.js",
1854        );
1855        assert_eq!(
1856            try_pnpm_workspace_fallback(&pnpm_path, &path_to_id, &workspace_roots),
1857            Some(FileId(4)),
1858            ".pnpm path with peer dep suffix should still resolve"
1859        );
1860    }
1861
1862    fn glob_pattern(
1863        prefix: &str,
1864        suffix: Option<&str>,
1865    ) -> fallow_types::extract::DynamicImportPattern {
1866        fallow_types::extract::DynamicImportPattern {
1867            prefix: prefix.to_string(),
1868            suffix: suffix.map(str::to_string),
1869            span: oxc_span::Span::default(),
1870            mechanism: ModuleLoadMechanism::EsModule,
1871            excludes: Vec::new(),
1872            imported_name: fallow_types::extract::ImportedName::Namespace,
1873        }
1874    }
1875
1876    #[test]
1877    fn make_glob_prefix_only_no_suffix() {
1878        let pattern = glob_pattern("./locales/", None);
1879        assert_eq!(make_glob_from_pattern(&pattern), "./locales/*");
1880    }
1881
1882    #[test]
1883    fn make_glob_passthrough_extglob_group() {
1884        let pattern = glob_pattern("./locales/@(en|nl).js", None);
1885        assert_eq!(make_glob_from_pattern(&pattern), "./locales/@(en|nl).js");
1886    }
1887
1888    #[test]
1889    fn make_glob_keeps_suffix_after_escaped_metacharacters() {
1890        let pattern = glob_pattern("./[{]group[}]/[*]/", Some(".js"));
1891        assert_eq!(make_glob_from_pattern(&pattern), "./[{]group[}]/[*]/*.js");
1892    }
1893
1894    #[test]
1895    fn make_glob_prefix_with_suffix() {
1896        let pattern = glob_pattern("./locales/", Some(".json"));
1897        assert_eq!(make_glob_from_pattern(&pattern), "./locales/*.json");
1898    }
1899
1900    #[test]
1901    fn make_glob_passthrough_star() {
1902        let pattern = glob_pattern("./pages/**/*.tsx", None);
1903        assert_eq!(make_glob_from_pattern(&pattern), "./pages/**/*.tsx");
1904    }
1905
1906    #[test]
1907    fn make_glob_passthrough_brace() {
1908        let pattern = glob_pattern("./i18n/{en,de,fr}.json", None);
1909        assert_eq!(make_glob_from_pattern(&pattern), "./i18n/{en,de,fr}.json");
1910    }
1911
1912    #[test]
1913    fn make_glob_empty_prefix_no_suffix() {
1914        let pattern = fallow_types::extract::DynamicImportPattern {
1915            prefix: String::new(),
1916            suffix: None,
1917            span: oxc_span::Span::default(),
1918            mechanism: ModuleLoadMechanism::EsModule,
1919            excludes: Vec::new(),
1920            imported_name: fallow_types::extract::ImportedName::Namespace,
1921        };
1922        assert_eq!(make_glob_from_pattern(&pattern), "*");
1923    }
1924
1925    #[test]
1926    fn make_glob_empty_prefix_with_suffix() {
1927        let pattern = fallow_types::extract::DynamicImportPattern {
1928            prefix: String::new(),
1929            suffix: Some(".ts".to_string()),
1930            span: oxc_span::Span::default(),
1931            mechanism: ModuleLoadMechanism::EsModule,
1932            excludes: Vec::new(),
1933            imported_name: fallow_types::extract::ImportedName::Namespace,
1934        };
1935        assert_eq!(make_glob_from_pattern(&pattern), "*.ts");
1936    }
1937
1938    #[test]
1939    fn make_glob_template_literal_prefix_only() {
1940        let pattern = glob_pattern("./pages/", None);
1941        assert_eq!(make_glob_from_pattern(&pattern), "./pages/*");
1942    }
1943
1944    #[test]
1945    fn make_glob_template_literal_deep_prefix() {
1946        let pattern = glob_pattern("./modules/", None);
1947        assert_eq!(make_glob_from_pattern(&pattern), "./modules/*");
1948    }
1949
1950    #[test]
1951    fn make_glob_string_concat_with_extension() {
1952        let pattern = glob_pattern("./views/", Some(".vue"));
1953        assert_eq!(make_glob_from_pattern(&pattern), "./views/*.vue");
1954    }
1955
1956    #[test]
1957    fn make_glob_import_meta_glob_recursive() {
1958        let pattern = glob_pattern("./components/**/*.vue", None);
1959        assert_eq!(
1960            make_glob_from_pattern(&pattern),
1961            "./components/**/*.vue",
1962            "import.meta.glob patterns with * should pass through as-is"
1963        );
1964    }
1965
1966    #[test]
1967    fn make_glob_import_meta_glob_brace_expansion() {
1968        let pattern = glob_pattern("./plugins/{auth,analytics}.ts", None);
1969        assert_eq!(
1970            make_glob_from_pattern(&pattern),
1971            "./plugins/{auth,analytics}.ts",
1972            "import.meta.glob patterns with braces should pass through as-is"
1973        );
1974    }
1975
1976    #[test]
1977    fn make_glob_import_meta_glob_star_with_brace() {
1978        let pattern = glob_pattern("./routes/**/*.{ts,tsx}", None);
1979        assert_eq!(
1980            make_glob_from_pattern(&pattern),
1981            "./routes/**/*.{ts,tsx}",
1982            "combined * and brace patterns should pass through"
1983        );
1984    }
1985
1986    #[test]
1987    fn make_glob_import_meta_glob_ignores_suffix_when_star_present() {
1988        let pattern = glob_pattern("./*.ts", Some(".extra"));
1989        assert_eq!(
1990            make_glob_from_pattern(&pattern),
1991            "./*.ts",
1992            "when prefix has glob chars, suffix is ignored (prefix used as-is)"
1993        );
1994    }
1995
1996    #[test]
1997    fn make_glob_single_dot_prefix() {
1998        let pattern = glob_pattern("./", None);
1999        assert_eq!(make_glob_from_pattern(&pattern), "./*");
2000    }
2001
2002    #[test]
2003    fn make_glob_prefix_without_trailing_slash() {
2004        let pattern = glob_pattern("./config", None);
2005        assert_eq!(make_glob_from_pattern(&pattern), "./config*");
2006    }
2007
2008    #[test]
2009    fn make_glob_prefix_with_dotdot() {
2010        let pattern = glob_pattern("../shared/", Some(".ts"));
2011        assert_eq!(make_glob_from_pattern(&pattern), "../shared/*.ts");
2012    }
2013
2014    #[test]
2015    fn test_extract_package_name_with_pnpm_plus_encoded_scope() {
2016        let path = PathBuf::from(
2017            "/project/node_modules/.pnpm/@mui+material@5.15.0/node_modules/@mui/material/index.js",
2018        );
2019        assert_eq!(
2020            extract_package_name_from_node_modules_path(&path),
2021            Some("@mui/material".to_string())
2022        );
2023    }
2024
2025    #[test]
2026    fn test_extract_package_name_windows_style_path() {
2027        let path = PathBuf::from("/project/node_modules/typescript/lib/tsc.js");
2028        assert_eq!(
2029            extract_package_name_from_node_modules_path(&path),
2030            Some("typescript".to_string())
2031        );
2032    }
2033
2034    #[test]
2035    fn test_try_source_fallback_out_dir() {
2036        let src_path = PathBuf::from("/project/packages/api/src/handler.ts");
2037        let mut path_to_id = FxHashMap::default();
2038        path_to_id.insert(src_path.as_path(), FileId(5));
2039
2040        let out_path = PathBuf::from("/project/packages/api/out/handler.js");
2041        assert_eq!(
2042            try_source_fallback(&out_path, &path_to_id),
2043            Some(FileId(5)),
2044            "out/handler.js should fall back to src/handler.ts"
2045        );
2046    }
2047
2048    #[test]
2049    fn test_try_source_fallback_mts_extension() {
2050        let src_path = PathBuf::from("/project/packages/lib/src/utils.mts");
2051        let mut path_to_id = FxHashMap::default();
2052        path_to_id.insert(src_path.as_path(), FileId(6));
2053
2054        let dist_path = PathBuf::from("/project/packages/lib/dist/utils.mjs");
2055        assert_eq!(
2056            try_source_fallback(&dist_path, &path_to_id),
2057            Some(FileId(6)),
2058            "dist/utils.mjs should fall back to src/utils.mts"
2059        );
2060    }
2061
2062    #[test]
2063    fn test_try_source_fallback_declaration_with_dotted_name() {
2064        let src_path = PathBuf::from("/project/packages/lib/src/x.port.ts");
2065        let mut path_to_id = FxHashMap::default();
2066        path_to_id.insert(src_path.as_path(), FileId(6));
2067
2068        let dist_path = PathBuf::from("/project/packages/lib/dist/x.port.d.ts");
2069        assert_eq!(
2070            try_source_fallback(&dist_path, &path_to_id),
2071            Some(FileId(6)),
2072            "dist/x.port.d.ts should fall back to src/x.port.ts"
2073        );
2074    }
2075
2076    #[test]
2077    fn test_try_source_fallback_module_declaration() {
2078        let src_path = PathBuf::from("/project/packages/lib/src/x.mts");
2079        let mut path_to_id = FxHashMap::default();
2080        path_to_id.insert(src_path.as_path(), FileId(6));
2081
2082        let dist_path = PathBuf::from("/project/packages/lib/dist/x.d.mts");
2083        assert_eq!(
2084            try_source_fallback(&dist_path, &path_to_id),
2085            Some(FileId(6)),
2086            "dist/x.d.mts should fall back to src/x.mts"
2087        );
2088    }
2089
2090    #[test]
2091    fn test_try_source_fallback_commonjs_declaration_in_subdir() {
2092        let src_path = PathBuf::from("/project/packages/lib/src/sub/x.cts");
2093        let mut path_to_id = FxHashMap::default();
2094        path_to_id.insert(src_path.as_path(), FileId(6));
2095
2096        let dist_path = PathBuf::from("/project/packages/lib/dist/sub/x.d.cts");
2097        assert_eq!(
2098            try_source_fallback(&dist_path, &path_to_id),
2099            Some(FileId(6)),
2100            "dist/sub/x.d.cts should fall back to src/sub/x.cts"
2101        );
2102    }
2103
2104    #[test]
2105    fn test_try_source_fallback_declaration_copied_from_src() {
2106        let src_path = PathBuf::from("/project/packages/lib/src/globals.d.ts");
2107        let mut path_to_id = FxHashMap::default();
2108        path_to_id.insert(src_path.as_path(), FileId(6));
2109
2110        let dist_path = PathBuf::from("/project/packages/lib/dist/globals.d.ts");
2111        assert_eq!(
2112            try_source_fallback(&dist_path, &path_to_id),
2113            Some(FileId(6)),
2114            "dist/globals.d.ts should fall back to a copied src/globals.d.ts"
2115        );
2116    }
2117
2118    #[test]
2119    fn test_try_source_fallback_js_with_dotted_name() {
2120        let src_path = PathBuf::from("/project/packages/lib/src/x.port.ts");
2121        let mut path_to_id = FxHashMap::default();
2122        path_to_id.insert(src_path.as_path(), FileId(6));
2123
2124        let dist_path = PathBuf::from("/project/packages/lib/dist/x.port.js");
2125        assert_eq!(
2126            try_source_fallback(&dist_path, &path_to_id),
2127            Some(FileId(6)),
2128            "dist/x.port.js should fall back to src/x.port.ts"
2129        );
2130    }
2131
2132    #[test]
2133    fn test_try_source_fallback_cts_extension() {
2134        let src_path = PathBuf::from("/project/packages/lib/src/config.cts");
2135        let mut path_to_id = FxHashMap::default();
2136        path_to_id.insert(src_path.as_path(), FileId(7));
2137
2138        let dist_path = PathBuf::from("/project/packages/lib/dist/config.cjs");
2139        assert_eq!(
2140            try_source_fallback(&dist_path, &path_to_id),
2141            Some(FileId(7)),
2142            "dist/config.cjs should fall back to src/config.cts"
2143        );
2144    }
2145
2146    #[test]
2147    fn test_try_source_fallback_jsx_extension() {
2148        let src_path = PathBuf::from("/project/packages/ui/src/App.jsx");
2149        let mut path_to_id = FxHashMap::default();
2150        path_to_id.insert(src_path.as_path(), FileId(8));
2151
2152        let build_path = PathBuf::from("/project/packages/ui/build/App.js");
2153        assert_eq!(
2154            try_source_fallback(&build_path, &path_to_id),
2155            Some(FileId(8)),
2156            "build/App.js should fall back to src/App.jsx"
2157        );
2158    }
2159
2160    #[test]
2161    fn test_try_source_fallback_no_file_stem() {
2162        let path_to_id: FxHashMap<&Path, FileId> = FxHashMap::default();
2163        let dist_path = PathBuf::from("/project/packages/ui/dist/");
2164        assert_eq!(
2165            try_source_fallback(&dist_path, &path_to_id),
2166            None,
2167            "directory path with no file should return None"
2168        );
2169    }
2170
2171    #[test]
2172    fn test_try_source_fallback_esm_subdir() {
2173        let src_path = PathBuf::from("/project/lib/src/index.ts");
2174        let mut path_to_id = FxHashMap::default();
2175        path_to_id.insert(src_path.as_path(), FileId(10));
2176
2177        let dist_path = PathBuf::from("/project/lib/esm/index.mjs");
2178        assert_eq!(
2179            try_source_fallback(&dist_path, &path_to_id),
2180            Some(FileId(10)),
2181            "standalone esm/ directory should fall back to src/"
2182        );
2183    }
2184
2185    #[test]
2186    fn test_try_source_fallback_cjs_subdir() {
2187        let src_path = PathBuf::from("/project/lib/src/index.ts");
2188        let mut path_to_id = FxHashMap::default();
2189        path_to_id.insert(src_path.as_path(), FileId(11));
2190
2191        let cjs_path = PathBuf::from("/project/lib/cjs/index.cjs");
2192        assert_eq!(
2193            try_source_fallback(&cjs_path, &path_to_id),
2194            Some(FileId(11)),
2195            "standalone cjs/ directory should fall back to src/"
2196        );
2197    }
2198
2199    #[test]
2200    fn test_try_pnpm_workspace_fallback_empty_after_pnpm() {
2201        let path_to_id: FxHashMap<&Path, FileId> = FxHashMap::default();
2202        let workspace_roots: FxHashMap<&str, &Path> = FxHashMap::default();
2203
2204        let pnpm_path = PathBuf::from("/project/node_modules/.pnpm/pkg@1.0.0/node_modules");
2205        assert_eq!(
2206            try_pnpm_workspace_fallback(&pnpm_path, &path_to_id, &workspace_roots),
2207            None,
2208            "path ending at node_modules with nothing after should return None"
2209        );
2210    }
2211
2212    #[test]
2213    fn test_try_pnpm_workspace_fallback_scoped_package_only_scope() {
2214        let path_to_id: FxHashMap<&Path, FileId> = FxHashMap::default();
2215        let workspace_roots: FxHashMap<&str, &Path> = FxHashMap::default();
2216
2217        let pnpm_path =
2218            PathBuf::from("/project/node_modules/.pnpm/@scope+pkg@1.0.0/node_modules/@scope");
2219        assert_eq!(
2220            try_pnpm_workspace_fallback(&pnpm_path, &path_to_id, &workspace_roots),
2221            None,
2222            "scoped package without full name and no matching workspace should return None"
2223        );
2224    }
2225
2226    #[test]
2227    fn test_try_pnpm_workspace_fallback_no_inner_node_modules() {
2228        let path_to_id: FxHashMap<&Path, FileId> = FxHashMap::default();
2229        let workspace_roots: FxHashMap<&str, &Path> = FxHashMap::default();
2230
2231        let pnpm_path = PathBuf::from("/project/node_modules/.pnpm/pkg@1.0.0/dist/index.js");
2232        assert_eq!(
2233            try_pnpm_workspace_fallback(&pnpm_path, &path_to_id, &workspace_roots),
2234            None,
2235            "path without inner node_modules after .pnpm should return None"
2236        );
2237    }
2238
2239    #[test]
2240    fn test_try_pnpm_workspace_fallback_package_without_relative_path() {
2241        let path_to_id: FxHashMap<&Path, FileId> = FxHashMap::default();
2242        let mut workspace_roots = FxHashMap::default();
2243        let ws_root = PathBuf::from("/project/packages/ui");
2244        workspace_roots.insert("@myorg/ui", ws_root.as_path());
2245
2246        let pnpm_path =
2247            PathBuf::from("/project/node_modules/.pnpm/@myorg+ui@1.0.0/node_modules/@myorg/ui");
2248        assert_eq!(
2249            try_pnpm_workspace_fallback(&pnpm_path, &path_to_id, &workspace_roots),
2250            None,
2251            "path ending at package name with no relative file should return None"
2252        );
2253    }
2254
2255    #[test]
2256    fn test_try_pnpm_workspace_fallback_nested_dist_esm() {
2257        let src_path = PathBuf::from("/project/packages/ui/src/Button.ts");
2258        let mut path_to_id = FxHashMap::default();
2259        path_to_id.insert(src_path.as_path(), FileId(10));
2260
2261        let mut workspace_roots = FxHashMap::default();
2262        let ws_root = PathBuf::from("/project/packages/ui");
2263        workspace_roots.insert("@myorg/ui", ws_root.as_path());
2264
2265        let pnpm_path = PathBuf::from(
2266            "/project/node_modules/.pnpm/@myorg+ui@1.0.0/node_modules/@myorg/ui/dist/esm/Button.mjs",
2267        );
2268        assert_eq!(
2269            try_pnpm_workspace_fallback(&pnpm_path, &path_to_id, &workspace_roots),
2270            Some(FileId(10)),
2271            "pnpm path with nested dist/esm should resolve through source fallback"
2272        );
2273    }
2274
2275    // --- package_map_target: non-object map branches (lines 583-586) ---
2276
2277    #[test]
2278    fn package_map_target_string_value_dot_key() {
2279        // A non-object top-level map with specifier_key "." delegates to
2280        // package_map_match_value immediately.
2281        let map = serde_json::Value::String("./src/index.ts".to_string());
2282        let conds = conditions();
2283        // A string value resolves to Targets.
2284        let result = package_map_target(&map, ".", &conds);
2285        assert!(
2286            matches!(result, PackageMapTarget::Targets(_)),
2287            "string map with '.' key should return Targets"
2288        );
2289    }
2290
2291    #[test]
2292    fn package_map_target_string_value_non_dot_key_no_match() {
2293        // A non-object top-level map with a non-"." specifier returns NoMatch.
2294        let map = serde_json::Value::String("./src/index.ts".to_string());
2295        let conds = conditions();
2296        let result = package_map_target(&map, "./sub", &conds);
2297        assert!(
2298            matches!(result, PackageMapTarget::NoMatch),
2299            "string map with non-dot key should return NoMatch"
2300        );
2301    }
2302
2303    #[test]
2304    fn package_map_target_null_value_dot_key() {
2305        // A null top-level map with "." returns Blocked (null means blocked).
2306        let map = serde_json::Value::Null;
2307        let conds = conditions();
2308        let result = package_map_target(&map, ".", &conds);
2309        assert!(
2310            matches!(result, PackageMapTarget::Blocked),
2311            "null map with '.' key should return Blocked"
2312        );
2313    }
2314
2315    #[test]
2316    fn package_map_target_bool_value_non_dot_key() {
2317        // A bool top-level map with non-dot key is not an object, returns NoMatch.
2318        let map = serde_json::Value::Bool(true);
2319        let conds = conditions();
2320        let result = package_map_target(&map, "./sub", &conds);
2321        assert!(
2322            matches!(result, PackageMapTarget::NoMatch),
2323            "bool map with non-dot key should return NoMatch"
2324        );
2325    }
2326
2327    // --- package_map_target: condition-only object map (lines 592-596) ---
2328
2329    #[test]
2330    fn package_map_target_condition_only_object_dot_key() {
2331        // An object whose keys are all conditions (not "." or "./...") is treated
2332        // as a condition map when specifier_key is ".".
2333        let map = serde_json::json!({
2334            "import": "./src/index.mjs",
2335            "require": "./src/index.cjs"
2336        });
2337        let conds = conditions();
2338        let result = package_map_target(&map, ".", &conds);
2339        assert!(
2340            matches!(result, PackageMapTarget::Targets(_)),
2341            "condition-only object with '.' key should return Targets"
2342        );
2343    }
2344
2345    #[test]
2346    fn package_map_target_condition_only_object_non_dot_key() {
2347        // Same object, but specifier_key != "." returns NoMatch because no
2348        // subpath key like "./foo" exists.
2349        let map = serde_json::json!({
2350            "import": "./src/index.mjs",
2351            "require": "./src/index.cjs"
2352        });
2353        let conds = conditions();
2354        let result = package_map_target(&map, "./nonexistent", &conds);
2355        assert!(
2356            matches!(result, PackageMapTarget::NoMatch),
2357            "condition-only object with non-dot key should return NoMatch"
2358        );
2359    }
2360
2361    // --- resolve_package_map_value: unmatched conditions, bool, null (lines 641-654) ---
2362
2363    #[test]
2364    fn resolve_package_map_value_unmatched_conditions_returns_none() {
2365        // Object whose only key is not in the active condition set returns None.
2366        let value = serde_json::json!({ "browser": "./src/browser.js" });
2367        let conds = conditions(); // does not include "browser"
2368        assert_eq!(
2369            resolve_package_map_value(&value, &conds, None),
2370            None,
2371            "unmatched condition should return None"
2372        );
2373    }
2374
2375    #[test]
2376    fn resolve_package_map_value_bool_returns_none() {
2377        let value = serde_json::Value::Bool(false);
2378        let conds = conditions();
2379        assert_eq!(
2380            resolve_package_map_value(&value, &conds, None),
2381            None,
2382            "bool value should return None"
2383        );
2384    }
2385
2386    #[test]
2387    fn resolve_package_map_value_number_returns_none() {
2388        let value = serde_json::Value::Number(42.into());
2389        let conds = conditions();
2390        assert_eq!(
2391            resolve_package_map_value(&value, &conds, None),
2392            None,
2393            "number value should return None"
2394        );
2395    }
2396
2397    #[test]
2398    fn resolve_package_map_value_null_returns_none() {
2399        let value = serde_json::Value::Null;
2400        let conds = conditions();
2401        assert_eq!(
2402            resolve_package_map_value(&value, &conds, None),
2403            None,
2404            "null value should return None"
2405        );
2406    }
2407
2408    #[test]
2409    fn resolve_package_map_value_array_all_null_returns_none() {
2410        // Array where every element resolves to None yields None.
2411        let value = serde_json::json!([null, false, 42]);
2412        let conds = conditions();
2413        assert_eq!(
2414            resolve_package_map_value(&value, &conds, None),
2415            None,
2416            "array of unresolvable values should return None"
2417        );
2418    }
2419
2420    #[test]
2421    fn resolve_package_map_value_array_with_valid_entry() {
2422        // Array where one element is a valid string target.
2423        let value = serde_json::json!([null, "./src/index.ts"]);
2424        let conds = conditions();
2425        let result = resolve_package_map_value(&value, &conds, None);
2426        assert_eq!(
2427            result,
2428            Some(vec!["./src/index.ts".to_string()]),
2429            "array with a valid string entry should return that entry"
2430        );
2431    }
2432
2433    // --- package_map_pattern_capture: two-star and no-star branches (lines 659-665) ---
2434
2435    #[test]
2436    fn package_map_pattern_capture_no_star_returns_none() {
2437        // A pattern without '*' returns None (no star found).
2438        assert_eq!(
2439            package_map_pattern_capture("./exact", "./exact"),
2440            None,
2441            "pattern with no star should return None"
2442        );
2443    }
2444
2445    #[test]
2446    fn package_map_pattern_capture_two_stars_returns_none() {
2447        // A pattern with more than one '*' returns None.
2448        assert_eq!(
2449            package_map_pattern_capture("./*/*.js", "./foo/bar.js"),
2450            None,
2451            "pattern with two stars should return None"
2452        );
2453    }
2454
2455    #[test]
2456    fn package_map_pattern_capture_single_star_captures() {
2457        // Sanity: the happy path still works after the guard checks.
2458        assert_eq!(
2459            package_map_pattern_capture("./dist/*/index.js", "./dist/utils/index.js"),
2460            Some("utils".to_string()),
2461        );
2462    }
2463
2464    #[test]
2465    fn package_map_pattern_capture_no_prefix_match_returns_none() {
2466        // Specifier does not start with the pattern prefix.
2467        assert_eq!(
2468            package_map_pattern_capture("./lib/*.js", "./src/foo.js"),
2469            None,
2470        );
2471    }
2472
2473    // --- resolve_package_map_target: parent-dir and root-absolute guard (lines 719-721) ---
2474
2475    #[test]
2476    fn resolve_package_map_target_no_dot_slash_prefix_returns_none() {
2477        // A target that does not start with "./" is rejected by strip_prefix.
2478        let root = PathBuf::from("/project/packages/ui");
2479        let pj = fallow_config::PackageJson::default();
2480        with_package_map_ctx(root, Some("@myorg/ui"), pj, &[], |ctx, manifest, _root| {
2481            let result = resolve_package_map_target(ctx, manifest, "src/index.ts", None);
2482            assert_eq!(result, None, "target without './' should return None");
2483        });
2484    }
2485
2486    #[test]
2487    fn resolve_package_map_target_parent_dir_returns_none() {
2488        // A target starting with "../" is rejected as a path escape.
2489        let root = PathBuf::from("/project/packages/ui");
2490        let pj = fallow_config::PackageJson::default();
2491        with_package_map_ctx(root, Some("@myorg/ui"), pj, &[], |ctx, manifest, _root| {
2492            let result = resolve_package_map_target(ctx, manifest, "./../outside/file.ts", None);
2493            assert_eq!(result, None, "parent-dir target should return None");
2494        });
2495    }
2496
2497    #[test]
2498    fn resolve_package_map_target_absolute_path_returns_none() {
2499        // A target starting with "/" after stripping "./" prefix is rejected.
2500        let root = PathBuf::from("/project/packages/ui");
2501        let pj = fallow_config::PackageJson::default();
2502        with_package_map_ctx(root, Some("@myorg/ui"), pj, &[], |ctx, manifest, _root| {
2503            // "./" + "/" -> "/" after strip_prefix("./") which is no-op, but
2504            // an absolute path disguised as ".//abs" yields "/" start after strip.
2505            let result = resolve_package_map_target(ctx, manifest, ".//abs/path.ts", None);
2506            assert_eq!(result, None, "absolute target should return None");
2507        });
2508    }
2509
2510    #[test]
2511    fn resolve_package_map_target_valid_target_hits_raw_path_map() {
2512        // A valid "./" target resolves when the path is in raw_path_to_id.
2513        let root = PathBuf::from("/project/packages/ui");
2514        let src = root.join("src/index.ts");
2515        let pj = fallow_config::PackageJson::default();
2516        with_package_map_ctx(
2517            root,
2518            Some("@myorg/ui"),
2519            pj,
2520            &[(src, FileId(5))],
2521            |ctx, manifest, _root| {
2522                let result = resolve_package_map_target(ctx, manifest, "./src/index.ts", None);
2523                assert_eq!(
2524                    result,
2525                    Some(FileId(5)),
2526                    "valid target in raw_path_to_id should resolve"
2527                );
2528            },
2529        );
2530    }
2531
2532    // --- package_import_source_subpath: variants (lines 673-689) ---
2533
2534    #[test]
2535    fn package_import_source_subpath_strips_hash_and_package_name() {
2536        let manifest = PackageManifestInfo {
2537            root: PathBuf::from("/project"),
2538            canonical_root: PathBuf::from("/project"),
2539            name: Some("my-pkg".to_string()),
2540            package_json: fallow_config::PackageJson::default(),
2541            deno_import_map: Vec::new(),
2542        };
2543        let result = package_import_source_subpath(&manifest, "#my-pkg/utils");
2544        assert_eq!(
2545            result,
2546            Some(PathBuf::from("utils")),
2547            "should strip '#', package name, and '/' separator"
2548        );
2549    }
2550
2551    #[test]
2552    fn package_import_source_subpath_no_package_name_match_keeps_full_subpath() {
2553        // When the specifier after '#' does not start with the package name,
2554        // the full stripped specifier is returned.
2555        let manifest = PackageManifestInfo {
2556            root: PathBuf::from("/project"),
2557            canonical_root: PathBuf::from("/project"),
2558            name: Some("my-pkg".to_string()),
2559            package_json: fallow_config::PackageJson::default(),
2560            deno_import_map: Vec::new(),
2561        };
2562        let result = package_import_source_subpath(&manifest, "#utils");
2563        assert_eq!(
2564            result,
2565            Some(PathBuf::from("utils")),
2566            "without package-name prefix the full subpath should be kept"
2567        );
2568    }
2569
2570    #[test]
2571    fn package_import_source_subpath_empty_hash_returns_none() {
2572        // "#" with nothing after returns None because stripped is empty and
2573        // the empty string is rejected by the is_empty guard.
2574        let manifest = PackageManifestInfo {
2575            root: PathBuf::from("/project"),
2576            canonical_root: PathBuf::from("/project"),
2577            name: Some("my-pkg".to_string()),
2578            package_json: fallow_config::PackageJson::default(),
2579            deno_import_map: Vec::new(),
2580        };
2581        // "#" strips to "", which is_empty is true, so returns None.
2582        let result = package_import_source_subpath(&manifest, "#");
2583        assert_eq!(
2584            result, None,
2585            "specifier '#' with empty body should return None"
2586        );
2587    }
2588
2589    #[test]
2590    fn package_import_source_subpath_no_hash_returns_none() {
2591        // A specifier not starting with '#' returns None.
2592        let manifest = PackageManifestInfo {
2593            root: PathBuf::from("/project"),
2594            canonical_root: PathBuf::from("/project"),
2595            name: Some("my-pkg".to_string()),
2596            package_json: fallow_config::PackageJson::default(),
2597            deno_import_map: Vec::new(),
2598        };
2599        let result = package_import_source_subpath(&manifest, "no-hash");
2600        assert_eq!(result, None, "specifier without '#' should return None");
2601    }
2602
2603    #[test]
2604    fn package_import_source_subpath_no_manifest_name() {
2605        // When the manifest has no name the full stripped specifier is returned.
2606        let manifest = PackageManifestInfo {
2607            root: PathBuf::from("/project"),
2608            canonical_root: PathBuf::from("/project"),
2609            name: None,
2610            package_json: fallow_config::PackageJson::default(),
2611            deno_import_map: Vec::new(),
2612        };
2613        let result = package_import_source_subpath(&manifest, "#internal/helper");
2614        assert_eq!(
2615            result,
2616            Some(PathBuf::from("internal/helper")),
2617            "manifest without name should return the full stripped specifier"
2618        );
2619    }
2620
2621    // --- nearest_package_manifest: deepest selection (lines 691-701) ---
2622
2623    #[test]
2624    fn nearest_package_manifest_returns_deepest_match() {
2625        let root1 = PathBuf::from("/project");
2626        let root2 = PathBuf::from("/project/packages/ui");
2627        let m1 = PackageManifestInfo {
2628            root: root1.clone(),
2629            canonical_root: root1,
2630            name: Some("root".to_string()),
2631            package_json: fallow_config::PackageJson::default(),
2632            deno_import_map: Vec::new(),
2633        };
2634        let m2 = PackageManifestInfo {
2635            root: root2.clone(),
2636            canonical_root: root2,
2637            name: Some("@myorg/ui".to_string()),
2638            package_json: fallow_config::PackageJson::default(),
2639            deno_import_map: Vec::new(),
2640        };
2641        let manifests = [m1, m2];
2642        let from_file = Path::new("/project/packages/ui/src/index.ts");
2643        let result = nearest_package_manifest(&manifests, from_file);
2644        assert_eq!(
2645            result.and_then(|m| m.name.as_deref()),
2646            Some("@myorg/ui"),
2647            "should pick the deepest (longest path) manifest that contains the file"
2648        );
2649    }
2650
2651    #[test]
2652    fn nearest_package_manifest_no_match_returns_none() {
2653        let root = PathBuf::from("/project/packages/ui");
2654        let m = PackageManifestInfo {
2655            root: root.clone(),
2656            canonical_root: root,
2657            name: Some("@myorg/ui".to_string()),
2658            package_json: fallow_config::PackageJson::default(),
2659            deno_import_map: Vec::new(),
2660        };
2661        let manifests = [m];
2662        // File is outside the manifest root.
2663        let from_file = Path::new("/other/project/src/index.ts");
2664        let result = nearest_package_manifest(&manifests, from_file);
2665        assert!(
2666            result.is_none(),
2667            "file outside all manifest roots should return None"
2668        );
2669    }
2670
2671    // --- lookup_internal_file_id: path_to_id fallback (line 832) ---
2672
2673    #[test]
2674    fn lookup_internal_file_id_uses_path_to_id_when_raw_misses() {
2675        // When raw_path_to_id does not contain the path but path_to_id does,
2676        // lookup_internal_file_id should fall back to path_to_id.
2677        let target = PathBuf::from("/project/src/index.ts");
2678        let mut path_to_id: FxHashMap<&Path, FileId> = FxHashMap::default();
2679        path_to_id.insert(target.as_path(), FileId(99));
2680        let raw_path_to_id: FxHashMap<&Path, FileId> = FxHashMap::default();
2681        let workspace_roots: FxHashMap<&str, &Path> = FxHashMap::default();
2682        let condition_names = conditions();
2683        let resolver = crate::read_trace::Resolver::new(oxc_resolver::ResolveOptions::default());
2684        let tsconfig_warned = std::sync::Mutex::new(FxHashSet::default());
2685        let tsconfig_cache = TsconfigCache::default();
2686        let canonicalize_cache = CanonicalizeCache::default();
2687        let root = PathBuf::from("/project");
2688        let script_resolver = crate::resolve::specifier::create_script_resolver(&resolver);
2689        let ctx = ResolveContext {
2690            resolver: &resolver,
2691            script_resolver: &script_resolver,
2692            style_resolver: &resolver,
2693            extensions: &[],
2694            path_to_id: &path_to_id,
2695            raw_path_to_id: &raw_path_to_id,
2696            workspace_roots: &workspace_roots,
2697            package_manifests: &[],
2698            has_deno_import_maps: false,
2699            condition_names: &condition_names,
2700            path_aliases: &[],
2701            scoped_path_aliases: &[],
2702            scss_include_paths: &[],
2703            static_dir_mappings: &[],
2704            framework_static_dir_mappings: &[],
2705            root: &root,
2706            canonical_fallback: None,
2707            tsconfig_warned: &tsconfig_warned,
2708            tsconfig_cache: &tsconfig_cache,
2709            canonicalize_cache: &canonicalize_cache,
2710        };
2711        let result = lookup_internal_file_id(&ctx, &target);
2712        assert_eq!(
2713            result,
2714            Some(FileId(99)),
2715            "should fall back from raw_path_to_id to path_to_id"
2716        );
2717    }
2718
2719    // --- try_scss_partial_fallback: colon guard (line 91) ---
2720
2721    #[test]
2722    fn try_scss_partial_fallback_rejects_colon_specifier() {
2723        // A specifier containing ':' (e.g. a Sass built-in like "sass:math")
2724        // must return None immediately.
2725        let root = PathBuf::from("/project");
2726        let pj = fallow_config::PackageJson::default();
2727        with_package_map_ctx(root.clone(), None, pj, &[], |ctx, _manifest, _r| {
2728            let from_file = root.join("src/main.scss");
2729            let result = try_scss_partial_fallback(ctx, &from_file, "sass:math");
2730            assert!(
2731                result.is_none(),
2732                "specifier with ':' should short-circuit to None"
2733            );
2734        });
2735    }
2736
2737    #[test]
2738    fn try_scss_partial_fallback_rejects_already_partial_filename() {
2739        // A specifier whose filename already starts with '_' (i.e. it's already a
2740        // partial path) must return None immediately.
2741        let root = PathBuf::from("/project");
2742        let pj = fallow_config::PackageJson::default();
2743        with_package_map_ctx(root.clone(), None, pj, &[], |ctx, _manifest, _r| {
2744            let from_file = root.join("src/main.scss");
2745            let result = try_scss_partial_fallback(ctx, &from_file, "./_variables");
2746            assert!(
2747                result.is_none(),
2748                "already-partial filename should short-circuit to None"
2749            );
2750        });
2751    }
2752}