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
27#[path = "viz_files.rs"]
28mod files;
29#[path = "viz_framework_findings.rs"]
30mod framework_findings;
31use files::build_files;
32use framework_findings::build_framework_findings;
33
34const HOTSPOT_CYCLOMATIC_FLOOR: u16 = 10;
36const CLONE_PREVIEW_MAX_BYTES: usize = 2000;
40const CLONE_PREVIEW_MAX_LINES: usize = 32;
44const CLONE_PREVIEW_CONTEXT: usize = 4;
49const MAX_CLONE_GROUPS: usize = 500;
53const MAX_ANALYSIS_FINDINGS: usize = 1000;
55const MAX_SECURITY_BLIND_SPOT_SAMPLES: usize = 100;
57const MAX_HEALTH_FILES: usize = 2000;
59const EDGE_FLAG_TYPE_ONLY: u32 = 1;
61const EDGE_FLAG_DYNAMIC: u32 = 2;
65const NO_RUNTIME_COVERAGE_REASON: &str = "No runtime coverage input was provided";
69
70pub struct VizBuildInput<'a> {
72 pub results: &'a AnalysisResults,
74 pub graph: &'a RetainedModuleGraph,
76 pub modules: Option<&'a [ModuleInfo]>,
78 pub files: &'a [DiscoveredFile],
80 pub duplication: &'a DuplicationReport,
82 pub workspaces: &'a [WorkspaceInfo],
84 pub config: &'a ResolvedConfig,
86 pub feature_flags: &'a [FeatureFlag],
88 pub include_analysis_details: bool,
90}
91
92#[derive(Serialize)]
94pub struct VizData {
95 pub root: String,
97 pub files: Vec<VizFile>,
99 pub edges: Vec<[u32; 3]>,
104 pub summary: VizSummary,
106 pub workspaces: Vec<VizWorkspace>,
108 pub zones: Vec<VizZone>,
110 pub cycles: Vec<Vec<u32>>,
112 pub clones: Vec<VizCloneGroup>,
114 pub violations: Vec<VizViolation>,
116 pub architecture: VizFindingAnalysis,
118 pub dependencies: VizFindingAnalysis,
120 pub health: VizHealthData,
122 pub security: VizSecurityData,
124 pub frameworks: VizFrameworkData,
126 pub styling: VizStylingData,
128 pub feature_flags: VizFindingAnalysis,
130}
131
132#[derive(Serialize, Clone, Copy, PartialEq, Eq)]
134#[serde(rename_all = "camelCase")]
135pub enum VizAvailabilityState {
136 Complete,
138 Disabled,
140 NotApplicable,
142 Unavailable,
144}
145
146#[derive(Serialize)]
153pub struct VizAvailability {
154 pub state: VizAvailabilityState,
156 pub count: usize,
158 pub unit: &'static str,
160 #[serde(skip_serializing_if = "Option::is_none")]
162 pub reason: Option<String>,
163 #[serde(skip_serializing_if = "Option::is_none")]
166 pub truncated: Option<usize>,
167}
168
169impl VizAvailability {
170 const fn complete(count: usize, unit: &'static str, truncated: Option<usize>) -> Self {
171 Self {
172 state: VizAvailabilityState::Complete,
173 count,
174 unit,
175 reason: None,
176 truncated,
177 }
178 }
179
180 fn unavailable(unit: &'static str, reason: impl Into<String>) -> Self {
181 Self {
182 state: VizAvailabilityState::Unavailable,
183 count: 0,
184 unit,
185 reason: Some(reason.into()),
186 truncated: None,
187 }
188 }
189
190 fn disabled(unit: &'static str, reason: impl Into<String>) -> Self {
191 Self {
192 state: VizAvailabilityState::Disabled,
193 count: 0,
194 unit,
195 reason: Some(reason.into()),
196 truncated: None,
197 }
198 }
199}
200
201#[derive(Serialize)]
203pub struct VizFinding {
204 kind: String,
205 title: String,
206 #[serde(skip_serializing_if = "Option::is_none")]
207 file: Option<u32>,
208 #[serde(skip_serializing_if = "Option::is_none")]
209 path: Option<String>,
210 #[serde(skip_serializing_if = "Option::is_none")]
211 line: Option<u32>,
212 #[serde(skip_serializing_if = "Vec::is_empty")]
213 files: Vec<u32>,
214 #[serde(skip_serializing_if = "Vec::is_empty")]
215 paths: Vec<String>,
216 #[serde(skip_serializing_if = "Option::is_none")]
217 description: Option<String>,
218 #[serde(skip_serializing_if = "Option::is_none")]
219 severity: Option<String>,
220 #[serde(skip_serializing_if = "Vec::is_empty")]
221 facts: Vec<VizFindingFact>,
222 actions: Vec<VizFindingAction>,
223}
224
225#[derive(Serialize)]
227pub struct VizFindingFact {
228 label: String,
229 value: String,
230}
231
232#[derive(Serialize)]
234pub struct VizFindingAction {
235 label: String,
236 #[serde(skip_serializing_if = "Option::is_none")]
237 kind: Option<String>,
238 auto_fixable: bool,
239 #[serde(skip_serializing_if = "Option::is_none")]
240 command: Option<String>,
241 #[serde(skip_serializing_if = "Option::is_none")]
242 comment: Option<String>,
243 #[serde(skip_serializing_if = "Option::is_none")]
244 config_key: Option<String>,
245 #[serde(skip_serializing_if = "Option::is_none")]
246 value: Option<Value>,
247 #[serde(skip_serializing_if = "Option::is_none")]
248 description: Option<String>,
249}
250
251#[derive(Serialize)]
253pub struct VizFindingAnalysis {
254 pub availability: VizAvailability,
256 #[serde(skip_serializing_if = "Option::is_none")]
258 pub findings_truncated: Option<usize>,
259 pub findings: Vec<VizFinding>,
261}
262
263#[derive(Serialize)]
265pub struct VizFrameworkData {
266 pub availability: VizAvailability,
268 pub detector_availability: VizAvailability,
271 #[serde(skip_serializing_if = "Option::is_none")]
273 pub findings_truncated: Option<usize>,
274 pub findings: Vec<VizFinding>,
276 pub detected_frameworks: Vec<String>,
278 pub detectors: Vec<VizFrameworkDetector>,
281}
282
283#[derive(Serialize)]
285pub struct VizFrameworkDetector {
286 id: String,
287 framework: String,
288 status: String,
289 #[serde(skip_serializing_if = "Option::is_none")]
290 reason: Option<String>,
291}
292
293#[derive(Serialize)]
295pub struct VizHealthCapabilities {
296 pub complexity: VizAvailability,
298 pub maintainability: VizAvailability,
300 pub crap: VizAvailability,
302 pub coverage: VizAvailability,
304 pub runtime: VizAvailability,
306 pub churn: VizAvailability,
308 pub hotspots: VizAvailability,
310 pub ownership: VizAvailability,
312}
313
314#[derive(Serialize)]
316pub struct VizHealthFile {
317 file: u32,
318 path: String,
319 maintainability_index: f64,
320 crap_max: f64,
321 complexity_density: f64,
322 fan_in: usize,
323 fan_out: usize,
324 #[serde(skip_serializing_if = "Option::is_none")]
325 hotspot_score: Option<f64>,
326 #[serde(skip_serializing_if = "Option::is_none")]
327 commits: Option<u32>,
328 #[serde(skip_serializing_if = "Option::is_none")]
329 ownership: Option<Value>,
330}
331
332#[derive(Serialize)]
334pub struct VizHealthData {
335 pub availability: VizAvailability,
337 pub capabilities: VizHealthCapabilities,
339 #[serde(skip_serializing_if = "Option::is_none")]
341 pub shared_parse: Option<bool>,
342 #[serde(skip_serializing_if = "Option::is_none")]
344 pub score: Option<f64>,
345 #[serde(skip_serializing_if = "Option::is_none")]
347 pub grade: Option<String>,
348 #[serde(skip_serializing_if = "Option::is_none")]
350 pub average_maintainability: Option<f64>,
351 pub files: Vec<VizHealthFile>,
353 #[serde(skip_serializing_if = "Option::is_none")]
355 pub files_truncated: Option<usize>,
356 #[serde(skip_serializing_if = "Option::is_none")]
358 pub findings_truncated: Option<usize>,
359 pub findings: Vec<VizFinding>,
361}
362
363#[derive(Serialize)]
365pub struct VizStylingData {
366 pub availability: VizAvailability,
368 #[serde(skip_serializing_if = "Option::is_none")]
370 pub findings_truncated: Option<usize>,
371 pub findings: Vec<VizFinding>,
373 #[serde(skip_serializing_if = "Option::is_none")]
375 pub score: Option<f64>,
376 #[serde(skip_serializing_if = "Option::is_none")]
378 pub grade: Option<String>,
379 #[serde(skip_serializing_if = "Option::is_none")]
381 pub confidence: Option<String>,
382 #[serde(skip_serializing_if = "Option::is_none")]
384 pub summary: Option<Value>,
385}
386
387#[derive(Serialize)]
389pub struct VizSecurityTraceHop {
390 #[serde(skip_serializing_if = "Option::is_none")]
391 file: Option<u32>,
392 path: String,
393 line: u32,
394 col: u32,
395 role: String,
396}
397
398#[derive(Serialize)]
400pub struct VizSecurityEndpoint {
401 #[serde(skip_serializing_if = "Option::is_none")]
402 file: Option<u32>,
403 path: String,
404 line: u32,
405 col: u32,
406}
407
408#[derive(Serialize)]
410pub struct VizSecurityTaintFlow {
411 source: VizSecurityEndpoint,
412 sink: VizSecurityEndpoint,
413 intra_module: bool,
414 cross_module_hops: u32,
415}
416
417#[derive(Serialize)]
420pub struct VizSecurityCandidate {
421 id: String,
422 kind: String,
423 #[serde(skip_serializing_if = "Option::is_none")]
424 category: Option<String>,
425 #[serde(skip_serializing_if = "Option::is_none")]
426 cwe: Option<u32>,
427 #[serde(skip_serializing_if = "Option::is_none")]
428 file: Option<u32>,
429 path: String,
430 line: u32,
431 col: u32,
432 evidence: String,
433 severity: String,
434 #[serde(skip_serializing_if = "Option::is_none")]
435 taint_confidence: Option<String>,
436 #[serde(skip_serializing_if = "Option::is_none")]
437 source_kind: Option<String>,
438 #[serde(skip_serializing_if = "Option::is_none")]
439 sink: Option<String>,
440 #[serde(skip_serializing_if = "Option::is_none")]
441 url_shape: Option<String>,
442 #[serde(skip_serializing_if = "Option::is_none")]
443 network_destination: Option<String>,
444 #[serde(skip_serializing_if = "Option::is_none")]
445 reachable_from_entry: Option<bool>,
446 #[serde(skip_serializing_if = "Option::is_none")]
447 reachable_from_untrusted_source: Option<bool>,
448 #[serde(skip_serializing_if = "Option::is_none")]
449 blast_radius: Option<u32>,
450 crosses_boundary: bool,
451 client_server_boundary: bool,
452 cross_module_boundary: bool,
453 #[serde(skip_serializing_if = "Option::is_none")]
454 architecture_zone: Option<String>,
455 #[serde(skip_serializing_if = "Option::is_none")]
456 dead_code: Option<Value>,
457 #[serde(skip_serializing_if = "Option::is_none")]
458 runtime: Option<Value>,
459 #[serde(skip_serializing_if = "Option::is_none")]
460 taint_flow: Option<VizSecurityTaintFlow>,
461 #[serde(skip_serializing_if = "Vec::is_empty")]
462 observed_controls: Vec<Value>,
463 #[serde(skip_serializing_if = "Option::is_none")]
464 control_verification_prompt: Option<String>,
465 trace: Vec<VizSecurityTraceHop>,
466 #[serde(skip_serializing_if = "Vec::is_empty")]
467 taint_trace: Vec<VizSecurityTraceHop>,
468 actions: Value,
469}
470
471#[derive(Serialize)]
473pub struct VizSecurityBlindSpot {
474 kind: String,
475 count: usize,
476 #[serde(skip_serializing_if = "Option::is_none")]
477 path: Option<String>,
478 #[serde(skip_serializing_if = "Option::is_none")]
479 file: Option<u32>,
480 #[serde(skip_serializing_if = "Option::is_none")]
481 line: Option<u32>,
482 #[serde(skip_serializing_if = "Option::is_none")]
483 reason: Option<String>,
484}
485
486#[derive(Serialize)]
489pub struct VizSecurityData {
490 pub availability: VizAvailability,
493 pub runtime_availability: VizAvailability,
496 pub candidates: Vec<VizSecurityCandidate>,
498 pub blind_spot_count: usize,
500 #[serde(skip_serializing_if = "Option::is_none")]
502 pub blind_spots_truncated: Option<usize>,
503 pub blind_spots: Vec<VizSecurityBlindSpot>,
505}
506
507#[derive(Serialize)]
509pub struct VizFile {
510 pub path: String,
512 pub size: u64,
514 pub status: VizFileStatus,
516 pub export_count: u16,
518 pub unused_export_count: u16,
520 pub is_entry: bool,
522 pub importer_count: u16,
524 pub import_count: u16,
526 #[serde(skip_serializing_if = "Option::is_none")]
528 pub workspace: Option<u16>,
529 #[serde(skip_serializing_if = "Option::is_none")]
531 pub zone: Option<u16>,
532 #[serde(skip_serializing_if = "Vec::is_empty")]
534 pub unused_exports: Vec<String>,
535 pub fn_count: u16,
537 pub max_cyclomatic: u16,
539 pub max_cognitive: u16,
541 pub react_hooks: u16,
543 pub jsx_depth: u16,
545 #[serde(skip_serializing_if = "Vec::is_empty")]
547 pub functions: Vec<VizFunction>,
548 pub dup_lines: u32,
550 #[serde(skip_serializing_if = "Vec::is_empty")]
552 pub clone_groups: Vec<u32>,
553 pub in_cycle: bool,
555}
556
557#[derive(Serialize, Clone, Copy, PartialEq, Eq)]
559#[serde(rename_all = "camelCase")]
560pub enum VizFileStatus {
561 Clean,
563 HasUnusedExports,
565 Unused,
567 EntryPoint,
569}
570
571#[derive(Serialize)]
573pub struct VizFunction {
574 name: String,
576 line: u32,
578 cyclomatic: u16,
580 cognitive: u16,
582 lines: u32,
584 hooks: u16,
586 jsx_depth: u16,
588 props: u16,
590}
591
592#[derive(Serialize)]
594pub struct VizSummary {
595 pub total_files: usize,
597 pub total_size: u64,
599 pub total_edges: usize,
601 pub unused_files: usize,
603 pub unused_exports: usize,
605 pub unused_types: usize,
607 pub unused_deps: usize,
609 pub unresolved_imports: usize,
611 pub circular_deps: usize,
613 pub clone_groups: usize,
615 pub duplicated_lines: usize,
617 pub boundary_violations: usize,
619 pub hotspot_files: usize,
621 #[serde(skip_serializing_if = "Option::is_none")]
624 pub clone_groups_truncated: Option<u32>,
625}
626
627#[derive(Serialize)]
629pub struct VizWorkspace {
630 name: String,
632 root: String,
634}
635
636#[derive(Serialize)]
638pub struct VizZone {
639 name: String,
641 files: u32,
643}
644
645#[derive(Serialize)]
647pub struct VizCloneGroup {
648 lines: usize,
650 tokens: usize,
652 instances: Vec<VizCloneInstance>,
654 preview: String,
658 highlight_start: u32,
661 highlight_lines: u32,
665}
666
667#[derive(Serialize)]
669pub struct VizCloneInstance {
670 file: u32,
672 start_line: u32,
674 end_line: u32,
676}
677
678#[derive(Serialize)]
680pub struct VizViolation {
681 from: u32,
683 to: u32,
685 from_zone: u16,
687 to_zone: u16,
689 line: u32,
691 specifier: String,
693}
694
695#[must_use]
697pub fn build_viz_data(input: &VizBuildInput<'_>) -> VizData {
698 let root = &input.config.root;
699 let index = FileIndex::new(input.files);
700 let workspaces = build_workspaces(input.workspaces, root);
701 let (zones, zone_by_file) = classify_zones(input, &index);
702 let (clones, clone_groups_by_file, dup_lines_by_file, clone_groups_truncated) =
703 build_clones(input.duplication, &index, MAX_CLONE_GROUPS);
704 let cycles = build_cycles(input.results, &index);
705 let violations = build_violations(input.results, &zones, &index);
706 let (architecture, dependencies, security, frameworks, feature_flags) =
707 if input.include_analysis_details {
708 (
709 build_architecture(input.results, &index, root),
710 build_dependencies(input.results, &index, root),
711 build_security(input.results, &index, root),
712 build_frameworks(input.results, &index, root),
713 build_feature_flags(input.feature_flags, &index, root),
714 )
715 } else {
716 skipped_analysis_details()
717 };
718
719 let files = build_files(
720 input,
721 &index,
722 &FilePropertyMaps {
723 zone_by_file: &zone_by_file,
724 clone_groups_by_file: &clone_groups_by_file,
725 dup_lines_by_file: &dup_lines_by_file,
726 cycles: &cycles,
727 },
728 );
729
730 let summary = build_summary(
731 input,
732 &files,
733 &clones,
734 &cycles,
735 &violations,
736 clone_groups_truncated,
737 );
738
739 VizData {
740 root: display_root(root),
741 files,
742 edges: build_edges(input.graph, &index),
743 summary,
744 workspaces,
745 zones,
746 cycles,
747 clones,
748 violations,
749 architecture,
750 dependencies,
751 health: VizHealthData {
752 availability: VizAvailability::unavailable("files", "Health analysis did not complete"),
753 capabilities: unavailable_health_capabilities("Health analysis did not complete"),
754 shared_parse: None,
755 score: None,
756 grade: None,
757 average_maintainability: None,
758 files: Vec::new(),
759 files_truncated: None,
760 findings_truncated: None,
761 findings: Vec::new(),
762 },
763 security,
764 frameworks,
765 styling: VizStylingData {
766 availability: VizAvailability::unavailable(
767 "findings",
768 "Styling analysis did not complete",
769 ),
770 findings_truncated: None,
771 findings: Vec::new(),
772 score: None,
773 grade: None,
774 confidence: None,
775 summary: None,
776 },
777 feature_flags,
778 }
779}
780
781fn skipped_analysis_details() -> (
782 VizFindingAnalysis,
783 VizFindingAnalysis,
784 VizSecurityData,
785 VizFrameworkData,
786 VizFindingAnalysis,
787) {
788 let skipped = |unit| VizFindingAnalysis {
789 availability: VizAvailability::disabled(unit, "Not needed for this Viz output format"),
790 findings_truncated: None,
791 findings: Vec::new(),
792 };
793 (
794 skipped("violations"),
795 skipped("findings"),
796 VizSecurityData {
797 availability: VizAvailability::disabled(
798 "candidates",
799 "Not needed for this Viz output format",
800 ),
801 runtime_availability: VizAvailability::disabled(
802 "observations",
803 "Not needed for this Viz output format",
804 ),
805 candidates: Vec::new(),
806 blind_spot_count: 0,
807 blind_spots_truncated: None,
808 blind_spots: Vec::new(),
809 },
810 VizFrameworkData {
811 availability: VizAvailability::disabled(
812 "findings",
813 "Not needed for this Viz output format",
814 ),
815 detector_availability: VizAvailability::disabled(
816 "detectors",
817 "Not needed for this Viz output format",
818 ),
819 findings_truncated: None,
820 findings: Vec::new(),
821 detected_frameworks: Vec::new(),
822 detectors: Vec::new(),
823 },
824 skipped("flags"),
825 )
826}
827
828struct FileIndex<'a> {
830 ordered: Vec<&'a DiscoveredFile>,
831 by_path: FxHashMap<&'a Path, u32>,
832 by_file_id: FxHashMap<u32, u32>,
833}
834
835impl<'a> FileIndex<'a> {
836 fn new(files: &'a [DiscoveredFile]) -> Self {
837 let mut ordered: Vec<&DiscoveredFile> = files.iter().collect();
838 ordered.sort_by_key(|f| f.id.0);
839 let mut by_path = FxHashMap::default();
840 let mut by_file_id = FxHashMap::default();
841 for (i, f) in ordered.iter().enumerate() {
842 let idx = clamp_u32(i);
843 by_path.insert(f.path.as_path(), idx);
844 by_file_id.insert(f.id.0, idx);
845 }
846 Self {
847 ordered,
848 by_path,
849 by_file_id,
850 }
851 }
852
853 fn index_of_path(&self, path: &Path) -> Option<u32> {
854 self.by_path.get(path).copied()
855 }
856
857 fn index_of_file_id(&self, file_id: u32) -> Option<u32> {
858 self.by_file_id.get(&file_id).copied()
859 }
860}
861
862fn analysis_from_records(
863 mut findings: Vec<VizFinding>,
864 total_findings: usize,
865 primary_count: usize,
866 unit: &'static str,
867) -> VizFindingAnalysis {
868 let findings_truncated = (total_findings > MAX_ANALYSIS_FINDINGS)
869 .then_some(total_findings.saturating_sub(MAX_ANALYSIS_FINDINGS));
870 let primary_truncated = (primary_count > MAX_ANALYSIS_FINDINGS)
871 .then_some(primary_count.saturating_sub(MAX_ANALYSIS_FINDINGS));
872 findings.truncate(MAX_ANALYSIS_FINDINGS);
873 VizFindingAnalysis {
874 availability: VizAvailability::complete(primary_count, unit, primary_truncated),
875 findings_truncated,
876 findings,
877 }
878}
879
880fn push_findings<T: Serialize>(
881 out: &mut Vec<VizFinding>,
882 kind: &str,
883 title: &str,
884 values: &[T],
885 root: &Path,
886 index: &FileIndex<'_>,
887) {
888 let remaining = MAX_ANALYSIS_FINDINGS.saturating_sub(out.len());
889 out.extend(values.iter().take(remaining).filter_map(|value| {
890 serde_json::to_value(value).ok().map(|detail| {
891 finding_from_value(kind, title, detail, root, &|path| index.index_of_path(path))
892 })
893 }));
894}
895
896fn finding_from_value(
897 kind: &str,
898 title: &str,
899 mut detail: Value,
900 root: &Path,
901 resolve_file: &dyn Fn(&Path) -> Option<u32>,
902) -> VizFinding {
903 let raw_path = find_string_key(&detail, &["path", "from_path", "consumer_path", "file"])
904 .map(str::to_owned);
905 let mut raw_paths = Vec::new();
906 collect_path_values(&detail, &mut raw_paths);
907 let mut paths = Vec::new();
908 let mut files = Vec::new();
909 for raw in raw_paths {
910 let raw_path = Path::new(&raw);
911 let absolute_path = if raw_path.has_root() {
915 raw_path.to_path_buf()
916 } else {
917 root.join(raw_path)
918 };
919 let display = relative_path(&absolute_path, root);
920 if !paths.contains(&display) {
921 paths.push(display);
922 }
923 if let Some(file) = resolve_file(&absolute_path)
924 && !files.contains(&file)
925 {
926 files.push(file);
927 }
928 }
929 let absolute = raw_path.as_deref().map(Path::new).map(|path| {
930 if path.has_root() {
931 path.to_path_buf()
932 } else {
933 root.join(path)
934 }
935 });
936 let file = absolute.as_deref().and_then(resolve_file);
937 let path = absolute.as_deref().map(|path| relative_path(path, root));
938 let line = find_u64_key(&detail, &["line", "start_line"])
939 .map(|value| u32::try_from(value).unwrap_or(u32::MAX));
940 relativize_value_paths(&mut detail, root);
941 let description =
942 find_string_key(&detail, &["message", "evidence", "reason"]).map(str::to_owned);
943 let severity = find_string_key(&detail, &["severity"]).map(str::to_owned);
944 let facts = finding_facts(&detail);
945 let actions = finding_actions(&detail);
946 VizFinding {
947 kind: kind.to_string(),
948 title: title.to_string(),
949 file,
950 path,
951 line,
952 files,
953 paths,
954 description,
955 severity,
956 facts,
957 actions,
958 }
959}
960
961fn finding_facts(detail: &Value) -> Vec<VizFindingFact> {
962 const EXCLUDED: &[&str] = &[
963 "path",
964 "from_path",
965 "to_path",
966 "consumer_path",
967 "file",
968 "files",
969 "paths",
970 "line",
971 "start_line",
972 "message",
973 "evidence",
974 "reason",
975 "severity",
976 "actions",
977 ];
978 let Some(fields) = detail.as_object() else {
979 return Vec::new();
980 };
981 fields
982 .iter()
983 .filter(|(label, _)| !EXCLUDED.contains(&label.as_str()))
984 .filter_map(|(label, value)| {
985 scalar_fact_value(value).map(|value| VizFindingFact {
986 label: label.clone(),
987 value,
988 })
989 })
990 .take(12)
991 .collect()
992}
993
994fn scalar_fact_value(value: &Value) -> Option<String> {
995 match value {
996 Value::String(value) => Some(value.clone()),
997 Value::Number(value) => Some(value.to_string()),
998 Value::Bool(value) => Some(value.to_string()),
999 Value::Array(values) if values.iter().all(Value::is_string) => Some(
1000 values
1001 .iter()
1002 .filter_map(Value::as_str)
1003 .collect::<Vec<_>>()
1004 .join(", "),
1005 ),
1006 Value::Null | Value::Array(_) | Value::Object(_) => None,
1007 }
1008}
1009
1010fn finding_actions(detail: &Value) -> Vec<VizFindingAction> {
1011 let mut actions = Vec::new();
1012 if let Some(record) = detail.as_object() {
1013 for key in ["verify_command", "trace_command", "command"] {
1014 if let Some(command) = record.get(key).and_then(Value::as_str) {
1015 actions.push(VizFindingAction {
1016 label: "Verify".to_string(),
1017 kind: None,
1018 auto_fixable: false,
1019 command: Some(command.to_string()),
1020 comment: None,
1021 config_key: None,
1022 value: None,
1023 description: None,
1024 });
1025 }
1026 }
1027 if let Some(value) = record.get("actions") {
1028 append_projected_actions(&mut actions, value);
1029 }
1030 }
1031 actions
1032}
1033
1034fn append_projected_actions(actions: &mut Vec<VizFindingAction>, value: &Value) {
1035 match value {
1036 Value::Array(values) => {
1037 for value in values {
1038 if let Some(action) = projected_action(value) {
1039 actions.push(action);
1040 }
1041 }
1042 }
1043 Value::Object(values) => {
1044 for (label, value) in values {
1045 if let Some(command) = value.as_str() {
1046 actions.push(VizFindingAction {
1047 label: label.clone(),
1048 kind: Some(label.clone()),
1049 auto_fixable: false,
1050 command: Some(command.to_string()),
1051 comment: None,
1052 config_key: None,
1053 value: None,
1054 description: None,
1055 });
1056 }
1057 }
1058 }
1059 Value::Null | Value::Bool(_) | Value::Number(_) | Value::String(_) => {}
1060 }
1061}
1062
1063fn projected_action(value: &Value) -> Option<VizFindingAction> {
1064 let action = value.as_object()?;
1065 let kind = ["kind", "type"]
1066 .iter()
1067 .find_map(|key| action.get(*key).and_then(Value::as_str))
1068 .map(str::to_owned);
1069 let label = ["label", "title"]
1070 .iter()
1071 .find_map(|key| action.get(*key).and_then(Value::as_str))
1072 .map(str::to_owned)
1073 .or_else(|| kind.clone())
1074 .unwrap_or_else(|| "Review".to_string());
1075 let command = action
1076 .get("command")
1077 .and_then(Value::as_str)
1078 .map(str::to_owned);
1079 let comment = action
1080 .get("comment")
1081 .and_then(Value::as_str)
1082 .map(str::to_owned);
1083 let auto_fixable = action
1084 .get("auto_fixable")
1085 .and_then(Value::as_bool)
1086 .unwrap_or(false);
1087 let config_key = action
1088 .get("config_key")
1089 .and_then(Value::as_str)
1090 .map(str::to_owned);
1091 let projected_value = action.get("value").cloned();
1092 let description = ["description", "note"]
1093 .iter()
1094 .find_map(|key| action.get(*key).and_then(Value::as_str))
1095 .map(str::to_owned);
1096 (command.is_some()
1097 || comment.is_some()
1098 || description.is_some()
1099 || config_key.is_some()
1100 || projected_value.is_some())
1101 .then_some(VizFindingAction {
1102 label,
1103 kind,
1104 auto_fixable,
1105 command,
1106 comment,
1107 config_key,
1108 value: projected_value,
1109 description,
1110 })
1111}
1112
1113fn collect_path_values(value: &Value, out: &mut Vec<String>) {
1114 match value {
1115 Value::Object(map) => {
1116 for (key, value) in map {
1117 if is_path_key(key)
1118 && let Some(path) = value.as_str()
1119 {
1120 out.push(path.to_string());
1121 }
1122 if is_path_collection_key(key)
1123 && let Some(values) = value.as_array()
1124 {
1125 out.extend(values.iter().filter_map(Value::as_str).map(str::to_string));
1126 }
1127 collect_path_values(value, out);
1128 }
1129 }
1130 Value::Array(values) => {
1131 for value in values {
1132 collect_path_values(value, out);
1133 }
1134 }
1135 Value::Null | Value::Bool(_) | Value::Number(_) | Value::String(_) => {}
1136 }
1137}
1138
1139fn find_string_key<'a>(value: &'a Value, keys: &[&str]) -> Option<&'a str> {
1140 match value {
1141 Value::Object(map) => {
1142 for key in keys {
1143 if let Some(value) = map.get(*key).and_then(Value::as_str) {
1144 return Some(value);
1145 }
1146 }
1147 map.values().find_map(|value| find_string_key(value, keys))
1148 }
1149 Value::Array(values) => values.iter().find_map(|value| find_string_key(value, keys)),
1150 _ => None,
1151 }
1152}
1153
1154fn find_u64_key(value: &Value, keys: &[&str]) -> Option<u64> {
1155 match value {
1156 Value::Object(map) => {
1157 for key in keys {
1158 if let Some(value) = map.get(*key).and_then(Value::as_u64) {
1159 return Some(value);
1160 }
1161 }
1162 map.values().find_map(|value| find_u64_key(value, keys))
1163 }
1164 Value::Array(values) => values.iter().find_map(|value| find_u64_key(value, keys)),
1165 _ => None,
1166 }
1167}
1168
1169fn relativize_value_paths(value: &mut Value, root: &Path) {
1170 relativize_keyed_paths(value, root, false);
1171}
1172
1173fn relativize_keyed_paths(value: &mut Value, root: &Path, is_path: bool) {
1174 match value {
1175 Value::String(text) if is_path => {
1176 let path = Path::new(text);
1177 if path.has_root() {
1183 *text = relative_path(path, root);
1184 }
1185 }
1186 Value::Array(values) => {
1187 for value in values {
1188 relativize_keyed_paths(value, root, is_path);
1189 }
1190 }
1191 Value::Object(map) => {
1192 for (key, value) in map {
1193 let is_path = is_path_key(key) || is_path_collection_key(key);
1194 relativize_keyed_paths(value, root, is_path);
1195 }
1196 }
1197 Value::Null | Value::Bool(_) | Value::Number(_) | Value::String(_) => {}
1198 }
1199}
1200
1201fn is_path_key(key: &str) -> bool {
1202 matches!(
1203 key,
1204 "path"
1205 | "file"
1206 | "from_path"
1207 | "to_path"
1208 | "consumer_path"
1209 | "source_path"
1210 | "definition_path"
1211 | "template_path"
1212 | "inherited_from"
1213 | "reachable_via"
1214 | "new_path"
1215 | "old_path"
1216 | "cycle_path"
1217 | "docs_path"
1218 | "meta_docs_path"
1219 | "full_report_path"
1220 )
1221}
1222
1223fn is_path_collection_key(key: &str) -> bool {
1224 matches!(
1225 key,
1226 "files"
1227 | "paths"
1228 | "conflicting_paths"
1229 | "used_in_workspaces"
1230 | "hardcoded_consumers"
1231 | "hot_paths"
1232 )
1233}
1234
1235fn serialized_label<T: Serialize>(value: &T) -> String {
1236 serde_json::to_value(value)
1237 .ok()
1238 .and_then(|value| value.as_str().map(str::to_owned))
1239 .unwrap_or_else(|| "unknown".to_string())
1240}
1241
1242fn build_architecture(
1243 results: &AnalysisResults,
1244 index: &FileIndex<'_>,
1245 root: &Path,
1246) -> VizFindingAnalysis {
1247 let mut findings = Vec::new();
1248 push_findings(
1249 &mut findings,
1250 "boundary-violation",
1251 "Forbidden import",
1252 &results.boundary_violations,
1253 root,
1254 index,
1255 );
1256 push_findings(
1257 &mut findings,
1258 "boundary-coverage",
1259 "File outside architecture zones",
1260 &results.boundary_coverage_violations,
1261 root,
1262 index,
1263 );
1264 push_findings(
1265 &mut findings,
1266 "boundary-call",
1267 "Forbidden call",
1268 &results.boundary_call_violations,
1269 root,
1270 index,
1271 );
1272 push_findings(
1273 &mut findings,
1274 "policy-violation",
1275 "Policy violation",
1276 &results.policy_violations,
1277 root,
1278 index,
1279 );
1280 push_findings(
1281 &mut findings,
1282 "circular-dependency",
1283 "Import cycle",
1284 &results.circular_dependencies,
1285 root,
1286 index,
1287 );
1288 push_findings(
1289 &mut findings,
1290 "re-export-cycle",
1291 "Re-export cycle",
1292 &results.re_export_cycles,
1293 root,
1294 index,
1295 );
1296 push_findings(
1297 &mut findings,
1298 "package-cycle",
1299 "Package cycle",
1300 &results.package_cycles,
1301 root,
1302 index,
1303 );
1304 let violation_count = results.boundary_violations.len()
1305 + results.boundary_coverage_violations.len()
1306 + results.boundary_call_violations.len()
1307 + results.policy_violations.len();
1308 let total_findings = violation_count
1309 + results.circular_dependencies.len()
1310 + results.re_export_cycles.len()
1311 + results.package_cycles.len();
1312 analysis_from_records(findings, total_findings, violation_count, "violations")
1313}
1314
1315fn build_dependencies(
1316 results: &AnalysisResults,
1317 index: &FileIndex<'_>,
1318 root: &Path,
1319) -> VizFindingAnalysis {
1320 let mut findings = Vec::new();
1321 let mut count = 0;
1322 macro_rules! add {
1323 ($field:ident, $kind:literal, $title:literal) => {
1324 count += results.$field.len();
1325 push_findings(&mut findings, $kind, $title, &results.$field, root, index);
1326 };
1327 }
1328 add!(unresolved_imports, "unresolved-import", "Unresolved import");
1329 add!(
1330 unlisted_dependencies,
1331 "unlisted-dependency",
1332 "Unlisted dependency"
1333 );
1334 add!(unlisted_binaries, "unlisted-binary", "Unlisted binary");
1335 add!(
1336 type_only_dependencies,
1337 "type-only-dependency",
1338 "Type-only dependency"
1339 );
1340 add!(
1341 test_only_dependencies,
1342 "test-only-dependency",
1343 "Test-only dependency"
1344 );
1345 add!(
1346 dev_dependencies_in_production,
1347 "dev-dependency-in-production",
1348 "Development dependency used in production"
1349 );
1350 add!(
1351 duplicate_exports,
1352 "duplicate-export",
1353 "Duplicate public export"
1354 );
1355 add!(
1356 duplicate_export_aliases,
1357 "duplicate-export-alias",
1358 "Binding exported under several names"
1359 );
1360 add!(
1361 private_type_leaks,
1362 "private-type-leak",
1363 "Private type leaked by public API"
1364 );
1365 add!(
1366 deprecated_exports_in_use,
1367 "deprecated-export-in-use",
1368 "Deprecated export still in use"
1369 );
1370 add!(
1371 unused_catalog_entries,
1372 "unused-catalog-entry",
1373 "Unused catalog entry"
1374 );
1375 add!(
1376 empty_catalog_groups,
1377 "empty-catalog-group",
1378 "Empty catalog group"
1379 );
1380 add!(
1381 unresolved_catalog_references,
1382 "unresolved-catalog-reference",
1383 "Unresolved catalog reference"
1384 );
1385 add!(
1386 unused_dependency_overrides,
1387 "unused-dependency-override",
1388 "Unused dependency override"
1389 );
1390 add!(
1391 misconfigured_dependency_overrides,
1392 "misconfigured-dependency-override",
1393 "Misconfigured dependency override"
1394 );
1395 analysis_from_records(findings, count, count, "findings")
1396}
1397
1398fn build_frameworks(
1399 results: &AnalysisResults,
1400 index: &FileIndex<'_>,
1401 root: &Path,
1402) -> VizFrameworkData {
1403 let analysis = build_framework_findings(results, index, root);
1404 VizFrameworkData {
1405 availability: analysis.availability,
1406 detector_availability: VizAvailability::unavailable(
1407 "detectors",
1408 "Framework detector coverage did not complete",
1409 ),
1410 findings_truncated: analysis.findings_truncated,
1411 findings: analysis.findings,
1412 detected_frameworks: Vec::new(),
1413 detectors: Vec::new(),
1414 }
1415}
1416
1417fn push_effect_findings(
1419 findings: &mut Vec<VizFinding>,
1420 results: &AnalysisResults,
1421 index: &FileIndex<'_>,
1422 root: &Path,
1423) -> usize {
1424 push_findings(
1425 findings,
1426 "unused-effect-layer",
1427 "Unused Effect layer",
1428 &results.unused_effect_layers,
1429 root,
1430 index,
1431 );
1432 push_findings(
1433 findings,
1434 "unused-tagged-error",
1435 "Unused tagged error",
1436 &results.unused_tagged_errors,
1437 root,
1438 index,
1439 );
1440 push_findings(
1441 findings,
1442 "unproduced-catch-tag",
1443 "Unproduced catch tag",
1444 &results.unproduced_catch_tags,
1445 root,
1446 index,
1447 );
1448 results.unused_effect_layers.len()
1449 + results.unused_tagged_errors.len()
1450 + results.unproduced_catch_tags.len()
1451}
1452
1453fn build_feature_flags(
1454 flags: &[FeatureFlag],
1455 index: &FileIndex<'_>,
1456 root: &Path,
1457) -> VizFindingAnalysis {
1458 let mut findings = Vec::new();
1459 push_findings(
1460 &mut findings,
1461 "feature-flag",
1462 "Feature flag use",
1463 flags,
1464 root,
1465 index,
1466 );
1467 analysis_from_records(findings, flags.len(), flags.len(), "flags")
1468}
1469
1470fn build_security(
1471 results: &AnalysisResults,
1472 index: &FileIndex<'_>,
1473 root: &Path,
1474) -> VizSecurityData {
1475 let total = results.security_findings.len();
1476 let truncated =
1477 (total > MAX_ANALYSIS_FINDINGS).then_some(total.saturating_sub(MAX_ANALYSIS_FINDINGS));
1478 let mut sorted_findings: Vec<&SecurityFinding> = results.security_findings.iter().collect();
1479 sorted_findings.sort_by_key(|finding| {
1480 let severity = serialized_label(&crate::security::derive_security_severity(finding));
1481 let priority = match severity.as_str() {
1482 "high" => 0,
1483 "medium" => 1,
1484 _ => 2,
1485 };
1486 (priority, relative_path(&finding.path, root), finding.line)
1487 });
1488 let candidates = sorted_findings
1489 .into_iter()
1490 .take(MAX_ANALYSIS_FINDINGS)
1491 .map(|finding| build_security_candidate(finding, index, root))
1492 .collect();
1493
1494 let mut blind_spots = Vec::new();
1495 if results.security_unresolved_edge_files > 0 {
1496 blind_spots.push(VizSecurityBlindSpot {
1497 kind: "unresolved-dynamic-imports".to_string(),
1498 count: results.security_unresolved_edge_files,
1499 path: None,
1500 file: None,
1501 line: None,
1502 reason: Some("Dynamic imports prevent complete client/server reachability".to_string()),
1503 });
1504 }
1505 if results.security_unresolved_callee_sites > 0 {
1506 blind_spots.push(VizSecurityBlindSpot {
1507 kind: "unresolved-callee-sites".to_string(),
1508 count: results.security_unresolved_callee_sites,
1509 path: None,
1510 file: None,
1511 line: None,
1512 reason: Some(
1513 "Dynamic or computed callees could not be matched to the sink catalogue"
1514 .to_string(),
1515 ),
1516 });
1517 }
1518 let diagnostic_count = results.security_unresolved_callee_diagnostics.len();
1519 for diagnostic in results
1520 .security_unresolved_callee_diagnostics
1521 .iter()
1522 .take(MAX_SECURITY_BLIND_SPOT_SAMPLES)
1523 {
1524 blind_spots.push(VizSecurityBlindSpot {
1525 kind: "unresolved-callee-sample".to_string(),
1526 count: 1,
1527 path: Some(relative_path(&diagnostic.path, root)),
1528 file: index.index_of_path(&diagnostic.path),
1529 line: Some(diagnostic.line),
1530 reason: Some(serialized_label(&diagnostic.reason)),
1531 });
1532 }
1533
1534 VizSecurityData {
1535 availability: VizAvailability::complete(total, "candidates", truncated),
1536 runtime_availability: VizAvailability::unavailable(
1537 "observations",
1538 NO_RUNTIME_COVERAGE_REASON,
1539 ),
1540 candidates,
1541 blind_spot_count: results.security_unresolved_edge_files
1542 + results.security_unresolved_callee_sites,
1543 blind_spots_truncated: (diagnostic_count > MAX_SECURITY_BLIND_SPOT_SAMPLES)
1544 .then_some(diagnostic_count.saturating_sub(MAX_SECURITY_BLIND_SPOT_SAMPLES)),
1545 blind_spots,
1546 }
1547}
1548
1549fn build_security_candidate(
1550 finding: &SecurityFinding,
1551 index: &FileIndex<'_>,
1552 root: &Path,
1553) -> VizSecurityCandidate {
1554 let kind = serialized_label(&finding.kind);
1555 let path = relative_path(&finding.path, root);
1556 let severity = serialized_label(&crate::security::derive_security_severity(finding));
1557 let id = finding.finding_id.clone();
1560 let reachability = finding.reachability.as_ref();
1561 let architecture_zone = finding
1562 .candidate
1563 .boundary
1564 .architecture_zone
1565 .as_ref()
1566 .map(|zone| format!("{} -> {}", zone.from, zone.to));
1567 let dead_code = serialize_relative(finding.dead_code.as_ref(), root);
1568 let runtime = serialize_relative(finding.runtime.as_ref(), root);
1569 let taint_flow = security_taint_flow(finding, index, root);
1570 let observed_controls = security_controls(finding, root);
1571 let actions = serialize_relative_value(&finding.actions, root)
1572 .unwrap_or_else(|| Value::Array(Vec::new()));
1573 let trace = security_trace(finding, index, root);
1574 let taint_trace = finding
1575 .reachability
1576 .as_ref()
1577 .map_or_else(Vec::new, |reachability| {
1578 trace_hops(&reachability.untrusted_source_trace, index, root)
1579 });
1580 VizSecurityCandidate {
1581 id,
1582 kind,
1583 category: finding.category.clone(),
1584 cwe: finding.cwe,
1585 file: index.index_of_path(&finding.path),
1586 path,
1587 line: finding.line,
1588 col: finding.col,
1589 evidence: finding.evidence.clone(),
1590 severity,
1591 taint_confidence: reachability
1592 .and_then(|reachability| reachability.taint_confidence.as_ref())
1593 .map(serialized_label),
1594 source_kind: finding.candidate.source_kind.clone(),
1595 sink: finding.candidate.sink.callee.clone(),
1596 url_shape: finding
1597 .candidate
1598 .sink
1599 .url_shape
1600 .as_ref()
1601 .map(serialized_label),
1602 network_destination: finding
1603 .candidate
1604 .network
1605 .as_ref()
1606 .and_then(|network| network.destination.clone()),
1607 reachable_from_entry: reachability.map(|value| value.reachable_from_entry),
1608 reachable_from_untrusted_source: reachability
1609 .map(|value| value.reachable_from_untrusted_source),
1610 blast_radius: reachability.map(|value| value.blast_radius),
1611 crosses_boundary: reachability.is_some_and(|value| value.crosses_boundary)
1612 || finding.candidate.boundary.client_server
1613 || finding.candidate.boundary.cross_module
1614 || architecture_zone.is_some(),
1615 client_server_boundary: finding.candidate.boundary.client_server,
1616 cross_module_boundary: finding.candidate.boundary.cross_module,
1617 architecture_zone,
1618 dead_code,
1619 runtime,
1620 taint_flow,
1621 observed_controls,
1622 control_verification_prompt: finding
1623 .attack_surface
1624 .as_ref()
1625 .map(|surface| surface.defensive_boundary.verification_prompt.clone()),
1626 trace,
1627 taint_trace,
1628 actions,
1629 }
1630}
1631
1632fn serialize_relative<T: Serialize>(value: Option<&T>, root: &Path) -> Option<Value> {
1633 value.and_then(|value| serialize_relative_value(value, root))
1634}
1635
1636fn serialize_relative_value<T: Serialize>(value: &T, root: &Path) -> Option<Value> {
1637 let mut serialized = serde_json::to_value(value).ok()?;
1638 relativize_value_paths(&mut serialized, root);
1639 Some(serialized)
1640}
1641
1642fn security_controls(finding: &SecurityFinding, root: &Path) -> Vec<Value> {
1643 finding
1644 .attack_surface
1645 .as_ref()
1646 .map_or_else(Vec::new, |surface| {
1647 surface
1648 .defensive_boundary
1649 .controls
1650 .iter()
1651 .filter_map(|control| serialize_relative_value(control, root))
1652 .collect()
1653 })
1654}
1655
1656fn security_trace(
1657 finding: &SecurityFinding,
1658 index: &FileIndex<'_>,
1659 root: &Path,
1660) -> Vec<VizSecurityTraceHop> {
1661 trace_hops(&finding.trace, index, root)
1662}
1663
1664fn trace_hops(
1665 hops: &[fallow_types::results::TraceHop],
1666 index: &FileIndex<'_>,
1667 root: &Path,
1668) -> Vec<VizSecurityTraceHop> {
1669 hops.iter()
1670 .map(|hop| VizSecurityTraceHop {
1671 file: index.index_of_path(&hop.path),
1672 path: relative_path(&hop.path, root),
1673 line: hop.line,
1674 col: hop.col,
1675 role: serialized_label(&hop.role),
1676 })
1677 .collect()
1678}
1679
1680fn security_taint_flow(
1681 finding: &SecurityFinding,
1682 index: &FileIndex<'_>,
1683 root: &Path,
1684) -> Option<VizSecurityTaintFlow> {
1685 let flow = finding.taint_flow.as_ref()?;
1686 let endpoint = |value: &fallow_types::results::TaintEndpoint| VizSecurityEndpoint {
1687 file: index.index_of_path(&value.path),
1688 path: relative_path(&value.path, root),
1689 line: value.line,
1690 col: value.col,
1691 };
1692 Some(VizSecurityTaintFlow {
1693 source: endpoint(&flow.source),
1694 sink: endpoint(&flow.sink),
1695 intra_module: flow.path.intra_module,
1696 cross_module_hops: flow.path.cross_module_hops,
1697 })
1698}
1699
1700pub fn apply_health_report(data: &mut VizData, report: &HealthReport, root: &Path) {
1703 let by_path: FxHashMap<String, u32> = data
1704 .files
1705 .iter()
1706 .enumerate()
1707 .map(|(index, file)| (file.path.clone(), clamp_u32(index)))
1708 .collect();
1709 apply_health_data(data, report, root, &by_path);
1710 apply_framework_data(data, report);
1711 apply_styling_data(data, report, root, &by_path);
1712}
1713
1714fn apply_health_data(
1715 data: &mut VizData,
1716 report: &HealthReport,
1717 root: &Path,
1718 by_path: &FxHashMap<String, u32>,
1719) {
1720 let resolve = |path: &Path| by_path.get(&relative_path(path, root)).copied();
1721 let hotspot_by_path: FxHashMap<String, &fallow_output::HotspotFinding> = report
1722 .hotspots
1723 .iter()
1724 .map(|hotspot| (relative_path(&hotspot.path, root), hotspot))
1725 .collect();
1726 let files = health_files(report, root, by_path, &hotspot_by_path);
1727 let (findings, total_findings) = health_findings(report, root, &resolve);
1728 let concern_count = health_concern_count(report, root, by_path);
1729 data.health = VizHealthData {
1730 availability: VizAvailability::complete(concern_count, "files", None),
1731 capabilities: health_capabilities(report),
1732 shared_parse: data.health.shared_parse,
1733 score: report.health_score.as_ref().map(|score| score.score),
1734 grade: report
1735 .health_score
1736 .as_ref()
1737 .map(|score| score.grade.to_string()),
1738 average_maintainability: report.summary.average_maintainability,
1739 files_truncated: report
1740 .file_scores
1741 .len()
1742 .checked_sub(MAX_HEALTH_FILES)
1743 .filter(|count| *count > 0),
1744 findings_truncated: total_findings
1745 .checked_sub(findings.len())
1746 .filter(|count| *count > 0),
1747 files,
1748 findings,
1749 };
1750}
1751
1752fn health_concern_count(
1753 report: &HealthReport,
1754 root: &Path,
1755 by_path: &FxHashMap<String, u32>,
1756) -> usize {
1757 let mut files = rustc_hash::FxHashSet::default();
1758 let mut add = |path: &Path| {
1759 if let Some(file) = by_path.get(&relative_path(path, root)) {
1760 files.insert(*file);
1761 }
1762 };
1763 for finding in &report.findings {
1764 add(&finding.path);
1765 }
1766 for hotspot in &report.hotspots {
1767 add(&hotspot.path);
1768 }
1769 if let Some(gaps) = &report.coverage_gaps {
1770 for finding in &gaps.files {
1771 add(&finding.file.path);
1772 }
1773 for finding in &gaps.exports {
1774 add(&finding.export.path);
1775 }
1776 }
1777 files.len()
1778}
1779
1780fn health_files(
1781 report: &HealthReport,
1782 root: &Path,
1783 by_path: &FxHashMap<String, u32>,
1784 hotspots: &FxHashMap<String, &fallow_output::HotspotFinding>,
1785) -> Vec<VizHealthFile> {
1786 report
1787 .file_scores
1788 .iter()
1789 .take(MAX_HEALTH_FILES)
1790 .filter_map(|score| {
1791 let path = relative_path(&score.path, root);
1792 let file = by_path.get(&path).copied()?;
1793 let hotspot = hotspots.get(&path).copied();
1794 Some(VizHealthFile {
1795 file,
1796 path,
1797 maintainability_index: score.maintainability_index,
1798 crap_max: score.crap_max,
1799 complexity_density: score.complexity_density,
1800 fan_in: score.fan_in,
1801 fan_out: score.fan_out,
1802 hotspot_score: hotspot.map(|entry| entry.score),
1803 commits: hotspot.map(|entry| entry.commits),
1804 ownership: hotspot
1805 .and_then(|entry| serialize_relative(entry.ownership.as_ref(), root)),
1806 })
1807 })
1808 .collect()
1809}
1810
1811fn health_findings(
1812 report: &HealthReport,
1813 root: &Path,
1814 resolve: &dyn Fn(&Path) -> Option<u32>,
1815) -> (Vec<VizFinding>, usize) {
1816 let coverage_count = report
1817 .coverage_gaps
1818 .as_ref()
1819 .map_or(0, |gaps| gaps.files.len() + gaps.exports.len());
1820 let total = report.findings.len() + report.hotspots.len() + coverage_count;
1821 let mut findings = Vec::with_capacity(total.min(MAX_ANALYSIS_FINDINGS));
1822 append_findings(
1823 &mut findings,
1824 &report.findings,
1825 "health-finding",
1826 "Health threshold exceeded",
1827 root,
1828 resolve,
1829 );
1830 append_findings(
1831 &mut findings,
1832 &report.hotspots,
1833 "git-hotspot",
1834 "Complex and frequently changed file",
1835 root,
1836 resolve,
1837 );
1838 if let Some(gaps) = &report.coverage_gaps {
1839 append_findings(
1840 &mut findings,
1841 &gaps.files,
1842 "coverage-gap-file",
1843 "File has no test path",
1844 root,
1845 resolve,
1846 );
1847 append_findings(
1848 &mut findings,
1849 &gaps.exports,
1850 "coverage-gap-export",
1851 "Export has no test path",
1852 root,
1853 resolve,
1854 );
1855 }
1856 (findings, total)
1857}
1858
1859fn append_findings<T: Serialize>(
1860 out: &mut Vec<VizFinding>,
1861 values: &[T],
1862 kind: &str,
1863 title: &str,
1864 root: &Path,
1865 resolve: &dyn Fn(&Path) -> Option<u32>,
1866) {
1867 let remaining = MAX_ANALYSIS_FINDINGS.saturating_sub(out.len());
1868 out.extend(values.iter().take(remaining).filter_map(|value| {
1869 serde_json::to_value(value)
1870 .ok()
1871 .map(|detail| finding_from_value(kind, title, detail, root, resolve))
1872 }));
1873}
1874
1875fn health_capabilities(report: &HealthReport) -> VizHealthCapabilities {
1876 let file_count = report.file_scores.len();
1877 let coverage = report.coverage_gaps.as_ref().map_or_else(
1878 || VizAvailability::unavailable("gaps", "Coverage gap analysis did not produce a result"),
1879 |gaps| VizAvailability::complete(gaps.files.len() + gaps.exports.len(), "gaps", None),
1880 );
1881 let runtime = report.runtime_coverage.as_ref().map_or_else(
1882 || VizAvailability::unavailable("observations", NO_RUNTIME_COVERAGE_REASON),
1883 |runtime| {
1884 VizAvailability::complete(runtime.summary.observed_functions(), "observations", None)
1885 },
1886 );
1887 VizHealthCapabilities {
1888 complexity: VizAvailability::complete(report.findings.len(), "findings", None),
1889 maintainability: VizAvailability::complete(file_count, "files", None),
1890 crap: VizAvailability::complete(file_count, "files", None),
1891 coverage,
1892 runtime,
1893 churn: VizAvailability::disabled("files", "Git history is not loaded by Viz"),
1894 hotspots: VizAvailability::disabled("files", "Git history is not loaded by Viz"),
1895 ownership: VizAvailability::disabled("files", "Git history is not loaded by Viz"),
1896 }
1897}
1898
1899fn unavailable_health_capabilities(reason: &str) -> VizHealthCapabilities {
1900 VizHealthCapabilities {
1901 complexity: VizAvailability::unavailable("findings", reason),
1902 maintainability: VizAvailability::unavailable("files", reason),
1903 crap: VizAvailability::unavailable("files", reason),
1904 coverage: VizAvailability::unavailable("gaps", reason),
1905 runtime: VizAvailability::unavailable("observations", NO_RUNTIME_COVERAGE_REASON),
1906 churn: VizAvailability::unavailable("files", reason),
1907 hotspots: VizAvailability::unavailable("files", reason),
1908 ownership: VizAvailability::unavailable("files", reason),
1909 }
1910}
1911
1912fn apply_framework_data(data: &mut VizData, report: &HealthReport) {
1913 let count = data.frameworks.availability.count;
1914 let Some(diagnostics) = &report.framework_health else {
1915 if count == 0 {
1916 data.frameworks.detector_availability = VizAvailability {
1917 state: VizAvailabilityState::NotApplicable,
1918 count: 0,
1919 unit: "detectors",
1920 reason: Some("No supported framework was detected".to_string()),
1921 truncated: None,
1922 };
1923 data.frameworks.availability.state = VizAvailabilityState::NotApplicable;
1924 data.frameworks.availability.reason =
1925 Some("No supported framework was detected".to_string());
1926 } else {
1927 data.frameworks.detector_availability = VizAvailability::unavailable(
1928 "detectors",
1929 "Framework detector metadata was not produced",
1930 );
1931 }
1932 return;
1933 };
1934 data.frameworks
1935 .detected_frameworks
1936 .clone_from(&diagnostics.detected_frameworks);
1937 data.frameworks.detectors = diagnostics
1938 .detectors
1939 .iter()
1940 .map(|detector| VizFrameworkDetector {
1941 id: detector.id.clone(),
1942 framework: detector.framework.clone(),
1943 status: serialized_label(&detector.status),
1944 reason: detector.reason.clone(),
1945 })
1946 .collect();
1947 data.frameworks.detector_availability =
1948 VizAvailability::complete(diagnostics.detectors.len(), "detectors", None);
1949 if diagnostics.detected_frameworks.is_empty() && count == 0 {
1950 data.frameworks.availability.state = VizAvailabilityState::NotApplicable;
1951 data.frameworks.availability.reason =
1952 Some("No supported framework was detected".to_string());
1953 data.frameworks.detector_availability.state = VizAvailabilityState::NotApplicable;
1954 data.frameworks.detector_availability.reason =
1955 Some("No supported framework was detected".to_string());
1956 }
1957}
1958
1959fn apply_styling_data(
1960 data: &mut VizData,
1961 report: &HealthReport,
1962 root: &Path,
1963 by_path: &FxHashMap<String, u32>,
1964) {
1965 let resolve = |path: &Path| by_path.get(&relative_path(path, root)).copied();
1966 let count = report.styling_findings.len();
1967 let mut findings = Vec::with_capacity(count.min(MAX_ANALYSIS_FINDINGS));
1968 append_findings(
1969 &mut findings,
1970 &report.styling_findings,
1971 "styling-finding",
1972 "Styling health finding",
1973 root,
1974 &resolve,
1975 );
1976 let truncated = count.checked_sub(findings.len()).filter(|value| *value > 0);
1977 let styling = report.styling_health.as_ref();
1978 data.styling = VizStylingData {
1979 availability: report.css_analytics.as_ref().map_or_else(
1980 || VizAvailability {
1981 state: VizAvailabilityState::NotApplicable,
1982 count: 0,
1983 unit: "findings",
1984 reason: Some("No supported CSS or component styling was detected".to_string()),
1985 truncated: None,
1986 },
1987 |_| VizAvailability::complete(count, "findings", truncated),
1988 ),
1989 findings_truncated: truncated,
1990 findings,
1991 score: styling.map(|health| health.score),
1992 grade: styling.map(|health| health.grade.to_string()),
1993 confidence: styling.map(|health| serialized_label(&health.confidence)),
1994 summary: report
1995 .css_analytics
1996 .as_ref()
1997 .and_then(|analytics| serde_json::to_value(&analytics.summary).ok()),
1998 };
1999}
2000
2001struct FilePropertyMaps<'a> {
2003 zone_by_file: &'a FxHashMap<u32, u16>,
2004 clone_groups_by_file: &'a FxHashMap<u32, Vec<u32>>,
2005 dup_lines_by_file: &'a FxHashMap<u32, u32>,
2006 cycles: &'a [Vec<u32>],
2007}
2008
2009fn display_root(root: &Path) -> String {
2010 root.file_name().map_or_else(
2011 || root.to_string_lossy().into_owned(),
2012 |n| n.to_string_lossy().into_owned(),
2013 )
2014}
2015
2016fn relative_path(path: &Path, root: &Path) -> String {
2017 if let Ok(relative) = path.strip_prefix(root) {
2018 return relative.to_string_lossy().replace('\\', "/");
2019 }
2020 if path.has_root() {
2025 let name = path
2026 .file_name()
2027 .map_or_else(|| "path".into(), |name| name.to_string_lossy());
2028 return format!("<external>/{name}");
2029 }
2030 path.to_string_lossy().replace('\\', "/")
2031}
2032
2033fn build_workspaces(workspaces: &[WorkspaceInfo], root: &Path) -> Vec<VizWorkspace> {
2034 workspaces
2035 .iter()
2036 .map(|ws| VizWorkspace {
2037 name: ws.name.clone(),
2038 root: relative_path(&ws.root, root),
2039 })
2040 .collect()
2041}
2042
2043fn workspace_index_for(path: &Path, workspaces: &[WorkspaceInfo]) -> Option<u16> {
2044 let mut best: Option<(usize, usize)> = None;
2045 for (i, ws) in workspaces.iter().enumerate() {
2046 if path.starts_with(&ws.root) {
2047 let depth = ws.root.components().count();
2048 if best.is_none_or(|(_, d)| depth > d) {
2049 best = Some((i, depth));
2050 }
2051 }
2052 }
2053 best.map(|(i, _)| clamp_u16(i))
2054}
2055
2056fn classify_zones(
2057 input: &VizBuildInput<'_>,
2058 index: &FileIndex<'_>,
2059) -> (Vec<VizZone>, FxHashMap<u32, u16>) {
2060 let boundaries = &input.config.boundaries;
2061 let mut zones: Vec<VizZone> = boundaries
2062 .zones
2063 .iter()
2064 .map(|z| VizZone {
2065 name: z.name.clone(),
2066 files: 0,
2067 })
2068 .collect();
2069 let name_to_index: FxHashMap<&str, u16> = boundaries
2070 .zones
2071 .iter()
2072 .enumerate()
2073 .map(|(i, z)| (z.name.as_str(), clamp_u16(i)))
2074 .collect();
2075
2076 let mut zone_by_file = FxHashMap::default();
2077 if zones.is_empty() {
2078 return (zones, zone_by_file);
2079 }
2080
2081 for (i, file) in index.ordered.iter().enumerate() {
2082 let rel = relative_path(&file.path, &input.config.root);
2083 if let Some(zone_name) = boundaries.classify_zone(&rel)
2084 && let Some(&zone_idx) = name_to_index.get(zone_name)
2085 {
2086 zone_by_file.insert(clamp_u32(i), zone_idx);
2087 zones[zone_idx as usize].files += 1;
2088 }
2089 }
2090
2091 (zones, zone_by_file)
2092}
2093
2094type CloneMaps = (
2097 Vec<VizCloneGroup>,
2098 FxHashMap<u32, Vec<u32>>,
2099 FxHashMap<u32, u32>,
2100 u32,
2101);
2102
2103fn build_clones(
2104 duplication: &DuplicationReport,
2105 index: &FileIndex<'_>,
2106 max_groups: usize,
2107) -> CloneMaps {
2108 let mut clones = Vec::new();
2109 let mut groups_by_file: FxHashMap<u32, Vec<u32>> = FxHashMap::default();
2110 let mut dup_lines_by_file: FxHashMap<u32, u32> = FxHashMap::default();
2111 let mut truncated: usize = 0;
2112
2113 for group in &duplication.clone_groups {
2114 let instances: Vec<VizCloneInstance> = group
2115 .instances
2116 .iter()
2117 .filter_map(|inst| {
2118 index
2119 .index_of_path(&inst.file)
2120 .map(|file| VizCloneInstance {
2121 file,
2122 start_line: clamp_u32(inst.start_line),
2123 end_line: clamp_u32(inst.end_line),
2124 })
2125 })
2126 .collect();
2127 if instances.len() < 2 {
2128 continue;
2129 }
2130 if clones.len() >= max_groups {
2131 truncated += 1;
2132 continue;
2133 }
2134
2135 let group_idx = clamp_u32(clones.len());
2136 for inst in &instances {
2137 let entry = groups_by_file.entry(inst.file).or_default();
2138 if entry.last() != Some(&group_idx) {
2139 entry.push(group_idx);
2140 }
2141 *dup_lines_by_file.entry(inst.file).or_default() +=
2142 inst.end_line.saturating_sub(inst.start_line) + 1;
2143 }
2144
2145 let (preview, highlight_start, highlight_lines) = group
2146 .instances
2147 .first()
2148 .map(build_clone_preview)
2149 .unwrap_or_default();
2150
2151 clones.push(VizCloneGroup {
2152 lines: group.line_count,
2153 tokens: group.token_count,
2154 instances,
2155 preview,
2156 highlight_start,
2157 highlight_lines,
2158 });
2159 }
2160
2161 (
2162 clones,
2163 groups_by_file,
2164 dup_lines_by_file,
2165 clamp_u32(truncated),
2166 )
2167}
2168
2169fn truncate_preview(fragment: &str) -> String {
2170 let mut out = String::new();
2171 for (i, line) in fragment.lines().enumerate() {
2172 if i >= CLONE_PREVIEW_MAX_LINES || out.len() + line.len() > CLONE_PREVIEW_MAX_BYTES {
2173 out.push('\u{2026}');
2174 break;
2175 }
2176 if i > 0 {
2177 out.push('\n');
2178 }
2179 out.push_str(line);
2180 }
2181 out
2182}
2183
2184fn build_clone_preview(inst: &CloneInstance) -> (String, u32, u32) {
2194 let Ok(source) = std::fs::read_to_string(&inst.file) else {
2195 return fragment_fallback(&inst.fragment);
2196 };
2197 let lines: Vec<&str> = source.lines().collect();
2198 let total = lines.len();
2199 if total == 0 || inst.start_line == 0 || inst.start_line > total {
2200 return fragment_fallback(&inst.fragment);
2201 }
2202
2203 let block_start = inst.start_line - 1;
2206 let block_end = inst.end_line.min(total).max(inst.start_line);
2207 let mut block_lines = block_end - block_start;
2208 let mut before = block_start.min(CLONE_PREVIEW_CONTEXT);
2209 let mut after = (total - block_end).min(CLONE_PREVIEW_CONTEXT);
2210
2211 if before + block_lines + after > CLONE_PREVIEW_MAX_LINES {
2216 if before + block_lines >= CLONE_PREVIEW_MAX_LINES {
2217 after = 0;
2218 block_lines = CLONE_PREVIEW_MAX_LINES.saturating_sub(before).max(1);
2219 } else {
2220 trim_context(
2221 &mut before,
2222 &mut after,
2223 CLONE_PREVIEW_MAX_LINES - block_lines,
2224 );
2225 }
2226 }
2227
2228 enforce_byte_cap(
2229 &lines,
2230 block_start,
2231 &mut before,
2232 &mut after,
2233 &mut block_lines,
2234 );
2235
2236 let win_start = block_start - before;
2237 let win_end = win_start + before + block_lines + after;
2238 let preview = lines[win_start..win_end].join("\n");
2239 (preview, clamp_u32(before), clamp_u32(block_lines))
2240}
2241
2242fn fragment_fallback(fragment: &str) -> (String, u32, u32) {
2245 let preview = truncate_preview(fragment);
2246 let highlight_lines = if preview.is_empty() {
2247 0
2248 } else {
2249 preview.lines().count()
2250 };
2251 (preview, 0, clamp_u32(highlight_lines))
2252}
2253
2254fn trim_context(before: &mut usize, after: &mut usize, budget: usize) {
2258 while *before + *after > budget {
2259 if *before >= *after {
2260 *before -= 1;
2261 } else {
2262 *after -= 1;
2263 }
2264 }
2265}
2266
2267fn enforce_byte_cap(
2272 lines: &[&str],
2273 block_start: usize,
2274 before: &mut usize,
2275 after: &mut usize,
2276 block_lines: &mut usize,
2277) {
2278 let window_bytes = |before: usize, after: usize, block_lines: usize| -> usize {
2279 let start = block_start - before;
2280 let end = start + before + block_lines + after;
2281 let separators = (end - start).saturating_sub(1);
2282 lines[start..end].iter().map(|l| l.len()).sum::<usize>() + separators
2283 };
2284 while window_bytes(*before, *after, *block_lines) > CLONE_PREVIEW_MAX_BYTES {
2285 if *before + *after > 0 {
2286 if *before >= *after {
2287 *before -= 1;
2288 } else {
2289 *after -= 1;
2290 }
2291 } else if *block_lines > 1 {
2292 *block_lines -= 1;
2293 } else {
2294 break;
2295 }
2296 }
2297}
2298
2299fn build_cycles(results: &AnalysisResults, index: &FileIndex<'_>) -> Vec<Vec<u32>> {
2300 results
2301 .circular_dependencies
2302 .iter()
2303 .filter_map(|cd| {
2304 let ids: Vec<u32> = cd
2305 .cycle
2306 .files
2307 .iter()
2308 .filter_map(|p| index.index_of_path(p))
2309 .collect();
2310 (ids.len() == cd.cycle.files.len()).then_some(ids)
2311 })
2312 .collect()
2313}
2314
2315fn build_violations(
2316 results: &AnalysisResults,
2317 zones: &[VizZone],
2318 index: &FileIndex<'_>,
2319) -> Vec<VizViolation> {
2320 let name_to_index: FxHashMap<&str, u16> = zones
2321 .iter()
2322 .enumerate()
2323 .map(|(i, z)| (z.name.as_str(), clamp_u16(i)))
2324 .collect();
2325
2326 results
2327 .boundary_violations
2328 .iter()
2329 .filter_map(|finding| {
2330 let v = &finding.violation;
2331 let from = index.index_of_path(&v.from_path)?;
2332 let to = index.index_of_path(&v.to_path)?;
2333 let from_zone = *name_to_index.get(v.from_zone.as_str())?;
2334 let to_zone = *name_to_index.get(v.to_zone.as_str())?;
2335 Some(VizViolation {
2336 from,
2337 to,
2338 from_zone,
2339 to_zone,
2340 line: v.line,
2341 specifier: v.import_specifier.clone(),
2342 })
2343 })
2344 .collect()
2345}
2346
2347fn build_edges(graph: &RetainedModuleGraph, index: &FileIndex<'_>) -> Vec<[u32; 3]> {
2348 let graph = graph.as_graph();
2349 let mut edges = Vec::with_capacity(graph.edge_count());
2350 for node in &graph.modules {
2351 let Some(source) = index.index_of_file_id(node.file_id.0) else {
2352 continue;
2353 };
2354 for (target_id, symbols) in graph.outgoing_symbol_edges(node.file_id) {
2355 let Some(target) = index.index_of_file_id(target_id.0) else {
2356 continue;
2357 };
2358 let all_type_only = !symbols.is_empty() && symbols.iter().all(|s| s.is_type_only);
2359 let flags = if all_type_only {
2360 EDGE_FLAG_TYPE_ONLY
2361 } else if symbols.iter().any(|s| s.is_eager_value()) {
2362 0
2363 } else {
2364 EDGE_FLAG_DYNAMIC
2365 };
2366 edges.push([source, target, flags]);
2367 }
2368 }
2369 edges
2370}
2371
2372#[derive(Default)]
2374struct ComplexityRollup {
2375 fn_count: u16,
2376 max_cyclomatic: u16,
2377 max_cognitive: u16,
2378 react_hooks: u16,
2379 jsx_depth: u16,
2380 functions: Vec<VizFunction>,
2381}
2382
2383fn rollup_complexity(functions: &[FunctionComplexity]) -> ComplexityRollup {
2384 let mut rollup = ComplexityRollup {
2385 fn_count: clamp_u16(functions.len()),
2386 ..ComplexityRollup::default()
2387 };
2388 for f in functions {
2389 rollup.max_cyclomatic = rollup.max_cyclomatic.max(f.cyclomatic);
2390 rollup.max_cognitive = rollup.max_cognitive.max(f.cognitive);
2391 rollup.react_hooks = rollup.react_hooks.saturating_add(f.react_hook_count);
2392 rollup.jsx_depth = rollup.jsx_depth.max(f.react_jsx_max_depth);
2393 }
2394
2395 let mut named: Vec<&FunctionComplexity> = functions
2400 .iter()
2401 .filter(|f| !f.name.starts_with('<'))
2402 .collect();
2403 named.sort_by(|a, b| {
2404 b.cyclomatic
2405 .cmp(&a.cyclomatic)
2406 .then(b.cognitive.cmp(&a.cognitive))
2407 });
2408 rollup.functions = named
2409 .into_iter()
2410 .map(|f| VizFunction {
2411 name: f.name.clone(),
2412 line: f.line,
2413 cyclomatic: f.cyclomatic,
2414 cognitive: f.cognitive,
2415 lines: f.line_count,
2416 hooks: f.react_hook_count,
2417 jsx_depth: f.react_jsx_max_depth,
2418 props: f.react_prop_count,
2419 })
2420 .collect();
2421 rollup
2422}
2423
2424fn build_summary(
2425 input: &VizBuildInput<'_>,
2426 files: &[VizFile],
2427 clones: &[VizCloneGroup],
2428 cycles: &[Vec<u32>],
2429 violations: &[VizViolation],
2430 clone_groups_truncated: u32,
2431) -> VizSummary {
2432 let results = input.results;
2433 VizSummary {
2434 total_files: files.len(),
2435 total_size: files.iter().map(|f| f.size).sum(),
2436 total_edges: input.graph.edge_count(),
2437 unused_files: results.unused_files.len(),
2438 unused_exports: results.unused_exports.len() + results.unused_types.len(),
2439 unused_types: results.unused_types.len(),
2440 unused_deps: results.unused_dependencies.len()
2441 + results.unused_dev_dependencies.len()
2442 + results.unused_optional_dependencies.len(),
2443 unresolved_imports: results.unresolved_imports.len(),
2444 circular_deps: cycles.len(),
2445 clone_groups: clones.len(),
2446 duplicated_lines: clones.iter().map(|c| c.lines * c.instances.len()).sum(),
2447 boundary_violations: violations.len(),
2448 hotspot_files: files
2449 .iter()
2450 .filter(|f| f.max_cyclomatic >= HOTSPOT_CYCLOMATIC_FLOOR)
2451 .count(),
2452 clone_groups_truncated: (clone_groups_truncated > 0).then_some(clone_groups_truncated),
2453 }
2454}
2455
2456fn clamp_u16(value: usize) -> u16 {
2457 u16::try_from(value).unwrap_or(u16::MAX)
2458}
2459
2460fn clamp_u32(value: usize) -> u32 {
2461 u32::try_from(value).unwrap_or(u32::MAX)
2462}
2463
2464#[cfg(test)]
2465#[path = "viz_tests.rs"]
2466mod tests;