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