diff --git a/.github/workflows/bazel-npm.yml b/.github/workflows/bazel-npm.yml index b7abd2c39..8a82a8605 100644 --- a/.github/workflows/bazel-npm.yml +++ b/.github/workflows/bazel-npm.yml @@ -2,12 +2,15 @@ name: Bazel patch compatibility (npm) # The npm flows of the real-Bazel tests (`npm::` in `e2e_bazel_build`): # hosted and vendored mode for a package that aspect_rules_js links from a -# pnpm lock, agent mode for the copy of it in `node_modules`, and hosted +# pnpm lock (hosted mode with the lock routed through the patch's registry, +# pinned beside `trustLockfile: true`, and pinned beside a `patches` entry +# of the hub), agent mode for the copy of it in `node_modules`, and hosted # mode on a hub that keeps the lock up to date with a pnpm of its own (a -# pnpm 11, and the pnpm 10 that rules_js picks), on each Bazel release -# below. bazel-compatibility.yml holds the legs and what -# every ecosystem shares; this file says when the npm legs run and on which -# releases. +# pnpm 11, and the pnpm 10 that rules_js picks), that hub also for a patch +# whose registry the patch service offers and for a scan that is told not +# to write `trustLockfile: true`, on each Bazel release below. +# bazel-compatibility.yml holds the legs and what every ecosystem shares; +# this file says when the npm legs run and on which releases. # # Beyond what every leg needs, an npm leg downloads Node from nodejs.org, # ruleset archives from codeload.github.com and, for the hubs that keep diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index bc390b2e6..88060d8a0 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -333,11 +333,11 @@ The declaration is what pnpm verifies the lock entries against; the override is **Registry names.** A registry is named after its patch: `socket-` and the first eight hex digits of the patch UUID, in lower case (`socket-58f14d5a`). When two patches of the project start with the same eight digits, or the project declares a registry of its own under that name, the name takes four more digits at a time (12, 16, … up to all 32) until it is free; every patch that shares the digits is lengthened, so each name still tells its patch. A registry is the CLI's only when its name has that shape (`socket-` and 8 to 32 lowercase hex digits) **and** its address is the serve directory of a patch whose UUID starts with those digits, on a patch server (Socket's own, a `--patch-server-url`, or the server a grant of the run is served from). An override is the CLI's only when it routes `@` to such a registry (`:`). Everything else in `namedRegistries`, in `overrides` and in a lock's `overrides:` is the user's and is never rewritten or removed: a registry of the user's under a name of that shape (`socket-58f14d5a: https://npm.corp.example/`) stays theirs, and so does one named `socket`. The one exception is a leftover: a name of that shape that `namedRegistries` does not declare at all, still used by an override or a lock key (an interrupted run), is the CLI's to clean up. **How a lock key is read.** Every reader of a pnpm lock (the hosted rewrite, `vex`, `list`, `rollback`, `remove`, vendoring, the lock inventory) takes a key `@:` for the release `@` only when `` has that shape, `socket-` and 8 to 32 lowercase hex digits: a lock is all they have to go by. A key through any other registry is a release from a registry of the project's own, never the npm release of the same name and version, whatever the registry is called: `leaf@socket:1.0.0` from a registry the project named `socket` is not read, not repointed and not counted. **A replaced patch renames its registry.** A patch that supersedes another for the same release has a new UUID, so its registry has a new name and a new address. The scan that is granted it rewrites the `namedRegistries` entry, the override's value, the lock's `overrides:` record and every lock key and reference of that release (`@socket-:` becomes `@socket-:`), with the new tarball and integrity. That is the whole diff of a superseded patch, and it is larger than the two `resolution` lines the `trustLockfile` path changes. -The route is taken only when **all** of these hold; otherwise the run takes the `trustLockfile` path below with the locks in the plain shape (a lock half routed would fail to install): (1) the project's own root file is the one pnpm reads (not a workspace member whose settings live in an ancestor file, #880), every governing lock is lockfileVersion 9 (Rush and legacy locks keep their own guidance); (2) every Socket-hosted tarball the governing locks record after the run has a registry: this run was granted it **with** a registry address, or an earlier run routed it, this run was **not** granted it, and the files still route it (the lock keys the release by a registry of the CLI's, the workspace file has its override to that registry, and the registry's address is the directory the tarball is served from). So a run granted only part of the project's patches (a scan of one subtree of a monorepo with one root lock, a search that lists fewer patches than the lock pins) leaves the rest routed and rewrites nothing for them. A pin this run was granted **without** an address is never kept that way (the grant overrules the files), and neither is an ungranted pin the files do not route: either one puts the whole lock on `trustLockfile` and is named. A pin on a patch mirror (`--patch-mirror-url`, experimental) has no address either, whatever its grant carries: see "Patch mirror (experimental)". A tarball is Socket-hosted when this run pinned it or its URL has the patch server's path shape, and every other tarball is the user's own; (3) every pnpm pin of the project (the sources of the #734 rule below, at least one present) proves pnpm 11.20 or newer: the lowest version it admits is 11.20 or higher (`11.28.13`, `^11.20.0`, `>=11.20`, `12`, `>=12`, `12 || 13`, `11.20.0 - 13.0.0`; `>` is read as `>=`, so `>11.19` proves nothing), since older releases write another lock for the same override; a range that reaches below it (`>=11`, `^11`), one the CLI cannot read, or pins that disagree prove nothing; (4) the workspace file can be read, is not a keyless file beside a lock that lists workspace members (#1096), and is a shape a line splice can extend (not a flow-style or indented root, several documents, a `namedRegistries` or `overrides` value on one line, a repeated key, an entry that is not a one-line `key: value`); (5) no override of the user's targets a patched package, by any selector (``, `@`, `>`): pnpm applies one override per dependency, so the CLI's would lose to it or displace it, and the user's is never overwritten. It is looked for in pnpm-workspace.yaml, the one place the gated pnpm releases read overrides from (`pnpm.overrides` and `resolutions` in package.json are not read by pnpm 11.20 and later, measured through 12.22.0); (6) each lock is one the rewrite was captured against: the release is not a `pnpm patch` copy or an npm alias, an importer that depends on it asks through a plain semver range that admits it (not a tag, `catalog:`, `workspace:`, `npm:` or a URL), no importer locks another version of the package through a range that admits the patched one, no package is installed both with and without the release as its peer (pnpm 11 and 12 lock that differently), the release is not installed as another package's optional peer (pnpm resolves that copy around an override, so it would stay unpatched), and every entry of the lock is one run of lines (a `deprecated:` message of several paragraphs, or one that keeps its trailing line breaks, is written with empty lines inside its entry; a message of several lines without one is a block the routed entry simply loses); (7) no package version is pinned to two patches (an override routes a package version to one registry, and a registry serves one patch); (8) `--no-trust-lockfile-config` is not set, or the file already holds the route exactly; (9) in a Bazel workspace, it is certain that no rules_js hub reads a governing lock. One reads it when an `npm.npm_translate_lock` call of aspect_rules_js names it in a plain string, or has a `pnpm_lock` that is not written out as one, whatever else the call says. And one may read it wherever the workspace was not read whole: a file that `MODULE.bazel` includes and that is missing or unreadable, a use of the extension that is not a plain call of a tag, a `WORKSPACE` file that cannot be read or that brings in rules_js (a `load` from `@aspect_rules_js`, a `load` of `npm_translate_lock` from anywhere, or a call of that rule under any name a `load` gives it). A `WORKSPACE` file that is about something else, an `http_archive` of another ruleset say, defines no hub of a pnpm lock and blocks nothing (see "In a Bazel workspace" below). The write respects `--dry-run` and is refused through a symlink. +The route is taken only when **all** of these hold; otherwise the run takes the `trustLockfile` path below with the locks in the plain shape (a lock half routed would fail to install): (1) the project's own root file is the one pnpm reads (not a workspace member whose settings live in an ancestor file, #880), every governing lock is lockfileVersion 9 (Rush and legacy locks keep their own guidance); (2) every Socket-hosted tarball the governing locks record after the run has a registry: this run was granted it **with** a registry address, or an earlier run routed it, this run was **not** granted it, and the files still route it (the lock keys the release by a registry of the CLI's, the workspace file has its override to that registry, and the registry's address is the directory the tarball is served from). So a run granted only part of the project's patches (a scan of one subtree of a monorepo with one root lock, a search that lists fewer patches than the lock pins) leaves the rest routed and rewrites nothing for them. A pin this run was granted **without** an address is never kept that way (the grant overrules the files), and neither is an ungranted pin the files do not route: either one puts the whole lock on `trustLockfile` and is named. A pin on a patch mirror (`--patch-mirror-url`, experimental) has no address either, whatever its grant carries: see "Patch mirror (experimental)". A tarball is Socket-hosted when this run pinned it or its URL has the patch server's path shape, and every other tarball is the user's own; (3) every pnpm pin of the project (the sources of the #734 rule below, at least one present) proves pnpm 11.20 or newer: the lowest version it admits is 11.20 or higher (`11.28.13`, `^11.20.0`, `>=11.20`, `12`, `>=12`, `12 || 13`, `11.20.0 - 13.0.0`; `>` is read as `>=`, so `>11.19` proves nothing), since older releases write another lock for the same override; a range that reaches below it (`>=11`, `^11`), one the CLI cannot read, or pins that disagree prove nothing; (4) the workspace file can be read, is not a keyless file beside a lock that lists workspace members (#1096), and is a shape a line splice can extend (not a flow-style or indented root, several documents, a `namedRegistries` or `overrides` value on one line, a repeated key, an entry that is not a one-line `key: value`); (5) no override of the user's targets a patched package, by any selector (``, `@`, `>`): pnpm applies one override per dependency, so the CLI's would lose to it or displace it, and the user's is never overwritten. It is looked for in pnpm-workspace.yaml, the one place the gated pnpm releases read overrides from (`pnpm.overrides` and `resolutions` in package.json are not read by pnpm 11.20 and later, measured through 12.22.0); (6) each lock is one the rewrite was captured against: the release is not a `pnpm patch` copy or an npm alias, an importer that depends on it asks through a plain semver range that admits it (not a tag, `catalog:`, `workspace:`, `npm:` or a URL), no importer locks another version of the package through a range that admits the patched one, no package is installed both with and without the release as its peer (pnpm 11 and 12 lock that differently), the release is not installed as another package's optional peer (pnpm resolves that copy around an override, so it would stay unpatched), and every entry of the lock is one run of lines (a `deprecated:` message of several paragraphs, or one that keeps its trailing line breaks, is written with empty lines inside its entry; a message of several lines without one is a block the routed entry simply loses); (7) no package version is pinned to two patches (an override routes a package version to one registry, and a registry serves one patch); (8) `--no-trust-lockfile-config` is not set, or the file already holds the route exactly; (9) in a Bazel workspace, every rules_js hub that reads a governing lock is one whose build takes a routed lock, and it is certain which hubs read one. A hub reads a lock when an `npm.npm_translate_lock` call of aspect_rules_js names it in a plain string, or has a `pnpm_lock` that is not written out as one. Its build takes a routed lock when the project is at the root of the Bazel workspace and has no pnpm lock but the root one (none of a workspace member's own under `sharedWorkspaceLockfile: false`), the call names the root `pnpm-lock.yaml` in a plain string and passes nothing but `name`, `pnpm_lock`, `data`, `update_pnpm_lock` and `use_pnpm` (no other attribute, no `*` or `**`), and the call either has no `update_pnpm_lock` (or `False`), or has `update_pnpm_lock = True`, a `data` that is a list of strings with the label of the `pnpm-workspace.yaml` beside the lock, and a pnpm that the root module states as a release of 11.20.0 or later (as `redirect_pnpm_bazel_workspace_hidden` reads the pnpm of a hub, in a repository of the use of the pnpm extension that every module shares, and by no use of that extension with `dev_dependency`, whose tags Bazel drops under `--ignore_dev_dependency`; a release that is not written out, a prerelease, a number of fewer than three parts, the pnpm rules_js picks and an older one do not count). And one may read a lock in another shape wherever the workspace was not read whole, also beside a call in one of those two: a file that `MODULE.bazel` includes and that is missing or unreadable, a use of the extension that is not a plain call of a tag, a `WORKSPACE` file that cannot be read or that brings in rules_js (a `load` from `@aspect_rules_js`, a `load` of `npm_translate_lock` from anywhere, or a call of that rule under any name a `load` gives it). A `WORKSPACE` file that is about something else, an `http_archive` of another ruleset say, defines no hub of a pnpm lock and blocks nothing (see "In a Bazel workspace" below). The write respects `--dry-run` and is refused through a symlink. -**In a Bazel workspace.** The lock reader of rules_js takes a routed lock (measured on macOS: rules_js 3.6.0 on Bazel 9.3.2 builds one for a hub without `update_pnpm_lock`, and the built packages hold the patched bytes; rules_js 2.9.3 on Bazel 8.8.2 does too). What holds the route back is the pnpm a hub runs with `update_pnpm_lock`: it sees pnpm-workspace.yaml only where the call lists it, and may be older than pnpm 11.20 (rules_js picks a pnpm 10 where the workspace states none). Run as the hub runs it (`pnpm install --lockfile-only` beside the lock and `package.json`, without the workspace file), pnpm 11.28.13 and 12.22.0 reject a routed lock (`ERR_PNPM_MISSING_NAMED_REGISTRY`, measured). No Bazel leg builds a routed lock with `update_pnpm_lock` yet, so for now every lock that a hub reads is pinned as on a patch service that offers no registry, the files byte for byte, which is the pin the Bazel legs build, and the warning names the call ("… because a Bazel hub reads the pnpm lock (MODULE.bazel:7), and a lock that a hub reads is not routed yet …"; for a project below the Bazel root, "(MODULE.bazel:7, with paths from the root of the Bazel workspace)"); a project routed before the hub was there leaves the route whole on its next scan, the locks and the workspace file together. Under such a hub a hosted scan never deletes pnpm-workspace.yaml, whose label the hub's `data` may name: where the last of a route leaves a file that a routed run created, the file stays as its `packages` list (`packages:` and `- '.'`), and the entries go as elsewhere. Where the hub also hides pnpm-workspace.yaml from a pnpm 11 (`redirect_pnpm_bazel_workspace_hidden`), that answer comes first, while the files are read, and the root lock is not part of the run: nothing in it is pinned or routed, the members' own locks of a workspace with `sharedWorkspaceLockfile: false` are pinned on `trustLockfile`, and a route an earlier run set up is left exactly as it is, in the workspace file and in every lock, because the root lock records the same overrides and is not written. The workspace file is then byte for byte the one it was: the registries still verify the routed releases, so no `trustLockfile: true` is added for them (it would switch the verification off for every entry). Only a release this run pins in the plain shape beside them, in a member's lock, brings the key. A hosted scan takes no unused entry out there either, and what it does to the files does not turn on what it was granted: with a patch for a package of the lock, with none, and with nothing crawled, it leaves the lock and the workspace file as they are and reports `redirect_pnpm_bazel_workspace_hidden` (a run with no npm patch reports it only for a project that holds something of a route; any other project it leaves without a word, as before). The commands that settle a route from the lockfiles alone pin nothing and work as without Bazel: `repair`, `scan --prune` with no mode, `rollback` and `remove`. **They read no Bazel file**, on this route as for every other hosted pin. So under a hub whose `data` lists a pnpm-workspace.yaml that a routed run created, they still delete that file with the last of the route (as `rollback` deletes a `trustLockfile` file hosted mode created), and the build is then handed a missing file. A hosted scan says so before it comes to that (`redirect_pnpm_bazel_workspace_hidden` asks for a comment line in such a file) and never deletes the file itself. **In memory**, "certain" is certain of the files the engine was handed: the Bazel files at the project's own root (`MODULE.bazel`, the `*.MODULE.bazel` files it can include and the `WORKSPACE` files, beside a `pnpm-lock.yaml` or a `pnpm-workspace.yaml`). A Bazel root above the project is not seen there, for the route as for the pin, so a project in a directory of a Bazel workspace is routed in memory where a checkout is not. A pnpm-workspace.yaml that holds nothing but a route and that a hub lists is one of the files `redirect_pnpm_bazel_workspace_hidden` asks for a comment line in: the scan that leaves the route would otherwise leave a file that `rollback` removes. +**In a Bazel workspace.** The lock reader of rules_js takes a routed lock, and so does the pnpm a hub runs with `update_pnpm_lock` where it sees pnpm-workspace.yaml and is 11.20 or later. Built on Bazel 9.3.2, 8.8.2 and 7.7.2 with rules_js 3.6.0 (macOS): a hub without `update_pnpm_lock`, and a hub with `update_pnpm_lock = True`, the file in `data` and pnpm 11.20.0, 11.28.10 or 12.17.0, stated by `pnpm_version`, by `pnpm_version_from` or by a `use_pnpm` label. Each build holds the patched bytes, that pnpm writes the lock back as it is, a second build changes no file, and `rollback` brings the upstream build back; the Bazel legs build the first shape and the second with pnpm 11.28.10. A lock that such a hub reads is routed exactly as without Bazel, the files byte for byte and nothing said of the hub; a pnpm-workspace.yaml in the `data` of the second shape that says `trustLockfile:` with another value than `true`, or that a line cannot be added to, is the exception, where `redirect_pnpm_bazel_workspace_hidden` comes first as before. What keeps a hub off the route is what else its call says, and the pnpm it runs. A routed lock holds the patched release under another version (`socket-:`), so a `patches` entry of the hub that is keyed by the package's name and version names no package of it and rules_js fails the build (``Patch file key … does not match any npm packages``, built on the three releases), and with `npm_package_lock`, `yarn_lock` or `preupdate` a pnpm writes the lock anew, which no build was run for: only a call of the attributes that were built is routed. As for the pnpm: without the workspace file in `data` it rejects a routed lock (`ERR_PNPM_MISSING_NAMED_REGISTRY`, built with pnpm 11.28.10 on the three releases), and with the file a pnpm below 11.20 builds the routed lock only until it resolves again (after a `package.json` asks for another package, pnpm 11.19.0 puts the upstream release back and pnpm 10.34.9 fails the build with `ERR_PNPM_SPEC_NOT_SUPPORTED_BY_ANY_RESOLVER`; built on Bazel 9.3.2). A lock that a hub reads in any other shape is pinned as on a patch service that offers no registry, the files byte for byte, and the warning names the call and what kept it off the route ("… because a Bazel hub reads the pnpm lock (MODULE.bazel:7), and the pnpm it runs for `update_pnpm_lock` is not stated as 11.20 or later (pnpm 11.19.0): a lock that a hub reads is routed only where the call of the hub passes nothing but `name`, `pnpm_lock`, `data`, `update_pnpm_lock` and `use_pnpm`, and either leaves `update_pnpm_lock` off, or lists pnpm-workspace.yaml in its `data` and states a pnpm of 11.20 or later …"; for a project below the Bazel root, "(MODULE.bazel:7, with paths from the root of the Bazel workspace)"). The clause after "and" is one of: "its `pnpm_lock` is not written out in a plain string", "the lock it reads is a workspace member's own", "the project is not at the root of the Bazel workspace", "the project has workspace members with pnpm locks of their own, a layout that no routed lock was built with" (the route records its overrides in every lock of the project, and the pnpm of a hub resolves beside the one lock its call names), "its `` is an attribute that no routed lock was built with", "it passes arguments that are not written out", "its `update_pnpm_lock` is not written out as `True` or `False`", "its `data` is not written out as a list of strings that holds `//:pnpm-workspace.yaml`", "the pnpm it runs for `update_pnpm_lock` is not stated as 11.20 or later" (with the release in parentheses where one is stated, and ", which is not a release of three numbers" after a prerelease or a shorter number), "the pnpm it runs for `update_pnpm_lock` is not shown to be the one the root module states (pnpm ): its repository is not taken from the pnpm extension as every module uses it, or that extension has an isolated use or an `inject_repo`", and the same up to the colon with "a use of the pnpm extension with `dev_dependency` states a release for it, and Bazel drops such a use under `--ignore_dev_dependency`" (the hub then runs the pnpm that rules_js picks, which builds a routed lock only until it resolves again; the pin builds with either pnpm). A project that was routed and whose hub is no longer in one of the two shapes leaves the route whole on its next scan, the locks and the workspace file together; one that was pinned and whose hub now is in one moves to the route, and a `trustLockfile: true` an earlier run wrote goes as it does without Bazel. Under such a hub a hosted scan never deletes pnpm-workspace.yaml, whose label the hub's `data` may name: where the last of a route leaves a file that a routed run created, the file stays as its `packages` list (`packages:` and `- '.'`), and the entries go as elsewhere. Where the hub also hides pnpm-workspace.yaml from a pnpm 11 (`redirect_pnpm_bazel_workspace_hidden`), that answer comes first, while the files are read, and the root lock is not part of the run: nothing in it is pinned or routed, the members' own locks of a workspace with `sharedWorkspaceLockfile: false` are pinned on `trustLockfile`, and a route an earlier run set up is left exactly as it is, in the workspace file and in every lock, because the root lock records the same overrides and is not written. The workspace file is then byte for byte the one it was: the registries still verify the routed releases, so no `trustLockfile: true` is added for them (it would switch the verification off for every entry). Only a release this run pins in the plain shape beside them, in a member's lock, brings the key. A hosted scan takes no unused entry out there either, and what it does to the files does not turn on what it was granted: with a patch for a package of the lock, with none, and with nothing crawled, it leaves the lock and the workspace file as they are and reports `redirect_pnpm_bazel_workspace_hidden` (a run with no npm patch reports it only for a project that holds something of a route; any other project it leaves without a word, as before). The commands that settle a route from the lockfiles alone pin nothing and work as without Bazel: `repair`, `scan --prune` with no mode, `rollback` and `remove`. **They read no Bazel file**, on this route as for every other hosted pin. So under a hub whose `data` lists a pnpm-workspace.yaml that a routed run created, they still delete that file with the last of the route (as `rollback` deletes a `trustLockfile` file hosted mode created), and the build is then handed a missing file. A hosted scan says so before it comes to that (`redirect_pnpm_bazel_workspace_hidden` asks for a comment line in such a file) and never deletes the file itself. **In memory**, "certain" is certain of the files the engine was handed: the Bazel files at the project's own root (`MODULE.bazel`, the `*.MODULE.bazel` files it can include and the `WORKSPACE` files, beside a `pnpm-lock.yaml` or a `pnpm-workspace.yaml`). A Bazel root above the project is not seen there, for the route as for the pin, so a project in a directory of a Bazel workspace is routed in memory where a checkout is not. A pnpm-workspace.yaml that holds nothing but a route and that a hub lists is one of the files `redirect_pnpm_bazel_workspace_hidden` asks for a comment line in: the scan that leaves the route would otherwise leave a file that `rollback` removes. -**What the warning says.** A patch service that gives no pin of the project a registry address offers no route, and the run and its warning are exactly what they were. As soon as one pin has an address, a run that still ends on `trustLockfile` says why, in one sentence of the `redirect_pnpm_trust_lockfile` warning ("Per-package registry verification was not set up because …"): the hosted packages the patch service gave no address for, by `name@version` (the first five, then "and N more"), since one of them puts the whole lock on `trustLockfile`; the hosted packages pinned on a patch mirror, named the same way; pins that do not prove pnpm 11.20; a Bazel hub that reads the lock (9), by the file and line of its call, or what of the Bazel workspace was not read so that one may ("… because a Bazel hub may read the pnpm lock (WORKSPACE:3: it brings in rules_js, and a hub that this file defines is not read) …"); and whichever of (4) to (7) applied, naming the file, the override or the lock entry. With no pnpm pin at all (and not under `--no-trust-lockfile-config`) the sentence is instead that pinning pnpm 11.20 or later (for example with package.json `packageManager`) and re-running the scan switches the project to per-package registry verification. On the route the warning's detail says the file declares the patch server's registry of each patched package (the `socket-` entries, one per patch) and routes each patched release to its own, to commit it alongside the lock, and keeps the rebuild-the-lockfile and clean-reinstall cautions; it carries no whole-lock tradeoff note. **A newer release in range (a note, never a refusal).** An override keyed `@` applies to every dependency whose range admits that version, and a lock records what a transitive dependent resolved, not the range it asked through. So when a governing lock also holds a newer release of a routed package within the routed release's caret range (the same major, or the same minor below 1.0), on the default registry, the detail ends with a note that names the package and both versions: "pnpm-lock.yaml also locks `` at ``, which a range that admits `` may admit too: a package that depends on `` through such a range moves to the patched `@` the next time pnpm resolves (`pnpm add`, `update`, `dedupe`), …". The lock is written as it is (pnpm installs it frozen, and re-locks it unchanged, until a command resolves the project again: see the [pnpm compatibility notes](../../docs/testing/pnpm-compatibility.md) for what each command does). The note is reported on every run that leaves the project routed, a re-run that changes nothing included (in human mode after the one-line reminder), and changes neither the route nor the exit code. +**What the warning says.** A patch service that gives no pin of the project a registry address offers no route, and the run and its warning are exactly what they were. As soon as one pin has an address, a run that still ends on `trustLockfile` says why, in one sentence of the `redirect_pnpm_trust_lockfile` warning ("Per-package registry verification was not set up because …"): the hosted packages the patch service gave no address for, by `name@version` (the first five, then "and N more"), since one of them puts the whole lock on `trustLockfile`; the hosted packages pinned on a patch mirror, named the same way; pins that do not prove pnpm 11.20; a Bazel hub that reads the lock in a shape that is not routed (9), by the file and line of its call and what the call says, or what of the Bazel workspace was not read so that one may ("… because a Bazel hub may read the pnpm lock (WORKSPACE:3: it brings in rules_js, and a hub that this file defines is not read), in a shape that was not read: a lock that a hub reads is routed only where …"); and whichever of (4) to (7) applied, naming the file, the override or the lock entry. With no pnpm pin at all (and not under `--no-trust-lockfile-config`) the sentence is instead that pinning pnpm 11.20 or later (for example with package.json `packageManager`) and re-running the scan switches the project to per-package registry verification. On the route the warning's detail says the file declares the patch server's registry of each patched package (the `socket-` entries, one per patch) and routes each patched release to its own, to commit it alongside the lock, and keeps the rebuild-the-lockfile and clean-reinstall cautions; it carries no whole-lock tradeoff note. **A newer release in range (a note, never a refusal).** An override keyed `@` applies to every dependency whose range admits that version, and a lock records what a transitive dependent resolved, not the range it asked through. So when a governing lock also holds a newer release of a routed package within the routed release's caret range (the same major, or the same minor below 1.0), on the default registry, the detail ends with a note that names the package and both versions: "pnpm-lock.yaml also locks `` at ``, which a range that admits `` may admit too: a package that depends on `` through such a range moves to the patched `@` the next time pnpm resolves (`pnpm add`, `update`, `dedupe`), …". The lock is written as it is (pnpm installs it frozen, and re-locks it unchanged, until a command resolves the project again: see the [pnpm compatibility notes](../../docs/testing/pnpm-compatibility.md) for what each command does). The note is reported on every run that leaves the project routed, a re-run that changes nothing included (in human mode after the one-line reminder), and changes neither the route nor the exit code. **The file edit.** The file is created with the root-only `packages:` scaffold; a file with no keys gets the scaffold and the two maps; otherwise each map is appended after the last non-empty line (before a `...` end marker), or its missing entries are inserted after the map's last entry at its own indent. These are line splices: every other byte and the file's line endings are kept. Each registry and each override is one line. A file the run creates lists the registries by name and the overrides by key; an entry added to a map that already has entries goes after the map's last entry, so a file that grew over several runs lists the patches in the order they arrived (pnpm reads either, and the lock's `overrides:` record follows the file's order). An entry of the CLI's already as wanted is a byte-stable no-op (so is the whole re-run). `trustLockfile` plays no part here: an explicit non-true value or a `pnpm_config_trust_lockfile` variable blocks nothing. A `trustLockfile: true` an earlier run wrote is removed in the same run (a `redirect_pnpm_workspace_trust` edit with action `removed`) when the file's bytes prove that run wrote it: the file is exactly what the trust write creates (its `packages:` scaffold stays), or a keyless document plus exactly the lines that write splices into one. Any other `trustLockfile: true` is left untouched (v5 keeps no record of who wrote a line) and the warning says the hosted patches no longer need it. The `registries: {: {prefix: …}}` spelling pnpm 12 also reads is never written: pnpm 10 fails on it. The registry's version document is dated by the upstream release of the version (undated when unknown), so pnpm's default `minimumReleaseAge` does not hold back a freshly published patch. @@ -2554,7 +2554,7 @@ command's integration tests check its output. | `patch_fetch_failed` (eject) | `failed` | vendor eject (v5.0): a hosted pin's patch record could not be fetched from `…/patches/view/`; the whole eject is refused (`eject_refused`), nothing touched, exit 1. | | `redirect_pnpm_lockfile_elsewhere` / `redirect_workspace_lockfile_elsewhere` / `cargo_manifest_not_workspace_root` (hosted) | top-level `error.code` (`status: "error"`) | scan / get `--mode hosted` (v5.0): the project directory is a workspace member whose lock lives in another directory, so the rewriters, which read only the project directory, would pin nothing, or would pin a lock of its own that its package manager never reads (`redirect_workspace_lockfile_elsewhere`: a `pnpm-lock.yaml` in a member a `pnpm-workspace.yaml` lists, which pnpm ignores for the workspace's shared lock unless the workspace sets `sharedWorkspaceLockfile: false`, checked with pnpm 10.34 and 11.27; a yarn 1 `yarn.lock` in a `package.json` workspace member, which yarn 1.22 never reads; the message names the workspace root to run from) (pnpm: no npm-family lock here, and the nearest ancestor `pnpm-workspace.yaml` or the project's `lockfile-dir` (`.npmrc`) / `lockfileDir` (`pnpm-workspace.yaml`) puts `pnpm-lock.yaml` elsewhere; npm / yarn / Bun, `redirect_workspace_lockfile_elsewhere`: no npm-family lock here, and the nearest ancestor `package.json` whose `workspaces` (array, or the object form's `packages`) matches the directory holds `package-lock.json`, `npm-shrinkwrap.json`, `yarn.lock`, `bun.lock` or `bun.lockb`; a matching root with none of them that is itself listed by an outer root's `workspaces` hands the check to that root; vlt, same code: the nearest ancestor `vlt.json` whose `workspaces` (a string, an array, or an object of groups) matches the directory holds `vlt-lock.json`, or, as vlt falls back to it when `vlt.json` has no `workspaces` field, the `package.json` `workspaces` root above holds `vlt-lock.json`, and the nearer of a `vlt.json` and a `package.json` root is named; `workspaces` patterns use the glob grammar the package managers share: `*`, `?`, `**`, brace sets and sequences (`{a,b}`, `{1..3}`) and character classes (`[a-c]`, `[!a]`), read the way the root's lock's package manager reads them (#1097): extglobs (`@(a|b)`, `?(…)`, `*(…)`, `+(…)`, `!(…)`) match for npm and yarn but not Bun or vlt; for Bun and vlt, `*`, `?` and `**` never match a directory whose name starts with `.` (`packages/*` does not list `packages/.tools`, #1542, #1631) unless the pattern spells the dot (`packages/.tools`, `packages/.*`), while a `!` pattern still excludes one; yarn berry (picomatch) also reads regex groups (`packages/(a|b)`; a group without `|` only in a pattern fast-glob deems dynamic, or in a `!` pattern), the regex quantifiers `?` / `+` after a group, `+` after a class and `+` inside a group, POSIX classes (`[[:alpha:]]`) and `..` segments in a static pattern or after a static prefix (`packages/a/../b` lists `packages/b`; literal in a `!` pattern); a group alternative holding `/` (`(packages/ui|apps/web)`) is matched across components, and a `?` or `+` quantifying such a group fails closed (the pattern lists every directory, and excludes none as a `!` pattern) (#1490); so does a pattern with extglob or regex groups that is past what socket-patch works out — a brace alternative longer than 4,096 characters or with more than 64 groups, or one whose matching against a directory takes more than about a million steps (an ambiguous group such as `*(a|aa)` repeated dozens of times against a name hundreds of characters long) — while a pattern without groups is read whatever its length, and a brace set is expanded to at most 4,096 alternatives and a megabyte of text; a `!` pattern excludes what earlier patterns matched for npm, Bun 1.3+ (a `bun.lock` with a top-level `configVersion`) and vlt, excludes whatever the order for yarn berry (a `yarn.lock` with `__metadata`, where a leading `!(` is an extglob), and is ignored by yarn classic and older Bun (a `bun.lock` without `configVersion`, or a `bun.lockb` alone without the trailing `cNfGvRsN` config-version extension, its binary twin, #1492); only the root's locks whose package manager lists the directory govern it (and are named), and a lockless root lists it when any of them would; when a pnpm workspace also governs the directory, the nearer root is named and a tie goes to `redirect_pnpm_lockfile_elsewhere`; uv (pypi, #1138), `redirect_workspace_lockfile_elsewhere`: the directory holds a `pyproject.toml`, and the nearest ancestor `pyproject.toml` declaring `[tool.uv.workspace]` lists it in `members` (and not in `exclude`), with no standalone project (`[project]`, no workspace) in between, so uv installs it from that root's `uv.lock` (a `uv.lock`, `poetry.lock`, `pdm.lock`, `Pipfile.lock` or pylock left in the member is never read and does not exempt it); the message says uv workspaces are not patched from their root yet either, and vendored refuses the same layout with `pypi_uv_workspace_unsupported` instead of rewriting a member with Hatch configuration as a lockless Hatch project; a directory whose own locks are all ones its manager never reads inside a workspace member is refused the same way, naming the ignored locks: `package-lock.json` / `npm-shrinkwrap.json` when its `package.json` `workspaces` root holds `package-lock.json` or `npm-shrinkwrap.json` (npm, #1094), `bun.lock` / `bun.lockb` when that root holds `bun.lock` or `bun.lockb` (Bun, #1101), and `vlt-lock.json` in a directory with no `vlt.json` of its own when its vlt workspace root (as above) holds `vlt-lock.json` (vlt, #1134), or, listed or not, when vlt's project root for the directory is another directory holding `vlt-lock.json` (vlt, #1584: the nearest ancestor `vlt.json`, else the outermost directory holding a `package.json` or `node_modules`, the walk ending at a directory holding `.git` and below the home directory, as vlt's own `find("project")` does; the message names that root and says a `vlt.json` in the directory makes it a project of its own); vendored refuses it with `vendor_lockfile_missing`, and `vex` reads the ignored lock as absent, with one `patched_ref_unattributable` warning naming it when it holds Socket references) or rewrite the member as a lockless project (cargo: the vendored workspace-root check). Refused before any takeover or write, `--dry-run` included; the message names the directory to run from; exit 1. Disk runs only (an in-memory project has no ancestors). | | `redirect_pnpm_settings_elsewhere` | top-level `error.code` (`status: "error"`) | scan / get `--mode hosted`: the project directory is a pnpm workspace member (listed by the `packages:` globs of the nearest ancestor `pnpm-workspace.yaml`) with its own v9 `pnpm-lock.yaml` (`sharedWorkspaceLockfile: false`) and no `pnpm-workspace.yaml` of its own, so its pnpm settings come from that ancestor file, which pnpm reads alone (a member's own file is ignored). A directory those globs do not list (no `packages:`, an empty list, a non-matching or `!`-excluded path) is a standalone project on pnpm 11.28+/12 that reads only its own file: it is pinned and gets its own `pnpm-workspace.yaml` like any single project. A root file that does not parse, or whose patterns use braces, classes or extglobs, counts as listing the project. When that file neither carries `trustLockfile: true` nor explicitly sets another value, the trust auto-config has nowhere to go: refused before any takeover or write, `--dry-run` included; the message names the root file to add `trustLockfile: true` to (or `--no-trust-lockfile-config` pins without it); exit 1. Once the root file trusts the lock (or opts out), the member is pinned and no nested `pnpm-workspace.yaml` is created; the `redirect_pnpm_trust_lockfile` warning names the root file. In memory, a member whose lock is demoted into its workspace root (#492) is never refused; one whose lock is not (the workspace root's files do not confirm it pins or ignores that lock, or socket.yml leaves the root out) is refused with this code as its project error, nothing written for it, whenever its lock is v9, the trust auto-config is on and that file may list it (listed, unreadable, or not readable as globs), whatever it says about `trustLockfile`. | -| `redirect_pnpm_bazel_workspace_hidden` | `warnings[]` (warning, one per run) | scan / get `--mode hosted`, dry and wet, and the in-memory engine: the project is in a Bazel workspace where one `npm.npm_translate_lock` call of aspect_rules_js names its `pnpm-lock.yaml` in a plain string, keeps it up to date (`update_pnpm_lock` is `True` or not written out as `True` or `False`), does not list the `pnpm-workspace.yaml` beside the lock in a `data` that is a list of strings (or lists a file that would hold only what hosted mode writes, or one hosted mode does not write `trustLockfile: true` to), and runs a pnpm that the workspace states as 11 or later or in a way that is no version, or states none under a release of aspect_rules_js whose own choice is not known (any but 1.x to 3.x, 4.0.0-alpha.0 and 4.0.0-alpha.1, by `bazel_dep`, a `single_version_override` and `MODULE.bazel.lock`) (the `pnpm_version`, or the `packageManager` of the `pnpm_version_from` file, of the `pnpm.pnpm` tag whose `name` is the repository of the call's `use_pnpm`, `pnpm` without one; a `use_pnpm` whose repository no `use_repo` takes by position under that name, or that no such tag makes unless it is `pnpm`, is no version). The pnpm that Bazel runs would not read the `trustLockfile: true` hosted mode writes, would reject the pinned lock (`ERR_PNPM_TARBALL_URL_MISMATCH`), and `bazel build` would fail. Every root pnpm lock is left untouched and no npm pin is confirmed from it; the members' own locks of a workspace with `sharedWorkspaceLockfile: false` are pinned as without Bazel (in the root lock each package is a `skipped` event: `redirect_unconfirmed`, or `redirect_unattributable` where another npm lock of the project names it, which is then not pinned either), exit 0, `status: "success"`. The detail starts with the file and the line of the call, named as the file writes it (`MODULE.bazel:7: this `npm.npm_translate_lock` …`; `MODULE.bazel:7, with paths from the root of the Bazel workspace: …` for a project below that root) and ends with what to do: `; pnpm-lock.yaml was not rewritten — list `//:pnpm-workspace.yaml` in the `data` of that call and re-run`, with the label of the file beside the lock. Before the label, or alone where the call lists the file: where the file would hold only what hosted mode writes (none, an empty file, the root-only `packages` scaffold, a file of an earlier hosted run), `put a comment line in pnpm-workspace.yaml (create the file where there is none: …)`, because `rollback` removes such a file and the call would name a missing one; where the file says `trustLockfile:` with another value than `true`, or is YAML a line cannot be added to, to set `trustLockfile: true` in it. Where `data` is not written out as a list of strings, the last step is to write it out as one that holds the label. A hub without `update_pnpm_lock`, one that runs pnpm 10 or states no release under a release of the ruleset whose choice is known, one that lists a file of the user's own that takes the setting, a project whose lock no call names and a project in no Bazel workspace are not affected. See docs/ecosystems.md, "Bazel workspaces: npm". | +| `redirect_pnpm_bazel_workspace_hidden` | `warnings[]` (warning, one per run) | scan / get `--mode hosted`, dry and wet, and the in-memory engine: the project is in a Bazel workspace where one `npm.npm_translate_lock` call of aspect_rules_js names its `pnpm-lock.yaml` in a plain string, keeps it up to date (`update_pnpm_lock` is `True` or not written out as `True` or `False`), does not list the `pnpm-workspace.yaml` beside the lock in a `data` that is a list of strings (or lists a file that would hold only what hosted mode writes, or one hosted mode does not write `trustLockfile: true` to: a file that sets it to another value, YAML a line cannot be added to, and under `--no-trust-lockfile-config` any file that does not hold it already), and runs a pnpm that the workspace states as 11 or later or in a way that is no version, or states none under a release of aspect_rules_js whose own choice is not known (any but 1.x to 3.x, 4.0.0-alpha.0 and 4.0.0-alpha.1, by `bazel_dep`, a `single_version_override` and `MODULE.bazel.lock`) (the `pnpm_version`, or the `packageManager` of the `pnpm_version_from` file, of the `pnpm.pnpm` tag whose `name` is the repository of the call's `use_pnpm`, `pnpm` without one; a `use_pnpm` whose repository no `use_repo` takes by position under that name, or that no such tag makes unless it is `pnpm`, is no version). The pnpm that Bazel runs would not read the `trustLockfile: true` hosted mode writes, would reject the pinned lock (`ERR_PNPM_TARBALL_URL_MISMATCH`), and `bazel build` would fail. Every root pnpm lock is left untouched and no npm pin is confirmed from it; the members' own locks of a workspace with `sharedWorkspaceLockfile: false` are pinned as without Bazel (in the root lock each package is a `skipped` event: `redirect_unconfirmed`, or `redirect_unattributable` where another npm lock of the project names it, which is then not pinned either), exit 0, `status: "success"`. The detail starts with the file and the line of the call, named as the file writes it (`MODULE.bazel:7: this `npm.npm_translate_lock` …`; `MODULE.bazel:7, with paths from the root of the Bazel workspace: …` for a project below that root) and ends with what to do: `; pnpm-lock.yaml was not rewritten — list `//:pnpm-workspace.yaml` in the `data` of that call and re-run`, with the label of the file beside the lock. Before the label, or alone where the call lists the file: where the file would hold only what hosted mode writes (none, an empty file, the root-only `packages` scaffold, a file of an earlier hosted run), `put a comment line in pnpm-workspace.yaml (create the file where there is none: …)`, because `rollback` removes such a file and the call would name a missing one; where the file says `trustLockfile:` with another value than `true`, `set `trustLockfile: true` in pnpm-workspace.yaml or take the line out (it says `trustLockfile: false`, which hosted mode leaves as it is)`; where it is YAML a line cannot be added to, to write the setting there yourself; where the run is under `--no-trust-lockfile-config` (in memory: `trustLockfileConfig` off) and the file lacks the setting, `let hosted mode write to pnpm-workspace.yaml (this run was told not to, which is `--no-trust-lockfile-config` on the command line, so it writes neither the setting nor the registries that take its place) or set `trustLockfile: true` there yourself`: without this the scan would exit 0 with a pin that the pnpm of the build rejects. A scan under the option that crawls nothing adds no pin and is not held back by this case: it takes out what a route left and no lock uses, in the lock and in the file together, as without Bazel. Not where such a run ends routed: in a project an earlier run routed, whose file holds the route of every pin, it has nothing to write to the file and needs no setting, and it is the run of the same project without Bazel (the package `applied`, in a dry run `verified`). Where `data` is not written out as a list of strings, the last step is to write it out as one that holds the label. A hub without `update_pnpm_lock`, one that runs pnpm 10 or states no release under a release of the ruleset whose choice is known, one that lists a file of the user's own that takes the setting, a project whose lock no call names and a project in no Bazel workspace are not affected. See docs/ecosystems.md, "Bazel workspaces: npm". | | `eject_refused` | top-level `error.code` (`status: "error"`) | vendor eject (v5.0): a record fetch failed or a pin's upstream restore was refused while planning; nothing was changed, exit 1. | | `eject_planned` | `applied` (reason) | vendor eject `--dry-run` (v5.0): the pin would be restored upstream and vendored; nothing written. | | `eject_rolled_back` | warning; `skipped` event | vendor eject (v5.0): a package failed after the restore began; every touched file was put back from the pre-eject snapshot, so the project is still hosted; `partialFailure`, exit 1. Also the `errorCode` of the `skipped` event re-reporting each package the eject had vendored before it was rolled back (not counted in `summary.applied`). | diff --git a/crates/socket-patch-cli/tests/e2e_bazel_build/cargo.rs b/crates/socket-patch-cli/tests/e2e_bazel_build/cargo.rs index d77fb6975..a8f49e0a5 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/cargo.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/cargo.rs @@ -172,10 +172,12 @@ //! the same. //! - Bazel would read that file as a package of the user's workspace. The //! crate has a dependency ([`DEP`]), so the file names a repository of -//! the hub, which the main repository does not see, and the commands -//! that analyse every target fail on it: `bazel cquery //...` and -//! `bazel query 'deps(//...)'` ([`analyses`]). The line that the scan -//! wrote into `.bazelignore` keeps the copies out of Bazel's packages: +//! the hub, which the main repository does not see, as it does not see +//! `platforms`, which the file names too. The commands that analyse +//! every target fail on the first of the two that Bazel meets: +//! `bazel cquery //...` and `bazel query 'deps(//...)'` ([`analyses`]). +//! The line that the scan wrote into `.bazelignore` keeps the copies out +//! of Bazel's packages: //! `//...` is the user's own target ([`every_target`]), both commands //! pass, and the build is the patched one, because the hub reads the //! copy by its path, not as a package. A user who comments the line out @@ -872,15 +874,42 @@ fn every_target(cell: &Cell) -> Vec { targets } +/// Whether `stderr` says that the main repository does not see a +/// repository that the build file in the copy names: one of the hub, or +/// `platforms`. Bazel names the first one it meets, and which one that is +/// differs from run to run. The same words about another repository's view +/// are another failure. +fn unseen(stderr: &str) -> bool { + (stderr.split("No repository visible as '@").skip(1)) + .filter_map(|rest| rest.split_once("' from main repository")) + .any(|(repo, _)| { + !repo.contains('\'') && (repo == "platforms" || repo.starts_with("crates__")) + }) +} + +/// [`unseen`] takes the two messages Bazel was seen to print, and neither +/// another repository's name nor another repository's view. +#[test] +fn an_unseen_repository_is_one_the_copy_names_and_the_main_repository_misses() { + let said = |repo: &str, from: &str| { + format!("ERROR: no such package: No repository visible as '@{repo}' from {from}\n") + }; + assert!(unseen(&said("platforms", "main repository"))); + assert!(unseen(&said("crates__dep-1.0.0", "main repository"))); + assert!(!unseen(&said("rules_cc", "main repository"))); + assert!(!unseen(&said("platforms", "repository '@@rules_rust+'"))); + assert!(!unseen("Loading: 0 packages loaded\n")); +} + /// Whether the commands that analyse every target of the checkout of /// `cell` pass: `bazel cquery //...` and `bazel query 'deps(//...)'`, which -/// agree. One that fails has met a repository of the hub, which the main -/// repository does not see. +/// agree. One that fails has met a repository that the build file in the +/// copy names and the main repository does not see ([`unseen`]). fn analyses(cell: &Cell) -> bool { let runs = [("cquery", "//..."), ("query", "deps(//...)")]; let runs = runs.map(|(command, targets)| cell.bazel(command, &[targets])); for run in &runs { - let unseen = run.stderr().contains("No repository visible as '@crates__"); + let unseen = unseen(&run.stderr()); assert_ne!(run.ok(), unseen, "{}: {}", cell.test, run.dump()); } assert_eq!(runs[0].ok(), runs[1].ok(), "{}", cell.test); @@ -1194,8 +1223,9 @@ fn vendored_from_cargo_with_config() { // package: `//...` is the consumer alone, and the commands that analyse // every target pass. A user who comments the line out has the package // back, where the ruleset writes the build file: `//...` names targets - // there, those commands fail on the repository of the dependency, and - // the file Bazel now reads is a change of the copy again. + // there, those commands fail on a repository that the file names and + // the main repository does not see, and the file Bazel now reads is a + // change of the copy again. assert_eq!(every_target(&cell), [CONSUMER], "{test}"); assert!(analyses(&cell), "{test}: under the line of the scan"); cell.write(".bazelignore", DECLINED); diff --git a/crates/socket-patch-cli/tests/e2e_bazel_build/npm.rs b/crates/socket-patch-cli/tests/e2e_bazel_build/npm.rs index 94c2855cc..4f2520914 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/npm.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/npm.rs @@ -10,22 +10,25 @@ //! pnpm runs, no `node_modules` of the checkout is read, and the machine //! needs no Node: the ruleset downloads the one that runs the consumer. //! -//! The hosted and the vendored flow, one test each, on the Bazel the run is -//! given ([`FIXTURE`] says which ruleset goes with its release), each in a -//! fresh output base: +//! The hosted and the vendored flow, on the Bazel the run is given +//! ([`FIXTURE`] says which ruleset goes with its release), each in a fresh +//! output base. The hosted flow is two tests: the lock routed through the +//! patch's registry, as below, and the lock pinned beside `trustLockfile: +//! true` where the patch service offers no registry ([`hosted_flow`]): //! //! - (a) `bazel build` and `bazel run //:consumer` print the unpatched //! marker, and Bazel fetched the upstream tarball from the stand-in //! registry. //! - (b) The one command of the mode writes its files and no other. -//! `scan --mode hosted --yes` gives the package's entry of -//! `pnpm-lock.yaml` the integrity of the patched tarball and its URL on -//! the patch host, and creates `pnpm-workspace.yaml` with the -//! `trustLockfile: true` that pnpm 11 and later ask for. The patch -//! service of this flow also offers the patch's own registry, and the -//! checkout proves pnpm 12, for which hosted mode would route the lock -//! through that registry: beside the hub, which reads the lock, it -//! writes this pin all the same, and the build of it is what (c) holds. +//! The patch service of the hosted flow offers the patch's own +//! registry and the checkout proves pnpm 12, so `scan --mode hosted +//! --yes` routes the lock through that registry, as it does without +//! Bazel: it creates `pnpm-workspace.yaml` with the registry and the +//! override that sends the package's one version there, and gives +//! `pnpm-lock.yaml` the shape pnpm writes for that, the package under +//! the registry's key with the integrity of the patched tarball and its +//! URL on the patch host. The hub runs no pnpm, and the lock reader of +//! rules_js builds such a lock, which is what (c) holds. //! `scan --mode vendored --yes` downloads the patched tarball to //! `.socket/vendor/npm//`, records it in the ledger //! `.socket/vendor/state.json`, and points the lock's entry and a pnpm @@ -88,6 +91,25 @@ //! and that every hub which hides nothing leaves the run as it is without //! Bazel. //! +//! Three more flows are that hub with the user's `pnpm-workspace.yaml` in +//! its `data` and pnpm 11 stated in each way socket-patch reads as written +//! out ([`Stated`]), for a patch whose registry the patch service offers +//! ([`keeps_the_lock_up_to_date_where_a_registry_is_offered`]): hosted mode +//! routes the lock through that registry, the pnpm that Bazel runs reads +//! the registry in the file the hub lists and leaves the lock as it is, +//! and the build is the patched one. Another flow is that hub and a scan +//! that is told not to write to that file +//! ([`hosted_update_pnpm_lock_without_the_trust_setting`]): the pnpm that +//! Bazel runs would reject the pin, so the scan writes nothing and says +//! what to do, and the build stays the unpatched one that passes; once the +//! lock is routed, the same scan needs to write nothing and leaves the +//! patched build. A hub in any other shape keeps the pin with +//! `trustLockfile: true`, which the pinned hosted flow, the agent flow and +//! the two flows above build. The last flow is one such shape, a hub whose +//! call says more than the calls a routed lock was built with +//! ([`hosted_npm_translate_lock_with_patches_of_the_hub`]): its `patches` +//! entry names the package by a version that a routed lock does not have. +//! //! A marker is read from what Bazel built. Bazel's downloader keeps every //! file it fetches in the repository cache, under its checksum, and hands it //! out again without a request; the tests of a leg share that cache, and CI @@ -340,8 +362,10 @@ fn grant_recorded(standin: &StandIn, patch: &Patched, served: &[u8], record: &Va /// [`grant_recorded`]. With `registry`, the patch service also offers the /// patch's own registry: the directory its tarball is served from, as its /// address. Hosted mode routes a pnpm lock through that registry in a -/// project that proves pnpm 11.20 or later ([`proves_pnpm_12`]), and not -/// where a rules_js hub reads the lock, which is what these tests hold. +/// project that proves pnpm 11.20 or later ([`proves_pnpm_12`]), also +/// where a rules_js hub reads the lock in a shape whose build takes a +/// routed lock, and not under any other hub, which is what these tests +/// hold. fn grant_as(standin: &StandIn, patch: &Patched, served: &[u8], record: &Value, registry: bool) { let url = format!("{}{}", standin.origin(), patch.route); let mut reference = json!({ @@ -425,8 +449,78 @@ fn proves_pnpm_12(cell: &Cell) { /// What the `redirect_pnpm_trust_lockfile` warning of a hosted scan says /// where the patch service offers a registry and the fixture's hub reads -/// the lock: the route is not taken, and the hub's call is why. -const HUB_READS_THE_LOCK: &str = "a Bazel hub reads the pnpm lock (MODULE.bazel:7)"; +/// the lock in a shape that is not routed: the hub's call is why, and +/// what the call says is named after it. +const HUB_READS_THE_LOCK: &str = "a Bazel hub reads the pnpm lock (MODULE.bazel:7), and "; + +/// The registry of `patch` on `standin`, as the patch service has it: the +/// one document of the package, beside the tarball, with the patched +/// tarball as its one version. The pnpm of a hub asks for it when it holds +/// a routed lock to the registries of `pnpm-workspace.yaml`. Gives the +/// route of the document. +fn serves_registry(standin: &StandIn, patch: &Patched) -> String { + let directory = patch.route.strip_suffix(TGZ).expect("a tarball"); + let route = format!("{directory}{}", NAME.replace('/', "%2F")); + let document = json!({ + "name": NAME, + "dist-tags": { "latest": VERSION }, + "versions": { VERSION: { + "name": NAME, + "version": VERSION, + "dist": { + "tarball": format!("{}{}", standin.origin(), patch.route), + "integrity": integrity(&patch.package.tarball), + }, + }}, + }); + let document = serde_json::to_vec(&document).expect("a JSON document"); + standin.serve(5, &route, &document); + route +} + +/// The files `routed` of a checkout whose lock hosted mode routed through +/// the registry of `patch` on the patch host at `origin`. +/// `pnpm-workspace.yaml` holds `own`, the root as its one package, the +/// registry under the name of the patch and the override that sends the +/// package's one version there, and no `trustLockfile`. The lock has the +/// shape pnpm writes for that: it records the override and keys the +/// package by the registry, with the patched tarball's sum and URL. +fn is_routed(test: &str, routed: &Tree, origin: &str, patch: &Patched, own: &str) { + let registry = format!("socket-{}", &patch.uuid[..8]); + let directory = patch.route.strip_suffix(TGZ).expect("a tarball"); + let workspace = format!( + "{own}packages:\n - '.'\nnamedRegistries:\n {registry}: {origin}{directory}\n\ + overrides:\n '{NAME}@{VERSION}': '{registry}:{VERSION}'\n" + ); + assert_eq!(text(routed, "pnpm-workspace.yaml"), workspace, "{test}"); + let lock = text(routed, LOCK); + let entry = format!( + " '{NAME}@{registry}:{VERSION}':\n resolution: {{integrity: {}, tarball: \ + {origin}{}}}\n", + integrity(&patch.package.tarball), + patch.route + ); + let record = format!("overrides:\n '{NAME}@{VERSION}': {registry}:{VERSION}\n"); + let shaped = lock.contains(&entry) && lock.contains(&record); + assert!(shaped, "{test}: {LOCK}:\n{lock}"); +} + +/// The files `pinned` of a checkout whose lock hosted mode pinned to +/// `patch` on the patch host at `origin` without a registry: the entry of +/// the package names the patched tarball, by its sum and by its URL, under +/// the key it had, and `pnpm-workspace.yaml` holds `own`, the root as its +/// one package and `trustLockfile: true`. +fn is_pinned(test: &str, pinned: &Tree, origin: &str, patch: &Patched, own: &str) { + let lock = text(pinned, LOCK); + let entry = format!( + " '{NAME}@{VERSION}':\n resolution: {{integrity: {}, tarball: {origin}{}}}\n", + integrity(&patch.package.tarball), + patch.route + ); + assert!(lock.contains(&entry), "{test}: {LOCK}:\n{lock}"); + let workspace = format!("{own}{TRUSTING_WORKSPACE}"); + assert_eq!(text(pinned, "pnpm-workspace.yaml"), workspace, "{test}"); +} /// The directory of the package in pnpm's virtual store, from the checkout. fn store() -> String { @@ -618,13 +712,30 @@ fn refuses(twin: &Cell, other: &StandIn, found: &[u8], pinned: &[u8]) -> (Run, S (build, refusal) } -/// The hosted flow of the module docs. Its second scan, beside the links of -/// the Bazel that built in the checkout, reports the patch applied again, -/// and `vex` writes a document that attests the package. +/// The hosted flow of the module docs, routed: the patch service offers +/// the patch's registry. #[test] #[ignore = "real Bazel; run with --ignored"] fn hosted_npm_translate_lock() { - let test = "npm::hosted_npm_translate_lock"; + hosted_flow("npm::hosted_npm_translate_lock", true); +} + +/// The hosted flow of the module docs on the pin with `trustLockfile: +/// true`, which is what a project gets where the patch service offers no +/// registry, where its own pnpm pins do not prove pnpm 11.20, and under +/// every hub that is not routed. +#[test] +#[ignore = "real Bazel; run with --ignored"] +fn hosted_npm_translate_lock_on_the_trust_pin() { + hosted_flow("npm::hosted_npm_translate_lock_on_the_trust_pin", false); +} + +/// The hosted flow of the module docs, for a patch whose registry the +/// patch service offers (`offered`: the lock is routed) or does not (it is +/// pinned beside `trustLockfile: true`). Its second scan, beside the links +/// of the Bazel that built in the checkout, reports the patch applied +/// again, and `vex` writes a document that attests the package. +fn hosted_flow(test: &str, offered: bool) { let started = Instant::now(); let Some((cell, standin, upstream)) = open(test) else { return; @@ -632,20 +743,23 @@ fn hosted_npm_translate_lock() { let release = cell.release().to_string(); let origin = standin.origin(); let patch = Patched::new(); - // The patch service offers the patch's registry and the checkout - // proves a pnpm that reads one, so nothing but the hub keeps hosted - // mode from routing the lock through it: the lock is pinned as the - // steps below hold it, and the build of that pin is the patched one. + // Where the patch service offers the patch's registry: the checkout + // proves a pnpm that reads one, and the hub runs no pnpm, so hosted + // mode routes the lock as it does without Bazel, and the build of + // that lock is the patched one. let record = record(&upstream, &patch); - grant_as(&standin, &patch, &patch.package.tarball, &record, true); + grant_as(&standin, &patch, &patch.package.tarball, &record, offered); proves_pnpm_12(&cell); // (a) The unpatched build, with the upstream tarball from the stand-in. let before = builds_upstream(&cell, &standin, &upstream); - // (b) The one command of hosted mode. It rewrites those two files and - // no other: the entry of the package names the patched tarball, by its - // sum and by its URL on the patch host. + // (b) The one command of hosted mode. It writes those two files and + // no other. Routed, the workspace file declares the patch's registry + // and the lock keys the package by it; pinned, the file holds + // `trustLockfile: true` and the entry keeps its key. Either way the + // lock names the patched tarball, by its sum and by its URL on the + // patch host. let hosted = ["scan", "--mode", "hosted", "--yes"]; let claim = Claim::new(PURL, &patch.uuid, How::Hosted); let run = |cell: &Cell, args: &[&str]| socket_patch(cell, &standin, args); @@ -653,18 +767,13 @@ fn hosted_npm_translate_lock() { let scan = run(&cell, &[&hosted[..], &with_vex(&in_run)].concat()); let written = [LOCK, "pnpm-workspace.yaml"]; let pinned = cell.pinned_by(&scan, PURL, &patch.uuid, &before, &written); - let lock = text(&pinned, LOCK); - let entry = format!( - " '{NAME}@{VERSION}':\n resolution: {{integrity: {}, tarball: {origin}{}}}\n", - integrity(&patch.package.tarball), - patch.route - ); - assert!(lock.contains(&entry), "{test}: {LOCK}:\n{lock}"); - let workspace = text(&pinned, "pnpm-workspace.yaml"); - assert_eq!(workspace, TRUSTING_WORKSPACE, "{test}"); - // The registry was offered and not taken, and the warning says why. + match offered { + true => is_routed(test, &pinned, &origin, &patch, ""), + false => is_pinned(test, &pinned, &origin, &patch, ""), + } + // Nothing is said of the hub: the run is the one without Bazel. let warned = scan.envelope["warnings"].to_string(); - assert!(warned.contains(HUB_READS_THE_LOCK), "{test}: {}", scan.dump); + assert!(!warned.contains("Bazel"), "{test}: {}", scan.dump); // The document of that run and the one of `vex` say so, in a checkout // Bazel has built in, before the patched build. cell.wrote_in_run(&scan, &in_run, &claim); @@ -702,8 +811,13 @@ fn hosted_npm_translate_lock() { "{test}: the patch host was not asked, so the failed build proves nothing" ); + let how = match offered { + true => "routed the lock through the patch's registry", + false => "pinned the lock beside `trustLockfile: true`", + }; println!( - "{test}: Bazel {release} built {:?} from {origin}{} after `scan --mode hosted`; beside \ + "{test}: Bazel {release} built {:?} from {origin}{} after `scan --mode hosted` {how}; \ + beside \ Bazel's links a second scan reported the patch applied again, `vex` attested the \ package and the build stayed patched; `rollback` restored all {} files and the {:?} \ build; other bytes at the patch host failed a second machine's build ({refusal}); the \ @@ -718,6 +832,131 @@ fn hosted_npm_translate_lock() { ); } +/// A `patches` entry of the user's own on the fixture's hub in the +/// checkout of `cell`, for the package and keyed by its name and version, +/// as rules_js takes one, with the patch file it names: one more key in +/// the package's `package.json`, which both tarballs of a run hold alike. +fn patches_the_package(cell: &Cell) { + let (module, lock) = (text(&cell.tree(), MODULE), lock_line()); + assert_eq!(module.matches(&lock).count(), 1, "{}: {module}", cell.test); + let patches = format!("{lock} patches = {{\"{NAME}@{VERSION}\": [\"//:own.patch\"]}},\n"); + cell.write(MODULE, module.replace(&lock, &patches)); + let manifest = MANIFEST.trim_end(); + let own = manifest.replace("\"index.js\"}", "\"index.js\", \"own\": 1}"); + assert_ne!(own, manifest); + let patch = format!("--- package.json\n+++ package.json\n@@ -1 +1 @@\n-{manifest}\n+{own}\n"); + cell.write("own.patch", patch); +} + +/// The first Bazel release that builds a package anew after rules_js +/// unpacked other bytes of it into the same repository. For a package with +/// a `patches` entry rules_js unpacks the tarball when it fetches it and +/// hands the directory to the build (3.6.0, `npm/private/npm_import.bzl`: +/// without one it hands over the tarball, a file). Bazel 7 does not look +/// into a source directory, so an output base that built the package keeps +/// that output when a pin, or its undo, changes the bytes under the same +/// repository name, until `bazel clean`. +const STALE: (u32, u32, u32) = (8, 0, 0); + +/// What the warning says of the hub of [`patches_the_package`], after the +/// call: the attribute that kept it off the route. +const PATCHES_OF_THE_HUB: &str = "its `patches` is an attribute that no routed lock was built \ + with: a lock that a hub reads is routed only"; + +/// Hosted mode on the fixture's hub with a `patches` entry of the user's +/// own for the package ([`patches_the_package`]), for a patch whose +/// registry the patch service offers to a checkout that proves pnpm 12. +/// +/// A routed lock holds the package under another version +/// (`socket-:1.0.0`), which the entry does not name, and rules_js +/// fails a build on an entry that names no package of the lock (`Patch +/// file key ... does not match any npm packages`). The call says more than +/// the calls a routed lock was built with, so hosted mode keeps the pin +/// beside `trustLockfile: true`, under which the package keeps its key, +/// and says which attribute kept the hub off the route. +/// +/// - (a) The first build prints the unpatched marker. +/// - (b) `scan --mode hosted --yes` pins the lock ([`is_pinned`]) and +/// names the call and its `patches` in its warning; `vex` attests the +/// pin. +/// - (c) The same build passes, with the tarball from the stand-in patch +/// host, and changes no file. On Bazel 8 and 9 it prints the patched +/// marker. On Bazel 7 it prints the unpatched one until `bazel clean`, +/// as it does on the base ([`STALE`]): a known problem of +/// docs/ecosystems.md, which this flow records as it is. +/// - (d) `rollback --yes` leaves the checkout of before the scan, and the +/// build prints the unpatched marker, on Bazel 7 after `bazel clean`. +#[test] +#[ignore = "real Bazel; run with --ignored"] +fn hosted_npm_translate_lock_with_patches_of_the_hub() { + let test = "npm::hosted_npm_translate_lock_with_patches_of_the_hub"; + let started = Instant::now(); + let Some((cell, standin, upstream)) = open(test) else { + return; + }; + let release = cell.release().to_string(); + patches_the_package(&cell); + let patch = Patched::new(); + let record = record(&upstream, &patch); + grant_as(&standin, &patch, &patch.package.tarball, &record, true); + proves_pnpm_12(&cell); + + // (a) The unpatched build, with the user's patch applied. + let before = builds_upstream(&cell, &standin, &upstream); + + // (b) The pin, and why it is not the route. + let scan = socket_patch(&cell, &standin, &["scan", "--mode", "hosted", "--yes"]); + let written = [LOCK, "pnpm-workspace.yaml"]; + let pinned = cell.pinned_by(&scan, PURL, &patch.uuid, &before, &written); + is_pinned(test, &pinned, &standin.origin(), &patch, ""); + let warned = scan.envelope["warnings"].to_string(); + let named = format!("{HUB_READS_THE_LOCK}{PATCHES_OF_THE_HUB}"); + assert!(warned.contains(&named), "{test}: {}", scan.dump); + // `vex` reads the lock: it attests the pin, whatever Bazel has built. + let run = |cell: &Cell, args: &[&str]| socket_patch(cell, &standin, args); + cell.stands_alone(run, &Claim::new(PURL, &patch.uuid, How::Hosted), true); + + // (c) The build of the pin. + let stale = cell.numbers() < STALE; + let cleans = |cell: &Cell| { + let clean = cell.bazel("clean", &[]); + assert!(clean.ok(), "{test}: {}", clean.dump()); + }; + let fetches = standin.asked(&patch.route); + if stale { + cell.builds_patched(&pinned, &upstream.marker); + cleans(&cell); + } + cell.builds_patched(&pinned, &patch.package.marker); + assert!( + standin.asked(&patch.route) > fetches, + "{test}: the build did not fetch the patched tarball from the stand-in patch host" + ); + + // (d) The undo. + let undo = socket_patch(&cell, &standin, &["rollback", "--yes"]); + if stale { + cell.builds(&patch.package.marker); + cleans(&cell); + } + cell.undone(&undo, "rolledBack", &before, &upstream.marker); + + let kept = match stale { + true => "kept the output of the earlier build until `bazel clean`, then printed", + false => "printed", + }; + println!( + "{test}: Bazel {release} built {:?} with a `patches` entry of the hub for the package; \ + `scan --mode hosted` kept the pin beside `trustLockfile: true` and named `patches` as \ + what kept the hub off the route; the build of the pin passed and {kept} {:?}; \ + `rollback` brought {:?} back; {:?}", + upstream.marker, + patch.package.marker, + upstream.marker, + started.elapsed() + ); +} + /// The vendored flow of the module docs. Its second scan, beside the links /// of the Bazel that built in the checkout, reports the package /// `already_vendored`, and `vex` writes a document that attests it. @@ -1173,6 +1412,257 @@ fn hosted_update_pnpm_lock_on_pnpm_10() { ); } +/// How a workspace states the pnpm that a hub runs, in the three ways +/// socket-patch reads as written out. +#[derive(Clone, Copy, Debug)] +enum Stated { + /// `pnpm.pnpm(name = "pnpm", pnpm_version = "11.28.10")`. + Version, + /// `pnpm.pnpm(name = "pnpm", pnpm_version_from = "//:package.json")`, + /// and the `packageManager` of that file. + PackageManager, + /// `use_pnpm = "@eleven//:package/bin/pnpm.cjs"` on the hub, the + /// repository of a tag of that name. + Label, +} + +const EVERY_WAY: [Stated; 3] = [Stated::Version, Stated::PackageManager, Stated::Label]; + +/// The hub of [`keeps_the_lock_up_to_date`] with [`PNPM_11`], in the +/// checkout of `cell`, as one whose pnpm reads the workspace file: a +/// `pnpm-workspace.yaml` of the user's own in its `data` +/// ([`lists_the_workspace_file`]), and its pnpm stated as `stated` says. +fn lists_the_file_and_states(cell: &Cell, stated: Stated) { + lists_the_workspace_file(cell); + let module = text(&cell.tree(), MODULE); + let version = format!("pnpm.pnpm(name = \"pnpm\", pnpm_version = \"{PNPM_11}\")\n"); + let tag = format!("{version}use_repo(pnpm, \"pnpm\")\n"); + assert_eq!(module.matches(&tag).count(), 1, "{}: {module}", cell.test); + let module = match stated { + Stated::Version => return, + Stated::PackageManager => { + let manifest = text(&cell.tree(), "package.json"); + let private = " \"private\": true,\n"; + assert_eq!(manifest.matches(private).count(), 1, "{manifest}"); + let pin = format!("{private} \"packageManager\": \"pnpm@{PNPM_11}\",\n"); + cell.write("package.json", manifest.replace(private, &pin)); + let from = "pnpm.pnpm(name = \"pnpm\", pnpm_version_from = \"//:package.json\")\n"; + module.replace(&version, from) + } + Stated::Label => { + let (lock, named) = (lock_line(), tag.replace("\"pnpm\"", "\"eleven\"")); + let entry = format!("{lock} use_pnpm = \"@eleven//:package/bin/pnpm.cjs\",\n"); + module.replace(&tag, &named).replace(&lock, &entry) + } + }; + cell.write(MODULE, module); +} + +/// Hosted mode on a hub that keeps the lock up to date with pnpm 11 +/// ([`open_updating`]), lists a `pnpm-workspace.yaml` of the user's own as +/// `data` and states that pnpm as `stated` says +/// ([`lists_the_file_and_states`]). The patch service offers the patch's +/// registry and the checkout proves pnpm 12, as in +/// [`hosted_npm_translate_lock`]. +/// +/// - (a) The first build prints the unpatched marker. +/// - (b) `scan --mode hosted --yes` routes the lock through the patch's +/// registry ([`is_routed`]): the registry and the override go under the +/// user's comment, and no `trustLockfile`. It says nothing of the hub, +/// and its document and the one of `vex` attest the package. +/// - (c) The same build prints the patched marker ([`builds_pinned`]): the +/// pnpm that Bazel runs asked the patch's registry about the package and +/// left the lock as it was, and a second build changes no file. +/// - (d) `rollback --yes` leaves the checkout of before the scan, the +/// user's file included, and the build prints the unpatched marker +/// ([`rolls_back`]). +fn keeps_the_lock_up_to_date_where_a_registry_is_offered(test: &str, stated: Stated) { + let started = Instant::now(); + let Some((cell, standin, upstream)) = open_updating(test, Some(PNPM_11)) else { + return; + }; + let release = cell.release().to_string(); + lists_the_file_and_states(&cell, stated); + let patch = Patched::new(); + let record = record(&upstream, &patch); + grant_as(&standin, &patch, &patch.package.tarball, &record, true); + let registry = serves_registry(&standin, &patch); + proves_pnpm_12(&cell); + + // (a) The unpatched build, by a hub that ran its pnpm. + let before = builds_upstream(&cell, &standin, &upstream); + + // (b) The one command of hosted mode. + let claim = Claim::new(PURL, &patch.uuid, How::Hosted); + let run = |cell: &Cell, args: &[&str]| socket_patch(cell, &standin, args); + let in_run = cell.document("in-run"); + let hosted = ["scan", "--mode", "hosted", "--yes"]; + let scan = run(&cell, &[&hosted[..], &with_vex(&in_run)].concat()); + let written = [LOCK, "pnpm-workspace.yaml"]; + let pinned = cell.pinned_by(&scan, PURL, &patch.uuid, &before, &written); + is_routed(test, &pinned, &standin.origin(), &patch, OWN_WORKSPACE); + let warned = scan.envelope["warnings"].to_string(); + assert!(!warned.contains("Bazel"), "{test}: {}", scan.dump); + cell.wrote_in_run(&scan, &in_run, &claim); + cell.stands_alone(run, &claim, true); + + // (c) The patched build. The pnpm of the hub held the lock to the + // patch's registry, and a second build finds nothing to do. + builds_pinned(&cell, &standin, &patch, &pinned); + assert!( + standin.asked(®istry) > 0, + "{test}: no pnpm asked the patch's registry about the package" + ); + let built = cell.tree(); + assert_eq!(text(&built, LOCK), text(&pinned, LOCK), "{test}"); + cell.builds(&patch.package.marker); + assert_eq!(changed(&built, &cell.tree()), NOTHING, "{test}"); + + // (d) The undo. + rolls_back(&cell, &standin, &before, &upstream.marker); + + println!( + "{test}: Bazel {release} built {:?} with pnpm {PNPM_11} ({stated:?}) keeping the lock \ + up to date and pnpm-workspace.yaml in the hub's `data`; `scan --mode hosted` routed \ + the lock through the patch's registry, that pnpm left it as it was and the build \ + printed {:?}; `rollback` brought {:?} back; {:?}", + upstream.marker, + patch.package.marker, + upstream.marker, + started.elapsed() + ); +} + +#[test] +#[ignore = "real Bazel; run with --ignored"] +fn hosted_update_pnpm_lock_with_a_registry_by_version() { + let test = "npm::hosted_update_pnpm_lock_with_a_registry_by_version"; + keeps_the_lock_up_to_date_where_a_registry_is_offered(test, Stated::Version); +} + +#[test] +#[ignore = "real Bazel; run with --ignored"] +fn hosted_update_pnpm_lock_with_a_registry_by_package_manager() { + let test = "npm::hosted_update_pnpm_lock_with_a_registry_by_package_manager"; + keeps_the_lock_up_to_date_where_a_registry_is_offered(test, Stated::PackageManager); +} + +#[test] +#[ignore = "real Bazel; run with --ignored"] +fn hosted_update_pnpm_lock_with_a_registry_by_label() { + let test = "npm::hosted_update_pnpm_lock_with_a_registry_by_label"; + keeps_the_lock_up_to_date_where_a_registry_is_offered(test, Stated::Label); +} + +/// The option that keeps hosted mode from writing to `pnpm-workspace.yaml`. +const NO_SETTING: &str = "--no-trust-lockfile-config"; + +/// What the `redirect_pnpm_trust_lockfile` warning of a scan under +/// [`NO_SETTING`] says of the lock it pinned. +const REJECTED: &str = "pnpm >=11 rejects the rewritten lock"; + +/// What the warning of [`HIDDEN`] says to do where the scan was told not +/// to write to the file the hub lists: its last words. +const WAY_ON_UNSET: &str = " — let hosted mode write to pnpm-workspace.yaml (this run was told \ + not to, which is `--no-trust-lockfile-config` on the command line, so it writes neither the \ + setting nor the registries that take its place) or set `trustLockfile: true` there yourself \ + and re-run"; + +/// Hosted mode told not to write to `pnpm-workspace.yaml` +/// ([`NO_SETTING`]), on the hub of +/// [`keeps_the_lock_up_to_date_where_a_registry_is_offered`] with the +/// pnpm stated by its version. +/// +/// - (a) The first build prints the unpatched marker. +/// - (b) `scan --mode hosted --yes --no-trust-lockfile-config` passes and +/// pins nothing ([`pinned_nothing`]): the pnpm that Bazel runs would +/// reject a pin that no `trustLockfile: true` covers, and the scan may +/// write neither that setting nor the registries that take its place. +/// The warning names the call and what to do. +/// - (c) The same build passes and prints the unpatched marker. +/// - (d) What the warning says: the same scan without the option routes +/// the lock, and the build prints the patched marker +/// ([`builds_pinned`]). +/// - (e) The scan with the option again, on the routed project +/// ([`stays_routed`]): it reports the patch applied and changes no +/// file, and the build stays the patched one. `rollback --yes` brings +/// the unpatched build back ([`rolls_back`]). +#[test] +#[ignore = "real Bazel; run with --ignored"] +fn hosted_update_pnpm_lock_without_the_trust_setting() { + let test = "npm::hosted_update_pnpm_lock_without_the_trust_setting"; + let started = Instant::now(); + let Some((cell, standin, upstream)) = open_updating(test, Some(PNPM_11)) else { + return; + }; + let release = cell.release().to_string(); + lists_the_file_and_states(&cell, Stated::Version); + let patch = Patched::new(); + let record = record(&upstream, &patch); + grant_as(&standin, &patch, &patch.package.tarball, &record, true); + serves_registry(&standin, &patch); + proves_pnpm_12(&cell); + + // (a) The unpatched build. + let before = builds_upstream(&cell, &standin, &upstream); + + // (b) The scan writes nothing, and says why. + let hosted = ["scan", "--mode", "hosted", "--yes"]; + let scan = socket_patch(&cell, &standin, &[&hosted[..], &[NO_SETTING]].concat()); + pinned_nothing(&cell, &scan, &before, &names_the_hub(&cell), WAY_ON_UNSET); + + // (c) The same build is the one of (a). + cell.builds(&upstream.marker); + assert_eq!(changed(&before, &cell.tree()), NOTHING, "{test}"); + + // (d) Without the option the lock is routed, and the build patched. + let scan = socket_patch(&cell, &standin, &hosted); + let written = [LOCK, "pnpm-workspace.yaml"]; + let pinned = cell.pinned_by(&scan, PURL, &patch.uuid, &before, &written); + is_routed(test, &pinned, &standin.origin(), &patch, OWN_WORKSPACE); + builds_pinned(&cell, &standin, &patch, &pinned); + + // (e) The option again, on the project that is routed now: the file + // holds the route, so the run has nothing to write there and needs no + // setting. It reports the patch applied, as it does without Bazel, + // and the build stays the patched one. + let built = cell.tree(); + let again = socket_patch(&cell, &standin, &[&hosted[..], &[NO_SETTING]].concat()); + stays_routed(&cell, &again, &built, "applied"); + cell.builds(&patch.package.marker); + assert_eq!(changed(&built, &cell.tree()), NOTHING, "{test}"); + + rolls_back(&cell, &standin, &before, &upstream.marker); + + println!( + "{test}: Bazel {release} built {:?} with pnpm {PNPM_11} keeping the lock up to date; \ + `scan --mode hosted {NO_SETTING}` pinned nothing and warned {HIDDEN}, and the build \ + stayed that one; without the option the scan routed the lock and the build printed \ + {:?}; `rollback` brought {:?} back; {:?}", + upstream.marker, + patch.package.marker, + upstream.marker, + started.elapsed() + ); +} + +/// A finished hosted scan under [`NO_SETTING`] in the checkout of `cell`, +/// whose lock an earlier run routed and whose files are `routed`: +/// `pnpm-workspace.yaml` holds the route of the pin already, so the run +/// is the one of the same project without Bazel. It passes, reports the +/// patch under `action` (`applied`, or `verified` for a dry run), says +/// nothing of the hub and changes no file. +fn stays_routed(cell: &Cell, ran: &Ran, routed: &Tree, action: &str) { + let (test, said) = (&cell.test, &ran.dump); + assert_eq!(ran.code, 0, "{test}: {said}"); + assert_eq!(ran.envelope["status"], "success", "{test}: {said}"); + let seen = [(canonical_purl(PURL), action.into(), String::new())]; + assert_eq!(reported(&ran.envelope), seen, "{test}: {said}"); + let warnings = &ran.envelope["warnings"]; + assert!(!warnings.to_string().contains("Bazel"), "{test}: {said}"); + assert_eq!(changed(routed, &cell.tree()), NOTHING, "{test}: {said}"); +} + /// The directory of the checkout where rules_js keeps the hashes of what a /// hub with `update_pnpm_lock` read, one file per hub. const HASHES: &str = ".aspect/rules/external_repository_action_cache/"; @@ -2117,14 +2607,14 @@ fn hosted_scan(cell: &Cell, standin: &StandIn, project: &str, more: &[&str]) -> /// Without a Bazel: the scan of [`hosted_npm_translate_lock`], whose patch /// service offers the patch's registry to a checkout that proves pnpm 12 /// and has no installed copy of the package, as the flow on a real Bazel -/// has it. Beside the fixture's hub, which reads the lock, hosted mode -/// does not route the lock through that registry: it writes the two files -/// of a trust pin, with the package under its plain key, the warning -/// names the hub's call, and `rollback` gives every file back. The same -/// files in a checkout that is no Bazel workspace are routed, so the -/// offer is live and the hub is what decides. +/// has it. Beside the fixture's hub, which runs no pnpm, hosted mode +/// routes the lock through that registry: it writes the two files of the +/// route ([`is_routed`]), exactly those of the same checkout without its +/// `MODULE.bazel`, and says nothing of the hub. A second scan changes +/// nothing, and `rollback` gives every file back: the workspace file, +/// which the scan created, is gone again. #[test] -fn a_lock_that_a_hub_reads_stays_on_the_trust_pin_where_a_registry_is_offered() { +fn a_lock_that_a_hub_reads_is_routed_where_the_hub_runs_no_pnpm() { let (cell, standin, patch, _) = checkout_granted("", false, true); let test = &cell.test; std::fs::remove_dir_all(cell.path("node_modules")).expect("the tree"); @@ -2138,33 +2628,14 @@ fn a_lock_that_a_hub_reads_stays_on_the_trust_pin_where_a_registry_is_offered() let pinned = pins_the_lock(&cell, &standin, &patch); let written = [LOCK, "pnpm-workspace.yaml"]; assert_eq!(changed(&before, &pinned), written, "{test}"); - assert_eq!( - text(&pinned, "pnpm-workspace.yaml"), - TRUSTING_WORKSPACE, - "{test}" - ); - let lock = text(&pinned, LOCK); - let entry = format!( - " '{NAME}@{VERSION}':\n resolution: {{integrity: {}, tarball: {}{}}}\n", - integrity(&patch.package.tarball), - standin.origin(), - patch.route - ); - assert!( - lock.contains(&entry) && !lock.contains("@socket-") && !lock.contains("\noverrides:"), - "{test}: {lock}" - ); + is_routed(test, &pinned, &standin.origin(), &patch, ""); let hosted = ["scan", "--mode", "hosted", "--yes"]; let again = socket_patch(&cell, &standin, &hosted); assert_eq!(again.code, 0, "{test}: {}", again.dump); let scanned = &again.envelope["scannedPackages"]; assert_eq!(*scanned, 1, "{test}: {}", again.dump); let warned = again.envelope["warnings"].to_string(); - assert!( - warned.contains(HUB_READS_THE_LOCK), - "{test}: {}", - again.dump - ); + assert!(!warned.contains("Bazel"), "{test}: {}", again.dump); assert_eq!(changed(&pinned, &cell.tree()), NOTHING, "{test}"); // The undo and the documents, as step (d) of the flow asks for them. @@ -2184,13 +2655,25 @@ fn a_lock_that_a_hub_reads_stays_on_the_trust_pin_where_a_registry_is_offered() }; cell.attests_unbuilt(run, &hosted, &unmarked(&before), &unmarked(&pinned), &claim); + // The same files in a checkout that is no Bazel workspace. let routed = socket_patch(&twin, &standin, &hosted); assert_eq!(routed.code, 0, "{test}: {}", routed.dump); - let lock = text(&twin.tree(), LOCK); - let key = format!("'{NAME}@socket-{}:{VERSION}':", &patch.uuid[..8]); - assert!(lock.contains(&key), "{test}: {lock}"); - let warned = routed.envelope["warnings"].to_string(); - assert!(!warned.contains("Bazel"), "{test}: {}", routed.dump); + for file in written { + assert_eq!(text(&twin.tree(), file), text(&pinned, file), "{test}"); + } + + // The hub with a `patches` entry for the package, as + // [`hosted_npm_translate_lock_with_patches_of_the_hub`] has it: the + // call says more than the calls a routed lock was built with, so the + // lock keeps the pin, and the warning names the attribute. + patches_the_package(&cell); + let before = cell.tree(); + let scan = socket_patch(&cell, &standin, &hosted); + let pinned = cell.pinned_by(&scan, PURL, &patch.uuid, &before, &written); + is_pinned(test, &pinned, &standin.origin(), &patch, ""); + let warned = scan.envelope["warnings"].to_string(); + let named = format!("{HUB_READS_THE_LOCK}{PATCHES_OF_THE_HUB}"); + assert!(warned.contains(&named), "{test}: {}", scan.dump); } /// Without a Bazel: the two scans of [`hosted_update_pnpm_lock_on_pnpm_11`] @@ -2312,8 +2795,8 @@ fn a_listed_workspace_file_has_to_hold_the_setting_and_a_line_of_the_users_own() (String::new(), format!("{own} and re-run")), ( format!("{OWN_WORKSPACE}trustLockfile: false\n"), - " — set `trustLockfile: true` in pnpm-workspace.yaml (it says `trustLockfile: \ - false`, which hosted mode leaves as it is) and re-run" + " — set `trustLockfile: true` in pnpm-workspace.yaml or take the line out (it says \ + `trustLockfile: false`, which hosted mode leaves as it is) and re-run" .to_string(), ), ]; @@ -2330,6 +2813,185 @@ fn a_listed_workspace_file_has_to_hold_the_setting_and_a_line_of_the_users_own() } } +/// Without a Bazel: the scan of +/// [`keeps_the_lock_up_to_date_where_a_registry_is_offered`], for the pnpm +/// of the hub stated in each of the three ways. Beside the hub hosted mode +/// routes the lock through the registry it is offered: it writes the two +/// files of the route, the registry and the override under the user's +/// comment ([`is_routed`]); a second scan says nothing of the hub and +/// changes nothing; and `rollback` gives every file back, the user's file +/// as it was. +/// +/// The same hub in a shape that is not routed keeps the pin with +/// `trustLockfile: true`, and the warning says what kept it off the +/// route: its pnpm below 11.20, and no `pnpm-workspace.yaml` in a `data` +/// that a pnpm 10 has no need of. And where the file that the hub lists +/// would hold only what hosted mode writes, the lock is neither routed +/// nor pinned: `rollback` would remove such a file, and the call would +/// name a missing one. +#[test] +fn a_hub_that_keeps_the_lock_up_to_date_is_routed_where_its_pnpm_reads_the_registries() { + let hosted = ["scan", "--mode", "hosted", "--yes"]; + for stated in EVERY_WAY { + let (mut cell, standin, patch, _) = checkout_granted("", false, true); + cell.test = format!("{stated:?}"); + let test = &cell.test; + std::fs::remove_dir_all(cell.path("node_modules")).expect("the tree"); + proves_pnpm_12(&cell); + keeps_the_lock_up_to_date(&cell, Some(PNPM_11)); + lists_the_file_and_states(&cell, stated); + let before = cell.tree(); + + let pinned = pins_the_lock(&cell, &standin, &patch); + let written = [LOCK, "pnpm-workspace.yaml"]; + assert_eq!(changed(&before, &pinned), written, "{test}"); + is_routed(test, &pinned, &standin.origin(), &patch, OWN_WORKSPACE); + + let again = socket_patch(&cell, &standin, &hosted); + assert_eq!(again.code, 0, "{test}: {}", again.dump); + let warned = again.envelope["warnings"].to_string(); + assert!(!warned.contains("Bazel"), "{test}: {}", again.dump); + assert_eq!(changed(&pinned, &cell.tree()), NOTHING, "{test}"); + + let undo = socket_patch(&cell, &standin, &["rollback", "--yes"]); + assert_eq!(undo.code, 0, "{test}: {}", undo.dump); + assert_eq!(changed(&before, &cell.tree()), NOTHING, "{test}"); + } + + let older: Arrange = |cell| { + let module = text(&cell.tree(), MODULE); + cell.write(MODULE, module.replace(PNPM_11, "11.19.0")); + }; + let unlisted: Arrange = |cell| { + let module = text(&cell.tree(), MODULE); + let data = " data = [\"//:pnpm-workspace.yaml\"],\n"; + let module = module.replace(data, "").replace(PNPM_11, "10.34.9"); + cell.write(MODULE, module); + }; + let cases = [ + ( + older, + "the pnpm it runs for `update_pnpm_lock` is not stated as 11.20 or later (pnpm \ + 11.19.0)", + ), + ( + unlisted, + "its `data` is not written out as a list of strings that holds \ + `//:pnpm-workspace.yaml`", + ), + ]; + for (arrange, why) in cases { + let (mut cell, standin, patch, _) = checkout_granted("", false, true); + cell.test = why.to_string(); + let test = &cell.test; + std::fs::remove_dir_all(cell.path("node_modules")).expect("the tree"); + proves_pnpm_12(&cell); + keeps_the_lock_up_to_date(&cell, Some(PNPM_11)); + lists_the_workspace_file(&cell); + arrange(&cell); + let before = cell.tree(); + assert!(!text(&before, MODULE).contains(PNPM_11), "{test}"); + + let scan = socket_patch(&cell, &standin, &hosted); + let pinned = cell.pinned_by( + &scan, + PURL, + &patch.uuid, + &before, + &[LOCK, "pnpm-workspace.yaml"], + ); + let workspace = format!("{OWN_WORKSPACE}{TRUSTING_WORKSPACE}"); + assert_eq!(text(&pinned, "pnpm-workspace.yaml"), workspace, "{test}"); + let lock = text(&pinned, LOCK); + let plain = lock.contains(&patch.route) && !lock.contains("@socket-"); + assert!(plain && !lock.contains("\noverrides:"), "{test}: {lock}"); + let warned = scan.envelope["warnings"].to_string(); + let named = format!("{HUB_READS_THE_LOCK}{why}: a lock that a hub reads is routed only"); + assert!(warned.contains(&named), "{test}: {}", scan.dump); + } + + let (cell, standin, _, _) = checkout_granted("", false, true); + std::fs::remove_dir_all(cell.path("node_modules")).expect("the tree"); + proves_pnpm_12(&cell); + keeps_the_lock_up_to_date(&cell, Some(PNPM_11)); + lists_the_workspace_file(&cell); + std::fs::remove_file(cell.path("pnpm-workspace.yaml")).expect("the user's file"); + let before = cell.tree(); + let scan = socket_patch(&cell, &standin, &hosted); + let own = WAY_ON[0].split_once(", list ").expect("the first step").0; + let way_on = format!("{own} and re-run"); + pinned_nothing(&cell, &scan, &before, &names_the_hub(&cell), &way_on); +} + +/// Without a Bazel: the scan of +/// [`hosted_update_pnpm_lock_without_the_trust_setting`], which is told +/// not to write to `pnpm-workspace.yaml`, beside a hub that keeps the lock +/// up to date and lists the user's file. +/// +/// - The hub runs pnpm 11, which would reject a pin that no +/// `trustLockfile: true` covers: the scan, a dry run of it and +/// `get --mode hosted` pin nothing ([`pinned_nothing`]), and the warning +/// says to drop the option or to write the setting. +/// - Once a scan without the option has routed the lock, the file holds +/// the route and the scan with the option needs to write nothing: it +/// reports the patch applied, its dry run finds it in place, and +/// neither changes a file ([`stays_routed`]). +/// - The user's file holds the setting already, or the hub runs a pnpm +/// 10, which has no such check: the scan pins the lock, and that file +/// alone, with the warning of the option that pnpm 11 rejects a lock +/// without the setting, as it does without Bazel. +#[test] +fn a_scan_told_not_to_write_the_setting_leaves_a_lock_that_the_pnpm_of_a_hub_rejects() { + let checkout = |pnpm: &str, workspace: &str| { + let (mut cell, standin, patch, _) = checkout_granted("", false, true); + cell.test = format!("pnpm {pnpm}, {workspace:?}"); + std::fs::remove_dir_all(cell.path("node_modules")).expect("the tree"); + proves_pnpm_12(&cell); + keeps_the_lock_up_to_date(&cell, Some(pnpm)); + lists_the_workspace_file(&cell); + cell.write("pnpm-workspace.yaml", workspace); + (cell, standin, patch) + }; + + let (cell, standin, patch) = checkout(PNPM_11, OWN_WORKSPACE); + let before = cell.tree(); + let names = names_the_hub(&cell); + for more in [&["--yes", NO_SETTING][..], &["--dry-run", NO_SETTING]] { + let scan = hosted_scan(&cell, &standin, "", more); + pinned_nothing(&cell, &scan, &before, &names, WAY_ON_UNSET); + } + let get = ["get", PURL, "--mode", "hosted", "--yes", NO_SETTING]; + let get = socket_patch(&cell, &standin, &get); + pinned_nothing(&cell, &get, &before, &names, WAY_ON_UNSET); + // Routed by a scan without the option: the file holds the route, and + // the scan with the option is then the one without Bazel. + let routed = pins_the_lock(&cell, &standin, &patch); + is_routed( + &cell.test, + &routed, + &standin.origin(), + &patch, + OWN_WORKSPACE, + ); + for (how, action) in [("--yes", "applied"), ("--dry-run", "verified")] { + let scan = hosted_scan(&cell, &standin, "", &[how, NO_SETTING]); + stays_routed(&cell, &scan, &routed, action); + } + + let trusting = format!("{OWN_WORKSPACE}trustLockfile: true\n"); + for (pnpm, workspace) in [(PNPM_11, trusting.as_str()), ("10.34.9", OWN_WORKSPACE)] { + let (cell, standin, patch) = checkout(pnpm, workspace); + let before = cell.tree(); + let scan = hosted_scan(&cell, &standin, "", &["--yes", NO_SETTING]); + let (test, said) = (&cell.test, &scan.dump); + let pinned = cell.pinned_by(&scan, PURL, &patch.uuid, &before, &[LOCK]); + assert!(text(&pinned, LOCK).contains(&patch.route), "{test}"); + let warnings = &scan.envelope["warnings"]; + assert!(warnings.to_string().contains(REJECTED), "{test}: {said}"); + assert!(!codes_in(warnings).contains(&HIDDEN.to_string()), "{said}"); + } +} + /// A `package-lock.json` in the checkout of `cell` that pins the package as /// its pnpm lock does: the lock of a project that npm installs. fn locks_with_npm(cell: &Cell) { diff --git a/crates/socket-patch-cli/tests/e2e_redirect_pnpm_build.rs b/crates/socket-patch-cli/tests/e2e_redirect_pnpm_build.rs index 0c9eca8b2..398dfcef1 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_pnpm_build.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_pnpm_build.rs @@ -2807,19 +2807,22 @@ async fn pnpm11_registry_route_reaches_a_newer_release_in_range() { } /// A PROJECT ROUTED BEFORE ITS BAZEL WORKSPACE GOT A RULES_JS HUB, with a -/// real pnpm. Hosted mode does not route a lock that a hub reads, so the -/// next scan has to settle the project one of two ways, and a frozen -/// install has to pass afterwards wherever pnpm reads the workspace file: +/// real pnpm. Hosted mode routes a lock that a hub reads only where the +/// build of that hub takes a routed lock, so under any other hub the next +/// scan has to settle the project one of two ways, and a frozen install +/// has to pass afterwards wherever pnpm reads the workspace file: /// /// * the hub keeps the lock up to date with a pnpm 11 that does not see /// pnpm-workspace.yaml: the scan leaves the lock to the hub /// (`redirect_pnpm_bazel_workspace_hidden`) and the route with it, every /// byte of the lock and of the workspace file as it was, so pnpm still /// installs the patched release through its registry; -/// * the hub only reads the lock: the scan leaves the route whole, the -/// registry and the override out of the workspace file, the `overrides:` -/// record and the registry keys out of the lock, in one run, and pins the -/// release on `trustLockfile`, which pnpm installs frozen and patched. +/// * the hub keeps the lock up to date with a pnpm 10, which reads no +/// registry of the workspace file it is shown: the scan leaves the route +/// whole, the registry and the override out of the workspace file, the +/// `overrides:` record and the registry keys out of the lock, in one +/// run, and pins the release on `trustLockfile`, which pnpm installs +/// frozen and patched. async fn registry_route_is_left_for_a_bazel_hub_added_later(pm: &str, tag: &str) { if !has_corepack_pm(pm) { println!("SKIP {tag}: `corepack {pm}` unavailable"); @@ -2965,8 +2968,10 @@ async fn registry_route_is_left_for_a_bazel_hub_added_later(pm: &str, tag: &str) "{tag}: the routed release still installs patched" ); - // ── a hub that reads the lock ── - std::fs::write(proj.join("MODULE.bazel"), hub("")).unwrap(); + // ── a hub whose pnpm reads no registry of the workspace file ── + let listing = ", update_pnpm_lock = True, data = [\"//:pnpm-workspace.yaml\"]"; + let older = hub(listing).replace("11.28.10", "10.34.9"); + std::fs::write(proj.join("MODULE.bazel"), older).unwrap(); let (code, stdout, stderr) = run_hosted(HostedDriver::Scan, &proj, &server.uri(), &[]); assert_eq!(code, 0, "{tag}: scan failed.\n{stdout}\n{stderr}"); let env = parse_envelope(&stdout); diff --git a/crates/socket-patch-cli/tests/hosted_memory_parity.rs b/crates/socket-patch-cli/tests/hosted_memory_parity.rs index ea168f952..a896775ac 100644 --- a/crates/socket-patch-cli/tests/hosted_memory_parity.rs +++ b/crates/socket-patch-cli/tests/hosted_memory_parity.rs @@ -1440,10 +1440,30 @@ async fn assert_pnpm_workspace_parity_with_roots( files: &BTreeMap>, trust_lockfile_config: bool, roots: &[&str], +) -> (Value, BTreeMap>) { + assert_pnpm_workspace_parity_granted(files, trust_lockfile_config, roots, false).await +} + +/// [`assert_pnpm_workspace_parity_with_roots`]. With `registry`, the patch +/// service also offers each patch's own registry: the directory its +/// tarball is served from, which hosted mode can route a pnpm lock through. +async fn assert_pnpm_workspace_parity_granted( + files: &BTreeMap>, + trust_lockfile_config: bool, + roots: &[&str], + registry: bool, ) -> (Value, BTreeMap>) { let dir = fixtures_root().join("redirect/npm/pnpm/basic"); let server = MockServer::start().await; - let patches = patches_from_overrides(&dir.join("overrides.json"), Some(&server.uri())); + let mut patches = patches_from_overrides(&dir.join("overrides.json"), Some(&server.uri())); + for patch in patches.iter_mut().filter(|_| registry) { + let url = patch.reference["url"] + .as_str() + .expect("a tarball") + .to_string(); + let directory = &url[..=url.rfind('/').expect("the URL of a tarball")]; + patch.reference["npmRegistryUrl"] = directory.into(); + } mount_api(&server, &patches).await; let extra: &[&str] = if trust_lockfile_config { &[] @@ -1639,6 +1659,87 @@ async fn parity_pnpm_bazel_hub_that_hides_the_workspace_file() { ); } +/// A rules_js hub that reads the pnpm lock, a patch whose registry the +/// patch service offers and a project that proves pnpm 12: both engines +/// give the one answer. A hub that runs no pnpm, and one whose pnpm 11 +/// reads the user's `pnpm-workspace.yaml`, have the lock routed through +/// the registry. The same hub with a pnpm 10 keeps the pin with +/// `trustLockfile: true`, and the warning says what kept it off the +/// route. Told not to write to the workspace file, both engines write +/// nothing beside the hub whose pnpm 11 would reject the pin, and say what +/// to do. +#[tokio::test] +async fn parity_pnpm_bazel_hub_and_the_registry_route() { + let lock = + String::from_utf8(read_fixture("redirect/npm/pnpm/basic/input/pnpm-lock.yaml")).unwrap(); + let module = |hub: &str, pnpm: &str| { + format!( + "bazel_dep(name = \"aspect_rules_js\", version = \"3.6.0\")\n\ + npm = use_extension(\"@aspect_rules_js//npm:extensions.bzl\", \"npm\")\n\ + npm.npm_translate_lock(pnpm_lock = \"//:pnpm-lock.yaml\"{hub})\n\ + pnpm = use_extension(\"@aspect_rules_js//npm:extensions.bzl\", \"pnpm\")\n\ + pnpm.pnpm(name = \"pnpm\", pnpm_version = \"{pnpm}\")\n" + ) + }; + let listing = ", update_pnpm_lock = True, data = [\"//:pnpm-workspace.yaml\"]"; + let manifest = r#"{ "name": "root", "private": true, "packageManager": "pnpm@12.22.0" }"#; + let run = |module: String, trust: bool| { + let lock = lock.clone(); + async move { + let extra = [ + ("MODULE.bazel", module.as_str()), + ("package.json", manifest), + ]; + let files = pnpm_workspace("# own\n", Some(&lock), &[], &extra); + assert_pnpm_workspace_parity_granted(&files, trust, &[""], true).await + } + }; + let written = ["pnpm-lock.yaml", "pnpm-workspace.yaml"]; + let workspace = |changed: &BTreeMap>| { + String::from_utf8(changed["pnpm-workspace.yaml"].clone()).unwrap() + }; + + for hub in ["", listing] { + let (redirect, changed) = run(module(hub, "11.28.10"), true).await; + assert_eq!(changed.keys().collect::>(), written, "{hub}"); + let workspace = workspace(&changed); + assert!( + workspace.contains("namedRegistries:") && !workspace.contains("trustLockfile"), + "{hub}: {workspace}" + ); + assert!( + !redirect["warnings"].to_string().contains("Bazel"), + "{hub}: {redirect:#}" + ); + } + + let (redirect, changed) = run(module(listing, "10.34.9"), true).await; + assert_eq!(changed.keys().collect::>(), written); + assert_eq!( + workspace(&changed), + "# own\npackages:\n - '.'\ntrustLockfile: true\n" + ); + assert!( + redirect["warnings"].to_string().contains( + "a Bazel hub reads the pnpm lock (MODULE.bazel:3), and the pnpm it runs for \ + `update_pnpm_lock` is not stated as 11.20 or later (pnpm 10.34.9)" + ), + "{redirect:#}" + ); + + let (redirect, changed) = run(module(listing, "11.28.10"), false).await; + assert!(changed.is_empty(), "{}", describe(&changed)); + let warned = redirect["warnings"].to_string(); + assert!( + warned.contains("redirect_pnpm_bazel_workspace_hidden") + && warned.contains( + "let hosted mode write to pnpm-workspace.yaml (this run was told not to, which \ + is `--no-trust-lockfile-config` on the command line" + ), + "{redirect:#}" + ); +} + /// #492: a member lock beside a shared root lock (one listing the member's /// importer) is a stale leftover pnpm never reads: both engines pin the /// root lock alone. diff --git a/crates/socket-patch-cli/tests/in_process_pnpm_registry_cleanup.rs b/crates/socket-patch-cli/tests/in_process_pnpm_registry_cleanup.rs index 1f25479d3..bfd865300 100644 --- a/crates/socket-patch-cli/tests/in_process_pnpm_registry_cleanup.rs +++ b/crates/socket-patch-cli/tests/in_process_pnpm_registry_cleanup.rs @@ -1702,7 +1702,11 @@ const LISTING_HUB: &str = "bazel_dep(name = \"aspect_rules_js\", version = \"3.6 /// the lock, with none, and with nothing crawled at all, it rewrites /// neither the lock nor pnpm-workspace.yaml, and says why. Before, only /// the first left the files: the other two took the unused entries out, and -/// with the last of them the file that the hub's `data` names. +/// with the last of them the file that the hub's `data` names. The last +/// hub lists a file that holds a line of the user's own, which is left to +/// the hub by a scan that is told not to write to it +/// (`--no-trust-lockfile-config`): the pnpm of the hub would reject a pin +/// that such a scan adds. #[tokio::test] async fn a_hosted_scan_leaves_a_lock_to_its_bazel_hub_whatever_it_is_granted() { let granting = MockServer::start().await; @@ -1716,7 +1720,12 @@ async fn a_hosted_scan_leaves_a_lock_to_its_bazel_hub_whatever_it_is_granted() { .iter() .any(|w| w["code"] == "redirect_pnpm_bazel_workspace_hidden") }; - for hub in [HIDING_HUB, LISTING_HUB] { + let told: &[&str] = &["--no-trust-lockfile-config"]; + for (hub, extra) in [ + (HIDING_HUB, &[][..]), + (LISTING_HUB, &[]), + (LISTING_HUB, told), + ] { for (granted, server, installed) in [ ("a patch", &granting, true), ("no patch", &empty, true), @@ -1724,12 +1733,16 @@ async fn a_hosted_scan_leaves_a_lock_to_its_bazel_hub_whatever_it_is_granted() { ] { let tmp = tempfile::tempdir().unwrap(); let root = tmp.path(); - let (workspace, lock_text) = departed_project(root, "removed"); + let (mut workspace, lock_text) = departed_project(root, "removed"); + if !extra.is_empty() { + workspace.insert_str(0, "# the project's own\n"); + std::fs::write(root.join("pnpm-workspace.yaml"), &workspace).unwrap(); + } if !installed { std::fs::remove_dir_all(root.join("node_modules")).unwrap(); } std::fs::write(root.join("MODULE.bazel"), hub).unwrap(); - let (code, doc) = scan_hosted(root, server, &[]); + let (code, doc) = scan_hosted(root, server, extra); assert_eq!(code, Some(0), "{granted}: {doc}"); assert_eq!(entries(&doc, "removed"), [], "{granted}: {doc}"); assert_unchanged(root, &workspace, &lock_text, granted); @@ -1795,6 +1808,68 @@ async fn a_hub_of_a_root_lock_that_is_not_there_stands_against_no_cleanup() { } } +/// A scan that crawls nothing adds no pin: what it does beside a hub is +/// to take out what a route left and no lock uses, in the lock and in +/// pnpm-workspace.yaml together. So it does that also where it is told not +/// to write the setting (`--no-trust-lockfile-config`) beside a hub that +/// lists a file of the user's own: the pnpm of that hub would reject a pin +/// such a scan adds, and this one adds none. The lock it leaves is the +/// one without the record, byte for byte, and nothing is said of Bazel. +/// A hub that hides the file is still left its lock, as a scan that crawls +/// a package leaves it. +#[tokio::test] +async fn a_scan_that_crawls_nothing_tidies_beside_a_listing_hub_also_under_the_option() { + const BARE: &str = "lockfileVersion: '9.0'\n\nimporters:\n\n .: {}\n"; + const OWN: &str = "# the project's own\n"; + let server = MockServer::start().await; + mock_api(&server, &[], &[]).await; + let record = "overrides:\n leaf@1.0.0: socket-11111111:1.0.0\n\nimporters:\n"; + let routed = BARE.replace("importers:\n", record); + let told: &[&str] = &["--no-trust-lockfile-config"]; + for (case, hub, extra, tidied) in [ + ("told", LISTING_HUB, told, true), + ("not told", LISTING_HUB, &[][..], true), + ("hidden, told", HIDING_HUB, told, false), + ("hidden", HIDING_HUB, &[], false), + ] { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + for (rel, text) in [ + ("package.json", r#"{"name":"app","private":true}"#), + ("pnpm-workspace.yaml", OWN), + ("pnpm-lock.yaml", routed.as_str()), + ("MODULE.bazel", hub), + ] { + std::fs::write(root.join(rel), text).unwrap(); + } + let (code, doc) = scan_hosted(root, &server, extra); + assert_eq!(code, Some(0), "{case}: {doc}"); + assert_eq!(doc["scannedPackages"].as_u64(), Some(0), "{case}: {doc}"); + let warned = doc["warnings"].to_string(); + assert_eq!( + warned.contains("redirect_pnpm_bazel_workspace_hidden"), + !tidied, + "{case}: {doc}" + ); + let removed = match tidied { + true => vec![entry("pnpm-lock.yaml", "lockOverride", "leaf@1.0.0")], + false => Vec::new(), + }; + assert_eq!(entries(&doc, "removed"), removed, "{case}: {doc}"); + let kept = if tidied { BARE } else { routed.as_str() }; + assert_eq!( + read(root, "pnpm-lock.yaml").as_deref(), + Some(kept), + "{case}: {doc}" + ); + assert_eq!( + read(root, "pnpm-workspace.yaml").as_deref(), + Some(OWN), + "{case}" + ); + } +} + // ── what a person is told ──────────────────────────────────────────────── /// (4) Without `--json` each removal is a line, in `repair` and in a diff --git a/crates/socket-patch-cli/tests/in_process_redirect_pnpm.rs b/crates/socket-patch-cli/tests/in_process_redirect_pnpm.rs index c2459d8df..c1494e1e8 100644 --- a/crates/socket-patch-cli/tests/in_process_redirect_pnpm.rs +++ b/crates/socket-patch-cli/tests/in_process_redirect_pnpm.rs @@ -3888,14 +3888,22 @@ async fn hosted_registry_route_needs_a_pnpm_11_20_pin() { } /// A lock that a rules_js hub of the project's Bazel workspace reads is -/// not routed, also with a registry address and a pnpm 12 pin. The pnpm a -/// hub runs with `update_pnpm_lock` may not read the registries, so the -/// project keeps the pin the Bazel legs build. The run writes what -/// a patch service that offers no registry gets, the warning names the -/// call, and `rollback` gives the user's file and the lock back. +/// routed where the build of that hub takes a routed lock, and keeps the +/// pin with `trustLockfile` where it may not. The hub here keeps the lock +/// up to date and lists the user's pnpm-workspace.yaml; what differs is +/// the pnpm it runs. +/// +/// With the pnpm rules_js picks, a pnpm 10 that reads no registry of the +/// file, the run writes what a patch service that offers no registry +/// gets, and the warning names the call and what kept it off the route. +/// Once the workspace states pnpm 11.28.10 the next run moves the project +/// to the route, and the setting the earlier run wrote goes; a second run +/// changes nothing. Without that tag again the next run leaves the route +/// whole, and with it the one after takes it again. `rollback` gives the +/// user's file and the lock back from either. #[tokio::test] #[serial] -async fn hosted_registry_route_is_not_taken_for_a_lock_a_bazel_hub_reads() { +async fn hosted_registry_route_under_a_bazel_hub_follows_what_its_build_takes() { let server = MockServer::start().await; mock_discovery(&server).await; mock_registry_reference(&server).await; @@ -3905,40 +3913,99 @@ async fn hosted_registry_route_is_not_taken_for_a_lock_a_bazel_hub_reads() { let own = "# the project's own\n"; let ws_path = tmp.path().join("pnpm-workspace.yaml"); std::fs::write(&ws_path, own).unwrap(); - std::fs::write( - tmp.path().join("MODULE.bazel"), - "bazel_dep(name = \"aspect_rules_js\", version = \"3.6.0\")\n\ - npm = use_extension(\"@aspect_rules_js//npm:extensions.bzl\", \"npm\")\n\ - npm.npm_translate_lock(pnpm_lock = \"//:pnpm-lock.yaml\")\n", - ) - .unwrap(); + let hub = |pnpm: &str| { + let module = format!( + "bazel_dep(name = \"aspect_rules_js\", version = \"3.6.0\")\n\ + npm = use_extension(\"@aspect_rules_js//npm:extensions.bzl\", \"npm\")\n\ + npm.npm_translate_lock(pnpm_lock = \"//:pnpm-lock.yaml\", update_pnpm_lock = True, \ + data = [\"//:pnpm-workspace.yaml\"])\n\ + pnpm = use_extension(\"@aspect_rules_js//npm:extensions.bzl\", \"pnpm\")\n{pnpm}" + ); + std::fs::write(tmp.path().join("MODULE.bazel"), module).unwrap(); + }; + let eleven = "pnpm.pnpm(name = \"pnpm\", pnpm_version = \"11.28.10\")\n"; let lock_path = tmp.path().join("pnpm-lock.yaml"); let pristine = read(&lock_path); + let trusting = format!("{own}packages:\n - '.'\ntrustLockfile: true\n"); + let routed = format!("{own}packages:\n - '.'\n{}", route_maps()); + let scan = || { + let (code, doc) = run_hosted_json(tmp.path(), &server.uri()); + assert_eq!(code, Some(0), "{doc}"); + (read(&ws_path), read(&lock_path), warning_texts(&doc)) + }; - let (code, doc) = run_hosted_json(tmp.path(), &server.uri()); - assert_eq!(code, Some(0), "{doc}"); - assert_eq!( - read(&ws_path), - format!("{own}packages:\n - '.'\ntrustLockfile: true\n") - ); - let lock = read(&lock_path); + // The pnpm of the hub is not stated: pinned with `trustLockfile`. + hub(""); + let (workspace, pinned, texts) = scan(); + assert_eq!(workspace, trusting); assert!( - lock.contains(HOSTED_URL) && !lock.contains("@socket-") && !lock.contains("overrides:"), - "{lock}" + pinned.contains(HOSTED_URL) + && !pinned.contains("@socket-") + && !pinned.contains("overrides:"), + "{pinned}" ); - let texts = warning_texts(&doc); assert!( texts.contains( "Per-package registry verification was not set up because a Bazel hub reads the \ - pnpm lock (MODULE.bazel:3)" + pnpm lock (MODULE.bazel:3), and the pnpm it runs for `update_pnpm_lock` is not \ + stated as 11.20 or later: a lock that a hub reads is routed only where the call \ + of the hub passes nothing but `name`, `pnpm_lock`, `data`, `update_pnpm_lock` and \ + `use_pnpm`, and either leaves `update_pnpm_lock` off, or lists pnpm-workspace.yaml \ + in its `data` and states a pnpm of 11.20 or later" ), - "{doc}" + "{texts}" ); - let code = rollback_hosted(tmp.path(), &server).await; assert_eq!(code, 0, "rollback must restore the pnpm pin"); + assert_eq!( + (read(&lock_path), read(&ws_path)), + (pristine.clone(), own.to_string()) + ); + assert_eq!(scan(), (trusting.clone(), pinned.clone(), texts)); + + // Stated as 11.28.10: the project moves to the route, and stays. + hub(eleven); + for run in ["moves to the route", "changes nothing"] { + let (workspace, lock, texts) = scan(); + assert_eq!( + (workspace, lock), + (routed.clone(), routed_fixture_lock()), + "{run}" + ); + assert!(!texts.contains("Bazel"), "{run}: {texts}"); + } + + // The tag goes: the route goes whole, the lock and the file together. + hub(""); + let (workspace, lock, texts) = scan(); + assert_eq!((workspace, lock), (trusting, pinned.clone())); + assert!( + texts.contains("a Bazel hub reads the pnpm lock (MODULE.bazel:3)") + && texts.contains("An earlier run routed the hosted patches"), + "{texts}" + ); + + hub(eleven); + assert_eq!( + (scan().0, read(&lock_path)), + (routed, routed_fixture_lock()) + ); + let code = rollback_hosted(tmp.path(), &server).await; + assert_eq!(code, 0, "rollback must restore the routed pin"); assert_eq!(read(&lock_path), pristine); assert_eq!(read(&ws_path), own); + + // Routed before the hub was there, in a file the run created: under + // a hub that states a pnpm 10 the route goes and the file, which the + // hub lists, stays. + for file in [&ws_path, &tmp.path().join("MODULE.bazel")] { + std::fs::remove_file(file).unwrap(); + } + assert_eq!(scan().1, routed_fixture_lock()); + hub("pnpm.pnpm(name = \"pnpm\", pnpm_version = \"10.34.9\")\n"); + let (workspace, lock, _) = scan(); + assert_eq!(workspace, "packages:\n - '.'\ntrustLockfile: true\n"); + assert_eq!(lock, pinned); } /// `--dry-run` with a registry address: nothing lands on disk, the diff --git a/crates/socket-patch-core/src/bazel/maven.rs b/crates/socket-patch-core/src/bazel/maven.rs index 73eb1d69d..3a7b9b0a7 100644 --- a/crates/socket-patch-core/src/bazel/maven.rs +++ b/crates/socket-patch-core/src/bazel/maven.rs @@ -3640,6 +3640,7 @@ override_repo( file, call, dev_dependency: Some(false), + isolate: Some(false), }; proxy(&ws, &tag) }; diff --git a/crates/socket-patch-core/src/bazel/pnpm.rs b/crates/socket-patch-core/src/bazel/pnpm.rs index bbd4d0bee..31c7839a1 100644 --- a/crates/socket-patch-core/src/bazel/pnpm.rs +++ b/crates/socket-patch-core/src/bazel/pnpm.rs @@ -21,6 +21,18 @@ //! written out, keep it up to date, not list the `pnpm-workspace.yaml` //! beside it, and run a pnpm that may be 11 or later. //! +//! Told not to write to that file (`--no-trust-lockfile-config`), hosted +//! mode writes no setting for such a pnpm to read, so a hub that lists the +//! file gets nothing either unless the file holds `trustLockfile: true` +//! already ([`Hubs::unset`]). That answer is about a pin: a scan that +//! crawls nothing adds none, and takes out what a route left as it does +//! without Bazel. +//! +//! The same read says whether a lock may be routed through the named +//! registries of `pnpm-workspace.yaml` in place of that setting +//! ([`Hubs::reader`]): only where every call that reads it is written out +//! in a shape whose build takes a routed lock ([`Reader`]). +//! //! A hub that lists the file is passed over only where the pin would be //! one the build takes and an undo leaves standing. It is not where hosted //! mode does not write the setting to the file (the file sets @@ -53,6 +65,23 @@ //! repository rule, can be any pnpm (the first measured: Bazel 9.3.2 runs //! the pnpm 11 of the tag `pnpm` under the name `eleven`). //! +//! The route asks for more than the pin does, because a release that is +//! taken for 11.20 or later and is not the one the hub runs loses the +//! patch or fails the build: the repository has to be one of the use of +//! the pnpm extension that every module shares ([`Pnpm::Stated`]). A +//! `use_repo` on another extension's proxy can take a repository of the +//! same name as a tag, a use with `isolate` has tags and repositories of +//! its own, and an `inject_repo` on the extension is not read: each keeps +//! the hub off the route and changes nothing for the pin. Only a `use_repo` +//! on a name of the extension's proxy is followed for it. And the release +//! has to be the hub's in every build: a use of the extension with +//! `dev_dependency` is one whose tags Bazel drops under +//! `--ignore_dev_dependency` (`ModuleFileGlobals.useExtension` at 7.7.2, +//! 8.8.2 and 9.3.2), and the hub then runs the pnpm that rules_js picks. +//! So a release that such a use states does not count for the route. The +//! pin builds either way: its setting is in the file the hub lists, for +//! whichever pnpm asks for it. +//! //! In memory the workspace is the project's own files: path selection //! asks for the `MODULE.bazel` beside a `pnpm-lock.yaml` or a //! `pnpm-workspace.yaml`, for the files one can include and for the @@ -63,7 +92,8 @@ //! `pnpm_version_from` file that was not handed in (one outside the //! project's own manifests) and `MODULE.bazel.lock` are not there either: //! the first reads as a release that is not written out, so a lock that a -//! checkout pins can be left as it is in memory. +//! checkout pins can be left as it is in memory, and one that a checkout +//! routes can be pinned there. //! //! What is not written out counts against writing, because a broken build //! outranks a missed patch that a warning explains: an `update_pnpm_lock` @@ -75,9 +105,11 @@ //! ([`Workspace::doubts`], a `WORKSPACE` file) withholds nothing: a //! project whose lock no listed call names is left as it is. +use std::cell::OnceCell; + use super::rc::ModuleLock; use super::starlark::{Arg, Call, File, How, Value}; -use super::workspace::{disk, Doubt, Entry, Extension, Label, Repo, Workspace}; +use super::workspace::{disk, Doubt, Entry, Extension, Label, Repo, Tag, Tags, Workspace}; use crate::formats::text::strip_bom; use crate::hosted::guidance::{is_trust_scaffold, plan_workspace_trust, TrustPlan}; use crate::patch::redirect::RewriteWarning; @@ -119,41 +151,72 @@ pub struct Hubs { /// module docs): hosted mode then writes nothing for the root pnpm /// lock. pub hidden: Option, + /// That warning for a run that is told not to write to + /// `pnpm-workspace.yaml` (`--no-trust-lockfile-config`), where + /// [`Self::hidden`] is none: the hub lists the file, its pnpm may be + /// 11 or later, and the file does not hold `trustLockfile: true`, + /// which this run would not write. The pin would be one that the pnpm + /// of the build rejects, so such a run writes nothing for the root + /// lock either ([`Self::hides`]). + pub unset: Option, /// The hub that reads one of the project's pnpm locks ([`Reader`]): - /// hosted mode then routes none of them through a named registry. + /// hosted mode then routes them through named registries only where + /// the build of every such hub takes a routed lock. pub reader: Option, } +impl Hubs { + /// The warning with which a run leaves the root lock as it is: one + /// that writes its setting to `pnpm-workspace.yaml` (`writes`), or one + /// that is told not to. + pub fn hides(&self, writes: bool) -> Option<&RewriteWarning> { + let unset = self.unset.as_ref().filter(|_| !writes); + self.hidden.as_ref().or(unset) + } +} + /// A rules_js hub that reads a pnpm lock of the project. /// /// Hosted mode asks before it routes a patched release through a named -/// registry of pnpm-workspace.yaml, and keeps such a project on the pin -/// that the Bazel legs build, whatever else the call says: with or without -/// `update_pnpm_lock`, and whatever pnpm it runs. +/// registry of pnpm-workspace.yaml. It does where the build of every hub +/// that reads a lock takes a routed lock ([`Self::Takes`]), and keeps the +/// project on the pin with `trustLockfile` everywhere else, where the +/// warning says what kept the hub off the route. +/// +/// Two shapes of a call take one, for a project at the root of the Bazel +/// workspace whose root lock is its one pnpm lock, which the call names in +/// a plain string, and which passes nothing but the attributes those +/// calls had ([`BUILT`]) (measured on Bazel 9.3.2, 8.8.2 and 7.7.2 with +/// rules_js 3.6.0: the build holds the patched bytes, a second build +/// changes no file, and `rollback` brings the upstream build back): /// -/// The lock reader of rules_js is not what holds the route back: it takes -/// a routed lock (measured on macOS: rules_js 3.6.0 on Bazel 9.3.2 builds -/// one, a hub without `update_pnpm_lock`, and the packages it builds hold -/// the patched bytes; so does rules_js 2.9.3 on Bazel 8.8.2). The pnpm of -/// a hub with `update_pnpm_lock` is: it runs in a directory that holds the -/// lock, the `package.json` files and the `data` of the call, so it sees -/// the registries only where the call lists pnpm-workspace.yaml, and -/// without them pnpm 11.28.13 and 12.22.0 reject a routed lock -/// (`ERR_PNPM_MISSING_NAMED_REGISTRY`, measured with -/// `pnpm install --lockfile-only`). It may also be older than the pnpm -/// 11.20 that reads such a lock: rules_js picks a pnpm 10 where the -/// workspace states none. No Bazel leg builds a routed lock with -/// `update_pnpm_lock` yet, and a hub can turn that attribute on at any -/// time, so the answer is the same for every hub that reads the lock. +/// - No `update_pnpm_lock`, or `False`: no pnpm runs, and the lock reader +/// of rules_js builds a routed lock. +/// - `update_pnpm_lock = True`, a `data` that lists the pnpm-workspace.yaml +/// beside the lock, and a pnpm that the root module states as a release +/// of 11.20.0 or later, in a repository of the use of the pnpm extension +/// that every module shares and by no use that is a dev dependency +/// ([`release`]). That pnpm runs in a directory that holds the lock, the +/// `package.json` files and the `data` of the call, reads the registries +/// there, and writes the lock back as it is. Without the file it fails +/// the build (`ERR_PNPM_MISSING_NAMED_REGISTRY`). A pnpm below 11.20 +/// builds the routed lock as long as it does not resolve again; once a +/// `package.json` asks for another package, pnpm 11.19.0 puts the +/// upstream release back and pnpm 10.34.9 fails the build. #[derive(Debug, Clone, PartialEq, Eq)] pub enum Reader { /// The call (`MODULE.bazel:7`) that names one of the locks in a plain /// string, or whose `pnpm_lock` is not written out as one, which may. - /// For a project below the Bazel root the text says that its paths are + /// With what keeps it off the route, as a clause of the warning. For + /// a project below the Bazel root the text says that its paths are /// from that root, here and in [`Self::Unseen`], as the warning of /// [`Hubs::hidden`] does: a run in the project's directory has no file /// of that name beside it. - Call(String), + Call(String, String), + /// Every call that reads a lock was read, and each is in a shape whose + /// build takes a routed lock: the first of them. The workspace file + /// still has to stay where it is, for the `data` that may name it. + Takes(String), /// No such call was read, and the workspace was not read whole: what /// could not be read of it, where a hub may be. A doubt of the reader /// ([`Workspace::doubts`], the doubts of the hub's tags) as `file:line: @@ -164,8 +227,8 @@ pub enum Reader { /// [`Hubs::hidden`] passes over what was not seen, because withholding /// there would take a patch from projects that are patched today. Not /// taking the route costs no patch: the project gets the pin it gets - /// today. So the route is taken only where it is certain that no hub - /// reads a lock. + /// today. So the route is taken only where it is certain which hubs + /// read a lock, also beside a call that takes a routed one. /// /// Certain of the files that were read, that is. On disk those are the /// files of the Bazel workspace the project is in. In memory they are @@ -191,7 +254,7 @@ pub async fn hubs(view: &ProjectView<'_>, root: bool, members: &[String]) -> Hub locks.extend(members.iter().cloned()); let mut hubs = read(view, &locks).await; if !root { - hubs.hidden = None; + (hubs.hidden, hubs.unset) = (None, None); } hubs } @@ -233,12 +296,28 @@ pub async fn hidden(view: &ProjectView<'_>) -> Option { /// root, empty for the root) of the workspace behind `view`. fn answer(view: &dyn Fn(&str) -> Entry, project: &str, locks: &[String]) -> Hubs { let ws = Workspace::read(view); - let hidden = judge(&ws, view, project).map(|detail| RewriteWarning { + let hubs = ws.tags(&extension("npm"), "npm_translate_lock"); + // What the three answers ask for is read once, when the first of them + // does: the pnpm-workspace.yaml beside the lock, and the pnpm of a hub. + let beside = OnceCell::new(); + let beside = || beside.get_or_init(|| view(&below(project, SETTINGS))); + let read: Vec<_> = hubs.calls.iter().map(|_| OnceCell::new()).collect(); + let pnpm = |at: usize| read[at].get_or_init(|| release(&ws, view, hubs.calls[at].call)); + let warning = |detail| RewriteWarning { code: HIDDEN.into(), detail, - }); - let reader = reader(&ws, project, locks); - Hubs { hidden, reader } + }; + let said = |writes| judge(&ws, &beside, project, &hubs, &pnpm, writes).map(warning); + let hidden = said(true); + let unset = match hidden { + Some(_) => None, + None => said(false), + }; + Hubs { + hidden, + unset, + reader: reader(&ws, project, locks, &hubs, &pnpm), + } } /// A path of the project in the directory `project`, from the Bazel root. @@ -283,26 +362,139 @@ fn names(ws: &Workspace, call: &Call) -> Named { } } +/// Whether the `data` of the hub `call` lists `settings`, the +/// pnpm-workspace.yaml beside its lock: `None` where it does, else whether +/// `data` is written out, so that the label is one to add to it. +fn unlisted(ws: &Workspace, call: &Call, settings: &str) -> Option { + let main = |label: &str| ws.label(label).filter(|label| label.repo == Repo::Main); + let listed = |label: &String| main(label).is_some_and(|label| label.path() == settings); + match call.arg("data") { + Some(Value::List(labels)) if labels.iter().any(listed) => None, + Some(Value::List(_)) => Some(true), + None => Some(!call.unpacks()), + _ => Some(false), + } +} + +/// The attributes of the calls that were built with a routed lock +/// ([`Reader`]). Any other can change what the hub makes of the lock. A +/// routed lock has the patched release under another version +/// (`socket-:1.0.0`), so a `patches` entry that is keyed by the +/// package's name and version names no package of it, and rules_js fails +/// the build on such an entry (3.6.0, `npm_translate_lock_helpers.bzl`; +/// measured on Bazel 9.3.2, 8.8.2 and 7.7.2). With `npm_package_lock`, +/// `yarn_lock` or `preupdate` a pnpm writes the lock anew, which no build +/// was run for. +const BUILT: [&str; 5] = ["name", "pnpm_lock", "data", "update_pnpm_lock", "use_pnpm"]; + +/// What keeps the hub `call`, which reads the lock `named`, off the route +/// through named registries, as a clause of the warning: `None` for the +/// two shapes whose build takes a routed lock ([`Reader`]). `several`: the +/// project has other pnpm locks than its root lock. `pnpm`: the pnpm the +/// hub runs ([`release`]). +fn off_route<'a>( + ws: &Workspace, + project: &str, + call: &Call, + named: &Named, + several: bool, + pnpm: &dyn Fn() -> &'a Pnpm, +) -> Option { + let settings = below(project, SETTINGS); + match named { + Named::File(lock) if lock.path() == below(project, LOCK) => {} + Named::File(_) => return Some("the lock it reads is a workspace member's own".into()), + _ => return Some("its `pnpm_lock` is not written out in a plain string".into()), + } + if !project.is_empty() { + return Some("the project is not at the root of the Bazel workspace".into()); + } + // The route records its overrides in every lock of the project, and + // the pnpm of a hub resolves beside the one lock its call names. + if several { + return Some( + "the project has workspace members with pnpm locks of their own, a layout that no \ + routed lock was built with" + .into(), + ); + } + let unbuilt = call.args.iter().find_map(|arg| match &arg.how { + How::Keyword(name) if BUILT.contains(&name.as_str()) => None, + How::Keyword(name) => Some(format!( + "its `{name}` is an attribute that no routed lock was built with" + )), + _ => Some("it passes arguments that are not written out".into()), + }); + if unbuilt.is_some() { + return unbuilt; + } + match call.arg("update_pnpm_lock") { + Some(Value::Name(written)) if written == "False" => return None, + None => return None, + Some(Value::Name(written)) if written == "True" => {} + _ => return Some("its `update_pnpm_lock` is not written out as `True` or `False`".into()), + } + if unlisted(ws, call, &settings).is_some() { + return Some(format!( + "its `data` is not written out as a list of strings that holds `//:{settings}`" + )); + } + let stated = match pnpm() { + Pnpm::Stated(_, version, Some(unshown)) => { + return Some(format!( + "the pnpm it runs for `update_pnpm_lock` is not shown to be the one the root \ + module states (pnpm {version}): {unshown}" + )) + } + // A release in full: a prerelease of 11.20.0 is older than it, and + // a number of fewer parts is none that a build was run with. + Pnpm::Stated(numbers, version, _) if *numbers >= (11, 20, 0) => { + let (major, minor, patch) = numbers; + if *version == format!("{major}.{minor}.{patch}") { + return None; + } + format!(" (pnpm {version}, which is not a release of three numbers)") + } + Pnpm::Stated(_, version, _) => format!(" (pnpm {version})"), + _ => String::new(), + }; + Some(format!( + "the pnpm it runs for `update_pnpm_lock` is not stated as 11.20 or later{stated}" + )) +} + /// [`Hubs::reader`] for the locks `locks` of the project in the directory -/// `project` of the workspace `ws`. -fn reader(ws: &Workspace, project: &str, locks: &[String]) -> Option { - let hubs = ws.tags(&extension("npm"), "npm_translate_lock"); +/// `project` of the workspace `ws`: of its hubs `hubs`, each of which runs +/// the pnpm that `pnpm` gives for its place in that list. +fn reader<'a>( + ws: &Workspace, + project: &str, + locks: &[String], + hubs: &Tags, + pnpm: &dyn Fn(usize) -> &'a Pnpm, +) -> Option { let from = from_root(project); - let call = hubs.calls.iter().find_map(|tag| { - let reads = match names(ws, tag.call) { + let mut takes = None; + for (at, tag) in hubs.calls.iter().enumerate() { + let named = names(ws, tag.call); + let reads = match &named { Named::File(label) => locks .iter() .any(|lock| label.path() == below(project, lock)), Named::Elsewhere => false, Named::Unwritten => true, }; - reads.then(|| Reader::Call(format!("{}:{}{from}", tag.file, tag.call.line))) - }); - if call.is_some() { - return call; + if !reads { + continue; + } + let call = format!("{}:{}{from}", tag.file, tag.call.line); + match off_route(ws, project, tag.call, &named, locks.len() > 1, &|| pnpm(at)) { + Some(why) => return Some(Reader::Call(call, why)), + None => takes = takes.or(Some(Reader::Takes(call))), + } } - // No call that was read reads a lock. That is the answer only where - // every call was read. + // No call that was read keeps the lock off the route. That is the + // answer only where every call was read. let doubt = |doubt: &Doubt| match doubt.line { 0 => format!("{}: {}{from}", doubt.file, doubt.why), line => format!("{}:{line}: {}{from}", doubt.file, doubt.why), @@ -320,6 +512,7 @@ fn reader(ws: &Workspace, project: &str, locks: &[String]) -> Option { Some(Err(unread)) => Some(Reader::Unseen(doubt(unread))), None => None, } + .or(takes) } /// The line on which the file of the older `WORKSPACE` system brings in @@ -358,13 +551,21 @@ fn brings_in_rules_js(legacy: &File) -> Option { } /// The text of [`Hubs::hidden`] for the project in the directory `project` -/// (from the Bazel root, empty for the root) of the workspace `ws`, whose -/// other files are read through `view`. -fn judge(ws: &Workspace, view: &dyn Fn(&str) -> Entry, project: &str) -> Option { +/// (from the Bazel root, empty for the root) of the workspace `ws`: for a +/// run that writes its setting to pnpm-workspace.yaml (`writes`), or for +/// one that is told not to ([`Hubs::unset`]). `beside` reads that file, +/// and `pnpm` the pnpm of a hub, by its place in `hubs` ([`release`]). +fn judge<'a>( + ws: &Workspace, + beside: &dyn Fn() -> &'a Entry, + project: &str, + hubs: &Tags, + pnpm: &dyn Fn(usize) -> &'a Pnpm, + writes: bool, +) -> Option { let (lock, settings) = (below(project, LOCK), below(project, SETTINGS)); - let main = |label: &str| ws.label(label).filter(|label| label.repo == Repo::Main); - let hubs = ws.tags(&extension("npm"), "npm_translate_lock"); - for (file, call) in hubs.calls.iter().map(|tag| (tag.file, tag.call)) { + for (at, tag) in hubs.calls.iter().enumerate() { + let (file, call) = (tag.file, tag.call); let named = match names(ws, call) { Named::File(named) if named.path() == lock => named, _ => continue, @@ -378,15 +579,7 @@ fn judge(ws: &Workspace, view: &dyn Fn(&str) -> Entry, project: &str) -> Option< "its `update_pnpm_lock` is not written out as `True` or `False`", ), }; - let listed = |label: &String| main(label).is_some_and(|label| label.path() == settings); - // `None`: the call lists the file. Else whether its `data` is - // written out, so that the label is one to add to it. - let written = match call.arg("data") { - Some(Value::List(labels)) if labels.iter().any(listed) => None, - Some(Value::List(_)) => Some(true), - None => Some(!call.unpacks()), - _ => Some(false), - }; + let written = unlisted(ws, call, &settings); // What the file needs before a pin in the lock is one the build // takes and an undo leaves standing. let own = format!( @@ -394,13 +587,13 @@ fn judge(ws: &Workspace, view: &dyn Fn(&str) -> Entry, project: &str) -> Option< removes one that holds only what hosted mode writes, and the call would then name a \ missing file)" ); - let (fix, unset) = match view(&settings) { + let (fix, unset) = match beside() { Entry::Absent => (Some(own), false), - Entry::Text(text) => match plan_workspace_trust(Some(&text)) { + Entry::Text(text) => match plan_workspace_trust(Some(text)) { TrustPlan::UserSet(value) => ( Some(format!( - "set `trustLockfile: true` in {settings} (it says `trustLockfile: \ - {value}`, which hosted mode leaves as it is)" + "set `trustLockfile: true` in {settings} or take the line out (it says \ + `trustLockfile: {value}`, which hosted mode leaves as it is)" )), true, ), @@ -411,15 +604,28 @@ fn judge(ws: &Workspace, view: &dyn Fn(&str) -> Entry, project: &str) -> Option< )), true, ), - _ if removed_with_the_pin(&text) => (Some(own), false), - _ => (None, false), + _ if removed_with_the_pin(text) => (Some(own), false), + TrustPlan::AlreadyTrue => (None, false), + _ if writes => (None, false), + // Told not to write to the file, the run leaves it + // without the setting. Said so that it holds for a caller + // that is no command line. + _ => ( + Some(format!( + "let hosted mode write to {settings} (this run was told not to, which \ + is `--no-trust-lockfile-config` on the command line, so it writes \ + neither the setting nor the registries that take its place) or set \ + `trustLockfile: true` there yourself" + )), + true, + ), }, Entry::Unreadable(_) => (None, false), }; if written.is_none() && fix.is_none() { continue; } - let Some(pnpm) = release(ws, view, call) else { + let Some(pnpm) = pnpm(at).may_reject() else { continue; }; // The label of the file beside the lock, in the lock's own package. @@ -506,33 +712,91 @@ fn removed_with_the_pin(text: &str) -> bool { } } -/// The pnpm that the hub `hub` runs, when it may be 11 or later: the newest -/// release a tag of its repository states, or that one is not written out, -/// or the one a release of rules_js picks whose choice is not known (the -/// module docs). `None` when all that is stated is older, and when nothing -/// is and [`picks_an_older_pnpm`]. -fn release(ws: &Workspace, view: &dyn Fn(&str) -> Entry, hub: &Call) -> Option { - let unread = "a pnpm whose release is not written out as a version (it may be 11 or later)"; +/// The pnpm that a hub runs, as far as the workspace states it. +enum Pnpm { + /// The newest release that the tags of its repository state, each of + /// them read as a version: its numbers, and as it is written. And + /// what keeps it from being shown as the pnpm the hub runs in every + /// build, which the route asks for ([`ELSEWHERE`], [`DROPPED`]): none + /// where it is shown. + Stated((u64, u64, u64), String, Option<&'static str>), + /// One that may be 11 or later, in the words of a warning: a release + /// that is not written out, or the one a release of rules_js picks + /// whose choice is not known (the module docs). + May(String), + /// The one rules_js picks where nothing is stated, which is older than + /// 11 ([`picks_an_older_pnpm`]). + Older, +} + +impl Pnpm { + /// The pnpm in the words of a warning, when it may be 11 or later and + /// so reject a pinned lock: `None` for one that is known to be older. + fn may_reject(&self) -> Option { + match self { + Pnpm::Stated((11.., ..), version, _) => Some(format!("pnpm {version}")), + Pnpm::Stated(..) | Pnpm::Older => None, + Pnpm::May(what) => Some(what.clone()), + } + } +} + +/// Why a stated release is not shown to be the pnpm of the hub: its +/// repository may be another than the one the tags make. +const ELSEWHERE: &str = "its repository is not taken from the pnpm extension as every module \ + uses it, or that extension has an isolated use or an `inject_repo`"; + +/// Why a stated release is not the pnpm of the hub in every build: without +/// the tag the hub runs the pnpm that rules_js picks. +const DROPPED: &str = "a use of the pnpm extension with `dev_dependency` states a release for \ + it, and Bazel drops such a use under `--ignore_dev_dependency`"; + +/// The pnpm that the hub `hub` runs ([`Pnpm`]). +fn release(ws: &Workspace, view: &dyn Fn(&str) -> Entry, hub: &Call) -> Pnpm { + let unread = || { + Pnpm::May( + "a pnpm whose release is not written out as a version (it may be 11 or later)".into(), + ) + }; + // Whether `call` names the repository `repo` by position. + let named = |repo: &String, call: &Call| { + let is = |arg: &Arg| arg.how == How::Positional && arg.value == Value::Str(repo.clone()); + call.args.iter().any(is) + }; // Whether a `use_repo` takes the repository `repo` under that very name. let taken = |repo: &String| { let takes = |call: &&Call| call.bind.is_none() && call.callee == "use_repo"; - let named = |arg: &Arg| arg.how == How::Positional && arg.value == Value::Str(repo.clone()); let calls = ws.files.iter().flat_map(|(_, file)| &file.calls); - calls.filter(takes).any(|call| call.args.iter().any(named)) + calls.filter(takes).any(|call| named(repo, call)) }; let repo = match hub.arg("use_pnpm") { None if !hub.unpacks() => "pnpm".to_string(), Some(Value::Str(label)) => match ws.label(label).map(|label| label.repo) { Some(Repo::Apparent(repo)) if taken(&repo) => repo, - _ => return Some(unread.to_string()), + _ => return unread(), }, - _ => return Some(unread.to_string()), + _ => return unread(), }; let tags = ws.tags(&extension("pnpm"), "pnpm"); + // For the route: the repository is one of the shared use, which the + // hub runs by default and a `use_repo` of that use takes by its name. + let handed = |callee: &'static str| { + let calls = tags.handed.iter(); + calls.filter(move |taken| taken.call.callee == callee) + }; + let by_name = |taken: &Tag| taken.isolate == Some(false) && named(&repo, taken.call); + let mut shared = hub.arg("use_pnpm").is_none() || handed("use_repo").any(by_name); + shared &= handed("inject_repo").next().is_none(); + // And no use that is a dev dependency states a release for it: Bazel + // drops the tags of such a use under `--ignore_dev_dependency`. + let mut dropped = false; // Without a tag, the repository `pnpm` is the one rules_js makes. let (mut newest, mut made) = (None::<((u64, u64, u64), String)>, repo == "pnpm"); let mut read = tags.doubts.is_empty(); - for call in tags.calls.iter().map(|tag| tag.call) { + for tag in &tags.calls { + let call = tag.call; + // A tag of an isolated use makes a repository of that use alone. + shared &= tag.isolate == Some(false); match call.arg("name") { None if !call.unpacks() && repo != "pnpm" => continue, Some(Value::Str(name)) if *name != repo => continue, @@ -558,6 +822,7 @@ fn release(ws: &Workspace, view: &dyn Fn(&str) -> Entry, hub: &Call) -> Option None, }; + dropped |= tag.dev_dependency != Some(false); // The numbers of a release: rules_js runs the newest of several. let numbers = |version: &String| { let release = version.split(['-', '+']).next().unwrap_or(version); @@ -574,15 +839,22 @@ fn release(ws: &Workspace, view: &dyn Fn(&str) -> Entry, hub: &Call) -> Option read = false, } } + let unshown = match (shared, dropped) { + (false, _) => Some(ELSEWHERE), + (true, true) => Some(DROPPED), + (true, false) => None, + }; match newest { - Some(((major, ..), version)) if major >= 11 => Some(format!("pnpm {version}")), - _ if !read || !made => Some(unread.to_string()), - Some(_) => None, - None if picks_an_older_pnpm(ws, view) => None, - None => Some( + // A tag that states a release also makes the repository. + Some((numbers, version)) if read => Pnpm::Stated(numbers, version, unshown), + Some(((11.., ..), version)) => Pnpm::May(format!("pnpm {version}")), + Some(_) => unread(), + None if !read || !made => unread(), + None if picks_an_older_pnpm(ws, view) => Pnpm::Older, + None => Pnpm::May( "the pnpm that aspect_rules_js picks itself, at a release of the ruleset whose \ choice is not known here (it may be 11 or later)" - .to_string(), + .into(), ), } } @@ -684,14 +956,24 @@ mod tests { /// The tag that states the pnpm of that build. const ELEVEN: &str = "pnpm.pnpm(name = \"pnpm\", pnpm_version = \"11.28.10\")"; - /// [`judge`] for the project in `project` of the workspace that holds - /// `files` and nothing else. - fn said(files: &[(&str, &str)], project: &str) -> Option { - let view = |path: &str| match files.iter().find(|(name, _)| *name == path) { + /// The files `files`, and nothing else, as a workspace is read. + fn holding<'a>(files: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Entry + 'a { + |path| match files.iter().find(|(name, _)| *name == path) { Some((_, text)) => Entry::Text(text.to_string()), None => Entry::Absent, - }; - judge(&Workspace::read(&view), &view, project) + } + } + + /// The text of [`Hubs::hidden`] for the project in `project` of the + /// workspace that holds `files` and nothing else. + fn said(files: &[(&str, &str)], project: &str) -> Option { + answered(files, project).hidden.map(|hidden| hidden.detail) + } + + /// [`answer`] about the root lock of that project. + fn answered(files: &[(&str, &str)], project: &str) -> Hubs { + let view = holding(files); + answer(&view, project, &[LOCK.to_string()]) } /// [`said`] for the root project of a workspace with `module` and a @@ -765,8 +1047,8 @@ mod tests { // the label alone the next run would still pin nothing. let off = "packages:\n - '.'\ntrustLockfile: false\n"; let said = said_of(&[("MODULE.bazel", &module), (SETTINGS, off)]); - let set = "set `trustLockfile: true` in pnpm-workspace.yaml (it says `trustLockfile: \ - false`, which hosted mode leaves as it is)"; + let set = "set `trustLockfile: true` in pnpm-workspace.yaml or take the line out (it \ + says `trustLockfile: false`, which hosted mode leaves as it is)"; assert_eq!(said, format!("{reason} — {set}, {way_on}")); let flow = said_of(&[("MODULE.bazel", &module), (SETTINGS, "{packages: ['.']}\n")]); let write = " — write `trustLockfile: true` to pnpm-workspace.yaml yourself (hosted \ @@ -824,8 +1106,8 @@ mod tests { pnpm-lock.yaml was not rewritten — " ); let off = with(ELEVEN, Some("# mine\ntrustLockfile: false\n")).expect("withheld"); - let set = "set `trustLockfile: true` in pnpm-workspace.yaml (it says `trustLockfile: \ - false`, which hosted mode leaves as it is) and re-run"; + let set = "set `trustLockfile: true` in pnpm-workspace.yaml or take the line out (it \ + says `trustLockfile: false`, which hosted mode leaves as it is) and re-run"; assert_eq!(off, format!("{unset}{set}")); let flow = with(ELEVEN, Some("{packages: ['.']}\n")).expect("withheld"); let write = "write `trustLockfile: true` to pnpm-workspace.yaml yourself (hosted mode \ @@ -1279,47 +1561,548 @@ mod tests { assert_eq!(hub("//:pnpm-lock.yaml", ""), None, "the lock of the root"); } - /// [`Hubs::reader`] names the call of a hub that reads one of the locks - /// asked about, whatever else the call says, and a call whose lock is - /// not written out, which may be one of them. A hub that reads another - /// lock, another repository's, or no hub at all is no reader. + /// [`Hubs::reader`] for the locks `locks` of the project in `project` + /// of the workspace whose root module has the hub `hub` and the lines + /// `pnpm`, beside a `pnpm-workspace.yaml` of the user's own. + fn reads(hub: &str, pnpm: &str, project: &str, locks: &[&str]) -> Option { + let module = module(hub, pnpm); + let settings = below(project, SETTINGS); + let files = [("MODULE.bazel", module.as_str()), (&settings, "# own\n")]; + let view = holding(&files); + let locks: Vec = locks.iter().map(|lock| lock.to_string()).collect(); + answer(&view, project, &locks).reader + } + + /// The hub of a build that takes a routed lock with a pnpm of its own: + /// it keeps the root lock up to date and lists the workspace file. + const LISTING: &str = "pnpm_lock = \"//:pnpm-lock.yaml\", update_pnpm_lock = True, \ + data = [\"//:pnpm-workspace.yaml\"]"; + /// The arguments of a `use_extension` of the pnpm extension. + const PNPM_EXTENSION: &str = "\"@aspect_rules_js//npm:extensions.bzl\", \"pnpm\""; + + /// The two shapes of a hub whose build takes a routed lock + /// ([`Reader::Takes`]): one that runs no pnpm, and one whose pnpm sees + /// the workspace file and is stated as 11.20 or later, in each way a + /// release is read as written out. Another repository's lock, another + /// project's and a workspace with no hub have no reader at all. #[test] - fn a_hub_reads_the_lock_it_names_whatever_else_it_says() { - let reads = |hub: &str, project: &str, locks: &[&str]| { - let module = module(hub, ELEVEN); - let view = |path: &str| match path { - "MODULE.bazel" => Entry::Text(module.clone()), - _ => Entry::Absent, - }; - let locks: Vec = locks.iter().map(|lock| lock.to_string()).collect(); - answer(&view, project, &locks).reader + fn a_hub_takes_a_routed_lock_in_the_two_shapes_that_were_built() { + let takes = Some(Reader::Takes("MODULE.bazel:4".to_string())); + let off = format!("{LOCKED}, update_pnpm_lock = False"); + let unlisted_off = format!("{LOCKED}, data = DATA"); + let named_hub = format!("name = \"npm\", {LOCKED}"); + for hub in [LOCKED, off.as_str(), unlisted_off.as_str(), &named_hub] { + // No pnpm runs, whatever the workspace states of one. + for pnpm in ["", ELEVEN, "pnpm.pnpm(pnpm_version = \"10.34.9\")"] { + assert_eq!(reads(hub, pnpm, "", &[LOCK]), takes, "{hub}: {pnpm}"); + } + } + let by_label = format!("{LISTING}, use_pnpm = \"@eleven//:package/bin/pnpm.cjs\""); + let named = "pnpm.pnpm(name = \"eleven\", pnpm_version = \"11.28.10\")\n\ + use_repo(pnpm, \"eleven\")"; + for (hub, pnpm) in [ + (LISTING, ELEVEN), + (LISTING, "pnpm.pnpm(pnpm_version = \"11.20.0\")"), + (LISTING, "pnpm.pnpm(pnpm_version = \"12.17.0\")"), + // The newest of two is the one rules_js runs. + ( + LISTING, + "pnpm.pnpm(pnpm_version = \"10.34.9\")\npnpm.pnpm(pnpm_version = \"11.20.0\")", + ), + (by_label.as_str(), named), + // A use that says it is not isolated is the one every module + // shares, as Bazel takes it. + ( + by_label.as_str(), + &format!( + "same = use_extension({PNPM_EXTENSION}, isolate = False)\n\ + same.pnpm(name = \"eleven\", pnpm_version = \"11.28.10\")\n\ + use_repo(same, \"eleven\")" + ), + ), + ] { + assert_eq!(reads(hub, pnpm, "", &[LOCK]), takes, "{hub}: {pnpm}"); + } + // By the `packageManager` of the file the tag names. + let from = module( + LISTING, + "pnpm.pnpm(pnpm_version_from = \"//:package.json\")", + ); + let pinned = |pin: &str| { + let manifest = format!("{{\"packageManager\": \"{pin}\"}}"); + let files = [ + ("MODULE.bazel", from.as_str()), + ("package.json", manifest.as_str()), + (SETTINGS, "# own\n"), + ]; + answered(&files, "").reader }; - let call = Some(Reader::Call("MODULE.bazel:4".to_string())); - let listed = format!("{HUB}, data = [\"//:pnpm-workspace.yaml\"]"); - for hub in [LOCKED, HUB, listed.as_str(), "pnpm_lock = LOCK", "**hub"] { - assert_eq!(reads(hub, "", &[LOCK]), call, "{hub}"); + assert_eq!(pinned("pnpm@11.28.10+sha512.abc"), takes); + assert!(matches!( + pinned("pnpm@11.19.0"), + Some(Reader::Call(_, why)) if why.ends_with("(pnpm 11.19.0)") + )); + + // No reader: the lock of another repository, of another project, + // of a member that was not asked about, and no hub. + let member = "pnpm_lock = \"//packages/a:pnpm-lock.yaml\""; + for (hub, project) in [ + ("pnpm_lock = \"@other//:pnpm-lock.yaml\"", ""), + (LOCKED, "packages/a"), + (member, ""), + ] { + assert_eq!(reads(hub, ELEVEN, project, &[LOCK]), None, "{hub}"); } - // The lock of a member, and a project below the Bazel root. + let none = |_: &str| Entry::Absent; + assert_eq!(answer(&none, "", &[LOCK.to_string()]), Hubs::default()); + } + + /// Every other hub that reads a lock keeps it off the route, and + /// [`Reader::Call`] says what did, after the place of the call: what + /// is not written out, a pnpm that is not stated as 11.20 or later, a + /// `data` without the workspace file, the lock of a member, and a + /// project below the root of the Bazel workspace, whose text also says + /// where its paths are from. One such call is enough beside one that + /// takes a routed lock. + #[test] + fn what_keeps_a_hub_off_the_route_is_named() { + let unlisted = "its `data` is not written out as a list of strings that holds \ + `//:pnpm-workspace.yaml`"; + let unstated = "the pnpm it runs for `update_pnpm_lock` is not stated as 11.20 or later"; + let other = format!("{HUB}, data = [\"//web:pnpm-workspace.yaml\"]"); + let named = format!("{LISTING}, use_pnpm = \"@eleven//:package/bin/pnpm.cjs\""); + let cases = [ + ( + "pnpm_lock = LOCK", + ELEVEN, + "its `pnpm_lock` is not written out in a plain string", + ), + ( + "**hub", + ELEVEN, + "its `pnpm_lock` is not written out in a plain string", + ), + ( + "pnpm_lock = \"//:pnpm-lock.yaml\", update_pnpm_lock = UP", + ELEVEN, + "its `update_pnpm_lock` is not written out as `True` or `False`", + ), + // A `**` may pass any attribute, also beside one that is off. + ( + "pnpm_lock = \"//:pnpm-lock.yaml\", **MORE", + ELEVEN, + "it passes arguments that are not written out", + ), + ( + "pnpm_lock = \"//:pnpm-lock.yaml\", update_pnpm_lock = False, **MORE", + ELEVEN, + "it passes arguments that are not written out", + ), + (HUB, ELEVEN, unlisted), + (other.as_str(), ELEVEN, unlisted), + ( + "pnpm_lock = \"//:pnpm-lock.yaml\", update_pnpm_lock = True, data = DATA", + ELEVEN, + unlisted, + ), + (LISTING, "", unstated), + (LISTING, "pnpm.pnpm(pnpm_version = \"latest\")", unstated), + ( + LISTING, + "pnpm.pnpm(pnpm_version_from = \"//:package.json\")", + unstated, + ), + // A tag whose release is not read may ask for any. + ( + LISTING, + "pnpm.pnpm(pnpm_version = \"11.28.10\")\npnpm.pnpm(pnpm_version = PNPM)", + unstated, + ), + // The repository is the one of the tag `pnpm`, under a name + // the reader does not follow. + ( + named.as_str(), + "pnpm.pnpm(pnpm_version = \"11.28.10\")\nuse_repo(pnpm, eleven = \"pnpm\")", + unstated, + ), + ]; + for (hub, pnpm, why) in cases { + let call = Reader::Call("MODULE.bazel:4".to_string(), why.to_string()); + assert_eq!(reads(hub, pnpm, "", &[LOCK]), Some(call), "{hub}: {pnpm}"); + } + // A release in full, 11.20.0 or later: a prerelease of it is older, + // and a number of fewer parts is none that a build was run with. + let short = "which is not a release of three numbers"; + for (release, said) in [ + ("11.19.0", "11.19.0".to_string()), + ("10.34.9", "10.34.9".to_string()), + ("11", "11".to_string()), + ("11.20", format!("11.20, {short}")), + ("12", format!("12, {short}")), + ("11.20.0-rc.1", format!("11.20.0-rc.1, {short}")), + ("12.0.0-alpha.3", format!("12.0.0-alpha.3, {short}")), + ] { + let pnpm = format!("pnpm.pnpm(pnpm_version = \"{release}\")"); + let why = format!("{unstated} (pnpm {said})"); + let call = Reader::Call("MODULE.bazel:4".to_string(), why); + assert_eq!(reads(LISTING, &pnpm, "", &[LOCK]), Some(call), "{release}"); + } + + // What else a call says: only the attributes of the calls that + // were built keep a hub on the route, whether it runs a pnpm or + // not. A `patches` that is keyed by a version names no package of + // a routed lock, and the other three have a pnpm write the lock. + let patches = "patches = {\"left-pad@1.3.0\": [\"//:own.patch\"]}"; + for (more, name) in [ + (patches, "patches"), + ( + "npm_package_lock = \"//:package-lock.json\"", + "npm_package_lock", + ), + ("yarn_lock = \"//:yarn.lock\"", "yarn_lock"), + ("preupdate = [\"//:fix.js\"]", "preupdate"), + ("npmrc = \"//:.npmrc\"", "npmrc"), + ("bins = {\"left-pad@1.3.0\": [\"pad=./bin.js\"]}", "bins"), + ] { + let why = format!("its `{name}` is an attribute that no routed lock was built with"); + for hub in [LOCKED, LISTING] { + let call = Reader::Call("MODULE.bazel:4".to_string(), why.clone()); + let hub = format!("{hub}, {more}"); + assert_eq!(reads(&hub, ELEVEN, "", &[LOCK]), Some(call), "{hub}"); + } + } + // The warning names every attribute that was built. + let call = Reader::Call("MODULE.bazel:4".to_string(), String::new()); + let reason = crate::hosted::guidance::pnpm_registry_bazel_reason(&call).expect("a clause"); + for name in BUILT { + assert!(reason.contains(&format!("`{name}`")), "{name}: {reason}"); + } + + // The pnpm a tag states is the one the hub runs only where its + // repository is one of the use of the pnpm extension that every + // module shares. A repository of another extension under the name + // of a tag, an isolated use with tags of its own and an + // `inject_repo` on the extension keep the hub off the route. + let unshown = "the pnpm it runs for `update_pnpm_lock` is not shown to be the one the \ + root module states (pnpm 11.28.10): its repository is not taken from the \ + pnpm extension as every module uses it, or that extension has an isolated \ + use or an `inject_repo`"; + let by_label = + |repo: &str| format!("{LISTING}, use_pnpm = \"@{repo}//:package/bin/pnpm.cjs\""); + let other = "other = use_extension(\"//:ext.bzl\", \"other\")"; + let isolated = format!("iso = use_extension({PNPM_EXTENSION}, isolate = True)"); + for (case, hub, pnpm) in [ + ( + "another extension's `pnpm`", + by_label("pnpm"), + format!("{ELEVEN}\n{other}\nuse_repo(other, \"pnpm\")"), + ), + ( + "another extension's repository under the name of a tag", + by_label("eleven"), + format!( + "pnpm.pnpm(name = \"eleven\", pnpm_version = \"11.28.10\")\n{other}\n\ + use_repo(other, \"eleven\")" + ), + ), + // Only a name of a proxy is followed, and an `isolate` that is + // not written out as `False` counts as an isolated use. + ( + "the use of the extension as it stands", + by_label("eleven"), + format!( + "pnpm.pnpm(name = \"eleven\", pnpm_version = \"11.28.10\")\n\ + use_repo(use_extension({PNPM_EXTENSION}), \"eleven\")" + ), + ), + ( + "a use that may be isolated", + by_label("eleven"), + format!( + "same = use_extension({PNPM_EXTENSION}, isolate = ISOLATE)\n\ + same.pnpm(name = \"eleven\", pnpm_version = \"11.28.10\")\n\ + use_repo(same, \"eleven\")" + ), + ), + ( + "a tag of an isolated use", + LISTING.to_string(), + format!("{isolated}\niso.pnpm(pnpm_version = \"11.28.10\")"), + ), + ( + "a repository of an isolated use", + by_label("pnpm"), + format!( + "{isolated}\niso.pnpm(pnpm_version = \"11.28.10\")\nuse_repo(iso, \"pnpm\")" + ), + ), + ( + "a repository that only an isolated use takes", + by_label("eleven"), + format!( + "pnpm.pnpm(name = \"eleven\", pnpm_version = \"11.28.10\")\n{isolated}\n\ + use_repo(iso, \"eleven\")" + ), + ), + ( + "a repository that is injected", + LISTING.to_string(), + format!("{ELEVEN}\ninject_repo(pnpm, \"tools\")"), + ), + ] { + let call = Reader::Call("MODULE.bazel:4".to_string(), unshown.to_string()); + assert_eq!(reads(&hub, &pnpm, "", &[LOCK]), Some(call), "{case}"); + } + // An `override_repo` on the extension leaves its release unread. + let overridden = format!("{ELEVEN}\noverride_repo(pnpm, pnpm = \"mine\")"); + let call = Reader::Call("MODULE.bazel:4".to_string(), unstated.to_string()); + assert_eq!(reads(LISTING, &overridden, "", &[LOCK]), Some(call)); + // None of this changes what a pin is withheld for: the pnpm 11 of + // each is one that may reject it, as before. + for pnpm in [ + format!("{ELEVEN}\n{other}\nuse_repo(other, \"pnpm\")"), + format!("{isolated}\niso.pnpm(pnpm_version = \"11.28.10\")"), + ] { + let said = root(HUB, &pnpm).expect("withheld"); + assert!( + said.contains("has Bazel run pnpm 11.28.10 to keep"), + "{said}" + ); + } + + // Nor does a release that a use of the extension states as a dev + // dependency count: under `--ignore_dev_dependency` Bazel drops + // the tag, and the hub runs the pnpm that rules_js picks. Written + // as `True` or not written out, on the one use or beside a use + // that every build has. + let dropped = "the pnpm it runs for `update_pnpm_lock` is not shown to be the one the \ + root module states (pnpm 11.28.10): a use of the pnpm extension with \ + `dev_dependency` states a release for it, and Bazel drops such a use \ + under `--ignore_dev_dependency`"; + let dev = |how: &str| { + format!( + "dev = use_extension({PNPM_EXTENSION}, dev_dependency = {how})\n\ + dev.pnpm(pnpm_version = \"11.28.10\")" + ) + }; + let on_the_one_use = module(LISTING, ELEVEN).replace( + &format!("pnpm = use_extension({PNPM_EXTENSION})"), + &format!("pnpm = use_extension({PNPM_EXTENSION}, dev_dependency = True)"), + ); + assert_ne!(on_the_one_use, module(LISTING, ELEVEN)); + let files = [ + ("MODULE.bazel", on_the_one_use.as_str()), + (SETTINGS, "# own\n"), + ]; + let call = Reader::Call("MODULE.bazel:4".to_string(), dropped.to_string()); + assert_eq!(answered(&files, "").reader, Some(call.clone())); + for (case, pnpm) in [ + ("a dev dependency", dev("True")), + ("one that may be", dev("DEV")), + ( + "beside a use that every build has", + format!("pnpm.pnpm(pnpm_version = \"11.20.0\")\n{}", dev("True")), + ), + ] { + assert_eq!( + reads(LISTING, &pnpm, "", &[LOCK]), + Some(call.clone()), + "{case}" + ); + // A hub that runs no pnpm is routed whatever a tag states, and + // the pin is withheld for such a release as it was. + assert!( + matches!(reads(LOCKED, &pnpm, "", &[LOCK]), Some(Reader::Takes(_))), + "{case}" + ); + let said = root(HUB, &pnpm).expect("withheld"); + assert!( + said.contains("has Bazel run pnpm 11.28.10 to keep"), + "{case}: {said}" + ); + } + // A use that says it is none, and a dev tag that states no release + // or makes another repository, change nothing. + for pnpm in [ + dev("False"), + format!( + "{ELEVEN}\ndev = use_extension({PNPM_EXTENSION}, dev_dependency = True)\n\ + dev.pnpm(name = \"pnpm\")\ndev.pnpm(name = \"ten\", pnpm_version = \"10.34.9\")" + ), + ] { + assert!( + matches!(reads(LISTING, &pnpm, "", &[LOCK]), Some(Reader::Takes(_))), + "{pnpm}" + ); + } + + // The lock of a member, by a hub that runs no pnpm. let member = "pnpm_lock = \"//packages/a:pnpm-lock.yaml\""; - assert_eq!(reads(member, "", &[LOCK]), None); - assert_eq!( - reads(member, "", &[LOCK, "packages/a/pnpm-lock.yaml"]), - call + let own = Reader::Call( + "MODULE.bazel:4".to_string(), + "the lock it reads is a workspace member's own".to_string(), + ); + let locks = [LOCK, "packages/a/pnpm-lock.yaml"]; + assert_eq!(reads(member, ELEVEN, "", &locks), Some(own)); + // The root lock, beside the members' own + // (`sharedWorkspaceLockfile: false`): the route records its + // overrides in every lock, and no build was run of a hub that reads + // one of several. Whichever of the two shapes the call is in. + let several = Reader::Call( + "MODULE.bazel:4".to_string(), + "the project has workspace members with pnpm locks of their own, a layout that no \ + routed lock was built with" + .to_string(), + ); + for hub in [LOCKED, LISTING] { + assert_eq!( + reads(hub, ELEVEN, "", &locks), + Some(several.clone()), + "{hub}" + ); + } + // A project below the Bazel root: its call is in a file of that + // root, not of the project. + let below_root = Reader::Call( + "MODULE.bazel:4, with paths from the root of the Bazel workspace".to_string(), + "the project is not at the root of the Bazel workspace".to_string(), ); - // Its call is in a file of the Bazel root, not of the project. - let from_root = "MODULE.bazel:4, with paths from the root of the Bazel workspace"; assert_eq!( - reads(member, "packages/a", &[LOCK]), - Some(Reader::Call(from_root.to_string())) + reads(member, ELEVEN, "packages/a", &[LOCK]), + Some(below_root) ); - assert_eq!(reads(LOCKED, "packages/a", &[LOCK]), None); - // Another repository's lock, and a workspace with no hub. + + // Two hubs of the one lock: the one that is off the route decides, + // whichever comes first. + let two = |first: &str, second: &str| { + let module = module(first, ELEVEN); + let module = format!("{module}npm.npm_translate_lock({second})\n"); + answered(&[("MODULE.bazel", &module), (SETTINGS, "# own\n")], "").reader + }; + assert!(matches!(two(LOCKED, LOCKED), Some(Reader::Takes(_)))); + for (first, second, line) in [(LOCKED, HUB, 7), (HUB, LOCKED, 4)] { + let call = Reader::Call(format!("MODULE.bazel:{line}"), unlisted.to_string()); + assert_eq!(two(first, second), Some(call), "{first}"); + } + } + + /// A run that is told not to write to `pnpm-workspace.yaml` gives the + /// pnpm of a hub no setting to read ([`Hubs::unset`]). Where a hub + /// lists a file of the user's own that would take the setting, such a + /// run is told to write nothing for the root lock, and what to do; a + /// run that writes the setting is told nothing. A file that holds the + /// setting already, a pnpm 10 and a hub that runs no pnpm withhold + /// nothing from either, and a hub that hides the file withholds from + /// both alike. + #[test] + fn a_run_told_not_to_write_the_setting_leaves_the_lock_of_a_listing_hub() { + let asked = |hub: &str, pnpm: &str, settings: &str| { + let module = module(hub, pnpm); + answered(&[("MODULE.bazel", &module), (SETTINGS, settings)], "") + }; + let hubs = asked(LISTING, ELEVEN, "# own\n"); + assert_eq!(hubs.hidden, None); + assert_eq!(hubs.hides(true), None); + let unset = hubs.hides(false).expect("withheld"); + assert_eq!(unset.code, HIDDEN); assert_eq!( - reads("pnpm_lock = \"@other//:pnpm-lock.yaml\"", "", &[LOCK]), - None + unset.detail, + "MODULE.bazel:4: this `npm.npm_translate_lock` has Bazel run pnpm 11.28.10 to keep \ + pnpm-lock.yaml up to date (`update_pnpm_lock`), and hosted mode does not write \ + `trustLockfile: true` to the pnpm-workspace.yaml that its `data` lists. Without \ + that setting pnpm 11 and later reject a lock that names the patch server \ + (ERR_PNPM_TARBALL_URL_MISMATCH): `bazel build` would fail; pnpm-lock.yaml was not \ + rewritten — let hosted mode write to pnpm-workspace.yaml (this run was told not \ + to, which is `--no-trust-lockfile-config` on the command line, so it writes \ + neither the setting nor the registries that take its place) or set \ + `trustLockfile: true` there yourself and re-run" ); - let none = |_: &str| Entry::Absent; - assert_eq!(answer(&none, "", &[LOCK.to_string()]), Hubs::default()); + // The hub still takes a routed lock: a run that writes is routed. + assert!(matches!(hubs.reader, Some(Reader::Takes(_)))); + + let ten = "pnpm.pnpm(pnpm_version = \"10.34.9\")"; + for (case, hub, pnpm, settings) in [ + ( + "the setting is there", + LISTING, + ELEVEN, + "# own\ntrustLockfile: true\n", + ), + ("pnpm 10", LISTING, ten, "# own\n"), + ("the pnpm rules_js picks", LISTING, "", "# own\n"), + ("no pnpm runs", LOCKED, ELEVEN, "# own\n"), + ] { + let hubs = asked(hub, pnpm, settings); + assert_eq!( + (hubs.hides(true), hubs.hides(false)), + (None, None), + "{case}" + ); + } + // Hidden from the pnpm of the hub: the one warning for both runs. + for (hub, settings) in [(HUB, "# own\n"), (LISTING, "trustLockfile: false\n")] { + let hubs = asked(hub, ELEVEN, settings); + assert!(hubs.hidden.is_some() && hubs.unset.is_none(), "{hub}"); + assert_eq!(hubs.hides(false), hubs.hidden.as_ref(), "{hub}"); + } + // Two hubs of the one lock. The first that leaves the file without + // the setting is the answer for the run that is told not to write, + // and a later one that hides the file is the answer for both. + let two = |second: &str| { + let module = module(LISTING, ELEVEN); + let module = format!("{module}npm.npm_translate_lock({second})\n"); + answered(&[("MODULE.bazel", &module), (SETTINGS, "# own\n")], "") + }; + let both = two(LISTING); + assert_eq!(both.hidden, None); + let first = both.unset.expect("withheld").detail; + assert!(first.starts_with("MODULE.bazel:4: "), "{first}"); + let hiding = two(HUB); + let hidden = hiding.hidden.expect("withheld").detail; + assert!(hidden.starts_with("MODULE.bazel:7: "), "{hidden}"); + assert_eq!(hiding.unset, None); + } + + /// One answer asks for each file once, whichever of its three parts + /// needs it: the `pnpm-workspace.yaml` beside the lock, the + /// `package.json` that a tag takes its release from, and + /// `MODULE.bazel.lock`, which says what rules_js picks where no tag + /// states a release and can be several MiB. + #[test] + fn one_answer_asks_for_each_file_once() { + let from = "pnpm.pnpm(pnpm_version_from = \"//:package.json\")"; + let eleven = "{\"packageManager\": \"pnpm@11.28.10\"}"; + for (pnpm, manifest, want) in [(from, eleven, [1, 1, 0]), ("", "{}", [1, 0, 1])] { + let module = module(LISTING, pnpm); + let files = [ + ("MODULE.bazel", module.as_str()), + (SETTINGS, "# own\n"), + ("package.json", manifest), + ("MODULE.bazel.lock", "{}"), + ]; + let (held, asked) = (holding(&files), std::cell::RefCell::new(Vec::new())); + let view = |path: &str| { + asked.borrow_mut().push(path.to_string()); + held(path) + }; + let hubs = answer(&view, "", &[LOCK.to_string()]); + // Every part was asked: the pin of a run that writes the + // setting, the one of a run that does not, and the route. + assert_eq!(hubs.hidden, None, "{pnpm}"); + assert_eq!(hubs.unset.is_some(), !pnpm.is_empty(), "{pnpm}"); + assert_eq!( + matches!(hubs.reader, Some(Reader::Takes(_))), + !pnpm.is_empty(), + "{pnpm}" + ); + let asked = asked.borrow(); + let times = |file: &str| asked.iter().filter(|path| *path == file).count(); + assert_eq!( + [SETTINGS, "package.json", "MODULE.bazel.lock"].map(times), + want, + "{pnpm}: {asked:?}" + ); + } } /// Where no call that was read reads the lock, the answer is "no hub @@ -1356,7 +2139,8 @@ mod tests { what.starts_with("tools/npm.MODULE.bazel: ") && what.contains("MODULE.bazel:7"), "{what}" ); - // The same file, there: read, and its hub is the reader. + // The same file, there: read, and its hub is the reader, in a + // shape that takes a routed lock. let hub = "npm = use_extension(\"@aspect_rules_js//npm:extensions.bzl\", \"npm\")\n\ npm.npm_translate_lock(pnpm_lock = \"//:pnpm-lock.yaml\")\n"; assert_eq!( @@ -1364,8 +2148,17 @@ mod tests { ("MODULE.bazel", &including), ("tools/npm.MODULE.bazel", hub) ]), - Some(Reader::Call("tools/npm.MODULE.bazel:2".to_string())) + Some(Reader::Takes("tools/npm.MODULE.bazel:2".to_string())) ); + // Beside a call that takes a routed lock, what was not read still + // counts: a hub in it may read the lock in another shape. + let taking = module(LOCKED, ELEVEN); + let beside = format!("{taking}include(\"//tools:npm.MODULE.bazel\")\n"); + let what = unseen(&[("MODULE.bazel", &beside)]); + assert!(what.starts_with("tools/npm.MODULE.bazel: "), "{what}"); + let rule = "npm_translate_lock(name = \"npm\", pnpm_lock = \"//:pnpm-lock.yaml\")\n"; + let what = unseen(&[("MODULE.bazel", &taking), ("WORKSPACE", rule)]); + assert!(what.starts_with("WORKSPACE:1: it brings in"), "{what}"); // A proxy of the extension that is not only called. let handed = format!("{elsewhere}register(npm)\n"); let what = unseen(&[("MODULE.bazel", &handed)]); @@ -1434,10 +2227,10 @@ mod tests { ); // A lock that is no label may be any. let odd = module("pnpm_lock = \"//:a:b\"", ELEVEN); - assert_eq!( + assert!(matches!( reader(&[("MODULE.bazel", &odd)]), - Some(Reader::Call("MODULE.bazel:4".to_string())) - ); + Some(Reader::Call(call, _)) if call == "MODULE.bazel:4" + )); } /// A checkout and a project in memory with the same files get the same @@ -1468,17 +2261,31 @@ mod tests { assert_eq!(hidden(&ProjectView::Memory(&project)).await, Some(on_disk)); // One read answers both questions, on disk and in memory alike. let disk = hubs(&ProjectView::Disk(dir.path()), true, &[]).await; - assert_eq!( - disk.reader, - Some(Reader::Call("MODULE.bazel:4".to_string())) - ); + assert!(matches!( + &disk.reader, + Some(Reader::Call(call, _)) if call == "MODULE.bazel:4" + )); assert_eq!(disk.hidden, hidden(&ProjectView::Disk(dir.path())).await); assert_eq!(hubs(&ProjectView::Memory(&project), true, &[]).await, disk); // No root lock: nothing to keep out of a run, and the call is - // still the reader of a member's lock. No pnpm lock: nothing asked. + // still the reader of a member's lock, which a hub of the root lock + // keeps off the route. No pnpm lock: nothing asked. let member = ["packages/a/pnpm-lock.yaml".to_string()]; let lockless = hubs(&ProjectView::Memory(&project), false, &member).await; - assert_eq!((lockless.hidden, lockless.reader), (None, disk.reader)); + assert_eq!(lockless.hidden, None); + assert!(matches!( + &lockless.reader, + Some(Reader::Call(call, why)) + if call == "MODULE.bazel:4" && why.starts_with("the project has workspace members") + )); + // The same of a run that is told not to write the setting. + let listing = self::module(LISTING, ELEVEN); + for (name, text) in [("MODULE.bazel", listing.as_str()), (SETTINGS, "# own\n")] { + project.insert_text(name, text); + } + let view = ProjectView::Memory(&project); + assert!(hubs(&view, true, &member).await.hides(false).is_some()); + assert_eq!(hubs(&view, false, &member).await.hides(false), None); let none = hubs(&ProjectView::Memory(&project), false, &[]).await; assert_eq!(none, Hubs::default()); } diff --git a/crates/socket-patch-core/src/bazel/workspace.rs b/crates/socket-patch-core/src/bazel/workspace.rs index 292811c2e..dd54c5f69 100644 --- a/crates/socket-patch-core/src/bazel/workspace.rs +++ b/crates/socket-patch-core/src/bazel/workspace.rs @@ -258,12 +258,21 @@ pub struct Tag<'a> { /// file included with `dev_dependency`, which 9.3.2 takes, is not /// read at all. pub dev_dependency: Option, + /// Whether that proxy was made with `isolate = True`: such a use has + /// tags and repositories of its own, apart from the use of the + /// extension that every module shares. `None` when that argument is + /// not written as `True` or `False`. + pub isolate: Option, } /// The calls of one tag of one extension in a workspace. #[derive(Debug, Default, PartialEq, Eq)] pub struct Tags<'a> { pub calls: Vec>, + /// The `use_repo` and `inject_repo` calls that take a proxy of the + /// extension, by its name, as their first argument: each as a tag is, + /// with the use its proxy was made by. + pub handed: Vec>, /// Why there may be other calls of this extension than these, beyond /// what [`Workspace::doubts`] says of every answer. Empty: the /// extension's proxies are only ever called and handed to `use_repo` @@ -303,7 +312,7 @@ pub struct Workspace { /// The module behind each repository name a `bazel_dep` gives. deps: BTreeMap, /// What [`handed`] finds in each of `files`. - handed: Vec>, + handed: Vec>, } /// The functions a proxy may be handed to. `override_repo` is none: it @@ -317,15 +326,17 @@ const TAKE_A_PROXY: [&str; 2] = ["use_repo", "inject_repo"]; const PREDECLARED: [&str; 4] = ["bazel_dep", "include", "module", "use_extension"]; /// The bytes of the first argument of each `use_repo` and `inject_repo` -/// of `file`. To be the whole of one is the one use of a proxy, besides -/// calling a tag on it, that is read. -fn handed(file: &File) -> BTreeSet<(usize, usize)> { - let takes = |call: &&Call| call.bind.is_none() && TAKE_A_PROXY.contains(&call.callee.as_str()); - let first = |call: &Call| { +/// of `file`, with the call: an index into [`File::calls`]. To be the +/// whole of one is the one use of a proxy, besides calling a tag on it, +/// that is read. +fn handed(file: &File) -> BTreeMap<(usize, usize), usize> { + let takes = |call: &Call| call.bind.is_none() && TAKE_A_PROXY.contains(&call.callee.as_str()); + let first = |(at, call): (usize, &Call)| { let first = call.args.first().filter(|arg| arg.how == How::Positional); - first.map(|arg| (arg.span.start, arg.span.end)) + let first = first.filter(|_| takes(call)); + first.map(|arg| ((arg.span.start, arg.span.end), at)) }; - file.calls.iter().filter(takes).filter_map(first).collect() + file.calls.iter().enumerate().filter_map(first).collect() } fn string(value: Option<&Value>) -> Option<&str> { @@ -485,7 +496,7 @@ impl Workspace { // The proxy gets a name, goes to `use_repo`, or is dropped. "use_extension" => { let span = (call.span.start, call.span.end); - let placed = call.whole || handed.contains(&span); + let placed = call.whole || handed.contains_key(&span); placed && extension(call).is_some() } // Bazel takes none here, and what it binds is not followed. @@ -601,19 +612,19 @@ impl Workspace { let mut tags = Tags::default(); for ((path, file), handed) in self.files.iter().zip(&self.handed) { // The `use_extension` calls that ask for the extension, and - // whether each makes a dev dependency. Each call is looked at - // once, however many names it has. + // whether each makes a dev dependency and an isolated use. Each + // call is looked at once, however many names it has. let mut asked = BTreeMap::new(); for (at, call) in file.calls.iter().enumerate() { let asks = call.bind.is_none() && call.callee == "use_extension"; if asks && self.asks_for(call, extension) { - let dev = match call.arg("dev_dependency") { + let said = |name| match call.arg(name) { None => Some(false), - Some(Value::Name(dev)) if dev == "True" => Some(true), - Some(Value::Name(dev)) if dev == "False" => Some(false), + Some(Value::Name(said)) if said == "True" => Some(true), + Some(Value::Name(said)) if said == "False" => Some(false), Some(_) => None, }; - asked.insert(at, dev); + asked.insert(at, (said("dev_dependency"), said("isolate"))); } } if asked.is_empty() { @@ -623,9 +634,15 @@ impl Workspace { let mut proxies = BTreeMap::new(); for (at, bind) in file.binds.iter().enumerate() { if let Bound::Call(call) = bind.to { - proxies.extend(asked.get(&call).map(|dev| (at, *dev))); + proxies.extend(asked.get(&call).map(|said| (at, *said))); } } + let of = |call, (dev_dependency, isolate)| Tag { + file: path, + call, + dev_dependency, + isolate, + }; let mut doubt = |line, why: String| { if tags.doubts.len() < MAX_DOUBTS { let file = path.clone(); @@ -633,22 +650,23 @@ impl Workspace { } }; for used in &file.uses { - let proxy = used.bind.is_some_and(|bind| proxies.contains_key(&bind)); - if proxy && !handed.contains(&(used.at, used.at + used.name.len())) { - let why = format!("`{}` is used other than to call a tag", used.name); - doubt(used.line, why); + let Some(said) = used.bind.and_then(|bind| proxies.get(&bind)) else { + continue; + }; + match handed.get(&(used.at, used.at + used.name.len())) { + Some(call) => tags.handed.push(of(&file.calls[*call], *said)), + None => { + let why = format!("`{}` is used other than to call a tag", used.name); + doubt(used.line, why); + } } } for call in &file.calls { - let Some(dev) = call.bind.and_then(|bind| proxies.get(&bind)) else { + let Some(said) = call.bind.and_then(|bind| proxies.get(&bind)) else { continue; }; match call.callee.split('.').collect::>()[..] { - [_, name] if name == tag => tags.calls.push(Tag { - file: path, - call, - dev_dependency: *dev, - }), + [_, name] if name == tag => tags.calls.push(of(call, *said)), [_, _] => {} _ => doubt(call.line, format!("`{}` is no call of a tag", call.callee)), } @@ -1361,6 +1379,15 @@ use_repo(go_deps, "com_github_google_uuid", "org_golang_x_net") let tags = ws.tags(&NPM, "npm_translate_lock"); assert_eq!(sites(&tags), ["MODULE.bazel:2", "MODULE.bazel:7"]); assert_eq!((&ws.doubts, &tags.doubts), (&vec![], &vec![])); + // The calls that take the proxy by a name are listed, in the order + // of the file: not the one that takes the `use_extension` itself. + let handed = |tag: &Tag| format!("{}:{}", tag.call.callee, tag.call.line); + assert_eq!( + tags.handed.iter().map(handed).collect::>(), + ["use_repo:3", "use_repo:4", "inject_repo:5", "use_repo:8"] + ); + // And none of another extension's proxy. + assert_eq!(ws.tags(&PIP, "parse").handed, []); } #[test] @@ -1723,6 +1750,31 @@ use_repo(go_deps, "com_github_google_uuid", "org_golang_x_net") } } + /// `isolate` is told as `dev_dependency` is, and a call that takes the + /// proxy is told both of the use its proxy was made by, as a tag is. + #[test] + fn isolate_is_told_when_it_is_written_out_and_a_handed_proxy_has_its_use() { + for (written, want) in [ + ("", Some(false)), + (", isolate = False", Some(false)), + (", isolate = True", Some(true)), + (", isolate = ISOLATED", None), + ] { + let ws = module(&format!( + "pip = use_extension('@rules_python//python/extensions:pip.bzl', 'pip', \ + dev_dependency = True{written})\n\ + pip.parse()\nuse_repo(pip, 'hub')\n" + )); + let tags = ws.tags(&PIP, "parse"); + assert_eq!(tags.handed[0].call.callee, "use_repo", "{written}"); + for tag in [tags.calls[0], tags.handed[0]] { + let said = (tag.dev_dependency, tag.isolate); + assert_eq!(said, (Some(true), want), "{written}"); + } + assert_eq!(tags.doubts, [], "{written}"); + } + } + #[test] fn a_file_that_cannot_be_had_is_a_doubt_and_never_a_silent_skip() { let pip = diff --git a/crates/socket-patch-core/src/hosted/engine.rs b/crates/socket-patch-core/src/hosted/engine.rs index 0f2616cea..907236929 100644 --- a/crates/socket-patch-core/src/hosted/engine.rs +++ b/crates/socket-patch-core/src/hosted/engine.rs @@ -21,7 +21,10 @@ //! rewritten files) stays with the caller. use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; +use std::future::Future; +use std::pin::Pin; +use futures_util::future::Either; use serde::{Deserialize, Serialize}; use crate::api::types::PackageVendorResult; @@ -918,10 +921,15 @@ pub struct CandidateFiles { /// What the Bazel workspace of the project says of its pnpm locks /// ([`crate::bazel::pnpm::hubs`]), asked once, here, where the files /// are read: whether a hub keeps the root lock out of the run (then - /// also [`Self::pnpm_refusal`]), and whether one reads a lock, which - /// then is not routed through a named registry. The rewrite plans - /// from this alone and reads nothing of Bazel itself. - pub pnpm_bazel: crate::bazel::pnpm::Hubs, + /// also [`Self::pnpm_refusal`]; for a run that is told not to write to + /// pnpm-workspace.yaml the rewrite decides it, from + /// [`crate::bazel::pnpm::Hubs::unset`]), and whether one reads a lock + /// in a shape that is not routed through a named registry. The rewrite + /// plans from this alone and reads nothing of Bazel itself. + /// + /// In a box, so that these files are no larger for what it holds: a + /// scan in any mode builds the futures that hold them on its stack. + pub pnpm_bazel: Box, } impl CandidateFiles { @@ -1982,7 +1990,7 @@ async fn read_pnpm_bazel(view: &ProjectView<'_>, root: bool, out: &mut Candidate if let Some(hidden) = hubs.hidden.clone() { withhold_root_pnpm_locks(out, hidden); } - out.pnpm_bazel = hubs; + *out.pnpm_bazel = hubs; } /// Whether a hosted scan leaves the root pnpm lock of the project of @@ -1990,6 +1998,12 @@ async fn read_pnpm_bazel(view: &ProjectView<'_>, root: bool, out: &mut Candidate /// caller that reads no other file: the answer [`read_candidate_files`] /// gets, with the root lock read as it reads it, so that a scan which /// crawls nothing and one which crawls a package decide alike. +/// +/// Not [`crate::bazel::pnpm::Hubs::unset`], whatever the caller was told +/// of pnpm-workspace.yaml: that answer stands against a pin which the +/// pnpm of the hub would reject, and this caller adds none. It takes out +/// what no lock uses, in the lock and in the file together, and the file +/// that answer is about holds a line of the user's own, so it stays. pub async fn pnpm_root_lock_left_to_bazel(view: &ProjectView<'_>) -> Option { let mut out = CandidateFiles::default(); let root = out.read(view, &BTreeSet::new(), ROOT_PNPM_LOCKS[0]).await; @@ -2925,7 +2939,7 @@ pub async fn rewrite( let mut kept: Vec = candidates.to_vec(); let mut unattributed: Vec = Vec::new(); loop { - let mut done = rewrite_once( + let mut done = rewrite_pass( view, read.clone(), &kept, @@ -3333,6 +3347,72 @@ pub const REDIRECT_COPY_UNPATCHED: &str = "redirect_copy_unpatched"; /// attribute (see [`rewrite`]). pub const REDIRECT_UNATTRIBUTABLE: &str = "redirect_unattributable"; +/// One pass of [`rewrite`]: [`rewrite_once`], or [`rewrite_told`] for a +/// run that is told not to write to pnpm-workspace.yaml beside a Bazel hub +/// whose pnpm asks for a setting there +/// ([`crate::bazel::pnpm::Hubs::unset`]). +/// +/// No `async fn`, so that the second, which holds two passes, is built and +/// boxed on this frame, which is gone before anything is polled. An +/// `async fn` builds each future it awaits on its own poll frame first, +/// also where the branch is not taken, and keeps what it clones for it in +/// its own future: under every hosted rewrite, and in every future a +/// scan builds on its stack to hold this one. +fn rewrite_pass<'a>( + view: &'a ProjectView<'a>, + read: CandidateFiles, + candidates: &'a [Candidate], + python_metadata: BTreeMap, + options: RewriteOptions<'a>, +) -> Either< + impl Future + 'a, + Pin + Send + 'a>>, +> { + let told = read.pnpm_bazel.hides(options.trust_lockfile_config); + match told.filter(|_| read.pnpm_bazel.hidden.is_none()).cloned() { + None => Either::Left(rewrite_once( + view, + read, + candidates, + python_metadata, + options, + )), + Some(unset) => Either::Right(Box::pin(rewrite_told( + view, + read, + candidates, + python_metadata, + options, + unset, + ))), + } +} + +/// A pass for a run that is told not to write to pnpm-workspace.yaml and +/// so gives the pnpm of a Bazel hub no setting to read, where that pnpm +/// asks for one (`unset`: [`crate::bazel::pnpm::Hubs::unset`]). The root +/// lock is kept out of the pass as it is where the hub hides the file. Not +/// where the pass ends routed without that, as it does in a project whose +/// file holds the route of every pin already: a routed lock needs no +/// setting, and the pass is the one of the same project without Bazel. +async fn rewrite_told( + view: &ProjectView<'_>, + mut read: CandidateFiles, + candidates: &[Candidate], + python_metadata: BTreeMap, + options: RewriteOptions<'_>, + unset: RewriteWarning, +) -> Rewritten { + let (asked, metadata) = (read.clone(), python_metadata.clone()); + let routed = rewrite_once(view, asked, candidates, metadata, options.clone()).await; + if routed.pnpm_named_registries { + return routed; + } + read.pnpm_bazel.hidden = Some(unset.clone()); + withhold_root_pnpm_locks(&mut read, unset); + rewrite_once(view, read, candidates, python_metadata, options).await +} + async fn rewrite_once( view: &ProjectView<'_>, read: CandidateFiles, @@ -4531,10 +4611,11 @@ fn is_patch_server(origin: &str, overrides: &[DepOverride], options: &RewriteOpt /// version is pinned to two patches ([`release_with_two_patches`]); /// * the workspace file may be written, or needs no write /// (`--no-trust-lockfile-config`); -/// * no rules_js hub of a Bazel workspace reads a governing lock -/// ([`crate::bazel::pnpm::Reader`]): the pnpm such a hub runs with -/// `update_pnpm_lock` may not see the workspace file, or be too old to -/// read its registries. +/// * every rules_js hub of a Bazel workspace that reads a governing lock +/// is one whose build takes a routed lock +/// ([`crate::bazel::pnpm::Reader::Takes`]): the pnpm another hub runs +/// with `update_pnpm_lock` may not see the workspace file, or be too +/// old to read its registries. /// /// Whatever keeps a project the service offers the route to off it is /// said in the warning ([`pnpm_registry_blocked_note`]), the pins without @@ -4962,16 +5043,19 @@ fn pnpm_registry_route( ); } // What the Bazel workspace says of these locks. A lock that a rules_js - // hub reads keeps the pin the Bazel legs build + // hub reads is routed where the build of that hub takes a routed lock, + // and keeps the pin with `trustLockfile` elsewhere // ([`crate::bazel::pnpm::Reader`]). And where a hub keeps the root lock // out of the run, the locks that were read are not routed either, // whatever was read of the hub: the overrides would have to be // recorded in the root lock too, and it is not written. Said only // here, to a project the patch service offers the route to. - match (&bazel.reader, &bazel.hidden) { - (Some(reader), _) => { - blocked.push(crate::hosted::guidance::pnpm_registry_bazel_reason(reader)) - } + let hub = bazel.reader.as_ref(); + match ( + hub.and_then(crate::hosted::guidance::pnpm_registry_bazel_reason), + &bazel.hidden, + ) { + (Some(reason), _) => blocked.push(reason), (None, Some(_)) => { blocked.push(crate::hosted::guidance::PNPM_REGISTRY_BAZEL_WITHHELD.to_string()) } @@ -13705,69 +13789,262 @@ snapshots: use crate::bazel::pnpm::fixtures::{rules_js_hub, HIDING_HUB_CALL}; - /// A pnpm lock that a rules_js hub of the Bazel workspace reads is not - /// routed through a named registry, whatever the patch service offers - /// and whatever pnpm the project pins: with `update_pnpm_lock` the hub - /// runs a pnpm of its own, which sees pnpm-workspace.yaml only where the - /// call lists it and may be too old to read its registries, and no - /// Bazel leg builds a routed lock that way. The project gets the files of a - /// run that is offered no registry, byte for byte, which the Bazel legs - /// build, and the warning names the call. A hub that reads another lock - /// changes nothing. A project routed before the hub was there leaves - /// the route whole: the locks and the workspace file together. + /// The two hubs whose build takes a routed lock + /// ([`crate::bazel::pnpm::Reader::Takes`]): one that leaves the lock + /// to the lock reader of rules_js, and one that keeps it up to date + /// with a pnpm 11.20 or later that is shown the workspace file. + const ROUTED_HUBS: [&str; 2] = [ + "pnpm_lock = \"//:pnpm-lock.yaml\"", + "pnpm_lock = \"//:pnpm-lock.yaml\", data = [\"//:pnpm-workspace.yaml\"], \ + update_pnpm_lock = True", + ]; + + /// What hosted mode puts on the stack of a scan in any mode stays as + /// small as it is without the answers about Bazel. A debug build + /// builds every future on the poll frame of the function that awaits + /// it, also in a branch that is not taken, and a scan that applies a + /// patch in place is within a few KiB of the 2 MiB a test thread has: + /// the candidate files hold the answers behind one pointer, and a + /// pass of the rewrite is one `rewrite_once` beside the pointer to + /// the two passes of a run under `--no-trust-lockfile-config`, which + /// are not built in line. + #[test] + fn the_bazel_answers_cost_a_scan_one_pointer_and_a_pass_no_second_rewrite() { + use std::mem::{size_of, size_of_val}; + let word = size_of::(); + assert_eq!(size_of_val(&CandidateFiles::default().pnpm_bazel), word); + // Eight collections of three words, two warnings of six, the pointer. + assert!(size_of::() <= 37 * word); + + let project = MemoryProject::new(); + let view = ProjectView::Memory(&project); + let outer = OuterAllowRemote::default; + let options = || RewriteOptions { + dry_run: false, + targets_pipenv_lock: false, + pipenv_major: None, + pipenv_unknown_detail: String::new(), + trust_lockfile_config: false, + npm_allow_remote_config: true, + npm_outer: &outer, + yarn_classic_outer: &OuterYarnMirror::default, + cargo_outer: &no_cargo_outer, + maven_selection: &no_maven_selection, + pnpm_env: &no_env, + blocking: false, + takeover_uuids: Default::default(), + patch_server_origins: Vec::new(), + prior_discovery: None, + }; + let read = CandidateFiles::default; + let once = rewrite_once(&view, read(), &[], BTreeMap::new(), options()); + let pass = rewrite_pass(&view, read(), &[], BTreeMap::new(), options()); + assert!(matches!(pass, Either::Left(_))); + assert!(size_of_val(&pass) <= size_of_val(&once) + 2 * word); + // The run that is told not to write, beside a hub that asks for + // the setting: its two passes are behind a pointer. + let mut told = read(); + told.pnpm_bazel.unset = Some(warning(crate::bazel::pnpm::HIDDEN, "unset")); + let pass = rewrite_pass(&view, told, &[], BTreeMap::new(), options()); + assert!(matches!(pass, Either::Right(_))); + } + + /// A pnpm lock that such a hub reads is routed through a named + /// registry exactly as it is without Bazel: the files of the run are + /// those of the same project without its `MODULE.bazel`, byte for byte, + /// and nothing is said of Bazel. A project that an earlier run pinned + /// with `trustLockfile` moves to the route, and the setting that run + /// wrote goes, as without Bazel. A second run changes nothing. Told + /// not to write to pnpm-workspace.yaml, the run leaves the lock that a + /// pnpm of the build would reject and says what to do, and pins the + /// one that no pnpm of the build reads, as it does today. #[tokio::test] - async fn a_lock_that_a_bazel_hub_reads_is_not_routed() { + async fn a_lock_that_a_bazel_hub_reads_is_routed_where_its_build_takes_one() { let candidates = [left_pad_registry_candidate()]; let users = "# the project's own\npackages:\n - '.'\n"; + let mut plain = pnpm12_project(LEFT_PAD_V9_LOCK); + plain.insert_text(PNPM_WORKSPACE_REL, users); + let without = registry_rewrite(&plain, &candidates).await; + assert!(without.pnpm_named_registries); + for call in ROUTED_HUBS { + let mut project = plain.clone(); + project.insert_text("MODULE.bazel", rules_js_hub(call)); + let done = registry_rewrite(&project, &candidates).await; + assert!(done.pnpm_named_registries, "{call}"); + assert_eq!(done.rewrite.files, without.rewrite.files, "{call}"); + assert_eq!(done.confirmed.len(), 1, "{call}"); + let said = format!("{:?}", done.pnpm_warnings); + assert!(!said.contains("Bazel"), "{call}: {said}"); + assert_eq!( + pnpm_trust_detail(&done), + pnpm_trust_detail(&without), + "{call}" + ); + + // Pinned with `trustLockfile` by a run that was offered no + // registry: the next run takes the route and the setting goes. + let pinned = registry_rewrite(&project, &[left_pad_candidate()]).await; + let trusting = format!("{users}trustLockfile: true\n"); + assert_eq!(workspace_of(&pinned), Some(trusting.as_str()), "{call}"); + let moved = registry_rewrite(&after(&project, &pinned), &candidates).await; + assert!(moved.pnpm_named_registries, "{call}"); + assert_eq!(moved.rewrite.files, without.rewrite.files, "{call}"); + + let again = registry_rewrite(&after(&project, &done), &candidates).await; + assert!(again.pnpm_named_registries, "{call}"); + assert!(again.rewrite.files.is_empty(), "{call}"); + assert_eq!(again.confirmed.len(), 1, "{call}"); + } + + // `--no-trust-lockfile-config`. + let told = |project: MemoryProject| async move { + let view = ProjectView::Memory(&project); + pnpm_rewrite( + &view, + &[left_pad_registry_candidate()], + false, + false, + &no_env, + ) + .await + }; + let mut read_by_pnpm = plain.clone(); + read_by_pnpm.insert_text("MODULE.bazel", rules_js_hub(ROUTED_HUBS[1])); + let left = told(read_by_pnpm.clone()).await; + assert!(left.rewrite.files.is_empty(), "{:?}", left.rewrite.files); + assert!(left.confirmed.is_empty(), "{:?}", left.confirmed); + let hidden = left.rewrite.warnings.iter(); + let hidden: Vec<_> = hidden + .filter(|w| w.code == crate::bazel::pnpm::HIDDEN) + .collect(); + assert!( + matches!(&hidden[..], [w] if w.detail.contains("this run was told not to, which is")), + "{:?}", + left.rewrite.warnings + ); + // Routed by an earlier run: the file holds the route already, so + // the run writes nothing to it, needs no setting, and is the one + // of the same project without Bazel. + let routed = registry_rewrite(&read_by_pnpm, &candidates).await; + let kept = told(after(&read_by_pnpm, &routed)).await; + let plain_kept = told(after(&plain, &without)).await; + assert!(kept.pnpm_named_registries && plain_kept.pnpm_named_registries); + assert!(kept.rewrite.files.is_empty(), "{:?}", kept.rewrite.files); + assert_eq!(kept.confirmed.len(), 1); + assert!(!warning_codes(&kept).contains(&crate::bazel::pnpm::HIDDEN)); + assert_eq!(pnpm_trust_detail(&kept), pnpm_trust_detail(&plain_kept)); + // The setting is there already: pinned, as without the option. + let trusted = format!("{users}trustLockfile: true\n"); + read_by_pnpm.insert_text(PNPM_WORKSPACE_REL, trusted.as_str()); + let pinned = told(read_by_pnpm).await; + assert_eq!(pinned.confirmed.len(), 1); + assert!(lock_of(&pinned).is_some_and(|lock| lock.contains(&left_pad_url()))); + // No pnpm of the build reads the lock: pinned as it is today. + let mut read_by_rules_js = plain.clone(); + read_by_rules_js.insert_text("MODULE.bazel", rules_js_hub(ROUTED_HUBS[0])); + let pinned = told(read_by_rules_js).await; + assert_eq!(pinned.confirmed.len(), 1); + assert_eq!( + pinned.rewrite.files.keys().collect::>(), + ["pnpm-lock.yaml"] + ); + assert!(!warning_codes(&pinned).contains(&crate::bazel::pnpm::HIDDEN)); + } + + /// A pnpm lock that a hub reads in any other shape is not routed, + /// whatever the patch service offers and whatever pnpm the project + /// pins: the hub may run a pnpm that does not see pnpm-workspace.yaml, + /// or one too old to read its registries. The project gets the files + /// of a run that is offered no registry, byte for byte, and the + /// warning names the call and what kept it off the route. A hub that + /// reads another lock changes nothing. A project that was routed + /// before its hub left those shapes leaves the route whole: the locks + /// and the workspace file together. + #[tokio::test] + async fn a_lock_that_a_bazel_hub_reads_in_another_shape_is_not_routed() { + let candidates = [left_pad_registry_candidate()]; + let users = "# the project's own\npackages:\n - '.'\n"; + // The pnpm of the second hub is below 11.20. + let older = rules_js_hub(ROUTED_HUBS[1]).replace("11.28.10", "11.19.0"); + assert!(older.contains("pnpm_version = \"11.19.0\""), "{older}"); + // It is stated by a use of the extension that a build can drop. + let dev = rules_js_hub(ROUTED_HUBS[1]).replace( + "\"pnpm\")\npnpm.pnpm(", + "\"pnpm\", dev_dependency = True)\npnpm.pnpm(", + ); + assert!(dev.contains("dev_dependency = True"), "{dev}"); let hubs = [ - // Read by the lock reader of rules_js alone. - "pnpm_lock = \"//:pnpm-lock.yaml\"", - // Kept up to date by a pnpm that is shown the workspace file. - "pnpm_lock = \"//:pnpm-lock.yaml\", data = [\"//:pnpm-workspace.yaml\"], \ - update_pnpm_lock = True", - // A lock that is not written out may be this one. - "pnpm_lock = LOCK", + ( + dev, + "the pnpm it runs for `update_pnpm_lock` is not shown to be the one the root \ + module states (pnpm 11.28.10): a use of the pnpm extension with \ + `dev_dependency` states a release for it, and Bazel drops such a use under \ + `--ignore_dev_dependency`", + ), + ( + // A lock that is not written out may be this one. + rules_js_hub("pnpm_lock = LOCK"), + "its `pnpm_lock` is not written out in a plain string", + ), + ( + older.clone(), + "the pnpm it runs for `update_pnpm_lock` is not stated as 11.20 or later (pnpm \ + 11.19.0)", + ), + ( + rules_js_hub(&ROUTED_HUBS[1].replace("= True", "= UPDATE")), + "its `update_pnpm_lock` is not written out as `True` or `False`", + ), + ( + // A hub that runs no pnpm and says more than the calls + // that were built: its entry names the package by a + // version that a routed lock does not have. + rules_js_hub(&format!( + "{}, patches = {{\"left-pad@1.3.0\": [\"//:own.patch\"]}}", + ROUTED_HUBS[0] + )), + "its `patches` is an attribute that no routed lock was built with", + ), ]; - for call in hubs { + for (module, why) in &hubs { let mut project = pnpm12_project(LEFT_PAD_V9_LOCK); project.insert_text(PNPM_WORKSPACE_REL, users); - project.insert_text("MODULE.bazel", rules_js_hub(call)); + project.insert_text("MODULE.bazel", module.as_str()); let unoffered = registry_rewrite(&project, &[left_pad_candidate()]).await; let done = registry_rewrite(&project, &candidates).await; - assert!(!done.pnpm_named_registries, "{call}"); - assert_eq!(done.rewrite.files, unoffered.rewrite.files, "{call}"); + assert!(!done.pnpm_named_registries, "{why}"); + assert_eq!(done.rewrite.files, unoffered.rewrite.files, "{why}"); assert_eq!( workspace_of(&done), Some(format!("{users}trustLockfile: true\n").as_str()), - "{call}" + "{why}" ); let lock = lock_of(&done).expect("the lock, pinned"); assert!( lock.contains(&format!("tarball: {}", left_pad_url())) && !lock.contains("@socket-") && !lock.contains("overrides:"), - "{call}: {lock}" + "{why}: {lock}" ); - assert_eq!(done.confirmed.len(), 1, "{call}"); + assert_eq!(done.confirmed.len(), 1, "{why}"); assert!( !warning_codes(&done).contains(&crate::bazel::pnpm::HIDDEN), - "{call}" + "{why}" ); let detail = pnpm_trust_detail(&done); - assert!( - detail.contains( - "Per-package registry verification was not set up because a Bazel hub \ - reads the pnpm lock (MODULE.bazel:3), and a lock that a hub reads is not \ - routed yet: the pnpm a hub runs for `update_pnpm_lock` may not read the \ - registries in pnpm-workspace.yaml; the hosted patches rely on \ - `trustLockfile` instead" - ), - "{call}: {detail}" + let said = format!( + "Per-package registry verification was not set up because a Bazel hub reads \ + the pnpm lock (MODULE.bazel:3), and {why}: a lock that a hub reads is routed \ + only where the call of the hub passes nothing but `name`, `pnpm_lock`, `data`, \ + `update_pnpm_lock` and `use_pnpm`, and either leaves `update_pnpm_lock` off, or \ + lists pnpm-workspace.yaml in its `data` and states a pnpm of 11.20 or later; \ + the hosted patches rely on `trustLockfile` instead" ); + assert!(detail.contains(&said), "{why}: {detail}"); // Not offered a registry, the run says nothing of the hub. assert!( !pnpm_trust_detail(&unoffered).contains("Bazel"), - "{call}: {}", + "{why}: {}", pnpm_trust_detail(&unoffered) ); } @@ -13784,12 +14061,15 @@ snapshots: Some(left_pad_routed_workspace().as_str()) ); + // Routed under a hub that takes a routed lock, which then states + // an older pnpm. let mut root = pnpm12_project(LEFT_PAD_V9_LOCK); root.insert_text(PNPM_WORKSPACE_REL, users); + root.insert_text("MODULE.bazel", rules_js_hub(ROUTED_HUBS[1])); let first = registry_rewrite(&root, &candidates).await; assert!(first.pnpm_named_registries); let mut routed = after(&root, &first); - routed.insert_text("MODULE.bazel", rules_js_hub(hubs[0])); + routed.insert_text("MODULE.bazel", older.as_str()); let done = registry_rewrite(&routed, &candidates).await; assert!(!done.pnpm_named_registries); assert_eq!( @@ -13859,6 +14139,8 @@ snapshots: let detail = pnpm_trust_detail(&done); let said = format!("because a Bazel hub may read the pnpm lock {named}"); assert!(detail.contains(&said), "{file}: {detail}"); + let shapes = "), in a shape that was not read: a lock that a hub reads is routed only"; + assert!(detail.contains(shapes), "{file}: {detail}"); assert!( !pnpm_trust_detail(&unoffered).contains("Bazel"), "{file}: {}", @@ -14108,6 +14390,55 @@ snapshots: assert!(!done.pnpm_named_registries); } + /// The members' own locks beside a root lock that a hub reads are not + /// routed where the hub is one whose build takes a routed lock either: + /// the route records its overrides in every lock that + /// pnpm-workspace.yaml governs, and no build was run of a hub that + /// reads one lock of several. The project gets the files of a run that + /// is offered no registry, byte for byte, and the warning says why. + #[tokio::test] + async fn a_hub_of_the_root_lock_keeps_a_project_with_member_locks_off_the_route() { + let tmp = tempfile::tempdir().unwrap(); + let ws = "packages:\n - 'packages/*'\nsharedWorkspaceLockfile: false\n"; + write_member_workspace(tmp.path(), ws); + write_rel( + tmp.path(), + "package.json", + r#"{"name":"root","private":true,"packageManager":"pnpm@12.22.0"}"#, + ); + write_rel( + tmp.path(), + "packages/a/package.json", + r#"{"name":"a","dependencies":{"is-number":"7.0.0"}}"#, + ); + let mut offered = is_number_candidates(); + offered[0].dep.npm_registry_url = Some(registry_address(MEMBER_URL)); + let view = ProjectView::Disk(tmp.path()); + for call in ROUTED_HUBS { + write_rel(tmp.path(), "MODULE.bazel", &rules_js_hub(call)); + let unoffered = + pnpm_rewrite(&view, &is_number_candidates(), true, false, &no_env).await; + let done = pnpm_rewrite(&view, &offered, true, false, &no_env).await; + assert!(!done.pnpm_named_registries, "{call}"); + assert_eq!(done.rewrite.files, unoffered.rewrite.files, "{call}"); + assert_eq!( + workspace_of(&done), + Some(format!("{ws}trustLockfile: true\n").as_str()), + "{call}" + ); + assert_eq!(done.confirmed.len(), 1, "{call}: {:?}", done.confirmed); + let detail = pnpm_trust_detail(&done); + assert!( + detail.contains( + "because a Bazel hub reads the pnpm lock (MODULE.bazel:3), and the project \ + has workspace members with pnpm locks of their own, a layout that no routed \ + lock was built with: a lock that a hub reads is routed only where" + ), + "{call}: {detail}" + ); + } + } + /// The members' own locks beside a root lock that a hub withholds are /// pinned as main pins them, on `trustLockfile`, also where the patch /// service offers a registry and the project pins pnpm 12: the route's @@ -14315,7 +14646,7 @@ snapshots: let view = ProjectView::Disk(tmp.path()); let read = read_candidate_files(&view, &BTreeSet::new(), &candidates).await; // No Bazel workspace: nothing was read of one. - assert_eq!(read.pnpm_bazel, crate::bazel::pnpm::Hubs::default()); + assert_eq!(*read.pnpm_bazel, crate::bazel::pnpm::Hubs::default()); let hidden = RewriteWarning { code: crate::bazel::pnpm::HIDDEN.into(), detail: "a hub keeps pnpm-lock.yaml up to date".into(), diff --git a/crates/socket-patch-core/src/hosted/guidance.rs b/crates/socket-patch-core/src/hosted/guidance.rs index 0bc9f2278..94821fa07 100644 --- a/crates/socket-patch-core/src/hosted/guidance.rs +++ b/crates/socket-patch-core/src/hosted/guidance.rs @@ -553,22 +553,26 @@ pub fn pnpm_registry_mirrored_reason(packages: &[String]) -> String { } /// The clause for a project whose pnpm lock a rules_js hub of its Bazel -/// workspace reads, or may read where the workspace could not be read -/// whole ([`crate::bazel::pnpm::Reader`]). What holds the route -/// back is the pnpm such a hub runs with `update_pnpm_lock`, which sees the -/// registries only where the call lists pnpm-workspace.yaml and may be -/// older than pnpm 11.20; the lock reader of rules_js takes a routed lock. -/// The project keeps the pin that the Bazel legs build. -pub fn pnpm_registry_bazel_reason(reader: &crate::bazel::pnpm::Reader) -> String { +/// workspace reads in a shape whose build of a routed lock is not known, +/// or may read where the workspace could not be read whole +/// ([`crate::bazel::pnpm::Reader`]): what kept the hub off the route, and +/// the two shapes that are routed. `None` for a hub that takes a routed +/// lock. +pub fn pnpm_registry_bazel_reason(reader: &crate::bazel::pnpm::Reader) -> Option { use crate::bazel::pnpm::Reader; let hub = match reader { - Reader::Call(call) => format!("a Bazel hub reads the pnpm lock ({call})"), - Reader::Unseen(what) => format!("a Bazel hub may read the pnpm lock ({what})"), + Reader::Takes(_) => return None, + Reader::Call(call, why) => format!("a Bazel hub reads the pnpm lock ({call}), and {why}"), + Reader::Unseen(what) => { + format!("a Bazel hub may read the pnpm lock ({what}), in a shape that was not read") + } }; - format!( - "{hub}, and a lock that a hub reads is not routed yet: the pnpm a hub runs for \ - `update_pnpm_lock` may not read the registries in {PNPM_WORKSPACE_REL}" - ) + Some(format!( + "{hub}: a lock that a hub reads is routed only where the call of the hub passes nothing \ + but `name`, `pnpm_lock`, `data`, `update_pnpm_lock` and `use_pnpm`, and either leaves \ + `update_pnpm_lock` off, or lists {PNPM_WORKSPACE_REL} in its `data` and states a pnpm \ + of 11.20 or later" + )) } /// The clause for a project whose root pnpm lock a Bazel hub keeps out of diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 1388da628..6965df1ad 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -383,7 +383,7 @@ Each Legacy format has an upgrade path and an undo path. Both work in v5: the whole lock. When the patch service gave at least one pin a registry address, the warning names what kept the project off the registry route: the packages that have no address (one is enough), pnpm pins that do not prove - 11.20, a Bazel hub that reads the lock + 11.20, a Bazel hub that reads the lock in a shape that is not routed ([Bazel workspaces: npm](#bazel-workspaces-npm)), an override of yours for a patched package, a workspace file or a lock entry the edit cannot follow. A project with no pnpm pin is told that pinning pnpm 11.20 or later (for example with `packageManager`) and @@ -2199,9 +2199,13 @@ What the table was tested with: on 7.4.0. Every row is a workspace under Bzlmod (`MODULE.bazel`): nothing is tested for dependencies that a `WORKSPACE` file declares. - **npm**: aspect_rules_js 3.6.0, `npm.npm_translate_lock(pnpm_lock = "//:pnpm-lock.yaml")` - without `update_pnpm_lock`, and a lock of `lockfileVersion: '9.0'`. Hosted mode also with - `update_pnpm_lock = True`, where rules_js runs a pnpm of its own: with the pnpm it picks - itself (10.34.9) and no `data`, and with pnpm 11.28.10 and `pnpm-workspace.yaml` in `data`. + without `update_pnpm_lock`, and a lock of `lockfileVersion: '9.0'`. Hosted mode there both + with the pin it writes beside `trustLockfile: true` and with the lock it routes through a + named registry, and with that pin beside a `patches` entry of the hub for the package. + Hosted mode also with `update_pnpm_lock = True`, where rules_js runs a + pnpm of its own: with the pnpm it picks itself (10.34.9) and no `data`, and with pnpm + 11.28.10 and `pnpm-workspace.yaml` in `data`, pinned and routed, that pnpm stated by + `pnpm_version`, by `pnpm_version_from` and by a `use_pnpm` label. [Bazel workspaces: npm](#bazel-workspaces-npm) says what hosted mode does on such a hub. - **PyPI**: rules_python 2.5.0-rc4, `pip.parse(requirements_lock = "//:requirements.txt")`, and a root `requirements.txt` with hashes. @@ -2294,13 +2298,6 @@ Known problems. In each of these a command exits 0 today and the next Bazel buil the lock has one), or run `socket-patch rollback`. - **Vendored npm on a hub with `update_pnpm_lock = True`** (measured with pnpm 9 and 10): the pnpm that Bazel runs does not see `.socket/vendor`. Use hosted mode there. -- **Hosted npm on such a hub with a pnpm of 11 or later, when hosted mode is told not to - write `trustLockfile: true`** (`--no-trust-lockfile-config`): the lock is pinned, with the - warning that pnpm 11 rejects it, and the pnpm that Bazel runs does - (`ERR_PNPM_TARBALL_URL_MISMATCH`; measured by hand with the option on Bazel 9.3.2). Run - `socket-patch rollback`, and scan again without the option. A `trustLockfile: false` of - the project's own is not this case: hosted mode pins nothing beside it (see - [Bazel workspaces: npm](#bazel-workspaces-npm)). - **`rollback` of a hosted npm pin on such a hub that an earlier release wrote, where the `pnpm-workspace.yaml` the hub lists holds only what hosted mode writes**: the undo removes the file, and the call then names a missing one. Put the file back with a comment line in @@ -2321,6 +2318,16 @@ In these a command exits 0 and the Bazel build passes on the unpatched package: - **Hosted PyPI, when `pip.parse` takes the requirements of the build's platform from another file** than the one socket-patch rewrote (`requirements_by_platform`, `requirements_linux` and its siblings). +- **Hosted npm on Bazel 7, where the hub has a `patches` entry for the package** and Bazel + has built the package before. For such a package rules_js unpacks the tarball when it + fetches it and hands the build a directory (3.6.0, read in its source; without the entry + it hands over the tarball), and Bazel 7 does not look into a source directory. So after + the scan Bazel 7 fetches the patched tarball and keeps the output it built from the + upstream one, and after `rollback` it keeps the patched output the same way. Run + `bazel clean` after the scan and after `rollback`. A machine that has not built the + package builds the patched one, and so do Bazel 8 and 9. `vex` reads the lock and says + `not_affected` in the meantime. A test builds this on Bazel 7.7.2. rules_js unpacks a + package with lifecycle hooks the same way, which was not measured. [Bazel workspaces: VEX](#bazel-workspaces-vex) lists what the document says in such cases. @@ -2372,36 +2379,112 @@ npm.npm_translate_lock( Run the command again after that: it pins the lock, and the next build takes the patched package. rules_js asks for this `data` itself (`docs/pnpm.md`, "update_pnpm_lock"). -**No named registries for a lock that a hub reads.** For pnpm 11.20 and later hosted mode +**Named registries for a lock that a hub reads.** For pnpm 11.20 and later hosted mode can route a patched release through a named registry of `pnpm-workspace.yaml` in place of -`trustLockfile` (see pnpm above). It never does for a lock that a rules_js hub reads: one -that an `npm.npm_translate_lock` names in a plain string, the root lock or a member's own, -or a call whose `pnpm_lock` is not written out, whatever else the call says. In a Bazel -workspace it takes the route only where it is certain that no hub reads the lock, so what -the reader could not see counts as a hub that may: a file that `MODULE.bazel` includes and -that is missing or unreadable, a use of the extension that is not a plain call of a tag, -and a `WORKSPACE` file that cannot be read or that brings in rules_js (a `load` from -`@aspect_rules_js`, a `load` of `npm_translate_lock`, or a call of that rule), whose -repositories are not looked through. A `WORKSPACE` file that is about something else -blocks nothing. Unlike the answer above, which passes over what it cannot see so that no -project loses a patch, declining the route costs nothing: the project gets the same pin as -before, and the warning names what was not read ("… because a Bazel hub may read the pnpm -lock (WORKSPACE:3: it brings in rules_js, …) …"). The lock -reader of rules_js is not the reason: it takes a routed lock (measured on macOS: rules_js -3.6.0 on Bazel 9.3.2 builds one for a hub without `update_pnpm_lock`, and the packages it -builds hold the patched bytes; rules_js 2.9.3 on Bazel 8.8.2 does too). The pnpm that a -hub runs with `update_pnpm_lock` is. It sees `pnpm-workspace.yaml` only where the call -lists it, and it may be older than pnpm 11.20: rules_js picks a pnpm 10 where the -workspace states none. Run as the hub runs it (`pnpm install --lockfile-only` beside the -lock and `package.json`, without the workspace file), pnpm 11.28.13 and 12.22.0 reject a -routed lock (`ERR_PNPM_MISSING_NAMED_REGISTRY`, measured). No Bazel test leg builds a -routed lock with `update_pnpm_lock` yet, so for now every such project is pinned exactly -as it is on a patch service that offers no registry, which is the pin the Bazel legs -build, and the `redirect_pnpm_trust_lockfile` warning names the call ("… because a Bazel -hub reads the pnpm lock (MODULE.bazel:7), and a lock that a hub reads is not routed -yet …"). For a project below the Bazel root it says, as the warning above does, that its -paths are from that root. A project that was routed before the -hub was there leaves the route on its next scan, the lock and the workspace file together. +`trustLockfile` (see pnpm above). For a lock that a rules_js hub reads it does so in two +shapes of the hub, in which a build took the routed lock on Bazel 9.3.2, 8.8.2 and 7.7.2 +with rules_js 3.6.0: the build holds the patched package, a second build changes no file, +and `rollback` brings the upstream build and the files of before back. The project has to +be at the root of the Bazel workspace and have one pnpm lock, the root one, and every call +that reads it has to name it in a plain string, pass nothing but the attributes of the +calls that were built (`name`, `pnpm_lock`, `data`, `update_pnpm_lock`, `use_pnpm`), and +be one of the two: + +- **A hub that runs no pnpm**: the call has no `update_pnpm_lock`, or `False`. The lock + reader of rules_js builds a routed lock as it builds a pinned one, and a build that may + update nothing passes right after the scan. +- **A hub whose pnpm reads the registries**: `update_pnpm_lock = True`, a `data` that + lists the `pnpm-workspace.yaml` beside the lock, and a pnpm that the root module states + as a release of 11.20.0 or later, in one of the ways the list below reads (`pnpm_version`, + `pnpm_version_from`, a `use_pnpm` that is followed to a tag). That pnpm asks the patch's + registry about the package and writes the lock back as it is. The first build after the + scan rewrites the hashes under `.aspect/`, as after any change of the lock. Measured + with pnpm 11.20.0, 11.28.10 and 12.17.0; a test builds 11.28.10 stated in each of the + three ways. + +Under such a hub the scan routes the lock exactly as it does for the same project without +Bazel, its files and its messages, and `rollback` undoes it the same way. One file is the +exception: where the `pnpm-workspace.yaml` that a hub of the second shape lists says +`trustLockfile: false`, or is YAML that a line cannot be added to, hosted mode writes +nothing, as before (see the cases below), although a routed lock needs no setting. Take +the `trustLockfile: false` out, or set it to `true`, and scan again. Every other hub +keeps the project on the pin with `trustLockfile: true`, exactly as on a patch service +that offers no registry, and the `redirect_pnpm_trust_lockfile` warning names the call and +what kept it off the route ("… +because a Bazel hub reads the pnpm lock (MODULE.bazel:7), and the pnpm it runs for +`update_pnpm_lock` is not stated as 11.20 or later (pnpm 11.19.0): a lock that a hub reads +is routed only where the call of the hub passes nothing but `name`, `pnpm_lock`, `data`, +`update_pnpm_lock` and `use_pnpm`, and either leaves `update_pnpm_lock` off, or lists +pnpm-workspace.yaml in its `data` and states a pnpm of 11.20 or later …"). What keeps a +hub off the route: + +- A `pnpm_lock` that is not written out in a plain string, or that names a workspace + member's own lock, and a project below the root of the Bazel workspace: no build of + these was run. +- A project that keeps a lock per workspace member (`sharedWorkspaceLockfile: false`), + whichever of its locks the hub names ("… and the project has workspace members with pnpm + locks of their own, a layout that no routed lock was built with …"). The route records + its overrides in every lock of the project, and the pnpm of a hub resolves in a directory + that holds the one lock its call names: no build of that was run either. +- Any other attribute on the call than the five above, and a `*` or `**`, which may pass + one ("… and its `patches` is an attribute that no routed lock was built with …"). A + routed lock holds the patched release under another version (`socket-:1.0.0`), so a + `patches` entry that is keyed by the package's name and version names no package of it, + and rules_js fails the build on such an entry (``Patch file key … does not match any + npm packages``, measured on the three Bazel releases); the pin keeps the package's key + and builds, which a test holds (for Bazel 7 see the known problems of + [Bazel workspaces: what is supported](#bazel-workspaces-what-is-supported)). With + `npm_package_lock`, `yarn_lock` or `preupdate` a pnpm writes the lock anew, and the + other attributes that are keyed by a name and a version (`bins`, `lifecycle_hooks`, + `package_visibility`, `public_hoist_packages`, `replace_packages`, + `custom_postinstalls`) would stop naming the package: none of these was built with a + routed lock. Nor was any other attribute, `npmrc` and `verify_node_modules_ignored` + among them, so a hub with one keeps the pin until a build is run for it. +- An `update_pnpm_lock` that is not written out as `True` or `False`. +- A `data` that is not a list of strings that holds the label of the file. The pnpm of + such a hub fails the build on a routed lock (`ERR_PNPM_MISSING_NAMED_REGISTRY`, measured + on the three Bazel releases with pnpm 11.28.10). +- A pnpm that is not stated as 11.20 or later: the one rules_js picks, one stated in a way + that is no version, and an older one. With the file listed such a pnpm builds the routed + lock only until it resolves again. Once a `package.json` asks for another package, pnpm + 11.19.0 puts the upstream release back in the lock without a word, and pnpm 10.34.9 + fails the build (`ERR_PNPM_SPEC_NOT_SUPPORTED_BY_ANY_RESOLVER`); pnpm 11.20.0, 11.28.10 + and 12.17.0 keep the patched release (measured on Bazel 9.3.2). A prerelease + (`11.20.0-rc.1`) and a number of fewer than three parts (`11.20`) do not count as stated + either. +- A pnpm that is not shown to be the one the root module states. The route takes a stated + release for the pnpm of the hub only where its repository is one of the use of the pnpm + extension that every module shares: the hub has no `use_pnpm`, or a `use_repo` on the + name of a proxy of that extension takes the repository by its name. A `use_repo` on + another extension's proxy can take a repository under the name of a `pnpm.pnpm` tag, a + use of the extension with `isolate = True`, or with an `isolate` that is not written + out, has tags and repositories of its own, and an `inject_repo` on the extension is not + read. Nor does a release count that a use of the extension with `dev_dependency` states + ("… a use of the pnpm extension with `dev_dependency` states a release for it, and Bazel + drops such a use under `--ignore_dev_dependency` …"): a build under that option has no + such tag (read in Bazel's source at 7.7.2, 8.8.2 and 9.3.2; not built), so its hub runs + the pnpm that rules_js picks, a pnpm 10 at 3.6.0, which builds a routed lock only until + it resolves again. The pin is not held to any of this: for it such a release counts as + it did, and it builds with either pnpm, because its setting is in the file the hub + lists. + +The route is taken only where it is certain which hubs read the lock, so what the reader +could not see counts as a hub that may read it in another shape, also beside a call in one +of the two: a file that `MODULE.bazel` includes and that is missing or unreadable, a use +of the extension that is not a plain call of a tag, and a `WORKSPACE` file that cannot be +read or that brings in rules_js (a `load` from `@aspect_rules_js`, a `load` of +`npm_translate_lock`, or a call of that rule), whose repositories are not looked through. +A `WORKSPACE` file that is about something else blocks nothing. Unlike the answer above, +which passes over what it cannot see so that no project loses a patch, declining the route +costs nothing: the project gets the same pin as before, and the warning names what was not +read ("… because a Bazel hub may read the pnpm lock (WORKSPACE:3: it brings in rules_js, +…), in a shape that was not read …"). For a project below the Bazel root the warning says, +as the one above does, that its paths are from that root. A project that was routed and +whose hub is no longer in one of the two shapes leaves the route on its next scan, the +lock and the workspace file together. One that was pinned and whose hub now is in one +moves to the route, and a `trustLockfile: true` that the earlier run wrote goes as it does +without Bazel. + Where hosted mode writes nothing for the root lock (the hub above), a route of an earlier run is left exactly as it is, in the workspace file and in every lock, and a `pnpm-workspace.yaml` that holds nothing but such a route counts as a file that holds only @@ -2416,7 +2499,7 @@ comment line in the file first, as the warning of a hosted scan says; a hosted s never deletes the file under a hub that reads, or may read, the lock. The file the hub lists has to be one that a pin and its undo leave standing, so hosted mode -also writes nothing for a hub that lists it in two cases, and the warning then names what +also writes nothing for a hub that lists it in three cases, and the warning then names what the file needs and no label: - **The file would hold only what hosted mode writes**: there is none, or it is empty, or @@ -2429,14 +2512,31 @@ the file needs and no label: - **Hosted mode does not write the setting to the file**: it says `trustLockfile: false` (or any value but `true`), which hosted mode leaves as it is, or it is YAML that a line cannot be added to (a flow-style root, several documents). The pnpm of the hub would read - the file and still reject the lock. Set `trustLockfile: true` in it yourself. + the file and still reject the lock. Set `trustLockfile: true` in it yourself, or take a + `trustLockfile: false` out: hosted mode then writes the setting with a pin, and none + where it routes the lock. This case comes before the route, so it holds also where the + lock would be routed. +- **Hosted mode is told not to write to the file** (`--no-trust-lockfile-config`), and the + file does not hold `trustLockfile: true` already. The option keeps the setting out of + the file, and the registries of the route with it, so the pin would be one that the pnpm + of the hub rejects (`ERR_PNPM_TARBALL_URL_MISMATCH`, measured on the three Bazel + releases with pnpm 11.28.10). Drop the option, or set `trustLockfile: true` in the file + yourself. A project that an earlier run routed is not this case as long as the file + holds the route of every pin: the run then has nothing to write there and needs no + setting, and it reports the packages as applied, as it does without Bazel (a test builds + it). Where it would have to add to the route, it writes nothing and warns as above. A + scan under the option that crawls nothing is not this case either: it adds no pin, so it + takes out what a route left and no lock uses, in the lock and in the file together, as + it does without Bazel, and says nothing of the hub. A hub that runs no pnpm, or one that + is known to be older than 11, is pinned under the option as it is without Bazel: no pnpm + of the build asks for the setting. Hosted mode withholds when one call names the project's `pnpm-lock.yaml` in a plain string and all three hold for it: - `update_pnpm_lock` is `True`, or is not written out as `True` or `False`. - `data` is not a list of strings that holds the label of the `pnpm-workspace.yaml` beside - the lock, or it is and the file is one of the two cases above. + the lock, or it is and the file is one of the three cases above. - The pnpm it runs is stated as 11 or later, or in a way that is no version (`latest`, a constant, a `package.json` that cannot be read). That pnpm is the repository `use_pnpm` names, `@pnpm` without one, and a `pnpm.pnpm` tag of that `name` states its release: in @@ -2454,7 +2554,8 @@ and all three hold for it: A `use_pnpm` is followed to such a tag only where a `use_repo` takes its repository by position, under the tag's own name. One that names a repository `use_repo` renames (`use_repo(pnpm, eleven = "pnpm")`, which runs the pnpm of the tag `pnpm`), or a - repository of another extension or rule, is read as no version. + repository of another extension or rule under a name that no tag has, is read as no + version. What is not written out counts against writing, because a failing build is worse than a patch that a warning explains. So a hub whose `data` is a constant gets no new hosted pin @@ -2481,9 +2582,7 @@ project, for the pin and for the route through a named registry alike (a project directory of a Bazel workspace is routed in memory where a checkout is not), and no `MODULE.bazel.lock`, and a `pnpm_version_from` file that is not among the project's own manifests reads there as a release that is not written out, so a lock that a checkout pins -can be left as it is in memory. Nor does hosted mode look at `--no-trust-lockfile-config` -when it decides this: see the known problems of -[Bazel workspaces: what is supported](#bazel-workspaces-what-is-supported). +can be left as it is in memory, and one that a checkout routes can be pinned there. ## Bazel workspaces: Maven @@ -3227,8 +3326,9 @@ adds no line. What the line is for, measured with rules_rust 0.75.0 on Bazel 9.3 tags the crate's library so). That package names repositories only the hub sees, so for a vendored crate with a dependency the commands that analyse every target fail on it: `bazel cquery //...` and `bazel query 'deps(//...)'` end with `No repository visible as - '@crates__' from main repository`. With the line both pass, and `//...` holds - your own targets alone. + '@crates__' from main repository`, or with the same words about `@platforms`, + which the file names too: Bazel reports the first of the two that it meets. With the line + both pass, and `//...` holds your own targets alone. **Under that line, the file is no change of the copy.** `vendor --check` passes, `vex` attests the crate, `repair` has nothing to restore, and a second `scan --mode vendored` diff --git a/docs/testing/pnpm-compatibility.md b/docs/testing/pnpm-compatibility.md index 19126ae53..6a38ba4aa 100644 --- a/docs/testing/pnpm-compatibility.md +++ b/docs/testing/pnpm-compatibility.md @@ -194,11 +194,20 @@ routed lock and `package.json` and no workspace file fails with `ERR_PNPM_MISSING_NAMED_REGISTRY` ("has registry prefix 'socket-…:', which is not declared by the registries setting") and leaves the lock as it is. That directory is what a rules_js hub of a Bazel workspace gives the pnpm it runs for `update_pnpm_lock` when the -hub does not list the file. The lock reader of rules_js itself takes a routed lock: -measured on macOS, rules_js 3.6.0 on Bazel 9.3.2 builds one for a hub without -`update_pnpm_lock`, with the patched bytes in the built packages, and rules_js 2.9.3 on -Bazel 8.8.2 does too. Until a Bazel leg builds a routed lock with `update_pnpm_lock`, the -scan does not take the route for a lock that a hub reads (see "Bazel workspaces: npm" in +hub does not list the file, and a build of such a hub fails the same way (pnpm 11.28.10, +rules_js 3.6.0 on Bazel 9.3.2, 8.8.2 and 7.7.2). The lock reader of rules_js itself takes +a routed lock: on those three releases rules_js 3.6.0 builds one for a hub without +`update_pnpm_lock`, with the patched bytes in the built packages (and, measured by hand, +rules_js 2.9.3 on Bazel 8.8.2 does too). So does a hub with `update_pnpm_lock` that lists +the file and runs pnpm 11.20.0, 11.28.10 or 12.17.0: that pnpm writes the lock back as it +is, also after a `package.json` asks for another package. A pnpm below 11.20 does not +survive that change: pnpm 11.19.0 puts the upstream release back and pnpm 10.34.9 fails +(`ERR_PNPM_SPEC_NOT_SUPPORTED_BY_ANY_RESOLVER`). And a routed lock holds the patched +release under another version, so a `patches` entry of the hub that is keyed by the +package's name and version names no package of it, and rules_js fails the build (measured +on the three releases). The scan therefore takes the route for a lock that a hub reads in +those two shapes of the hub alone, and only where the call of the hub passes nothing but +the attributes those builds had (see "Bazel workspaces: npm" in [ecosystems](../ecosystems.md)). ### Tests @@ -229,10 +238,11 @@ no lock. twin route a project, add a rules_js hub to its `MODULE.bazel` and scan again, with no Bazel. Where the hub keeps the lock up to date with a pnpm 11 that does not see the workspace file, the scan changes neither file; where the hub -only reads the lock, the scan takes the registry, the override, the lock's -record and the registry keys out in one run and pins the release on -`trustLockfile`. A fresh checkout frozen-installs the patched bytes from an -empty store after either. +keeps it up to date with a pnpm 10 that is shown the file, the scan takes the +registry, the override, the lock's record and the registry keys out in one run +and pins the release on `trustLockfile`. A fresh checkout frozen-installs the +patched bytes from an empty store after either. (A hub that only reads the +lock keeps the route now.) `pnpm12_registry_route_is_cleaned_up_when_a_patch_is_not_needed` and its pnpm 11 twin run in the same suite, against the same two loopback servers. They diff --git a/scripts/loc-budget.json b/scripts/loc-budget.json index 2be5dcf83..b63be1c72 100644 --- a/scripts/loc-budget.json +++ b/scripts/loc-budget.json @@ -4,7 +4,7 @@ "paths": [ "crates/socket-patch-core/src/bazel/" ], - "max": 3917 + "max": 4091 }, "lock-readers": { "paths": [