aube-lockfile 1.28.0

Multi-format lockfile reader/writer for Aube (aube-lock, pnpm-lock, package-lock, yarn.lock, bun.lock)
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
use crate::{GitSource, LocalSource, RemoteTarballSource};
use serde::Deserialize;
use std::collections::BTreeMap;

/// Parse `pnpm-lock.yaml` content, tolerating pnpm v11's multi-document
/// layout.
///
/// pnpm v11 splits the lockfile into two YAML documents: a bootstrap
/// document that tracks pnpm's own `packageManagerDependencies` /
/// `configDependencies`, and the "real" project lockfile (with the
/// workspace's `dependencies` / `devDependencies`, `settings`,
/// `catalogs`, `overrides`, `patchedDependencies`, etc.). We want the
/// second one. Heuristic: score every parseable document by
/// project-lockfile signal (real importer deps + settings/catalogs/
/// overrides + packages/snapshots count) and take the highest. If only
/// one document is present (pnpm v9/v10 and older) this reduces to the
/// previous single-document parse.
pub(super) fn parse_raw_lockfile(content: &str) -> Result<RawPnpmLockfile, yaml_serde::Error> {
    // Fast path: the purpose-built subset parser handles the common
    // single-document pnpm shape directly off the bytes. It returns
    // `None` for anything outside the recognized subset (multi-doc
    // streams, flow constructs it doesn't model, unexpected indent),
    // and we fall through to the general serde parser below — so
    // behavior is preserved by construction.
    if let Some(raw) = super::subset::try_parse(content) {
        return Ok(raw);
    }
    parse_raw_lockfile_serde(content)
}

/// Benchmark helper: cheap fingerprint of a parsed lockfile so the
/// bench's black-box has something to consume. Gated with the bench
/// shims it feeds.
#[cfg(feature = "bench")]
pub(super) fn __bench_counts(raw: &RawPnpmLockfile) -> (usize, usize, usize) {
    (raw.packages.len(), raw.snapshots.len(), raw.importers.len())
}

/// Outcome of comparing the subset fast path against the serde path for
/// one lockfile. Used only by the differential test harness.
#[cfg(test)]
pub(super) enum SubsetDiff {
    /// Subset parser produced a structurally-identical result.
    Match,
    /// Subset parser declined (returned `None`) — an acceptable
    /// fallback to serde, never a bug.
    Declined,
    /// Subset parser accepted but produced a DIFFERENT result than
    /// serde — a silent wrong parse. This is the only real bug. Carries
    /// the two `{:#?}` renderings for a self-debugging assert message.
    Divergence { subset: String, serde: String },
}

/// Differential check for ONE lockfile: parse it both ways and classify
/// the outcome. Equality is compared via the `Debug` rendering — the raw
/// types are `Deserialize`-only (no `PartialEq`), and two structurally
/// equal values produce byte-identical `{:#?}` output, so this is an
/// exact structural comparison without an intrusive derive. The serde
/// path here is the SINGLE-document `yaml_serde::from_str` (not the
/// scoring multi-doc wrapper): the subset parser declines multi-document
/// streams up front, so for any input it accepts the two must agree on
/// the single-document parse.
#[cfg(test)]
pub(super) fn diff_subset_vs_serde(content: &str) -> SubsetDiff {
    let Some(subset) = super::subset::try_parse(content) else {
        return SubsetDiff::Declined;
    };
    let serde: RawPnpmLockfile = match yaml_serde::from_str(content) {
        Ok(v) => v,
        // Subset accepted but serde itself errors: the subset path must
        // never accept input the serde path rejects (it would change the
        // error surface). Treat as a divergence so the harness flags it.
        Err(e) => {
            return SubsetDiff::Divergence {
                subset: format!("{subset:#?}"),
                serde: format!("<serde error: {e}>"),
            };
        }
    };
    let s = format!("{subset:#?}");
    let d = format!("{serde:#?}");
    if s == d {
        SubsetDiff::Match
    } else {
        SubsetDiff::Divergence {
            subset: s,
            serde: d,
        }
    }
}

