fallow-engine 3.23.0

Typed analysis engine facade for fallow consumers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
//! Module graph contracts owned by the engine boundary.

#![allow(
    clippy::implicit_hasher,
    reason = "engine graph helpers use FxHashSet changed-file sets consistently with the rest of fallow"
)]

use std::path::{Path, PathBuf};

use fallow_output::TestAdjacency;
use fallow_types::discover::FileId;
use rustc_hash::{FxHashMap, FxHashSet};

use fallow_graph::graph::{
    CoordinationGapPaths as GraphCoordinationGapPaths,
    FocusFileFactsPaths as GraphFocusFileFactsPaths, ImpactClosurePaths as GraphImpactClosurePaths,
    ModuleGraph, PartitionOrderPaths as GraphPartitionOrderPaths,
    ReviewUnitPaths as GraphReviewUnitPaths,
};
use fallow_graph::graph::{
    DirectImporterSummary as GraphDirectImporterSummary,
    ImportedSymbolSummary as GraphImportedSymbolSummary,
};

/// Engine-owned retained graph handle.
///
/// Downstream crates can request stable graph facts through engine helpers
/// without depending on `fallow-graph` node internals.
#[derive(Debug)]
pub struct RetainedModuleGraph {
    inner: ModuleGraph,
}

impl RetainedModuleGraph {
    /// Wrap a freshly built module graph for engine result contracts.
    #[must_use]
    const fn new(inner: ModuleGraph) -> Self {
        Self { inner }
    }

    pub(crate) const fn as_graph(&self) -> &ModuleGraph {
        &self.inner
    }

    /// Borrow the shared static test-coverage view for health analysis.
    pub(crate) const fn static_test_coverage(&self) -> StaticTestCoverage<'_> {
        StaticTestCoverage::new(&self.inner)
    }

    /// Number of modules in the retained graph.
    #[must_use]
    pub fn module_count(&self) -> usize {
        self.inner.module_count()
    }

    /// Number of edges in the retained graph.
    #[must_use]
    pub fn edge_count(&self) -> usize {
        self.inner.edge_count()
    }

    /// Build public export keys for a precomputed public-entry set.
    #[must_use]
    pub(crate) fn public_export_keys(
        &self,
        public_entries: &FxHashSet<FileId>,
        root: &Path,
    ) -> FxHashSet<String> {
        self.inner.public_export_keys(public_entries, root)
    }

    /// Count direct importer modules for one file id.
    #[must_use]
    pub fn direct_importer_count(&self, file_id: FileId) -> usize {
        self.inner
            .reverse_deps
            .get(file_id.0 as usize)
            .map_or(0, Vec::len)
    }

    /// Summaries for modules that directly import one file.
    #[must_use]
    pub fn direct_importer_summaries(&self, target: FileId) -> Vec<DirectImporterSummary> {
        self.inner
            .direct_importer_summaries(target)
            .into_iter()
            .map(DirectImporterSummary::from)
            .collect()
    }
}

/// Engine-owned view of root-correlated static test reachability.
///
/// This keeps health consumers on one contract while the graph crate owns the
/// traversal and replacement-mask representation.
#[derive(Clone, Copy)]
pub(crate) struct StaticTestCoverage<'a> {
    graph: &'a ModuleGraph,
}

impl<'a> StaticTestCoverage<'a> {
    pub(crate) const fn new(graph: &'a ModuleGraph) -> Self {
        Self { graph }
    }

    pub(crate) fn covers_file(self, file_id: FileId) -> bool {
        self.graph.is_test_reachable(file_id)
    }

    pub(crate) fn covers_any_reference(self, export: &fallow_graph::graph::ExportSymbol) -> bool {
        self.graph.is_any_test_reference_covered(export)
    }
}

impl From<ModuleGraph> for RetainedModuleGraph {
    fn from(inner: ModuleGraph) -> Self {
        Self::new(inner)
    }
}

/// Engine-owned importer details for one file that directly imports a target module.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DirectImporterSummary {
    /// File containing the import statement.
    pub source: FileId,
    /// Symbols this importer pulls from the target module.
    pub symbols: Vec<ImportedSymbolSummary>,
}

