syncable-cli 0.37.1

A Rust-based CLI that analyzes code repositories and generates Infrastructure as Code configurations
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
use super::MutableLanguageVulnerabilityChecker;
use crate::analyzer::dependency_parser::{DependencyInfo, Language};
use crate::analyzer::runtime::{PackageManager, RuntimeDetector};
use crate::analyzer::tool_management::ToolDetector;
use crate::analyzer::vulnerability::{
    VulnerabilityError, VulnerabilityInfo, VulnerabilitySeverity, VulnerableDependency,
};
use log::{info, warn};
use serde_json::Value as JsonValue;
use std::path::Path;
use std::process::Command;

pub struct JavaScriptVulnerabilityChecker {
    tool_detector: ToolDetector,
}

impl Default for JavaScriptVulnerabilityChecker {
    fn default() -> Self {
        Self::new()
    }
}

impl JavaScriptVulnerabilityChecker {
    pub fn new() -> Self {
        Self {
            tool_detector: ToolDetector::new(),
        }
    }

    fn execute_audit_for_manager(
        &mut self,
        manager: &PackageManager,
        project_path: &Path,
        dependencies: &[DependencyInfo],
    ) -> Result<Option<Vec<VulnerableDependency>>, VulnerabilityError> {
        match manager {
            PackageManager::Bun => self.execute_bun_audit(project_path, dependencies),
            PackageManager::Npm => self.execute_npm_audit(project_path, dependencies),
            PackageManager::Yarn => self.execute_yarn_audit(project_path, dependencies),
            PackageManager::Pnpm => self.execute_pnpm_audit(project_path, dependencies),
            PackageManager::Unknown => Ok(None),
        }
    }

    fn execute_bun_audit(
        &mut self,
        project_path: &Path,
        dependencies: &[DependencyInfo],
    ) -> Result<Option<Vec<VulnerableDependency>>, VulnerabilityError> {
        // Check if bun is available
        let bun_status = self.tool_detector.detect_tool("bun");
        if !bun_status.available {
            warn!("bun not found, skipping bun audit");
            return Ok(None);
        }

        info!("Executing bun audit in {}", project_path.display());

        // Execute bun audit --json
        let output = Command::new("bun")
            .args(["audit", "--json"])
            .current_dir(project_path)
            .output()
            .map_err(|e| {
                VulnerabilityError::CommandError(format!("Failed to run bun audit: {}", e))
            })?;

        // bun audit returns non-zero exit code when vulnerabilities found
        // This is expected behavior, not an error
        if !output.status.success() && !output.stdout.is_empty() {
            info!("bun audit completed with findings");
        }

        if output.stdout.is_empty() {
            return Ok(None);
        }

        // Parse bun audit output
        let audit_data: serde_json::Value =
            serde_json::from_slice(&output.stdout).map_err(|e| {
                VulnerabilityError::ParseError(format!("Failed to parse bun audit output: {}", e))
            })?;

        self.parse_bun_audit_output(&audit_data, dependencies)
    }

    fn execute_npm_audit(
        &mut self,
        project_path: &Path,
        dependencies: &[DependencyInfo],
    ) -> Result<Option<Vec<VulnerableDependency>>, VulnerabilityError> {
        // Check if npm is available
        let npm_status = self.tool_detector.detect_tool("npm");
        if !npm_status.available {
            warn!("npm not found, skipping npm audit");
            return Ok(None);
        }

        info!("Executing npm audit in {}", project_path.display());

        // Execute npm audit --json
        let output = Command::new("npm")
            .args(["audit", "--json"])
            .current_dir(project_path)
            .output()
            .map_err(|e| {
                VulnerabilityError::CommandError(format!("Failed to run npm audit: {}", e))
            })?;

        // npm audit returns 0 even when vulnerabilities are found
        // Non-zero exit code indicates an actual error
        if !output.status.success() && output.stdout.is_empty() {
            return Err(VulnerabilityError::CommandError(format!(
                "npm audit failed with exit code {}: {}",
                output.status.code().unwrap_or(-1),
                String::from_utf8_lossy(&output.stderr)
            )));
        }

        if output.stdout.is_empty() {
            return Ok(None);
        }

        // Parse npm audit output
        let audit_data: serde_json::Value =
            serde_json::from_slice(&output.stdout).map_err(|e| {
                VulnerabilityError::ParseError(format!("Failed to parse npm audit output: {}", e))
            })?;

        self.parse_npm_audit_output(&audit_data, dependencies)
    }

