From 1fe3eb906dbedc7e69967834636d13875ab0545d Mon Sep 17 00:00:00 2001 From: Sakana <15715093608@163.com> Date: Sun, 22 Nov 2026 14:00:12 +0800 Subject: [PATCH 1/4] fix(pm): keep npm workspace root edits out of the current member A workspace member can become an implicit target of npm install and uninstall. Resolve the owning project before a root-only dependency edit, while keeping relative package arguments in the calling directory. Use npm to verify membership on early npm 8 and preserve explicit workspace selections. Cover member dependency and lockfile retention, including nested workspaces with the same package name. --- .../snapshots.toml | 5 +- .../command_add_npm11_with_workspace.md | 56 +++- .../package.json | 12 + .../packages/app/package.json | 12 + .../packages/app/plugins/docs/package.json | 7 + .../packages/docs/package.json | 7 + .../snapshots.toml | 10 + .../command_remove_npm8_nested_workspace.md | 67 ++++ crates/vp_pm_cli/src/config.rs | 93 +++++- crates/vp_pm_cli/src/resolution/command.rs | 14 +- .../vp_pm_cli/src/resolution/commands/add.rs | 11 +- .../src/resolution/commands/remove.rs | 18 +- crates/vp_pm_cli/src/resolution/dialect.rs | 24 ++ crates/vp_pm_cli/src/resolution/mod.rs | 2 + crates/vp_pm_cli/src/resolution/npm_entry.rs | 111 +++++++ .../vp_pm_cli/src/resolution/npm_workspace.rs | 288 ++++++++++++++++++ crates/vp_pm_cli/src/resolution/runner.rs | 7 +- 17 files changed, 721 insertions(+), 23 deletions(-) create mode 100644 crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/package.json create mode 100644 crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/packages/app/package.json create mode 100644 crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/packages/app/plugins/docs/package.json create mode 100644 crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/packages/docs/package.json create mode 100644 crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/snapshots.toml create mode 100644 crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/snapshots/command_remove_npm8_nested_workspace.md create mode 100644 crates/vp_pm_cli/src/resolution/npm_entry.rs create mode 100644 crates/vp_pm_cli/src/resolution/npm_workspace.rs diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm11_with_workspace/snapshots.toml b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm11_with_workspace/snapshots.toml index b3edd43e93..745e23f09d 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm11_with_workspace/snapshots.toml +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm11_with_workspace/snapshots.toml @@ -3,7 +3,7 @@ name = "command_add_npm11_with_workspace" vp = "global" skip-platforms = ["windows"] steps = [ - { argv = ["vp", "add", "testnpm2", "-D", "-w", "--", "--no-audit"], comment = "should add package to workspace root" }, + { argv = ["vp", "add", "testnpm2", "-D", "-w", "--", "--no-audit"], cwd = "packages/app", comment = "add to the root from a workspace member" }, { argv = ["vpt", "print-file", "package.json", "packages/app/package.json", "packages/utils/package.json"], continue-on-failure = true }, { argv = ["vp", "add", "@vite-plus-test/utils", "--workspace", "--", "--no-audit"], comment = "reject unsupported --workspace without adding packages to the root", continue-on-failure = true }, { argv = ["vpt", "print-file", "package.json", "packages/app/package.json", "packages/utils/package.json"], continue-on-failure = true }, @@ -17,4 +17,7 @@ steps = [ { argv = ["vpt", "print-file", "package.json", "packages/app/package.json", "packages/utils/package.json"], continue-on-failure = true }, { argv = ["vp", "install", "test-vite-plus-package@1.0.0", "--filter", "*", "--workspace-root", "--", "--no-audit"], comment = "should install packages alias for add command" }, { argv = ["vpt", "print-file", "package.json", "packages/app/package.json", "packages/utils/package.json"], continue-on-failure = true }, + { argv = ["vp", "remove", "-w", "testnpm2", "--", "--no-audit"], cwd = "packages/app", comment = "remove the root devDependency and preserve the member dependencies" }, + { argv = ["vpt", "print-file", "package.json", "packages/app/package.json", "packages/utils/package.json"] }, + { argv = ["node", "-e", "const { packages } = require('./package-lock.json'); console.log(packages[''].devDependencies?.testnpm2, packages['packages/app'].dependencies.testnpm2)"], comment = "the lockfile records the same removal at the root and keeps the app dependency" }, ] diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm11_with_workspace/snapshots/command_add_npm11_with_workspace.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm11_with_workspace/snapshots/command_add_npm11_with_workspace.md index 4f9e5a0234..50b7440aed 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm11_with_workspace/snapshots/command_add_npm11_with_workspace.md +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm11_with_workspace/snapshots/command_add_npm11_with_workspace.md @@ -1,8 +1,8 @@ # command_add_npm11_with_workspace -## `vp add testnpm2 -D -w -- --no-audit` +## `cd packages/app && vp add testnpm2 -D -w -- --no-audit` -should add package to workspace root +add to the root from a workspace member ``` @@ -274,3 +274,55 @@ added 1 package in } } ``` + +## `cd packages/app && vp remove -w testnpm2 -- --no-audit` + +remove the root devDependency and preserve the member dependencies + +``` + +up to date in +``` + +## `vpt print-file package.json packages/app/package.json packages/utils/package.json` + +``` +{ + "name": "command-add-npm11-with-workspace", + "version": "1.0.0", + "workspaces": [ + "packages/*" + ], + "packageManager": "npm@11.6.2", + "dependencies": { + "test-vite-plus-install": "1.0.0", + "test-vite-plus-package": "^1.0.0" + } +} +{ + "name": "app", + "dependencies": { + "test-vite-plus-install": "1.0.0", + "test-vite-plus-package": "^1.0.0", + "testnpm2": "1.0.1" + } +} +{ + "name": "@vite-plus-test/utils", + "version": "1.0.0", + "private": true, + "dependencies": { + "test-vite-plus-install": "1.0.0", + "test-vite-plus-package": "^1.0.0", + "testnpm2": "1.0.1" + } +} +``` + +## `node -e 'const { packages } = require('\''./package-lock.json'\''); console.log(packages['\'''\''].devDependencies?.testnpm2, packages['\''packages/app'\''].dependencies.testnpm2)'` + +the lockfile records the same removal at the root and keeps the app dependency + +``` +undefined 1.0.1 +``` diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/package.json b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/package.json new file mode 100644 index 0000000000..6b7e54e44f --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/package.json @@ -0,0 +1,12 @@ +{ + "name": "root", + "private": true, + "packageManager": "npm@8.1.0", + "workspaces": [ + "packages/*" + ], + "devDependencies": { + "testnpm2": "1.0.1", + "test-vite-plus-install": "1.0.0" + } +} diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/packages/app/package.json b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/packages/app/package.json new file mode 100644 index 0000000000..aa4ddee795 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/packages/app/package.json @@ -0,0 +1,12 @@ +{ + "name": "app", + "version": "1.0.0", + "packageManager": "npm@8.1.0", + "workspaces": [ + "plugins/*" + ], + "dependencies": { + "testnpm2": "1.0.1", + "test-vite-plus-install": "1.0.0" + } +} diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/packages/app/plugins/docs/package.json b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/packages/app/plugins/docs/package.json new file mode 100644 index 0000000000..49e5bba220 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/packages/app/plugins/docs/package.json @@ -0,0 +1,7 @@ +{ + "name": "docs", + "version": "1.0.0", + "dependencies": { + "test-vite-plus-install": "1.0.0" + } +} diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/packages/docs/package.json b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/packages/docs/package.json new file mode 100644 index 0000000000..49e5bba220 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/packages/docs/package.json @@ -0,0 +1,7 @@ +{ + "name": "docs", + "version": "1.0.0", + "dependencies": { + "test-vite-plus-install": "1.0.0" + } +} diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/snapshots.toml b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/snapshots.toml new file mode 100644 index 0000000000..53c65d8166 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/snapshots.toml @@ -0,0 +1,10 @@ +[[case]] +name = "command_remove_npm8_nested_workspace" +vp = "global" +steps = [ + { argv = ["vp", "remove", "-w", "testnpm2", "--", "--no-audit"], cwd = "packages/app", comment = "remove only the outer root declaration when the current member owns a workspace" }, + { argv = ["vp", "remove", "-w", "--filter", "docs", "test-vite-plus-install", "--", "--no-audit"], cwd = "packages/app", comment = "select the outer docs package when the inner workspace also has a member named docs" }, + ["vpt", "print-file", "package.json", "packages/app/package.json", "packages/docs/package.json", "packages/app/plugins/docs/package.json"], + ["node", "-p", "require('./package-lock.json').packages['packages/app'].dependencies"], + ["vpt", "stat-file", "packages/app/package-lock.json", "--assert", "missing"], +] diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/snapshots/command_remove_npm8_nested_workspace.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/snapshots/command_remove_npm8_nested_workspace.md new file mode 100644 index 0000000000..acf7021695 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/snapshots/command_remove_npm8_nested_workspace.md @@ -0,0 +1,67 @@ +# command_remove_npm8_nested_workspace + +## `cd packages/app && vp remove -w testnpm2 -- --no-audit` + +remove only the outer root declaration when the current member owns a workspace + +``` + +added 4 packages in +``` + +## `cd packages/app && vp remove -w --filter docs test-vite-plus-install -- --no-audit` + +select the outer docs package when the inner workspace also has a member named docs + +``` + +up to date in +``` + +## `vpt print-file package.json packages/app/package.json packages/docs/package.json packages/app/plugins/docs/package.json` + +``` +{ + "name": "root", + "private": true, + "packageManager": "npm@8.1.0", + "workspaces": [ + "packages/*" + ] +} +{ + "name": "app", + "version": "1.0.0", + "packageManager": "npm@8.1.0", + "workspaces": [ + "plugins/*" + ], + "dependencies": { + "testnpm2": "1.0.1", + "test-vite-plus-install": "1.0.0" + } +} +{ + "name": "docs", + "version": "1.0.0" +} +{ + "name": "docs", + "version": "1.0.0", + "dependencies": { + "test-vite-plus-install": "1.0.0" + } +} +``` + +## `node -p require('./package-lock.json').packages['packages/app'].dependencies` + +``` +{ 'test-vite-plus-install': '1.0.0', testnpm2: '1.0.1' } +``` + +## `vpt stat-file packages/app/package-lock.json --assert missing` + +``` +packages/app/package-lock.json: missing +``` diff --git a/crates/vp_pm_cli/src/config.rs b/crates/vp_pm_cli/src/config.rs index 2038258f23..52dcd3c662 100644 --- a/crates/vp_pm_cli/src/config.rs +++ b/crates/vp_pm_cli/src/config.rs @@ -45,15 +45,8 @@ impl NpmConfig { project_root: Option, cwd: Option<&AbsolutePath>, ) -> Self { - let mut project_values = HashMap::new(); - if let Some(root) = project_root { - load_npmrc(root.join(".npmrc"), &mut project_values); - } - let user_config = npm_user_config_path(cwd) - .or_else(|| project_values.get("userconfig").map(|path| config_path(path, cwd))) - .unwrap_or_else(|| EnvConfig::get().user_home.join(".npmrc").into_path_buf()); - let mut user_values = HashMap::new(); - load_npmrc(user_config, &mut user_values); + let (project_values, user_values) = + project_and_user_npmrc(project_root, cwd, npm_user_config_path(cwd)); // Higher-priority layers select config files; merge their values from low to high. // Default global paths require npm, so only explicitly selected files are loaded. @@ -341,6 +334,23 @@ fn load_npmrc(path: PathBuf, values: &mut HashMap) { } } +fn project_and_user_npmrc( + project_root: Option, + cwd: Option<&AbsolutePath>, + userconfig: Option, +) -> (HashMap, HashMap) { + let mut project = HashMap::new(); + if let Some(root) = project_root { + load_npmrc(root.join(".npmrc"), &mut project); + } + let userconfig = userconfig + .or_else(|| project.get("userconfig").map(|path| config_path(path, cwd))) + .unwrap_or_else(|| EnvConfig::get().user_home.join(".npmrc").into_path_buf()); + let mut user = HashMap::new(); + load_npmrc(userconfig, &mut user); + (project, user) +} + fn parse_npmrc_value(value: &str) -> String { let value = value.trim(); if value.len() >= 2 && value.starts_with('"') && value.ends_with('"') { @@ -390,6 +400,35 @@ pub fn npm_user_config_path(cwd: Option<&AbsolutePath>) -> Option { env_value("userconfig").map(|path| config_path(&expand_value(&path), cwd)) } +/// Find the global npmrc selected before a workspace edit overrides npm's prefix. +pub(crate) fn workspace_globalconfig( + root: &AbsolutePath, + cwd: &AbsolutePath, + cli_userconfig: Option<&str>, + env: &HashMap, +) -> Option { + let from_env = |name: &str| { + let key = vt_str::format!("npm_config_{name}"); + env.iter() + .find(|(name, _)| name.eq_ignore_ascii_case(&key)) + .and_then(|(_, value)| (!value.is_empty()).then(|| expand_value(value))) + .or_else(|| env_value(name).map(|value| expand_value(&value))) + }; + let userconfig = cli_userconfig + .map(expand_value) + .or_else(|| from_env("userconfig")) + .map(|value| config_path(&value, Some(cwd))); + let (project, user) = + project_and_user_npmrc(Some(root.as_path().to_path_buf()), Some(cwd), userconfig); + let configured = |key: &str| { + from_env(key) + .or_else(|| project.get(key).cloned()) + .or_else(|| user.get(key).cloned()) + .map(|value| config_path(&value, Some(cwd))) + }; + configured("globalconfig").or_else(|| configured("prefix").map(|p| p.join("etc/npmrc"))) +} + /// Resolve the `Authorization` header value npm would send to `url` from the npm config at `cwd`. #[must_use] pub fn npm_authorization_for_url(cwd: &AbsolutePath, url: &str) -> Option { @@ -572,6 +611,42 @@ mod tests { }); } + #[test] + fn workspace_globalconfig_resolves_project_and_user_paths_from_the_caller() { + let root = project_with_npmrc("userconfig=./user.npmrc\nprefix=./project-prefix\n"); + let caller = root.path().join("child"); + fs::create_dir(&caller).unwrap(); + fs::write(caller.join("user.npmrc"), "globalconfig=./user-global.npmrc\n").unwrap(); + let root = AbsolutePath::new(root.path()).unwrap(); + let cwd = AbsolutePath::new(&caller).unwrap(); + EnvConfig::with_vars( + [ + ("npm_config_userconfig", None::<&std::ffi::OsStr>), + ("NPM_CONFIG_USERCONFIG", None), + ("npm_config_globalconfig", None), + ("NPM_CONFIG_GLOBALCONFIG", None), + ("npm_config_prefix", None), + ("NPM_CONFIG_PREFIX", None), + ], + |_| { + let mut env = HashMap::new(); + assert_eq!( + workspace_globalconfig(root, cwd, None, &env), + Some(caller.join("user-global.npmrc")), + ); + env.insert("NPM_CONFIG_USERCONFIG".into(), "missing".into()); + assert_eq!( + workspace_globalconfig(root, cwd, None, &env), + Some(caller.join("project-prefix/etc/npmrc")), + ); + assert_eq!( + workspace_globalconfig(root, cwd, Some("user.npmrc"), &env), + Some(caller.join("user-global.npmrc")), + ); + }, + ); + } + #[test] fn relative_config_paths_use_caller_cwd_without_changing_workspace_root() { with_isolated_npm_config(|| { diff --git a/crates/vp_pm_cli/src/resolution/command.rs b/crates/vp_pm_cli/src/resolution/command.rs index c81e8188f6..1d5fddb89c 100644 --- a/crates/vp_pm_cli/src/resolution/command.rs +++ b/crates/vp_pm_cli/src/resolution/command.rs @@ -13,6 +13,7 @@ pub(crate) struct ResolvedCommand { pub(crate) args: Vec, pub(crate) env: BTreeMap, pub(crate) pre_run: Vec, + pub(crate) npm_workspace_edit: Option, } impl ResolvedCommand { @@ -23,7 +24,7 @@ impl ResolvedCommand { // Include npm/npx fallbacks: Vite+ manages their versions too. env.insert("npm_config_update_notifier".to_string(), "false".to_string()); } - Self { program, args: Vec::new(), env, pre_run: Vec::new() } + Self { program, args: Vec::new(), env, pre_run: Vec::new(), npm_workspace_edit: None } } } @@ -33,6 +34,12 @@ impl From for CommandResolution { } } +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum NpmWorkspaceEdit { + AutomaticRoot, + LegacyRoot { local_dependency: bool }, +} + #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) enum PreRunAction { CreateDir { path: String }, @@ -94,6 +101,11 @@ impl CommandBuilder { self } + pub(crate) fn npm_workspace_edit(&mut self, edit: Option) -> &mut Self { + self.command.npm_workspace_edit = edit; + self + } + pub(crate) fn create_dir(&mut self, path: impl ToString) -> &mut Self { self.command.pre_run.push(PreRunAction::CreateDir { path: path.to_string() }); self diff --git a/crates/vp_pm_cli/src/resolution/commands/add.rs b/crates/vp_pm_cli/src/resolution/commands/add.rs index 1973513a27..53c38b2cf2 100644 --- a/crates/vp_pm_cli/src/resolution/commands/add.rs +++ b/crates/vp_pm_cli/src/resolution/commands/add.rs @@ -227,9 +227,14 @@ impl Npm { return cmd.into(); } - cmd.arg("install") - .repeated("--workspace", args.filter.iter()) - .arg_if("--include-workspace-root", args.workspace_root); + cmd.npm_workspace_edit(self.workspace_edit( + args.workspace_root && !args.packages.is_empty(), + !args.filter.is_empty(), + &args.packages, + )) + .arg("install") + .repeated("--workspace", args.filter.iter()) + .arg_if("--include-workspace-root", args.workspace_root); match args.save_dependency.target() { Some(SaveDependencyTarget::Production) => { // `--save` overrides npm's `save=false` setting when the user explicitly selects production. diff --git a/crates/vp_pm_cli/src/resolution/commands/remove.rs b/crates/vp_pm_cli/src/resolution/commands/remove.rs index e2b3a6516e..764ae9254f 100644 --- a/crates/vp_pm_cli/src/resolution/commands/remove.rs +++ b/crates/vp_pm_cli/src/resolution/commands/remove.rs @@ -51,7 +51,7 @@ pub struct RemoveArgs { impl Resolve for Pnpm { fn resolve(&self, args: &RemoveArgs, _diag: &mut Diagnostics) -> CommandResolution { if args.global { - return Npm::resolve_remove(args); + return Npm::unknown_version().resolve_remove(args); } let mut cmd = CommandBuilder::new("pnpm"); @@ -69,7 +69,7 @@ impl Resolve for Pnpm { } impl Npm { - fn resolve_remove(args: &RemoveArgs) -> CommandResolution { + fn resolve_remove(&self, args: &RemoveArgs) -> CommandResolution { let mut cmd = CommandBuilder::new("npm"); if args.global { cmd.arg("uninstall") @@ -79,7 +79,13 @@ impl Npm { return cmd.into(); } - cmd.arg("uninstall").repeated("--workspace", args.filter.iter()); + cmd.npm_workspace_edit(self.workspace_edit( + args.workspace_root && !args.recursive, + !args.filter.is_empty(), + &[], + )) + .arg("uninstall") + .repeated("--workspace", args.filter.iter()); if args.workspace_root || args.recursive { cmd.arg("--include-workspace-root"); } @@ -95,14 +101,14 @@ impl Npm { impl Resolve for Npm { fn resolve(&self, args: &RemoveArgs, _diag: &mut Diagnostics) -> CommandResolution { - Self::resolve_remove(args) + self.resolve_remove(args) } } impl Resolve for Yarn { fn resolve(&self, args: &RemoveArgs, _diag: &mut Diagnostics) -> CommandResolution { if args.global { - return Npm::resolve_remove(args); + return Npm::unknown_version().resolve_remove(args); } let mut cmd = CommandBuilder::new("yarn"); @@ -132,7 +138,7 @@ impl Resolve for Yarn { impl Resolve for Bun { fn resolve(&self, args: &RemoveArgs, _diag: &mut Diagnostics) -> CommandResolution { if args.global { - return Npm::resolve_remove(args); + return Npm::unknown_version().resolve_remove(args); } let mut cmd = CommandBuilder::new("bun"); diff --git a/crates/vp_pm_cli/src/resolution/dialect.rs b/crates/vp_pm_cli/src/resolution/dialect.rs index f853867018..c4864ad608 100644 --- a/crates/vp_pm_cli/src/resolution/dialect.rs +++ b/crates/vp_pm_cli/src/resolution/dialect.rs @@ -57,6 +57,30 @@ impl Npm { Self { version: None } } + pub(crate) fn workspace_edit( + &self, + enabled: bool, + has_filter: bool, + packages: &[String], + ) -> Option { + use super::command::NpmWorkspaceEdit; + if !enabled { + return None; + } + if self.version.as_ref().is_some_and(|v| v < &Version::new(8, 5, 0)) { + Some(NpmWorkspaceEdit::LegacyRoot { + local_dependency: packages + .iter() + .any(|spec| super::npm_workspace::is_local_dependency(spec)), + }) + } else if has_filter { + // npm 8.5+ already resolves explicit selections from the calling directory. + None + } else { + Some(NpmWorkspaceEdit::AutomaticRoot) + } + } + /// `--omit` and `--include` landed in npm 7. Unknown versions are treated as current. pub(crate) fn supports_v7_commands(&self) -> bool { self.version.as_ref().is_none_or(|version| version >= &Version::new(7, 0, 0)) diff --git a/crates/vp_pm_cli/src/resolution/mod.rs b/crates/vp_pm_cli/src/resolution/mod.rs index 52302e0da0..66fdf627ed 100644 --- a/crates/vp_pm_cli/src/resolution/mod.rs +++ b/crates/vp_pm_cli/src/resolution/mod.rs @@ -31,6 +31,8 @@ mod command; mod commands; mod diagnostics; mod dialect; +mod npm_entry; +mod npm_workspace; mod resolve; mod runner; mod support; diff --git a/crates/vp_pm_cli/src/resolution/npm_entry.rs b/crates/vp_pm_cli/src/resolution/npm_entry.rs new file mode 100644 index 0000000000..8c0f0883a7 --- /dev/null +++ b/crates/vp_pm_cli/src/resolution/npm_entry.rs @@ -0,0 +1,111 @@ +//! Find a member's enclosing npm project on releases before automatic workspace roots. +use std::{ + collections::HashMap, + ffi::OsString, + fs, io, + path::{Component, Path, PathBuf}, + process::Stdio, +}; + +use serde_json::{Map, Value}; +use vt_path::AbsolutePath; + +use crate::Error; + +pub(super) async fn legacy_root( + cwd: &AbsolutePath, + npm: &AbsolutePath, + env: &HashMap, +) -> Result { + let package = vt_workspace::find_package_root(cwd)?; + let member = package.path.as_path(); + let parse_manifest = |bytes: &[u8]| { + serde_json::from_slice::(bytes.strip_prefix(b"\xef\xbb\xbf").unwrap_or(bytes)) + }; + let member_manifest = parse_manifest(package.package_json.content())?; + // npm 8 also treats a path selector as a glob for that directory's children. + // An empty brace alternative expands to the same glob but changes the exact path. + let mut children = PathBuf::new(); + let mut add_braces = true; + for component in member.components() { + if add_braces && let Component::Normal(name) = component { + let mut part = OsString::from("{,}"); + part.push(name); + children.push(part); + add_braces = false; + } else { + children.push(component); + } + } + for ancestor in member.ancestors().skip(1) { + let bytes = match fs::read(ancestor.join("package.json")) { + Ok(bytes) => bytes, + Err(error) if error.kind() == io::ErrorKind::NotFound => continue, + Err(error) => return Err(error.into()), + }; + let Ok(manifest) = parse_manifest(&bytes) else { continue }; + if manifest["workspaces"].is_null() { + continue; + } + // npm keys the response by name. If a member can replace the root's + // entry, compare the manifests too. An ordinary query needs only names. + let same_name = + member_manifest["name"].is_null() || member_manifest["name"] == manifest["name"]; + let selected = workspace_entries(npm, cwd, env, ancestor, member, same_name).await?; + let descendants = workspace_entries(npm, cwd, env, ancestor, &children, same_name).await?; + if selected.iter().any(|(name, value)| descendants.get(name) != Some(value)) { + return Ok(ancestor.to_owned()); + } + // A literal globstar or brace expansion can match the directory itself. An + // identical manifest can also hide behind the root's key in npm's JSON. + let could_match_itself = member.components().any(|part| { + let segment = part.as_os_str().to_string_lossy(); + segment.contains("**") || segment.contains(['{', '}']) + }); + let name_was_selected = + member_manifest["name"].as_str().is_none_or(|name| selected.contains_key(name)); + if name_was_selected && could_match_itself || same_name && member_manifest == manifest { + return Err(Error::UserMessage( + "Could not distinguish the workspace path from its matches with this npm version." + .into(), + )); + } + } + Ok(member.to_owned()) +} + +async fn workspace_entries( + npm: &AbsolutePath, + cwd: &AbsolutePath, + env: &HashMap, + root: &Path, + filter: &Path, + compare_manifests: bool, +) -> Result, Error> { + let mut command = super::npm_workspace::npm_probe(npm, cwd); + command.args(["pkg", "get"]); + if !compare_manifests { + command.arg("name"); + } + // Including the root gives both queries a common entry when no member matches. + let output = command + .args(["--include-workspace-root", "--prefix"]) + .arg(root) + .arg("--workspace") + .arg(filter) + .envs(env) + .env_remove("NODE_OPTIONS") + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .await?; + if !output.status.success() { + return Err(Error::UserMessage(vt_str::format!( + "Could not read npm workspaces in {}: {}", + root.display(), + String::from_utf8_lossy(&output.stderr).trim() + ))); + } + Ok(serde_json::from_slice(&output.stdout)?) +} diff --git a/crates/vp_pm_cli/src/resolution/npm_workspace.rs b/crates/vp_pm_cli/src/resolution/npm_workspace.rs new file mode 100644 index 0000000000..bcf143f86a --- /dev/null +++ b/crates/vp_pm_cli/src/resolution/npm_workspace.rs @@ -0,0 +1,288 @@ +//! Select the owner of a workspace dependency edit without changing the caller's directory. +use std::{ + collections::HashMap, + ffi::OsStr, + io, + path::{Path, PathBuf}, + process::Stdio, +}; + +use cow_utils::CowUtils; +use vt_path::AbsolutePath; + +use super::{command::NpmWorkspaceEdit, npm_entry::legacy_root}; +use crate::Error; + +pub(super) async fn edit_args( + program: &str, + cwd: &AbsolutePath, + edit: NpmWorkspaceEdit, + mut args: Vec, + env: &HashMap, +) -> Result, Error> { + let flags = args.iter().take_while(|arg| arg.as_str() != "--"); + let mut has_selector = std::env::vars_os().any(|(key, value)| { + !value.is_empty() + && key.to_str().is_some_and(|key| key.eq_ignore_ascii_case("npm_config_workspace")) + }); + let mut has_globalconfig = false; + for arg in flags { + let (option, value) = arg.split_once('=').unwrap_or((arg, "")); + match option { + "--global" | "-g" if value != "false" => return Ok(args), + "--include-workspace-root" if value == "false" => return Ok(args), + "--prefix" | "--no-workspaces" | "--no-include-workspace-root" => { + return Ok(args); + } + "--workspace" | "-w" | "--workspaces" | "-ws" => has_selector = true, + "--globalconfig" => has_globalconfig = true, + _ => {} + } + } + if edit == NpmWorkspaceEdit::AutomaticRoot && has_selector { + return Ok(args); + } + + let Ok(package) = vt_workspace::find_package_root(cwd) else { return Ok(args) }; + if !package.path.as_path().ancestors().skip(1).any(|p| p.join("package.json").is_file()) { + return Ok(args); + } + let npm = vp_command::resolve_bin(program, env.get("PATH").map(OsStr::new), cwd)?; + let root = match edit { + NpmWorkspaceEdit::AutomaticRoot => npm_path(&npm, cwd, &["prefix"], env).await?, + NpmWorkspaceEdit::LegacyRoot { .. } => legacy_root(cwd, &npm, env).await?, + }; + if root == package.path.as_path() { + return Ok(args); + } + let root = AbsolutePath::new(&root) + .ok_or_else(|| io::Error::other("npm returned a relative workspace root"))?; + + if matches!(edit, NpmWorkspaceEdit::LegacyRoot { .. }) { + // Early npm 8 interprets even ./ and ../ workspace paths from its prefix. + let mut next_selector = false; + for arg in &mut args { + if arg == "--" { + break; + } + if next_selector { + *arg = caller_selector(arg, cwd); + next_selector = false; + } else if matches!(arg.as_str(), "--workspace" | "-w") { + next_selector = true; + } else if let Some((option, value)) = arg.split_once('=') + && matches!(option, "--workspace" | "-w") + { + *arg = vt_str::format!("{option}={}", caller_selector(value, cwd)).to_string(); + } + } + } + if !has_globalconfig { + let globalconfig = original_globalconfig(&npm, root, cwd, &args, env).await?; + args.insert(1, vt_str::format!("--globalconfig={}", globalconfig.display()).to_string()); + } + args.insert(1, vt_str::format!("--prefix={}", root.as_path().display()).to_string()); + if matches!(edit, NpmWorkspaceEdit::LegacyRoot { local_dependency: true }) + && (has_selector || legacy_config_selects_members(&npm, cwd, &args, env).await?) + { + // Early Arborist writes the same root-relative file path into every selected manifest. + return Err(Error::UserMessage( + "Adding a local dependency to both the root and a workspace requires npm 8.19.0 or later.".into(), + )); + } + Ok(args) +} + +// A selection can come from any npmrc. A non-workspace `npm pkg get name` returns +// the root's name (or an empty object). A workspace query returns a map of packages. +async fn legacy_config_selects_members( + npm: &AbsolutePath, + cwd: &AbsolutePath, + args: &[String], + env: &HashMap, +) -> Result { + let mut probe = npm_probe(npm, cwd); + probe.args(["pkg", "get", "name", "--include-workspace-root"]); + let mut flags = args.iter().take_while(|arg| arg.as_str() != "--"); + while let Some(arg) = flags.next() { + let key = arg.split('=').next().unwrap_or(arg); + if matches!(key, "--prefix" | "--globalconfig" | "--userconfig") { + probe.arg(arg); + if arg == key + && let Some(value) = flags.next() + { + probe.arg(value); + } + } + } + let output = probe + .envs(env) + .env_remove("NODE_OPTIONS") + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .await?; + if !output.status.success() { + return Err(Error::UserMessage( + "Could not check npm's configured workspace selection.".into(), + )); + } + let selection: serde_json::Value = serde_json::from_slice(&output.stdout)?; + Ok(selection.as_object().is_some_and(|members| !members.is_empty())) +} + +async fn original_globalconfig( + npm: &AbsolutePath, + root: &AbsolutePath, + cwd: &AbsolutePath, + args: &[String], + env: &HashMap, +) -> Result { + let mut userconfig = None; + let mut flags = args.iter().take_while(|arg| arg.as_str() != "--"); + while let Some(arg) = flags.next() { + if arg == "--userconfig" { + userconfig = flags.next().map(String::as_str); + } else if let Some(path) = arg.strip_prefix("--userconfig=") { + userconfig = Some(path); + } + } + if let Some(path) = crate::config::workspace_globalconfig(root, cwd, userconfig, env) { + return Ok(path); + } + + // Ask this npm installation for its default. Its global mode rejects workspace + // selectors, and the caller's selected user npmrc has already been checked. + let mut probe_env = env.clone(); + for key in + std::env::vars_os().filter_map(|(key, _)| key.into_string().ok()).chain(env.keys().cloned()) + { + if key.eq_ignore_ascii_case("npm_config_workspace") + || key.eq_ignore_ascii_case("npm_config_workspaces") + { + probe_env.insert(key, String::new()); + } + } + let userconfig = if cfg!(windows) { "--userconfig=NUL" } else { "--userconfig=/dev/null" }; + npm_path(npm, cwd, &["config", "get", "globalconfig", "--global", userconfig], &probe_env).await +} + +// Early npm saves local paths relative to the root even in a member's manifest. +pub(super) fn is_local_dependency(package: &str) -> bool { + fn is_path(spec: &str) -> bool { + spec.starts_with('.') + || spec.starts_with("~/") + || Path::new(spec).is_absolute() + || spec.get(..5).is_some_and(|prefix| prefix.eq_ignore_ascii_case("file:")) + || spec.as_bytes().get(1) == Some(&b':') + || (cfg!(windows) && spec.contains('\\')) + } + if is_path(package) { + return true; + } + let unscoped = package.strip_prefix('@').unwrap_or(package); + let spec = unscoped.split_once('@').map_or(package, |(_, spec)| spec); + if is_path(spec) { + return true; + } + // Remote URLs, hosted Git references and registry aliases can also contain slashes. + let path = spec.split('#').next().unwrap_or(spec); + if path.contains(':') || package.contains("://") { + return false; + } + if let Some((owner, repo)) = path.split_once('/') { + if owner.starts_with('@') { + return repo.contains('/'); + } + return repo.is_empty() || repo.contains('/') || path.contains(char::is_whitespace); + } + let lower = path.cow_to_ascii_lowercase(); + lower.ends_with(".tgz") || lower.ends_with(".tar") || lower.ends_with(".tar.gz") +} + +fn caller_selector(value: &str, cwd: &AbsolutePath) -> String { + let path = Path::new(value); + if path.starts_with(".") || path.starts_with("..") { + cwd.as_path().join(path).to_string_lossy().into_owned() + } else { + value.to_owned() + } +} + +// Use the same Windows shim as the final install or uninstall command. +pub(super) fn npm_probe(npm: &AbsolutePath, cwd: &AbsolutePath) -> tokio::process::Command { + if let Some((program, args)) = vp_command::rewrite_cmd_to_powershell(npm) { + let mut command = vp_command::build_command(&program, cwd); + command.args(args); + command + } else { + vp_command::build_command(npm, cwd) + } +} + +async fn npm_path( + npm: &AbsolutePath, + cwd: &AbsolutePath, + args: &[&str], + env: &HashMap, +) -> Result { + let output = npm_probe(npm, cwd) + .args(args) + .arg("--json=false") + .envs(env) + .env_remove("NODE_OPTIONS") + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .await?; + if !output.status.success() { + return Err(Error::UserMessage(vt_str::format!( + "Could not read npm {}: {}", + args[0], + String::from_utf8_lossy(&output.stderr).trim() + ))); + } + let path = std::str::from_utf8(&output.stdout) + .map_err(io::Error::other)? + .trim_end_matches(['\r', '\n']); + if !Path::new(path).is_absolute() { + return Err(Error::UserMessage( + "npm returned an invalid configuration or prefix path".into(), + )); + } + Ok(PathBuf::from(path)) +} + +#[cfg(test)] +mod tests { + use super::is_local_dependency; + + #[test] + fn early_npm_local_dependencies() { + for package in [ + "file:./a@b", + "./pkg", + "/tmp/a@b.tgz", + "a.tgz", + "pkg@a.tar.gz", + "@scope/pkg@file:./a.tgz", + "nested/path/to/package", + "with spaces/pkg", + ] { + assert!(is_local_dependency(package), "{package}"); + } + for package in [ + "pkg@~1", + "@scope/pkg", + "pkg@npm:@scope/other@1", + "owner/repo", + "owner/repo#feature/branch", + "https://example.com/a.tgz", + "git+ssh://git@example.com/a/b", + ] { + assert!(!is_local_dependency(package), "{package}"); + } + } +} diff --git a/crates/vp_pm_cli/src/resolution/runner.rs b/crates/vp_pm_cli/src/resolution/runner.rs index 58a26a84a3..a70ce982f1 100644 --- a/crates/vp_pm_cli/src/resolution/runner.rs +++ b/crates/vp_pm_cli/src/resolution/runner.rs @@ -27,10 +27,15 @@ pub(crate) async fn run_resolution( } async fn run_command(cwd: &AbsolutePath, command: ResolvedCommand) -> Result { - let ResolvedCommand { program, args, env, pre_run } = command; + let ResolvedCommand { program, args, env, pre_run, npm_workspace_edit } = command; run_pre_run_actions(cwd, pre_run).await?; let env = env.into_iter().collect::>(); + let args = if let Some(edit) = npm_workspace_edit { + super::npm_workspace::edit_args(&program, cwd, edit, args, &env).await? + } else { + args + }; Ok(vp_command::run_command(&program, args, &env, cwd).await?) } From 6c78634dee389d77586782f6ca7017fd8c393e06 Mon Sep 17 00:00:00 2001 From: Sakana <15715093608@163.com> Date: Sun, 22 Nov 2026 14:24:34 +0800 Subject: [PATCH 2/4] fix(pm): preserve Windows paths in npm workspace edits PowerShell splits attached path options at the drive colon when it runs the npm shim with -File. Pass generated prefix, global config and caller-relative workspace paths as separate arguments so npm edits the intended project. Extend the nested npm 8 fixture to remove a dependency from the outer docs workspace using a caller-relative selector. --- .../packages/docs/package.json | 1 + .../snapshots.toml | 1 + .../command_remove_npm8_nested_workspace.md | 9 +++ .../vp_pm_cli/src/resolution/npm_workspace.rs | 58 +++++++++++-------- 4 files changed, 45 insertions(+), 24 deletions(-) diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/packages/docs/package.json b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/packages/docs/package.json index 49e5bba220..0dbbff9ce8 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/packages/docs/package.json +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/packages/docs/package.json @@ -2,6 +2,7 @@ "name": "docs", "version": "1.0.0", "dependencies": { + "testnpm2": "1.0.1", "test-vite-plus-install": "1.0.0" } } diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/snapshots.toml b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/snapshots.toml index 53c65d8166..d31e553239 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/snapshots.toml +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/snapshots.toml @@ -4,6 +4,7 @@ vp = "global" steps = [ { argv = ["vp", "remove", "-w", "testnpm2", "--", "--no-audit"], cwd = "packages/app", comment = "remove only the outer root declaration when the current member owns a workspace" }, { argv = ["vp", "remove", "-w", "--filter", "docs", "test-vite-plus-install", "--", "--no-audit"], cwd = "packages/app", comment = "select the outer docs package when the inner workspace also has a member named docs" }, + { argv = ["vp", "remove", "-w", "testnpm2", "--", "--workspace=../docs", "--no-audit"], cwd = "packages/app", comment = "resolve an attached workspace path from the calling member" }, ["vpt", "print-file", "package.json", "packages/app/package.json", "packages/docs/package.json", "packages/app/plugins/docs/package.json"], ["node", "-p", "require('./package-lock.json').packages['packages/app'].dependencies"], ["vpt", "stat-file", "packages/app/package-lock.json", "--assert", "missing"], diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/snapshots/command_remove_npm8_nested_workspace.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/snapshots/command_remove_npm8_nested_workspace.md index acf7021695..38e446f869 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/snapshots/command_remove_npm8_nested_workspace.md +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/snapshots/command_remove_npm8_nested_workspace.md @@ -18,6 +18,15 @@ select the outer docs package when the inner workspace also has a member named d up to date in ``` +## `cd packages/app && vp remove -w testnpm2 -- --workspace=../docs --no-audit` + +resolve an attached workspace path from the calling member + +``` + +up to date in +``` + ## `vpt print-file package.json packages/app/package.json packages/docs/package.json packages/app/plugins/docs/package.json` ``` diff --git a/crates/vp_pm_cli/src/resolution/npm_workspace.rs b/crates/vp_pm_cli/src/resolution/npm_workspace.rs index bcf143f86a..f513c9a9b4 100644 --- a/crates/vp_pm_cli/src/resolution/npm_workspace.rs +++ b/crates/vp_pm_cli/src/resolution/npm_workspace.rs @@ -60,28 +60,15 @@ pub(super) async fn edit_args( if matches!(edit, NpmWorkspaceEdit::LegacyRoot { .. }) { // Early npm 8 interprets even ./ and ../ workspace paths from its prefix. - let mut next_selector = false; - for arg in &mut args { - if arg == "--" { - break; - } - if next_selector { - *arg = caller_selector(arg, cwd); - next_selector = false; - } else if matches!(arg.as_str(), "--workspace" | "-w") { - next_selector = true; - } else if let Some((option, value)) = arg.split_once('=') - && matches!(option, "--workspace" | "-w") - { - *arg = vt_str::format!("{option}={}", caller_selector(value, cwd)).to_string(); - } - } + args = rebase_workspace_selectors(args, cwd); } + // PowerShell -File splits an attached --option=C:\path at the drive colon. + // Keep each generated path in its own argument when forwarding it to npm. if !has_globalconfig { let globalconfig = original_globalconfig(&npm, root, cwd, &args, env).await?; - args.insert(1, vt_str::format!("--globalconfig={}", globalconfig.display()).to_string()); + args.splice(1..1, ["--globalconfig".to_owned(), globalconfig.display().to_string()]); } - args.insert(1, vt_str::format!("--prefix={}", root.as_path().display()).to_string()); + args.splice(1..1, ["--prefix".to_owned(), root.as_path().display().to_string()]); if matches!(edit, NpmWorkspaceEdit::LegacyRoot { local_dependency: true }) && (has_selector || legacy_config_selects_members(&npm, cwd, &args, env).await?) { @@ -201,13 +188,36 @@ pub(super) fn is_local_dependency(package: &str) -> bool { lower.ends_with(".tgz") || lower.ends_with(".tar") || lower.ends_with(".tar.gz") } -fn caller_selector(value: &str, cwd: &AbsolutePath) -> String { - let path = Path::new(value); - if path.starts_with(".") || path.starts_with("..") { - cwd.as_path().join(path).to_string_lossy().into_owned() - } else { - value.to_owned() +fn rebase_workspace_selectors(args: Vec, cwd: &AbsolutePath) -> Vec { + let mut result = Vec::with_capacity(args.len()); + let mut args = args.into_iter(); + let mut next_selector = false; + while let Some(arg) = args.next() { + if arg == "--" { + result.push(arg); + result.extend(args); + break; + } + if next_selector { + result.push(caller_relative_selector(&arg, cwd).unwrap_or(arg)); + next_selector = false; + } else if let Some((option @ ("--workspace" | "-w"), value)) = arg.split_once('=') + && let Some(path) = caller_relative_selector(value, cwd) + { + result.push(option.to_owned()); + result.push(path); + } else { + next_selector = matches!(arg.as_str(), "--workspace" | "-w"); + result.push(arg); + } } + result +} + +fn caller_relative_selector(value: &str, cwd: &AbsolutePath) -> Option { + let path = Path::new(value); + (path.starts_with(".") || path.starts_with("..")) + .then(|| cwd.as_path().join(path).to_string_lossy().into_owned()) } // Use the same Windows shim as the final install or uninstall command. From b698cab8b0434698d36f620be98a146abe8db557 Mon Sep 17 00:00:00 2001 From: Sakana <15715093608@163.com> Date: Sat, 28 Nov 2026 15:24:20 +0800 Subject: [PATCH 3/4] fix(pm): preserve npm configuration during workspace root edits Select the project through the active npm configuration while keeping the launcher and caller directory. This preserves lifecycle paths, global configuration, and workspace links during dependency edits. Reject combined local adds before npm can save a path that fails from a member. Cover the old npm tarball boundary and run a lifecycle script in a fresh workspace. --- .../check.cjs | 13 + .../local-package/capture.cjs | 7 + .../local-package/package.json | 7 + .../package.json | 10 + .../packages/app/package.json | 4 + .../snapshots.toml | 9 + .../command_add_npm_workspace_lifecycle.md | 16 + .../check-tarball.cjs | 17 + .../snapshots.toml | 2 + .../command_remove_npm8_nested_workspace.md | 9 + crates/vp_pm_cli/src/config.rs | 93 +---- crates/vp_pm_cli/src/resolution/command.rs | 12 +- .../vp_pm_cli/src/resolution/commands/add.rs | 12 +- .../src/resolution/commands/remove.rs | 20 +- crates/vp_pm_cli/src/resolution/dialect.rs | 24 -- crates/vp_pm_cli/src/resolution/mod.rs | 1 - crates/vp_pm_cli/src/resolution/npm_entry.rs | 111 ------ .../src/resolution/npm_workspace.cjs | 146 ++++++++ .../vp_pm_cli/src/resolution/npm_workspace.rs | 327 ++---------------- crates/vp_pm_cli/src/resolution/runner.rs | 9 +- docs/guide/package-management/add.md | 4 + 21 files changed, 309 insertions(+), 544 deletions(-) create mode 100644 crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm_workspace_lifecycle/check.cjs create mode 100644 crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm_workspace_lifecycle/local-package/capture.cjs create mode 100644 crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm_workspace_lifecycle/local-package/package.json create mode 100644 crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm_workspace_lifecycle/package.json create mode 100644 crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm_workspace_lifecycle/packages/app/package.json create mode 100644 crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm_workspace_lifecycle/snapshots.toml create mode 100644 crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm_workspace_lifecycle/snapshots/command_add_npm_workspace_lifecycle.md create mode 100644 crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/check-tarball.cjs delete mode 100644 crates/vp_pm_cli/src/resolution/npm_entry.rs create mode 100644 crates/vp_pm_cli/src/resolution/npm_workspace.cjs diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm_workspace_lifecycle/check.cjs b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm_workspace_lifecycle/check.cjs new file mode 100644 index 0000000000..57128d025d --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm_workspace_lifecycle/check.cjs @@ -0,0 +1,13 @@ +const assert = require('node:assert/strict'); +const { realpathSync } = require('node:fs'); +const path = require('node:path'); + +const member = realpathSync('packages/app'); +assert.equal(realpathSync(require.resolve('fixture-member/package.json')), path.join(member, 'package.json')); +assert.equal(require('./package.json').dependencies['lifecycle-probe'], 'file:packages/app/lifecycle-probe-1.0.0.tgz'); +assert.equal(require('./packages/app/package.json').dependencies?.['lifecycle-probe'], undefined); + +const { caller, globalPrefix } = require('lifecycle-probe/install-context.json'); +assert.equal(realpathSync(caller), member); +assert.equal(realpathSync(globalPrefix), path.join(member, 'test-global')); +console.log('Root dependencies resolve and the install script retains its caller and global prefix.'); diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm_workspace_lifecycle/local-package/capture.cjs b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm_workspace_lifecycle/local-package/capture.cjs new file mode 100644 index 0000000000..6fbc797bd7 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm_workspace_lifecycle/local-package/capture.cjs @@ -0,0 +1,7 @@ +const { execFileSync } = require('node:child_process'); +const { writeFileSync } = require('node:fs'); + +const globalPrefix = execFileSync(process.execPath, [process.env.npm_execpath, 'prefix', '-g'], { + encoding: 'utf8', +}).trim(); +writeFileSync('install-context.json', JSON.stringify({ caller: process.env.INIT_CWD, globalPrefix })); diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm_workspace_lifecycle/local-package/package.json b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm_workspace_lifecycle/local-package/package.json new file mode 100644 index 0000000000..0bd5870547 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm_workspace_lifecycle/local-package/package.json @@ -0,0 +1,7 @@ +{ + "name": "lifecycle-probe", + "version": "1.0.0", + "scripts": { + "install": "node capture.cjs" + } +} diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm_workspace_lifecycle/package.json b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm_workspace_lifecycle/package.json new file mode 100644 index 0000000000..2eb17812ad --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm_workspace_lifecycle/package.json @@ -0,0 +1,10 @@ +{ + "name": "workspace-root", + "private": true, + "version": "1.0.0", + "packageManager": "npm@10.9.2", + "workspaces": ["packages/*"], + "dependencies": { + "fixture-member": "1.0.0" + } +} diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm_workspace_lifecycle/packages/app/package.json b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm_workspace_lifecycle/packages/app/package.json new file mode 100644 index 0000000000..2ad20c0797 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm_workspace_lifecycle/packages/app/package.json @@ -0,0 +1,4 @@ +{ + "name": "fixture-member", + "version": "1.0.0" +} diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm_workspace_lifecycle/snapshots.toml b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm_workspace_lifecycle/snapshots.toml new file mode 100644 index 0000000000..8e04bfe31a --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm_workspace_lifecycle/snapshots.toml @@ -0,0 +1,9 @@ +[[case]] +name = "command_add_npm_workspace_lifecycle" +vp = "global" +steps = [ + { argv = ["npm", "pack", "./local-package", "--pack-destination", "packages/app", "--silent"], snapshot = false }, + { argv = ["vpt", "mkdir", "packages/app/test-global"], snapshot = false }, + { argv = ["vp", "add", "-w", "./lifecycle-probe-1.0.0.tgz", "--offline", "--", "--no-audit", "--no-fund"], cwd = "packages/app", envs = [["NPM_CONFIG_PREFIX", "${workspace}/test-global"]], snapshot = false }, + ["node", "check.cjs"], +] diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm_workspace_lifecycle/snapshots/command_add_npm_workspace_lifecycle.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm_workspace_lifecycle/snapshots/command_add_npm_workspace_lifecycle.md new file mode 100644 index 0000000000..d07f2bde6d --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm_workspace_lifecycle/snapshots/command_add_npm_workspace_lifecycle.md @@ -0,0 +1,16 @@ +# command_add_npm_workspace_lifecycle + +## `npm pack ./local-package --pack-destination packages/app --silent` + + +## `vpt mkdir packages/app/test-global` + + +## `cd packages/app && NPM_CONFIG_PREFIX=${workspace}/test-global vp add -w ./lifecycle-probe-1.0.0.tgz --offline -- --no-audit --no-fund` + + +## `node check.cjs` + +``` +Root dependencies resolve and the install script retains its caller and global prefix. +``` diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/check-tarball.cjs b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/check-tarball.cjs new file mode 100644 index 0000000000..2249949b19 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/check-tarball.cjs @@ -0,0 +1,17 @@ +const assert = require('node:assert/strict'); +const { spawnSync } = require('node:child_process'); +const { existsSync, readFileSync } = require('node:fs'); + +const files = ['package.json', 'packages/app/package.json', 'packages/docs/package.json']; +const manifests = () => files.map((file) => readFileSync(file, 'utf8')); +const before = manifests(); +const result = spawnSync('vp', ['add', '-w', '--filter', 'docs', './docs-1.0.0.tgz', '--offline'], { + cwd: 'packages/app', + encoding: 'utf8', +}); +assert.ifError(result.error); +assert.notEqual(result.status, 0); +assert.match(result.stdout + result.stderr, /requires npm 8\.19\.0 or later/); +assert.deepEqual(manifests(), before); +assert.equal(existsSync('package-lock.json'), false); +console.log('npm 8.1 rejected the combined tarball edit before writing manifests or a lockfile.'); diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/snapshots.toml b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/snapshots.toml index d31e553239..8d0fd4c962 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/snapshots.toml +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/snapshots.toml @@ -2,6 +2,8 @@ name = "command_remove_npm8_nested_workspace" vp = "global" steps = [ + { argv = ["npm", "pack", "./packages/docs", "--pack-destination", "packages/app", "--silent"], snapshot = false }, + ["node", "check-tarball.cjs"], { argv = ["vp", "remove", "-w", "testnpm2", "--", "--no-audit"], cwd = "packages/app", comment = "remove only the outer root declaration when the current member owns a workspace" }, { argv = ["vp", "remove", "-w", "--filter", "docs", "test-vite-plus-install", "--", "--no-audit"], cwd = "packages/app", comment = "select the outer docs package when the inner workspace also has a member named docs" }, { argv = ["vp", "remove", "-w", "testnpm2", "--", "--workspace=../docs", "--no-audit"], cwd = "packages/app", comment = "resolve an attached workspace path from the calling member" }, diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/snapshots/command_remove_npm8_nested_workspace.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/snapshots/command_remove_npm8_nested_workspace.md index 38e446f869..e0320be4d1 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/snapshots/command_remove_npm8_nested_workspace.md +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/snapshots/command_remove_npm8_nested_workspace.md @@ -1,5 +1,14 @@ # command_remove_npm8_nested_workspace +## `npm pack ./packages/docs --pack-destination packages/app --silent` + + +## `node check-tarball.cjs` + +``` +npm 8.1 rejected the combined tarball edit before writing manifests or a lockfile. +``` + ## `cd packages/app && vp remove -w testnpm2 -- --no-audit` remove only the outer root declaration when the current member owns a workspace diff --git a/crates/vp_pm_cli/src/config.rs b/crates/vp_pm_cli/src/config.rs index 52dcd3c662..2038258f23 100644 --- a/crates/vp_pm_cli/src/config.rs +++ b/crates/vp_pm_cli/src/config.rs @@ -45,8 +45,15 @@ impl NpmConfig { project_root: Option, cwd: Option<&AbsolutePath>, ) -> Self { - let (project_values, user_values) = - project_and_user_npmrc(project_root, cwd, npm_user_config_path(cwd)); + let mut project_values = HashMap::new(); + if let Some(root) = project_root { + load_npmrc(root.join(".npmrc"), &mut project_values); + } + let user_config = npm_user_config_path(cwd) + .or_else(|| project_values.get("userconfig").map(|path| config_path(path, cwd))) + .unwrap_or_else(|| EnvConfig::get().user_home.join(".npmrc").into_path_buf()); + let mut user_values = HashMap::new(); + load_npmrc(user_config, &mut user_values); // Higher-priority layers select config files; merge their values from low to high. // Default global paths require npm, so only explicitly selected files are loaded. @@ -334,23 +341,6 @@ fn load_npmrc(path: PathBuf, values: &mut HashMap) { } } -fn project_and_user_npmrc( - project_root: Option, - cwd: Option<&AbsolutePath>, - userconfig: Option, -) -> (HashMap, HashMap) { - let mut project = HashMap::new(); - if let Some(root) = project_root { - load_npmrc(root.join(".npmrc"), &mut project); - } - let userconfig = userconfig - .or_else(|| project.get("userconfig").map(|path| config_path(path, cwd))) - .unwrap_or_else(|| EnvConfig::get().user_home.join(".npmrc").into_path_buf()); - let mut user = HashMap::new(); - load_npmrc(userconfig, &mut user); - (project, user) -} - fn parse_npmrc_value(value: &str) -> String { let value = value.trim(); if value.len() >= 2 && value.starts_with('"') && value.ends_with('"') { @@ -400,35 +390,6 @@ pub fn npm_user_config_path(cwd: Option<&AbsolutePath>) -> Option { env_value("userconfig").map(|path| config_path(&expand_value(&path), cwd)) } -/// Find the global npmrc selected before a workspace edit overrides npm's prefix. -pub(crate) fn workspace_globalconfig( - root: &AbsolutePath, - cwd: &AbsolutePath, - cli_userconfig: Option<&str>, - env: &HashMap, -) -> Option { - let from_env = |name: &str| { - let key = vt_str::format!("npm_config_{name}"); - env.iter() - .find(|(name, _)| name.eq_ignore_ascii_case(&key)) - .and_then(|(_, value)| (!value.is_empty()).then(|| expand_value(value))) - .or_else(|| env_value(name).map(|value| expand_value(&value))) - }; - let userconfig = cli_userconfig - .map(expand_value) - .or_else(|| from_env("userconfig")) - .map(|value| config_path(&value, Some(cwd))); - let (project, user) = - project_and_user_npmrc(Some(root.as_path().to_path_buf()), Some(cwd), userconfig); - let configured = |key: &str| { - from_env(key) - .or_else(|| project.get(key).cloned()) - .or_else(|| user.get(key).cloned()) - .map(|value| config_path(&value, Some(cwd))) - }; - configured("globalconfig").or_else(|| configured("prefix").map(|p| p.join("etc/npmrc"))) -} - /// Resolve the `Authorization` header value npm would send to `url` from the npm config at `cwd`. #[must_use] pub fn npm_authorization_for_url(cwd: &AbsolutePath, url: &str) -> Option { @@ -611,42 +572,6 @@ mod tests { }); } - #[test] - fn workspace_globalconfig_resolves_project_and_user_paths_from_the_caller() { - let root = project_with_npmrc("userconfig=./user.npmrc\nprefix=./project-prefix\n"); - let caller = root.path().join("child"); - fs::create_dir(&caller).unwrap(); - fs::write(caller.join("user.npmrc"), "globalconfig=./user-global.npmrc\n").unwrap(); - let root = AbsolutePath::new(root.path()).unwrap(); - let cwd = AbsolutePath::new(&caller).unwrap(); - EnvConfig::with_vars( - [ - ("npm_config_userconfig", None::<&std::ffi::OsStr>), - ("NPM_CONFIG_USERCONFIG", None), - ("npm_config_globalconfig", None), - ("NPM_CONFIG_GLOBALCONFIG", None), - ("npm_config_prefix", None), - ("NPM_CONFIG_PREFIX", None), - ], - |_| { - let mut env = HashMap::new(); - assert_eq!( - workspace_globalconfig(root, cwd, None, &env), - Some(caller.join("user-global.npmrc")), - ); - env.insert("NPM_CONFIG_USERCONFIG".into(), "missing".into()); - assert_eq!( - workspace_globalconfig(root, cwd, None, &env), - Some(caller.join("project-prefix/etc/npmrc")), - ); - assert_eq!( - workspace_globalconfig(root, cwd, Some("user.npmrc"), &env), - Some(caller.join("user-global.npmrc")), - ); - }, - ); - } - #[test] fn relative_config_paths_use_caller_cwd_without_changing_workspace_root() { with_isolated_npm_config(|| { diff --git a/crates/vp_pm_cli/src/resolution/command.rs b/crates/vp_pm_cli/src/resolution/command.rs index 1d5fddb89c..1ba21e5095 100644 --- a/crates/vp_pm_cli/src/resolution/command.rs +++ b/crates/vp_pm_cli/src/resolution/command.rs @@ -13,7 +13,7 @@ pub(crate) struct ResolvedCommand { pub(crate) args: Vec, pub(crate) env: BTreeMap, pub(crate) pre_run: Vec, - pub(crate) npm_workspace_edit: Option, + pub(crate) npm_workspace_edit: bool, } impl ResolvedCommand { @@ -24,7 +24,7 @@ impl ResolvedCommand { // Include npm/npx fallbacks: Vite+ manages their versions too. env.insert("npm_config_update_notifier".to_string(), "false".to_string()); } - Self { program, args: Vec::new(), env, pre_run: Vec::new(), npm_workspace_edit: None } + Self { program, args: Vec::new(), env, pre_run: Vec::new(), npm_workspace_edit: false } } } @@ -34,12 +34,6 @@ impl From for CommandResolution { } } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(crate) enum NpmWorkspaceEdit { - AutomaticRoot, - LegacyRoot { local_dependency: bool }, -} - #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) enum PreRunAction { CreateDir { path: String }, @@ -101,7 +95,7 @@ impl CommandBuilder { self } - pub(crate) fn npm_workspace_edit(&mut self, edit: Option) -> &mut Self { + pub(crate) fn npm_workspace_edit(&mut self, edit: bool) -> &mut Self { self.command.npm_workspace_edit = edit; self } diff --git a/crates/vp_pm_cli/src/resolution/commands/add.rs b/crates/vp_pm_cli/src/resolution/commands/add.rs index 53c38b2cf2..8058a97b88 100644 --- a/crates/vp_pm_cli/src/resolution/commands/add.rs +++ b/crates/vp_pm_cli/src/resolution/commands/add.rs @@ -227,14 +227,10 @@ impl Npm { return cmd.into(); } - cmd.npm_workspace_edit(self.workspace_edit( - args.workspace_root && !args.packages.is_empty(), - !args.filter.is_empty(), - &args.packages, - )) - .arg("install") - .repeated("--workspace", args.filter.iter()) - .arg_if("--include-workspace-root", args.workspace_root); + cmd.npm_workspace_edit(args.workspace_root && !args.packages.is_empty()) + .arg("install") + .repeated("--workspace", args.filter.iter()) + .arg_if("--include-workspace-root", args.workspace_root); match args.save_dependency.target() { Some(SaveDependencyTarget::Production) => { // `--save` overrides npm's `save=false` setting when the user explicitly selects production. diff --git a/crates/vp_pm_cli/src/resolution/commands/remove.rs b/crates/vp_pm_cli/src/resolution/commands/remove.rs index 764ae9254f..84d5860ca3 100644 --- a/crates/vp_pm_cli/src/resolution/commands/remove.rs +++ b/crates/vp_pm_cli/src/resolution/commands/remove.rs @@ -51,7 +51,7 @@ pub struct RemoveArgs { impl Resolve for Pnpm { fn resolve(&self, args: &RemoveArgs, _diag: &mut Diagnostics) -> CommandResolution { if args.global { - return Npm::unknown_version().resolve_remove(args); + return Npm::resolve_remove(args); } let mut cmd = CommandBuilder::new("pnpm"); @@ -69,7 +69,7 @@ impl Resolve for Pnpm { } impl Npm { - fn resolve_remove(&self, args: &RemoveArgs) -> CommandResolution { + fn resolve_remove(args: &RemoveArgs) -> CommandResolution { let mut cmd = CommandBuilder::new("npm"); if args.global { cmd.arg("uninstall") @@ -79,13 +79,9 @@ impl Npm { return cmd.into(); } - cmd.npm_workspace_edit(self.workspace_edit( - args.workspace_root && !args.recursive, - !args.filter.is_empty(), - &[], - )) - .arg("uninstall") - .repeated("--workspace", args.filter.iter()); + cmd.npm_workspace_edit(args.workspace_root && !args.recursive) + .arg("uninstall") + .repeated("--workspace", args.filter.iter()); if args.workspace_root || args.recursive { cmd.arg("--include-workspace-root"); } @@ -101,14 +97,14 @@ impl Npm { impl Resolve for Npm { fn resolve(&self, args: &RemoveArgs, _diag: &mut Diagnostics) -> CommandResolution { - self.resolve_remove(args) + Self::resolve_remove(args) } } impl Resolve for Yarn { fn resolve(&self, args: &RemoveArgs, _diag: &mut Diagnostics) -> CommandResolution { if args.global { - return Npm::unknown_version().resolve_remove(args); + return Npm::resolve_remove(args); } let mut cmd = CommandBuilder::new("yarn"); @@ -138,7 +134,7 @@ impl Resolve for Yarn { impl Resolve for Bun { fn resolve(&self, args: &RemoveArgs, _diag: &mut Diagnostics) -> CommandResolution { if args.global { - return Npm::unknown_version().resolve_remove(args); + return Npm::resolve_remove(args); } let mut cmd = CommandBuilder::new("bun"); diff --git a/crates/vp_pm_cli/src/resolution/dialect.rs b/crates/vp_pm_cli/src/resolution/dialect.rs index c4864ad608..f853867018 100644 --- a/crates/vp_pm_cli/src/resolution/dialect.rs +++ b/crates/vp_pm_cli/src/resolution/dialect.rs @@ -57,30 +57,6 @@ impl Npm { Self { version: None } } - pub(crate) fn workspace_edit( - &self, - enabled: bool, - has_filter: bool, - packages: &[String], - ) -> Option { - use super::command::NpmWorkspaceEdit; - if !enabled { - return None; - } - if self.version.as_ref().is_some_and(|v| v < &Version::new(8, 5, 0)) { - Some(NpmWorkspaceEdit::LegacyRoot { - local_dependency: packages - .iter() - .any(|spec| super::npm_workspace::is_local_dependency(spec)), - }) - } else if has_filter { - // npm 8.5+ already resolves explicit selections from the calling directory. - None - } else { - Some(NpmWorkspaceEdit::AutomaticRoot) - } - } - /// `--omit` and `--include` landed in npm 7. Unknown versions are treated as current. pub(crate) fn supports_v7_commands(&self) -> bool { self.version.as_ref().is_none_or(|version| version >= &Version::new(7, 0, 0)) diff --git a/crates/vp_pm_cli/src/resolution/mod.rs b/crates/vp_pm_cli/src/resolution/mod.rs index 66fdf627ed..168ef9c1d4 100644 --- a/crates/vp_pm_cli/src/resolution/mod.rs +++ b/crates/vp_pm_cli/src/resolution/mod.rs @@ -31,7 +31,6 @@ mod command; mod commands; mod diagnostics; mod dialect; -mod npm_entry; mod npm_workspace; mod resolve; mod runner; diff --git a/crates/vp_pm_cli/src/resolution/npm_entry.rs b/crates/vp_pm_cli/src/resolution/npm_entry.rs deleted file mode 100644 index 8c0f0883a7..0000000000 --- a/crates/vp_pm_cli/src/resolution/npm_entry.rs +++ /dev/null @@ -1,111 +0,0 @@ -//! Find a member's enclosing npm project on releases before automatic workspace roots. -use std::{ - collections::HashMap, - ffi::OsString, - fs, io, - path::{Component, Path, PathBuf}, - process::Stdio, -}; - -use serde_json::{Map, Value}; -use vt_path::AbsolutePath; - -use crate::Error; - -pub(super) async fn legacy_root( - cwd: &AbsolutePath, - npm: &AbsolutePath, - env: &HashMap, -) -> Result { - let package = vt_workspace::find_package_root(cwd)?; - let member = package.path.as_path(); - let parse_manifest = |bytes: &[u8]| { - serde_json::from_slice::(bytes.strip_prefix(b"\xef\xbb\xbf").unwrap_or(bytes)) - }; - let member_manifest = parse_manifest(package.package_json.content())?; - // npm 8 also treats a path selector as a glob for that directory's children. - // An empty brace alternative expands to the same glob but changes the exact path. - let mut children = PathBuf::new(); - let mut add_braces = true; - for component in member.components() { - if add_braces && let Component::Normal(name) = component { - let mut part = OsString::from("{,}"); - part.push(name); - children.push(part); - add_braces = false; - } else { - children.push(component); - } - } - for ancestor in member.ancestors().skip(1) { - let bytes = match fs::read(ancestor.join("package.json")) { - Ok(bytes) => bytes, - Err(error) if error.kind() == io::ErrorKind::NotFound => continue, - Err(error) => return Err(error.into()), - }; - let Ok(manifest) = parse_manifest(&bytes) else { continue }; - if manifest["workspaces"].is_null() { - continue; - } - // npm keys the response by name. If a member can replace the root's - // entry, compare the manifests too. An ordinary query needs only names. - let same_name = - member_manifest["name"].is_null() || member_manifest["name"] == manifest["name"]; - let selected = workspace_entries(npm, cwd, env, ancestor, member, same_name).await?; - let descendants = workspace_entries(npm, cwd, env, ancestor, &children, same_name).await?; - if selected.iter().any(|(name, value)| descendants.get(name) != Some(value)) { - return Ok(ancestor.to_owned()); - } - // A literal globstar or brace expansion can match the directory itself. An - // identical manifest can also hide behind the root's key in npm's JSON. - let could_match_itself = member.components().any(|part| { - let segment = part.as_os_str().to_string_lossy(); - segment.contains("**") || segment.contains(['{', '}']) - }); - let name_was_selected = - member_manifest["name"].as_str().is_none_or(|name| selected.contains_key(name)); - if name_was_selected && could_match_itself || same_name && member_manifest == manifest { - return Err(Error::UserMessage( - "Could not distinguish the workspace path from its matches with this npm version." - .into(), - )); - } - } - Ok(member.to_owned()) -} - -async fn workspace_entries( - npm: &AbsolutePath, - cwd: &AbsolutePath, - env: &HashMap, - root: &Path, - filter: &Path, - compare_manifests: bool, -) -> Result, Error> { - let mut command = super::npm_workspace::npm_probe(npm, cwd); - command.args(["pkg", "get"]); - if !compare_manifests { - command.arg("name"); - } - // Including the root gives both queries a common entry when no member matches. - let output = command - .args(["--include-workspace-root", "--prefix"]) - .arg(root) - .arg("--workspace") - .arg(filter) - .envs(env) - .env_remove("NODE_OPTIONS") - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .output() - .await?; - if !output.status.success() { - return Err(Error::UserMessage(vt_str::format!( - "Could not read npm workspaces in {}: {}", - root.display(), - String::from_utf8_lossy(&output.stderr).trim() - ))); - } - Ok(serde_json::from_slice(&output.stdout)?) -} diff --git a/crates/vp_pm_cli/src/resolution/npm_workspace.cjs b/crates/vp_pm_cli/src/resolution/npm_workspace.cjs new file mode 100644 index 0000000000..51ced23899 --- /dev/null +++ b/crates/vp_pm_cli/src/resolution/npm_workspace.cjs @@ -0,0 +1,146 @@ +// This preload is scoped to the npm process that performs the edit. Loading +// through the original launcher preserves its Node version and environment. +const fs = require('fs'); +const path = require('path'); +const Module = require('module'); + +async function plan(Config, options, npm, member) { + async function loadConfig(root) { + const config = new Config({ ...options, env: { ...process.env } }); + if (root) + config.loadLocalPrefix = () => { + config.localPrefix = root; + }; + await config.load(); + return config; + } + function nativeScope(config) { + return ( + config.get('global') || + config.get('location') === 'global' || + config.find('prefix') === 'cli' || + config.get('workspaces') === false || + !config.get('include-workspace-root') + ); + } + let config = await loadConfig(); + if (nativeScope(config)) return null; + + const mapWorkspaces = npm('@npmcli/map-workspaces'); + member = fs.realpathSync(member); + function readManifest(dir) { + try { + return JSON.parse( + fs.readFileSync(path.join(dir, 'package.json'), 'utf8').replace(/^\uFEFF/, ''), + ); + } catch (error) { + if (error.code !== 'ENOENT' && !(error instanceof SyntaxError)) throw error; + } + } + let root = member; + let workspaces; + for (let dir = path.dirname(member); ; dir = path.dirname(dir)) { + const pkg = readManifest(dir); + if (pkg && pkg.workspaces) { + const members = await mapWorkspaces({ cwd: dir, pkg }); + if ([...members.values()].includes(member)) { + root = dir; + workspaces = members; + break; + } + } + if (dir === path.dirname(dir)) break; + } + if (!workspaces) { + const pkg = readManifest(member); + if (!pkg || !pkg.workspaces) return null; + workspaces = await mapWorkspaces({ cwd: member, pkg }); + } + // An early npm 8 release or a nested node_modules can select the wrong + // project configuration. Load the owner's npmrc before resolving selectors. + const differentRoot = config.localPrefix !== root; + if (differentRoot) { + config = await loadConfig(root); + if (nativeScope(config)) return null; + } + const selectors = config.find('workspace') === 'default' ? [] : config.get('workspace'); + const combined = selectors.length > 0 || config.get('workspaces') === true; + const [command, ...operands] = config.parsedArgv.remain; + if (command === 'install' && combined && config.get('save') && !config.get('dry-run')) { + const npa = npm('npm-package-arg'); + const specs = operands.map((arg) => npa(arg, process.cwd())); + const members = new Set(workspaces.values()); + const oldNpm = npm('semver').lt(npm('../package.json').version, '8.19.0'); + if ( + specs.some((spec) => { + if (spec.type !== 'directory') return false; + return oldNpm || spec.name || !members.has(spec.fetchSpec); + }) + ) { + throw new Error( + 'Add the local directory to the root and each selected workspace separately so npm saves the correct relative paths.', + ); + } + if (specs.some((spec) => spec.type === 'file' && spec.name)) { + throw new Error( + 'Pass the tarball path without a package name, or add it to each target separately.', + ); + } + if (specs.some((spec) => spec.type === 'file') && oldNpm) { + throw new Error( + 'Adding a local tarball to both the root and a workspace requires npm 8.19.0 or later.', + ); + } + } + if (!differentRoot && (root === member || selectors.length > 0)) return null; + // npm 8 resolves path selectors from its prefix. Preserve their origin + // when selecting another prefix, including selectors configured in npmrc. + return { + root, + selectors: selectors.map((value) => + /^(?:\.{1,2})(?:[\\/]|$)/.test(value) ? path.resolve(value) : value, + ), + }; +} + +module.exports = function enable(member, preload) { + const original = Module.prototype.require; + let active = true; + function workspaceRequire(id) { + const result = original.call(this, id); + if (!active || id !== '@npmcli/config' || path.basename(this.filename) !== 'npm.js') + return result; + const npm = Module.createRequire(this.filename); + if ( + path.basename(path.dirname(this.filename)) !== 'lib' || + !fs.existsSync(path.resolve(path.dirname(this.filename), '../package.json')) || + npm('../package.json').name !== 'npm' + ) + return result; + active = false; + // A user preload may have wrapped this function after it was installed. + if (Module.prototype.require === workspaceRequire) Module.prototype.require = original; + // A lifecycle script can start another npm. Only the outer invocation is scoped. + const options = (process.env.NODE_OPTIONS || '') + .replace(preload + ' ', '') + .replace(preload, ''); + if (options) process.env.NODE_OPTIONS = options; + else delete process.env.NODE_OPTIONS; + return class WorkspaceConfig extends result { + constructor(options) { + super(options); + this.workspaceOptions = options; + } + async load() { + const edit = await plan(result, this.workspaceOptions, npm, member); + if (edit) + this.loadLocalPrefix = () => { + this.localPrefix = edit.root; + }; + await super.load(); + if (edit && edit.selectors.length) this.set('workspace', edit.selectors); + } + }; + } + Module.prototype.require = workspaceRequire; +}; diff --git a/crates/vp_pm_cli/src/resolution/npm_workspace.rs b/crates/vp_pm_cli/src/resolution/npm_workspace.rs index f513c9a9b4..895c3161f2 100644 --- a/crates/vp_pm_cli/src/resolution/npm_workspace.rs +++ b/crates/vp_pm_cli/src/resolution/npm_workspace.rs @@ -1,298 +1,47 @@ -//! Select the owner of a workspace dependency edit without changing the caller's directory. -use std::{ - collections::HashMap, - ffi::OsStr, - io, - path::{Path, PathBuf}, - process::Stdio, -}; +//! Select npm's local project while preserving its launcher, cwd and global configuration. +use std::{collections::HashMap, ffi::OsString, io::Write}; -use cow_utils::CowUtils; +use tempfile::NamedTempFile; use vt_path::AbsolutePath; -use super::{command::NpmWorkspaceEdit, npm_entry::legacy_root}; use crate::Error; -pub(super) async fn edit_args( - program: &str, +pub(super) fn prepare( cwd: &AbsolutePath, - edit: NpmWorkspaceEdit, - mut args: Vec, - env: &HashMap, -) -> Result, Error> { - let flags = args.iter().take_while(|arg| arg.as_str() != "--"); - let mut has_selector = std::env::vars_os().any(|(key, value)| { - !value.is_empty() - && key.to_str().is_some_and(|key| key.eq_ignore_ascii_case("npm_config_workspace")) - }); - let mut has_globalconfig = false; - for arg in flags { - let (option, value) = arg.split_once('=').unwrap_or((arg, "")); - match option { - "--global" | "-g" if value != "false" => return Ok(args), - "--include-workspace-root" if value == "false" => return Ok(args), - "--prefix" | "--no-workspaces" | "--no-include-workspace-root" => { - return Ok(args); - } - "--workspace" | "-w" | "--workspaces" | "-ws" => has_selector = true, - "--globalconfig" => has_globalconfig = true, - _ => {} - } - } - if edit == NpmWorkspaceEdit::AutomaticRoot && has_selector { - return Ok(args); - } - - let Ok(package) = vt_workspace::find_package_root(cwd) else { return Ok(args) }; - if !package.path.as_path().ancestors().skip(1).any(|p| p.join("package.json").is_file()) { - return Ok(args); - } - let npm = vp_command::resolve_bin(program, env.get("PATH").map(OsStr::new), cwd)?; - let root = match edit { - NpmWorkspaceEdit::AutomaticRoot => npm_path(&npm, cwd, &["prefix"], env).await?, - NpmWorkspaceEdit::LegacyRoot { .. } => legacy_root(cwd, &npm, env).await?, - }; - if root == package.path.as_path() { - return Ok(args); - } - let root = AbsolutePath::new(&root) - .ok_or_else(|| io::Error::other("npm returned a relative workspace root"))?; - - if matches!(edit, NpmWorkspaceEdit::LegacyRoot { .. }) { - // Early npm 8 interprets even ./ and ../ workspace paths from its prefix. - args = rebase_workspace_selectors(args, cwd); - } - // PowerShell -File splits an attached --option=C:\path at the drive colon. - // Keep each generated path in its own argument when forwarding it to npm. - if !has_globalconfig { - let globalconfig = original_globalconfig(&npm, root, cwd, &args, env).await?; - args.splice(1..1, ["--globalconfig".to_owned(), globalconfig.display().to_string()]); - } - args.splice(1..1, ["--prefix".to_owned(), root.as_path().display().to_string()]); - if matches!(edit, NpmWorkspaceEdit::LegacyRoot { local_dependency: true }) - && (has_selector || legacy_config_selects_members(&npm, cwd, &args, env).await?) - { - // Early Arborist writes the same root-relative file path into every selected manifest. - return Err(Error::UserMessage( - "Adding a local dependency to both the root and a workspace requires npm 8.19.0 or later.".into(), - )); - } - Ok(args) -} - -// A selection can come from any npmrc. A non-workspace `npm pkg get name` returns -// the root's name (or an empty object). A workspace query returns a map of packages. -async fn legacy_config_selects_members( - npm: &AbsolutePath, - cwd: &AbsolutePath, - args: &[String], - env: &HashMap, -) -> Result { - let mut probe = npm_probe(npm, cwd); - probe.args(["pkg", "get", "name", "--include-workspace-root"]); - let mut flags = args.iter().take_while(|arg| arg.as_str() != "--"); - while let Some(arg) = flags.next() { - let key = arg.split('=').next().unwrap_or(arg); - if matches!(key, "--prefix" | "--globalconfig" | "--userconfig") { - probe.arg(arg); - if arg == key - && let Some(value) = flags.next() - { - probe.arg(value); - } - } - } - let output = probe - .envs(env) - .env_remove("NODE_OPTIONS") - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .output() - .await?; - if !output.status.success() { - return Err(Error::UserMessage( - "Could not check npm's configured workspace selection.".into(), - )); - } - let selection: serde_json::Value = serde_json::from_slice(&output.stdout)?; - Ok(selection.as_object().is_some_and(|members| !members.is_empty())) -} - -async fn original_globalconfig( - npm: &AbsolutePath, - root: &AbsolutePath, - cwd: &AbsolutePath, - args: &[String], - env: &HashMap, -) -> Result { - let mut userconfig = None; - let mut flags = args.iter().take_while(|arg| arg.as_str() != "--"); - while let Some(arg) = flags.next() { - if arg == "--userconfig" { - userconfig = flags.next().map(String::as_str); - } else if let Some(path) = arg.strip_prefix("--userconfig=") { - userconfig = Some(path); - } - } - if let Some(path) = crate::config::workspace_globalconfig(root, cwd, userconfig, env) { - return Ok(path); - } - - // Ask this npm installation for its default. Its global mode rejects workspace - // selectors, and the caller's selected user npmrc has already been checked. - let mut probe_env = env.clone(); - for key in - std::env::vars_os().filter_map(|(key, _)| key.into_string().ok()).chain(env.keys().cloned()) + env: &mut HashMap, +) -> Result, Error> { + let Ok(member) = vt_workspace::find_package_root(cwd) else { return Ok(None) }; + let has_parent_project = + member.path.as_path().ancestors().skip(1).any(|p| p.join("package.json").is_file()); + if !has_parent_project + && serde_json::from_slice::(member.package_json.content()) + .is_ok_and(|pkg| pkg.get("workspaces").is_none()) { - if key.eq_ignore_ascii_case("npm_config_workspace") - || key.eq_ignore_ascii_case("npm_config_workspaces") - { - probe_env.insert(key, String::new()); - } - } - let userconfig = if cfg!(windows) { "--userconfig=NUL" } else { "--userconfig=/dev/null" }; - npm_path(npm, cwd, &["config", "get", "globalconfig", "--global", userconfig], &probe_env).await -} - -// Early npm saves local paths relative to the root even in a member's manifest. -pub(super) fn is_local_dependency(package: &str) -> bool { - fn is_path(spec: &str) -> bool { - spec.starts_with('.') - || spec.starts_with("~/") - || Path::new(spec).is_absolute() - || spec.get(..5).is_some_and(|prefix| prefix.eq_ignore_ascii_case("file:")) - || spec.as_bytes().get(1) == Some(&b':') - || (cfg!(windows) && spec.contains('\\')) - } - if is_path(package) { - return true; - } - let unscoped = package.strip_prefix('@').unwrap_or(package); - let spec = unscoped.split_once('@').map_or(package, |(_, spec)| spec); - if is_path(spec) { - return true; - } - // Remote URLs, hosted Git references and registry aliases can also contain slashes. - let path = spec.split('#').next().unwrap_or(spec); - if path.contains(':') || package.contains("://") { - return false; - } - if let Some((owner, repo)) = path.split_once('/') { - if owner.starts_with('@') { - return repo.contains('/'); - } - return repo.is_empty() || repo.contains('/') || path.contains(char::is_whitespace); - } - let lower = path.cow_to_ascii_lowercase(); - lower.ends_with(".tgz") || lower.ends_with(".tar") || lower.ends_with(".tar.gz") -} - -fn rebase_workspace_selectors(args: Vec, cwd: &AbsolutePath) -> Vec { - let mut result = Vec::with_capacity(args.len()); - let mut args = args.into_iter(); - let mut next_selector = false; - while let Some(arg) = args.next() { - if arg == "--" { - result.push(arg); - result.extend(args); - break; - } - if next_selector { - result.push(caller_relative_selector(&arg, cwd).unwrap_or(arg)); - next_selector = false; - } else if let Some((option @ ("--workspace" | "-w"), value)) = arg.split_once('=') - && let Some(path) = caller_relative_selector(value, cwd) - { - result.push(option.to_owned()); - result.push(path); - } else { - next_selector = matches!(arg.as_str(), "--workspace" | "-w"); - result.push(arg); - } - } - result -} - -fn caller_relative_selector(value: &str, cwd: &AbsolutePath) -> Option { - let path = Path::new(value); - (path.starts_with(".") || path.starts_with("..")) - .then(|| cwd.as_path().join(path).to_string_lossy().into_owned()) -} - -// Use the same Windows shim as the final install or uninstall command. -pub(super) fn npm_probe(npm: &AbsolutePath, cwd: &AbsolutePath) -> tokio::process::Command { - if let Some((program, args)) = vp_command::rewrite_cmd_to_powershell(npm) { - let mut command = vp_command::build_command(&program, cwd); - command.args(args); - command + return Ok(None); + } + // npm has no CLI flag for its local prefix alone. Load the adapter in the + // selected npm, including when the launcher chooses a runtime for this cwd. + let mut script = tempfile::Builder::new().prefix("vp-npm-").suffix(".cjs").tempfile()?; + let preload = + vt_str::format!("--require {}", serde_json::to_string(script.path())?).to_string(); + writeln!( + script, + "{}\nmodule.exports({}, {});", + include_str!("npm_workspace.cjs"), + serde_json::to_string(member.path.as_path())?, + serde_json::to_string(&preload)?, + )?; + script.flush()?; + let original = env + .get("NODE_OPTIONS") + .map(OsString::from) + .or_else(|| std::env::var_os("NODE_OPTIONS")) + .unwrap_or_default(); + let options = if original.is_empty() { + preload } else { - vp_command::build_command(npm, cwd) - } -} - -async fn npm_path( - npm: &AbsolutePath, - cwd: &AbsolutePath, - args: &[&str], - env: &HashMap, -) -> Result { - let output = npm_probe(npm, cwd) - .args(args) - .arg("--json=false") - .envs(env) - .env_remove("NODE_OPTIONS") - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .output() - .await?; - if !output.status.success() { - return Err(Error::UserMessage(vt_str::format!( - "Could not read npm {}: {}", - args[0], - String::from_utf8_lossy(&output.stderr).trim() - ))); - } - let path = std::str::from_utf8(&output.stdout) - .map_err(io::Error::other)? - .trim_end_matches(['\r', '\n']); - if !Path::new(path).is_absolute() { - return Err(Error::UserMessage( - "npm returned an invalid configuration or prefix path".into(), - )); - } - Ok(PathBuf::from(path)) -} - -#[cfg(test)] -mod tests { - use super::is_local_dependency; - - #[test] - fn early_npm_local_dependencies() { - for package in [ - "file:./a@b", - "./pkg", - "/tmp/a@b.tgz", - "a.tgz", - "pkg@a.tar.gz", - "@scope/pkg@file:./a.tgz", - "nested/path/to/package", - "with spaces/pkg", - ] { - assert!(is_local_dependency(package), "{package}"); - } - for package in [ - "pkg@~1", - "@scope/pkg", - "pkg@npm:@scope/other@1", - "owner/repo", - "owner/repo#feature/branch", - "https://example.com/a.tgz", - "git+ssh://git@example.com/a/b", - ] { - assert!(!is_local_dependency(package), "{package}"); - } - } + vt_str::format!("{preload} {}", original.to_string_lossy()).to_string() + }; + env.insert("NODE_OPTIONS".into(), options); + Ok(Some(script)) } diff --git a/crates/vp_pm_cli/src/resolution/runner.rs b/crates/vp_pm_cli/src/resolution/runner.rs index a70ce982f1..4a657452f6 100644 --- a/crates/vp_pm_cli/src/resolution/runner.rs +++ b/crates/vp_pm_cli/src/resolution/runner.rs @@ -30,12 +30,9 @@ async fn run_command(cwd: &AbsolutePath, command: ResolvedCommand) -> Result>(); - let args = if let Some(edit) = npm_workspace_edit { - super::npm_workspace::edit_args(&program, cwd, edit, args, &env).await? - } else { - args - }; + let mut env = env.into_iter().collect::>(); + let _npm_workspace_preload = + if npm_workspace_edit { super::npm_workspace::prepare(cwd, &mut env)? } else { None }; Ok(vp_command::run_command(&program, args, &env, cwd).await?) } diff --git a/docs/guide/package-management/add.md b/docs/guide/package-management/add.md index ec03914ae5..42a77153d6 100644 --- a/docs/guide/package-management/add.md +++ b/docs/guide/package-management/add.md @@ -81,4 +81,8 @@ The commands below describe project operations. Global mode is described under [ ## Native Options +With npm, `-w` adds the dependency to the root even when you run the command in a member. Add `--filter ` to include a member too. + +When adding a local tarball to both the root and a member, pass the tarball path without a package name and use npm 8.19.0 or later. For an external directory, add it to each target separately so each manifest gets the correct relative path. + For native options, see [npm install](https://docs.npmjs.com/cli/v11/commands/npm-install), [pnpm add](https://pnpm.io/cli/add), [Yarn add](https://yarnpkg.com/cli/add), [Yarn Classic add](https://classic.yarnpkg.com/en/docs/cli/add), and [Bun add](https://bun.com/docs/pm/cli/add). To pass these options through Vite+, see [Native Arguments](./#native-arguments). From 056fdffe8d291785a8b1aa62985035d2e8adf7f1 Mon Sep 17 00:00:00 2001 From: Sakana <15715093608@163.com> Date: Sat, 28 Nov 2026 15:27:44 +0800 Subject: [PATCH 4/4] refactor(pm): apply workspace adapter lint rules --- .../src/resolution/npm_workspace.cjs | 92 ++++++++++++------- 1 file changed, 60 insertions(+), 32 deletions(-) diff --git a/crates/vp_pm_cli/src/resolution/npm_workspace.cjs b/crates/vp_pm_cli/src/resolution/npm_workspace.cjs index 51ced23899..d3fb5bcbee 100644 --- a/crates/vp_pm_cli/src/resolution/npm_workspace.cjs +++ b/crates/vp_pm_cli/src/resolution/npm_workspace.cjs @@ -4,39 +4,47 @@ const fs = require('fs'); const path = require('path'); const Module = require('module'); +function nativeScope(config) { + return ( + config.get('global') || + config.get('location') === 'global' || + config.find('prefix') === 'cli' || + config.get('workspaces') === false || + !config.get('include-workspace-root') + ); +} + +function readManifest(dir) { + try { + return JSON.parse( + fs.readFileSync(path.join(dir, 'package.json'), 'utf8').replace(/^\uFEFF/, ''), + ); + } catch (error) { + if (error.code !== 'ENOENT' && !(error instanceof SyntaxError)) { + throw error; + } + return null; + } +} + async function plan(Config, options, npm, member) { async function loadConfig(root) { const config = new Config({ ...options, env: { ...process.env } }); - if (root) + if (root) { config.loadLocalPrefix = () => { config.localPrefix = root; }; + } await config.load(); return config; } - function nativeScope(config) { - return ( - config.get('global') || - config.get('location') === 'global' || - config.find('prefix') === 'cli' || - config.get('workspaces') === false || - !config.get('include-workspace-root') - ); - } let config = await loadConfig(); - if (nativeScope(config)) return null; + if (nativeScope(config)) { + return null; + } const mapWorkspaces = npm('@npmcli/map-workspaces'); member = fs.realpathSync(member); - function readManifest(dir) { - try { - return JSON.parse( - fs.readFileSync(path.join(dir, 'package.json'), 'utf8').replace(/^\uFEFF/, ''), - ); - } catch (error) { - if (error.code !== 'ENOENT' && !(error instanceof SyntaxError)) throw error; - } - } let root = member; let workspaces; for (let dir = path.dirname(member); ; dir = path.dirname(dir)) { @@ -49,11 +57,15 @@ async function plan(Config, options, npm, member) { break; } } - if (dir === path.dirname(dir)) break; + if (dir === path.dirname(dir)) { + break; + } } if (!workspaces) { const pkg = readManifest(member); - if (!pkg || !pkg.workspaces) return null; + if (!pkg || !pkg.workspaces) { + return null; + } workspaces = await mapWorkspaces({ cwd: member, pkg }); } // An early npm 8 release or a nested node_modules can select the wrong @@ -61,7 +73,9 @@ async function plan(Config, options, npm, member) { const differentRoot = config.localPrefix !== root; if (differentRoot) { config = await loadConfig(root); - if (nativeScope(config)) return null; + if (nativeScope(config)) { + return null; + } } const selectors = config.find('workspace') === 'default' ? [] : config.get('workspace'); const combined = selectors.length > 0 || config.get('workspaces') === true; @@ -73,7 +87,9 @@ async function plan(Config, options, npm, member) { const oldNpm = npm('semver').lt(npm('../package.json').version, '8.19.0'); if ( specs.some((spec) => { - if (spec.type !== 'directory') return false; + if (spec.type !== 'directory') { + return false; + } return oldNpm || spec.name || !members.has(spec.fetchSpec); }) ) { @@ -92,7 +108,9 @@ async function plan(Config, options, npm, member) { ); } } - if (!differentRoot && (root === member || selectors.length > 0)) return null; + if (!differentRoot && (root === member || selectors.length > 0)) { + return null; + } // npm 8 resolves path selectors from its prefix. Preserve their origin // when selecting another prefix, including selectors configured in npmrc. return { @@ -108,24 +126,31 @@ module.exports = function enable(member, preload) { let active = true; function workspaceRequire(id) { const result = original.call(this, id); - if (!active || id !== '@npmcli/config' || path.basename(this.filename) !== 'npm.js') + if (!active || id !== '@npmcli/config' || path.basename(this.filename) !== 'npm.js') { return result; + } const npm = Module.createRequire(this.filename); if ( path.basename(path.dirname(this.filename)) !== 'lib' || !fs.existsSync(path.resolve(path.dirname(this.filename), '../package.json')) || npm('../package.json').name !== 'npm' - ) + ) { return result; + } active = false; // A user preload may have wrapped this function after it was installed. - if (Module.prototype.require === workspaceRequire) Module.prototype.require = original; + if (Module.prototype.require === workspaceRequire) { + Module.prototype.require = original; + } // A lifecycle script can start another npm. Only the outer invocation is scoped. const options = (process.env.NODE_OPTIONS || '') .replace(preload + ' ', '') .replace(preload, ''); - if (options) process.env.NODE_OPTIONS = options; - else delete process.env.NODE_OPTIONS; + if (options) { + process.env.NODE_OPTIONS = options; + } else { + delete process.env.NODE_OPTIONS; + } return class WorkspaceConfig extends result { constructor(options) { super(options); @@ -133,12 +158,15 @@ module.exports = function enable(member, preload) { } async load() { const edit = await plan(result, this.workspaceOptions, npm, member); - if (edit) + if (edit) { this.loadLocalPrefix = () => { this.localPrefix = edit.root; }; + } await super.load(); - if (edit && edit.selectors.length) this.set('workspace', edit.selectors); + if (edit && edit.selectors.length) { + this.set('workspace', edit.selectors); + } } }; }