@paretools/cargo 0.8.4 → 0.9.0

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 (53) hide show
  1. package/dist/lib/cargo-runner.d.ts +1 -1
  2. package/dist/lib/cargo-runner.d.ts.map +1 -1
  3. package/dist/lib/cargo-runner.js +2 -2
  4. package/dist/lib/cargo-runner.js.map +1 -1
  5. package/dist/lib/formatters.d.ts +29 -8
  6. package/dist/lib/formatters.d.ts.map +1 -1
  7. package/dist/lib/formatters.js +166 -45
  8. package/dist/lib/formatters.js.map +1 -1
  9. package/dist/lib/parsers.d.ts +78 -18
  10. package/dist/lib/parsers.d.ts.map +1 -1
  11. package/dist/lib/parsers.js +613 -60
  12. package/dist/lib/parsers.js.map +1 -1
  13. package/dist/schemas/index.d.ts +94 -9
  14. package/dist/schemas/index.d.ts.map +1 -1
  15. package/dist/schemas/index.js +88 -11
  16. package/dist/schemas/index.js.map +1 -1
  17. package/dist/tools/add.d.ts.map +1 -1
  18. package/dist/tools/add.js +71 -4
  19. package/dist/tools/add.js.map +1 -1
  20. package/dist/tools/audit.d.ts.map +1 -1
  21. package/dist/tools/audit.js +80 -4
  22. package/dist/tools/audit.js.map +1 -1
  23. package/dist/tools/build.d.ts.map +1 -1
  24. package/dist/tools/build.js +91 -2
  25. package/dist/tools/build.js.map +1 -1
  26. package/dist/tools/check.d.ts.map +1 -1
  27. package/dist/tools/check.js +84 -1
  28. package/dist/tools/check.js.map +1 -1
  29. package/dist/tools/clippy.d.ts.map +1 -1
  30. package/dist/tools/clippy.js +139 -3
  31. package/dist/tools/clippy.js.map +1 -1
  32. package/dist/tools/doc.d.ts.map +1 -1
  33. package/dist/tools/doc.js +81 -3
  34. package/dist/tools/doc.js.map +1 -1
  35. package/dist/tools/fmt.d.ts.map +1 -1
  36. package/dist/tools/fmt.js +66 -2
  37. package/dist/tools/fmt.js.map +1 -1
  38. package/dist/tools/remove.d.ts.map +1 -1
  39. package/dist/tools/remove.js +59 -4
  40. package/dist/tools/remove.js.map +1 -1
  41. package/dist/tools/run.d.ts.map +1 -1
  42. package/dist/tools/run.js +103 -3
  43. package/dist/tools/run.js.map +1 -1
  44. package/dist/tools/test.d.ts.map +1 -1
  45. package/dist/tools/test.js +108 -3
  46. package/dist/tools/test.js.map +1 -1
  47. package/dist/tools/tree.d.ts.map +1 -1
  48. package/dist/tools/tree.js +119 -9
  49. package/dist/tools/tree.js.map +1 -1
  50. package/dist/tools/update.d.ts.map +1 -1
  51. package/dist/tools/update.js +64 -5
  52. package/dist/tools/update.js.map +1 -1
  53. package/package.json +2 -2
@@ -1,14 +1,18 @@
1
1
  /**
2
2
  * Parses `cargo build --message-format=json` output.
3
3
  * Each line is a JSON object with a "reason" field.
4
- * We care about reason="compiler-message" entries.
4
+ * We care about reason="compiler-message" entries and the "build-finished" event.
5
+ * Gap #89: Uses build-finished event's success field as authoritative success indicator.
5
6
  */
