Skip to main content

ask/lockfiles/
mod.rs

1//! Lockfile readers — translate a dependency name into the version pinned by
2//! the project's package manager. Rust port of `packages/cli/src/lockfiles/`.
3//!
4//! The npm-ecosystem facade probes lockfiles in priority order:
5//!
6//!   `bun.lock → package-lock.json → pnpm-lock.yaml → yarn.lock → package.json`
7//!
8//! The first hit wins; the `package.json` fallback returns a *range* (not an
9//! exact pin), so callers can decide whether to normalize it via a resolver.
10//!
11//! **Port status:** all five readers (`bun.lock`, `package-lock.json`,
12//! `pnpm-lock.yaml`, `yarn.lock`, `package.json`) are ported, restoring full
13//! priority parity with `lockfiles/index.ts`.
14
15mod pnpm;
16
17pub use pnpm::{parse_pnpm_lock, PNPM_LOCK_READER};
18
19use std::path::Path;
20
21/// A resolved dependency version plus provenance.
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub struct LockfileHit {
24    /// The resolved version (exact pin if `exact`, otherwise a range).
25    pub version: String,
26    /// Provenance label, e.g. `"bun.lock"`, `"package.json"`.
27    pub source: String,
28    /// True when read from a lockfile, false when read from a manifest range.
29    pub exact: bool,
30}
31
32/// Per-format reader: probes a single lockfile/manifest and returns `None` when
33/// the file is missing or the package is absent.
34pub struct LockfileReader {
35    /// Filename inspected, relative to `project_dir`.
36    pub file: &'static str,
37    /// Whether hits are exact pins.
38    pub exact: bool,
39    /// Reader fn: `(name, project_dir) -> Option<LockfileHit>`.
40    pub read: fn(&str, &Path) -> Option<LockfileHit>,
41}
42
43// ---------------------------------------------------------------------------
44// parse-helpers — shared text utilities (port of parse-helpers.ts)
45// ---------------------------------------------------------------------------
46
47/// Strip a pnpm peer-dependency suffix (`18.2.0(react@17.0.0)` → `18.2.0`).
48/// Cuts at the first `(` so nested suffixes collapse too.
49pub fn strip_peer_suffix(v: &str) -> &str {
50    match v.find('(') {
51        Some(i) => v[..i].trim_end(),
52        None => v.trim_end(),
53    }
54}
55
56/// Strip a YAML-style inline comment, but only when `#` is preceded by a space,
57/// so `github:foo/bar#branch` fragments pass through intact.
58pub fn strip_inline_comment(s: &str) -> &str {
59    match s.find(" #") {
60        Some(i) => s[..i].trim_end(),
61        None => s,
62    }
63}
64
65/// Strip any mix of surrounding single/double quotes (`^['"]+|['"]+$`).
66pub fn trim_quotes(s: &str) -> &str {
67    s.trim_matches(['\'', '"'])
68}
69
70/// Normalize a raw YAML value: trim, strip inline comment, strip quotes. Does
71/// NOT strip peer-dep suffixes — callers do that when appropriate.
72pub fn clean_value(s: &str) -> &str {
73    trim_quotes(strip_inline_comment(s.trim()))
74}
75
76/// Split a `<pkg>@<rest>` spec into `(name, rest)`, handling scoped names
77/// (`@scope/pkg`). Returns `None` if there is no `@` separator.
78pub fn split_pkg_spec(spec: &str) -> Option<(&str, &str)> {
79    let at_pos = match spec.strip_prefix('@') {
80        // Scoped: separating `@` is the next one after the leading `@` (+1 to
81        // map the index in `rest` back onto `spec`).
82        Some(rest) => rest.find('@').map(|i| i + 1)?,
83        None => spec.find('@')?,
84    };
85    Some((&spec[..at_pos], &spec[at_pos + 1..]))
86}
87
88/// Whether `v` is a version resolvable against a public registry. Lockfiles can
89/// carry protocol strings (`link:`, `file:`, `workspace:`, git/URL, and yarn
90/// Berry's `0.0.0-use.local`); real npm versions never contain `:`, so a colon
91/// (or the Berry sentinel, or emptiness) disqualifies.
92pub fn is_registry_version(v: &str) -> bool {
93    !v.is_empty() && v != "0.0.0-use.local" && !v.contains(':')
94}
95
96// ---------------------------------------------------------------------------
97// Readers
98// ---------------------------------------------------------------------------
99
100/// Parse a `bun.lock` for the version of `name`. bun.lock is a text-ish format
101/// where deps appear as quoted `"<name>@<version>"` tokens. Hand-rolled scan
102/// equivalent to the TS regex `"<name>@([^"@][^"]*)"`: literal `"<name>@`, a
103/// first version char that is neither `@` nor `"`, then up to the next `"`.
104/// Returns the first valid occurrence in file order.
105fn parse_bun(content: &str, name: &str) -> Option<String> {
106    let needle = format!("\"{name}@");
107    let mut base = 0;
108    while let Some(rel) = content[base..].find(&needle) {
109        let start = base + rel + needle.len();
110        let rest = &content[start..];
111        // First version char must be neither `@` (double separator) nor `"`
112        // (empty version).
113        match rest.chars().next() {
114            Some(c) if c != '@' && c != '"' => {
115                if let Some(qpos) = rest.find('"') {
116                    return Some(rest[..qpos].to_string());
117                }
118            }
119            _ => {}
120        }
121        base = base + rel + 1; // advance past this occurrence and keep scanning
122    }
123    None
124}
125
126fn read_file(project_dir: &Path, file: &str) -> Option<String> {
127    std::fs::read_to_string(project_dir.join(file)).ok()
128}
129
130fn bun_read(name: &str, project_dir: &Path) -> Option<LockfileHit> {
131    let content = read_file(project_dir, "bun.lock")?;
132    parse_bun(&content, name).map(|version| LockfileHit {
133        version,
134        source: "bun.lock".to_string(),
135        exact: true,
136    })
137}
138
139/// Parse a `package-lock.json` (npm v2/v3): prefer
140/// `packages["node_modules/<name>"].version` (lockfileVersion 2+), then
141/// `dependencies.<name>.version` (v1).
142fn parse_npm(content: &str, name: &str) -> Option<String> {
143    let json: serde_json::Value = serde_json::from_str(content).ok()?;
144    let pkg_key = format!("node_modules/{name}");
145    if let Some(v) = json
146        .get("packages")
147        .and_then(|p| p.get(&pkg_key))
148        .and_then(|e| e.get("version"))
149        .and_then(|v| v.as_str())
150    {
151        return Some(v.to_string());
152    }
153    json.get("dependencies")
154        .and_then(|d| d.get(name))
155        .and_then(|e| e.get("version"))
156        .and_then(|v| v.as_str())
157        .map(str::to_string)
158}
159
160fn npm_read(name: &str, project_dir: &Path) -> Option<LockfileHit> {
161    let content = read_file(project_dir, "package-lock.json")?;
162    parse_npm(&content, name).map(|version| LockfileHit {
163        version,
164        source: "package-lock.json".to_string(),
165        exact: true,
166    })
167}
168
169/// Parse `package.json` for a dependency range (dependencies → dev → peer →
170/// optional). Non-registry protocol strings are skipped. The hit is NOT exact.
171fn parse_package_json(content: &str, name: &str) -> Option<String> {
172    let json: serde_json::Value = serde_json::from_str(content).ok()?;
173    let lookup = |field: &str| {
174        json.get(field)
175            .and_then(|m| m.get(name))
176            .and_then(|v| v.as_str())
177            .map(str::to_string)
178    };
179    let value = lookup("dependencies")
180        .or_else(|| lookup("devDependencies"))
181        .or_else(|| lookup("peerDependencies"))
182        .or_else(|| lookup("optionalDependencies"))?;
183    is_registry_version(&value).then_some(value)
184}
185
186fn package_json_read(name: &str, project_dir: &Path) -> Option<LockfileHit> {
187    let content = read_file(project_dir, "package.json")?;
188    parse_package_json(&content, name).map(|version| LockfileHit {
189        version,
190        source: "package.json".to_string(),
191        exact: false,
192    })
193}
194
195/// Block-based `yarn.lock` parser handling both classic v1 and Berry v2+ in one
196/// path (port of `parseYarnLock`, itself from opensrc's `core/version.rs`).
197///
198/// Blocks are separated by blank lines. For each block whose header mentions
199/// `pkg` in ANY comma-separated specifier, the nearest body `version` line wins
200/// — unless it is a workspace sentinel / protocol string, in which case a later
201/// block may still provide a real version.
202pub fn parse_yarn_lock(text: &str, pkg: &str) -> Option<String> {
203    // Split into blocks on blank lines (CR-stripped).
204    let mut blocks: Vec<Vec<&str>> = Vec::new();
205    let mut current: Vec<&str> = Vec::new();
206    for raw in text.split('\n') {
207        let line = raw.strip_suffix('\r').unwrap_or(raw);
208        if line.trim().is_empty() {
209            if !current.is_empty() {
210                blocks.push(std::mem::take(&mut current));
211            }
212        } else {
213            current.push(line);
214        }
215    }
216    if !current.is_empty() {
217        blocks.push(current);
218    }
219
220    for block in blocks {
221        let mut header: Option<&str> = None;
222        let mut body: Vec<&str> = Vec::new();
223
224        for line in block {
225            if line.trim_start().starts_with('#') {
226                continue;
227            }
228            let first_is_ws = line.chars().next().is_some_and(char::is_whitespace);
229            if header.is_none() && !first_is_ws {
230                header = Some(line);
231            } else {
232                body.push(line);
233            }
234        }
235
236        let Some(header) = header else { continue };
237        if header.starts_with("__metadata:") || !header.ends_with(':') {
238            continue;
239        }
240        let header_body = &header[..header.len() - 1];
241
242        // Split on `, ` to cover v1 multi-specifier headers and Berry's
243        // `foo@npm:^1, foo@workspace:*`; trim_quotes handles the outer quotes.
244        let matched = header_body.split(", ").any(|s| {
245            let spec = trim_quotes(s.trim());
246            split_pkg_spec(spec).is_some_and(|(name, _)| name == pkg)
247        });
248        if !matched {
249            continue;
250        }
251
252        for line in body {
253            let trimmed = line.trim_start();
254            let Some(rest) = trimmed.strip_prefix("version") else {
255                continue;
256            };
257            // Must be followed by `:` (Berry) or whitespace (v1) — not `versions:`.
258            match rest.chars().next() {
259                Some(':') | Some(' ') | Some('\t') => {}
260                _ => continue,
261            }
262            let rest = rest.trim_start();
263            let rest = rest.strip_prefix(':').unwrap_or(rest);
264            let stripped = strip_peer_suffix(clean_value(rest));
265            if is_registry_version(stripped) {
266                return Some(stripped.to_string());
267            }
268        }
269    }
270
271    None
272}
273
274fn yarn_read(name: &str, project_dir: &Path) -> Option<LockfileHit> {
275    let content = read_file(project_dir, "yarn.lock")?;
276    parse_yarn_lock(&content, name).map(|version| LockfileHit {
277        version,
278        source: "yarn.lock".to_string(),
279        exact: true,
280    })
281}
282
283pub const BUN_LOCK_READER: LockfileReader = LockfileReader {
284    file: "bun.lock",
285    exact: true,
286    read: bun_read,
287};
288pub const NPM_LOCK_READER: LockfileReader = LockfileReader {
289    file: "package-lock.json",
290    exact: true,
291    read: npm_read,
292};
293pub const PACKAGE_JSON_READER: LockfileReader = LockfileReader {
294    file: "package.json",
295    exact: false,
296    read: package_json_read,
297};
298pub const YARN_LOCK_READER: LockfileReader = LockfileReader {
299    file: "yarn.lock",
300    exact: true,
301    read: yarn_read,
302};
303
304/// The npm-ecosystem chain in priority order:
305/// bun → package-lock → pnpm → yarn → package.json.
306pub const NPM_ECOSYSTEM_CHAIN: &[LockfileReader] = &[
307    BUN_LOCK_READER,
308    NPM_LOCK_READER,
309    PNPM_LOCK_READER,
310    YARN_LOCK_READER,
311    PACKAGE_JSON_READER,
312];
313
314/// Probe the npm-ecosystem chain in order; return the first hit.
315pub fn npm_ecosystem_read(name: &str, project_dir: &Path) -> Option<LockfileHit> {
316    for reader in NPM_ECOSYSTEM_CHAIN {
317        if let Some(hit) = (reader.read)(name, project_dir) {
318            return Some(hit);
319        }
320    }
321    None
322}
323
324#[cfg(test)]
325mod tests {
326    use super::*;
327
328    // ---- parse-helpers ----
329
330    #[test]
331    fn strip_peer_suffix_cases() {
332        assert_eq!(strip_peer_suffix("18.2.0(react@17.0.0)"), "18.2.0");
333        assert_eq!(strip_peer_suffix("18.2.0(a@1)(b@2(c@3))"), "18.2.0");
334        assert_eq!(strip_peer_suffix("1.0.0 "), "1.0.0");
335    }
336
337    #[test]
338    fn strip_inline_comment_keeps_url_fragments() {
339        assert_eq!(strip_inline_comment("1.0.0 # a comment"), "1.0.0");
340        assert_eq!(
341            strip_inline_comment("github:foo/bar#branch"),
342            "github:foo/bar#branch"
343        );
344    }
345
346    #[test]
347    fn trim_and_clean() {
348        assert_eq!(trim_quotes("\"'x'\""), "x");
349        assert_eq!(clean_value("  \"1.0.0\" # c "), "1.0.0");
350    }
351
352    #[test]
353    fn split_pkg_spec_scoped_and_plain() {
354        assert_eq!(split_pkg_spec("next@15.0.0"), Some(("next", "15.0.0")));
355        assert_eq!(
356            split_pkg_spec("@scope/pkg@1.2.3"),
357            Some(("@scope/pkg", "1.2.3"))
358        );
359        assert_eq!(split_pkg_spec("noatsign"), None);
360    }
361
362    #[test]
363    fn is_registry_version_rejects_protocols() {
364        assert!(is_registry_version("1.2.3"));
365        assert!(!is_registry_version("workspace:*"));
366        assert!(!is_registry_version("link:../pkg"));
367        assert!(!is_registry_version("0.0.0-use.local"));
368        assert!(!is_registry_version(""));
369    }
370
371    // ---- bun ----
372
373    #[test]
374    fn bun_finds_scoped_and_plain() {
375        let content = r#"{
376          "packages": {
377            "next": ["next@15.0.3", {}],
378            "@scope/pkg": ["@scope/pkg@1.2.3", {}]
379          }
380        }"#;
381        assert_eq!(parse_bun(content, "next").as_deref(), Some("15.0.3"));
382        assert_eq!(parse_bun(content, "@scope/pkg").as_deref(), Some("1.2.3"));
383        assert_eq!(parse_bun(content, "absent"), None);
384    }
385
386    #[test]
387    fn bun_skips_empty_or_double_at_token() {
388        // `"next@"` (empty) and `"next@@"` (leading @) must not match; the real
389        // pin later in the file wins.
390        let content = "\"next@\": x\n\"next@1.0.0\": y\n";
391        assert_eq!(parse_bun(content, "next").as_deref(), Some("1.0.0"));
392    }
393
394    // ---- npm ----
395
396    #[test]
397    fn npm_prefers_packages_then_dependencies() {
398        let v3 = r#"{"packages":{"node_modules/next":{"version":"15.0.3"}}}"#;
399        assert_eq!(parse_npm(v3, "next").as_deref(), Some("15.0.3"));
400        let v1 = r#"{"dependencies":{"next":{"version":"14.0.0"}}}"#;
401        assert_eq!(parse_npm(v1, "next").as_deref(), Some("14.0.0"));
402        assert_eq!(parse_npm("{}", "next"), None);
403        assert_eq!(parse_npm("not json", "next"), None);
404    }
405
406    // ---- package.json ----
407
408    #[test]
409    fn package_json_ranges_and_protocol_skip() {
410        let json = r#"{
411          "dependencies": { "next": "^15.0.0", "linked": "link:../x" },
412          "devDependencies": { "vitest": "1.2.3" }
413        }"#;
414        assert_eq!(parse_package_json(json, "next").as_deref(), Some("^15.0.0"));
415        assert_eq!(parse_package_json(json, "vitest").as_deref(), Some("1.2.3"));
416        assert_eq!(parse_package_json(json, "linked"), None); // protocol skipped
417        assert_eq!(parse_package_json(json, "absent"), None);
418    }
419
420    // ---- yarn ----
421
422    #[test]
423    fn yarn_v1_multi_specifier_header() {
424        let text = "\
425# yarn lockfile v1
426
427
428\"next@^15.0.0\", \"next@~15.0.3\":
429  version \"15.0.3\"
430  resolved \"https://...\"
431";
432        assert_eq!(parse_yarn_lock(text, "next").as_deref(), Some("15.0.3"));
433    }
434
435    #[test]
436    fn yarn_berry_and_peer_suffix_and_protocol_skip() {
437        // Berry header form + a peer suffix on the version; workspace sentinel
438        // block is skipped in favor of the real one.
439        let text = "\
440__metadata:
441  version: 8
442
443\"root@workspace:.\":
444  version: 0.0.0-use.local
445
446\"react@npm:^18.0.0, react@npm:^18.2.0\":
447  version: 18.2.0(loose)
448";
449        assert_eq!(parse_yarn_lock(text, "react").as_deref(), Some("18.2.0"));
450        // The workspace root resolves to a sentinel → no registry version.
451        assert_eq!(parse_yarn_lock(text, "root"), None);
452    }
453
454    #[test]
455    fn yarn_versions_key_is_not_the_version_key() {
456        // `versions:` (plural) must not be mistaken for the `version` key.
457        let text = "\
458\"pkg@^1.0.0\":
459  versions:
460    - 1.0.0
461  version \"1.0.0\"
462";
463        assert_eq!(parse_yarn_lock(text, "pkg").as_deref(), Some("1.0.0"));
464    }
465
466    // ---- facade ----
467
468    #[test]
469    fn chain_priority_bun_beats_package_json() {
470        let dir = tempfile::tempdir().unwrap();
471        std::fs::write(dir.path().join("bun.lock"), "\"next@15.0.3\": {}").unwrap();
472        std::fs::write(
473            dir.path().join("package.json"),
474            r#"{"dependencies":{"next":"^14.0.0"}}"#,
475        )
476        .unwrap();
477        let hit = npm_ecosystem_read("next", dir.path()).unwrap();
478        assert_eq!(hit.version, "15.0.3");
479        assert_eq!(hit.source, "bun.lock");
480        assert!(hit.exact);
481    }
482
483    #[test]
484    fn chain_falls_back_to_package_json_range() {
485        let dir = tempfile::tempdir().unwrap();
486        std::fs::write(
487            dir.path().join("package.json"),
488            r#"{"dependencies":{"next":"^14.0.0"}}"#,
489        )
490        .unwrap();
491        let hit = npm_ecosystem_read("next", dir.path()).unwrap();
492        assert_eq!(hit.version, "^14.0.0");
493        assert_eq!(hit.source, "package.json");
494        assert!(!hit.exact);
495        assert!(npm_ecosystem_read("absent", dir.path()).is_none());
496    }
497}