impl From<GraphDirectImporterSummary> for DirectImporterSummary {
    fn from(summary: GraphDirectImporterSummary) -> Self {
        Self {
            source: summary.source,
            symbols: summary.symbols.into_iter().map(Into::into).collect(),
        }
    }
}

/// Engine-owned symbol details for a direct import edge.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ImportedSymbolSummary {
    /// Exported name as declared by the target module.
    pub imported: String,
    /// Local binding name at the import site.
    pub local: String,
    /// True for type-only imports, which do not count as value usage.
    pub type_only: bool,
}

impl From<GraphImportedSymbolSummary> for ImportedSymbolSummary {
    fn from(symbol: GraphImportedSymbolSummary) -> Self {
        Self {
            imported: symbol.imported,
            local: symbol.local,
            type_only: symbol.type_only,
        }
    }
}

/// Engine-owned snapshot of one value export in a module graph.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ModuleValueExport {
    /// File declaring the export.
    pub file_id: FileId,
    /// Exported name.
    pub name: String,
    /// Byte offset where the export declaration starts.
    pub span_start: u32,
    /// True when a test file references this export.
    pub test_referenced: bool,
}

/// Engine-owned impact closure with file ids resolved to paths.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ImpactClosurePaths {
    /// Changed files that are part of the diff under review.
    pub in_diff: Vec<String>,
    /// Files affected through the import closure but absent from the diff.
    pub affected_not_shown: Vec<String>,
    /// Changed contracts whose consumers were not updated in the same diff.
    pub coordination_gap: Vec<CoordinationGapPaths>,
}

impl From<GraphImpactClosurePaths> for ImpactClosurePaths {
    fn from(paths: GraphImpactClosurePaths) -> Self {
        Self {
            in_diff: paths.in_diff,
            affected_not_shown: paths.affected_not_shown,
            coordination_gap: paths
                .coordination_gap
                .into_iter()
                .map(CoordinationGapPaths::from)
                .collect(),
        }
    }
}

/// Engine-owned coordination gap between a changed contract and consumer.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CoordinationGapPaths {
    /// Path of the changed file whose contract moved.
    pub changed_file: String,
    /// Path of the consumer that was not updated alongside it.
    pub consumer_file: String,
    /// Symbols the consumer imports from the changed file.
    pub consumed_symbols: Vec<String>,
}

impl From<GraphCoordinationGapPaths> for CoordinationGapPaths {
    fn from(paths: GraphCoordinationGapPaths) -> Self {
        Self {
            changed_file: paths.changed_file,
            consumer_file: paths.consumer_file,
            consumed_symbols: paths.consumed_symbols,
        }
    }
}

/// Engine-owned review partition and dependency-sensible order.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct PartitionOrderPaths {
    /// Changed files partitioned into per-module review units.
    pub units: Vec<ReviewUnitPaths>,
    /// File paths in dependency-sensible review order (dependencies first).
    pub order: Vec<String>,
    /// Connected components of the inter-unit dependency graph: units that
    /// share no import edge with any unit outside their slice.
    pub independent_slices: Vec<Vec<String>>,
}

impl From<GraphPartitionOrderPaths> for PartitionOrderPaths {
    fn from(paths: GraphPartitionOrderPaths) -> Self {
        Self {
            units: paths.units.into_iter().map(ReviewUnitPaths::from).collect(),
            order: paths.order,
            independent_slices: paths.independent_slices,
        }
    }
}

/// Engine-owned changed-file review unit.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReviewUnitPaths {
    /// Directory the unit's files share.
    pub module_dir: String,
    /// Changed files grouped into this unit.
    pub files: Vec<String>,
}

impl From<GraphReviewUnitPaths> for ReviewUnitPaths {
    fn from(paths: GraphReviewUnitPaths) -> Self {
        Self {
            module_dir: paths.module_dir,
            files: paths.files,
        }
    }
}

