diff --git a/.changeset/upgrade-supported-node.md b/.changeset/upgrade-supported-node.md new file mode 100644 index 00000000000..f124270ab0b --- /dev/null +++ b/.changeset/upgrade-supported-node.md @@ -0,0 +1,6 @@ +--- +'@shopify/cli-kit': patch +'@shopify/cli': patch +--- + +`shopify upgrade` and the upgrade notice no longer offer a release that needs a newer Node, and the daily notice, even with auto-upgrade on, says which Node the latest release needs diff --git a/packages/cli-kit/src/private/node/cli-version-cache.ts b/packages/cli-kit/src/private/node/cli-version-cache.ts index 131ab59dd8b..3e3677541c0 100644 --- a/packages/cli-kit/src/private/node/cli-version-cache.ts +++ b/packages/cli-kit/src/private/node/cli-version-cache.ts @@ -27,6 +27,10 @@ export function getCLIVersionCacheKey(registry: string, versionRange?: string): return `npm-package-@shopify/cli${versionRange ? `@${versionRange}` : ''}:registry:${hashString(registry)}` } +export function getCLINodeRangeCacheKey(registry: string): PackageVersionKey { + return `${getCLIVersionCacheKey(registry)}:node` +} + export function getPublicCLIVersionCacheKey(registry: string, versionRange?: string): PackageVersionKey { const latestCacheKey = getCLIVersionCacheKey(registry) // Generic range results are not vetted for deprecation and must not feed auto-upgrades. @@ -46,3 +50,36 @@ export function getCachedCLIVersion(versionRange?: string, registry = currentReg } return undefined } + +/** + * The cache entry for the Node range in a release's `engines`. It names the release, because other lookups refresh + * the latest version on their own and must not inherit another release's range. + * + * @param version - The release the range belongs to. + * @param nodeRange - Its `engines.node`, if it declares one. + * @returns The value to cache under {@link getCLINodeRangeCacheKey}. + */ +export function cliNodeRangeCacheValue(version: string, nodeRange: string | undefined): string { + return `${version} ${nodeRange ?? ''}` +} + +/** + * The Node range in the `engines` of `version`, from a fresh entry the version lookup cached for that release. + * Undefined when the release declares none, or when nothing fresh is cached for it. + */ +export function getCachedCLINodeRange(version: string, registry = currentRegistry): string | undefined { + if (!registry) return undefined + const cached = cacheRetrieve(getCLINodeRangeCacheKey(registry)) + if (!cached || Date.now() - cached.timestamp >= cacheExpiryMs) return undefined + const separator = cached.value.indexOf(' ') + if (separator === -1 || cached.value.slice(0, separator) !== version) return undefined + return cached.value.slice(separator + 1) || undefined +} + +/** + * Whether a release whose `engines.node` is `nodeRange` supports the running Node. A release that declares no range + * supports it. + */ +export function supportsRunningNode(nodeRange: string | undefined): boolean { + return nodeRange === undefined || satisfies(process.version, nodeRange, {includePrerelease: true}) +} diff --git a/packages/cli-kit/src/private/node/cli-version-check.test.ts b/packages/cli-kit/src/private/node/cli-version-check.test.ts index 83d2d6b04bd..81954984406 100644 --- a/packages/cli-kit/src/private/node/cli-version-check.test.ts +++ b/packages/cli-kit/src/private/node/cli-version-check.test.ts @@ -225,6 +225,7 @@ test('does not select a release whose engines exclude the running Node version', await expect(checkForCLIVersions()).resolves.toEqual({ latest: unsupportedVersion, currentMajor: currentMajorVersion, + latestNodeRange: `>${process.versions.node}`, }) expect(versionToAutoUpgrade()).toBe(currentMajorVersion) }, @@ -250,6 +251,46 @@ test('keeps a release that declares no engines eligible', async () => { ) }) +test('caches the Node range that the latest release needs with the versions', async () => { + const latest = new SemVer(CLI_KIT_VERSION).inc('minor').version + let requests = 0 + await withRegistry( + http.get('https://registry.npmjs.org/*', () => { + requests += 1 + return HttpResponse.json({ + 'dist-tags': {latest}, + versions: {[latest]: {version: latest, engines: {node: '>=22.20.0'}}}, + }) + }), + async () => { + const versions = {latest, currentMajor: latest, latestNodeRange: '>=22.20.0'} + await expect(checkForCLIVersions()).resolves.toEqual(versions) + await expect(checkForCLIVersions()).resolves.toEqual(versions) + expect(requests).toBe(1) + }, + ) +}) + +test('ignores a cached Node range once another lookup refreshes latest to a different release', async () => { + const latest = new SemVer(CLI_KIT_VERSION).inc('minor').version + const refreshedLatest = new SemVer(latest).inc('patch').version + await withRegistry( + http.get('https://registry.npmjs.org/*', () => + HttpResponse.json({ + 'dist-tags': {latest}, + versions: {[latest]: {version: latest, engines: {node: '>=22.20.0'}}}, + }), + ), + async () => { + await checkForCLIVersions() + // The generic latest-version lookup refreshes the same entry and caches no Node range. + confStore.cacheStore(latestCacheKey, refreshedLatest) + + await expect(checkForCLIVersions()).resolves.toEqual({latest: refreshedLatest, currentMajor: latest}) + }, + ) +}) + test('public ranged checks cannot seed or overwrite the vetted auto-upgrade target with a deprecated release', async () => { const deprecatedVersion = new SemVer(CLI_KIT_VERSION).inc('minor').version let requests = 0 diff --git a/packages/cli-kit/src/private/node/cli-version-check.ts b/packages/cli-kit/src/private/node/cli-version-check.ts index 7db38a21208..522740db8bd 100644 --- a/packages/cli-kit/src/private/node/cli-version-check.ts +++ b/packages/cli-kit/src/private/node/cli-version-check.ts @@ -1,5 +1,13 @@ import {cacheRetrieve, cacheStore} from './conf-store.js' -import {getCachedCLIVersion, getCLIVersionCacheKey, resolveCLIRegistry} from './cli-version-cache.js' +import { + cliNodeRangeCacheValue, + getCachedCLINodeRange, + getCachedCLIVersion, + getCLINodeRangeCacheKey, + getCLIVersionCacheKey, + resolveCLIRegistry, + supportsRunningNode, +} from './cli-version-cache.js' import {CLI_KIT_VERSION} from '../../public/common/version.js' import {outputDebug} from '../../public/node/output.js' import {maxSatisfying, satisfies, SemVer, valid} from 'semver' @@ -12,6 +20,8 @@ const currentMajorRange = `${new SemVer(CLI_KIT_VERSION).major}.x` interface CLIVersions { latest?: string currentMajor?: string + /** The Node range in the latest release's `engines`, when it declares one. */ + latestNodeRange?: string } interface PackageMetadata { @@ -25,6 +35,14 @@ export function getCachedCurrentMajorCLIVersion(): string | undefined { return getCachedCLIVersion(currentMajorRange) } +/** + * The Node range in the `engines` of the cached latest release, when the version lookup cached one for it. + */ +export function getCachedLatestCLINodeRange(): string | undefined { + const latest = getCachedCLIVersion() + return latest ? getCachedCLINodeRange(latest) : undefined +} + export async function checkForCLIVersions({includeCurrentMajor = true} = {}): Promise { try { const registry = await resolveCLIRegistry() @@ -34,7 +52,9 @@ export async function checkForCLIVersions({includeCurrentMajor = true} = {}): Pr const latest = getCachedCLIVersion(undefined, registry) const currentMajor = getCachedCLIVersion(currentMajorRange, registry) - if (latest && (!includeCurrentMajor || currentMajor)) return {latest, currentMajor} + if (latest && (!includeCurrentMajor || currentMajor)) { + return {latest, currentMajor, latestNodeRange: getCachedCLINodeRange(latest, registry)} + } const failure = cacheRetrieve(`${lookupKey}-lookup-failure`) if (failure && Date.now() - failure.timestamp < failureBackoffMs) return {} @@ -85,6 +105,8 @@ async function fetchAndCacheVersions(registry: string): Promise { if (!latest || !valid(latest) || !metadata.versions[latest]) { throw new Error('The npm registry did not return a stable latest CLI version.') } + // A release whose engines exclude the running Node installs with a warning under npm and fails to install under + // Yarn 1, so auto-upgrade leaves the CLI on the newest release that supports this Node. const eligibleVersions = Object.keys(metadata.versions).filter((version) => { const release = metadata.versions[version] return !release?.deprecated && supportsRunningNode(release?.engines?.node) @@ -95,9 +117,11 @@ async function fetchAndCacheVersions(registry: string): Promise { if (!currentMajor) { throw new Error('The npm registry did not return a stable CLI version in the current major.') } + const latestNodeRange = metadata.versions[latest]?.engines?.node cacheStore(latestCacheKey, latest) + cacheStore(getCLINodeRangeCacheKey(registry), cliNodeRangeCacheValue(latest, latestNodeRange)) cacheStore(currentMajorCacheKey, currentMajor) - return {latest, currentMajor} + return {latest, currentMajor, latestNodeRange} // eslint-disable-next-line no-catch-all/no-catch-all } catch { outputDebug('Skipping the CLI version lookup after a registry or cache failure.') @@ -105,9 +129,3 @@ async function fetchAndCacheVersions(registry: string): Promise { return {} } } - -// A release whose engines exclude the running Node installs with a warning under npm and fails to install under -// Yarn 1, so auto-upgrade must leave the CLI on the newest release that supports this Node. -function supportsRunningNode(nodeRange: string | undefined): boolean { - return nodeRange === undefined || satisfies(process.version, nodeRange, {includePrerelease: true}) -} diff --git a/packages/cli-kit/src/public/node/upgrade.test.ts b/packages/cli-kit/src/public/node/upgrade.test.ts index 690cfe702ff..4c1bb8b36a4 100644 --- a/packages/cli-kit/src/public/node/upgrade.test.ts +++ b/packages/cli-kit/src/public/node/upgrade.test.ts @@ -31,7 +31,11 @@ import {inTemporaryDirectory, writeFile} from './fs.js' import {joinPath} from './path.js' import {LocalStorage} from './local-storage.js' import {getAutoUpgradeEnabled, runAtMinimumInterval, type ConfSchema} from '../../private/node/conf-store.js' -import {checkForCLIVersions, getCachedCurrentMajorCLIVersion} from '../../private/node/cli-version-check.js' +import { + checkForCLIVersions, + getCachedCurrentMajorCLIVersion, + getCachedLatestCLINodeRange, +} from '../../private/node/cli-version-check.js' import {CLI_KIT_VERSION} from '../common/version.js' import {SemVer} from 'semver' import {vi, describe, test, expect, beforeEach, afterEach} from 'vitest' @@ -436,6 +440,72 @@ describe('runCLIUpgrade', () => { ) }) + test('installs the newest release that supports the running Node when latest needs a newer one', async () => { + // Given + const latest = new SemVer(CLI_KIT_VERSION).inc('minor').version + const supportedVersion = new SemVer(CLI_KIT_VERSION).inc('patch').version + vi.mocked(currentProcessIsGlobal).mockReturnValue(true) + vi.mocked(inferPackageManagerForGlobalCLI).mockReturnValue('npm') + vi.mocked(exec).mockResolvedValue() + vi.mocked(checkForCLIVersions).mockResolvedValue({ + latest, + currentMajor: supportedVersion, + latestNodeRange: `>${process.versions.node}`, + }) + vi.mocked(globalCLIVersion).mockResolvedValue(supportedVersion) + const outputMock = mockAndCaptureOutput() + outputMock.clear() + + // When + await runCLIUpgrade() + + // Then + expect(exec).toHaveBeenCalledWith('npm', ['install', '-g', `@shopify/cli@${supportedVersion}`], {stdio: 'inherit'}) + expect(outputMock.info()).toContain( + `Version ${latest} needs Node >${process.versions.node}, and this is Node ${process.versions.node}.`, + ) + expect(checkForNewVersion).not.toHaveBeenCalled() + }) + + test('says which Node latest needs instead of upgrading when no newer release supports the running Node', async () => { + // Given + const latest = new SemVer(CLI_KIT_VERSION).inc('minor').version + vi.mocked(currentProcessIsGlobal).mockReturnValue(true) + vi.mocked(inferPackageManagerForGlobalCLI).mockReturnValue('npm') + vi.mocked(checkForCLIVersions).mockResolvedValue({ + latest, + currentMajor: CLI_KIT_VERSION, + latestNodeRange: `>${process.versions.node}`, + }) + + // When/Then + await expect(runCLIUpgrade()).rejects.toThrow( + `Version ${latest} needs Node >${process.versions.node}, and this is Node ${process.versions.node}.`, + ) + expect(exec).not.toHaveBeenCalled() + }) + + test('installs latest when it supports the running Node', async () => { + // Given + const latest = new SemVer(CLI_KIT_VERSION).inc('minor').version + vi.mocked(currentProcessIsGlobal).mockReturnValue(true) + vi.mocked(inferPackageManagerForGlobalCLI).mockReturnValue('npm') + vi.mocked(exec).mockResolvedValue() + vi.mocked(checkForCLIVersions).mockResolvedValue({ + latest, + currentMajor: latest, + latestNodeRange: `>=${process.versions.node}`, + }) + vi.mocked(checkForNewVersion).mockResolvedValue(latest) + vi.mocked(globalCLIVersion).mockResolvedValue(latest) + + // When + await runCLIUpgrade() + + // Then + expect(exec).toHaveBeenCalledWith('npm', ['install', '-g', '@shopify/cli@latest'], {stdio: 'inherit'}) + }) + test('throws when the installed version cannot be verified', async () => { // Given vi.mocked(currentProcessIsGlobal).mockReturnValue(true) @@ -572,6 +642,51 @@ describe('warnIfUpgradeAvailable', () => { } }) + test('says once a day which Node the latest release needs, even with auto-upgrade on', async () => { + const nextMinor = new SemVer(CLI_KIT_VERSION).inc('minor').version + vi.mocked(getAutoUpgradeEnabled).mockReturnValue(true) + vi.mocked(checkForCachedNewVersion).mockReturnValue(nextMinor) + vi.mocked(getCachedLatestCLINodeRange).mockReturnValue(`>${process.versions.node}`) + + await warnIfUpgradeAvailable() + + expect(runAtMinimumInterval).toHaveBeenCalledWith('warn-on-available-upgrade', {days: 1}, expect.any(Function)) + const warning = mockAndCaptureOutput().warn() + expect(warning).toContain( + `Version ${nextMinor} needs Node >${process.versions.node}, and this is Node ${process.versions.node}.`, + ) + expect(warning).not.toContain(`@shopify/cli@${nextMinor}`) + }) + + test('offers the newest release that supports the running Node when auto-upgrade is disabled', async () => { + const nextMinor = new SemVer(CLI_KIT_VERSION).inc('minor').version + const nextPatch = new SemVer(CLI_KIT_VERSION).inc('patch').version + vi.mocked(getAutoUpgradeEnabled).mockReturnValue(false) + vi.mocked(checkForCachedNewVersion).mockReturnValue(nextMinor) + vi.mocked(getCachedLatestCLINodeRange).mockReturnValue(`>${process.versions.node}`) + vi.mocked(getCachedCurrentMajorCLIVersion).mockReturnValue(nextPatch) + + await warnIfUpgradeAvailable() + + const warning = mockAndCaptureOutput().warn() + expect(warning).toContain(`npm install -g @shopify/cli@${nextPatch}`) + expect(warning).toContain(`Version ${nextMinor} needs Node >${process.versions.node}`) + expect(warning).not.toContain(`@shopify/cli@${nextMinor}`) + }) + + test('keeps the Homebrew notice when the latest release needs a newer Node', async () => { + const nextMajor = new SemVer(CLI_KIT_VERSION).inc('major').version + vi.mocked(inferPackageManagerForGlobalCLI).mockReturnValue('homebrew') + vi.mocked(checkForCachedNewVersion).mockReturnValue(nextMajor) + vi.mocked(getCachedLatestCLINodeRange).mockReturnValue(`>${process.versions.node}`) + + await warnIfUpgradeAvailable() + + const warning = mockAndCaptureOutput().warn() + expect(warning).toContain(`Version ${nextMajor} available!`) + expect(warning).not.toContain('needs Node') + }) + test.each(['CI', 'prerelease'])('skips notices in %s', async (environment) => { vi.mocked(checkForCachedNewVersion).mockReturnValue(new SemVer(CLI_KIT_VERSION).inc('major').version) vi.mocked(isCI).mockReturnValue(environment === 'CI') diff --git a/packages/cli-kit/src/public/node/upgrade.ts b/packages/cli-kit/src/public/node/upgrade.ts index 574a3e2f72a..89b5b9ea267 100644 --- a/packages/cli-kit/src/public/node/upgrade.ts +++ b/packages/cli-kit/src/public/node/upgrade.ts @@ -24,7 +24,12 @@ import {isCI} from './system.js' import {globalCLIVersion, isPreReleaseVersion, isMajorVersionChange, availableHomebrewCLIVersion} from './version.js' import {AbortError} from './error.js' import {getAutoUpgradeEnabled, setAutoUpgradeEnabled, runAtMinimumInterval} from '../../private/node/conf-store.js' -import {getCachedCurrentMajorCLIVersion} from '../../private/node/cli-version-check.js' +import { + checkForCLIVersions, + getCachedCurrentMajorCLIVersion, + getCachedLatestCLINodeRange, +} from '../../private/node/cli-version-check.js' +import {supportsRunningNode} from '../../private/node/cli-version-cache.js' import {CLI_KIT_VERSION} from '../common/version.js' import {lt as semverLt, SemVer} from 'semver' import type {UpgradeResult} from './upgrade/types.js' @@ -116,7 +121,9 @@ export async function upgradeCLI(options: RunCLIUpgradeOptions = {}): Promise { const newerVersion = checkForCachedNewVersion('@shopify/cli', CLI_KIT_VERSION) if (!newerVersion) return + // Homebrew upgrades install the formula, which brings the Node it runs on. + const nodeRange = inferPackageManagerForGlobalCLI() === 'homebrew' ? undefined : getCachedLatestCLINodeRange() + if (nodeRange && !supportsRunningNode(nodeRange)) { + await warnThatLatestNeedsNewerNode(newerVersion, nodeRange) + return + } const isMajor = isMajorVersionChange(CLI_KIT_VERSION, newerVersion) if (getAutoUpgradeEnabled() && !isMajor) return @@ -256,6 +269,50 @@ export async function warnIfUpgradeAvailable(): Promise { }) } +/** + * Offers the newest release that supports the running Node, unless auto-upgrade installs it anyway, and says which + * Node the latest release needs. + * + * @param latest - The latest release, newer than the running version. + * @param nodeRange - The Node range in the latest release's `engines`, which excludes the running Node. + */ +async function warnThatLatestNeedsNewerNode(latest: string, nodeRange: string): Promise { + const supported = getCachedCurrentMajorCLIVersion() + const offer = !getAutoUpgradeEnabled() && supported && semverLt(CLI_KIT_VERSION, supported) ? supported : undefined + await runAtMinimumInterval('warn-on-available-upgrade', {days: 1}, async () => { + const needs = `${latestNeedsNewerNode(latest, nodeRange)} Upgrade Node to use it.` + outputWarn(offer ? `${getOutputUpdateCLIReminder(offer)}\n${needs}` : needs) + }) +} + +/** + * Picks the release a manual upgrade installs when the latest release's `engines` exclude the running Node: the + * newest release in the current major that supports it. + * + * @returns The version to install, or undefined to install `latest` because it supports the running Node or the + * lookup can't tell. + * @throws AbortError when no newer release supports the running Node. + */ +async function versionForRunningNode(): Promise { + const {latest, currentMajor, latestNodeRange} = (await checkForCLIVersions()) ?? {} + if (!latest || !latestNodeRange || !semverLt(CLI_KIT_VERSION, latest) || supportsRunningNode(latestNodeRange)) { + return undefined + } + const needs = latestNeedsNewerNode(latest, latestNodeRange) + if (currentMajor && semverLt(CLI_KIT_VERSION, currentMajor)) { + outputInfo(`${needs} Upgrading to ${currentMajor}, the newest version that supports it.`) + return currentMajor + } + throw new AbortError( + needs, + outputContent`Upgrade Node, then run ${outputToken.genericShellCommand('shopify upgrade')} again.`, + ) +} + +function latestNeedsNewerNode(latest: string, nodeRange: string): string { + return `Version ${latest} needs Node ${nodeRange}, and this is Node ${process.versions.node}.` +} + /** * Generates a message to remind the user to update the CLI. * For major version bumps, appends a link to the GitHub release notes so users