npm-utils 0.6.1

Pure-Rust npm toolkit: resolve, download, install/ci, add/remove/upgrade, search, SBOM (CycloneDX/SPDX), and vulnerability audit (npm + OSV) — no Node.
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
//! `package-lock.json` (lockfileVersion 2 or 3) parsing, per
//! <https://docs.npmjs.com/cli/v8/configuring-npm/package-lock-json>.
//!
//! [`Lockfile::parse`] reads the flat `packages` map into faithful [`LockedPackage`] data.
//! [`render_v3`] is the inverse: it emits a `lockfileVersion`-3 document for a flat resolved set
//! (what `cargo npm-utils add`/`upgrade` write). Both are pure — they touch no filesystem and
//! resolve no paths: a caller turns a [`LockedPackage::key`] into an install path itself, so this
//! parser stays pure and the path-safety check lives with the installer. lockfileVersion 1 (the
//! legacy hierarchical `dependencies` tree, with no `packages` map) is unsupported.

use std::path::Path;

use serde_json::{Map, Value};

use super::{manifest, spec};
use crate::registry::{Omission, Registry, ResolveEvent};

/// A parsed `package-lock.json`.
#[derive(Debug, Clone)]
pub struct Lockfile {
    /// The `lockfileVersion` (always ≥ 2 here).
    pub version: u64,
    /// Every entry of the `packages` map, sorted by key — so install order, and thus
    /// `.bin` name-collision resolution, is deterministic. Includes the root `""` entry.
    pub packages: Vec<LockedPackage>,
}

/// One entry of the `packages` map.
#[derive(Debug, Clone)]
pub struct LockedPackage {
    /// The map key: `""` for the root project, else a `node_modules/…`-relative path.
    pub key: String,
    /// The package name — the entry's `name` field when the lockfile records one (npm writes it
    /// exactly when the installed path differs from the real package, i.e. an `npm:` alias; the
    /// root `""` entry carries the project name), else the segment after the last
    /// `node_modules/` (empty for the root).
    pub name: String,
    /// `version` from the entry (empty for the root or a pure link).
    pub version: String,
    /// `resolved` — the registry URL, git source, or `file:` path; `None` if absent.
    pub resolved: Option<String>,
    /// `integrity` — the Subresource-Integrity string (`sha512-…`); `None` if absent.
    pub integrity: Option<String>,
    /// `license` — the package's declared SPDX license string, when the lockfile records one
    /// (npm writes it per package; so does this crate's [`render_v3`]). `None` if absent.
    /// Read so SBOM/compliance output ([`crate::sbom`]) can carry it.
    pub license: Option<String>,
    /// `dev` — strictly in the devDependencies tree.
    pub dev: bool,
    /// `optional` — strictly in the optionalDependencies tree.
    pub optional: bool,
    /// `devOptional` — both a dev and an optional dependency.
    pub dev_optional: bool,
    /// `link: true` — a symlink to a local path; nothing is fetched.
    pub link: bool,
    /// `os` constraints (npm spelling — `darwin`, `linux`, `win32`; `!`-negation allowed).
    pub os: Vec<String>,
    /// `cpu` constraints (npm spelling — `x64`, `arm64`, `ia32`; `!`-negation allowed).
    pub cpu: Vec<String>,
    /// `bin` as `(name, path-within-package)` pairs.
    pub bin: Vec<(String, String)>,
}

impl Lockfile {
    /// Parse a `package-lock.json` document (lockfileVersion 2 or 3).
    pub fn parse(s: &str) -> Result<Lockfile, Box<dyn std::error::Error + Send + Sync>> {
        let json: Value = serde_json::from_str(s)?;
        let version = json
            .get("lockfileVersion")
            .and_then(Value::as_u64)
            .unwrap_or(0);
        if version < 2 {
            return Err(format!(
                "package-lock.json lockfileVersion {version} is unsupported \
                 (need 2 or 3, which carry the `packages` map)"
            )
            .into());
        }
        let packages = json
            .get("packages")
            .and_then(Value::as_object)
            .ok_or("package-lock.json has no `packages` map")?;
        let mut out: Vec<LockedPackage> = packages
            .iter()
            .filter_map(|(key, entry)| {
                entry
                    .as_object()
                    .map(|entry| LockedPackage::from_entry(key, entry))
            })
            .collect();
        out.sort_by(|a, b| a.key.cmp(&b.key));
        Ok(Lockfile {
            version,
            packages: out,
        })
    }