6
7
  export function parseCargoBuildJson(stdout, exitCode) {
7
- const diagnostics = parseCompilerMessages(stdout);
8
+ const { diagnostics, buildFinishedSuccess } = parseCompilerMessages(stdout);
8
9
  const errors = diagnostics.filter((d) => d.severity === "error").length;
9
10
  const warnings = diagnostics.filter((d) => d.severity === "warning").length;
11
+ // Gap #89: Use build-finished event's success field when available,
12
+ // fall back to exit code
13
+ const success = buildFinishedSuccess !== undefined ? buildFinishedSuccess : exitCode === 0;
10
14
  return {
11
- success: exitCode === 0,
15
+ success,
12
16
  diagnostics,
13
17
  total: diagnostics.length,
14
18
  errors,
@@ -19,8 +23,13 @@ export function parseCargoBuildJson(stdout, exitCode) {
19
23
  * Parses `cargo test` output.
20
24
  * Format: "test name ... ok/FAILED/ignored"
21
25
  * Summary: "test result: ok/FAILED. X passed; Y failed; Z ignored"
26
+ *
27
+ * For failed tests, captures stdout/stderr output between the "failures:" section
28
+ * and the "failures:" name list or "test result:" line.
29
+ *
30
+ * Gap #95: Also parses JSON message format output for compilation diagnostics.
22
31
  */
23
- export function parseCargoTestOutput(stdout, exitCode) {
32
+ export function parseCargoTestOutput(stdout, exitCode, jsonOutput) {
24
33
  const lines = stdout.split("\n");
25
34
  const tests = [];
26
35
  for (const line of lines) {
@@ -32,10 +41,29 @@ export function parseCargoTestOutput(stdout, exitCode) {
32
41
  });
33
42
  }
34
43
  }
44
+ // Parse failure output sections.
45
+ // Cargo test output has a "failures:" section containing stdout/stderr for each failed test:
46
+ // failures:
47
+ //
48
+ // ---- tests::test_div stdout ----
49
+ // thread 'tests::test_div' panicked at 'assertion failed: ...'
50
+ // ...
51
+ //
52
+ // failures:
53
+ // tests::test_div
54
+ //
55
+ // We parse output blocks between "---- <name> stdout ----" markers.
56
+ const failureOutputMap = parseFailureOutputSections(stdout);
57
+ // Attach captured output to failed tests
58
+ for (const test of tests) {
59
+ if (test.status === "FAILED" && failureOutputMap.has(test.name)) {
60
+ test.output = failureOutputMap.get(test.name);
61
+ }
62
+ }
35
63
  const passed = tests.filter((t) => t.status === "ok").length;
36
64
  const failed = tests.filter((t) => t.status === "FAILED").length;
37
65
  const ignored = tests.filter((t) => t.status === "ignored").length;
38
- return {
66
+ const result = {
39
67
  success: exitCode === 0,
40
68
  tests,
41
69
  total: tests.length,
@@ -43,16 +71,75 @@ export function parseCargoTestOutput(stdout, exitCode) {
43
71
  failed,
44
72
  ignored,
45
73
  };
74
+ // Gap #95: Parse compilation diagnostics from JSON message format output
75
+ if (jsonOutput) {
76
+ const { diagnostics } = parseCompilerMessages(jsonOutput);
77
+ if (diagnostics.length > 0) {
78
+ result.compilationDiagnostics = diagnostics;
79
+ }
80
+ }
81
+ return result;
82
+ }
83
+ /**
84
+ * Extracts failure output sections from cargo test output.
85
+ * Looks for blocks starting with "---- <name> stdout ----" and ending at
86
+ * the next "---- " marker or "failures:" or "test result:" line.
87
+ * Returns a map of test name -> captured output.
88
+ */
89
+ function parseFailureOutputSections(stdout) {
90
+ const map = new Map();
91
+ const lines = stdout.split("\n");
92
+ let currentName = null;
93
+ let currentOutput = [];
94
+ for (const line of lines) {
95
+ // Match "---- tests::test_name stdout ----"
96
+ const headerMatch = line.match(/^---- (.+?) stdout ----$/);
97
+ if (headerMatch) {
98
+ // Save previous block if any
99
+ if (currentName !== null && currentOutput.length > 0) {
100
+ map.set(currentName, currentOutput.join("\n").trim());
101
+ }
102
+ currentName = headerMatch[1];
103
+ currentOutput = [];
104
+ continue;
105
+ }
106
+ // End markers: next section, failures list, or test result
107
+ if (currentName !== null) {
108
+ if (line.match(/^failures:/) ||
109
+ line.match(/^test result:/) ||
110
+ line.match(/^---- .+ stdout ----$/)) {
111
+ if (currentOutput.length > 0) {
112
+ map.set(currentName, currentOutput.join("\n").trim());
113
+ }
114
+ currentName = null;
115
+ currentOutput = [];
116
+ // Check if this line starts a new output section
117
+ const newHeader = line.match(/^---- (.+?) stdout ----$/);
118
+ if (newHeader) {
119
+ currentName = newHeader[1];
120
+ }
121
+ continue;
122
+ }
123
+ currentOutput.push(line);
124
+ }
125
+ }
126
+ // Save final block if any
127
+ if (currentName !== null && currentOutput.length > 0) {
128
+ map.set(currentName, currentOutput.join("\n").trim());
129
+ }
130
+ return map;
46
131
  }
47
132
  /**
48
133
  * Parses `cargo clippy --message-format=json` output.
49
- * Same JSON format as cargo build.
134
+ * Same JSON format as cargo build. Now includes success field.
135
+ * Gap #90: Captures suggestion text from JSON children.
50
136
  */
51
- export function parseCargoClippyJson(stdout) {
52
- const diagnostics = parseCompilerMessages(stdout);
137
+ export function parseCargoClippyJson(stdout, exitCode) {
138
+ const { diagnostics } = parseCompilerMessages(stdout);
53
139
  const errors = diagnostics.filter((d) => d.severity === "error").length;
54
140
  const warnings = diagnostics.filter((d) => d.severity === "warning").length;
55
141
  return {
142
+ success: exitCode === 0,
56
143
  diagnostics,
57
144
  total: diagnostics.length,
58
145
  errors,
@@ -62,71 +149,196 @@ export function parseCargoClippyJson(stdout) {
62
149
  /**
63
150
  * Parses `cargo run` output.
64
151
  * Returns exit code, stdout, stderr, and success flag.
152
+ * Optionally truncates stdout/stderr to maxOutputSize bytes.
153
+ * Gap #94: Distinguishes compilation vs runtime vs timeout failure.
65
154
  */
66
- export function parseCargoRunOutput(stdout, stderr, exitCode) {
67
- return {
155
+ export function parseCargoRunOutput(stdout, stderr, exitCode, maxOutputSize, timedOut) {
156
+ const limit = maxOutputSize ?? 0;
157
+ let stdoutTruncated = false;
158
+ let stderrTruncated = false;
159
+ let finalStdout = stdout;
160
+ let finalStderr = stderr;
161
+ if (limit > 0) {
162
+ if (stdout.length > limit) {
163
+ finalStdout = stdout.slice(0, limit);
164
+ stdoutTruncated = true;
165
+ }
166
+ if (stderr.length > limit) {
167
+ finalStderr = stderr.slice(0, limit);
168
+ stderrTruncated = true;
169
+ }
170
+ }
171
+ const result = {
68
172
  exitCode,
69
- stdout,
70
- stderr,
173
+ stdout: finalStdout,
174
+ stderr: finalStderr,
71
175
  success: exitCode === 0,
72
176
  };
177
+ // Gap #94: Determine failure type
178
+ if (exitCode !== 0) {
179
+ result.failureType = detectRunFailureType(stderr, exitCode, timedOut);
180
+ }
181
+ if (stdoutTruncated)
182
+ result.stdoutTruncated = true;
183
+ if (stderrTruncated)
184
+ result.stderrTruncated = true;
185
+ return result;
186
+ }
187
+ /**
188
+ * Detects whether a cargo run failure is a compilation error, runtime error, or timeout.
189
+ * Gap #94: Compilation errors have specific patterns from rustc.
190
+ */
191
+ export function detectRunFailureType(stderr, exitCode, timedOut) {
192
+ if (timedOut)
193
+ return "timeout";
194
+ // Compilation failure patterns from cargo/rustc
195
+ const compilationPatterns = [
196
+ /error\[E\d+\]/,
197
+ /could not compile/,
198
+ /aborting due to \d+ previous error/,
199
+ /^error: .+ not found/m,
200
+ /cannot find/,
201
+ ];
202
+ for (const pattern of compilationPatterns) {
203
+ if (pattern.test(stderr)) {
204
+ return "compilation";
205
+ }
206
+ }
207
+ // Exit code 101 is commonly used by cargo for compilation failures,
208
+ // but also by panics. If we didn't match compilation patterns, it's runtime.
209
+ return "runtime";
73
210
  }
74
211
  /**
75
- * Parses `cargo add` output.
212
+ * Parses `cargo add` output (including `--dry-run` mode).
76
213
  * Lines like: " Adding serde v1.0.217 to dependencies"
77
214
  * Also handles: " Adding serde v1.0.217 to dev-dependencies"
215
+ * Dry-run mode outputs the same Adding lines followed by:
216
+ * "warning: aborting add due to dry run"
217
+ * On failure, captures the error message.
218
+ *
219
+ * Gap #86: Accepts dependency type flags to include in output.
78
220
  */
79
- export function parseCargoAddOutput(stdout, stderr, exitCode) {
221
+ export function parseCargoAddOutput(stdout, stderr, exitCode, depType) {
80
222
  const combined = stdout + "\n" + stderr;
81
223
  const lines = combined.split("\n");
82
224
  const added = [];
225
+ // Detect dry-run mode from the cargo warning message
226
+ const isDryRun = /warning[:\s]*aborting add due to dry run/i.test(combined);
227
+ // Gap #86: Detect dependency type from output if not explicitly provided
228
+ let detectedType = depType;
83
229
  for (const line of lines) {
84
- const match = line.match(/Adding\s+(\S+)\s+v(\S+)\s+to\s+/);
85
- if (match) {
86
- added.push({ name: match[1], version: match[2] });
230
+ // Match both "Adding" (normal and dry-run) and "Updating" lines
231
+ const addMatch = line.match(/Adding\s+(\S+)\s+v(\S+)\s+to\s+(\S+)/);
232
+ if (addMatch) {
233
+ added.push({ name: addMatch[1], version: addMatch[2] });
234
+ // Detect type from "to dev-dependencies" / "to build-dependencies" / "to dependencies"
235
+ if (!depType) {
236
+ const target = addMatch[3];
237
+ if (target === "dev-dependencies")
238
+ detectedType = "dev";
239
+ else if (target === "build-dependencies")
240
+ detectedType = "build";
241
+ else if (target === "dependencies")
242
+ detectedType = "normal";
243
+ }
244
+ continue;
245
+ }
246
+ // Some cargo versions use "Updating" in dry-run output when a dep is already present
247
+ const updateMatch = line.match(/Updating\s+(\S+)\s+v\S+\s+->\s+v(\S+)/);
248
+ if (updateMatch) {
249
+ added.push({ name: updateMatch[1], version: updateMatch[2] });
87
250
  }
88
251
  }
89
- return {
252
+ const result = {
90
253
  success: exitCode === 0,
91
254
  added,
92
255
  total: added.length,
93
256
  };
257
+ if (detectedType) {
258
+ result.dependencyType = detectedType;
259
+ }
260
+ if (isDryRun) {
261
+ result.dryRun = true;
262
+ }
263
+ if (exitCode !== 0) {
264
+ // Extract error message from stderr, filtering out dry-run warnings
265
+ const errorLines = stderr
266
+ .split("\n")
267
+ .filter((l) => !/aborting add due to dry run/i.test(l))
268
+ .map((l) => l.replace(/^\s*error\s*:\s*/i, "").trim())
269
+ .filter(Boolean);
270
+ if (errorLines.length > 0) {
271
+ result.error = errorLines.join("; ");
272
+ }
273
+ }
274
+ return result;
94
275
  }
95
276
  /**
96
277
  * Parses `cargo remove` output.
97
278
  * Lines like: " Removing serde from dependencies"
279
+ * On failure, captures the error message.
280
+ *
281
+ * Gap #93: Accepts dependency type flags to include in output.
98
282
  */
99
- export function parseCargoRemoveOutput(stdout, stderr, exitCode) {
283
+ export function parseCargoRemoveOutput(stdout, stderr, exitCode, depType) {
100
284
  const combined = stdout + "\n" + stderr;
101
285
  const lines = combined.split("\n");
102
286
  const removed = [];
287
+ // Gap #93: Detect dependency type from output if not explicitly provided
288
+ let detectedType = depType;
103
289
  for (const line of lines) {
104
- const match = line.match(/Removing\s+(\S+)\s+from\s+/);
290
+ const match = line.match(/Removing\s+(\S+)\s+from\s+(\S+)/);
105
291
  if (match) {
106
292
  removed.push(match[1]);
293
+ // Detect type from "from dev-dependencies" / "from build-dependencies" / "from dependencies"
294
+ if (!depType) {
295
+ const target = match[2];
296
+ if (target === "dev-dependencies")
297
+ detectedType = "dev";
298
+ else if (target === "build-dependencies")
299
+ detectedType = "build";
300
+ else if (target === "dependencies")
301
+ detectedType = "normal";
302
+ }
107
303
  }
108
304
  }
109
- return {
305
+ const result = {
110
306
  success: exitCode === 0,
111
307
  removed,
112
308
  total: removed.length,
113
309
  };
310
+ if (detectedType) {
311
+ result.dependencyType = detectedType;
312
+ }
313
+ if (exitCode !== 0) {
314
+ const errorLines = stderr
315
+ .split("\n")
316
+ .map((l) => l.replace(/^\s*error\s*:\s*/i, "").trim())
317
+ .filter(Boolean);
318
+ if (errorLines.length > 0) {
319
+ result.error = errorLines.join("; ");
320
+ }
321
+ }
322
+ return result;
114
323
  }
115
324
  /**
116
- * Parses `cargo fmt --check` output.
117
- * In check mode, lists files with formatting differences (one path per line).
118
- * In fix mode, returns empty list (files are reformatted in place).
325
+ * Parses `cargo fmt` output in both check and fix (non-check) modes.
326
+ *
327
+ * Check mode: Gap #92 - uses --files-with-diff for more reliable file detection.
328
+ * Fix mode: parses file paths from `-- -l` (--files-with-diff) output, which lists
329
+ * files that were actually reformatted, one path per line on stdout.
119
330
  */
120
331
  export function parseCargoFmtOutput(stdout, stderr, exitCode, checkMode) {
121
332
  const files = [];
122
333
  if (checkMode) {
123
- // In check mode, cargo fmt --check outputs "Diff in <file>:" lines to stdout
124
- // or just lists file paths. It may also output raw diff lines.
334
+ // Gap #92: In check mode with --files-with-diff, the output contains
335
+ // file paths directly, one per line. Parse those first.
125
336
  const combined = stdout + "\n" + stderr;
126
337
  const lines = combined.split("\n");
127
338
  for (const line of lines) {
128
- // Match "Diff in <path> at line N:" format
129
- const diffMatch = line.match(/^Diff in (.+?) at line/);
339
+ const trimmed = line.trim();
340
+ // Match "Diff in <path> at line N:" format (legacy/verbose output)
341
+ const diffMatch = trimmed.match(/^Diff in (.+?) at line/);
130
342
  if (diffMatch) {
131
343
  const file = diffMatch[1];
132
344
  if (!files.includes(file)) {
@@ -134,12 +346,13 @@ export function parseCargoFmtOutput(stdout, stderr, exitCode, checkMode) {
134
346
  }
135
347
  continue;
136
348
  }
137
- // Some versions just list the file path directly
138
- const trimmed = line.trim();
349
+ // File paths from --files-with-diff or bare paths ending in .rs
139
350
  if (trimmed &&
140
351
  !trimmed.startsWith("+") &&
141
352
  !trimmed.startsWith("-") &&
142
353
  !trimmed.startsWith("@") &&
354
+ !trimmed.startsWith("warning") &&
355
+ !trimmed.startsWith("error") &&
143
356
  trimmed.endsWith(".rs")) {
144
357
  if (!files.includes(trimmed)) {
145
358
  files.push(trimmed);
@@ -147,8 +360,30 @@ export function parseCargoFmtOutput(stdout, stderr, exitCode, checkMode) {
147
360
  }
148
361
  }
149
362
  }
363
+ else {
364
+ // In fix mode with -l flag, rustfmt lists reformatted file paths on stdout,
365
+ // one per line. Parse those to report which files were actually changed.
366
+ const combined = stdout + "\n" + stderr;
367
+ const lines = combined.split("\n");
368
+ for (const line of lines) {
369
+ const trimmed = line.trim();
370
+ if (trimmed &&
371
+ !trimmed.startsWith("warning") &&
372
+ !trimmed.startsWith("error") &&
373
+ trimmed.endsWith(".rs")) {
374
+ if (!files.includes(trimmed)) {
375
+ files.push(trimmed);
376
+ }
377
+ }
378
+ }
379
+ }
380
+ // In check mode, exit code 1 with files means "needs formatting" (not a hard error).
381
+ // needsFormatting is true when check mode finds files that need formatting.
382
+ // In fix mode, needsFormatting is always false (files were already reformatted).
383
+ const needsFormatting = checkMode && (exitCode !== 0 || files.length > 0);
150
384
  return {
151
385
  success: exitCode === 0,
386
+ needsFormatting,
152
387
  filesChanged: files.length,
153
388
  files,
154
389
  };
@@ -157,73 +392,196 @@ export function parseCargoFmtOutput(stdout, stderr, exitCode, checkMode) {
157
392
  * Parses `cargo doc` output.
158
393
  * Counts "warning:" or "warning[" lines from stderr,
159
394
  * excluding the summary line "warning: N warnings emitted".
395
+ * Parses structured warning details with file location and message.
396
+ * Optionally extracts the output directory path.
160
397
  */
161
- export function parseCargoDocOutput(stderr, exitCode) {
398
+ export function parseCargoDocOutput(stderr, exitCode, cwd) {
162
399
  const lines = stderr.split("\n");
163
400
  let warnings = 0;
164
- for (const line of lines) {
401
+ const warningDetails = [];
402
+ for (let i = 0; i < lines.length; i++) {
403
+ const line = lines[i];
165
404
  if (line.match(/\bwarning\b(\[|:)/) && !line.match(/\d+ warnings? emitted/)) {
166
405
  warnings++;
406
+ // Extract the warning message from the line.
407
+ // Format: "warning: <message>" or "warning[E0599]: <message>"
408
+ const msgMatch = line.match(/\bwarning(?:\[[^\]]+\])?\s*:\s*(.+)/);
409
+ const message = msgMatch ? msgMatch[1].trim() : line.trim();
410
+ // Look ahead for a file location line like " --> src/lib.rs:10:1"
411
+ let file = "";
412
+ let lineNum = 0;
413
+ if (i + 1 < lines.length) {
414
+ const locMatch = lines[i + 1].match(/\s*-->\s+([^:]+):(\d+)/);
415
+ if (locMatch) {
416
+ file = locMatch[1];
417
+ lineNum = parseInt(locMatch[2], 10);
418
+ }
419
+ }
420
+ warningDetails.push({ file, line: lineNum, message });
167
421
  }
168
422
  }
169
- return {
423
+ const result = {
170
424
  success: exitCode === 0,
171
425
  warnings,
172
426
  };
427
+ if (warningDetails.length > 0) {
428
+ result.warningDetails = warningDetails;
429
+ }
430
+ // Report the doc output directory if available
431
+ if (cwd) {
432
+ result.outputDir = `${cwd}/target/doc`;
433
+ }
434
+ return result;
173
435
  }
174
436
  /**
175
437
  * Parses `cargo update` output.
176
- * Returns success flag and combined output text.
438
+ * Returns success flag, parsed updated packages, and combined output text.
439
+ *
440
+ * Cargo update outputs lines like:
441
+ * " Updating serde v1.0.200 -> v1.0.217"
442
+ * " Updating crates.io index"
443
+ * " Adding new-crate v1.0.0"
444
+ * " Removing old-crate v0.5.0"
445
+ * " Downgrading foo v2.0.0 -> v1.5.0"
446
+ * " Locking serde v1.0.200 -> v1.0.217" (newer cargo versions)
447
+ *
448
+ * Gap #96: Compact mode now includes updateCount instead of dropping all data.
177
449
  */
178
450
  export function parseCargoUpdateOutput(stdout, stderr, exitCode) {
179
451
  const output = (stdout + "\n" + stderr).trim();
452
+ const combined = stdout + "\n" + stderr;
453
+ const lines = combined.split("\n");
454
+ const updated = [];
455
+ for (const line of lines) {
456
+ // Match "Updating <name> v<from> -> v<to>" or "Locking <name> v<from> -> v<to>"
457
+ // or "Downgrading <name> v<from> -> v<to>"
458
+ const match = line.match(/(?:Updating|Locking|Downgrading)\s+(\S+)\s+v(\S+)\s+->\s+v(\S+)/);
459
+ if (match) {
460
+ updated.push({ name: match[1], from: match[2], to: match[3] });
461
+ }
462
+ }
180
463
  return {
181
464
  success: exitCode === 0,
465
+ updated,
466
+ totalUpdated: updated.length,
182
467
  output,
183
468
  };
184
469
  }
185
470
  /**
186
- * Parses `cargo tree` output.
187
- * Returns the full tree text and counts unique package names.
471
+ * Parses `cargo tree` output into structured dependency data.
472
+ * Returns the full tree text, a flat list of dependencies with depth,
473
+ * counts unique package names, and success flag.
474
+ *
475
+ * Tree lines use ASCII art prefixes to indicate depth:
476
+ * "my-app v0.1.0 (/path/to/project)" -> depth 0
477
+ * "├── serde v1.0.217" -> depth 1
478
+ * "│ └── serde_derive v1.0.217" -> depth 2
479
+ * "└── anyhow v1.0.89" -> depth 1
188
480
  */
189
- export function parseCargoTreeOutput(stdout) {
481
+ export function parseCargoTreeOutput(stdout, stderr, exitCode) {
482
+ if (exitCode !== 0) {
483
+ return {
484
+ success: false,
485
+ tree: stderr.trim() || undefined,
486
+ packages: 0,
487
+ };
488
+ }
190
489
  const tree = stdout.trim();
191
490
  const lines = tree.split("\n").filter(Boolean);
192
- // Extract unique package names from tree lines
193
- // Typical line: "my-app v0.1.0 (/path/to/project)" or "├── serde v1.0.217"
491
+ // Extract unique package names and structured dependency list
194
492
  const packageNames = new Set();
493
+ const dependencies = [];
195
494
  for (const line of lines) {
196
495
  // Match package name + version pattern like "name v1.2.3"
197
- const match = line.match(/([a-zA-Z0-9_-]+)\s+v\d+/);
496
+ const match = line.match(/([a-zA-Z0-9_-]+)\s+v(\d+[^\s]*)/);
198
497
  if (match) {
199
498
  packageNames.add(match[1]);
499
+ // Calculate depth from the tree indentation.
500
+ // Each level of depth is represented by 4 chars of tree drawing:
501
+ // depth 0: "name v1.0.0"
502
+ // depth 1: "├── name v1.0.0" or "└── name v1.0.0"
503
+ // depth 2: "│ ├── name v1.0.0" or "│ └── name v1.0.0"
504
+ // We find the position of the package name in the line.
505
+ const nameIndex = line.indexOf(match[1]);
506
+ // The prefix before the name contains tree-drawing characters.
507
+ // Each depth level is 4 characters wide (e.g., "├── " or "│ ")
508
+ // For depth 0, nameIndex is 0.
509
+ // For depth 1, nameIndex is 4 (after "├── ").
510
+ // For depth 2, nameIndex is 8 (after "│ ├── ").
511
+ const depth = nameIndex > 0 ? Math.round(nameIndex / 4) : 0;
512
+ dependencies.push({ name: match[1], version: match[2], depth });
200
513
  }
201
514
  }
202
515
  return {
516
+ success: true,
517
+ dependencies,
203
518
  tree,
204
519
  packages: packageNames.size,
205
520
  };
206
521
  }
207
522
  /**
208
- * Converts a CVSS v3 base score to a severity label.
523
+ * Converts a CVSS score (numeric string or v2/v3/v4 vector string) to a severity label.
209
524
  * See https://www.first.org/cvss/specification-document#Qualitative-Severity-Rating-Scale
525
+ *
526
+ * Supports:
527
+ * - Plain numeric scores: "9.8", "5.5", "0.0"
528
+ * - CVSS v3.x vector strings: "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H"
529
+ * - CVSS v2 vector strings: "(AV:N/AC:L/Au:N/C:C/I:C/A:C)"
210
530
  */
211
- function cvssToSeverity(cvss) {
531
+ export function cvssToSeverity(cvss) {
212
532
  if (!cvss)
213
533
  return "unknown";
214
- // Extract numeric score from CVSS vector or raw number
215
- let score;
216
- const vectorMatch = cvss.match(/CVSS:\d+\.\d+\/.*?$/);
217
- if (vectorMatch) {
218
- // Try to extract the base score from the end or use a simple heuristic
219
- // CVSS vectors don't embed the score directly; we need to look at AV/AC/etc.
220
- // However, cargo audit often provides the score separately or we parse from the vector.
221
- // In practice, cargo audit JSON may include a numeric score field too.
534
+ const trimmed = cvss.trim();
535
+ // Try CVSS v3.x vector string: "CVSS:3.0/..." or "CVSS:3.1/..."
536
+ const v3Match = trimmed.match(/^CVSS:3\.\d+\/(.*)/);
537
+ if (v3Match) {
538
+ const score = computeCvss3BaseScore(v3Match[1]);
539
+ if (score !== null)
540
+ return scoreToSeverity(score);
541
+ return "unknown";
542
+ }
543
+ // Try CVSS v2 vector string: "(AV:N/AC:L/Au:N/C:C/I:C/A:C)" or "AV:N/AC:L/..."
544
+ const v2Cleaned = trimmed.replace(/^\(|\)$/g, "");
545
+ if (/^AV:[NAL]\/AC:[HML]\/Au:[MSN]\/C:[NPC]\/I:[NPC]\/A:[NPC]/.test(v2Cleaned)) {
546
+ const score = computeCvss2BaseScore(v2Cleaned);
547
+ if (score !== null)
548
+ return scoreToSeverity(score);
222
549
  return "unknown";
223
550
  }
224
- score = parseFloat(cvss);
551
+ // Try plain numeric score
552
+ const score = parseFloat(trimmed);
225
553
  if (isNaN(score))
226
554
  return "unknown";
555
+ return scoreToSeverity(score);
556
+ }
557
+ /**
558
+ * Extracts a numeric CVSS score from a CVSS string.
559
+ * Gap #88: Used to populate cvssScore field in audit output.
560
+ */
561
+ export function extractCvssScore(cvss) {
562
+ if (!cvss)
563
+ return undefined;
564
+ const trimmed = cvss.trim();
565
+ // Try CVSS v3.x vector string
566
+ const v3Match = trimmed.match(/^CVSS:3\.\d+\/(.*)/);
567
+ if (v3Match) {
568
+ const score = computeCvss3BaseScore(v3Match[1]);
569
+ return score !== null ? score : undefined;
570
+ }
571
+ // Try CVSS v2 vector string
572
+ const v2Cleaned = trimmed.replace(/^\(|\)$/g, "");
573
+ if (/^AV:[NAL]\/AC:[HML]\/Au:[MSN]\/C:[NPC]\/I:[NPC]\/A:[NPC]/.test(v2Cleaned)) {
574
+ const score = computeCvss2BaseScore(v2Cleaned);
575
+ return score !== null ? score : undefined;
576
+ }
577
+ // Try plain numeric score
578
+ const score = parseFloat(trimmed);
579
+ return isNaN(score) ? undefined : score;
580
+ }
581
+ /**
582
+ * Maps a numeric CVSS score (0.0-10.0) to a severity label.
583
+ */
584
+ function scoreToSeverity(score) {
227
585
  if (score >= 9.0)
228
586
  return "critical";
229
587
  if (score >= 7.0)
@@ -234,27 +592,191 @@ function cvssToSeverity(cvss) {
234
592
  return "low";
235
593
  return "informational";
236
594
  }
595
+ /**
596
+ * Computes the CVSS v3 base score from a vector string (without the "CVSS:3.x/" prefix).
597
+ * Implements the CVSS v3.1 specification scoring equations.
598
+ * See https://www.first.org/cvss/v3.1/specification-document#7-4-Metric-Values
599
+ */
600
+ function computeCvss3BaseScore(vector) {
601
+ const metrics = parseVectorMetrics(vector);
602
+ // Required base metrics
603
+ const av = metrics["AV"];
604
+ const ac = metrics["AC"];
605
+ const pr = metrics["PR"];
606
+ const ui = metrics["UI"];
607
+ const s = metrics["S"];
608
+ const c = metrics["C"];
609
+ const i = metrics["I"];
610
+ const a = metrics["A"];
611
+ if (!av || !ac || !pr || !ui || !s || !c || !i || !a)
612
+ return null;
613
+ // Attack Vector
614
+ const avScores = { N: 0.85, A: 0.62, L: 0.55, P: 0.2 };
615
+ // Attack Complexity
616
+ const acScores = { L: 0.77, H: 0.44 };
617
+ // User Interaction
618
+ const uiScores = { N: 0.85, R: 0.62 };
619
+ // Confidentiality, Integrity, Availability Impact
620
+ const impactScores = { H: 0.56, L: 0.22, N: 0 };
621
+ // Privileges Required (depends on Scope)
622
+ const scopeChanged = s === "C";
623
+ const prScores = {
624
+ U: { N: 0.85, L: 0.62, H: 0.27 },
625
+ C: { N: 0.85, L: 0.68, H: 0.5 },
626
+ };
627
+ const avVal = avScores[av];
628
+ const acVal = acScores[ac];
629
+ const prVal = prScores[scopeChanged ? "C" : "U"]?.[pr];
630
+ const uiVal = uiScores[ui];
631
+ const cVal = impactScores[c];
632
+ const iVal = impactScores[i];
633
+ const aVal = impactScores[a];
634
+ if (avVal === undefined ||
635
+ acVal === undefined ||
636
+ prVal === undefined ||
637
+ uiVal === undefined ||
638
+ cVal === undefined ||
639
+ iVal === undefined ||
640
+ aVal === undefined) {
641
+ return null;
642
+ }
643
+ // ISS = 1 - [(1 - C) x (1 - I) x (1 - A)]
644
+ const iss = 1 - (1 - cVal) * (1 - iVal) * (1 - aVal);
645
+ // Impact
646
+ let impact;
647
+ if (scopeChanged) {
648
+ impact = 7.52 * (iss - 0.029) - 3.25 * Math.pow(iss - 0.02, 15);
649
+ }
650
+ else {
651
+ impact = 6.42 * iss;
652
+ }
653
+ if (impact <= 0)
654
+ return 0;
655
+ // Exploitability = 8.22 x AV x AC x PR x UI
656
+ const exploitability = 8.22 * avVal * acVal * prVal * uiVal;
657
+ let baseScore;
658
+ if (scopeChanged) {
659
+ baseScore = Math.min(1.08 * (impact + exploitability), 10);
660
+ }
661
+ else {
662
+ baseScore = Math.min(impact + exploitability, 10);
663
+ }
664
+ // Round up to 1 decimal place (CVSS rounding)
665
+ return roundUp(baseScore);
666
+ }
667
+ /**
668
+ * Computes the CVSS v2 base score from a vector string.
669
+ * Implements the simplified CVSS v2 specification scoring equations.
670
+ * See https://www.first.org/cvss/v2/guide#3-2-1-Base-Equation
671
+ */
672
+ function computeCvss2BaseScore(vector) {
673
+ const metrics = parseVectorMetrics(vector);
674
+ const av = metrics["AV"];
675
+ const ac = metrics["AC"];
676
+ const au = metrics["Au"];
677
+ const c = metrics["C"];
678
+ const i = metrics["I"];
679
+ const a = metrics["A"];
680
+ if (!av || !ac || !au || !c || !i || !a)
681
+ return null;
682
+ const avScores = { L: 0.395, A: 0.646, N: 1.0 };
683
+ const acScores = { H: 0.35, M: 0.61, L: 0.71 };
684
+ const auScores = { M: 0.45, S: 0.56, N: 0.704 };
685
+ const impactScores = { N: 0, P: 0.275, C: 0.66 };
686
+ const avVal = avScores[av];
687
+ const acVal = acScores[ac];
688
+ const auVal = auScores[au];
689
+ const cVal = impactScores[c];
690
+ const iVal = impactScores[i];
691
+ const aVal = impactScores[a];
692
+ if (avVal === undefined ||
693
+ acVal === undefined ||
694
+ auVal === undefined ||
695
+ cVal === undefined ||
696
+ iVal === undefined ||
697
+ aVal === undefined) {
698
+ return null;
699
+ }
700
+ const impact = 10.41 * (1 - (1 - cVal) * (1 - iVal) * (1 - aVal));
701
+ const exploitability = 20 * avVal * acVal * auVal;
702
+ const fImpact = impact === 0 ? 0 : 1.176;
703
+ const baseScore = (0.6 * impact + 0.4 * exploitability - 1.5) * fImpact;
704
+ return roundUp(Math.max(0, baseScore));
705
+ }
706
+ /**
707
+ * Parses a CVSS vector string into key-value metric pairs.
708
+ * Example: "AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H" -> {AV:"N", AC:"L", ...}
709
+ */
710
+ function parseVectorMetrics(vector) {
711
+ const metrics = {};
712
+ for (const part of vector.split("/")) {
713
+ const colonIdx = part.indexOf(":");
714
+ if (colonIdx > 0) {
715
+ metrics[part.substring(0, colonIdx)] = part.substring(colonIdx + 1);
716
+ }
717
+ }
718
+ return metrics;
719
+ }
720
+ /**
721
+ * Rounds up to 1 decimal place per CVSS specification.
722
+ * "If the value to be rounded has more than one decimal place, round up."
723
+ */
724
+ function roundUp(value) {
725
+ const rounded = Math.ceil(value * 10) / 10;
726
+ return rounded;
727
+ }
237
728
  /**
238
729
  * Parses `cargo audit --json` output.
239
- * Returns structured vulnerability data with severity summary.
730
+ * Returns structured vulnerability data with severity summary and success flag.
731
+ * Gap #87: Supports cargo audit fix with fixesApplied count.
732
+ * Gap #88: Includes raw CVSS score and vector string.
240
733
  */
241
- export function parseCargoAuditJson(jsonStr) {
242
- const data = JSON.parse(jsonStr);
243
- const vulnList = data.vulnerabilities?.list ?? [];
734
+ export function parseCargoAuditJson(jsonStr, exitCode, fixMode) {
735
+ let data;
736
+ try {
737
+ data = JSON.parse(jsonStr);
738
+ }
739
+ catch {
740
+ return {
741
+ success: false,
742
+ vulnerabilities: [],
743
+ summary: {
744
+ total: 0,
745
+ critical: 0,
746
+ high: 0,
747
+ medium: 0,
748
+ low: 0,
749
+ informational: 0,
750
+ unknown: 0,
751
+ },
752
+ };
753
+ }
754
+ const vulnData = data.vulnerabilities;
755
+ const vulnList = vulnData?.list ?? [];
244
756
  const vulnerabilities = vulnList.map((v) => {
245
757
  const advisory = v.advisory ?? {};
246
758
  const pkg = v.package ?? {};
247
759
  const versions = v.versions ?? {};
248
- return {
760
+ const entry = {
249
761
  id: advisory.id ?? "unknown",
250
762
  package: pkg.name ?? "unknown",
251
763
  version: pkg.version ?? "unknown",
252
764
  severity: cvssToSeverity(advisory.cvss),
253
765
  title: advisory.title ?? "Unknown vulnerability",
254
766
  url: advisory.url || undefined,
767
+ date: advisory.date || undefined,
255
768
  patched: versions.patched ?? [],
256
769
  unaffected: versions.unaffected ?? [],
257
770
  };
771
+ // Gap #88: Include raw CVSS score and vector
772
+ if (advisory.cvss) {
773
+ const score = extractCvssScore(advisory.cvss);
774
+ if (score !== undefined) {
775
+ entry.cvssScore = score;
776
+ }
777
+ entry.cvssVector = advisory.cvss;
778
+ }
779
+ return entry;
258
780
  });
259
781
  const summary = {
260
782
  total: vulnerabilities.length,
@@ -271,11 +793,29 @@ export function parseCargoAuditJson(jsonStr) {
271
793
  summary[sev]++;
272
794
  }
273
795
  }
274
- return { vulnerabilities, summary };
796
+ const result = {
797
+ success: exitCode === 0 || vulnerabilities.length === 0,
798
+ vulnerabilities,
799
+ summary,
800
+ };
801
+ // Gap #87: For fix mode, count fixes from patched vulnerabilities
802
+ if (fixMode) {
803
+ // In fix mode, cargo audit fix attempts to fix all vulnerabilities.
804
+ // The number of fixes is inferred from vulnerabilities that have patched versions.
805
+ const fixable = vulnerabilities.filter((v) => v.patched.length > 0).length;
806
+ result.fixesApplied = fixable;
807
+ }
808
+ return result;
275
809
  }
810
+ /**
811
+ * Parses compiler messages from JSON output.
812
+ * Gap #89: Extracts build-finished event's success field.
813
+ * Gap #90: Extracts suggestion text from children array.
814
+ */
276
815
  function parseCompilerMessages(stdout) {
277
816
  const lines = stdout.trim().split("\n").filter(Boolean);
278
817
  const diagnostics = [];
818
+ let buildFinishedSuccess;
279
819
  for (const line of lines) {
280
820
  let msg;
281
821
  try {
@@ -284,6 +824,11 @@ function parseCompilerMessages(stdout) {
284
824
  catch {
285
825
  continue;
286
826
  }
827
+ // Gap #89: Capture build-finished event's success field
828
+ if (msg.reason === "build-finished") {
829
+ buildFinishedSuccess = msg.success;
830
+ continue;
831
+ }
287
832
  if (msg.reason !== "compiler-message" || !msg.message)
288
833
  continue;
289
834
  const span = msg.message.spans[0];
@@ -292,15 +837,23 @@ function parseCompilerMessages(stdout) {
292
837
  const severity = (["error", "warning", "note", "help"].includes(msg.message.level)
293
838
  ? msg.message.level
294
839
  : "warning");
295
- diagnostics.push({
840
+ const diagnostic = {
296
841
  file: span.file_name,
297
842
  line: span.line_start,
298
843
  column: span.column_start,
299
844
  severity,
300
845
  code: msg.message.code?.code || undefined,
301
846
  message: msg.message.message,
302
- });
847
+ };
848
+ // Gap #90: Extract suggestion text from children array
849
+ if (msg.message.children && msg.message.children.length > 0) {
850
+ const helpChild = msg.message.children.find((c) => c.level === "help" || c.level === "suggestion");
851
+ if (helpChild && helpChild.message) {
852
+ diagnostic.suggestion = helpChild.message;
853
+ }
854
+ }
855
+ diagnostics.push(diagnostic);
303
856
  }
304
- return diagnostics;
857
+ return { diagnostics, buildFinishedSuccess };
305
858
  }
306
859
  //# sourceMappingURL=parsers.js.map