Skip to main content

fallow_engine/
results.rs

1//! Internal analysis result contracts re-exported through typed engine modules.
2
3#![allow(
4    unused_imports,
5    reason = "private result contract aggregation re-exports types consumed through typed engine modules"
6)]
7
8use std::path::PathBuf;
9use std::sync::Arc;
10use std::time::Duration;
11
12use fallow_config::ResolvedConfig;
13use fallow_output::{HealthGrouping, HealthReport, HealthTimings};
14use fallow_types::discover::DiscoveredFile;
15use fallow_types::extract::ModuleInfo;
16use fallow_types::source_fingerprint::SourceFingerprint;
17use fallow_types::workspace::WorkspaceDiagnostic;
18use rustc_hash::{FxHashMap, FxHashSet};
19
20use crate::{duplicates, module_graph, trace};
21
22pub use crate::security::{
23    derive_security_severity, enable_security_rules, resolve_security_finding_severity,
24    security_catalogue_title, security_rule_id, security_rules_can_error,
25};
26pub use fallow_types::output_dead_code::{
27    AbsentComponentPropFinding, BoundaryCallViolationFinding, BoundaryCoverageViolationFinding,
28    BoundaryViolationFinding, CircularDependencyFinding, DuplicateExportFinding,
29    DuplicatePropShapeFinding, DynamicSegmentNameConflictFinding, EmptyCatalogGroupFinding,
30    InvalidClientExportFinding, MisconfiguredDependencyOverrideFinding, MisplacedDirectiveFinding,
31    MixedClientServerBarrelFinding, PackageCycleFinding, PolicyViolationFinding,
32    PrivateTypeLeakFinding, PropDrillingChainFinding, ReExportCycleFinding, RouteCollisionFinding,
33    TestOnlyDependencyFinding, ThinWrapperFinding, TypeOnlyDependencyFinding,
34    UnlistedDependencyFinding, UnprovidedInjectFinding, UnrenderedComponentFinding,
35    UnresolvedCatalogReferenceFinding, UnresolvedImportFinding, UnusedCatalogEntryFinding,
36    UnusedClassMemberFinding, UnusedComponentEmitFinding, UnusedComponentInputFinding,
37    UnusedComponentOutputFinding, UnusedComponentPropFinding, UnusedDependencyFinding,
38    UnusedDependencyOverrideFinding, UnusedDevDependencyFinding, UnusedEnumMemberFinding,
39    UnusedExportFinding, UnusedFileFinding, UnusedLoadDataKeyFinding, UnusedNamespaceMemberFinding,
40    UnusedOptionalDependencyFinding, UnusedProtectedClassMemberFinding, UnusedServerActionFinding,
41    UnusedStoreMemberFinding, UnusedSvelteEventFinding, UnusedTypeFinding,
42};
43pub use fallow_types::output_dead_code::{
44    UnproducedCatchTagFinding, UnusedEffectLayerFinding, UnusedTaggedErrorFinding,
45};
46pub use fallow_types::results::{
47    AbsentComponentProp, ActiveSuppression, AnalysisResults, BoundaryCallViolation,
48    BoundaryCoverageViolation, BoundaryViolation, CircularDependency, CircularDependencyEdge,
49    ComponentPropCallSite, DependencyLocation, DependencyOverrideMisconfigReason,
50    DependencyOverrideSource, DuplicateExport, DuplicateLocation, DuplicatePropShape,
51    DuplicatePropShapeMember, DynamicSegmentNameConflict, EmptyCatalogGroup, EntryPointSummary,
52    ExportUsage, FeatureFlag, FlagConfidence, FlagKind, ImportSite, InvalidClientExport,
53    MisconfiguredDependencyOverride, MisplacedDirective, MixedClientServerBarrel, PackageCycle,
54    PackageCycleEdge, PolicyRuleKind, PolicyViolation, PolicyViolationSeverity, PrivateTypeLeak,
55    PropDrillHop, PropDrillingChain, ReExportCycle, ReExportCycleKind, ReactComponentIntel,
56    ReactHookSummary, ReactPropDrill, ReactPropIntel, ReferenceLocation, RenderFanInComponent,
57    RenderFanInMetric, RouteCollision, SecurityAttackSurfaceEntry, SecurityCandidate,
58    SecurityCandidateBoundary, SecurityCandidateSink, SecurityDeadCodeContext,
59    SecurityDeadCodeKind, SecurityDefensiveBoundary, SecurityDefensiveControl, SecurityFinding,
60    SecurityFindingKind, SecurityNetworkContext, SecurityReachability, SecurityRuntimeContext,
61    SecurityRuntimeState, SecuritySeverity, SecurityTaintFlow, SecurityUnresolvedCalleeDiagnostic,
62    SecurityZoneCrossing, StaleSuppression, SuppressionOrigin, TaintConfidence, TaintEndpoint,
63    TaintPath, TestOnlyDependency, ThinWrapper, TraceHop, TraceHopRole, TypeOnlyDependency,
64    UnlistedDependency, UnprovidedInject, UnrenderedComponent, UnresolvedCatalogReference,
65    UnresolvedImport, UnusedCatalogEntry, UnusedComponentEmit, UnusedComponentInput,
66    UnusedComponentOutput, UnusedComponentProp, UnusedDependency, UnusedDependencyOverride,
67    UnusedExport, UnusedFile, UnusedLoadDataKey, UnusedMember, UnusedServerAction,
68    UnusedSvelteEvent,
69};
70pub use fallow_types::results::{
71    CandidateArgument, ConstantParameter, ConstantParameterCallSite, ConstantParameterCandidates,
72    ConstantParameterEvidence, ConstantParameterFinding, ConstantParameterReason,
73    ConstantParameterValue, ConstantParameterValueKind, MethodClassCandidate,
74    UnusedDefaultCandidate, constant_parameter_explanation,
75};
76pub use fallow_types::results::{
77    EffectCatchSite, EffectLayerKind, UnproducedCatchTag, UnusedEffectLayer, UnusedTaggedError,
78};
79
80/// Typed dead-code analysis result.
81#[derive(Debug)]
82pub struct DeadCodeAnalysis {
83    /// Findings across all dead-code categories.
84    pub results: AnalysisResults,
85}
86
87/// Typed dead-code analysis result with per-file source hashes.
88#[derive(Debug)]
89pub struct DeadCodeAnalysisWithHashes {
90    /// Findings across all dead-code categories.
91    pub results: AnalysisResults,
92    /// Per-file source content hashes for cache invalidation.
93    pub file_hashes: FxHashMap<PathBuf, u64>,
94}
95
96/// Typed dead-code analysis result with retained parser artifacts.
97#[derive(Debug)]
98pub struct DeadCodeAnalysisOutput {
99    /// Findings across all dead-code categories.
100    pub results: AnalysisResults,
101    /// Parsed modules retained for reuse, when the caller asked for them.
102    pub modules: Option<Vec<ModuleInfo>>,
103    /// Discovered files retained for reuse, when the caller asked for them.
104    pub files: Option<Vec<DiscoveredFile>>,
105}
106
107/// Typed dead-code analysis result with all reusable pipeline artifacts.
108#[derive(Debug)]
109pub struct DeadCodeAnalysisArtifacts {
110    /// Findings across all dead-code categories.
111    pub results: AnalysisResults,
112    /// Per-phase pipeline timings, when the run measured them.
113    pub timings: Option<trace::PipelineTimings>,
114    /// Retained module graph for downstream passes (health, trace, impact).
115    pub graph: Option<module_graph::RetainedModuleGraph>,
116    /// Parsed modules retained for reuse, when the caller asked for them.
117    pub modules: Option<Vec<ModuleInfo>>,
118    /// Discovered files retained for reuse, when the caller asked for them.
119    pub files: Option<Vec<DiscoveredFile>>,
120    /// Package names referenced from package.json scripts, which keeps those
121    /// dependencies from being reported unused.
122    pub script_used_packages: FxHashSet<String>,
123    /// Which configs name which files and dependency names, for the trace
124    /// output.
125    pub trace_provenance: trace::TraceProvenance,
126    /// Per-file source content hashes for cache invalidation.
127    pub file_hashes: FxHashMap<PathBuf, u64>,
128}
129
130/// Shared parser artifacts for workspace-internal session consumers.
131///
132/// This additive contract lets internal callers retain immutable parsed
133/// modules without deep-cloning the session cache. Stable owned APIs continue
134/// to return [`DeadCodeAnalysisArtifacts`].
135#[doc(hidden)]
136#[derive(Debug)]
137pub struct SharedDeadCodeAnalysisArtifacts {
138    pub results: AnalysisResults,
139    pub timings: Option<trace::PipelineTimings>,
140    pub graph: Option<module_graph::RetainedModuleGraph>,
141    pub modules: Option<Arc<[ModuleInfo]>>,
142    pub files: Option<Vec<DiscoveredFile>>,
143    pub script_used_packages: FxHashSet<String>,
144    pub trace_provenance: trace::TraceProvenance,
145    pub file_hashes: FxHashMap<PathBuf, u64>,
146}
147
148impl SharedDeadCodeAnalysisArtifacts {
149    /// Convert shared parser artifacts to the stable owned result contract.
150    #[must_use]
151    pub fn into_owned(self) -> DeadCodeAnalysisArtifacts {
152        let modules = self.modules.map(|modules| {
153            let mut owned = modules.to_vec();
154            for module in &mut owned {
155                module.release_resolution_payload();
156            }
157            owned
158        });
159        DeadCodeAnalysisArtifacts {
160            results: self.results,
161            timings: self.timings,
162            graph: self.graph,
163            modules,
164            files: self.files,
165            script_used_packages: self.script_used_packages,
166            trace_provenance: self.trace_provenance,
167            file_hashes: self.file_hashes,
168        }
169    }
170}
171
172/// Typed project analysis result combining dead-code and duplication outputs.
173#[derive(Debug)]
174pub struct ProjectAnalysisOutput {
175    /// Dead-code findings with optionally retained parser artifacts.
176    pub dead_code: DeadCodeAnalysisOutput,
177    /// Duplication report for the same file set.
178    pub duplication: duplicates::DuplicationReport,
179}
180
181/// Typed project analysis result with reusable session artifacts.
182#[derive(Debug)]
183pub struct ProjectAnalysisArtifacts {
184    /// Dead-code findings with all reusable pipeline artifacts.
185    pub dead_code: DeadCodeAnalysisArtifacts,
186    /// Duplication report for the same file set.
187    pub duplication: duplicates::DuplicationReport,
188    /// Diff scope the run was limited to, when one was resolved.
189    pub changed_files: Option<FxHashSet<PathBuf>>,
190    /// Per-file source fingerprints for downstream cache invalidation.
191    pub source_fingerprints: Option<FxHashMap<PathBuf, SourceFingerprint>>,
192}
193
194impl ProjectAnalysisArtifacts {
195    /// Drop retained reuse-only artifacts and return the stable project output.
196    #[must_use]
197    pub fn into_output(self) -> ProjectAnalysisOutput {
198        ProjectAnalysisOutput {
199            dead_code: DeadCodeAnalysisOutput {
200                results: self.dead_code.results,
201                modules: self.dead_code.modules,
202                files: self.dead_code.files,
203            },
204            duplication: self.duplication,
205        }
206    }
207}
208
209/// Typed duplication analysis result.
210#[derive(Debug)]
211pub struct DuplicationAnalysis {
212    pub report: duplicates::DuplicationReport,
213    pub default_ignore_skips: duplicates::DefaultIgnoreSkips,
214}
215
216/// Typed health analysis result shared by CLI, API, NAPI, and future embedders.
217///
218/// The result contract belongs at the engine boundary so downstream callers can
219/// depend on a command-neutral shape.
220#[derive(Debug)]
221pub struct HealthAnalysisResult<GroupResolver = ()> {
222    /// The assembled health report for the active run scope.
223    pub report: HealthReport,
224    /// Optional TypeScript semantic metadata for advisory health overlays.
225    pub type_aware_meta: Option<fallow_types::envelope::TypeAwareMeta>,
226    /// Per-file branching totals, keyed by absolute path.
227    ///
228    /// Threshold-blind and suppression-blind, unlike `report`, which holds only
229    /// units that breached a threshold. The audit compares this map across the
230    /// base and head revisions; nothing else reads it, and it is not
231    /// serialized, so it carries no schema version.
232    pub branching_by_file: crate::health::BranchingByFile,
233    /// Per-group health output when grouping is active.
234    ///
235    /// `None` for the default run; `Some` for any grouped invocation. The
236    /// top-level report reflects the active run scope; consumers that want
237    /// per-group metrics read from `grouping.groups`.
238    pub grouping: Option<HealthGrouping>,
239    /// Optional grouping resolver retained by callers that need to tag findings
240    /// after analysis without rediscovering ownership or package metadata.
241    pub group_resolver: Option<GroupResolver>,
242    /// Resolved config the run executed under.
243    pub config: ResolvedConfig,
244    /// Diagnostics from workspace discovery (undeclared or invalid members).
245    pub workspace_diagnostics: Vec<WorkspaceDiagnostic>,
246    /// Total wall time of the health run.
247    pub elapsed: Duration,
248    /// Per-phase timings, when the run measured them.
249    pub timings: Option<HealthTimings>,
250    /// True when the coverage gaps section produced findings.
251    pub coverage_gaps_has_findings: bool,
252    /// True when coverage gap findings should fail the run (the gate is
253    /// enforced rather than advisory).
254    pub should_fail_on_coverage_gaps: bool,
255    /// The changed files the run analyzed, when a changed-file set narrowed
256    /// it: the files of that set that discovery kept. `None` when the run was
257    /// not narrowed by changed files. Callers size a `changed-since` scope
258    /// from it.
259    pub changed_files_analyzed: Option<Vec<std::path::PathBuf>>,
260}
261
262impl<GroupResolver> HealthAnalysisResult<GroupResolver> {
263    /// Drop presentation-only grouping resolver state while preserving the
264    /// command-neutral health analysis payload.
265    #[must_use]
266    pub fn without_group_resolver(self) -> HealthAnalysisResult<()> {
267        HealthAnalysisResult {
268            report: self.report,
269            type_aware_meta: self.type_aware_meta,
270            branching_by_file: self.branching_by_file,
271            grouping: self.grouping,
272            group_resolver: None,
273            config: self.config,
274            workspace_diagnostics: self.workspace_diagnostics,
275            elapsed: self.elapsed,
276            timings: self.timings,
277            coverage_gaps_has_findings: self.coverage_gaps_has_findings,
278            should_fail_on_coverage_gaps: self.should_fail_on_coverage_gaps,
279            changed_files_analyzed: self.changed_files_analyzed,
280        }
281    }
282}
283
284#[cfg(test)]
285mod tests {
286    use crate::project_config::{ProjectConfigOptions, config_for_project_analysis};
287    use fallow_config::ProductionAnalysis;
288    use fallow_types::output_format::OutputFormat;
289
290    use super::*;
291
292    #[test]
293    fn health_analysis_result_drops_presentation_resolver() {
294        let project = tempfile::tempdir().expect("temp dir");
295        let project_config = config_for_project_analysis(
296            project.path(),
297            None,
298            ProjectConfigOptions {
299                output: OutputFormat::Json,
300                no_cache: true,
301                threads: 1,
302                production_override: None,
303                quiet: true,
304                analysis: ProductionAnalysis::Health,
305                allow_remote_extends: false,
306            },
307        )
308        .expect("project config loads");
309        let result = HealthAnalysisResult {
310            report: HealthReport::default(),
311            branching_by_file: crate::health::BranchingByFile::default(),
312            grouping: None,
313            group_resolver: Some("resolver"),
314            config: project_config.config,
315            workspace_diagnostics: Vec::new(),
316            elapsed: Duration::from_millis(7),
317            timings: None,
318            coverage_gaps_has_findings: true,
319            should_fail_on_coverage_gaps: true,
320            type_aware_meta: None,
321            changed_files_analyzed: None,
322        };
323
324        let neutral = result.without_group_resolver();
325
326        assert!(neutral.group_resolver.is_none());
327        assert_eq!(neutral.elapsed, Duration::from_millis(7));
328        assert!(neutral.coverage_gaps_has_findings);
329        assert!(neutral.should_fail_on_coverage_gaps);
330    }
331
332    #[test]
333    fn engine_result_surface_uses_explicit_reexports() {
334        let source = include_str!("results.rs");
335        let output_dead_code_wildcard = concat!("pub use fallow_types::output_dead_code::", "*");
336        let results_wildcard = concat!("pub use fallow_types::results::", "*");
337
338        assert!(!source.contains(output_dead_code_wildcard));
339        assert!(!source.contains(results_wildcard));
340    }
341}