/// The original serde/`yaml_serde` parse path. Retained verbatim as the
/// fallback for inputs the subset parser declines, and exercised
/// directly by the parse benchmark for an old-vs-new comparison.
pub(super) fn parse_raw_lockfile_serde(
    content: &str,
) -> Result<RawPnpmLockfile, yaml_serde::Error> {
    // Hard cap on documents inspected. pnpm v11 emits exactly two;
    // anything beyond a handful is pathological. This also guards
    // against malformed YAML that puts
    // `yaml_serde::Deserializer::from_str`'s iterator into an
    // infinite-yield state — `test_parse_invalid_yaml` tripped that
    // mode on Windows CI with an unbounded loop.
    const MAX_DOCUMENTS: usize = 16;

    let mut best: Option<(u64, RawPnpmLockfile)> = None;
    let mut first_err: Option<yaml_serde::Error> = None;
    for (idx, doc) in yaml_serde::Deserializer::from_str(content)
        .enumerate()
        .take(MAX_DOCUMENTS)
    {
        match RawPnpmLockfile::deserialize(doc) {
            Ok(raw) => {
                let score = project_lockfile_score(&raw);
                best = match best {
                    Some((prev, _)) if prev >= score => best,
                    _ => Some((score, raw)),
                };
            }
            Err(e) => {
                // Log the first per-document failure and stop. A malformed document
                // typically puts yaml_serde's iterator into a state
                // where further iteration is either more garbage or an
                // infinite loop (see `test_parse_invalid_yaml`). The
                // returned error is the first failure, which is both
                // most explanatory and the only one we actually
                // observed.
                tracing::debug!("pnpm-lock.yaml document {idx} failed to parse: {e}");
                first_err = Some(e);
                break;
            }
        }
    }
    match (best, first_err) {
        (Some((_, raw)), _) => Ok(raw),
        (None, Some(e)) => Err(e),
        // No documents at all — defer to the single-doc parser so the
        // error surface matches what callers saw before.
        (None, None) => yaml_serde::from_str(content),
    }
}

/// Score for picking the "main" document out of a multi-document
/// `pnpm-lock.yaml`. Weighted so a document with real importer
/// dependencies beats one with only `packageManagerDependencies`
/// (pnpm v11's bootstrap doc has the latter but no regular deps).
pub(super) fn project_lockfile_score(raw: &RawPnpmLockfile) -> u64 {
    let importer_dep_count: usize = raw
        .importers
        .values()
        .map(|i| {
            i.dependencies.as_ref().map(|m| m.len()).unwrap_or(0)
                + i.dev_dependencies.as_ref().map(|m| m.len()).unwrap_or(0)
                + i.optional_dependencies
                    .as_ref()
                    .map(|m| m.len())
                    .unwrap_or(0)
        })
        .sum();
    let mut score = importer_dep_count as u64 * 1000;
    if raw.settings.is_some() {
        score += 100;
    }
    if raw.catalogs.as_ref().is_some_and(|c| !c.is_empty()) {
        score += 100;
    }
    if raw.overrides.as_ref().is_some_and(|o| !o.is_empty()) {
        score += 100;
    }
    score += raw.packages.len() as u64;
    score += raw.snapshots.len() as u64;
    score
}

// -- Raw serde types for pnpm-lock.yaml v9 (deserialization) --

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(super) struct RawPnpmLockfile {
    #[allow(dead_code)]
    pub(super) lockfile_version: yaml_serde::Value,
    #[serde(default)]
    pub(super) settings: Option<RawSettings>,
    #[serde(default)]
    pub(super) overrides: Option<BTreeMap<String, String>>,
    /// `sha256-` prefixed `object-hash` of the effective
    /// `packageExtensions`. Round-tripped verbatim so a parse/write
    /// cycle preserves the value pnpm wrote and drift detection can
    /// compare it against a freshly computed hash.
    #[serde(default)]
    pub(super) package_extensions_checksum: Option<String>,
    /// `sha256-` prefixed hash of the local pnpmfile contents.
    /// Round-tripped verbatim alongside `package_extensions_checksum`.
    #[serde(default)]
    pub(super) pnpmfile_checksum: Option<String>,
    #[serde(default)]
    pub(super) catalogs: Option<BTreeMap<String, BTreeMap<String, RawCatalogEntry>>>,
    /// pnpm v9+ top-level `patchedDependencies:` block. Map of
    /// `pkg@version` selector → patch entry (pnpm uses a nested
    /// `{ path, hash }` object, but we only model the path string
    /// on the shared graph). Round-tripped verbatim so a parse/
    /// write cycle doesn't drop user patches.
    #[serde(default)]
    pub(super) patched_dependencies: Option<BTreeMap<String, RawPatchedDependency>>,
    #[serde(default)]
    pub(super) ignored_optional_dependencies: Option<Vec<String>>,
    #[serde(default)]
    pub(super) importers: BTreeMap<String, RawImporter>,
    #[serde(default)]
    pub(super) packages: BTreeMap<String, RawPackageInfo>,
    #[serde(default)]
    pub(super) snapshots: BTreeMap<String, RawSnapshot>,
    #[serde(default)]
    pub(super) time: Option<BTreeMap<String, String>>,
}

