Skip to content

Commit c704e86

Browse files
zkochanclaude
andcommitted
fix(pack): use only workspace-declared prefixes for workspace: rewrites
- A prefix from the global config.yaml, the environment, or the command line no longer reaches a packed manifest, so the result does not depend on the machine that packed it. - Skip reading sibling publishConfig.directory manifests when the workspace declares no prefix. - Propagate an unreadable sibling publication manifest instead of dropping every workspace lookup entry. - v11: cache publication manifests per project across a recursive run, and read them without the engine installability check. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 6042b5b commit c704e86

22 files changed

Lines changed: 256 additions & 50 deletions

File tree

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
---
22
"@pnpm/config.pick-registry-for-package": minor
3+
"@pnpm/config.reader": patch
34
"@pnpm/releasing.exportable-manifest": minor
45
"@pnpm/releasing.commands": patch
56
"pnpm": patch
67
"pacquet": minor
78
---
89

9-
`pnpm pack` and `pnpm publish` now write a `workspace:` dependency with the named-registry prefix of the registry the target package publishes to. With `prefix: work` declared for that registry, `"foo": "workspace:^"` is published as `"foo": "work:^1.0.0"`, and a consumer that installs `foo` through the prefix records one lockfile entry for it. Peer dependency ranges stay plain semver ranges. When several prefixes declare the same registry, the first in alphabetical order is used.
10+
`pnpm pack` and `pnpm publish` now write a `workspace:` dependency with the named-registry prefix of the registry the target package publishes to. With `prefix: work` declared for that registry in `pnpm-workspace.yaml`, `"foo": "workspace:^"` is published as `"foo": "work:^1.0.0"`, and a consumer that installs `foo` through the prefix records one lockfile entry for it. Peer dependency ranges stay plain semver ranges. When several prefixes declare the same registry, the first in alphabetical order is used.

‎pnpm-lock.yaml‎

Lines changed: 3 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎pnpm/crates/cli/src/cli_args/pack.rs‎

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,11 @@ impl PackArgs {
138138
out: self.out.clone(),
139139
pack_destination: self.pack_destination.clone(),
140140
before_packing_hooks,
141-
workspace_packages: None,
141+
workspace_packages:
142+
crate::cli_args::workspace_packages::discover_workspace_package_manifests(
143+
config.workspace_dir.as_deref(),
144+
config,
145+
)?,
142146
};
143147
let mut options = self.pack_options(dir.to_path_buf(), config, shared);
144148
set_injected_changelog(&mut options, config, dir).await?;
@@ -201,12 +205,6 @@ impl PackArgs {
201205
config: &Config,
202206
shared: PackSharedContext,
203207
) -> PackOptions {
204-
let workspace_packages = shared.workspace_packages.or_else(|| {
205-
crate::cli_args::workspace_packages::discover_workspace_package_manifests(
206-
config.workspace_dir.as_deref(),
207-
config,
208-
)
209-
});
210208
PackOptions {
211209
dir,
212210
workspace_dir: config.workspace_dir.clone(),
@@ -228,7 +226,7 @@ impl PackArgs {
228226
config.skip_manifest_obfuscation,
229227
),
230228
before_packing_hooks: shared.before_packing_hooks,
231-
workspace_packages,
229+
workspace_packages: shared.workspace_packages,
232230
},
233231
output: pnpm_pack::PackOutputOptions {
234232
gzip_level: self.pack_gzip_level,

‎pnpm/crates/cli/src/cli_args/publish.rs‎

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -355,14 +355,13 @@ impl PublishArgs {
355355
before_packing_hooks: &[Arc<dyn PnpmfileHooks>],
356356
workspace_packages: Option<&Arc<WorkspacePackageManifests>>,
357357
) -> miette::Result<PackResult> {
358-
let workspace_packages = workspace_packages
359-
.cloned()
360-
.or_else(|| {
361-
crate::cli_args::workspace_packages::discover_workspace_package_manifests(
362-
config.workspace_dir.as_deref(),
363-
config,
364-
)
365-
});
358+
let workspace_packages = match workspace_packages {
359+
Some(workspace_packages) => Some(Arc::clone(workspace_packages)),
360+
None => crate::cli_args::workspace_packages::discover_workspace_package_manifests(
361+
config.workspace_dir.as_deref(),
362+
config,
363+
)?,
364+
};
366365
let manifest = crate::cli_args::workspace_packages::create_publish_pack_manifest_options(
367366
&self.flags.manifest,
368367
config,

‎pnpm/crates/cli/src/cli_args/workspace_packages.rs‎

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,9 @@ fn publish_registry_prefix<'config>(
4545
name: &str,
4646
config: &'config Config,
4747
) -> Result<Option<&'config str>, PackageManifestError> {
48+
if config.workspace_registry_prefixes.is_empty() {
49+
return Ok(None);
50+
}
4851
let manifest = publication_manifest(project)?;
4952
let published_name = manifest
5053
.get("publishConfig")
@@ -78,17 +81,25 @@ fn publication_manifest(project: &Project) -> Result<Cow<'_, Value>, PackageMani
7881
return Ok(Cow::Borrowed(manifest));
7982
};
8083
Ok(safe_read_project_manifest_from_dir(&project.root_dir.join(directory))?
81-
.map_or(Cow::Borrowed(manifest), Cow::Owned))
84+
.map(Cow::Owned)
85+
.unwrap_or(Cow::Borrowed(manifest)))
8286
}
8387

