1#![cfg_attr(not(test), deny(clippy::disallowed_methods))]
13#![cfg_attr(
14 test,
15 allow(
16 clippy::unwrap_used,
17 clippy::expect_used,
18 reason = "tests use unwrap and expect to keep fixture setup concise"
19 )
20)]
21
22pub mod analyze;
23pub mod cache;
24pub mod discover;
25pub(crate) mod errors;
26mod external_style_usage;
27pub mod extract;
28pub mod git_env;
29mod package_assets;
30pub mod plugins;
31pub(crate) mod progress;
32pub mod results;
33pub(crate) mod scripts;
34#[doc(hidden)]
37pub use scripts::parse_script;
38pub mod suppress;
39
40pub use fallow_graph::cache as graph_cache;
41pub use fallow_graph::graph;
42pub use fallow_graph::project;
43pub use fallow_graph::resolve;
44
45use std::path::{Path, PathBuf};
46use std::time::Instant;
47
48use errors::FallowError;
49use fallow_config::{
50 EntryPointRole, PackageJson, ResolvedConfig, discover_workspaces_with_diagnostics,
51 find_undeclared_workspaces_with_ignores,
52};
53use fallow_types::cache_rejection::CacheRejection;
54use fallow_types::trace::{EntryPointSpans, PipelineCounters, PipelineTimings};
55use rayon::prelude::*;
56use results::AnalysisResults;
57use rustc_hash::FxHashSet;
58
59const UNDECLARED_WORKSPACE_WARNING_PREVIEW: usize = 5;
60type LoadedWorkspacePackage = (fallow_config::WorkspaceInfo, PackageJson);
61
62fn record_graph_package_usage(
63 graph: &mut graph::ModuleGraph,
64 package_name: &str,
65 file_id: discover::FileId,
66 is_type_only: bool,
67) {
68 graph
69 .package_usage
70 .entry(package_name.to_owned())
71 .or_default()
72 .push(file_id);
73 if is_type_only {
74 graph
75 .type_only_package_usage
76 .entry(package_name.to_owned())
77 .or_default()
78 .push(file_id);
79 }
80}
81
82fn workspace_package_name<'a>(
83 source: &str,
84 workspace_names: &FxHashSet<&'a str>,
85) -> Option<&'a str> {
86 if !resolve::is_bare_specifier(source) {
87 return None;
88 }
89 let package_name = resolve::extract_package_name(source);
90 workspace_names.get(package_name.as_str()).copied()
91}
92
93fn credit_workspace_package_usage(
94 graph: &mut graph::ModuleGraph,
95 resolved: &[resolve::ResolvedModule],
96 workspaces: &[fallow_config::WorkspaceInfo],
97) {
98 if workspaces.is_empty() {
99 return;
100 }
101
102 let workspace_names: FxHashSet<&str> = workspaces.iter().map(|ws| ws.name.as_str()).collect();
103 for module in resolved {
104 for import in module.all_resolved_imports() {
105 if matches!(
106 import.target,
107 resolve::ResolveResult::InternalModule(_)
108 | resolve::ResolveResult::CommonJsInternalModule(_)
109 ) && let Some(package_name) =
110 workspace_package_name(&import.info.source, &workspace_names)
111 {
112 record_graph_package_usage(
113 graph,
114 package_name,
115 module.file_id,
116 import.info.is_type_only,
117 );
118 }
119 }
120
121 for re_export in &module.re_exports {
122 if matches!(re_export.target, resolve::ResolveResult::InternalModule(_))
123 && let Some(package_name) =
124 workspace_package_name(&re_export.info.source, &workspace_names)
125 {
126 record_graph_package_usage(
127 graph,
128 package_name,
129 module.file_id,
130 re_export.info.is_type_only,
131 );
132 }
133 }
134 }
135}
136
137fn credit_package_path_references(graph: &mut graph::ModuleGraph, modules: &[extract::ModuleInfo]) {
138 for module in modules {
139 for package_name in &module.package_path_references {
140 record_graph_package_usage(graph, package_name, module.file_id, false);
141 }
142 }
143}
144
145#[doc(hidden)]
147pub struct AnalysisOutput {
148 pub results: AnalysisResults,
149 pub timings: Option<PipelineTimings>,
150 pub graph: Option<graph::ModuleGraph>,
151 pub modules: Option<Vec<extract::ModuleInfo>>,
155 pub files: Option<Vec<discover::DiscoveredFile>>,
157 pub script_used_packages: rustc_hash::FxHashSet<String>,
162 pub trace_provenance: fallow_types::trace::TraceProvenance,
165 pub file_hashes: rustc_hash::FxHashMap<std::path::PathBuf, u64>,
174}
175
176#[derive(Debug, Clone, Copy)]
179#[doc(hidden)]
180pub struct AnalysisParseMetrics {
181 parse_ms: f64,
182 cache_ms: f64,
183 cache_hits: usize,
184 cache_misses: usize,
185 parse_cpu_ms: f64,
186 cache_rejection: Option<CacheRejection>,
187}
188
189fn update_cache(
199 store: &mut cache::CacheStore,
200 modules: &[extract::ModuleInfo],
201 files: &[discover::DiscoveredFile],
202 need_complexity: bool,
203) -> bool {
204 let mut dirty = false;
205 for module in modules {
206 if let Some(file) = files.get(module.file_id.0 as usize) {
207 let fingerprint = file_fingerprint(&file.path);
208 if let Some(cached) = store.get_by_path_only(&file.path)
209 && cached.content_hash == module.content_hash
210 {
211 let stale_metadata = cached.source_fingerprint() != fingerprint;
212 let adds_complexity = need_complexity && !cached.complexity_extracted;
213 if stale_metadata || adds_complexity {
214 let preserved_last_access = cached.last_access_secs;
215 let preserved_complexity = (!need_complexity && cached.complexity_extracted)
216 .then(|| cached.complexity.clone());
217 let mut refreshed =
218 cache::module_to_cached(module, fingerprint, need_complexity);
219 refreshed.last_access_secs = preserved_last_access;
220 if let Some(complexity) = preserved_complexity {
221 refreshed.complexity = complexity;
222 refreshed.complexity_extracted = true;
223 }
224 store.insert(&file.path, refreshed);
225 dirty = true;
226 }
227 continue;
228 }
229 store.insert(
230 &file.path,
231 cache::module_to_cached(module, fingerprint, need_complexity),
232 );
233 dirty = true;
234 }
235 }
236 let removed_stale_paths = store.retain_paths(files);
237 dirty || removed_stale_paths
238}
239
240#[must_use]
248fn resolve_cache_max_size_bytes(config: &ResolvedConfig) -> usize {
249 config
250 .cache_max_size_mb
251 .map_or(cache::DEFAULT_CACHE_MAX_SIZE, |mb| {
252 (mb as usize).saturating_mul(1024 * 1024)
253 })
254}
255
256fn file_fingerprint(path: &std::path::Path) -> fallow_types::source_fingerprint::SourceFingerprint {
258 std::fs::metadata(path).map_or(
259 fallow_types::source_fingerprint::SourceFingerprint::new(0, 0),
260 |metadata| fallow_types::source_fingerprint::SourceFingerprint::from_metadata(&metadata),
261 )
262}
263
264fn format_undeclared_workspace_warning(
265 root: &Path,
266 undeclared: &[fallow_config::WorkspaceDiagnostic],
267) -> Option<String> {
268 if undeclared.is_empty() {
269 return None;
270 }
271
272 let preview = undeclared
273 .iter()
274 .take(UNDECLARED_WORKSPACE_WARNING_PREVIEW)
275 .map(|diag| {
276 diag.path
277 .strip_prefix(root)
278 .unwrap_or(&diag.path)
279 .display()
280 .to_string()
281 .replace('\\', "/")
282 })
283 .collect::<Vec<_>>();
284 let remaining = undeclared
285 .len()
286 .saturating_sub(UNDECLARED_WORKSPACE_WARNING_PREVIEW);
287 let tail = if remaining > 0 {
288 format!(" (and {remaining} more)")
289 } else {
290 String::new()
291 };
292 let noun = if undeclared.len() == 1 {
293 "directory with package.json is"
294 } else {
295 "directories with package.json are"
296 };
297 let guidance = if undeclared.len() == 1 {
298 "Add that path to package.json workspaces or pnpm-workspace.yaml if it should be analyzed as a workspace."
299 } else {
300 "Add those paths to package.json workspaces or pnpm-workspace.yaml if they should be analyzed as workspaces."
301 };
302
303 Some(format!(
304 "{} {} not declared as {}: {}{}. {}",
305 undeclared.len(),
306 noun,
307 if undeclared.len() == 1 {
308 "a workspace"
309 } else {
310 "workspaces"
311 },
312 preview.join(", "),
313 tail,
314 guidance
315 ))
316}
317
318fn warn_undeclared_workspaces(
319 root: &Path,
320 workspaces_vec: &[fallow_config::WorkspaceInfo],
321 ignore_patterns: &fallow_config::IgnorePatternSet,
322 quiet: bool,
323) {
324 let undeclared = find_undeclared_workspaces_with_ignores(root, workspaces_vec, ignore_patterns);
325 if undeclared.is_empty() {
326 return;
327 }
328
329 let existing = fallow_config::workspace_diagnostics_for(root);
330 let already_flagged: rustc_hash::FxHashSet<PathBuf> = existing
331 .iter()
332 .map(|d| dunce::canonicalize(&d.path).unwrap_or_else(|_| d.path.clone()))
333 .collect();
334 let undeclared: Vec<_> = undeclared
335 .into_iter()
336 .filter(|diag| {
337 let canonical = dunce::canonicalize(&diag.path).unwrap_or_else(|_| diag.path.clone());
338 !already_flagged.contains(&canonical)
339 })
340 .collect();
341 if undeclared.is_empty() {
342 return;
343 }
344
345 fallow_config::append_workspace_diagnostics(root, undeclared.clone());
346
347 if !quiet && let Some(message) = format_undeclared_workspace_warning(root, &undeclared) {
348 tracing::warn!("{message}");
349 }
350}
351
352#[doc(hidden)]
358#[deprecated(
359 since = "2.76.0",
360 note = "fallow_core is internal; use fallow_api::run_dead_code for typed output; serialize with fallow_api::serialize_dead_code_programmatic_json for JSON output. See docs/fallow-core-migration.md."
361)]
362pub fn analyze(config: &ResolvedConfig) -> Result<AnalysisResults, FallowError> {
363 let output = analyze_full(config, false, false, false, false)?;
364 Ok(output.results)
365}
366
367#[doc(hidden)]
373#[deprecated(
374 since = "2.76.0",
375 note = "fallow_core is internal; use fallow_api::run_dead_code for public typed output. NOTE: export-usage collection is not exposed in the programmatic surface today. See docs/fallow-core-migration.md."
376)]
377pub fn analyze_with_usages(config: &ResolvedConfig) -> Result<AnalysisResults, FallowError> {
378 let output = analyze_full(config, false, true, false, false)?;
379 Ok(output.results)
380}
381
382#[doc(hidden)]
388#[deprecated(
389 since = "2.76.0",
390 note = "fallow_core is internal; use fallow_api::run_dead_code for public typed output. NOTE: trace timings are not exposed in the programmatic surface today; use `fallow dead-code --performance` for CLI-side timings. See docs/fallow-core-migration.md."
391)]
392pub fn analyze_with_trace(config: &ResolvedConfig) -> Result<AnalysisOutput, FallowError> {
393 analyze_full(config, true, false, false, false)
394}
395
396#[doc(hidden)]
406#[deprecated(
407 since = "2.76.0",
408 note = "fallow_core is internal; use fallow_api::run_dead_code for public typed output. NOTE: combined-mode module retention is not exposed in the programmatic surface today. See docs/fallow-core-migration.md."
409)]
410pub fn analyze_retaining_modules(
411 config: &ResolvedConfig,
412 need_complexity: bool,
413 retain_graph: bool,
414) -> Result<AnalysisOutput, FallowError> {
415 analyze_full(config, retain_graph, false, need_complexity, true)
416}
417
418fn new_analysis_progress(config: &ResolvedConfig) -> progress::AnalysisProgress {
419 let show_progress = !config.quiet
420 && std::io::IsTerminal::is_terminal(&std::io::stderr())
421 && matches!(
422 config.output,
423 fallow_config::OutputFormat::Human
424 | fallow_config::OutputFormat::Compact
425 | fallow_config::OutputFormat::Markdown
426 );
427 progress::AnalysisProgress::new(show_progress)
428}
429
430fn discover_analysis_workspaces(
431 config: &ResolvedConfig,
432) -> Result<(Vec<fallow_config::WorkspaceInfo>, f64), FallowError> {
433 let t = Instant::now();
434 let (workspaces, diagnostics) =
435 discover_workspaces_with_diagnostics(&config.root, &config.ignore_patterns)
436 .map_err(|error| FallowError::config(error.to_string()))?;
437 fallow_config::stash_workspace_diagnostics(&config.root, diagnostics);
438 let workspaces_ms = t.elapsed().as_secs_f64() * 1000.0;
439 if !workspaces.is_empty() {
440 tracing::info!(count = workspaces.len(), "workspaces discovered");
441 }
442
443 warn_undeclared_workspaces(
444 &config.root,
445 &workspaces,
446 &config.ignore_patterns,
447 config.quiet,
448 );
449
450 Ok((workspaces, workspaces_ms))
451}
452
453struct AnalysisSetup {
457 progress: progress::AnalysisProgress,
458 project: project::ProjectState,
459 root_pkg: Option<PackageJson>,
460 config_candidates: Vec<std::path::PathBuf>,
465 discover_ms: f64,
466 workspaces_ms: f64,
467}
468
469#[derive(Debug, Clone)]
475#[doc(hidden)]
476pub struct AnalysisDiscovery {
477 files: Vec<discover::DiscoveredFile>,
478 workspaces: Vec<fallow_config::WorkspaceInfo>,
479 root_pkg: Option<PackageJson>,
480 config_candidates: Vec<std::path::PathBuf>,
481 discover_ms: f64,
482 workspaces_ms: f64,
483}
484
485impl AnalysisDiscovery {
486 #[must_use]
488 pub fn from_parts(
489 files: Vec<discover::DiscoveredFile>,
490 workspaces: Vec<fallow_config::WorkspaceInfo>,
491 root_pkg: Option<PackageJson>,
492 config_candidates: Vec<std::path::PathBuf>,
493 discover_ms: f64,
494 workspaces_ms: f64,
495 ) -> Self {
496 Self {
497 files,
498 workspaces,
499 root_pkg,
500 config_candidates,
501 discover_ms,
502 workspaces_ms,
503 }
504 }
505
506 #[must_use]
508 fn files(&self) -> &[discover::DiscoveredFile] {
509 &self.files
510 }
511
512 #[must_use]
514 pub fn workspaces(&self) -> &[fallow_config::WorkspaceInfo] {
515 &self.workspaces
516 }
517
518 #[must_use]
520 pub fn into_files(self) -> Vec<discover::DiscoveredFile> {
521 self.files
522 }
523}
524
525pub(crate) struct AnalysisSession<'a> {
530 config: &'a ResolvedConfig,
531 pipeline_start: Instant,
532 progress: progress::AnalysisProgress,
533 project: project::ProjectState,
534 root_pkg: Option<PackageJson>,
535 config_candidates: Vec<std::path::PathBuf>,
536 discover_ms: f64,
537 workspaces_ms: f64,
538}
539
540impl<'a> AnalysisSession<'a> {
541 fn new(config: &'a ResolvedConfig) -> Result<Self, FallowError> {
542 let pipeline_start = Instant::now();
543 let AnalysisSetup {
544 progress,
545 project,
546 root_pkg,
547 config_candidates,
548 discover_ms,
549 workspaces_ms,
550 } = run_analysis_setup(config)?;
551
552 Ok(Self {
553 config,
554 pipeline_start,
555 progress,
556 project,
557 root_pkg,
558 config_candidates,
559 discover_ms,
560 workspaces_ms,
561 })
562 }
563
564 fn files(&self) -> &[discover::DiscoveredFile] {
565 self.project.files()
566 }
567
568 fn workspaces(&self) -> &[fallow_config::WorkspaceInfo] {
569 self.project.workspaces()
570 }
571
572 fn load_workspace_packages(&self) -> Vec<LoadedWorkspacePackage> {
573 load_workspace_packages(self.workspaces())
574 }
575
576 fn run_plugins_and_scripts(
577 &self,
578 workspace_pkgs: &[LoadedWorkspacePackage],
579 ) -> Result<(plugins::AggregatedPluginResult, f64, f64), FallowError> {
580 run_plugins_and_scripts(&PluginScriptInput {
581 config: self.config,
582 progress: &self.progress,
583 files: self.files(),
584 workspaces: self.workspaces(),
585 root_pkg: self.root_pkg.as_ref(),
586 workspace_pkgs,
587 config_candidates: &self.config_candidates,
588 })
589 }
590
591 fn prelude_timings(&self, plugins_ms: f64, scripts_ms: f64) -> PreludeTimings {
592 PreludeTimings {
593 discover_ms: self.discover_ms,
594 workspaces_ms: self.workspaces_ms,
595 plugins_ms,
596 scripts_ms,
597 }
598 }
599
600 fn parse_modules(&self, need_complexity: bool) -> AnalysisParseOutput {
601 let t = Instant::now();
602 self.progress
603 .set_stage(&format!("parsing {} files...", self.files().len()));
604 parse_analysis_modules(self.config, self.files(), need_complexity, t)
605 }
606
607 fn run_owned_core(
608 &self,
609 workspace_pkgs: &[LoadedWorkspacePackage],
610 plugin_result: &plugins::AggregatedPluginResult,
611 mut modules: Vec<extract::ModuleInfo>,
612 collect_usages: bool,
613 ) -> OwnedAnalysisCore {
614 let shared = AnalysisCoreSharedInput {
615 config: self.config,
616 progress: &self.progress,
617 files: self.files(),
618 workspaces: self.workspaces(),
619 root_pkg: self.root_pkg.as_ref(),
620 workspace_pkgs,
621 plugin_result,
622 };
623
624 let entry_points = discover_analysis_entry_points(&shared);
625 let mut graph_cache_rejection = None;
626 let (resolved, graph) =
627 match try_load_analysis_graph_cache(&shared, &entry_points, &modules) {
628 Ok(hit) => (
629 TimedResolvedModules {
630 project: hit.project,
631 elapsed_ms: 0.0,
632 },
633 TimedGraph {
634 graph: hit.graph,
635 elapsed_ms: hit.elapsed_ms,
636 },
637 ),
638 Err(rejection) => {
639 graph_cache_rejection = rejection;
640 let resolved = resolve_analysis_imports_timed(&shared, &modules);
641 let graph = build_analysis_graph_timed(
642 &shared,
643 &resolved.project,
644 &entry_points,
645 &modules,
646 );
647 (resolved, graph)
648 }
649 };
650 release_resolution_payloads(&mut modules);
651 let analysis = analyze_dead_code_timed(
652 &shared,
653 &graph.graph,
654 &resolved.project.modules,
655 &modules,
656 collect_usages,
657 entry_points.summary,
658 );
659
660 OwnedAnalysisCore {
661 result: analysis.result,
662 graph: graph.graph,
663 modules,
664 entry_point_count: entry_points.count,
665 entry_points_ms: entry_points.elapsed_ms,
666 entry_point_spans: entry_points.spans,
667 resolve_ms: resolved.elapsed_ms,
668 graph_ms: graph.elapsed_ms,
669 analyze_ms: analysis.elapsed_ms,
670 graph_cache_rejection,
671 resolve_work: resolved.project.work,
672 }
673 }
674
675 fn run_full(
676 self,
677 retain: bool,
678 collect_usages: bool,
679 need_complexity: bool,
680 retain_modules: bool,
681 ) -> Result<AnalysisOutput, FallowError> {
682 let workspace_pkgs = self.load_workspace_packages();
683 let (plugin_result, plugins_ms, scripts_ms) =
684 self.run_plugins_and_scripts(&workspace_pkgs)?;
685
686 let AnalysisParseOutput { modules, metrics } = self.parse_modules(need_complexity);
687 let core = self.run_owned_core(&workspace_pkgs, &plugin_result, modules, collect_usages);
688 self.progress.finish();
689
690 let profile = full_analysis_pipeline_profile(
691 &self.prelude_timings(plugins_ms, scripts_ms),
692 self.pipeline_start,
693 self.files(),
694 self.workspaces(),
695 &core,
696 &metrics,
697 );
698 trace_pipeline_profile(&profile);
699
700 let trace_provenance = plugins::federation_trace_provenance(
701 &self.config.root,
702 self.files(),
703 &plugin_result.federation_sources,
704 &core.modules,
705 );
706 let mut output = assemble_full_output(
707 core,
708 plugin_result,
709 &profile,
710 self.files(),
711 retain,
712 retain_modules,
713 );
714 output.trace_provenance = trace_provenance;
715 Ok(output)
716 }
717}
718
719fn run_analysis_setup(config: &ResolvedConfig) -> Result<AnalysisSetup, FallowError> {
722 let progress = new_analysis_progress(config);
723
724 let (workspaces_vec, workspaces_ms) = discover_analysis_workspaces(config)?;
725 let root_pkg = fallow_config::load_dir_package_json(&config.root);
726 let discovery_hidden_dir_scopes =
727 discover::collect_hidden_dir_scopes(config, root_pkg.as_ref(), &workspaces_vec);
728
729 let t = Instant::now();
730 progress.set_stage("discovering files...");
731 let (discovered_files, config_candidates) =
732 discover::discover_files_and_config_candidates(config, &discovery_hidden_dir_scopes);
733 let discover_ms = t.elapsed().as_secs_f64() * 1000.0;
734
735 let project = project::ProjectState::new(discovered_files, workspaces_vec);
736
737 Ok(AnalysisSetup {
738 progress,
739 project,
740 root_pkg,
741 config_candidates,
742 discover_ms,
743 workspaces_ms,
744 })
745}
746
747struct PluginScriptInput<'a> {
749 config: &'a ResolvedConfig,
750 progress: &'a progress::AnalysisProgress,
751 files: &'a [discover::DiscoveredFile],
752 workspaces: &'a [fallow_config::WorkspaceInfo],
753 root_pkg: Option<&'a PackageJson>,
754 workspace_pkgs: &'a [LoadedWorkspacePackage],
755 config_candidates: &'a [std::path::PathBuf],
756}
757
758fn run_plugins_and_scripts(
761 input: &PluginScriptInput<'_>,
762) -> Result<(plugins::AggregatedPluginResult, f64, f64), FallowError> {
763 let t = Instant::now();
764 input.progress.set_stage("detecting plugins...");
765 let mut plugin_result = run_plugins(
766 input.config,
767 input.files,
768 input.workspaces,
769 input.root_pkg,
770 input.workspace_pkgs,
771 input.config_candidates,
772 )?;
773 let plugins_ms = t.elapsed().as_secs_f64() * 1000.0;
774
775 let t = Instant::now();
776 analyze_all_scripts(
777 input.config,
778 input.workspaces,
779 input.root_pkg,
780 input.workspace_pkgs,
781 &mut plugin_result,
782 );
783 let scripts_ms = t.elapsed().as_secs_f64() * 1000.0;
784
785 Ok((plugin_result, plugins_ms, scripts_ms))
786}
787
788#[derive(Debug, Clone, Copy)]
790#[doc(hidden)]
791pub struct DeadCodePreludeTimings {
792 pub discover_ms: f64,
793 pub workspaces_ms: f64,
794 pub plugins_ms: f64,
795 pub scripts_ms: f64,
796}
797
798#[doc(hidden)]
803pub struct DeadCodeBackendPrelude<'a> {
804 config: &'a ResolvedConfig,
805 pipeline_start: Instant,
806 progress: progress::AnalysisProgress,
807 discovery: AnalysisDiscovery,
808 workspace_pkgs: Vec<LoadedWorkspacePackage>,
809 plugin_result: plugins::AggregatedPluginResult,
810 plugins_ms: f64,
811 scripts_ms: f64,
812}
813
814impl DeadCodeBackendPrelude<'_> {
815 #[must_use]
816 pub fn timings(&self) -> DeadCodePreludeTimings {
817 DeadCodePreludeTimings {
818 discover_ms: self.discovery.discover_ms,
819 workspaces_ms: self.discovery.workspaces_ms,
820 plugins_ms: self.plugins_ms,
821 scripts_ms: self.scripts_ms,
822 }
823 }
824
825 #[must_use]
826 pub fn elapsed_ms(&self) -> f64 {
827 self.pipeline_start.elapsed().as_secs_f64() * 1000.0
828 }
829
830 #[must_use]
831 pub fn script_used_packages(&self) -> FxHashSet<String> {
832 self.plugin_result.script_used_packages.clone()
833 }
834
835 #[must_use]
838 pub fn trace_provenance(
839 &self,
840 modules: &[extract::ModuleInfo],
841 ) -> fallow_types::trace::TraceProvenance {
842 plugins::federation_trace_provenance(
843 &self.config.root,
844 self.discovery.files(),
845 &self.plugin_result.federation_sources,
846 modules,
847 )
848 }
849
850 #[must_use]
853 pub const fn plugin_result(&self) -> &plugins::AggregatedPluginResult {
854 &self.plugin_result
855 }
856
857 pub fn finish(&self) {
858 self.progress.finish();
859 }
860}
861
862#[doc(hidden)]
864pub struct DeadCodeEntryPoints {
865 inner: TimedEntryPoints,
866}
867
868impl DeadCodeEntryPoints {
869 #[must_use]
870 pub fn count(&self) -> usize {
871 self.inner.count
872 }
873
874 #[must_use]
875 pub fn elapsed_ms(&self) -> f64 {
876 self.inner.elapsed_ms
877 }
878
879 #[must_use]
881 pub fn spans(&self) -> EntryPointSpans {
882 self.inner.spans
883 }
884
885 #[must_use]
887 pub fn all(&self) -> &[discover::EntryPoint] {
888 &self.inner.entry_points.all
889 }
890}
891
892#[doc(hidden)]
894pub struct DeadCodeResolvedModules {
895 pub project: resolve::ResolvedProject,
896 pub elapsed_ms: f64,
897}
898
899#[doc(hidden)]
901pub struct DeadCodeGraphRun {
902 pub graph: graph::ModuleGraph,
903 pub elapsed_ms: f64,
904}
905
906#[doc(hidden)]
908pub struct DeadCodeDetectorRun {
909 pub results: AnalysisResults,
910 pub elapsed_ms: f64,
911}
912
913pub fn prepare_dead_code_backend_prelude(
919 config: &ResolvedConfig,
920 discovery: AnalysisDiscovery,
921) -> Result<DeadCodeBackendPrelude<'_>, FallowError> {
922 let progress = new_analysis_progress(config);
923 let pipeline_start = Instant::now();
924 let workspace_pkgs = load_workspace_packages(&discovery.workspaces);
925 let (plugin_result, plugins_ms, scripts_ms) = run_plugins_and_scripts(&PluginScriptInput {
926 config,
927 progress: &progress,
928 files: discovery.files(),
929 workspaces: &discovery.workspaces,
930 root_pkg: discovery.root_pkg.as_ref(),
931 workspace_pkgs: &workspace_pkgs,
932 config_candidates: &discovery.config_candidates,
933 })?;
934
935 Ok(DeadCodeBackendPrelude {
936 config,
937 pipeline_start,
938 progress,
939 discovery,
940 workspace_pkgs,
941 plugin_result,
942 plugins_ms,
943 scripts_ms,
944 })
945}
946
947#[must_use]
949pub fn discover_dead_code_entry_points(
950 prelude: &DeadCodeBackendPrelude<'_>,
951) -> DeadCodeEntryPoints {
952 let shared = prelude.shared_input();
953 DeadCodeEntryPoints {
954 inner: discover_analysis_entry_points(&shared),
955 }
956}
957
958pub fn try_load_dead_code_graph_cache(
968 prelude: &DeadCodeBackendPrelude<'_>,
969 entry_points: &DeadCodeEntryPoints,
970 modules: &[extract::ModuleInfo],
971) -> Result<(DeadCodeResolvedModules, DeadCodeGraphRun), Option<CacheRejection>> {
972 let shared = prelude.shared_input();
973 try_load_analysis_graph_cache(&shared, &entry_points.inner, modules).map(|hit| {
974 (
975 DeadCodeResolvedModules {
976 project: hit.project,
977 elapsed_ms: 0.0,
978 },
979 DeadCodeGraphRun {
980 graph: hit.graph,
981 elapsed_ms: hit.elapsed_ms,
982 },
983 )
984 })
985}
986
987#[must_use]
989pub fn resolve_dead_code_imports(
990 prelude: &DeadCodeBackendPrelude<'_>,
991 modules: &[extract::ModuleInfo],
992) -> DeadCodeResolvedModules {
993 let shared = prelude.shared_input();
994 let resolved = resolve_analysis_imports_timed(&shared, modules);
995 DeadCodeResolvedModules {
996 project: resolved.project,
997 elapsed_ms: resolved.elapsed_ms,
998 }
999}
1000
1001#[must_use]
1003pub fn build_dead_code_graph(
1004 prelude: &DeadCodeBackendPrelude<'_>,
1005 project: &resolve::ResolvedProject,
1006 entry_points: &DeadCodeEntryPoints,
1007 modules: &[extract::ModuleInfo],
1008) -> DeadCodeGraphRun {
1009 let shared = prelude.shared_input();
1010 let graph = build_analysis_graph_timed(&shared, project, &entry_points.inner, modules);
1011 DeadCodeGraphRun {
1012 graph: graph.graph,
1013 elapsed_ms: graph.elapsed_ms,
1014 }
1015}
1016
1017#[must_use]
1019pub fn run_dead_code_detectors(
1020 prelude: &DeadCodeBackendPrelude<'_>,
1021 graph: &graph::ModuleGraph,
1022 resolved: &[resolve::ResolvedModule],
1023 modules: &[extract::ModuleInfo],
1024 collect_usages: bool,
1025 entry_points: &DeadCodeEntryPoints,
1026) -> DeadCodeDetectorRun {
1027 let shared = prelude.shared_input();
1028 let analysis = analyze_dead_code_timed(
1029 &shared,
1030 graph,
1031 resolved,
1032 modules,
1033 collect_usages,
1034 entry_points.inner.summary.clone(),
1035 );
1036 DeadCodeDetectorRun {
1037 results: analysis.result,
1038 elapsed_ms: analysis.elapsed_ms,
1039 }
1040}
1041
1042impl<'a> DeadCodeBackendPrelude<'a> {
1043 fn shared_input(&'a self) -> AnalysisCoreSharedInput<'a> {
1044 AnalysisCoreSharedInput {
1045 config: self.config,
1046 progress: &self.progress,
1047 files: self.discovery.files(),
1048 workspaces: &self.discovery.workspaces,
1049 root_pkg: self.discovery.root_pkg.as_ref(),
1050 workspace_pkgs: &self.workspace_pkgs,
1051 plugin_result: &self.plugin_result,
1052 }
1053 }
1054}
1055
1056struct PreludeMetrics {
1059 discover_ms: f64,
1060 workspaces_ms: f64,
1061 plugins_ms: f64,
1062 scripts_ms: f64,
1063 total_ms: f64,
1064 file_count: usize,
1065 workspace_count: usize,
1066 module_count: usize,
1067}
1068
1069#[expect(
1071 clippy::struct_field_names,
1072 reason = "timings are all milliseconds; the _ms suffix is the unit"
1073)]
1074struct PreludeTimings {
1075 discover_ms: f64,
1076 workspaces_ms: f64,
1077 plugins_ms: f64,
1078 scripts_ms: f64,
1079}
1080
1081fn prelude_metrics(
1084 timings: &PreludeTimings,
1085 pipeline_start: Instant,
1086 files: &[discover::DiscoveredFile],
1087 workspaces: &[fallow_config::WorkspaceInfo],
1088 module_count: usize,
1089) -> PreludeMetrics {
1090 PreludeMetrics {
1091 discover_ms: timings.discover_ms,
1092 workspaces_ms: timings.workspaces_ms,
1093 plugins_ms: timings.plugins_ms,
1094 scripts_ms: timings.scripts_ms,
1095 total_ms: pipeline_start.elapsed().as_secs_f64() * 1000.0,
1096 file_count: files.len(),
1097 workspace_count: workspaces.len(),
1098 module_count,
1099 }
1100}
1101
1102struct AnalysisCoreSharedInput<'a> {
1103 config: &'a ResolvedConfig,
1104 progress: &'a progress::AnalysisProgress,
1105 files: &'a [discover::DiscoveredFile],
1106 workspaces: &'a [fallow_config::WorkspaceInfo],
1107 root_pkg: Option<&'a PackageJson>,
1108 workspace_pkgs: &'a [LoadedWorkspacePackage],
1109 plugin_result: &'a plugins::AggregatedPluginResult,
1110}
1111
1112struct TimedEntryPoints {
1113 entry_points: discover::CategorizedEntryPoints,
1114 summary: results::EntryPointSummary,
1115 count: usize,
1116 elapsed_ms: f64,
1117 spans: EntryPointSpans,
1118}
1119
1120struct TimedResolvedModules {
1121 project: resolve::ResolvedProject,
1122 elapsed_ms: f64,
1123}
1124
1125struct TimedGraph {
1126 graph: graph::ModuleGraph,
1127 elapsed_ms: f64,
1128}
1129
1130struct GraphCacheHit {
1131 graph: graph::ModuleGraph,
1132 project: resolve::ResolvedProject,
1133 elapsed_ms: f64,
1134}
1135
1136#[derive(Clone, Copy)]
1137struct DiscoverAllEntryPointsInput<'a> {
1138 config: &'a ResolvedConfig,
1139 files: &'a [discover::DiscoveredFile],
1140 workspaces: &'a [fallow_config::WorkspaceInfo],
1141 root_pkg: Option<&'a PackageJson>,
1142 workspace_pkgs: &'a [LoadedWorkspacePackage],
1143 plugin_result: &'a plugins::AggregatedPluginResult,
1144}
1145
1146struct TimedAnalysis {
1147 result: AnalysisResults,
1148 elapsed_ms: f64,
1149}
1150
1151fn discover_analysis_entry_points(input: &AnalysisCoreSharedInput<'_>) -> TimedEntryPoints {
1152 let t = Instant::now();
1153 let (entry_points, spans) = discover_all_entry_points(DiscoverAllEntryPointsInput {
1154 config: input.config,
1155 files: input.files,
1156 workspaces: input.workspaces,
1157 root_pkg: input.root_pkg,
1158 workspace_pkgs: input.workspace_pkgs,
1159 plugin_result: input.plugin_result,
1160 });
1161 let elapsed_ms = t.elapsed().as_secs_f64() * 1000.0;
1162 let summary = summarize_entry_points(&entry_points.all);
1163 let count = entry_points.all.len();
1164
1165 TimedEntryPoints {
1166 entry_points,
1167 summary,
1168 count,
1169 elapsed_ms,
1170 spans,
1171 }
1172}
1173
1174fn try_load_analysis_graph_cache(
1184 input: &AnalysisCoreSharedInput<'_>,
1185 entry_points: &TimedEntryPoints,
1186 modules: &[extract::ModuleInfo],
1187) -> Result<GraphCacheHit, Option<CacheRejection>> {
1188 if input.config.no_cache {
1189 return Err(None);
1190 }
1191
1192 let t = Instant::now();
1193 input.progress.set_stage("loading module graph cache...");
1194 let current = build_graph_cache_manifest(
1195 input.config,
1196 input.plugin_result,
1197 &entry_points.entry_points,
1198 input.files,
1199 modules,
1200 );
1201 let store = graph_cache::GraphCacheStore::load(&input.config.cache_dir).map_err(Some)?;
1202 if store.manifest.matches_inputs(¤t) {
1203 let project = restore_cached_resolved_project(input, modules, &store.resolved_project)?;
1204 tracing::debug!("Graph cache hit: skipping import resolution and graph build");
1205
1206 return Ok(GraphCacheHit {
1207 graph: store.graph,
1208 project,
1209 elapsed_ms: t.elapsed().as_secs_f64() * 1000.0,
1210 });
1211 }
1212
1213 if let Some(rejection) = store.manifest.classify_resolution_mismatch(¤t) {
1214 if rejection.discarded_existing_work() {
1219 tracing::warn!(
1220 "Graph cache decoded but not reused: {}",
1221 rejection.describe()
1222 );
1223 } else {
1224 tracing::debug!(
1225 "Graph cache decoded but not reused: {}",
1226 rejection.describe()
1227 );
1228 }
1229 return Err(Some(rejection));
1230 }
1231
1232 let project = restore_cached_resolved_project(input, modules, &store.resolved_project)?;
1233 tracing::debug!("Graph resolver cache hit: skipping import resolution and rebuilding graph");
1234 let graph = build_analysis_graph_timed(input, &project, entry_points, modules);
1235
1236 Ok(GraphCacheHit {
1237 graph: graph.graph,
1238 project,
1239 elapsed_ms: t.elapsed().as_secs_f64() * 1000.0,
1240 })
1241}
1242
1243fn restore_cached_resolved_project(
1249 input: &AnalysisCoreSharedInput<'_>,
1250 modules: &[extract::ModuleInfo],
1251 resolved_project: &graph_cache::CachedResolvedProject,
1252) -> Result<resolve::ResolvedProject, Option<CacheRejection>> {
1253 graph_cache::restore_resolved_project(
1254 &input.config.root,
1255 modules,
1256 input.files,
1257 resolved_project,
1258 )
1259 .inspect(|project| {
1260 record_unreadable_auto_import_reads(
1261 project,
1262 input.files,
1263 input.plugin_result,
1264 input.config,
1265 );
1266 })
1267 .ok_or_else(|| {
1268 tracing::debug!(
1272 "Graph cache decoded but its resolver payload no longer maps to the discovered files"
1273 );
1274 Some(CacheRejection::FileSetChanged)
1275 })
1276}
1277
1278fn resolve_analysis_imports_timed(
1279 input: &AnalysisCoreSharedInput<'_>,
1280 modules: &[extract::ModuleInfo],
1281) -> TimedResolvedModules {
1282 let t = Instant::now();
1283 input.progress.set_stage("resolving imports...");
1284 let project = resolve_analysis_imports(
1285 modules,
1286 input.files,
1287 input.workspaces,
1288 input.plugin_result,
1289 input.config,
1290 );
1291 TimedResolvedModules {
1292 project,
1293 elapsed_ms: t.elapsed().as_secs_f64() * 1000.0,
1294 }
1295}
1296
1297fn build_analysis_graph_timed(
1298 input: &AnalysisCoreSharedInput<'_>,
1299 project: &resolve::ResolvedProject,
1300 entry_points: &TimedEntryPoints,
1301 modules: &[extract::ModuleInfo],
1302) -> TimedGraph {
1303 let t = Instant::now();
1304 input.progress.set_stage("building module graph...");
1305 let graph = build_analysis_graph(&BuildAnalysisGraphInput {
1306 config: input.config,
1307 plugin_result: input.plugin_result,
1308 project,
1309 entry_points: &entry_points.entry_points,
1310 files: input.files,
1311 modules,
1312 workspaces: input.workspaces,
1313 });
1314 TimedGraph {
1315 graph,
1316 elapsed_ms: t.elapsed().as_secs_f64() * 1000.0,
1317 }
1318}
1319
1320fn release_resolution_payloads(modules: &mut [extract::ModuleInfo]) {
1321 for module in modules {
1322 module.release_resolution_payload();
1323 }
1324}
1325
1326fn analyze_dead_code_timed(
1327 input: &AnalysisCoreSharedInput<'_>,
1328 graph: &graph::ModuleGraph,
1329 resolved: &[resolve::ResolvedModule],
1330 modules: &[extract::ModuleInfo],
1331 collect_usages: bool,
1332 entry_point_summary: results::EntryPointSummary,
1333) -> TimedAnalysis {
1334 let t = Instant::now();
1335 input.progress.set_stage("analyzing...");
1336 let mut result = analyze::find_dead_code_full(
1337 graph,
1338 input.config,
1339 resolved,
1340 Some(input.plugin_result),
1341 input.workspaces,
1342 modules,
1343 collect_usages,
1344 );
1345 result.entry_point_summary = Some(entry_point_summary);
1346 TimedAnalysis {
1347 result,
1348 elapsed_ms: t.elapsed().as_secs_f64() * 1000.0,
1349 }
1350}
1351
1352fn analyze_full(
1353 config: &ResolvedConfig,
1354 retain: bool,
1355 collect_usages: bool,
1356 need_complexity: bool,
1357 retain_modules: bool,
1358) -> Result<AnalysisOutput, FallowError> {
1359 let _span = tracing::info_span!("fallow_analyze").entered();
1360 AnalysisSession::new(config)?.run_full(retain, collect_usages, need_complexity, retain_modules)
1361}
1362
1363fn full_analysis_pipeline_profile(
1364 timings: &PreludeTimings,
1365 pipeline_start: Instant,
1366 files: &[discover::DiscoveredFile],
1367 workspaces: &[fallow_config::WorkspaceInfo],
1368 core: &OwnedAnalysisCore,
1369 metrics: &ParseMetrics,
1370) -> PipelineProfile {
1371 let prelude = prelude_metrics(
1372 timings,
1373 pipeline_start,
1374 files,
1375 workspaces,
1376 core.modules.len(),
1377 );
1378 full_pipeline_profile(&prelude, core, metrics)
1379}
1380
1381fn assemble_full_output(
1384 core: OwnedAnalysisCore,
1385 plugin_result: plugins::AggregatedPluginResult,
1386 profile: &PipelineProfile,
1387 files: &[discover::DiscoveredFile],
1388 retain: bool,
1389 retain_modules: bool,
1390) -> AnalysisOutput {
1391 let file_hashes = collect_file_hashes(&core.modules, files);
1392 AnalysisOutput {
1393 results: core.result,
1394 timings: retained_pipeline_timings(retain, profile),
1395 graph: if retain { Some(core.graph) } else { None },
1396 modules: if retain_modules {
1397 Some(core.modules)
1398 } else {
1399 None
1400 },
1401 files: if retain_modules {
1402 Some(files.to_vec())
1403 } else {
1404 None
1405 },
1406 script_used_packages: plugin_result.script_used_packages,
1407 trace_provenance: fallow_types::trace::TraceProvenance::default(),
1408 file_hashes,
1409 }
1410}
1411
1412struct OwnedAnalysisCore {
1415 result: AnalysisResults,
1416 graph: graph::ModuleGraph,
1417 modules: Vec<extract::ModuleInfo>,
1418 entry_point_count: usize,
1419 entry_points_ms: f64,
1420 entry_point_spans: EntryPointSpans,
1421 resolve_ms: f64,
1422 graph_ms: f64,
1423 analyze_ms: f64,
1424 graph_cache_rejection: Option<CacheRejection>,
1425 resolve_work: resolve::ResolveWork,
1426}
1427
1428fn full_pipeline_profile(
1430 prelude: &PreludeMetrics,
1431 core: &OwnedAnalysisCore,
1432 parse: &ParseMetrics,
1433) -> PipelineProfile {
1434 PipelineProfile {
1435 discover_ms: prelude.discover_ms,
1436 workspaces_ms: prelude.workspaces_ms,
1437 plugins_ms: prelude.plugins_ms,
1438 scripts_ms: prelude.scripts_ms,
1439 parse_ms: parse.parse_ms,
1440 cache_ms: parse.cache_ms,
1441 entry_points_ms: core.entry_points_ms,
1442 entry_point_spans: core.entry_point_spans,
1443 resolve_ms: core.resolve_ms,
1444 graph_ms: core.graph_ms,
1445 analyze_ms: core.analyze_ms,
1446 total_ms: prelude.total_ms,
1447 file_count: prelude.file_count,
1448 workspace_count: prelude.workspace_count,
1449 module_count: prelude.module_count,
1450 entry_point_count: core.entry_point_count,
1451 cache_hits: parse.cache_hits,
1452 cache_misses: parse.cache_misses,
1453 parse_cpu_ms: parse.parse_cpu_ms,
1454 parse_cache_load_ms: parse.parse_cache_load_ms,
1455 cache_rejection: parse.cache_rejection,
1456 graph_cache_rejection: core.graph_cache_rejection,
1457 counters: PipelineCounters {
1458 files_read: parse.files_read,
1459 source_bytes_read: parse.source_bytes_read,
1460 parse_cache_bytes_read: parse.parse_cache_bytes_read,
1461 css_masked_bytes: parse.css_masked_bytes,
1462 resolve_specifier_calls: core.resolve_work.specifier_calls,
1463 unique_specifiers: core.resolve_work.unique_specifiers,
1464 oxc_resolve_calls: core.resolve_work.oxc_resolve_calls,
1465 canonicalize_calls: core.resolve_work.canonicalize_calls,
1466 },
1467 }
1468}
1469
1470#[derive(Clone, Copy)]
1471struct PipelineProfile {
1472 discover_ms: f64,
1473 workspaces_ms: f64,
1474 plugins_ms: f64,
1475 scripts_ms: f64,
1476 parse_ms: f64,
1477 cache_ms: f64,
1478 entry_points_ms: f64,
1479 entry_point_spans: EntryPointSpans,
1480 resolve_ms: f64,
1481 graph_ms: f64,
1482 analyze_ms: f64,
1483 total_ms: f64,
1484 file_count: usize,
1485 workspace_count: usize,
1486 module_count: usize,
1487 entry_point_count: usize,
1488 cache_hits: usize,
1489 cache_misses: usize,
1490 parse_cpu_ms: f64,
1491 parse_cache_load_ms: f64,
1492 cache_rejection: Option<CacheRejection>,
1493 graph_cache_rejection: Option<CacheRejection>,
1494 counters: PipelineCounters,
1495}
1496
1497struct AnalysisParseOutput {
1498 modules: Vec<extract::ModuleInfo>,
1499 metrics: ParseMetrics,
1500}
1501
1502struct ParseMetrics {
1504 parse_ms: f64,
1505 cache_ms: f64,
1506 cache_hits: usize,
1507 cache_misses: usize,
1508 parse_cpu_ms: f64,
1509 cache_rejection: Option<CacheRejection>,
1511 files_read: u64,
1512 source_bytes_read: u64,
1513 parse_cache_bytes_read: u64,
1514 css_masked_bytes: u64,
1515 parse_cache_load_ms: f64,
1516}
1517
1518impl From<AnalysisParseMetrics> for ParseMetrics {
1519 fn from(metrics: AnalysisParseMetrics) -> Self {
1520 Self {
1521 parse_ms: metrics.parse_ms,
1522 cache_ms: metrics.cache_ms,
1523 cache_hits: metrics.cache_hits,
1524 cache_misses: metrics.cache_misses,
1525 parse_cpu_ms: metrics.parse_cpu_ms,
1526 cache_rejection: metrics.cache_rejection,
1527 files_read: 0,
1528 source_bytes_read: 0,
1529 parse_cache_bytes_read: 0,
1530 css_masked_bytes: 0,
1531 parse_cache_load_ms: 0.0,
1532 }
1533 }
1534}
1535
1536fn parse_analysis_modules(
1537 config: &ResolvedConfig,
1538 files: &[discover::DiscoveredFile],
1539 need_complexity: bool,
1540 start: Instant,
1541) -> AnalysisParseOutput {
1542 let cache_max_size_bytes = resolve_cache_max_size_bytes(config);
1543 let mut cache_rejection = None;
1544 let mut parse_cache_bytes_read = 0;
1545 let mut parse_cache_load_ms = 0.0;
1546 let mut cache_store = if config.no_cache {
1547 None
1548 } else {
1549 let load_start = Instant::now();
1550 let (loaded, bytes_read) = cache::CacheStore::load_counting_bytes(
1551 &config.cache_dir,
1552 &config.root,
1553 config.cache_config_hash,
1554 cache_max_size_bytes,
1555 );
1556 parse_cache_bytes_read = bytes_read;
1557 parse_cache_load_ms = load_start.elapsed().as_secs_f64() * 1000.0;
1558 match loaded {
1559 Ok(store) => Some(store),
1560 Err(rejection) => {
1561 cache_rejection = Some(rejection);
1562 None
1563 }
1564 }
1565 };
1566
1567 let parse_result = extract::parse_all_files_cancellable(
1568 files,
1569 cache_store.as_ref(),
1570 need_complexity,
1571 None,
1572 &config.flags.patterns(),
1573 );
1574 let _ = fallow_config::record_source_read_failures(&config.root, &parse_result.read_failures);
1575 let _ = fallow_config::record_source_parse_degradations(
1576 &config.root,
1577 &parse_result.parse_degradations,
1578 );
1579 let modules = parse_result.modules;
1580 let parse_ms = start.elapsed().as_secs_f64() * 1000.0;
1581 let cache_ms = update_parse_cache_if_enabled(
1582 config,
1583 &mut cache_store,
1584 &modules,
1585 files,
1586 cache_max_size_bytes,
1587 need_complexity,
1588 );
1589
1590 AnalysisParseOutput {
1591 modules,
1592 metrics: ParseMetrics {
1593 parse_ms,
1594 cache_ms,
1595 cache_hits: parse_result.cache_hits,
1596 cache_misses: parse_result.cache_misses,
1597 parse_cpu_ms: parse_result.parse_cpu_ms,
1598 cache_rejection,
1599 files_read: parse_result.files_read,
1600 source_bytes_read: parse_result.source_bytes_read,
1601 parse_cache_bytes_read,
1602 css_masked_bytes: parse_result.css_masked_bytes,
1603 parse_cache_load_ms,
1604 },
1605 }
1606}
1607
1608fn retained_pipeline_timings(retain: bool, profile: &PipelineProfile) -> Option<PipelineTimings> {
1609 retain.then_some(PipelineTimings {
1610 discover_files_ms: profile.discover_ms,
1611 file_count: profile.file_count,
1612 workspaces_ms: profile.workspaces_ms,
1613 workspace_count: profile.workspace_count,
1614 plugins_ms: profile.plugins_ms,
1615 script_analysis_ms: profile.scripts_ms,
1616 parse_extract_ms: profile.parse_ms,
1617 parse_cpu_ms: profile.parse_cpu_ms,
1618 parse_cache_load_ms: profile.parse_cache_load_ms,
1619 module_count: profile.module_count,
1620 cache_hits: profile.cache_hits,
1621 cache_misses: profile.cache_misses,
1622 cache_rejection: profile.cache_rejection,
1623 graph_cache_rejection: profile.graph_cache_rejection,
1624 cache_update_ms: profile.cache_ms,
1625 entry_points_ms: profile.entry_points_ms,
1626 entry_point_spans: profile.entry_point_spans,
1627 entry_point_count: profile.entry_point_count,
1628 resolve_imports_ms: profile.resolve_ms,
1629 build_graph_ms: profile.graph_ms,
1630 analyze_ms: profile.analyze_ms,
1631 duplication_ms: None,
1632 total_ms: profile.total_ms,
1633 counters: profile.counters,
1634 })
1635}
1636
1637fn update_parse_cache_if_enabled(
1638 config: &ResolvedConfig,
1639 cache_store: &mut Option<cache::CacheStore>,
1640 modules: &[extract::ModuleInfo],
1641 files: &[discover::DiscoveredFile],
1642 cache_max_size_bytes: usize,
1643 need_complexity: bool,
1644) -> f64 {
1645 let t = Instant::now();
1646 if !config.no_cache {
1647 let store = cache_store.get_or_insert_with(|| cache::CacheStore::new(&config.root));
1648 if update_cache(store, modules, files, need_complexity)
1649 && let Err(error) = store.save(
1650 &config.cache_dir,
1651 config.cache_config_hash,
1652 cache_max_size_bytes,
1653 )
1654 {
1655 tracing::warn!("Failed to save cache: {error}");
1656 }
1657 }
1658 t.elapsed().as_secs_f64() * 1000.0
1659}
1660
1661fn resolve_analysis_imports(
1662 modules: &[extract::ModuleInfo],
1663 files: &[discover::DiscoveredFile],
1664 workspaces: &[fallow_config::WorkspaceInfo],
1665 plugin_result: &plugins::AggregatedPluginResult,
1666 config: &ResolvedConfig,
1667) -> resolve::ResolvedProject {
1668 let mut project = resolve::resolve_all_imports(&resolve::ResolveAllImportsInput {
1669 modules,
1670 files,
1671 workspaces,
1672 active_plugins: &plugin_result.active_plugins,
1673 path_aliases: &plugin_result.path_aliases,
1674 auto_imports: &plugin_result.auto_imports,
1675 scss_include_paths: &plugin_result.scss_include_paths,
1676 static_dir_mappings: &plugin_result.static_dir_mappings,
1677 framework_static_dir_mappings: &plugin_result.framework_static_dir_mappings,
1678 root: &config.root,
1679 extra_conditions: &config.resolve.conditions,
1680 });
1681 external_style_usage::augment_external_style_package_usage(
1682 &mut project.modules,
1683 config,
1684 workspaces,
1685 plugin_result,
1686 );
1687 record_unreadable_auto_import_reads(&project, files, plugin_result, config);
1688 project
1689}
1690
1691fn record_unreadable_auto_import_reads(
1703 project: &resolve::ResolvedProject,
1704 files: &[discover::DiscoveredFile],
1705 plugin_result: &plugins::AggregatedPluginResult,
1706 config: &ResolvedConfig,
1707) {
1708 if !config.auto_imports
1709 || plugin_result.auto_imports.is_empty()
1710 || !plugin_result
1711 .active_plugins
1712 .iter()
1713 .any(|name| name == "nuxt")
1714 {
1715 return;
1716 }
1717 let diagnostics: Vec<fallow_config::WorkspaceDiagnostic> =
1718 resolve::unreadable_auto_import_reads(&project.modules)
1719 .into_iter()
1720 .filter_map(|read| {
1721 let file = files.get(read.file_id.0 as usize)?;
1722 let diagnostic = plugins::PluginConfigDiagnostic::not_modeled(
1723 &file.path,
1724 "nuxt",
1725 read.module,
1726 AUTO_IMPORT_KEY_NOT_MODELED,
1727 );
1728 Some(diagnostic.into_workspace_diagnostic(&config.root))
1729 })
1730 .collect();
1731 fallow_config::append_workspace_diagnostics(&config.root, diagnostics);
1732}
1733
1734struct BuildAnalysisGraphInput<'a> {
1735 config: &'a ResolvedConfig,
1736 plugin_result: &'a plugins::AggregatedPluginResult,
1737 project: &'a resolve::ResolvedProject,
1738 entry_points: &'a discover::CategorizedEntryPoints,
1739 files: &'a [discover::DiscoveredFile],
1740 modules: &'a [extract::ModuleInfo],
1741 workspaces: &'a [fallow_config::WorkspaceInfo],
1742}
1743
1744fn build_analysis_graph(input: &BuildAnalysisGraphInput<'_>) -> graph::ModuleGraph {
1752 let caching_enabled = !input.config.no_cache;
1753 let current_manifest = caching_enabled.then(|| {
1754 build_graph_cache_manifest(
1755 input.config,
1756 input.plugin_result,
1757 input.entry_points,
1758 input.files,
1759 input.modules,
1760 )
1761 });
1762
1763 let mut graph = graph::ModuleGraph::build_with_reachability_roots_and_replacements(
1764 &input.project.modules,
1765 &input.project.replaced_module_targets,
1766 &input.entry_points.all,
1767 &input.entry_points.runtime,
1768 &input.entry_points.test,
1769 input.files,
1770 );
1771 credit_package_path_references(&mut graph, input.modules);
1772 credit_workspace_package_usage(&mut graph, &input.project.modules, input.workspaces);
1773
1774 if let Some(manifest) = current_manifest {
1775 let Some(resolved_project) =
1776 graph_cache::cache_resolved_project(&input.config.root, input.files, input.project)
1777 else {
1778 return graph;
1779 };
1780 let store = graph_cache::GraphCacheStore {
1781 version: graph_cache::GRAPH_CACHE_VERSION,
1782 manifest,
1783 graph,
1784 resolved_project,
1785 };
1786 store.save(&input.config.cache_dir);
1787 return store.graph;
1792 }
1793
1794 graph
1795}
1796
1797fn build_graph_cache_manifest(
1800 config: &ResolvedConfig,
1801 plugin_result: &plugins::AggregatedPluginResult,
1802 entry_points: &discover::CategorizedEntryPoints,
1803 files: &[discover::DiscoveredFile],
1804 modules: &[extract::ModuleInfo],
1805) -> graph_cache::GraphCacheManifest {
1806 let mode = graph_cache::GraphCacheMode::new(
1807 resolver_options_hash(config),
1808 entry_points_hash(entry_points, &config.root),
1809 plugin_config_hash(plugin_result, &config.root),
1810 );
1811 let mut content_hashes = vec![0u64; files.len()];
1816 for module in modules {
1817 if let Some(slot) = content_hashes.get_mut(module.file_id.0 as usize) {
1818 *slot = module.content_hash;
1819 }
1820 }
1821 graph_cache::GraphCacheManifest::from_discovered_files(&config.root, files, mode, |file| {
1822 content_hashes
1823 .get(file.id.0 as usize)
1824 .copied()
1825 .unwrap_or_default()
1826 })
1827}
1828
1829fn resolver_options_hash(config: &ResolvedConfig) -> u64 {
1847 use std::hash::{Hash, Hasher};
1848 let mut hasher = rustc_hash::FxHasher::default();
1849 config.cache_config_hash.hash(&mut hasher);
1850 config.resolve.conditions.hash(&mut hasher);
1851 hasher.finish()
1852}
1853
1854fn root_relative_key(root: &std::path::Path, path: &std::path::Path) -> String {
1858 path.strip_prefix(root)
1859 .unwrap_or(path)
1860 .to_string_lossy()
1861 .replace('\\', "/")
1862}
1863
1864fn entry_points_hash(
1867 entry_points: &discover::CategorizedEntryPoints,
1868 root: &std::path::Path,
1869) -> u64 {
1870 use std::hash::{Hash, Hasher};
1871 let mut hasher = rustc_hash::FxHasher::default();
1872 for role in [&entry_points.all, &entry_points.runtime, &entry_points.test] {
1873 let mut keys: Vec<String> = role
1874 .iter()
1875 .map(|ep| root_relative_key(root, &ep.path))
1876 .collect();
1877 keys.sort_unstable();
1878 keys.len().hash(&mut hasher);
1879 for key in keys {
1880 key.hash(&mut hasher);
1881 }
1882 }
1883 hasher.finish()
1884}
1885
1886fn plugin_config_hash(
1889 plugin_result: &plugins::AggregatedPluginResult,
1890 root: &std::path::Path,
1891) -> u64 {
1892 use std::hash::{Hash, Hasher};
1893 let mut hasher = rustc_hash::FxHasher::default();
1894
1895 hash_active_plugins(plugin_result, &mut hasher);
1896 hash_path_aliases(plugin_result, root, &mut hasher);
1897
1898 let mut auto_imports: Vec<AutoImportHashKey<'_>> = plugin_result
1899 .auto_imports
1900 .iter()
1901 .map(|rule| {
1902 let mut scope: Vec<String> = rule
1903 .scope
1904 .iter()
1905 .map(|scope_root| root_relative_key(root, scope_root))
1906 .collect();
1907 scope.sort_unstable();
1908 (
1909 rule.name.as_str(),
1910 root_relative_key(root, &rule.source),
1911 auto_import_kind_rank(rule.kind),
1912 scope,
1913 )
1914 })
1915 .collect();
1916 auto_imports.sort_unstable();
1917 auto_imports.len().hash(&mut hasher);
1918 for key in &auto_imports {
1919 key.hash(&mut hasher);
1920 }
1921
1922 let mut scss_include_paths: Vec<String> = plugin_result
1923 .scss_include_paths
1924 .iter()
1925 .map(|path| root_relative_key(root, path))
1926 .collect();
1927 scss_include_paths.sort_unstable();
1928 scss_include_paths.len().hash(&mut hasher);
1929 for path in scss_include_paths {
1930 path.hash(&mut hasher);
1931 }
1932
1933 let mut static_dir_mappings: Vec<(String, &str)> = plugin_result
1934 .static_dir_mappings
1935 .iter()
1936 .map(|(from_dir, mount)| (root_relative_key(root, from_dir), mount.as_str()))
1937 .collect();
1938 static_dir_mappings.sort_unstable();
1939 static_dir_mappings.len().hash(&mut hasher);
1940 for (from_dir, mount) in static_dir_mappings {
1941 from_dir.hash(&mut hasher);
1942 mount.hash(&mut hasher);
1943 }
1944
1945 hasher.finish()
1946}
1947
1948fn hash_active_plugins(
1949 plugin_result: &plugins::AggregatedPluginResult,
1950 hasher: &mut rustc_hash::FxHasher,
1951) {
1952 use std::hash::Hash;
1953 let mut active: Vec<&str> = plugin_result
1954 .active_plugins
1955 .iter()
1956 .map(String::as_str)
1957 .collect();
1958 active.sort_unstable();
1959 active.len().hash(hasher);
1960 for name in active {
1961 name.hash(hasher);
1962 }
1963}
1964
1965fn hash_path_aliases(
1969 plugin_result: &plugins::AggregatedPluginResult,
1970 root: &std::path::Path,
1971 hasher: &mut rustc_hash::FxHasher,
1972) {
1973 use std::hash::Hash;
1974 let mut aliases: Vec<(&str, String)> = plugin_result
1975 .path_aliases
1976 .iter()
1977 .map(|(prefix, replacement)| {
1978 (
1979 prefix.as_str(),
1980 root_relative_key(root, std::path::Path::new(replacement)),
1981 )
1982 })
1983 .collect();
1984 aliases.sort_unstable();
1985 aliases.len().hash(hasher);
1986 for (prefix, replacement) in aliases {
1987 prefix.hash(hasher);
1988 replacement.hash(hasher);
1989 }
1990}
1991
1992type AutoImportHashKey<'a> = (&'a str, String, u8, Vec<String>);
1995
1996fn auto_import_kind_rank(kind: fallow_config::AutoImportKind) -> u8 {
1997 match kind {
1998 fallow_config::AutoImportKind::Named => 0,
1999 fallow_config::AutoImportKind::Default => 1,
2000 fallow_config::AutoImportKind::DefaultComponent => 2,
2001 }
2002}
2003
2004fn collect_file_hashes(
2005 modules: &[extract::ModuleInfo],
2006 files: &[discover::DiscoveredFile],
2007) -> rustc_hash::FxHashMap<std::path::PathBuf, u64> {
2008 modules
2009 .iter()
2010 .filter_map(|module| {
2011 files
2012 .get(module.file_id.0 as usize)
2013 .map(|file| (file.path.clone(), module.content_hash))
2014 })
2015 .collect()
2016}
2017
2018fn trace_pipeline_profile(profile: &PipelineProfile) {
2019 let PipelineProfile {
2020 discover_ms,
2021 workspaces_ms,
2022 plugins_ms,
2023 scripts_ms,
2024 parse_ms,
2025 cache_ms,
2026 entry_points_ms,
2027 resolve_ms,
2028 graph_ms,
2029 analyze_ms,
2030 total_ms,
2031 file_count,
2032 module_count,
2033 entry_point_count,
2034 cache_hits,
2035 cache_misses,
2036 cache_rejection,
2037 ..
2038 } = *profile;
2039 let cache_summary = cache_rejection.map_or_else(
2040 || format!(" ({cache_hits} cached, {cache_misses} parsed)"),
2041 |rejection| {
2042 format!(
2043 " ({cache_hits} cached, {cache_misses} parsed, cache refused: {})",
2044 rejection.describe()
2045 )
2046 },
2047 );
2048
2049 tracing::debug!(
2050 "\n┌─ Pipeline Profile ─────────────────────────────\n\
2051 │ discover files: {:>8.1}ms ({} files)\n\
2052 │ workspaces: {:>8.1}ms\n\
2053 │ plugin detection: {:>8.1}ms\n\
2054 │ script analysis: {:>8.1}ms\n\
2055 │ parse/extract: {:>8.1}ms ({} modules{})\n\
2056 │ cache update: {:>8.1}ms\n\
2057 │ entry points: {:>8.1}ms ({} entries)\n\
2058 │ resolve imports: {:>8.1}ms\n\
2059 │ build graph: {:>8.1}ms\n\
2060 │ analyze: {:>8.1}ms\n\
2061 │ ────────────────────────────────────────────\n\
2062 │ TOTAL: {:>8.1}ms\n\
2063 └─────────────────────────────────────────────────",
2064 discover_ms,
2065 file_count,
2066 workspaces_ms,
2067 plugins_ms,
2068 scripts_ms,
2069 parse_ms,
2070 module_count,
2071 cache_summary,
2072 cache_ms,
2073 entry_points_ms,
2074 entry_point_count,
2075 resolve_ms,
2076 graph_ms,
2077 analyze_ms,
2078 total_ms,
2079 );
2080}
2081
2082fn load_workspace_packages(
2083 workspaces: &[fallow_config::WorkspaceInfo],
2084) -> Vec<LoadedWorkspacePackage> {
2085 workspaces
2086 .iter()
2087 .filter_map(|ws| {
2088 fallow_config::load_dir_package_json(&ws.root).map(|pkg| (ws.clone(), pkg))
2089 })
2090 .collect()
2091}
2092
2093fn analyze_all_scripts(
2098 config: &ResolvedConfig,
2099 workspaces: &[fallow_config::WorkspaceInfo],
2100 root_pkg: Option<&PackageJson>,
2101 workspace_pkgs: &[LoadedWorkspacePackage],
2102 plugin_result: &mut plugins::AggregatedPluginResult,
2103) {
2104 let all_dep_names = collect_all_dependency_names(root_pkg, workspace_pkgs);
2105 let all_dep_set: FxHashSet<String> = all_dep_names.iter().cloned().collect();
2106 let workspace_packages =
2107 discover::collect_workspace_packages(&config.root, root_pkg, workspace_pkgs);
2108 let all_scripts = collect_all_scripts(root_pkg, workspace_pkgs, &workspace_packages);
2109
2110 let nm_roots = collect_node_modules_roots(config, workspaces);
2111 let bin_map = scripts::build_bin_to_package_map(&nm_roots, &all_dep_names);
2112 let deps = ScriptDependencyContext {
2113 bin_map: &bin_map,
2114 all_dep_set: &all_dep_set,
2115 workspace_packages: &workspace_packages,
2116 };
2117
2118 analyze_root_scripts(config, root_pkg, &deps, plugin_result);
2119 analyze_workspace_scripts(config, workspace_pkgs, &deps, plugin_result);
2120 analyze_ci_scripts(config, &bin_map, &all_dep_set, &all_scripts, plugin_result);
2121
2122 plugin_result
2123 .entry_point_roles
2124 .entry("scripts".to_string())
2125 .or_insert(EntryPointRole::Support);
2126}
2127
2128fn collect_all_dependency_names(
2130 root_pkg: Option<&PackageJson>,
2131 workspace_pkgs: &[LoadedWorkspacePackage],
2132) -> Vec<String> {
2133 let mut all_dep_names: Vec<String> = Vec::new();
2134 if let Some(pkg) = root_pkg {
2135 all_dep_names.extend(pkg.all_dependency_names());
2136 }
2137 for (_, ws_pkg) in workspace_pkgs {
2138 all_dep_names.extend(ws_pkg.all_dependency_names());
2139 }
2140 all_dep_names.sort_unstable();
2141 all_dep_names.dedup();
2142 all_dep_names
2143}
2144
2145struct ScriptDependencyContext<'a> {
2148 bin_map: &'a rustc_hash::FxHashMap<String, String>,
2149 all_dep_set: &'a FxHashSet<String>,
2150 workspace_packages: &'a std::sync::Arc<scripts::WorkspacePackages>,
2151}
2152
2153fn workspace_dir(root: &std::path::Path, ws: &fallow_config::WorkspaceInfo) -> String {
2156 ws.root
2157 .strip_prefix(root)
2158 .unwrap_or(&ws.root)
2159 .to_string_lossy()
2160 .replace('\\', "/")
2161}
2162
2163fn collect_all_scripts(
2165 root_pkg: Option<&PackageJson>,
2166 workspace_pkgs: &[LoadedWorkspacePackage],
2167 workspace_packages: &std::sync::Arc<scripts::WorkspacePackages>,
2168) -> scripts::ScriptCatalog {
2169 let mut catalog = scripts::ScriptCatalog::default();
2170 if let Some(pkg) = root_pkg
2171 && let Some(ref pkg_scripts) = pkg.scripts
2172 {
2173 catalog.merge_scripts(pkg_scripts);
2174 }
2175 for (_, ws_pkg) in workspace_pkgs {
2176 if let Some(ref ws_scripts) = ws_pkg.scripts {
2177 catalog.merge_workspace_scripts(ws_scripts);
2178 }
2179 }
2180 catalog.with_workspaces(std::sync::Arc::clone(workspace_packages), "")
2181}
2182
2183fn collect_node_modules_roots<'a>(
2185 config: &'a ResolvedConfig,
2186 workspaces: &'a [fallow_config::WorkspaceInfo],
2187) -> Vec<&'a std::path::Path> {
2188 let mut nm_roots: Vec<&std::path::Path> = Vec::new();
2189 if config.root.join("node_modules").is_dir() {
2190 nm_roots.push(&config.root);
2191 }
2192 for ws in workspaces {
2193 if ws.root.join("node_modules").is_dir() {
2194 nm_roots.push(&ws.root);
2195 }
2196 }
2197 nm_roots
2198}
2199
2200fn analyze_root_scripts(
2202 config: &ResolvedConfig,
2203 root_pkg: Option<&PackageJson>,
2204 deps: &ScriptDependencyContext<'_>,
2205 plugin_result: &mut plugins::AggregatedPluginResult,
2206) {
2207 let Some(pkg) = root_pkg else {
2208 return;
2209 };
2210 let Some(ref pkg_scripts) = pkg.scripts else {
2211 return;
2212 };
2213 let scripts_to_analyze = if config.production {
2214 scripts::filter_production_scripts(pkg_scripts)
2215 } else {
2216 pkg_scripts.clone()
2217 };
2218 let catalog =
2219 scripts::ScriptCatalog::from_scripts_with_bodies(pkg_scripts, &scripts_to_analyze)
2220 .with_workspaces(std::sync::Arc::clone(deps.workspace_packages), "");
2221 let script_analysis = scripts::analyze_scripts_with_dependency_context(
2222 &scripts_to_analyze,
2223 &config.root,
2224 deps.bin_map,
2225 deps.all_dep_set,
2226 &catalog,
2227 scripts::IgnoredCommandEntries::new(&config.ignore_command_entries),
2228 );
2229 plugin_result.script_used_packages = script_analysis.used_packages;
2230
2231 for config_file in &script_analysis.config_files {
2232 plugin_result
2233 .discovered_always_used
2234 .push((config_file.clone(), "scripts".to_string()));
2235 }
2236 for entry in &script_analysis.entry_files {
2237 if let Some(pat) = scripts::normalize_script_entry_pattern("", entry) {
2238 plugin_result
2239 .entry_patterns
2240 .push((plugins::PathRule::new(pat), "scripts".to_string()));
2241 }
2242 }
2243}
2244
2245type WsScriptOut = (
2247 Vec<String>,
2248 Vec<(String, String)>,
2249 Vec<(plugins::PathRule, String)>,
2250);
2251
2252fn analyze_workspace_scripts(
2253 config: &ResolvedConfig,
2254 workspace_pkgs: &[LoadedWorkspacePackage],
2255 deps: &ScriptDependencyContext<'_>,
2256 plugin_result: &mut plugins::AggregatedPluginResult,
2257) {
2258 let ws_results: Vec<WsScriptOut> = workspace_pkgs
2259 .par_iter()
2260 .map(|(ws, ws_pkg)| analyze_one_workspace_scripts(config, ws, ws_pkg, deps))
2261 .collect();
2262 for (used_packages, discovered_always_used, entry_patterns) in ws_results {
2263 plugin_result.script_used_packages.extend(used_packages);
2264 plugin_result
2265 .discovered_always_used
2266 .extend(discovered_always_used);
2267 plugin_result.entry_patterns.extend(entry_patterns);
2268 }
2269}
2270
2271fn analyze_one_workspace_scripts(
2274 config: &ResolvedConfig,
2275 ws: &fallow_config::WorkspaceInfo,
2276 ws_pkg: &PackageJson,
2277 deps: &ScriptDependencyContext<'_>,
2278) -> WsScriptOut {
2279 let mut used_packages = Vec::new();
2280 let mut discovered_always_used: Vec<(String, String)> = Vec::new();
2281 let mut entry_patterns: Vec<(plugins::PathRule, String)> = Vec::new();
2282 let Some(ref ws_scripts) = ws_pkg.scripts else {
2283 return (used_packages, discovered_always_used, entry_patterns);
2284 };
2285 let scripts_to_analyze = if config.production {
2286 scripts::filter_production_scripts(ws_scripts)
2287 } else {
2288 ws_scripts.clone()
2289 };
2290 let ws_prefix = workspace_dir(&config.root, ws);
2291 let catalog = scripts::ScriptCatalog::from_scripts_with_bodies(ws_scripts, &scripts_to_analyze)
2292 .with_workspaces(std::sync::Arc::clone(deps.workspace_packages), &ws_prefix);
2293 let ws_analysis = scripts::analyze_scripts_with_dependency_context(
2294 &scripts_to_analyze,
2295 &ws.root,
2296 deps.bin_map,
2297 deps.all_dep_set,
2298 &catalog,
2299 scripts::IgnoredCommandEntries::new(&config.ignore_command_entries),
2300 );
2301 used_packages.extend(ws_analysis.used_packages);
2302
2303 for config_file in &ws_analysis.config_files {
2304 discovered_always_used.push((format!("{ws_prefix}/{config_file}"), "scripts".to_string()));
2305 }
2306 for entry in &ws_analysis.entry_files {
2307 if let Some(pat) = scripts::normalize_script_entry_pattern(&ws_prefix, entry) {
2308 entry_patterns.push((plugins::PathRule::new(pat), "scripts".to_string()));
2309 }
2310 }
2311 (used_packages, discovered_always_used, entry_patterns)
2312}
2313
2314fn analyze_ci_scripts(
2316 config: &ResolvedConfig,
2317 bin_map: &rustc_hash::FxHashMap<String, String>,
2318 all_dep_set: &FxHashSet<String>,
2319 all_scripts: &scripts::ScriptCatalog,
2320 plugin_result: &mut plugins::AggregatedPluginResult,
2321) {
2322 let ci_analysis = scripts::ci::analyze_ci_files(
2323 &config.root,
2324 bin_map,
2325 all_dep_set,
2326 all_scripts,
2327 scripts::IgnoredCommandEntries::new(&config.ignore_command_entries),
2328 );
2329 plugin_result
2330 .script_used_packages
2331 .extend(ci_analysis.used_packages);
2332 for entry in &ci_analysis.entry_files {
2333 if let Some(pat) = scripts::normalize_script_entry_pattern("", entry) {
2334 plugin_result
2335 .entry_patterns
2336 .push((plugins::PathRule::new(pat), "scripts".to_string()));
2337 }
2338 }
2339}
2340
2341fn discover_all_entry_points(
2343 input: DiscoverAllEntryPointsInput<'_>,
2344) -> (discover::CategorizedEntryPoints, EntryPointSpans) {
2345 let mut spans = EntryPointSpans::default();
2346 let mut mark = Instant::now();
2347 let mut entry_points = discover::CategorizedEntryPoints::default();
2348 let workspace_packages = discover::collect_workspace_packages(
2351 &input.config.root,
2352 input.root_pkg,
2353 input.workspace_pkgs,
2354 );
2355 let runtime_seeds = discover::workspace_runtime_script_seeds(&workspace_packages);
2356 let script_workspaces = discover::ScriptWorkspaces {
2357 packages: &workspace_packages,
2358 project_root: &input.config.root,
2359 runtime_seeds: &runtime_seeds,
2360 };
2361 let root_discovery = discover::discover_root_entry_points(
2362 input.config,
2363 input.files,
2364 input.root_pkg,
2365 input.workspaces.is_empty(),
2366 script_workspaces,
2367 );
2368 spans.root_ms = split_ms(&mut mark);
2369
2370 let workspace_pkg_by_root: rustc_hash::FxHashMap<std::path::PathBuf, &PackageJson> = input
2371 .workspace_pkgs
2372 .iter()
2373 .map(|(ws, pkg)| (ws.root.clone(), pkg))
2374 .collect();
2375 let workspace_discovery: Vec<discover::EntryPointDiscovery> = input
2376 .workspaces
2377 .par_iter()
2378 .map(|ws| {
2379 let pkg = workspace_pkg_by_root.get(&ws.root).copied();
2380 discover::discover_workspace_package_entry_points(
2381 &ws.root,
2382 input.files,
2383 pkg,
2384 scripts::IgnoredCommandEntries::new(&input.config.ignore_command_entries),
2385 script_workspaces,
2386 )
2387 })
2388 .collect();
2389 let mut skipped_entries = rustc_hash::FxHashMap::default();
2390 entry_points.extend_runtime(root_discovery.entries);
2391 entry_points.extend_support(root_discovery.support_entries);
2392 for (path, count) in root_discovery.skipped_entries {
2393 *skipped_entries.entry(path).or_insert(0) += count;
2394 }
2395 let mut ws_entries = Vec::new();
2396 let mut ws_support_entries = Vec::new();
2397 for workspace in workspace_discovery {
2398 ws_entries.extend(workspace.entries);
2399 ws_support_entries.extend(workspace.support_entries);
2400 for (path, count) in workspace.skipped_entries {
2401 *skipped_entries.entry(path).or_insert(0) += count;
2402 }
2403 }
2404 discover::warn_skipped_entry_summary(&skipped_entries);
2405 entry_points.extend_runtime(ws_entries);
2406 entry_points.extend_support(ws_support_entries);
2407 spans.workspaces_ms = split_ms(&mut mark);
2408
2409 let plugin_entries = discover::discover_plugin_entry_point_sets_timed(
2410 input.plugin_result,
2411 input.config,
2412 input.files,
2413 );
2414 spans.plugin_glob_build_ms = plugin_entries.build_ms;
2415 spans.plugin_glob_match_ms = plugin_entries.match_ms;
2416 entry_points.extend(plugin_entries.entries);
2417 spans.plugins_ms = split_ms(&mut mark);
2418
2419 let all_scripts =
2422 collect_all_scripts(input.root_pkg, input.workspace_pkgs, &workspace_packages);
2423 let infra_entries = discover::discover_infrastructure_entry_points(
2424 &input.config.root,
2425 discover::CommandRefContext {
2426 ignored: scripts::IgnoredCommandEntries::new(&input.config.ignore_command_entries),
2427 scripts: &all_scripts,
2428 },
2429 );
2430 entry_points.extend_runtime(infra_entries);
2431 spans.infrastructure_ms = split_ms(&mut mark);
2432
2433 if !input.config.dynamically_loaded.is_empty() {
2434 let dynamic_entries =
2435 discover::discover_dynamically_loaded_entry_points(input.config, input.files);
2436 entry_points.extend_runtime(dynamic_entries);
2437 }
2438 spans.dynamic_ms = split_ms(&mut mark);
2439
2440 let deduped = entry_points.dedup();
2441 spans.dedup_ms = split_ms(&mut mark);
2442 (deduped, spans)
2443}
2444
2445fn split_ms(mark: &mut Instant) -> f64 {
2450 let now = Instant::now();
2451 let elapsed = now.duration_since(*mark).as_secs_f64() * 1000.0;
2452 *mark = now;
2453 elapsed
2454}
2455
2456fn summarize_entry_points(entry_points: &[discover::EntryPoint]) -> results::EntryPointSummary {
2458 let mut counts: rustc_hash::FxHashMap<String, usize> = rustc_hash::FxHashMap::default();
2459 for ep in entry_points {
2460 let category = match &ep.source {
2461 discover::EntryPointSource::PackageJsonMain
2462 | discover::EntryPointSource::PackageJsonModule
2463 | discover::EntryPointSource::PackageJsonExports
2464 | discover::EntryPointSource::PackageJsonBin
2465 | discover::EntryPointSource::PackageJsonScript => "package.json",
2466 discover::EntryPointSource::Plugin { .. } => "plugin",
2467 discover::EntryPointSource::TestFile => "test file",
2468 discover::EntryPointSource::DefaultIndex => "default index",
2469 discover::EntryPointSource::ManualEntry => "manual entry",
2470 discover::EntryPointSource::InfrastructureConfig => "config",
2471 discover::EntryPointSource::DynamicallyLoaded => "dynamically loaded",
2472 };
2473 *counts.entry(category.to_string()).or_insert(0) += 1;
2474 }
2475 let mut by_source: Vec<(String, usize)> = counts.into_iter().collect();
2476 by_source.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
2477 results::EntryPointSummary {
2478 total: entry_points.len(),
2479 by_source,
2480 }
2481}
2482
2483fn append_package_file_asset_patterns(
2484 result: &mut plugins::AggregatedPluginResult,
2485 prefix: &str,
2486 pkg: &PackageJson,
2487) {
2488 let prefix = prefix.trim_matches('/');
2489 for pattern in package_assets::scaffold_template_asset_patterns(pkg) {
2490 let pattern = if prefix.is_empty() {
2491 pattern
2492 } else {
2493 format!("{prefix}/{pattern}")
2494 };
2495 result
2496 .discovered_always_used
2497 .push((pattern, package_assets::PACKAGE_FILES_SOURCE.to_string()));
2498 }
2499}
2500
2501fn append_workspace_package_file_asset_patterns(
2502 result: &mut plugins::AggregatedPluginResult,
2503 config: &ResolvedConfig,
2504 workspace_pkgs: &[LoadedWorkspacePackage],
2505) {
2506 for (ws, ws_pkg) in workspace_pkgs {
2507 let ws_prefix = ws
2508 .root
2509 .strip_prefix(&config.root)
2510 .unwrap_or(&ws.root)
2511 .to_string_lossy()
2512 .replace('\\', "/");
2513 append_package_file_asset_patterns(result, &ws_prefix, ws_pkg);
2514 }
2515}
2516
2517fn run_plugins(
2519 config: &ResolvedConfig,
2520 files: &[discover::DiscoveredFile],
2521 workspaces: &[fallow_config::WorkspaceInfo],
2522 root_pkg: Option<&PackageJson>,
2523 workspace_pkgs: &[LoadedWorkspacePackage],
2524 config_candidates: &[std::path::PathBuf],
2525) -> Result<plugins::AggregatedPluginResult, FallowError> {
2526 let registry = plugins::PluginRegistry::new(config.external_plugins.clone());
2527 let file_paths: Vec<std::path::PathBuf> = files.iter().map(|f| f.path.clone()).collect();
2528
2529 let candidate_index = (!config.production).then(|| {
2534 plugins::registry::ConfigCandidateIndex::build(
2535 file_paths
2536 .iter()
2537 .map(std::path::PathBuf::as_path)
2538 .chain(config_candidates.iter().map(std::path::PathBuf::as_path)),
2539 )
2540 });
2541
2542 let mut result = run_root_plugins(
2543 ®istry,
2544 config,
2545 root_pkg,
2546 &file_paths,
2547 candidate_index.as_ref(),
2548 )?;
2549
2550 if workspaces.is_empty() {
2551 share_auto_imports_across_layers(&mut result, config, workspaces);
2552 gate_auto_import_entry_patterns(&mut result, config, workspaces);
2553 record_plugin_config_diagnostics(&result, &config.root);
2554 return Ok(result);
2555 }
2556
2557 append_workspace_package_file_asset_patterns(&mut result, config, workspace_pkgs);
2558
2559 let ws_results = run_workspace_plugins(
2560 ®istry,
2561 config,
2562 workspace_pkgs,
2563 &file_paths,
2564 &result.active_plugins,
2565 candidate_index.as_ref(),
2566 );
2567 merge_workspace_plugin_results(&mut result, ws_results)?;
2568
2569 share_auto_imports_across_layers(&mut result, config, workspaces);
2570 gate_auto_import_entry_patterns(&mut result, config, workspaces);
2571 record_plugin_config_diagnostics(&result, &config.root);
2572
2573 Ok(result)
2574}
2575
2576fn record_plugin_config_diagnostics(result: &plugins::AggregatedPluginResult, root: &Path) {
2588 let diagnostics = result
2589 .config_diagnostics
2590 .iter()
2591 .cloned()
2592 .map(|diagnostic| diagnostic.into_workspace_diagnostic(root))
2593 .collect();
2594 let _ = fallow_config::record_plugin_config_diagnostics(root, diagnostics);
2595}
2596
2597type WorkspacePluginResult = Result<
2598 (plugins::AggregatedPluginResult, String),
2599 Vec<plugins::registry::PluginRegexValidationError>,
2600>;
2601
2602fn run_root_plugins(
2604 registry: &plugins::PluginRegistry,
2605 config: &ResolvedConfig,
2606 root_pkg: Option<&PackageJson>,
2607 file_paths: &[std::path::PathBuf],
2608 candidate_index: Option<&plugins::registry::ConfigCandidateIndex>,
2609) -> Result<plugins::AggregatedPluginResult, FallowError> {
2610 let root_config_search_roots = collect_config_search_roots(&config.root, file_paths);
2611 let root_config_search_root_refs: Vec<&Path> = root_config_search_roots
2612 .iter()
2613 .map(std::path::PathBuf::as_path)
2614 .collect();
2615
2616 let mut result = if let Some(pkg) = root_pkg {
2617 registry
2618 .try_run_with_search_roots(
2619 pkg,
2620 &config.root,
2621 file_paths,
2622 &root_config_search_root_refs,
2623 config.production,
2624 candidate_index,
2625 )
2626 .map_err(|errors| {
2627 FallowError::config(plugins::registry::format_plugin_regex_errors(&errors))
2628 })?
2629 } else {
2630 plugins::AggregatedPluginResult::default()
2631 };
2632 if let Some(pkg) = root_pkg {
2633 append_package_file_asset_patterns(&mut result, "", pkg);
2634 }
2635 Ok(result)
2636}
2637
2638fn run_workspace_plugins(
2641 registry: &plugins::PluginRegistry,
2642 config: &ResolvedConfig,
2643 workspace_pkgs: &[LoadedWorkspacePackage],
2644 file_paths: &[std::path::PathBuf],
2645 root_active_plugins: &[String],
2646 candidate_index: Option<&plugins::registry::ConfigCandidateIndex>,
2647) -> Vec<WorkspacePluginResult> {
2648 let root_active_plugins: rustc_hash::FxHashSet<&str> =
2649 root_active_plugins.iter().map(String::as_str).collect();
2650
2651 let precompiled_matchers = registry.precompile_config_matchers();
2652 let workspace_relative_files = bucket_files_by_workspace(workspace_pkgs, file_paths);
2653
2654 workspace_pkgs
2655 .par_iter()
2656 .zip(workspace_relative_files.par_iter())
2657 .filter_map(|((ws, ws_pkg), relative_files)| {
2658 let ws_result =
2659 match registry.try_run_workspace_fast(&plugins::registry::WorkspacePluginRunInput {
2660 pkg: ws_pkg,
2661 root: &ws.root,
2662 project_root: &config.root,
2663 precompiled_config_matchers: &precompiled_matchers,
2664 relative_files,
2665 skip_config_plugins: &root_active_plugins,
2666 production_mode: config.production,
2667 candidate_index,
2668 }) {
2669 Ok(result) => result,
2670 Err(errors) => return Some(Err(errors)),
2671 };
2672 if ws_result.active_plugins.is_empty() {
2673 return None;
2674 }
2675 Some(Ok((ws_result, workspace_prefix(&config.root, &ws.root))))
2676 })
2677 .collect::<Vec<_>>()
2678}
2679
2680fn merge_workspace_plugin_results(
2683 result: &mut plugins::AggregatedPluginResult,
2684 ws_results: Vec<WorkspacePluginResult>,
2685) -> Result<(), FallowError> {
2686 let mut regex_errors = Vec::new();
2687 for ws_result in ws_results {
2688 match ws_result {
2689 Ok((mut ws_result, ws_prefix)) => {
2690 ws_result.apply_workspace_prefix(&ws_prefix);
2691 ws_result.config_patterns.clear();
2692 ws_result.script_used_packages.clear();
2693 result.merge_into(ws_result);
2694 }
2695 Err(mut errors) => regex_errors.append(&mut errors),
2696 }
2697 }
2698 if !regex_errors.is_empty() {
2699 return Err(FallowError::config(
2700 plugins::registry::format_plugin_regex_errors(®ex_errors),
2701 ));
2702 }
2703 Ok(())
2704}
2705
2706fn workspace_prefix(root: &Path, workspace_root: &Path) -> String {
2710 workspace_root
2711 .strip_prefix(root)
2712 .unwrap_or(workspace_root)
2713 .to_string_lossy()
2714 .into_owned()
2715}
2716
2717fn share_auto_imports_across_layers(
2733 result: &mut plugins::AggregatedPluginResult,
2734 config: &ResolvedConfig,
2735 workspaces: &[fallow_config::WorkspaceInfo],
2736) {
2737 if result.auto_imports.is_empty() || !result.active_plugins.iter().any(|name| name == "nuxt") {
2738 return;
2739 }
2740 let links = layer_links(config, workspaces);
2741 if links.is_empty() {
2742 return;
2743 }
2744 let mut related: rustc_hash::FxHashMap<PathBuf, Vec<PathBuf>> =
2745 rustc_hash::FxHashMap::default();
2746 for rule in &mut result.auto_imports {
2747 let declared = rule.scope.clone();
2748 for root in &declared {
2749 let roots = related.entry(root.clone()).or_insert_with(|| {
2750 let mut roots = reachable_roots(root, &links, |(app, layer)| (app, layer));
2751 roots.extend(reachable_roots(root, &links, |(app, layer)| (layer, app)));
2752 roots
2753 });
2754 for extra in roots.iter() {
2755 if !rule.scope.contains(extra) {
2756 rule.scope.push(extra.clone());
2757 }
2758 }
2759 }
2760 }
2761}
2762
2763fn reachable_roots<'a>(
2767 start: &Path,
2768 links: &'a [(PathBuf, PathBuf)],
2769 direction: impl Fn(&'a (PathBuf, PathBuf)) -> (&'a PathBuf, &'a PathBuf),
2770) -> Vec<PathBuf> {
2771 let mut found: Vec<PathBuf> = Vec::new();
2772 let mut pending: Vec<&Path> = vec![start];
2773 while let Some(current) = pending.pop() {
2774 for link in links {
2775 let (from, to) = direction(link);
2776 if from.as_path() == current && to.as_path() != start && !found.contains(to) {
2777 found.push(to.clone());
2778 pending.push(to.as_path());
2779 }
2780 }
2781 }
2782 found
2783}
2784
2785fn layer_links(
2789 config: &ResolvedConfig,
2790 workspaces: &[fallow_config::WorkspaceInfo],
2791) -> Vec<(PathBuf, PathBuf)> {
2792 let roots_by_name: rustc_hash::FxHashMap<&str, &Path> = workspaces
2793 .iter()
2794 .map(|ws| (ws.name.as_str(), ws.root.as_path()))
2795 .collect();
2796 let app_roots =
2797 std::iter::once(config.root.as_path()).chain(workspaces.iter().map(|ws| ws.root.as_path()));
2798 let mut links: Vec<(PathBuf, PathBuf)> = Vec::new();
2799 for app in app_roots {
2800 let package_layers = plugins::nuxt::package_layer_names(app)
2801 .into_iter()
2802 .filter_map(|name| {
2803 roots_by_name
2804 .get(name.as_str())
2805 .map(|root| root.to_path_buf())
2806 });
2807 for layer in plugins::nuxt::outside_layer_roots(app)
2808 .into_iter()
2809 .chain(package_layers)
2810 {
2811 let link = (app.to_path_buf(), layer);
2812 if link.0 != link.1 && !links.contains(&link) {
2813 links.push(link);
2814 }
2815 }
2816 }
2817 links
2818}
2819
2820fn gate_auto_import_entry_patterns(
2839 result: &mut plugins::AggregatedPluginResult,
2840 config: &ResolvedConfig,
2841 workspaces: &[fallow_config::WorkspaceInfo],
2842) {
2843 if !config.auto_imports {
2844 return;
2845 }
2846 if !result.active_plugins.iter().any(|name| name == "nuxt") {
2847 return;
2848 }
2849 let root_settings = plugins::nuxt::auto_import_settings(&config.root);
2850 let workspace_settings: Vec<_> = workspaces
2851 .iter()
2852 .map(|ws| {
2853 (
2854 workspace_prefix(&config.root, &ws.root),
2855 plugins::nuxt::auto_import_settings(&ws.root),
2856 )
2857 })
2858 .collect();
2859 let mut retained: Vec<plugins::PluginConfigDiagnostic> = Vec::new();
2860 result.entry_patterns.retain(|(rule, plugin)| {
2861 if plugin != "nuxt" {
2862 return true;
2863 }
2864 let setting =
2865 settings_for_entry_pattern(&root_settings, &workspace_settings, &rule.pattern);
2866 if plugins::nuxt::is_component_entry_pattern(&rule.pattern) {
2867 if !setting.components.is_custom() {
2868 return false;
2869 }
2870 record_retained_auto_import_surface(
2871 &mut retained,
2872 &setting.components_origin,
2873 "components",
2874 );
2875 return true;
2876 }
2877 if plugins::nuxt::is_script_auto_import_entry_pattern(&rule.pattern) {
2878 if !setting.scripts.is_custom() {
2879 return false;
2880 }
2881 record_retained_auto_import_surface(&mut retained, &setting.scripts_origin, "imports");
2882 return true;
2883 }
2884 true
2885 });
2886 result.config_diagnostics.extend(retained);
2887}
2888
2889const AUTO_IMPORT_PROPERTY_UNREADABLE: &str = "config-property-unreadable";
2894const AUTO_IMPORT_KEY_NOT_MODELED: &str = "key-effect-not-modeled";
2895
2896fn record_retained_auto_import_surface(
2899 retained: &mut Vec<plugins::PluginConfigDiagnostic>,
2900 origin: &plugins::nuxt::SurfaceOrigin,
2901 key: &str,
2902) {
2903 let Some(config_path) = origin.config_path.as_deref() else {
2904 return;
2905 };
2906 let reason = if origin.unreadable_property {
2907 AUTO_IMPORT_PROPERTY_UNREADABLE
2908 } else {
2909 AUTO_IMPORT_KEY_NOT_MODELED
2910 };
2911 let diagnostic = plugins::PluginConfigDiagnostic::not_modeled(config_path, "nuxt", key, reason);
2912 if !retained.contains(&diagnostic) {
2913 retained.push(diagnostic);
2914 }
2915}
2916
2917fn settings_for_entry_pattern<'a>(
2922 root: &'a plugins::nuxt::AutoImportSettings,
2923 workspaces: &'a [(String, plugins::nuxt::AutoImportSettings)],
2924 pattern: &str,
2925) -> &'a plugins::nuxt::AutoImportSettings {
2926 workspaces
2927 .iter()
2928 .filter(|(prefix, _)| {
2929 !prefix.is_empty()
2930 && pattern
2931 .strip_prefix(prefix.as_str())
2932 .is_some_and(|rest| rest.starts_with('/'))
2933 })
2934 .max_by_key(|(prefix, _)| prefix.len())
2935 .map_or(root, |(_, setting)| setting)
2936}
2937
2938fn bucket_files_by_workspace(
2939 workspace_pkgs: &[LoadedWorkspacePackage],
2940 file_paths: &[std::path::PathBuf],
2941) -> Vec<Vec<(std::path::PathBuf, String)>> {
2942 let workspace_roots: Vec<_> = workspace_pkgs
2943 .iter()
2944 .map(|(workspace, _)| workspace.root.as_path())
2945 .collect();
2946 bucket_files_by_workspace_roots(&workspace_roots, file_paths)
2947}
2948
2949fn bucket_files_by_workspace_roots(
2950 workspace_roots: &[&Path],
2951 file_paths: &[std::path::PathBuf],
2952) -> Vec<Vec<(std::path::PathBuf, String)>> {
2953 use rayon::prelude::*;
2954
2955 let mut workspace_by_root: rustc_hash::FxHashMap<&Path, usize> =
2959 rustc_hash::FxHashMap::default();
2960 for (idx, root) in workspace_roots.iter().enumerate() {
2961 workspace_by_root.entry(root).or_insert(idx);
2962 }
2963
2964 let assignments: Vec<Option<(usize, std::path::PathBuf, String)>> = file_paths
2965 .par_iter()
2966 .map(|file_path| {
2967 let idx = file_path
2968 .ancestors()
2969 .filter_map(|ancestor| workspace_by_root.get(ancestor).copied())
2970 .min()?;
2971 let relative = file_path.strip_prefix(workspace_roots[idx]).ok()?;
2972 Some((
2973 idx,
2974 file_path.clone(),
2975 relative.to_string_lossy().into_owned(),
2976 ))
2977 })
2978 .collect();
2979
2980 let mut buckets = vec![Vec::new(); workspace_roots.len()];
2981 for (idx, file_path, relative) in assignments.into_iter().flatten() {
2982 buckets[idx].push((file_path, relative));
2983 }
2984
2985 buckets
2986}
2987
2988#[doc(hidden)]
2990pub fn benchmark_bucket_files_by_workspace(
2991 workspace_roots: &[std::path::PathBuf],
2992 file_paths: &[std::path::PathBuf],
2993) -> Vec<Vec<(std::path::PathBuf, String)>> {
2994 let workspace_roots: Vec<_> = workspace_roots
2995 .iter()
2996 .map(std::path::PathBuf::as_path)
2997 .collect();
2998 bucket_files_by_workspace_roots(&workspace_roots, file_paths)
2999}
3000
3001fn collect_config_search_roots(
3002 root: &Path,
3003 file_paths: &[std::path::PathBuf],
3004) -> Vec<std::path::PathBuf> {
3005 let mut roots: rustc_hash::FxHashSet<std::path::PathBuf> = rustc_hash::FxHashSet::default();
3006 roots.insert(root.to_path_buf());
3007
3008 for file_path in file_paths {
3009 let mut current = file_path.parent();
3010 while let Some(dir) = current {
3011 if !dir.starts_with(root) {
3012 break;
3013 }
3014 roots.insert(dir.to_path_buf());
3015 if dir == root {
3016 break;
3017 }
3018 current = dir.parent();
3019 }
3020 }
3021
3022 let mut roots_vec: Vec<_> = roots.into_iter().collect();
3023 roots_vec.sort();
3024 roots_vec
3025}
3026
3027fn config_for_project(
3035 root: &Path,
3036 config_path: Option<&Path>,
3037) -> Result<(ResolvedConfig, Option<std::path::PathBuf>), FallowError> {
3038 let user_config = if let Some(path) = config_path {
3039 Some((
3040 fallow_config::FallowConfig::load(path)
3041 .map_err(|e| FallowError::config(format!("{e:#}")))?,
3042 path.to_path_buf(),
3043 ))
3044 } else {
3045 fallow_config::FallowConfig::find_and_load(root).map_err(FallowError::config)?
3046 };
3047
3048 let config = match user_config {
3049 Some((config, path)) => resolve_user_config(config, path, root)?,
3050 None => (
3051 fallow_config::FallowConfig::default().resolve(
3052 root.to_path_buf(),
3053 fallow_config::OutputFormat::Human,
3054 num_cpus(),
3055 false,
3056 true,
3057 None,
3058 ),
3059 None,
3060 ),
3061 };
3062
3063 Ok(config)
3064}
3065
3066fn resolve_user_config(
3069 mut config: fallow_config::FallowConfig,
3070 path: std::path::PathBuf,
3071 root: &Path,
3072) -> Result<(ResolvedConfig, Option<std::path::PathBuf>), FallowError> {
3073 let dead_code_production = config
3074 .production
3075 .for_analysis(fallow_config::ProductionAnalysis::DeadCode);
3076 config.production = dead_code_production.into();
3077 config
3078 .validate_resolved_boundaries(root)
3079 .map_err(|errors| {
3080 let joined = errors
3081 .iter()
3082 .map(ToString::to_string)
3083 .collect::<Vec<_>>()
3084 .join("\n - ");
3085 FallowError::config(format!("invalid boundary configuration:\n - {joined}"))
3086 })?;
3087 let packs = fallow_config::load_rule_packs(root, &config.rule_packs).map_err(|errors| {
3088 let joined = errors
3089 .iter()
3090 .map(ToString::to_string)
3091 .collect::<Vec<_>>()
3092 .join("\n - ");
3093 FallowError::config(format!("invalid rule pack:\n - {joined}"))
3094 })?;
3095 let zone_errors = fallow_config::validate_rule_pack_zones(
3096 root,
3097 &config.boundaries,
3098 &config.rule_packs,
3099 &packs,
3100 );
3101 if !zone_errors.is_empty() {
3102 let joined = zone_errors
3103 .iter()
3104 .map(ToString::to_string)
3105 .collect::<Vec<_>>()
3106 .join("\n - ");
3107 return Err(FallowError::config(format!(
3108 "invalid rule pack:\n - {joined}"
3109 )));
3110 }
3111 Ok((
3112 config.resolve(
3113 root.to_path_buf(),
3114 fallow_config::OutputFormat::Human,
3115 num_cpus(),
3116 false,
3117 true, None, ),
3120 Some(path),
3121 ))
3122}
3123
3124#[cfg_attr(
3135 not(test),
3136 allow(
3137 dead_code,
3138 reason = "config resolution fallback is exercised by session tests"
3139 )
3140)]
3141pub(crate) fn default_config(root: &Path) -> ResolvedConfig {
3142 config_for_project(root, None).map_or_else(
3143 |_| {
3144 fallow_config::FallowConfig::default().resolve(
3145 root.to_path_buf(),
3146 fallow_config::OutputFormat::Human,
3147 num_cpus(),
3148 false,
3149 true,
3150 None,
3151 )
3152 },
3153 |(config, _)| config,
3154 )
3155}
3156
3157fn num_cpus() -> usize {
3158 std::thread::available_parallelism().map_or(4, std::num::NonZeroUsize::get)
3159}
3160
3161#[cfg(test)]
3162mod tests {
3163 use super::{
3164 AnalysisSession, bucket_files_by_workspace, bucket_files_by_workspace_roots,
3165 collect_config_search_roots, credit_workspace_package_usage, default_config,
3166 format_undeclared_workspace_warning, gate_auto_import_entry_patterns,
3167 parse_analysis_modules, plugin_config_hash, resolver_options_hash,
3168 settings_for_entry_pattern, warn_undeclared_workspaces, workspace_prefix,
3169 };
3170 use std::path::{Path, PathBuf};
3171 use std::time::Instant;
3172
3173 use fallow_config::{
3174 AutoImportKind, AutoImportRule, WorkspaceDiagnostic, WorkspaceDiagnosticKind,
3175 };
3176 use fallow_types::discover::{DiscoveredFile, FileId};
3177 use fallow_types::extract::{ImportInfo, ImportedName};
3178
3179 fn plugin_result() -> crate::plugins::AggregatedPluginResult {
3180 let mut result = crate::plugins::AggregatedPluginResult::default();
3181 result.active_plugins.push("nuxt".to_string());
3182 result
3183 .path_aliases
3184 .push(("@/".to_string(), "src/".to_string()));
3185 result
3186 }
3187
3188 fn auto_import_settings(
3189 components: crate::plugins::nuxt::AutoImportSetting,
3190 ) -> crate::plugins::nuxt::AutoImportSettings {
3191 crate::plugins::nuxt::AutoImportSettings {
3192 components,
3193 scripts: crate::plugins::nuxt::AutoImportSetting::Default,
3194 components_origin: crate::plugins::nuxt::SurfaceOrigin {
3195 config_path: Some(std::path::PathBuf::from("nuxt.config.ts")),
3196 unreadable_property: false,
3197 },
3198 scripts_origin: crate::plugins::nuxt::SurfaceOrigin::default(),
3199 }
3200 }
3201
3202 #[test]
3203 fn entry_pattern_settings_prefer_the_longest_workspace_prefix() {
3204 let root = auto_import_settings(crate::plugins::nuxt::AutoImportSetting::Default);
3205 let workspaces = vec![
3206 (
3207 "packages/web".to_string(),
3208 auto_import_settings(crate::plugins::nuxt::AutoImportSetting::Custom),
3209 ),
3210 (
3211 "packages/web-admin".to_string(),
3212 auto_import_settings(crate::plugins::nuxt::AutoImportSetting::Disabled),
3213 ),
3214 ];
3215
3216 let admin = settings_for_entry_pattern(
3217 &root,
3218 &workspaces,
3219 "packages/web-admin/components/**/*.{vue,ts,tsx,js,jsx}",
3220 );
3221 assert_eq!(
3222 admin.components,
3223 crate::plugins::nuxt::AutoImportSetting::Disabled,
3224 "a sibling whose name starts with another workspace name is its own"
3225 );
3226
3227 let web = settings_for_entry_pattern(
3228 &root,
3229 &workspaces,
3230 "packages/web/components/**/*.{vue,ts,tsx,js,jsx}",
3231 );
3232 assert_eq!(
3233 web.components,
3234 crate::plugins::nuxt::AutoImportSetting::Custom
3235 );
3236 }
3237
3238 #[test]
3239 fn entry_pattern_without_a_workspace_prefix_belongs_to_the_project_root() {
3240 let root = auto_import_settings(crate::plugins::nuxt::AutoImportSetting::Custom);
3241 let workspaces = vec![(
3242 "packages/web".to_string(),
3243 auto_import_settings(crate::plugins::nuxt::AutoImportSetting::Default),
3244 )];
3245
3246 let setting = settings_for_entry_pattern(
3247 &root,
3248 &workspaces,
3249 "app/components/**/*.{vue,ts,tsx,js,jsx}",
3250 );
3251 assert_eq!(
3252 setting.components,
3253 crate::plugins::nuxt::AutoImportSetting::Custom
3254 );
3255 }
3256
3257 fn nuxt_gate_fixture(
3260 config_source: &str,
3261 ) -> (tempfile::TempDir, crate::plugins::AggregatedPluginResult) {
3262 let dir = tempfile::tempdir().expect("temp project");
3263 std::fs::write(dir.path().join("nuxt.config.ts"), config_source).expect("nuxt config");
3264 let mut result = crate::plugins::AggregatedPluginResult::default();
3265 result.active_plugins.push("nuxt".to_string());
3266 for pattern in [
3267 "app/components/**/*.{vue,ts,tsx,js,jsx}",
3268 "app/composables/*.{ts,tsx,js,jsx,mts,cts,mjs,cjs}",
3269 ] {
3270 result.entry_patterns.push((
3271 crate::plugins::PathRule::new(pattern.to_string()),
3272 "nuxt".to_string(),
3273 ));
3274 }
3275 (dir, result)
3276 }
3277
3278 fn gate(root: &Path, result: &mut crate::plugins::AggregatedPluginResult) {
3279 let config = fallow_config::FallowConfig {
3280 auto_imports: true,
3281 ..fallow_config::FallowConfig::default()
3282 };
3283 let resolved = config.resolve(
3284 root.to_path_buf(),
3285 fallow_config::OutputFormat::Json,
3286 1,
3287 false,
3288 true,
3289 None,
3290 );
3291 assert!(resolved.auto_imports, "the gate only runs when opted in");
3292 gate_auto_import_entry_patterns(result, &resolved, &[]);
3293 }
3294
3295 #[test]
3299 fn a_retained_auto_import_surface_records_one_advisory_per_surface() {
3300 let (project, mut result) =
3301 nuxt_gate_fixture("export default { components: { dirs: ['~/ui'] } };\n");
3302 gate(project.path(), &mut result);
3303
3304 let recorded: Vec<(&str, &str, &str)> = result
3305 .config_diagnostics
3306 .iter()
3307 .map(|diagnostic| {
3308 (
3309 diagnostic.plugin.as_str(),
3310 diagnostic.key.as_str(),
3311 diagnostic.reason.as_str(),
3312 )
3313 })
3314 .collect();
3315 assert_eq!(
3316 recorded,
3317 vec![("nuxt", "components", "key-effect-not-modeled")],
3318 "only the surface that kept its patterns is reported: {:?}",
3319 result.config_diagnostics
3320 );
3321 assert_eq!(
3322 result.config_diagnostics[0].config_path,
3323 project.path().join("nuxt.config.ts")
3324 );
3325 assert_eq!(
3326 result.entry_patterns.len(),
3327 1,
3328 "the modeled surface still loses its patterns: {:?}",
3329 result.entry_patterns
3330 );
3331 }
3332
3333 #[test]
3337 fn an_unreadable_top_level_property_reports_both_surfaces_with_its_own_reason() {
3338 let (project, mut result) =
3339 nuxt_gate_fixture("export default { ...baseConfig, modules: [] };\n");
3340 gate(project.path(), &mut result);
3341
3342 let recorded: Vec<(&str, &str)> = result
3343 .config_diagnostics
3344 .iter()
3345 .map(|diagnostic| (diagnostic.key.as_str(), diagnostic.reason.as_str()))
3346 .collect();
3347 assert_eq!(
3348 recorded,
3349 vec![
3350 ("components", "config-property-unreadable"),
3351 ("imports", "config-property-unreadable"),
3352 ],
3353 "{:?}",
3354 result.config_diagnostics
3355 );
3356 assert_eq!(
3357 result.entry_patterns.len(),
3358 2,
3359 "a spread keeps every gated pattern"
3360 );
3361 }
3362
3363 #[test]
3366 fn a_modeled_nuxt_config_records_no_advisory() {
3367 let (project, mut result) = nuxt_gate_fixture("export default { modules: [] };\n");
3368 gate(project.path(), &mut result);
3369 assert!(
3370 result.config_diagnostics.is_empty(),
3371 "{:?}",
3372 result.config_diagnostics
3373 );
3374 assert!(
3375 result.entry_patterns.is_empty(),
3376 "both modeled surfaces lose their patterns: {:?}",
3377 result.entry_patterns
3378 );
3379 }
3380
3381 #[test]
3382 fn a_workspace_outside_the_project_keeps_its_own_prefix() {
3383 let project_root = Path::new("/repo");
3384 let outside = Path::new("/elsewhere/app");
3385 let prefix = workspace_prefix(project_root, outside);
3386 assert_eq!(prefix, "/elsewhere/app");
3387
3388 let root = auto_import_settings(crate::plugins::nuxt::AutoImportSetting::Default);
3389 let workspaces = vec![(
3390 prefix,
3391 auto_import_settings(crate::plugins::nuxt::AutoImportSetting::Custom),
3392 )];
3393 let setting = settings_for_entry_pattern(
3394 &root,
3395 &workspaces,
3396 "/elsewhere/app/components/**/*.{vue,ts,tsx,js,jsx}",
3397 );
3398 assert_eq!(
3399 setting.components,
3400 crate::plugins::nuxt::AutoImportSetting::Custom,
3401 "an out-of-tree workspace is classified on its own config"
3402 );
3403 }
3404
3405 #[test]
3406 fn commonjs_internal_import_credits_workspace_package_usage() {
3407 let workspace = fallow_config::WorkspaceInfo {
3408 root: PathBuf::from("/repo/packages/shared"),
3409 name: "@repo/shared".to_string(),
3410 is_internal_dependency: true,
3411 };
3412 let resolved = vec![crate::resolve::ResolvedModule {
3413 file_id: FileId(0),
3414 resolved_imports: vec![crate::resolve::ResolvedImport {
3415 info: ImportInfo {
3416 source: "@repo/shared".to_string(),
3417 imported_name: ImportedName::Namespace,
3418 local_name: "shared".to_string(),
3419 is_type_only: false,
3420 is_type_only_star: false,
3421 from_style: false,
3422 span: oxc_span::Span::new(0, 20),
3423 source_span: oxc_span::Span::new(8, 20),
3424 },
3425 target: crate::resolve::ResolveResult::CommonJsInternalModule(FileId(1)),
3426 }],
3427 ..crate::resolve::ResolvedModule::default()
3428 }];
3429 let mut graph = crate::graph::ModuleGraph::build(&[], &[], &[]);
3430
3431 credit_workspace_package_usage(&mut graph, &resolved, &[workspace]);
3432
3433 assert_eq!(
3434 graph.package_usage.get("@repo/shared"),
3435 Some(&vec![FileId(0)])
3436 );
3437 }
3438
3439 #[test]
3442 fn graph_cache_resolver_hash_is_independent_of_the_project_root() {
3443 let dir_a = tempfile::tempdir().expect("create temp dir a");
3444 let dir_b = tempfile::tempdir().expect("create temp dir b");
3445 let config_a = session_config(dir_a.path());
3446 let config_b = session_config(dir_b.path());
3447
3448 assert_eq!(
3449 resolver_options_hash(&config_a),
3450 resolver_options_hash(&config_b),
3451 "root identity is handled separately from resolver options"
3452 );
3453 }
3454
3455 #[test]
3458 fn graph_cache_manifest_still_rejects_a_different_file_set() {
3459 let dir_a = tempfile::tempdir().expect("create temp dir a");
3460 let mode = crate::graph_cache::GraphCacheMode::new(1, 2, 3);
3461 let files_a = [crate::discover::DiscoveredFile {
3462 id: crate::discover::FileId(0),
3463 path: dir_a.path().join("src/a.ts"),
3464 size_bytes: 1,
3465 }];
3466 let files_b = [crate::discover::DiscoveredFile {
3467 id: crate::discover::FileId(0),
3468 path: dir_a.path().join("src/b.ts"),
3469 size_bytes: 1,
3470 }];
3471
3472 let manifest_a = crate::graph_cache::GraphCacheManifest::from_discovered_files(
3473 dir_a.path(),
3474 &files_a,
3475 mode,
3476 |_| 7,
3477 );
3478 let manifest_b = crate::graph_cache::GraphCacheManifest::from_discovered_files(
3479 dir_a.path(),
3480 &files_b,
3481 mode,
3482 |_| 7,
3483 );
3484
3485 assert_eq!(
3486 manifest_a.classify_resolution_mismatch(&manifest_b),
3487 Some(fallow_types::cache_rejection::CacheRejection::FileSetChanged)
3488 );
3489 }
3490
3491 #[test]
3492 fn graph_cache_resolver_hash_includes_resolve_conditions() {
3493 let dir = tempfile::tempdir().expect("create temp dir");
3494 let config_a = session_config(dir.path());
3495 let mut config_b = session_config(dir.path());
3496 config_b.resolve.conditions.push("react-server".to_string());
3497
3498 assert_ne!(
3499 resolver_options_hash(&config_a),
3500 resolver_options_hash(&config_b),
3501 "resolve condition changes must invalidate the graph cache"
3502 );
3503 }
3504
3505 #[test]
3506 fn graph_cache_plugin_hash_includes_auto_imports() {
3507 let mut without_auto_import = plugin_result();
3508 let mut with_auto_import = plugin_result();
3509 with_auto_import.auto_imports.push(AutoImportRule::new(
3510 "useCounter".to_string(),
3511 PathBuf::from("/project/composables/useCounter.ts"),
3512 AutoImportKind::Named,
3513 ));
3514
3515 assert_ne!(
3516 plugin_config_hash(&without_auto_import, std::path::Path::new("")),
3517 plugin_config_hash(&with_auto_import, std::path::Path::new("")),
3518 "auto-import edge changes must invalidate the graph cache"
3519 );
3520
3521 without_auto_import.auto_imports.push(AutoImportRule::new(
3522 "useCounter".to_string(),
3523 PathBuf::from("/project/composables/useCounter.ts"),
3524 AutoImportKind::Default,
3525 ));
3526 assert_ne!(
3527 plugin_config_hash(&without_auto_import, std::path::Path::new("")),
3528 plugin_config_hash(&with_auto_import, std::path::Path::new("")),
3529 "auto-import kind changes must invalidate the graph cache"
3530 );
3531
3532 let mut scoped = with_auto_import.auto_imports.clone();
3533 scoped[0].scope = vec![PathBuf::from("/project/packages/a")];
3534 let mut with_scoped_auto_import = plugin_result();
3535 with_scoped_auto_import.auto_imports = scoped;
3536 assert_ne!(
3537 plugin_config_hash(&with_scoped_auto_import, std::path::Path::new("")),
3538 plugin_config_hash(&with_auto_import, std::path::Path::new("")),
3539 "auto-import scope changes must invalidate the graph cache"
3540 );
3541 }
3542
3543 #[test]
3544 fn graph_cache_plugin_hash_includes_style_and_static_mappings() {
3545 let base = plugin_result();
3546 let mut with_scss = base.clone();
3547 with_scss
3548 .scss_include_paths
3549 .push(PathBuf::from("/project/styles"));
3550 assert_ne!(
3551 plugin_config_hash(&base, std::path::Path::new("")),
3552 plugin_config_hash(&with_scss, std::path::Path::new("")),
3553 "SCSS include path changes must invalidate the graph cache"
3554 );
3555
3556 let mut with_static_dir = base.clone();
3557 with_static_dir
3558 .static_dir_mappings
3559 .push((PathBuf::from("/project/public"), "/".to_string()));
3560 assert_ne!(
3561 plugin_config_hash(&base, std::path::Path::new("")),
3562 plugin_config_hash(&with_static_dir, std::path::Path::new("")),
3563 "static directory mapping changes must invalidate the graph cache"
3564 );
3565 }
3566
3567 fn diag(root: &Path, relative: &str) -> WorkspaceDiagnostic {
3568 WorkspaceDiagnostic::new(
3569 root,
3570 root.join(relative),
3571 WorkspaceDiagnosticKind::UndeclaredWorkspace,
3572 )
3573 }
3574
3575 fn session_config(root: &Path) -> fallow_config::ResolvedConfig {
3576 let mut config = default_config(root);
3577 config.no_cache = true;
3578 config.quiet = true;
3579 config
3580 }
3581
3582 fn write_session_fixture(root: &Path) {
3583 let src = root.join("src");
3584 std::fs::create_dir_all(&src).expect("create src");
3585 std::fs::write(
3586 root.join("package.json"),
3587 r#"{"name":"session-fixture","type":"module"}"#,
3588 )
3589 .expect("write package json");
3590 std::fs::write(
3591 src.join("index.ts"),
3592 "import { used } from './used';\nconsole.log(used);\n",
3593 )
3594 .expect("write index");
3595 std::fs::write(src.join("used.ts"), "export const used = 1;\n").expect("write used");
3596 }
3597
3598 #[test]
3599 fn analysis_session_discovers_project_files() {
3600 let dir = tempfile::tempdir().expect("create temp dir");
3601 write_session_fixture(dir.path());
3602 let config = session_config(dir.path());
3603
3604 let session = AnalysisSession::new(&config).expect("session setup should succeed");
3605
3606 assert!(
3607 session
3608 .files()
3609 .iter()
3610 .any(|file| file.path.ends_with("src/index.ts")),
3611 "session should own discovered project files"
3612 );
3613 assert_eq!(session.workspaces().len(), 0);
3614 }
3615
3616 #[test]
3617 fn direct_core_parse_surfaces_source_read_failure_diagnostic() {
3618 let project = tempfile::tempdir().expect("create project");
3619 let root = project.path();
3620 let paths = ["a.ts", "b.ts", "c.ts"].map(|name| root.join(name));
3621 for (index, path) in paths.iter().enumerate() {
3622 std::fs::write(path, format!("export const value{index} = {index};\n"))
3623 .expect("write source");
3624 }
3625 let files: Vec<DiscoveredFile> = paths
3626 .iter()
3627 .enumerate()
3628 .map(|(index, path)| DiscoveredFile {
3629 id: FileId(u32::try_from(index).expect("test index fits u32")),
3630 path: path.clone(),
3631 size_bytes: std::fs::metadata(path).expect("source metadata").len(),
3632 })
3633 .collect();
3634 std::fs::remove_file(&paths[1]).expect("remove source after discovery");
3635 let config = session_config(root);
3636
3637 let parsed = parse_analysis_modules(&config, &files, false, Instant::now());
3638
3639 assert_eq!(
3640 parsed
3641 .modules
3642 .iter()
3643 .map(|module| module.file_id)
3644 .collect::<Vec<_>>(),
3645 vec![FileId(0), FileId(2)]
3646 );
3647 let diagnostics = fallow_config::workspace_diagnostics_for(root);
3648 let diagnostic = diagnostics
3649 .iter()
3650 .find(|diagnostic| diagnostic.kind.id() == "source-read-failure")
3651 .expect("source read failure diagnostic");
3652 assert_eq!(diagnostic.path, paths[1]);
3653 assert!(matches!(
3654 diagnostic.kind,
3655 WorkspaceDiagnosticKind::SourceReadFailure { .. }
3656 ));
3657 }
3658
3659 #[test]
3660 fn analysis_session_parses_owned_modules() {
3661 let dir = tempfile::tempdir().expect("create temp dir");
3662 write_session_fixture(dir.path());
3663 let config = session_config(dir.path());
3664
3665 let session = AnalysisSession::new(&config).expect("session setup should succeed");
3666 let parsed = session.parse_modules(false);
3667
3668 assert!(
3669 parsed
3670 .modules
3671 .iter()
3672 .any(|module| session.files()[module.file_id.0 as usize]
3673 .path
3674 .ends_with("src/index.ts")),
3675 "session parsing should return modules keyed to session files"
3676 );
3677 }
3678
3679 #[test]
3680 fn undeclared_workspace_warning_is_singular_for_one_path() {
3681 let root = Path::new("/repo");
3682 let warning = format_undeclared_workspace_warning(root, &[diag(root, "packages/api")])
3683 .expect("warning should be rendered");
3684
3685 assert_eq!(
3686 warning,
3687 "1 directory with package.json is not declared as a workspace: packages/api. Add that path to package.json workspaces or pnpm-workspace.yaml if it should be analyzed as a workspace."
3688 );
3689 }
3690
3691 #[test]
3692 fn undeclared_workspace_warning_summarizes_many_paths() {
3693 let root = PathBuf::from("/repo");
3694 let diagnostics = [
3695 "examples/a",
3696 "examples/b",
3697 "examples/c",
3698 "examples/d",
3699 "examples/e",
3700 "examples/f",
3701 ]
3702 .into_iter()
3703 .map(|path| diag(&root, path))
3704 .collect::<Vec<_>>();
3705
3706 let warning = format_undeclared_workspace_warning(&root, &diagnostics)
3707 .expect("warning should be rendered");
3708
3709 assert_eq!(
3710 warning,
3711 "6 directories with package.json are not declared as workspaces: examples/a, examples/b, examples/c, examples/d, examples/e (and 1 more). Add those paths to package.json workspaces or pnpm-workspace.yaml if they should be analyzed as workspaces."
3712 );
3713 }
3714
3715 #[test]
3716 fn collect_config_search_roots_includes_file_ancestors_once() {
3717 let root = PathBuf::from("/repo");
3718 let search_roots = collect_config_search_roots(
3719 &root,
3720 &[
3721 root.join("apps/query/src/main.ts"),
3722 root.join("packages/shared/lib/index.ts"),
3723 ],
3724 );
3725
3726 assert_eq!(
3727 search_roots,
3728 vec![
3729 root.clone(),
3730 root.join("apps"),
3731 root.join("apps/query"),
3732 root.join("apps/query/src"),
3733 root.join("packages"),
3734 root.join("packages/shared"),
3735 root.join("packages/shared/lib"),
3736 ]
3737 );
3738 }
3739
3740 #[test]
3741 fn bucket_files_by_workspace_uses_workspace_relative_paths() {
3742 let root = PathBuf::from("/repo");
3743 let ui = fallow_config::WorkspaceInfo {
3744 root: root.join("apps/ui"),
3745 name: "ui".to_string(),
3746 is_internal_dependency: false,
3747 };
3748 let api = fallow_config::WorkspaceInfo {
3749 root: root.join("apps/api"),
3750 name: "api".to_string(),
3751 is_internal_dependency: false,
3752 };
3753 let workspace_pkgs = vec![
3754 (
3755 ui,
3756 fallow_config::PackageJson {
3757 name: Some("ui".to_string()),
3758 ..Default::default()
3759 },
3760 ),
3761 (
3762 api,
3763 fallow_config::PackageJson {
3764 name: Some("api".to_string()),
3765 ..Default::default()
3766 },
3767 ),
3768 ];
3769 let files = vec![
3770 root.join("apps/ui/vite.config.ts"),
3771 root.join("apps/ui/src/main.ts"),
3772 root.join("apps/api/src/server.ts"),
3773 root.join("tools/build.ts"),
3774 ];
3775
3776 let buckets = bucket_files_by_workspace(&workspace_pkgs, &files);
3777
3778 assert_eq!(
3779 buckets[0],
3780 vec![
3781 (
3782 root.join("apps/ui/vite.config.ts"),
3783 "vite.config.ts".to_string()
3784 ),
3785 (root.join("apps/ui/src/main.ts"), "src/main.ts".to_string()),
3786 ]
3787 );
3788 assert_eq!(
3789 buckets[1],
3790 vec![(
3791 root.join("apps/api/src/server.ts"),
3792 "src/server.ts".to_string()
3793 )]
3794 );
3795 }
3796
3797 #[test]
3798 fn workspace_bucketing_preserves_first_declared_match_and_file_order() {
3799 let root = PathBuf::from("/repo");
3800 let parent = root.join("apps");
3801 let child = parent.join("web");
3802 let nested_first = child.join("src/first.ts");
3803 let nested_second = child.join("src/second.ts");
3804 let unmatched = root.join("tools/build.ts");
3805 let files = vec![nested_first.clone(), unmatched, nested_second.clone()];
3806
3807 let normalize = |bucket: &[(PathBuf, String)]| -> Vec<(PathBuf, String)> {
3812 bucket
3813 .iter()
3814 .map(|(path, rel)| (path.clone(), rel.replace('\\', "/")))
3815 .collect()
3816 };
3817
3818 let parent_first = bucket_files_by_workspace_roots(&[&parent, &child, &child], &files);
3819 assert_eq!(
3820 normalize(&parent_first[0]),
3821 vec![
3822 (nested_first.clone(), "web/src/first.ts".to_string()),
3823 (nested_second.clone(), "web/src/second.ts".to_string()),
3824 ]
3825 );
3826 assert!(parent_first[1].is_empty());
3827 assert!(parent_first[2].is_empty());
3828
3829 let child_first = bucket_files_by_workspace_roots(&[&child, &parent], &files);
3830 assert_eq!(
3831 normalize(&child_first[0]),
3832 vec![
3833 (nested_first, "src/first.ts".to_string()),
3834 (nested_second, "src/second.ts".to_string()),
3835 ]
3836 );
3837 assert!(child_first[1].is_empty());
3838 }
3839
3840 #[test]
3841 fn warn_undeclared_workspaces_suppresses_paths_already_flagged_as_malformed() {
3842 let dir = tempfile::tempdir().expect("create temp dir");
3843 let pkg_good = dir.path().join("packages").join("good");
3844 let pkg_bad = dir.path().join("packages").join("bad");
3845 std::fs::create_dir_all(&pkg_good).unwrap();
3846 std::fs::create_dir_all(&pkg_bad).unwrap();
3847 std::fs::write(
3848 dir.path().join("package.json"),
3849 r#"{"workspaces": ["packages/*"]}"#,
3850 )
3851 .unwrap();
3852 std::fs::write(pkg_good.join("package.json"), r#"{"name": "good"}"#).unwrap();
3853 std::fs::write(pkg_bad.join("package.json"), r"{,").unwrap();
3854
3855 let (workspaces, diagnostics) = fallow_config::discover_workspaces_with_diagnostics(
3856 dir.path(),
3857 &fallow_config::IgnorePatternSet::empty(),
3858 )
3859 .expect("root package.json is valid");
3860 assert_eq!(workspaces.len(), 1, "only the valid workspace discovers");
3861 fallow_config::stash_workspace_diagnostics(dir.path(), diagnostics);
3862
3863 warn_undeclared_workspaces(
3864 dir.path(),
3865 &workspaces,
3866 &fallow_config::IgnorePatternSet::empty(),
3867 false,
3868 );
3869
3870 let diagnostics = fallow_config::workspace_diagnostics_for(dir.path());
3871 let mut malformed = 0;
3872 let mut undeclared_for_bad = 0;
3873 for diag in &diagnostics {
3874 if matches!(
3875 diag.kind,
3876 WorkspaceDiagnosticKind::MalformedPackageJson { .. }
3877 ) && diag.path.ends_with("bad")
3878 {
3879 malformed += 1;
3880 }
3881 if matches!(diag.kind, WorkspaceDiagnosticKind::UndeclaredWorkspace)
3882 && diag.path.ends_with("bad")
3883 {
3884 undeclared_for_bad += 1;
3885 }
3886 }
3887 assert_eq!(
3888 malformed, 1,
3889 "expected one MalformedPackageJson for packages/bad: {diagnostics:?}"
3890 );
3891 assert_eq!(
3892 undeclared_for_bad, 0,
3893 "warn_undeclared_workspaces must NOT re-flag a path that already \
3894 carries MalformedPackageJson; got duplicates: {diagnostics:?}"
3895 );
3896 }
3897}