Skip to main content

fallow_graph/graph/
mod.rs

1//! Module dependency graph with re-export chain propagation and reachability analysis.
2//!
3//! The graph is built from resolved modules and entry points, then used to determine
4//! which files are reachable and which exports are referenced.
5
6mod ambiguity;
7mod build;
8mod cache_check;
9mod cycle_edge_span;
10mod cycles;
11mod effective_exports;
12mod effective_re_exports;
13mod entry_load;
14mod entry_marks;
15mod fan_io;
16mod impact_closure;
17mod import_elision;
18mod namespace_aliases;
19mod namespace_escapes;
20mod namespace_indexes;
21mod namespace_re_exports;
22mod narrowing;
23pub mod package_entry;
24mod partition_order;
25mod platform_family_credit;
26mod public_exports;
27mod re_exports;
28mod reachability;
29mod shortest_import_path;
30mod support_reach;
31mod test_reach;
32pub mod types;
33
34use std::path::Path;
35
36use fixedbitset::FixedBitSet;
37use rustc_hash::{FxHashMap, FxHashSet};
38
39use crate::resolve::{ResolvedModule, ResolvedReplacedModuleTarget};
40use fallow_types::discover::{DiscoveredFile, EntryPoint, FileId};
41use fallow_types::extract::{ImportLoadKind, ImportedName, ModuleLoadMechanism};
42use types::{ReferencePathInterner, ReferencePathNode, ReferenceRouteNodeId, ReferenceRoutes};
43
44/// Strip `root` and forward-slash-normalize a module path so report keys match
45/// across platforms. Every report surface that emits a root-relative path key
46/// goes through this, so the four surfaces cannot drift apart.
47pub(super) fn relativize(path: &Path, root: &Path) -> String {
48    path.strip_prefix(root)
49        .unwrap_or(path)
50        .to_string_lossy()
51        .replace('\\', "/")
52}
53
54pub use ambiguity::{AmbiguityParticipants, AmbiguousStarExport};
55pub use cycles::{CycleOptions, CycleSearch, MAX_CYCLE_LENGTH, MAX_CYCLES_PER_SCC};
56pub use effective_exports::{EffectiveExportBinding, EffectiveExportResolution, ExportNamespace};
57pub use effective_re_exports::EffectiveReExportRoute;
58pub use entry_load::{DominatingImport, EntryLoadClosure};
59pub use entry_marks::untracked_load_targets;
60pub use fan_io::{FocusFileFacts, FocusFileFactsPaths};
61pub use impact_closure::{
62    CoordinationGap, CoordinationGapPaths, ImpactClosure, ImpactClosurePaths,
63};
64pub use import_elision::{DecoratorMetadata, ImportElision, MetadataEmit};
65pub use namespace_escapes::{NamespaceEscape, NamespaceEscapeReason};
66pub use partition_order::{PartitionOrder, PartitionOrderPaths, ReviewUnit, ReviewUnitPaths};
67pub use public_exports::PublicExportOrigin;
68pub use re_exports::GraphReExportCycle;
69pub use shortest_import_path::ImportPathHop;
70pub use test_reach::{ExportTestReach, ExportTestReachResult, TestMaskingState};
71pub use types::{
72    ExportSymbol, ModuleNode, ReExportEdge, ReachabilityRoots, ReferenceKind, ReferencePathId,
73    SymbolReference,
74};
75
76/// Direct declaration selected by one unique effective export binding.
77#[derive(Debug, Clone, Copy)]
78pub struct EffectiveExportOrigin<'graph> {
79    file_id: FileId,
80    export: &'graph ExportSymbol,
81}
82
83/// One namespace-specific export exposed by a module and its effective binding.
84#[derive(Debug, Clone, Copy)]
85pub struct EffectiveExportSurface<'graph> {
86    binding: EffectiveExportBinding,
87    namespace: ExportNamespace,
88    export: Option<&'graph ExportSymbol>,
89    origin: Option<EffectiveExportOrigin<'graph>>,
90    local_export: bool,
91}
92
93impl<'graph> EffectiveExportSurface<'graph> {
94    /// Canonical binding exposed by the requested module/name/namespace.
95    #[must_use]
96    pub const fn binding(self) -> EffectiveExportBinding {
97        self.binding
98    }
99
100    /// Namespace selected for this surface.
101    #[must_use]
102    pub const fn namespace(self) -> ExportNamespace {
103        self.namespace
104    }
105
106    /// Reference-bearing graph export selected for this surface.
107    ///
108    /// Direct declarations use their origin export. Named re-exports use their
109    /// single barrel surface while references remain namespace-specific;
110    /// namespace objects and implicit SFC defaults have no declaration export.
111    #[must_use]
112    pub const fn export(self) -> Option<&'graph ExportSymbol> {
113        self.export
114    }
115
116    /// Direct declaration that owns this binding, when one exists.
117    #[must_use]
118    pub const fn origin(self) -> Option<EffectiveExportOrigin<'graph>> {
119        self.origin
120    }
121}
122
123impl<'graph> EffectiveExportOrigin<'graph> {
124    /// Module that owns the selected declaration.
125    #[must_use]
126    pub const fn file_id(self) -> FileId {
127        self.file_id
128    }
129
130    /// Selected declaration in its owning module.
131    #[must_use]
132    pub const fn export(self) -> &'graph ExportSymbol {
133        self.export
134    }
135}
136
137/// True when the path's final component looks like a TypeScript declaration
138/// file (`.d.ts`, `.d.mts`, `.d.cts`). Used to seed declaration files as
139/// overall entry points so ambient `typeof import()` references stay alive;
140/// see [`ModuleGraph::build_with_declaration_seeding`] for the exception.
141///
142/// The analysis layer reuses this predicate. Keep it in sync with the
143/// discovery walk's declaration-file predicate, which exempts declaration
144/// files from the file-size skip.
145#[must_use]
146pub fn is_declaration_file_path(path: &Path) -> bool {
147    path.file_name()
148        .and_then(|n| n.to_str())
149        .is_some_and(|name| {
150            name.ends_with(".d.ts") || name.ends_with(".d.mts") || name.ends_with(".d.cts")
151        })
152}
153
154/// The core module dependency graph.
155///
156/// Derives `serde` so the whole graph can be persisted to `.fallow/graph-cache.bin`
157/// (see `crate::cache`) and skipped on a re-run whose inputs are byte-identical.
158/// `namespace_imported` is a derived `FixedBitSet` reconstructed from the edge
159/// set on cache load (`reconstruct_namespace_imported`), so it is
160/// `#[serde(skip, default)]` rather than persisted.
161#[derive(Debug, serde::Serialize, serde::Deserialize)]
162pub struct ModuleGraph {
163    /// All modules indexed by `FileId`.
164    ///
165    /// Invariant: `modules[file_id.0 as usize].file_id == file_id` for every
166    /// `FileId` in the graph. Holds because `discover/walk.rs` assigns FileIds
167    /// sequentially via `.enumerate()` after path-sorting, and
168    /// `build::populate_edges` pushes one `ModuleNode` per file in iteration
169    /// order. [`ModuleGraph::module`] relies on this for O(1) FileId-to-module
170    /// lookup, so callers do not build a per-call `FxHashMap<FileId, &ModuleNode>`.
171    /// The field is private so that only this crate can break the invariant.
172    modules: Vec<ModuleNode>,
173    /// Flat edge storage for cache-friendly iteration.
174    edges: Vec<Edge>,
175    /// Maps npm package names to the `FileId`s that import them, with one
176    /// entry per import. A file with two imports of a package appears twice.
177    pub package_usage: FxHashMap<String, Vec<FileId>>,
178    /// Maps npm package names to the `FileId`s that import them with type-only
179    /// imports, with one entry per type-only import.
180    /// A package appearing here but not in `package_usage` (or only in both) indicates
181    /// it's only used for types and could be a devDependency.
182    pub type_only_package_usage: FxHashMap<String, Vec<FileId>>,
183    /// Maps npm package names to the `FileId`s that read a file of the
184    /// package through a webpack asset loader (`raw-loader!pkg/file.txt`),
185    /// or that run the package as a macro (`with { type: "macro" }`).
186    /// The bundle holds the text, the bytes, a URL of the file or the macro
187    /// result, so the package is used at build time and the import is not a
188    /// runtime import.
189    /// Every entry is also in `package_usage`.
190    pub asset_package_usage: FxHashMap<String, Vec<FileId>>,
191    /// Package specifiers that each module imports statically with a runtime
192    /// value (no `import()`, no type-only import). Read by the startup weight
193    /// report to list the packages on the startup path of an entry.
194    pub eager_package_imports: FxHashMap<FileId, Vec<EagerPackageImport>>,
195    /// All entry point `FileId`s.
196    pub entry_points: FxHashSet<FileId>,
197    /// Runtime/application entry point `FileId`s.
198    pub runtime_entry_points: FxHashSet<FileId>,
199    /// Test entry point `FileId`s.
200    pub test_entry_points: FxHashSet<FileId>,
201    /// Support entry point `FileId`s, such as files that package.json scripts run.
202    support_entry_points: FxHashSet<FileId>,
203    /// Compact correlation index for distinct test-root replacement profiles.
204    ///
205    /// Empty when no test root declares a project-internal replacement. That
206    /// preserves the ordinary single-BFS test reachability path.
207    test_reachability_index: TestReachabilityIndex,
208    /// Flat interned linked paths used by exact export references.
209    reference_paths: Vec<ReferencePathNode>,
210    /// Compact transition graphs used by namespace-derived references.
211    reference_routes: ReferenceRoutes,
212    /// Reverse index: for each `FileId`, which files import it.
213    pub reverse_deps: Vec<Vec<FileId>>,
214    /// Precomputed: which modules have namespace imports (import * as ns).
215    ///
216    /// Derived entirely from the edge set (a module is namespace-imported iff
217    /// some edge to it carries an `ImportedName::Namespace` symbol), so it is
218    /// not persisted: on cache load it is rebuilt by
219    /// [`ModuleGraph::reconstruct_namespace_imported`], which replicates the
220    /// exact insertion logic from `build.rs`.
221    #[serde(skip, default)]
222    namespace_imported: FixedBitSet,
223    /// Re-export cycles and self-loops detected during Phase 4 chain
224    /// resolution. Each entry names the participating files (sorted
225    /// lexicographically) and a `is_self_loop` flag distinguishing
226    /// single-file self-re-exports from multi-node cycles. Populated by
227    /// `re_exports::find_re_export_cycles` and consumed by the analysis
228    /// backend, which wraps each entry in a typed `ReExportCycleFinding`.
229    pub re_export_cycles: Vec<GraphReExportCycle>,
230    /// Namespace bindings that get the full export credit of their target,
231    /// sorted by consumer and import position. See [`NamespaceEscape`].
232    pub namespace_escapes: Vec<NamespaceEscape>,
233    /// Canonical direct and transitive export binding resolution.
234    effective_exports: effective_exports::EffectiveExportIndex,
235    /// The [`ImportElision`] of each module whose decorator metadata emits an
236    /// import binding. The persisted graph does not track `tsconfig.json`, so
237    /// the caller reads the options after each build or cache load with
238    /// [`ModuleGraph::read_decorator_metadata_options`].
239    #[serde(skip, default)]
240    decorator_metadata_elision: FxHashMap<FileId, ImportElision>,
241}
242
243/// An edge in the module graph.
244///
245/// Public consumers inspect relationships through summary methods such as
246/// [`ModuleGraph::direct_importer_summaries`] and
247/// [`ModuleGraph::outgoing_edge_summaries`]. Keeping the raw storage private
248/// preserves graph invariants and the `Edge == 32` size assertion below.
249#[derive(Debug, serde::Serialize, serde::Deserialize)]
250pub struct Edge {
251    /// Source module of this import edge.
252    source: FileId,
253    /// Target module imported by `source`.
254    target: FileId,
255    /// Symbols imported across this edge.
256    symbols: Vec<ImportedSymbol>,
257}
258
259impl Edge {
260    /// Whether the target can run as code through this edge (see
261    /// [`ImportLoadKind::runs_target_code`]). An edge whose every symbol is an
262    /// asset reference keeps the target in use, but reachability does not
263    /// continue into the imports of the target.
264    #[must_use]
265    fn runs_target_code(&self) -> bool {
266        self.symbols.is_empty()
267            || self
268                .symbols
269                .iter()
270                .any(|symbol| symbol.load_kind.runs_target_code())
271    }
272
273    /// Whether the target can run as code in the shipped program through this
274    /// edge (see [`ImportLoadKind::runs_at_runtime`]). An edge whose every
275    /// symbol is a macro import keeps the target reachable, but not runtime
276    /// reachable.
277    #[must_use]
278    fn runs_target_code_at_runtime(&self) -> bool {
279        self.symbols.is_empty()
280            || self
281                .symbols
282                .iter()
283                .any(|symbol| symbol.load_kind.runs_at_runtime())
284    }
285
286    /// Whether a test that loads the target through this edge runs target
287    /// code. The build erases a type-only import before the test runs, so an
288    /// edge whose every symbol is type-only gives no test reach. Dead-code
289    /// reachability keeps [`Self::runs_target_code`].
290    #[must_use]
291    fn runs_target_code_in_tests(&self) -> bool {
292        self.symbols.is_empty()
293            || self
294                .symbols
295                .iter()
296                .any(|symbol| !symbol.is_type_only && symbol.load_kind.runs_target_code())
297    }
298}
299
300/// One package specifier that a module imports statically with a runtime value.
301#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
302pub struct EagerPackageImport {
303    /// The package name, for example `lodash` or `@scope/pkg`.
304    pub package: String,
305    /// The specifier as written, for example `lodash/debounce`.
306    pub specifier: String,
307}
308
309/// A symbol imported across an edge.
310#[derive(Debug, serde::Serialize, serde::Deserialize)]
311pub struct ImportedSymbol {
312    /// The name as imported from the target (`Named`, `Default`, `Namespace`,
313    /// `SideEffect`).
314    pub imported_name: ImportedName,
315    /// Local binding name in the importing file.
316    pub local_name: String,
317    /// Byte span of the import statement in the source file.
318    #[serde(with = "crate::cache::span_serde")]
319    pub import_span: oxc_span::Span,
320    /// Whether this import is type-only (`import type { ... }`).
321    /// Used to skip type-only edges in circular dependency detection.
322    pub is_type_only: bool,
323    /// Whether the ambient star this symbol stands for is spelled
324    /// `export type *` (issue #2375), which forwards type meanings only.
325    pub(crate) is_type_only_star: bool,
326    /// Runtime module mechanism that created this symbol edge.
327    mechanism: ModuleLoadMechanism,
328    /// How the importer uses the local binding. TypeScript keeps an import
329    /// that the file reads as a value, also when the name has no value
330    /// declaration in the target (an ambient namespace, issue #5262), and
331    /// removes one that the file never reads as a value (issue #5309).
332    binding_use: import_elision::BindingUse,
333    /// When the target loads relative to the importer, and whether it runs
334    /// at all. Fits in the padding after the flags, so the 64-byte size
335    /// assertion holds.
336    load_kind: ImportLoadKind,
337}
338
339impl ImportedSymbol {
340    /// How the decorator metadata of the importer emits this binding, when
341    /// the importer uses it only in type positions. TypeScript always erases
342    /// an `import type`, so its binding never reaches the metadata.
343    pub(crate) const fn decorator_metadata(&self) -> Option<MetadataEmit> {
344        match self.binding_use {
345            import_elision::BindingUse::DecoratorMetadata(emit) if !self.is_type_only => Some(emit),
346            _ => None,
347        }
348    }
349
350    /// When the target of this symbol edge loads, relative to the importer.
351    #[must_use]
352    pub const fn load_kind(&self) -> ImportLoadKind {
353        self.load_kind
354    }
355
356    /// Whether this symbol loads its target before the importer runs and
357    /// carries a runtime value, so the target is on the startup path.
358    #[must_use]
359    pub const fn is_eager_value(&self) -> bool {
360        self.load_kind.is_eager_value(self.is_type_only)
361    }
362
363    /// Whether this symbol runs its target (see
364    /// [`ImportLoadKind::loads_target`]). A path reference and an asset
365    /// reference keep the target in use without running it.
366    #[must_use]
367    pub const fn loads_target(&self) -> bool {
368        self.load_kind.loads_target()
369    }
370
371    /// Whether this symbol is the whole-module shape of `export *` or
372    /// `export * as ns` inside a `declare module '...'` body (issue #2357):
373    /// type-only, bound to no local name, and naming the module namespace or
374    /// its `default` member (recorded for the `export * as ns` form).
375    ///
376    /// The ambient body is erased at runtime, so package usage stays
377    /// type-only, but the star forwards every export of the target, so the
378    /// graph credits its star surface instead of narrowing to imported names.
379    /// Every other type-only symbol, bound (`import type { x }`) or not (an
380    /// ambient named re-export, an `import()` type reference), credits the
381    /// names it actually imports.
382    #[must_use]
383    fn is_ambient_star(&self) -> bool {
384        self.is_type_only
385            && self.local_name.is_empty()
386            && matches!(
387                self.imported_name,
388                ImportedName::Namespace | ImportedName::Default
389            )
390    }
391
392    /// Whether this ambient star forwards both meanings of every name it
393    /// carries.
394    ///
395    /// `export *` inside the body re-exports the target's value and type
396    /// declarations alike, so it credits both namespaces. `export type *`
397    /// erases every value meaning (issue #2375), so it credits type space
398    /// only, exactly like the ambient named re-exports of issue #2349.
399    #[must_use]
400    fn is_value_bearing_ambient_star(&self) -> bool {
401        self.is_ambient_star() && !self.is_type_only_star
402    }
403}
404
405/// Flat bitset index mapping files to the test profiles that reach them.
406///
407/// Each file owns `words_per_file` contiguous reachable-profile words. Masks are
408/// target-sparse: only explicit replacement targets own a row, while every row
409/// retains dense profile words for constant-time word lookup. Retained storage
410/// is `O((files + replaced_targets) * ceil(profiles / 64))`; correlation queries
411/// intersect machine words instead of scanning profile file lists.
412#[derive(Debug, Default, serde::Serialize, serde::Deserialize)]
413struct TestReachabilityIndex {
414    profile_count: usize,
415    words_per_file: usize,
416    reachable_profiles: Vec<u64>,
417    masked_profiles: Vec<MaskedTestProfiles>,
418    /// The test roots of each profile, by profile index. The per-root query
419    /// reads it to find the replacement mask of one root.
420    profile_roots: Vec<Vec<FileId>>,
421    /// True when test roots declare replacement masks, but the distinct mask
422    /// count passed the profile safety cap. Reachability then ignores the
423    /// masks, so a mocked module counts as reached.
424    masking_capped: bool,
425}
426
427/// Sparse profile-mask row for one replaced target.
428#[derive(Debug, serde::Serialize, serde::Deserialize)]
429struct MaskedTestProfiles {
430    target: FileId,
431    profiles: Vec<u64>,
432}
433
434impl TestReachabilityIndex {
435    fn new(file_capacity: usize, profile_count: usize) -> Self {
436        let words_per_file = profile_count.div_ceil(u64::BITS as usize);
437        let storage_len = file_capacity.saturating_mul(words_per_file);
438        Self {
439            profile_count,
440            words_per_file,
441            reachable_profiles: vec![0; storage_len],
442            masked_profiles: Vec::new(),
443            profile_roots: Vec::new(),
444            masking_capped: false,
445        }
446    }
447
448    /// The replaced targets of each test root that has a replacement, sorted
449    /// by target id.
450    fn root_masks(&self) -> FxHashMap<FileId, Vec<FileId>> {
451        let mut masks: FxHashMap<FileId, Vec<FileId>> = FxHashMap::default();
452        for row in &self.masked_profiles {
453            for (profile, roots) in self.profile_roots.iter().enumerate() {
454                let masked = row
455                    .profiles
456                    .get(profile / u64::BITS as usize)
457                    .is_some_and(|word| word & (1_u64 << (profile % u64::BITS as usize)) != 0);
458                if !masked {
459                    continue;
460                }
461                for &root in roots {
462                    masks.entry(root).or_default().push(row.target);
463                }
464            }
465        }
466        masks
467    }
468
469    fn set_sparse_masks(&mut self, masks: FxHashMap<FileId, Vec<u64>>) {
470        let mut rows: Vec<_> = masks
471            .into_iter()
472            .map(|(target, profiles)| MaskedTestProfiles { target, profiles })
473            .collect();
474        rows.sort_unstable_by_key(|row| row.target.0);
475        self.masked_profiles = rows;
476    }
477
478    fn profiles_for<'a>(&self, storage: &'a [u64], file_id: FileId) -> Option<&'a [u64]> {
479        let start = (file_id.0 as usize).checked_mul(self.words_per_file)?;
480        let end = start.checked_add(self.words_per_file)?;
481        storage.get(start..end)
482    }
483
484    fn masked_profiles_for(&self, file_id: FileId) -> Option<&[u64]> {
485        self.masked_profiles
486            .binary_search_by_key(&file_id.0, |row| row.target.0)
487            .ok()
488            .map(|index| self.masked_profiles[index].profiles.as_slice())
489    }
490
491    fn covers_reference_path(
492        &self,
493        source: FileId,
494        path: types::ReferencePathId,
495        paths: &[ReferencePathNode],
496        routes: &ReferenceRoutes,
497    ) -> bool {
498        let Some(source_profiles) = self.profiles_for(&self.reachable_profiles, source) else {
499            return false;
500        };
501
502        for (word_index, &source_word) in source_profiles.iter().enumerate() {
503            let mut active_profiles = source_word;
504            if active_profiles == 0 {
505                continue;
506            }
507
508            let mut next = Some(path);
509            while let Some(path_id) = next {
510                let Some(path_node) = paths.get(path_id.index()) else {
511                    return false;
512                };
513                next = path_node.parent();
514                active_profiles = match *path_node {
515                    ReferencePathNode::Hop {
516                        target, mechanism, ..
517                    } => self.active_hop_profiles(target, mechanism, word_index, active_profiles),
518                    ReferencePathNode::Route {
519                        graph,
520                        start,
521                        terminal,
522                        start_mechanism,
523                        ..
524                    } => self.active_route_profiles(
525                        routes,
526                        graph,
527                        start,
528                        terminal,
529                        start_mechanism,
530                        word_index,
531                        active_profiles,
532                    ),
533                };
534                if active_profiles == 0 {
535                    break;
536                }
537            }
538
539            if active_profiles != 0 {
540                return true;
541            }
542        }
543
544        false
545    }
546
547    fn active_hop_profiles(
548        &self,
549        target: FileId,
550        mechanism: ModuleLoadMechanism,
551        word_index: usize,
552        mut active_profiles: u64,
553    ) -> u64 {
554        let Some(target_word) = self
555            .profiles_for(&self.reachable_profiles, target)
556            .and_then(|profiles| profiles.get(word_index))
557        else {
558            return 0;
559        };
560        active_profiles &= target_word;
561        if matches!(mechanism, ModuleLoadMechanism::EsModule)
562            && let Some(masked_profiles) = self.masked_profiles_for(target)
563        {
564            let Some(masked_word) = masked_profiles.get(word_index) else {
565                return 0;
566            };
567            active_profiles &= !masked_word;
568        }
569        active_profiles
570    }
571
572    /// Evaluate one compact namespace transition graph with a monotone
573    /// profile-bit worklist. Each `(route node, profile bit)` is processed at
574    /// most once, including cyclic graphs.
575    #[expect(
576        clippy::too_many_arguments,
577        reason = "the route identity and profile word form one evaluation contract"
578    )]
579    fn active_route_profiles(
580        &self,
581        routes: &ReferenceRoutes,
582        graph_id: types::ReferenceRouteGraphId,
583        start: ReferenceRouteNodeId,
584        terminal: ReferenceRouteNodeId,
585        start_mechanism: Option<ModuleLoadMechanism>,
586        word_index: usize,
587        candidate_profiles: u64,
588    ) -> u64 {
589        let Some(graph) = routes.graphs.get(graph_id.0 as usize) else {
590            return 0;
591        };
592        let node_count = graph.nodes.end.saturating_sub(graph.nodes.start) as usize;
593        let start_index = start.0 as usize;
594        let terminal_index = terminal.0 as usize;
595        if start_index >= node_count || terminal_index >= node_count {
596            return 0;
597        }
598
599        let mut attempted = vec![0_u64; node_count];
600        let mut pending = vec![0_u64; node_count];
601        let mut queued = vec![false; node_count];
602        let mut queue = std::collections::VecDeque::from([start_index]);
603        pending[start_index] = candidate_profiles;
604        queued[start_index] = true;
605        let mut successful_profiles = 0_u64;
606
607        while let Some(local_index) = queue.pop_front() {
608            queued[local_index] = false;
609            let incoming = pending[local_index] & !attempted[local_index];
610            pending[local_index] = 0;
611            attempted[local_index] |= incoming;
612            if incoming == 0 {
613                continue;
614            }
615
616            let Some(node) = routes.nodes.get(graph.nodes.start as usize + local_index) else {
617                return 0;
618            };
619            let active = if local_index == start_index {
620                start_mechanism.map_or(incoming, |mechanism| {
621                    self.active_hop_profiles(node.target, mechanism, word_index, incoming)
622                })
623            } else {
624                self.active_hop_profiles(node.target, node.mechanism, word_index, incoming)
625            };
626            if active == 0 {
627                continue;
628            }
629            if local_index == terminal_index {
630                successful_profiles |= active;
631                continue;
632            }
633
634            let Some(successors) = routes
635                .edges
636                .get(node.successors.start as usize..node.successors.end as usize)
637            else {
638                return 0;
639            };
640            for successor in successors {
641                let successor_index = successor.0 as usize;
642                if successor_index >= node_count {
643                    return 0;
644                }
645                let new_profiles = active & !attempted[successor_index] & !pending[successor_index];
646                if new_profiles == 0 {
647                    continue;
648                }
649                pending[successor_index] |= new_profiles;
650                if !queued[successor_index] {
651                    queued[successor_index] = true;
652                    queue.push_back(successor_index);
653                }
654            }
655        }
656
657        successful_profiles
658    }
659
660    #[cfg(test)]
661    fn profile_contains(&self, storage: &[u64], file_id: FileId, profile: usize) -> bool {
662        self.profiles_for(storage, file_id)
663            .and_then(|words| words.get(profile / u64::BITS as usize))
664            .is_some_and(|word| word & (1_u64 << (profile % u64::BITS as usize)) != 0)
665    }
666
667    #[cfg(test)]
668    fn profile_reaches(&self, file_id: FileId, profile: usize) -> bool {
669        self.profile_contains(&self.reachable_profiles, file_id, profile)
670    }
671
672    #[cfg(test)]
673    fn profile_masks(&self, file_id: FileId, profile: usize) -> bool {
674        self.masked_profiles_for(file_id)
675            .and_then(|words| words.get(profile / u64::BITS as usize))
676            .is_some_and(|word| word & (1_u64 << (profile % u64::BITS as usize)) != 0)
677    }
678}
679
680/// One outgoing edge that runs its target, from
681/// [`ModuleGraph::outgoing_edge_summaries`].
682#[derive(Debug, Clone, Copy)]
683pub struct OutgoingEdgeSummary<'a> {
684    /// The imported module.
685    pub target: FileId,
686    /// Whether every symbol that loads the target is type-only, so the build
687    /// erases the import.
688    pub all_type_only: bool,
689    /// Byte offset of the first value symbol that loads the target, or of
690    /// the first loading symbol when all of them are type-only.
691    pub span_start: Option<u32>,
692    /// Every symbol of the edge, also the symbols that do not load the
693    /// target. Filter with [`ImportedSymbol::loads_target`].
694    pub symbols: &'a [ImportedSymbol],
695}
696
697/// Importer details for one file that directly imports a target module.
698#[derive(Debug, Clone, PartialEq, Eq)]
699pub struct DirectImporterSummary {
700    /// Source file that imports the requested target.
701    pub source: FileId,
702    /// Symbols imported from the target by this source file.
703    pub symbols: Vec<ImportedSymbolSummary>,
704}
705
706/// Symbol details for a direct import edge.
707#[derive(Debug, Clone, PartialEq, Eq)]
708pub struct ImportedSymbolSummary {
709    /// Imported binding name, using `default`, `*`, and `side-effect` for
710    /// non-named imports.
711    pub imported: String,
712    /// Local binding name in the importing file.
713    pub local: String,
714    /// Whether this symbol came from a type-only import.
715    pub type_only: bool,
716}
717
718#[cfg(target_pointer_width = "64")]
719const _: () = assert!(std::mem::size_of::<Edge>() == 32);
720#[cfg(target_pointer_width = "64")]
721const _: () = assert!(std::mem::size_of::<ImportedSymbol>() == 64);
722
723#[cold]
724#[inline(never)]
725fn propagate_namespace_references(
726    graph: &mut ModuleGraph,
727    module_by_id: &FxHashMap<FileId, &ResolvedModule>,
728    features: build::NamespaceFeatures,
729    exposed_namespace_targets: &re_exports::ExposedNamespaceTargets,
730    reference_paths: &mut ReferencePathInterner,
731) {
732    let indexes = namespace_indexes::NamespacePropagationIndexes::new(graph, module_by_id);
733    if features.has_aliases {
734        namespace_aliases::propagate_cross_package_aliases(
735            graph,
736            module_by_id,
737            &indexes,
738            reference_paths,
739        );
740    }
741    if features.has_re_exports {
742        namespace_re_exports::propagate_namespace_re_exports(
743            graph,
744            &indexes,
745            exposed_namespace_targets,
746            reference_paths,
747        );
748    }
749}
750
751impl ModuleGraph {
752    /// True when the graph has a valid structure and holds exactly one module
753    /// for each file of `files`, with the same `FileId` and the same path.
754    ///
755    /// A graph from the cache is reused only when this holds, so each module
756    /// path that goes into a finding is a path that discovery found.
757    #[must_use]
758    pub fn describes_files(&self, files: &[DiscoveredFile]) -> bool {
759        self.modules.len() == files.len()
760            && self.has_valid_structure()
761            && self
762                .modules
763                .iter()
764                .zip(files)
765                .all(|(module, file)| (module.file_id, &module.path) == (file.id, &file.path))
766    }
767
768    fn resolve_entry_point_ids(
769        entry_points: &[EntryPoint],
770        path_to_id: &FxHashMap<&Path, FileId>,
771    ) -> FxHashSet<FileId> {
772        entry_points
773            .iter()
774            .filter_map(|ep| {
775                path_to_id.get(ep.path.as_path()).copied().or_else(|| {
776                    dunce::canonicalize(&ep.path)
777                        .ok()
778                        .and_then(|path| path_to_id.get(path.as_path()).copied())
779                })
780            })
781            .collect()
782    }
783
784    /// Build the module graph from resolved modules and entry points.
785    pub fn build(
786        resolved_modules: &[ResolvedModule],
787        entry_points: &[EntryPoint],
788        files: &[DiscoveredFile],
789    ) -> Self {
790        Self::build_with_reachability_roots(
791            resolved_modules,
792            entry_points,
793            entry_points,
794            &[],
795            files,
796        )
797    }
798
799    /// Build the module graph with explicit runtime and test reachability roots.
800    fn build_with_reachability_roots(
801        resolved_modules: &[ResolvedModule],
802        entry_points: &[EntryPoint],
803        runtime_entry_points: &[EntryPoint],
804        test_entry_points: &[EntryPoint],
805        files: &[DiscoveredFile],
806    ) -> Self {
807        Self::build_with_reachability_roots_and_replacements(
808            resolved_modules,
809            &[],
810            entry_points,
811            runtime_entry_points,
812            test_entry_points,
813            files,
814        )
815    }
816
817    /// Build the module graph with root-specific test-time module replacements.
818    pub fn build_with_reachability_roots_and_replacements(
819        resolved_modules: &[ResolvedModule],
820        replaced_module_targets: &[ResolvedReplacedModuleTarget],
821        entry_points: &[EntryPoint],
822        runtime_entry_points: &[EntryPoint],
823        test_entry_points: &[EntryPoint],
824        files: &[DiscoveredFile],
825    ) -> Self {
826        Self::build_with_declaration_seeding(
827            resolved_modules,
828            replaced_module_targets,
829            &ReachabilityRoots {
830                all: entry_points,
831                runtime: runtime_entry_points,
832                test: test_entry_points,
833                consumer_checked: &FxHashSet::default(),
834            },
835            files,
836            &FxHashSet::default(),
837        )
838    }
839
840    /// Build the module graph like
841    /// [`Self::build_with_reachability_roots_and_replacements`], except that
842    /// the declaration files in `unseeded_declaration_files` are not seeded as
843    /// entry points.
844    ///
845    /// Every other declaration file is seeded so ambient declarations and
846    /// their `typeof import()` references stay alive. The caller names the
847    /// orphan module declaration files: a module declaration file that nothing
848    /// points to adds nothing to the global scope, so it must be reachable
849    /// through an import to stay used.
850    pub fn build_with_declaration_seeding(
851        resolved_modules: &[ResolvedModule],
852        replaced_module_targets: &[ResolvedReplacedModuleTarget],
853        roots: &ReachabilityRoots<'_>,
854        files: &[DiscoveredFile],
855        unseeded_declaration_files: &FxHashSet<FileId>,
856    ) -> Self {
857        let ReachabilityRoots {
858            all: entry_points,
859            runtime: runtime_entry_points,
860            test: test_entry_points,
861            consumer_checked,
862        } = *roots;
863        let _span = tracing::info_span!("build_graph").entered();
864
865        let module_count = files.len();
866
867        let max_file_id = files
868            .iter()
869            .map(|f| f.id.0 as usize)
870            .max()
871            .map_or(0, |m| m + 1);
872        let total_capacity = max_file_id.max(module_count);
873
874        let path_to_id: FxHashMap<&Path, FileId> =
875            files.iter().map(|f| (f.path.as_path(), f.id)).collect();
876
877        let module_by_id: FxHashMap<FileId, &ResolvedModule> =
878            resolved_modules.iter().map(|m| (m.file_id, m)).collect();
879
880        let mut entry_point_ids = Self::resolve_entry_point_ids(entry_points, &path_to_id);
881        let runtime_entry_point_ids =
882            Self::resolve_entry_point_ids(runtime_entry_points, &path_to_id);
883        let test_entry_point_ids = Self::resolve_entry_point_ids(test_entry_points, &path_to_id);
884
885        for file in files {
886            if is_declaration_file_path(&file.path)
887                && !unseeded_declaration_files.contains(&file.id)
888            {
889                entry_point_ids.insert(file.id);
890            }
891        }
892
893        let (mut graph, namespace_features) = Self::populate_edges(&build::PopulateEdgesInput {
894            files,
895            module_by_id: &module_by_id,
896            entry_point_ids: &entry_point_ids,
897            runtime_entry_point_ids: &runtime_entry_point_ids,
898            test_entry_point_ids: &test_entry_point_ids,
899            module_count,
900            total_capacity,
901        });
902        graph.index_exports(resolved_modules, consumer_checked);
903
904        let test_reachability_plan = reachability::TestReachabilityPlan::new(
905            &test_entry_point_ids,
906            replaced_module_targets,
907            total_capacity,
908        );
909
910        let mut reference_paths =
911            ReferencePathInterner::new(test_reachability_plan.requires_reference_provenance());
912        let mut whole_module_targets =
913            graph.populate_references(&module_by_id, &entry_point_ids, &mut reference_paths);
914        graph.namespace_escapes = whole_module_targets.take_escapes();
915        // Entry-point reachability depends on edges alone, so it is available
916        // here and is reused verbatim by `mark_reachable` below. The exposed
917        // namespace closure needs it to stay off modules the report already
918        // calls unused files.
919        let entry_reachable = graph.collect_reachable(&entry_point_ids, total_capacity);
920        let exposed_namespace_targets = graph.collect_exposed_namespace_targets(
921            &whole_module_targets,
922            &entry_reachable,
923            &module_by_id,
924        );
925
926        if namespace_features.has_aliases || namespace_features.has_re_exports {
927            propagate_namespace_references(
928                &mut graph,
929                &module_by_id,
930                namespace_features,
931                &exposed_namespace_targets,
932                &mut reference_paths,
933            );
934        }
935
936        graph.mark_reachable(
937            &entry_reachable,
938            &entry_point_ids,
939            &runtime_entry_point_ids,
940            test_reachability_plan,
941            total_capacity,
942        );
943
944        graph.re_export_cycles = graph.resolve_re_export_chains(
945            &module_by_id,
946            &exposed_namespace_targets,
947            consumer_checked,
948            &mut reference_paths,
949        );
950        graph.credit_platform_family_re_exports(&module_by_id);
951        namespace_escapes::normalize(&mut graph.namespace_escapes);
952        let finalized_paths = reference_paths.finalize(&mut graph.modules);
953        graph.reference_paths = finalized_paths.paths;
954        graph.reference_routes = finalized_paths.routes;
955
956        graph
957    }
958
959    /// Total number of modules.
960    #[must_use]
961    pub const fn module_count(&self) -> usize {
962        self.modules.len()
963    }
964
965    /// All modules, in `FileId` order: the module at index `i` has
966    /// `file_id == FileId(i)`.
967    #[inline]
968    #[must_use]
969    pub fn modules(&self) -> &[ModuleNode] {
970        &self.modules
971    }
972
973    /// The module of `file_id`, or `None` when the id is not in the graph.
974    #[inline]
975    #[must_use]
976    pub fn module(&self, file_id: FileId) -> Option<&ModuleNode> {
977        self.modules.get(file_id.0 as usize)
978    }
979
980    /// Mutable access to the modules, for tests in other crates that patch
981    /// a built graph.
982    #[cfg(any(test, feature = "testing"))]
983    #[must_use]
984    pub fn modules_mut(&mut self) -> &mut Vec<ModuleNode> {
985        &mut self.modules
986    }
987
988    /// Total number of edges.
989    #[must_use]
990    pub const fn edge_count(&self) -> usize {
991        self.edges.len()
992    }
993
994    /// Return whether any test-root traversal reaches `file_id`.
995    #[must_use]
996    pub fn is_test_reachable(&self, file_id: FileId) -> bool {
997        self.modules
998            .get(file_id.0 as usize)
999            .is_some_and(ModuleNode::is_test_reachable)
1000    }
1001
1002    /// Return whether one test-root traversal covers the export reference at
1003    /// `reference_index` on `export`.
1004    ///
1005    /// Coverage requires one profile that reaches the referencing file and
1006    /// every target hop. ESM hops also require that profile not to replace the
1007    /// hop target; CommonJS hops remain active because Vitest replacement mocks
1008    /// do not intercept `require()`.
1009    ///
1010    /// Only a reference that runs the export can give coverage (see
1011    /// [`ModuleGraph::reference_runs_export`]).
1012    #[must_use]
1013    fn is_test_reference_covered(&self, export: &ExportSymbol, reference_index: usize) -> bool {
1014        let Some(reference) = export.references.get(reference_index) else {
1015            return false;
1016        };
1017        if !self.reference_runs_export(reference) {
1018            return false;
1019        }
1020        if self.test_reachability_index.profile_count == 0 {
1021            return self.is_test_reachable(reference.from_file);
1022        }
1023
1024        let Some(path) = export.reference_path(reference_index) else {
1025            return false;
1026        };
1027
1028        self.test_reachability_index.covers_reference_path(
1029            reference.from_file,
1030            path,
1031            &self.reference_paths,
1032            &self.reference_routes,
1033        )
1034    }
1035
1036    /// Whether `reference` reads the export at runtime. A value reference
1037    /// does. A type reference does not, which includes `import type` and a
1038    /// plain import that the file uses only in type positions. The exception
1039    /// is a type position that the decorator metadata of the file reads
1040    /// (issue #5362).
1041    fn reference_runs_export(&self, reference: &SymbolReference) -> bool {
1042        reference.namespace == ExportNamespace::Value
1043            || reference.decorator_metadata.is_some_and(|emit| {
1044                self.decorator_metadata_elision
1045                    .get(&reference.from_file)
1046                    .is_some_and(|elision| elision.reads_decorator_metadata(emit))
1047            })
1048    }
1049
1050    /// Read the [`ImportElision`] of each module whose decorator metadata
1051    /// emits an import binding. `elision_of` gets the path of each such
1052    /// TypeScript module. Call it after each build or cache load, before a
1053    /// test coverage query.
1054    pub fn read_decorator_metadata_options(
1055        &mut self,
1056        elision_of: &mut dyn FnMut(&Path) -> ImportElision,
1057    ) {
1058        self.decorator_metadata_elision = self
1059            .modules
1060            .iter()
1061            .filter(|module| module.has_decorator_metadata())
1062            .map(|module| {
1063                let elision = import_elision::ImporterElision::new(&module.path)
1064                    .get(&module.path, elision_of);
1065                (module.file_id, elision)
1066            })
1067            .collect();
1068    }
1069
1070    /// Return whether any reference on `export` is covered by a test-root
1071    /// traversal.
1072    #[must_use]
1073    pub fn is_any_test_reference_covered(&self, export: &ExportSymbol) -> bool {
1074        (0..export.references.len())
1075            .any(|reference_index| self.is_test_reference_covered(export, reference_index))
1076    }
1077
1078    #[cfg(test)]
1079    fn reference_path_hops(
1080        &self,
1081        export: &ExportSymbol,
1082        reference_index: usize,
1083    ) -> Vec<(FileId, ModuleLoadMechanism)> {
1084        let mut hops = Vec::new();
1085        let mut next = export.reference_path(reference_index);
1086        while let Some(path_id) = next {
1087            let Some(node) = self.reference_paths.get(path_id.index()) else {
1088                return Vec::new();
1089            };
1090            next = node.parent();
1091            match *node {
1092                ReferencePathNode::Hop {
1093                    target, mechanism, ..
1094                } => hops.push((target, mechanism)),
1095                ReferencePathNode::Route {
1096                    graph,
1097                    start,
1098                    terminal,
1099                    start_mechanism,
1100                    ..
1101                } => hops.extend(self.reference_routes.canonical_hops(
1102                    graph,
1103                    start,
1104                    terminal,
1105                    start_mechanism,
1106                )),
1107            }
1108        }
1109        hops
1110    }
1111
1112    /// Rebuild the `namespace_imported` bitset from the edge set.
1113    ///
1114    /// `namespace_imported` is `#[serde(skip)]`, so a graph loaded from the
1115    /// persisted cache (`crate::cache`) arrives with an empty default bitset.
1116    /// This restores it by replicating the EXACT insertion rule from
1117    /// `build.rs`: a target `FileId` is namespace-imported iff some edge to it
1118    /// carries an `ImportedName::Namespace` symbol. Both build-time insertion
1119    /// sites (static / dynamic `import * as ns` in `collect_import_edge`, and
1120    /// glob dynamic-import patterns in `collect_edges_for_module`) push a
1121    /// `Namespace` symbol onto the target's edge, so iterating the persisted
1122    /// edges and checking for a `Namespace` symbol reproduces the original
1123    /// bitset bit-for-bit. The capacity matches `build.rs`'s
1124    /// `max_file_id.max(module_count)`, which equals `modules.len()` under the
1125    /// dense path-sorted FileId invariant.
1126    pub(crate) fn reconstruct_namespace_imported(&mut self) {
1127        let capacity = self
1128            .edges
1129            .iter()
1130            .map(|edge| edge.target.0 as usize + 1)
1131            .max()
1132            .unwrap_or(0)
1133            .max(self.modules.len());
1134        let mut bitset = FixedBitSet::with_capacity(capacity);
1135        for edge in &self.edges {
1136            if edge
1137                .symbols
1138                .iter()
1139                .any(|sym| matches!(sym.imported_name, ImportedName::Namespace))
1140            {
1141                let idx = edge.target.0 as usize;
1142                if idx < capacity {
1143                    bitset.insert(idx);
1144                }
1145            }
1146        }
1147        self.namespace_imported = bitset;
1148    }
1149
1150    /// Resolve the effective declaration exported under `name` in one namespace.
1151    ///
1152    /// This is the canonical graph contract for direct exports and every named
1153    /// or star re-export path. Missing and ambiguous bindings are explicit so
1154    /// consumers cannot accidentally credit an arbitrary source declaration.
1155    #[must_use]
1156    pub fn resolve_export(
1157        &self,
1158        file_id: FileId,
1159        name: &str,
1160        namespace: ExportNamespace,
1161    ) -> EffectiveExportResolution {
1162        self.effective_exports.resolve(file_id, name, namespace)
1163    }
1164
1165    /// Whether two effective bindings denote the same declaration surface.
1166    ///
1167    /// TypeScript declaration merges occupy separate export slots while
1168    /// representing one symbol. Consumers that compare type and value lanes
1169    /// use this instead of raw binding equality so either half can carry the
1170    /// reference credit for the merged declaration.
1171    #[must_use]
1172    pub fn effective_bindings_share_declaration_group(
1173        &self,
1174        left: EffectiveExportBinding,
1175        right: EffectiveExportBinding,
1176    ) -> bool {
1177        if left == right || left.origin_file() != right.origin_file() {
1178            return left == right;
1179        }
1180        let Some(right_slot) = right.origin_slot() else {
1181            return false;
1182        };
1183        self.effective_exports
1184            .declaration_group_slots(left)
1185            .contains(&right_slot)
1186    }
1187
1188    /// Resolve one exported name to its unique direct declaration.
1189    ///
1190    /// Missing and ambiguous bindings return `None`. Namespace-object exports
1191    /// are bindings in their own right rather than direct declarations, so
1192    /// they also have no declaration origin.
1193    #[must_use]
1194    pub fn resolve_export_origin(
1195        &self,
1196        file_id: FileId,
1197        name: &str,
1198        namespace: ExportNamespace,
1199    ) -> Option<EffectiveExportOrigin<'_>> {
1200        let EffectiveExportResolution::Unique(binding) =
1201            self.resolve_export(file_id, name, namespace)
1202        else {
1203            return None;
1204        };
1205        self.export_binding_origin(binding)
1206    }
1207
1208    /// Resolve one module surface to its canonical binding and reference-bearing
1209    /// graph export. Value and type namespaces are selected independently.
1210    #[must_use]
1211    pub fn effective_export_surface(
1212        &self,
1213        file_id: FileId,
1214        name: &str,
1215        namespace: ExportNamespace,
1216    ) -> Option<EffectiveExportSurface<'_>> {
1217        let EffectiveExportResolution::Unique(binding) =
1218            self.resolve_export(file_id, name, namespace)
1219        else {
1220            return None;
1221        };
1222        let module = self.modules.get(file_id.0 as usize)?;
1223        let exact_surface = module.exports.iter().find(|export| {
1224            export.name.matches_str(name)
1225                && match namespace {
1226                    ExportNamespace::Type => export.is_type_only,
1227                    ExportNamespace::Value => !export.is_type_only,
1228                }
1229        });
1230        let surface_export = exact_surface.or_else(|| {
1231            module
1232                .exports
1233                .iter()
1234                .find(|export| export.name.matches_str(name))
1235        });
1236        let origin = self.export_binding_origin(binding);
1237        let export = surface_export.or_else(|| origin.map(|o| o.export));
1238        Some(EffectiveExportSurface {
1239            binding,
1240            namespace,
1241            export,
1242            origin,
1243            local_export: surface_export.is_some(),
1244        })
1245    }
1246
1247    /// Local re-export specifier that owns one effective module surface.
1248    ///
1249    /// Direct declarations and star-only forwarded surfaces return `None`.
1250    /// Named and namespace re-exports return the namespace-compatible edge
1251    /// whose source resolves to the same canonical binding.
1252    #[must_use]
1253    pub fn effective_export_surface_re_export(
1254        &self,
1255        file_id: FileId,
1256        name: &str,
1257        namespace: ExportNamespace,
1258    ) -> Option<&ReExportEdge> {
1259        let EffectiveExportResolution::Unique(binding) =
1260            self.resolve_export(file_id, name, namespace)
1261        else {
1262            return None;
1263        };
1264        self.modules
1265            .get(file_id.0 as usize)?
1266            .re_exports
1267            .iter()
1268            .find(|re_export| {
1269                re_export.exported_name == name
1270                    && (namespace == ExportNamespace::Type || !re_export.is_type_only)
1271                    && if re_export.imported_name == "*" {
1272                        binding.namespace_source() == Some(re_export.source_file)
1273                    } else {
1274                        self.resolve_export(
1275                            re_export.source_file,
1276                            &re_export.imported_name,
1277                            namespace,
1278                        ) == EffectiveExportResolution::Unique(binding)
1279                    }
1280            })
1281    }
1282
1283    /// References that reach one exact module export surface.
1284    ///
1285    /// Star-only surfaces share their declaration with other barrels, so their
1286    /// origin references are filtered by recorded provenance instead of being
1287    /// borrowed wholesale from the declaration.
1288    #[must_use]
1289    pub fn effective_export_surface_references(
1290        &self,
1291        file_id: FileId,
1292        name: &str,
1293        namespace: ExportNamespace,
1294    ) -> Vec<&SymbolReference> {
1295        let Some(surface) = self.effective_export_surface(file_id, name, namespace) else {
1296            return Vec::new();
1297        };
1298        let Some(export) = surface.export() else {
1299            return Vec::new();
1300        };
1301        if surface.local_export
1302            || surface
1303                .origin()
1304                .is_none_or(|origin| origin.file_id() == file_id)
1305        {
1306            return export.references_in(namespace).collect();
1307        }
1308        let mut exposed: FxHashMap<FileId, FxHashSet<String>> = FxHashMap::default();
1309        exposed.entry(file_id).or_default().insert(name.to_string());
1310        for route in self.effective_re_export_routes(file_id, name, namespace) {
1311            exposed
1312                .entry(route.barrel_file())
1313                .or_default()
1314                .insert(route.exported_name().to_string());
1315        }
1316        export
1317            .references
1318            .iter()
1319            .filter(|reference| {
1320                reference.namespace == namespace
1321                    && self.reference_reaches_surface(reference, &exposed, namespace)
1322            })
1323            .collect()
1324    }
1325
1326    fn reference_reaches_surface(
1327        &self,
1328        reference: &SymbolReference,
1329        exposed: &FxHashMap<FileId, FxHashSet<String>>,
1330        namespace: ExportNamespace,
1331    ) -> bool {
1332        if reference.kind == ReferenceKind::ReExport && exposed.contains_key(&reference.from_file) {
1333            return true;
1334        }
1335        self.outgoing_symbol_edges(reference.from_file)
1336            .any(|(target, symbols)| {
1337                let Some(names) = exposed.get(&target) else {
1338                    return false;
1339                };
1340                symbols.iter().any(|symbol| {
1341                    symbol.import_span == reference.import_span
1342                        && (namespace == ExportNamespace::Type
1343                            || !symbol.is_type_only
1344                            || symbol.is_value_bearing_ambient_star())
1345                        && match &symbol.imported_name {
1346                            ImportedName::Named(imported) => names.contains(imported.as_str()),
1347                            ImportedName::Default => names.contains("default"),
1348                            ImportedName::Namespace => true,
1349                            ImportedName::SideEffect => false,
1350                        }
1351                })
1352            })
1353    }
1354
1355    /// Resolve a unique binding to its direct declaration, when it has one.
1356    #[must_use]
1357    pub fn export_binding_origin(
1358        &self,
1359        binding: EffectiveExportBinding,
1360    ) -> Option<EffectiveExportOrigin<'_>> {
1361        let origin_file = binding.origin_file();
1362        let export = self
1363            .modules
1364            .get(origin_file.0 as usize)?
1365            .exports
1366            .get(binding.origin_slot()?)?;
1367        Some(EffectiveExportOrigin {
1368            file_id: origin_file,
1369            export,
1370        })
1371    }
1372
1373    /// Unique bindings exposed by a module in one namespace.
1374    ///
1375    /// Multiple names that resolve to the same declaration are deduplicated;
1376    /// missing and ambiguous exports are excluded.
1377    #[must_use]
1378    pub fn unique_export_bindings(
1379        &self,
1380        file_id: FileId,
1381        namespace: ExportNamespace,
1382    ) -> FxHashSet<EffectiveExportBinding> {
1383        self.effective_exports.unique_bindings(file_id, namespace)
1384    }
1385
1386    /// Whether `importer` connects to `source` as an origin of `name`.
1387    ///
1388    /// Any direct import connects the two modules for duplicate-export
1389    /// grouping, even when it imports a different symbol. A re-export-only edge
1390    /// connects them only when it contributes this binding, including each
1391    /// contributor to an ambiguous star export and excluding star bindings
1392    /// shadowed by an explicit export.
1393    #[must_use]
1394    pub fn importer_connects_export_origin(
1395        &self,
1396        importer: FileId,
1397        source: FileId,
1398        name: &str,
1399        namespace: ExportNamespace,
1400    ) -> bool {
1401        let Some(importer_module) = self.modules.get(importer.0 as usize) else {
1402            return false;
1403        };
1404        let re_export_count = importer_module
1405            .re_exports
1406            .iter()
1407            .filter(|re_export| re_export.source_file == source)
1408            .count();
1409        if self.edges[importer_module.edge_range.clone()]
1410            .iter()
1411            .any(|edge| edge.target == source && edge.symbols.len() > re_export_count)
1412        {
1413            return true;
1414        }
1415
1416        importer_module.re_exports.iter().any(|re_export| {
1417            if re_export.source_file != source
1418                || (namespace == ExportNamespace::Value && re_export.is_type_only)
1419            {
1420                return false;
1421            }
1422            let exported_name = if re_export.imported_name == "*" {
1423                if re_export.exported_name != "*" || name == "default" {
1424                    return false;
1425                }
1426                name
1427            } else {
1428                if re_export.imported_name != name {
1429                    return false;
1430                }
1431                &re_export.exported_name
1432            };
1433            self.effective_exports.contributes_through(
1434                importer,
1435                exported_name,
1436                source,
1437                name,
1438                namespace,
1439            )
1440        })
1441    }
1442
1443    /// Check if any importer uses `import * as ns` for this module.
1444    /// Uses precomputed bitset, O(1) lookup.
1445    #[must_use]
1446    pub fn has_namespace_import(&self, file_id: FileId) -> bool {
1447        // `FixedBitSet::contains` is false for an index past the end.
1448        self.namespace_imported.contains(file_id.0 as usize)
1449    }
1450
1451    /// Get the target `FileId`s of all outgoing edges for a module.
1452    #[must_use]
1453    pub fn edges_for(&self, file_id: FileId) -> Vec<FileId> {
1454        let idx = file_id.0 as usize;
1455        if idx >= self.modules.len() {
1456            return Vec::new();
1457        }
1458        let range = &self.modules[idx].edge_range;
1459        self.edges[range.clone()].iter().map(|e| e.target).collect()
1460    }
1461
1462    /// Iterate the outgoing edges of `file_id` with full per-symbol data.
1463    ///
1464    /// `fallow trace` needs the raw `ImportedSymbol` set on each edge in
1465    /// both directions, which the flattened summary structs cannot express.
1466    /// Returns an empty iterator for out-of-range file ids.
1467    pub fn outgoing_symbol_edges(
1468        &self,
1469        file_id: FileId,
1470    ) -> impl Iterator<Item = (FileId, &[ImportedSymbol])> + '_ {
1471        let idx = file_id.0 as usize;
1472        let range = if idx < self.modules.len() {
1473            self.modules[idx].edge_range.clone()
1474        } else {
1475            0..0
1476        };
1477        self.edges[range]
1478            .iter()
1479            .map(|edge| (edge.target, edge.symbols.as_slice()))
1480    }
1481
1482    /// The importer `FileId`s that directly import `target` (reverse-dep view).
1483    ///
1484    /// Returns an empty slice when `target` is out of range.
1485    #[must_use]
1486    pub fn importers_of(&self, target: FileId) -> &[FileId] {
1487        self.reverse_deps
1488            .get(target.0 as usize)
1489            .map_or(&[], Vec::as_slice)
1490    }
1491
1492    /// Summarize files that directly import `target`.
1493    ///
1494    /// Uses existing reverse dependency and edge indexes. Returns an empty
1495    /// list when the target is out of range or has no importers.
1496    #[must_use]
1497    pub fn direct_importer_summaries(&self, target: FileId) -> Vec<DirectImporterSummary> {
1498        let Some(importers) = self.reverse_deps.get(target.0 as usize) else {
1499            return Vec::new();
1500        };
1501
1502        let mut summaries = Vec::new();
1503        for &source in importers {
1504            let idx = source.0 as usize;
1505            let Some(source_node) = self.modules.get(idx) else {
1506                continue;
1507            };
1508            let mut symbols = Vec::new();
1509            for edge in &self.edges[source_node.edge_range.clone()] {
1510                if edge.target != target {
1511                    continue;
1512                }
1513                symbols.extend(edge.symbols.iter().map(|symbol| ImportedSymbolSummary {
1514                    imported: imported_name_label(&symbol.imported_name),
1515                    local: symbol.local_name.clone(),
1516                    type_only: symbol.is_type_only,
1517                }));
1518            }
1519            symbols.sort_by(|a, b| {
1520                a.imported
1521                    .cmp(&b.imported)
1522                    .then_with(|| a.local.cmp(&b.local))
1523                    .then_with(|| a.type_only.cmp(&b.type_only))
1524            });
1525            symbols.dedup();
1526            summaries.push(DirectImporterSummary { source, symbols });
1527        }
1528        summaries.sort_by_key(|summary| summary.source.0);
1529        summaries
1530    }
1531
1532    /// Iterate the outgoing edges of `file_id` that run their target, with
1533    /// the data the boundary detector and the security scans need in a single
1534    /// pass.
1535    ///
1536    /// Only symbols that load the target count (see
1537    /// [`ImportedSymbol::loads_target`]). A `require.resolve('./x')` path
1538    /// reference and an asset loader request (`raw-loader!./x.js`) keep the
1539    /// target in use but do not run it, so they cannot cross an architecture
1540    /// boundary or carry code into a bundle. An edge without such a symbol is
1541    /// skipped.
1542    ///
1543    /// When `featureB` has both `import type { Foo } from './x'` and
1544    /// `import { bar } from './x'`, fallow groups them into ONE edge with the
1545    /// type-only symbol first and the value symbol second. The summary
1546    /// anchors on the value symbol, so findings anchor on the runtime import
1547    /// line; otherwise a `// fallow-ignore-next-line` above the type-only line
1548    /// would silently suppress the real violation.
1549    ///
1550    /// Returns an empty iterator for out-of-range file ids.
1551    pub fn outgoing_edge_summaries(
1552        &self,
1553        file_id: FileId,
1554    ) -> impl Iterator<Item = OutgoingEdgeSummary<'_>> + '_ {
1555        self.outgoing_symbol_edges(file_id)
1556            .filter_map(|(target, symbols)| {
1557                let mut loading = symbols.iter().filter(|s| s.loads_target()).peekable();
1558                let first = loading.peek().copied()?;
1559                let value = loading.find(|s| !s.is_type_only);
1560                Some(OutgoingEdgeSummary {
1561                    target,
1562                    all_type_only: value.is_none(),
1563                    span_start: Some(value.unwrap_or(first).import_span.start),
1564                    symbols,
1565                })
1566            })
1567    }
1568
1569    /// Iterate outgoing edges with the symbols of each edge.
1570    ///
1571    /// One edge holds every import from `file_id` to one target, so
1572    /// `import type { Y } from './y'` and `import { y } from './y'` share an
1573    /// edge. Use this method when a consumer must suppress or report each
1574    /// import statement on its own line; [`Self::outgoing_edge_summaries`]
1575    /// gives only one span per edge. A re-export or a dynamic import pattern
1576    /// has an empty `import_span`.
1577    ///
1578    /// Returns an empty iterator for out-of-range file ids.
1579    pub fn outgoing_edge_symbols(
1580        &self,
1581        file_id: FileId,
1582    ) -> impl Iterator<Item = (FileId, &[ImportedSymbol])> + '_ {
1583        let idx = file_id.0 as usize;
1584        let range = if idx < self.modules.len() {
1585            self.modules[idx].edge_range.clone()
1586        } else {
1587            0..0
1588        };
1589        self.edges[range]
1590            .iter()
1591            .map(|edge| (edge.target, edge.symbols.as_slice()))
1592    }
1593
1594    /// Like [`Self::outgoing_edge_summaries`] (only edges that run their
1595    /// target, and only their loading symbols) but additionally reports, as a
1596    /// fourth boolean, whether EVERY non-type-only symbol on the edge has an
1597    /// `import_span` start in `excluded_span_starts` (`all_client_only`). The
1598    /// security `client-server-leak` BFS passes the `next/dynamic ssr:false`
1599    /// dynamic-import span starts so it can skip an edge reached ONLY through the
1600    /// client-only escape hatch. An edge with no non-type-only symbols, or with at
1601    /// least one non-type-only symbol whose span is not excluded, reports `false`
1602    /// (so a target also reached via a real static import stays in the cone).
1603    ///
1604    /// Unlike [`Self::outgoing_edge_summaries`], a named symbol also counts as
1605    /// type-only when the name resolves on the target to a type declaration and
1606    /// to no value declaration (`import { Props } from "./x"` where `x` has
1607    /// `export interface Props`). The build erases such an import, so it cannot
1608    /// leak into a client bundle. Default, namespace, and side-effect imports,
1609    /// and names that do not resolve to a type, stay live.
1610    ///
1611    /// Returns an empty iterator for out-of-range file ids.
1612    pub fn outgoing_edge_summaries_with_exclusions<'a>(
1613        &'a self,
1614        file_id: FileId,
1615        excluded_span_starts: &'a FxHashSet<u32>,
1616    ) -> impl Iterator<Item = (FileId, bool, Option<u32>, bool)> + 'a {
1617        let idx = file_id.0 as usize;
1618        let range = if idx < self.modules.len() {
1619            self.modules[idx].edge_range.clone()
1620        } else {
1621            0..0
1622        };
1623        self.edges[range].iter().filter_map(move |edge| {
1624            let loading = || edge.symbols.iter().filter(|s| s.loads_target());
1625            let first = loading().next()?;
1626            let erased = |s: &&ImportedSymbol| {
1627                s.is_type_only || self.names_only_type_exports(edge.target, &s.imported_name)
1628            };
1629            let all_type_only = loading().all(|s| erased(&s));
1630            let span = loading()
1631                .find(|s| !erased(s))
1632                .unwrap_or(first)
1633                .import_span
1634                .start;
1635            // `all_client_only`: there is at least one non-type-only symbol and
1636            // every such symbol's import span is in the excluded set. A
1637            // non-excluded value symbol keeps the edge live.
1638            let mut value_symbols = loading().filter(|s| !erased(s)).peekable();
1639            let all_client_only = value_symbols.peek().is_some()
1640                && value_symbols.all(|s| excluded_span_starts.contains(&s.import_span.start));
1641            Some((edge.target, all_type_only, Some(span), all_client_only))
1642        })
1643    }
1644}
1645
1646impl ModuleGraph {
1647    /// Return `true` when `name` is a named import that resolves on `target`
1648    /// to a type declaration and to no value declaration. Default, namespace,
1649    /// and side-effect imports return `false`, and so does a name that the
1650    /// graph cannot resolve in the type namespace.
1651    fn names_only_type_exports(&self, target: FileId, name: &ImportedName) -> bool {
1652        let ImportedName::Named(name) = name else {
1653            return false;
1654        };
1655        matches!(
1656            self.resolve_export(target, name, ExportNamespace::Value),
1657            EffectiveExportResolution::Missing
1658        ) && matches!(
1659            self.resolve_export(target, name, ExportNamespace::Type),
1660            EffectiveExportResolution::Unique(_)
1661        )
1662    }
1663
1664    /// Whether an edge holds a macro import. A macro import runs its target
1665    /// only in the bundler, so without one the runtime pass over the overall
1666    /// entry points equals the overall pass.
1667    fn has_build_time_edge(&self) -> bool {
1668        self.edges.iter().any(|edge| {
1669            edge.symbols
1670                .iter()
1671                .any(|symbol| symbol.load_kind == ImportLoadKind::BuildTime)
1672        })
1673    }
1674
1675    /// BFS from `entry_points` over the edges that run their target in the
1676    /// shipped program.
1677    fn collect_runtime_reachable(
1678        &self,
1679        entry_points: &FxHashSet<FileId>,
1680        total_capacity: usize,
1681    ) -> FixedBitSet {
1682        self.collect_reachable_along(
1683            entry_points,
1684            total_capacity,
1685            Edge::runs_target_code_at_runtime,
1686        )
1687    }
1688}
1689
1690fn imported_name_label(name: &ImportedName) -> String {
1691    match name {
1692        ImportedName::Named(name) => name.clone(),
1693        ImportedName::Default => "default".to_string(),
1694        ImportedName::Namespace => "*".to_string(),
1695        ImportedName::SideEffect => "side-effect".to_string(),
1696    }
1697}
1698
1699#[cfg(test)]
1700#[path = "graph_tests.rs"]
1701mod tests;