1use std::path::Path;
13
14use rustc_hash::FxHashMap;
15use serde::Serialize;
16use serde_json::Value;
17
18use fallow_config::{ResolvedConfig, WorkspaceInfo};
19use fallow_output::HealthReport;
20use fallow_types::discover::DiscoveredFile;
21use fallow_types::duplicates::{CloneInstance, DuplicationReport};
22use fallow_types::extract::{FunctionComplexity, ModuleInfo};
23use fallow_types::results::{AnalysisResults, FeatureFlag, SecurityFinding};
24
25use crate::module_graph::RetainedModuleGraph;
26
27const HOTSPOT_CYCLOMATIC_FLOOR: u16 = 10;
29const CLONE_PREVIEW_MAX_BYTES: usize = 2000;
33const CLONE_PREVIEW_MAX_LINES: usize = 32;
37const CLONE_PREVIEW_CONTEXT: usize = 4;
42const MAX_CLONE_GROUPS: usize = 500;
46const MAX_ANALYSIS_FINDINGS: usize = 1000;
48const MAX_SECURITY_BLIND_SPOT_SAMPLES: usize = 100;
50const MAX_HEALTH_FILES: usize = 2000;
52const EDGE_FLAG_TYPE_ONLY: u32 = 1;
54const NO_RUNTIME_COVERAGE_REASON: &str = "No runtime coverage input was provided";
58
59pub struct VizBuildInput<'a> {
61 pub results: &'a AnalysisResults,
63 pub graph: &'a RetainedModuleGraph,
65 pub modules: Option<&'a [ModuleInfo]>,
67 pub files: &'a [DiscoveredFile],
69 pub duplication: &'a DuplicationReport,
71 pub workspaces: &'a [WorkspaceInfo],
73 pub config: &'a ResolvedConfig,
75 pub feature_flags: &'a [FeatureFlag],
77 pub include_analysis_details: bool,
79}
80
81#[derive(Serialize)]
83pub struct VizData {
84 pub root: String,
86 pub files: Vec<VizFile>,
88 pub edges: Vec<[u32; 3]>,
91 pub summary: VizSummary,
93 pub workspaces: Vec<VizWorkspace>,
95 pub zones: Vec<VizZone>,
97 pub cycles: Vec<Vec<u32>>,
99 pub clones: Vec<VizCloneGroup>,
101 pub violations: Vec<VizViolation>,
103 pub architecture: VizFindingAnalysis,
105 pub dependencies: VizFindingAnalysis,
107 pub health: VizHealthData,
109 pub security: VizSecurityData,
111 pub frameworks: VizFrameworkData,
113 pub styling: VizStylingData,
115 pub feature_flags: VizFindingAnalysis,
117}
118
119#[derive(Serialize, Clone, Copy, PartialEq, Eq)]
121#[serde(rename_all = "camelCase")]
122pub enum VizAvailabilityState {
123 Complete,
125 Disabled,
127 NotApplicable,
129 Unavailable,
131}
132
133#[derive(Serialize)]
140pub struct VizAvailability {
141 pub state: VizAvailabilityState,
143 pub count: usize,
145 pub unit: &'static str,
147 #[serde(skip_serializing_if = "Option::is_none")]
149 pub reason: Option<String>,
150 #[serde(skip_serializing_if = "Option::is_none")]
153 pub truncated: Option<usize>,
154}
155
156impl VizAvailability {
157 const fn complete(count: usize, unit: &'static str, truncated: Option<usize>) -> Self {
158 Self {
159 state: VizAvailabilityState::Complete,
160 count,
161 unit,
162 reason: None,
163 truncated,
164 }
165 }
166
167 fn unavailable(unit: &'static str, reason: impl Into<String>) -> Self {
168 Self {
169 state: VizAvailabilityState::Unavailable,
170 count: 0,
171 unit,
172 reason: Some(reason.into()),
173 truncated: None,
174 }
175 }
176
177 fn disabled(unit: &'static str, reason: impl Into<String>) -> Self {
178 Self {
179 state: VizAvailabilityState::Disabled,
180 count: 0,
181 unit,
182 reason: Some(reason.into()),
183 truncated: None,
184 }
185 }
186}
187
188#[derive(Serialize)]
190pub struct VizFinding {
191 kind: String,
192 title: String,
193 #[serde(skip_serializing_if = "Option::is_none")]
194 file: Option<u32>,
195 #[serde(skip_serializing_if = "Option::is_none")]
196 path: Option<String>,
197 #[serde(skip_serializing_if = "Option::is_none")]
198 line: Option<u32>,
199 #[serde(skip_serializing_if = "Vec::is_empty")]
200 files: Vec<u32>,
201 #[serde(skip_serializing_if = "Vec::is_empty")]
202 paths: Vec<String>,
203 #[serde(skip_serializing_if = "Option::is_none")]
204 description: Option<String>,
205 #[serde(skip_serializing_if = "Option::is_none")]
206 severity: Option<String>,
207 #[serde(skip_serializing_if = "Vec::is_empty")]
208 facts: Vec<VizFindingFact>,
209 actions: Vec<VizFindingAction>,
210}
211
212#[derive(Serialize)]
214pub struct VizFindingFact {
215 label: String,
216 value: String,
217}
218
219#[derive(Serialize)]
221pub struct VizFindingAction {
222 label: String,
223 #[serde(skip_serializing_if = "Option::is_none")]
224 kind: Option<String>,
225 auto_fixable: bool,
226 #[serde(skip_serializing_if = "Option::is_none")]
227 command: Option<String>,
228 #[serde(skip_serializing_if = "Option::is_none")]
229 comment: Option<String>,
230 #[serde(skip_serializing_if = "Option::is_none")]
231 config_key: Option<String>,
232 #[serde(skip_serializing_if = "Option::is_none")]
233 value: Option<Value>,
234 #[serde(skip_serializing_if = "Option::is_none")]
235 description: Option<String>,
236}
237
238#[derive(Serialize)]
240pub struct VizFindingAnalysis {
241 pub availability: VizAvailability,
243 #[serde(skip_serializing_if = "Option::is_none")]
245 pub findings_truncated: Option<usize>,
246 pub findings: Vec<VizFinding>,
248}
249
250#[derive(Serialize)]
252pub struct VizFrameworkData {
253 pub availability: VizAvailability,
255 pub detector_availability: VizAvailability,
258 #[serde(skip_serializing_if = "Option::is_none")]
260 pub findings_truncated: Option<usize>,
261 pub findings: Vec<VizFinding>,
263 pub detected_frameworks: Vec<String>,
265 pub detectors: Vec<VizFrameworkDetector>,
268}
269
270#[derive(Serialize)]
272pub struct VizFrameworkDetector {
273 id: String,
274 framework: String,
275 status: String,
276 #[serde(skip_serializing_if = "Option::is_none")]
277 reason: Option<String>,
278}
279
280#[derive(Serialize)]
282pub struct VizHealthCapabilities {
283 pub complexity: VizAvailability,
285 pub maintainability: VizAvailability,
287 pub crap: VizAvailability,
289 pub coverage: VizAvailability,
291 pub runtime: VizAvailability,
293 pub churn: VizAvailability,
295 pub hotspots: VizAvailability,
297 pub ownership: VizAvailability,
299}
300
301#[derive(Serialize)]
303pub struct VizHealthFile {
304 file: u32,
305 path: String,
306 maintainability_index: f64,
307 crap_max: f64,
308 complexity_density: f64,
309 fan_in: usize,
310 fan_out: usize,
311 #[serde(skip_serializing_if = "Option::is_none")]
312 hotspot_score: Option<f64>,
313 #[serde(skip_serializing_if = "Option::is_none")]
314 commits: Option<u32>,
315 #[serde(skip_serializing_if = "Option::is_none")]
316 ownership: Option<Value>,
317}
318
319#[derive(Serialize)]
321pub struct VizHealthData {
322 pub availability: VizAvailability,
324 pub capabilities: VizHealthCapabilities,
326 #[serde(skip_serializing_if = "Option::is_none")]
328 pub shared_parse: Option<bool>,
329 #[serde(skip_serializing_if = "Option::is_none")]
331 pub score: Option<f64>,
332 #[serde(skip_serializing_if = "Option::is_none")]
334 pub grade: Option<String>,
335 #[serde(skip_serializing_if = "Option::is_none")]
337 pub average_maintainability: Option<f64>,
338 pub files: Vec<VizHealthFile>,
340 #[serde(skip_serializing_if = "Option::is_none")]
342 pub files_truncated: Option<usize>,
343 #[serde(skip_serializing_if = "Option::is_none")]
345 pub findings_truncated: Option<usize>,
346 pub findings: Vec<VizFinding>,
348}
349
350#[derive(Serialize)]
352pub struct VizStylingData {
353 pub availability: VizAvailability,
355 #[serde(skip_serializing_if = "Option::is_none")]
357 pub findings_truncated: Option<usize>,
358 pub findings: Vec<VizFinding>,
360 #[serde(skip_serializing_if = "Option::is_none")]
362 pub score: Option<f64>,
363 #[serde(skip_serializing_if = "Option::is_none")]
365 pub grade: Option<String>,
366 #[serde(skip_serializing_if = "Option::is_none")]
368 pub confidence: Option<String>,
369 #[serde(skip_serializing_if = "Option::is_none")]
371 pub summary: Option<Value>,
372}
373
374#[derive(Serialize)]
376pub struct VizSecurityTraceHop {
377 #[serde(skip_serializing_if = "Option::is_none")]
378 file: Option<u32>,
379 path: String,
380 line: u32,
381 col: u32,
382 role: String,
383}
384
385#[derive(Serialize)]
387pub struct VizSecurityEndpoint {
388 #[serde(skip_serializing_if = "Option::is_none")]
389 file: Option<u32>,
390 path: String,
391 line: u32,
392 col: u32,
393}
394
395#[derive(Serialize)]
397pub struct VizSecurityTaintFlow {
398 source: VizSecurityEndpoint,
399 sink: VizSecurityEndpoint,
400 intra_module: bool,
401 cross_module_hops: u32,
402}
403
404#[derive(Serialize)]
407pub struct VizSecurityCandidate {
408 id: String,
409 kind: String,
410 #[serde(skip_serializing_if = "Option::is_none")]
411 category: Option<String>,
412 #[serde(skip_serializing_if = "Option::is_none")]
413 cwe: Option<u32>,
414 #[serde(skip_serializing_if = "Option::is_none")]
415 file: Option<u32>,
416 path: String,
417 line: u32,
418 col: u32,
419 evidence: String,
420 severity: String,
421 #[serde(skip_serializing_if = "Option::is_none")]
422 taint_confidence: Option<String>,
423 #[serde(skip_serializing_if = "Option::is_none")]
424 source_kind: Option<String>,
425 #[serde(skip_serializing_if = "Option::is_none")]
426 sink: Option<String>,
427 #[serde(skip_serializing_if = "Option::is_none")]
428 url_shape: Option<String>,
429 #[serde(skip_serializing_if = "Option::is_none")]
430 network_destination: Option<String>,
431 #[serde(skip_serializing_if = "Option::is_none")]
432 reachable_from_entry: Option<bool>,
433 #[serde(skip_serializing_if = "Option::is_none")]
434 reachable_from_untrusted_source: Option<bool>,
435 #[serde(skip_serializing_if = "Option::is_none")]
436 blast_radius: Option<u32>,
437 crosses_boundary: bool,
438 client_server_boundary: bool,
439 cross_module_boundary: bool,
440 #[serde(skip_serializing_if = "Option::is_none")]
441 architecture_zone: Option<String>,
442 #[serde(skip_serializing_if = "Option::is_none")]
443 dead_code: Option<Value>,
444 #[serde(skip_serializing_if = "Option::is_none")]
445 runtime: Option<Value>,
446 #[serde(skip_serializing_if = "Option::is_none")]
447 taint_flow: Option<VizSecurityTaintFlow>,
448 #[serde(skip_serializing_if = "Vec::is_empty")]
449 observed_controls: Vec<Value>,
450 #[serde(skip_serializing_if = "Option::is_none")]
451 control_verification_prompt: Option<String>,
452 trace: Vec<VizSecurityTraceHop>,
453 #[serde(skip_serializing_if = "Vec::is_empty")]
454 taint_trace: Vec<VizSecurityTraceHop>,
455 actions: Value,
456}
457
458#[derive(Serialize)]
460pub struct VizSecurityBlindSpot {
461 kind: String,
462 count: usize,
463 #[serde(skip_serializing_if = "Option::is_none")]
464 path: Option<String>,
465 #[serde(skip_serializing_if = "Option::is_none")]
466 file: Option<u32>,
467 #[serde(skip_serializing_if = "Option::is_none")]
468 line: Option<u32>,
469 #[serde(skip_serializing_if = "Option::is_none")]
470 reason: Option<String>,
471}
472
473#[derive(Serialize)]
476pub struct VizSecurityData {
477 pub availability: VizAvailability,
480 pub runtime_availability: VizAvailability,
483 pub candidates: Vec<VizSecurityCandidate>,
485 pub blind_spot_count: usize,
487 #[serde(skip_serializing_if = "Option::is_none")]
489 pub blind_spots_truncated: Option<usize>,
490 pub blind_spots: Vec<VizSecurityBlindSpot>,
492}
493
494#[derive(Serialize)]
496pub struct VizFile {
497 pub path: String,
499 pub size: u64,
501 pub status: VizFileStatus,
503 pub export_count: u16,
505 pub unused_export_count: u16,
507 pub is_entry: bool,
509 pub importer_count: u16,
511 pub import_count: u16,
513 #[serde(skip_serializing_if = "Option::is_none")]
515 pub workspace: Option<u16>,
516 #[serde(skip_serializing_if = "Option::is_none")]
518 pub zone: Option<u16>,
519 #[serde(skip_serializing_if = "Vec::is_empty")]
521 pub unused_exports: Vec<String>,
522 pub fn_count: u16,
524 pub max_cyclomatic: u16,
526 pub max_cognitive: u16,
528 pub react_hooks: u16,
530 pub jsx_depth: u16,
532 #[serde(skip_serializing_if = "Vec::is_empty")]
534 pub functions: Vec<VizFunction>,
535 pub dup_lines: u32,
537 #[serde(skip_serializing_if = "Vec::is_empty")]
539 pub clone_groups: Vec<u32>,
540 pub in_cycle: bool,
542}
543
544#[derive(Serialize, Clone, Copy, PartialEq, Eq)]
546#[serde(rename_all = "camelCase")]
547pub enum VizFileStatus {
548 Clean,
550 HasUnusedExports,
552 Unused,
554 EntryPoint,
556}
557
558#[derive(Serialize)]
560pub struct VizFunction {
561 name: String,
563 line: u32,
565 cyclomatic: u16,
567 cognitive: u16,
569 lines: u32,
571 hooks: u16,
573 jsx_depth: u16,
575 props: u16,
577}
578
579#[derive(Serialize)]
581pub struct VizSummary {
582 pub total_files: usize,
584 pub total_size: u64,
586 pub total_edges: usize,
588 pub unused_files: usize,
590 pub unused_exports: usize,
592 pub unused_types: usize,
594 pub unused_deps: usize,
596 pub unresolved_imports: usize,
598 pub circular_deps: usize,
600 pub clone_groups: usize,
602 pub duplicated_lines: usize,
604 pub boundary_violations: usize,
606 pub hotspot_files: usize,
608 #[serde(skip_serializing_if = "Option::is_none")]
611 pub clone_groups_truncated: Option<u32>,
612}
613
614#[derive(Serialize)]
616pub struct VizWorkspace {
617 name: String,
619 root: String,
621}
622
623#[derive(Serialize)]
625pub struct VizZone {
626 name: String,
628 files: u32,
630}
631
632#[derive(Serialize)]
634pub struct VizCloneGroup {
635 lines: usize,
637 tokens: usize,
639 instances: Vec<VizCloneInstance>,
641 preview: String,
645 highlight_start: u32,
648 highlight_lines: u32,
652}
653
654#[derive(Serialize)]
656pub struct VizCloneInstance {
657 file: u32,
659 start_line: u32,
661 end_line: u32,
663}
664
665#[derive(Serialize)]
667pub struct VizViolation {
668 from: u32,
670 to: u32,
672 from_zone: u16,
674 to_zone: u16,
676 line: u32,
678 specifier: String,
680}
681
682#[must_use]
684pub fn build_viz_data(input: &VizBuildInput<'_>) -> VizData {
685 let root = &input.config.root;
686 let index = FileIndex::new(input.files);
687 let workspaces = build_workspaces(input.workspaces, root);
688 let (zones, zone_by_file) = classify_zones(input, &index);
689 let (clones, clone_groups_by_file, dup_lines_by_file, clone_groups_truncated) =
690 build_clones(input.duplication, &index, MAX_CLONE_GROUPS);
691 let cycles = build_cycles(input.results, &index);
692 let violations = build_violations(input.results, &zones, &index);
693 let (architecture, dependencies, security, frameworks, feature_flags) =
694 if input.include_analysis_details {
695 (
696 build_architecture(input.results, &index, root),
697 build_dependencies(input.results, &index, root),
698 build_security(input.results, &index, root),
699 build_frameworks(input.results, &index, root),
700 build_feature_flags(input.feature_flags, &index, root),
701 )
702 } else {
703 skipped_analysis_details()
704 };
705
706 let files = build_files(
707 input,
708 &index,
709 &FilePropertyMaps {
710 zone_by_file: &zone_by_file,
711 clone_groups_by_file: &clone_groups_by_file,
712 dup_lines_by_file: &dup_lines_by_file,
713 cycles: &cycles,
714 },
715 );
716
717 let summary = build_summary(
718 input,
719 &files,
720 &clones,
721 &cycles,
722 &violations,
723 clone_groups_truncated,
724 );
725
726 VizData {
727 root: display_root(root),
728 files,
729 edges: build_edges(input.graph, &index),
730 summary,
731 workspaces,
732 zones,
733 cycles,
734 clones,
735 violations,
736 architecture,
737 dependencies,
738 health: VizHealthData {
739 availability: VizAvailability::unavailable("files", "Health analysis did not complete"),
740 capabilities: unavailable_health_capabilities("Health analysis did not complete"),
741 shared_parse: None,
742 score: None,
743 grade: None,
744 average_maintainability: None,
745 files: Vec::new(),
746 files_truncated: None,
747 findings_truncated: None,
748 findings: Vec::new(),
749 },
750 security,
751 frameworks,
752 styling: VizStylingData {
753 availability: VizAvailability::unavailable(
754 "findings",
755 "Styling analysis did not complete",
756 ),
757 findings_truncated: None,
758 findings: Vec::new(),
759 score: None,
760 grade: None,
761 confidence: None,
762 summary: None,
763 },
764 feature_flags,
765 }
766}
767
768fn skipped_analysis_details() -> (
769 VizFindingAnalysis,
770 VizFindingAnalysis,
771 VizSecurityData,
772 VizFrameworkData,
773 VizFindingAnalysis,
774) {
775 let skipped = |unit| VizFindingAnalysis {
776 availability: VizAvailability::disabled(unit, "Not needed for this Viz output format"),
777 findings_truncated: None,
778 findings: Vec::new(),
779 };
780 (
781 skipped("violations"),
782 skipped("findings"),
783 VizSecurityData {
784 availability: VizAvailability::disabled(
785 "candidates",
786 "Not needed for this Viz output format",
787 ),
788 runtime_availability: VizAvailability::disabled(
789 "observations",
790 "Not needed for this Viz output format",
791 ),
792 candidates: Vec::new(),
793 blind_spot_count: 0,
794 blind_spots_truncated: None,
795 blind_spots: Vec::new(),
796 },
797 VizFrameworkData {
798 availability: VizAvailability::disabled(
799 "findings",
800 "Not needed for this Viz output format",
801 ),
802 detector_availability: VizAvailability::disabled(
803 "detectors",
804 "Not needed for this Viz output format",
805 ),
806 findings_truncated: None,
807 findings: Vec::new(),
808 detected_frameworks: Vec::new(),
809 detectors: Vec::new(),
810 },
811 skipped("flags"),
812 )
813}
814
815struct FileIndex<'a> {
817 ordered: Vec<&'a DiscoveredFile>,
818 by_path: FxHashMap<&'a Path, u32>,
819 by_file_id: FxHashMap<u32, u32>,
820}
821
822impl<'a> FileIndex<'a> {
823 fn new(files: &'a [DiscoveredFile]) -> Self {
824 let mut ordered: Vec<&DiscoveredFile> = files.iter().collect();
825 ordered.sort_by_key(|f| f.id.0);
826 let mut by_path = FxHashMap::default();
827 let mut by_file_id = FxHashMap::default();
828 for (i, f) in ordered.iter().enumerate() {
829 let idx = clamp_u32(i);
830 by_path.insert(f.path.as_path(), idx);
831 by_file_id.insert(f.id.0, idx);
832 }
833 Self {
834 ordered,
835 by_path,
836 by_file_id,
837 }
838 }
839
840 fn index_of_path(&self, path: &Path) -> Option<u32> {
841 self.by_path.get(path).copied()
842 }
843
844 fn index_of_file_id(&self, file_id: u32) -> Option<u32> {
845 self.by_file_id.get(&file_id).copied()
846 }
847}
848
849fn analysis_from_records(
850 mut findings: Vec<VizFinding>,
851 total_findings: usize,
852 primary_count: usize,
853 unit: &'static str,
854) -> VizFindingAnalysis {
855 let findings_truncated = (total_findings > MAX_ANALYSIS_FINDINGS)
856 .then_some(total_findings.saturating_sub(MAX_ANALYSIS_FINDINGS));
857 let primary_truncated = (primary_count > MAX_ANALYSIS_FINDINGS)
858 .then_some(primary_count.saturating_sub(MAX_ANALYSIS_FINDINGS));
859 findings.truncate(MAX_ANALYSIS_FINDINGS);
860 VizFindingAnalysis {
861 availability: VizAvailability::complete(primary_count, unit, primary_truncated),
862 findings_truncated,
863 findings,
864 }
865}
866
867fn push_findings<T: Serialize>(
868 out: &mut Vec<VizFinding>,
869 kind: &str,
870 title: &str,
871 values: &[T],
872 root: &Path,
873 index: &FileIndex<'_>,
874) {
875 let remaining = MAX_ANALYSIS_FINDINGS.saturating_sub(out.len());
876 out.extend(values.iter().take(remaining).filter_map(|value| {
877 serde_json::to_value(value).ok().map(|detail| {
878 finding_from_value(kind, title, detail, root, &|path| index.index_of_path(path))
879 })
880 }));
881}
882
883fn finding_from_value(
884 kind: &str,
885 title: &str,
886 mut detail: Value,
887 root: &Path,
888 resolve_file: &dyn Fn(&Path) -> Option<u32>,
889) -> VizFinding {
890 let raw_path = find_string_key(&detail, &["path", "from_path", "consumer_path", "file"])
891 .map(str::to_owned);
892 let mut raw_paths = Vec::new();
893 collect_path_values(&detail, &mut raw_paths);
894 let mut paths = Vec::new();
895 let mut files = Vec::new();
896 for raw in raw_paths {
897 let raw_path = Path::new(&raw);
898 let absolute_path = if raw_path.has_root() {
902 raw_path.to_path_buf()
903 } else {
904 root.join(raw_path)
905 };
906 let display = relative_path(&absolute_path, root);
907 if !paths.contains(&display) {
908 paths.push(display);
909 }
910 if let Some(file) = resolve_file(&absolute_path)
911 && !files.contains(&file)
912 {
913 files.push(file);
914 }
915 }
916 let absolute = raw_path.as_deref().map(Path::new).map(|path| {
917 if path.has_root() {
918 path.to_path_buf()
919 } else {
920 root.join(path)
921 }
922 });
923 let file = absolute.as_deref().and_then(resolve_file);
924 let path = absolute.as_deref().map(|path| relative_path(path, root));
925 let line = find_u64_key(&detail, &["line", "start_line"])
926 .map(|value| u32::try_from(value).unwrap_or(u32::MAX));
927 relativize_value_paths(&mut detail, root);
928 let description =
929 find_string_key(&detail, &["message", "evidence", "reason"]).map(str::to_owned);
930 let severity = find_string_key(&detail, &["severity"]).map(str::to_owned);
931 let facts = finding_facts(&detail);
932 let actions = finding_actions(&detail);
933 VizFinding {
934 kind: kind.to_string(),
935 title: title.to_string(),
936 file,
937 path,
938 line,
939 files,
940 paths,
941 description,
942 severity,
943 facts,
944 actions,
945 }
946}
947
948fn finding_facts(detail: &Value) -> Vec<VizFindingFact> {
949 const EXCLUDED: &[&str] = &[
950 "path",
951 "from_path",
952 "to_path",
953 "consumer_path",
954 "file",
955 "files",
956 "paths",
957 "line",
958 "start_line",
959 "message",
960 "evidence",
961 "reason",
962 "severity",
963 "actions",
964 ];
965 let Some(fields) = detail.as_object() else {
966 return Vec::new();
967 };
968 fields
969 .iter()
970 .filter(|(label, _)| !EXCLUDED.contains(&label.as_str()))
971 .filter_map(|(label, value)| {
972 scalar_fact_value(value).map(|value| VizFindingFact {
973 label: label.clone(),
974 value,
975 })
976 })
977 .take(12)
978 .collect()
979}
980
981fn scalar_fact_value(value: &Value) -> Option<String> {
982 match value {
983 Value::String(value) => Some(value.clone()),
984 Value::Number(value) => Some(value.to_string()),
985 Value::Bool(value) => Some(value.to_string()),
986 Value::Array(values) if values.iter().all(Value::is_string) => Some(
987 values
988 .iter()
989 .filter_map(Value::as_str)
990 .collect::<Vec<_>>()
991 .join(", "),
992 ),
993 Value::Null | Value::Array(_) | Value::Object(_) => None,
994 }
995}
996
997fn finding_actions(detail: &Value) -> Vec<VizFindingAction> {
998 let mut actions = Vec::new();
999 if let Some(record) = detail.as_object() {
1000 for key in ["verify_command", "trace_command", "command"] {
1001 if let Some(command) = record.get(key).and_then(Value::as_str) {
1002 actions.push(VizFindingAction {
1003 label: "Verify".to_string(),
1004 kind: None,
1005 auto_fixable: false,
1006 command: Some(command.to_string()),
1007 comment: None,
1008 config_key: None,
1009 value: None,
1010 description: None,
1011 });
1012 }
1013 }
1014 if let Some(value) = record.get("actions") {
1015 append_projected_actions(&mut actions, value);
1016 }
1017 }
1018 actions
1019}
1020
1021fn append_projected_actions(actions: &mut Vec<VizFindingAction>, value: &Value) {
1022 match value {
1023 Value::Array(values) => {
1024 for value in values {
1025 if let Some(action) = projected_action(value) {
1026 actions.push(action);
1027 }
1028 }
1029 }
1030 Value::Object(values) => {
1031 for (label, value) in values {
1032 if let Some(command) = value.as_str() {
1033 actions.push(VizFindingAction {
1034 label: label.clone(),
1035 kind: Some(label.clone()),
1036 auto_fixable: false,
1037 command: Some(command.to_string()),
1038 comment: None,
1039 config_key: None,
1040 value: None,
1041 description: None,
1042 });
1043 }
1044 }
1045 }
1046 Value::Null | Value::Bool(_) | Value::Number(_) | Value::String(_) => {}
1047 }
1048}
1049
1050fn projected_action(value: &Value) -> Option<VizFindingAction> {
1051 let action = value.as_object()?;
1052 let kind = ["kind", "type"]
1053 .iter()
1054 .find_map(|key| action.get(*key).and_then(Value::as_str))
1055 .map(str::to_owned);
1056 let label = ["label", "title"]
1057 .iter()
1058 .find_map(|key| action.get(*key).and_then(Value::as_str))
1059 .map(str::to_owned)
1060 .or_else(|| kind.clone())
1061 .unwrap_or_else(|| "Review".to_string());
1062 let command = action
1063 .get("command")
1064 .and_then(Value::as_str)
1065 .map(str::to_owned);
1066 let comment = action
1067 .get("comment")
1068 .and_then(Value::as_str)
1069 .map(str::to_owned);
1070 let auto_fixable = action
1071 .get("auto_fixable")
1072 .and_then(Value::as_bool)
1073 .unwrap_or(false);
1074 let config_key = action
1075 .get("config_key")
1076 .and_then(Value::as_str)
1077 .map(str::to_owned);
1078 let projected_value = action.get("value").cloned();
1079 let description = ["description", "note"]
1080 .iter()
1081 .find_map(|key| action.get(*key).and_then(Value::as_str))
1082 .map(str::to_owned);
1083 (command.is_some()
1084 || comment.is_some()
1085 || description.is_some()
1086 || config_key.is_some()
1087 || projected_value.is_some())
1088 .then_some(VizFindingAction {
1089 label,
1090 kind,
1091 auto_fixable,
1092 command,
1093 comment,
1094 config_key,
1095 value: projected_value,
1096 description,
1097 })
1098}
1099
1100fn collect_path_values(value: &Value, out: &mut Vec<String>) {
1101 match value {
1102 Value::Object(map) => {
1103 for (key, value) in map {
1104 if is_path_key(key)
1105 && let Some(path) = value.as_str()
1106 {
1107 out.push(path.to_string());
1108 }
1109 if is_path_collection_key(key)
1110 && let Some(values) = value.as_array()
1111 {
1112 out.extend(values.iter().filter_map(Value::as_str).map(str::to_string));
1113 }
1114 collect_path_values(value, out);
1115 }
1116 }
1117 Value::Array(values) => {
1118 for value in values {
1119 collect_path_values(value, out);
1120 }
1121 }
1122 Value::Null | Value::Bool(_) | Value::Number(_) | Value::String(_) => {}
1123 }
1124}
1125
1126fn find_string_key<'a>(value: &'a Value, keys: &[&str]) -> Option<&'a str> {
1127 match value {
1128 Value::Object(map) => {
1129 for key in keys {
1130 if let Some(value) = map.get(*key).and_then(Value::as_str) {
1131 return Some(value);
1132 }
1133 }
1134 map.values().find_map(|value| find_string_key(value, keys))
1135 }
1136 Value::Array(values) => values.iter().find_map(|value| find_string_key(value, keys)),
1137 _ => None,
1138 }
1139}
1140
1141fn find_u64_key(value: &Value, keys: &[&str]) -> Option<u64> {
1142 match value {
1143 Value::Object(map) => {
1144 for key in keys {
1145 if let Some(value) = map.get(*key).and_then(Value::as_u64) {
1146 return Some(value);
1147 }
1148 }
1149 map.values().find_map(|value| find_u64_key(value, keys))
1150 }
1151 Value::Array(values) => values.iter().find_map(|value| find_u64_key(value, keys)),
1152 _ => None,
1153 }
1154}
1155
1156fn relativize_value_paths(value: &mut Value, root: &Path) {
1157 relativize_keyed_paths(value, root, false);
1158}
1159
1160fn relativize_keyed_paths(value: &mut Value, root: &Path, is_path: bool) {
1161 match value {
1162 Value::String(text) if is_path => {
1163 let path = Path::new(text);
1164 if path.has_root() {
1170 *text = relative_path(path, root);
1171 }
1172 }
1173 Value::Array(values) => {
1174 for value in values {
1175 relativize_keyed_paths(value, root, is_path);
1176 }
1177 }
1178 Value::Object(map) => {
1179 for (key, value) in map {
1180 let is_path = is_path_key(key) || is_path_collection_key(key);
1181 relativize_keyed_paths(value, root, is_path);
1182 }
1183 }
1184 Value::Null | Value::Bool(_) | Value::Number(_) | Value::String(_) => {}
1185 }
1186}
1187
1188fn is_path_key(key: &str) -> bool {
1189 matches!(
1190 key,
1191 "path"
1192 | "file"
1193 | "from_path"
1194 | "to_path"
1195 | "consumer_path"
1196 | "source_path"
1197 | "definition_path"
1198 | "template_path"
1199 | "inherited_from"
1200 | "reachable_via"
1201 | "new_path"
1202 | "old_path"
1203 | "cycle_path"
1204 | "docs_path"
1205 | "meta_docs_path"
1206 | "full_report_path"
1207 )
1208}
1209
1210fn is_path_collection_key(key: &str) -> bool {
1211 matches!(
1212 key,
1213 "files"
1214 | "paths"
1215 | "conflicting_paths"
1216 | "used_in_workspaces"
1217 | "hardcoded_consumers"
1218 | "hot_paths"
1219 )
1220}
1221
1222fn serialized_label<T: Serialize>(value: &T) -> String {
1223 serde_json::to_value(value)
1224 .ok()
1225 .and_then(|value| value.as_str().map(str::to_owned))
1226 .unwrap_or_else(|| "unknown".to_string())
1227}
1228
1229fn build_architecture(
1230 results: &AnalysisResults,
1231 index: &FileIndex<'_>,
1232 root: &Path,
1233) -> VizFindingAnalysis {
1234 let mut findings = Vec::new();
1235 push_findings(
1236 &mut findings,
1237 "boundary-violation",
1238 "Forbidden import",
1239 &results.boundary_violations,
1240 root,
1241 index,
1242 );
1243 push_findings(
1244 &mut findings,
1245 "boundary-coverage",
1246 "File outside architecture zones",
1247 &results.boundary_coverage_violations,
1248 root,
1249 index,
1250 );
1251 push_findings(
1252 &mut findings,
1253 "boundary-call",
1254 "Forbidden call",
1255 &results.boundary_call_violations,
1256 root,
1257 index,
1258 );
1259 push_findings(
1260 &mut findings,
1261 "policy-violation",
1262 "Policy violation",
1263 &results.policy_violations,
1264 root,
1265 index,
1266 );
1267 push_findings(
1268 &mut findings,
1269 "circular-dependency",
1270 "Import cycle",
1271 &results.circular_dependencies,
1272 root,
1273 index,
1274 );
1275 push_findings(
1276 &mut findings,
1277 "re-export-cycle",
1278 "Re-export cycle",
1279 &results.re_export_cycles,
1280 root,
1281 index,
1282 );
1283 let violation_count = results.boundary_violations.len()
1284 + results.boundary_coverage_violations.len()
1285 + results.boundary_call_violations.len()
1286 + results.policy_violations.len();
1287 let total_findings =
1288 violation_count + results.circular_dependencies.len() + results.re_export_cycles.len();
1289 analysis_from_records(findings, total_findings, violation_count, "violations")
1290}
1291
1292fn build_dependencies(
1293 results: &AnalysisResults,
1294 index: &FileIndex<'_>,
1295 root: &Path,
1296) -> VizFindingAnalysis {
1297 let mut findings = Vec::new();
1298 let mut count = 0;
1299 macro_rules! add {
1300 ($field:ident, $kind:literal, $title:literal) => {
1301 count += results.$field.len();
1302 push_findings(&mut findings, $kind, $title, &results.$field, root, index);
1303 };
1304 }
1305 add!(unresolved_imports, "unresolved-import", "Unresolved import");
1306 add!(
1307 unlisted_dependencies,
1308 "unlisted-dependency",
1309 "Unlisted dependency"
1310 );
1311 add!(
1312 type_only_dependencies,
1313 "type-only-dependency",
1314 "Type-only dependency"
1315 );
1316 add!(
1317 test_only_dependencies,
1318 "test-only-dependency",
1319 "Test-only dependency"
1320 );
1321 add!(
1322 dev_dependencies_in_production,
1323 "dev-dependency-in-production",
1324 "Development dependency used in production"
1325 );
1326 add!(
1327 duplicate_exports,
1328 "duplicate-export",
1329 "Duplicate public export"
1330 );
1331 add!(
1332 private_type_leaks,
1333 "private-type-leak",
1334 "Private type leaked by public API"
1335 );
1336 add!(
1337 unused_catalog_entries,
1338 "unused-catalog-entry",
1339 "Unused catalog entry"
1340 );
1341 add!(
1342 empty_catalog_groups,
1343 "empty-catalog-group",
1344 "Empty catalog group"
1345 );
1346 add!(
1347 unresolved_catalog_references,
1348 "unresolved-catalog-reference",
1349 "Unresolved catalog reference"
1350 );
1351 add!(
1352 unused_dependency_overrides,
1353 "unused-dependency-override",
1354 "Unused dependency override"
1355 );
1356 add!(
1357 misconfigured_dependency_overrides,
1358 "misconfigured-dependency-override",
1359 "Misconfigured dependency override"
1360 );
1361 analysis_from_records(findings, count, count, "findings")
1362}
1363
1364fn build_frameworks(
1365 results: &AnalysisResults,
1366 index: &FileIndex<'_>,
1367 root: &Path,
1368) -> VizFrameworkData {
1369 let mut findings = Vec::new();
1370 let mut count = 0;
1371 macro_rules! add {
1372 ($field:ident, $kind:literal, $title:literal) => {
1373 count += results.$field.len();
1374 push_findings(&mut findings, $kind, $title, &results.$field, root, index);
1375 };
1376 }
1377 add!(
1378 invalid_client_exports,
1379 "invalid-client-export",
1380 "Invalid client export"
1381 );
1382 add!(
1383 mixed_client_server_barrels,
1384 "mixed-client-server-barrel",
1385 "Mixed client/server barrel"
1386 );
1387 add!(
1388 misplaced_directives,
1389 "misplaced-directive",
1390 "Misplaced framework directive"
1391 );
1392 add!(
1393 unprovided_injects,
1394 "unprovided-inject",
1395 "Injected value is never provided"
1396 );
1397 add!(
1398 unrendered_components,
1399 "unrendered-component",
1400 "Component is never rendered"
1401 );
1402 add!(route_collisions, "route-collision", "Route collision");
1403 add!(
1404 dynamic_segment_name_conflicts,
1405 "dynamic-segment-conflict",
1406 "Dynamic segment conflict"
1407 );
1408 add!(
1409 unused_component_props,
1410 "unused-component-prop",
1411 "Unused component prop"
1412 );
1413 add!(
1414 unused_component_emits,
1415 "unused-component-emit",
1416 "Unused component event"
1417 );
1418 add!(
1419 unused_component_inputs,
1420 "unused-component-input",
1421 "Unused component input"
1422 );
1423 add!(
1424 unused_component_outputs,
1425 "unused-component-output",
1426 "Unused component output"
1427 );
1428 add!(
1429 unused_svelte_events,
1430 "unused-svelte-event",
1431 "Unused Svelte event"
1432 );
1433 add!(
1434 unused_server_actions,
1435 "unused-server-action",
1436 "Unused server action"
1437 );
1438 add!(
1439 unused_load_data_keys,
1440 "unused-load-data-key",
1441 "Unused load-data key"
1442 );
1443 add!(prop_drilling_chains, "prop-drilling", "Prop-drilling chain");
1444 add!(thin_wrappers, "thin-wrapper", "Thin component wrapper");
1445 add!(
1446 duplicate_prop_shapes,
1447 "duplicate-prop-shape",
1448 "Duplicate prop shape"
1449 );
1450 let mut analysis = analysis_from_records(findings, count, count, "findings");
1451 if results.unused_load_data_keys_global_abstain {
1452 analysis.availability.reason = Some(
1453 "Load-data-key analysis abstained because whole-object page data usage was detected"
1454 .to_string(),
1455 );
1456 }
1457 VizFrameworkData {
1458 availability: analysis.availability,
1459 detector_availability: VizAvailability::unavailable(
1460 "detectors",
1461 "Framework detector coverage did not complete",
1462 ),
1463 findings_truncated: analysis.findings_truncated,
1464 findings: analysis.findings,
1465 detected_frameworks: Vec::new(),
1466 detectors: Vec::new(),
1467 }
1468}
1469
1470fn build_feature_flags(
1471 flags: &[FeatureFlag],
1472 index: &FileIndex<'_>,
1473 root: &Path,
1474) -> VizFindingAnalysis {
1475 let mut findings = Vec::new();
1476 push_findings(
1477 &mut findings,
1478 "feature-flag",
1479 "Feature flag use",
1480 flags,
1481 root,
1482 index,
1483 );
1484 analysis_from_records(findings, flags.len(), flags.len(), "flags")
1485}
1486
1487fn build_security(
1488 results: &AnalysisResults,
1489 index: &FileIndex<'_>,
1490 root: &Path,
1491) -> VizSecurityData {
1492 let total = results.security_findings.len();
1493 let truncated =
1494 (total > MAX_ANALYSIS_FINDINGS).then_some(total.saturating_sub(MAX_ANALYSIS_FINDINGS));
1495 let mut sorted_findings: Vec<&SecurityFinding> = results.security_findings.iter().collect();
1496 sorted_findings.sort_by_key(|finding| {
1497 let severity = serialized_label(&crate::security::derive_security_severity(finding));
1498 let priority = match severity.as_str() {
1499 "high" => 0,
1500 "medium" => 1,
1501 _ => 2,
1502 };
1503 (priority, relative_path(&finding.path, root), finding.line)
1504 });
1505 let candidates = sorted_findings
1506 .into_iter()
1507 .take(MAX_ANALYSIS_FINDINGS)
1508 .map(|finding| build_security_candidate(finding, index, root))
1509 .collect();
1510
1511 let mut blind_spots = Vec::new();
1512 if results.security_unresolved_edge_files > 0 {
1513 blind_spots.push(VizSecurityBlindSpot {
1514 kind: "unresolved-dynamic-imports".to_string(),
1515 count: results.security_unresolved_edge_files,
1516 path: None,
1517 file: None,
1518 line: None,
1519 reason: Some("Dynamic imports prevent complete client/server reachability".to_string()),
1520 });
1521 }
1522 if results.security_unresolved_callee_sites > 0 {
1523 blind_spots.push(VizSecurityBlindSpot {
1524 kind: "unresolved-callee-sites".to_string(),
1525 count: results.security_unresolved_callee_sites,
1526 path: None,
1527 file: None,
1528 line: None,
1529 reason: Some(
1530 "Dynamic or computed callees could not be matched to the sink catalogue"
1531 .to_string(),
1532 ),
1533 });
1534 }
1535 let diagnostic_count = results.security_unresolved_callee_diagnostics.len();
1536 for diagnostic in results
1537 .security_unresolved_callee_diagnostics
1538 .iter()
1539 .take(MAX_SECURITY_BLIND_SPOT_SAMPLES)
1540 {
1541 blind_spots.push(VizSecurityBlindSpot {
1542 kind: "unresolved-callee-sample".to_string(),
1543 count: 1,
1544 path: Some(relative_path(&diagnostic.path, root)),
1545 file: index.index_of_path(&diagnostic.path),
1546 line: Some(diagnostic.line),
1547 reason: Some(serialized_label(&diagnostic.reason)),
1548 });
1549 }
1550
1551 VizSecurityData {
1552 availability: VizAvailability::complete(total, "candidates", truncated),
1553 runtime_availability: VizAvailability::unavailable(
1554 "observations",
1555 NO_RUNTIME_COVERAGE_REASON,
1556 ),
1557 candidates,
1558 blind_spot_count: results.security_unresolved_edge_files
1559 + results.security_unresolved_callee_sites,
1560 blind_spots_truncated: (diagnostic_count > MAX_SECURITY_BLIND_SPOT_SAMPLES)
1561 .then_some(diagnostic_count.saturating_sub(MAX_SECURITY_BLIND_SPOT_SAMPLES)),
1562 blind_spots,
1563 }
1564}
1565
1566fn build_security_candidate(
1567 finding: &SecurityFinding,
1568 index: &FileIndex<'_>,
1569 root: &Path,
1570) -> VizSecurityCandidate {
1571 let kind = serialized_label(&finding.kind);
1572 let path = relative_path(&finding.path, root);
1573 let severity = serialized_label(&crate::security::derive_security_severity(finding));
1574 let id = crate::security::security_finding_id(finding, Path::new(&path));
1575 let reachability = finding.reachability.as_ref();
1576 let architecture_zone = finding
1577 .candidate
1578 .boundary
1579 .architecture_zone
1580 .as_ref()
1581 .map(|zone| format!("{} -> {}", zone.from, zone.to));
1582 let dead_code = serialize_relative(finding.dead_code.as_ref(), root);
1583 let runtime = serialize_relative(finding.runtime.as_ref(), root);
1584 let taint_flow = security_taint_flow(finding, index, root);
1585 let observed_controls = security_controls(finding, root);
1586 let actions = serialize_relative_value(&finding.actions, root)
1587 .unwrap_or_else(|| Value::Array(Vec::new()));
1588 let trace = security_trace(finding, index, root);
1589 let taint_trace = finding
1590 .reachability
1591 .as_ref()
1592 .map_or_else(Vec::new, |reachability| {
1593 trace_hops(&reachability.untrusted_source_trace, index, root)
1594 });
1595 VizSecurityCandidate {
1596 id,
1597 kind,
1598 category: finding.category.clone(),
1599 cwe: finding.cwe,
1600 file: index.index_of_path(&finding.path),
1601 path,
1602 line: finding.line,
1603 col: finding.col,
1604 evidence: finding.evidence.clone(),
1605 severity,
1606 taint_confidence: reachability
1607 .and_then(|reachability| reachability.taint_confidence.as_ref())
1608 .map(serialized_label),
1609 source_kind: finding.candidate.source_kind.clone(),
1610 sink: finding.candidate.sink.callee.clone(),
1611 url_shape: finding
1612 .candidate
1613 .sink
1614 .url_shape
1615 .as_ref()
1616 .map(serialized_label),
1617 network_destination: finding
1618 .candidate
1619 .network
1620 .as_ref()
1621 .and_then(|network| network.destination.clone()),
1622 reachable_from_entry: reachability.map(|value| value.reachable_from_entry),
1623 reachable_from_untrusted_source: reachability
1624 .map(|value| value.reachable_from_untrusted_source),
1625 blast_radius: reachability.map(|value| value.blast_radius),
1626 crosses_boundary: reachability.is_some_and(|value| value.crosses_boundary)
1627 || finding.candidate.boundary.client_server
1628 || finding.candidate.boundary.cross_module
1629 || architecture_zone.is_some(),
1630 client_server_boundary: finding.candidate.boundary.client_server,
1631 cross_module_boundary: finding.candidate.boundary.cross_module,
1632 architecture_zone,
1633 dead_code,
1634 runtime,
1635 taint_flow,
1636 observed_controls,
1637 control_verification_prompt: finding
1638 .attack_surface
1639 .as_ref()
1640 .map(|surface| surface.defensive_boundary.verification_prompt.clone()),
1641 trace,
1642 taint_trace,
1643 actions,
1644 }
1645}
1646
1647fn serialize_relative<T: Serialize>(value: Option<&T>, root: &Path) -> Option<Value> {
1648 value.and_then(|value| serialize_relative_value(value, root))
1649}
1650
1651fn serialize_relative_value<T: Serialize>(value: &T, root: &Path) -> Option<Value> {
1652 let mut serialized = serde_json::to_value(value).ok()?;
1653 relativize_value_paths(&mut serialized, root);
1654 Some(serialized)
1655}
1656
1657fn security_controls(finding: &SecurityFinding, root: &Path) -> Vec<Value> {
1658 finding
1659 .attack_surface
1660 .as_ref()
1661 .map_or_else(Vec::new, |surface| {
1662 surface
1663 .defensive_boundary
1664 .controls
1665 .iter()
1666 .filter_map(|control| serialize_relative_value(control, root))
1667 .collect()
1668 })
1669}
1670
1671fn security_trace(
1672 finding: &SecurityFinding,
1673 index: &FileIndex<'_>,
1674 root: &Path,
1675) -> Vec<VizSecurityTraceHop> {
1676 trace_hops(&finding.trace, index, root)
1677}
1678
1679fn trace_hops(
1680 hops: &[fallow_types::results::TraceHop],
1681 index: &FileIndex<'_>,
1682 root: &Path,
1683) -> Vec<VizSecurityTraceHop> {
1684 hops.iter()
1685 .map(|hop| VizSecurityTraceHop {
1686 file: index.index_of_path(&hop.path),
1687 path: relative_path(&hop.path, root),
1688 line: hop.line,
1689 col: hop.col,
1690 role: serialized_label(&hop.role),
1691 })
1692 .collect()
1693}
1694
1695fn security_taint_flow(
1696 finding: &SecurityFinding,
1697 index: &FileIndex<'_>,
1698 root: &Path,
1699) -> Option<VizSecurityTaintFlow> {
1700 let flow = finding.taint_flow.as_ref()?;
1701 let endpoint = |value: &fallow_types::results::TaintEndpoint| VizSecurityEndpoint {
1702 file: index.index_of_path(&value.path),
1703 path: relative_path(&value.path, root),
1704 line: value.line,
1705 col: value.col,
1706 };
1707 Some(VizSecurityTaintFlow {
1708 source: endpoint(&flow.source),
1709 sink: endpoint(&flow.sink),
1710 intra_module: flow.path.intra_module,
1711 cross_module_hops: flow.path.cross_module_hops,
1712 })
1713}
1714
1715pub fn apply_health_report(data: &mut VizData, report: &HealthReport, root: &Path) {
1718 let by_path: FxHashMap<String, u32> = data
1719 .files
1720 .iter()
1721 .enumerate()
1722 .map(|(index, file)| (file.path.clone(), clamp_u32(index)))
1723 .collect();
1724 apply_health_data(data, report, root, &by_path);
1725 apply_framework_data(data, report);
1726 apply_styling_data(data, report, root, &by_path);
1727}
1728
1729fn apply_health_data(
1730 data: &mut VizData,
1731 report: &HealthReport,
1732 root: &Path,
1733 by_path: &FxHashMap<String, u32>,
1734) {
1735 let resolve = |path: &Path| by_path.get(&relative_path(path, root)).copied();
1736 let hotspot_by_path: FxHashMap<String, &fallow_output::HotspotFinding> = report
1737 .hotspots
1738 .iter()
1739 .map(|hotspot| (relative_path(&hotspot.path, root), hotspot))
1740 .collect();
1741 let files = health_files(report, root, by_path, &hotspot_by_path);
1742 let (findings, total_findings) = health_findings(report, root, &resolve);
1743 let concern_count = health_concern_count(report, root, by_path);
1744 data.health = VizHealthData {
1745 availability: VizAvailability::complete(concern_count, "files", None),
1746 capabilities: health_capabilities(report),
1747 shared_parse: data.health.shared_parse,
1748 score: report.health_score.as_ref().map(|score| score.score),
1749 grade: report
1750 .health_score
1751 .as_ref()
1752 .map(|score| score.grade.to_string()),
1753 average_maintainability: report.summary.average_maintainability,
1754 files_truncated: report
1755 .file_scores
1756 .len()
1757 .checked_sub(MAX_HEALTH_FILES)
1758 .filter(|count| *count > 0),
1759 findings_truncated: total_findings
1760 .checked_sub(findings.len())
1761 .filter(|count| *count > 0),
1762 files,
1763 findings,
1764 };
1765}
1766
1767fn health_concern_count(
1768 report: &HealthReport,
1769 root: &Path,
1770 by_path: &FxHashMap<String, u32>,
1771) -> usize {
1772 let mut files = rustc_hash::FxHashSet::default();
1773 let mut add = |path: &Path| {
1774 if let Some(file) = by_path.get(&relative_path(path, root)) {
1775 files.insert(*file);
1776 }
1777 };
1778 for finding in &report.findings {
1779 add(&finding.path);
1780 }
1781 for hotspot in &report.hotspots {
1782 add(&hotspot.path);
1783 }
1784 if let Some(gaps) = &report.coverage_gaps {
1785 for finding in &gaps.files {
1786 add(&finding.file.path);
1787 }
1788 for finding in &gaps.exports {
1789 add(&finding.export.path);
1790 }
1791 }
1792 files.len()
1793}
1794
1795fn health_files(
1796 report: &HealthReport,
1797 root: &Path,
1798 by_path: &FxHashMap<String, u32>,
1799 hotspots: &FxHashMap<String, &fallow_output::HotspotFinding>,
1800) -> Vec<VizHealthFile> {
1801 report
1802 .file_scores
1803 .iter()
1804 .take(MAX_HEALTH_FILES)
1805 .filter_map(|score| {
1806 let path = relative_path(&score.path, root);
1807 let file = by_path.get(&path).copied()?;
1808 let hotspot = hotspots.get(&path).copied();
1809 Some(VizHealthFile {
1810 file,
1811 path,
1812 maintainability_index: score.maintainability_index,
1813 crap_max: score.crap_max,
1814 complexity_density: score.complexity_density,
1815 fan_in: score.fan_in,
1816 fan_out: score.fan_out,
1817 hotspot_score: hotspot.map(|entry| entry.score),
1818 commits: hotspot.map(|entry| entry.commits),
1819 ownership: hotspot
1820 .and_then(|entry| serialize_relative(entry.ownership.as_ref(), root)),
1821 })
1822 })
1823 .collect()
1824}
1825
1826fn health_findings(
1827 report: &HealthReport,
1828 root: &Path,
1829 resolve: &dyn Fn(&Path) -> Option<u32>,
1830) -> (Vec<VizFinding>, usize) {
1831 let coverage_count = report
1832 .coverage_gaps
1833 .as_ref()
1834 .map_or(0, |gaps| gaps.files.len() + gaps.exports.len());
1835 let total = report.findings.len() + report.hotspots.len() + coverage_count;
1836 let mut findings = Vec::with_capacity(total.min(MAX_ANALYSIS_FINDINGS));
1837 append_findings(
1838 &mut findings,
1839 &report.findings,
1840 "health-finding",
1841 "Health threshold exceeded",
1842 root,
1843 resolve,
1844 );
1845 append_findings(
1846 &mut findings,
1847 &report.hotspots,
1848 "git-hotspot",
1849 "Complex and frequently changed file",
1850 root,
1851 resolve,
1852 );
1853 if let Some(gaps) = &report.coverage_gaps {
1854 append_findings(
1855 &mut findings,
1856 &gaps.files,
1857 "coverage-gap-file",
1858 "File has no test path",
1859 root,
1860 resolve,
1861 );
1862 append_findings(
1863 &mut findings,
1864 &gaps.exports,
1865 "coverage-gap-export",
1866 "Export has no test path",
1867 root,
1868 resolve,
1869 );
1870 }
1871 (findings, total)
1872}
1873
1874fn append_findings<T: Serialize>(
1875 out: &mut Vec<VizFinding>,
1876 values: &[T],
1877 kind: &str,
1878 title: &str,
1879 root: &Path,
1880 resolve: &dyn Fn(&Path) -> Option<u32>,
1881) {
1882 let remaining = MAX_ANALYSIS_FINDINGS.saturating_sub(out.len());
1883 out.extend(values.iter().take(remaining).filter_map(|value| {
1884 serde_json::to_value(value)
1885 .ok()
1886 .map(|detail| finding_from_value(kind, title, detail, root, resolve))
1887 }));
1888}
1889
1890fn health_capabilities(report: &HealthReport) -> VizHealthCapabilities {
1891 let file_count = report.file_scores.len();
1892 let coverage = report.coverage_gaps.as_ref().map_or_else(
1893 || VizAvailability::unavailable("gaps", "Coverage gap analysis did not produce a result"),
1894 |gaps| VizAvailability::complete(gaps.files.len() + gaps.exports.len(), "gaps", None),
1895 );
1896 let runtime = report.runtime_coverage.as_ref().map_or_else(
1897 || VizAvailability::unavailable("observations", NO_RUNTIME_COVERAGE_REASON),
1898 |runtime| {
1899 VizAvailability::complete(runtime.summary.functions_tracked, "observations", None)
1900 },
1901 );
1902 VizHealthCapabilities {
1903 complexity: VizAvailability::complete(report.findings.len(), "findings", None),
1904 maintainability: VizAvailability::complete(file_count, "files", None),
1905 crap: VizAvailability::complete(file_count, "files", None),
1906 coverage,
1907 runtime,
1908 churn: VizAvailability::disabled("files", "Git history is not loaded by Viz"),
1909 hotspots: VizAvailability::disabled("files", "Git history is not loaded by Viz"),
1910 ownership: VizAvailability::disabled("files", "Git history is not loaded by Viz"),
1911 }
1912}
1913
1914fn unavailable_health_capabilities(reason: &str) -> VizHealthCapabilities {
1915 VizHealthCapabilities {
1916 complexity: VizAvailability::unavailable("findings", reason),
1917 maintainability: VizAvailability::unavailable("files", reason),
1918 crap: VizAvailability::unavailable("files", reason),
1919 coverage: VizAvailability::unavailable("gaps", reason),
1920 runtime: VizAvailability::unavailable("observations", NO_RUNTIME_COVERAGE_REASON),
1921 churn: VizAvailability::unavailable("files", reason),
1922 hotspots: VizAvailability::unavailable("files", reason),
1923 ownership: VizAvailability::unavailable("files", reason),
1924 }
1925}
1926
1927fn apply_framework_data(data: &mut VizData, report: &HealthReport) {
1928 let count = data.frameworks.availability.count;
1929 let Some(diagnostics) = &report.framework_health else {
1930 if count == 0 {
1931 data.frameworks.detector_availability = VizAvailability {
1932 state: VizAvailabilityState::NotApplicable,
1933 count: 0,
1934 unit: "detectors",
1935 reason: Some("No supported framework was detected".to_string()),
1936 truncated: None,
1937 };
1938 data.frameworks.availability.state = VizAvailabilityState::NotApplicable;
1939 data.frameworks.availability.reason =
1940 Some("No supported framework was detected".to_string());
1941 } else {
1942 data.frameworks.detector_availability = VizAvailability::unavailable(
1943 "detectors",
1944 "Framework detector metadata was not produced",
1945 );
1946 }
1947 return;
1948 };
1949 data.frameworks
1950 .detected_frameworks
1951 .clone_from(&diagnostics.detected_frameworks);
1952 data.frameworks.detectors = diagnostics
1953 .detectors
1954 .iter()
1955 .map(|detector| VizFrameworkDetector {
1956 id: detector.id.clone(),
1957 framework: detector.framework.clone(),
1958 status: serialized_label(&detector.status),
1959 reason: detector.reason.clone(),
1960 })
1961 .collect();
1962 data.frameworks.detector_availability =
1963 VizAvailability::complete(diagnostics.detectors.len(), "detectors", None);
1964 if diagnostics.detected_frameworks.is_empty() && count == 0 {
1965 data.frameworks.availability.state = VizAvailabilityState::NotApplicable;
1966 data.frameworks.availability.reason =
1967 Some("No supported framework was detected".to_string());
1968 data.frameworks.detector_availability.state = VizAvailabilityState::NotApplicable;
1969 data.frameworks.detector_availability.reason =
1970 Some("No supported framework was detected".to_string());
1971 }
1972}
1973
1974fn apply_styling_data(
1975 data: &mut VizData,
1976 report: &HealthReport,
1977 root: &Path,
1978 by_path: &FxHashMap<String, u32>,
1979) {
1980 let resolve = |path: &Path| by_path.get(&relative_path(path, root)).copied();
1981 let count = report.styling_findings.len();
1982 let mut findings = Vec::with_capacity(count.min(MAX_ANALYSIS_FINDINGS));
1983 append_findings(
1984 &mut findings,
1985 &report.styling_findings,
1986 "styling-finding",
1987 "Styling health finding",
1988 root,
1989 &resolve,
1990 );
1991 let truncated = count.checked_sub(findings.len()).filter(|value| *value > 0);
1992 let styling = report.styling_health.as_ref();
1993 data.styling = VizStylingData {
1994 availability: report.css_analytics.as_ref().map_or_else(
1995 || VizAvailability {
1996 state: VizAvailabilityState::NotApplicable,
1997 count: 0,
1998 unit: "findings",
1999 reason: Some("No supported CSS or component styling was detected".to_string()),
2000 truncated: None,
2001 },
2002 |_| VizAvailability::complete(count, "findings", truncated),
2003 ),
2004 findings_truncated: truncated,
2005 findings,
2006 score: styling.map(|health| health.score),
2007 grade: styling.map(|health| health.grade.to_string()),
2008 confidence: styling.map(|health| serialized_label(&health.confidence)),
2009 summary: report
2010 .css_analytics
2011 .as_ref()
2012 .and_then(|analytics| serde_json::to_value(&analytics.summary).ok()),
2013 };
2014}
2015
2016struct FilePropertyMaps<'a> {
2018 zone_by_file: &'a FxHashMap<u32, u16>,
2019 clone_groups_by_file: &'a FxHashMap<u32, Vec<u32>>,
2020 dup_lines_by_file: &'a FxHashMap<u32, u32>,
2021 cycles: &'a [Vec<u32>],
2022}
2023
2024fn display_root(root: &Path) -> String {
2025 root.file_name().map_or_else(
2026 || root.to_string_lossy().into_owned(),
2027 |n| n.to_string_lossy().into_owned(),
2028 )
2029}
2030
2031fn relative_path(path: &Path, root: &Path) -> String {
2032 if let Ok(relative) = path.strip_prefix(root) {
2033 return relative.to_string_lossy().replace('\\', "/");
2034 }
2035 if path.has_root() {
2040 let name = path
2041 .file_name()
2042 .map_or_else(|| "path".into(), |name| name.to_string_lossy());
2043 return format!("<external>/{name}");
2044 }
2045 path.to_string_lossy().replace('\\', "/")
2046}
2047
2048fn build_workspaces(workspaces: &[WorkspaceInfo], root: &Path) -> Vec<VizWorkspace> {
2049 workspaces
2050 .iter()
2051 .map(|ws| VizWorkspace {
2052 name: ws.name.clone(),
2053 root: relative_path(&ws.root, root),
2054 })
2055 .collect()
2056}
2057
2058fn workspace_index_for(path: &Path, workspaces: &[WorkspaceInfo]) -> Option<u16> {
2059 let mut best: Option<(usize, usize)> = None;
2060 for (i, ws) in workspaces.iter().enumerate() {
2061 if path.starts_with(&ws.root) {
2062 let depth = ws.root.components().count();
2063 if best.is_none_or(|(_, d)| depth > d) {
2064 best = Some((i, depth));
2065 }
2066 }
2067 }
2068 best.map(|(i, _)| clamp_u16(i))
2069}
2070
2071fn classify_zones(
2072 input: &VizBuildInput<'_>,
2073 index: &FileIndex<'_>,
2074) -> (Vec<VizZone>, FxHashMap<u32, u16>) {
2075 let boundaries = &input.config.boundaries;
2076 let mut zones: Vec<VizZone> = boundaries
2077 .zones
2078 .iter()
2079 .map(|z| VizZone {
2080 name: z.name.clone(),
2081 files: 0,
2082 })
2083 .collect();
2084 let name_to_index: FxHashMap<&str, u16> = boundaries
2085 .zones
2086 .iter()
2087 .enumerate()
2088 .map(|(i, z)| (z.name.as_str(), clamp_u16(i)))
2089 .collect();
2090
2091 let mut zone_by_file = FxHashMap::default();
2092 if zones.is_empty() {
2093 return (zones, zone_by_file);
2094 }
2095
2096 for (i, file) in index.ordered.iter().enumerate() {
2097 let rel = relative_path(&file.path, &input.config.root);
2098 if let Some(zone_name) = boundaries.classify_zone(&rel)
2099 && let Some(&zone_idx) = name_to_index.get(zone_name)
2100 {
2101 zone_by_file.insert(clamp_u32(i), zone_idx);
2102 zones[zone_idx as usize].files += 1;
2103 }
2104 }
2105
2106 (zones, zone_by_file)
2107}
2108
2109type CloneMaps = (
2112 Vec<VizCloneGroup>,
2113 FxHashMap<u32, Vec<u32>>,
2114 FxHashMap<u32, u32>,
2115 u32,
2116);
2117
2118fn build_clones(
2119 duplication: &DuplicationReport,
2120 index: &FileIndex<'_>,
2121 max_groups: usize,
2122) -> CloneMaps {
2123 let mut clones = Vec::new();
2124 let mut groups_by_file: FxHashMap<u32, Vec<u32>> = FxHashMap::default();
2125 let mut dup_lines_by_file: FxHashMap<u32, u32> = FxHashMap::default();
2126 let mut truncated: usize = 0;
2127
2128 for group in &duplication.clone_groups {
2129 let instances: Vec<VizCloneInstance> = group
2130 .instances
2131 .iter()
2132 .filter_map(|inst| {
2133 index
2134 .index_of_path(&inst.file)
2135 .map(|file| VizCloneInstance {
2136 file,
2137 start_line: clamp_u32(inst.start_line),
2138 end_line: clamp_u32(inst.end_line),
2139 })
2140 })
2141 .collect();
2142 if instances.len() < 2 {
2143 continue;
2144 }
2145 if clones.len() >= max_groups {
2146 truncated += 1;
2147 continue;
2148 }
2149
2150 let group_idx = clamp_u32(clones.len());
2151 for inst in &instances {
2152 let entry = groups_by_file.entry(inst.file).or_default();
2153 if entry.last() != Some(&group_idx) {
2154 entry.push(group_idx);
2155 }
2156 *dup_lines_by_file.entry(inst.file).or_default() +=
2157 inst.end_line.saturating_sub(inst.start_line) + 1;
2158 }
2159
2160 let (preview, highlight_start, highlight_lines) = group
2161 .instances
2162 .first()
2163 .map(build_clone_preview)
2164 .unwrap_or_default();
2165
2166 clones.push(VizCloneGroup {
2167 lines: group.line_count,
2168 tokens: group.token_count,
2169 instances,
2170 preview,
2171 highlight_start,
2172 highlight_lines,
2173 });
2174 }
2175
2176 (
2177 clones,
2178 groups_by_file,
2179 dup_lines_by_file,
2180 clamp_u32(truncated),
2181 )
2182}
2183
2184fn truncate_preview(fragment: &str) -> String {
2185 let mut out = String::new();
2186 for (i, line) in fragment.lines().enumerate() {
2187 if i >= CLONE_PREVIEW_MAX_LINES || out.len() + line.len() > CLONE_PREVIEW_MAX_BYTES {
2188 out.push('\u{2026}');
2189 break;
2190 }
2191 if i > 0 {
2192 out.push('\n');
2193 }
2194 out.push_str(line);
2195 }
2196 out
2197}
2198
2199fn build_clone_preview(inst: &CloneInstance) -> (String, u32, u32) {
2209 let Ok(source) = std::fs::read_to_string(&inst.file) else {
2210 return fragment_fallback(&inst.fragment);
2211 };
2212 let lines: Vec<&str> = source.lines().collect();
2213 let total = lines.len();
2214 if total == 0 || inst.start_line == 0 || inst.start_line > total {
2215 return fragment_fallback(&inst.fragment);
2216 }
2217
2218 let block_start = inst.start_line - 1;
2221 let block_end = inst.end_line.min(total).max(inst.start_line);
2222 let mut block_lines = block_end - block_start;
2223 let mut before = block_start.min(CLONE_PREVIEW_CONTEXT);
2224 let mut after = (total - block_end).min(CLONE_PREVIEW_CONTEXT);
2225
2226 if before + block_lines + after > CLONE_PREVIEW_MAX_LINES {
2231 if before + block_lines >= CLONE_PREVIEW_MAX_LINES {
2232 after = 0;
2233 block_lines = CLONE_PREVIEW_MAX_LINES.saturating_sub(before).max(1);
2234 } else {
2235 trim_context(
2236 &mut before,
2237 &mut after,
2238 CLONE_PREVIEW_MAX_LINES - block_lines,
2239 );
2240 }
2241 }
2242
2243 enforce_byte_cap(
2244 &lines,
2245 block_start,
2246 &mut before,
2247 &mut after,
2248 &mut block_lines,
2249 );
2250
2251 let win_start = block_start - before;
2252 let win_end = win_start + before + block_lines + after;
2253 let preview = lines[win_start..win_end].join("\n");
2254 (preview, clamp_u32(before), clamp_u32(block_lines))
2255}
2256
2257fn fragment_fallback(fragment: &str) -> (String, u32, u32) {
2260 let preview = truncate_preview(fragment);
2261 let highlight_lines = if preview.is_empty() {
2262 0
2263 } else {
2264 preview.lines().count()
2265 };
2266 (preview, 0, clamp_u32(highlight_lines))
2267}
2268
2269fn trim_context(before: &mut usize, after: &mut usize, budget: usize) {
2273 while *before + *after > budget {
2274 if *before >= *after {
2275 *before -= 1;
2276 } else {
2277 *after -= 1;
2278 }
2279 }
2280}
2281
2282fn enforce_byte_cap(
2287 lines: &[&str],
2288 block_start: usize,
2289 before: &mut usize,
2290 after: &mut usize,
2291 block_lines: &mut usize,
2292) {
2293 let window_bytes = |before: usize, after: usize, block_lines: usize| -> usize {
2294 let start = block_start - before;
2295 let end = start + before + block_lines + after;
2296 let separators = (end - start).saturating_sub(1);
2297 lines[start..end].iter().map(|l| l.len()).sum::<usize>() + separators
2298 };
2299 while window_bytes(*before, *after, *block_lines) > CLONE_PREVIEW_MAX_BYTES {
2300 if *before + *after > 0 {
2301 if *before >= *after {
2302 *before -= 1;
2303 } else {
2304 *after -= 1;
2305 }
2306 } else if *block_lines > 1 {
2307 *block_lines -= 1;
2308 } else {
2309 break;
2310 }
2311 }
2312}
2313
2314fn build_cycles(results: &AnalysisResults, index: &FileIndex<'_>) -> Vec<Vec<u32>> {
2315 results
2316 .circular_dependencies
2317 .iter()
2318 .filter_map(|cd| {
2319 let ids: Vec<u32> = cd
2320 .cycle
2321 .files
2322 .iter()
2323 .filter_map(|p| index.index_of_path(p))
2324 .collect();
2325 (ids.len() == cd.cycle.files.len()).then_some(ids)
2326 })
2327 .collect()
2328}
2329
2330fn build_violations(
2331 results: &AnalysisResults,
2332 zones: &[VizZone],
2333 index: &FileIndex<'_>,
2334) -> Vec<VizViolation> {
2335 let name_to_index: FxHashMap<&str, u16> = zones
2336 .iter()
2337 .enumerate()
2338 .map(|(i, z)| (z.name.as_str(), clamp_u16(i)))
2339 .collect();
2340
2341 results
2342 .boundary_violations
2343 .iter()
2344 .filter_map(|finding| {
2345 let v = &finding.violation;
2346 let from = index.index_of_path(&v.from_path)?;
2347 let to = index.index_of_path(&v.to_path)?;
2348 let from_zone = *name_to_index.get(v.from_zone.as_str())?;
2349 let to_zone = *name_to_index.get(v.to_zone.as_str())?;
2350 Some(VizViolation {
2351 from,
2352 to,
2353 from_zone,
2354 to_zone,
2355 line: v.line,
2356 specifier: v.import_specifier.clone(),
2357 })
2358 })
2359 .collect()
2360}
2361
2362fn build_edges(graph: &RetainedModuleGraph, index: &FileIndex<'_>) -> Vec<[u32; 3]> {
2363 let graph = graph.as_graph();
2364 let mut edges = Vec::with_capacity(graph.edge_count());
2365 for node in &graph.modules {
2366 let Some(source) = index.index_of_file_id(node.file_id.0) else {
2367 continue;
2368 };
2369 for (target_id, all_type_only, _span) in graph.outgoing_edge_summaries(node.file_id) {
2370 let Some(target) = index.index_of_file_id(target_id.0) else {
2371 continue;
2372 };
2373 let flags = if all_type_only {
2374 EDGE_FLAG_TYPE_ONLY
2375 } else {
2376 0
2377 };
2378 edges.push([source, target, flags]);
2379 }
2380 }
2381 edges
2382}
2383
2384#[derive(Default)]
2386struct ComplexityRollup {
2387 fn_count: u16,
2388 max_cyclomatic: u16,
2389 max_cognitive: u16,
2390 react_hooks: u16,
2391 jsx_depth: u16,
2392 functions: Vec<VizFunction>,
2393}
2394
2395fn rollup_complexity(functions: &[FunctionComplexity]) -> ComplexityRollup {
2396 let mut rollup = ComplexityRollup {
2397 fn_count: clamp_u16(functions.len()),
2398 ..ComplexityRollup::default()
2399 };
2400 for f in functions {
2401 rollup.max_cyclomatic = rollup.max_cyclomatic.max(f.cyclomatic);
2402 rollup.max_cognitive = rollup.max_cognitive.max(f.cognitive);
2403 rollup.react_hooks = rollup.react_hooks.saturating_add(f.react_hook_count);
2404 rollup.jsx_depth = rollup.jsx_depth.max(f.react_jsx_max_depth);
2405 }
2406
2407 let mut named: Vec<&FunctionComplexity> = functions
2412 .iter()
2413 .filter(|f| !f.name.starts_with('<'))
2414 .collect();
2415 named.sort_by(|a, b| {
2416 b.cyclomatic
2417 .cmp(&a.cyclomatic)
2418 .then(b.cognitive.cmp(&a.cognitive))
2419 });
2420 rollup.functions = named
2421 .into_iter()
2422 .map(|f| VizFunction {
2423 name: f.name.clone(),
2424 line: f.line,
2425 cyclomatic: f.cyclomatic,
2426 cognitive: f.cognitive,
2427 lines: f.line_count,
2428 hooks: f.react_hook_count,
2429 jsx_depth: f.react_jsx_max_depth,
2430 props: f.react_prop_count,
2431 })
2432 .collect();
2433 rollup
2434}
2435
2436fn build_files(
2437 input: &VizBuildInput<'_>,
2438 index: &FileIndex<'_>,
2439 maps: &FilePropertyMaps<'_>,
2440) -> Vec<VizFile> {
2441 let graph = input.graph.as_graph();
2442 let unused_file_paths: rustc_hash::FxHashSet<&Path> = input
2443 .results
2444 .unused_files
2445 .iter()
2446 .map(|f| f.file.path.as_path())
2447 .collect();
2448
2449 let mut unused_exports_by_file: FxHashMap<&Path, Vec<String>> = FxHashMap::default();
2450 for export in &input.results.unused_exports {
2451 unused_exports_by_file
2452 .entry(export.export.path.as_path())
2453 .or_default()
2454 .push(export.export.export_name.clone());
2455 }
2456 for export in &input.results.unused_types {
2457 unused_exports_by_file
2458 .entry(export.export.path.as_path())
2459 .or_default()
2460 .push(export.export.export_name.clone());
2461 }
2462
2463 let mut complexity_by_file_id: FxHashMap<u32, ComplexityRollup> = FxHashMap::default();
2464 if let Some(modules) = input.modules {
2465 for module in modules {
2466 if !module.complexity.is_empty() {
2467 complexity_by_file_id
2468 .insert(module.file_id.0, rollup_complexity(&module.complexity));
2469 }
2470 }
2471 }
2472
2473 let mut in_cycle = vec![false; index.ordered.len()];
2474 for cycle in maps.cycles {
2475 for &idx in cycle {
2476 if let Some(slot) = in_cycle.get_mut(idx as usize) {
2477 *slot = true;
2478 }
2479 }
2480 }
2481
2482 index
2483 .ordered
2484 .iter()
2485 .enumerate()
2486 .map(|(i, file)| {
2487 let viz_idx = clamp_u32(i);
2488 let node_idx = file.id.0 as usize;
2489 let node = graph.modules.get(node_idx);
2490 let is_entry = node.is_some_and(|n| n.is_entry_point());
2491 let export_count = node.map_or(0, |n| clamp_u16(n.exports.len()));
2492 let import_count = clamp_u16(graph.edges_for(file.id).len());
2493 let importer_count = clamp_u16(input.graph.direct_importer_count(file.id));
2494
2495 let unused_export_names = unused_exports_by_file
2496 .remove(file.path.as_path())
2497 .unwrap_or_default();
2498 let unused_export_count = clamp_u16(unused_export_names.len());
2499
2500 let status = if unused_file_paths.contains(file.path.as_path()) {
2501 VizFileStatus::Unused
2502 } else if unused_export_count > 0 {
2503 VizFileStatus::HasUnusedExports
2504 } else if is_entry {
2505 VizFileStatus::EntryPoint
2506 } else {
2507 VizFileStatus::Clean
2508 };
2509
2510 let complexity = complexity_by_file_id.remove(&file.id.0).unwrap_or_default();
2511
2512 VizFile {
2513 path: relative_path(&file.path, &input.config.root),
2514 size: file.size_bytes,
2515 status,
2516 export_count,
2517 unused_export_count,
2518 is_entry,
2519 importer_count,
2520 import_count,
2521 workspace: workspace_index_for(&file.path, input.workspaces),
2522 zone: maps.zone_by_file.get(&viz_idx).copied(),
2523 unused_exports: unused_export_names,
2524 fn_count: complexity.fn_count,
2525 max_cyclomatic: complexity.max_cyclomatic,
2526 max_cognitive: complexity.max_cognitive,
2527 react_hooks: complexity.react_hooks,
2528 jsx_depth: complexity.jsx_depth,
2529 functions: complexity.functions,
2530 dup_lines: maps.dup_lines_by_file.get(&viz_idx).copied().unwrap_or(0),
2531 clone_groups: maps
2532 .clone_groups_by_file
2533 .get(&viz_idx)
2534 .cloned()
2535 .unwrap_or_default(),
2536 in_cycle: in_cycle[i],
2537 }
2538 })
2539 .collect()
2540}
2541
2542fn build_summary(
2543 input: &VizBuildInput<'_>,
2544 files: &[VizFile],
2545 clones: &[VizCloneGroup],
2546 cycles: &[Vec<u32>],
2547 violations: &[VizViolation],
2548 clone_groups_truncated: u32,
2549) -> VizSummary {
2550 let results = input.results;
2551 VizSummary {
2552 total_files: files.len(),
2553 total_size: files.iter().map(|f| f.size).sum(),
2554 total_edges: input.graph.edge_count(),
2555 unused_files: results.unused_files.len(),
2556 unused_exports: results.unused_exports.len() + results.unused_types.len(),
2557 unused_types: results.unused_types.len(),
2558 unused_deps: results.unused_dependencies.len()
2559 + results.unused_dev_dependencies.len()
2560 + results.unused_optional_dependencies.len(),
2561 unresolved_imports: results.unresolved_imports.len(),
2562 circular_deps: cycles.len(),
2563 clone_groups: clones.len(),
2564 duplicated_lines: clones.iter().map(|c| c.lines * c.instances.len()).sum(),
2565 boundary_violations: violations.len(),
2566 hotspot_files: files
2567 .iter()
2568 .filter(|f| f.max_cyclomatic >= HOTSPOT_CYCLOMATIC_FLOOR)
2569 .count(),
2570 clone_groups_truncated: (clone_groups_truncated > 0).then_some(clone_groups_truncated),
2571 }
2572}
2573
2574fn clamp_u16(value: usize) -> u16 {
2575 u16::try_from(value).unwrap_or(u16::MAX)
2576}
2577
2578fn clamp_u32(value: usize) -> u32 {
2579 u32::try_from(value).unwrap_or(u32::MAX)
2580}
2581
2582#[cfg(test)]
2583mod tests {
2584 use std::path::PathBuf;
2585
2586 use fallow_config::{BoundaryConfig, BoundaryZone, FallowConfig};
2587 use fallow_graph::graph::ModuleGraph;
2588 use fallow_graph::resolve::{ResolveResult, ResolvedImport, ResolvedModule};
2589 use fallow_types::duplicates::{CloneGroup, CloneInstance};
2590 use fallow_types::extract::{ImportInfo, ImportedName};
2591 use fallow_types::output_dead_code::{BoundaryViolationFinding, CircularDependencyFinding};
2592 use fallow_types::output_format::OutputFormat;
2593 use fallow_types::results::{BoundaryViolation, CircularDependency};
2594
2595 use super::*;
2596 use crate::discover::{EntryPoint, EntryPointSource, FileId};
2597
2598 struct Fixture {
2600 config: ResolvedConfig,
2601 files: Vec<DiscoveredFile>,
2602 results: AnalysisResults,
2603 graph: crate::module_graph::RetainedModuleGraph,
2604 duplication: DuplicationReport,
2605 workspaces: Vec<WorkspaceInfo>,
2606 }
2607
2608 impl Fixture {
2609 fn input(&self) -> VizBuildInput<'_> {
2610 VizBuildInput {
2611 results: &self.results,
2612 graph: &self.graph,
2613 modules: None,
2614 files: &self.files,
2615 duplication: &self.duplication,
2616 workspaces: &self.workspaces,
2617 config: &self.config,
2618 feature_flags: &[],
2619 include_analysis_details: true,
2620 }
2621 }
2622 }
2623
2624 fn project_root() -> PathBuf {
2625 PathBuf::from("/viz-project")
2626 }
2627
2628 fn discovered(id: u32, path: PathBuf, size_bytes: u64) -> DiscoveredFile {
2629 DiscoveredFile {
2630 id: FileId(id),
2631 path,
2632 size_bytes,
2633 }
2634 }
2635
2636 fn import_of(target: FileId, specifier: &str) -> ResolvedImport {
2637 ResolvedImport {
2638 info: ImportInfo {
2639 source: specifier.to_owned(),
2640 imported_name: ImportedName::Named("value".to_owned()),
2641 local_name: "value".to_owned(),
2642 is_type_only: false,
2643 is_type_only_star: false,
2644 from_style: false,
2645 span: oxc_span::Span::new(0, 0),
2646 source_span: oxc_span::Span::new(0, 0),
2647 },
2648 target: ResolveResult::InternalModule(target),
2649 }
2650 }
2651
2652 fn zone(name: &str, pattern: &str) -> BoundaryZone {
2653 BoundaryZone {
2654 name: name.to_owned(),
2655 patterns: vec![pattern.to_owned()],
2656 auto_discover: Vec::new(),
2657 root: None,
2658 }
2659 }
2660
2661 fn resolved_config(root: &Path) -> ResolvedConfig {
2662 let config = FallowConfig {
2663 boundaries: BoundaryConfig {
2664 zones: vec![zone("app", "src/**"), zone("shared", "lib/**")],
2665 ..BoundaryConfig::default()
2666 },
2667 ..FallowConfig::default()
2668 };
2669 config.resolve(root.to_path_buf(), OutputFormat::Json, 1, false, true, None)
2670 }
2671
2672 fn cycle_finding(files: Vec<PathBuf>) -> CircularDependencyFinding {
2673 let length = files.len();
2674 CircularDependencyFinding::with_actions(CircularDependency {
2675 files,
2676 length,
2677 line: 1,
2678 col: 0,
2679 edges: Vec::new(),
2680 is_cross_package: false,
2681 })
2682 }
2683
2684 fn violation_finding(from_path: PathBuf, to_path: PathBuf) -> BoundaryViolationFinding {
2685 BoundaryViolationFinding::with_actions(BoundaryViolation {
2686 from_path,
2687 to_path,
2688 from_zone: "app".to_owned(),
2689 to_zone: "shared".to_owned(),
2690 import_specifier: "../lib/c".to_owned(),
2691 line: 2,
2692 col: 0,
2693 })
2694 }
2695
2696 fn clone_instance(file: PathBuf, start_line: usize, end_line: usize) -> CloneInstance {
2697 CloneInstance {
2698 file,
2699 start_line,
2700 end_line,
2701 start_col: 0,
2702 end_col: 0,
2703 fragment: "const shared = 1;\nconst repeated = 2;\nconst block = 3;".to_owned(),
2704 }
2705 }
2706
2707 fn clone_group(instances: Vec<CloneInstance>) -> CloneGroup {
2708 CloneGroup {
2709 instances,
2710 token_count: 12,
2711 line_count: 3,
2712 similarity: None,
2713 }
2714 }
2715
2716 fn fixture_with(extra_graph_file: bool) -> Fixture {
2721 let root = project_root();
2722 let a = root.join("src/a.ts");
2723 let b = root.join("src/b.ts");
2724 let c = root.join("lib/c.ts");
2725 let missing = root.join("src/missing.ts");
2726
2727 let files = vec![
2728 discovered(0, a.clone(), 100),
2729 discovered(1, b.clone(), 50),
2730 discovered(2, c.clone(), 25),
2731 ];
2732
2733 let mut graph_files = files.clone();
2734 let mut imports = vec![import_of(FileId(1), "./b")];
2735 if extra_graph_file {
2736 graph_files.push(discovered(3, root.join("src/d.ts"), 10));
2737 imports.push(import_of(FileId(3), "./d"));
2738 }
2739 let resolved = vec![ResolvedModule {
2740 file_id: FileId(0),
2741 path: a.clone(),
2742 resolved_imports: imports,
2743 ..ResolvedModule::default()
2744 }];
2745 let entry_points = vec![EntryPoint {
2746 path: a.clone(),
2747 source: EntryPointSource::PackageJsonMain,
2748 }];
2749 let graph = crate::module_graph::RetainedModuleGraph::from(ModuleGraph::build(
2750 &resolved,
2751 &entry_points,
2752 &graph_files,
2753 ));
2754
2755 let results = AnalysisResults {
2756 circular_dependencies: vec![
2757 cycle_finding(vec![a.clone(), b]),
2758 cycle_finding(vec![a.clone(), missing.clone()]),
2759 ],
2760 boundary_violations: vec![
2761 violation_finding(a.clone(), c.clone()),
2762 violation_finding(a.clone(), missing),
2763 ],
2764 ..AnalysisResults::default()
2765 };
2766
2767 let duplication = DuplicationReport {
2768 clone_groups: vec![
2769 clone_group(vec![
2770 clone_instance(a.clone(), 1, 3),
2771 clone_instance(c, 10, 12),
2772 ]),
2773 clone_group(vec![
2774 clone_instance(a.clone(), 20, 22),
2775 clone_instance(root.join("outside.ts"), 1, 3),
2776 ]),
2777 clone_group(vec![
2778 clone_instance(a.clone(), 30, 32),
2779 clone_instance(a, 40, 42),
2780 ]),
2781 ],
2782 ..DuplicationReport::default()
2783 };
2784
2785 let workspaces = vec![WorkspaceInfo {
2786 root: root.join("lib"),
2787 name: "shared-lib".to_owned(),
2788 is_internal_dependency: false,
2789 }];
2790
2791 Fixture {
2792 config: resolved_config(&root),
2793 files,
2794 results,
2795 graph,
2796 duplication,
2797 workspaces,
2798 }
2799 }
2800
2801 fn fixture() -> Fixture {
2802 fixture_with(false)
2803 }
2804
2805 #[test]
2806 fn files_and_edges_use_stable_indices() {
2807 let fx = fixture();
2808 let data = build_viz_data(&fx.input());
2809
2810 let paths: Vec<&str> = data.files.iter().map(|f| f.path.as_str()).collect();
2811 assert_eq!(paths, ["src/a.ts", "src/b.ts", "lib/c.ts"]);
2812 assert_eq!(data.edges, vec![[0, 1, 0]]);
2813 assert!(data.files[0].is_entry);
2814 assert!(matches!(data.files[0].status, VizFileStatus::EntryPoint));
2815 assert!(matches!(data.files[1].status, VizFileStatus::Clean));
2816 assert_eq!(data.files[0].import_count, 1);
2817 assert_eq!(data.files[1].importer_count, 1);
2818 assert_eq!(data.files[0].workspace, None);
2819 assert_eq!(data.files[2].workspace, Some(0));
2820 assert_eq!(data.workspaces.len(), 1);
2821 assert_eq!(data.workspaces[0].root, "lib");
2822 }
2823
2824 #[test]
2825 fn edges_to_files_missing_from_input_are_dropped() {
2826 let fx = fixture_with(true);
2827 let data = build_viz_data(&fx.input());
2828
2829 assert_eq!(fx.graph.edge_count(), 2);
2833 assert_eq!(data.edges, vec![[0, 1, 0]]);
2834 }
2835
2836 #[test]
2837 fn clone_groups_drop_unresolvable_and_dedup_per_file() {
2838 let fx = fixture();
2839 let data = build_viz_data(&fx.input());
2840
2841 assert_eq!(data.clones.len(), 2);
2844 assert_eq!(data.clones[0].instances.len(), 2);
2845 assert_eq!(data.clones[0].instances[0].file, 0);
2846 assert_eq!(data.clones[0].instances[1].file, 2);
2847 assert_eq!(data.clones[0].lines, 3);
2848 assert_eq!(data.clones[0].tokens, 12);
2849 assert_eq!(data.files[0].clone_groups, vec![0, 1]);
2851 assert_eq!(data.files[2].clone_groups, vec![0]);
2852 assert_eq!(data.files[0].dup_lines, 9);
2854 assert_eq!(data.files[2].dup_lines, 3);
2855 assert_eq!(data.files[1].dup_lines, 0);
2856 }
2857
2858 #[test]
2859 fn truncate_preview_caps_lines_and_bytes() {
2860 let last_kept = CLONE_PREVIEW_MAX_LINES - 1;
2863 let many_lines = (0..CLONE_PREVIEW_MAX_LINES + 5)
2864 .map(|i| format!("line {i}"))
2865 .collect::<Vec<_>>();
2866 let out = truncate_preview(&many_lines.join("\n"));
2867 assert_eq!(out.matches('\n').count(), CLONE_PREVIEW_MAX_LINES - 1);
2868 assert!(out.contains(&format!("line {last_kept}")));
2869 assert!(!out.contains(&format!("line {CLONE_PREVIEW_MAX_LINES}")));
2870 assert!(out.ends_with('\u{2026}'));
2871
2872 let big = CLONE_PREVIEW_MAX_BYTES * 3 / 4;
2875 let two_long_lines = format!("{}\n{}", "a".repeat(big), "b".repeat(big));
2876 let out = truncate_preview(&two_long_lines);
2877 assert_eq!(out, format!("{}\u{2026}", "a".repeat(big)));
2878
2879 let emoji_line = "\u{1f389}".repeat(CLONE_PREVIEW_MAX_BYTES);
2882 let out = truncate_preview(&emoji_line);
2883 assert_eq!(out, "\u{2026}");
2884 }
2885
2886 #[test]
2887 fn clone_preview_windows_context_around_the_block() {
2888 use std::io::Write as _;
2889
2890 let mut file = tempfile::NamedTempFile::new().expect("temp file");
2892 let body = (1..=20)
2893 .map(|i| format!("line {i}"))
2894 .collect::<Vec<_>>()
2895 .join("\n");
2896 file.write_all(body.as_bytes()).expect("write source");
2897 let inst = clone_instance(file.path().to_path_buf(), 8, 11);
2898
2899 let (preview, highlight_start, highlight_lines) = build_clone_preview(&inst);
2900 let preview_lines: Vec<&str> = preview.lines().collect();
2901
2902 assert_eq!(preview_lines.len(), 12);
2905 assert_eq!(highlight_start, 4);
2906 assert_eq!(highlight_lines, 4);
2907 assert_eq!(preview_lines.first(), Some(&"line 4"));
2908 let start = highlight_start as usize;
2909 let end = start + highlight_lines as usize;
2910 assert_eq!(
2911 &preview_lines[start..end],
2912 ["line 8", "line 9", "line 10", "line 11"],
2913 );
2914 assert_eq!(preview_lines[start - 1], "line 7");
2916 }
2917
2918 #[test]
2919 fn clone_preview_keeps_leading_context_when_the_block_fills_the_cap() {
2920 use std::io::Write as _;
2921
2922 let mut file = tempfile::NamedTempFile::new().expect("temp file");
2926 let body = (1..=200)
2927 .map(|i| format!("line {i}"))
2928 .collect::<Vec<_>>()
2929 .join("\n");
2930 file.write_all(body.as_bytes()).expect("write source");
2931 let inst = clone_instance(file.path().to_path_buf(), 50, 150);
2932
2933 let (preview, highlight_start, highlight_lines) = build_clone_preview(&inst);
2934 let preview_lines: Vec<&str> = preview.lines().collect();
2935
2936 assert_eq!(highlight_start, CLONE_PREVIEW_CONTEXT as u32);
2937 assert!(
2938 highlight_start > 0,
2939 "leading context must survive a huge block"
2940 );
2941 assert_eq!(preview_lines.len(), CLONE_PREVIEW_MAX_LINES);
2942 assert_eq!(
2943 highlight_lines as usize,
2944 CLONE_PREVIEW_MAX_LINES - CLONE_PREVIEW_CONTEXT,
2945 );
2946 assert_eq!(preview_lines[highlight_start as usize - 1], "line 49");
2947 assert_eq!(preview_lines[highlight_start as usize], "line 50");
2948 }
2949
2950 #[test]
2951 fn clone_preview_clamps_context_at_file_start() {
2952 use std::io::Write as _;
2953
2954 let mut file = tempfile::NamedTempFile::new().expect("temp file");
2955 file.write_all(b"line 1\nline 2\nline 3\nline 4\nline 5")
2956 .expect("write source");
2957 let inst = clone_instance(file.path().to_path_buf(), 1, 2);
2960
2961 let (preview, highlight_start, highlight_lines) = build_clone_preview(&inst);
2962 assert_eq!(highlight_start, 0);
2963 assert_eq!(highlight_lines, 2);
2964 assert_eq!(preview, "line 1\nline 2\nline 3\nline 4\nline 5");
2965 }
2966
2967 #[test]
2968 fn clone_preview_falls_back_when_source_is_unreadable() {
2969 let inst = clone_instance(project_root().join("does-not-exist.ts"), 1, 3);
2972 let (preview, highlight_start, highlight_lines) = build_clone_preview(&inst);
2973 assert_eq!(preview, inst.fragment);
2974 assert_eq!(highlight_start, 0);
2975 assert_eq!(highlight_lines as usize, preview.lines().count());
2976 }
2977
2978 #[test]
2979 fn cycles_drop_when_any_member_unresolved() {
2980 let fx = fixture();
2981 let data = build_viz_data(&fx.input());
2982
2983 assert_eq!(data.cycles, vec![vec![0, 1]]);
2986 assert!(data.files[0].in_cycle);
2987 assert!(data.files[1].in_cycle);
2988 assert!(!data.files[2].in_cycle);
2989 assert_eq!(data.summary.circular_deps, data.cycles.len());
2992 }
2993
2994 #[test]
2995 fn violations_resolve_zone_and_file_indices() {
2996 let fx = fixture();
2997 let data = build_viz_data(&fx.input());
2998
2999 assert_eq!(data.zones.len(), 2);
3000 assert_eq!(data.zones[0].name, "app");
3001 assert_eq!(data.zones[0].files, 2);
3002 assert_eq!(data.zones[1].name, "shared");
3003 assert_eq!(data.zones[1].files, 1);
3004 assert_eq!(data.files[0].zone, Some(0));
3005 assert_eq!(data.files[1].zone, Some(0));
3006 assert_eq!(data.files[2].zone, Some(1));
3007
3008 assert_eq!(data.violations.len(), 1);
3010 let v = &data.violations[0];
3011 assert_eq!((v.from, v.to), (0, 2));
3012 assert_eq!((v.from_zone, v.to_zone), (0, 1));
3013 assert_eq!(v.line, 2);
3014 assert_eq!(v.specifier, "../lib/c");
3015 }
3016
3017 #[test]
3018 fn clone_group_cap_counts_truncated_groups() {
3019 let fx = fixture();
3020 let index = FileIndex::new(&fx.files);
3021
3022 let (clones, groups_by_file, _dup_lines, truncated) =
3027 build_clones(&fx.duplication, &index, 1);
3028 assert_eq!(clones.len(), 1);
3029 assert_eq!(truncated, 1);
3030 assert!(
3031 groups_by_file
3032 .values()
3033 .all(|ids| ids.iter().all(|&id| (id as usize) < clones.len()))
3034 );
3035
3036 let data = build_viz_data(&fx.input());
3038 assert_eq!(data.clones.len(), 2);
3039 assert_eq!(data.summary.clone_groups_truncated, None);
3040 }
3041
3042 #[test]
3043 fn summary_flags_clone_truncation_only_when_nonzero() {
3044 let fx = fixture();
3045 let data = build_viz_data(&fx.input());
3046
3047 let summary = build_summary(&fx.input(), &data.files, &data.clones, &[], &[], 3);
3048 assert_eq!(summary.clone_groups_truncated, Some(3));
3049 let summary = build_summary(&fx.input(), &data.files, &data.clones, &[], &[], 0);
3050 assert_eq!(summary.clone_groups_truncated, None);
3051 }
3052
3053 #[test]
3054 fn summary_counts_match_rendered_arrays() {
3055 let fx = fixture();
3056 let data = build_viz_data(&fx.input());
3057 let s = &data.summary;
3058
3059 assert_eq!(s.total_files, data.files.len());
3060 assert_eq!(s.total_size, 175);
3061 assert_eq!(s.total_edges, data.edges.len());
3062 assert_eq!(s.clone_groups, data.clones.len());
3063 assert_eq!(s.duplicated_lines, 12);
3064 assert_eq!(s.hotspot_files, 0);
3065 assert_eq!(s.unused_files, 0);
3066 assert_eq!(s.unused_exports, 0);
3067 assert_eq!(s.circular_deps, data.cycles.len());
3070 assert_eq!(s.circular_deps, 1);
3071 assert_eq!(s.boundary_violations, data.violations.len());
3072 assert_eq!(s.boundary_violations, 1);
3073 }
3074
3075 #[test]
3076 fn payload_keeps_counts_and_availability_explicit() {
3077 let fx = fixture();
3078 let data = build_viz_data(&fx.input());
3079 let value = serde_json::to_value(&data).expect("viz data serializes");
3080
3081 assert_eq!(value["architecture"]["availability"]["unit"], "violations");
3082 assert_eq!(value["dependencies"]["availability"]["unit"], "findings");
3083 assert_eq!(value["security"]["availability"]["unit"], "candidates");
3084 assert_eq!(value["security"]["availability"]["state"], "complete");
3085 assert_eq!(
3086 value["security"]["runtime_availability"]["state"],
3087 "unavailable"
3088 );
3089 assert_eq!(value["health"]["availability"]["state"], "unavailable");
3090 assert_eq!(
3091 value["health"]["capabilities"]["coverage"]["state"],
3092 "unavailable"
3093 );
3094 assert!(value["frameworks"]["detectors"].is_array());
3095 assert_eq!(
3096 value["frameworks"]["detector_availability"]["state"],
3097 "unavailable"
3098 );
3099 assert!(value["styling"].get("score").is_none());
3100 }
3101
3102 #[test]
3106 fn health_reports_runtime_evidence_as_unavailable_without_a_runtime_input() {
3107 let fx = fixture();
3108 let mut data = build_viz_data(&fx.input());
3109 apply_health_report(&mut data, &HealthReport::default(), Path::new("/project"));
3110 let value = serde_json::to_value(&data).expect("viz data serializes");
3111
3112 assert_eq!(value["health"]["availability"]["state"], "complete");
3113 let runtime = &value["health"]["capabilities"]["runtime"];
3114 assert_eq!(runtime["state"], "unavailable");
3115 assert_eq!(runtime["unit"], "observations");
3116 assert_eq!(runtime["reason"], NO_RUNTIME_COVERAGE_REASON);
3117 assert_eq!(runtime["count"], 0);
3118 assert_eq!(
3119 value["security"]["runtime_availability"]["reason"],
3120 NO_RUNTIME_COVERAGE_REASON
3121 );
3122 }
3123
3124 #[test]
3128 fn rooted_paths_without_a_drive_are_redacted() {
3129 let root = Path::new("/project");
3130 assert_eq!(
3131 relative_path(Path::new("/Users/private/secret.ts"), root),
3132 "<external>/secret.ts"
3133 );
3134 assert_eq!(
3135 relative_path(Path::new("/etc/passwd"), root),
3136 "<external>/passwd"
3137 );
3138 assert_eq!(relative_path(Path::new("src/a.ts"), root), "src/a.ts");
3140
3141 let mut detail = serde_json::json!({ "path": "/Users/private/secret.ts" });
3143 relativize_value_paths(&mut detail, root);
3144 assert_eq!(detail["path"], "<external>/secret.ts");
3145
3146 let mut route = serde_json::json!({ "specifier": "/api/v1" });
3149 relativize_value_paths(&mut route, root);
3150 assert_eq!(route["specifier"], "/api/v1");
3151 }
3152
3153 #[test]
3154 fn external_absolute_paths_are_redacted() {
3155 let root = Path::new("/project");
3156 assert_eq!(
3157 relative_path(Path::new("/project/src/a.ts"), root),
3158 "src/a.ts"
3159 );
3160 assert_eq!(
3161 relative_path(Path::new("/Users/private/secret.ts"), root),
3162 "<external>/secret.ts"
3163 );
3164
3165 let mut detail = serde_json::json!({ "path": "/Users/private/secret.ts" });
3166 relativize_value_paths(&mut detail, root);
3167 assert_eq!(detail["path"], "<external>/secret.ts");
3168
3169 let mut route = serde_json::json!({ "specifier": "/api/v1" });
3170 relativize_value_paths(&mut route, root);
3171 assert_eq!(route["specifier"], "/api/v1");
3172
3173 let mut conflicts = serde_json::json!({
3174 "conflicting_paths": ["/project/app/a.ts", "/project/app/b.ts"]
3175 });
3176 relativize_value_paths(&mut conflicts, root);
3177 assert_eq!(conflicts["conflicting_paths"][0], "app/a.ts");
3178 assert_eq!(conflicts["conflicting_paths"][1], "app/b.ts");
3179 }
3180
3181 #[test]
3182 fn config_action_values_are_not_rendered_as_commands() {
3183 let finding = finding_from_value(
3184 "dependency",
3185 "Dependency finding",
3186 serde_json::json!({
3187 "actions": [{
3188 "kind": "add-to-config",
3189 "auto_fixable": false,
3190 "config_key": "entry",
3191 "value": "./errors",
3192 "description": "Add the entry to configuration"
3193 }]
3194 }),
3195 Path::new("/project"),
3196 &|_| None,
3197 );
3198 assert_eq!(finding.actions.len(), 1);
3199 let action = &finding.actions[0];
3200 assert_eq!(action.kind.as_deref(), Some("add-to-config"));
3201 assert!(!action.auto_fixable);
3202 assert_eq!(action.config_key.as_deref(), Some("entry"));
3203 assert_eq!(action.value, Some(Value::String("./errors".to_string())));
3204 assert!(action.command.is_none());
3205 }
3206}