    fn execute_yarn_audit(
        &mut self,
        project_path: &Path,
        dependencies: &[DependencyInfo],
    ) -> Result<Option<Vec<VulnerableDependency>>, VulnerabilityError> {
        // Check if yarn is available
        let yarn_status = self.tool_detector.detect_tool("yarn");
        if !yarn_status.available {
            warn!("yarn not found, skipping yarn audit");
            return Ok(None);
        }

        info!("Executing yarn audit in {}", project_path.display());

        // Strategy:
        // 1) Try Yarn Berry command: yarn npm audit --json (Yarn v2+)
        // 2) Fallback to classic: yarn audit --json (Yarn v1)
        // 3) Handle both single-JSON and line-delimited JSON formats
        let candidates: Vec<Vec<&str>> =
            vec![vec!["npm", "audit", "--json"], vec!["audit", "--json"]];

        for args in candidates {
            let output = match Command::new("yarn")
                .args(&args)
                .current_dir(project_path)
                .output()
            {
                Ok(o) => o,
                Err(e) => {
                    warn!("Failed to run 'yarn {}': {}", args.join(" "), e);
                    continue;
                }
            };

            // Non-zero with empty stdout is a hard failure; otherwise attempt to parse what we got
            if !output.status.success() && output.stdout.is_empty() {
                warn!(
                    "yarn {} failed (code {:?}): {}",
                    args.join(" "),
                    output.status.code(),
                    String::from_utf8_lossy(&output.stderr)
                );
                continue;
            }

            if output.stdout.is_empty() {
                // Nothing to parse
                continue;
            }

            // Try to parse as a single JSON blob first (be tolerant of banners/noise)
            if let Some(audit_data) = try_parse_json_tolerant(&output.stdout) {
                // If it looks like NPM's shape (common for `yarn npm audit`), reuse NPM parser
                if audit_data.get("vulnerabilities").is_some()
                    && let Ok(res) = self.parse_npm_audit_output(&audit_data, dependencies)
                    && res.is_some()
                {
                    return Ok(res);
                }

                // Otherwise try Yarn object shape
                if let Ok(res) = self.parse_yarn_audit_output(&audit_data, dependencies)
                    && res.is_some()
                {
                    return Ok(res);
                }
            } else if let Ok(res) =
                self.parse_yarn_streaming_audit_lines(&output.stdout, dependencies)
                && res.is_some()
            {
                // If not a single JSON, try line-delimited JSON format (Yarn v1 classic)
                return Ok(res);
            }
        }

        // If we got here, we couldn't parse Yarn output; don't fail the whole scan
        warn!("Unable to parse yarn audit output; skipping Yarn results");
        Ok(None)
    }

    fn execute_pnpm_audit(
        &mut self,
        project_path: &Path,
        dependencies: &[DependencyInfo],
    ) -> Result<Option<Vec<VulnerableDependency>>, VulnerabilityError> {
        // Check if pnpm is available
        let pnpm_status = self.tool_detector.detect_tool("pnpm");
        if !pnpm_status.available {
            warn!("pnpm not found, skipping pnpm audit");
            return Ok(None);
        }

        info!("Executing pnpm audit in {}", project_path.display());

        // Execute pnpm audit --json
        let output = Command::new("pnpm")
            .args(["audit", "--json"])
            .current_dir(project_path)
            .output()
            .map_err(|e| {
                VulnerabilityError::CommandError(format!("Failed to run pnpm audit: {}", e))
            })?;

        // pnpm audit behavior: returns 0 even when vulnerabilities are found
        // Non-zero exit code indicates an actual error
        if !output.status.success() && output.stdout.is_empty() {
            return Err(VulnerabilityError::CommandError(format!(
                "pnpm audit failed with exit code {}: {}",
                output.status.code().unwrap_or(-1),
                String::from_utf8_lossy(&output.stderr)
            )));
        }

        if output.stdout.is_empty() {
            return Ok(None);
        }

        // Parse pnpm audit output
        let audit_data: serde_json::Value =
            serde_json::from_slice(&output.stdout).map_err(|e| {
                VulnerabilityError::ParseError(format!("Failed to parse pnpm audit output: {}", e))
            })?;

        self.parse_pnpm_audit_output(&audit_data, dependencies)
    }

