aube_lockfile/lib.rs
1pub mod bun;
2pub mod dep_path_filename;
3pub mod graph_hash;
4pub mod merge;
5pub mod npm;
6pub mod pnpm;
7pub mod yarn;
8
9pub use merge::{MergeReport, merge_branch_lockfiles};
10
11use smallvec::SmallVec;
12use std::collections::{BTreeMap, BTreeSet};
13use std::path::{Path, PathBuf};
14
15/// Most npm packages declare zero or one entry in `os`, `cpu`,
16/// `libc`. Two inline `SmallVec` slots cover empty on construction
17/// (zero heap alloc) and one-entry push (still zero heap) for ~99%
18/// of lockfile entries.
19pub type PlatformList = SmallVec<[String; 2]>;
20
21/// Represents a resolved dependency graph from any lockfile format.
22#[derive(Debug, Clone, Default)]
23pub struct LockfileGraph {
24 /// Direct dependencies of the root project (and workspace packages).
25 /// Key: importer path (e.g., "." for root), Value: list of (name, version) pairs.
26 pub importers: BTreeMap<String, Vec<DirectDep>>,
27 /// All resolved packages.
28 pub packages: BTreeMap<String, LockedPackage>,
29 /// Per-graph settings that round-trip through the lockfile header
30 /// (pnpm v9's `settings:` block). Don't affect graph structure;
31 /// stamped into the YAML when writing and read back when parsing,
32 /// so subsequent installs see the same resolution-mode state.
33 pub settings: LockfileSettings,
34 /// Dependency overrides recorded in pnpm-lock.yaml's top-level
35 /// `overrides:` block. Map of raw selector key → version specifier
36 /// (or `npm:` alias). Keys are the user's verbatim selector
37 /// strings — bare name, `foo>bar`, `foo@<2`, `**/foo`, or any
38 /// combination. Round-tripped so subsequent installs can detect
39 /// override drift on a string-compare of the key+value without
40 /// re-running the resolver. The resolver parses these into
41 /// `override_rule::OverrideRule`s at the start of each resolve
42 /// pass.
43 pub overrides: BTreeMap<String, String>,
44 /// Names listed in the root manifest's `pnpm.ignoredOptionalDependencies`.
45 /// The resolver drops entries in this set from every `optionalDependencies`
46 /// map before enqueueing, matching pnpm's read-package hook. Round-tripped
47 /// through pnpm-lock.yaml's top-level `ignoredOptionalDependencies:` list
48 /// so drift detection can notice when the user edits the field.
49 pub ignored_optional_dependencies: BTreeSet<String>,
50 /// Per-package publish timestamps, keyed by canonical `name@version`
51 /// (no peer suffix). Round-trips through pnpm-lock.yaml's top-level
52 /// `time:` block so `--resolution-mode=time-based` can compute a
53 /// `publishedBy` cutoff from packages already in the lockfile
54 /// without re-fetching packuments.
55 pub times: BTreeMap<String, String>,
56 /// Optional dependencies the resolver intentionally skipped on the
57 /// platform that wrote this lockfile (either filtered by
58 /// `os`/`cpu`/`libc`, or named in
59 /// `pnpm.ignoredOptionalDependencies`). Keyed by importer path,
60 /// inner map is name → specifier captured from `package.json` at
61 /// resolve time.
62 ///
63 /// Drift detection uses this to distinguish "user just added a new
64 /// optional dep" (which is real drift) from "this optional was
65 /// already considered and consciously dropped on this platform"
66 /// (which is *not* drift). Without it, every `--frozen-lockfile`
67 /// install on a platform that skipped a fixture would hard-fail.
68 pub skipped_optional_dependencies: BTreeMap<String, BTreeMap<String, String>>,
69 /// Resolved catalog entries, mirroring pnpm v9's top-level
70 /// `catalogs:` block. Outer key is the catalog name (`default` for
71 /// the unnamed `catalog:` field in `pnpm-workspace.yaml`); inner key
72 /// is the package name. Each entry pairs the original specifier
73 /// from the workspace catalog with the version the resolver chose
74 /// for it. Round-tripped through the lockfile so drift detection
75 /// can fire when a catalog spec changes without re-resolving.
76 pub catalogs: BTreeMap<String, BTreeMap<String, CatalogEntry>>,
77 /// bun's top-level `configVersion` — a second format counter bun
78 /// added alongside `lockfileVersion` to track its own config-
79 /// schema changes. Only the bun parser/writer ever touches this;
80 /// other formats leave it `None`. Round-tripping the parsed
81 /// value keeps the writer from silently downgrading the field
82 /// (e.g. from `2` back to `1`) when bun bumps it in a future
83 /// release.
84 pub bun_config_version: Option<u32>,
85 /// Top-level `patchedDependencies:` block mirrored by bun 1.1+ and
86 /// pnpm 9+. Key: selector (`lodash@4.17.21`), value: relative patch
87 /// file path (`patches/lodash@4.17.21.patch`). Round-tripped
88 /// verbatim so a parse/write cycle doesn't silently drop user
89 /// patches from the lockfile.
90 pub patched_dependencies: BTreeMap<String, String>,
91 /// Top-level `trustedDependencies:` block (bun) — a package-name
92 /// allowlist for lifecycle script execution. Preserved so
93 /// re-emitting a bun.lock doesn't strip the allowlist and cause
94 /// subsequent installs to skip scripts the user explicitly
95 /// approved.
96 ///
97 /// Kept as a `Vec` (not a set) so bun's original order round-trips
98 /// byte-identically; bun emits the list in insertion order. The
99 /// parser is responsible for deduping if the source lockfile
100 /// carried a duplicate.
101 pub trusted_dependencies: Vec<String>,
102 /// Top-level lockfile fields that aren't explicitly modeled on
103 /// `LockfileGraph`. Populated by per-format parsers on best-effort
104 /// basis so the writer can re-emit blocks a future lockfile
105 /// version might add (or ones we haven't promoted to typed fields
106 /// yet) without silently stripping them on round-trip. Each
107 /// parser/writer is responsible for emitting values in its
108 /// format's native serialization.
109 pub extra_fields: BTreeMap<String, serde_json::Value>,
110 /// Per-workspace-importer extras keyed by importer path (`""` for
111 /// root in bun, `"."` for others). Stores anything in the
112 /// workspace entry the typed model doesn't capture so a parse/
113 /// write cycle doesn't drop fields the user (or bun) wrote there.
114 pub workspace_extra_fields: BTreeMap<String, BTreeMap<String, serde_json::Value>>,
115}
116
117/// One entry in a lockfile catalog: the workspace-declared range and the
118/// resolved version. Mirrors pnpm v9's `catalogs:` block exactly.
119#[derive(Debug, Clone, PartialEq, Eq)]
120pub struct CatalogEntry {
121 pub specifier: String,
122 pub version: String,
123}
124
125/// Per-graph settings that mirror pnpm v9's `settings:` header.
126/// Extend as more knobs become round-trip-aware.
127#[derive(Debug, Clone, PartialEq, Eq)]
128pub struct LockfileSettings {
129 /// pnpm's `auto-install-peers` — when false the resolver leaves
130 /// unmet peers alone (just warns) instead of dragging them in.
131 pub auto_install_peers: bool,
132 /// pnpm's `exclude-links-from-lockfile` — not yet honored by aube
133 /// but round-tripped for lockfile compatibility.
134 pub exclude_links_from_lockfile: bool,
135 /// pnpm's `lockfile-include-tarball-url` — when true the writer
136 /// emits the full registry tarball URL in each package's
137 /// `resolution.tarball:` field alongside `integrity:`. Makes the
138 /// lockfile self-contained so air-gapped installs don't need to
139 /// derive the URL from `.npmrc`. Round-tripped through the
140 /// `settings:` header so it survives parse/write cycles without
141 /// re-reading `.npmrc`.
142 pub lockfile_include_tarball_url: bool,
143}
144
145impl Default for LockfileSettings {
146 fn default() -> Self {
147 Self {
148 auto_install_peers: true,
149 exclude_links_from_lockfile: false,
150 lockfile_include_tarball_url: false,
151 }
152 }
153}
154
155/// A direct dependency of a workspace importer.
156#[derive(Debug, Clone)]
157pub struct DirectDep {
158 pub name: String,
159 /// The dep_path key in the lockfile (e.g., "is-odd@3.0.1")
160 pub dep_path: String,
161 pub dep_type: DepType,
162 /// The specifier as written in package.json at the time the lockfile was
163 /// generated (e.g., `"^4.17.0"`). Used by drift detection to compare against
164 /// the current manifest. Only populated by formats that record it
165 /// (pnpm-lock.yaml v9). `None` for npm/yarn/bun lockfiles.
166 pub specifier: Option<String>,
167}
168
169#[derive(Debug, Clone, Copy, PartialEq, Eq)]
170pub enum DepType {
171 Production,
172 Dev,
173 Optional,
174}
175
176/// Non-registry source for a locked package.
177///
178/// When a package comes from a local path (via `file:` or `link:` in
179/// `package.json`) it doesn't have a tarball URL or integrity hash, so we
180/// record the source separately and let the linker materialize it
181/// on-the-fly.
182#[derive(Debug, Clone, PartialEq, Eq)]
183pub enum LocalSource {
184 /// `file:<dir>` — a directory on disk whose contents should be
185 /// hardlink-copied into the virtual store like a normal package.
186 /// Path is stored relative to the project root.
187 Directory(PathBuf),
188 /// `file:<tarball>` — a `.tgz` on disk, extracted into the virtual
189 /// store the same way we extract registry tarballs.
190 Tarball(PathBuf),
191 /// `link:<dir>` — a plain symlink into `node_modules/<name>`, never
192 /// materialized into the virtual store. Transitive deps are the
193 /// target's responsibility.
194 Link(PathBuf),
195 /// `git+https://`, `git+ssh://`, `github:user/repo`, etc. — a
196 /// remote git repo. Cloned at fetch time and imported like a
197 /// `file:` directory. `url` is the normalized clone URL (what
198 /// gets passed to `git clone`). `committish` is the user-written
199 /// ref after `#` (branch, tag, or commit; `None` means HEAD).
200 /// `resolved` is the 40-char commit SHA that `git ls-remote`
201 /// pinned the ref to — the lockfile records this so repeat
202 /// installs reproduce bit-for-bit.
203 Git(GitSource),
204 /// `https://example.com/pkg.tgz` — a remote tarball URL. Fetched
205 /// once at resolve time so the resolver can read the enclosed
206 /// `package.json` for version + transitive deps and pin the
207 /// sha512 integrity. `integrity` stays empty on freshly-parsed
208 /// specifiers and is filled in by the resolver after download.
209 RemoteTarball(RemoteTarballSource),
210}
211
212/// A remote tarball dependency spec. See [`LocalSource::RemoteTarball`].
213#[derive(Debug, Clone, PartialEq, Eq)]
214pub struct RemoteTarballSource {
215 pub url: String,
216 pub integrity: String,
217}
218
219/// A git dependency spec. See [`LocalSource::Git`].
220#[derive(Debug, Clone, PartialEq, Eq)]
221pub struct GitSource {
222 pub url: String,
223 pub committish: Option<String>,
224 pub resolved: String,
225 /// pnpm `&path:/sub/dir` selector — when set, only this
226 /// subdirectory of the cloned repo is treated as the package
227 /// root. Stored without leading slash so dep_path hashes are
228 /// stable regardless of whether the user wrote `path:/x` or
229 /// `path:x`.
230 pub subpath: Option<String>,
231}
232
233impl LocalSource {
234 /// The original path (relative to the project root) the user wrote
235 /// in `package.json`. `None` for non-path sources like git.
236 pub fn path(&self) -> Option<&Path> {
237 match self {
238 LocalSource::Directory(p) | LocalSource::Tarball(p) | LocalSource::Link(p) => Some(p),
239 LocalSource::Git(_) | LocalSource::RemoteTarball(_) => None,
240 }
241 }
242
243 /// The protocol kind (`"file"` / `"link"` / `"git"` / `"url"`).
244 pub fn kind_str(&self) -> &'static str {
245 match self {
246 LocalSource::Directory(_) | LocalSource::Tarball(_) => "file",
247 LocalSource::Link(_) => "link",
248 LocalSource::Git(_) => "git",
249 LocalSource::RemoteTarball(_) => "url",
250 }
251 }
252
253 /// The path as a POSIX-style string with forward-slash separators.
254 /// `Path::display()` and `to_string_lossy()` honor the host's
255 /// separator (backslash on Windows), which would make `dep_path`
256 /// hashes and lockfile `specifier:` strings non-portable: the
257 /// same `file:./some/dir` would render as `some\dir` on Windows
258 /// and `some/dir` on Unix, producing two different hashes for
259 /// the same logical target. Always rendering with `/` keeps
260 /// lockfiles cross-platform identical.
261 pub fn path_posix(&self) -> String {
262 self.path()
263 .map(|p| p.to_string_lossy().replace('\\', "/"))
264 .unwrap_or_default()
265 }
266
267 /// Canonical specifier string as pnpm writes it in the `packages:`
268 /// and `snapshots:` keys (post-`<name>@` part). For `file:` /
269 /// `link:` this is `file:./vendor/foo` / `link:../sibling`. For
270 /// `git`, pnpm uses the resolved form `<url>#<commit>` (no
271 /// `git+` prefix) because the lockfile pins to the exact commit
272 /// regardless of what the user wrote. Always emits POSIX
273 /// separators so the resulting lockfile is portable.
274 pub fn specifier(&self) -> String {
275 match self {
276 LocalSource::Git(g) => match &g.subpath {
277 Some(sub) => format!("{}#{}&path:/{}", g.url, g.resolved, sub),
278 None => format!("{}#{}", g.url, g.resolved),
279 },
280 LocalSource::RemoteTarball(t) => t.url.clone(),
281 _ => format!("{}:{}", self.kind_str(), self.path_posix()),
282 }
283 }
284
285 /// Internal FS-safe dep_path used as the key in
286 /// `LockfileGraph.packages` and as the `.aube/` subdir name.
287 ///
288 /// Distinct paths must map to distinct keys (otherwise the
289 /// linker would silently mix files between two local packages),
290 /// and the result must be a single filesystem component — no
291 /// `/`, `\`, `:`, or `..`. Ad-hoc character substitution trips
292 /// over cases like `../vendor` vs `__/vendor` or `a.b` vs `a_b`
293 /// collapsing to the same string, so we hash the raw path bytes
294 /// and suffix the first 16 hex chars (64 bits — more than enough
295 /// to avoid collisions inside a single project).
296 ///
297 /// The hash input is the POSIX-form path string so a checked-in
298 /// lockfile resolves to the same key regardless of which
299 /// platform ran `aube install`.
300 pub fn dep_path(&self, name: &str) -> String {
301 use sha2::{Digest, Sha256};
302 let mut hasher = Sha256::new();
303 match self {
304 LocalSource::Git(g) => {
305 hasher.update(g.url.as_bytes());
306 hasher.update(b"#");
307 hasher.update(g.resolved.as_bytes());
308 if let Some(sub) = &g.subpath {
309 hasher.update(b"&path:/");
310 hasher.update(sub.as_bytes());
311 }
312 }
313 LocalSource::RemoteTarball(t) => {
314 hasher.update(t.url.as_bytes());
315 }
316 _ => hasher.update(self.path_posix().as_bytes()),
317 }
318 let digest = hasher.finalize();
319 let short: String = digest.iter().take(8).map(|b| format!("{b:02x}")).collect();
320 format!("{name}@{}+{short}", self.kind_str())
321 }
322
323 /// Classify a user-written `file:` / `link:` specifier against the
324 /// project root. Returns `None` if `spec` isn't a local specifier.
325 /// Resolves the target path relative to `project_root`; a `file:`
326 /// target that resolves to a `.tgz` / `.tar.gz` on disk is treated
327 /// as a tarball, anything else as a directory.
328 pub fn parse(spec: &str, project_root: &Path) -> Option<Self> {
329 // Check git first so URLs like `https://host/user/repo.git`
330 // aren't swallowed by the broader bare-http tarball check
331 // below.
332 if let Some((url, committish, subpath)) = parse_git_spec(spec) {
333 // `resolved` is filled in by the resolver after running
334 // `git ls-remote`. A lockfile round-trip that never
335 // re-resolves will leave this empty, which is the sentinel
336 // the resolver checks for before calling ls-remote.
337 return Some(LocalSource::Git(GitSource {
338 url,
339 committish,
340 resolved: String::new(),
341 subpath,
342 }));
343 }
344 // Any remaining bare `http(s)://` URL is a remote tarball.
345 // npm semantics treat *all* non-git HTTP URLs in a dependency
346 // value as tarball URLs, so services that serve tarballs from
347 // URLs without a `.tgz` extension (pkg.pr.new, GitHub
348 // codeload, etc.) classify correctly here.
349 if Self::looks_like_remote_tarball_url(spec) {
350 return Some(LocalSource::RemoteTarball(RemoteTarballSource {
351 url: spec.to_string(),
352 integrity: String::new(),
353 }));
354 }
355 let (kind, rest) = if let Some(r) = spec.strip_prefix("file:") {
356 ("file", r)
357 } else if let Some(r) = spec.strip_prefix("link:") {
358 ("link", r)
359 } else {
360 return None;
361 };
362 let rel = PathBuf::from(rest);
363 let abs = project_root.join(&rel);
364 if kind == "link" {
365 return Some(LocalSource::Link(rel));
366 }
367 if abs.is_file() && Self::path_looks_like_tarball(&rel) {
368 return Some(LocalSource::Tarball(rel));
369 }
370 Some(LocalSource::Directory(rel))
371 }
372
373 /// Whether a specifier looks like a direct HTTP(S) URL that should
374 /// be fetched as a tarball. Per npm semantics, *any* `http://` or
375 /// `https://` URL in a dependency value is a tarball URL — services
376 /// like pkg.pr.new, GitHub codeload, and private registries with
377 /// auth-token query strings serve tarballs from URLs that don't
378 /// carry a `.tgz` extension. Git URLs must already have been
379 /// ruled out by the caller (see [`parse_git_spec`]) so a
380 /// `.git`-suffixed URL doesn't get misclassified here.
381 pub fn looks_like_remote_tarball_url(spec: &str) -> bool {
382 spec.starts_with("https://") || spec.starts_with("http://")
383 }
384
385 pub fn path_looks_like_tarball(path: &Path) -> bool {
386 let name = match path.file_name().and_then(|n| n.to_str()) {
387 Some(n) => n,
388 None => return false,
389 };
390 let lower = name.to_ascii_lowercase();
391 lower.ends_with(".tgz") || lower.ends_with(".tar.gz")
392 }
393}
394
395/// Parse a git dependency specifier into `(clone_url, committish)`.
396///
397/// Recognized forms:
398/// - `git+https://host/user/repo.git[#ref]`
399/// - `git+ssh://git@host/user/repo.git[#ref]`
400/// - `git://host/user/repo.git[#ref]`
401/// - `https://host/user/repo.git[#ref]` (only when ending in `.git`)
402/// - `github:user/repo[#ref]` → `https://github.com/user/repo.git`
403/// - `gitlab:user/repo[#ref]` → `https://gitlab.com/user/repo.git`
404/// - `bitbucket:user/repo[#ref]` → `https://bitbucket.org/user/repo.git`
405///
406/// Returns `None` for any specifier that doesn't look like a git URL,
407/// so the caller can fall through to other protocol parsers.
408pub fn parse_git_spec(spec: &str) -> Option<(String, Option<String>, Option<String>)> {
409 let (body, committish, subpath) = match spec.find('#') {
410 Some(idx) => {
411 let (c, s) = parse_git_fragment(&spec[idx + 1..]);
412 (&spec[..idx], c, s)
413 }
414 None => (spec, None, None),
415 };
416 let is_bare_transport = body.starts_with("https://")
417 || body.starts_with("http://")
418 || body.starts_with("ssh://")
419 || body.starts_with("file://");
420 let url = if let Some(rest) = body.strip_prefix("git+") {
421 // `git+` explicitly tags the URL as git, so the `.git`
422 // suffix is optional (GitHub/GitLab accept both forms).
423 rest.to_string()
424 } else if body.starts_with("git://") {
425 body.to_string()
426 } else if let Some(path) = body.strip_prefix("github:") {
427 format!("https://github.com/{path}.git")
428 } else if let Some(path) = body.strip_prefix("gitlab:") {
429 format!("https://gitlab.com/{path}.git")
430 } else if let Some(path) = body.strip_prefix("bitbucket:") {
431 format!("https://bitbucket.org/{path}.git")
432 } else if is_bare_transport && body.ends_with(".git") {
433 body.to_string()
434 } else if is_bare_transport
435 && committish
436 .as_deref()
437 .is_some_and(|c| c.len() == 40 && c.chars().all(|ch| ch.is_ascii_hexdigit()))
438 {
439 // Lockfile round-trip form: `specifier()` writes the stored
440 // URL verbatim plus `#<sha>`. URLs that dropped the `git+`
441 // prefix (and happen to lack `.git`) are disambiguated from
442 // plain tarball URLs by the 40-hex committish suffix.
443 body.to_string()
444 } else {
445 return None;
446 };
447 Some((url, committish, subpath))
448}
449
450/// Normalize git URL fragments used by npm-compatible lockfiles.
451///
452/// Plain git accepts `#<ref>`, while npm and Yarn Berry also write
453/// key/value fragments such as `#commit=<sha>` for pinned git deps.
454/// Downstream code passes this value directly to `git ls-remote` and
455/// `git checkout`, so strip the selector key here and keep only the
456/// actual ref name or SHA.
457pub(crate) fn normalize_git_fragment(fragment: &str) -> Option<String> {
458 parse_git_fragment(fragment).0
459}
460
461/// Parse a git URL fragment into `(committish, subpath)`. Handles the
462/// pnpm/hosted-git-info form `<ref>&path:/sub/dir` (the `path:` key
463/// uses a colon, not `=`, by historical convention) as well as the
464/// `key=value` form npm/Yarn Berry write. Unknown selectors are
465/// ignored. Subpath is returned without leading slash so the caller
466/// can join it with a clone dir without tripping the absolute-path
467/// branch of `Path::join`.
468pub(crate) fn parse_git_fragment(fragment: &str) -> (Option<String>, Option<String>) {
469 if fragment.is_empty() {
470 return (None, None);
471 }
472
473 let mut fallback: Option<&str> = None;
474 let mut preferred: Option<&str> = None;
475 let mut subpath: Option<String> = None;
476 for part in fragment.split('&') {
477 if part.is_empty() {
478 continue;
479 }
480 // Try `key=value` first; fall back to `key:value` only for
481 // the small set of selectors we actually handle below. A tag
482 // name with a colon (e.g. `release:2026-01`) is left alone —
483 // and `semver:^1.0.0` stays as a literal ref so `ls-remote`
484 // surfaces an explicit error rather than silently HEAD-ing.
485 let split = part.split_once('=').or_else(|| {
486 part.split_once(':')
487 .filter(|(k, _)| matches!(*k, "commit" | "tag" | "head" | "branch" | "path"))
488 });
489 let (key, value) = split.unwrap_or(("", part));
490 if value.is_empty() {
491 continue;
492 }
493 match key {
494 "commit" => {
495 preferred.get_or_insert(value);
496 }
497 "tag" | "head" | "branch" => {
498 fallback.get_or_insert(value);
499 }
500 "path" => {
501 // Strip leading slashes (pnpm writes `path:/sub`) and
502 // reject any `..` / `.` component. Without this, a
503 // crafted spec like `&path:/../../etc` would let the
504 // resolver and installer escape the clone dir and
505 // import an arbitrary host directory into the store.
506 if subpath.is_some() {
507 // First-wins, matching the other selectors above.
508 continue;
509 }
510 let trimmed = value.trim_start_matches('/');
511 if trimmed.is_empty() {
512 continue;
513 }
514 if trimmed
515 .split('/')
516 .any(|c| c.is_empty() || c == "." || c == "..")
517 {
518 continue;
519 }
520 subpath = Some(trimmed.to_string());
521 }
522 "" => {
523 fallback.get_or_insert(value);
524 }
525 _ => {}
526 }
527 }
528
529 (preferred.or(fallback).map(ToString::to_string), subpath)
530}
531
532/// A single resolved package in the lockfile.
533///
534/// The `dependencies` map keys are dep names and values are the dependency's
535/// dep_path *tail* — i.e. the string that follows `<name>@`. For a plain
536/// package this is just the version (`"4.17.21"`); for a package with its
537/// own peer context it includes the suffix (`"18.2.0(prop-types@15.8.1)"`).
538/// Combining the key with its value reproduces the full dep_path (which is
539/// also the key in `LockfileGraph.packages`).
540#[derive(Debug, Clone, Default)]
541pub struct LockedPackage {
542 /// Package name (e.g., "lodash")
543 pub name: String,
544 /// Exact resolved version (e.g., "4.17.21")
545 pub version: String,
546 /// Integrity hash (e.g., "sha512-...")
547 pub integrity: Option<String>,
548 /// Dependencies of this package (name -> dep_path tail, see struct docs)
549 pub dependencies: BTreeMap<String, String>,
550 /// Optional dependency edges for this package. Active optional edges are
551 /// also mirrored in `dependencies` so graph walks and the linker continue
552 /// to see them; this separate map lets platform filtering prune optional
553 /// edges without touching regular dependencies.
554 pub optional_dependencies: BTreeMap<String, String>,
555 /// Peer dependency ranges as *declared* by the package (from its
556 /// package.json / packument). These are the constraints; the resolved
557 /// versions live in `dependencies` after the peer-context pass runs.
558 pub peer_dependencies: BTreeMap<String, String>,
559 /// `peerDependenciesMeta` entries, keyed by peer name.
560 pub peer_dependencies_meta: BTreeMap<String, PeerDepMeta>,
561 /// The dep_path key used in the lockfile. For packages with resolved
562 /// peer contexts this includes the suffix, e.g.
563 /// `"styled-components@6.1.0(react@18.2.0)"`.
564 pub dep_path: String,
565 /// Set for non-registry packages (those installed via `file:` or
566 /// `link:` specifiers). `None` for the common case of a package
567 /// resolved from an npm registry, where `integrity` is the full
568 /// record of where the bits came from.
569 pub local_source: Option<LocalSource>,
570 /// `os` / `cpu` / `libc` arrays from the package's manifest. Used
571 /// by the resolver to filter optional deps that can't run on the
572 /// current (or user-overridden) platform. Empty arrays mean no
573 /// constraint.
574 pub os: PlatformList,
575 pub cpu: PlatformList,
576 pub libc: PlatformList,
577 /// Names declared in the package's own `bundledDependencies`. These
578 /// ship inside the parent tarball's `node_modules/`, so the resolver
579 /// neither fetches nor recurses into them, and the linker avoids
580 /// creating sibling symlinks that would shadow the bundled tree.
581 /// An empty Vec means "no bundled deps"; `None` is kept as a
582 /// distinct value only inside the resolver and collapsed to empty
583 /// here because the lockfile round-trip doesn't need to preserve
584 /// the "unset" vs "empty list" distinction.
585 pub bundled_dependencies: Vec<String>,
586 /// Full registry tarball URL for registry-sourced packages. Only
587 /// populated when `LockfileSettings::lockfile_include_tarball_url`
588 /// is active on this graph; otherwise `None` and the lockfile
589 /// writer derives the URL at fetch time from the configured
590 /// registry. `local_source`-backed packages (file:, link:, git:,
591 /// remote tarball) already carry their own URL via `LocalSource`
592 /// and don't populate this field.
593 pub tarball_url: Option<String>,
594 /// For npm-alias deps (`"h3-v2": "npm:h3@2.0.1-rc.20"`): the real
595 /// package name on the registry (`"h3"`). `None` means the entry
596 /// is not aliased and `name` already holds the registry name.
597 ///
598 /// Install semantics when `Some(real)`:
599 /// - `name` is the *alias* — that's the folder under `node_modules/`,
600 /// the symlink name for transitive deps, and the key every package
601 /// that declares this dep refers to.
602 /// - `alias_of` is the real package name used for tarball URL lookup,
603 /// store index keying, and packument fetches.
604 /// - `version` is the real resolved version.
605 ///
606 /// `registry_name()` returns the right name for registry IO; every
607 /// call site that talks to the registry or the CAS uses that helper.
608 pub alias_of: Option<String>,
609 /// Yarn berry's `checksum:` field, preserved verbatim when parsing a
610 /// yarn 2+ lockfile (e.g. `"10c0/<blake2b-hex>"`). The format is
611 /// yarn-specific — it uses a yarn-chosen hash family prefixed with
612 /// the `cacheKey` that produced it — and doesn't share a hash
613 /// algorithm with `integrity` (sha-512). When re-emitting a yarn
614 /// berry lockfile we write this field back as-is; packages that
615 /// didn't come through a berry parse (e.g. freshly-resolved entries
616 /// in a new install) leave this `None` and the writer omits the
617 /// `checksum:` field, which berry tolerates at the default
618 /// `checksumBehavior: throw` when the cache is fresh.
619 pub yarn_checksum: Option<String>,
620 /// `engines:` from the package's manifest, round-tripped through
621 /// the lockfile so pnpm-style writers can emit the same flow-form
622 /// `engines: {node: '>=8'}` line pnpm writes. Empty map means
623 /// "no engines declared" — the writer skips the field entirely.
624 pub engines: BTreeMap<String, String>,
625 /// `bin:` map from the package's manifest, normalized to
626 /// `name → path`. An empty map means "no bins declared".
627 ///
628 /// pnpm-style writers derive `hasBin: true` from
629 /// `!bin.is_empty()` (they don't preserve the names/paths); bun's
630 /// format emits the full map on the package's meta block. Keeping
631 /// the map here lets both writers render byte-identical output
632 /// without an extra tarball-level re-parse.
633 pub bin: BTreeMap<String, String>,
634 /// Dependency ranges as declared in this package's own
635 /// `package.json` — keyed by dep name, values are the raw
636 /// specifiers (`"^4.1.0"`, `"~1.1.4"`, `"workspace:*"`, …).
637 ///
638 /// Distinct from [`Self::dependencies`], which stores the
639 /// *resolved* dep_path tail (`"4.3.0"`). npm / yarn / bun
640 /// lockfiles preserve the declared ranges on every nested
641 /// package entry — rewriting them to the resolved pins is the
642 /// biggest source of round-trip churn against those formats. This
643 /// map lets writers emit the declared range when available and
644 /// fall back to the resolved pin otherwise (e.g. when the source
645 /// lockfile was pnpm, whose `snapshots:` only carries pins).
646 ///
647 /// Empty means "unknown" — writers should fall back to pins.
648 /// Covers production *and* optional dependencies in one map since
649 /// a package can't declare the same name twice across those
650 /// sections.
651 pub declared_dependencies: BTreeMap<String, String>,
652 /// Package's `license` field, collapsed to the simple string
653 /// form. Round-tripped so npm's lockfile keeps its per-entry
654 /// `"license": "MIT"` line; pnpm / yarn / bun don't record
655 /// licenses and leave this `None` on parse.
656 pub license: Option<String>,
657 /// Package's funding URL, extracted from whatever shape the
658 /// manifest's `funding:` field took (string / object / array).
659 /// Round-tripped so npm's lockfile keeps its per-entry
660 /// `"funding": {"url": "…"}` block.
661 pub funding_url: Option<String>,
662 /// Per-package-meta extras preserved verbatim from the source
663 /// lockfile. Captures fields the typed model doesn't yet cover
664 /// (`deprecated`, `hasInstallScript`, bun's `optionalPeers`, and
665 /// anything a future lockfile bump adds) so a parse/write cycle
666 /// doesn't drop them. Each format's writer re-emits what makes
667 /// sense there — bun inlines the extras back on the package-entry
668 /// meta object, pnpm / yarn / npm currently ignore them.
669 pub extra_meta: BTreeMap<String, serde_json::Value>,
670}
671
672impl LockedPackage {
673 /// The package name to use for registry / store operations — the real
674 /// name behind an npm-alias when aliased, otherwise just `name`. Used
675 /// at every site that derives a tarball URL, a packument URL, or an
676 /// aube-store cache key so aliased entries hit the actual package
677 /// instead of the alias-qualified name.
678 pub fn registry_name(&self) -> &str {
679 self.alias_of.as_deref().unwrap_or(&self.name)
680 }
681
682 /// Canonical `"name@version"` key used as a handle in patches,
683 /// approve-builds prompts, lockfile canonical maps, and display
684 /// paths. Not the dep-path — that includes peer-context suffixes.
685 pub fn spec_key(&self) -> String {
686 format!("{}@{}", self.name, self.version)
687 }
688}
689
690/// Metadata about a single declared peer dependency. Matches the shape of
691/// `peerDependenciesMeta` in package.json.
692#[derive(Debug, Clone, Default, PartialEq, Eq)]
693pub struct PeerDepMeta {
694 /// When true, an unmet peer is silently allowed rather than warned about.
695 pub optional: bool,
696}
697
698/// Which source lockfile format was parsed.
699#[derive(Debug, Clone, Copy, PartialEq, Eq)]
700pub enum LockfileKind {
701 /// `aube-lock.yaml` — aube's default lockfile when no existing
702 /// lockfile is present. Same on-disk format as pnpm v9 for now
703 /// (we piggyback on pnpm::read/write).
704 Aube,
705 /// `pnpm-lock.yaml` — pnpm v9 format. If this is the existing
706 /// project lockfile, aube reads and writes it in place.
707 Pnpm,
708 Npm,
709 /// `yarn.lock` v1 (classic yarn). Line-based text format with
710 /// 2-space indented fields.
711 Yarn,
712 /// `yarn.lock` v2+ (yarn berry). YAML format with `__metadata:`
713 /// header, `resolution:` / `checksum:` fields, and
714 /// `languageName` / `linkType`. Same filename as `Yarn`; detection
715 /// peeks at the content for the `__metadata:` marker to pick
716 /// between the two.
717 YarnBerry,
718 NpmShrinkwrap,
719 Bun,
720}
721
722impl LockfileKind {
723 pub fn filename(self) -> &'static str {
724 match self {
725 LockfileKind::Aube => "aube-lock.yaml",
726 LockfileKind::Pnpm => "pnpm-lock.yaml",
727 LockfileKind::Npm => "package-lock.json",
728 LockfileKind::Yarn | LockfileKind::YarnBerry => "yarn.lock",
729 LockfileKind::NpmShrinkwrap => "npm-shrinkwrap.json",
730 LockfileKind::Bun => "bun.lock",
731 }
732 }
733}
734
735impl LockfileGraph {
736 /// Get all direct dependencies of the root project.
737 pub fn root_deps(&self) -> &[DirectDep] {
738 self.importers.get(".").map(|v| v.as_slice()).unwrap_or(&[])
739 }
740
741 /// Get a package by its dep_path key.
742 pub fn get_package(&self, dep_path: &str) -> Option<&LockedPackage> {
743 self.packages.get(dep_path)
744 }
745
746 /// `true` when at least one package in the graph carries a
747 /// non-empty `bin` map — a cheap signal that the source (lockfile
748 /// parser or fresh resolve) populated bin metadata. Bin-linking
749 /// passes use this to short-circuit the `package.json` read on
750 /// packages whose `bin` is empty (95%+ of a typical graph).
751 ///
752 /// The pnpm, bun, npm, and aube parsers all fill `bin`; a fresh
753 /// resolve fills it from packument data. The yarn-classic parser
754 /// leaves it empty, so a graph loaded exclusively from `yarn.lock`
755 /// returns `false` here and bin linking falls back to the full
756 /// `package.json` read. That's a correctness-over-speed choice:
757 /// misreading "empty" as "no bin" on yarn would silently drop
758 /// executables from `node_modules/.bin/`.
759 pub fn has_bin_metadata(&self) -> bool {
760 self.packages.values().any(|p| !p.bin.is_empty())
761 }
762
763 /// BFS the transitive closure of `roots` through `self.packages`,
764 /// returning every reachable dep_path (roots included). Missing
765 /// roots are skipped silently — a root without a matching package
766 /// is treated as a leaf, which matches what `filter_deps` /
767 /// `subset_to_importer` need when a retained importer points at a
768 /// package that was never fully installed (e.g. optional deps
769 /// filtered out on this platform).
770 ///
771 /// `LockedPackage.dependencies` maps `child_name → dep_path tail`,
772 /// so each child's full key reconstructs as `{child_name}@{tail}`.
773 fn transitive_closure<'a>(
774 &self,
775 roots: impl IntoIterator<Item = &'a str>,
776 ) -> std::collections::HashSet<String> {
777 let mut reachable: std::collections::HashSet<String> = std::collections::HashSet::new();
778 let mut queue: std::collections::VecDeque<String> = std::collections::VecDeque::new();
779 for root in roots {
780 if reachable.insert(root.to_string()) {
781 queue.push_back(root.to_string());
782 }
783 }
784 while let Some(dep_path) = queue.pop_front() {
785 let Some(pkg) = self.packages.get(&dep_path) else {
786 continue;
787 };
788 for (child_name, child_version) in &pkg.dependencies {
789 let child_key = format!("{child_name}@{child_version}");
790 if reachable.insert(child_key.clone()) {
791 queue.push_back(child_key);
792 }
793 }
794 }
795 reachable
796 }
797
798 /// Clone only the `packages` entries whose keys are in `reachable`.
799 /// Paired with `transitive_closure` to produce the pruned
800 /// `LockfileGraph.packages` for `filter_deps` / `subset_to_importer`.
801 fn packages_restricted_to(
802 &self,
803 reachable: &std::collections::HashSet<String>,
804 ) -> BTreeMap<String, LockedPackage> {
805 self.packages
806 .iter()
807 .filter(|(dep_path, _)| reachable.contains(*dep_path))
808 .map(|(k, v)| (k.clone(), v.clone()))
809 .collect()
810 }
811
812 /// Produce a new `LockfileGraph` containing only the direct deps that match
813 /// `keep` and the transitive deps reachable from them.
814 ///
815 /// Used by `install --prod` to drop `DepType::Dev` roots and everything
816 /// only reachable through them, and by `install --no-optional` for optional
817 /// deps. The filter runs over every importer's direct-dep list, so workspace
818 /// projects behave correctly.
819 ///
820 /// Packages that are reachable from a retained root through a transitive
821 /// chain are kept even if a pruned dev dep also happened to depend on them —
822 /// the check is "is this package reachable from any retained root?", not
823 /// "was this package introduced by a retained root?".
824 pub fn filter_deps<F>(&self, keep: F) -> LockfileGraph
825 where
826 F: Fn(&DirectDep) -> bool,
827 {
828 // Filter each importer's DirectDep list.
829 let importers: BTreeMap<String, Vec<DirectDep>> = self
830 .importers
831 .iter()
832 .map(|(path, deps)| {
833 let filtered: Vec<DirectDep> = deps.iter().filter(|d| keep(d)).cloned().collect();
834 (path.clone(), filtered)
835 })
836 .collect();
837
838 // BFS from every retained root across every importer.
839 let reachable = self.transitive_closure(
840 importers
841 .values()
842 .flat_map(|deps| deps.iter().map(|d| d.dep_path.as_str())),
843 );
844 let packages = self.packages_restricted_to(&reachable);
845
846 LockfileGraph {
847 importers,
848 packages,
849 // Preserve the source graph's settings — filter is a
850 // structural operation, not a resolution-mode reset.
851 // Writing the filtered graph (e.g. from `aube prune`) must
852 // emit the same `settings:` header the user chose.
853 settings: self.settings.clone(),
854 // Overrides are part of the user's resolution intent and
855 // should survive structural filters like `aube prune`.
856 overrides: self.overrides.clone(),
857 ignored_optional_dependencies: self.ignored_optional_dependencies.clone(),
858 // Times follow the same round-trip invariant as settings:
859 // filter doesn't change what versions are locked, so the
860 // per-package publish timestamps carry through unchanged.
861 times: self.times.clone(),
862 skipped_optional_dependencies: self.skipped_optional_dependencies.clone(),
863 catalogs: self.catalogs.clone(),
864 bun_config_version: self.bun_config_version,
865 patched_dependencies: self.patched_dependencies.clone(),
866 trusted_dependencies: self.trusted_dependencies.clone(),
867 extra_fields: self.extra_fields.clone(),
868 workspace_extra_fields: self.workspace_extra_fields.clone(),
869 }
870 }
871
872 /// Produce a new `LockfileGraph` rooted at the importer at
873 /// `importer_path`, with its transitive closure preserved and every
874 /// other importer dropped. The retained importer is remapped to
875 /// `"."` because the consumer installs the result as a standalone
876 /// project.
877 ///
878 /// Used by `aube deploy`: reading the source workspace lockfile
879 /// and subsetting it to the deployed package lets a frozen install
880 /// in the target reproduce the workspace's exact versions without
881 /// re-resolving against the registry. `keep` filters the importer's
882 /// direct deps the same way `filter_deps` does, so `--prod` /
883 /// `--dev` / `--no-optional` deploys drop the matching roots.
884 ///
885 /// Returns `None` if `importer_path` is not present in
886 /// `self.importers`. Graph-wide metadata (`settings`, `overrides`,
887 /// `times`, `catalogs`, `ignored_optional_dependencies`) is copied
888 /// verbatim — structural pruning, not a resolution-mode reset.
889 /// Callers targeting a non-workspace install may want to clear
890 /// workspace-scope fields that would otherwise trigger drift
891 /// detection against a rewritten target manifest.
892 pub fn subset_to_importer<F>(&self, importer_path: &str, keep: F) -> Option<LockfileGraph>
893 where
894 F: Fn(&DirectDep) -> bool,
895 {
896 let src_deps = self.importers.get(importer_path)?;
897 let kept: Vec<DirectDep> = src_deps.iter().filter(|d| keep(d)).cloned().collect();
898
899 // BFS the transitive closure from retained roots, scoped to
900 // just this importer's kept direct deps.
901 let reachable = self.transitive_closure(kept.iter().map(|d| d.dep_path.as_str()));
902 let packages = self.packages_restricted_to(&reachable);
903
904 // Per-importer metadata: keep only the retained importer's
905 // entry, rekeyed to `.`. The source workspace's other
906 // importers are meaningless in a target that has exactly one.
907 let mut skipped_optional_dependencies = BTreeMap::new();
908 if let Some(skipped) = self.skipped_optional_dependencies.get(importer_path) {
909 skipped_optional_dependencies.insert(".".to_string(), skipped.clone());
910 }
911
912 let mut importers = BTreeMap::new();
913 importers.insert(".".to_string(), kept);
914
915 Some(LockfileGraph {
916 importers,
917 packages,
918 settings: self.settings.clone(),
919 overrides: self.overrides.clone(),
920 ignored_optional_dependencies: self.ignored_optional_dependencies.clone(),
921 times: self.times.clone(),
922 skipped_optional_dependencies,
923 catalogs: self.catalogs.clone(),
924 bun_config_version: self.bun_config_version,
925 patched_dependencies: self.patched_dependencies.clone(),
926 trusted_dependencies: self.trusted_dependencies.clone(),
927 extra_fields: self.extra_fields.clone(),
928 workspace_extra_fields: self.workspace_extra_fields.clone(),
929 })
930 }
931
932 /// Overlay per-package metadata fields from `prior` onto `self`
933 /// for every `(name, version)` that survives in both graphs.
934 /// Carries forward only fields the abbreviated packument (npm
935 /// corgi) doesn't ship — `license`, `funding_url`, and the
936 /// bun-format `configVersion` — so a fresh re-resolve against
937 /// the same spec set doesn't lose them.
938 ///
939 /// Keyed by canonical `name@version`, so a peer-context rewrite
940 /// between the old and new graph still lines up. `self`'s own
941 /// values win when set (fresh registry data is authoritative);
942 /// `prior`'s fill in only the `None` / empty slots. Safe to call
943 /// on any pair of graphs — parsing the old lockfile is the
944 /// caller's concern.
945 pub fn overlay_metadata_from(&mut self, prior: &LockfileGraph) {
946 // Build a canonical `name@version → prior pkg` lookup once so
947 // repeated peer-context variants in `self.packages` all hit
948 // the same prior entry.
949 let prior_index = build_canonical_map(prior);
950 for pkg in self.packages.values_mut() {
951 let key = pkg.spec_key();
952 let Some(prior_pkg) = prior_index.get(&key) else {
953 continue;
954 };
955 if pkg.license.is_none() && prior_pkg.license.is_some() {
956 pkg.license = prior_pkg.license.clone();
957 }
958 if pkg.funding_url.is_none() && prior_pkg.funding_url.is_some() {
959 pkg.funding_url = prior_pkg.funding_url.clone();
960 }
961 // Per-entry extras (`deprecated`, `optionalPeers`,
962 // format-specific fields bun/npm/yarn wrote into the
963 // meta block) can't be recovered from a fresh resolve,
964 // so carry them forward when the newer graph doesn't
965 // already carry its own. `self`-side keys always win.
966 for (k, v) in &prior_pkg.extra_meta {
967 pkg.extra_meta.entry(k.clone()).or_insert_with(|| v.clone());
968 }
969 }
970 if self.bun_config_version.is_none() {
971 self.bun_config_version = prior.bun_config_version;
972 }
973 if self.patched_dependencies.is_empty() {
974 self.patched_dependencies = prior.patched_dependencies.clone();
975 }
976 if self.trusted_dependencies.is_empty() {
977 self.trusted_dependencies = prior.trusted_dependencies.clone();
978 }
979 if self.extra_fields.is_empty() {
980 self.extra_fields = prior.extra_fields.clone();
981 }
982 if self.workspace_extra_fields.is_empty() {
983 self.workspace_extra_fields = prior.workspace_extra_fields.clone();
984 }
985 }
986
987 /// Compare this lockfile's root importer against a single manifest.
988 ///
989 /// Mirrors pnpm's `prefer-frozen-lockfile` check: a lockfile is "fresh" iff
990 /// every direct dep specifier in `package.json` exactly matches the specifier
991 /// recorded in the lockfile (string compare, not semver). Used to decide
992 /// whether to skip resolution and trust the lockfile (`Fresh`) or fall back
993 /// to a full re-resolve (`Stale { reason }`).
994 ///
995 /// For workspace projects, use [`check_drift_workspace`] instead — this
996 /// method only inspects the root importer.
997 ///
998 /// `workspace_overrides` is the `overrides:` block from
999 /// `pnpm-workspace.yaml` (pnpm v10 moved overrides there). Pass an
1000 /// empty map when the project has no workspace-yaml overrides. Keys
1001 /// are merged on top of `manifest.overrides_map()` before the drift
1002 /// comparison, matching the resolver's effective-override set —
1003 /// otherwise a lockfile written with a workspace override
1004 /// immediately looks stale on the next `--frozen-lockfile` run.
1005 ///
1006 /// `workspace_ignored_optional` is the same idea for
1007 /// `pnpm-workspace.yaml`'s `ignoredOptionalDependencies` block:
1008 /// the resolver unions it with the manifest's list, so the drift
1009 /// check has to see the same union or a freshly-written lockfile
1010 /// immediately reads as stale.
1011 ///
1012 /// `workspace_catalogs` is the `catalog:` / `catalogs:` block from
1013 /// `pnpm-workspace.yaml`. pnpm resolves `catalog:` references in
1014 /// override values against this map before writing the lockfile
1015 /// and before comparing on re-install, so both sides of the drift
1016 /// check have to see the catalog-resolved form — otherwise a
1017 /// `"lodash": "catalog:"` override reads as stale against a
1018 /// lockfile that recorded the resolved `"lodash": "4.17.21"`.
1019 ///
1020 /// Lockfile formats that don't record specifiers (npm, yarn, bun) always
1021 /// return `Fresh` since we have no way to detect drift without re-resolving.
1022 ///
1023 /// [`check_drift_workspace`]: Self::check_drift_workspace
1024 pub fn check_drift(
1025 &self,
1026 manifest: &aube_manifest::PackageJson,
1027 workspace_overrides: &BTreeMap<String, String>,
1028 workspace_ignored_optional: &[String],
1029 workspace_catalogs: &BTreeMap<String, BTreeMap<String, String>>,
1030 ) -> DriftStatus {
1031 let effective = resolve_catalog_refs_in_overrides(
1032 &merge_manifest_and_workspace_overrides(manifest, workspace_overrides),
1033 workspace_catalogs,
1034 );
1035 let locked = resolve_catalog_refs_in_overrides(&self.overrides, workspace_catalogs);
1036 if let Some(reason) = overrides_drift_reason(&locked, &effective) {
1037 return DriftStatus::Stale { reason };
1038 }
1039 let mut effective_ignored = manifest.pnpm_ignored_optional_dependencies();
1040 effective_ignored.extend(workspace_ignored_optional.iter().cloned());
1041 if let Some(reason) =
1042 ignored_optional_drift_reason(&self.ignored_optional_dependencies, &effective_ignored)
1043 {
1044 return DriftStatus::Stale { reason };
1045 }
1046 self.check_drift_for_importer(".", manifest, &effective)
1047 }
1048
1049 /// Workspace-aware drift check.
1050 ///
1051 /// Each entry in `manifests` is `(importer_path, manifest)` — for example
1052 /// `(".", root_manifest), ("packages/app", app_manifest), ...`. Every
1053 /// importer is checked against its own manifest; the first stale importer
1054 /// determines the result.
1055 ///
1056 /// See [`check_drift`] for the `workspace_overrides` contract.
1057 ///
1058 /// [`check_drift`]: Self::check_drift
1059 pub fn check_drift_workspace(
1060 &self,
1061 manifests: &[(String, aube_manifest::PackageJson)],
1062 workspace_overrides: &BTreeMap<String, String>,
1063 workspace_ignored_optional: &[String],
1064 workspace_catalogs: &BTreeMap<String, BTreeMap<String, String>>,
1065 ) -> DriftStatus {
1066 // Override drift is checked once at the workspace level, against
1067 // the root manifest. Workspace-package manifests may declare
1068 // their own `overrides` blocks but pnpm only honors the root's,
1069 // so we mirror that here.
1070 let effective_overrides = match manifests.iter().find(|(p, _)| p == ".") {
1071 Some((_, root_manifest)) => {
1072 let effective = resolve_catalog_refs_in_overrides(
1073 &merge_manifest_and_workspace_overrides(root_manifest, workspace_overrides),
1074 workspace_catalogs,
1075 );
1076 let locked = resolve_catalog_refs_in_overrides(&self.overrides, workspace_catalogs);
1077 if let Some(reason) = overrides_drift_reason(&locked, &effective) {
1078 return DriftStatus::Stale { reason };
1079 }
1080 let mut effective_ignored = root_manifest.pnpm_ignored_optional_dependencies();
1081 effective_ignored.extend(workspace_ignored_optional.iter().cloned());
1082 if let Some(reason) = ignored_optional_drift_reason(
1083 &self.ignored_optional_dependencies,
1084 &effective_ignored,
1085 ) {
1086 return DriftStatus::Stale { reason };
1087 }
1088 effective
1089 }
1090 None => BTreeMap::new(),
1091 };
1092 for (importer_path, manifest) in manifests {
1093 match self.check_drift_for_importer(importer_path, manifest, &effective_overrides) {
1094 DriftStatus::Fresh => continue,
1095 stale => return stale,
1096 }
1097 }
1098 DriftStatus::Fresh
1099 }
1100
1101 /// Compare this lockfile's catalog snapshot against the current
1102 /// `pnpm-workspace.yaml` catalogs.
1103 ///
1104 /// pnpm only writes catalog entries that at least one importer
1105 /// references — unused entries are absent from the lockfile. So
1106 /// "missing from lockfile" doesn't mean "added by the user", it
1107 /// means "declared but unreferenced", which is not drift. The
1108 /// transition from unused → used is caught by the importer-level
1109 /// drift check, since a fresh `catalog:` reference shows up as a
1110 /// new dep in some `package.json`.
1111 ///
1112 /// We fire on two cases only:
1113 /// - the spec changed for an entry the lockfile already records
1114 /// (the entry is in use, and re-resolution must rerun);
1115 /// - the workspace removed an entry that the lockfile records
1116 /// (the importer using `catalog:` now points at nothing).
1117 ///
1118 /// Resolved versions are deliberately not part of the comparison —
1119 /// the version is an *output* of resolution, so a stale lockfile
1120 /// version is what re-resolution is supposed to fix. Drift only
1121 /// fires on user intent (the specifier).
1122 pub fn check_catalogs_drift(
1123 &self,
1124 workspace_catalogs: &BTreeMap<String, BTreeMap<String, String>>,
1125 ) -> DriftStatus {
1126 for (cat_name, cat) in workspace_catalogs {
1127 let Some(locked) = self.catalogs.get(cat_name) else {
1128 continue;
1129 };
1130 for (pkg, spec) in cat {
1131 if let Some(entry) = locked.get(pkg)
1132 && entry.specifier != *spec
1133 {
1134 return DriftStatus::Stale {
1135 reason: format!(
1136 "catalogs.{cat_name}.{pkg}: workspace says {spec}, lockfile says {}",
1137 entry.specifier
1138 ),
1139 };
1140 }
1141 }
1142 }
1143 for (cat_name, cat) in &self.catalogs {
1144 let workspace_cat = workspace_catalogs.get(cat_name);
1145 for pkg in cat.keys() {
1146 if workspace_cat.map(|c| c.contains_key(pkg)) != Some(true) {
1147 return DriftStatus::Stale {
1148 reason: format!("catalogs.{cat_name}: workspace removed {pkg}"),
1149 };
1150 }
1151 }
1152 }
1153 DriftStatus::Fresh
1154 }
1155
1156 /// Compare a single importer's `DirectDep` list against the corresponding
1157 /// `package.json`. Used by both [`check_drift`] and [`check_drift_workspace`].
1158 ///
1159 /// [`check_drift`]: Self::check_drift
1160 /// [`check_drift_workspace`]: Self::check_drift_workspace
1161 fn check_drift_for_importer(
1162 &self,
1163 importer_path: &str,
1164 manifest: &aube_manifest::PackageJson,
1165 effective_overrides: &BTreeMap<String, String>,
1166 ) -> DriftStatus {
1167 let label = if importer_path == "." {
1168 String::new()
1169 } else {
1170 format!("{importer_path}: ")
1171 };
1172
1173 let importer_deps: &[DirectDep] = self
1174 .importers
1175 .get(importer_path)
1176 .map(|v| v.as_slice())
1177 .unwrap_or(&[]);
1178
1179 // Skip the check entirely if no DirectDep has a specifier (non-pnpm format).
1180 if importer_deps.iter().all(|d| d.specifier.is_none()) {
1181 return DriftStatus::Fresh;
1182 }
1183 let lockfile_specs: BTreeMap<&str, &str> = importer_deps
1184 .iter()
1185 .filter_map(|d| d.specifier.as_deref().map(|s| (d.name.as_str(), s)))
1186 .collect();
1187
1188 // Optionals the previous resolve recorded as intentionally
1189 // skipped on this importer's platform — keyed by name, value
1190 // is the specifier captured at that time. Distinct from
1191 // `ignored_optional_dependencies`, which is the user's static
1192 // ignore list; this map captures *runtime* platform skips.
1193 let skipped_optionals: BTreeMap<&str, &str> = self
1194 .skipped_optional_dependencies
1195 .get(importer_path)
1196 .map(|m| m.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect())
1197 .unwrap_or_default();
1198
1199 // Iterate prod / dev / optional with a flag so the
1200 // skipped-optional exemption only applies to deps that came
1201 // from `optional_dependencies`. Without the flag, moving a
1202 // previously-skipped optional into `dependencies` with the same
1203 // specifier would silently report Fresh and the dep would
1204 // never install as a required dep.
1205 //
1206 // Optionals named in `ignored_optional_dependencies` are
1207 // dropped from the manifest-side scan: the resolver never
1208 // enqueues them, so the lockfile importer never has them
1209 // either, and the loop would otherwise report drift on every
1210 // install. (Their *spec* is still verified separately by the
1211 // round-tripped `ignored_optional_dependencies` block below.)
1212 let ignored = &self.ignored_optional_dependencies;
1213 let manifest_deps = manifest
1214 .dependencies
1215 .iter()
1216 .map(|(k, v)| (k, v, false))
1217 .chain(manifest.dev_dependencies.iter().map(|(k, v)| (k, v, false)))
1218 .chain(
1219 manifest
1220 .optional_dependencies
1221 .iter()
1222 .filter(|(name, _)| !ignored.contains(name.as_str()))
1223 .map(|(k, v)| (k, v, true)),
1224 );
1225
1226 for (name, spec, is_optional) in manifest_deps {
1227 match lockfile_specs.get(name.as_str()) {
1228 None => {
1229 // A *missing* optional dep is only "fresh" if the
1230 // previous resolve recorded it as intentionally
1231 // skipped (platform mismatch or
1232 // `pnpm.ignoredOptionalDependencies`) AND the
1233 // recorded specifier still matches what's in the
1234 // manifest. A genuinely *new* optional that the
1235 // resolver has never seen is real drift — without
1236 // that branch, adding `fsevents` to a fresh manifest
1237 // would silently never get installed.
1238 if is_optional && let Some(locked_spec) = skipped_optionals.get(name.as_str()) {
1239 if *locked_spec == spec {
1240 continue;
1241 }
1242 return DriftStatus::Stale {
1243 reason: format!(
1244 "{label}{name}: manifest says {spec}, lockfile (skipped) says {locked_spec}"
1245 ),
1246 };
1247 }
1248 return DriftStatus::Stale {
1249 reason: format!("{label}manifest adds {name}@{spec}"),
1250 };
1251 }
1252 Some(locked_spec) if *locked_spec != spec => {
1253 // pnpm rewrites the importer specifier to the
1254 // override-applied value when a bare-name override
1255 // fires, so a pnpm-generated lockfile shows
1256 // `specifier: 4.17.21` even though `package.json`
1257 // still reads `^4.17.0`. Accept that as fresh when
1258 // the effective override for this name matches the
1259 // lockfile's recorded spec — otherwise any
1260 // pnpm-written lockfile with overrides reads stale
1261 // on every frozen install.
1262 if let Some(override_spec) = effective_overrides.get(name.as_str())
1263 && override_spec == locked_spec
1264 {
1265 continue;
1266 }
1267 return DriftStatus::Stale {
1268 reason: format!(
1269 "{label}{name}: manifest says {spec}, lockfile says {locked_spec}"
1270 ),
1271 };
1272 }
1273 Some(_) => {}
1274 }
1275 }
1276
1277 // Anything in the lockfile but missing from the manifest is stale
1278 // — UNLESS it was auto-hoisted as a peer by the resolver. pnpm-style
1279 // `auto-install-peers=true` puts peers into the importer's
1280 // `dependencies` without the user having written them in
1281 // `package.json`, so we have to recognize those as derived state
1282 // rather than user intent.
1283 //
1284 // Critically, we identify an auto-hoisted entry by matching its
1285 // *recorded specifier* against peer ranges declared in the graph,
1286 // not just by name. A name-only check would silently exempt a
1287 // user-pinned `react` that the user later removed (if any package
1288 // anywhere in the graph peer-declares react, the name match would
1289 // fire and we'd report Fresh forever — defeating the drift check).
1290 //
1291 // The rule: a lockfile entry whose (name, specifier) pair exactly
1292 // matches some package's declared (peer_name, peer_range) is
1293 // auto-hoisted. If the user had pinned react with a different
1294 // specifier string and then removed it, the (name, specifier)
1295 // pair no longer matches any peer range, and drift correctly
1296 // fires so the resolver re-runs and rewrites the lockfile.
1297 let manifest_names: std::collections::HashSet<&str> = manifest
1298 .dependencies
1299 .keys()
1300 .chain(manifest.dev_dependencies.keys())
1301 .chain(
1302 manifest
1303 .optional_dependencies
1304 .keys()
1305 .filter(|name| !ignored.contains(name.as_str())),
1306 )
1307 .map(|s| s.as_str())
1308 .collect();
1309 let auto_hoisted_peer_specs: std::collections::HashSet<(&str, &str)> = self
1310 .packages
1311 .values()
1312 .flat_map(|p| {
1313 p.peer_dependencies
1314 .iter()
1315 .map(|(name, range)| (name.as_str(), range.as_str()))
1316 })
1317 .collect();
1318 for (locked_name, locked_spec) in &lockfile_specs {
1319 if manifest_names.contains(locked_name) {
1320 continue;
1321 }
1322 if auto_hoisted_peer_specs.contains(&(*locked_name, *locked_spec)) {
1323 continue;
1324 }
1325 return DriftStatus::Stale {
1326 reason: format!("{label}manifest removed {locked_name}"),
1327 };
1328 }
1329
1330 DriftStatus::Fresh
1331 }
1332}
1333
1334/// Merge `pnpm-workspace.yaml` overrides on top of the manifest's
1335/// `overrides_map()`. Workspace entries win on key conflict, matching
1336/// pnpm v10's behavior where the workspace yaml is the canonical
1337/// home for overrides. Callers pass this into `overrides_drift_reason`
1338/// so the drift check sees the same effective map the resolver used.
1339fn merge_manifest_and_workspace_overrides(
1340 manifest: &aube_manifest::PackageJson,
1341 workspace_overrides: &BTreeMap<String, String>,
1342) -> BTreeMap<String, String> {
1343 let mut out = manifest.overrides_map();
1344 for (k, v) in workspace_overrides {
1345 out.insert(k.clone(), v.clone());
1346 }
1347 out
1348}
1349
1350/// Rewrite `catalog:` / `catalog:<name>` override values to the catalog's
1351/// resolved range. pnpm writes resolved override values into the lockfile
1352/// and compares against the resolved form on re-install, so both sides
1353/// of the drift check have to see the catalog-substituted map — otherwise
1354/// a `"lodash": "catalog:"` workspace-yaml override reads as stale against
1355/// a lockfile that recorded `"lodash": "4.17.21"`. Unresolvable references
1356/// (missing catalog or missing entry) pass through untouched; the caller
1357/// would have errored at resolve time if this ever reached a real install,
1358/// so a drift-mismatch here is fine.
1359fn resolve_catalog_refs_in_overrides(
1360 overrides: &BTreeMap<String, String>,
1361 workspace_catalogs: &BTreeMap<String, BTreeMap<String, String>>,
1362) -> BTreeMap<String, String> {
1363 overrides
1364 .iter()
1365 .map(|(k, v)| {
1366 let resolved = v
1367 .strip_prefix("catalog:")
1368 .map(|tail| if tail.is_empty() { "default" } else { tail })
1369 .and_then(|cat_name| workspace_catalogs.get(cat_name))
1370 .and_then(|cat| cat.get(override_key_package_name(k)))
1371 .cloned()
1372 .unwrap_or_else(|| v.clone());
1373 (k.clone(), resolved)
1374 })
1375 .collect()
1376}
1377
1378/// Extract the package name from an override selector key so the catalog
1379/// can be looked up by pkg name. Handles bare (`lodash`), scoped
1380/// (`@babel/core`), ranged (`lodash@<5`), ancestor-chained
1381/// (`parent>lodash`), and combinations. Unparseable keys return the
1382/// input unchanged; the catalog lookup will then miss and leave the
1383/// value as-is.
1384fn override_key_package_name(key: &str) -> &str {
1385 let last = key.rsplit('>').next().unwrap_or(key);
1386 if let Some(after_scope) = last.strip_prefix('@') {
1387 match after_scope.find('@') {
1388 Some(idx) => &last[..idx + 1],
1389 None => last,
1390 }
1391 } else {
1392 match last.find('@') {
1393 Some(idx) => &last[..idx],
1394 None => last,
1395 }
1396 }
1397}
1398
1399/// Compare two override maps and return a human-readable reason
1400/// describing the first difference, or `None` if they're identical.
1401/// Drift messages cite the offending key by name so users can act on
1402/// them — `(lockfile: N entries, manifest: M entries)` is useless
1403/// when N == M but a value changed.
1404fn overrides_drift_reason(
1405 lockfile: &BTreeMap<String, String>,
1406 manifest: &BTreeMap<String, String>,
1407) -> Option<String> {
1408 for (k, v) in manifest {
1409 match lockfile.get(k) {
1410 None => return Some(format!("overrides: manifest adds {k}@{v}")),
1411 Some(locked) if locked != v => {
1412 return Some(format!("overrides: {k} changed ({locked} → {v})"));
1413 }
1414 Some(_) => {}
1415 }
1416 }
1417 for k in lockfile.keys() {
1418 if !manifest.contains_key(k) {
1419 return Some(format!("overrides: manifest removes {k}"));
1420 }
1421 }
1422 None
1423}
1424
1425/// Compare two `ignoredOptionalDependencies` sets and return a drift
1426/// reason string for the first difference, or `None` if identical.
1427fn ignored_optional_drift_reason(
1428 lockfile: &BTreeSet<String>,
1429 manifest: &BTreeSet<String>,
1430) -> Option<String> {
1431 for name in manifest {
1432 if !lockfile.contains(name) {
1433 return Some(format!("ignoredOptionalDependencies: manifest adds {name}"));
1434 }
1435 }
1436 for name in lockfile {
1437 if !manifest.contains(name) {
1438 return Some(format!(
1439 "ignoredOptionalDependencies: manifest removes {name}"
1440 ));
1441 }
1442 }
1443 None
1444}
1445
1446/// Result of comparing a lockfile against a manifest.
1447#[derive(Debug, Clone, PartialEq, Eq)]
1448pub enum DriftStatus {
1449 /// The lockfile is in sync with the manifest. Safe to use without re-resolving.
1450 Fresh,
1451 /// The lockfile is out of date. The reason describes the first mismatch found.
1452 Stale { reason: String },
1453}
1454
1455/// Atomic lockfile write. Tempfile in the same dir, fsync, rename
1456/// over the target. Every format writer goes through this so a
1457/// crash or Ctrl+C mid-write cannot leave a truncated lockfile on
1458/// disk. Rename is atomic on POSIX, on Windows MoveFileEx gives
1459/// the same guarantee post Win10. Caller passes the serialized
1460/// bytes already formatted, this just handles the IO layer.
1461pub(crate) fn atomic_write_lockfile(path: &Path, body: &[u8]) -> Result<(), Error> {
1462 aube_util::fs_atomic::atomic_write(path, body).map_err(|e| Error::Io(path.to_path_buf(), e))
1463}
1464
1465/// Write a lockfile to the given project directory using aube's default
1466/// filename (`aube-lock.yaml`, or `aube-lock.<branch>.yaml` when branch
1467/// lockfiles are enabled).
1468pub fn write_lockfile(
1469 project_dir: &Path,
1470 graph: &LockfileGraph,
1471 manifest: &aube_manifest::PackageJson,
1472) -> Result<(), Error> {
1473 write_lockfile_as(project_dir, graph, manifest, LockfileKind::Aube)?;
1474 Ok(())
1475}
1476
1477/// Write a lockfile using the existing project lockfile kind, or
1478/// Collapse peer-context variants from `graph` into a single map keyed
1479/// by `"name@version"`, pointing at the first-seen package. Several
1480/// writers (npm, yarn, …) share this shape: one canonical entry per
1481/// `(name, version)` pair regardless of how many peer suffixes the
1482/// full graph emits.
1483pub fn build_canonical_map(graph: &LockfileGraph) -> BTreeMap<String, &LockedPackage> {
1484 let mut canonical: BTreeMap<String, &LockedPackage> = BTreeMap::new();
1485 for pkg in graph.packages.values() {
1486 canonical.entry(pkg.spec_key()).or_insert(pkg);
1487 }
1488 canonical
1489}
1490
1491/// `aube-lock.yaml` when the project does not have one yet.
1492///
1493/// This is the default write path for commands that mutate the active
1494/// project graph (`install`, `add`, `remove`, `update`, `dedupe`, ...).
1495pub fn write_lockfile_preserving_existing(
1496 project_dir: &Path,
1497 graph: &LockfileGraph,
1498 manifest: &aube_manifest::PackageJson,
1499) -> Result<PathBuf, Error> {
1500 let kind = detect_existing_lockfile_kind(project_dir).unwrap_or(LockfileKind::Aube);
1501 write_lockfile_as(project_dir, graph, manifest, kind)
1502}
1503
1504/// Write `graph` in the requested lockfile format into `project_dir`.
1505///
1506/// Returns the path that was actually written (useful for logging
1507/// since `Aube` may resolve to a branch-specific filename). Callers
1508/// that want to preserve whatever format was already on disk should
1509/// pair this with [`detect_existing_lockfile_kind`].
1510///
1511/// All supported formats: `Aube`, `Pnpm`, `Npm`, `NpmShrinkwrap`,
1512/// `Yarn`, and `Bun`. This preserves the lockfile kind that already
1513/// exists in the project; callers should pass `Aube` only when no
1514/// lockfile exists yet. See each writer module's doc comment for
1515/// per-format lossy areas (peer contexts, `resolved` URLs, etc.).
1516pub fn write_lockfile_as(
1517 project_dir: &Path,
1518 graph: &LockfileGraph,
1519 manifest: &aube_manifest::PackageJson,
1520 kind: LockfileKind,
1521) -> Result<PathBuf, Error> {
1522 let filename = match kind {
1523 LockfileKind::Aube => aube_lock_filename(project_dir),
1524 LockfileKind::Pnpm => pnpm_lock_filename(project_dir),
1525 other => other.filename().to_string(),
1526 };
1527 let path = project_dir.join(&filename);
1528 match kind {
1529 LockfileKind::Aube | LockfileKind::Pnpm => pnpm::write(&path, graph, manifest)?,
1530 LockfileKind::Npm | LockfileKind::NpmShrinkwrap => npm::write(&path, graph, manifest)?,
1531 LockfileKind::Yarn => yarn::write_classic(&path, graph, manifest)?,
1532 LockfileKind::YarnBerry => yarn::write_berry(&path, graph, manifest)?,
1533 LockfileKind::Bun => bun::write(&path, graph, manifest)?,
1534 }
1535 Ok(path)
1536}
1537
1538/// Return the [`LockfileKind`] of the lockfile already on disk in
1539/// `project_dir`, if any. Follows the same precedence as
1540/// [`parse_lockfile_with_kind`] (aube > pnpm > bun > yarn >
1541/// npm-shrinkwrap > npm). Used by install to preserve a project's
1542/// existing lockfile format when rewriting after a re-resolve — a
1543/// user with only `pnpm-lock.yaml`, `package-lock.json`, or another
1544/// supported lockfile gets that file written back, not a surprise
1545/// `aube-lock.yaml` alongside it.
1546pub fn detect_existing_lockfile_kind(project_dir: &Path) -> Option<LockfileKind> {
1547 for (path, kind) in lockfile_candidates(project_dir, /*include_aube=*/ true) {
1548 if path.exists() {
1549 return Some(refine_yarn_kind(&path, kind));
1550 }
1551 }
1552 None
1553}
1554
1555/// Resolve the canonical lockfile filename for `project_dir` (aube's own).
1556///
1557/// Returns `aube-lock.<branch>.yaml` when `gitBranchLockfile: true` is
1558/// set in `pnpm-workspace.yaml` (or `aube-workspace.yaml`) and the
1559/// project is inside a git checkout with a current branch. Forward
1560/// slashes in the branch name are encoded as `!`, matching pnpm. Falls
1561/// back to plain `aube-lock.yaml` in every other case.
1562///
1563/// Memoized per `project_dir` for the lifetime of the process: a
1564/// single install resolves this 3–5 times (lockfile_candidates,
1565/// write_lockfile, debug log, state read/write), and
1566/// `check_needs_install` runs on every `aube run`/`aube exec` via
1567/// `ensure_installed`. Without caching, every command would pay for a
1568/// YAML parse + a `git branch --show-current` subprocess just to
1569/// recompute a value that can't change mid-process.
1570pub fn aube_lock_filename(project_dir: &Path) -> String {
1571 use std::sync::{Mutex, OnceLock};
1572 static CACHE: OnceLock<Mutex<std::collections::HashMap<PathBuf, String>>> = OnceLock::new();
1573 let cache = CACHE.get_or_init(|| Mutex::new(std::collections::HashMap::new()));
1574 if let Ok(map) = cache.lock()
1575 && let Some(hit) = map.get(project_dir)
1576 {
1577 return hit.clone();
1578 }
1579 let resolved = if !git_branch_lockfile_enabled(project_dir) {
1580 "aube-lock.yaml".to_string()
1581 } else {
1582 match current_git_branch(project_dir) {
1583 Some(branch) => format!("aube-lock.{}.yaml", branch.replace('/', "!")),
1584 None => "aube-lock.yaml".to_string(),
1585 }
1586 };
1587 if let Ok(mut map) = cache.lock() {
1588 map.insert(project_dir.to_path_buf(), resolved.clone());
1589 }
1590 resolved
1591}
1592
1593/// Resolve the pnpm lockfile filename for `project_dir`.
1594///
1595/// Mirrors [`aube_lock_filename`] for branch lockfiles, but keeps the
1596/// pnpm filename prefix so projects with an existing `pnpm-lock.yaml`
1597/// keep writing to pnpm's file.
1598pub fn pnpm_lock_filename(project_dir: &Path) -> String {
1599 let aube_name = aube_lock_filename(project_dir);
1600 // `aube_lock_filename` always returns "aube-lock.<rest>", so strip_prefix
1601 // always succeeds. The fallback is purely defensive.
1602 aube_name
1603 .strip_prefix("aube-lock.")
1604 .map(|rest| format!("pnpm-lock.{rest}"))
1605 .unwrap_or_else(|| "pnpm-lock.yaml".to_string())
1606}
1607
1608fn git_branch_lockfile_enabled(project_dir: &Path) -> bool {
1609 // Goes through the build-time-generated typed accessor in
1610 // `aube_settings::resolved` so the alias list is driven off
1611 // `settings.toml` — no hand-maintained typed field. This path
1612 // reads only `pnpm-workspace.yaml`; `.npmrc` values are out of
1613 // scope here because aube-lockfile doesn't want a dependency on
1614 // aube-registry just to load npmrc (and the historical behavior
1615 // never read `.npmrc` either).
1616 let Ok(raw) = aube_manifest::workspace::load_raw(project_dir) else {
1617 return false;
1618 };
1619 let npmrc: Vec<(String, String)> = Vec::new();
1620 let ctx = aube_settings::ResolveCtx::files_only(&npmrc, &raw);
1621 aube_settings::resolved::git_branch_lockfile(&ctx)
1622}
1623
1624pub(crate) fn current_git_branch(project_dir: &Path) -> Option<String> {
1625 let out = std::process::Command::new("git")
1626 .args(["-C"])
1627 .arg(project_dir)
1628 .args(["branch", "--show-current"])
1629 .output()
1630 .ok()?;
1631 if !out.status.success() {
1632 return None;
1633 }
1634 let branch = String::from_utf8(out.stdout).ok()?.trim().to_string();
1635 if branch.is_empty() {
1636 None
1637 } else {
1638 Some(branch)
1639 }
1640}
1641
1642/// Detect and parse the lockfile in the given project directory.
1643///
1644/// Priority: `aube-lock.yaml` → `pnpm-lock.yaml` → `bun.lock` →
1645/// `yarn.lock` → `npm-shrinkwrap.json` → `package-lock.json`.
1646/// (Shrinkwrap takes priority over package-lock.json when both exist, matching npm's behavior.)
1647///
1648/// `manifest` is needed to classify direct vs transitive deps when
1649/// reading yarn.lock (which has no notion of that distinction).
1650pub fn parse_lockfile(
1651 project_dir: &Path,
1652 manifest: &aube_manifest::PackageJson,
1653) -> Result<LockfileGraph, Error> {
1654 let (graph, _kind) = parse_lockfile_with_kind(project_dir, manifest)?;
1655 Ok(graph)
1656}
1657
1658/// Like [`parse_lockfile`] but also returns which format was read.
1659pub fn parse_lockfile_with_kind(
1660 project_dir: &Path,
1661 manifest: &aube_manifest::PackageJson,
1662) -> Result<(LockfileGraph, LockfileKind), Error> {
1663 reject_bun_binary(project_dir)?;
1664 for (path, kind) in lockfile_candidates(project_dir, /*include_aube=*/ true) {
1665 if !path.exists() {
1666 continue;
1667 }
1668 let kind = refine_yarn_kind(&path, kind);
1669 let graph = parse_one(&path, kind, manifest)?;
1670 return Ok((graph, kind));
1671 }
1672 Err(Error::NotFound(project_dir.to_path_buf()))
1673}
1674
1675/// Variant of [`parse_lockfile_with_kind`] used by `aube import`.
1676///
1677/// Skips `aube-lock.yaml` — if the project already has one, there's
1678/// nothing to import. `pnpm-lock.yaml` *is* included because the whole
1679/// point of `aube import` is to convert a foreign lockfile (including
1680/// pnpm's) into `aube-lock.yaml`.
1681pub fn parse_for_import(
1682 project_dir: &Path,
1683 manifest: &aube_manifest::PackageJson,
1684) -> Result<(LockfileGraph, LockfileKind), Error> {
1685 reject_bun_binary(project_dir)?;
1686 for (path, kind) in lockfile_candidates(project_dir, /*include_aube=*/ false) {
1687 if !path.exists() {
1688 continue;
1689 }
1690 let kind = refine_yarn_kind(&path, kind);
1691 let graph = parse_one(&path, kind, manifest)?;
1692 return Ok((graph, kind));
1693 }
1694 Err(Error::NotFound(project_dir.to_path_buf()))
1695}
1696
1697/// If only `bun.lockb` is present (without a text `bun.lock`), surface an
1698/// actionable error instead of silently falling through to another format.
1699fn reject_bun_binary(project_dir: &Path) -> Result<(), Error> {
1700 let lockb = project_dir.join("bun.lockb");
1701 let text = project_dir.join("bun.lock");
1702 if lockb.exists() && !text.exists() {
1703 return Err(Error::parse(
1704 &lockb,
1705 "bun.lockb (binary format) is not supported — run `bun install --save-text-lockfile` to generate a bun.lock text file first, or upgrade to bun 1.2+ where text is the default",
1706 ));
1707 }
1708 Ok(())
1709}
1710
1711fn lockfile_candidates(project_dir: &Path, include_aube: bool) -> Vec<(PathBuf, LockfileKind)> {
1712 let mut out = Vec::new();
1713 if include_aube {
1714 // Prefer the branch-specific lockfile (if `gitBranchLockfile` is on
1715 // and we resolve a branch); fall through to plain `aube-lock.yaml`
1716 // so a freshly-enabled branch still picks up the base lockfile.
1717 let branch_name = aube_lock_filename(project_dir);
1718 if branch_name != "aube-lock.yaml" {
1719 out.push((project_dir.join(&branch_name), LockfileKind::Aube));
1720 }
1721 out.push((project_dir.join("aube-lock.yaml"), LockfileKind::Aube));
1722 }
1723 // Preserve pnpm lockfiles in place. Branch-specific
1724 // `pnpm-lock.<branch>.yaml` mirrors the aube branch lockfile naming
1725 // logic, so a project that already uses pnpm branch lockfiles keeps
1726 // writing through that file.
1727 let pnpm_branch = {
1728 let mut s = aube_lock_filename(project_dir);
1729 if let Some(rest) = s.strip_prefix("aube-lock.") {
1730 s = format!("pnpm-lock.{rest}");
1731 }
1732 s
1733 };
1734 if pnpm_branch != "pnpm-lock.yaml" {
1735 out.push((project_dir.join(&pnpm_branch), LockfileKind::Pnpm));
1736 }
1737 out.push((project_dir.join("pnpm-lock.yaml"), LockfileKind::Pnpm));
1738 out.push((project_dir.join("bun.lock"), LockfileKind::Bun));
1739 out.push((project_dir.join("yarn.lock"), LockfileKind::Yarn));
1740 out.push((
1741 project_dir.join("npm-shrinkwrap.json"),
1742 LockfileKind::NpmShrinkwrap,
1743 ));
1744 out.push((project_dir.join("package-lock.json"), LockfileKind::Npm));
1745 out
1746}
1747
1748fn parse_one(
1749 path: &Path,
1750 kind: LockfileKind,
1751 manifest: &aube_manifest::PackageJson,
1752) -> Result<LockfileGraph, Error> {
1753 match kind {
1754 // `aube-lock.yaml` uses the same on-disk format as pnpm v9 for
1755 // now — same parser, same writer — so we piggyback on the pnpm
1756 // module. Keeping the variant distinct lets detection/import
1757 // treat the two differently even though the bytes are the same.
1758 LockfileKind::Aube | LockfileKind::Pnpm => pnpm::parse(path),
1759 // yarn.rs::parse peeks the file for `__metadata:` and
1760 // dispatches between classic (v1) and berry (v2+) internally,
1761 // so we can hand both kinds to the same entry point. The
1762 // caller keeps the kind label it resolved from
1763 // `refine_yarn_kind` for downstream write-back.
1764 LockfileKind::Yarn | LockfileKind::YarnBerry => yarn::parse(path, manifest),
1765 LockfileKind::Npm | LockfileKind::NpmShrinkwrap => npm::parse(path),
1766 LockfileKind::Bun => bun::parse(path),
1767 }
1768}
1769
1770/// Replace `LockfileKind::Yarn` with `LockfileKind::YarnBerry` when
1771/// the yarn.lock at `path` is actually a yarn 2+ lockfile. Other
1772/// kinds pass through unchanged.
1773///
1774/// `lockfile_candidates` only knows filenames, not content, so the
1775/// yarn entry is always tagged `Yarn`. Callers that need the precise
1776/// variant (install write-back, import conversions, drift logging)
1777/// funnel through this helper after confirming the candidate exists.
1778fn refine_yarn_kind(path: &Path, kind: LockfileKind) -> LockfileKind {
1779 if kind == LockfileKind::Yarn && yarn::is_berry_path(path) {
1780 LockfileKind::YarnBerry
1781 } else {
1782 kind
1783 }
1784}
1785
1786#[derive(Debug, thiserror::Error, miette::Diagnostic)]
1787pub enum Error {
1788 #[error("no lockfile found in {0}")]
1789 NotFound(std::path::PathBuf),
1790 #[error("unsupported lockfile format: {0}")]
1791 UnsupportedFormat(String),
1792 #[error("failed to read lockfile {0}: {1}")]
1793 Io(std::path::PathBuf, std::io::Error),
1794 /// Structural/serialization lockfile errors that have no source
1795 /// location — shape checks (`must be a mapping`), version guards
1796 /// (`lockfileVersion N unsupported`), and `serde_yaml::to_string`
1797 /// failures during write.
1798 #[error("failed to parse lockfile {0}: {1}")]
1799 Parse(std::path::PathBuf, String),
1800 /// Deserialization failure with a byte offset into the source
1801 /// content, so miette's `fancy` handler can draw a pointer at the
1802 /// offending byte of the lockfile. Reuses `aube_manifest`'s
1803 /// `ParseError` — identical shape, identical rendering — via the
1804 /// same `ParseDiag` pattern `aube-workspace` uses.
1805 #[error(transparent)]
1806 #[diagnostic(transparent)]
1807 ParseDiag(Box<aube_manifest::ParseError>),
1808}
1809
1810/// Read a lockfile from disk, mapping I/O errors to `Error::Io`.
1811pub fn read_lockfile(path: &std::path::Path) -> Result<String, Error> {
1812 std::fs::read_to_string(path).map_err(|e| Error::Io(path.to_path_buf(), e))
1813}
1814
1815/// Parse a JSON lockfile document, attaching a miette source span on
1816/// failure so the fancy handler can point at the offending byte.
1817pub fn parse_json<T: serde::de::DeserializeOwned>(
1818 path: &std::path::Path,
1819 content: String,
1820) -> Result<T, Error> {
1821 let mut buf = content.clone().into_bytes();
1822 match simd_json::serde::from_slice(&mut buf) {
1823 Ok(v) => Ok(v),
1824 Err(_) => match serde_json::from_str(&content) {
1825 Ok(v) => Ok(v),
1826 Err(e) => Err(Error::parse_json_err(path, content, &e)),
1827 },
1828 }
1829}
1830
1831impl Error {
1832 pub fn parse(path: &std::path::Path, msg: impl Into<String>) -> Self {
1833 Error::Parse(path.to_path_buf(), msg.into())
1834 }
1835
1836 pub fn parse_json_err(
1837 path: &std::path::Path,
1838 content: String,
1839 err: &serde_json::Error,
1840 ) -> Self {
1841 Error::ParseDiag(Box::new(aube_manifest::ParseError::from_json_err(
1842 path, content, err,
1843 )))
1844 }
1845
1846 pub fn parse_yaml_err(
1847 path: &std::path::Path,
1848 content: String,
1849 err: &serde_yaml::Error,
1850 ) -> Self {
1851 Error::ParseDiag(Box::new(aube_manifest::ParseError::from_yaml_err(
1852 path, content, err,
1853 )))
1854 }
1855}
1856
1857#[cfg(test)]
1858mod has_bin_metadata_tests {
1859 use super::*;
1860
1861 fn pkg_with_bin(bin: BTreeMap<String, String>) -> LockedPackage {
1862 LockedPackage {
1863 name: "p".to_string(),
1864 version: "1.0.0".to_string(),
1865 dep_path: "p@1.0.0".to_string(),
1866 bin,
1867 ..Default::default()
1868 }
1869 }
1870
1871 #[test]
1872 fn empty_graph_has_no_bin_metadata() {
1873 let g = LockfileGraph::default();
1874 assert!(!g.has_bin_metadata());
1875 }
1876
1877 #[test]
1878 fn graph_with_no_bins_returns_false() {
1879 let mut g = LockfileGraph::default();
1880 g.packages
1881 .insert("a@1.0.0".to_string(), pkg_with_bin(BTreeMap::new()));
1882 g.packages
1883 .insert("b@2.0.0".to_string(), pkg_with_bin(BTreeMap::new()));
1884 assert!(!g.has_bin_metadata());
1885 }
1886
1887 #[test]
1888 fn any_non_empty_bin_flips_to_true() {
1889 let mut g = LockfileGraph::default();
1890 g.packages
1891 .insert("a@1.0.0".to_string(), pkg_with_bin(BTreeMap::new()));
1892 let mut bin = BTreeMap::new();
1893 bin.insert("tool".to_string(), "bin/tool.js".to_string());
1894 g.packages.insert("b@2.0.0".to_string(), pkg_with_bin(bin));
1895 assert!(g.has_bin_metadata());
1896 }
1897
1898 /// pnpm parsers record `hasBin: true` as a one-entry placeholder
1899 /// map (empty key + empty value). That still flips the flag.
1900 #[test]
1901 fn pnpm_placeholder_bin_counts() {
1902 let mut g = LockfileGraph::default();
1903 let mut bin = BTreeMap::new();
1904 bin.insert(String::new(), String::new());
1905 g.packages.insert("a@1.0.0".to_string(), pkg_with_bin(bin));
1906 assert!(g.has_bin_metadata());
1907 }
1908}
1909
1910#[cfg(test)]
1911mod parse_diag_tests {
1912 use super::*;
1913 use std::path::Path;
1914
1915 /// Trailing `,` in an otherwise fine JSON lockfile — confirm the
1916 /// helper attaches a `NamedSource` pointed at the lockfile path and
1917 /// the span stays in bounds so miette can render a pointer.
1918 #[test]
1919 fn parse_json_attaches_span_for_bad_input() {
1920 let path = Path::new("package-lock.json");
1921 let content = r#"{"name":"x","#.to_string();
1922 let Err(Error::ParseDiag(pe)) = parse_json::<serde_json::Value>(path, content.clone())
1923 else {
1924 panic!("parse_json must produce ParseDiag on malformed input");
1925 };
1926 let offset: usize = pe.span.offset();
1927 let len: usize = pe.span.len();
1928 assert!(offset + len <= content.len());
1929 assert_eq!(pe.path, path);
1930 }
1931
1932 /// Same story for YAML — serde_yaml reports a `Location` with a
1933 /// byte index directly, so no line/col conversion is exercised
1934 /// here. Both production sites (`pnpm.rs`, `yarn.rs`) call
1935 /// `Error::parse_yaml_err` directly (one iterates multiple YAML
1936 /// documents, the other has only borrowed content), so that's the
1937 /// entry point this test locks down.
1938 #[test]
1939 fn parse_yaml_err_attaches_span_for_bad_input() {
1940 let path = Path::new("yarn.lock");
1941 let content = "packages:\n\t- pkg\n".to_string();
1942 let yaml_err: serde_yaml::Error = serde_yaml::from_str::<serde_yaml::Value>(&content)
1943 .expect_err("tab-indented YAML must fail");
1944 let Error::ParseDiag(pe) = Error::parse_yaml_err(path, content.clone(), &yaml_err) else {
1945 panic!("parse_yaml_err must produce ParseDiag");
1946 };
1947 let offset: usize = pe.span.offset();
1948 let len: usize = pe.span.len();
1949 assert!(offset + len <= content.len());
1950 assert_eq!(pe.path, path);
1951 }
1952}
1953
1954#[cfg(test)]
1955mod looks_like_remote_tarball_url_tests {
1956 use super::*;
1957
1958 #[test]
1959 fn matches_https_tgz() {
1960 assert!(LocalSource::looks_like_remote_tarball_url(
1961 "https://example.com/pkg-1.0.0.tgz"
1962 ));
1963 }
1964
1965 #[test]
1966 fn matches_http_tar_gz() {
1967 assert!(LocalSource::looks_like_remote_tarball_url(
1968 "http://example.com/pkg-1.0.0.tar.gz"
1969 ));
1970 }
1971
1972 #[test]
1973 fn strips_fragment_before_suffix_check() {
1974 assert!(LocalSource::looks_like_remote_tarball_url(
1975 "https://example.com/pkg-1.0.0.tgz#sha512-abc"
1976 ));
1977 }
1978
1979 #[test]
1980 fn strips_query_string_before_suffix_check() {
1981 // Auth-token URLs from private registries (JFrog, Nexus,
1982 // CodeArtifact, …) routinely trail `?token=…` after the
1983 // filename. Must still classify as a tarball URL.
1984 assert!(LocalSource::looks_like_remote_tarball_url(
1985 "https://registry.example.com/pkg/-/pkg-1.0.0.tgz?token=abc"
1986 ));
1987 assert!(LocalSource::looks_like_remote_tarball_url(
1988 "https://example.com/pkg-1.0.0.tar.gz?v=2&signed=1"
1989 ));
1990 }
1991
1992 #[test]
1993 fn matches_bare_http_url_without_tarball_suffix() {
1994 // pkg.pr.new serves tarballs from URLs without a `.tgz`
1995 // extension; npm treats all non-git http(s) URLs as tarball
1996 // URLs, so these must classify as remote tarballs.
1997 assert!(LocalSource::looks_like_remote_tarball_url(
1998 "https://pkg.pr.new/lunariajs/lunaria/@lunariajs/core@904b935"
1999 ));
2000 assert!(LocalSource::looks_like_remote_tarball_url(
2001 "https://codeload.github.com/user/repo/tar.gz/main"
2002 ));
2003 }
2004
2005 #[test]
2006 fn rejects_non_http_schemes() {
2007 assert!(!LocalSource::looks_like_remote_tarball_url(
2008 "ftp://example.com/pkg.tgz"
2009 ));
2010 assert!(!LocalSource::looks_like_remote_tarball_url(
2011 "git://example.com/repo.git"
2012 ));
2013 }
2014
2015 #[test]
2016 fn parse_classifies_bare_http_url_as_remote_tarball() {
2017 use std::path::Path;
2018 let parsed = LocalSource::parse(
2019 "https://pkg.pr.new/lunariajs/lunaria/@lunariajs/core@904b935",
2020 Path::new(""),
2021 );
2022 assert!(matches!(parsed, Some(LocalSource::RemoteTarball(_))));
2023 }
2024
2025 #[test]
2026 fn parse_prefers_git_over_tarball_for_dot_git_url() {
2027 use std::path::Path;
2028 let parsed = LocalSource::parse("https://github.com/user/repo.git", Path::new(""));
2029 assert!(matches!(parsed, Some(LocalSource::Git(_))));
2030 }
2031}
2032
2033#[cfg(test)]
2034mod filename_tests {
2035 use super::*;
2036
2037 #[test]
2038 fn defaults_to_plain_lockfile_when_setting_absent() {
2039 let dir = tempfile::tempdir().unwrap();
2040 assert_eq!(aube_lock_filename(dir.path()), "aube-lock.yaml");
2041 assert_eq!(pnpm_lock_filename(dir.path()), "pnpm-lock.yaml");
2042 }
2043
2044 #[test]
2045 fn defaults_to_plain_lockfile_when_setting_explicit_false() {
2046 let dir = tempfile::tempdir().unwrap();
2047 std::fs::write(
2048 dir.path().join("pnpm-workspace.yaml"),
2049 "gitBranchLockfile: false\n",
2050 )
2051 .unwrap();
2052 assert_eq!(aube_lock_filename(dir.path()), "aube-lock.yaml");
2053 }
2054
2055 #[test]
2056 fn uses_branch_filename_when_enabled_inside_git_repo() {
2057 let dir = tempfile::tempdir().unwrap();
2058 std::fs::write(
2059 dir.path().join("pnpm-workspace.yaml"),
2060 "gitBranchLockfile: true\n",
2061 )
2062 .unwrap();
2063 // git init + checkout a branch with a `/` so we exercise the
2064 // pnpm-style `!` encoding.
2065 let run = |args: &[&str]| {
2066 std::process::Command::new("git")
2067 .args(["-C"])
2068 .arg(dir.path())
2069 .args(args)
2070 .output()
2071 .unwrap()
2072 };
2073 if run(&["init", "-q"]).status.success() {
2074 run(&["checkout", "-q", "-b", "feature/x"]);
2075 assert_eq!(aube_lock_filename(dir.path()), "aube-lock.feature!x.yaml");
2076 assert_eq!(pnpm_lock_filename(dir.path()), "pnpm-lock.feature!x.yaml");
2077 }
2078 }
2079}
2080
2081#[cfg(test)]
2082mod git_spec_tests {
2083 use super::*;
2084
2085 #[test]
2086 fn git_plus_https_without_dot_git_roundtrips_via_lockfile_form() {
2087 // Initial parse: `git+https://…/repo` (no `.git`).
2088 let (url, committish, subpath) = parse_git_spec("git+https://host/user/repo").unwrap();
2089 assert_eq!(url, "https://host/user/repo");
2090 assert_eq!(committish, None);
2091 assert_eq!(subpath, None);
2092
2093 // After resolving, the serializer writes `<url>#<sha>` into
2094 // the lockfile's importer `version:` field.
2095 let sha = "abcdef0123456789abcdef0123456789abcdef01";
2096 let source = LocalSource::Git(GitSource {
2097 url: url.clone(),
2098 committish: None,
2099 resolved: sha.to_string(),
2100 subpath: None,
2101 });
2102 let lockfile_version = source.specifier();
2103 assert_eq!(lockfile_version, format!("https://host/user/repo#{sha}"));
2104
2105 // Re-parse must recognize the bare URL because the 40-hex
2106 // committish suffix unambiguously tags it as git.
2107 let (round_url, round_committish, round_subpath) =
2108 parse_git_spec(&lockfile_version).unwrap();
2109 assert_eq!(round_url, "https://host/user/repo");
2110 assert_eq!(round_committish.as_deref(), Some(sha));
2111 assert_eq!(round_subpath, None);
2112 }
2113
2114 #[test]
2115 fn bare_https_without_dot_git_and_no_committish_is_not_git() {
2116 // A plain `https://…` URL with no `.git` and no SHA could be
2117 // anything (including a tarball); don't claim it.
2118 assert!(parse_git_spec("https://example.com/pkg").is_none());
2119 }
2120
2121 #[test]
2122 fn github_shorthand_expands_and_roundtrips() {
2123 let (url, _, _) = parse_git_spec("github:user/repo").unwrap();
2124 assert_eq!(url, "https://github.com/user/repo.git");
2125 }
2126
2127 #[test]
2128 fn commit_selector_fragment_normalizes_to_sha() {
2129 let sha = "abcdef0123456789abcdef0123456789abcdef01";
2130 let (url, committish, _) =
2131 parse_git_spec(&format!("https://host/user/repo.git#commit={sha}")).unwrap();
2132 assert_eq!(url, "https://host/user/repo.git");
2133 assert_eq!(committish.as_deref(), Some(sha));
2134 }
2135
2136 #[test]
2137 fn named_selector_fragment_normalizes_to_ref() {
2138 let (url, committish, _) = parse_git_spec("git+https://host/user/repo#tag=v1.2.3").unwrap();
2139 assert_eq!(url, "https://host/user/repo");
2140 assert_eq!(committish.as_deref(), Some("v1.2.3"));
2141 }
2142
2143 #[test]
2144 fn pnpm_path_subpath_extracted_from_fragment() {
2145 // pnpm syntax: `<url>#<ref>&path:/<subdir>` selects a
2146 // subdirectory of the cloned repo as the package root.
2147 let (url, committish, subpath) =
2148 parse_git_spec("github:org/dep#v0.1.4&path:/packages/special").unwrap();
2149 assert_eq!(url, "https://github.com/org/dep.git");
2150 assert_eq!(committish.as_deref(), Some("v0.1.4"));
2151 assert_eq!(subpath.as_deref(), Some("packages/special"));
2152 }
2153
2154 #[test]
2155 fn path_subpath_roundtrips_via_specifier() {
2156 let sha = "abcdef0123456789abcdef0123456789abcdef01";
2157 let source = LocalSource::Git(GitSource {
2158 url: "https://github.com/org/dep.git".to_string(),
2159 committish: None,
2160 resolved: sha.to_string(),
2161 subpath: Some("packages/special".to_string()),
2162 });
2163 let spec = source.specifier();
2164 assert_eq!(
2165 spec,
2166 format!("https://github.com/org/dep.git#{sha}&path:/packages/special")
2167 );
2168 let (url, committish, subpath) = parse_git_spec(&spec).unwrap();
2169 assert_eq!(url, "https://github.com/org/dep.git");
2170 assert_eq!(committish.as_deref(), Some(sha));
2171 assert_eq!(subpath.as_deref(), Some("packages/special"));
2172 }
2173
2174 #[test]
2175 fn path_traversal_components_in_subpath_are_rejected() {
2176 // `..` and `.` components would let a crafted spec escape the
2177 // clone dir at install time. The parser drops them so the
2178 // resolver/installer never see a traversal-laden subpath.
2179 let cases = [
2180 "github:org/dep#main&path:/../../etc",
2181 "github:org/dep#main&path:/packages/../../../etc",
2182 "github:org/dep#main&path:/./packages/foo",
2183 "github:org/dep#main&path:/packages//foo",
2184 ];
2185 for spec in cases {
2186 let (_, _, subpath) = parse_git_spec(spec).unwrap();
2187 assert_eq!(subpath, None, "spec should drop subpath: {spec}");
2188 }
2189 }
2190
2191 #[test]
2192 fn dep_path_distinguishes_subpaths_under_same_commit() {
2193 // Two packages from the same repo+commit but different
2194 // subdirs must hash to distinct dep_paths so the linker
2195 // doesn't collapse them.
2196 let sha = "abcdef0123456789abcdef0123456789abcdef01";
2197 let a = LocalSource::Git(GitSource {
2198 url: "https://example.com/r.git".to_string(),
2199 committish: None,
2200 resolved: sha.to_string(),
2201 subpath: Some("packages/a".to_string()),
2202 });
2203 let b = LocalSource::Git(GitSource {
2204 url: "https://example.com/r.git".to_string(),
2205 committish: None,
2206 resolved: sha.to_string(),
2207 subpath: Some("packages/b".to_string()),
2208 });
2209 assert_ne!(a.dep_path("dep"), b.dep_path("dep"));
2210 }
2211}
2212
2213#[cfg(test)]
2214mod drift_tests {
2215 use super::*;
2216 use aube_manifest::PackageJson;
2217 use std::collections::BTreeMap;
2218
2219 fn make_manifest(deps: &[(&str, &str)]) -> PackageJson {
2220 let mut m = PackageJson {
2221 name: Some("test".into()),
2222 version: Some("1.0.0".into()),
2223 dependencies: BTreeMap::new(),
2224 dev_dependencies: BTreeMap::new(),
2225 peer_dependencies: BTreeMap::new(),
2226 optional_dependencies: BTreeMap::new(),
2227 update_config: None,
2228 scripts: BTreeMap::new(),
2229 engines: BTreeMap::new(),
2230 workspaces: None,
2231 bundled_dependencies: None,
2232 extra: BTreeMap::new(),
2233 };
2234 for (name, spec) in deps {
2235 m.dependencies.insert((*name).into(), (*spec).into());
2236 }
2237 m
2238 }
2239
2240 fn make_graph(deps: &[(&str, &str, &str)]) -> LockfileGraph {
2241 // (name, specifier, dep_path)
2242 let direct: Vec<DirectDep> = deps
2243 .iter()
2244 .map(|(name, spec, dep_path)| DirectDep {
2245 name: (*name).into(),
2246 dep_path: (*dep_path).into(),
2247 dep_type: DepType::Production,
2248 specifier: Some((*spec).into()),
2249 })
2250 .collect();
2251 let mut importers = BTreeMap::new();
2252 importers.insert(".".to_string(), direct);
2253 LockfileGraph {
2254 importers,
2255 packages: BTreeMap::new(),
2256 ..Default::default()
2257 }
2258 }
2259
2260 #[test]
2261 fn fresh_when_specifiers_match() {
2262 let manifest = make_manifest(&[("lodash", "^4.17.0")]);
2263 let graph = make_graph(&[("lodash", "^4.17.0", "lodash@4.17.21")]);
2264 assert_eq!(
2265 graph.check_drift(&manifest, &BTreeMap::new(), &[], &BTreeMap::new()),
2266 DriftStatus::Fresh
2267 );
2268 }
2269
2270 #[test]
2271 fn stale_when_specifier_changes() {
2272 let manifest = make_manifest(&[("lodash", "^4.18.0")]);
2273 let graph = make_graph(&[("lodash", "^4.17.0", "lodash@4.17.21")]);
2274 match graph.check_drift(&manifest, &BTreeMap::new(), &[], &BTreeMap::new()) {
2275 DriftStatus::Stale { reason } => assert!(reason.contains("lodash")),
2276 DriftStatus::Fresh => panic!("expected Stale"),
2277 }
2278 }
2279
2280 #[test]
2281 fn stale_when_manifest_adds_dep() {
2282 let manifest = make_manifest(&[("lodash", "^4.17.0"), ("express", "^4.18.0")]);
2283 let graph = make_graph(&[("lodash", "^4.17.0", "lodash@4.17.21")]);
2284 match graph.check_drift(&manifest, &BTreeMap::new(), &[], &BTreeMap::new()) {
2285 DriftStatus::Stale { reason } => assert!(reason.contains("express")),
2286 DriftStatus::Fresh => panic!("expected Stale"),
2287 }
2288 }
2289
2290 #[test]
2291 fn stale_when_manifest_removes_dep() {
2292 let manifest = make_manifest(&[("lodash", "^4.17.0")]);
2293 let graph = make_graph(&[
2294 ("lodash", "^4.17.0", "lodash@4.17.21"),
2295 ("express", "^4.18.0", "express@4.18.0"),
2296 ]);
2297 match graph.check_drift(&manifest, &BTreeMap::new(), &[], &BTreeMap::new()) {
2298 DriftStatus::Stale { reason } => assert!(reason.contains("express")),
2299 DriftStatus::Fresh => panic!("expected Stale"),
2300 }
2301 }
2302
2303 // Regression guard for #42: the drift check must recognize
2304 // auto-hoisted peers as derived state, not as "manifest removed X".
2305 // Without this, every project that has any peer dep would trigger
2306 // a full re-resolve on every install, defeating lockfile caching.
2307 #[test]
2308 fn fresh_when_lockfile_has_auto_hoisted_peer() {
2309 let manifest = make_manifest(&[("use-sync-external-store", "1.2.0")]);
2310 let mut graph = make_graph(&[
2311 (
2312 "use-sync-external-store",
2313 "1.2.0",
2314 "use-sync-external-store@1.2.0",
2315 ),
2316 // Hoisted peer — in the lockfile importers but not in the
2317 // user's package.json.
2318 ("react", "^16.8.0 || ^17.0.0 || ^18.0.0", "react@18.3.1"),
2319 ]);
2320 // The declaring package must list react as a peer for the
2321 // drift check to recognize the hoist. We add that here.
2322 let mut declaring_pkg = LockedPackage {
2323 name: "use-sync-external-store".into(),
2324 version: "1.2.0".into(),
2325 dep_path: "use-sync-external-store@1.2.0".into(),
2326 ..Default::default()
2327 };
2328 declaring_pkg
2329 .peer_dependencies
2330 .insert("react".into(), "^16.8.0 || ^17.0.0 || ^18.0.0".into());
2331 graph
2332 .packages
2333 .insert("use-sync-external-store@1.2.0".into(), declaring_pkg);
2334
2335 assert_eq!(
2336 graph.check_drift(&manifest, &BTreeMap::new(), &[], &BTreeMap::new()),
2337 DriftStatus::Fresh
2338 );
2339 }
2340
2341 // Regression: when a user explicitly pinned a dep that also happens
2342 // to share its name with a peer declaration elsewhere in the graph,
2343 // removing that pin from package.json must still be flagged as
2344 // stale — otherwise the old pinned version gets locked forever.
2345 // The check must key on (name, specifier), not name alone.
2346 #[test]
2347 fn stale_when_user_removes_pinned_dep_that_shares_name_with_a_peer() {
2348 // Manifest after the user removed react entirely. Only
2349 // use-sync-external-store remains.
2350 let manifest = make_manifest(&[("use-sync-external-store", "1.2.0")]);
2351
2352 // Lockfile still has the user's old `react: 17.0.2` pin alongside
2353 // use-sync-external-store. Pre-removal state.
2354 let mut graph = make_graph(&[
2355 (
2356 "use-sync-external-store",
2357 "1.2.0",
2358 "use-sync-external-store@1.2.0",
2359 ),
2360 ("react", "17.0.2", "react@17.0.2"),
2361 ]);
2362 // Add the peer declaration on the consumer package. This is
2363 // the case that previously defeated the name-only check:
2364 // react's specifier "17.0.2" doesn't match the declared peer
2365 // range, so the hoist recognizer must reject it.
2366 let mut consumer = LockedPackage {
2367 name: "use-sync-external-store".into(),
2368 version: "1.2.0".into(),
2369 dep_path: "use-sync-external-store@1.2.0".into(),
2370 ..Default::default()
2371 };
2372 consumer
2373 .peer_dependencies
2374 .insert("react".into(), "^16.8.0 || ^17.0.0 || ^18.0.0".into());
2375 graph
2376 .packages
2377 .insert("use-sync-external-store@1.2.0".into(), consumer);
2378
2379 match graph.check_drift(&manifest, &BTreeMap::new(), &[], &BTreeMap::new()) {
2380 DriftStatus::Stale { reason } => assert!(reason.contains("react")),
2381 DriftStatus::Fresh => panic!(
2382 "drift check should flag a removed user-pinned dep as stale, \
2383 even when its name matches a peer declaration"
2384 ),
2385 }
2386 }
2387
2388 // But if the lockfile has a user-removed dep that ISN'T declared as a
2389 // peer anywhere, we still need to flag it as stale.
2390 #[test]
2391 fn stale_when_lockfile_has_removed_non_peer_dep() {
2392 let manifest = make_manifest(&[("lodash", "^4.17.0")]);
2393 let graph = make_graph(&[
2394 ("lodash", "^4.17.0", "lodash@4.17.21"),
2395 ("chalk", "^5.0.0", "chalk@5.0.0"),
2396 ]);
2397 match graph.check_drift(&manifest, &BTreeMap::new(), &[], &BTreeMap::new()) {
2398 DriftStatus::Stale { reason } => assert!(reason.contains("chalk")),
2399 DriftStatus::Fresh => panic!("expected Stale"),
2400 }
2401 }
2402
2403 #[test]
2404 fn fresh_when_no_specifiers_recorded() {
2405 // Non-pnpm formats (npm/yarn/bun) don't store specifiers, so we can't
2406 // detect drift — we treat them as fresh and let the resolver decide.
2407 let manifest = make_manifest(&[("lodash", "^4.17.0")]);
2408 let graph = LockfileGraph {
2409 importers: {
2410 let mut m = BTreeMap::new();
2411 m.insert(
2412 ".".to_string(),
2413 vec![DirectDep {
2414 name: "lodash".into(),
2415 dep_path: "lodash@4.17.21".into(),
2416 dep_type: DepType::Production,
2417 specifier: None,
2418 }],
2419 );
2420 m
2421 },
2422 packages: BTreeMap::new(),
2423 ..Default::default()
2424 };
2425 assert_eq!(
2426 graph.check_drift(&manifest, &BTreeMap::new(), &[], &BTreeMap::new()),
2427 DriftStatus::Fresh
2428 );
2429 }
2430
2431 #[test]
2432 fn stale_when_manifest_adds_override() {
2433 // Lockfile recorded no overrides; manifest now has one. Drift
2434 // must fire so the next install re-runs the resolver and bakes
2435 // the override into the graph.
2436 let mut manifest = make_manifest(&[("lodash", "^4.17.0")]);
2437 manifest
2438 .extra
2439 .insert("overrides".into(), serde_json::json!({"lodash": "4.17.21"}));
2440 let graph = make_graph(&[("lodash", "^4.17.0", "lodash@4.17.21")]);
2441 match graph.check_drift(&manifest, &BTreeMap::new(), &[], &BTreeMap::new()) {
2442 DriftStatus::Stale { reason } => assert!(reason.contains("overrides")),
2443 DriftStatus::Fresh => panic!("expected Stale"),
2444 }
2445 }
2446
2447 #[test]
2448 fn stale_drift_message_names_changed_override_key() {
2449 // Both sides have one entry, but the value differs. The reason
2450 // should name the key — the previous "lockfile: 1 entries,
2451 // manifest: 1 entries" message looked like nothing changed.
2452 let mut manifest = make_manifest(&[("lodash", "^4.17.0")]);
2453 manifest
2454 .extra
2455 .insert("overrides".into(), serde_json::json!({"lodash": "5.0.0"}));
2456 let mut graph = make_graph(&[("lodash", "^4.17.0", "lodash@4.17.21")]);
2457 graph.overrides.insert("lodash".into(), "4.17.21".into());
2458 match graph.check_drift(&manifest, &BTreeMap::new(), &[], &BTreeMap::new()) {
2459 DriftStatus::Stale { reason } => {
2460 assert!(reason.contains("lodash"), "expected key in: {reason}");
2461 assert!(
2462 reason.contains("4.17.21"),
2463 "expected old value in: {reason}"
2464 );
2465 assert!(reason.contains("5.0.0"), "expected new value in: {reason}");
2466 }
2467 DriftStatus::Fresh => panic!("expected Stale"),
2468 }
2469 }
2470
2471 #[test]
2472 fn stale_when_manifest_removes_override() {
2473 let manifest = make_manifest(&[("lodash", "^4.17.0")]);
2474 let mut graph = make_graph(&[("lodash", "^4.17.0", "lodash@4.17.21")]);
2475 graph.overrides.insert("lodash".into(), "4.17.21".into());
2476 match graph.check_drift(&manifest, &BTreeMap::new(), &[], &BTreeMap::new()) {
2477 DriftStatus::Stale { reason } => {
2478 assert!(reason.contains("removes"));
2479 assert!(reason.contains("lodash"));
2480 }
2481 DriftStatus::Fresh => panic!("expected Stale"),
2482 }
2483 }
2484
2485 #[test]
2486 fn fresh_when_overrides_match() {
2487 let mut manifest = make_manifest(&[("lodash", "^4.17.0")]);
2488 manifest
2489 .extra
2490 .insert("overrides".into(), serde_json::json!({"lodash": "4.17.21"}));
2491 let mut graph = make_graph(&[("lodash", "^4.17.0", "lodash@4.17.21")]);
2492 graph.overrides.insert("lodash".into(), "4.17.21".into());
2493 assert_eq!(
2494 graph.check_drift(&manifest, &BTreeMap::new(), &[], &BTreeMap::new()),
2495 DriftStatus::Fresh
2496 );
2497 }
2498
2499 #[test]
2500 fn fresh_when_workspace_yaml_overrides_match_lockfile() {
2501 // pnpm v10 moved `overrides` to pnpm-workspace.yaml. When the
2502 // resolver wrote them into `self.overrides`, the drift check
2503 // must see the same map — otherwise the second install run
2504 // rejects the lockfile as stale with "manifest removes ..."
2505 // (reported in discussion #174).
2506 let manifest = make_manifest(&[("semver", "^7.5.0")]);
2507 let mut graph = make_graph(&[("semver", "^7.5.0", "semver@7.7.1")]);
2508 graph.overrides.insert("semver".into(), "7.7.1".into());
2509 let mut ws_overrides = BTreeMap::new();
2510 ws_overrides.insert("semver".into(), "7.7.1".into());
2511 assert_eq!(
2512 graph.check_drift(&manifest, &ws_overrides, &[], &BTreeMap::new()),
2513 DriftStatus::Fresh,
2514 );
2515 }
2516
2517 #[test]
2518 fn workspace_yaml_overrides_win_over_package_json() {
2519 // When both pnpm-workspace.yaml and package.json declare an
2520 // override for the same key, the workspace yaml wins — pnpm
2521 // v10's precedence. The drift check must apply the merged
2522 // effective map.
2523 let mut manifest = make_manifest(&[("semver", "^7.5.0")]);
2524 manifest
2525 .extra
2526 .insert("overrides".into(), serde_json::json!({"semver": "7.0.0"}));
2527 let mut graph = make_graph(&[("semver", "^7.5.0", "semver@7.7.1")]);
2528 graph.overrides.insert("semver".into(), "7.7.1".into());
2529 let mut ws_overrides = BTreeMap::new();
2530 ws_overrides.insert("semver".into(), "7.7.1".into());
2531 assert_eq!(
2532 graph.check_drift(&manifest, &ws_overrides, &[], &BTreeMap::new()),
2533 DriftStatus::Fresh,
2534 );
2535 }
2536
2537 #[test]
2538 fn fresh_when_override_catalog_ref_matches_lockfile_resolved() {
2539 // pnpm-workspace.yaml: `overrides: { lodash: "catalog:" }` with
2540 // `catalog: { lodash: 4.17.21 }`. pnpm writes the lockfile with
2541 // the resolved override value (`lodash: 4.17.21`), so a frozen
2542 // install comparing the raw `catalog:` string against the
2543 // resolved form would always read stale (discussion #174).
2544 let manifest = make_manifest(&[("lodash", "^4.17.0")]);
2545 let mut graph = make_graph(&[("lodash", "^4.17.0", "lodash@4.17.21")]);
2546 graph.overrides.insert("lodash".into(), "4.17.21".into());
2547 let mut ws_overrides = BTreeMap::new();
2548 ws_overrides.insert("lodash".into(), "catalog:".into());
2549 let mut catalogs = BTreeMap::new();
2550 let mut default_cat = BTreeMap::new();
2551 default_cat.insert("lodash".into(), "4.17.21".into());
2552 catalogs.insert("default".into(), default_cat);
2553 assert_eq!(
2554 graph.check_drift(&manifest, &ws_overrides, &[], &catalogs),
2555 DriftStatus::Fresh,
2556 );
2557 }
2558
2559 #[test]
2560 fn fresh_when_override_named_catalog_ref_matches_lockfile_resolved() {
2561 // Named catalog variant: `overrides: { lodash: "catalog:evens" }`
2562 // resolves against `catalogs.evens.lodash`.
2563 let manifest = make_manifest(&[("lodash", "^4.17.0")]);
2564 let mut graph = make_graph(&[("lodash", "^4.17.0", "lodash@4.17.21")]);
2565 graph.overrides.insert("lodash".into(), "4.17.21".into());
2566 let mut ws_overrides = BTreeMap::new();
2567 ws_overrides.insert("lodash".into(), "catalog:evens".into());
2568 let mut catalogs = BTreeMap::new();
2569 let mut evens = BTreeMap::new();
2570 evens.insert("lodash".into(), "4.17.21".into());
2571 catalogs.insert("evens".into(), evens);
2572 assert_eq!(
2573 graph.check_drift(&manifest, &ws_overrides, &[], &catalogs),
2574 DriftStatus::Fresh,
2575 );
2576 }
2577
2578 #[test]
2579 fn stale_when_override_catalog_ref_diverges_from_lockfile() {
2580 // If the catalog moves to a new version, the resolved override
2581 // no longer matches the lockfile — drift must fire, not silently
2582 // accept.
2583 let manifest = make_manifest(&[("lodash", "^4.17.0")]);
2584 let mut graph = make_graph(&[("lodash", "^4.17.0", "lodash@4.17.21")]);
2585 graph.overrides.insert("lodash".into(), "4.17.21".into());
2586 let mut ws_overrides = BTreeMap::new();
2587 ws_overrides.insert("lodash".into(), "catalog:".into());
2588 let mut catalogs = BTreeMap::new();
2589 let mut default_cat = BTreeMap::new();
2590 default_cat.insert("lodash".into(), "4.17.22".into());
2591 catalogs.insert("default".into(), default_cat);
2592 match graph.check_drift(&manifest, &ws_overrides, &[], &catalogs) {
2593 DriftStatus::Stale { reason } => assert!(reason.contains("lodash")),
2594 other => panic!("expected stale, got {other:?}"),
2595 }
2596 }
2597
2598 #[test]
2599 fn fresh_when_pnpm_wrote_override_rewritten_importer_spec() {
2600 // pnpm rewrites the importer `specifier:` to the post-override
2601 // value when a bare-name override applies, so a pnpm-generated
2602 // lockfile records `specifier: 4.17.21` even though
2603 // `package.json` still reads `^4.17.0`. Without override-aware
2604 // drift, every frozen install against a pnpm lockfile with
2605 // overrides reads stale (discussion #174).
2606 let manifest = make_manifest(&[("lodash", "^4.17.0")]);
2607 let mut importers = BTreeMap::new();
2608 importers.insert(
2609 ".".to_string(),
2610 vec![DirectDep {
2611 name: "lodash".into(),
2612 dep_path: "lodash@4.17.21".into(),
2613 dep_type: DepType::Production,
2614 specifier: Some("4.17.21".into()),
2615 }],
2616 );
2617 let mut graph = LockfileGraph {
2618 importers,
2619 ..Default::default()
2620 };
2621 graph.overrides.insert("lodash".into(), "4.17.21".into());
2622 let mut ws_overrides = BTreeMap::new();
2623 ws_overrides.insert("lodash".into(), "4.17.21".into());
2624 assert_eq!(
2625 graph.check_drift(&manifest, &ws_overrides, &[], &BTreeMap::new()),
2626 DriftStatus::Fresh,
2627 );
2628 }
2629
2630 #[test]
2631 fn fresh_when_workspace_yaml_ignored_optional_matches_lockfile() {
2632 // Same drift-shaped bug as overrides: the resolver unions
2633 // `ignoredOptionalDependencies` from package.json and
2634 // pnpm-workspace.yaml, so the lockfile's
2635 // `ignored_optional_dependencies` carries the union, and the
2636 // drift check has to see the same union or the next
2637 // `--frozen-lockfile` run fails with "manifest removes".
2638 let manifest = make_manifest(&[("lodash", "^4.17.0")]);
2639 let mut graph = make_graph(&[("lodash", "^4.17.0", "lodash@4.17.21")]);
2640 graph
2641 .ignored_optional_dependencies
2642 .insert("fsevents".to_string());
2643 let ws_ignored = vec!["fsevents".to_string()];
2644 assert_eq!(
2645 graph.check_drift(&manifest, &BTreeMap::new(), &ws_ignored, &BTreeMap::new()),
2646 DriftStatus::Fresh,
2647 );
2648 }
2649
2650 #[test]
2651 fn fresh_when_optional_dep_was_recorded_as_skipped() {
2652 // Regression: a platform-skipped optional dep would otherwise
2653 // loop forever as "manifest adds X". When the previous
2654 // resolve recorded it under skipped_optional_dependencies with
2655 // a matching specifier, drift must report Fresh.
2656 let mut manifest = make_manifest(&[("lodash", "^4.17.0")]);
2657 manifest
2658 .optional_dependencies
2659 .insert("fsevents".into(), "^2.3.0".into());
2660 let mut graph = make_graph(&[("lodash", "^4.17.0", "lodash@4.17.21")]);
2661 let mut inner = BTreeMap::new();
2662 inner.insert("fsevents".to_string(), "^2.3.0".to_string());
2663 graph
2664 .skipped_optional_dependencies
2665 .insert(".".to_string(), inner);
2666 assert_eq!(
2667 graph.check_drift(&manifest, &BTreeMap::new(), &[], &BTreeMap::new()),
2668 DriftStatus::Fresh
2669 );
2670 }
2671
2672 #[test]
2673 fn stale_when_new_optional_dep_was_never_seen() {
2674 // Cursor Bugbot regression: a brand-new optional dep that the
2675 // previous resolve never saw must trigger drift, otherwise it
2676 // would silently never get installed. Distinct from a
2677 // platform-skipped optional, which has an entry in
2678 // `skipped_optional_dependencies`.
2679 let mut manifest = make_manifest(&[("lodash", "^4.17.0")]);
2680 manifest
2681 .optional_dependencies
2682 .insert("fsevents".into(), "^2.3.0".into());
2683 let graph = make_graph(&[("lodash", "^4.17.0", "lodash@4.17.21")]);
2684 match graph.check_drift(&manifest, &BTreeMap::new(), &[], &BTreeMap::new()) {
2685 DriftStatus::Stale { reason } => assert!(reason.contains("fsevents"), "{reason}"),
2686 DriftStatus::Fresh => panic!("expected Stale on new optional dep"),
2687 }
2688 }
2689
2690 #[test]
2691 fn stale_when_skipped_optional_dep_specifier_changes() {
2692 // The user bumped the range on a previously-skipped optional;
2693 // the recorded specifier no longer matches the manifest, so we
2694 // need to re-resolve.
2695 let mut manifest = make_manifest(&[("lodash", "^4.17.0")]);
2696 manifest
2697 .optional_dependencies
2698 .insert("fsevents".into(), "^2.4.0".into());
2699 let mut graph = make_graph(&[("lodash", "^4.17.0", "lodash@4.17.21")]);
2700 let mut inner = BTreeMap::new();
2701 inner.insert("fsevents".to_string(), "^2.3.0".to_string());
2702 graph
2703 .skipped_optional_dependencies
2704 .insert(".".to_string(), inner);
2705 match graph.check_drift(&manifest, &BTreeMap::new(), &[], &BTreeMap::new()) {
2706 DriftStatus::Stale { reason } => assert!(reason.contains("fsevents"), "{reason}"),
2707 DriftStatus::Fresh => panic!("expected Stale on skipped optional spec change"),
2708 }
2709 }
2710
2711 #[test]
2712 fn stale_when_skipped_optional_is_promoted_to_required() {
2713 // Cursor Bugbot regression: if the user moves a previously-
2714 // skipped optional into `dependencies` (same specifier), the
2715 // skipped-list exemption must NOT fire — the dep is now
2716 // required and the lockfile genuinely doesn't include it.
2717 let mut manifest = make_manifest(&[("lodash", "^4.17.0"), ("fsevents", "^2.3.0")]);
2718 // Note: fsevents lives in `dependencies`, not
2719 // `optional_dependencies`, even though the lockfile recorded
2720 // it under skipped optionals from a previous resolve.
2721 manifest.optional_dependencies.clear();
2722 let mut graph = make_graph(&[("lodash", "^4.17.0", "lodash@4.17.21")]);
2723 let mut inner = BTreeMap::new();
2724 inner.insert("fsevents".to_string(), "^2.3.0".to_string());
2725 graph
2726 .skipped_optional_dependencies
2727 .insert(".".to_string(), inner);
2728 match graph.check_drift(&manifest, &BTreeMap::new(), &[], &BTreeMap::new()) {
2729 DriftStatus::Stale { reason } => assert!(reason.contains("fsevents"), "{reason}"),
2730 DriftStatus::Fresh => {
2731 panic!("expected Stale: skipped-optional exemption must not apply to required deps")
2732 }
2733 }
2734 }
2735
2736 #[test]
2737 fn stale_when_optional_dep_specifier_changes_in_lockfile() {
2738 // Spec changes on optionals that *are* present must still
2739 // drift, so the resolver re-runs when the user bumps a range.
2740 let mut manifest = make_manifest(&[]);
2741 manifest
2742 .optional_dependencies
2743 .insert("fsevents".into(), "^2.4.0".into());
2744 let mut graph = make_graph(&[]);
2745 graph.importers.get_mut(".").unwrap().push(DirectDep {
2746 name: "fsevents".into(),
2747 dep_path: "fsevents@2.3.0".into(),
2748 dep_type: DepType::Optional,
2749 specifier: Some("^2.3.0".into()),
2750 });
2751 match graph.check_drift(&manifest, &BTreeMap::new(), &[], &BTreeMap::new()) {
2752 DriftStatus::Stale { reason } => assert!(reason.contains("fsevents"), "{reason}"),
2753 DriftStatus::Fresh => panic!("expected Stale on optional spec change"),
2754 }
2755 }
2756
2757 #[test]
2758 fn fresh_for_empty_manifest_and_lockfile() {
2759 let manifest = make_manifest(&[]);
2760 let graph = make_graph(&[]);
2761 assert_eq!(
2762 graph.check_drift(&manifest, &BTreeMap::new(), &[], &BTreeMap::new()),
2763 DriftStatus::Fresh
2764 );
2765 }
2766
2767 #[test]
2768 fn workspace_drift_detects_change_in_non_root_importer() {
2769 // Build a graph with two importers: root and packages/app.
2770 let root_dep = DirectDep {
2771 name: "lodash".into(),
2772 dep_path: "lodash@4.17.21".into(),
2773 dep_type: DepType::Production,
2774 specifier: Some("^4.17.0".into()),
2775 };
2776 let app_dep = DirectDep {
2777 name: "express".into(),
2778 dep_path: "express@4.18.0".into(),
2779 dep_type: DepType::Production,
2780 specifier: Some("^4.18.0".into()),
2781 };
2782 let mut importers = BTreeMap::new();
2783 importers.insert(".".to_string(), vec![root_dep]);
2784 importers.insert("packages/app".to_string(), vec![app_dep]);
2785 let graph = LockfileGraph {
2786 importers,
2787 packages: BTreeMap::new(),
2788 ..Default::default()
2789 };
2790
2791 let root_manifest = make_manifest(&[("lodash", "^4.17.0")]);
2792 // App manifest changed express to ^5.0.0 — should be detected as stale.
2793 let app_manifest = make_manifest(&[("express", "^5.0.0")]);
2794
2795 let workspace_manifests = vec![
2796 (".".to_string(), root_manifest.clone()),
2797 ("packages/app".to_string(), app_manifest),
2798 ];
2799 match graph.check_drift_workspace(
2800 &workspace_manifests,
2801 &BTreeMap::new(),
2802 &[],
2803 &BTreeMap::new(),
2804 ) {
2805 DriftStatus::Stale { reason } => {
2806 assert!(reason.contains("packages/app"));
2807 assert!(reason.contains("express"));
2808 }
2809 DriftStatus::Fresh => panic!("expected Stale"),
2810 }
2811
2812 // Single-importer check_drift on root only would say Fresh.
2813 assert_eq!(
2814 graph.check_drift(&root_manifest, &BTreeMap::new(), &[], &BTreeMap::new()),
2815 DriftStatus::Fresh
2816 );
2817 }
2818
2819 #[test]
2820 fn filter_deps_prunes_dev_only_subtree() {
2821 // Graph: prod-root (foo) + dev-root (jest) with transitive chains.
2822 // After filtering out Dev, jest + its transitives should be pruned,
2823 // foo + its transitives should remain.
2824 let mut importers = BTreeMap::new();
2825 importers.insert(
2826 ".".to_string(),
2827 vec![
2828 DirectDep {
2829 name: "foo".into(),
2830 dep_path: "foo@1.0.0".into(),
2831 dep_type: DepType::Production,
2832 specifier: Some("^1.0.0".into()),
2833 },
2834 DirectDep {
2835 name: "jest".into(),
2836 dep_path: "jest@29.0.0".into(),
2837 dep_type: DepType::Dev,
2838 specifier: Some("^29.0.0".into()),
2839 },
2840 ],
2841 );
2842
2843 let mut packages = BTreeMap::new();
2844 let mut foo_deps = BTreeMap::new();
2845 foo_deps.insert("bar".to_string(), "2.0.0".to_string());
2846 packages.insert(
2847 "foo@1.0.0".to_string(),
2848 LockedPackage {
2849 name: "foo".into(),
2850 version: "1.0.0".into(),
2851 integrity: None,
2852 dependencies: foo_deps,
2853 dep_path: "foo@1.0.0".into(),
2854 ..Default::default()
2855 },
2856 );
2857 packages.insert(
2858 "bar@2.0.0".to_string(),
2859 LockedPackage {
2860 name: "bar".into(),
2861 version: "2.0.0".into(),
2862 integrity: None,
2863 dependencies: BTreeMap::new(),
2864 dep_path: "bar@2.0.0".into(),
2865 ..Default::default()
2866 },
2867 );
2868 let mut jest_deps = BTreeMap::new();
2869 jest_deps.insert("jest-core".to_string(), "29.0.0".to_string());
2870 packages.insert(
2871 "jest@29.0.0".to_string(),
2872 LockedPackage {
2873 name: "jest".into(),
2874 version: "29.0.0".into(),
2875 integrity: None,
2876 dependencies: jest_deps,
2877 dep_path: "jest@29.0.0".into(),
2878 ..Default::default()
2879 },
2880 );
2881 packages.insert(
2882 "jest-core@29.0.0".to_string(),
2883 LockedPackage {
2884 name: "jest-core".into(),
2885 version: "29.0.0".into(),
2886 integrity: None,
2887 dependencies: BTreeMap::new(),
2888 dep_path: "jest-core@29.0.0".into(),
2889 ..Default::default()
2890 },
2891 );
2892
2893 let graph = LockfileGraph {
2894 importers,
2895 packages,
2896 ..Default::default()
2897 };
2898
2899 let prod = graph.filter_deps(|d| d.dep_type != DepType::Dev);
2900
2901 // Direct deps: only foo, jest dropped
2902 let roots = prod.root_deps();
2903 assert_eq!(roots.len(), 1);
2904 assert_eq!(roots[0].name, "foo");
2905
2906 // Reachable packages: foo + bar (transitive), NOT jest or jest-core
2907 assert!(prod.packages.contains_key("foo@1.0.0"));
2908 assert!(prod.packages.contains_key("bar@2.0.0"));
2909 assert!(!prod.packages.contains_key("jest@29.0.0"));
2910 assert!(!prod.packages.contains_key("jest-core@29.0.0"));
2911 }
2912
2913 // Regression for #50 feedback: `filter_deps` is a structural
2914 // operation and must preserve the source graph's `settings:`
2915 // metadata. A filtered graph that's handed to the lockfile writer
2916 // (as `aube prune` does today) would otherwise reset
2917 // `autoInstallPeers` to its default and silently flip the user's
2918 // choice on the next install.
2919 #[test]
2920 fn filter_deps_preserves_lockfile_settings() {
2921 let graph = LockfileGraph {
2922 importers: BTreeMap::new(),
2923 packages: BTreeMap::new(),
2924 settings: LockfileSettings {
2925 auto_install_peers: false,
2926 exclude_links_from_lockfile: true,
2927 lockfile_include_tarball_url: false,
2928 },
2929 ..Default::default()
2930 };
2931 let filtered = graph.filter_deps(|_| true);
2932 assert!(!filtered.settings.auto_install_peers);
2933 assert!(filtered.settings.exclude_links_from_lockfile);
2934 }
2935
2936 #[test]
2937 fn filter_deps_keeps_shared_transitive_reachable_via_prod() {
2938 // Graph: prod foo → shared, dev jest → shared
2939 // Filtering out Dev should still keep `shared` because foo → shared
2940 // keeps it reachable.
2941 let mut importers = BTreeMap::new();
2942 importers.insert(
2943 ".".to_string(),
2944 vec![
2945 DirectDep {
2946 name: "foo".into(),
2947 dep_path: "foo@1.0.0".into(),
2948 dep_type: DepType::Production,
2949 specifier: Some("^1.0.0".into()),
2950 },
2951 DirectDep {
2952 name: "jest".into(),
2953 dep_path: "jest@29.0.0".into(),
2954 dep_type: DepType::Dev,
2955 specifier: Some("^29.0.0".into()),
2956 },
2957 ],
2958 );
2959
2960 let mut packages = BTreeMap::new();
2961 for (name, ver, deps) in [
2962 ("foo", "1.0.0", vec![("shared", "1.0.0")]),
2963 ("jest", "29.0.0", vec![("shared", "1.0.0")]),
2964 ("shared", "1.0.0", vec![]),
2965 ] {
2966 let mut dep_map = BTreeMap::new();
2967 for (n, v) in deps {
2968 dep_map.insert(n.to_string(), v.to_string());
2969 }
2970 packages.insert(
2971 format!("{name}@{ver}"),
2972 LockedPackage {
2973 name: name.into(),
2974 version: ver.into(),
2975 integrity: None,
2976 dependencies: dep_map,
2977 dep_path: format!("{name}@{ver}"),
2978 ..Default::default()
2979 },
2980 );
2981 }
2982
2983 let graph = LockfileGraph {
2984 importers,
2985 packages,
2986 ..Default::default()
2987 };
2988 let prod = graph.filter_deps(|d| d.dep_type != DepType::Dev);
2989
2990 assert!(prod.packages.contains_key("foo@1.0.0"));
2991 assert!(prod.packages.contains_key("shared@1.0.0"));
2992 assert!(!prod.packages.contains_key("jest@29.0.0"));
2993 }
2994
2995 #[test]
2996 fn subset_to_importer_returns_none_for_missing_importer() {
2997 let graph = LockfileGraph {
2998 importers: BTreeMap::new(),
2999 packages: BTreeMap::new(),
3000 ..Default::default()
3001 };
3002 assert!(graph.subset_to_importer("packages/lib", |_| true).is_none());
3003 }
3004
3005 #[test]
3006 fn subset_to_importer_keeps_only_requested_importer_transitive_closure() {
3007 // Workspace graph with two importers that own independent
3008 // subtrees: packages/lib pulls is-odd → is-number, packages/app
3009 // pulls express. Subsetting to packages/lib must yield a graph
3010 // rooted at `.` containing only is-odd + is-number, with
3011 // express pruned. Matches what `aube deploy --filter @test/lib`
3012 // should write into the target.
3013 let mut importers = BTreeMap::new();
3014 importers.insert(".".to_string(), vec![]);
3015 importers.insert(
3016 "packages/lib".to_string(),
3017 vec![DirectDep {
3018 name: "is-odd".into(),
3019 dep_path: "is-odd@3.0.1".into(),
3020 dep_type: DepType::Production,
3021 specifier: Some("^3.0.1".into()),
3022 }],
3023 );
3024 importers.insert(
3025 "packages/app".to_string(),
3026 vec![DirectDep {
3027 name: "express".into(),
3028 dep_path: "express@4.18.0".into(),
3029 dep_type: DepType::Production,
3030 specifier: Some("^4.18.0".into()),
3031 }],
3032 );
3033
3034 let mut packages = BTreeMap::new();
3035 let mut is_odd_deps = BTreeMap::new();
3036 is_odd_deps.insert("is-number".to_string(), "6.0.0".to_string());
3037 packages.insert(
3038 "is-odd@3.0.1".to_string(),
3039 LockedPackage {
3040 name: "is-odd".into(),
3041 version: "3.0.1".into(),
3042 dependencies: is_odd_deps,
3043 dep_path: "is-odd@3.0.1".into(),
3044 ..Default::default()
3045 },
3046 );
3047 packages.insert(
3048 "is-number@6.0.0".to_string(),
3049 LockedPackage {
3050 name: "is-number".into(),
3051 version: "6.0.0".into(),
3052 dep_path: "is-number@6.0.0".into(),
3053 ..Default::default()
3054 },
3055 );
3056 packages.insert(
3057 "express@4.18.0".to_string(),
3058 LockedPackage {
3059 name: "express".into(),
3060 version: "4.18.0".into(),
3061 dep_path: "express@4.18.0".into(),
3062 ..Default::default()
3063 },
3064 );
3065
3066 let graph = LockfileGraph {
3067 importers,
3068 packages,
3069 ..Default::default()
3070 };
3071 let subset = graph
3072 .subset_to_importer("packages/lib", |_| true)
3073 .expect("packages/lib importer present");
3074
3075 assert_eq!(subset.importers.len(), 1);
3076 let roots = subset.root_deps();
3077 assert_eq!(roots.len(), 1);
3078 assert_eq!(roots[0].name, "is-odd");
3079
3080 assert!(subset.packages.contains_key("is-odd@3.0.1"));
3081 assert!(subset.packages.contains_key("is-number@6.0.0"));
3082 assert!(!subset.packages.contains_key("express@4.18.0"));
3083 }
3084
3085 #[test]
3086 fn subset_to_importer_honors_keep_predicate_for_prod_deploys() {
3087 // packages/lib has both prod (is-odd) and dev (jest) deps.
3088 // `aube deploy --prod` should pass `|d| d.dep_type != Dev` as
3089 // the keep filter; the resulting subset retains only is-odd
3090 // so drift against the target's dev-stripped manifest stays
3091 // clean.
3092 let mut importers = BTreeMap::new();
3093 importers.insert(
3094 "packages/lib".to_string(),
3095 vec![
3096 DirectDep {
3097 name: "is-odd".into(),
3098 dep_path: "is-odd@3.0.1".into(),
3099 dep_type: DepType::Production,
3100 specifier: Some("^3.0.1".into()),
3101 },
3102 DirectDep {
3103 name: "jest".into(),
3104 dep_path: "jest@29.0.0".into(),
3105 dep_type: DepType::Dev,
3106 specifier: Some("^29.0.0".into()),
3107 },
3108 ],
3109 );
3110 let mut packages = BTreeMap::new();
3111 packages.insert(
3112 "is-odd@3.0.1".to_string(),
3113 LockedPackage {
3114 name: "is-odd".into(),
3115 version: "3.0.1".into(),
3116 dep_path: "is-odd@3.0.1".into(),
3117 ..Default::default()
3118 },
3119 );
3120 packages.insert(
3121 "jest@29.0.0".to_string(),
3122 LockedPackage {
3123 name: "jest".into(),
3124 version: "29.0.0".into(),
3125 dep_path: "jest@29.0.0".into(),
3126 ..Default::default()
3127 },
3128 );
3129 let graph = LockfileGraph {
3130 importers,
3131 packages,
3132 ..Default::default()
3133 };
3134
3135 let prod = graph
3136 .subset_to_importer("packages/lib", |d| d.dep_type != DepType::Dev)
3137 .expect("importer present");
3138 let roots = prod.root_deps();
3139 assert_eq!(roots.len(), 1);
3140 assert_eq!(roots[0].name, "is-odd");
3141 assert!(prod.packages.contains_key("is-odd@3.0.1"));
3142 assert!(!prod.packages.contains_key("jest@29.0.0"));
3143 }
3144
3145 #[test]
3146 fn subset_to_importer_preserves_graph_settings() {
3147 // Structural pruning, not a resolution-mode reset: a deploy
3148 // into a target that uses the source workspace's settings
3149 // header (autoInstallPeers / lockfileIncludeTarballUrl)
3150 // should write them through unchanged so a frozen install in
3151 // the target sees the same resolution-mode state.
3152 let mut importers = BTreeMap::new();
3153 importers.insert("packages/lib".to_string(), vec![]);
3154 let graph = LockfileGraph {
3155 importers,
3156 packages: BTreeMap::new(),
3157 settings: LockfileSettings {
3158 auto_install_peers: false,
3159 exclude_links_from_lockfile: true,
3160 lockfile_include_tarball_url: true,
3161 },
3162 ..Default::default()
3163 };
3164 let subset = graph.subset_to_importer("packages/lib", |_| true).unwrap();
3165 assert!(!subset.settings.auto_install_peers);
3166 assert!(subset.settings.exclude_links_from_lockfile);
3167 assert!(subset.settings.lockfile_include_tarball_url);
3168 }
3169
3170 #[test]
3171 fn subset_to_importer_rekeys_skipped_optionals_to_root() {
3172 // `skipped_optional_dependencies` is per-importer. After
3173 // subsetting, only the retained importer's entry should
3174 // survive — rekeyed to `.` so a frozen install in the target
3175 // (which has exactly one importer) doesn't see ghost entries.
3176 let mut importers = BTreeMap::new();
3177 importers.insert("packages/lib".to_string(), vec![]);
3178 importers.insert("packages/app".to_string(), vec![]);
3179 let mut skipped = BTreeMap::new();
3180 let mut lib_skip = BTreeMap::new();
3181 lib_skip.insert("fsevents".to_string(), "^2".to_string());
3182 skipped.insert("packages/lib".to_string(), lib_skip);
3183 let mut app_skip = BTreeMap::new();
3184 app_skip.insert("ghost".to_string(), "*".to_string());
3185 skipped.insert("packages/app".to_string(), app_skip);
3186 let graph = LockfileGraph {
3187 importers,
3188 packages: BTreeMap::new(),
3189 skipped_optional_dependencies: skipped,
3190 ..Default::default()
3191 };
3192 let subset = graph.subset_to_importer("packages/lib", |_| true).unwrap();
3193 assert_eq!(subset.skipped_optional_dependencies.len(), 1);
3194 let root = subset.skipped_optional_dependencies.get(".").unwrap();
3195 assert!(root.contains_key("fsevents"));
3196 assert!(!root.contains_key("ghost"));
3197 }
3198
3199 #[test]
3200 fn workspace_drift_fresh_when_all_importers_match() {
3201 let root_dep = DirectDep {
3202 name: "lodash".into(),
3203 dep_path: "lodash@4.17.21".into(),
3204 dep_type: DepType::Production,
3205 specifier: Some("^4.17.0".into()),
3206 };
3207 let app_dep = DirectDep {
3208 name: "express".into(),
3209 dep_path: "express@4.18.0".into(),
3210 dep_type: DepType::Production,
3211 specifier: Some("^4.18.0".into()),
3212 };
3213 let mut importers = BTreeMap::new();
3214 importers.insert(".".to_string(), vec![root_dep]);
3215 importers.insert("packages/app".to_string(), vec![app_dep]);
3216 let graph = LockfileGraph {
3217 importers,
3218 packages: BTreeMap::new(),
3219 ..Default::default()
3220 };
3221
3222 let workspace_manifests = vec![
3223 (".".to_string(), make_manifest(&[("lodash", "^4.17.0")])),
3224 (
3225 "packages/app".to_string(),
3226 make_manifest(&[("express", "^4.18.0")]),
3227 ),
3228 ];
3229 assert_eq!(
3230 graph.check_drift_workspace(
3231 &workspace_manifests,
3232 &BTreeMap::new(),
3233 &[],
3234 &BTreeMap::new()
3235 ),
3236 DriftStatus::Fresh
3237 );
3238 }
3239
3240 #[allow(clippy::type_complexity)]
3241 fn mk_catalogs(
3242 entries: &[(&str, &[(&str, &str, &str)])],
3243 ) -> BTreeMap<String, BTreeMap<String, CatalogEntry>> {
3244 let mut out: BTreeMap<String, BTreeMap<String, CatalogEntry>> = BTreeMap::new();
3245 for (cat, pkgs) in entries {
3246 let mut inner = BTreeMap::new();
3247 for (pkg, spec, ver) in *pkgs {
3248 inner.insert(
3249 (*pkg).to_string(),
3250 CatalogEntry {
3251 specifier: (*spec).to_string(),
3252 version: (*ver).to_string(),
3253 },
3254 );
3255 }
3256 out.insert((*cat).to_string(), inner);
3257 }
3258 out
3259 }
3260
3261 fn mk_workspace_catalogs(
3262 entries: &[(&str, &[(&str, &str)])],
3263 ) -> BTreeMap<String, BTreeMap<String, String>> {
3264 entries
3265 .iter()
3266 .map(|(cat, pkgs)| {
3267 (
3268 (*cat).to_string(),
3269 pkgs.iter()
3270 .map(|(p, s)| ((*p).to_string(), (*s).to_string()))
3271 .collect(),
3272 )
3273 })
3274 .collect()
3275 }
3276
3277 #[test]
3278 fn catalog_drift_fresh_when_specifiers_match() {
3279 let graph = LockfileGraph {
3280 catalogs: mk_catalogs(&[("default", &[("react", "^18.0.0", "18.2.0")])]),
3281 ..Default::default()
3282 };
3283 let ws = mk_workspace_catalogs(&[("default", &[("react", "^18.0.0")])]);
3284 assert_eq!(graph.check_catalogs_drift(&ws), DriftStatus::Fresh);
3285 }
3286
3287 #[test]
3288 fn catalog_drift_stale_on_changed_specifier() {
3289 let graph = LockfileGraph {
3290 catalogs: mk_catalogs(&[("default", &[("react", "^18.0.0", "18.2.0")])]),
3291 ..Default::default()
3292 };
3293 let ws = mk_workspace_catalogs(&[("default", &[("react", "^19.0.0")])]);
3294 match graph.check_catalogs_drift(&ws) {
3295 DriftStatus::Stale { reason } => assert!(reason.contains("react")),
3296 other => panic!("expected stale, got {other:?}"),
3297 }
3298 }
3299
3300 #[test]
3301 fn catalog_drift_fresh_when_workspace_adds_unused_entry() {
3302 // pnpm only writes referenced entries — an unreferenced
3303 // workspace entry is not drift. The "newly used" transition
3304 // is caught by the importer-level drift check.
3305 let graph = LockfileGraph::default();
3306 let ws = mk_workspace_catalogs(&[("default", &[("react", "^18")])]);
3307 assert_eq!(graph.check_catalogs_drift(&ws), DriftStatus::Fresh);
3308 }
3309
3310 #[test]
3311 fn catalog_drift_stale_on_removed_workspace_entry() {
3312 let graph = LockfileGraph {
3313 catalogs: mk_catalogs(&[("default", &[("react", "^18", "18.2.0")])]),
3314 ..Default::default()
3315 };
3316 let ws = mk_workspace_catalogs(&[]);
3317 assert!(matches!(
3318 graph.check_catalogs_drift(&ws),
3319 DriftStatus::Stale { .. }
3320 ));
3321 }
3322}