|
| 1 | +/** |
| 2 | + * Copyright 2025 Google LLC |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +import { GenkitToolsError } from '@genkit-ai/tools-common/manager'; |
| 18 | +import { getUserSettings, logger } from '@genkit-ai/tools-common/utils'; |
| 19 | +import axios, { AxiosInstance } from 'axios'; |
| 20 | +import * as clc from 'colorette'; |
| 21 | +import { arch, platform } from 'os'; |
| 22 | +import semver from 'semver'; |
| 23 | +import { UPDATE_NOTIFICATIONS_OPT_OUT_CONFIG_TAG } from '../commands/config'; |
| 24 | +import { detectCLIRuntime } from '../utils/runtime-detector'; |
| 25 | +import { |
| 26 | + version as currentVersion, |
| 27 | + name as packageName, |
| 28 | +} from '../utils/version'; |
| 29 | + |
| 30 | +const GCS_BUCKET_URL = 'https://storage.googleapis.com/genkit-assets-cli'; |
| 31 | +const CLI_DOCS_URL = 'https://genkit.dev/docs/devtools/'; |
| 32 | +const AXIOS_INSTANCE: AxiosInstance = axios.create({ |
| 33 | + timeout: 3000, |
| 34 | +}); |
| 35 | + |
| 36 | +/** |
| 37 | + * Interface for update check result |
| 38 | + */ |
| 39 | +export interface UpdateCheckResult { |
| 40 | + hasUpdate: boolean; |
| 41 | + currentVersion: string; |
| 42 | + latestVersion: string; |
| 43 | +} |
| 44 | + |
| 45 | +/** |
| 46 | + * Returns the current CLI version, normalized. |
| 47 | + */ |
| 48 | +export function getCurrentVersion(): string { |
| 49 | + return normalizeVersion(currentVersion); |
| 50 | +} |
| 51 | + |
| 52 | +/** |
| 53 | + * Normalizes a version string by removing a leading 'v' if present. |
| 54 | + * @param version - The version string to normalize |
| 55 | + * @returns The normalized version string |
| 56 | + */ |
| 57 | +function normalizeVersion(version: string): string { |
| 58 | + return version.replace(/^v/, ''); |
| 59 | +} |
| 60 | + |
| 61 | +/** |
| 62 | + * Interface for the Google Cloud Storage latest.json response |
| 63 | + */ |
| 64 | +interface GCSLatestResponse { |
| 65 | + channel: string; |
| 66 | + latestVersion: string; |
| 67 | + lastUpdated: string; |
| 68 | + platforms: Record< |
| 69 | + string, |
| 70 | + { |
| 71 | + url: string; |
| 72 | + version: string; |
| 73 | + versionedUrl: string; |
| 74 | + } |
| 75 | + >; |
| 76 | +} |
| 77 | + |
| 78 | +/** |
| 79 | + * Interface for npm registry response |
| 80 | + */ |
| 81 | +interface NpmRegistryResponse { |
| 82 | + 'dist-tags': { |
| 83 | + latest: string; |
| 84 | + [key: string]: string; |
| 85 | + }; |
| 86 | + versions: Record<string, unknown>; |
| 87 | +} |
| 88 | + |
| 89 | +/** |
| 90 | + * Fetches the latest release data from GCS. |
| 91 | + */ |
| 92 | +async function getGCSLatestData(): Promise<GCSLatestResponse> { |
| 93 | + const response = await AXIOS_INSTANCE.get(`${GCS_BUCKET_URL}/latest.json`); |
| 94 | + |
| 95 | + if (response.status !== 200) { |
| 96 | + throw new GenkitToolsError( |
| 97 | + `Failed to fetch GCS latest.json: ${response.statusText}` |
| 98 | + ); |
| 99 | + } |
| 100 | + |
| 101 | + return response.data as GCSLatestResponse; |
| 102 | +} |
| 103 | + |
| 104 | +/** |
| 105 | + * Gets the latest CLI version from npm registry for non-binary installations. |
| 106 | + * @param ignoreRC - If true, ignore prerelease versions (default: true) |
| 107 | + */ |
| 108 | +export async function getLatestVersionFromNpm( |
| 109 | + ignoreRC: boolean = true |
| 110 | +): Promise<string | null> { |
| 111 | + try { |
| 112 | + const response = await AXIOS_INSTANCE.get( |
| 113 | + `https://registry.npmjs.org/${packageName}` |
| 114 | + ); |
| 115 | + |
| 116 | + if (response.status !== 200) { |
| 117 | + throw new GenkitToolsError( |
| 118 | + `Failed to fetch npm versions: ${response.statusText}` |
| 119 | + ); |
| 120 | + } |
| 121 | + |
| 122 | + const data: NpmRegistryResponse = response.data; |
| 123 | + |
| 124 | + // Prefer dist-tags.latest if valid and not a prerelease (if ignoreRC) |
| 125 | + const latest = data['dist-tags']?.latest; |
| 126 | + if (latest) { |
| 127 | + const clean = normalizeVersion(latest); |
| 128 | + if (semver.valid(clean) && (!ignoreRC || !semver.prerelease(clean))) { |
| 129 | + return clean; |
| 130 | + } |
| 131 | + } |
| 132 | + |
| 133 | + // Fallback: find the highest valid version in versions |
| 134 | + const versions = Object.keys(data.versions) |
| 135 | + .map(normalizeVersion) |
| 136 | + .filter((v) => semver.valid(v) && (!ignoreRC || !semver.prerelease(v))); |
| 137 | + |
| 138 | + if (versions.length === 0) { |
| 139 | + return null; |
| 140 | + } |
| 141 | + |
| 142 | + // Sort by semver descending (newest first) |
| 143 | + versions.sort(semver.rcompare); |
| 144 | + return versions[0]; |
| 145 | + } catch (error: unknown) { |
| 146 | + if (error instanceof GenkitToolsError) { |
| 147 | + throw error; |
| 148 | + } |
| 149 | + |
| 150 | + throw new GenkitToolsError( |
| 151 | + `Failed to fetch npm versions: ${(error as Error)?.message ?? String(error)}` |
| 152 | + ); |
| 153 | + } |
| 154 | +} |
| 155 | + |
| 156 | +/** |
| 157 | + * Checks if update notifications are disabled via environment variable or user config. |
| 158 | + */ |
| 159 | +function isUpdateNotificationsDisabled(): boolean { |
| 160 | + if (process.env.GENKIT_CLI_DISABLE_UPDATE_NOTIFICATIONS === 'true') { |
| 161 | + return true; |
| 162 | + } |
| 163 | + const userSettings = getUserSettings(); |
| 164 | + return Boolean(userSettings[UPDATE_NOTIFICATIONS_OPT_OUT_CONFIG_TAG]); |
| 165 | +} |
| 166 | + |
| 167 | +/** |
| 168 | + * Gets the latest version and update message for compiled binary installations. |
| 169 | + */ |
| 170 | +async function getBinaryUpdateInfo(): Promise<string | null> { |
| 171 | + const gcsLatestData = await getGCSLatestData(); |
| 172 | + const machine = `${platform}-${arch}`; |
| 173 | + const platformData = gcsLatestData.platforms[machine]; |
| 174 | + |
| 175 | + if (!platformData) { |
| 176 | + logger.debug(`No update information for platform: ${machine}`); |
| 177 | + return null; |
| 178 | + } |
| 179 | + |
| 180 | + const latestVersion = normalizeVersion(gcsLatestData.latestVersion); |
| 181 | + return latestVersion; |
| 182 | +} |
| 183 | + |
| 184 | +/** |
| 185 | + * Gets the latest version and update message for npm installations. |
| 186 | + */ |
| 187 | +async function getNpmUpdateInfo(): Promise<string | null> { |
| 188 | + const latestVersion = await getLatestVersionFromNpm(); |
| 189 | + if (!latestVersion) { |
| 190 | + logger.debug('No available versions found from npm.'); |
| 191 | + return null; |
| 192 | + } |
| 193 | + return latestVersion; |
| 194 | +} |
| 195 | + |
| 196 | +/** |
| 197 | + * Shows an update notification if a new version is available. |
| 198 | + * This function is designed to be called from the CLI entry point. |
| 199 | + * It can be disabled by the user's configuration or environment variable. |
| 200 | + */ |
| 201 | +export async function showUpdateNotification(): Promise<void> { |
| 202 | + try { |
| 203 | + if (isUpdateNotificationsDisabled()) { |
| 204 | + return; |
| 205 | + } |
| 206 | + |
| 207 | + const { isCompiledBinary } = detectCLIRuntime(); |
| 208 | + const updateInfo = isCompiledBinary |
| 209 | + ? await getBinaryUpdateInfo() |
| 210 | + : await getNpmUpdateInfo(); |
| 211 | + |
| 212 | + if (!updateInfo) { |
| 213 | + return; |
| 214 | + } |
| 215 | + |
| 216 | + const latestVersion = updateInfo; |
| 217 | + const current = normalizeVersion(currentVersion); |
| 218 | + |
| 219 | + if (!semver.valid(latestVersion) || !semver.valid(current)) { |
| 220 | + logger.debug( |
| 221 | + `Invalid semver: current=${current}, latest=${latestVersion}` |
| 222 | + ); |
| 223 | + return; |
| 224 | + } |
| 225 | + |
| 226 | + if (!semver.gt(latestVersion, current)) { |
| 227 | + return; |
| 228 | + } |
| 229 | + |
| 230 | + // Determine install method and update command for message |
| 231 | + const installMethod = isCompiledBinary |
| 232 | + ? 'installer script' |
| 233 | + : 'your package manager'; |
| 234 | + const updateCommand = isCompiledBinary |
| 235 | + ? 'curl -sL cli.genkit.dev | uninstall=true bash' |
| 236 | + : 'npm install -g genkit-cli'; |
| 237 | + |
| 238 | + const updateNotificationMessage = |
| 239 | + `Update available ${clc.gray(`v${current}`)} → ${clc.green(`v${latestVersion}`)}\n` + |
| 240 | + `To update to the latest version using ${installMethod}, run\n${clc.cyan(updateCommand)}\n` + |
| 241 | + `For other CLI management options, visit ${CLI_DOCS_URL}\n` + |
| 242 | + `${clc.dim('Run')} ${clc.bold('genkit config set updateNotificationsOptOut true')} ${clc.dim('to disable these notifications')}\n`; |
| 243 | + |
| 244 | + logger.info(`\n${updateNotificationMessage}`); |
| 245 | + } catch (e) { |
| 246 | + // Silently fail - update notifications shouldn't break the CLI |
| 247 | + logger.debug('Failed to show update notification', e); |
| 248 | + } |
| 249 | +} |
0 commit comments