dart-decimate 0.0.29 → 0.0.31

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 (70) hide show
  1. package/Cargo.lock +1 -1
  2. package/Cargo.toml +1 -1
  3. package/README.md +36 -60
  4. package/npm/bin/runner.js +26 -14
  5. package/npm/scripts/postinstall.js +89 -63
  6. package/package.json +3 -2
  7. package/src/baseline.rs +38 -0
  8. package/src/cli/health_args.rs +36 -7
  9. package/src/cli/html_open.rs +4 -0
  10. package/src/cli/issue_filter_args.rs +1 -0
  11. package/src/cli/security_summary_run.rs +1 -0
  12. package/src/config/health.rs +22 -2
  13. package/src/config/rule_aliases.rs +43 -0
  14. package/src/config/rules.rs +46 -1
  15. package/src/config.rs +2 -1
  16. package/src/dart_parser/test_support.rs +51 -0
  17. package/src/dart_parser.rs +8 -0
  18. package/src/dependencies/analyze.rs +3 -1
  19. package/src/dependencies/tests.rs +111 -7
  20. package/src/dependencies/usage.rs +5 -1
  21. package/src/dependencies.rs +7 -3
  22. package/src/explain/flutter_style.rs +43 -0
  23. package/src/explain/misc.rs +72 -0
  24. package/src/explain.rs +23 -67
  25. package/src/flutter_style/scanner.rs +883 -0
  26. package/src/flutter_style/types.rs +90 -0
  27. package/src/flutter_style/usage.rs +349 -0
  28. package/src/flutter_style.rs +72 -0
  29. package/src/generated.rs +154 -0
  30. package/src/health/large_units.rs +49 -0
  31. package/src/health/tests.rs +212 -1
  32. package/src/health/threshold_types.rs +31 -1
  33. package/src/health/thresholds.rs +49 -0
  34. package/src/health/types.rs +35 -0
  35. package/src/health.rs +72 -6
  36. package/src/inspect.rs +8 -0
  37. package/src/lib.rs +17 -5
  38. package/src/manifest.rs +7 -3
  39. package/src/output/dependency_findings.rs +14 -1
  40. package/src/output/flutter_style.rs +189 -0
  41. package/src/output/health_findings.rs +93 -10
  42. package/src/output/health_inventory.rs +121 -0
  43. package/src/output/html/tests.rs +20 -0
  44. package/src/output/html.rs +10 -1
  45. package/src/output/human.rs +85 -1
  46. package/src/output/human_details.rs +93 -12
  47. package/src/output/scope.rs +62 -2
  48. package/src/output/security_findings.rs +101 -76
  49. package/src/output/security_sarif.rs +24 -13
  50. package/src/output/suppressions.rs +4 -0
  51. package/src/output/types.rs +38 -2
  52. package/src/output/verdict.rs +12 -0
  53. package/src/output.rs +77 -74
  54. package/src/report_schema/inventory.rs +268 -4
  55. package/src/report_schema.rs +94 -60
  56. package/src/security/catalogue.rs +103 -0
  57. package/src/security/detect/weak_randomness.rs +762 -0
  58. package/src/security/detect.rs +1535 -221
  59. package/src/security/security_matchers.toml +172 -0
  60. package/src/security/tests.rs +336 -2
  61. package/src/security.rs +292 -56
  62. package/src/security_gate.rs +28 -0
  63. package/src/semantic.rs +276 -0
  64. package/src/symbols/semantic_evidence.rs +342 -0
  65. package/src/symbols.rs +20 -10
  66. package/src/trace/rendering.rs +54 -0
  67. package/src/trace/semantic.rs +126 -0
  68. package/src/trace.rs +54 -62
  69. package/src/widgets/inheritance.rs +63 -0
  70. package/src/widgets.rs +33 -3