/// Engine-owned focus facts for one changed file.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FocusFileFactsPaths {
    /// Path of the changed file the facts describe.
    pub file: String,
    /// Count of distinct files importing this file (blast radius), excluding
    /// the file itself.
    pub fan_in: u32,
    /// Count of distinct files this file imports, excluding the file itself.
    pub fan_out: u32,
    /// True when the file has a dynamic-import edge in either direction, so
    /// its static reachability signal is not complete. Conservative: a file
    /// that MAY be dynamically wired carries the flag.
    pub dynamic_dispatch: bool,
    /// True when the file's reachability runs through re-export indirection,
    /// so direct importer counts understate its reach.
    pub re_export_indirection: bool,
}

impl From<GraphFocusFileFactsPaths> for FocusFileFactsPaths {
    fn from(paths: GraphFocusFileFactsPaths) -> Self {
        Self {
            file: paths.file,
            fan_in: paths.fan_in,
            fan_out: paths.fan_out,
            dynamic_dispatch: paths.dynamic_dispatch,
            re_export_indirection: paths.re_export_indirection,
        }
    }
}

/// Return value exports with test-reference state without exposing graph node
/// internals to downstream crates.
#[must_use]
pub fn module_value_exports(graph: &RetainedModuleGraph) -> Vec<ModuleValueExport> {
    let test_coverage = graph.static_test_coverage();
    let graph = graph.as_graph();

    graph
        .modules
        .iter()
        .flat_map(|node| {
            node.exports
                .iter()
                .filter(|export| !export.is_type_only)
                .map(|export| ModuleValueExport {
                    file_id: node.file_id,
                    name: export.name.to_string(),
                    span_start: export.span.start,
                    test_referenced: test_coverage.covers_any_reference(export),
                })
        })
        .collect()
}

/// Compute a path-resolved impact closure for absolute changed paths.
#[must_use]
pub fn impact_closure_for_changed_paths(
    graph: &RetainedModuleGraph,
    root: &Path,
    changed_files: &FxHashSet<PathBuf>,
) -> Option<ImpactClosurePaths> {
    let graph = graph.as_graph();
    let changed_ids = changed_file_ids(graph, changed_files);
    if changed_ids.is_empty() {
        return None;
    }

    let closure = graph.impact_closure(&changed_ids);
    Some(graph.closure_with_paths(&closure, root).into())
}

/// Compute path-resolved partition order for absolute changed paths.
#[must_use]
pub fn partition_order_for_changed_paths(
    graph: &RetainedModuleGraph,
    root: &Path,
    changed_files: &FxHashSet<PathBuf>,
) -> Option<PartitionOrderPaths> {
    let graph = graph.as_graph();
    let changed_ids = changed_file_ids(graph, changed_files);
    if changed_ids.is_empty() {
        return None;
    }

    let partition = graph.partition_order(&changed_ids);
    Some(graph.partition_order_with_paths(&partition, root).into())
}

/// Compute path-resolved focus graph facts for absolute changed paths.
#[must_use]
pub fn focus_facts_for_changed_paths(
    graph: &RetainedModuleGraph,
    root: &Path,
    changed_files: &FxHashSet<PathBuf>,
) -> Option<Vec<FocusFileFactsPaths>> {
    let graph = graph.as_graph();
    let changed_ids = changed_file_ids(graph, changed_files);
    if changed_ids.is_empty() {
        return None;
    }

    let facts = graph.focus_file_facts(&changed_ids);
    Some(
        graph
            .focus_facts_with_paths(&facts, root)
            .into_iter()
            .map(FocusFileFactsPaths::from)
            .collect(),
    )
}

/// Compute changed-file export line anchors without exposing graph nodes.
#[must_use]
pub fn export_lines_for_changed_paths(
    graph: &RetainedModuleGraph,
    root: &Path,
    changed_files: &FxHashSet<PathBuf>,
) -> Option<FxHashMap<String, Vec<(String, u32)>>> {
    let graph = graph.as_graph();
    let changed_norm = normalized_changed_paths(changed_files);
    let mut map: FxHashMap<String, Vec<(String, u32)>> = FxHashMap::default();
    for module in &graph.modules {
        let abs = normalize_path(&module.path);
        if !changed_norm.contains(&abs) || module.exports.is_empty() {
            continue;
        }
        let Ok(content) = std::fs::read_to_string(&module.path) else {
            continue;
        };
        let offsets = fallow_types::extract::compute_line_offsets(&content);
        let exports: Vec<(String, u32)> = module
            .exports
            .iter()
            .map(|export| {
                let (line, _) =
                    fallow_types::extract::byte_offset_to_line_col(&offsets, export.span.start);
                (export.name.to_string(), line)
            })
            .collect();
        map.insert(relative_key_path(&module.path, root), exports);
    }
    Some(map)
}