    fn parse_bun_audit_output(
        &self,
        audit_data: &serde_json::Value,
        dependencies: &[DependencyInfo],
    ) -> Result<Option<Vec<VulnerableDependency>>, VulnerabilityError> {
        let mut vulnerable_deps: Vec<VulnerableDependency> = Vec::new();

        // Bun audit JSON structure parsing
        // Bun returns a JSON object where keys are package names and values are arrays of vulnerabilities
        if let Some(obj) = audit_data.as_object() {
            for (package_name, vulnerabilities) in obj {
                if let Some(vuln_array) = vulnerabilities.as_array() {
                    // Include all vulnerable packages, not just direct dependencies
                    // Audit tools report on the entire dependency tree
                    let mut package_vulns = Vec::new();

                    for vulnerability in vuln_array {
                        // Extract vulnerability information
                        let id = vulnerability
                            .get("id")
                            .and_then(|i| i.as_u64())
                            .map(|id| id.to_string())
                            .unwrap_or("unknown".to_string());
                        let title = vulnerability
                            .get("title")
                            .and_then(|t| t.as_str())
                            .unwrap_or("Unknown vulnerability")
                            .to_string();
                        let description = vulnerability
                            .get("title")
                            .and_then(|t| t.as_str())
                            .unwrap_or("")
                            .to_string();
                        let severity = self
                            .parse_severity(vulnerability.get("severity").and_then(|s| s.as_str()));
                        let affected_versions = vulnerability
                            .get("vulnerable_versions")
                            .and_then(|v| v.as_str())
                            .unwrap_or("*")
                            .to_string();
                        let cwe = vulnerability
                            .get("cwe")
                            .and_then(|c| c.as_array())
                            .and_then(|arr| arr.first())
                            .and_then(|v| v.as_str())
                            .map(|s| s.to_string());
                        let url = vulnerability
                            .get("url")
                            .and_then(|u| u.as_str())
                            .map(|s| s.to_string());

                        let vuln_info = VulnerabilityInfo {
                            id,
                            vuln_type: "security".to_string(), // Security vulnerability
                            severity,
                            title,
                            description,
                            cve: cwe.clone(), // Using CWE as CVE for now
                            ghsa: url
                                .clone()
                                .filter(|u| u.contains("GHSA"))
                                .map(|u| u.split('/').next_back().unwrap_or(&u).to_string()),
                            affected_versions,
                            patched_versions: None, // Bun doesn't provide this directly
                            published_date: None,   // Bun audit may not provide this
                            references: url.map(|u| vec![u]).unwrap_or_default(),
                        };

                        package_vulns.push(vuln_info);
                    }

                    if !package_vulns.is_empty() {
                        // Try to find version from direct dependencies, otherwise use "transitive"
                        let version = dependencies
                            .iter()
                            .find(|d| d.name == *package_name)
                            .map(|d| d.version.clone())
                            .unwrap_or_else(|| "transitive".to_string());

                        vulnerable_deps.push(VulnerableDependency {
                            name: package_name.clone(),
                            version,
                            language: Language::JavaScript,
                            vulnerabilities: package_vulns,
                            source_dir: None,
                        });
                    }
                }
            }
        }

        if vulnerable_deps.is_empty() {
            Ok(None)
        } else {
            Ok(Some(vulnerable_deps))
        }
    }

