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