@@ -17,6 +17,9 @@ pub struct HealthConfig {
17
17
  /// Maximum cognitive complexity before reporting.
18
18
  #[serde(default, alias = "maxCognitive")]
19
19
  pub max_cognitive: Option<usize>,
20
+ /// Maximum inclusive physical lines in one function-like declaration.
21
+ #[serde(default, alias = "maxUnitSize")]
22
+ pub max_unit_size: Option<usize>,
20
23
  /// Limit output to the N highest complexity findings.
21
24
  #[serde(default)]
22
25
  pub top: Option<usize>,
@@ -56,6 +59,9 @@ pub struct HealthConfig {
56
59
  /// Attach CODEOWNERS ownership metadata to health output.
57
60
  #[serde(default)]
58
61
  pub ownership: Option<bool>,
62
+ /// Include advisory Flutter theme/style analysis.
63
+ #[serde(default, alias = "flutterStyle")]
64
+ pub flutter_style: Option<bool>,
59
65
  /// Minimum file health score before hotspot reporting.
60
66
  #[serde(default, alias = "minScore")]
61
67
  pub min_score: Option<usize>,
@@ -76,7 +82,7 @@ impl HealthConfig {
76
82
  if !rule.has_threshold() {
77
83
  return Err(ConfigError::HealthThresholdOverride {
78
84
  index,
79
- message: "set maxCyclomatic, maxCognitive, or maxCrap".to_owned(),
85
+ message: "set maxCyclomatic, maxCognitive, maxCrap, or maxUnitSize".to_owned(),
80
86
  });
81
87
  }
82
88
  for pattern in &rule.files {
@@ -98,6 +104,9 @@ impl HealthConfig {
98
104
  if let Some(max_cognitive) = self.max_cognitive {
99
105
  options.max_cognitive = max_cognitive;
100
106
  }
107
+ if let Some(max_unit_size) = self.max_unit_size {
108
+ options.max_unit_size = max_unit_size;
109
+ }
101
110
  if self.top.is_some() {
102
111
  options.top = self.top;
103
112
  }
@@ -139,6 +148,9 @@ impl HealthConfig {
139
148
  if let Some(ownership) = self.ownership {
140
149
  options.ownership = ownership.into();
141
150
  }
151
+ if let Some(flutter_style) = self.flutter_style {
152
+ options.flutter_style = flutter_style.into();
153
+ }
142
154
  if let Some(min_score) = self.min_score {
143
155
  options.min_score = min_score.min(100);
144
156
  }
@@ -157,6 +169,8 @@ pub(super) fn health_schema() -> Value {
157
169
  "maxCyclomatic": positive_integer_schema(),
158
170
  "max_cognitive": positive_integer_schema(),
159
171
  "maxCognitive": positive_integer_schema(),
172
+ "max_unit_size": positive_integer_schema(),
173
+ "maxUnitSize": positive_integer_schema(),
160
174
  "top": positive_integer_schema(),
161
175
  "complexity_breakdown": { "type": "boolean" },
162
176
  "complexityBreakdown": { "type": "boolean" },
@@ -179,6 +193,8 @@ pub(super) fn health_schema() -> Value {
179
193
  "hotspots": { "type": "boolean" },
180
194
  "targets": { "type": "boolean" },
181
195
  "ownership": { "type": "boolean" },
196
+ "flutter_style": { "type": "boolean" },
197
+ "flutterStyle": { "type": "boolean" },
182
198
  "min_score": score_schema(),
183
199
  "minScore": score_schema(),
184
200
  "threshold_overrides": threshold_overrides_schema(),
@@ -212,7 +228,9 @@ fn threshold_overrides_schema() -> Value {
212
228
  { "required": ["max_cognitive"] },
213
229
  { "required": ["maxCognitive"] },
214
230
  { "required": ["max_crap"] },
215
- { "required": ["maxCrap"] }
231
+ { "required": ["maxCrap"] },
232
+ { "required": ["max_unit_size"] },
233
+ { "required": ["maxUnitSize"] }
216
234
  ],
217
235
  "properties": {
218
236
  "files": {
@@ -230,6 +248,8 @@ fn threshold_overrides_schema() -> Value {
230
248
  "maxCognitive": positive_integer_schema(),
231
249
  "max_crap": positive_integer_schema(),
232
250
  "maxCrap": positive_integer_schema(),
251
+ "max_unit_size": positive_integer_schema(),
252
+ "maxUnitSize": positive_integer_schema(),
233
253
  "reason": { "type": ["string", "null"] }
234
254
  }
235
255
  }
@@ -55,12 +55,23 @@ pub(super) fn aliases(rule_id: &str, kind: FindingKind) -> Vec<&'static str> {
55
55
  "security-plain-secret-storage",
56
56
  "plain-secret-storage",
57
57
  ],
58
+ "security-weak-randomness" => vec![
59
+ "dart-decimate/security-weak-randomness",
60
+ "security-weak-randomness",
61
+ "weak-randomness",
62
+ ],
58
63
  "unused-dev-dependency" => vec![
59
64
  "dart-decimate/unused-dev-dependency",
60
65
  "unused-dev-dependency",
61
66
  "unused-dev-dependencies",
62
67
  "unused-dev-deps",
63
68
  ],
69
+ "dev-dependency-in-production" => vec![
70
+ "dart-decimate/dev-dependency-in-production",
71
+ "dev-dependency-in-production",
72
+ "dev-dependencies-in-production",
73
+ "dev-deps-in-production",
74
+ ],
64
75
  "test-only-dependency" => vec![
65
76
  "dart-decimate/test-only-dependency",
66
77
  "test-only-dependency",
@@ -120,6 +131,9 @@ fn all_security_aliases() -> Vec<&'static str> {
120
131
  "dart-decimate/security-plain-secret-storage",
121
132
  "security-plain-secret-storage",
122
133
  "plain-secret-storage",
134
+ "dart-decimate/security-weak-randomness",
135
+ "security-weak-randomness",
136
+ "weak-randomness",
123
137
  ]
124
138
  .into()
125
139
  }
@@ -130,6 +144,10 @@ fn all_dependency_aliases() -> Vec<&'static str> {
130
144
  "unused-dev-dependency",
131
145
  "unused-dev-dependencies",
132
146
  "unused-dev-deps",
147
+ "dart-decimate/dev-dependency-in-production",
148
+ "dev-dependency-in-production",
149
+ "dev-dependencies-in-production",
150
+ "dev-deps-in-production",
133
151
  "dart-decimate/test-only-dependency",
134
152
  "test-only-dependency",
135
153
  "test-only-dependencies",
@@ -173,6 +191,7 @@ fn all_known_aliases() -> Vec<&'static str> {
173
191
  FindingKind::PartOfViolation,
174
192
  FindingKind::UnusedDependency,
175
193
  FindingKind::UnusedDevDependency,
194
+ FindingKind::DevDependencyInProduction,
176
195
  FindingKind::TestOnlyDependency,
177
196
  FindingKind::UnusedDependencyOverride,
178
197
  FindingKind::MisconfiguredDependencyOverride,
@@ -185,6 +204,9 @@ fn all_known_aliases() -> Vec<&'static str> {
185
204
  FindingKind::HighCrapScore,
186
205
  FindingKind::HealthHotspot,
187
206
  FindingKind::RefactoringTarget,
207
+ FindingKind::RawFlutterStyleValue,
208
+ FindingKind::NearDuplicateThemeToken,
209
+ FindingKind::UnusedThemeExtensionToken,
188
210
  FindingKind::FeatureFlag,
189
211
  FindingKind::SecurityCandidate,
190
212
  FindingKind::StaleSuppression,
@@ -380,6 +402,12 @@ fn dependency_kind_aliases(kind: FindingKind) -> Option<Vec<&'static str>> {
380
402
  "unused-dev-dependencies",
381
403
  "unused-dev-deps",
382
404
  ]),
405
+ FindingKind::DevDependencyInProduction => Some(vec![
406
+ "dart-decimate/dev-dependency-in-production",
407
+ "dev-dependency-in-production",
408
+ "dev-dependencies-in-production",
409
+ "dev-deps-in-production",
410
+ ]),
383
411
  FindingKind::TestOnlyDependency => Some(vec![
384
412
  "dart-decimate/test-only-dependency",
385
413
  "test-only-dependency",
@@ -478,6 +506,21 @@ fn quality_kind_aliases(kind: FindingKind) -> Option<Vec<&'static str>> {
478
506
  "target",
479
507
  "targets",
480
508
  ]),
509
+ FindingKind::RawFlutterStyleValue => Some(vec![
510
+ "dart-decimate/raw-flutter-style-value",
511
+ "raw-flutter-style-value",
512
+ "raw-flutter-style-values",
513
+ ]),
514
+ FindingKind::NearDuplicateThemeToken => Some(vec![
515
+ "dart-decimate/near-duplicate-theme-token",
516
+ "near-duplicate-theme-token",
517
+ "near-duplicate-theme-tokens",
518
+ ]),
519
+ FindingKind::UnusedThemeExtensionToken => Some(vec![
520
+ "dart-decimate/unused-theme-extension-token",
521
+ "unused-theme-extension-token",
522
+ "unused-theme-extension-tokens",
523
+ ]),
481
524
  FindingKind::FeatureFlag => Some(vec![
482
525
  "dart-decimate/feature-flag",
483
526
  "feature-flag",
@@ -93,6 +93,10 @@ pub fn apply_rules_to_report(report: &mut JsonReport, rules: &RuleConfig) -> Res
93
93
  FindingKind::RefactoringTarget,
94
94
  ) != RuleLevel::Off
95
95
  });
96
+ report.flutter_style.retain(|finding| {
97
+ style_finding_kind(&finding.kind)
98
+ .is_some_and(|kind| rules.level(&finding.rule_id, kind) != RuleLevel::Off)
99
+ });
96
100
  report.feature_flags.retain(|_| {
97
101
  rules.level("dart-decimate/feature-flag", FindingKind::FeatureFlag) != RuleLevel::Off
98
102
  });
@@ -120,6 +124,15 @@ pub fn apply_rules_to_report(report: &mut JsonReport, rules: &RuleConfig) -> Res
120
124
  Ok(())
121
125
  }
122
126
 
127
+ fn style_finding_kind(kind: &str) -> Option<FindingKind> {
128
+ match kind {
129
+ "raw-flutter-style-value" => Some(FindingKind::RawFlutterStyleValue),
130
+ "near-duplicate-theme-token" => Some(FindingKind::NearDuplicateThemeToken),
131
+ "unused-theme-extension-token" => Some(FindingKind::UnusedThemeExtensionToken),
132
+ _ => None,
133
+ }
134
+ }
135
+
123
136
  /// Error returned for invalid rule names.
124
137
  #[derive(Debug, thiserror::Error)]
125
138
  pub enum RuleError {
@@ -164,6 +177,9 @@ fn apply_security_candidate_level(
164
177
  }
165
178
 
166
179
  fn recompute_summary(report: &mut JsonReport) {
180
+ let raw_flutter_style_values = style_count(report, "raw-flutter-style-value");
181
+ let near_duplicate_theme_tokens = style_count(report, "near-duplicate-theme-token");
182
+ let unused_theme_extension_tokens = style_count(report, "unused-theme-extension-token");
167
183
  let summary = &mut report.summary;
168
184
  let previous_feature_flags = summary.feature_flags;
169
185
  let previous_feature_flag_occurrences = summary.feature_flag_occurrences;
@@ -175,6 +191,8 @@ fn recompute_summary(report: &mut JsonReport) {
175
191
  summary.unused_dependencies = dependency_count(&report.findings);
176
192
  summary.unused_dev_dependencies =
177
193
  kind_count(&report.findings, FindingKind::UnusedDevDependency);
194
+ summary.dev_dependencies_in_production =
195
+ kind_count(&report.findings, FindingKind::DevDependencyInProduction);
178
196
  summary.test_only_dependencies = kind_count(&report.findings, FindingKind::TestOnlyDependency);
179
197
  summary.dependency_overrides = dependency_override_count(&report.findings);
180
198
  summary.unused_dependency_overrides =
@@ -207,6 +225,18 @@ fn recompute_summary(report: &mut JsonReport) {
207
225
  );
208
226
  summary.code_duplications = report.clone_groups.len();
209
227
  summary.complex_functions = report.complexity.len();
228
+ summary.large_functions = report.large_functions.len();
229
+ summary.raw_flutter_style_values = raw_flutter_style_values;
230
+ summary.near_duplicate_theme_tokens = near_duplicate_theme_tokens;
231
+ summary.unused_theme_extension_tokens = unused_theme_extension_tokens;
232
+ summary.semantic_evidence = report
233
+ .semantic
234
+ .as_ref()
235
+ .map_or(0, |semantic| semantic.evidence.len());
236
+ summary.type_couplings = report
237
+ .semantic
238
+ .as_ref()
239
+ .map_or(0, |semantic| semantic.type_couplings.len());
210
240
  summary.coverage_gaps = kind_count(&report.findings, FindingKind::CoverageGap);
211
241
  summary.crap_functions = kind_count(&report.findings, FindingKind::HighCrapScore);
212
242
  summary.file_scores = report.file_scores.len();
@@ -233,6 +263,7 @@ fn recompute_summary(report: &mut JsonReport) {
233
263
  .map(|candidate| candidate.occurrences.len())
234
264
  .sum()
235
265
  };
266
+ summary.security_blind_spots = report.security_blind_spots.len();
236
267
  summary.attack_surface = report.attack_surface.len();
237
268
  summary.missing_entry_points = kind_count(&report.findings, FindingKind::MissingEntryPoint);
238
269
  summary.cycles = kind_count(&report.findings, FindingKind::CircularDependency);
@@ -247,6 +278,14 @@ fn recompute_summary(report: &mut JsonReport) {
247
278
  summary.findings = report.findings.len();
248
279
  }
249
280
 
281
+ fn style_count(report: &JsonReport, kind: &str) -> usize {
282
+ report
283
+ .flutter_style
284
+ .iter()
285
+ .filter(|finding| finding.kind == kind)
286
+ .count()
287
+ }
288
+
250
289
  fn kind_count(findings: &[Finding], kind: FindingKind) -> usize {
251
290
  findings
252
291
  .iter()
@@ -280,6 +319,7 @@ fn security_surface_enabled(entry: &JsonAttackSurfaceEntry, rules: &RuleMatcher)
280
319
  SecurityCategory::ProcessExecution => "dart-decimate/security-process-execution",
281
320
  SecurityCategory::RawSql => "dart-decimate/security-raw-sql",
282
321
  SecurityCategory::PlainSecretStorage => "dart-decimate/security-plain-secret-storage",
322
+ SecurityCategory::WeakRandomness => "dart-decimate/security-weak-randomness",
283
323
  };
284
324
  rules.level(rule_id, FindingKind::SecurityCandidate) != RuleLevel::Off
285
325
  }
@@ -348,9 +388,13 @@ impl<'a> RuleMatcher<'a> {
348
388
  fn default_rule_level(rule_id: &str, kind: FindingKind) -> RuleLevel {
349
389
  match kind {
350
390
  FindingKind::UnusedDependencyOverride
391
+ | FindingKind::DevDependencyInProduction
351
392
  | FindingKind::CodeDuplication
352
393
  | FindingKind::UnusedWidgetParam
353
- | FindingKind::UnrenderedWidget => RuleLevel::Warn,
394
+ | FindingKind::UnrenderedWidget
395
+ | FindingKind::RawFlutterStyleValue
396
+ | FindingKind::NearDuplicateThemeToken
397
+ | FindingKind::UnusedThemeExtensionToken => RuleLevel::Warn,
354
398
  FindingKind::SecurityCandidate
355
399
  if matches!(
356
400
  rule_id.as_bytes(),
@@ -376,6 +420,7 @@ const fn is_dependency_hygiene_kind(kind: FindingKind) -> bool {
376
420
  kind,
377
421
  FindingKind::UnusedDependency
378
422
  | FindingKind::UnusedDevDependency
423
+ | FindingKind::DevDependencyInProduction
379
424
  | FindingKind::TestOnlyDependency
380
425
  | FindingKind::UnusedDependencyOverride
381
426
  )
package/src/config.rs CHANGED
@@ -624,7 +624,8 @@ fn security_schema() -> Value {
624
624
  "web-view-risk",
625
625
  "process-execution",
626
626
  "raw-sql",
627
- "plain-secret-storage"
627
+ "plain-secret-storage",
628
+ "weak-randomness"
628
629
  ]
629
630
  },
630
631
  "uniqueItems": true
@@ -0,0 +1,51 @@
1
+ use std::collections::BTreeMap;
2
+ use std::path::{Path, PathBuf};
3
+ use std::sync::{Mutex, OnceLock};
4
+
5
+ static TRACKED_PARSE_COUNTS: OnceLock<Mutex<BTreeMap<PathBuf, usize>>> = OnceLock::new();
6
+
7
+ pub(crate) struct ParseCountGuard {
8
+ path: PathBuf,
9
+ }
10
+
11
+ impl ParseCountGuard {
12
+ pub(crate) fn count(&self) -> usize {
13
+ tracked_parse_counts_lock()
14
+ .get(&self.path)
15
+ .copied()
16
+ .unwrap_or(0)
17
+ }
18
+ }
19
+
20
+ impl Drop for ParseCountGuard {
21
+ fn drop(&mut self) {
22
+ tracked_parse_counts_lock().remove(&self.path);
23
+ }
24
+ }
25
+
26
+ pub(crate) fn track_parse_count(path: &Path) -> ParseCountGuard {
27
+ let path = path.to_path_buf();
28
+ let previous = tracked_parse_counts_lock().insert(path.clone(), 0);
29
+ assert!(
30
+ previous.is_none(),
31
+ "parse count already tracked for {path:?}"
32
+ );
33
+ ParseCountGuard { path }
34
+ }
35
+
36
+ pub(super) fn record_parse(path: &Path) {
37
+ if let Some(count) = tracked_parse_counts_lock().get_mut(path) {
38
+ *count += 1;
39
+ }
40
+ }
41
+
42
+ fn tracked_parse_counts() -> &'static Mutex<BTreeMap<PathBuf, usize>> {
43
+ TRACKED_PARSE_COUNTS.get_or_init(|| Mutex::new(BTreeMap::new()))
44
+ }
45
+
46
+ fn tracked_parse_counts_lock() -> std::sync::MutexGuard<'static, BTreeMap<PathBuf, usize>> {
47
+ match tracked_parse_counts().lock() {
48
+ Ok(guard) => guard,
49
+ Err(poisoned) => poisoned.into_inner(),
50
+ }
51
+ }
@@ -4,6 +4,11 @@ use std::path::{Path, PathBuf};
4
4
  use thiserror::Error;
5
5
  use tree_sitter::{Parser, Tree};
6
6
 
7
+ #[cfg(test)]
8
+ mod test_support;
9
+ #[cfg(test)]
10
+ pub(crate) use test_support::track_parse_count;
11
+
7
12
  /// Parsed Dart source and the source buffer used for the parse.
8
13
  ///
9
14
  /// Tree-Sitter node byte ranges are relative to this buffer, which may be a
@@ -104,6 +109,9 @@ pub(crate) fn parse_dart_source_lossy<'source>(
104
109
  }
105
110
 
106
111
  fn parse_raw(path: &Path, source: &str) -> Result<Tree, DartParseError> {
112
+ #[cfg(test)]
113
+ test_support::record_parse(path);
114
+
107
115
  let mut parser = Parser::new();
108
116
  parser.set_language(&tree_sitter_dart::LANGUAGE.into())?;
109
117
  parser
@@ -186,7 +186,9 @@ fn record_directive(
186
186
 
187
187
  record_dependency_usage(usage, owner, file_path, &dependency);
188
188
 
189
+ let declared_section = owner.declared_section(specifier);
189
190
  if !owner.declares_dependency_for_path(&dependency, file_path)
191
+ && declared_section != Some(super::DependencySection::DevDependencies)
190
192
  && !is_known_generated_internal_import(file_path, specifier)
191
193
  {
192
194
  usage
@@ -199,7 +201,7 @@ fn record_directive(
199
201
  dependency,
200
202
  specifier: specifier.to_owned(),
201
203
  kind,
202
- declared_section: owner.declared_section(specifier),
204
+ declared_section,
203
205
  location,
204
206
  });
205
207
  }
@@ -4,7 +4,7 @@ use std::path::Path;
4
4
  use tempfile::TempDir;
5
5
 
6
6
  use super::*;
7
- use crate::{DependencyKind, scan_project};
7
+ use crate::scan_project;
8
8
 
9
9
  #[test]
10
10
  fn parses_pubspec_dependency_keys_from_source() {
@@ -91,7 +91,7 @@ void main() {}\n",
91
91
  }
92
92
 
93
93
  #[test]
94
- fn reports_lib_import_declared_only_as_dev_dependency_as_unlisted()
94
+ fn reports_dev_dependency_used_from_lib_as_production_usage()
95
95
  -> Result<(), Box<dyn std::error::Error>> {
96
96
  let fixture = tempfile::tempdir()?;
97
97
  write(
@@ -109,17 +109,82 @@ dev_dependencies:\n collection: ^1.0.0\n",
109
109
 
110
110
  let report = analyze_dependency_hygiene(&project)?;
111
111
 
112
- assert_eq!(report.unlisted_dependencies.len(), 1);
113
- assert_eq!(report.unlisted_dependencies[0].dependency, "collection");
114
- assert_eq!(report.unlisted_dependencies[0].kind, DependencyKind::Import);
112
+ assert!(report.unlisted_dependencies.is_empty());
113
+ assert_eq!(report.unused_dependencies.len(), 1);
114
+ assert_eq!(report.unused_dependencies[0].dependency, "collection");
115
115
  assert_eq!(
116
- report.unlisted_dependencies[0].declared_section,
117
- Some(DependencySection::DevDependencies)
116
+ report.unused_dependencies[0].issue,
117
+ DependencyIssue::DevDependencyInProduction
118
+ );
119
+ assert!(!report.unused_dependencies[0].safe_to_delete);
120
+
121
+ Ok(())
122
+ }
123
+
124
+ #[test]
125
+ fn reports_dev_dependency_used_from_bin_as_production_usage()
126
+ -> Result<(), Box<dyn std::error::Error>> {
127
+ let fixture = tempfile::tempdir()?;
128
+ write(
129
+ &fixture,
130
+ "pubspec.yaml",
131
+ "name: app\n\
132
+ dev_dependencies:\n args: ^2.0.0\n",
133
+ )?;
134
+ write(
135
+ &fixture,
136
+ "bin/app.dart",
137
+ "import 'package:args/args.dart';\nvoid main() {}\n",
138
+ )?;
139
+ let project = scan_project(fixture.path())?;
140
+
141
+ let report = analyze_dependency_hygiene(&project)?;
142
+
143
+ assert!(report.unlisted_dependencies.is_empty());
144
+ assert_eq!(report.unused_dependencies.len(), 1);
145
+ assert_eq!(
146
+ report.unused_dependencies[0].issue,
147
+ DependencyIssue::DevDependencyInProduction
118
148
  );
119
149
 
120
150
  Ok(())
121
151
  }
122
152
 
153
+ #[test]
154
+ fn reports_dev_dependencies_used_from_dart_runtime_entrypoints()
155
+ -> Result<(), Box<dyn std::error::Error>> {
156
+ for (path, dependency) in [
157
+ ("web/main.dart", "web"),
158
+ ("hook/build.dart", "hooks"),
159
+ ("hook/link.dart", "native_toolchain_c"),
160
+ ] {
161
+ let fixture = tempfile::tempdir()?;
162
+ write(
163
+ &fixture,
164
+ "pubspec.yaml",
165
+ &format!("name: app\ndev_dependencies:\n {dependency}: ^1.0.0\n"),
166
+ )?;
167
+ write(
168
+ &fixture,
169
+ path,
170
+ &format!("import 'package:{dependency}/{dependency}.dart';\nvoid main() {{}}\n"),
171
+ )?;
172
+ let project = scan_project(fixture.path())?;
173
+
174
+ let report = analyze_dependency_hygiene(&project)?;
175
+
176
+ assert!(report.unlisted_dependencies.is_empty(), "{path}");
177
+ assert_eq!(report.unused_dependencies.len(), 1, "{path}");
178
+ assert_eq!(
179
+ report.unused_dependencies[0].issue,
180
+ DependencyIssue::DevDependencyInProduction,
181
+ "{path}"
182
+ );
183
+ }
184
+
185
+ Ok(())
186
+ }
187
+
123
188
  #[test]
124
189
  fn allows_test_imports_from_dev_dependencies() -> Result<(), Box<dyn std::error::Error>> {
125
190
  let fixture = tempfile::tempdir()?;
@@ -564,6 +629,45 @@ fn analyzes_workspace_packages_independently() -> Result<(), Box<dyn std::error:
564
629
  Ok(())
565
630
  }
566
631
 
632
+ #[test]
633
+ fn reports_dev_dependency_in_production_for_owning_workspace_package()
634
+ -> Result<(), Box<dyn std::error::Error>> {
635
+ let fixture = tempfile::tempdir()?;
636
+ write(
637
+ &fixture,
638
+ "pubspec.yaml",
639
+ "name: root\nworkspace:\n - packages/*\n",
640
+ )?;
641
+ write(
642
+ &fixture,
643
+ "packages/app/pubspec.yaml",
644
+ "name: app\ndev_dependencies:\n collection: ^1.0.0\n",
645
+ )?;
646
+ write(
647
+ &fixture,
648
+ "packages/app/lib/main.dart",
649
+ "import 'package:collection/collection.dart';\nvoid main() {}\n",
650
+ )?;
651
+ let project = scan_project(fixture.path())?;
652
+
653
+ let report = analyze_dependency_hygiene(&project)?;
654
+
655
+ assert!(report.unlisted_dependencies.is_empty());
656
+ assert_eq!(report.unused_dependencies.len(), 1);
657
+ assert_eq!(report.unused_dependencies[0].package, "app");
658
+ assert!(
659
+ report.unused_dependencies[0]
660
+ .pubspec_path
661
+ .ends_with("packages/app/pubspec.yaml")
662
+ );
663
+ assert_eq!(
664
+ report.unused_dependencies[0].issue,
665
+ DependencyIssue::DevDependencyInProduction
666
+ );
667
+
668
+ Ok(())
669
+ }
670
+
567
671
  fn write(fixture: &TempDir, path: &str, source: &str) -> Result<(), std::io::Error> {
568
672
  let path = fixture.path().join(path);
569
673
  if let Some(parent) = path.parent() {
@@ -28,6 +28,10 @@ pub(super) fn allows_dev_dependency(package_root: &Path, path: &Path) -> bool {
28
28
  let relative = path.strip_prefix(package_root).unwrap_or(path);
29
29
  !matches!(
30
30
  relative.components().next(),
31
- Some(std::path::Component::Normal(name)) if name == "lib" || name == "bin"
31
+ Some(std::path::Component::Normal(name))
32
+ if matches!(
33
+ name.to_str(),
34
+ Some("lib" | "bin" | "web" | "hook")
35
+ )
32
36
  )
33
37
  }
@@ -127,6 +127,8 @@ pub enum DependencyIssue {
127
127
  UnusedRuntimeDependency,
128
128
  /// Development dependency has no Dart import/export usage.
129
129
  UnusedDevDependency,
130
+ /// Development dependency is imported from production-owned Dart code.
131
+ DevDependencyInProduction,
130
132
  /// Runtime dependency is imported only from development-only files.
131
133
  TestOnlyDependency,
132
134
  /// Dependency override is absent from the resolved lockfile package graph.
@@ -328,9 +330,11 @@ fn dependency_issue(
328
330
  Some(usage) if usage.development => Some(DependencyIssue::TestOnlyDependency),
329
331
  Some(_) | None => Some(DependencyIssue::UnusedRuntimeDependency),
330
332
  },
331
- DependencySection::DevDependencies => usage
332
- .is_none()
333
- .then_some(DependencyIssue::UnusedDevDependency),
333
+ DependencySection::DevDependencies => match usage {
334
+ Some(usage) if usage.production => Some(DependencyIssue::DevDependencyInProduction),
335
+ Some(_) => None,
336
+ None => Some(DependencyIssue::UnusedDevDependency),
337
+ },
334
338
  DependencySection::DependencyOverrides => locked_packages.and_then(|locked| {
335
339
  (!locked.contains(&dependency.name))
336
340
  .then_some(DependencyIssue::UnusedDependencyOverride)
@@ -0,0 +1,43 @@
1
+ use super::IssueExplanation;
2
+
3
+ pub(super) const STYLE_ISSUES: &[IssueExplanation] = &[
4
+ issue!(
5
+ "raw-flutter-style-value",
6
+ "dart-decimate/raw-flutter-style-value",
7
+ &["raw-flutter-style-value", "raw-flutter-style-values"],
8
+ "Raw Flutter style value",
9
+ "A raw Color or TextStyle value has a resolvable project theme token.",
10
+ "Theme token use keeps visual intent consistent while allowing centralized changes.",
11
+ "A widget uses Color(0xFF112233) while colorScheme.primary is defined.",
12
+ "Review the nearest token evidence, then replace the raw value when its semantic role matches.",
13
+ &["// dart-decimate-ignore-next-line raw-flutter-style-value -- <reason>"],
14
+ &["dart-decimate health --format json --flutter-style"],
15
+ ),
16
+ issue!(
17
+ "near-duplicate-theme-token",
18
+ "dart-decimate/near-duplicate-theme-token",
19
+ &["near-duplicate-theme-token", "near-duplicate-theme-tokens"],
20
+ "Near-duplicate theme token",
21
+ "Two custom ThemeExtension color fields have near-identical ARGB values.",
22
+ "Nearly identical custom colors can indicate accidental token drift or duplicate semantic roles.",
23
+ "accent and accentSoft differ by one ARGB channel value.",
24
+ "Review both semantic roles before consolidating; Dart Decimate never replaces tokens automatically.",
25
+ &["// dart-decimate-ignore-next-line near-duplicate-theme-token -- <reason>"],
26
+ &["dart-decimate health --format json --flutter-style"],
27
+ ),
28
+ issue!(
29
+ "unused-theme-extension-token",
30
+ "dart-decimate/unused-theme-extension-token",
31
+ &[
32
+ "unused-theme-extension-token",
33
+ "unused-theme-extension-tokens"
34
+ ],
35
+ "Unused ThemeExtension token",
36
+ "A custom ThemeExtension field has no observed member access in included source.",
37
+ "Unused custom tokens increase design-system surface, but generated or dynamic consumers can remain invisible.",
38
+ "AppTokens.deprecatedAccent is declared and configured but never accessed.",
39
+ "Verify generated and dynamic consumers before removing the field.",
40
+ &["// dart-decimate-ignore-next-line unused-theme-extension-token -- <reason>"],
41
+ &["dart-decimate health --format json --flutter-style"],
42
+ ),
43
+ ];