    fn parse_npm_audit_output(
        &self,
        audit_data: &serde_json::Value,
        dependencies: &[DependencyInfo],
    ) -> Result<Option<Vec<VulnerableDependency>>, VulnerabilityError> {
        let mut vulnerable_deps: Vec<VulnerableDependency> = Vec::new();

        // NPM audit JSON structure parsing
        // NPM returns a JSON object with a "vulnerabilities" field containing package vulnerabilities
        if let Some(vulnerabilities) = audit_data
            .get("vulnerabilities")
            .and_then(|v| v.as_object())
        {
            for (package_name, vulnerability_info) in vulnerabilities {
                // Include all vulnerable packages, not just direct dependencies
                // Audit tools report on the entire dependency tree
                let mut package_vulns = Vec::new();

                // Get vulnerability details from the "via" array
                if let Some(via) = vulnerability_info.get("via").and_then(|v| v.as_array()) {
                    for advisory in via {
                        if let Some(advisory_obj) = advisory.as_object() {
                            // Skip if this is just a reference to another package
                            if advisory_obj.contains_key("source")
                                && !advisory_obj.contains_key("title")
                            {
                                continue;
                            }

                            let id = advisory_obj
                                .get("source")
                                .and_then(|s| s.as_u64())
                                .map(|id| id.to_string())
                                .or_else(|| {
                                    advisory_obj.get("url").and_then(|u| u.as_str()).and_then(
                                        |url| {
                                            if url.contains("GHSA") {
                                                url.rsplit('/').next().map(|s| s.to_string())
                                            } else {
                                                None
                                            }
                                        },
                                    )
                                })
                                .unwrap_or("unknown".to_string());

                            let title = advisory_obj
                                .get("title")
                                .and_then(|t| t.as_str())
                                .unwrap_or("Unknown vulnerability")
                                .to_string();
                            let description = title.clone();
                            let severity = self.parse_severity(
                                advisory_obj.get("severity").and_then(|s| s.as_str()),
                            );

                            let range = advisory_obj
                                .get("range")
                                .and_then(|r| r.as_str())
                                .unwrap_or("*")
                                .to_string();

                            let cwe = advisory_obj
                                .get("cwe")
                                .and_then(|c| c.as_array())
                                .and_then(|arr| arr.first())
                                .and_then(|v| v.as_str())
                                .map(|s| s.to_string());

                            let url = advisory_obj
                                .get("url")
                                .and_then(|u| u.as_str())
                                .map(|s| s.to_string());

                            let vuln_info = VulnerabilityInfo {
                                id,
                                vuln_type: "security".to_string(), // Security vulnerability
                                severity,
                                title,
                                description,
                                cve: cwe.clone(),
                                ghsa: url
                                    .clone()
                                    .filter(|u| u.contains("GHSA"))
                                    .map(|u| u.split('/').next_back().unwrap_or(&u).to_string()),
                                affected_versions: range,
                                patched_versions: None, // NPM doesn't provide this directly in via
                                published_date: None,
                                references: url.map(|u| vec![u]).unwrap_or_default(),
                            };

                            package_vulns.push(vuln_info);
                        }
                    }
                }

                if !package_vulns.is_empty() {
                    // Try to find version from direct dependencies, otherwise use "transitive"
                    let version = dependencies
                        .iter()
                        .find(|d| d.name == *package_name)
                        .map(|d| d.version.clone())
                        .unwrap_or_else(|| "transitive".to_string());

                    vulnerable_deps.push(VulnerableDependency {
                        name: package_name.clone(),
                        version,
                        language: Language::JavaScript,
                        vulnerabilities: package_vulns,
                        source_dir: None,
                    });
                }
            }
        }

        if vulnerable_deps.is_empty() {
            Ok(None)
        } else {
            Ok(Some(vulnerable_deps))
        }
    }

    fn parse_yarn_audit_output(
        &self,
        audit_data: &serde_json::Value,
        dependencies: &[DependencyInfo],
    ) -> Result<Option<Vec<VulnerableDependency>>, VulnerabilityError> {
        let mut vulnerable_deps: Vec<VulnerableDependency> = Vec::new();

        // Yarn audit JSON structure parsing
        // Shape 1: Single object with { data: { advisories: { id: {...} } } } (rare)
        if let Some(data) = audit_data.get("data").and_then(|d| d.as_object())
            && let Some(advisories) = data.get("advisories").and_then(|a| a.as_object())
        {
            for (advisory_id, advisory) in advisories {
                if let Some(advisory_obj) = advisory.as_object() {
                    let (vuln_info, pkg_name) =
                        self.extract_yarn_advisory(advisory_id, advisory_obj);
                    // Include all vulnerable packages, not just direct dependencies
                    if let Some(existing) = vulnerable_deps.iter_mut().find(|v| v.name == pkg_name)
                    {
                        existing.vulnerabilities.push(vuln_info);
                    } else {
                        // Try to find version from direct dependencies, otherwise use "transitive"
                        let version = dependencies
                            .iter()
                            .find(|d| d.name == pkg_name)
                            .map(|d| d.version.clone())
                            .unwrap_or_else(|| "transitive".to_string());

                        vulnerable_deps.push(VulnerableDependency {
                            name: pkg_name,
                            version,
                            language: Language::JavaScript,
                            vulnerabilities: vec![vuln_info],
                            source_dir: None,
                        });
                    }
                }
            }
        }

        if vulnerable_deps.is_empty() {
            Ok(None)
        } else {
            Ok(Some(vulnerable_deps))
        }
    }

