Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/upgrade-supported-node.md
Original file line number Diff line number Diff line change
@@ -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
37 changes: 37 additions & 0 deletions packages/cli-kit/src/private/node/cli-version-cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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})
}
41 changes: 41 additions & 0 deletions packages/cli-kit/src/private/node/cli-version-check.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
},
Expand All @@ -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
Expand Down
36 changes: 27 additions & 9 deletions packages/cli-kit/src/private/node/cli-version-check.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand All @@ -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 {
Expand All @@ -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<CLIVersions> {
try {
const registry = await resolveCLIRegistry()
Expand All @@ -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 {}
Expand Down Expand Up @@ -85,6 +105,8 @@ async function fetchAndCacheVersions(registry: string): Promise<CLIVersions> {
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)
Expand All @@ -95,19 +117,15 @@ async function fetchAndCacheVersions(registry: string): Promise<CLIVersions> {
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.')
cacheStore(failureCacheKey, '')
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})
}
117 changes: 116 additions & 1 deletion packages/cli-kit/src/public/node/upgrade.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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')
Expand Down
Loading
Loading