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,118 @@
1
+ use std::collections::BTreeSet;
2
+
3
+ use crate::DartFile;
4
+
5
+ #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
6
+ pub(super) struct CodegenDependency {
7
+ pub(super) name: &'static str,
8
+ pub(super) production: bool,
9
+ }
10
+
11
+ pub(super) fn codegen_dependencies_for_file(file: &DartFile) -> BTreeSet<CodegenDependency> {
12
+ let signals = codegen_signals(file);
13
+ let mut dependencies = BTreeSet::new();
14
+
15
+ if signals.contains(&CodegenSignal::Freezed) {
16
+ dependencies.insert(dev_dependency("build_runner"));
17
+ dependencies.insert(dev_dependency("freezed"));
18
+ }
19
+ if signals.contains(&CodegenSignal::JsonSerializable) {
20
+ dependencies.insert(dev_dependency("build_runner"));
21
+ dependencies.insert(dev_dependency("json_serializable"));
22
+ dependencies.insert(production_dependency("json_annotation"));
23
+ }
24
+ if signals.contains(&CodegenSignal::Riverpod) {
25
+ dependencies.insert(dev_dependency("build_runner"));
26
+ dependencies.insert(dev_dependency("riverpod_generator"));
27
+ }
28
+ if signals.contains(&CodegenSignal::GoRouter) {
29
+ dependencies.insert(dev_dependency("build_runner"));
30
+ dependencies.insert(dev_dependency("go_router_builder"));
31
+ }
32
+
33
+ dependencies
34
+ }
35
+
36
+ #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
37
+ enum CodegenSignal {
38
+ Freezed,
39
+ JsonSerializable,
40
+ Riverpod,
41
+ GoRouter,
42
+ }
43
+
44
+ fn codegen_signals(file: &DartFile) -> BTreeSet<CodegenSignal> {
45
+ let imports = file
46
+ .imports
47
+ .iter()
48
+ .map(|import| import.uri.as_str())
49
+ .collect::<Vec<_>>();
50
+ let parts = file
51
+ .parts
52
+ .iter()
53
+ .map(|part| part.uri.as_str())
54
+ .collect::<Vec<_>>();
55
+ let references = file
56
+ .references
57
+ .iter()
58
+ .map(|reference| reference.name.as_str())
59
+ .collect::<Vec<_>>();
60
+ let mut signals = BTreeSet::new();
61
+
62
+ if imports.contains(&"package:freezed_annotation/freezed_annotation.dart")
63
+ || parts.iter().any(|part| part.ends_with(".freezed.dart"))
64
+ || references
65
+ .iter()
66
+ .any(|reference| matches!(*reference, "freezed" | "Freezed" | "unfreezed" | "With"))
67
+ {
68
+ signals.insert(CodegenSignal::Freezed);
69
+ }
70
+ if imports.contains(&"package:json_annotation/json_annotation.dart")
71
+ || parts.iter().any(|part| part.ends_with(".g.dart"))
72
+ || references.iter().any(|reference| {
73
+ matches!(
74
+ *reference,
75
+ "JsonSerializable" | "JsonKey" | "JsonEnum" | "JsonValue"
76
+ )
77
+ })
78
+ {
79
+ signals.insert(CodegenSignal::JsonSerializable);
80
+ }
81
+ if imports.contains(&"package:riverpod_annotation/riverpod_annotation.dart")
82
+ || parts.iter().any(|part| part.ends_with(".g.dart"))
83
+ && references
84
+ .iter()
85
+ .any(|reference| matches!(*reference, "riverpod" | "Riverpod"))
86
+ {
87
+ signals.insert(CodegenSignal::Riverpod);
88
+ }
89
+ if parts.iter().any(|part| part.ends_with(".g.dart"))
90
+ && references.iter().any(|reference| {
91
+ matches!(
92
+ *reference,
93
+ "TypedGoRoute"
94
+ | "TypedShellRoute"
95
+ | "TypedStatefulShellRoute"
96
+ | "TypedStatefulShellBranch"
97
+ )
98
+ })
99
+ {
100
+ signals.insert(CodegenSignal::GoRouter);
101
+ }
102
+
103
+ signals
104
+ }
105
+
106
+ const fn dev_dependency(name: &'static str) -> CodegenDependency {
107
+ CodegenDependency {
108
+ name,
109
+ production: false,
110
+ }
111
+ }
112
+
113
+ const fn production_dependency(name: &'static str) -> CodegenDependency {
114
+ CodegenDependency {
115
+ name,
116
+ production: true,
117
+ }
118
+ }
@@ -0,0 +1,60 @@
1
+ use std::fs;
2
+ use std::path::{Path, PathBuf};
3
+
4
+ use crate::graph::normalize_path;
5
+
6
+ use super::{DependencyHygieneError, PubPackage, read_package};
7
+
8
+ pub(super) fn discover_packages(root: &Path) -> Result<Vec<PubPackage>, DependencyHygieneError> {
9
+ let mut pubspecs = Vec::new();
10
+ discover_pubspecs(root, &mut pubspecs)?;
11
+ let mut packages = pubspecs
12
+ .into_iter()
13
+ .filter_map(|path| read_package(&path).transpose())
14
+ .collect::<Result<Vec<_>, _>>()?;
15
+ packages.sort_by(|left, right| left.root.cmp(&right.root));
16
+ Ok(packages)
17
+ }
18
+
19
+ fn discover_pubspecs(
20
+ dir: &Path,
21
+ pubspecs: &mut Vec<PathBuf>,
22
+ ) -> Result<(), DependencyHygieneError> {
23
+ let entries = fs::read_dir(dir).map_err(|source| DependencyHygieneError::ReadDir {
24
+ path: dir.to_path_buf(),
25
+ source,
26
+ })?;
27
+
28
+ for entry in entries {
29
+ let entry = entry.map_err(|source| DependencyHygieneError::ReadDirEntry {
30
+ path: dir.to_path_buf(),
31
+ source,
32
+ })?;
33
+ let path = entry.path();
34
+ let file_type = entry
35
+ .file_type()
36
+ .map_err(|source| DependencyHygieneError::FileType {
37
+ path: path.clone(),
38
+ source,
39
+ })?;
40
+
41
+ if file_type.is_dir() {
42
+ if should_skip_dir(&path) {
43
+ continue;
44
+ }
45
+ discover_pubspecs(&path, pubspecs)?;
46
+ } else if file_type.is_file() && path.file_name().is_some_and(|name| name == "pubspec.yaml")
47
+ {
48
+ pubspecs.push(normalize_path(&path));
49
+ }
50
+ }
51
+
52
+ Ok(())
53
+ }
54
+
55
+ pub(super) fn should_skip_dir(path: &Path) -> bool {
56
+ matches!(
57
+ path.file_name().and_then(|name| name.to_str()),
58
+ Some(".dart_tool" | ".git" | ".idea" | ".pub-cache" | "build" | "target")
59
+ )
60
+ }
@@ -0,0 +1,76 @@
1
+ use std::path::{Path, PathBuf};
2
+
3
+ use serde::{Deserialize, Serialize};
4
+ use serde_yaml_ng::Value;
5
+
6
+ use crate::Location;
7
+
8
+ use super::{
9
+ DependencySection, mapping_field, pubspec_document::dependency_location,
10
+ valid_dart_package_name,
11
+ };
12
+
13
+ /// A dependency override declaration that Pub cannot honor.
14
+ #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
15
+ pub struct MisconfiguredDependencyOverride {
16
+ /// Package declaring the override.
17
+ pub package: String,
18
+ /// Pubspec path that declares the override.
19
+ pub pubspec_path: PathBuf,
20
+ /// Raw override key from `dependency_overrides`.
21
+ pub raw_key: String,
22
+ /// Parsed package name when the key is syntactically valid.
23
+ pub dependency: Option<String>,
24
+ /// Reason the override is misconfigured.
25
+ pub reason: DependencyOverrideMisconfigReason,
26
+ /// Best-effort location of the override key in `pubspec.yaml`.
27
+ pub location: Location,
28
+ }
29
+
30
+ /// Dependency override misconfiguration reason.
31
+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
32
+ #[serde(rename_all = "kebab-case")]
33
+ pub enum DependencyOverrideMisconfigReason {
34
+ /// Override key is not a valid Dart package name.
35
+ UnparsableKey,
36
+ /// Override value is empty.
37
+ EmptyValue,
38
+ }
39
+
40
+ pub(super) fn misconfigured_dependency_overrides(
41
+ value: &Value,
42
+ source: &str,
43
+ package: &str,
44
+ pubspec_path: &Path,
45
+ ) -> Vec<MisconfiguredDependencyOverride> {
46
+ let Some(overrides) = mapping_field(value, "dependency_overrides") else {
47
+ return Vec::new();
48
+ };
49
+ overrides
50
+ .iter()
51
+ .filter_map(|(name, value)| {
52
+ let raw_key = name
53
+ .as_str()
54
+ .map_or_else(|| format!("{name:?}"), ToOwned::to_owned);
55
+ let reason = if !name.as_str().is_some_and(valid_dart_package_name) {
56
+ DependencyOverrideMisconfigReason::UnparsableKey
57
+ } else if value.is_null() {
58
+ DependencyOverrideMisconfigReason::EmptyValue
59
+ } else {
60
+ return None;
61
+ };
62
+ Some(MisconfiguredDependencyOverride {
63
+ package: package.to_owned(),
64
+ pubspec_path: pubspec_path.to_path_buf(),
65
+ dependency: name.as_str().map(ToOwned::to_owned),
66
+ location: dependency_location(
67
+ source,
68
+ DependencySection::DependencyOverrides,
69
+ &raw_key,
70
+ ),
71
+ raw_key,
72
+ reason,
73
+ })
74
+ })
75
+ .collect()
76
+ }
@@ -0,0 +1,32 @@
1
+ use std::path::PathBuf;
2
+
3
+ use serde::{Deserialize, Serialize};
4
+
5
+ use crate::{DependencyKind, Location};
6
+
7
+ /// A Dart import/export that reaches into another package's private `lib/src`.
8
+ #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
9
+ pub struct PrivateSrcImport {
10
+ /// Package containing the import/export.
11
+ pub package: String,
12
+ /// Pubspec path for the package containing the import/export.
13
+ pub pubspec_path: PathBuf,
14
+ /// Dart file containing the import/export.
15
+ pub path: PathBuf,
16
+ /// Imported package name.
17
+ pub dependency: String,
18
+ /// Import/export URI.
19
+ pub specifier: String,
20
+ /// Whether the dependency came from an import or export directive.
21
+ pub kind: DependencyKind,
22
+ /// Location of the import/export directive.
23
+ pub location: Location,
24
+ }
25
+
26
+ pub(super) fn imports_private_src(specifier: &str) -> bool {
27
+ specifier
28
+ .strip_prefix("package:")
29
+ .and_then(|rest| rest.split_once('/'))
30
+ .map(|(_, path)| path)
31
+ .is_some_and(|path| path == "src" || path.starts_with("src/"))
32
+ }
@@ -0,0 +1,86 @@
1
+ use std::path::Path;
2
+
3
+ use crate::Location;
4
+
5
+ use super::{DeclaredDependency, DependencySection, pubspec_entry};
6
+
7
+ pub(super) fn declared_dependencies_from_source(
8
+ source: &str,
9
+ source_path: &Path,
10
+ ) -> Vec<DeclaredDependency> {
11
+ let mut dependencies = Vec::new();
12
+ let mut current_section = None;
13
+
14
+ for (index, line) in source.lines().enumerate() {
15
+ let trimmed = line.trim_start();
16
+ let indent = line.len() - trimmed.len();
17
+
18
+ if indent == 0 {
19
+ current_section = match trimmed.trim_end() {
20
+ "dependencies:" => Some(DependencySection::Dependencies),
21
+ "dev_dependencies:" => Some(DependencySection::DevDependencies),
22
+ "dependency_overrides:" => Some(DependencySection::DependencyOverrides),
23
+ _ => None,
24
+ };
25
+ continue;
26
+ }
27
+
28
+ let Some(section) = current_section else {
29
+ continue;
30
+ };
31
+ if indent != 2 {
32
+ continue;
33
+ }
34
+ let Some((name, _)) = trimmed.split_once(':') else {
35
+ continue;
36
+ };
37
+ let name = name.trim();
38
+ if name.is_empty() {
39
+ continue;
40
+ }
41
+ let location = Location {
42
+ line: index + 1,
43
+ column: indent,
44
+ };
45
+ dependencies.push(DeclaredDependency {
46
+ name: name.to_owned(),
47
+ source_path: source_path.to_path_buf(),
48
+ section,
49
+ location,
50
+ safe_to_delete: pubspec_entry::is_simple_scalar_dependency(
51
+ source, section, name, location,
52
+ ),
53
+ });
54
+ }
55
+
56
+ dependencies
57
+ }
58
+
59
+ pub(super) fn dependency_location(
60
+ source: &str,
61
+ section: DependencySection,
62
+ dependency: &str,
63
+ ) -> Location {
64
+ let mut in_section = false;
65
+ for (index, line) in source.lines().enumerate() {
66
+ let trimmed = line.trim_start();
67
+ let indent = line.len() - trimmed.len();
68
+ if indent == 0 {
69
+ in_section = trimmed.trim_end() == format!("{}:", section.as_pubspec_key());
70
+ continue;
71
+ }
72
+ if in_section
73
+ && indent == 2
74
+ && trimmed
75
+ .split_once(':')
76
+ .is_some_and(|(key, _)| key.trim() == dependency)
77
+ {
78
+ return Location {
79
+ line: index + 1,
80
+ column: indent,
81
+ };
82
+ }
83
+ }
84
+
85
+ Location { line: 1, column: 0 }
86
+ }
@@ -0,0 +1,96 @@
1
+ use serde_yaml_ng::Value;
2
+
3
+ use super::DependencySection;
4
+ use crate::Location;
5
+
6
+ pub(super) fn is_simple_scalar_dependency(
7
+ source: &str,
8
+ section: DependencySection,
9
+ dependency: &str,
10
+ location: Location,
11
+ ) -> bool {
12
+ if !matches!(
13
+ section,
14
+ DependencySection::Dependencies | DependencySection::DevDependencies
15
+ ) {
16
+ return false;
17
+ }
18
+ let Some(index) = location.line.checked_sub(1) else {
19
+ return false;
20
+ };
21
+ let lines = source.split_inclusive('\n').collect::<Vec<_>>();
22
+ let Some(line) = lines.get(index) else {
23
+ return false;
24
+ };
25
+ if line.contains('#') {
26
+ return false;
27
+ }
28
+ let Ok(indent) = indentation(line) else {
29
+ return false;
30
+ };
31
+ if indent == 0 || enclosing_section(&lines, index, indent) != Some(section) {
32
+ return false;
33
+ }
34
+ let Some((key, value)) = line.trim().split_once(':') else {
35
+ return false;
36
+ };
37
+ key.trim() == dependency && is_safe_scalar_value(value.trim())
38
+ }
39
+
40
+ fn is_safe_scalar_value(value: &str) -> bool {
41
+ if value.is_empty()
42
+ || value.contains('{')
43
+ || value.contains('}')
44
+ || value.contains('[')
45
+ || value.contains(']')
46
+ || value.contains("path:")
47
+ || value.contains("git:")
48
+ || value.contains("sdk:")
49
+ {
50
+ return false;
51
+ }
52
+ serde_yaml_ng::from_str::<Value>(value)
53
+ .is_ok_and(|value| !matches!(value, Value::Mapping(_) | Value::Sequence(_) | Value::Null))
54
+ }
55
+
56
+ fn enclosing_section(
57
+ lines: &[&str],
58
+ index: usize,
59
+ target_indent: usize,
60
+ ) -> Option<DependencySection> {
61
+ for line in lines[..index].iter().rev() {
62
+ let trimmed = line.trim();
63
+ if trimmed.is_empty() || trimmed.starts_with('#') {
64
+ continue;
65
+ }
66
+ let indent = indentation(line).ok()?;
67
+ if indent >= target_indent {
68
+ continue;
69
+ }
70
+ if indent != 0 {
71
+ return None;
72
+ }
73
+ let (key, value) = trimmed.split_once(':')?;
74
+ if !value.trim().is_empty() {
75
+ return None;
76
+ }
77
+ return match key.trim() {
78
+ "dependencies" => Some(DependencySection::Dependencies),
79
+ "dev_dependencies" => Some(DependencySection::DevDependencies),
80
+ _ => None,
81
+ };
82
+ }
83
+ None
84
+ }
85
+
86
+ fn indentation(line: &str) -> Result<usize, ()> {
87
+ let mut spaces = 0;
88
+ for character in line.chars() {
89
+ match character {
90
+ ' ' => spaces += 1,
91
+ '\t' => return Err(()),
92
+ _ => return Ok(spaces),
93
+ }
94
+ }
95
+ Ok(spaces)
96
+ }