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