dart-decimate 0.0.9 → 0.0.11

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 (48) hide show
  1. package/Cargo.lock +1 -1
  2. package/Cargo.toml +1 -1
  3. package/README.md +50 -58
  4. package/package.json +1 -1
  5. package/src/cli/analyze.rs +6 -3
  6. package/src/cli/entry_points.rs +18 -2
  7. package/src/cli/list_run.rs +1 -0
  8. package/src/cli/tests.rs +74 -0
  9. package/src/config/rules.rs +50 -13
  10. package/src/dependencies/analyze.rs +7 -1
  11. package/src/dependencies/tests.rs +29 -0
  12. package/src/dependencies.rs +19 -0
  13. package/src/dependency_scripts.rs +2 -0
  14. package/src/dupes/declarations.rs +512 -0
  15. package/src/dupes/packages.rs +213 -0
  16. package/src/dupes/tests.rs +197 -0
  17. package/src/dupes.rs +57 -19
  18. package/src/extract/reference_tests.rs +106 -0
  19. package/src/extract/references.rs +264 -2
  20. package/src/extract/tests.rs +25 -0
  21. package/src/extract.rs +6 -3
  22. package/src/generated.rs +96 -3
  23. package/src/graph/package_config_tests.rs +123 -0
  24. package/src/graph/tests.rs +125 -0
  25. package/src/graph.rs +6 -5
  26. package/src/output/feature_flag_findings.rs +63 -1
  27. package/src/output/graph_findings.rs +73 -37
  28. package/src/output/route_cycle/aliases.rs +875 -0
  29. package/src/output/route_cycle/navigation.rs +1005 -0
  30. package/src/output/route_cycle/receivers.rs +41 -0
  31. package/src/output/route_cycle/state_context.rs +209 -0
  32. package/src/output/route_cycle/tests.rs +175 -0
  33. package/src/output/route_cycle.rs +730 -0
  34. package/src/output/security_findings.rs +15 -2
  35. package/src/output/tests.rs +104 -1
  36. package/src/output.rs +2 -1
  37. package/src/package_map.rs +220 -28
  38. package/src/routes.rs +6 -1
  39. package/src/scan.rs +15 -5
  40. package/src/security/detect.rs +140 -6
  41. package/src/security/tests.rs +96 -0
  42. package/src/trace.rs +1 -1
  43. package/src/widgets/forwarding.rs +684 -0
  44. package/src/widgets/patterns.rs +2595 -0
  45. package/src/widgets/reads.rs +616 -0
  46. package/src/widgets/tests.rs +1837 -55
  47. package/src/widgets/unrendered.rs +150 -0
  48. package/src/widgets.rs +25 -93
@@ -377,6 +377,131 @@ fn package_config_hosted_entries_remain_external() -> Result<(), Box<dyn std::er
377
377
  Ok(())
378
378
  }
379
379
 