    /// The entries an npm-tarball installer fetches on the given host: real (non-root)
    /// `node_modules/…` packages that aren't links and whose `os`/`cpu` match. `host_os` and
    /// `host_arch` are Rust's `std::env::consts::{OS, ARCH}` spellings. Whether each entry's
    /// `resolved` is actually an http(s) registry tarball is left to the caller — see
    /// [`LockedPackage::is_registry_tarball`].
    pub fn installable(&self, host_os: &str, host_arch: &str) -> Vec<&LockedPackage> {
        self.packages
            .iter()
            .filter(|p| p.key.starts_with("node_modules/") && !p.link)
            .filter(|p| p.matches_platform(host_os, host_arch))
            .collect()
    }
}

impl crate::package_json::License for LockedPackage {
    /// The license the lockfile recorded for this package, if any.
    fn license(&self) -> Option<String> {
        self.license.clone()
    }
}

/// A resolved package to record in a generated lockfile — the write-side input mirroring a parsed
/// [`LockedPackage`], kept to the flat-tree fields [`render_v3`] emits.
#[derive(Debug, Clone)]
pub struct LockEntry {
    /// Package name (the `node_modules/<name>` key segment).
    pub name: String,
    /// Exact resolved version.
    pub version: String,
    /// The registry tarball URL — the entry's `resolved`.
    pub resolved: String,
    /// The `sha512-…` Subresource-Integrity, when the registry advertised one.
    pub integrity: Option<String>,
    /// The package's declared SPDX license, recorded for license/compliance tooling
    /// (npm's own lockfiles carry it too).
    pub license: Option<String>,
}

/// Render a `lockfileVersion`-3 `package-lock.json` for a **flat** dependency tree: a root `""`
/// entry (the project `name`/`version` and its direct dependency ranges) plus one
/// `node_modules/<name>` entry per resolved package. Keys are emitted in npm's order
/// (`name`, `version`, `lockfileVersion`, `requires`, `packages`) thanks to `serde_json`'s
/// `preserve_order`.
///
/// Scope (documented, intentional): this is an **npm-compatible v3 lock for the registry/prod
/// tree** that round-trips through [`Lockfile::parse`] and installs via
/// [`crate::install::from_lockfile`] — it is *not* a byte-for-byte npm reproduction. The flat set
/// from [`crate::registry::Registry::resolve_tree`] carries no dev/optional classification, so no
/// `dev`/`optional` flags are emitted, and `peerDependencies`/`bundleDependencies` and per-package
/// `dependencies` back-references are omitted.
pub fn render_v3(
    root_name: &str,
    root_version: &str,
    direct: &[(String, String)],
    entries: &[LockEntry],
) -> String {
    use serde_json::json;

    let mut packages = Map::new();

    // The root project entry, keyed "".
    let mut root = Map::new();
    root.insert("name".into(), json!(root_name));
    root.insert("version".into(), json!(root_version));
    if !direct.is_empty() {
        let mut deps = Map::new();
        for (name, range) in direct {
            deps.insert(name.clone(), json!(range));
        }
        root.insert("dependencies".into(), Value::Object(deps));
    }
    packages.insert(String::new(), Value::Object(root));

    // One node_modules/<name> entry per resolved package, in the order given (resolve_tree
    // returns them sorted by name).
    for entry in entries {
        let mut pkg = Map::new();
        pkg.insert("version".into(), json!(entry.version));
        pkg.insert("resolved".into(), json!(entry.resolved));
        if let Some(integrity) = &entry.integrity {
            pkg.insert("integrity".into(), json!(integrity));
        }
        if let Some(license) = &entry.license {
            pkg.insert("license".into(), json!(license));
        }
        packages.insert(format!("node_modules/{}", entry.name), Value::Object(pkg));
    }

    let doc = json!({
        "name": root_name,
        "version": root_version,
        "lockfileVersion": 3,
        "requires": true,
        "packages": Value::Object(packages),
    });
    let mut out = serde_json::to_string_pretty(&doc).expect("serialize package-lock.json");
    out.push('\n');
    out
}

