Skip to main content

fallow_types/
trace.rs

1//! Shared trace output contracts for analysis and integration surfaces.
2
3use std::path::{Path, PathBuf};
4
5use rustc_hash::{FxHashMap, FxHashSet};
6use serde::Serialize;
7
8use crate::cache_rejection::CacheRejection;
9use crate::duplicates::{CloneInstance, RefactoringSuggestion};
10use crate::semantic::SemanticNamespace;
11use crate::serde_path;
12use crate::trace_chain::StarExportAmbiguity;
13
14/// Result of tracing an export: why it is considered used or unused.
15#[derive(Debug, Serialize)]
16#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
17pub struct ExportTrace {
18    /// The file containing the export.
19    #[serde(serialize_with = "serde_path::serialize")]
20    pub file: PathBuf,
21    /// The export name being traced.
22    pub export_name: String,
23    /// Namespace whose references are listed for the traced export. The
24    /// preferred lane wins whenever it carries a reference: `value` for a
25    /// value export, `type` for a type-only one. When the preferred lane
26    /// carries none and the other lane resolves to the same declaration, the
27    /// other lane's references are listed and this field names it, so a value
28    /// export whose only credit is a bound `import type` reports `type` with
29    /// `is_used: true`. `is_used` and `direct_references` follow the listed
30    /// lane only, and only reachable reference sources can credit it. Legal
31    /// declaration merges share one declaration group across lanes, including
32    /// an `interface` next to a same-name `class` and a `class` next to a
33    /// same-name `namespace`, so references to either lane credit the merged
34    /// declaration. Distinct same-name declarations outside a merge remain
35    /// separate and keep the preferred lane. `semantic.target.namespace`
36    /// names the lane the declaration itself occupies and can therefore differ
37    /// from this field. Producers always emit the field; the schema permits
38    /// omission by payloads created before namespaces were exposed.
39    #[cfg_attr(feature = "schema", schemars(default))]
40    pub namespace: crate::semantic::SemanticNamespace,
41    /// Whether the file is reachable from an entry point.
42    pub file_reachable: bool,
43    /// Whether the file is an entry point.
44    pub is_entry_point: bool,
45    /// Whether the export is considered used.
46    pub is_used: bool,
47    /// Files that reference this export directly.
48    pub direct_references: Vec<ExportReference>,
49    /// Reachable direct references grouped by namespace. This is additive to
50    /// `namespace` and `direct_references`, whose winning-lane meaning remains
51    /// unchanged for backwards compatibility.
52    #[serde(default, skip_serializing_if = "Vec::is_empty")]
53    pub direct_references_by_namespace: Vec<NamespacedExportReferences>,
54    /// A star-export collision that makes the traced name ambiguous. When
55    /// present, `is_used: false` is an abstention rather than an unused-code
56    /// verdict.
57    #[serde(default, skip_serializing_if = "Option::is_none")]
58    pub star_export_ambiguity: Option<StarExportAmbiguity>,
59    /// Re-export chains that pass through this export.
60    pub re_export_chains: Vec<ReExportChain>,
61    /// The framework plugin rules that mark this export as used. The
62    /// framework calls or reads the export, so no import is necessary. A
63    /// credit sets `is_used` when the file is reachable. Absent when no
64    /// plugin credits the export.
65    #[serde(default, skip_serializing_if = "Vec::is_empty")]
66    pub plugin_credits: Vec<PluginExportCredit>,
67    /// Human-readable reason summary.
68    pub reason: String,
69    /// Exact checker-backed references when type-aware tracing is enabled.
70    #[serde(default, skip_serializing_if = "Option::is_none")]
71    pub semantic: Option<crate::semantic::SemanticSymbolTrace>,
72}
73
74/// Result of tracing a class / enum / store MEMBER: the `--trace FILE:NAME`
75/// fallback when `NAME` is not a top-level export but a member declared on one
76/// (issue #1744). The trace runs on the module graph only, so it reports the
77/// OWNING export's reachability and usage (the gating precondition for
78/// member-level crediting) plus a pointer to the right `--unused-*-members`
79/// command, rather than per-member crediting provenance.
80#[derive(Debug, Serialize)]
81#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
82pub struct ClassMemberTrace {
83    /// The file containing the member.
84    #[serde(serialize_with = "serde_path::serialize")]
85    pub file: PathBuf,
86    /// The member name being traced.
87    pub member_name: String,
88    /// The member kind: `class-method`, `class-property`, `enum-member`,
89    /// `store-member`, or `namespace-member`.
90    pub member_kind: String,
91    /// The export that declares this member (the class / enum / store name).
92    pub owner_export: String,
93    /// Namespace whose references credit the owning export, mirroring
94    /// [`ExportTrace::namespace`] for the export this member is declared on.
95    /// `owner_is_used` and `owner_direct_references` describe that lane, so a
96    /// member of a value export credited only by a bound `import type` reports
97    /// `type` here. `semantic.target.namespace` names the lane the checker
98    /// proof covers and can therefore differ. Producers always emit the field;
99    /// the schema permits omission by payloads created before the owner
100    /// namespace was exposed.
101    #[cfg_attr(feature = "schema", schemars(default))]
102    pub owner_namespace: crate::semantic::SemanticNamespace,
103    /// Whether the owning export is considered used.
104    pub owner_is_used: bool,
105    /// Whether the file is reachable from an entry point.
106    pub owner_file_reachable: bool,
107    /// Whether the file is an entry point.
108    pub owner_is_entry_point: bool,
109    /// Files that reference the owning export directly. The search visibility
110    /// fields on each entry check the owner export name, not the member name.
111    pub owner_direct_references: Vec<ExportReference>,
112    /// Re-export chains through which the owning export is reachable. Populated
113    /// so a machine consumer can tell "used via a barrel" (empty direct refs but
114    /// non-empty chains) from "genuinely unreferenced".
115    pub owner_re_export_chains: Vec<ReExportChain>,
116    /// Human-readable reason summary plus the follow-up command to inspect the
117    /// member finding.
118    pub reason: String,
119    /// Exact checker-backed member references when type-aware tracing is enabled.
120    #[serde(default, skip_serializing_if = "Option::is_none")]
121    pub semantic: Option<crate::semantic::SemanticSymbolTrace>,
122}
123
124/// A direct reference to an export.
125#[derive(Debug, Clone, Serialize)]
126#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
127pub struct ExportReference {
128    /// File that contains the reference.
129    #[serde(serialize_with = "serde_path::serialize")]
130    pub from_file: PathBuf,
131    /// Reference kind, such as named import, default import, or re-export.
132    pub kind: String,
133    /// 1-based line of the import statement in `from_file`. Absent when the
134    /// graph holds no source position for the reference or the file cannot be
135    /// read.
136    #[serde(default, skip_serializing_if = "Option::is_none")]
137    pub line: Option<u32>,
138    /// Whether a whole-word text search for the export name finds this
139    /// consumer. Absent when no check applies, for example when the consumer
140    /// source cannot be read.
141    #[serde(default, skip_serializing_if = "Option::is_none")]
142    pub search_visibility: Option<SearchVisibility>,
143    /// Why a text search does not find the uses in this consumer. With
144    /// `search_visibility` `found`, only `pass-through` occurs: the consumer
145    /// forwards the export and does not use it.
146    #[serde(default, skip_serializing_if = "Option::is_none")]
147    pub reason: Option<SearchGapReason>,
148    /// The name to search for in this consumer instead of the export name.
149    /// Absent when the export name finds the uses or no single name does.
150    #[serde(default, skip_serializing_if = "Option::is_none")]
151    pub search_as: Option<String>,
152}
153
154impl ExportReference {
155    /// A reference with no source position and no search check.
156    #[must_use]
157    pub const fn new(from_file: PathBuf, kind: String) -> Self {
158        Self {
159            from_file,
160            kind,
161            line: None,
162            search_visibility: None,
163            reason: None,
164            search_as: None,
165        }
166    }
167}
168
169/// Whether a whole-word text search for an export name finds a consumer that
170/// the module graph resolves. The levels sort from best to worst.
171#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
172#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
173#[serde(rename_all = "kebab-case")]
174pub enum SearchVisibility {
175    /// The consumer source contains the export name, and the consumer uses it
176    /// under that name.
177    Found,
178    /// The consumer source contains the export name, but the consumer uses
179    /// the export under another local name.
180    Renamed,
181    /// The consumer source does not contain the export name.
182    Missed,
183}
184
185/// Why a text search for an export name does not find the uses in a consumer,
186/// or why a consumer is not a search target (`pass-through`).
187#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
188#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
189#[serde(rename_all = "kebab-case")]
190pub enum SearchGapReason {
191    /// The consumer imports the export under another local name
192    /// (`import { foo as bar }`).
193    ImportAlias,
194    /// The consumer imports a default export under another local name.
195    DefaultImport,
196    /// A barrel re-exports the export under another name, and the consumer
197    /// imports that name.
198    ReExportAlias,
199    /// The consumer imports the whole module namespace and does not name the
200    /// export.
201    NamespaceUse,
202    /// The consumer loads the module with a dynamic `import()` and does not
203    /// name the export.
204    DynamicImport,
205    /// The consumer only forwards the export and does not use it: a barrel
206    /// (`export * from`, `export { foo } from`), or a file that imports the
207    /// export and only exports it again (`import { foo } from`, then a
208    /// top-level `export { foo }`). A change of the export
209    /// needs no edit there, and the files that import through it are checked
210    /// on their own. Occurs with `found`.
211    PassThrough,
212}
213
214/// Direct references that credit one namespace of an export binding.
215#[derive(Debug, Serialize)]
216#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
217pub struct NamespacedExportReferences {
218    /// Credited namespace.
219    pub namespace: SemanticNamespace,
220    /// Number of reachable references in this namespace.
221    pub reference_count: usize,
222    /// Reachable references in deterministic graph order.
223    pub references: Vec<ExportReference>,
224}
225
226/// A re-export chain showing how an export is propagated.
227#[derive(Debug, Serialize)]
228#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
229pub struct ReExportChain {
230    /// The barrel file that re-exports this symbol.
231    #[serde(serialize_with = "serde_path::serialize")]
232    pub barrel_file: PathBuf,
233    /// The name it is re-exported as.
234    pub exported_as: String,
235    /// Number of references on the barrel's re-exported symbol.
236    pub reference_count: usize,
237}
238
239/// Result of tracing all edges for a file.
240#[derive(Debug, Default, Serialize)]
241#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
242pub struct FileTrace {
243    /// The traced file.
244    #[serde(serialize_with = "serde_path::serialize")]
245    pub file: PathBuf,
246    /// Whether this file is reachable from entry points.
247    pub is_reachable: bool,
248    /// Whether this file is an entry point.
249    pub is_entry_point: bool,
250    /// Exports declared by this file.
251    pub exports: Vec<TracedExport>,
252    /// Files that this file imports from.
253    #[serde(serialize_with = "serde_path::serialize_vec")]
254    pub imports_from: Vec<PathBuf>,
255    /// Files that import from this file.
256    #[serde(serialize_with = "serde_path::serialize_vec")]
257    pub imported_by: Vec<PathBuf>,
258    /// Re-exports declared by this file.
259    pub re_exports: Vec<TracedReExport>,
260    /// The package.json script key that makes this file an entry point, e.g.
261    /// `build`. Absent when no script makes the file an entry point
262    /// (issue #4175).
263    #[serde(default, skip_serializing_if = "Option::is_none")]
264    pub entry_script: Option<String>,
265    /// The configs that make this file an entry point through Module
266    /// Federation `exposes`, one per config. Absent when no Federation config
267    /// exposes the file (issue #2796).
268    #[serde(default, skip_serializing_if = "Vec::is_empty")]
269    pub sources: Vec<TraceSource>,
270}
271
272/// Which configs name which files and which dependency names, collected by one
273/// analysis for the trace output.
274///
275/// It holds plain data, so a trace looks a file up without the rules that
276/// produced it.
277#[derive(Debug, Clone, Default, PartialEq, Eq)]
278pub struct TraceProvenance {
279    /// Root-relative file path and the config that names it.
280    files: Vec<(PathBuf, TraceSource)>,
281    /// Dependency name and the config that names it.
282    dependencies: Vec<(String, TraceSource)>,
283    /// Dependency name and why the unused devDependency check credits it as
284    /// tooling.
285    tooling_credits: Vec<(String, ToolingCredit)>,
286    /// Root-relative file path and an export name that a framework plugin
287    /// reads as configuration, such as the Next.js `dynamic` segment option.
288    config_exports: FxHashMap<PathBuf, FxHashSet<String>>,
289    /// Root-relative file path, export name, and the plugin rule that marks
290    /// the export as used.
291    export_credits: FxHashMap<PathBuf, FxHashMap<String, Vec<PluginExportCredit>>>,
292    /// Root-relative file path of a script entry point and the package.json
293    /// script key that runs the file.
294    entry_scripts: FxHashMap<PathBuf, String>,
295    /// The packages that start the peer-dependency closure in addition to the
296    /// imported packages.
297    peer_seeds: PeerClosureSeeds,
298}
299
300/// The packages that start a peer-dependency closure although no file
301/// imports them: packages that a script runs and packages that a plugin
302/// credits.
303///
304/// The unused-dependency check and the dependency trace read the same seeds,
305/// so the trace names the same hosts that give peer credit.
306#[derive(Debug, Clone, Default, PartialEq, Eq)]
307pub struct PeerClosureSeeds {
308    /// Seeds for every closure.
309    shared: FxHashSet<String>,
310    /// Seeds for the closure of one manifest, keyed by the absolute
311    /// `package.json` path.
312    by_manifest: FxHashMap<PathBuf, FxHashSet<String>>,
313}
314
315impl PeerClosureSeeds {
316    /// Seeds that every closure reads.
317    #[must_use]
318    pub fn from_shared(names: impl IntoIterator<Item = String>) -> Self {
319        Self {
320            shared: names.into_iter().collect(),
321            by_manifest: FxHashMap::default(),
322        }
323    }
324
325    /// Record a seed for the closure of the manifest at `manifest`, an
326    /// absolute `package.json` path.
327    pub fn push_manifest_seed(&mut self, manifest: PathBuf, name: String) {
328        self.by_manifest.entry(manifest).or_default().insert(name);
329    }
330
331    /// The seeds of the closure for the manifest at `manifest`: the shared
332    /// seeds and the seeds of that manifest.
333    pub fn for_manifest<'a>(&'a self, manifest: &Path) -> impl Iterator<Item = &'a str> {
334        self.shared
335            .iter()
336            .chain(self.by_manifest.get(manifest).into_iter().flatten())
337            .map(String::as_str)
338    }
339}
340
341impl TraceProvenance {
342    /// Record that a framework plugin reads the export `name` of the
343    /// root-relative `file` as configuration.
344    pub fn push_config_export(&mut self, file: PathBuf, name: String) {
345        self.config_exports.entry(file).or_default().insert(name);
346    }
347
348    /// Whether a framework plugin reads the export `name` of the
349    /// root-relative `file` as configuration.
350    #[must_use]
351    pub fn is_config_export(&self, file: &Path, name: &str) -> bool {
352        self.config_exports
353            .get(file)
354            .is_some_and(|names| names.contains(name))
355    }
356
357    /// Record the plugin rules that mark exports of the root-relative `file`
358    /// as used, as pairs of an export name and a credit.
359    pub fn push_export_credits(
360        &mut self,
361        file: PathBuf,
362        credits: impl IntoIterator<Item = (String, PluginExportCredit)>,
363    ) {
364        let by_name = self.export_credits.entry(file).or_default();
365        for (name, credit) in credits {
366            let known = by_name.entry(name).or_default();
367            if !known.contains(&credit) {
368                known.push(credit);
369            }
370        }
371    }
372
373    /// The plugin rules that mark the export `name` of the root-relative
374    /// `file` as used.
375    #[must_use]
376    pub fn export_credits(&self, file: &Path, name: &str) -> Vec<PluginExportCredit> {
377        self.export_credits
378            .get(file)
379            .and_then(|by_name| by_name.get(name))
380            .cloned()
381            .unwrap_or_default()
382    }
383
384    /// Record that `source` names the root-relative `file`.
385    pub fn push_file(&mut self, file: PathBuf, source: TraceSource) {
386        if !self
387            .files
388            .iter()
389            .any(|(known, known_source)| *known == file && *known_source == source)
390        {
391            self.files.push((file, source));
392        }
393    }
394
395    /// Record that `source` names the dependency `name`.
396    pub fn push_dependency(&mut self, name: String, source: TraceSource) {
397        if !self
398            .dependencies
399            .iter()
400            .any(|(known, known_source)| *known == name && *known_source == source)
401        {
402            self.dependencies.push((name, source));
403        }
404    }
405
406    /// The configs that name `file`, a root-relative path.
407    #[must_use]
408    pub fn file_sources(&self, file: &std::path::Path) -> Vec<TraceSource> {
409        self.files
410            .iter()
411            .filter(|(known, _)| known == file)
412            .map(|(_, source)| source.clone())
413            .collect()
414    }
415
416    /// The configs that name the dependency `name`.
417    #[must_use]
418    pub fn dependency_sources(&self, name: &str) -> Vec<TraceSource> {
419        self.dependencies
420            .iter()
421            .filter(|(known, _)| known == name)
422            .map(|(_, source)| source.clone())
423            .collect()
424    }
425
426    /// Record the package.json script of each script entry point in
427    /// `entries`, by path relative to `root`.
428    pub fn push_entry_scripts(&mut self, root: &Path, entries: &[crate::discover::EntryPoint]) {
429        for entry in entries {
430            if let Some(script) = entry.source.script() {
431                let file = entry.path.strip_prefix(root).unwrap_or(&entry.path);
432                self.entry_scripts
433                    .entry(file.to_path_buf())
434                    .or_insert_with(|| script.to_string());
435            }
436        }
437    }
438
439    /// The package.json script key that makes the root-relative `file` an
440    /// entry point, if a script does.
441    #[must_use]
442    pub fn entry_script(&self, file: &Path) -> Option<&str> {
443        self.entry_scripts.get(file).map(String::as_str)
444    }
445
446    /// Record why the dependency `name` is credited as tooling. The first
447    /// credit recorded for a name wins.
448    pub fn push_tooling_credit(&mut self, name: String, credit: ToolingCredit) {
449        if !self.tooling_credits.iter().any(|(known, _)| *known == name) {
450            self.tooling_credits.push((name, credit));
451        }
452    }
453
454    /// Why the dependency `name` is credited as tooling, if it is.
455    #[must_use]
456    pub fn tooling_credit(&self, name: &str) -> Option<ToolingCredit> {
457        self.tooling_credits
458            .iter()
459            .find(|(known, _)| known == name)
460            .map(|(_, credit)| credit.clone())
461    }
462
463    /// Set the packages that start the peer-dependency closure in addition to
464    /// the imported packages.
465    #[must_use]
466    pub fn with_peer_seeds(mut self, seeds: PeerClosureSeeds) -> Self {
467        self.peer_seeds = seeds;
468        self
469    }
470
471    /// The packages that start the peer-dependency closure in addition to the
472    /// imported packages.
473    #[must_use]
474    pub const fn peer_seeds(&self) -> &PeerClosureSeeds {
475        &self.peer_seeds
476    }
477}
478
479/// Why the unused devDependency check counts a dependency as used tooling
480/// although no source file imports it.
481#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
482#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
483pub struct ToolingCredit {
484    /// The evidence: `plugin-config` when the plugin that declares the
485    /// dependency found its own config file, `plugin-reference` when a
486    /// package.json script, a CI workflow or a git hook runs one of that
487    /// plugin's packages, `ambient-types` for a type package that declares
488    /// globals, `types-target` when the project declares or imports the
489    /// package that a `@types/` package types, `types-config` when a config
490    /// file, such as a tsconfig `types` entry, names the type package,
491    /// `known-tooling` for a library from the tooling catalogue,
492    /// `known-tooling-config` when a command-line tool from the catalogue has
493    /// its own config file, and `own-peer` when the same manifest lists the
494    /// devDependency in `peerDependencies`. The set is open.
495    pub reason: String,
496    /// The plugin that declares the dependency as tooling.
497    #[serde(default, skip_serializing_if = "Option::is_none")]
498    pub plugin: Option<String>,
499    /// The config file found, relative to the project root, for
500    /// `plugin-config` and `known-tooling-config`. A `package.json` path when
501    /// the config is a package.json key. For `own-peer`, the manifest that
502    /// lists the dependency.
503    #[serde(
504        serialize_with = "serde_path::serialize_option",
505        default,
506        skip_serializing_if = "Option::is_none"
507    )]
508    pub config: Option<PathBuf>,
509    /// The package that a script, CI workflow or git hook runs, for
510    /// `plugin-reference`, or the package that a `@types/` package types,
511    /// for `types-target`.
512    #[serde(default, skip_serializing_if = "Option::is_none")]
513    pub reference: Option<String>,
514}
515
516/// A config that names a traced file or a traced dependency, and the key that
517/// names it.
518#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
519#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
520pub struct TraceSource {
521    /// The mechanism that names the file or the dependency:
522    /// `module-federation`. The set is open.
523    pub kind: String,
524    /// The plugin that read the config, as it labels itself:
525    /// `module-federation` for a standalone `module-federation.config.*`,
526    /// or the bundler plugin (`webpack`, `rspack`, `rsbuild`, `vite`,
527    /// `nextjs`) that read the same options inline from its own config.
528    pub plugin: String,
529    /// The file that names the file or the dependency, relative to the
530    /// project root: the config file, or the source file of a Module
531    /// Federation runtime call.
532    #[serde(serialize_with = "serde_path::serialize")]
533    pub config: PathBuf,
534    /// The config key or the runtime function that names the file or the
535    /// dependency: `exposes` for an exposed file, `remotes` for a remote
536    /// alias, and `registerRemotes`, `loadRemote`, `init` or `createInstance`
537    /// for a remote that a runtime call names. The set is open.
538    pub key: String,
539}
540
541/// An export with usage information.
542#[derive(Debug, Serialize)]
543#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
544pub struct TracedExport {
545    /// Export name.
546    pub name: String,
547    /// Whether the export is type-only.
548    pub is_type_only: bool,
549    /// Number of references to this export.
550    pub reference_count: usize,
551    /// Files that reference this export.
552    pub referenced_by: Vec<ExportReference>,
553    /// The framework plugin rules that mark this export as used. Absent when
554    /// no plugin credits the export.
555    #[serde(default, skip_serializing_if = "Vec::is_empty")]
556    pub plugin_credits: Vec<PluginExportCredit>,
557}
558
559/// A framework plugin rule that marks an export as used.
560#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
561#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
562pub struct PluginExportCredit {
563    /// The plugin that gives the rule, for example `nextjs`.
564    pub plugin: String,
565    /// The project-relative file pattern of the rule.
566    pub pattern: String,
567}
568
569impl ExportTrace {
570    /// Add the plugin credits that `provenance` records for the traced export.
571    ///
572    /// The analysis does not report a credited export of a reachable file,
573    /// so the trace then marks the export as used. A star re-export
574    /// collision keeps its abstention.
575    pub fn apply_plugin_credits(&mut self, provenance: &TraceProvenance) {
576        let credits = provenance.export_credits(&self.file, &self.export_name);
577        if credits.is_empty() {
578            return;
579        }
580        if self.file_reachable && !self.is_used && self.star_export_ambiguity.is_none() {
581            let mut plugins: Vec<&str> = Vec::new();
582            for credit in &credits {
583                if !plugins.contains(&credit.plugin.as_str()) {
584                    plugins.push(&credit.plugin);
585                }
586            }
587            self.is_used = true;
588            self.reason = format!(
589                "Used by the framework: the {} plugin marks this export as used",
590                plugins.join(", ")
591            );
592        }
593        self.plugin_credits = credits;
594    }
595}
596
597impl FileTrace {
598    /// Add the plugin credits that `provenance` records for each export.
599    pub fn apply_plugin_credits(&mut self, provenance: &TraceProvenance) {
600        for export in &mut self.exports {
601            export.plugin_credits = provenance.export_credits(&self.file, &export.name);
602        }
603    }
604
605    /// Set the package.json script that `provenance` records for this file
606    /// when the file is an entry point.
607    pub fn apply_entry_script(&mut self, provenance: &TraceProvenance) {
608        self.entry_script = if self.is_entry_point {
609            provenance.entry_script(&self.file).map(str::to_string)
610        } else {
611            None
612        };
613    }
614}
615
616/// A re-export with source information.
617#[derive(Debug, Serialize)]
618#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
619pub struct TracedReExport {
620    /// Source file being re-exported from.
621    #[serde(serialize_with = "serde_path::serialize")]
622    pub source_file: PathBuf,
623    /// Imported symbol name.
624    pub imported_name: String,
625    /// Exported symbol name.
626    pub exported_name: String,
627}
628
629/// Result of tracing a dependency: where it is used.
630#[derive(Debug, Serialize)]
631#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
632pub struct DependencyTrace {
633    /// The dependency name being traced.
634    pub package_name: String,
635    /// Files that import this dependency, each listed once.
636    #[serde(serialize_with = "serde_path::serialize_vec")]
637    pub imported_by: Vec<PathBuf>,
638    /// Files whose every import of this dependency is type-only, each listed
639    /// once.
640    #[serde(serialize_with = "serde_path::serialize_vec")]
641    pub type_only_imported_by: Vec<PathBuf>,
642    /// Whether the dependency is invoked from package.json scripts, CI configs
643    /// or git hooks.
644    pub used_in_scripts: bool,
645    /// Whether the dependency is used at all: imported, invoked from scripts,
646    /// or listed as a peer by a used package (`peer_of`).
647    pub is_used: bool,
648    /// Number of files that import this dependency.
649    pub import_count: usize,
650    /// Used packages that list this dependency in their installed
651    /// `peerDependencies`, required or optional, sorted by name. The
652    /// unused-dependency check credits such a peer, because the package that
653    /// lists it loads it at runtime. Absent when no used package lists it.
654    #[serde(default, skip_serializing_if = "Vec::is_empty")]
655    pub peer_of: Vec<String>,
656    /// The configs that declare this name as a Module Federation remote alias
657    /// under `remotes`, one per config. A remote alias is provided by a
658    /// remote container at runtime, not by an npm package. Absent when no
659    /// Federation config declares the name (issue #2796).
660    #[serde(default, skip_serializing_if = "Vec::is_empty")]
661    pub sources: Vec<TraceSource>,
662    /// Why the unused devDependency check credits the dependency as tooling
663    /// when no file imports it and no script, CI workflow or git hook runs it.
664    /// When present, `is_used` is `true`. Absent otherwise.
665    #[serde(default, skip_serializing_if = "Option::is_none")]
666    pub tooling_credit: Option<ToolingCredit>,
667    /// The manifests that the unused-dependency check flags for this name,
668    /// relative to the project root and sorted. The check reads each
669    /// declaring manifest on its own. An import credits the nearest manifest
670    /// that installs the package, so a name that one workspace uses can still
671    /// be unused in the root manifest or in another workspace. Absent when no
672    /// manifest is flagged.
673    #[serde(
674        default,
675        serialize_with = "serde_path::serialize_vec",
676        skip_serializing_if = "Vec::is_empty"
677    )]
678    pub unused_in: Vec<PathBuf>,
679    /// How the code uses each imported name of the dependency. Present on
680    /// `fallow trace --dependency`, and on the MCP `trace_dependency` tool
681    /// when a usage parameter is set. Absent on
682    /// `fallow dead-code --trace-dependency`. The object has its own
683    /// `schema_version`.
684    #[serde(default, skip_serializing_if = "Option::is_none")]
685    pub usage: Option<crate::trace_usage::DependencyUsage>,
686}
687
688impl DependencyTrace {
689    /// Record the manifests that the unused-dependency report flags for this
690    /// name, so the trace names each declaration that the report lists.
691    pub fn apply_unused_declarations(
692        &mut self,
693        results: &crate::results::AnalysisResults,
694        root: &Path,
695    ) {
696        let flagged = results
697            .unused_dependencies
698            .iter()
699            .map(|finding| &finding.dep)
700            .chain(
701                results
702                    .unused_dev_dependencies
703                    .iter()
704                    .map(|finding| &finding.dep),
705            )
706            .chain(
707                results
708                    .unused_optional_dependencies
709                    .iter()
710                    .map(|finding| &finding.dep),
711            )
712            .filter(|dep| dep.package_name == self.package_name)
713            .map(|dep| {
714                dep.path
715                    .strip_prefix(root)
716                    .unwrap_or(&dep.path)
717                    .to_path_buf()
718            });
719        self.unused_in.extend(flagged);
720        self.unused_in.sort();
721        self.unused_in.dedup();
722    }
723
724    /// Attach the tooling credit of an otherwise unused dependency and count
725    /// the dependency as used, so the trace agrees with the unused-dependency
726    /// report. A dependency that an import or a script already uses keeps no
727    /// credit, because the credit does not decide its status.
728    pub fn apply_tooling_credit(&mut self, credit: Option<ToolingCredit>) {
729        if self.is_used {
730            return;
731        }
732        if let Some(credit) = credit {
733            self.is_used = true;
734            self.tooling_credit = Some(credit);
735        }
736    }
737}
738
739/// Sub-phase attribution inside the entry-point discovery stage.
740///
741/// `PipelineTimings::entry_points_ms` is a single opaque number; these are the
742/// consecutive wall-clock spans that make it up, so a slow discovery stage can
743/// be attributed instead of guessed at. The spans cover the discovery sections
744/// only, so they sum to slightly less than `entry_points_ms`: the summary and
745/// count that follow discovery are not attributed to any span.
746#[derive(Debug, Clone, Copy, Default, Serialize)]
747#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
748pub struct EntryPointSpans {
749    /// Root-package discovery: manual entry globs, root `package.json` fields,
750    /// and the nested `package.json` scan under the conventional monorepo
751    /// directories.
752    pub root_ms: f64,
753    /// Runtime script seed collection plus per-workspace discovery.
754    pub workspaces_ms: f64,
755    /// Plugin entry-point glob compilation and matching.
756    pub plugins_ms: f64,
757    /// The part of `plugins_ms` spent compiling plugin patterns into a glob
758    /// set. Scales with active pattern count, not with project size.
759    pub plugin_glob_build_ms: f64,
760    /// The part of `plugins_ms` spent matching the compiled set against every
761    /// discovered file. Scales with file count times pattern count.
762    pub plugin_glob_match_ms: f64,
763    /// Infrastructure config-file probing at the project root.
764    pub infrastructure_ms: f64,
765    /// Configured `dynamicallyLoaded` glob expansion. Zero when unconfigured.
766    pub dynamic_ms: f64,
767    /// Sorting and deduplicating the merged entry set.
768    pub dedup_ms: f64,
769}
770
771/// Deterministic work counts for one dead-code pipeline run.
772///
773/// Every count is exact for a given project, commit and cache state. It does
774/// not depend on the thread count, the machine or the load, so a regression
775/// test can compare it with exact equality where a millisecond value is too
776/// noisy. A count is zero when its stage did no work, for example the resolver
777/// counts on a run that reused the persisted module graph.
778#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
779#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
780pub struct PipelineCounters {
781    /// Source files whose bytes the parse stage read from disk. A warm cache
782    /// hit on file metadata reads no bytes. `cache_misses` counts the files
783    /// that were parsed.
784    pub files_read: u64,
785    /// Bytes of source read from disk by the parse stage.
786    pub source_bytes_read: u64,
787    /// Bytes of the persisted parse cache read from disk. Zero when the run
788    /// had no parse cache or used `--no-cache`.
789    pub parse_cache_bytes_read: u64,
790    /// Bytes of stylesheet source that the parse stage passed through the CSS
791    /// comment mask. The parse masks each stylesheet once, so this value is
792    /// the size of the parsed stylesheets. A higher value shows a repeated
793    /// mask. Zero when no stylesheet was parsed.
794    pub css_masked_bytes: u64,
795    /// Specifier resolutions that the import sites asked for: one for each
796    /// static import binding, re-export, `require()`, `import()` and module
797    /// mock. Internal retries inside the resolver are not counted here.
798    pub resolve_specifier_calls: u64,
799    /// Distinct `(specifier, from_style)` pairs for each importing file,
800    /// summed over all files. A ratio of `resolve_specifier_calls` to this
801    /// value above 1.0 shows bindings that share a specifier. The resolver
802    /// runs at most once for each of these pairs. A pair that returns before
803    /// the resolver, such as an external URL, makes no resolver call.
804    pub unique_specifiers: u64,
805    /// Calls into the module resolver, including fallback retries.
806    pub oxc_resolve_calls: u64,
807    /// Path canonicalize calls that import resolution needs: each direct call,
808    /// plus one for each distinct path that goes through the canonicalize
809    /// cache. Resolver setup is not counted.
810    pub canonicalize_calls: u64,
811}
812
813/// Pipeline performance timings.
814#[derive(Debug, Clone, Serialize)]
815#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
816pub struct PipelineTimings {
817    /// Time spent discovering files.
818    pub discover_files_ms: f64,
819    /// Number of discovered files.
820    pub file_count: usize,
821    /// Time spent discovering workspaces.
822    pub workspaces_ms: f64,
823    /// Number of discovered workspaces.
824    pub workspace_count: usize,
825    /// Time spent running plugin discovery.
826    pub plugins_ms: f64,
827    /// Time spent analyzing package scripts and CI configuration.
828    pub script_analysis_ms: f64,
829    /// Wall-clock time spent parsing and extracting modules.
830    pub parse_extract_ms: f64,
831    /// Summed parser CPU time across workers.
832    pub parse_cpu_ms: f64,
833    /// The part of `parse_extract_ms` that reads and decodes the persisted
834    /// parse cache. Zero with `--no-cache`.
835    pub parse_cache_load_ms: f64,
836    /// Number of extracted modules.
837    pub module_count: usize,
838    /// Number of files loaded from the parse cache.
839    pub cache_hits: usize,
840    /// Number of files parsed without a cache hit.
841    pub cache_misses: usize,
842    /// Why the persisted parse cache was not reused, when it was not. `None`
843    /// means the cache was loaded; the hit and miss counts then describe how
844    /// much of it applied.
845    #[serde(default, skip_serializing_if = "Option::is_none")]
846    pub cache_rejection: Option<CacheRejection>,
847    /// Why the persisted module-graph cache was not reused, when it was not.
848    #[serde(default, skip_serializing_if = "Option::is_none")]
849    pub graph_cache_rejection: Option<CacheRejection>,
850    /// Time spent updating the parse cache.
851    pub cache_update_ms: f64,
852    /// Time spent categorizing entry points.
853    pub entry_points_ms: f64,
854    /// Sub-phase attribution for `entry_points_ms`.
855    pub entry_point_spans: EntryPointSpans,
856    /// Number of entry points considered.
857    pub entry_point_count: usize,
858    /// Time spent resolving imports.
859    pub resolve_imports_ms: f64,
860    /// Time spent building the module graph.
861    pub build_graph_ms: f64,
862    /// Time spent running analysis.
863    pub analyze_ms: f64,
864    /// Time spent running duplicate-code analysis, when included.
865    #[serde(default, skip_serializing_if = "Option::is_none")]
866    pub duplication_ms: Option<f64>,
867    /// Total pipeline time.
868    pub total_ms: f64,
869    /// Deterministic work counts for this run.
870    pub counters: PipelineCounters,
871}
872
873/// Result of computing the impact closure for a single file as the seed.
874#[derive(Debug, Serialize)]
875#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
876pub struct ImpactClosureTrace {
877    /// The seed file, root-relative.
878    pub seed: String,
879    /// Root-relative paths transitively affected by the seed.
880    pub affected_not_shown: Vec<String>,
881    /// Coordination gaps between the seed and consumers.
882    pub coordination_gap: Vec<ImpactClosureGap>,
883}
884
885/// Wire-version discriminator for [`ImportPathTrace`]. Independent from the
886/// global `SchemaVersion`: the import-path payload versions on its own cadence,
887/// like the other independently-versioned envelopes. Serializes as a string
888/// `const` so JSON consumers can switch on it.
889#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
890#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
891pub enum ImportPathTraceSchemaVersion {
892    /// First release of the `fallow trace --path` shape.
893    #[serde(rename = "1")]
894    V1,
895}
896
897/// Result of asking how one module reaches another: the shortest import path.
898///
899/// `reachable` is the only field that separates "no route exists" from "the
900/// route is empty because both ends are the same module". Both report
901/// `hops: 0`, so a consumer must read `reachable`, never the hop count.
902#[derive(Debug, Serialize)]
903#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
904#[cfg_attr(feature = "schema", schemars(title = "fallow trace --path"))]
905pub struct ImportPathTrace {
906    /// Wire-shape version of this payload.
907    pub schema_version: ImportPathTraceSchemaVersion,
908    /// The module the walk started from, root-relative.
909    pub from: String,
910    /// The module the walk was looking for, root-relative.
911    pub to: String,
912    /// Whether `to` is reachable from `from` by following import edges.
913    pub reachable: bool,
914    /// Number of import edges on the reported route. `0` both when the two ends
915    /// are the same module and when there is no route at all.
916    pub hops: usize,
917    /// The route, in import order. Empty whenever `hops` is `0`.
918    pub path: Vec<ImportPathHop>,
919    /// Human-readable summary of the outcome.
920    pub reason: String,
921}
922
923/// One import edge on an [`ImportPathTrace`].
924#[derive(Debug, Serialize, PartialEq, Eq)]
925#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
926pub struct ImportPathHop {
927    /// The importing module, root-relative.
928    pub from: String,
929    /// The imported module, root-relative.
930    pub to: String,
931    /// Whether every symbol on this edge is type-only, so the hop is erased at
932    /// build time. Type-only hops are reported, never skipped: an `import type`
933    /// chain is a real compile-time coupling.
934    pub type_only: bool,
935    /// Whether the edge carries a runtime value but no static one: the target
936    /// loads only on demand (`import()`, a lazy glob or template pattern) or
937    /// on another thread (a worker URL, a worker loader request,
938    /// `child_process.fork`). False for a
939    /// static hop and for a type-only hop.
940    pub dynamic: bool,
941    /// 1-based line in `from` of the imported binding that creates this edge:
942    /// the first value-carrying symbol on the import, or the first symbol when
943    /// every symbol is type-only. On a multi-line import that is the binding's
944    /// own line, not the `import` keyword's. Absent when the edge carries no
945    /// span or the source could not be read.
946    #[serde(default, skip_serializing_if = "Option::is_none")]
947    pub import_line: Option<u32>,
948}
949
950/// One coordination-gap entry in an [`ImpactClosureTrace`].
951#[derive(Debug, Serialize)]
952#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
953pub struct ImpactClosureGap {
954    /// Root-relative path of the consumer module.
955    pub consumer_file: String,
956    /// Exported symbol names the consumer references.
957    pub consumed_symbols: Vec<String>,
958    /// Scope note for the syntactic trace.
959    pub note: String,
960    /// Whether a whole-word text search for the consumed symbol names finds
961    /// this consumer. When the consumer uses more than one symbol, the worst
962    /// level wins (`missed`, then `renamed`, then `found`). Absent when no
963    /// check applies, for example when the consumer source cannot be read.
964    #[serde(default, skip_serializing_if = "Option::is_none")]
965    pub search_visibility: Option<SearchVisibility>,
966    /// Why a text search does not find the uses of the worst symbol. With
967    /// `search_visibility` `found`, only `pass-through` occurs.
968    #[serde(default, skip_serializing_if = "Option::is_none")]
969    pub reason: Option<SearchGapReason>,
970    /// The name to search for in this consumer instead of the symbol name.
971    #[serde(default, skip_serializing_if = "Option::is_none")]
972    pub search_as: Option<String>,
973    /// The entry of `consumed_symbols` that `search_visibility`, `reason`
974    /// and `search_as` describe: the worst symbol, `default` for a default
975    /// export. Present when `search_visibility` is present.
976    #[serde(default, skip_serializing_if = "Option::is_none")]
977    pub search_symbol: Option<String>,
978}
979
980/// Result of tracing a clone: all groups containing the code at a source
981/// location or addressed by a stable clone fingerprint.
982#[derive(Debug, Serialize)]
983#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
984pub struct CloneTrace {
985    /// File passed to the trace request, root-relative when a group matches.
986    #[serde(serialize_with = "serde_path::serialize")]
987    pub file: PathBuf,
988    /// 1-based line passed to the trace request or representative group line.
989    pub line: usize,
990    /// The matched clone instance, if one exists.
991    pub matched_instance: Option<CloneInstance>,
992    /// Clone groups matched by the trace request.
993    pub clone_groups: Vec<TracedCloneGroup>,
994}
995
996/// One clone group returned from a clone trace request.
997#[derive(Debug, Serialize)]
998#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
999pub struct TracedCloneGroup {
1000    /// Stable content fingerprint, usually `dup:<8hex>` and widened on rare
1001    /// report collisions.
1002    pub fingerprint: String,
1003    /// Number of tokens in the duplicated block.
1004    pub token_count: usize,
1005    /// Number of lines in the duplicated block.
1006    pub line_count: usize,
1007    /// Maximum directory-tree or same-file line distance between instances.
1008    pub spread: usize,
1009    /// Lowest all-pairs similarity for a near-miss clone group.
1010    #[serde(default, skip_serializing_if = "Option::is_none")]
1011    #[cfg_attr(feature = "schema", schemars(with = "f64"))]
1012    pub similarity: Option<f64>,
1013    /// Root-relative clone instances in this group.
1014    pub instances: Vec<CloneInstance>,
1015    /// Group-level refactoring suggestion.
1016    pub suggestion: RefactoringSuggestion,
1017    /// Best-effort name for the extracted function. Advisory only.
1018    #[serde(default, skip_serializing_if = "Option::is_none")]
1019    pub suggested_name: Option<String>,
1020}
1021
1022#[cfg(test)]
1023mod tests {
1024    use super::*;
1025
1026    fn unreferenced_trace(file_reachable: bool) -> ExportTrace {
1027        ExportTrace {
1028            file: PathBuf::from("app/page.tsx"),
1029            export_name: "default".to_string(),
1030            namespace: SemanticNamespace::Value,
1031            file_reachable,
1032            is_entry_point: true,
1033            is_used: false,
1034            direct_references: Vec::new(),
1035            direct_references_by_namespace: Vec::new(),
1036            star_export_ambiguity: None,
1037            re_export_chains: Vec::new(),
1038            plugin_credits: Vec::new(),
1039            reason: "No references".to_string(),
1040            semantic: None,
1041        }
1042    }
1043
1044    fn page_provenance() -> TraceProvenance {
1045        let mut provenance = TraceProvenance::default();
1046        let credit = PluginExportCredit {
1047            plugin: "nextjs".to_string(),
1048            pattern: "app/**/page.tsx".to_string(),
1049        };
1050        provenance.push_export_credits(
1051            PathBuf::from("app/page.tsx"),
1052            [
1053                ("default".to_string(), credit.clone()),
1054                ("default".to_string(), credit),
1055            ],
1056        );
1057        provenance
1058    }
1059
1060    #[test]
1061    fn a_plugin_credit_marks_an_export_of_a_reachable_file_as_used() {
1062        let mut trace = unreferenced_trace(true);
1063        trace.apply_plugin_credits(&page_provenance());
1064        assert!(trace.is_used);
1065        assert_eq!(trace.plugin_credits.len(), 1);
1066        assert!(trace.reason.contains("nextjs"), "{}", trace.reason);
1067    }
1068
1069    #[test]
1070    fn a_plugin_credit_does_not_mark_an_unreachable_file_as_used() {
1071        let mut trace = unreferenced_trace(false);
1072        trace.apply_plugin_credits(&page_provenance());
1073        assert!(!trace.is_used);
1074        assert_eq!(trace.plugin_credits.len(), 1);
1075        assert_eq!(trace.reason, "No references");
1076    }
1077
1078    #[test]
1079    fn a_star_export_collision_keeps_its_abstention() {
1080        let mut trace = unreferenced_trace(true);
1081        trace.star_export_ambiguity = Some(StarExportAmbiguity {
1082            sources: vec![PathBuf::from("a.ts"), PathBuf::from("b.ts")],
1083            namespaces: vec![SemanticNamespace::Value],
1084        });
1085        trace.apply_plugin_credits(&page_provenance());
1086        assert!(!trace.is_used);
1087    }
1088
1089    #[test]
1090    fn an_export_without_a_credit_keeps_its_trace() {
1091        let mut trace = unreferenced_trace(true);
1092        trace.export_name = "helper".to_string();
1093        trace.apply_plugin_credits(&page_provenance());
1094        assert!(!trace.is_used);
1095        assert!(trace.plugin_credits.is_empty());
1096    }
1097
1098    fn file_trace(file: &str, is_entry_point: bool) -> FileTrace {
1099        FileTrace {
1100            file: PathBuf::from(file),
1101            is_reachable: true,
1102            is_entry_point,
1103            exports: Vec::new(),
1104            imports_from: Vec::new(),
1105            imported_by: Vec::new(),
1106            re_exports: Vec::new(),
1107            entry_script: None,
1108            sources: Vec::new(),
1109        }
1110    }
1111
1112    fn script_provenance() -> TraceProvenance {
1113        use crate::discover::{EntryPoint, EntryPointSource};
1114        let mut provenance = TraceProvenance::default();
1115        provenance.push_entry_scripts(
1116            Path::new("/project"),
1117            &[
1118                EntryPoint {
1119                    path: PathBuf::from("/project/scripts/build.js"),
1120                    source: EntryPointSource::PackageJsonScript {
1121                        script: "build".to_string(),
1122                    },
1123                },
1124                EntryPoint {
1125                    path: PathBuf::from("/project/src/index.js"),
1126                    source: EntryPointSource::PackageJsonMain,
1127                },
1128            ],
1129        );
1130        provenance
1131    }
1132
1133    #[test]
1134    fn a_script_entry_point_names_its_script() {
1135        let mut trace = file_trace("scripts/build.js", true);
1136        trace.apply_entry_script(&script_provenance());
1137        assert_eq!(trace.entry_script.as_deref(), Some("build"));
1138    }
1139
1140    #[test]
1141    fn an_entry_point_of_another_source_names_no_script() {
1142        let mut trace = file_trace("src/index.js", true);
1143        trace.apply_entry_script(&script_provenance());
1144        assert_eq!(trace.entry_script, None);
1145    }
1146
1147    #[test]
1148    fn a_file_that_is_not_an_entry_point_names_no_script() {
1149        let mut trace = file_trace("scripts/build.js", false);
1150        trace.apply_entry_script(&script_provenance());
1151        assert_eq!(trace.entry_script, None);
1152    }
1153}