88+
/// The workspace's packages, or `None` outside a workspace or when its
89+
/// projects cannot be discovered. A sibling's unreadable publication manifest
90+
/// is an error: the prefix of a dependency on it would be guessed.
8491
pub fn discover_workspace_package_manifests(
8592
workspace_dir: Option<&Path>,
8693
config: &Config,
87-
) -> Option<Arc<WorkspacePackageManifests>> {
88-
let ws_dir = workspace_dir?;
89-
let (projects, _) =
90-
crate::cli_args::recursive::discover_workspace_projects(ws_dir, config).ok()?;
91-
Some(Arc::new(build_workspace_package_manifest_map(&projects, config).ok()?))
94+
) -> Result<Option<Arc<WorkspacePackageManifests>>, PackageManifestError> {
95+
let Some(ws_dir) = workspace_dir else {
96+
return Ok(None);
97+
};
98+
let Ok((projects, _)) = crate::cli_args::recursive::discover_workspace_projects(ws_dir, config)
99+
else {
100+
return Ok(None);
101+
};
102+
build_workspace_package_manifest_map(&projects, config).map(Arc::new).map(Some)
92103
}
93104

94105
pub fn create_publish_pack_manifest_options(

‎pnpm/crates/cli/src/cli_args/workspace_packages/tests.rs‎

Lines changed: 46 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
1-
use std::{collections::BTreeMap, fs, path::Path};
1+
use std::{
2+
collections::{BTreeMap, BTreeSet},
3+
fs,
4+
path::Path,
5+
};
26

37
use pnpm_config::Config;
48
use pnpm_package_manifest::PackageManifest;
@@ -31,6 +35,7 @@ fn config_with_work_prefix() -> Config {
3135
let mut config = Config::new();
3236
config.registries_by_scope = BTreeMap::from([("@work".to_string(), WORK.to_string())]);
3337
config.registries_by_prefix = BTreeMap::from([("work".to_string(), WORK.to_string())]);
38+
config.workspace_registry_prefixes = BTreeSet::from(["work".to_string()]);
3439
config
3540
}
3641

@@ -177,3 +182,43 @@ fn an_unbuilt_publish_directory_leaves_the_project_manifest_to_select_the_regist
177182

178183
assert_eq!(registry_prefix_of_project(project), Some("work".to_string()));
179184
}
185+
186+
#[test]
187+
fn a_prefix_the_workspace_does_not_declare_is_not_published() {
188+
let mut config = config_with_work_prefix();
189+
config.workspace_registry_prefixes.clear();
190+
let project = project_with_manifest(
191+
Path::new("/workspace/pkg"),
192+
json!({ "name": "@work/pkg", "version": "1.0.0" }),
193+
);
194+
195+
let map = build_workspace_package_manifest_map(&[project], &config).expect("build the map");
196+
197+
assert_eq!(map["@work/pkg"][0].registry_prefix, None);
198+
}
199+
200+
#[test]
201+
fn a_workspace_without_prefixes_does_not_read_publish_directories() {
202+
let root = tempfile::tempdir().expect("project dir");
203+
fs::create_dir_all(root.path().join("dist")).expect("create dist");
204+
fs::write(root.path().join("dist/package.json"), "{ not json")
205+
.expect("write the dist manifest");
206+
let project = project_publishing_from_dist(root.path(), json!({}), None);
207+
208+
let map = build_workspace_package_manifest_map(&[project], &Config::new())
209+
.expect("an unread manifest cannot fail the build");
210+
211+
assert_eq!(map["pkg-f"][0].registry_prefix, None);
212+
}
213+
214+
#[test]
215+
fn an_unreadable_publish_directory_manifest_is_an_error_when_prefixes_are_declared() {
216+
let root = tempfile::tempdir().expect("project dir");
217+
fs::create_dir_all(root.path().join("dist")).expect("create dist");
218+
fs::write(root.path().join("dist/package.json"), "{ not json")
219+
.expect("write the dist manifest");
220+
let project = project_publishing_from_dist(root.path(), json!({}), None);
221+
222+
build_workspace_package_manifest_map(&[project], &config_with_work_prefix())
223+
.expect_err("the prefix of a dependency on it would be guessed");
224+
}