/// Resolve a `package.json`-shaped manifest's **registry** dependencies into a flat tree and
/// render it as a `lockfileVersion`-3 `package-lock.json` string (with per-package `license`).
/// Talks to `registry` over the network but touches no filesystem and installs no
/// `node_modules/` — the lockfile-only half of `add`/`upgrade`. Non-registry deps (git /
/// `file:`) are skipped: recorded in the manifest, but not resolvable to a registry tarball.
pub fn render_v3_from_manifest(
    doc: &Value,
    registry: &Registry,
) -> Result<String, Box<dyn std::error::Error + Send + Sync>> {
    render_v3_from_manifest_observed(doc, registry, |_| {})
}

/// [`render_v3_from_manifest`] with the resolve walk's progress observer
/// ([`ResolveEvent`]) — the CLI's lockfile-writing verbs drive their `[resolve]` tasks from it.
pub(crate) fn render_v3_from_manifest_observed(
    doc: &Value,
    registry: &Registry,
    on_resolve: impl Fn(ResolveEvent<'_>) + Sync,
) -> Result<String, Box<dyn std::error::Error + Send + Sync>> {
    let direct = manifest::dependencies(doc);
    let roots = registry_roots(doc)?;

    let entries: Vec<LockEntry> = registry
        .resolve_tree_observed(&roots, on_resolve)?
        .into_iter()
        .map(|r| LockEntry {
            name: r.name,
            version: r.version.to_string(),
            resolved: r.tarball_url,
            integrity: r.integrity,
            license: r.license,
        })
        .collect();

    let name = doc.get("name").and_then(Value::as_str).unwrap_or("");
    let version = doc
        .get("version")
        .and_then(Value::as_str)
        .unwrap_or("0.0.0");
    Ok(render_v3(name, version, &direct, &entries))
}

/// A manifest's **registry** `dependencies` as resolvable roots — entries whose spec is a
/// registry range (git / `file:` / tarball specs are skipped), each parsed by the npm range
/// grammar. The lockfile writer's root extraction; the audit uses [`audit_roots`], which skips
/// nothing silently.
pub(crate) fn registry_roots(
    doc: &Value,
) -> Result<Vec<(String, spec::Range)>, Box<dyn std::error::Error + Send + Sync>> {
    manifest::dependencies(doc)
        .iter()
        .filter(|(_, range)| spec::Spec::parse(range).is_registry())
        .map(|(name, range)| Ok((name.clone(), spec::Range::parse(range)?)))
        .collect()
}

/// A manifest's dependency roots for an **audit**: `dependencies` merged with
/// `optionalDependencies` (an optional entry overrides a same-name regular one, as npm applies
/// them), each classified by [`crate::registry::classify_dep`] — registry ranges and `npm:`
/// aliases to them become `(name, range, optional)` roots, non-registry specs become
/// [`Omission`]s with their verbatim spec text, and a manifest declaring `workspaces` records
/// one omission (workspace packages are not traversed). A malformed range is a hard error
/// naming the dependency.
#[cfg_attr(not(feature = "cli"), allow(dead_code))]
pub(crate) fn audit_roots(
    doc: &Value,
) -> Result<AuditRoots, Box<dyn std::error::Error + Send + Sync>> {
    let mut merged: Vec<(String, String, bool)> = manifest::dependencies(doc)
        .into_iter()
        .map(|(name, spec_text)| (name, spec_text, false))
        .collect();
    for (name, spec_text) in manifest::optional_dependencies(doc) {
        match merged.iter_mut().find(|(existing, ..)| *existing == name) {
            Some(entry) => *entry = (name, spec_text, true),
            None => merged.push((name, spec_text, true)),
        }
    }

    let mut roots = Vec::new();
    let mut omissions = Vec::new();
    for (name, spec_text, optional) in merged {
        let action = crate::registry::classify_dep(&name, &spec_text)
            .map_err(|e| format!("package.json dependency `{name}`: {e}"))?;
        match action {
            crate::registry::EdgeAction::Resolve { name, range } => {
                roots.push((name, range, optional))
            }
            crate::registry::EdgeAction::Omit(omission) => omissions.push(omission),
        }
    }
    if has_workspaces(doc) {
        omissions.push(Omission::new("workspaces", "", "not traversed"));
    }
    Ok((roots, omissions))
}

/// [`audit_roots`]'s result: the resolvable `(name, range, optional)` roots and the manifest
/// entries the audit cannot follow.
pub(crate) type AuditRoots = (Vec<(String, spec::Range, bool)>, Vec<Omission>);

/// Whether the manifest declares any workspaces — the array form or the object form's
/// `packages` list.
#[cfg_attr(not(feature = "cli"), allow(dead_code))]
fn has_workspaces(doc: &Value) -> bool {
    match doc.get("workspaces") {
        Some(Value::Array(list)) => !list.is_empty(),
        Some(Value::Object(map)) => map
            .get("packages")
            .and_then(Value::as_array)
            .is_some_and(|list| !list.is_empty()),
        _ => false,
    }
}

/// Read a `package.json`-shaped manifest and (re)write its `package-lock.json` from the
/// registry — pure Rust, no Node, no npm, no `node_modules/`. This is the "update the
/// lockfile" primitive for build scripts and vendoring flows (where the lock is a manifest of
/// resolved versions + licenses, not an install); [`render_v3_from_manifest`] is the in-memory
/// core. Resolves against the public npm registry.
pub fn write_from_manifest(
    manifest_path: &Path,
    lockfile_path: &Path,
    registry: &Registry,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    write_from_manifest_observed(manifest_path, lockfile_path, registry, |_| {})
}

/// [`write_from_manifest`] with the resolve walk's progress observer ([`ResolveEvent`]).
pub(crate) fn write_from_manifest_observed(
    manifest_path: &Path,
    lockfile_path: &Path,
    registry: &Registry,
    on_resolve: impl Fn(ResolveEvent<'_>) + Sync,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    let text = std::fs::read_to_string(manifest_path)
        .map_err(|e| format!("reading {}: {e}", manifest_path.display()))?;
    let doc: Value = serde_json::from_str(&text)
        .map_err(|e| format!("parsing {}: {e}", manifest_path.display()))?;
    let lockfile = render_v3_from_manifest_observed(&doc, registry, on_resolve)?;
    std::fs::write(lockfile_path, lockfile)
        .map_err(|e| format!("writing {}: {e}", lockfile_path.display()))?;
    Ok(())
}

impl LockedPackage {
    fn from_entry(key: &str, entry: &Map<String, Value>) -> LockedPackage {
        // Prefer the entry's `name` field: npm records it when the installed path differs from
        // the real package (an `npm:` alias), and advisory queries, purls, and string-form bins
        // must name the real package. Install paths keep coming from the key.
        let name = entry
            .get("name")
            .and_then(Value::as_str)
            .filter(|n| !n.is_empty())
            .map(str::to_string)
            .unwrap_or_else(|| {
                key.rsplit_once("node_modules/")
                    .map(|(_, n)| n)
                    .unwrap_or(key)
                    .to_string()
            });
        LockedPackage {
            bin: bin_entries(entry, &name),
            key: key.to_string(),
            name,
            version: string_field(entry, "version"),
            resolved: opt_string(entry, "resolved"),
            integrity: opt_string(entry, "integrity"),
            license: opt_string(entry, "license"),
            dev: bool_field(entry, "dev"),
            optional: bool_field(entry, "optional"),
            dev_optional: bool_field(entry, "devOptional"),
            link: bool_field(entry, "link"),
            os: string_list(entry, "os"),
            cpu: string_list(entry, "cpu"),
        }
    }

    /// Whether `resolved` is an http(s) registry tarball — the only source `npm-utils` fetches.
    pub fn is_registry_tarball(&self) -> bool {
        self.resolved
            .as_deref()
            .is_some_and(|r| r.starts_with("https://") || r.starts_with("http://"))
    }

    /// Whether the host satisfies this entry's `os`/`cpu`. `host_os`/`host_arch` are Rust's
    /// `std::env::consts::{OS, ARCH}`; they are mapped to npm's spelling before comparing.
    pub fn matches_platform(&self, host_os: &str, host_arch: &str) -> bool {
        constraint_allows(&self.os, node_os(host_os))
            && constraint_allows(&self.cpu, node_cpu(host_arch))
    }
}

/// npm `os`/`cpu` matching: a positive list must include `host`; a `!`-prefixed value excludes
/// it; an empty constraint allows everything.
pub fn constraint_allows(constraint: &[String], host: &str) -> bool {
    let mut has_positive = false;
    let mut matched_positive = false;
    for item in constraint {
        if let Some(excluded) = item.strip_prefix('!') {
            if excluded == host {
                return false;
            }
        } else {
            has_positive = true;
            if item == host {
                matched_positive = true;
            }
        }
    }
    !has_positive || matched_positive
}

const OS_MAP: &[(&str, &str)] = &[("macos", "darwin"), ("windows", "win32")];
const CPU_MAP: &[(&str, &str)] = &[("x86_64", "x64"), ("aarch64", "arm64"), ("x86", "ia32")];

/// Map a Rust `std::env::consts::OS` value to npm's `os` spelling (`linux` is shared).
fn node_os(rust: &str) -> &str {
    map_value(rust, OS_MAP)
}

/// Map a Rust `std::env::consts::ARCH` value to npm's `cpu` spelling.
fn node_cpu(rust: &str) -> &str {
    map_value(rust, CPU_MAP)
}

fn map_value<'a>(rust: &'a str, map: &[(&'static str, &'static str)]) -> &'a str {
    map.iter()
        .find(|(r, _)| *r == rust)
        .map(|(_, n)| *n)
        .unwrap_or(rust)
}