    // Parse Yarn classic line-delimited JSON output
    fn parse_yarn_streaming_audit_lines(
        &self,
        stdout: &[u8],
        dependencies: &[DependencyInfo],
    ) -> Result<Option<Vec<VulnerableDependency>>, VulnerabilityError> {
        let mut vulnerable_deps: Vec<VulnerableDependency> = Vec::new();
        let text = String::from_utf8_lossy(stdout);
        for line in text.lines() {
            let line = line.trim();
            if line.is_empty() {
                continue;
            }
            if let Ok(json) = serde_json::from_str::<serde_json::Value>(line)
                && json.get("type").and_then(|t| t.as_str()) == Some("auditAdvisory")
                && let Some(advisory_obj) = json
                    .get("data")
                    .and_then(|d| d.get("advisory"))
                    .and_then(|a| a.as_object())
            {
                let _package_name = advisory_obj
                    .get("module_name")
                    .and_then(|n| n.as_str())
                    .unwrap_or("")
                    .to_string();
                let (vuln_info, pkg_name) = self.extract_yarn_advisory(
                    advisory_obj
                        .get("id")
                        .and_then(|v| v.as_i64())
                        .map(|v| v.to_string())
                        .unwrap_or_else(|| "unknown".to_string())
                        .as_str(),
                    advisory_obj,
                );

                // Include all vulnerable packages, not just direct dependencies
                if let Some(existing) = vulnerable_deps.iter_mut().find(|v| v.name == pkg_name) {
                    existing.vulnerabilities.push(vuln_info);
                } else {
                    // Try to find version from direct dependencies, otherwise use "transitive"
                    let version = dependencies
                        .iter()
                        .find(|d| d.name == pkg_name)
                        .map(|d| d.version.clone())
                        .unwrap_or_else(|| "transitive".to_string());

                    vulnerable_deps.push(VulnerableDependency {
                        name: pkg_name,
                        version,
                        language: Language::JavaScript,
                        vulnerabilities: vec![vuln_info],
                        source_dir: None,
                    });
                }
            }
        }

        if vulnerable_deps.is_empty() {
            Ok(None)
        } else {
            Ok(Some(vulnerable_deps))
        }
    }

    fn extract_yarn_advisory(
        &self,
        advisory_id: impl Into<String>,
        advisory_obj: &serde_json::Map<String, serde_json::Value>,
    ) -> (VulnerabilityInfo, String) {
        let package_name = advisory_obj
            .get("module_name")
            .and_then(|n| n.as_str())
            .unwrap_or("")
            .to_string();
        let id = advisory_id.into();
        let title = advisory_obj
            .get("title")
            .and_then(|t| t.as_str())
            .unwrap_or("Unknown vulnerability")
            .to_string();
        let description = advisory_obj
            .get("overview")
            .and_then(|o| o.as_str())
            .unwrap_or("")
            .to_string();
        let severity = self.parse_severity(advisory_obj.get("severity").and_then(|s| s.as_str()));
        let vulnerable_versions = advisory_obj
            .get("vulnerable_versions")
            .and_then(|v| v.as_str())
            .unwrap_or("*")
            .to_string();
        let cve = advisory_obj
            .get("cves")
            .and_then(|c| c.as_array())
            .and_then(|arr| arr.first())
            .and_then(|v| v.as_str())
            .map(|s| s.to_string());
        let url = advisory_obj
            .get("url")
            .and_then(|u| u.as_str())
            .map(|s| s.to_string());

        let vuln_info = VulnerabilityInfo {
            id,
            vuln_type: "security".to_string(),
            severity,
            title,
            description,
            cve,
            ghsa: url
                .clone()
                .filter(|u| u.contains("GHSA"))
                .map(|u| u.split('/').next_back().unwrap_or(&u).to_string()),
            affected_versions: vulnerable_versions,
            patched_versions: advisory_obj
                .get("patched_versions")
                .and_then(|p| p.as_str())
                .map(|s| s.to_string()),
            published_date: None,
            references: url.map(|u| vec![u]).unwrap_or_default(),
        };

        (vuln_info, package_name)
    }

    fn parse_pnpm_audit_output(
        &self,
        audit_data: &serde_json::Value,
        dependencies: &[DependencyInfo],
    ) -> Result<Option<Vec<VulnerableDependency>>, VulnerabilityError> {
        // PNPM audit output can resemble NPM or provide an advisories map similar to Yarn classic
        if audit_data.get("vulnerabilities").is_some() {
            return self.parse_npm_audit_output(audit_data, dependencies);
        }

        if let Some(advisories) = audit_data.get("advisories").cloned() {
            // Wrap into Yarn-like shape and reuse Yarn parser
            let yarn_like = serde_json::json!({
                "data": { "advisories": advisories }
            });
            return self.parse_yarn_audit_output(&yarn_like, dependencies);
        }

        // Some pnpm versions produce per-advisory arrays; attempt best-effort mapping if present
        if audit_data
            .get("audit")
            .or_else(|| audit_data.get("metadata"))
            .or_else(|| audit_data.get("data"))
            .is_some()
            && let Ok(res) = self.parse_npm_audit_output(audit_data, dependencies)
            && res.is_some()
        {
            return Ok(res);
        }

        Ok(None)
    }

