// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. import * as semver from 'semver'; import { FileConstants, FileSystem, type IPackageJson, JsonFile, LockFile } from '@rushstack/node-core-library'; import { Colorize, type ITerminal } from '@rushstack/terminal'; import { LastInstallFlag } from '../../api/LastInstallFlag'; import type { PackageManagerName } from '../../api/packageManager/PackageManager'; import type { RushConfiguration } from '../../api/RushConfiguration'; import type { RushGlobalFolder } from '../../api/RushGlobalFolder'; import { Utilities } from '../../utilities/Utilities'; import type { IConfigurationEnvironment } from '../base/BasePackageManagerOptionsConfiguration'; import type { PnpmOptionsConfiguration } from '../pnpm/PnpmOptionsConfiguration'; import { PnpmWorkspaceFile } from '../pnpm/PnpmWorkspaceFile'; import { getEffectivePnpmOptions } from '../pnpm/EffectivePnpmOptions'; import { merge } from '../../utilities/objectUtilities'; import { getNpmrcEnvironmentVariables } from '../../utilities/npmrcUtilities'; import type { Subspace } from '../../api/Subspace'; import { RushConstants } from '../RushConstants'; export interface ICommonPackageJsonPnpmSection { overrides?: typeof PnpmOptionsConfiguration.prototype.globalOverrides; packageExtensions?: typeof PnpmOptionsConfiguration.prototype.globalPackageExtensions; peerDependencyRules?: typeof PnpmOptionsConfiguration.prototype.globalPeerDependencyRules; neverBuiltDependencies?: typeof PnpmOptionsConfiguration.prototype.globalNeverBuiltDependencies; onlyBuiltDependencies?: typeof PnpmOptionsConfiguration.prototype.globalOnlyBuiltDependencies; ignoredOptionalDependencies?: typeof PnpmOptionsConfiguration.prototype.globalIgnoredOptionalDependencies; allowedDeprecatedVersions?: typeof PnpmOptionsConfiguration.prototype.globalAllowedDeprecatedVersions; patchedDependencies?: typeof PnpmOptionsConfiguration.prototype.globalPatchedDependencies; trustPolicy?: typeof PnpmOptionsConfiguration.prototype.trustPolicy; trustPolicyExclude?: typeof PnpmOptionsConfiguration.prototype.trustPolicyExclude; trustPolicyIgnoreAfter?: typeof PnpmOptionsConfiguration.prototype.trustPolicyIgnoreAfterMinutes; } interface ICommonPackageJson extends IPackageJson { pnpm?: ICommonPackageJsonPnpmSection; } /** * The pnpm-specific settings that Rush writes into the generated `common/temp` install files, * derived from a subspace's pnpm options by {@link InstallHelpers.resolvePnpmSettings}. */ export interface IResolvedPnpmSettings { /** * The "pnpm" field to write into `common/temp/package.json`, or `undefined` for pnpm 11+ (which * no longer reads that field — all settings are placed on {@link workspaceFile} instead). */ packageJsonPnpmSection: ICommonPackageJsonPnpmSection | undefined; /** * Additional top-level properties to merge into `common/temp/package.json` * (from `pnpmOptions.unsupportedPackageJsonSettings`). */ additionalPackageJsonProperties: unknown; /** * The `common/temp/pnpm-workspace.yaml` file, populated with the version-gated pnpm settings. * The caller is responsible for adding the workspace packages and saving the file. Only used by * workspace installs. */ workspaceFile: PnpmWorkspaceFile; /** * The configured pnpm `globalOverrides` (defaulting to `{}`), regardless of the pnpm version. * Used to verify that the shrinkwrap file is up to date. */ configuredOverrides: Record; /** * The configured pnpm `globalPackageExtensions`, regardless of the pnpm version. Used to verify * that the shrinkwrap file is up to date. */ configuredPackageExtensions: typeof PnpmOptionsConfiguration.prototype.globalPackageExtensions; } export class InstallHelpers { public static async generateCommonPackageJsonAsync( subspace: Subspace, dependenciesMap: Map = new Map(), resolvedPnpmSettings: IResolvedPnpmSettings | undefined ): Promise { const { packageJsonPnpmSection, additionalPackageJsonProperties } = resolvedPnpmSettings ?? {}; // Add any preferred versions to the top of the commonPackageJson // do this in alphabetical order for simpler debugging const sortedDependencyEntries: [string, string][] = Array.from(dependenciesMap.entries()).sort( ([a], [b]) => (a < b ? -1 : a > b ? 1 : 0) ); const dependencies: Record = Object.fromEntries(sortedDependencyEntries); const commonPackageJson: ICommonPackageJson = { dependencies, description: 'Temporary file generated by the Rush tool', name: 'rush-common', private: true, version: '0.0.0', pnpm: packageJsonPnpmSection }; if (additionalPackageJsonProperties) { merge(commonPackageJson, additionalPackageJsonProperties); } // Example: "C:\MyRepo\common\temp\package.json" const commonPackageJsonFilename: string = `${subspace.getSubspaceTempFolderPath()}/${FileConstants.PackageJson}`; // Don't update the file timestamp unless the content has changed, since "rush install" // will consider this timestamp await JsonFile.saveAsync(commonPackageJson, commonPackageJsonFilename, { onlyIfChanged: true, ignoreUndefinedValues: true }); } /** * Interprets the pnpm options for the given subspace and derives the pnpm-specific settings that * Rush writes into the generated install files: the "pnpm" field of `common/temp/package.json` * (see {@link IResolvedPnpmSettings.packageJsonPnpmSection}) and the settings for * `common/temp/pnpm-workspace.yaml` (see {@link IResolvedPnpmSettings.workspaceSettings}). * * This is the single place that reads through the pnpm options and emits the associated * version-compatibility warnings, so that both "rush install" code paths stay consistent. * * Returns `undefined` when the package manager is not pnpm. */ public static resolvePnpmSettings( rushConfiguration: RushConfiguration, subspace: Subspace, terminal: ITerminal ): IResolvedPnpmSettings | undefined { if (!rushConfiguration.isPnpm) { return undefined; } const { globalOverrides = {}, globalPackageExtensions, globalPeerDependencyRules, globalNeverBuiltDependencies, globalOnlyBuiltDependencies, globalIgnoredOptionalDependencies, globalAllowedDeprecatedVersions, globalPatchedDependencies, globalCatalogs, globalAllowBuilds, minimumReleaseAgeMinutes, minimumReleaseAgeExclude, trustPolicy, trustPolicyExclude, // NOTE: the pnpm setting is `trustPolicyIgnoreAfter`, but the rush pnpm setting is `trustPolicyIgnoreAfterMinutes` trustPolicyIgnoreAfterMinutes: trustPolicyIgnoreAfter, unsupportedPackageJsonSettings } = getEffectivePnpmOptions(subspace, rushConfiguration).pnpmOptions; const pnpmVersion: string = rushConfiguration.packageManagerToolVersion; const isPnpm11: boolean = semver.gte(pnpmVersion, '11.0.0'); // Example: "C:\MyRepo\common\config\rush\pnpm-config.json" const pnpmConfigLocation: string = `${rushConfiguration.commonRushConfigFolder}/${RushConstants.pnpmConfigFilename}`; // // Derive the "pnpm" field of common/temp/package.json // let neverBuiltDependencies: ICommonPackageJsonPnpmSection['neverBuiltDependencies']; if (globalNeverBuiltDependencies) { if (isPnpm11) { terminal.writeWarningLine( Colorize.yellow( `Your version of PNPM (${pnpmVersion}) ` + `no longer supports the "globalNeverBuiltDependencies" field in ` + `${pnpmConfigLocation}. ` + 'Use "globalAllowBuilds" instead (with a value of false to deny build scripts).' ) ); } else { neverBuiltDependencies = globalNeverBuiltDependencies; } } let onlyBuiltDependencies: ICommonPackageJsonPnpmSection['onlyBuiltDependencies']; if (globalOnlyBuiltDependencies) { if (isPnpm11) { terminal.writeWarningLine( Colorize.yellow( `Your version of PNPM (${pnpmVersion}) ` + `no longer supports the "globalOnlyBuiltDependencies" field in ` + `${pnpmConfigLocation}. ` + 'Use "globalAllowBuilds" instead (with a value of true to allow build scripts).' ) ); } else { if (semver.lt(pnpmVersion, '10.1.0')) { terminal.writeWarningLine( Colorize.yellow( `Your version of PNPM (${pnpmVersion}) ` + `doesn't support the "globalOnlyBuiltDependencies" field in ` + `${pnpmConfigLocation}. ` + 'Remove this field or upgrade to PNPM 10.1.0 or newer.' ) ); } onlyBuiltDependencies = globalOnlyBuiltDependencies; } } if (globalIgnoredOptionalDependencies && semver.lt(pnpmVersion, '9.0.0')) { terminal.writeWarningLine( Colorize.yellow( `Your version of PNPM (${pnpmVersion}) ` + `doesn't support the "globalIgnoredOptionalDependencies" field in ` + `${pnpmConfigLocation}. ` + 'Remove this field or upgrade to PNPM 9.' ) ); } if (trustPolicy !== undefined && semver.lt(pnpmVersion, '10.21.0')) { terminal.writeWarningLine( Colorize.yellow( `Your version of PNPM (${pnpmVersion}) ` + `doesn't support the "trustPolicy" field in ` + `${pnpmConfigLocation}. ` + 'Remove this field or upgrade to PNPM 10.21.0 or newer.' ) ); } if (trustPolicyExclude && semver.lt(pnpmVersion, '10.22.0')) { terminal.writeWarningLine( Colorize.yellow( `Your version of PNPM (${pnpmVersion}) ` + `doesn't support the "trustPolicyExclude" field in ` + `${pnpmConfigLocation}. ` + 'Remove this field or upgrade to PNPM 10.22.0 or newer.' ) ); } if (trustPolicyIgnoreAfter !== undefined && semver.lt(pnpmVersion, '10.27.0')) { terminal.writeWarningLine( Colorize.yellow( `Your version of PNPM (${pnpmVersion}) ` + `doesn't support the "trustPolicyIgnoreAfterMinutes" field in ` + `${pnpmConfigLocation}. ` + 'Remove this field or upgrade to PNPM 10.27.0 or newer.' ) ); } // // Derive the settings for common/temp/pnpm-workspace.yaml // if (globalCatalogs && semver.lt(pnpmVersion, '9.5.0')) { terminal.writeWarningLine( Colorize.yellow( `Your version of pnpm (${pnpmVersion}) ` + `doesn't support the "globalCatalogs" fields in ` + `${pnpmConfigLocation}. ` + 'Remove these fields or upgrade to pnpm 9.5.0 or newer.' ) ); } // For pnpm 11+, "allowBuilds" replaces onlyBuiltDependencies/neverBuiltDependencies let allowBuilds: Record | undefined; if (isPnpm11) { if (globalAllowBuilds) { allowBuilds = globalAllowBuilds; } else if (globalOnlyBuiltDependencies || globalNeverBuiltDependencies) { // Backward compatibility: convert globalOnlyBuiltDependencies/globalNeverBuiltDependencies // to allowBuilds format for pnpm 11+ allowBuilds = {}; if (globalOnlyBuiltDependencies) { for (const pkg of globalOnlyBuiltDependencies) { allowBuilds[pkg] = true; } } if (globalNeverBuiltDependencies) { for (const pkg of globalNeverBuiltDependencies) { allowBuilds[pkg] = false; } } } } else if (globalAllowBuilds) { terminal.writeWarningLine( Colorize.yellow( `Your version of pnpm (${pnpmVersion}) ` + `doesn't support the "globalAllowBuilds" field in ` + `${pnpmConfigLocation}. ` + 'Remove this field or upgrade to pnpm 11.0.0 or newer.' ) ); } // pnpm does not read these fields from package.json, only from pnpm-workspace.yaml or .npmrc. if ( (minimumReleaseAgeMinutes !== undefined || minimumReleaseAgeExclude) && semver.lt(pnpmVersion, '10.16.0') ) { terminal.writeWarningLine( Colorize.yellow( `Your version of pnpm (${pnpmVersion}) ` + `doesn't support the "minimumReleaseAgeMinutes" or "minimumReleaseAgeExclude" fields in ` + `${pnpmConfigLocation}. ` + 'Remove these fields or upgrade to pnpm 10.16.0 or newer.' ) ); } // Populate a PnpmWorkspaceFile with the workspace settings. The caller adds the workspace // packages to this file and saves it; here we only set the pnpm settings. const workspaceFile: PnpmWorkspaceFile = new PnpmWorkspaceFile( `${subspace.getSubspaceTempFolderPath()}/${RushConstants.pnpmWorkspaceFileName}` ); workspaceFile.catalogs = globalCatalogs; workspaceFile.allowBuilds = allowBuilds; // NOTE: the pnpm setting is `minimumReleaseAge`, but the Rush setting is `minimumReleaseAgeMinutes` workspaceFile.minimumReleaseAge = minimumReleaseAgeMinutes; workspaceFile.minimumReleaseAgeExclude = minimumReleaseAgeExclude; // pnpm 11 no longer reads the "pnpm" field of package.json, so for pnpm 11+ we don't generate // it at all; every setting is written to common/temp/pnpm-workspace.yaml instead. // See https://github.com/microsoft/rushstack/issues/5837 let packageJsonPnpmSection: ICommonPackageJsonPnpmSection | undefined; if (isPnpm11) { workspaceFile.overrides = globalOverrides; workspaceFile.packageExtensions = globalPackageExtensions; workspaceFile.peerDependencyRules = globalPeerDependencyRules; workspaceFile.allowedDeprecatedVersions = globalAllowedDeprecatedVersions; workspaceFile.patchedDependencies = globalPatchedDependencies; workspaceFile.ignoredOptionalDependencies = globalIgnoredOptionalDependencies; workspaceFile.trustPolicy = trustPolicy; workspaceFile.trustPolicyExclude = trustPolicyExclude; workspaceFile.trustPolicyIgnoreAfter = trustPolicyIgnoreAfter; if (rushConfiguration.subspacesFeatureEnabled) { // When subspaces are enabled, Rush generates a "global pnpmfile" that rewrites // cross-subspace "workspace:*" dependency specifiers to "link:" specifiers. For pnpm 10 and // earlier it is wired up via a "global-pnpmfile=" line in the generated .npmrc (see // BaseInstallManager), but pnpm 11+ only reads auth/registry settings from .npmrc, so that // line is silently ignored and installation fails with ERR_PNPM_WORKSPACE_PKG_NOT_FOUND. // For pnpm 11+, emit the path via the generated pnpm-workspace.yaml instead. workspaceFile.globalPnpmfile = `${subspace.getSubspaceTempFolderPath()}/${RushConstants.pnpmfileGlobalFilename}`; } } else { // For older pnpm, these settings live in the "pnpm" field of package.json. packageJsonPnpmSection = { neverBuiltDependencies, onlyBuiltDependencies, overrides: globalOverrides, packageExtensions: globalPackageExtensions, peerDependencyRules: globalPeerDependencyRules, allowedDeprecatedVersions: globalAllowedDeprecatedVersions, patchedDependencies: globalPatchedDependencies, ignoredOptionalDependencies: globalIgnoredOptionalDependencies, trustPolicy, trustPolicyExclude, trustPolicyIgnoreAfter }; } return { packageJsonPnpmSection, additionalPackageJsonProperties: unsupportedPackageJsonSettings, workspaceFile, // The configured overrides/packageExtensions are needed to verify the shrinkwrap is up to // date, regardless of the pnpm version. configuredOverrides: globalOverrides, configuredPackageExtensions: globalPackageExtensions }; } /** * Returns true if Rush (rather than PNPM) should expand the `${VAR}` tokens that appear in * credentials and registry URLs in the `.npmrc` file. See the * `provideNpmrcCredentialsViaEnvironment` experiment. */ public static shouldProvideNpmrcCredentialsViaEnvironment(rushConfiguration: RushConfiguration): boolean { const { isPnpm, packageManagerToolVersion, experimentsConfiguration: { configuration: { provideNpmrcCredentialsViaEnvironment = false } } } = rushConfiguration; if (!isPnpm || !provideNpmrcCredentialsViaEnvironment) { return false; } // PNPM 11.6.0 added URL-scoped `pnpm_config_//...` credentials, which let CI bind a token to // a registry without deriving that trusted binding from repository-controlled configuration. // Keep this compatibility workaround only for patched versions that lack that native path. return ( (semver.gte(packageManagerToolVersion, '10.34.2') && semver.lt(packageManagerToolVersion, '11.0.0')) || (semver.gte(packageManagerToolVersion, '11.5.3') && semver.lt(packageManagerToolVersion, '11.6.0')) ); } /** * Returns the environment that the package manager should be invoked with, including any * credentials that were moved out of the generated `.npmrc` file in `npmrcFolder`. */ public static getPackageManagerEnvironment( rushConfiguration: RushConfiguration, options: { debug?: boolean; npmrcFolder?: string; } = {} ): NodeJS.ProcessEnv { let configurationEnvironment: IConfigurationEnvironment | undefined = undefined; if (rushConfiguration.packageManager === 'npm') { configurationEnvironment = rushConfiguration.npmOptions?.environmentVariables; } else if (rushConfiguration.isPnpm) { configurationEnvironment = rushConfiguration.pnpmOptions?.environmentVariables; } else if (rushConfiguration.packageManager === 'yarn') { configurationEnvironment = rushConfiguration.yarnOptions?.environmentVariables; } const packageManagerEnvironment: NodeJS.ProcessEnv = _mergeEnvironmentVariables( process.env, configurationEnvironment, options ); const { npmrcFolder } = options; const shouldProvideCredentials: boolean = InstallHelpers.shouldProvideNpmrcCredentialsViaEnvironment(rushConfiguration); if (npmrcFolder !== undefined && shouldProvideCredentials) { Object.assign( packageManagerEnvironment, getNpmrcEnvironmentVariables({ npmrcFolder, supportEnvVarFallbackSyntax: rushConfiguration.isPnpm }) ); } return packageManagerEnvironment; } /** * If the "(p)npm-local" symlink hasn't been set up yet, this creates it, installing the * specified (P)npm version in the user's home directory if needed. */ public static async ensureLocalPackageManagerAsync( rushConfiguration: RushConfiguration, rushGlobalFolder: RushGlobalFolder, maxInstallAttempts: number, restrictConsoleOutput?: boolean ): Promise { let logIfConsoleOutputIsNotRestricted: (message?: string) => void; if (restrictConsoleOutput) { logIfConsoleOutputIsNotRestricted = () => { /* noop */ }; } else { logIfConsoleOutputIsNotRestricted = (message?: string) => { // eslint-disable-next-line no-console console.log(message); }; } // Example: "C:\Users\YourName\.rush" const rushUserFolder: string = rushGlobalFolder.nodeSpecificPath; if (!FileSystem.exists(rushUserFolder)) { logIfConsoleOutputIsNotRestricted('Creating ' + rushUserFolder); FileSystem.ensureFolder(rushUserFolder); } const packageManager: PackageManagerName = rushConfiguration.packageManager; const packageManagerVersion: string = rushConfiguration.packageManagerToolVersion; const packageManagerAndVersion: string = `${packageManager}-${packageManagerVersion}`; // Example: "C:\Users\YourName\.rush\pnpm-1.2.3" const packageManagerToolFolder: string = `${rushUserFolder}/${packageManagerAndVersion}`; const packageManagerMarker: LastInstallFlag = new LastInstallFlag(packageManagerToolFolder, { node: process.versions.node }); logIfConsoleOutputIsNotRestricted(`Trying to acquire lock for ${packageManagerAndVersion}`); const lock: LockFile = await LockFile.acquireAsync(rushUserFolder, packageManagerAndVersion); logIfConsoleOutputIsNotRestricted(`Acquired lock for ${packageManagerAndVersion}`); try { // Only the flag decides whether to reinstall. A stale lock (lock.dirtyWhenAcquired) only means that // some process exited while it held the lock. An install deletes the flag before it changes the // folder, so an interrupted install leaves no flag. Reinstalling because of a stale lock alone would // empty a shared folder that other processes may be running the package manager from. if (!(await packageManagerMarker.isValidAsync())) { logIfConsoleOutputIsNotRestricted( Colorize.bold(`Installing ${packageManager} version ${packageManagerVersion}\n`) ); // Delete the flag first, so that an interrupted install can't leave it next to a partly // deleted or partly installed folder. await packageManagerMarker.clearAsync(); await Utilities.installPackageInDirectoryAsync({ directory: packageManagerToolFolder, packageName: packageManager, version: rushConfiguration.packageManagerToolVersion, tempPackageTitle: `${packageManager}-local-install`, maxInstallAttempts: maxInstallAttempts, // This is using a local configuration to install a package in a shared global location. // Generally that's a bad practice, but in this case if we can successfully install // the package at all, we can reasonably assume it's good for all the repositories. // In particular, we'll assume that two different NPM registries cannot have two // different implementations of the same version of the same package. // This was needed for: https://github.com/microsoft/rushstack/issues/691 commonRushConfigFolder: rushConfiguration.commonRushConfigFolder, // Only filter npm-incompatible properties when the repo uses pnpm or yarn. // If the repo uses npm, the .npmrc is already configured for npm, so don't filter. filterNpmIncompatibleProperties: rushConfiguration.packageManager !== 'npm' }); logIfConsoleOutputIsNotRestricted( `Successfully installed ${packageManager} version ${packageManagerVersion}` ); // Write the flag only after an install. Rewriting a valid flag on every call would let a process // that is killed during the write leave an empty flag, and the next caller would reinstall. await packageManagerMarker.createAsync(); } else { logIfConsoleOutputIsNotRestricted( `Found ${packageManager} version ${packageManagerVersion} in ${packageManagerToolFolder}` ); } // Example: "C:\MyRepo\common\temp" FileSystem.ensureFolder(rushConfiguration.commonTempFolder); // Example: "C:\MyRepo\common\temp\pnpm-local" const localPackageManagerToolFolder: string = `${rushConfiguration.commonTempFolder}/${packageManager}-local`; logIfConsoleOutputIsNotRestricted(`\nSymlinking "${localPackageManagerToolFolder}"`); logIfConsoleOutputIsNotRestricted(` --> "${packageManagerToolFolder}"`); // We cannot use FileSystem.exists() to test the existence of a symlink, because it will // return false for broken symlinks. There is no way to test without catching an exception. try { await FileSystem.deleteFolderAsync(localPackageManagerToolFolder); } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') { throw error; } } await FileSystem.createSymbolicLinkJunctionAsync({ linkTargetPath: packageManagerToolFolder, newLinkPath: localPackageManagerToolFolder }); } finally { // A long-lived process such as the Rush daemon calls this again after a failed install. // LockFile keeps an in-process record of every held lock, so a lock that is never released // makes that later call wait forever. A failed install deletes the last-install flag before it // changes the tool folder, so the next caller installs again. lock.release(); } } } // Helper for getPackageManagerEnvironment function _mergeEnvironmentVariables( baseEnv: NodeJS.ProcessEnv, environmentVariables?: IConfigurationEnvironment, options: { debug?: boolean; } = {} ): NodeJS.ProcessEnv { const packageManagerEnv: NodeJS.ProcessEnv = { ...baseEnv }; if (environmentVariables) { // eslint-disable-next-line guard-for-in for (const envVar in environmentVariables) { let setEnvironmentVariable: boolean = true; // eslint-disable-next-line no-console console.log(`\nProcessing definition for environment variable: ${envVar}`); if (baseEnv.hasOwnProperty(envVar)) { setEnvironmentVariable = false; // eslint-disable-next-line no-console console.log(`Environment variable already defined:`); // eslint-disable-next-line no-console console.log(` Name: ${envVar}`); // eslint-disable-next-line no-console console.log(` Existing value: ${baseEnv[envVar]}`); // eslint-disable-next-line no-console console.log( ` Value set in ${RushConstants.rushJsonFilename}: ${environmentVariables[envVar].value}` ); if (environmentVariables[envVar].override) { setEnvironmentVariable = true; // eslint-disable-next-line no-console console.log( `Overriding the environment variable with the value set in ${RushConstants.rushJsonFilename}.` ); } else { // eslint-disable-next-line no-console console.log(Colorize.yellow(`WARNING: Not overriding the value of the environment variable.`)); } } if (setEnvironmentVariable) { if (options.debug) { // eslint-disable-next-line no-console console.log(`Setting environment variable for package manager.`); // eslint-disable-next-line no-console console.log(` Name: ${envVar}`); // eslint-disable-next-line no-console console.log(` Value: ${environmentVariables[envVar].value}`); } packageManagerEnv[envVar] = environmentVariables[envVar].value; } } } return packageManagerEnv; }