/// Compute direct non-diff internal consumer counts for absolute changed paths.
#[must_use]
pub fn internal_consumers_for_changed_paths(
    graph: &RetainedModuleGraph,
    root: &Path,
    changed_files: &FxHashSet<PathBuf>,
) -> Option<FxHashMap<String, u64>> {
    let graph = graph.as_graph();
    let changed_norm = normalized_changed_paths(changed_files);
    let id_to_norm: FxHashMap<FileId, String> = graph
        .modules
        .iter()
        .map(|module| (module.file_id, normalize_path(&module.path)))
        .collect();

    let mut map: FxHashMap<String, u64> = FxHashMap::default();
    for module in &graph.modules {
        let abs = normalize_path(&module.path);
        if !changed_norm.contains(&abs) {
            continue;
        }
        let count = graph
            .importers_of(module.file_id)
            .iter()
            .filter(|imp| {
                id_to_norm
                    .get(imp)
                    .is_none_or(|p| !changed_norm.contains(p))
            })
            .count() as u64;
        map.insert(relative_key_path(&module.path, root), count);
    }
    Some(map)
}

/// Compute per-changed-file test adjacency for the review direction: whether a
/// test file imports the changed module directly, and whether one of those tests
/// is itself in the changed set. `is_test_path` classifies a root-relative,
/// forward-slashed path; the caller owns that definition so the brief's
/// weakening and direction surfaces agree on it. Changed test files get no
/// entry of their own. `None` when no module matches a changed path.
#[must_use]
pub fn test_adjacency_for_changed_paths(
    graph: &RetainedModuleGraph,
    root: &Path,
    changed_files: &FxHashSet<PathBuf>,
    is_test_path: &dyn Fn(&str) -> bool,
) -> Option<FxHashMap<String, TestAdjacency>> {
    let graph = graph.as_graph();
    // A project with no test files at all gets no adjacency claims: "no direct
    // test" on every unit would say nothing about the change.
    if !graph
        .modules
        .iter()
        .any(|module| is_test_path(&relative_key_path(&module.path, root)))
    {
        return None;
    }
    let changed_norm = normalized_changed_paths(changed_files);
    let mut map: FxHashMap<String, TestAdjacency> = FxHashMap::default();
    for module in &graph.modules {
        if !changed_norm.contains(&normalize_path(&module.path)) {
            continue;
        }
        let rel = relative_key_path(&module.path, root);
        if is_test_path(&rel) {
            continue;
        }
        let mut adjacency = TestAdjacency::None;
        for importer in graph.importers_of(module.file_id) {
            let Some(node) = graph.modules.get(importer.0 as usize) else {
                continue;
            };
            if !is_test_path(&relative_key_path(&node.path, root)) {
                continue;
            }
            if changed_norm.contains(&normalize_path(&node.path)) {
                adjacency = TestAdjacency::Changed;
                break;
            }
            adjacency = TestAdjacency::Untouched;
        }
        map.insert(rel, adjacency);
    }
    if map.is_empty() {
        return None;
    }
    Some(map)
}

/// In-repo importer counts for one third-party package.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct PackageImporters {
    /// Modules that import the package (value imports only), id-sorted. Kept
    /// as ids rather than a count so a decision that batches several packages
    /// can take the union instead of double-counting a module that imports
    /// more than one of them.
    pub importers: Vec<FileId>,
    /// The subset of `importers` outside the changed set, id-sorted.
    pub out_of_diff: Vec<FileId>,
}

