dart-decimate 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (188) hide show
  1. package/Cargo.lock +572 -0
  2. package/Cargo.toml +41 -0
  3. package/LICENSE +21 -0
  4. package/README.md +617 -0
  5. package/assets/dart-decimate-banner.png +0 -0
  6. package/npm/bin/dart-decimate-mcp.js +48 -0
  7. package/npm/bin/dart-decimate.js +48 -0
  8. package/npm/scripts/postinstall.js +46 -0
  9. package/npm/scripts/test-npx-local.js +54 -0
  10. package/npm/scripts/test-npx-mcp-local.js +56 -0
  11. package/package.json +45 -0
  12. package/src/baseline.rs +643 -0
  13. package/src/bin/dart-decimate-mcp.rs +11 -0
  14. package/src/boundaries/tests.rs +60 -0
  15. package/src/boundaries.rs +317 -0
  16. package/src/changed_scope.rs +117 -0
  17. package/src/ci_template.rs +399 -0
  18. package/src/cli/analyze.rs +462 -0
  19. package/src/cli/analyzer_options.rs +82 -0
  20. package/src/cli/audit_run.rs +327 -0
  21. package/src/cli/boundary_args.rs +44 -0
  22. package/src/cli/ci_template_run.rs +196 -0
  23. package/src/cli/command_name.rs +20 -0
  24. package/src/cli/common_args.rs +167 -0
  25. package/src/cli/config_run.rs +78 -0
  26. package/src/cli/coverage_run.rs +393 -0
  27. package/src/cli/decision_surface_run.rs +99 -0
  28. package/src/cli/default_command.rs +69 -0
  29. package/src/cli/dupes_args.rs +150 -0
  30. package/src/cli/entry_points.rs +121 -0
  31. package/src/cli/error.rs +149 -0
  32. package/src/cli/error_output.rs +68 -0
  33. package/src/cli/explain_run.rs +72 -0
  34. package/src/cli/fix_run.rs +162 -0
  35. package/src/cli/flags_args.rs +23 -0
  36. package/src/cli/health_args.rs +200 -0
  37. package/src/cli/hooks_run.rs +191 -0
  38. package/src/cli/impact_run.rs +95 -0
  39. package/src/cli/init_run.rs +49 -0
  40. package/src/cli/inspect_args.rs +20 -0
  41. package/src/cli/inspect_run.rs +66 -0
  42. package/src/cli/issue_filter_args.rs +240 -0
  43. package/src/cli/list_run.rs +311 -0
  44. package/src/cli/mode_args.rs +72 -0
  45. package/src/cli/output_format.rs +62 -0
  46. package/src/cli/regression_args.rs +156 -0
  47. package/src/cli/request_args.rs +175 -0
  48. package/src/cli/schema_commands.rs +72 -0
  49. package/src/cli/scope_args.rs +174 -0
  50. package/src/cli/security_args.rs +175 -0
  51. package/src/cli/security_gate_run.rs +66 -0
  52. package/src/cli/security_summary_run.rs +43 -0
  53. package/src/cli/summary_args.rs +12 -0
  54. package/src/cli/tests.rs +516 -0
  55. package/src/cli/trace_args.rs +67 -0
  56. package/src/cli/trace_run.rs +131 -0
  57. package/src/cli/trace_tests.rs +235 -0
  58. package/src/cli/unsupported_run.rs +116 -0
  59. package/src/cli/watch_run.rs +153 -0
  60. package/src/cli.rs +603 -0
  61. package/src/config/boundary_config.rs +235 -0
  62. package/src/config/cache.rs +25 -0
  63. package/src/config/dependencies.rs +114 -0
  64. package/src/config/health.rs +237 -0
  65. package/src/config/jsonc.rs +66 -0
  66. package/src/config/policy.rs +91 -0
  67. package/src/config/rule_aliases.rs +487 -0
  68. package/src/config/rules.rs +339 -0
  69. package/src/config.rs +635 -0
  70. package/src/coverage.rs +469 -0
  71. package/src/dart_parser.rs +673 -0
  72. package/src/decision_surface.rs +405 -0
  73. package/src/dependencies/analyze.rs +218 -0
  74. package/src/dependencies/codegen.rs +118 -0
  75. package/src/dependencies/discovery.rs +60 -0
  76. package/src/dependencies/overrides.rs +76 -0
  77. package/src/dependencies/private_src_imports.rs +32 -0
  78. package/src/dependencies/pubspec_document.rs +86 -0
  79. package/src/dependencies/pubspec_entry.rs +96 -0
  80. package/src/dependencies/tests.rs +544 -0
  81. package/src/dependencies/usage.rs +33 -0
  82. package/src/dependencies.rs +553 -0
  83. package/src/dependency_scripts.rs +91 -0
  84. package/src/dupes/lex.rs +236 -0
  85. package/src/dupes/tests.rs +119 -0
  86. package/src/dupes.rs +625 -0
  87. package/src/explain.rs +692 -0
  88. package/src/extract/directives.rs +252 -0
  89. package/src/extract/error_tests.rs +25 -0
  90. package/src/extract/members.rs +210 -0
  91. package/src/extract/primary_constructors.rs +421 -0
  92. package/src/extract/references.rs +151 -0
  93. package/src/extract/routes.rs +691 -0
  94. package/src/extract/signatures.rs +266 -0
  95. package/src/extract/string_tests.rs +18 -0
  96. package/src/extract/strings.rs +107 -0
  97. package/src/extract/tests.rs +697 -0
  98. package/src/extract.rs +680 -0
  99. package/src/feature_flags/tests.rs +76 -0
  100. package/src/feature_flags.rs +453 -0
  101. package/src/finding_identity.rs +60 -0
  102. package/src/fix.rs +551 -0
  103. package/src/generated.rs +53 -0
  104. package/src/graph/augment_tests.rs +212 -0
  105. package/src/graph/conditionals.rs +74 -0
  106. package/src/graph/package_config_tests.rs +100 -0
  107. package/src/graph/parts.rs +248 -0
  108. package/src/graph/pubspec_tests.rs +119 -0
  109. package/src/graph/tests.rs +837 -0
  110. package/src/graph/uri_tests.rs +102 -0
  111. package/src/graph.rs +644 -0
  112. package/src/health/coverage.rs +309 -0
  113. package/src/health/ownership.rs +175 -0
  114. package/src/health/runtime_coverage.rs +616 -0
  115. package/src/health/runtime_intelligence.rs +511 -0
  116. package/src/health/scores.rs +296 -0
  117. package/src/health/tests.rs +240 -0
  118. package/src/health/threshold_types.rs +163 -0
  119. package/src/health/thresholds.rs +229 -0
  120. package/src/health/types.rs +636 -0
  121. package/src/health.rs +597 -0
  122. package/src/hooks/agent_settings.rs +175 -0
  123. package/src/hooks/templates.rs +51 -0
  124. package/src/hooks.rs +569 -0
  125. package/src/impact.rs +287 -0
  126. package/src/init.rs +237 -0
  127. package/src/inspect.rs +142 -0
  128. package/src/intelligence/tests.rs +232 -0
  129. package/src/intelligence.rs +305 -0
  130. package/src/lib.rs +198 -0
  131. package/src/main.rs +5 -0
  132. package/src/manifest/mcp.rs +565 -0
  133. package/src/manifest.rs +552 -0
  134. package/src/mcp/cli_args/value_args.rs +175 -0
  135. package/src/mcp/cli_args.rs +658 -0
  136. package/src/mcp/cli_args_tests.rs +522 -0
  137. package/src/mcp/code_execute.rs +671 -0
  138. package/src/mcp/tools.rs +660 -0
  139. package/src/mcp.rs +325 -0
  140. package/src/output/audit_risk.rs +135 -0
  141. package/src/output/dependency_findings.rs +327 -0
  142. package/src/output/duplication_findings.rs +114 -0
  143. package/src/output/feature_flag_findings.rs +122 -0
  144. package/src/output/format.rs +31 -0
  145. package/src/output/graph_findings.rs +461 -0
  146. package/src/output/health_findings.rs +612 -0
  147. package/src/output/human.rs +27 -0
  148. package/src/output/next_steps.rs +92 -0
  149. package/src/output/route_findings.rs +76 -0
  150. package/src/output/runtime_coverage.rs +515 -0
  151. package/src/output/scope.rs +183 -0
  152. package/src/output/security_findings.rs +390 -0
  153. package/src/output/security_sarif.rs +150 -0
  154. package/src/output/suppressions.rs +323 -0
  155. package/src/output/symbol_findings.rs +257 -0
  156. package/src/output/tests.rs +114 -0
  157. package/src/output/types.rs +604 -0
  158. package/src/output/widget_findings.rs +213 -0
  159. package/src/output.rs +682 -0
  160. package/src/package_map.rs +495 -0
  161. package/src/policy/packs.rs +232 -0
  162. package/src/policy/tests.rs +134 -0
  163. package/src/policy.rs +640 -0
  164. package/src/project_list.rs +376 -0
  165. package/src/report_schema/inventory.rs +418 -0
  166. package/src/report_schema.rs +488 -0
  167. package/src/routes.rs +354 -0
  168. package/src/scan/tests.rs +250 -0
  169. package/src/scan.rs +275 -0
  170. package/src/security/detect.rs +639 -0
  171. package/src/security/tests.rs +178 -0
  172. package/src/security.rs +373 -0
  173. package/src/security_gate.rs +555 -0
  174. package/src/symbols/path_filters.rs +27 -0
  175. package/src/symbols/private_type_leaks.rs +125 -0
  176. package/src/symbols/riverpod.rs +113 -0
  177. package/src/symbols/tests.rs +692 -0
  178. package/src/symbols.rs +693 -0
  179. package/src/trace/tests.rs +225 -0
  180. package/src/trace.rs +690 -0
  181. package/src/unsupported.rs +47 -0
  182. package/src/widgets/lifecycle.rs +484 -0
  183. package/src/widgets/params.rs +236 -0
  184. package/src/widgets/tests.rs +430 -0
  185. package/src/widgets/top_level.rs +110 -0
  186. package/src/widgets/unrendered.rs +374 -0
  187. package/src/widgets.rs +590 -0
  188. package/src/workspace_scope.rs +358 -0