fn string_field(entry: &Map<String, Value>, key: &str) -> String {
    entry
        .get(key)
        .and_then(Value::as_str)
        .unwrap_or_default()
        .to_string()
}

fn opt_string(entry: &Map<String, Value>, key: &str) -> Option<String> {
    entry.get(key).and_then(Value::as_str).map(str::to_string)
}

fn bool_field(entry: &Map<String, Value>, key: &str) -> bool {
    entry.get(key).and_then(Value::as_bool).unwrap_or(false)
}

fn string_list(entry: &Map<String, Value>, key: &str) -> Vec<String> {
    entry
        .get(key)
        .and_then(Value::as_array)
        .map(|a| {
            a.iter()
                .filter_map(Value::as_str)
                .map(str::to_string)
                .collect()
        })
        .unwrap_or_default()
}

/// The `(bin-name, path-in-package)` pairs an entry exposes. npm allows either an object
/// (`{"foo": "cli.js"}`) or a bare string (the bin takes the package's unscoped name).
fn bin_entries(entry: &Map<String, Value>, name: &str) -> Vec<(String, String)> {
    match entry.get("bin") {
        Some(Value::String(path)) => {
            let bin_name = name.rsplit('/').next().unwrap_or(name).to_string();
            vec![(bin_name, path.clone())]
        }
        Some(Value::Object(map)) => map
            .iter()
            .filter_map(|(n, v)| v.as_str().map(|p| (n.clone(), p.to_string())))
            .collect(),
        _ => Vec::new(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // A lockfileVersion-3 fixture exercising the field variety: a runtime dep, a scoped dep,
    // a dev dep with a `bin` map, an off-platform optional native dep, and a `file:` link.
    const SAMPLE_LOCK: &str = r#"{
      "name": "harness",
      "lockfileVersion": 3,
      "packages": {
        "": { "name": "harness", "devDependencies": { "typescript": "^5" } },
        "node_modules/@scope/pkg": {
          "version": "1.2.3",
          "resolved": "https://registry.npmjs.org/@scope/pkg/-/pkg-1.2.3.tgz",
          "integrity": "sha512-BBBB"
        },
        "node_modules/typescript": {
          "version": "5.9.3",
          "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
          "integrity": "sha512-AAAA",
          "dev": true,
          "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" }
        },
        "node_modules/fsevents": {
          "version": "2.3.2",
          "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
          "integrity": "sha512-CCCC",
          "dev": true,
          "optional": true,
          "os": ["darwin"]
        },
        "node_modules/local-link": { "resolved": "file:../local", "link": true }
      }
    }"#;

    fn names(packages: &[&LockedPackage]) -> Vec<String> {
        packages.iter().map(|p| p.name.clone()).collect()
    }

    #[test]
    fn parses_fields_and_selects_installable_per_host() {
        let lock = Lockfile::parse(SAMPLE_LOCK).unwrap();
        assert_eq!(lock.version, 3);

        // On linux/x86_64: the scoped dep + typescript. The darwin-only optional is skipped;
        // the root "" and the `file:` link are never installable.
        assert_eq!(
            names(&lock.installable("linux", "x86_64")),
            ["@scope/pkg", "typescript"]
        );
        // On macos/aarch64 the darwin-only fsevents joins (sorted by key).
        assert_eq!(
            names(&lock.installable("macos", "aarch64")),
            ["@scope/pkg", "fsevents", "typescript"]
        );

        // Fields parsed: dev flag, integrity, the full bin map.
        let ts = lock
            .packages
            .iter()
            .find(|p| p.name == "typescript")
            .unwrap();
        assert!(ts.dev);
        assert_eq!(ts.integrity.as_deref(), Some("sha512-AAAA"));
        assert!(ts.bin.iter().any(|(n, p)| n == "tsc" && p == "bin/tsc"));
        assert!(ts.bin.iter().any(|(n, _)| n == "tsserver"));
        // The link entry is parsed (faithful) but excluded from installable.
        assert!(lock.packages.iter().any(|p| p.link));
    }

    #[test]
    fn name_field_wins_over_the_install_path() {
        // npm writes `name` when the installed path differs from the real package — an `npm:`
        // alias — and on the root entry; a workspace-nested key still derives from its key.
        let lock = Lockfile::parse(
            r#"{
              "name": "ws", "lockfileVersion": 3,
              "packages": {
                "": { "name": "ws" },
                "node_modules/lodash-alias": {
                  "name": "lodash",
                  "version": "4.17.11",
                  "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.11.tgz",
                  "bin": "cli.js"
                },
                "app/node_modules/minimist": { "version": "1.2.0" }
              }
            }"#,
        )
        .unwrap();
        let by_key = |k: &str| lock.packages.iter().find(|p| p.key == k).unwrap();
        assert_eq!(by_key("node_modules/lodash-alias").name, "lodash");
        // The string-form bin takes the real package's (unscoped) name too.
        assert_eq!(
            by_key("node_modules/lodash-alias").bin,
            [("lodash".to_string(), "cli.js".to_string())]
        );
        assert_eq!(by_key("app/node_modules/minimist").name, "minimist");
        assert_eq!(by_key("").name, "ws");
    }

    #[test]
    fn distinguishes_registry_tarballs_from_other_sources() {
        let lock = Lockfile::parse(SAMPLE_LOCK).unwrap();
        let ts = lock
            .packages
            .iter()
            .find(|p| p.name == "typescript")
            .unwrap();
        assert!(
            ts.is_registry_tarball(),
            "https resolved is a registry tarball"
        );
        let link = lock.packages.iter().find(|p| p.link).unwrap();
        assert!(!link.is_registry_tarball(), "a file: link is not");
    }

    #[test]
    fn rejects_lockfile_version_1() {
        // v1 has no `packages` map — the hierarchical `dependencies` tree is unsupported.
        assert!(Lockfile::parse(r#"{"lockfileVersion":1,"dependencies":{}}"#).is_err());
    }

    #[test]
    fn constraint_allows_follows_npm_os_cpu_rules() {
        let v = |xs: &[&str]| xs.iter().map(|s| s.to_string()).collect::<Vec<_>>();
        assert!(constraint_allows(&[], "linux"), "no constraint allows all");
        assert!(constraint_allows(&v(&["linux"]), "linux"));
        assert!(!constraint_allows(&v(&["darwin"]), "linux"));
        assert!(constraint_allows(&v(&["darwin", "linux"]), "linux"));
        assert!(constraint_allows(&v(&["!win32"]), "linux"));
        assert!(!constraint_allows(&v(&["!linux"]), "linux"));
    }

    #[test]
    fn matches_platform_maps_rust_host_to_npm_spelling() {
        let lock = Lockfile::parse(SAMPLE_LOCK).unwrap();
        let fsevents = lock.packages.iter().find(|p| p.name == "fsevents").unwrap();
        // os:["darwin"] — excluded on a linux host, allowed on macos (rust "macos" → "darwin").
        assert!(!fsevents.matches_platform("linux", "x86_64"));
        assert!(fsevents.matches_platform("macos", "aarch64"));
    }

    #[test]
    fn render_v3_emits_npm_order_and_round_trips_through_parse() {
        let entries = vec![
            LockEntry {
                name: "ms".into(),
                version: "2.1.3".into(),
                resolved: "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz".into(),
                integrity: Some("sha512-MS".into()),
                license: Some("MIT".into()),
            },
            LockEntry {
                name: "@scope/pkg".into(),
                version: "1.0.0".into(),
                resolved: "https://registry.npmjs.org/@scope/pkg/-/pkg-1.0.0.tgz".into(),
                integrity: Some("sha512-SP".into()),
                license: None,
            },
        ];
        let direct = vec![("ms".to_string(), "^2".to_string())];
        let json = render_v3("fixture", "1.0.0", &direct, &entries);

        // Top-level keys come out in npm's order (preserve_order), not alphabetized.
        let doc: Value = serde_json::from_str(&json).unwrap();
        let keys: Vec<&str> = doc
            .as_object()
            .unwrap()
            .keys()
            .map(String::as_str)
            .collect();
        assert_eq!(
            keys,
            ["name", "version", "lockfileVersion", "requires", "packages"]
        );
        // The root "" entry records the direct dependency ranges from package.json.
        assert_eq!(doc["packages"][""]["dependencies"]["ms"], "^2");

        // A declared license is emitted per package; omitted when None.
        assert_eq!(doc["packages"]["node_modules/ms"]["license"], "MIT");
        assert!(doc["packages"]["node_modules/@scope/pkg"]
            .get("license")
            .is_none());

        // It parses back as a v3 lock; the two registry entries are installable (root "" and
        // any link excluded), sorted by key, with integrity + resolved threaded through.
        let lock = Lockfile::parse(&json).unwrap();
        assert_eq!(lock.version, 3);
        let names: Vec<&str> = lock
            .installable("linux", "x86_64")
            .iter()
            .map(|p| p.name.as_str())
            .collect();
        assert_eq!(names, ["@scope/pkg", "ms"]);
        let ms = lock.packages.iter().find(|p| p.name == "ms").unwrap();
        assert_eq!(ms.integrity.as_deref(), Some("sha512-MS"));
        assert!(
            ms.is_registry_tarball(),
            "resolved is an https registry tarball"
        );
    }

    #[test]
    fn audit_roots_merges_optional_over_regular_and_flags_it() {
        let doc = serde_json::json!({
            "dependencies": { "a": "^1", "x": "^1" },
            "optionalDependencies": { "x": "^2", "opt": "^3" }
        });
        let (roots, omissions) = audit_roots(&doc).unwrap();
        let flat: Vec<(String, String, bool)> = roots
            .into_iter()
            .map(|(n, r, o)| (n, r.to_string(), o))
            .collect();
        assert_eq!(
            flat,
            [
                ("a".to_string(), "^1".to_string(), false),
                ("x".to_string(), "^2".to_string(), true),
                ("opt".to_string(), "^3".to_string(), true),
            ],
            "the optional entry overrides the regular one in place, flag flipped"
        );
        assert!(omissions.is_empty());
    }

    #[test]
    fn audit_roots_records_non_registry_specs_and_workspaces_as_omissions() {
        let doc = serde_json::json!({
            "dependencies": {
                "g": "git+ssh://git@github.com/x/y.git",
                "local": "file:../local",
                "w": "workspace:*",
                "keep": "^1"
            },
            "workspaces": ["packages/*"]
        });
        let (roots, omissions) = audit_roots(&doc).unwrap();
        assert_eq!(roots.len(), 1, "only the registry dep resolves");
        assert_eq!(roots[0].0, "keep");
        let rendered: Vec<String> = omissions.iter().map(ToString::to_string).collect();
        assert_eq!(
            rendered,
            [
                "g (git+ssh://git@github.com/x/y.git: git dependency)",
                "local (file:../local: local path)",
                "w (workspace:*: workspace: protocol)",
                "workspaces (not traversed)",
            ],
            "verbatim spec text, and workspace:* no longer aborts the audit"
        );
    }

    #[test]
    fn audit_roots_resolves_an_alias_target_and_rejects_garbage() {
        let doc = serde_json::json!({ "dependencies": { "aliased": "npm:real@^2" } });
        let (roots, omissions) = audit_roots(&doc).unwrap();
        assert_eq!(roots[0].0, "real", "the alias target is what gets audited");
        assert!(omissions.is_empty());

        let doc = serde_json::json!({ "dependencies": { "bad": "%% nope %%" } });
        let err = audit_roots(&doc).unwrap_err().to_string();
        assert!(
            err.contains("package.json dependency `bad`"),
            "malformed ranges stay hard errors naming the dependency: {err}"
        );
    }

    #[test]
    fn has_workspaces_reads_both_declaration_forms() {
        assert!(has_workspaces(&serde_json::json!({ "workspaces": ["a"] })));
        assert!(has_workspaces(
            &serde_json::json!({ "workspaces": { "packages": ["a"] } })
        ));
        assert!(!has_workspaces(&serde_json::json!({ "workspaces": [] })));
        assert!(!has_workspaces(&serde_json::json!({ "name": "x" })));
    }
}