diff --git a/crates/socket-patch-cli/src/commands/vendor.rs b/crates/socket-patch-cli/src/commands/vendor.rs index 1c2af7c4fe..d2bfbddbe5 100644 --- a/crates/socket-patch-cli/src/commands/vendor.rs +++ b/crates/socket-patch-cli/src/commands/vendor.rs @@ -583,6 +583,9 @@ pub(crate) async fn dispatch_revert_one_opts( /// * for PyPI, a project file still names the artifact although nothing /// installs from it (a half-unwound uv pair, #1374): name it, and /// re-lock before re-vendoring or reverting; +/// * a pnpm lock wires the artifact through an override the project's +/// settings do not declare, so pnpm does not install that lock (#2382): +/// the extractor's own diagnostic, which names the file and the remedy; /// * otherwise a relock dropped the reference while the package stayed. async fn unwired_check_failure( discovery: &socket_patch_core::vex::discover::Discovery, @@ -619,6 +622,12 @@ async fn unwired_check_failure( registry release there (or remove that copy) to have it patched" ); } + // A pnpm lock still wires the artifact, but pnpm installs that lock + // only with the override its settings no longer declare: say which + // file, and the remedy the diagnostic ends with (#2382). + if let Some(diag) = discovery.pnpm_override_undeclared(&entry.uuid) { + return format!("wiring incomplete: {}", diag.detail); + } // Only the npm-family and Python extractors record every lock entry // (`resolved_elsewhere`), so only there does "no lock resolves it" // prove the dependency is gone rather than unreadable. diff --git a/crates/socket-patch-cli/tests/vendor_pnpm_override_e2e.rs b/crates/socket-patch-cli/tests/vendor_pnpm_override_e2e.rs new file mode 100644 index 0000000000..50ff2855b1 --- /dev/null +++ b/crates/socket-patch-cli/tests/vendor_pnpm_override_e2e.rs @@ -0,0 +1,231 @@ +//! pnpm installs a lock only when the lock's `overrides:` equal the ones +//! its settings declare, and each pnpm release reads those from its own +//! place: package.json before pnpm 10.5.1, package.json when it declares +//! overrides or else pnpm-workspace.yaml `overrides:` from 10.5.1 through +//! 10.x, the workspace file alone from pnpm 11 on. With a vendored override declared +//! where the project's pnpm does not read it, a frozen install fails +//! (`ERR_PNPM_LOCKFILE_CONFIG_MISMATCH`) and a plain `pnpm install` puts +//! the registry release back (#2382; measured on pnpm 8.15.9, 9.15.9, +//! 10.2.0, 10.4.1, 10.5.0, 10.5.1, 10.28.0, 11.29.0 and 12.23.0). +//! +//! `vendor --check` and `vex` read the vendored reference from the lock +//! alone, so both called such a package patched. Each case vendors the pnpm +//! project of `vendor_ecosystem_fixtures` (`alpha`, `beta`) through the +//! built binary and takes the override out of one place. + +#[path = "common/mod.rs"] +mod common; + +#[path = "vendor_ecosystem_fixtures/mod.rs"] +mod fx; + +use fx::Fixture; + +const WORKSPACE: &str = "pnpm-workspace.yaml"; +const MANIFEST: &str = "package.json"; + +/// The pnpm fixture, with `pin` as its `packageManager` when given. +fn project(pin: Option<&str>) -> Fixture { + let f = Fixture::new("pnpm"); + if let Some(pin) = pin { + let text = std::fs::read_to_string(f.root.join(MANIFEST)).unwrap(); + let pinned = text.replacen('{', &format!(r#"{{"packageManager":"pnpm@{pin}","#), 1); + std::fs::write(f.root.join(MANIFEST), pinned).unwrap(); + } + f +} + +/// `vendor --check`: the exit code and what it printed. +fn check(f: &Fixture) -> (i32, String) { + let (code, stdout, stderr) = f.run(&["vendor", "--check"], &[]); + (code, format!("{stdout}{stderr}")) +} + +/// `vex`: the number of `not_affected` statements and the warnings. +fn vex(f: &Fixture) -> (usize, String) { + let (_, stdout, stderr) = f.run(&["vex", "--product", "pkg:npm/app@1.0.0"], &[]); + let attested = stdout.matches("\"status\": \"not_affected\"").count(); + (attested, stderr) +} + +/// Whether `rel` declares a vendored override. +fn declares(f: &Fixture, rel: &str) -> bool { + std::fs::read_to_string(f.root.join(rel)).is_ok_and(|text| text.contains(".socket/vendor/npm/")) +} + +/// Take the vendored overrides out of package.json: its bytes before the +/// vendored run, which are `before`. +fn drop_manifest_override(f: &Fixture, before: &[u8]) { + std::fs::write(f.root.join(MANIFEST), before).unwrap(); +} + +/// The issue's case: the override is declared in no file. The lock still +/// names the artifact, so both verifiers passed. +#[test] +fn a_lock_whose_override_no_file_declares_is_not_verified() { + let f = project(None); + let before = std::fs::read(f.root.join(MANIFEST)).unwrap(); + let (code, stdout, stderr) = f.vendor(&[], &[]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!(declares(&f, MANIFEST) && declares(&f, WORKSPACE)); + assert_eq!((check(&f).0, vex(&f).0), (0, 1), "as vendored"); + + drop_manifest_override(&f, &before); + std::fs::remove_file(f.root.join(WORKSPACE)).unwrap(); + assert!(declares(&f, "pnpm-lock.yaml")); + let tree = f.tree(); + + let (code, said) = check(&f); + let (attested, warned) = vex(&f); + assert_eq!( + (code, attested), + (1, 0), + "(vendor --check exit code, not_affected statements)\n{said}\n{warned}" + ); + for (name, uuid) in [("alpha", "000000000001"), ("beta", "000000000002")] { + let line = said + .lines() + .find(|l| l.starts_with(&format!("pkg:npm/{name}@1.0.0: wiring incomplete: "))) + .unwrap_or_else(|| panic!("{name}: {said}")); + assert!( + line.contains(&format!("the override `{name}@1.0.0`")) + && line.contains(&format!("-{uuid}/{name}-1.0.0.tgz")) + && line.contains("neither package.json `pnpm.overrides` nor pnpm-workspace.yaml") + && line.contains("ERR_PNPM_LOCKFILE_CONFIG_MISMATCH") + && line.ends_with("Re-run `socket-patch vendor` to declare it again, and commit the files it changes"), + "{line}" + ); + assert!(!line.contains("no lockfile or config references"), "{line}"); + // `vex` folds the second package into the first one's warning. + assert!(warned.contains(&format!("{name}@1.0.0")), "{warned}"); + } + assert!( + warned.contains("patched_ref_invalid: pnpm-lock.yaml: the lock records the override") + && warned.contains("(vendor_unwired)"), + "{warned}" + ); + assert_eq!(f.tree(), tree, "the two read-only commands wrote nothing"); + + // The remedy the message names puts both declarations back. + let (code, stdout, stderr) = f.vendor(&[], &[]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!(declares(&f, MANIFEST) && declares(&f, WORKSPACE)); + assert_eq!((check(&f).0, vex(&f).0), (0, 1), "after the re-run"); +} + +/// The override is read where the project's pnpm reads it, so a file left +/// out of a commit (or a pnpm upgrade) is caught as soon as the checkout +/// says which pnpm it uses. +#[test] +fn the_override_counts_only_where_the_projects_pnpm_reads_it() { + // (the pnpm the project pins, the file the override is taken out of, + // whether pnpm still installs the lock). + for (pin, dropped, installs) in [ + // No pin: either file. + (None, MANIFEST, true), + (None, WORKSPACE, true), + // pnpm 10.5.1 and newer 10.x read the workspace file when + // package.json has no table, and the table when it has one. + (Some("10.28.0"), MANIFEST, true), + (Some("10.28.0"), WORKSPACE, true), + // pnpm 11 and newer read the workspace file alone. + (Some("11.29.0"), MANIFEST, true), + (Some("11.29.0"), WORKSPACE, false), + (Some("12.23.0"), WORKSPACE, false), + // pnpm older than 10.5.1 reads package.json alone, and a project + // pinned to one with no workspace file gets none. + (Some("9.15.9"), MANIFEST, false), + (Some("10.4.1"), MANIFEST, false), + ] { + let case = format!("pnpm {pin:?} without the override in {dropped}"); + let f = project(pin); + let before = std::fs::read(f.root.join(MANIFEST)).unwrap(); + let (code, stdout, stderr) = f.vendor(&[], &[]); + assert_eq!(code, 0, "{case}: {stdout}\n{stderr}"); + assert_eq!( + declares(&f, WORKSPACE), + !matches!(pin, Some("9.15.9" | "10.4.1")), + "{case}: what vendor wrote" + ); + assert_eq!((check(&f).0, vex(&f).0), (0, 1), "{case}: as vendored"); + match dropped { + MANIFEST => drop_manifest_override(&f, &before), + _ => std::fs::remove_file(f.root.join(WORKSPACE)).unwrap(), + } + + let (code, said) = check(&f); + let (attested, warned) = vex(&f); + let expected = if installs { (0, 1) } else { (1, 0) }; + assert_eq!((code, attested), expected, "{case}\n{said}\n{warned}"); + if installs { + continue; + } + let file = match dropped { + MANIFEST => "package.json `pnpm.overrides`", + _ => "pnpm-workspace.yaml `overrides`", + }; + assert!( + said.contains(&format!( + "{file} does not declare it, and that is the only place this project's pnpm \ + (pnpm@{} (package.json packageManager)) reads overrides from", + pin.unwrap() + )), + "{case}: {said}" + ); + // Re-running vendor declares it where that pnpm reads it. + let (code, stdout, stderr) = f.vendor(&[], &[]); + assert_eq!(code, 0, "{case}: {stdout}\n{stderr}"); + assert!(declares(&f, dropped), "{case}: the re-run wrote {dropped}"); + assert_eq!((check(&f).0, vex(&f).0), (0, 1), "{case}: after the re-run"); + } +} + +/// pnpm 10.5.1 to 10.x read a `pnpm.overrides` table of package.json in +/// place of the workspace file's `overrides:` (measured on 10.28.0). A +/// project with a table of its own whose package.json loses the vendored +/// entries (a merge that took the other side) keeps them in the workspace +/// file, where that pnpm no longer looks. +#[test] +fn a_package_json_table_hides_the_workspace_override_on_pnpm_10() { + for (pin, installs) in [ + (Some("10.28.0"), false), + // pnpm 11 ignores the table, and with no pin either map counts. + (Some("11.29.0"), true), + (None, true), + ] { + let case = format!("pnpm {pin:?}"); + let f = project(pin); + let text = std::fs::read_to_string(f.root.join(MANIFEST)).unwrap(); + let own = text.replacen('{', r#"{"pnpm":{"overrides":{"gamma@1.0.0":"1.0.1"}},"#, 1); + std::fs::write(f.root.join(MANIFEST), &own).unwrap(); + let (code, stdout, stderr) = f.vendor(&[], &[]); + assert_eq!(code, 0, "{case}: {stdout}\n{stderr}"); + assert!(declares(&f, MANIFEST) && declares(&f, WORKSPACE), "{case}"); + assert_eq!((check(&f).0, vex(&f).0), (0, 1), "{case}: as vendored"); + + drop_manifest_override(&f, own.as_bytes()); + let (code, said) = check(&f); + let expected = if installs { (0, 1) } else { (1, 0) }; + assert_eq!((code, vex(&f).0), expected, "{case}\n{said}"); + if installs { + continue; + } + assert!( + said.contains( + "package.json declares overrides without it, and this project's pnpm \ + (pnpm@10.28.0 (package.json packageManager)) reads those in place of \ + pnpm-workspace.yaml `overrides`" + ), + "{said}" + ); + // The re-run adds the entries to the table that exists. + let (code, stdout, stderr) = f.vendor(&[], &[]); + assert_eq!(code, 0, "{case}: {stdout}\n{stderr}"); + let after = std::fs::read_to_string(f.root.join(MANIFEST)).unwrap(); + assert!( + after.contains("gamma@1.0.0") && declares(&f, MANIFEST), + "{after}" + ); + assert_eq!((check(&f).0, vex(&f).0), (0, 1), "{case}: after the re-run"); + } +} diff --git a/crates/socket-patch-core/src/formats/pnpm/mod.rs b/crates/socket-patch-core/src/formats/pnpm/mod.rs index c6e0650be1..98bda45446 100644 --- a/crates/socket-patch-core/src/formats/pnpm/mod.rs +++ b/crates/socket-patch-core/src/formats/pnpm/mod.rs @@ -36,8 +36,9 @@ pub(crate) mod workspace; pub(crate) use version::range_admits; pub use version::{ - matches_file_id_build_keys, registry_route_pins, root_only_workspace_breaks_add, - routed_build_keys, RegistryRoutePins, RoutedBuildKeys, REGISTRY_ROUTE_FLOOR, + matches_file_id_build_keys, pinned_override_sources, registry_route_pins, + root_only_workspace_breaks_add, routed_build_keys, OverrideSource, RegistryRoutePins, + RoutedBuildKeys, REGISTRY_ROUTE_FLOOR, }; pub use grammar::PnpmDocument; @@ -528,6 +529,21 @@ impl<'t> PnpmLock<'t> { .any(|p| pnpm_registry_key(p.key) == Some((name, version))) } + /// The `(key, value)` entries of the project documents' `overrides:` + /// sections: the overrides the lock was resolved with, which pnpm + /// compares with the ones its settings declare before it installs the + /// lock. The env lockfile document resolves pnpm's own dependencies and + /// is not read. Empty for a lock that records none. + pub(crate) fn overrides(&self) -> Vec<(String, String)> { + grammar::documents(self.text) + .into_iter() + .filter(|(_, kind)| *kind == PnpmDocument::Project) + .flat_map(|(span, _)| { + crate::vendor::pnpm_lock::override_section_entries(&self.text[span]) + }) + .collect() + } + /// Every packages entry whose flat resolution names a `tarball:`, in /// lock order. pub(crate) fn wired_refs(&self) -> impl Iterator> { diff --git a/crates/socket-patch-core/src/formats/pnpm/version.rs b/crates/socket-patch-core/src/formats/pnpm/version.rs index 9df1c4649d..e3fa7ce5e6 100644 --- a/crates/socket-patch-core/src/formats/pnpm/version.rs +++ b/crates/socket-patch-core/src/formats/pnpm/version.rs @@ -9,7 +9,8 @@ //! 9.0.0, 9.7.1, 9.15.9, 10.0.0–10.4.1 failing and 10.5.0+ passing). Those //! versions also read nothing the modes would write there: `trustLockfile` //! is a pnpm >= 11 setting, and `overrides:` in pnpm-workspace.yaml is read -//! from 10.5 on (older ones read package.json `pnpm.overrides`). +//! from 10.5.1 on (older ones read package.json `pnpm.overrides`, see +//! [`OverrideSource`]). //! //! The evidence is read conservatively, because a wrong "skip" loses a //! setting pnpm >= 11 needs: every present source must pin pnpm inside @@ -167,6 +168,98 @@ pub fn root_only_workspace_breaks_add( }) } +/// Where a pnpm release reads the overrides it resolves with. pnpm +/// installs a lock only when the lock's `overrides:` equal the ones it +/// reads here (`ERR_PNPM_LOCKFILE_CONFIG_MISMATCH` on a frozen install +/// otherwise, and a plain install resolves afresh and takes the registry +/// release), so this is where a vendored override has to be declared. +/// +/// Measured with a vendored `left-pad` (#2382). pnpm 8.15.9, 9.15.9, +/// 10.2.0, 10.4.1 and 10.5.0 install the lock only with the override in +/// package.json. pnpm 10.5.1, 10.5.2, 10.6.0, 10.9.0, 10.13.1, 10.20.0 and +/// 10.28.0 also install it with the override in pnpm-workspace.yaml +/// `overrides:` alone, but 10.28.0 does not while package.json declares +/// overrides that lack it: those are read in place of the workspace +/// file's. pnpm 11.29.0 and 12.23.0 install it only with the override in +/// the workspace file. +/// +/// package.json's overrides are `pnpm.overrides` over the top-level +/// `resolutions` (9.15.9 and 10.28.0 install the lock with the override +/// in `resolutions` alone, 11.29.0 does not), and declaring none is the +/// same as an empty table (10.5.1 and 10.28.0 read the workspace file +/// beside `"overrides": {}`, 10.28.0 does not beside a `resolutions` +/// entry of the project's own). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum OverrideSource { + /// pnpm older than 10.5.1: package.json alone. + Manifest, + /// pnpm 10.5.1 through 10.x: package.json's overrides when it declares + /// any, else pnpm-workspace.yaml `overrides:`. + ManifestElseWorkspace, + /// pnpm 11 and newer: pnpm-workspace.yaml `overrides:` alone. + Workspace, + /// The project's files do not say which of those its pnpm is: either + /// map counts, the side that withholds no working wiring. + Unstated, +} + +impl OverrideSource { + /// The source every release in `lo..=hi` reads; `None` when the span + /// crosses a boundary. + fn of((lo, hi): (Release, Release)) -> Option { + const WORKSPACE_READ: Release = (10, 5, 1); + const MANIFEST_IGNORED: Release = (11, 0, 0); + if hi < WORKSPACE_READ { + Some(OverrideSource::Manifest) + } else if lo >= MANIFEST_IGNORED { + Some(OverrideSource::Workspace) + } else if lo >= WORKSPACE_READ && hi < MANIFEST_IGNORED { + Some(OverrideSource::ManifestElseWorkspace) + } else { + None + } + } + + /// Whether this pnpm reads an override that package.json declares + /// (`manifest`) or the workspace file declares (`workspace`); + /// `manifest_table` says package.json declares any override at all. + pub fn reads(self, manifest: bool, workspace: bool, manifest_table: bool) -> bool { + match self { + OverrideSource::Manifest => manifest, + OverrideSource::ManifestElseWorkspace if manifest_table => manifest, + OverrideSource::ManifestElseWorkspace | OverrideSource::Workspace => workspace, + OverrideSource::Unstated => manifest || workspace, + } + } +} + +/// The [`OverrideSource`]s the pnpm pins package.json commits state +/// (`packageManager`, `devEngines.packageManager`, `engines.pnpm`), each +/// with its pin as prose (``pnpm@9.15.9 (package.json packageManager)``), +/// one entry per source; empty when no pin states one. +/// +/// A pin states a source when every release it admits reads the same one +/// (an exact version, `~11.29.0`, `9.x`); a range that reaches across a +/// boundary (`>=9`, `^10.4.0`) or does not parse states none and is left +/// out. Pins that state different sources are all returned: a declaration +/// counts when a pnpm the project names reads it. +/// +/// The install record (`node_modules/.modules.yaml`) is not read here. It +/// is not committed, so the same commit would verify on one machine and +/// fail on another, by whichever pnpm last installed there. +pub fn pinned_override_sources(package_json: Option<&str>) -> Vec<(OverrideSource, String)> { + let mut stated: Vec<(OverrideSource, String)> = Vec::new(); + for (source, spec) in pnpm_pins(package_json, None) { + let Some(reads) = version_bounds(&spec).and_then(OverrideSource::of) else { + continue; + }; + if stated.iter().all(|(known, _)| *known != reads) { + stated.push((reads, format!("pnpm@{spec} ({source})"))); + } + } + stated +} + /// The oldest pnpm hosted mode routes a patched package through a named /// registry for ([`registry_route_pins`]). pub const REGISTRY_ROUTE_FLOOR: (u64, u64) = (11, 20); diff --git a/crates/socket-patch-core/src/vendor/pnpm_lock.rs b/crates/socket-patch-core/src/vendor/pnpm_lock.rs index 7e0cd84616..e7c1eef559 100644 --- a/crates/socket-patch-core/src/vendor/pnpm_lock.rs +++ b/crates/socket-patch-core/src/vendor/pnpm_lock.rs @@ -2273,7 +2273,11 @@ pub(super) fn apply_pkg_override( /// vendored value counts too: after a workspace-only takeover (#854) or /// an earlier skipped copy, the lock recording it still shows the /// workspace file governs, and a copy now would shadow it. -fn workspace_overrides_govern(pkg: &Value, ws_text: Option<&str>, lock: &[String]) -> bool { +pub(crate) fn workspace_overrides_govern( + pkg: &Value, + ws_text: Option<&str>, + lock: &[String], +) -> bool { if pkg.get("pnpm").and_then(|p| p.get("overrides")).is_some() { return false; } @@ -2375,13 +2379,14 @@ fn ws_overrides_section(lines: &[String]) -> Option<(usize, usize, usize)> { Some((start, end, indent)) } -/// The `(key, value)` entries of a pnpm-workspace.yaml's block-style -/// `overrides:` section, values as YAML reads them ([`ws_override_value`]). +/// The `(key, value)` entries of the block-style top-level `overrides:` +/// section of a pnpm-workspace.yaml, or of one document of a pnpm lock +/// (the same shape), values as YAML reads them ([`ws_override_value`]). /// Empty for a missing or flow-style section: VEX discovery asks which /// packages the map routes, and a shape the surgery cannot read routes none /// it can vouch for. -pub(crate) fn workspace_override_entries(ws_text: &str) -> Vec<(String, String)> { - let lines = split_lines(ws_text); +pub(crate) fn override_section_entries(text: &str) -> Vec<(String, String)> { + let lines = split_lines(text); let Some((start, end, indent)) = ws_overrides_section(&lines) else { return Vec::new(); }; @@ -2392,6 +2397,41 @@ pub(crate) fn workspace_override_entries(ws_text: &str) -> Vec<(String, String)> .collect() } +/// Whether a top-level `overrides:` key carries an inline value (a flow +/// mapping, an alias): a shape the line reader does not follow. +fn has_inline_overrides(lines: &[String]) -> bool { + lines.iter().any(|l| { + workspace::top_level_key(l) + .is_some_and(|(key, value)| key == "overrides" && !value.is_empty()) + }) +} + +/// Whether a pnpm-workspace.yaml carries an inline `overrides:` value, +/// which [`check_workspace_override`] refuses to edit, whatever it holds. +pub(crate) fn override_section_inline(text: &str) -> bool { + has_inline_overrides(&split_lines(text)) +} + +/// Whether a pnpm-workspace.yaml may declare overrides that +/// [`override_section_entries`] cannot read: the shapes +/// [`check_workspace_override`] refuses to edit (a document that is not a +/// single block mapping, an inline `overrides:` value that holds +/// entries). pnpm reads them all the same, so a reader that finds no entry +/// there cannot say the file declares none. +pub(crate) fn override_section_unreadable(text: &str) -> bool { + let lines = split_lines(text); + // An empty mapping or a null declares nothing, inline or not. + let holds_entries = |value: &str| { + let value: String = value.split_whitespace().collect(); + !matches!(value.as_str(), "" | "{}" | "~" | "null") + }; + workspace::block_insert_point(&lines).is_err() + || lines.iter().any(|l| { + workspace::top_level_key(l) + .is_some_and(|(key, value)| key == "overrides" && holds_entries(value)) + }) +} + /// Pre-flight mirror check for pnpm-workspace.yaml (analogous to /// [`check_lock_override`]): a block-style `overrides:` section may only /// carry a same-name key equal to `effective_key` with an ownable value. @@ -2415,10 +2455,7 @@ fn check_workspace_override( corrupting it — rewrite it as a single block mapping and re-run" )); } - if lines.iter().any(|l| { - workspace::top_level_key(l) - .is_some_and(|(key, value)| key == "overrides" && !value.is_empty()) - }) { + if has_inline_overrides(&lines) { return Err(format!( "{PNPM_WORKSPACE} has an inline `overrides:` mapping the pair surgery cannot \ edit — rewrite it as a block mapping (`overrides:` then indented entries) \ diff --git a/crates/socket-patch-core/src/vex/discover/mod.rs b/crates/socket-patch-core/src/vex/discover/mod.rs index 87d8b835db..87cd922d56 100644 --- a/crates/socket-patch-core/src/vex/discover/mod.rs +++ b/crates/socket-patch-core/src/vex/discover/mod.rs @@ -985,7 +985,9 @@ pub struct Discovery { /// Vendored wiring an extractor rejects as [`DIAG_REF_INVALID`] although /// the next relock consumes it: cargo's `[patch]` at this copy while /// `Cargo.lock` builds another generation's copy (tagged for another - /// uuid, or untagged). Not attested, but still wiring: the prune GC must + /// uuid, or untagged), or although a rewire completes it: a pnpm lock + /// entry whose override the project's settings no longer declare. Not + /// attested, but still wiring: the prune GC must /// keep such an entry ([`Discovery::vendor_entry_in_use`]). Wiring /// dropped as [`DIAG_REF_UNATTRIBUTABLE`] needs no record here: the GC /// keeps it through the diagnostic itself. Sorted, deduped. @@ -1801,6 +1803,26 @@ impl Discovery { Some((shadowed, diag)) } + /// The diagnostic of a vendored pnpm lock entry of patch `uuid` that + /// was withheld because the project does not declare the override the + /// lock records for it (`npm::confirm_pnpm_overrides`): it names the + /// file that lacks the declaration and the remedy. Lets a reader of + /// the dead claim say what is missing instead of saying nothing wires + /// the artifact. + pub fn pnpm_override_undeclared(&self, uuid: &str) -> Option<&Diag> { + self.withheld + .iter() + .filter(|w| w.uuid == uuid && w.mode == WiringMode::Vendored) + .find_map(|w| { + self.diagnostics.iter().find(|d| { + d.code == DIAG_REF_INVALID + && d.file == w.file + && d.detail.contains(npm::PNPM_OVERRIDE_UNDECLARED) + && d.detail.contains(uuid) + }) + }) + } + /// Whether any lock discovery read resolves `purl` (any spelling) at /// all: wired to a Socket patch, contested, or from elsewhere /// ([`Discovery::resolved_elsewhere`]). @@ -2420,6 +2442,21 @@ impl<'a> DiscoverCtx<'a> { self.view.read_text(rel).await.ok() } + /// [`DiscoverCtx::read_advisory_text`] that tells a file that is not + /// there (`Ok(None)`) from one that is there and cannot be read + /// (`Err`), for a reader that must not take the second for "declares + /// nothing". + pub(crate) async fn read_advisory_text_if_present( + &self, + rel: &str, + ) -> Result, ()> { + match self.view.read_text(rel).await { + Ok(text) => Ok(Some(text)), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(_) => Err(()), + } + } + /// Bytes twin of [`DiscoverCtx::read_advisory_text`] (a user's `file:` /// tarball, read only to name the package it holds). pub(crate) async fn read_advisory_bytes(&self, rel: &str) -> Option> { diff --git a/crates/socket-patch-core/src/vex/discover/npm.rs b/crates/socket-patch-core/src/vex/discover/npm.rs index 2cb0d2432d..0f3df40970 100644 --- a/crates/socket-patch-core/src/vex/discover/npm.rs +++ b/crates/socket-patch-core/src/vex/discover/npm.rs @@ -61,17 +61,18 @@ use serde_json::Value; use super::{ npm_purl, npm_vendored_tarball_names, parse_json, vendor_ref, CopyTarget, DiscoverCtx, Discovery, LocateOpts, Located, PatchedRef, TreePart, UnattestedKind, UnwiredCopy, VendorRef, - DIAG_LOCKFILE_UNPARSEABLE, DIAG_REF_INVALID, DIAG_REF_UNATTRIBUTABLE, + WiringMode, DIAG_LOCKFILE_UNPARSEABLE, DIAG_REF_INVALID, DIAG_REF_UNATTRIBUTABLE, }; use crate::constants::npm_family::{NPM_LOCKS, PNPM_LOCK, PNPM_SHRINKWRAP_LEGACY}; use crate::formats::pnpm::plan::governing_pnpm_lock; use crate::formats::pnpm::{ - classify_pnpm_key, entry_bundled, entry_field, pnpm_registry_key, Bundled, PnpmDocument, - PnpmKey, PnpmLock, PnpmPackage, + classify_pnpm_key, entry_bundled, entry_field, pnpm_registry_key, Bundled, OverrideSource, + PnpmDocument, PnpmKey, PnpmLock, PnpmPackage, }; use crate::formats::text::strip_bom; use crate::patch::redirect::NpmUserPatches; use crate::utils::digest::is_sri_pin; +use crate::utils::pnpm_workspace::PNPM_WORKSPACE; use crate::vendor::lock_inventory::pnpm::{is_rush, rush_lock_rels}; use crate::vendor::lock_inventory::{ npm_lock_bundled_nodes, npm_lock_legacy_mirror_nodes, npm_lock_located_nodes, LockIntegrity, @@ -82,6 +83,15 @@ use crate::vendor::npm_origin::{ npm_shrinkwrapped_entries, NpmOverrides, }; +/// The manifest a pnpm project declares `pnpm.overrides` in. +const PNPM_MANIFEST: &str = "package.json"; + +/// How the diagnostic of a vendored pnpm entry whose override the project +/// does not declare starts, after the lock's name +/// ([`confirm_pnpm_overrides`]); [`Discovery::pnpm_override_undeclared`] +/// finds the diagnostic by it. +pub(crate) const PNPM_OVERRIDE_UNDECLARED: &str = "the lock records the override"; + pub(crate) async fn extract(ctx: &DiscoverCtx<'_>, out: &mut Discovery) { let mut locks: Vec = Vec::new(); let mut twin_present = false; @@ -996,7 +1006,9 @@ fn unattest_git_branch_lock(file: &str, branch_locks: &[String], out: &mut Disco /// them. A vendored ref stands only while the override map pnpm reads /// without a lock routes its package to the same artifact /// ([`PnpmLockOff::routes`]); otherwise it is marked -/// [`UnattestedKind::LockNotRead`]. +/// [`UnattestedKind::LockNotRead`]. With the lock on, a vendored ref of +/// the root lock stands only while the project's settings declare the +/// override the lock records for it ([`confirm_pnpm_overrides`]). async fn extract_pnpm_lock( ctx: &DiscoverCtx<'_>, file: &str, @@ -1040,8 +1052,220 @@ async fn extract_pnpm_lock( let tree = PnpmTree::of(file, document); extract_pnpm_document(ctx, &tree, &lock, document, disabled, out).await; } - if let Some(off) = off { - out.unattest_vendored_not_read(file, &off.unrouted(), |r| off.routes(r)); + match off { + Some(off) => out.unattest_vendored_not_read(file, &off.unrouted(), |r| off.routes(r)), + None => confirm_pnpm_overrides(ctx, file, &lock, out).await, + } +} + +/// Drop each vendored ref of the pnpm lock `file` whose override the lock +/// records while the project's settings do not declare it (#2382). +/// +/// pnpm installs a lock only when the lock's `overrides:` equal the ones +/// its settings declare: otherwise a frozen install stops with +/// `ERR_PNPM_LOCKFILE_CONFIG_MISMATCH`, and a plain `pnpm install` resolves +/// again, takes the package from the registry and rewrites the lock +/// without the vendored entry. Which file holds those settings depends on +/// the pnpm release ([`OverrideSource`]). So an entry whose override is +/// declared nowhere pnpm reads is the yarn berry orphan: it is diagnosed +/// ([`DIAG_REF_INVALID`], with the remedy) and is no ref. The lock still +/// wires the artifact and a rewire restores the declaration, so the entry +/// is still wiring to the prune GC ([`Discovery::withheld`]). +/// +/// Only an override the lock itself records is asked for: an entry wired +/// with none (a `file:` dependency of the project's own, a hand-pointed +/// tarball) has nothing for pnpm to compare. A declaration the reader +/// cannot follow (an inline `overrides:` mapping that holds entries, a +/// package.json that does not parse, a file that cannot be read) may hold +/// the override, so the ref then stands, as it did before this check. A Rush lock is installed with Rush's own +/// settings, and a member's lock holds no vendored ref. +async fn confirm_pnpm_overrides( + ctx: &DiscoverCtx<'_>, + file: &str, + lock: &PnpmLock<'_>, + out: &mut Discovery, +) { + if crate::vendor::pnpm_lock::rush::is_lock_rel(file) { + return; + } + // `(override key, artifact)` of the lock's own `overrides:` section. + let recorded: Vec<(String, VendorRef)> = lock + .overrides() + .into_iter() + .filter_map(|(key, value)| Some((key, vendor_ref(&value)?))) + .collect(); + let recorded_for = |r: &PatchedRef| -> Vec<&(String, VendorRef)> { + let governed = r.mode == WiringMode::Vendored + && r.source_file == Path::new(file) + && r.part == TreePart::File; + recorded + .iter() + .filter(|(_, v)| governed && Some(v.artifact_rel.as_str()) == r.artifact_rel.as_deref()) + .collect() + }; + if out.refs.iter().all(|r| recorded_for(r).is_empty()) { + return; + } + let maps = PnpmOverrideMaps::read(ctx).await; + let pnpm = PnpmOverrideReader::of(lock, maps.manifest_text.as_deref()); + if pnpm.sources.iter().any(|source| maps.unreadable(*source)) { + return; + } + let undeclared = |r: &PatchedRef| -> Vec<&(String, VendorRef)> { + recorded_for(r) + .into_iter() + .filter(|(key, v)| !pnpm.reads(&maps, key, &v.artifact_rel)) + .collect() + }; + let (kept, dropped): (Vec, Vec) = std::mem::take(&mut out.refs) + .into_iter() + .partition(|r| undeclared(r).is_empty()); + out.refs = kept; + // Where `vendor` writes no `pnpm.overrides` table on a re-run: a + // lockfileVersion 9 project whose package.json has none while the + // workspace file carries an override the lock records, whatever pnpm + // reads (the backend's own predicate). + let vendor_skips_manifest = crate::formats::pnpm::lock_version_major(lock.text()) + .is_some_and(|v| v >= 9) + && crate::vendor::pnpm_lock::workspace_overrides_govern( + maps.manifest_doc.as_ref().unwrap_or(&Value::Null), + maps.workspace_text.as_deref(), + &crate::formats::pnpm::lines::split_lines(&lock.text().replace("\r\n", "\n")), + ); + for r in dropped { + let missing = undeclared(&r); + let keys: Vec = missing.iter().map(|(key, _)| format!("`{key}`")).collect(); + let artifact = r.artifact_rel.as_deref().unwrap_or_default(); + let who = &pnpm.who; + let table = format!("{PNPM_MANIFEST} `pnpm.overrides`"); + let block = format!("{PNPM_WORKSPACE} `overrides`"); + let undeclared_in = match pnpm.sources.as_slice() { + [OverrideSource::Manifest] => format!( + "{table} does not declare it, and that is the only place {who} reads overrides \ + from" + ), + [OverrideSource::Workspace] => format!( + "{block} does not declare it, and that is the only place {who} reads overrides \ + from" + ), + [OverrideSource::ManifestElseWorkspace] if maps.manifest_table => format!( + "{PNPM_MANIFEST} declares overrides without it, and {who} reads those in place \ + of {block}" + ), + [OverrideSource::ManifestElseWorkspace | OverrideSource::Unstated] => { + format!("neither {table} nor {block} declares it") + } + _ => format!("it is not declared where any of {who} reads overrides from"), + }; + // A re-run that skips package.json declares the override in the + // workspace file alone: by hand, unless a pnpm the project names + // reads it there. + let by_hand = vendor_skips_manifest + && !pnpm + .sources + .iter() + .any(|source| source.reads(false, true, maps.manifest_table)); + let remedy = if by_hand { + let entries: Vec = missing + .iter() + .map(|(key, v)| format!("`\"{key}\": \"file:{}\"`", v.artifact_rel)) + .collect(); + format!( + "Add {} to {table}: `socket-patch vendor` writes no such table while \ + {PNPM_WORKSPACE} carries overrides the lock records", + entries.join(", ") + ) + } else if maps + .workspace_text + .as_deref() + .is_some_and(crate::vendor::pnpm_lock::override_section_inline) + { + // An empty inline mapping (one with entries is unreadable and + // never gets here): the re-run refuses to edit it. + format!( + "Take the empty inline `overrides:` out of {PNPM_WORKSPACE} (`socket-patch \ + vendor` does not edit an inline mapping), then re-run `socket-patch vendor` \ + and commit the files it changes" + ) + } else { + "Re-run `socket-patch vendor` to declare it again, and commit the files it changes" + .to_string() + }; + out.diag( + DIAG_REF_INVALID, + file, + format!( + "{file}: {PNPM_OVERRIDE_UNDECLARED} {} for {} ({artifact}), but \ + {undeclared_in}. pnpm installs a lock only when its `overrides:` equal the \ + declared ones: a frozen install fails (ERR_PNPM_LOCKFILE_CONFIG_MISMATCH) and a \ + plain `pnpm install` takes the package from the registry again; not counted. \ + {remedy}", + keys.join(", "), + r.purl, + ), + ); + out.withheld.push(super::Recognized { + uuid: r.uuid, + mode: WiringMode::Vendored, + file: PathBuf::from(file), + }); + } +} + +/// Where the pnpm of a project reads its overrides from, and how a +/// diagnostic names that pnpm. +struct PnpmOverrideReader { + /// One source, or the several that the project's pins state. + sources: Vec, + /// `this project's pnpm (pnpm@9.15.9 (package.json packageManager))`. + who: String, +} + +impl PnpmOverrideReader { + /// From the pnpm pins package.json commits + /// ([`pinned_override_sources`]), else from what only one generation + /// of pnpm writes into a lock: a pre-9 lockfileVersion (pnpm 8 and + /// older) or an env lockfile document (pnpm 11 and newer). Committed + /// files only, so every checkout of a commit reads the same pnpm. + /// + /// [`pinned_override_sources`]: crate::formats::pnpm::pinned_override_sources + fn of(lock: &PnpmLock<'_>, manifest: Option<&str>) -> Self { + let stated = crate::formats::pnpm::pinned_override_sources(manifest); + if !stated.is_empty() { + let pins: Vec<&str> = stated.iter().map(|(_, pin)| pin.as_str()).collect(); + let who = match pins.as_slice() { + [pin] => format!("this project's pnpm ({pin})"), + pins => format!("the pnpm releases this project names ({})", pins.join(", ")), + }; + return PnpmOverrideReader { + sources: stated.iter().map(|(source, _)| *source).collect(), + who, + }; + } + let implied = crate::patch::redirect::upstream::npm::pnpm_settings_major(lock.text(), None); + let (source, who) = match implied { + Some(major) if major >= 11 => ( + OverrideSource::Workspace, + "the pnpm 11 or newer that wrote the lock's env document", + ), + Some(_) => ( + OverrideSource::Manifest, + "the pnpm 8 or older that wrote this lockfileVersion", + ), + None => (OverrideSource::Unstated, "pnpm"), + }; + PnpmOverrideReader { + sources: vec![source], + who: who.to_string(), + } + } + + /// Whether a pnpm the project names reads the override `key` onto the + /// artifact at `artifact_rel` from where `maps` declare it. + fn reads(&self, maps: &PnpmOverrideMaps, key: &str, artifact_rel: &str) -> bool { + self.sources + .iter() + .any(|source| maps.declare(*source, key, artifact_rel)) } } @@ -1057,10 +1281,7 @@ async fn extract_pnpm_lock( /// `pnpm.overrides`). struct PnpmLockOff { source: String, - /// `(override key, artifact)` of package.json `pnpm.overrides`. - manifest: Vec<(String, VendorRef)>, - /// `(override key, artifact)` of pnpm-workspace.yaml `overrides:`. - workspace: Vec<(String, VendorRef)>, + maps: PnpmOverrideMaps, /// The lock is off for pnpm 11+, which reads the workspace map alone. needs_workspace: bool, /// The lock is off for pnpm 10 and older, which read `pnpm.overrides`. @@ -1069,36 +1290,118 @@ struct PnpmLockOff { pnpm10: bool, } -impl PnpmLockOff { - async fn read(ctx: &DiscoverCtx<'_>, source: String) -> Self { +/// The vendored artifacts the two override maps of a pnpm project route +/// packages to: the declarations pnpm resolves with, with or without a +/// lock. +struct PnpmOverrideMaps { + /// `(override key, artifact)` of package.json: `pnpm.overrides` over + /// the top-level `resolutions`, which pnpm 10 and older read as + /// overrides too. + manifest: Vec<(String, VendorRef)>, + /// Whether package.json declares any override at all (an empty table + /// is none). + manifest_table: bool, + /// package.json holds text that is not JSON, or overrides that are not + /// a table: what it declares cannot be read. + manifest_unreadable: bool, + /// package.json's text and document, for the readers of its pnpm pins + /// and of what `vendor` would write. + manifest_text: Option, + manifest_doc: Option, + /// `(override key, artifact)` of pnpm-workspace.yaml `overrides:`. + workspace: Vec<(String, VendorRef)>, + /// The workspace file may declare overrides in a shape the line reader + /// does not follow ([`override_section_unreadable`]). + /// + /// [`override_section_unreadable`]: crate::vendor::pnpm_lock::override_section_unreadable + workspace_unreadable: bool, + workspace_text: Option, +} + +impl PnpmOverrideMaps { + async fn read(ctx: &DiscoverCtx<'_>) -> Self { let vendored = |entries: Vec<(String, String)>| -> Vec<(String, VendorRef)> { entries .into_iter() .filter_map(|(key, value)| Some((key, vendor_ref(&value)?))) .collect() }; - let manifest = ctx - .read_advisory_text("package.json") - .await - .and_then(|text| serde_json::from_str::(strip_bom(&text)).ok()) - .and_then(|doc| doc.pointer("/pnpm/overrides")?.as_object().cloned()) - .map(|map| { - map.into_iter() - .filter_map(|(key, value)| Some((key, value.as_str()?.to_string()))) - .collect() - }) - .unwrap_or_default(); - let workspace = ctx - .read_advisory_text(crate::utils::pnpm_workspace::PNPM_WORKSPACE) - .await - .map(|text| crate::vendor::pnpm_lock::workspace_override_entries(&text)) + // A file that is there and cannot be read may declare anything. + let manifest_read = ctx.read_advisory_text_if_present(PNPM_MANIFEST).await; + let workspace_read = ctx.read_advisory_text_if_present(PNPM_WORKSPACE).await; + let manifest_text = manifest_read.clone().ok().flatten(); + let doc = manifest_text + .as_deref() + .map(|text| serde_json::from_str::(strip_bom(text))); + let manifest_doc = match &doc { + Some(Ok(doc)) => Some(doc.clone()), + _ => None, + }; + // `pnpm.overrides` wins over a `resolutions` entry of the same key. + let tables: Vec<&Value> = ["/resolutions", "/pnpm/overrides"] + .iter() + .filter_map(|pointer| manifest_doc.as_ref()?.pointer(pointer)) + .collect(); + let mut merged: BTreeMap = BTreeMap::new(); + for (key, value) in tables.iter().filter_map(|t| t.as_object()).flatten() { + // A value that is not a string is no vendored override, but it + // still makes the table one that declares something. + merged.insert(key.clone(), value.as_str().unwrap_or_default().to_string()); + } + let workspace_text = workspace_read.clone().ok().flatten(); + let workspace = workspace_text + .as_deref() + .map(crate::vendor::pnpm_lock::override_section_entries) .unwrap_or_default(); + PnpmOverrideMaps { + manifest_table: !merged.is_empty(), + manifest: vendored(merged.into_iter().collect()), + manifest_unreadable: manifest_read.is_err() + || matches!(doc, Some(Err(_))) + || tables.iter().any(|table| !table.is_object()), + workspace: vendored(workspace), + workspace_unreadable: workspace_read.is_err() + || workspace_text + .as_deref() + .is_some_and(crate::vendor::pnpm_lock::override_section_unreadable), + manifest_text, + manifest_doc, + workspace_text, + } + } + + /// Whether the map a pnpm of `source` reads declares the override + /// `key` onto the artifact at `artifact_rel`, as a lock records it. + fn declare(&self, source: OverrideSource, key: &str, artifact_rel: &str) -> bool { + let declared = |map: &[(String, VendorRef)]| { + map.iter() + .any(|(k, artifact)| k == key && artifact.artifact_rel == artifact_rel) + }; + source.reads( + declared(&self.manifest), + declared(&self.workspace), + self.manifest_table, + ) + } + + /// Whether a map a pnpm of `source` reads is in a shape this reader + /// cannot follow, so that what it declares cannot be told. + fn unreadable(&self, source: OverrideSource) -> bool { + source.reads( + self.manifest_unreadable, + self.workspace_unreadable, + self.manifest_table || self.manifest_unreadable, + ) + } +} + +impl PnpmLockOff { + async fn read(ctx: &DiscoverCtx<'_>, source: String) -> Self { let (needs_workspace, needs_manifest, major) = crate::utils::pnpm_workspace::lockfile_off_sources(&ctx.view).await; PnpmLockOff { source, - manifest: vendored(manifest), - workspace: vendored(workspace), + maps: PnpmOverrideMaps::read(ctx).await, needs_workspace, needs_manifest, pnpm10: major == Some(10), @@ -1121,7 +1424,7 @@ impl PnpmLockOff { && Some(artifact.artifact_rel.as_str()) == r.artifact_rel.as_deref() }) }; - let (manifest, workspace) = (routed(&self.manifest), routed(&self.workspace)); + let (manifest, workspace) = (routed(&self.maps.manifest), routed(&self.maps.workspace)); (!self.needs_workspace || workspace) && (!self.needs_manifest || manifest || (self.pnpm10 && workspace)) } @@ -4580,6 +4883,649 @@ mod tests { assert!(attested(&run(&p).await), "pnpm 10, workspace override"); } + /// The vendored lock `vendor` writes for `left-pad@1.3.0` under + /// [`UUID_B`]: the override it records, the importer and the rekeyed + /// entry. `head` goes ahead of it (an env lockfile document). + fn pnpm_vendored_lock(head: &str) -> String { + let rel = format!(".socket/vendor/npm/{UUID_B}/left-pad-1.3.0.tgz"); + format!( + "{head}lockfileVersion: '9.0'\n\noverrides:\n left-pad@1.3.0: file:{rel}\n\n\ + importers:\n\n .:\n dependencies:\n left-pad:\n \ + specifier: file:{rel}\n version: file:{rel}\n\npackages:\n\n \ + left-pad@file:{rel}:\n resolution: {{integrity: {SRI}, tarball: file:{rel}}}\n \ + version: 1.3.0\n\nsnapshots:\n\n left-pad@file:{rel}: {{}}\n" + ) + } + + /// REGRESSION (#2382): pnpm installs a lock only when the lock's + /// `overrides:` equal the ones its settings declare, and each release + /// reads them from its own place ([`OverrideSource`], with the pnpm + /// releases each row was measured on). With the override declared + /// where that pnpm does not read it, a frozen install stops with + /// `ERR_PNPM_LOCKFILE_CONFIG_MISMATCH` and a plain one installs the + /// registry release and rewrites the lock. Such an entry was a ref, so + /// `vex` attested it and `vendor --check` verified it. + #[tokio::test] + async fn pnpm_vendored_ref_needs_its_recorded_override_declared() { + let rel = format!(".socket/vendor/npm/{UUID_B}/left-pad-1.3.0.tgz"); + const PURL: &str = "pkg:npm/left-pad@1.3.0"; + let project = |pin: Option<&str>, manifest: bool, workspace: bool| { + let p = Project::new(); + p.write("pnpm-lock.yaml", pnpm_vendored_lock("")); + let pin = pin.map_or(String::new(), |v| { + format!(r#""packageManager":"pnpm@{v}","#) + }); + let overrides = match manifest { + true => format!(r#","pnpm":{{"overrides":{{"left-pad@1.3.0":"file:{rel}"}}}}"#), + false => String::new(), + }; + p.write( + "package.json", + format!( + r#"{{"name":"app",{pin}"dependencies":{{"left-pad":"1.3.0"}}{overrides}}}"# + ), + ); + if workspace { + p.write( + "pnpm-workspace.yaml", + format!("packages:\n - '.'\noverrides:\n left-pad@1.3.0: file:{rel}\n"), + ); + } + p + }; + // What an undeclared entry's diagnostic says of the place. + #[derive(Debug, Clone, Copy, PartialEq)] + enum Place { + Manifest, + Workspace, + Neither, + } + use Place::*; + // (the pnpm the project pins, package.json declares, the workspace + // file declares, `Err(place)` when pnpm does not install the lock). + for (pin, manifest, workspace, installs) in [ + // No file states the pnpm: either map. + (None, false, false, Err(Neither)), + (None, true, false, Ok(())), + (None, false, true, Ok(())), + (None, true, true, Ok(())), + // pnpm older than 10.5.1: package.json alone. + (Some("8.15.9"), true, false, Ok(())), + (Some("8.15.9"), false, true, Err(Manifest)), + (Some("9.15.9"), true, false, Ok(())), + (Some("9.15.9"), true, true, Ok(())), + (Some("9.15.9"), false, true, Err(Manifest)), + (Some("9.15.9"), false, false, Err(Manifest)), + (Some("10.4.1"), true, false, Ok(())), + (Some("10.4.1"), false, true, Err(Manifest)), + (Some("10.5.0"), false, true, Err(Manifest)), + // pnpm 10.5.1 to 10.x: the workspace file when package.json + // has no table. + (Some("10.5.1"), false, true, Ok(())), + (Some("10.5.1"), true, false, Ok(())), + (Some("10.5.1"), false, false, Err(Neither)), + (Some("10.28.0"), true, false, Ok(())), + (Some("10.28.0"), false, true, Ok(())), + (Some("10.28.0"), true, true, Ok(())), + (Some("10.28.0"), false, false, Err(Neither)), + // pnpm 11 and newer: the workspace file alone. + (Some("11.29.0"), false, true, Ok(())), + (Some("11.29.0"), true, true, Ok(())), + (Some("11.29.0"), true, false, Err(Workspace)), + (Some("12.23.0"), false, true, Ok(())), + (Some("12.23.0"), true, false, Err(Workspace)), + (Some("12.23.0"), false, false, Err(Workspace)), + ] { + let case = format!("pnpm {pin:?}, package.json {manifest}, workspace {workspace}"); + let out = run(&project(pin, manifest, workspace)).await; + let invalid: Vec<&str> = out + .diagnostics + .iter() + .filter(|d| d.code == DIAG_REF_INVALID) + .map(|d| d.detail.as_str()) + .collect(); + let Err(place) = installs else { + assert_refs(&out, &[(PURL, UUID_B, WiringMode::Vendored)]); + assert!( + invalid.is_empty() && out.withheld.is_empty(), + "{case}: {invalid:#?}" + ); + continue; + }; + assert_refs(&out, &[]); + assert!( + out.shadowed.is_empty() && out.unattested.is_empty(), + "{case}" + ); + // Still wiring: the prune GC keeps the ledger entry, and the + // reason names the patch, the file pnpm reads and the remedy. + assert_eq!(out.withheld.len(), 1, "{case}"); + assert_eq!(out.withheld[0].uuid, UUID_B, "{case}"); + let [detail] = invalid.as_slice() else { + panic!("{case}: {invalid:#?}"); + }; + assert_eq!( + out.pnpm_override_undeclared(UUID_B) + .map(|d| d.detail.as_str()), + Some(*detail) + ); + assert!( + detail.contains(PURL) + && detail.contains(&rel) + && detail.contains("the lock records the override `left-pad@1.3.0`") + && detail.contains("ERR_PNPM_LOCKFILE_CONFIG_MISMATCH"), + "{case}: {detail}" + ); + let who = format!( + "this project's pnpm (pnpm@{} (package.json packageManager))", + pin.unwrap_or_default() + ); + let said = match place { + Manifest => format!( + "package.json `pnpm.overrides` does not declare it, and that is the only \ + place {who} reads overrides from" + ), + Workspace => format!( + "pnpm-workspace.yaml `overrides` does not declare it, and that is the only \ + place {who} reads overrides from" + ), + Neither => "neither package.json `pnpm.overrides` nor pnpm-workspace.yaml \ + `overrides` declares it" + .to_string(), + }; + assert!(detail.contains(&said), "{case}: {detail}"); + // `vendor` writes no `pnpm.overrides` table while the workspace + // file carries the override, so there the remedy is the entry. + let by_hand = place == Manifest && workspace; + let remedy = match by_hand { + true => format!(r#"Add `"left-pad@1.3.0": "file:{rel}"` to package.json"#), + false => "Re-run `socket-patch vendor`".to_string(), + }; + assert!(detail.contains(&remedy), "{case}: {detail}"); + assert_eq!(by_hand, !detail.contains("Re-run"), "{case}: {detail}"); + } + } + + /// A lock entry whose override is undeclared is dead to the liveness + /// gate (`vendor --check`, `vex`) but still wiring to the prune GC, + /// whose mistake would be a revert: re-running `vendor` completes it + /// (#2382). + #[tokio::test] + async fn pnpm_undeclared_override_is_dead_but_kept_by_the_prune_gc() { + let rel = format!(".socket/vendor/npm/{UUID_B}/left-pad-1.3.0.tgz"); + let entry: crate::vendor::state::VendorEntry = serde_json::from_value(serde_json::json!({ + "ecosystem": "npm", + "basePurl": "pkg:npm/left-pad@1.3.0", + "uuid": UUID_B, + "artifact": { "path": rel, "sha256": "" }, + "wiring": [{ "file": "pnpm-lock.yaml", "kind": "lock", "action": "added" }], + })) + .unwrap(); + let p = Project::new(); + p.write("pnpm-lock.yaml", pnpm_vendored_lock("")); + p.write("package.json", r#"{"name":"app"}"#); + let dead = p.discover().await; + assert!(!dead.vendor_entry_live(p.root(), &entry).await); + assert_eq!( + dead.vendor_entry_liveness(p.root(), &entry).await, + Some(false) + ); + assert_eq!(dead.vendor_entry_in_use(p.root(), &entry).await, Some(true)); + + p.write( + "package.json", + format!(r#"{{"name":"app","pnpm":{{"overrides":{{"left-pad@1.3.0":"file:{rel}"}}}}}}"#), + ); + let live = p.discover().await; + assert!(live.vendor_entry_live(p.root(), &entry).await); + assert_eq!(live.vendor_entry_in_use(p.root(), &entry).await, Some(true)); + } + + /// Which pnpm reads the overrides comes from the pins package.json + /// commits, read conservatively, then from what only one generation of + /// pnpm writes into a lock (#2382). Committed files only: the same + /// commit reads the same on every machine. + #[tokio::test] + async fn pnpm_recorded_override_is_read_for_the_projects_pnpm() { + let rel = format!(".socket/vendor/npm/{UUID_B}/left-pad-1.3.0.tgz"); + const PURL: &str = "pkg:npm/left-pad@1.3.0"; + let wired = [(PURL, UUID_B, WiringMode::Vendored)]; + let manifest = |pins: &str| { + format!( + r#"{{"name":"app",{pins}"dependencies":{{"left-pad":"1.3.0"}},"pnpm":{{"overrides":{{"left-pad@1.3.0":"file:{rel}"}}}}}}"# + ) + }; + let bare = |pins: &str| format!(r#"{{"name":"app",{pins}"private":true}}"#); + let workspace = format!("packages:\n - '.'\noverrides:\n left-pad@1.3.0: file:{rel}\n"); + let detail = |out: &Discovery| out.diagnostics[0].detail.clone(); + + // The install record is machine-local: whichever pnpm installed + // this checkout last decides nothing. + for record in [ + r#"{"layoutVersion":5,"packageManager":"pnpm@11.29.0"}"#, + "layoutVersion: 5\npackageManager: pnpm@9.15.9\n", + ] { + let p = Project::new(); + p.write("pnpm-lock.yaml", pnpm_vendored_lock("")); + p.write("node_modules/.modules.yaml", record); + p.write("package.json", manifest("")); + assert_refs(&run(&p).await, &wired); + p.write("package.json", bare("")); + p.write("pnpm-workspace.yaml", &workspace); + assert_refs(&run(&p).await, &wired); + } + + // Pins that name pnpm releases reading different places: a + // declaration counts when one of them reads it. + let two = r#""packageManager":"pnpm@9.15.9","engines":{"pnpm":"11.x"},"#; + let p = Project::new(); + p.write("pnpm-lock.yaml", pnpm_vendored_lock("")); + p.write("package.json", manifest(two)); + assert_refs(&run(&p).await, &wired); + p.write("package.json", bare(two)); + let out = run(&p).await; + assert_refs(&out, &[]); + assert!( + detail(&out).contains( + "it is not declared where any of the pnpm releases this project names \ + (pnpm@9.15.9 (package.json packageManager), pnpm@11.x (package.json \ + engines.pnpm)) reads overrides from" + ) && detail(&out).contains("Re-run `socket-patch vendor`"), + "{}", + detail(&out) + ); + p.write("pnpm-workspace.yaml", &workspace); + assert_refs(&run(&p).await, &wired); + // Neither of two pinned releases reads the workspace file beside a + // table of the project's own: either file alone is not enough. + let both10 = r#""packageManager":"pnpm@10.28.0","devEngines":{"packageManager":{"name":"pnpm","version":"10.4.1"}},"pnpm":{"overrides":{"ms@2.0.0":"2.1.3"}},"#; + p.write("package.json", bare(both10)); + assert_refs(&run(&p).await, &[]); + + // A range that reaches across a boundary states nothing: beside an + // exact pin the pin decides, alone it leaves either map. + for (pins, attested) in [ + ( + r#""packageManager":"pnpm@11.29.0","engines":{"pnpm":">=9"},"#, + false, + ), + (r#""engines":{"pnpm":">=9"},"#, true), + (r#""engines":{"pnpm":"^10.4.0"},"#, true), + (r#""engines":{"pnpm":"11.x"},"#, false), + (r#""engines":{"pnpm":"~10.4.0"},"#, true), + ( + r#""devEngines":{"packageManager":{"name":"pnpm","version":"12.23.0"}},"#, + false, + ), + ] { + let p = Project::new(); + p.write("pnpm-lock.yaml", pnpm_vendored_lock("")); + p.write("package.json", manifest(pins)); + let expected: &[_] = if attested { &wired } else { &[] }; + assert_refs(&run(&p).await, expected); + } + + // No pin: an env lockfile document is pnpm 11's. + let env = + "---\nlockfileVersion: '9.0'\n\nimporters:\n\n .:\n configDependencies:\n \ + cfg:\n specifier: 1.0.0\n version: 1.0.0\n\npackages:\n\n \ + cfg@1.0.0:\n resolution: {integrity: sha512-CFG==}\n\n---\n"; + let p = Project::new(); + p.write("pnpm-lock.yaml", pnpm_vendored_lock(env)); + p.write("package.json", manifest("")); + let out = run(&p).await; + assert_refs(&out, &[]); + assert!( + detail(&out).contains("the pnpm 11 or newer that wrote the lock's env document"), + "{}", + detail(&out) + ); + p.write("pnpm-workspace.yaml", &workspace); + assert_refs(&run(&p).await, &wired); + + // No pin: a lockfileVersion 6 lock is pnpm 8's, which reads + // package.json alone. The legacy backend always writes the + // package.json override, so re-running `vendor` is the remedy. + let legacy = format!( + "lockfileVersion: '6.0'\n\noverrides:\n left-pad@1.3.0: file:{rel}\n\ndependencies:\n \ + left-pad:\n specifier: file:/abs/app/{rel}\n version: file:{rel}\n\npackages:\n\n \ + file:{rel}:\n resolution: {{integrity: {SRI}, tarball: file:{rel}}}\n \ + name: left-pad\n version: 1.3.0\n dev: false\n" + ); + let p = Project::new(); + p.write("pnpm-lock.yaml", &legacy); + p.write("package.json", manifest("")); + assert_refs(&run(&p).await, &wired); + p.write("package.json", r#"{"name":"app"}"#); + p.write("pnpm-workspace.yaml", &workspace); + let out = run(&p).await; + assert_refs(&out, &[]); + assert!( + detail(&out).contains("the pnpm 8 or older that wrote this lockfileVersion") + && detail(&out).contains("Re-run `socket-patch vendor`"), + "{}", + detail(&out) + ); + } + + /// Only what pnpm compares is asked for (#2382): the override keys the + /// lock records, spelled as the lock spells them, in the map that pnpm + /// reads. An entry wired with no recorded override has nothing to + /// confirm, and a declaration in a shape the reader cannot follow + /// leaves the ref as it was. + #[tokio::test] + async fn pnpm_recorded_override_is_compared_as_pnpm_compares_it() { + let rel = format!(".socket/vendor/npm/{UUID_B}/left-pad-1.3.0.tgz"); + const PURL: &str = "pkg:npm/left-pad@1.3.0"; + let wired = [(PURL, UUID_B, WiringMode::Vendored)]; + let manifest = |key: &str, value: &str| { + format!(r#"{{"name":"app","pnpm":{{"overrides":{{"{key}":"{value}"}}}}}}"#) + }; + let block = format!("packages:\n - '.'\noverrides:\n left-pad@1.3.0: file:{rel}\n"); + let p = Project::new(); + p.write("pnpm-lock.yaml", pnpm_vendored_lock("")); + // Another key, another artifact, a registry version: not the + // lock's override. + for (key, value) in [ + ("left-pad", format!("file:{rel}")), + ("left-pad@1", format!("file:{rel}")), + ( + "left-pad@1.3.0", + format!("file:.socket/vendor/npm/{UUID_A}/left-pad-1.3.0.tgz"), + ), + ("left-pad@1.3.0", "1.3.0".to_string()), + ("right-pad@1.3.0", format!("file:{rel}")), + ] { + p.write("package.json", manifest(key, &value)); + assert_refs(&run(&p).await, &[]); + } + p.write( + "package.json", + manifest("left-pad@1.3.0", &format!("file:{rel}")), + ); + assert_refs(&run(&p).await, &wired); + // A BOM, and a quoted key in the workspace file, read as pnpm reads + // them. + p.write( + "package.json", + format!( + "\u{feff}{}", + manifest("left-pad@1.3.0", &format!("file:{rel}")) + ), + ); + assert_refs(&run(&p).await, &wired); + p.write("package.json", r#"{"name":"app"}"#); + p.write( + "pnpm-workspace.yaml", + format!( + "packages:\n - '.'\noverrides:\n 'left-pad@1.3.0': \"file:{rel}\" # socket\n" + ), + ); + assert_refs(&run(&p).await, &wired); + + // pnpm 10.5.1 to 10.x read a `pnpm.overrides` table in place of + // the workspace file's (measured on 10.28.0): a table without the + // override hides the workspace declaration, and `vendor` adds the + // override to a table that exists. + let p = Project::new(); + p.write("pnpm-lock.yaml", pnpm_vendored_lock("")); + p.write("pnpm-workspace.yaml", &block); + let pinned = |pin: &str, table: &str| { + format!(r#"{{"name":"app","packageManager":"pnpm@{pin}"{table}}}"#) + }; + let own_table = r#","pnpm":{"overrides":{"ms@2.0.0":"2.1.3"}}"#; + p.write("package.json", pinned("10.28.0", "")); + assert_refs(&run(&p).await, &wired); + p.write("package.json", pinned("10.28.0", own_table)); + let out = run(&p).await; + assert_refs(&out, &[]); + let detail = &out.diagnostics[0].detail; + assert!( + detail.contains( + "package.json declares overrides without it, and this project's pnpm \ + (pnpm@10.28.0 (package.json packageManager)) reads those in place of \ + pnpm-workspace.yaml `overrides`" + ) && detail.contains("Re-run `socket-patch vendor`"), + "{detail}" + ); + // pnpm 11 ignores the table, and with no pin either map counts. + p.write("package.json", pinned("11.29.0", own_table)); + assert_refs(&run(&p).await, &wired); + p.write("package.json", format!(r#"{{"name":"app"{own_table}}}"#)); + assert_refs(&run(&p).await, &wired); + // An empty table declares nothing (measured on 10.5.1 and 10.28.0), + // and a top-level `resolutions` is a table like `pnpm.overrides` + // (10.28.0). + p.write( + "package.json", + pinned("10.28.0", r#","pnpm":{"overrides":{}}"#), + ); + assert_refs(&run(&p).await, &wired); + p.write( + "package.json", + pinned("10.28.0", r#","resolutions":{"ms@2.0.0":"2.1.3"}"#), + ); + assert_refs(&run(&p).await, &[]); + + // pnpm 10 and older read `resolutions` as overrides (measured on + // 9.15.9 and 10.28.0); pnpm 11 does not (11.29.0). + let resolved = format!(r#","resolutions":{{"left-pad@1.3.0":"file:{rel}"}}"#); + for (pin, installs) in [("9.15.9", true), ("10.28.0", true), ("11.29.0", false)] { + let p = Project::new(); + p.write("pnpm-lock.yaml", pnpm_vendored_lock("")); + p.write("package.json", pinned(pin, &resolved)); + let expected: &[_] = if installs { &wired } else { &[] }; + assert_refs(&run(&p).await, expected); + } + // `pnpm.overrides` wins over `resolutions` for the same key. + let shadowed = format!( + r#","resolutions":{{"left-pad@1.3.0":"file:{rel}"}},"pnpm":{{"overrides":{{"left-pad@1.3.0":"1.3.0"}}}}"# + ); + let p = Project::new(); + p.write("pnpm-lock.yaml", pnpm_vendored_lock("")); + p.write("pnpm-workspace.yaml", &block); + p.write("package.json", pinned("9.15.9", &shadowed)); + assert_refs(&run(&p).await, &[]); + + // pnpm 9, the override in the workspace file alone: `vendor` adds + // it to a `pnpm.overrides` table that exists, so re-running is the + // remedy there; with no table the entry has to be added by hand. + for (table, by_hand) in [("", true), (own_table, false)] { + p.write("package.json", pinned("9.15.9", table)); + let out = run(&p).await; + assert_refs(&out, &[]); + let detail = &out.diagnostics[0].detail; + assert_eq!( + detail.contains("Add `\"left-pad@1.3.0\""), + by_hand, + "{detail}" + ); + assert_eq!( + detail.contains("Re-run `socket-patch vendor`"), + !by_hand, + "{detail}" + ); + } + + // pnpm 10.28.0 beside a `resolutions` entry of the project's own: + // it reads package.json, where a re-run writes nothing (the + // backend looks for a `pnpm.overrides` table), so the entry is + // given there too. + p.write( + "package.json", + pinned("10.28.0", r#","resolutions":{"ms@2.0.0":"2.1.3"}"#), + ); + let out = run(&p).await; + assert_refs(&out, &[]); + assert!( + out.diagnostics[0] + .detail + .contains("Add `\"left-pad@1.3.0\"") + && !out.diagnostics[0].detail.contains("Re-run"), + "{}", + out.diagnostics[0].detail + ); + + // The same holds when the workspace file carries another override + // the lock records and this one is in neither file: the re-run + // would write the workspace entry alone. + let two_recorded = + pnpm_vendored_lock("").replace("overrides:\n", "overrides:\n ms@2.0.0: 2.1.3\n"); + let q = Project::new(); + q.write("pnpm-lock.yaml", &two_recorded); + q.write("package.json", pinned("9.15.9", "")); + q.write( + "pnpm-workspace.yaml", + "packages:\n - '.'\noverrides:\n ms@2.0.0: 2.1.3\n", + ); + let out = run(&q).await; + assert_refs(&out, &[]); + assert!( + out.diagnostics[0] + .detail + .contains("Add `\"left-pad@1.3.0\""), + "{}", + out.diagnostics[0].detail + ); + + // A declaration the line reader cannot follow may hold the + // override (pnpm reads it all the same), so the ref stands as it + // did before: an inline mapping, a second YAML document, a + // package.json that is not JSON. + for (pin, file, text) in [ + ( + "11.29.0", + "pnpm-workspace.yaml", + format!("packages: ['.']\noverrides: {{'left-pad@1.3.0': 'file:{rel}'}}\n"), + ), + ( + "11.29.0", + "pnpm-workspace.yaml", + "packages:\n - '.'\n---\noverrides:\n a: b\n".to_string(), + ), + ("9.15.9", "package.json", "{ not json".to_string()), + ] { + let p = Project::new(); + p.write("pnpm-lock.yaml", pnpm_vendored_lock("")); + p.write("package.json", pinned(pin, "")); + p.write(file, &text); + let out = run(&p).await; + assert_refs(&out, &wired); + assert!(out.diagnostics.is_empty(), "{file}: {:#?}", out.diagnostics); + } + + // A file that is there and cannot be read may declare anything. + let q = Project::new(); + q.write("pnpm-lock.yaml", pnpm_vendored_lock("")); + q.write("package.json/not-a-file", ""); + assert_refs(&run(&q).await, &wired); + // An empty inline mapping or a null declares nothing, though. + for empty in [ + "overrides: {}", + "overrides: { } # none", + "overrides: ~", + "overrides: null", + ] { + let q = Project::new(); + q.write("pnpm-lock.yaml", pnpm_vendored_lock("")); + q.write("package.json", pinned("11.29.0", "")); + q.write( + "pnpm-workspace.yaml", + format!("packages:\n - '.'\n{empty}\n"), + ); + let out = run(&q).await; + assert_refs(&out, &[]); + // `vendor` refuses to edit an inline mapping, so the remedy + // says to take it out first. + assert!( + out.diagnostics[0] + .detail + .contains("Take the empty inline `overrides:` out of pnpm-workspace.yaml"), + "{empty}: {}", + out.diagnostics[0].detail + ); + } + + // A CRLF checkout and a BOM read like their plain twins: the + // recorded override is still found, and still has to be declared. + for text in [ + pnpm_vendored_lock("").replace('\n', "\r\n"), + format!("\u{feff}{}", pnpm_vendored_lock("")), + ] { + let p = Project::new(); + p.write("pnpm-lock.yaml", &text); + p.write("package.json", r#"{"name":"app"}"#); + assert_refs(&run(&p).await, &[]); + p.write( + "pnpm-workspace.yaml", + format!("packages:\r\n - '.'\r\noverrides:\r\n left-pad@1.3.0: file:{rel}\r\n"), + ); + assert_refs(&run(&p).await, &wired); + } + + // The lock records no override for the artifact (a `file:` + // dependency of the project's own): pnpm compares nothing. + let unrecorded = pnpm_vendored_lock("") + .replace(&format!("overrides:\n left-pad@1.3.0: file:{rel}\n\n"), ""); + let p = Project::new(); + p.write("pnpm-lock.yaml", &unrecorded); + p.write("package.json", pinned("11.29.0", "")); + let out = run(&p).await; + assert_refs(&out, &wired); + assert!(out.diagnostics.is_empty(), "{:#?}", out.diagnostics); + // An override for another package does not ask for this one's. + let other = unrecorded.replace("importers:", "overrides:\n ms@2.0.0: 2.1.3\n\nimporters:"); + p.write("pnpm-lock.yaml", &other); + assert_refs(&run(&p).await, &wired); + + // Two keys for one artifact: each must be declared. + let two = pnpm_vendored_lock("").replace( + &format!(" left-pad@1.3.0: file:{rel}\n"), + &format!(" left-pad: file:{rel}\n left-pad@1.3.0: file:{rel}\n"), + ); + let p = Project::new(); + p.write("pnpm-lock.yaml", &two); + p.write( + "package.json", + manifest("left-pad@1.3.0", &format!("file:{rel}")), + ); + let out = run(&p).await; + assert_refs(&out, &[]); + let detail = &out.diagnostics[0].detail; + assert!( + detail.contains("the override `left-pad` for") && !detail.contains("`left-pad@1.3.0`"), + "{detail}" + ); + + // Another rejected entry of the same artifact does not stand in + // for the reason `vendor --check` prints. + let twin = pnpm_vendored_lock("").replace( + "\nsnapshots:", + &format!( + "\n left-pad@file:.socket/vendor/npm/{UUID_B}/other-1.3.0.tgz:\n \ + resolution: {{integrity: {SRI}, tarball: file:{rel}}}\n version: 1.3.0\n\nsnapshots:" + ), + ); + let p = Project::new(); + p.write("pnpm-lock.yaml", &twin); + p.write("package.json", r#"{"name":"app"}"#); + let out = run(&p).await; + assert_refs(&out, &[]); + let invalid: Vec<&str> = out + .diagnostics + .iter() + .filter(|d| d.code == DIAG_REF_INVALID && d.detail.contains(UUID_B)) + .map(|d| d.detail.as_str()) + .collect(); + assert_eq!(invalid.len(), 2, "{invalid:#?}"); + let named = out.pnpm_override_undeclared(UUID_B).unwrap(); + assert!( + named.detail.contains("the lock records the override"), + "{}", + named.detail + ); + } + /// npm's `package-lock=false` (or its `shrinkwrap=false` alias) in the /// project `.npmrc` makes `npm install` ignore both npm locks and /// resolve from the registry, while `npm ci` still installs from them @@ -5275,6 +6221,15 @@ packages: dev: false "; + /// The package.json a vendored golden's project carries: the override + /// the backend writes beside the lock, without which pnpm does not + /// install that lock (#2382). + fn golden_manifest(uuid: &str) -> String { + format!( + r#"{{"name":"app","pnpm":{{"overrides":{{"left-pad@1.3.0":"file:.socket/vendor/npm/{uuid}/left-pad-1.3.0.tgz"}}}}}}"# + ) + } + /// Every vendored golden (v9 single + workspace, v5.4 direct + /// transitive-only, v6.0), LF and CRLF (a Windows autocrlf checkout), /// yields exactly the vendored left-pad with its artifact path and the @@ -5302,6 +6257,7 @@ packages: text = text.replace('\n', "\r\n"); } p.write("pnpm-lock.yaml", &text); + p.write("package.json", golden_manifest(uuid)); let out = run(&p).await; assert_refs( &out, @@ -5500,6 +6456,7 @@ packages: async fn pnpm_and_npm_locks_are_both_discovered() { let p = Project::new(); p.write("pnpm-lock.yaml", P1_AFTER_LOCK); + p.write("package.json", golden_manifest(V_UUID)); let url = hosted_url("npm", "ms", "2.1.3", UUID_A, "ms-2.1.3.tgz"); p.write( "package-lock.json", diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 7a93fa819e..f79504db60 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -238,6 +238,32 @@ Each Legacy format has an upgrade path and an undo path. Both work in v5: which pnpm applies through `overrides` without a lock; `vex` attests such a vendored pin only while the override map that pnpm reads still routes the package to its artifact, and omits it otherwise (`vex_lock_not_read`). + **A vendored override has to stay declared.** pnpm installs a lock only + when the lock's `overrides:` equal the ones its settings declare: with a + vendored override missing from the place pnpm reads, a frozen install + fails (`ERR_PNPM_LOCKFILE_CONFIG_MISMATCH`) and a plain `pnpm install` + takes the package from the registry again. pnpm older than 10.5.1 reads + `package.json` alone (`pnpm.overrides`, over the top-level + `resolutions`); pnpm 10.5.1 through 10.x reads `package.json` when it + declares any override, and `overrides:` in `pnpm-workspace.yaml` when it + declares none; pnpm 11 and newer read the workspace file alone. Which + pnpm that is comes from the pins `package.json` commits + (`packageManager`, `devEngines`, `engines.pnpm`), each counted when + every release it admits reads the same place, and else from the lock (a + pnpm 7 or 8 lock, or pnpm 11's env document). The install record in + `node_modules` is not read, so a commit reads the same on every machine. + With no pin either file counts, and with pins that name different + releases the override counts when one of them reads it. + So a `pnpm-workspace.yaml` left out of the commit, a `package.json` put + back by a merge, or a move from pnpm 9 to 11 leaves the lock wired and + the patch uninstallable. `vendor --check` then fails the package (`wiring + incomplete`, naming the file) and `vex` omits it (`patched_ref_invalid`, + `vendor_unwired`). Re-running `socket-patch vendor` declares the override + again; before pnpm 10.5.1 it writes no `pnpm.overrides` table while + `pnpm-workspace.yaml` carries overrides the lock records, and the message + then gives the entry to add. Not checked this way: a Rush lock, a lock + entry that records no override, and a declaration `socket-patch` cannot + read (an inline `overrides:` mapping, a `package.json` that is not JSON). **One mode for a package and its dependency.** pnpm 12.23 and newer refuse a lock in which a package fetched from a hosted patch depends on a local file (`ERR_PNPM_LOCAL_SUBDEP_NOT_ALLOWED`), on every install, frozen or