/// Compute per-package in-repo importer counts for every third-party package
/// the graph saw an import of, value or type-only, split by whether the
/// importer is in the changed set. Type-only importers count because a major
/// bump of a types package is a compile-wide change even when no value
/// crosses the boundary. The dependency decision arm reads these so a new or
/// bumped `package.json` entry carries the modules it actually reaches. `None`
/// when the graph recorded no package usage.
#[must_use]
pub fn package_importers_for_changed_paths(
    graph: &RetainedModuleGraph,
    changed_files: &FxHashSet<PathBuf>,
) -> Option<FxHashMap<String, PackageImporters>> {
    let graph = graph.as_graph();
    if graph.package_usage.is_empty() && graph.type_only_package_usage.is_empty() {
        return None;
    }
    let changed_norm = normalized_changed_paths(changed_files);
    let id_to_norm: FxHashMap<FileId, String> = graph
        .modules
        .iter()
        .map(|module| (module.file_id, normalize_path(&module.path)))
        .collect();
    let mut usage: FxHashMap<&str, Vec<FileId>> = FxHashMap::default();
    for (package, files) in graph
        .package_usage
        .iter()
        .chain(graph.type_only_package_usage.iter())
    {
        usage
            .entry(package.as_str())
            .or_default()
            .extend(files.iter().copied());
    }
    let map = usage
        .into_iter()
        .map(|(package, files)| {
            let mut importers: Vec<FileId> = files;
            importers.sort_unstable_by_key(|id| id.0);
            importers.dedup();
            let out_of_diff: Vec<FileId> = importers
                .iter()
                .copied()
                .filter(|id| id_to_norm.get(id).is_none_or(|p| !changed_norm.contains(p)))
                .collect();
            (
                package.to_string(),
                PackageImporters {
                    importers,
                    out_of_diff,
                },
            )
        })
        .collect();
    Some(map)
}

fn changed_file_ids(graph: &ModuleGraph, changed_files: &FxHashSet<PathBuf>) -> Vec<FileId> {
    let path_to_id: FxHashMap<String, FileId> = graph
        .modules
        .iter()
        .map(|module| (normalize_path(&module.path), module.file_id))
        .collect();

    changed_files
        .iter()
        .filter_map(|path| path_to_id.get(&normalize_path(path)).copied())
        .collect()
}

fn normalized_changed_paths(changed_files: &FxHashSet<PathBuf>) -> FxHashSet<String> {
    changed_files
        .iter()
        .map(|path| normalize_path(path))
        .collect()
}

fn normalize_path(path: &Path) -> String {
    path.to_string_lossy().replace('\\', "/")
}

fn relative_key_path(path: &Path, root: &Path) -> String {
    let simple_path = dunce::simplified(path);
    let simple_root = dunce::simplified(root);
    simple_path
        .strip_prefix(simple_root)
        .unwrap_or(simple_path)
        .to_string_lossy()
        .replace('\\', "/")
}

#[cfg(test)]
mod tests {
    use super::{RetainedModuleGraph, module_value_exports};
    use fallow_graph::graph::ModuleGraph;
    use fallow_graph::resolve::{
        ResolveResult, ResolvedImport, ResolvedModule, ResolvedReplacedModuleTarget,
    };
    use fallow_types::discover::{DiscoveredFile, EntryPoint, EntryPointSource, FileId};
    use fallow_types::extract::{ExportInfo, ExportName, ImportInfo, ImportedName, VisibilityTag};
    use std::path::PathBuf;

    fn import(target: FileId, imported_name: ImportedName) -> ResolvedImport {
        import_with_mechanism(target, imported_name, false)
    }

    fn import_with_mechanism(
        target: FileId,
        imported_name: ImportedName,
        commonjs: bool,
    ) -> ResolvedImport {
        ResolvedImport {
            info: ImportInfo {
                source: "./target".to_string(),
                imported_name,
                local_name: "target".to_string(),
                is_type_only: false,
                is_type_only_star: false,
                from_style: false,
                span: oxc_span::Span::new(0, 10),
                source_span: oxc_span::Span::default(),
            },
            target: if commonjs {
                ResolveResult::CommonJsInternalModule(target)
            } else {
                ResolveResult::InternalModule(target)
            },
        }
    }

    fn value_export(name: &str, span_start: u32) -> ExportInfo {
        ExportInfo {
            name: ExportName::Named(name.to_string()),
            local_name: Some(name.to_string()),
            is_type_only: false,
            visibility: VisibilityTag::None,
            expected_unused_reason: None,
            span: oxc_span::Span::new(span_start, span_start + 10),
            members: Vec::new(),
            is_side_effect_used: false,
            super_class: None,
        }
    }