‎pnpm/crates/config/src/registry_options.rs‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -338,20 +338,22 @@ impl Config {
338338
registries
339339
}
340340

341-
/// The named-registry prefix declared for the registry at `registry_url`:
342-
/// the `prefix` of a `registries` entry or a `namedRegistries` alias. A
343-
/// published manifest qualifies a `workspace:` dependency with it so the
344-
/// dependency names the registry its consumers address it by.
341+
/// The named-registry prefix the project's `pnpm-workspace.yaml` declares
342+
/// for the registry at `registry_url`: the `prefix` of a `registries`
343+
/// entry or a `namedRegistries` alias. A published manifest qualifies a
344+
/// `workspace:` dependency with it so the dependency names the registry
345+
/// its consumers address it by.
345346
///
346347
/// URLs compare with a trailing slash and a lower-case scheme and host.
347348
/// When several prefixes declare one URL, the first in alphabetical order
348-
/// is answered. The built-in `gh` and `npmjs` prefixes are not declared
349-
/// by the project and are never answered.
349+
/// is answered. Only [`Self::workspace_registry_prefixes`] are answered,
350+
/// so a published manifest does not depend on the machine that packed it.
350351
#[must_use]
351352
pub fn declared_registry_prefix(&self, registry_url: &str) -> Option<&str> {
352353
let wanted = comparable_registry_url(registry_url);
353354
self.registries_by_prefix
354355
.iter()
356+
.filter(|(prefix, _)| self.workspace_registry_prefixes.contains(*prefix))
355357
.find(|(_, url)| comparable_registry_url(url) == wanted)
356358
.map(|(prefix, _)| prefix.as_str())
357359
}

