|
| 1 | +import { homedir } from "os" |
| 2 | +import { join } from "path" |
| 3 | +import { mkdirSync, readFileSync, writeFileSync, existsSync } from "fs" |
| 4 | +import { createRequire } from "node:module" |
| 5 | +import { resolvePackageJson } from "../runtime/root.js" |
| 6 | +import { appDebug } from "../logging/logger.js" |
| 7 | +import type { UpdateCache } from "./types.js" |
| 8 | + |
| 9 | +function debug(message: string, ...args: unknown[]) { |
| 10 | + appDebug(`[UpdateChecker] ${message}`, ...args) |
| 11 | +} |
| 12 | + |
| 13 | +const CACHE_DIR = join(homedir(), ".codemachine", "resources") |
| 14 | +const CACHE_PATH = join(CACHE_DIR, "updates.json") |
| 15 | +const CHECK_INTERVAL = 1000 * 60 * 60 * 24 // 24 hours |
| 16 | + |
| 17 | +function getPackageInfo(): { name: string; version: string } { |
| 18 | + const require = createRequire(import.meta.url) |
| 19 | + const packageJsonPath = resolvePackageJson(import.meta.url, "update checker") |
| 20 | + return require(packageJsonPath) as { name: string; version: string } |
| 21 | +} |
| 22 | + |
| 23 | +function readCache(): UpdateCache | null { |
| 24 | + try { |
| 25 | + if (!existsSync(CACHE_PATH)) { |
| 26 | + debug("Cache file does not exist") |
| 27 | + return null |
| 28 | + } |
| 29 | + const data = readFileSync(CACHE_PATH, "utf-8") |
| 30 | + const cache = JSON.parse(data) as UpdateCache |
| 31 | + debug("Read cache:", cache) |
| 32 | + return cache |
| 33 | + } catch (error) { |
| 34 | + debug("Failed to read cache:", error) |
| 35 | + return null |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +function writeCache(cache: UpdateCache): void { |
| 40 | + try { |
| 41 | + mkdirSync(CACHE_DIR, { recursive: true }) |
| 42 | + writeFileSync(CACHE_PATH, JSON.stringify(cache, null, 2)) |
| 43 | + debug("Wrote cache:", cache) |
| 44 | + } catch (error) { |
| 45 | + debug("Failed to write cache:", error) |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +async function fetchLatestVersion(packageName: string): Promise<string | null> { |
| 50 | + try { |
| 51 | + debug("Fetching latest version for:", packageName) |
| 52 | + const response = await fetch(`https://registry.npmjs.org/${packageName}/latest`, { |
| 53 | + headers: { Accept: "application/json" }, |
| 54 | + signal: AbortSignal.timeout(10000), |
| 55 | + }) |
| 56 | + if (!response.ok) { |
| 57 | + debug("Registry response not ok:", response.status) |
| 58 | + return null |
| 59 | + } |
| 60 | + const data = (await response.json()) as { version: string } |
| 61 | + debug("Latest version:", data.version) |
| 62 | + return data.version |
| 63 | + } catch (error) { |
| 64 | + debug("Failed to fetch latest version:", error) |
| 65 | + return null |
| 66 | + } |
| 67 | +} |
| 68 | + |
| 69 | +function compareVersions(current: string, latest: string): boolean { |
| 70 | + const currentParts = current.split(".").map(Number) |
| 71 | + const latestParts = latest.split(".").map(Number) |
| 72 | + |
| 73 | + for (let i = 0; i < Math.max(currentParts.length, latestParts.length); i++) { |
| 74 | + const c = currentParts[i] || 0 |
| 75 | + const l = latestParts[i] || 0 |
| 76 | + if (l > c) return true |
| 77 | + if (l < c) return false |
| 78 | + } |
| 79 | + return false |
| 80 | +} |
| 81 | + |
| 82 | +/** |
| 83 | + * Check for updates. Spawns background check if cache is stale. |
| 84 | + * Safe to call on every CLI startup - returns immediately if cache is fresh. |
| 85 | + */ |
| 86 | +export async function check(): Promise<void> { |
| 87 | + debug("check() called") |
| 88 | + |
| 89 | + if (process.env.NO_UPDATE_NOTIFIER || process.env.CODEMACHINE_NO_UPDATE_CHECK) { |
| 90 | + debug("Update check disabled by environment variable") |
| 91 | + return |
| 92 | + } |
| 93 | + |
| 94 | + const cache = readCache() |
| 95 | + const now = Date.now() |
| 96 | + |
| 97 | + if (cache && now - cache.checked < CHECK_INTERVAL) { |
| 98 | + debug("Cache is fresh, skipping check") |
| 99 | + return |
| 100 | + } |
| 101 | + |
| 102 | + debug("Cache is stale or missing, performing check") |
| 103 | + |
| 104 | + const pkg = getPackageInfo() |
| 105 | + const latest = await fetchLatestVersion(pkg.name) |
| 106 | + |
| 107 | + const newCache: UpdateCache = { |
| 108 | + current: pkg.version, |
| 109 | + latest, |
| 110 | + available: latest ? compareVersions(pkg.version, latest) : false, |
| 111 | + checked: now, |
| 112 | + } |
| 113 | + |
| 114 | + writeCache(newCache) |
| 115 | + debug("Check complete:", newCache) |
| 116 | +} |
| 117 | + |
| 118 | +/** |
| 119 | + * Get cached update status. Returns null if no cache exists. |
| 120 | + * This is synchronous and safe to call from TUI render. |
| 121 | + */ |
| 122 | +export function status(): UpdateCache | null { |
| 123 | + debug("status() called") |
| 124 | + return readCache() |
| 125 | +} |
0 commit comments