    fn mixed_root_graph(unmasked_root_imports_export: bool) -> RetainedModuleGraph {
        let files: Vec<_> = (0..3)
            .map(|id| DiscoveredFile {
                id: FileId(id),
                path: PathBuf::from(format!("/project/file{id}.ts")),
                size_bytes: 1,
            })
            .collect();
        let modules = vec![
            ResolvedModule {
                file_id: FileId(0),
                path: files[0].path.clone(),
                resolved_imports: vec![import(
                    FileId(2),
                    ImportedName::Named("target".to_string()),
                )],
                ..ResolvedModule::default()
            },
            ResolvedModule {
                file_id: FileId(1),
                path: files[1].path.clone(),
                resolved_imports: vec![import(
                    FileId(2),
                    if unmasked_root_imports_export {
                        ImportedName::Named("target".to_string())
                    } else {
                        ImportedName::SideEffect
                    },
                )],
                ..ResolvedModule::default()
            },
            ResolvedModule {
                file_id: FileId(2),
                path: files[2].path.clone(),
                exports: vec![value_export("target", 0)].into(),
                ..ResolvedModule::default()
            },
        ];
        let test_entry_points = vec![
            EntryPoint {
                path: files[0].path.clone(),
                source: EntryPointSource::TestFile,
            },
            EntryPoint {
                path: files[1].path.clone(),
                source: EntryPointSource::TestFile,
            },
        ];
        let graph = ModuleGraph::build_with_reachability_roots_and_replacements(
            &modules,
            &[ResolvedReplacedModuleTarget {
                source_file: FileId(0),
                target_file: FileId(2),
            }],
            &test_entry_points,
            &[],
            &test_entry_points,
            &files,
        );
        RetainedModuleGraph::from(graph)
    }

    #[test]
    fn export_coverage_requires_one_root_to_reach_consumer_and_target() {
        let graph = mixed_root_graph(false);

        let exports = module_value_exports(&graph);

        assert_eq!(exports.len(), 1);
        assert!(!exports[0].test_referenced);
    }

    #[test]
    fn export_coverage_accepts_an_unmasked_correlated_reference() {
        let graph = mixed_root_graph(true);

        let exports = module_value_exports(&graph);

        assert_eq!(exports.len(), 1);
        assert!(exports[0].test_referenced);
    }

    #[test]
    fn commonjs_reference_does_not_credit_a_mocked_esm_export() {
        let files: Vec<_> = (0..2)
            .map(|id| DiscoveredFile {
                id: FileId(id),
                path: PathBuf::from(format!("/project/file{id}.ts")),
                size_bytes: 1,
            })
            .collect();
        let modules = vec![
            ResolvedModule {
                file_id: FileId(0),
                path: files[0].path.clone(),
                resolved_imports: vec![
                    import_with_mechanism(
                        FileId(1),
                        ImportedName::Named("esmOnly".to_string()),
                        false,
                    ),
                    import_with_mechanism(
                        FileId(1),
                        ImportedName::Named("required".to_string()),
                        true,
                    ),
                ],
                ..ResolvedModule::default()
            },
            ResolvedModule {
                file_id: FileId(1),
                path: files[1].path.clone(),
                exports: vec![value_export("esmOnly", 0), value_export("required", 20)].into(),
                ..ResolvedModule::default()
            },
        ];
        let test_entry_points = vec![EntryPoint {
            path: files[0].path.clone(),
            source: EntryPointSource::TestFile,
        }];
        let graph =
            RetainedModuleGraph::from(ModuleGraph::build_with_reachability_roots_and_replacements(
                &modules,
                &[ResolvedReplacedModuleTarget {
                    source_file: FileId(0),
                    target_file: FileId(1),
                }],
                &test_entry_points,
                &[],
                &test_entry_points,
                &files,
            ));

        let exports = module_value_exports(&graph);
        let coverage: rustc_hash::FxHashMap<_, _> = exports
            .into_iter()
            .map(|export| (export.name, export.test_referenced))
            .collect();

        assert_eq!(coverage.get("esmOnly"), Some(&false));
        assert_eq!(coverage.get("required"), Some(&true));
    }
}