‎pnpm/crates/config/src/settings.rs‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -656,6 +656,11 @@ pub struct Config {
656656
/// `namedRegistries` setting.
657657
pub registries_by_prefix: BTreeMap<String, String>,
658658

659+
/// The keys of [`Self::registries_by_prefix`] that the project's
660+
/// `pnpm-workspace.yaml` declares. A prefix from the global `config.yaml`,
661+
/// the environment, or the command line is machine-local.
662+
pub workspace_registry_prefixes: BTreeSet<String>,
663+
659664
/// Non-secret per-registry settings from
660665
/// `pnpm-workspace.yaml#registries`, keyed by registry URL with a
661666
/// trailing slash. Deliberately separate from the auth config: that one

‎pnpm/crates/config/src/tests/declared_registry_prefix.rs‎

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
1-
use super::{Config, assert_eq};
1+
use super::{
2+
Config, EnvVar, EnvVarOs, GetCurrentDir, GetHomeDir, LinkProbe, OsString, Path, PathBuf,
3+
assert_eq, fs, io, tempdir,
4+
};
25

36
const WORK: &str = "https://npm.work.example.com/";
47

@@ -8,6 +11,10 @@ fn config_with_prefixes(prefixes: &[(&str, &str)]) -> Config {
811
.iter()
912
.map(|(prefix, url)| (prefix.to_string(), url.to_string()))
1013
.collect();
14+
config.workspace_registry_prefixes = prefixes
15+
.iter()
16+
.map(|(prefix, _)| prefix.to_string())
17+
.collect();
1118
config
1219
}
1320

@@ -37,3 +44,32 @@ fn the_built_in_prefixes_are_not_declared() {
3744
assert_eq!(Config::new().declared_registry_prefix("https://registry.npmjs.org/"), None);
3845
assert_eq!(Config::new().declared_registry_prefix("https://npm.pkg.github.com/"), None);
3946
}
47+
48+
#[test]
49+
fn only_prefixes_from_the_workspace_yaml_are_declared() {
50+
fake_env!(load_with_fake_env);
51+
let xdg = tempdir().expect("xdg tempdir");
52+
let config_dir = xdg.path().join("pnpm");
53+
fs::create_dir_all(&config_dir).expect("create config dir");
54+
fs::write(
55+
config_dir.join("config.yaml"),
56+
"namedRegistries:\n personal: https://registry.npmjs.org/\n mine: https://npm.mine.example.com/\n",
57+
)
58+
.expect("write global config.yaml");
59+
60+
let project = tempdir().expect("project tempdir");
61+
fs::write(
62+
project.path().join("pnpm-workspace.yaml"),
63+
format!("registries:\n {WORK}:\n prefix: work\nnamedRegistries:\n legacy: https://npm.legacy.example.com/\n"),
64+
)
65+
.expect("write workspace yaml");
66+
67+
set_fake_env(&[("XDG_CONFIG_HOME", xdg.path().to_str().unwrap())]);
68+
let config = load_with_fake_env(project.path());
69+
70+
assert_eq!(config.declared_registry_prefix(WORK), Some("work"));
71+
assert_eq!(config.declared_registry_prefix("https://npm.legacy.example.com/"), Some("legacy"));
72+
assert_eq!(config.declared_registry_prefix("https://registry.npmjs.org/"), None);
73+
assert_eq!(config.declared_registry_prefix("https://npm.mine.example.com/"), None);
74+
assert!(config.registries_by_prefix.contains_key("mine"), "global aliases still resolve");
75+
}

‎pnpm/crates/config/src/workspace_settings.rs‎

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use super::{
2-
Arc, Config, EnvVar, EnvVarOs, ExplicitPaths, GetCurrentDir, GetHomeDir, LinkProbe,
3-
LoadWorkspaceYamlError, Path, PathBuf, WorkspaceSettings, collect_explicit_settings,
2+
Arc, BTreeMap, BTreeSet, Config, EnvVar, EnvVarOs, ExplicitPaths, GetCurrentDir, GetHomeDir,
3+
LinkProbe, LoadWorkspaceYamlError, Path, PathBuf, WorkspaceSettings, collect_explicit_settings,
44
default_pnpm_home_dir, note_declared_registries, resolve_configured_state_dir,
55
workspace_yaml::{parse_settings, read_workspace_document},
66
};
@@ -115,6 +115,7 @@ impl Config {
115115
self.workspace_key_issues = settings.key_issues.clone();
116116
self.workspace_includes = settings.includes.take().map(Arc::new);
117117
note_declared_registries(declared_registries, &settings);
118+
self.workspace_registry_prefixes = workspace_registry_prefixes(&settings);
118119
collect_explicit_settings(&mut self.explicit_settings, &settings);
119120
settings.resolve_script_shell(base_dir);
120121
settings.apply_to(self, base_dir);
@@ -257,3 +258,15 @@ fn workspace_includes_start_dir(
257258
let patterns = settings.and_then(|settings| settings.packages.as_deref());
258259
pnpm_workspace::belongs_to_workspace(base_dir, start_dir, patterns).unwrap_or(true)
259260
}
261+
262+
/// The prefixes `settings` declares, through `registries` or the deprecated
263+
/// `namedRegistries`.
264+
fn workspace_registry_prefixes(settings: &WorkspaceSettings) -> BTreeSet<String> {
265+
let registries =
266+
settings.registries.iter().flat_map(crate::workspace_yaml::registries::declared_prefixes);
267+
let named = settings.named_registries.iter().flat_map(BTreeMap::keys);
268+
registries
269+
.chain(named.map(String::as_str))
270+
.map(str::to_owned)
271+
.collect()
272+
}

0 commit comments

Comments
 (0)