380
+ #[test]
381
+ fn package_config_prevents_nested_same_name_fallback() -> Result<(), Box<dyn std::error::Error>> {
382
+ let fixture = Fixture::new()?;
383
+ fixture.write(
384
+ "pubspec.yaml",
385
+ "name: app\ndependencies:\n shared: ^1.0.0\n",
386
+ )?;
387
+ fixture.write("functions/a/shared/pubspec.yaml", "name: shared\n")?;
388
+ fixture.write(
389
+ ".dart_tool/package_config.json",
390
+ r#"{
391
+ "configVersion": 2,
392
+ "packages": [
393
+ {"name": "app", "rootUri": "../", "packageUri": "lib/"},
394
+ {"name": "shared", "rootUri": "file:///tmp/.pub-cache/hosted/shared-1.0.0", "packageUri": "lib/"}
395
+ ]
396
+ }
397
+ "#,
398
+ )?;
399
+ let main = fixture.file(
400
+ "lib/main.dart",
401
+ vec![import("package:shared/shared.dart")],
402
+ vec![],
403
+ );
404
+ let nested = fixture.file("functions/a/shared/lib/shared.dart", vec![], vec![]);
405
+
406
+ let graph = build_module_graph(fixture.root(), &[main, nested])?;
407
+
408
+ assert_eq!(graph.edge_count(), 0);
409
+ assert!(graph.unresolved().is_empty());
410
+
411
+ Ok(())
412
+ }
413
+
414
+ #[test]
415
+ fn package_config_owned_import_missing_from_config_ignores_nested_pubspec()
416
+ -> Result<(), Box<dyn std::error::Error>> {
417
+ let fixture = Fixture::new()?;
418
+ fixture.write("pubspec.yaml", "name: app\n")?;
419
+ fixture.write("functions/shared/pubspec.yaml", "name: shared\n")?;
420
+ fixture.write(
421
+ ".dart_tool/package_config.json",
422
+ r#"{
423
+ "configVersion": 2,
424
+ "packages": [
425
+ {"name": "app", "rootUri": "../", "packageUri": "lib/"}
426
+ ]
427
+ }
428
+ "#,
429
+ )?;
430
+ let main = fixture.file(
431
+ "lib/main.dart",
432
+ vec![import("package:shared/shared.dart")],
433
+ vec![],
434
+ );
435
+ let nested = fixture.file("functions/shared/lib/shared.dart", vec![], vec![]);
436
+
437
+ let graph = build_module_graph(fixture.root(), &[main, nested])?;
438
+
439
+ assert_eq!(graph.edge_count(), 0);
440
+ assert!(graph.unresolved().is_empty());
441
+
442
+ Ok(())
443
+ }
444
+
445
+ #[test]
446
+ fn package_config_ignores_malformed_unowned_nested_pubspec()
447
+ -> Result<(), Box<dyn std::error::Error>> {
448
+ let fixture = Fixture::new()?;
449
+ fixture.write("pubspec.yaml", "name: app\n")?;
450
+ fixture.write("fixtures/bad/pubspec.yaml", "name: [\n")?;
451
+ fixture.write(
452
+ ".dart_tool/package_config.json",
453
+ r#"{
454
+ "configVersion": 2,
455
+ "packages": [
456
+ {"name": "app", "rootUri": "../", "packageUri": "lib/"}
457
+ ]
458
+ }
459
+ "#,
460
+ )?;
461
+ let main = fixture.file("lib/main.dart", vec![], vec![]);
462
+
463
+ let graph = build_module_graph(fixture.root(), &[main])?;
464
+
465
+ assert_eq!(graph.package_names(), vec!["app"]);
466
+ assert_eq!(graph.edge_count(), 0);
467
+
468
+ Ok(())
469
+ }
470
+
471
+ #[test]
472
+ fn package_config_keeps_nested_self_imports_local() -> Result<(), Box<dyn std::error::Error>> {
473
+ let fixture = Fixture::new()?;
474
+ fixture.write("pubspec.yaml", "name: app\n")?;
475
+ fixture.write("functions/a/shared/pubspec.yaml", "name: shared\n")?;
476
+ fixture.write(
477
+ ".dart_tool/package_config.json",
478
+ r#"{
479
+ "configVersion": 2,
480
+ "packages": [
481
+ {"name": "app", "rootUri": "../", "packageUri": "lib/"},
482
+ {"name": "shared", "rootUri": "file:///tmp/.pub-cache/hosted/shared-1.0.0", "packageUri": "lib/"}
483
+ ]
484
+ }
485
+ "#,
486
+ )?;
487
+ let main = fixture.file(
488
+ "functions/a/shared/lib/main.dart",
489
+ vec![import("package:shared/src/foo.dart")],
490
+ vec![],
491
+ );
492
+ let foo = fixture.file("functions/a/shared/lib/src/foo.dart", vec![], vec![]);
493
+
494
+ let graph = build_module_graph(fixture.root(), &[main, foo])?;
495
+
496
+ assert_eq!(graph.edge_count(), 1);
497
+ assert_eq!(
498
+ strip_root(fixture.root(), &graph.dependencies()[0].to_path),
499
+ "functions/a/shared/lib/src/foo.dart"
500
+ );
501
+
502
+ Ok(())
503
+ }
504
+
380
505
  #[test]