@@ -0,0 +1,616 @@
1
+ use std::collections::{BTreeMap, BTreeSet};
2
+ use std::fs;
3
+ use std::path::{Path, PathBuf};
4
+
5
+ use serde_json::Value;
6
+
7
+ use crate::graph::normalize_against;
8
+ use crate::{ScannedProject, health::is_ignored_path};
9
+
10
+ use super::FunctionMetrics;
11
+ use super::runtime_intelligence::runtime_intelligence;
12
+ use super::types::{
13
+ HealthError, HealthOptions, LowTrafficThreshold, RuntimeCoverageConfidence,
14
+ RuntimeCoverageFinding, RuntimeCoverageFindingKind, RuntimeCoverageFormat,
15
+ RuntimeCoverageReport, RuntimeHotPath, SourceMapConfidence,
16
+ };
17
+
18
+ const FNV_OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
19
+ const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;
20
+
21
+ #[derive(Debug, Default)]
22
+ pub(super) struct RuntimeCoverageAccumulator {
23
+ pub(super) files: BTreeMap<PathBuf, RuntimeFileCoverage>,
24
+ pub(super) formats: BTreeSet<RuntimeCoverageFormat>,
25
+ pub(super) warnings: Vec<String>,
26
+ }
27
+
28
+ #[derive(Debug, Clone)]
29
+ pub(super) struct RuntimeFileCoverage {
30
+ pub(super) invocations: usize,
31
+ pub(super) source_map_confidence: SourceMapConfidence,
32
+ pub(super) functions: Vec<RuntimeFunctionCoverage>,
33
+ }
34
+
35
+ #[derive(Debug, Clone)]
36
+ pub(super) struct RuntimeFunctionCoverage {
37
+ pub(super) symbol: Option<String>,
38
+ pub(super) line: Option<usize>,
39
+ pub(super) invocations: usize,
40
+ }
41
+
42
+ pub(super) fn load_runtime_coverage(
43
+ project: &ScannedProject,
44
+ options: &HealthOptions,
45
+ functions: &[FunctionMetrics],
46
+ ) -> Result<Option<RuntimeCoverageReport>, HealthError> {
47
+ let Some(path) = &options.runtime_coverage_path else {
48
+ return Ok(None);
49
+ };
50
+ let source_path = normalize_against(&project.root, path);
51
+ let mut hash = FNV_OFFSET;
52
+ let mut accumulator = RuntimeCoverageAccumulator::default();
53
+ for file in runtime_coverage_files(&source_path)? {
54
+ let source =
55
+ fs::read_to_string(&file).map_err(|source| HealthError::ReadRuntimeCoverage {
56
+ path: file.clone(),
57
+ source,
58
+ })?;
59
+ update_hash(&mut hash, file.to_string_lossy().as_bytes());
60
+ update_hash(&mut hash, source.as_bytes());
61
+ parse_runtime_coverage_file(project, &file, &source, &mut accumulator)?;
62
+ }
63
+
64
+ Ok(Some(build_report(
65
+ project,
66
+ options,
67
+ functions,
68
+ source_path,
69
+ hash,
70
+ accumulator,
71
+ )))
72
+ }
73
+
74
+ fn runtime_coverage_files(path: &Path) -> Result<Vec<PathBuf>, HealthError> {
75
+ if path.is_file() {
76
+ return Ok(vec![path.to_path_buf()]);
77
+ }
78
+ if !path.is_dir() {
79
+ return Err(HealthError::ReadRuntimeCoverage {
80
+ path: path.to_path_buf(),
81
+ source: std::io::Error::new(
82
+ std::io::ErrorKind::NotFound,
83
+ "runtime coverage path was not found",
84
+ ),
85
+ });
86
+ }
87
+
88
+ let mut files = Vec::new();
89
+ collect_json_files(path, &mut files)?;
90
+ files.sort();
91
+ Ok(files)
92
+ }
93
+
94
+ fn collect_json_files(path: &Path, files: &mut Vec<PathBuf>) -> Result<(), HealthError> {
95
+ let entries = fs::read_dir(path).map_err(|source| HealthError::ReadRuntimeCoverage {
96
+ path: path.to_path_buf(),
97
+ source,
98
+ })?;
99
+ for entry in entries {
100
+ let entry = entry.map_err(|source| HealthError::ReadRuntimeCoverage {
101
+ path: path.to_path_buf(),
102
+ source,
103
+ })?;
104
+ let path = entry.path();
105
+ if path.is_dir() {
106
+ collect_json_files(&path, files)?;
107
+ } else if path
108
+ .extension()
109
+ .is_some_and(|extension| extension == "json")
110
+ {
111
+ files.push(path);
112
+ }
113
+ }
114
+ Ok(())
115
+ }
116
+
117
+ fn parse_runtime_coverage_file(
118
+ project: &ScannedProject,
119
+ path: &Path,
120
+ source: &str,
121
+ accumulator: &mut RuntimeCoverageAccumulator,
122
+ ) -> Result<(), HealthError> {
123
+ let value = serde_json::from_str::<Value>(source).map_err(|error| {
124
+ HealthError::ParseRuntimeCoverage {
125
+ path: path.to_path_buf(),
126
+ message: error.to_string(),
127
+ }
128
+ })?;
129
+
130
+ if is_v8_coverage(&value) {
131
+ accumulator.formats.insert(RuntimeCoverageFormat::V8);
132
+ parse_v8_coverage(project, &value, accumulator);
133
+ } else if is_istanbul_coverage(&value) {
134
+ accumulator.formats.insert(RuntimeCoverageFormat::Istanbul);
135
+ parse_istanbul_coverage(project, &value, accumulator);
136
+ } else {
137
+ accumulator.warnings.push(format!(
138
+ "{} did not look like V8 or Istanbul runtime coverage",
139
+ path.display()
140
+ ));
141
+ }
142
+ Ok(())
143
+ }
144
+
145
+ fn is_v8_coverage(value: &Value) -> bool {
146
+ value.get("result").is_some_and(Value::is_array)
147
+ || value.as_array().is_some_and(|items| {
148
+ items
149
+ .iter()
150
+ .any(|item| item.get("url").is_some() && item.get("functions").is_some())
151
+ })
152
+ }
153
+
154
+ fn is_istanbul_coverage(value: &Value) -> bool {
155
+ value.as_object().is_some_and(|coverage| {
156
+ coverage.values().any(|entry| {
157
+ entry.get("s").is_some()
158
+ || entry.get("statementMap").is_some()
159
+ || entry.get("fnMap").is_some()
160
+ })
161
+ })
162
+ }
163
+
164
+ fn parse_v8_coverage(
165
+ project: &ScannedProject,
166
+ value: &Value,
167
+ accumulator: &mut RuntimeCoverageAccumulator,
168
+ ) {
169
+ let scripts = value
170
+ .get("result")
171
+ .and_then(Value::as_array)
172
+ .or_else(|| value.as_array());
173
+ let Some(scripts) = scripts else {
174
+ return;
175
+ };
176
+
177
+ for script in scripts {
178
+ let Some(raw_path) = script.get("url").and_then(Value::as_str) else {
179
+ continue;
180
+ };
181
+ let Some((path, confidence)) = runtime_path(project, raw_path) else {
182
+ continue;
183
+ };
184
+ let functions = script
185
+ .get("functions")
186
+ .and_then(Value::as_array)
187
+ .into_iter()
188
+ .flatten()
189
+ .filter_map(|function| v8_function_coverage(&path, function))
190
+ .collect::<Vec<_>>();
191
+ let invocations = functions
192
+ .iter()
193
+ .map(|function| function.invocations)
194
+ .sum::<usize>();
195
+ if invocations > 0 {
196
+ add_file_coverage(accumulator, path, invocations, confidence, functions);
197
+ }
198
+ }
199
+ }
200
+
201
+ fn v8_function_coverage(path: &Path, function: &Value) -> Option<RuntimeFunctionCoverage> {
202
+ let ranges = function.get("ranges").and_then(Value::as_array)?;
203
+ let invocations = ranges
204
+ .iter()
205
+ .filter_map(|range| range.get("count"))
206
+ .map(value_count)
207
+ .max()
208
+ .unwrap_or(0);
209
+ if invocations == 0 {
210
+ return None;
211
+ }
212
+ let line = ranges
213
+ .first()
214
+ .and_then(|range| range.get("startOffset"))
215
+ .and_then(Value::as_u64)
216
+ .and_then(|offset| usize::try_from(offset).ok())
217
+ .and_then(|offset| line_for_offset(path, offset));
218
+ Some(RuntimeFunctionCoverage {
219
+ symbol: function
220
+ .get("functionName")
221
+ .and_then(Value::as_str)
222
+ .filter(|name| !name.is_empty())
223
+ .map(str::to_owned),
224
+ line,
225
+ invocations,
226
+ })
227
+ }
228
+
229
+ fn parse_istanbul_coverage(
230
+ project: &ScannedProject,
231
+ value: &Value,
232
+ accumulator: &mut RuntimeCoverageAccumulator,
233
+ ) {
234
+ let Some(entries) = value.as_object() else {
235
+ return;
236
+ };
237
+
238
+ for (key, entry) in entries {
239
+ let raw_path = entry.get("path").and_then(Value::as_str).unwrap_or(key);
240
+ let Some((path, confidence)) = runtime_path(project, raw_path) else {
241
+ continue;
242
+ };
243
+ let statement_invocations = entry
244
+ .get("s")
245
+ .and_then(Value::as_object)
246
+ .map_or(0, count_map_invocations);
247
+ let functions = istanbul_functions(entry);
248
+ let function_invocations = functions
249
+ .iter()
250
+ .map(|function| function.invocations)
251
+ .sum::<usize>();
252
+ let invocations = statement_invocations.max(function_invocations);
253
+ if invocations > 0 {
254
+ add_file_coverage(accumulator, path, invocations, confidence, functions);
255
+ }
256
+ }
257
+ }
258
+
259
+ fn istanbul_functions(entry: &Value) -> Vec<RuntimeFunctionCoverage> {
260
+ let Some(function_counts) = entry.get("f").and_then(Value::as_object) else {
261
+ return Vec::new();
262
+ };
263
+ let function_map = entry.get("fnMap").and_then(Value::as_object);
264
+ function_counts
265
+ .iter()
266
+ .filter_map(|(id, count)| {
267
+ let invocations = value_count(count);
268
+ if invocations == 0 {
269
+ return None;
270
+ }
271
+ let metadata = function_map.and_then(|items| items.get(id));
272
+ Some(RuntimeFunctionCoverage {
273
+ symbol: metadata
274
+ .and_then(|item| item.get("name"))
275
+ .and_then(Value::as_str)
276
+ .filter(|name| !name.is_empty())
277
+ .map(str::to_owned),
278
+ line: istanbul_line(metadata),
279
+ invocations,
280
+ })
281
+ })
282
+ .collect()
283
+ }
284
+
285
+ fn istanbul_line(metadata: Option<&Value>) -> Option<usize> {
286
+ metadata
287
+ .and_then(|item| item.get("decl").or_else(|| item.get("loc")))
288
+ .and_then(|location| location.get("start"))
289
+ .and_then(|start| start.get("line"))
290
+ .and_then(Value::as_u64)
291
+ .and_then(|line| usize::try_from(line).ok())
292
+ }
293
+
294
+ fn add_file_coverage(
295
+ accumulator: &mut RuntimeCoverageAccumulator,
296
+ path: PathBuf,
297
+ invocations: usize,
298
+ confidence: SourceMapConfidence,
299
+ functions: Vec<RuntimeFunctionCoverage>,
300
+ ) {
301
+ accumulator
302
+ .files
303
+ .entry(path)
304
+ .and_modify(|file| {
305
+ file.invocations += invocations;
306
+ file.source_map_confidence = best_confidence(file.source_map_confidence, confidence);
307
+ file.functions.extend(functions.clone());
308
+ })
309
+ .or_insert(RuntimeFileCoverage {
310
+ invocations,
311
+ source_map_confidence: confidence,
312
+ functions,
313
+ });
314
+ }
315
+
316
+ fn build_report(
317
+ project: &ScannedProject,
318
+ options: &HealthOptions,
319
+ functions: &[FunctionMetrics],
320
+ source_path: PathBuf,
321
+ source_hash: u64,
322
+ accumulator: RuntimeCoverageAccumulator,
323
+ ) -> RuntimeCoverageReport {
324
+ let total_invocations = accumulator
325
+ .files
326
+ .values()
327
+ .map(|file| file.invocations)
328
+ .sum::<usize>();
329
+ let hot_paths = hot_paths(&accumulator, options.min_invocations_hot);
330
+ let findings = runtime_findings(project, &accumulator, total_invocations, options);
331
+ let intelligence = runtime_intelligence(
332
+ project,
333
+ options,
334
+ functions,
335
+ &accumulator,
336
+ total_invocations,
337
+ &hot_paths,
338
+ &findings,
339
+ );
340
+
341
+ RuntimeCoverageReport {
342
+ source_path,
343
+ source_format: source_format(&accumulator.formats),
344
+ source_hash: format!("{source_hash:016x}"),
345
+ observed_files: accumulator.files.len(),
346
+ total_invocations,
347
+ min_invocations_hot: options.min_invocations_hot,
348
+ min_observation_volume: options.min_observation_volume,
349
+ low_traffic_threshold: options.low_traffic_threshold,
350
+ hot_paths,
351
+ findings,
352
+ coverage_intelligence: intelligence.coverage_intelligence,
353
+ blast_radius: intelligence.blast_radius,
354
+ importance: intelligence.importance,
355
+ warnings: accumulator.warnings,
356
+ }
357
+ }
358
+
359
+ fn source_format(formats: &BTreeSet<RuntimeCoverageFormat>) -> RuntimeCoverageFormat {
360
+ if formats.len() == 1 {
361
+ *formats
362
+ .iter()
363
+ .next()
364
+ .unwrap_or(&RuntimeCoverageFormat::Mixed)
365
+ } else {
366
+ RuntimeCoverageFormat::Mixed
367
+ }
368
+ }
369
+
370
+ fn hot_paths(
371
+ accumulator: &RuntimeCoverageAccumulator,
372
+ min_invocations_hot: usize,
373
+ ) -> Vec<RuntimeHotPath> {
374
+ let mut paths = Vec::new();
375
+ for (path, file) in &accumulator.files {
376
+ let mut file_hot_functions = file
377
+ .functions
378
+ .iter()
379
+ .filter(|function| function.invocations >= min_invocations_hot)
380
+ .map(|function| RuntimeHotPath {
381
+ path: path.clone(),
382
+ line: function.line,
383
+ symbol: function.symbol.clone(),
384
+ invocations: function.invocations,
385
+ source_map_confidence: file.source_map_confidence,
386
+ })
387
+ .collect::<Vec<_>>();
388
+ if file_hot_functions.is_empty() && file.invocations >= min_invocations_hot {
389
+ file_hot_functions.push(RuntimeHotPath {
390
+ path: path.clone(),
391
+ line: None,
392
+ symbol: None,
393
+ invocations: file.invocations,
394
+ source_map_confidence: file.source_map_confidence,
395
+ });
396
+ }
397
+ paths.extend(file_hot_functions);
398
+ }
399
+ paths.sort_by(|left, right| {
400
+ right
401
+ .invocations
402
+ .cmp(&left.invocations)
403
+ .then_with(|| left.path.cmp(&right.path))
404
+ .then_with(|| left.line.cmp(&right.line))
405
+ .then_with(|| left.symbol.cmp(&right.symbol))
406
+ });
407
+ paths
408
+ }
409
+
410
+ fn runtime_findings(
411
+ project: &ScannedProject,
412
+ accumulator: &RuntimeCoverageAccumulator,
413
+ total_invocations: usize,
414
+ options: &HealthOptions,
415
+ ) -> Vec<RuntimeCoverageFinding> {
416
+ let mut findings = low_traffic_findings(accumulator, total_invocations, options);
417
+ findings.extend(coverage_unavailable_findings(
418
+ project,
419
+ accumulator,
420
+ total_invocations,
421
+ options,
422
+ ));
423
+ findings.sort_by(|left, right| {
424
+ left.path
425
+ .cmp(&right.path)
426
+ .then_with(|| left.kind.cmp(&right.kind))
427
+ });
428
+ findings
429
+ }
430
+
431
+ fn low_traffic_findings(
432
+ accumulator: &RuntimeCoverageAccumulator,
433
+ total_invocations: usize,
434
+ options: &HealthOptions,
435
+ ) -> Vec<RuntimeCoverageFinding> {
436
+ if total_invocations == 0 {
437
+ return Vec::new();
438
+ }
439
+ accumulator
440
+ .files
441
+ .iter()
442
+ .filter_map(|(path, file)| {
443
+ let traffic = LowTrafficThreshold::from_fraction(file.invocations, total_invocations);
444
+ (traffic <= options.low_traffic_threshold).then(|| RuntimeCoverageFinding {
445
+ path: path.clone(),
446
+ kind: RuntimeCoverageFindingKind::LowTraffic,
447
+ line: 1,
448
+ invocations: file.invocations,
449
+ traffic_fraction: traffic,
450
+ safe_to_delete: false,
451
+ review_required: true,
452
+ confidence: observation_confidence(total_invocations, options),
453
+ reason: "runtime coverage observed this file below the low-traffic threshold"
454
+ .to_owned(),
455
+ })
456
+ })
457
+ .collect()
458
+ }
459
+
460
+ fn coverage_unavailable_findings(
461
+ project: &ScannedProject,
462
+ accumulator: &RuntimeCoverageAccumulator,
463
+ total_invocations: usize,
464
+ options: &HealthOptions,
465
+ ) -> Vec<RuntimeCoverageFinding> {
466
+ project
467
+ .files
468
+ .iter()
469
+ .map(|file| normalize_against(&project.root, &file.path))
470
+ .filter(|path| path.starts_with(&project.root) && !is_ignored_path(path))
471
+ .filter(|path| !accumulator.files.contains_key(path))
472
+ .map(|path| RuntimeCoverageFinding {
473
+ path,
474
+ kind: RuntimeCoverageFindingKind::CoverageUnavailable,
475
+ line: 1,
476
+ invocations: 0,
477
+ traffic_fraction: LowTrafficThreshold::from_ratio(0.0),
478
+ safe_to_delete: false,
479
+ review_required: true,
480
+ confidence: observation_confidence(total_invocations, options),
481
+ reason: "runtime coverage did not include this scanned Dart file".to_owned(),
482
+ })
483
+ .collect()
484
+ }
485
+
486
+ fn observation_confidence(
487
+ total_invocations: usize,
488
+ options: &HealthOptions,
489
+ ) -> RuntimeCoverageConfidence {
490
+ if total_invocations == 0 {
491
+ RuntimeCoverageConfidence::Low
492
+ } else if total_invocations >= options.min_observation_volume {
493
+ RuntimeCoverageConfidence::High
494
+ } else {
495
+ RuntimeCoverageConfidence::Medium
496
+ }
497
+ }
498
+
499
+ fn runtime_path(
500
+ project: &ScannedProject,
501
+ raw_path: &str,
502
+ ) -> Option<(PathBuf, SourceMapConfidence)> {
503
+ let decoded = decode_runtime_path(raw_path);
504
+ if decoded.is_empty() || !decoded.contains(".dart") {
505
+ return None;
506
+ }
507
+ let path = if let Some(rest) = decoded.strip_prefix("package:") {
508
+ let (_, package_path) = rest.split_once('/')?;
509
+ project.root.join("lib").join(package_path)
510
+ } else if let Some(rest) = decoded.strip_prefix("org-dartlang-app:///") {
511
+ project.root.join(rest.trim_start_matches('/'))
512
+ } else if let Some(rest) = decoded.strip_prefix("file://") {
513
+ PathBuf::from(rest)
514
+ } else if decoded.starts_with("http://") || decoded.starts_with("https://") {
515
+ let lib_path = decoded.split("/lib/").nth(1)?;
516
+ project.root.join("lib").join(lib_path)
517
+ } else {
518
+ PathBuf::from(&decoded)
519
+ };
520
+ let normalized = normalize_against(&project.root, &path);
521
+ let confidence = if normalized.starts_with(&project.root) && normalized.is_file() {
522
+ SourceMapConfidence::Resolved
523
+ } else if normalized.starts_with(&project.root) {
524
+ SourceMapConfidence::Fallback
525
+ } else {
526
+ SourceMapConfidence::Unresolved
527
+ };
528
+ Some((normalized, confidence))
529
+ }
530
+
531
+ fn decode_runtime_path(raw_path: &str) -> String {
532
+ let mut output = String::with_capacity(raw_path.len());
533
+ let mut bytes = raw_path.as_bytes().iter().copied();
534
+ while let Some(byte) = bytes.next() {
535
+ if byte == b'%' {
536
+ let high = bytes.next();
537
+ let low = bytes.next();
538
+ if let (Some(high), Some(low)) = (high, low)
539
+ && let Some(decoded) = decode_hex_pair(high, low)
540
+ {
541
+ output.push(char::from(decoded));
542
+ continue;
543
+ }
544
+ output.push('%');
545
+ if let Some(high) = high {
546
+ output.push(char::from(high));
547
+ }
548
+ if let Some(low) = low {
549
+ output.push(char::from(low));
550
+ }
551
+ } else {
552
+ output.push(char::from(byte));
553
+ }
554
+ }
555
+ output
556
+ }
557
+
558
+ fn decode_hex_pair(high: u8, low: u8) -> Option<u8> {
559
+ Some(hex_value(high)? * 16 + hex_value(low)?)
560
+ }
561
+
562
+ fn hex_value(byte: u8) -> Option<u8> {
563
+ match byte {
564
+ b'0'..=b'9' => Some(byte - b'0'),
565
+ b'a'..=b'f' => Some(byte - b'a' + 10),
566
+ b'A'..=b'F' => Some(byte - b'A' + 10),
567
+ _ => None,
568
+ }
569
+ }
570
+
571
+ fn count_map_invocations(values: &serde_json::Map<String, Value>) -> usize {
572
+ values.values().map(value_count).sum()
573
+ }
574
+
575
+ fn value_count(value: &Value) -> usize {
576
+ let count = value
577
+ .as_u64()
578
+ .or_else(|| value.as_i64().and_then(|count| u64::try_from(count).ok()))
579
+ .unwrap_or(0);
580
+ usize::try_from(count).unwrap_or(usize::MAX)
581
+ }
582
+
583
+ fn line_for_offset(path: &Path, offset: usize) -> Option<usize> {
584
+ let source = fs::read_to_string(path).ok()?;
585
+ let offset = offset.min(source.len());
586
+ Some(
587
+ source[..offset]
588
+ .bytes()
589
+ .filter(|byte| *byte == b'\n')
590
+ .count()
591
+ + 1,
592
+ )
593
+ }
594
+
595
+ fn best_confidence(left: SourceMapConfidence, right: SourceMapConfidence) -> SourceMapConfidence {
596
+ if confidence_rank(left) <= confidence_rank(right) {
597
+ left
598
+ } else {
599
+ right
600
+ }
601
+ }
602
+
603
+ const fn confidence_rank(confidence: SourceMapConfidence) -> usize {
604
+ match confidence {
605
+ SourceMapConfidence::Resolved => 0,
606
+ SourceMapConfidence::Fallback => 1,
607
+ SourceMapConfidence::Unresolved => 2,
608
+ }
609
+ }
610
+
611
+ fn update_hash(hash: &mut u64, bytes: &[u8]) {
612
+ for byte in bytes {
613
+ *hash ^= u64::from(*byte);
614
+ *hash = hash.wrapping_mul(FNV_PRIME);
615
+ }
616
+ }