/// pnpm writes `patchedDependencies` as either a hash string (v11), a
/// legacy path string, or a nested `{ path, hash }` object (v9/v10).
/// Preserve the hash when one is present; the pnpm writer needs it to
/// retain `(patch_hash=...)` package identities without rereading a
/// patch file that may not be available during a pure lockfile
/// conversion.
#[derive(Debug, Deserialize)]
#[serde(untagged)]
pub(super) enum RawPatchedDependency {
    Path(String),
    Object {
        path: String,
        #[serde(default)]
        hash: Option<String>,
    },
}

impl RawPatchedDependency {
    pub(super) fn into_value(self) -> String {
        match self {
            RawPatchedDependency::Path(p) => p,
            RawPatchedDependency::Object { path, hash } => hash.unwrap_or(path),
        }
    }
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(super) struct RawSettings {
    #[serde(default)]
    pub(super) auto_install_peers: Option<bool>,
    #[serde(default)]
    pub(super) exclude_links_from_lockfile: Option<bool>,
    #[serde(default)]
    pub(super) lockfile_include_tarball_url: Option<bool>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(super) struct RawImporter {
    pub(super) dependencies: Option<BTreeMap<String, RawDepSpec>>,
    pub(super) dev_dependencies: Option<BTreeMap<String, RawDepSpec>>,
    pub(super) optional_dependencies: Option<BTreeMap<String, RawDepSpec>>,
    pub(super) skipped_optional_dependencies: Option<BTreeMap<String, RawDepSpec>>,
}

#[derive(Debug, Deserialize)]
pub(super) struct RawDepSpec {
    pub(super) specifier: String,
    pub(super) version: String,
}

#[derive(Debug, Deserialize)]
pub(super) struct RawCatalogEntry {
    pub(super) specifier: String,
    pub(super) version: String,
}

#[derive(Debug, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(super) struct RawPackageInfo {
    pub(super) resolution: Option<Resolution>,
    #[serde(default)]
    pub(super) engines: BTreeMap<String, String>,
    pub(super) peer_dependencies: Option<BTreeMap<String, String>>,
    pub(super) peer_dependencies_meta: Option<BTreeMap<String, RawPeerDepMeta>>,
    #[serde(default, deserialize_with = "aube_util::string_or_seq")]
    pub(super) os: Vec<String>,
    #[serde(default, deserialize_with = "aube_util::string_or_seq")]
    pub(super) cpu: Vec<String>,
    #[serde(default, deserialize_with = "aube_util::string_or_seq")]
    pub(super) libc: Vec<String>,
    #[serde(default)]
    pub(super) has_bin: bool,
    /// Registry deprecation message pnpm records on a `packages:` entry
    /// (`deprecated: <reason>`). Round-tripped so a parse/write cycle
    /// keeps the field pnpm wrote; carried on the shared graph via
    /// `LockedPackage::extra_meta["deprecated"]`.
    #[serde(default)]
    pub(super) deprecated: Option<String>,
    /// Paired writer field. See `WritablePackageInfo::alias_of`. `None`
    /// for ordinary (non-aliased) packages.
    #[serde(default)]
    pub(super) alias_of: Option<String>,
    /// pnpm emits `version: <semver>` on `packages:` entries whose dep-path
    /// key is a URL (remote tarball, git) rather than a bare semver —
    /// that way the key stays unique (one URL, one entry) while the real
    /// semver is still recorded for tooling. None for ordinary registry
    /// entries, where the version lives in the dep-path key itself.
    #[serde(default)]
    pub(super) version: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub(super) struct RawPeerDepMeta {
    #[serde(default)]
    pub(super) optional: bool,
}

#[derive(Debug, Deserialize)]
pub(super) struct Resolution {
    pub(super) integrity: Option<String>,
    #[serde(default, rename = "gitHosted")]
    pub(super) git_hosted: bool,
    #[serde(default)]
    pub(super) directory: Option<String>,
    #[serde(default)]
    pub(super) tarball: Option<String>,
    #[serde(default)]
    pub(super) commit: Option<String>,
    #[serde(default)]
    pub(super) repo: Option<String>,
    #[serde(default, rename = "type")]
    #[allow(dead_code)]
    pub(super) type_: Option<String>,
    /// pnpm `&path:/<sub>` selector for git deps. Newer pnpm
    /// (>= v9.x) emits this on the resolution block in addition to
    /// encoding it in the snapshot key.
    #[serde(default, deserialize_with = "deserialize_subpath")]
    pub(super) path: Option<String>,
    /// pnpm 10.14+ `type: variations` resolution (runtime pins like
    /// `node@runtime:24.4.1`): one downloadable artifact per platform.
    /// `None` for every ordinary package resolution.
    #[serde(default)]
    pub(super) variants: Option<Vec<RawRuntimeVariant>>,
}

/// One entry of a `variations` resolution's `variants:` list —
/// pnpm's `PlatformAssetResolution` (a binary artifact plus the
/// platform targets it serves).
#[derive(Debug, Deserialize)]
pub(super) struct RawRuntimeVariant {
    pub(super) targets: Vec<RawRuntimeTarget>,
    pub(super) resolution: RawBinaryResolution,
}

#[derive(Debug, Deserialize)]
pub(super) struct RawRuntimeTarget {
    pub(super) os: String,
    pub(super) cpu: String,
    #[serde(default)]
    pub(super) libc: Option<String>,
}

/// pnpm's `BinaryResolution` (`type: binary`).
#[derive(Debug, Deserialize)]
pub(super) struct RawBinaryResolution {
    #[serde(default, rename = "type")]
    #[allow(dead_code)]
    pub(super) type_: Option<String>,
    #[serde(default)]
    pub(super) archive: Option<String>,
    pub(super) url: String,
    #[serde(default)]
    pub(super) integrity: Option<String>,
    #[serde(default)]
    pub(super) bin: Option<RawBinSpec>,
    /// Top-level directory pnpm strips when extracting zip archives.
    #[serde(default)]
    pub(super) prefix: Option<String>,
}

/// pnpm's `bin` field on a binary resolution: bare string (the path
/// of a bin named after the package) or a `name → path` map.
#[derive(Debug, Deserialize)]
#[serde(untagged)]
pub(super) enum RawBinSpec {
    Single(String),
    Map(BTreeMap<String, String>),
}

/// Strip the leading `/` from pnpm's `path:` field so the value lines
/// up with how `parse_git_fragment` stores it. Mirror the same
/// `..`/`.`/empty-component guard as the in-URL parser so a crafted
/// lockfile cannot direct the resolver to read a `package.json`
/// outside the clone dir.
pub(super) fn deserialize_subpath<'de, D>(de: D) -> Result<Option<String>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let raw: Option<String> = serde::Deserialize::deserialize(de)?;
    Ok(raw.and_then(|s| {
        let trimmed = s.trim_start_matches('/');
        if trimmed.is_empty()
            || trimmed
                .split('/')
                .any(|c| c.is_empty() || c == "." || c == "..")
        {
            None
        } else {
            Some(trimmed.to_string())
        }
    }))
}

/// Convert a pnpm `resolution:` block into a `LocalSource` classification.
/// Returns `None` for registry-sourced packages (plain integrity with no
/// tarball/directory/repo fields). Shared by the direct-dep and
/// transitive-dep reader paths so both stay in lockstep when new
/// resolution shapes are added.
pub(super) fn local_source_from_resolution(res: &Resolution) -> Option<LocalSource> {
    if let Some(ref tb) = res.tarball {
        if let Some(rel) = tb.strip_prefix("file:") {
            return Some(LocalSource::Tarball(std::path::PathBuf::from(rel)));
        }
        if tb.starts_with("http://") || tb.starts_with("https://") {
            return Some(LocalSource::RemoteTarball(RemoteTarballSource {
                url: tb.clone(),
                integrity: res.integrity.clone().unwrap_or_default(),
                git_hosted: res.git_hosted,
            }));
        }
        return None;
    }
    if let Some(ref dir) = res.directory {
        return Some(LocalSource::Directory(std::path::PathBuf::from(dir)));
    }
    if let (Some(repo), Some(commit)) = (res.repo.as_ref(), res.commit.as_ref()) {
        return Some(LocalSource::Git(GitSource {
            url: repo.clone(),
            committish: None,
            resolved: commit.clone(),
            integrity: res.integrity.clone(),
            subpath: res.path.clone(),
        }));
    }
    None
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(super) struct RawSnapshot {
    #[serde(default)]
    pub(super) dependencies: Option<BTreeMap<String, String>>,
    #[serde(default)]
    pub(super) optional_dependencies: Option<BTreeMap<String, String>>,
    #[serde(default)]
    pub(super) bundled_dependencies: Option<Vec<String>>,
    #[serde(default)]
    pub(super) optional: Option<bool>,
    #[serde(default)]
    pub(super) transitive_peer_dependencies: Option<Vec<String>>,
}