1use std::path::{Component, Path, PathBuf};
2
3use super::parse_scripts::extract_script_file_refs;
4use super::walk::SOURCE_EXTENSIONS;
5use fallow_config::{EntryPointRole, PackageJson, ResolvedConfig};
6use fallow_types::discover::{DiscoveredFile, EntryPoint, EntryPointSource};
7use rustc_hash::FxHashMap;
8
9const OUTPUT_DIRS: &[&str] = &["dist", "build", "out", "esm", "cjs"];
13const SKIPPED_ENTRY_WARNING_PREVIEW: usize = 5;
14
15fn format_skipped_entry_warning(skipped_entries: &FxHashMap<String, usize>) -> Option<String> {
16 if skipped_entries.is_empty() {
17 return None;
18 }
19
20 let mut entries = skipped_entries
21 .iter()
22 .map(|(path, count)| (path.as_str(), *count))
23 .collect::<Vec<_>>();
24 entries.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(b.0)));
25
26 let preview = entries
27 .iter()
28 .take(SKIPPED_ENTRY_WARNING_PREVIEW)
29 .map(|(path, count)| {
30 if *count > 1 {
31 format!("{path} ({count}x)")
32 } else {
33 (*path).to_owned()
34 }
35 })
36 .collect::<Vec<_>>();
37
38 let omitted = entries.len().saturating_sub(SKIPPED_ENTRY_WARNING_PREVIEW);
39 let tail = if omitted > 0 {
40 format!(" (and {omitted} more)")
41 } else {
42 String::new()
43 };
44 let total = entries.iter().map(|(_, count)| *count).sum::<usize>();
45 let noun = if total == 1 {
46 "package.json entry point"
47 } else {
48 "package.json entry points"
49 };
50
51 Some(format!(
52 "Skipped {total} {noun} outside project root or containing parent directory traversal: {}{tail}",
53 preview.join(", ")
54 ))
55}
56
57pub fn warn_skipped_entry_summary(skipped_entries: &FxHashMap<String, usize>) {
58 if let Some(message) = format_skipped_entry_warning(skipped_entries) {
59 tracing::warn!("{message}");
60 }
61}
62
63#[derive(Debug, Clone, Default)]
65pub struct CategorizedEntryPoints {
66 pub all: Vec<EntryPoint>,
67 pub runtime: Vec<EntryPoint>,
68 pub test: Vec<EntryPoint>,
69}
70
71impl CategorizedEntryPoints {
72 pub fn push_runtime(&mut self, entry: EntryPoint) {
73 self.runtime.push(entry.clone());
74 self.all.push(entry);
75 }
76
77 pub fn push_test(&mut self, entry: EntryPoint) {
78 self.test.push(entry.clone());
79 self.all.push(entry);
80 }
81
82 pub fn push_support(&mut self, entry: EntryPoint) {
83 self.all.push(entry);
84 }
85
86 pub fn extend_runtime<I>(&mut self, entries: I)
87 where
88 I: IntoIterator<Item = EntryPoint>,
89 {
90 for entry in entries {
91 self.push_runtime(entry);
92 }
93 }
94
95 pub fn extend_test<I>(&mut self, entries: I)
96 where
97 I: IntoIterator<Item = EntryPoint>,
98 {
99 for entry in entries {
100 self.push_test(entry);
101 }
102 }
103
104 pub fn extend_support<I>(&mut self, entries: I)
105 where
106 I: IntoIterator<Item = EntryPoint>,
107 {
108 for entry in entries {
109 self.push_support(entry);
110 }
111 }
112
113 pub fn extend(&mut self, other: Self) {
114 self.all.extend(other.all);
115 self.runtime.extend(other.runtime);
116 self.test.extend(other.test);
117 }
118
119 #[must_use]
120 pub fn dedup(mut self) -> Self {
121 dedup_entry_paths(&mut self.all);
122 dedup_entry_paths(&mut self.runtime);
123 dedup_entry_paths(&mut self.test);
124 self
125 }
126}
127
128fn dedup_entry_paths(entries: &mut Vec<EntryPoint>) {
129 entries.sort_by(|a, b| a.path.cmp(&b.path));
130 entries.dedup_by(|a, b| a.path == b.path);
131}
132
133#[derive(Debug, Default)]
134pub struct EntryPointDiscovery {
135 pub entries: Vec<EntryPoint>,
136 pub skipped_entries: FxHashMap<String, usize>,
137}
138
139fn resolve_entry_path_with_tracking(
146 base: &Path,
147 entry: &str,
148 canonical_root: &Path,
149 source: EntryPointSource,
150 mut skipped_entries: Option<&mut FxHashMap<String, usize>>,
151) -> Option<EntryPoint> {
152 if entry.contains('*') {
155 return None;
156 }
157
158 if entry_has_parent_dir(entry) {
159 if let Some(skipped_entries) = skipped_entries.as_mut() {
160 *skipped_entries.entry(entry.to_owned()).or_default() += 1;
161 } else {
162 tracing::warn!(path = %entry, "Skipping entry point containing parent directory traversal");
163 }
164 return None;
165 }
166
167 let resolved = base.join(entry);
168
169 if let Some(source_path) = try_output_to_source_path(base, entry) {
174 return validated_entry_point(
175 &source_path,
176 canonical_root,
177 entry,
178 source,
179 skipped_entries.as_deref_mut(),
180 );
181 }
182
183 if is_entry_in_output_dir(entry)
191 && let Some(source_path) = try_source_index_fallback(base)
192 {
193 tracing::info!(
194 entry = %entry,
195 fallback = %source_path.display(),
196 "package.json entry resolves to an ignored output directory; falling back to source index"
197 );
198 return validated_entry_point(
199 &source_path,
200 canonical_root,
201 entry,
202 source,
203 skipped_entries.as_deref_mut(),
204 );
205 }
206
207 if resolved.is_file() {
208 return validated_entry_point(
209 &resolved,
210 canonical_root,
211 entry,
212 source,
213 skipped_entries.as_deref_mut(),
214 );
215 }
216
217 for ext in SOURCE_EXTENSIONS {
219 let with_ext = resolved.with_extension(ext);
220 if with_ext.is_file() {
221 return validated_entry_point(
222 &with_ext,
223 canonical_root,
224 entry,
225 source,
226 skipped_entries.as_deref_mut(),
227 );
228 }
229 }
230 None
231}
232
233fn entry_has_parent_dir(entry: &str) -> bool {
234 Path::new(entry)
235 .components()
236 .any(|component| matches!(component, Component::ParentDir))
237}
238
239fn validated_entry_point(
240 candidate: &Path,
241 canonical_root: &Path,
242 entry: &str,
243 source: EntryPointSource,
244 mut skipped_entries: Option<&mut FxHashMap<String, usize>>,
245) -> Option<EntryPoint> {
246 let canonical_candidate = match dunce::canonicalize(candidate) {
247 Ok(path) => path,
248 Err(err) => {
249 tracing::warn!(
250 path = %candidate.display(),
251 %entry,
252 error = %err,
253 "Skipping entry point that could not be canonicalized"
254 );
255 return None;
256 }
257 };
258
259 if !canonical_candidate.starts_with(canonical_root) {
260 if let Some(skipped_entries) = skipped_entries.as_mut() {
261 *skipped_entries.entry(entry.to_owned()).or_default() += 1;
262 } else {
263 tracing::warn!(
264 path = %candidate.display(),
265 %entry,
266 "Skipping entry point outside project root"
267 );
268 }
269 return None;
270 }
271
272 Some(EntryPoint {
273 path: candidate.to_path_buf(),
274 source,
275 })
276}
277
278pub fn resolve_entry_path(
279 base: &Path,
280 entry: &str,
281 canonical_root: &Path,
282 source: EntryPointSource,
283) -> Option<EntryPoint> {
284 resolve_entry_path_with_tracking(base, entry, canonical_root, source, None)
285}
286fn try_output_to_source_path(base: &Path, entry: &str) -> Option<PathBuf> {
298 let entry_path = Path::new(entry);
299 let components: Vec<_> = entry_path.components().collect();
300
301 let output_pos = components.iter().rposition(|c| {
303 if let std::path::Component::Normal(s) = c
304 && let Some(name) = s.to_str()
305 {
306 return OUTPUT_DIRS.contains(&name);
307 }
308 false
309 })?;
310
311 let prefix: PathBuf = components[..output_pos]
313 .iter()
314 .filter(|c| !matches!(c, std::path::Component::CurDir))
315 .collect();
316
317 let suffix: PathBuf = components[output_pos + 1..].iter().collect();
319
320 for ext in SOURCE_EXTENSIONS {
322 let source_candidate = base
323 .join(&prefix)
324 .join("src")
325 .join(suffix.with_extension(ext));
326 if source_candidate.exists() {
327 return Some(source_candidate);
328 }
329 }
330
331 None
332}
333
334const SOURCE_INDEX_FALLBACK_STEMS: &[&str] = &["src/index", "src/main", "index", "main"];
337
338fn is_entry_in_output_dir(entry: &str) -> bool {
343 Path::new(entry).components().any(|c| {
344 matches!(
345 c,
346 std::path::Component::Normal(s)
347 if s.to_str().is_some_and(|name| OUTPUT_DIRS.contains(&name))
348 )
349 })
350}
351
352fn try_source_index_fallback(base: &Path) -> Option<PathBuf> {
359 for stem in SOURCE_INDEX_FALLBACK_STEMS {
360 for ext in SOURCE_EXTENSIONS {
361 let candidate = base.join(format!("{stem}.{ext}"));
362 if candidate.is_file() {
363 return Some(candidate);
364 }
365 }
366 }
367 None
368}
369
370const DEFAULT_INDEX_PATTERNS: &[&str] = &[
372 "src/index.{ts,tsx,js,jsx}",
373 "src/main.{ts,tsx,js,jsx}",
374 "index.{ts,tsx,js,jsx}",
375 "main.{ts,tsx,js,jsx}",
376];
377
378fn apply_default_fallback(
383 files: &[DiscoveredFile],
384 root: &Path,
385 ws_filter: Option<&Path>,
386) -> Vec<EntryPoint> {
387 let default_matchers: Vec<globset::GlobMatcher> = DEFAULT_INDEX_PATTERNS
388 .iter()
389 .filter_map(|p| globset::Glob::new(p).ok().map(|g| g.compile_matcher()))
390 .collect();
391
392 let mut entries = Vec::new();
393 for file in files {
394 if let Some(ws_root) = ws_filter
396 && file.path.strip_prefix(ws_root).is_err()
397 {
398 continue;
399 }
400 let relative = file.path.strip_prefix(root).unwrap_or(&file.path);
401 let relative_str = relative.to_string_lossy();
402 if default_matchers
403 .iter()
404 .any(|m| m.is_match(relative_str.as_ref()))
405 {
406 entries.push(EntryPoint {
407 path: file.path.clone(),
408 source: EntryPointSource::DefaultIndex,
409 });
410 }
411 }
412 entries
413}
414
415fn discover_entry_points_with_warnings_impl(
417 config: &ResolvedConfig,
418 files: &[DiscoveredFile],
419 root_pkg: Option<&PackageJson>,
420 include_nested_package_entries: bool,
421) -> EntryPointDiscovery {
422 let _span = tracing::info_span!("discover_entry_points").entered();
423 let mut discovery = EntryPointDiscovery::default();
424
425 let relative_paths: Vec<String> = files
427 .iter()
428 .map(|f| {
429 f.path
430 .strip_prefix(&config.root)
431 .unwrap_or(&f.path)
432 .to_string_lossy()
433 .into_owned()
434 })
435 .collect();
436
437 {
440 let mut builder = globset::GlobSetBuilder::new();
441 for pattern in &config.entry_patterns {
442 if let Ok(glob) = globset::Glob::new(pattern) {
443 builder.add(glob);
444 }
445 }
446 if let Ok(glob_set) = builder.build()
447 && !glob_set.is_empty()
448 {
449 for (idx, rel) in relative_paths.iter().enumerate() {
450 if glob_set.is_match(rel) {
451 discovery.entries.push(EntryPoint {
452 path: files[idx].path.clone(),
453 source: EntryPointSource::ManualEntry,
454 });
455 }
456 }
457 }
458 }
459
460 let canonical_root = dunce::canonicalize(&config.root).unwrap_or_else(|_| config.root.clone());
463 if let Some(pkg) = root_pkg {
464 for entry_path in pkg.entry_points() {
465 if let Some(ep) = resolve_entry_path_with_tracking(
466 &config.root,
467 &entry_path,
468 &canonical_root,
469 EntryPointSource::PackageJsonMain,
470 Some(&mut discovery.skipped_entries),
471 ) {
472 discovery.entries.push(ep);
473 }
474 }
475
476 if let Some(scripts) = &pkg.scripts {
478 for script_value in scripts.values() {
479 for file_ref in extract_script_file_refs(script_value) {
480 if let Some(ep) = resolve_entry_path_with_tracking(
481 &config.root,
482 &file_ref,
483 &canonical_root,
484 EntryPointSource::PackageJsonScript,
485 Some(&mut discovery.skipped_entries),
486 ) {
487 discovery.entries.push(ep);
488 }
489 }
490 }
491 }
492
493 }
495
496 if include_nested_package_entries {
500 let exports_dirs = root_pkg
501 .map(PackageJson::exports_subdirectories)
502 .unwrap_or_default();
503 discover_nested_package_entries(
504 &config.root,
505 files,
506 &mut discovery.entries,
507 &canonical_root,
508 &exports_dirs,
509 &mut discovery.skipped_entries,
510 );
511 }
512
513 if discovery.entries.is_empty() {
515 discovery.entries = apply_default_fallback(files, &config.root, None);
516 }
517
518 discovery.entries.sort_by(|a, b| a.path.cmp(&b.path));
520 discovery.entries.dedup_by(|a, b| a.path == b.path);
521
522 discovery
523}
524
525pub fn discover_entry_points_with_warnings_from_pkg(
526 config: &ResolvedConfig,
527 files: &[DiscoveredFile],
528 root_pkg: Option<&PackageJson>,
529 include_nested_package_entries: bool,
530) -> EntryPointDiscovery {
531 discover_entry_points_with_warnings_impl(
532 config,
533 files,
534 root_pkg,
535 include_nested_package_entries,
536 )
537}
538
539pub fn discover_entry_points_with_warnings(
540 config: &ResolvedConfig,
541 files: &[DiscoveredFile],
542) -> EntryPointDiscovery {
543 let pkg_path = config.root.join("package.json");
544 let root_pkg = PackageJson::load(&pkg_path).ok();
545 discover_entry_points_with_warnings_impl(config, files, root_pkg.as_ref(), true)
546}
547
548pub fn discover_entry_points(config: &ResolvedConfig, files: &[DiscoveredFile]) -> Vec<EntryPoint> {
549 let discovery = discover_entry_points_with_warnings(config, files);
550 warn_skipped_entry_summary(&discovery.skipped_entries);
551 discovery.entries
552}
553
554fn discover_nested_package_entries(
564 root: &Path,
565 _files: &[DiscoveredFile],
566 entries: &mut Vec<EntryPoint>,
567 canonical_root: &Path,
568 exports_subdirectories: &[String],
569 skipped_entries: &mut FxHashMap<String, usize>,
570) {
571 let mut visited = rustc_hash::FxHashSet::default();
572
573 let search_dirs = [
575 "packages", "apps", "libs", "modules", "plugins", "services", "tools", "utils",
576 ];
577 for dir_name in &search_dirs {
578 let search_dir = root.join(dir_name);
579 if !search_dir.is_dir() {
580 continue;
581 }
582 let Ok(read_dir) = std::fs::read_dir(&search_dir) else {
583 continue;
584 };
585 for entry in read_dir.flatten() {
586 let pkg_dir = entry.path();
587 if visited.insert(pkg_dir.clone()) {
588 collect_nested_package_entries(&pkg_dir, entries, canonical_root, skipped_entries);
589 }
590 }
591 }
592
593 for dir_name in exports_subdirectories {
595 let pkg_dir = root.join(dir_name);
596 if pkg_dir.is_dir() && visited.insert(pkg_dir.clone()) {
597 collect_nested_package_entries(&pkg_dir, entries, canonical_root, skipped_entries);
598 }
599 }
600}
601
602fn collect_nested_package_entries(
604 pkg_dir: &Path,
605 entries: &mut Vec<EntryPoint>,
606 canonical_root: &Path,
607 skipped_entries: &mut FxHashMap<String, usize>,
608) {
609 let pkg_path = pkg_dir.join("package.json");
610 if !pkg_path.exists() {
611 return;
612 }
613 let Ok(pkg) = PackageJson::load(&pkg_path) else {
614 return;
615 };
616 for entry_path in pkg.entry_points() {
617 if entry_path.contains('*') {
618 expand_wildcard_entries(pkg_dir, &entry_path, canonical_root, entries);
619 } else if let Some(ep) = resolve_entry_path_with_tracking(
620 pkg_dir,
621 &entry_path,
622 canonical_root,
623 EntryPointSource::PackageJsonExports,
624 Some(&mut *skipped_entries),
625 ) {
626 entries.push(ep);
627 }
628 }
629 if let Some(scripts) = &pkg.scripts {
630 for script_value in scripts.values() {
631 for file_ref in extract_script_file_refs(script_value) {
632 if let Some(ep) = resolve_entry_path_with_tracking(
633 pkg_dir,
634 &file_ref,
635 canonical_root,
636 EntryPointSource::PackageJsonScript,
637 Some(&mut *skipped_entries),
638 ) {
639 entries.push(ep);
640 }
641 }
642 }
643 }
644}
645
646fn expand_wildcard_entries(
652 base: &Path,
653 pattern: &str,
654 canonical_root: &Path,
655 entries: &mut Vec<EntryPoint>,
656) {
657 let full_pattern = base.join(pattern).to_string_lossy().to_string();
658 let Ok(matches) = glob::glob(&full_pattern) else {
659 return;
660 };
661 for path_result in matches {
662 let Ok(path) = path_result else {
663 continue;
664 };
665 if let Ok(canonical) = dunce::canonicalize(&path)
666 && canonical.starts_with(canonical_root)
667 {
668 entries.push(EntryPoint {
669 path,
670 source: EntryPointSource::PackageJsonExports,
671 });
672 }
673 }
674}
675
676#[must_use]
678fn discover_workspace_entry_points_with_warnings_impl(
679 ws_root: &Path,
680 all_files: &[DiscoveredFile],
681 pkg: Option<&PackageJson>,
682) -> EntryPointDiscovery {
683 let mut discovery = EntryPointDiscovery::default();
684
685 if let Some(pkg) = pkg {
686 let canonical_ws_root =
687 dunce::canonicalize(ws_root).unwrap_or_else(|_| ws_root.to_path_buf());
688 for entry_path in pkg.entry_points() {
689 if entry_path.contains('*') {
690 expand_wildcard_entries(
691 ws_root,
692 &entry_path,
693 &canonical_ws_root,
694 &mut discovery.entries,
695 );
696 } else if let Some(ep) = resolve_entry_path_with_tracking(
697 ws_root,
698 &entry_path,
699 &canonical_ws_root,
700 EntryPointSource::PackageJsonMain,
701 Some(&mut discovery.skipped_entries),
702 ) {
703 discovery.entries.push(ep);
704 }
705 }
706
707 if let Some(scripts) = &pkg.scripts {
709 for script_value in scripts.values() {
710 for file_ref in extract_script_file_refs(script_value) {
711 if let Some(ep) = resolve_entry_path_with_tracking(
712 ws_root,
713 &file_ref,
714 &canonical_ws_root,
715 EntryPointSource::PackageJsonScript,
716 Some(&mut discovery.skipped_entries),
717 ) {
718 discovery.entries.push(ep);
719 }
720 }
721 }
722 }
723
724 }
726
727 if discovery.entries.is_empty() {
729 discovery.entries = apply_default_fallback(all_files, ws_root, Some(ws_root));
730 }
731
732 discovery.entries.sort_by(|a, b| a.path.cmp(&b.path));
733 discovery.entries.dedup_by(|a, b| a.path == b.path);
734 discovery
735}
736
737pub fn discover_workspace_entry_points_with_warnings_from_pkg(
738 ws_root: &Path,
739 all_files: &[DiscoveredFile],
740 pkg: Option<&PackageJson>,
741) -> EntryPointDiscovery {
742 discover_workspace_entry_points_with_warnings_impl(ws_root, all_files, pkg)
743}
744
745#[must_use]
746pub fn discover_workspace_entry_points_with_warnings(
747 ws_root: &Path,
748 _config: &ResolvedConfig,
749 all_files: &[DiscoveredFile],
750) -> EntryPointDiscovery {
751 let pkg_path = ws_root.join("package.json");
752 let pkg = PackageJson::load(&pkg_path).ok();
753 discover_workspace_entry_points_with_warnings_impl(ws_root, all_files, pkg.as_ref())
754}
755
756#[must_use]
757pub fn discover_workspace_entry_points(
758 ws_root: &Path,
759 config: &ResolvedConfig,
760 all_files: &[DiscoveredFile],
761) -> Vec<EntryPoint> {
762 let discovery = discover_workspace_entry_points_with_warnings(ws_root, config, all_files);
763 warn_skipped_entry_summary(&discovery.skipped_entries);
764 discovery.entries
765}
766
767#[must_use]
772pub fn discover_plugin_entry_points(
773 plugin_result: &crate::plugins::AggregatedPluginResult,
774 config: &ResolvedConfig,
775 files: &[DiscoveredFile],
776) -> Vec<EntryPoint> {
777 discover_plugin_entry_point_sets(plugin_result, config, files).all
778}
779
780#[must_use]
782pub fn discover_plugin_entry_point_sets(
783 plugin_result: &crate::plugins::AggregatedPluginResult,
784 config: &ResolvedConfig,
785 files: &[DiscoveredFile],
786) -> CategorizedEntryPoints {
787 let mut entries = CategorizedEntryPoints::default();
788
789 let relative_paths: Vec<String> = files
791 .iter()
792 .map(|f| {
793 f.path
794 .strip_prefix(&config.root)
795 .unwrap_or(&f.path)
796 .to_string_lossy()
797 .into_owned()
798 })
799 .collect();
800
801 let mut builder = globset::GlobSetBuilder::new();
804 let mut glob_meta: Vec<CompiledEntryRule<'_>> = Vec::new();
805 for (rule, pname) in &plugin_result.entry_patterns {
806 if let Some((include, compiled)) = compile_entry_rule(rule, pname, plugin_result) {
807 builder.add(include);
808 glob_meta.push(compiled);
809 }
810 }
811 for (pattern, pname) in plugin_result
812 .discovered_always_used
813 .iter()
814 .chain(plugin_result.always_used.iter())
815 .chain(plugin_result.fixture_patterns.iter())
816 {
817 if let Ok(glob) = globset::GlobBuilder::new(pattern)
818 .literal_separator(true)
819 .build()
820 {
821 builder.add(glob);
822 if let Some(path) = crate::plugins::CompiledPathRule::for_entry_rule(
823 &crate::plugins::PathRule::new(pattern.clone()),
824 "support entry pattern",
825 ) {
826 glob_meta.push(CompiledEntryRule {
827 path,
828 plugin_name: pname,
829 role: EntryPointRole::Support,
830 });
831 }
832 }
833 }
834 if let Ok(glob_set) = builder.build()
835 && !glob_set.is_empty()
836 {
837 for (idx, rel) in relative_paths.iter().enumerate() {
838 let matches: Vec<usize> = glob_set
839 .matches(rel)
840 .into_iter()
841 .filter(|match_idx| glob_meta[*match_idx].matches(rel))
842 .collect();
843 if !matches.is_empty() {
844 let name = glob_meta[matches[0]].plugin_name;
845 let entry = EntryPoint {
846 path: files[idx].path.clone(),
847 source: EntryPointSource::Plugin {
848 name: name.to_string(),
849 },
850 };
851
852 let mut has_runtime = false;
853 let mut has_test = false;
854 let mut has_support = false;
855 for match_idx in matches {
856 match glob_meta[match_idx].role {
857 EntryPointRole::Runtime => has_runtime = true,
858 EntryPointRole::Test => has_test = true,
859 EntryPointRole::Support => has_support = true,
860 }
861 }
862
863 if has_runtime {
864 entries.push_runtime(entry.clone());
865 }
866 if has_test {
867 entries.push_test(entry.clone());
868 }
869 if has_support || (!has_runtime && !has_test) {
870 entries.push_support(entry);
871 }
872 }
873 }
874 }
875
876 for (setup_file, pname) in &plugin_result.setup_files {
878 let resolved = if setup_file.is_absolute() {
879 setup_file.clone()
880 } else {
881 config.root.join(setup_file)
882 };
883 if resolved.exists() {
884 entries.push_support(EntryPoint {
885 path: resolved,
886 source: EntryPointSource::Plugin {
887 name: pname.clone(),
888 },
889 });
890 } else {
891 for ext in SOURCE_EXTENSIONS {
893 let with_ext = resolved.with_extension(ext);
894 if with_ext.exists() {
895 entries.push_support(EntryPoint {
896 path: with_ext,
897 source: EntryPointSource::Plugin {
898 name: pname.clone(),
899 },
900 });
901 break;
902 }
903 }
904 }
905 }
906
907 entries.dedup()
908}
909
910#[must_use]
915pub fn discover_dynamically_loaded_entry_points(
916 config: &ResolvedConfig,
917 files: &[DiscoveredFile],
918) -> Vec<EntryPoint> {
919 if config.dynamically_loaded.is_empty() {
920 return Vec::new();
921 }
922
923 let mut builder = globset::GlobSetBuilder::new();
924 for pattern in &config.dynamically_loaded {
925 if let Ok(glob) = globset::Glob::new(pattern) {
926 builder.add(glob);
927 }
928 }
929 let Ok(glob_set) = builder.build() else {
930 return Vec::new();
931 };
932 if glob_set.is_empty() {
933 return Vec::new();
934 }
935
936 let mut entries = Vec::new();
937 for file in files {
938 let rel = file
939 .path
940 .strip_prefix(&config.root)
941 .unwrap_or(&file.path)
942 .to_string_lossy();
943 if glob_set.is_match(rel.as_ref()) {
944 entries.push(EntryPoint {
945 path: file.path.clone(),
946 source: EntryPointSource::DynamicallyLoaded,
947 });
948 }
949 }
950 entries
951}
952
953struct CompiledEntryRule<'a> {
954 path: crate::plugins::CompiledPathRule,
955 plugin_name: &'a str,
956 role: EntryPointRole,
957}
958
959impl CompiledEntryRule<'_> {
960 fn matches(&self, path: &str) -> bool {
961 self.path.matches(path)
962 }
963}
964
965fn compile_entry_rule<'a>(
966 rule: &'a crate::plugins::PathRule,
967 plugin_name: &'a str,
968 plugin_result: &'a crate::plugins::AggregatedPluginResult,
969) -> Option<(globset::Glob, CompiledEntryRule<'a>)> {
970 let include = match globset::GlobBuilder::new(&rule.pattern)
971 .literal_separator(true)
972 .build()
973 {
974 Ok(glob) => glob,
975 Err(err) => {
976 tracing::warn!("invalid entry pattern '{}': {err}", rule.pattern);
977 return None;
978 }
979 };
980 let role = plugin_result
981 .entry_point_roles
982 .get(plugin_name)
983 .copied()
984 .unwrap_or(EntryPointRole::Support);
985 Some((
986 include,
987 CompiledEntryRule {
988 path: crate::plugins::CompiledPathRule::for_entry_rule(rule, "entry pattern")?,
989 plugin_name,
990 role,
991 },
992 ))
993}
994
995#[must_use]
997pub fn compile_glob_set(patterns: &[String]) -> Option<globset::GlobSet> {
998 if patterns.is_empty() {
999 return None;
1000 }
1001 let mut builder = globset::GlobSetBuilder::new();
1002 for pattern in patterns {
1003 if let Ok(glob) = globset::GlobBuilder::new(pattern)
1004 .literal_separator(true)
1005 .build()
1006 {
1007 builder.add(glob);
1008 }
1009 }
1010 builder.build().ok()
1011}
1012
1013#[cfg(test)]
1014mod tests {
1015 use super::*;
1016 use fallow_config::{FallowConfig, OutputFormat, RulesConfig};
1017 use fallow_types::discover::FileId;
1018 use proptest::prelude::*;
1019
1020 proptest! {
1021 #[test]
1023 fn glob_patterns_never_panic_on_compile(
1024 prefix in "[a-zA-Z0-9_]{1,20}",
1025 ext in prop::sample::select(vec!["ts", "tsx", "js", "jsx", "vue", "svelte", "astro", "mdx"]),
1026 ) {
1027 let pattern = format!("**/{prefix}*.{ext}");
1028 let result = globset::Glob::new(&pattern);
1030 prop_assert!(result.is_ok(), "Glob::new should not fail for well-formed patterns");
1031 }
1032
1033 #[test]
1035 fn non_source_extensions_not_in_list(
1036 ext in prop::sample::select(vec!["py", "rb", "rs", "go", "java", "xml", "yaml", "toml", "md", "txt", "png", "jpg", "wasm", "lock"]),
1037 ) {
1038 prop_assert!(
1039 !SOURCE_EXTENSIONS.contains(&ext),
1040 "Extension '{ext}' should NOT be in SOURCE_EXTENSIONS"
1041 );
1042 }
1043
1044 #[test]
1046 fn compile_glob_set_no_panic(
1047 patterns in prop::collection::vec("[a-zA-Z0-9_*/.]{1,30}", 0..10),
1048 ) {
1049 let _ = compile_glob_set(&patterns);
1051 }
1052 }
1053
1054 #[test]
1056 fn compile_glob_set_empty_input() {
1057 assert!(
1058 compile_glob_set(&[]).is_none(),
1059 "empty patterns should return None"
1060 );
1061 }
1062
1063 #[test]
1064 fn compile_glob_set_valid_patterns() {
1065 let patterns = vec!["**/*.ts".to_string(), "src/**/*.js".to_string()];
1066 let set = compile_glob_set(&patterns);
1067 assert!(set.is_some(), "valid patterns should compile");
1068 let set = set.unwrap();
1069 assert!(set.is_match("src/foo.ts"));
1070 assert!(set.is_match("src/bar.js"));
1071 assert!(!set.is_match("src/bar.py"));
1072 }
1073
1074 #[test]
1075 fn compile_glob_set_keeps_star_within_a_single_path_segment() {
1076 let patterns = vec!["composables/*.{ts,js}".to_string()];
1077 let set = compile_glob_set(&patterns).expect("pattern should compile");
1078
1079 assert!(set.is_match("composables/useFoo.ts"));
1080 assert!(!set.is_match("composables/nested/useFoo.ts"));
1081 }
1082
1083 #[test]
1084 fn plugin_entry_point_sets_preserve_runtime_test_and_support_roles() {
1085 let dir = tempfile::tempdir().expect("create temp dir");
1086 let root = dir.path();
1087 std::fs::create_dir_all(root.join("src")).unwrap();
1088 std::fs::create_dir_all(root.join("tests")).unwrap();
1089 std::fs::write(root.join("src/runtime.ts"), "export const runtime = 1;").unwrap();
1090 std::fs::write(root.join("src/setup.ts"), "export const setup = 1;").unwrap();
1091 std::fs::write(root.join("tests/app.test.ts"), "export const test = 1;").unwrap();
1092
1093 let config = FallowConfig {
1094 schema: None,
1095 extends: vec![],
1096 entry: vec![],
1097 ignore_patterns: vec![],
1098 framework: vec![],
1099 workspaces: None,
1100 ignore_dependencies: vec![],
1101 ignore_exports: vec![],
1102 ignore_catalog_references: vec![],
1103 ignore_dependency_overrides: vec![],
1104 ignore_exports_used_in_file: fallow_config::IgnoreExportsUsedInFileConfig::default(),
1105 used_class_members: vec![],
1106 duplicates: fallow_config::DuplicatesConfig::default(),
1107 health: fallow_config::HealthConfig::default(),
1108 rules: RulesConfig::default(),
1109 boundaries: fallow_config::BoundaryConfig::default(),
1110 production: false.into(),
1111 plugins: vec![],
1112 dynamically_loaded: vec![],
1113 overrides: vec![],
1114 regression: None,
1115 audit: fallow_config::AuditConfig::default(),
1116 codeowners: None,
1117 public_packages: vec![],
1118 flags: fallow_config::FlagsConfig::default(),
1119 resolve: fallow_config::ResolveConfig::default(),
1120 sealed: false,
1121 include_entry_exports: false,
1122 }
1123 .resolve(root.to_path_buf(), OutputFormat::Human, 4, true, true);
1124
1125 let files = vec![
1126 DiscoveredFile {
1127 id: FileId(0),
1128 path: root.join("src/runtime.ts"),
1129 size_bytes: 1,
1130 },
1131 DiscoveredFile {
1132 id: FileId(1),
1133 path: root.join("src/setup.ts"),
1134 size_bytes: 1,
1135 },
1136 DiscoveredFile {
1137 id: FileId(2),
1138 path: root.join("tests/app.test.ts"),
1139 size_bytes: 1,
1140 },
1141 ];
1142
1143 let mut plugin_result = crate::plugins::AggregatedPluginResult::default();
1144 plugin_result.entry_patterns.push((
1145 crate::plugins::PathRule::new("src/runtime.ts"),
1146 "runtime-plugin".to_string(),
1147 ));
1148 plugin_result.entry_patterns.push((
1149 crate::plugins::PathRule::new("tests/app.test.ts"),
1150 "test-plugin".to_string(),
1151 ));
1152 plugin_result
1153 .always_used
1154 .push(("src/setup.ts".to_string(), "support-plugin".to_string()));
1155 plugin_result
1156 .entry_point_roles
1157 .insert("runtime-plugin".to_string(), EntryPointRole::Runtime);
1158 plugin_result
1159 .entry_point_roles
1160 .insert("test-plugin".to_string(), EntryPointRole::Test);
1161 plugin_result
1162 .entry_point_roles
1163 .insert("support-plugin".to_string(), EntryPointRole::Support);
1164
1165 let entries = discover_plugin_entry_point_sets(&plugin_result, &config, &files);
1166
1167 assert_eq!(entries.runtime.len(), 1, "expected one runtime entry");
1168 assert!(
1169 entries.runtime[0].path.ends_with("src/runtime.ts"),
1170 "runtime entry should stay runtime-only"
1171 );
1172 assert_eq!(entries.test.len(), 1, "expected one test entry");
1173 assert!(
1174 entries.test[0].path.ends_with("tests/app.test.ts"),
1175 "test entry should stay test-only"
1176 );
1177 assert_eq!(
1178 entries.all.len(),
1179 3,
1180 "support entries should stay in all entries"
1181 );
1182 assert!(
1183 entries
1184 .all
1185 .iter()
1186 .any(|entry| entry.path.ends_with("src/setup.ts")),
1187 "support entries should remain in the overall entry-point set"
1188 );
1189 assert!(
1190 !entries
1191 .runtime
1192 .iter()
1193 .any(|entry| entry.path.ends_with("src/setup.ts")),
1194 "support entries should not bleed into runtime reachability"
1195 );
1196 assert!(
1197 !entries
1198 .test
1199 .iter()
1200 .any(|entry| entry.path.ends_with("src/setup.ts")),
1201 "support entries should not bleed into test reachability"
1202 );
1203 }
1204
1205 #[test]
1206 fn plugin_entry_point_rules_respect_exclusions() {
1207 let dir = tempfile::tempdir().expect("create temp dir");
1208 let root = dir.path();
1209 std::fs::create_dir_all(root.join("app/pages")).unwrap();
1210 std::fs::write(
1211 root.join("app/pages/index.tsx"),
1212 "export default function Page() { return null; }",
1213 )
1214 .unwrap();
1215 std::fs::write(
1216 root.join("app/pages/-helper.ts"),
1217 "export const helper = 1;",
1218 )
1219 .unwrap();
1220
1221 let config = FallowConfig {
1222 schema: None,
1223 extends: vec![],
1224 entry: vec![],
1225 ignore_patterns: vec![],
1226 framework: vec![],
1227 workspaces: None,
1228 ignore_dependencies: vec![],
1229 ignore_exports: vec![],
1230 ignore_catalog_references: vec![],
1231 ignore_dependency_overrides: vec![],
1232 ignore_exports_used_in_file: fallow_config::IgnoreExportsUsedInFileConfig::default(),
1233 used_class_members: vec![],
1234 duplicates: fallow_config::DuplicatesConfig::default(),
1235 health: fallow_config::HealthConfig::default(),
1236 rules: RulesConfig::default(),
1237 boundaries: fallow_config::BoundaryConfig::default(),
1238 production: false.into(),
1239 plugins: vec![],
1240 dynamically_loaded: vec![],
1241 overrides: vec![],
1242 regression: None,
1243 audit: fallow_config::AuditConfig::default(),
1244 codeowners: None,
1245 public_packages: vec![],
1246 flags: fallow_config::FlagsConfig::default(),
1247 resolve: fallow_config::ResolveConfig::default(),
1248 sealed: false,
1249 include_entry_exports: false,
1250 }
1251 .resolve(root.to_path_buf(), OutputFormat::Human, 4, true, true);
1252
1253 let files = vec![
1254 DiscoveredFile {
1255 id: FileId(0),
1256 path: root.join("app/pages/index.tsx"),
1257 size_bytes: 1,
1258 },
1259 DiscoveredFile {
1260 id: FileId(1),
1261 path: root.join("app/pages/-helper.ts"),
1262 size_bytes: 1,
1263 },
1264 ];
1265
1266 let mut plugin_result = crate::plugins::AggregatedPluginResult::default();
1267 plugin_result.entry_patterns.push((
1268 crate::plugins::PathRule::new("app/pages/**/*.{ts,tsx,js,jsx}")
1269 .with_excluded_globs(["app/pages/**/-*", "app/pages/**/-*/**/*"]),
1270 "tanstack-router".to_string(),
1271 ));
1272 plugin_result
1273 .entry_point_roles
1274 .insert("tanstack-router".to_string(), EntryPointRole::Runtime);
1275
1276 let entries = discover_plugin_entry_point_sets(&plugin_result, &config, &files);
1277 let entry_paths: Vec<_> = entries
1278 .all
1279 .iter()
1280 .map(|entry| {
1281 entry
1282 .path
1283 .strip_prefix(root)
1284 .unwrap()
1285 .to_string_lossy()
1286 .into_owned()
1287 })
1288 .collect();
1289
1290 assert!(entry_paths.contains(&"app/pages/index.tsx".to_string()));
1291 assert!(!entry_paths.contains(&"app/pages/-helper.ts".to_string()));
1292 }
1293
1294 mod resolve_entry_path_tests {
1296 use super::*;
1297
1298 #[test]
1299 fn resolves_existing_file() {
1300 let dir = tempfile::tempdir().expect("create temp dir");
1301 let src = dir.path().join("src");
1302 std::fs::create_dir_all(&src).unwrap();
1303 std::fs::write(src.join("index.ts"), "export const a = 1;").unwrap();
1304
1305 let canonical = dunce::canonicalize(dir.path()).unwrap();
1306 let result = resolve_entry_path(
1307 dir.path(),
1308 "src/index.ts",
1309 &canonical,
1310 EntryPointSource::PackageJsonMain,
1311 );
1312 assert!(result.is_some(), "should resolve an existing file");
1313 assert!(result.unwrap().path.ends_with("src/index.ts"));
1314 }
1315
1316 #[test]
1317 fn resolves_with_extension_fallback() {
1318 let dir = tempfile::tempdir().expect("create temp dir");
1319 let canonical = dunce::canonicalize(dir.path()).unwrap();
1321 let src = canonical.join("src");
1322 std::fs::create_dir_all(&src).unwrap();
1323 std::fs::write(src.join("index.ts"), "export const a = 1;").unwrap();
1324
1325 let result = resolve_entry_path(
1327 &canonical,
1328 "src/index",
1329 &canonical,
1330 EntryPointSource::PackageJsonMain,
1331 );
1332 assert!(
1333 result.is_some(),
1334 "should resolve via extension fallback when exact path doesn't exist"
1335 );
1336 let ep = result.unwrap();
1337 assert!(
1338 ep.path.to_string_lossy().contains("index.ts"),
1339 "should find index.ts via extension fallback"
1340 );
1341 }
1342
1343 #[test]
1344 fn returns_none_for_nonexistent_file() {
1345 let dir = tempfile::tempdir().expect("create temp dir");
1346 let canonical = dunce::canonicalize(dir.path()).unwrap();
1347 let result = resolve_entry_path(
1348 dir.path(),
1349 "does/not/exist.ts",
1350 &canonical,
1351 EntryPointSource::PackageJsonMain,
1352 );
1353 assert!(result.is_none(), "should return None for nonexistent files");
1354 }
1355
1356 #[test]
1357 fn maps_dist_output_to_src() {
1358 let dir = tempfile::tempdir().expect("create temp dir");
1359 let src = dir.path().join("src");
1360 std::fs::create_dir_all(&src).unwrap();
1361 std::fs::write(src.join("utils.ts"), "export const u = 1;").unwrap();
1362
1363 let dist = dir.path().join("dist");
1365 std::fs::create_dir_all(&dist).unwrap();
1366 std::fs::write(dist.join("utils.js"), "// compiled").unwrap();
1367
1368 let canonical = dunce::canonicalize(dir.path()).unwrap();
1369 let result = resolve_entry_path(
1370 dir.path(),
1371 "./dist/utils.js",
1372 &canonical,
1373 EntryPointSource::PackageJsonExports,
1374 );
1375 assert!(result.is_some(), "should resolve dist/ path to src/");
1376 let ep = result.unwrap();
1377 assert!(
1378 ep.path
1379 .to_string_lossy()
1380 .replace('\\', "/")
1381 .contains("src/utils.ts"),
1382 "should map ./dist/utils.js to src/utils.ts"
1383 );
1384 }
1385
1386 #[test]
1387 fn maps_build_output_to_src() {
1388 let dir = tempfile::tempdir().expect("create temp dir");
1389 let canonical = dunce::canonicalize(dir.path()).unwrap();
1391 let src = canonical.join("src");
1392 std::fs::create_dir_all(&src).unwrap();
1393 std::fs::write(src.join("index.tsx"), "export default () => {};").unwrap();
1394
1395 let result = resolve_entry_path(
1396 &canonical,
1397 "./build/index.js",
1398 &canonical,
1399 EntryPointSource::PackageJsonExports,
1400 );
1401 assert!(result.is_some(), "should map build/ output to src/");
1402 let ep = result.unwrap();
1403 assert!(
1404 ep.path
1405 .to_string_lossy()
1406 .replace('\\', "/")
1407 .contains("src/index.tsx"),
1408 "should map ./build/index.js to src/index.tsx"
1409 );
1410 }
1411
1412 #[test]
1413 fn preserves_entry_point_source() {
1414 let dir = tempfile::tempdir().expect("create temp dir");
1415 std::fs::write(dir.path().join("index.ts"), "export const a = 1;").unwrap();
1416
1417 let canonical = dunce::canonicalize(dir.path()).unwrap();
1418 let result = resolve_entry_path(
1419 dir.path(),
1420 "index.ts",
1421 &canonical,
1422 EntryPointSource::PackageJsonScript,
1423 );
1424 assert!(result.is_some());
1425 assert!(
1426 matches!(result.unwrap().source, EntryPointSource::PackageJsonScript),
1427 "should preserve the source kind"
1428 );
1429 }
1430 #[test]
1431 fn tracks_skipped_entries_without_logging_each_repeat() {
1432 let dir = tempfile::tempdir().expect("create temp dir");
1433 let canonical = dunce::canonicalize(dir.path()).unwrap();
1434 let mut skipped_entries = FxHashMap::default();
1435
1436 let result = resolve_entry_path_with_tracking(
1437 dir.path(),
1438 "../scripts/build.js",
1439 &canonical,
1440 EntryPointSource::PackageJsonScript,
1441 Some(&mut skipped_entries),
1442 );
1443
1444 assert!(result.is_none(), "unsafe entry should be skipped");
1445 assert_eq!(
1446 skipped_entries.get("../scripts/build.js"),
1447 Some(&1),
1448 "warning tracker should count the skipped path"
1449 );
1450 }
1451
1452 #[test]
1453 fn formats_skipped_entry_warning_with_counts() {
1454 let mut skipped_entries = FxHashMap::default();
1455 skipped_entries.insert("../../scripts/rm.mjs".to_owned(), 8);
1456 skipped_entries.insert("../utils/bar.js".to_owned(), 2);
1457
1458 let warning =
1459 format_skipped_entry_warning(&skipped_entries).expect("warning should be rendered");
1460
1461 assert_eq!(
1462 warning,
1463 "Skipped 10 package.json entry points outside project root or containing parent directory traversal: ../../scripts/rm.mjs (8x), ../utils/bar.js (2x)"
1464 );
1465 }
1466
1467 #[test]
1468 fn rejects_parent_dir_escape_for_exact_file() {
1469 let sandbox = tempfile::tempdir().expect("create sandbox");
1470 let root = sandbox.path().join("project");
1471 std::fs::create_dir_all(&root).unwrap();
1472 std::fs::write(
1473 sandbox.path().join("escape.ts"),
1474 "export const escape = true;",
1475 )
1476 .unwrap();
1477
1478 let canonical = dunce::canonicalize(&root).unwrap();
1479 let result = resolve_entry_path(
1480 &root,
1481 "../escape.ts",
1482 &canonical,
1483 EntryPointSource::PackageJsonMain,
1484 );
1485
1486 assert!(
1487 result.is_none(),
1488 "should reject exact paths that escape the root"
1489 );
1490 }
1491
1492 #[test]
1493 fn rejects_parent_dir_escape_via_extension_fallback() {
1494 let sandbox = tempfile::tempdir().expect("create sandbox");
1495 let root = sandbox.path().join("project");
1496 std::fs::create_dir_all(&root).unwrap();
1497 std::fs::write(
1498 sandbox.path().join("escape.ts"),
1499 "export const escape = true;",
1500 )
1501 .unwrap();
1502
1503 let canonical = dunce::canonicalize(&root).unwrap();
1504 let result = resolve_entry_path(
1505 &root,
1506 "../escape",
1507 &canonical,
1508 EntryPointSource::PackageJsonMain,
1509 );
1510
1511 assert!(
1512 result.is_none(),
1513 "should reject extension fallback paths that escape the root"
1514 );
1515 }
1516 }
1517
1518 mod output_to_source_tests {
1520 use super::*;
1521
1522 #[test]
1523 fn maps_dist_to_src_with_ts_extension() {
1524 let dir = tempfile::tempdir().expect("create temp dir");
1525 let src = dir.path().join("src");
1526 std::fs::create_dir_all(&src).unwrap();
1527 std::fs::write(src.join("utils.ts"), "export const u = 1;").unwrap();
1528
1529 let result = try_output_to_source_path(dir.path(), "./dist/utils.js");
1530 assert!(result.is_some());
1531 assert!(
1532 result
1533 .unwrap()
1534 .to_string_lossy()
1535 .replace('\\', "/")
1536 .contains("src/utils.ts")
1537 );
1538 }
1539
1540 #[test]
1541 fn returns_none_when_no_source_file_exists() {
1542 let dir = tempfile::tempdir().expect("create temp dir");
1543 let result = try_output_to_source_path(dir.path(), "./dist/missing.js");
1545 assert!(result.is_none());
1546 }
1547
1548 #[test]
1549 fn ignores_non_output_directories() {
1550 let dir = tempfile::tempdir().expect("create temp dir");
1551 let src = dir.path().join("src");
1552 std::fs::create_dir_all(&src).unwrap();
1553 std::fs::write(src.join("foo.ts"), "export const f = 1;").unwrap();
1554
1555 let result = try_output_to_source_path(dir.path(), "./lib/foo.js");
1557 assert!(result.is_none());
1558 }
1559
1560 #[test]
1561 fn maps_nested_output_path_preserving_prefix() {
1562 let dir = tempfile::tempdir().expect("create temp dir");
1563 let modules_src = dir.path().join("modules").join("src");
1564 std::fs::create_dir_all(&modules_src).unwrap();
1565 std::fs::write(modules_src.join("helper.ts"), "export const h = 1;").unwrap();
1566
1567 let result = try_output_to_source_path(dir.path(), "./modules/dist/helper.js");
1568 assert!(result.is_some());
1569 assert!(
1570 result
1571 .unwrap()
1572 .to_string_lossy()
1573 .replace('\\', "/")
1574 .contains("modules/src/helper.ts")
1575 );
1576 }
1577 }
1578
1579 mod source_index_fallback_tests {
1581 use super::*;
1582
1583 #[test]
1584 fn detects_dist_entry_in_output_dir() {
1585 assert!(is_entry_in_output_dir("./dist/esm2022/index.js"));
1586 assert!(is_entry_in_output_dir("dist/index.js"));
1587 assert!(is_entry_in_output_dir("./build/index.js"));
1588 assert!(is_entry_in_output_dir("./out/main.js"));
1589 assert!(is_entry_in_output_dir("./esm/index.js"));
1590 assert!(is_entry_in_output_dir("./cjs/index.js"));
1591 }
1592
1593 #[test]
1594 fn rejects_non_output_entry_paths() {
1595 assert!(!is_entry_in_output_dir("./src/index.ts"));
1596 assert!(!is_entry_in_output_dir("src/main.ts"));
1597 assert!(!is_entry_in_output_dir("./index.js"));
1598 assert!(!is_entry_in_output_dir(""));
1599 }
1600
1601 #[test]
1602 fn rejects_substring_match_for_output_dir() {
1603 assert!(!is_entry_in_output_dir("./distro/index.js"));
1605 assert!(!is_entry_in_output_dir("./build-scripts/run.js"));
1606 }
1607
1608 #[test]
1609 fn finds_src_index_ts() {
1610 let dir = tempfile::tempdir().expect("create temp dir");
1611 let src = dir.path().join("src");
1612 std::fs::create_dir_all(&src).unwrap();
1613 let index_path = src.join("index.ts");
1614 std::fs::write(&index_path, "export const a = 1;").unwrap();
1615
1616 let result = try_source_index_fallback(dir.path());
1617 assert_eq!(result.as_deref(), Some(index_path.as_path()));
1618 }
1619
1620 #[test]
1621 fn finds_src_index_tsx_when_ts_missing() {
1622 let dir = tempfile::tempdir().expect("create temp dir");
1623 let src = dir.path().join("src");
1624 std::fs::create_dir_all(&src).unwrap();
1625 let index_path = src.join("index.tsx");
1626 std::fs::write(&index_path, "export default 1;").unwrap();
1627
1628 let result = try_source_index_fallback(dir.path());
1629 assert_eq!(result.as_deref(), Some(index_path.as_path()));
1630 }
1631
1632 #[test]
1633 fn prefers_src_index_over_root_index() {
1634 let dir = tempfile::tempdir().expect("create temp dir");
1637 let src = dir.path().join("src");
1638 std::fs::create_dir_all(&src).unwrap();
1639 let src_index = src.join("index.ts");
1640 std::fs::write(&src_index, "export const a = 1;").unwrap();
1641 let root_index = dir.path().join("index.ts");
1642 std::fs::write(&root_index, "export const b = 2;").unwrap();
1643
1644 let result = try_source_index_fallback(dir.path());
1645 assert_eq!(result.as_deref(), Some(src_index.as_path()));
1646 }
1647
1648 #[test]
1649 fn falls_back_to_src_main() {
1650 let dir = tempfile::tempdir().expect("create temp dir");
1651 let src = dir.path().join("src");
1652 std::fs::create_dir_all(&src).unwrap();
1653 let main_path = src.join("main.ts");
1654 std::fs::write(&main_path, "export const a = 1;").unwrap();
1655
1656 let result = try_source_index_fallback(dir.path());
1657 assert_eq!(result.as_deref(), Some(main_path.as_path()));
1658 }
1659
1660 #[test]
1661 fn falls_back_to_root_index_when_no_src() {
1662 let dir = tempfile::tempdir().expect("create temp dir");
1663 let index_path = dir.path().join("index.js");
1664 std::fs::write(&index_path, "module.exports = {};").unwrap();
1665
1666 let result = try_source_index_fallback(dir.path());
1667 assert_eq!(result.as_deref(), Some(index_path.as_path()));
1668 }
1669
1670 #[test]
1671 fn returns_none_when_nothing_matches() {
1672 let dir = tempfile::tempdir().expect("create temp dir");
1673 let result = try_source_index_fallback(dir.path());
1674 assert!(result.is_none());
1675 }
1676
1677 #[test]
1678 fn resolve_entry_path_falls_back_to_src_index_for_dist_entry() {
1679 let dir = tempfile::tempdir().expect("create temp dir");
1680 let canonical = dunce::canonicalize(dir.path()).unwrap();
1681
1682 let dist_dir = canonical.join("dist").join("esm2022");
1687 std::fs::create_dir_all(&dist_dir).unwrap();
1688 std::fs::write(dist_dir.join("index.js"), "export const x = 1;").unwrap();
1689
1690 let src = canonical.join("src");
1691 std::fs::create_dir_all(&src).unwrap();
1692 let src_index = src.join("index.ts");
1693 std::fs::write(&src_index, "export const x = 1;").unwrap();
1694
1695 let result = resolve_entry_path(
1696 &canonical,
1697 "./dist/esm2022/index.js",
1698 &canonical,
1699 EntryPointSource::PackageJsonMain,
1700 );
1701 assert!(result.is_some());
1702 let entry = result.unwrap();
1703 assert_eq!(entry.path, src_index);
1704 }
1705
1706 #[test]
1707 fn resolve_entry_path_uses_direct_src_mirror_when_available() {
1708 let dir = tempfile::tempdir().expect("create temp dir");
1711 let canonical = dunce::canonicalize(dir.path()).unwrap();
1712
1713 let src_mirror = canonical.join("src").join("esm2022");
1714 std::fs::create_dir_all(&src_mirror).unwrap();
1715 let mirror_index = src_mirror.join("index.ts");
1716 std::fs::write(&mirror_index, "export const x = 1;").unwrap();
1717
1718 let src_index = canonical.join("src").join("index.ts");
1720 std::fs::write(&src_index, "export const y = 2;").unwrap();
1721
1722 let result = resolve_entry_path(
1723 &canonical,
1724 "./dist/esm2022/index.js",
1725 &canonical,
1726 EntryPointSource::PackageJsonMain,
1727 );
1728 assert_eq!(result.map(|e| e.path), Some(mirror_index));
1729 }
1730 }
1731
1732 mod default_fallback_tests {
1734 use super::*;
1735
1736 #[test]
1737 fn finds_src_index_ts_as_fallback() {
1738 let dir = tempfile::tempdir().expect("create temp dir");
1739 let src = dir.path().join("src");
1740 std::fs::create_dir_all(&src).unwrap();
1741 let index_path = src.join("index.ts");
1742 std::fs::write(&index_path, "export const a = 1;").unwrap();
1743
1744 let files = vec![DiscoveredFile {
1745 id: FileId(0),
1746 path: index_path.clone(),
1747 size_bytes: 20,
1748 }];
1749
1750 let entries = apply_default_fallback(&files, dir.path(), None);
1751 assert_eq!(entries.len(), 1);
1752 assert_eq!(entries[0].path, index_path);
1753 assert!(matches!(entries[0].source, EntryPointSource::DefaultIndex));
1754 }
1755
1756 #[test]
1757 fn finds_root_index_js_as_fallback() {
1758 let dir = tempfile::tempdir().expect("create temp dir");
1759 let index_path = dir.path().join("index.js");
1760 std::fs::write(&index_path, "module.exports = {};").unwrap();
1761
1762 let files = vec![DiscoveredFile {
1763 id: FileId(0),
1764 path: index_path.clone(),
1765 size_bytes: 21,
1766 }];
1767
1768 let entries = apply_default_fallback(&files, dir.path(), None);
1769 assert_eq!(entries.len(), 1);
1770 assert_eq!(entries[0].path, index_path);
1771 }
1772
1773 #[test]
1774 fn returns_empty_when_no_index_file() {
1775 let dir = tempfile::tempdir().expect("create temp dir");
1776 let other_path = dir.path().join("src").join("utils.ts");
1777
1778 let files = vec![DiscoveredFile {
1779 id: FileId(0),
1780 path: other_path,
1781 size_bytes: 10,
1782 }];
1783
1784 let entries = apply_default_fallback(&files, dir.path(), None);
1785 assert!(
1786 entries.is_empty(),
1787 "non-index files should not match default fallback"
1788 );
1789 }
1790
1791 #[test]
1792 fn workspace_filter_restricts_scope() {
1793 let dir = tempfile::tempdir().expect("create temp dir");
1794 let ws_a = dir.path().join("packages").join("a").join("src");
1795 std::fs::create_dir_all(&ws_a).unwrap();
1796 let ws_b = dir.path().join("packages").join("b").join("src");
1797 std::fs::create_dir_all(&ws_b).unwrap();
1798
1799 let index_a = ws_a.join("index.ts");
1800 let index_b = ws_b.join("index.ts");
1801
1802 let files = vec![
1803 DiscoveredFile {
1804 id: FileId(0),
1805 path: index_a.clone(),
1806 size_bytes: 10,
1807 },
1808 DiscoveredFile {
1809 id: FileId(1),
1810 path: index_b,
1811 size_bytes: 10,
1812 },
1813 ];
1814
1815 let ws_root = dir.path().join("packages").join("a");
1817 let entries = apply_default_fallback(&files, &ws_root, Some(&ws_root));
1818 assert_eq!(entries.len(), 1);
1819 assert_eq!(entries[0].path, index_a);
1820 }
1821 }
1822
1823 mod wildcard_entry_tests {
1825 use super::*;
1826
1827 #[test]
1828 fn expands_wildcard_css_entries() {
1829 let dir = tempfile::tempdir().expect("create temp dir");
1832 let themes = dir.path().join("src").join("themes");
1833 std::fs::create_dir_all(&themes).unwrap();
1834 std::fs::write(themes.join("dark.css"), ":root { --bg: #000; }").unwrap();
1835 std::fs::write(themes.join("light.css"), ":root { --bg: #fff; }").unwrap();
1836
1837 let canonical = dunce::canonicalize(dir.path()).unwrap();
1838 let mut entries = Vec::new();
1839 expand_wildcard_entries(dir.path(), "./src/themes/*.css", &canonical, &mut entries);
1840
1841 assert_eq!(entries.len(), 2, "should expand wildcard to 2 CSS files");
1842 let paths: Vec<String> = entries
1843 .iter()
1844 .map(|ep| ep.path.file_name().unwrap().to_string_lossy().to_string())
1845 .collect();
1846 assert!(paths.contains(&"dark.css".to_string()));
1847 assert!(paths.contains(&"light.css".to_string()));
1848 assert!(
1849 entries
1850 .iter()
1851 .all(|ep| matches!(ep.source, EntryPointSource::PackageJsonExports))
1852 );
1853 }
1854
1855 #[test]
1856 fn wildcard_does_not_match_nonexistent_files() {
1857 let dir = tempfile::tempdir().expect("create temp dir");
1858 std::fs::create_dir_all(dir.path().join("src/themes")).unwrap();
1860
1861 let canonical = dunce::canonicalize(dir.path()).unwrap();
1862 let mut entries = Vec::new();
1863 expand_wildcard_entries(dir.path(), "./src/themes/*.css", &canonical, &mut entries);
1864
1865 assert!(
1866 entries.is_empty(),
1867 "should return empty when no files match the wildcard"
1868 );
1869 }
1870
1871 #[test]
1872 fn wildcard_only_matches_specified_extension() {
1873 let dir = tempfile::tempdir().expect("create temp dir");
1875 let themes = dir.path().join("src").join("themes");
1876 std::fs::create_dir_all(&themes).unwrap();
1877 std::fs::write(themes.join("dark.css"), ":root {}").unwrap();
1878 std::fs::write(themes.join("index.ts"), "export {};").unwrap();
1879
1880 let canonical = dunce::canonicalize(dir.path()).unwrap();
1881 let mut entries = Vec::new();
1882 expand_wildcard_entries(dir.path(), "./src/themes/*.css", &canonical, &mut entries);
1883
1884 assert_eq!(entries.len(), 1, "should only match CSS files");
1885 assert!(
1886 entries[0]
1887 .path
1888 .file_name()
1889 .unwrap()
1890 .to_string_lossy()
1891 .ends_with(".css")
1892 );
1893 }
1894 }
1895}