|
| 1 | +import { Logger } from "./logger.js"; |
| 2 | +import { createRequire } from "module"; |
| 3 | +import type { PackageJson } from "type-fest"; |
| 4 | + |
| 5 | +const require = createRequire(import.meta.url); |
| 6 | +const packageInfo = require("../../package.json") as PackageJson; |
| 7 | +const logger = new Logger({ name: "version-check" }); |
| 8 | + |
| 9 | +/** |
| 10 | + * Checks if a newer version of the package is available on npm. |
| 11 | + * Only runs check when package is installed globally. |
| 12 | + * |
| 13 | + * @returns Upgrade message string if update available, null otherwise |
| 14 | + */ |
| 15 | +export async function checkForUpdates(): Promise<string | null> { |
| 16 | + try { |
| 17 | + // Only check for updates if running as global package |
| 18 | + if (!process.env.npm_config_global) { |
| 19 | + return null; |
| 20 | + } |
| 21 | + |
| 22 | + const packageName = packageInfo.name; |
| 23 | + const currentVersion = packageInfo.version; |
| 24 | + |
| 25 | + if (!packageName || !currentVersion) { |
| 26 | + logger.warn("Unable to determine package name or version"); |
| 27 | + return null; |
| 28 | + } |
| 29 | + |
| 30 | + // Fetch latest version from npm registry |
| 31 | + const registryUrl = `https://registry.npmjs.org/${packageName}/latest`; |
| 32 | + const response = await fetch(registryUrl); |
| 33 | + |
| 34 | + if (!response.ok) { |
| 35 | + throw new Error(`Failed to fetch version info: ${response.statusText}`); |
| 36 | + } |
| 37 | + |
| 38 | + const data = (await response.json()) as { version: string | undefined }; |
| 39 | + const latestVersion = data.version; |
| 40 | + |
| 41 | + if (!latestVersion) { |
| 42 | + throw new Error("Unable to determine latest version"); |
| 43 | + } |
| 44 | + |
| 45 | + // Compare versions |
| 46 | + if (currentVersion !== latestVersion) { |
| 47 | + return `Update available: ${currentVersion} → ${latestVersion}\nRun 'npm install -g ${packageName}' to update`; |
| 48 | + } |
| 49 | + |
| 50 | + return null; |
| 51 | + } catch (error) { |
| 52 | + // Log error but don't throw to handle gracefully |
| 53 | + logger.error( |
| 54 | + "Error checking for updates:", |
| 55 | + error instanceof Error ? error.message : String(error) |
| 56 | + ); |
| 57 | + return null; |
| 58 | + } |
| 59 | +} |
0 commit comments