381
506
  fn package_config_local_missing_target_is_unresolved() -> Result<(), Box<dyn std::error::Error>> {
382
507
  let fixture = Fixture::new()?;
package/src/graph.rs CHANGED
@@ -271,13 +271,14 @@ pub enum GraphError {
271
271
  /// Build a directed module graph from extracted Dart file facts.
272
272
  ///
273
273
  /// Local relative imports and exports are resolved from the source file's
274
- /// directory. `package:` imports resolve through local package names discovered
275
- /// from `pubspec.yaml` files, including pub workspaces and path dependencies.
274
+ /// directory. `package:` imports resolve through Pub package metadata,
275
+ /// including `.dart_tool/package_config.json`, workspaces, path dependencies,
276
+ /// same-package imports, and owner-local copied packages with duplicate names.
276
277
  ///
277
278
  /// # Errors
278
279
  ///
279
- /// Returns [`GraphError`] if a discovered `pubspec.yaml` cannot be read or
280
- /// parsed, or if a workspace glob entry is invalid.
280
+ /// Returns [`GraphError`] if package config or declared Pub package metadata
281
+ /// cannot be read or parsed, or if a workspace glob entry is invalid.
281
282
  pub fn build_module_graph(
282
283
  root: impl AsRef<Path>,
283
284
  files: &[DartFile],
@@ -547,7 +548,7 @@ pub(super) fn resolve_local_uri(
547
548
  let (package, path) = rest.split_once('/')?;
548
549
  let path = percent_decode_uri_path(path);
549
550
  return packages
550
- .resolve(package, &path)
551
+ .resolve_from(from_path, package, &path)
551
552
  .map(|resolution| ResolvedTarget {
552
553
  path: resolution.path,
553
554
  local: resolution.local,
@@ -86,7 +86,7 @@ fn feature_flag_finding(root: &Path, flag: &FeatureFlag) -> Finding {
86
86
  rule_id: "dart-decimate/feature-flag".to_owned(),
87
87
  fingerprint: Some(feature_flag_fingerprint(flag)),
88
88
  kind: FindingKind::FeatureFlag,
89
- severity: Severity::Error,
89
+ severity: feature_flag_severity(root, flag),
90
90
  message: format!(
91
91
  "Feature flag {} is referenced via {}",
92
92
  flag.name, flag.provider
@@ -111,6 +111,68 @@ fn feature_flag_finding(root: &Path, flag: &FeatureFlag) -> Finding {
111
111
  }
112
112
  }
113
113
 
114
+ fn feature_flag_severity(root: &Path, flag: &FeatureFlag) -> Severity {
115
+ if flag.source == FeatureFlagSource::CompileTimeEnvironment
116
+ && flag.occurrences.iter().all(|occurrence| {
117
+ let path = occurrence.path.as_path();
118
+ is_dev_or_test_path(root, path)
119
+ })
120
+ {
121
+ Severity::Warning
122
+ } else {
123
+ Severity::Error
124
+ }
125
+ }
126
+
127
+ fn is_dev_or_test_path(root: &Path, path: &Path) -> bool {
128
+ let relative = path.strip_prefix(root).unwrap_or(path);
129
+ let mut under_production_lib = false;
130
+ let mut saw_lib = false;
131
+ for component in relative
132
+ .components()
133
+ .filter_map(|component| component.as_os_str().to_str())
134
+ {
135
+ if matches!(
136
+ component,
137
+ "test"
138
+ | "tests"
139
+ | "integration_test"
140
+ | "test_driver"
141
+ | "tool"
142
+ | "scripts"
143
+ | "dev"
144
+ | "debug"
145
+ | "e2e"
146
+ | "example"
147
+ ) && !under_production_lib
148
+ {
149
+ return true;
150
+ }
151
+ if component == "lib" {
152
+ under_production_lib = true;
153
+ saw_lib = true;
154
+ }
155
+ }
156
+ if saw_lib {
157
+ return relative
158
+ .file_name()
159
+ .and_then(|file_name| file_name.to_str())
160
+ .is_some_and(is_non_production_flutter_entrypoint);
161
+ }
162
+ false
163
+ }
164
+
165
+ fn is_non_production_flutter_entrypoint(file_name: &str) -> bool {
166
+ matches!(
167
+ file_name,
168
+ "main_dev.dart"
169
+ | "main_debug.dart"
170
+ | "main_e2e.dart"
171
+ | "main_test.dart"
172
+ | "main_driver.dart"
173
+ )
174
+ }
175
+
114
176
  fn feature_flag_fingerprint(flag: &FeatureFlag) -> String {
115
177
  let text = format!("{}:{}:{}", flag.name, flag.provider, flag.source as u8);
116
178
  let mut hash = 0xcbf2_9ce4_8422_2325_u64;
@@ -1,4 +1,5 @@
1
1
  use super::format::{dependency_kind, display_path};
2
+ use super::route_cycle::is_typed_go_router_registry_cycle;
2
3
  use super::{Finding, FindingAction, FindingEdge, FindingKind, Severity};
3
4
  use crate::{
4
5
  BoundaryCallViolation, BoundaryCoverageGap, BoundaryViolation, DeadCodeReport, DependencyCycle,
@@ -52,37 +53,42 @@ pub(super) fn add_dead_code_findings(
52
53
  safe_to_delete: dead_file.safe_to_delete,
53
54
  files: Vec::new(),
54
55
  edge: None,
55
- actions: vec![
56
- FindingAction::new(
57
- "delete-file",
58
- "Delete the unreachable Dart file after confirming no dynamic entry point uses it",
59
- dead_file.safe_to_delete,
60
- )
61
- .with_target_path(path.clone())
62
- .with_dart_decimate_args(["inspect", "--format", "json", "--file", path.as_str()]),
63
- ],
56
+ actions: vec![FindingAction::new(
57
+ "delete-file",
58
+ "Delete the unreachable Dart file after confirming no dynamic entry point uses it",
59
+ dead_file.safe_to_delete,
60
+ )
61
+ .with_target_path(path.clone())
62
+ .with_dart_decimate_args([
63
+ "inspect",
64
+ "--format",
65
+ "json",
66
+ "--file",
67
+ path.as_str(),
68
+ ])],
64
69
  });
65
70
  }
66
71
  }
67
72
 
68
73
  pub(super) fn add_cycle_findings(
69
- root: &std::path::Path,
74
+ project: &ScannedProject,
70
75
  cycles: &[DependencyCycle],
71
76
  findings: &mut Vec<Finding>,
72
77
  ) {
73
78
  for cycle in cycles {
79
+ let classification = cycle_classification(project, cycle);
74
80
  let files = cycle
75
81
  .files
76
82
  .iter()
77
- .map(|path| display_path(root, path))
83
+ .map(|path| display_path(&project.root, path))
78
84
  .collect::<Vec<_>>();
79
85
  let path = files.first().cloned().unwrap_or_default();
80
86
  findings.push(Finding {
81
87
  rule_id: "dart-decimate/circular-dependency".to_owned(),
82
88
  fingerprint: None,
83
89
  kind: FindingKind::CircularDependency,
84
- severity: Severity::Error,
85
- message: format!("Circular dependency spans {} Dart files", files.len()),
90
+ severity: classification.severity,
91
+ message: classification.message(files.len()),
86
92
  path: path.clone(),
87
93
  line: 1,
88
94
  column: 0,
@@ -90,24 +96,56 @@ pub(super) fn add_cycle_findings(
90
96
  files,
91
97
  edge: None,
92
98
  actions: vec![
93
- FindingAction::new(
94
- "break-cycle",
95
- "Move shared dependencies inward or invert one import edge",
96
- false,
97
- )
98
- .with_target_path(path.clone())
99
- .with_dart_decimate_args([
100
- "inspect",
101
- "--format",
102
- "json",
103
- "--file",
104
- path.as_str(),
105
- ]),
99
+ FindingAction::new(classification.action, classification.description, false)
100
+ .with_target_path(path.clone())
101
+ .with_dart_decimate_args([
102
+ "inspect",
103
+ "--format",
104
+ "json",
105
+ "--file",
106
+ path.as_str(),
107
+ ]),
106
108
  ],
107
109
  });
108
110
  }
109
111
  }
110
112
 
113
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
114
+ struct CycleClassification {
115
+ severity: Severity,
116
+ action: &'static str,
117
+ description: &'static str,
118
+ route_registry: bool,
119
+ }
120
+
121
+ impl CycleClassification {
122
+ fn message(self, file_count: usize) -> String {
123
+ if self.route_registry {
124
+ format!("Typed GoRouter route registry cycle spans {file_count} Dart files")
125
+ } else {
126
+ format!("Circular dependency spans {file_count} Dart files")
127
+ }
128
+ }
129
+ }
130
+
131
+ fn cycle_classification(project: &ScannedProject, cycle: &DependencyCycle) -> CycleClassification {
132
+ if is_typed_go_router_registry_cycle(project, cycle) {
133
+ return CycleClassification {
134
+ severity: Severity::Warning,
135
+ action: "review-typed-route-cycle",
136
+ description: "Keep typed routes if this is only the route registry to screen navigation helper cycle; split unrelated imports out of the cycle",
137
+ route_registry: true,
138
+ };
139
+ }
140
+
141
+ CycleClassification {
142
+ severity: Severity::Error,
143
+ action: "break-cycle",
144
+ description: "Inspect the cycle edge; split barrels or move shared ownership before expanding imports",
145
+ route_registry: false,
146
+ }
147
+ }
148
+
111
149
  pub(super) fn add_re_export_cycle_findings(
112
150
  root: &std::path::Path,
113
151
  cycles: &[ReExportCycle],
@@ -251,17 +289,15 @@ pub(super) fn add_boundary_call_findings(
251
289
  safe_to_delete: false,
252
290
  files: vec![display_path(root, &violation.from_boundary)],
253
291
  edge: None,
254
- actions: vec![
255
- FindingAction::new(
256
- "repair-boundary-call",
257
- "Move the call behind an allowed boundary or replace it with an owned abstraction",
258
- false,
259
- )
260
- .with_target_path(path.clone())
261
- .with_config_key("boundary_calls")
262
- .with_value_schema("array of FROM:PATTERN forbidden direct call rules")
263
- .with_suppression_comment("// dart-decimate-ignore-next-line boundary-call-violation"),
264
- ],
292
+ actions: vec![FindingAction::new(
293
+ "repair-boundary-call",
294
+ "Move the call behind an allowed boundary or replace it with an owned abstraction",
295
+ false,
296
+ )
297
+ .with_target_path(path.clone())
298
+ .with_config_key("boundary_calls")
299
+ .with_value_schema("array of FROM:PATTERN forbidden direct call rules")
300
+ .with_suppression_comment("// dart-decimate-ignore-next-line boundary-call-violation")],
265
301
  });
266
302
  }
267
303
  }