    fn parse_severity(&self, severity: Option<&str>) -> VulnerabilitySeverity {
        match severity.map(|s| s.to_lowercase()).as_deref() {
            Some("critical") => VulnerabilitySeverity::Critical,
            Some("high") => VulnerabilitySeverity::High,
            Some("moderate") => VulnerabilitySeverity::Medium,
            Some("medium") => VulnerabilitySeverity::Medium,
            Some("low") => VulnerabilitySeverity::Low,
            _ => VulnerabilitySeverity::Medium, // Default to medium if not specified
        }
    }
}

impl MutableLanguageVulnerabilityChecker for JavaScriptVulnerabilityChecker {
    fn check_vulnerabilities(
        &mut self,
        dependencies: &[DependencyInfo],
        project_path: &Path,
    ) -> Result<Vec<VulnerableDependency>, VulnerabilityError> {
        info!("Checking JavaScript/TypeScript dependencies");

        let runtime_detector = RuntimeDetector::new(project_path.to_path_buf());
        let detection_result = runtime_detector.detect_js_runtime_and_package_manager();

        info!(
            "Runtime detection: {}",
            runtime_detector.get_detection_summary()
        );

        // Build execution order: primary detected manager first, then any lockfile-based managers
        let mut managers = Vec::new();
        if detection_result.package_manager != crate::analyzer::runtime::PackageManager::Unknown {
            managers.push(detection_result.package_manager.clone());
        }
        for m in runtime_detector.detect_all_package_managers() {
            if !managers.contains(&m) {
                managers.push(m);
            }
        }

        // Always consider running Bun audit for JS projects if available,
        // as Bun often surfaces advisories even when other managers don't.
        if !managers.contains(&crate::analyzer::runtime::PackageManager::Bun)
            && runtime_detector.is_js_project()
        {
            managers.push(crate::analyzer::runtime::PackageManager::Bun);
        }

        // If still empty but it's a JS project, default to npm as a last resort
        if managers.is_empty() && runtime_detector.is_js_project() {
            managers.push(crate::analyzer::runtime::PackageManager::Npm);
        }

        // Execute audit commands for each selected manager
        let mut all_vulnerabilities = Vec::new();

        for manager in managers {
            if let Some(vulns) =
                self.execute_audit_for_manager(&manager, project_path, dependencies)?
            {
                all_vulnerabilities.extend(vulns);
            }
        }

        // Deduplicate vulnerabilities by package name and vulnerability ID
        let mut deduplicated: Vec<VulnerableDependency> = Vec::new();
        for vuln_dep in all_vulnerabilities {
            if let Some(existing) = deduplicated.iter_mut().find(|d| d.name == vuln_dep.name) {
                // Merge vulnerabilities, avoiding duplicates by ID
                for new_vuln in vuln_dep.vulnerabilities {
                    if !existing.vulnerabilities.iter().any(|v| v.id == new_vuln.id) {
                        existing.vulnerabilities.push(new_vuln);
                    }
                }
            } else {
                deduplicated.push(vuln_dep);
            }
        }

        Ok(deduplicated)
    }
}

// Best-effort tolerant JSON extractor: handles banners/noise by
// 1) parsing whole buffer, 2) slicing between first '{' and last '}',
// 3) scanning lines for a valid JSON object.
fn try_parse_json_tolerant(buf: &[u8]) -> Option<JsonValue> {
    if let Ok(val) = serde_json::from_slice::<JsonValue>(buf) {
        return Some(val);
    }
    let text = String::from_utf8_lossy(buf);
    if let (Some(start), Some(end)) = (text.find('{'), text.rfind('}'))
        && start < end
        && let Ok(val) = serde_json::from_str::<JsonValue>(&text[start..=end])
    {
        return Some(val);
    }
    for line in text.lines() {
        let line = line.trim();
        if !line.starts_with('{') || !line.ends_with('}') {
            continue;
        }
        if let Ok(val) = serde_json::from_str::<JsonValue>(line) {
            return Some(val);
        }
    }
    None
}