The best way to control Claude Code, Codex and more from any computer or phone
| 1 | // @effect-diagnostics nodeBuiltinImport:off -- Synchronous hashing keeps env values out of cache keys. |
| 2 | import * as NodeCrypto from "node:crypto"; |
| 3 | export type { |
| 4 | ProviderMaintenanceCapabilities, |
| 5 | ProviderMaintenanceCommandAction, |
| 6 | } from "@t3tools/provider-core/server/maintenance"; |
| 7 | import type { |
| 8 | ProviderMaintenanceCapabilities, |
| 9 | ProviderMaintenanceCommandAction, |
| 10 | } from "@t3tools/provider-core/server/maintenance"; |
| 11 | import { |
| 12 | ProviderDriverKind, |
| 13 | type ServerProvider, |
| 14 | type ServerProviderVersionAdvisory, |
| 15 | } from "@t3tools/contracts"; |
| 16 | import { compareSemverVersions, satisfiesSemverRange } from "@t3tools/shared/semver"; |
| 17 | import * as HostProcess from "@t3tools/shared/HostProcess"; |
| 18 | import { causeErrorTag } from "@t3tools/shared/observability"; |
| 19 | import { resolveCommandPath, resolveSpawnCommand } from "@t3tools/shared/shell"; |
| 20 | import * as Cache from "effect/Cache"; |
| 21 | import * as Config from "effect/Config"; |
| 22 | import * as DateTime from "effect/DateTime"; |
| 23 | import * as Duration from "effect/Duration"; |
| 24 | import * as Effect from "effect/Effect"; |
| 25 | import * as FileSystem from "effect/FileSystem"; |
| 26 | import * as Option from "effect/Option"; |
| 27 | import * as Path from "effect/Path"; |
| 28 | import * as Schema from "effect/Schema"; |
| 29 | import * as Stream from "effect/Stream"; |
| 30 | import * as HttpClient from "effect/http/HttpClient"; |
| 31 | import * as HttpClientRequest from "effect/http/HttpClientRequest"; |
| 32 | import * as HttpClientResponse from "effect/http/HttpClientResponse"; |
| 33 | import * as ChildProcess from "effect/process/ChildProcess"; |
| 34 | import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; |
| 35 | |
| 36 | import { collectUint8StreamText } from "./collectStreamText.ts"; |
| 37 | import * as ProviderLatestVersions from "./ProviderLatestVersions.ts"; |
| 38 | |
| 39 | const LATEST_VERSION_TIMEOUT_MS = 4_000; |
| 40 | const PROBE_TIMEOUT_MS = 10_000; |
| 41 | const PROBE_MAX_BYTES = 256 * 1_024; |
| 42 | const WRAPPER_SCRIPT_MAX_BYTES = 16 * 1_024; |
| 43 | const PROVIDER_UPDATE_ACTION_TOAST_MESSAGE = "Install the update now or review provider settings."; |
| 44 | |
| 45 | const MAINTENANCE_CAPABILITIES_CACHE_TTL = Duration.hours(1); |
| 46 | |
| 47 | const compactEnv = (input: Record<string, Option.Option<string>>): NodeJS.ProcessEnv => |
| 48 | Object.fromEntries( |
| 49 | Object.entries(input).flatMap(([key, value]) => |
| 50 | Option.match(value, { |
| 51 | onNone: () => [], |
| 52 | onSome: (resolved) => [[key, resolved]], |
| 53 | }), |
| 54 | ), |
| 55 | ); |
| 56 | |
| 57 | const CommandLookupEnvConfig = Config.all({ |
| 58 | PATH: Config.String("PATH").pipe(Config.option), |
| 59 | Path: Config.String("Path").pipe(Config.option), |
| 60 | path: Config.String("path").pipe(Config.option), |
| 61 | PATHEXT: Config.String("PATHEXT").pipe(Config.option), |
| 62 | }).pipe(Config.map(compactEnv)); |
| 63 | |
| 64 | const readCommandLookupEnv = CommandLookupEnvConfig.pipe(Effect.orElseSucceed(() => ({}))); |
| 65 | |
| 66 | export interface ProviderMaintenanceResolutionContext { |
| 67 | readonly binaryPath: string; |
| 68 | readonly resolvedCommandPath: string; |
| 69 | readonly realCommandPath: string; |
| 70 | readonly env: NodeJS.ProcessEnv; |
| 71 | readonly platform: NodeJS.Platform; |
| 72 | } |
| 73 | |
| 74 | export type ProviderMaintenanceResolverServices = |
| 75 | | FileSystem.FileSystem |
| 76 | | Path.Path |
| 77 | | ChildProcessSpawner.ChildProcessSpawner; |
| 78 | |
| 79 | export interface ProviderMaintenanceCapabilitiesResolver { |
| 80 | readonly resolve: ( |
| 81 | context: ProviderMaintenanceResolutionContext | null, |
| 82 | ) => Effect.Effect<ProviderMaintenanceCapabilities, never, ProviderMaintenanceResolverServices>; |
| 83 | } |
| 84 | |
| 85 | export interface PackageManagedProviderMaintenanceDefinition { |
| 86 | readonly provider: ProviderDriverKind; |
| 87 | readonly npmPackageName: string; |
| 88 | readonly nativeUpdate: { |
| 89 | readonly args: ReadonlyArray<string>; |
| 90 | readonly isCommandPath?: (commandPath: string) => boolean; |
| 91 | /** The updater cannot detect installs outside `isCommandPath`, so leave those manual-only. */ |
| 92 | readonly requiresCommandPath?: boolean; |
| 93 | readonly env?: |
| 94 | | NodeJS.ProcessEnv |
| 95 | | ((context: ProviderMaintenanceResolutionContext) => NodeJS.ProcessEnv); |
| 96 | } | null; |
| 97 | /** The mise registry tool that installs this provider; unset keeps mise installs manual-only. */ |
| 98 | readonly mise?: MiseProviderTool; |
| 99 | } |
| 100 | |
| 101 | export interface MiseProviderTool { |
| 102 | readonly tool: string; |
| 103 | /** False still claims the tool's installs, but keeps them manual-only. */ |
| 104 | readonly upgrade?: boolean; |
| 105 | } |
| 106 | |
| 107 | const NpmLatestVersionResponse = Schema.Struct({ |
| 108 | version: Schema.optional(Schema.String), |
| 109 | }); |
| 110 | |
| 111 | function nonEmptyString(value: unknown): string | null { |
| 112 | return typeof value === "string" && value.trim().length > 0 ? value.trim() : null; |
| 113 | } |
| 114 | |
| 115 | function quoteShellWord(word: string, platform: NodeJS.Platform): string { |
| 116 | const safeWord = platform === "win32" ? /^[\w./:\\@=-]+$/ : /^[\w./:@=-]+$/; |
| 117 | if (safeWord.test(word)) return word; |
| 118 | return platform === "win32" |
| 119 | ? `'${word.replace(/['\u2018\u2019]/g, "$&$&")}'` |
| 120 | : `'${word.replaceAll("'", "'\\''")}'`; |
| 121 | } |
| 122 | |
| 123 | function quoteUpdateExecutable(executable: string, platform: NodeJS.Platform): string { |
| 124 | const quoted = quoteShellWord(executable, platform); |
| 125 | // Windows terminals default to PowerShell, where a quoted executable needs &. |
| 126 | return platform === "win32" && quoted !== executable ? `& ${quoted}` : quoted; |
| 127 | } |
| 128 | |
| 129 | export function makeProviderMaintenanceCapabilities(input: { |
| 130 | readonly provider: ProviderDriverKind; |
| 131 | readonly packageName: string | null; |
| 132 | readonly updateExecutable: string | null; |
| 133 | readonly updateArgs: ReadonlyArray<string>; |
| 134 | readonly updateLockKey: string | null; |
| 135 | readonly updateCommand?: string; |
| 136 | readonly platform?: NodeJS.Platform; |
| 137 | readonly env?: NodeJS.ProcessEnv; |
| 138 | readonly latestVersion?: string | null; |
| 139 | readonly lookupLatestVersion?: Effect.Effect<string | null>; |
| 140 | }): ProviderMaintenanceCapabilities { |
| 141 | const platform = input.platform ?? HostProcess.Platform.defaultValue(); |
| 142 | const update = |
| 143 | input.updateExecutable === null || input.updateLockKey === null |
| 144 | ? null |
| 145 | : { |
| 146 | command: |
| 147 | input.updateCommand ?? |
| 148 | [ |
| 149 | quoteUpdateExecutable(input.updateExecutable, platform), |
| 150 | ...input.updateArgs.map((arg) => quoteShellWord(arg, platform)), |
| 151 | ].join(" "), |
| 152 | executable: input.updateExecutable, |
| 153 | args: input.updateArgs, |
| 154 | lockKey: input.updateLockKey, |
| 155 | ...(input.env ? { env: input.env } : {}), |
| 156 | }; |
| 157 | return { |
| 158 | provider: input.provider, |
| 159 | packageName: input.packageName, |
| 160 | update, |
| 161 | ...("latestVersion" in input ? { latestVersion: input.latestVersion } : {}), |
| 162 | ...(input.lookupLatestVersion ? { lookupLatestVersion: input.lookupLatestVersion } : {}), |
| 163 | }; |
| 164 | } |
| 165 | |
| 166 | export function makeTargetedProviderUpdateAction( |
| 167 | capabilities: ProviderMaintenanceCapabilities, |
| 168 | version: string, |
| 169 | ): ProviderMaintenanceCommandAction | null { |
| 170 | if (!/^\d+\.\d+\.\d+$/.test(version)) return null; |
| 171 | const update = capabilities.update; |
| 172 | const packageName = capabilities.packageName; |
| 173 | if (!update || !packageName) return null; |
| 174 | if ( |
| 175 | !/^(?:npm-global:|bun-global$|pnpm-global$|vite-plus-global$|yarn-global$|volta$)/.test( |
| 176 | update.lockKey, |
| 177 | ) |
| 178 | ) |
| 179 | return null; |
| 180 | const packageIndex = update.args.findIndex( |
| 181 | (arg) => arg === `${packageName}@latest` || arg === packageName, |
| 182 | ); |
| 183 | if (packageIndex < 0) return null; |
| 184 | const args = update.args.map((arg, index) => |
| 185 | index === packageIndex ? `${packageName}@${version}` : arg, |
| 186 | ); |
| 187 | const previous = update.args[packageIndex]!; |
| 188 | const commandIndex = update.command.lastIndexOf(previous); |
| 189 | const command = |
| 190 | commandIndex < 0 |
| 191 | ? update.command |
| 192 | : `${update.command.slice(0, commandIndex)}${packageName}@${version}${update.command.slice(commandIndex + previous.length)}`; |
| 193 | return { ...update, args, command }; |
| 194 | } |
| 195 | |
| 196 | // pnpm 11 resolves `@latest` to the newest release older than `minimumReleaseAge` |
| 197 | // and exits 0, so a release advertised from the npm dist-tag would never install. |
| 198 | // An exact spec installs it and pnpm records it in `minimumReleaseAgeExclude`. |
| 199 | export function resolveLatestProviderUpdateAction( |
| 200 | capabilities: ProviderMaintenanceCapabilities, |
| 201 | latestVersion: string | null, |
| 202 | ): ProviderMaintenanceCommandAction | null { |
| 203 | const update = capabilities.update; |
| 204 | if (update?.lockKey !== "pnpm-global" || latestVersion === null) return update; |
| 205 | return makeTargetedProviderUpdateAction(capabilities, latestVersion) ?? update; |
| 206 | } |
| 207 | |
| 208 | export function makeManualOnlyProviderMaintenanceCapabilities(input: { |
| 209 | readonly provider: ProviderDriverKind; |
| 210 | readonly packageName: string | null; |
| 211 | readonly installPath?: string; |
| 212 | readonly lookupLatestVersion?: Effect.Effect<string | null>; |
| 213 | readonly manualCommand?: string; |
| 214 | }): ProviderMaintenanceCapabilities { |
| 215 | return { |
| 216 | ...makeProviderMaintenanceCapabilities({ |
| 217 | provider: input.provider, |
| 218 | packageName: input.packageName, |
| 219 | updateExecutable: null, |
| 220 | updateArgs: [], |
| 221 | updateLockKey: null, |
| 222 | ...(input.lookupLatestVersion |
| 223 | ? { latestVersion: null, lookupLatestVersion: input.lookupLatestVersion } |
| 224 | : {}), |
| 225 | }), |
| 226 | ...(input.installPath ? { installPath: input.installPath } : {}), |
| 227 | ...(input.manualCommand ? { manualCommand: input.manualCommand } : {}), |
| 228 | }; |
| 229 | } |
| 230 | |
| 231 | export function normalizeCommandPath(commandPath: string): string { |
| 232 | return commandPath.replaceAll("\\", "/").toLowerCase(); |
| 233 | } |
| 234 | |
| 235 | /** |
| 236 | * Vite+ shims live in `<VP_HOME>/bin`: `~/.vite-plus` by default, |
| 237 | * `~/.local/share/vite-plus` with the XDG layout, and `%LOCALAPPDATA%\vite-plus` |
| 238 | * on Windows. |
| 239 | */ |
| 240 | function isVitePlusGlobalCommandPath(commandPath: string): boolean { |
| 241 | return /\/(?:\.vite-plus|\.local\/share\/vite-plus|appdata\/local\/vite-plus)\/bin\//.test( |
| 242 | normalizeCommandPath(commandPath), |
| 243 | ); |
| 244 | } |
| 245 | |
| 246 | function isBunGlobalCommandPath(commandPath: string): boolean { |
| 247 | return normalizeCommandPath(commandPath).includes("/.bun/bin/"); |
| 248 | } |
| 249 | |
| 250 | function isYarnGlobalCommandPath(commandPath: string): boolean { |
| 251 | return /\/yarn\/(?:data\/)?global\/node_modules\//.test(normalizeCommandPath(commandPath)); |
| 252 | } |
| 253 | |
| 254 | /** |
| 255 | * Paths mise owns. npm globals under mise's own Node belong to npm, which proves their prefix. |
| 256 | * A command wrapper is a symlink to the `mise` binary, which dispatches on argv[0]. |
| 257 | */ |
| 258 | function isMiseCommandPath(commandPath: string, env: NodeJS.ProcessEnv): boolean { |
| 259 | const normalized = normalizeCommandPath(commandPath); |
| 260 | const dir = (root: string | undefined, ...segments: ReadonlyArray<string>) => |
| 261 | root ? [normalizeCommandPath(root).replace(/\/+$/, ""), ...segments].join("/") : undefined; |
| 262 | // `MISE_DATA_DIR` and friends move mise's layout off its usual `/mise/` paths. |
| 263 | const installRoots = [ |
| 264 | dir(env.MISE_DATA_DIR, "installs"), |
| 265 | dir(env.MISE_DATA_DIR, "i"), |
| 266 | dir(env.MISE_SYSTEM_DATA_DIR, "installs"), |
| 267 | dir(env.MISE_INSTALLS_DIR), |
| 268 | dir(env.MISE_INSTALL_STORE_DIR), |
| 269 | dir(env.MISE_SYSTEM_INSTALLS_DIR), |
| 270 | ]; |
| 271 | const otherRoots = [ |
| 272 | dir(env.MISE_DATA_DIR, "shims"), |
| 273 | dir(env.MISE_DATA_DIR, "command-wrappers"), |
| 274 | dir(env.MISE_SYSTEM_DATA_DIR, "shims"), |
| 275 | ]; |
| 276 | const under = (root: string | undefined) => |
| 277 | root !== undefined && normalized.startsWith(`${root}/`); |
| 278 | return ( |
| 279 | (normalized.includes("/mise/installs/") && !normalized.includes("/mise/installs/node/")) || |
| 280 | normalized.includes("/mise/shims/") || |
| 281 | normalized.includes("/mise/command-wrappers/") || |
| 282 | installRoots.some((root) => under(root) && !under(dir(root, "node"))) || |
| 283 | otherRoots.some(under) |
| 284 | ); |
| 285 | } |
| 286 | |
| 287 | /** A mise shim or command wrapper is a link to mise itself, wherever mise keeps its data. */ |
| 288 | function isMiseExecutablePath(commandPath: string): boolean { |
| 289 | return /(?:^|\/)mise(?:\.exe)?$/.test(normalizeCommandPath(commandPath)); |
| 290 | } |
| 291 | |
| 292 | /** The Nix store is read-only, so no updater can replace a CLI that lives there. */ |
| 293 | export function isNixStoreCommandPath(commandPath: string): boolean { |
| 294 | return normalizeCommandPath(commandPath).startsWith("/nix/store/"); |
| 295 | } |
| 296 | |
| 297 | const winGetClaudeCommandPath = |
| 298 | /^[a-z]:\/(?:users\/[^/]+\/appdata\/local\/microsoft|program files(?: \(x86\))?)\/winget\/(?:links|packages\/anthropic\.claudecode_[^/]+)\/claude\.exe$/; |
| 299 | |
| 300 | function isWinGetClaudeCommandPath(commandPath: string): boolean { |
| 301 | return winGetClaudeCommandPath.test(normalizeCommandPath(commandPath)); |
| 302 | } |
| 303 | |
| 304 | const CHOCOLATEY_CLAUDE_PACKAGE_ID = "claude-code"; |
| 305 | |
| 306 | // Chocolatey's executable shim is not a symlink, so realpath cannot prove its owner. |
| 307 | const chocolateyClaudeCommandPath = /\/chocolatey\/(?:bin|lib\/claude-code\/tools)\/claude\.exe$/; |
| 308 | |
| 309 | function isChocolateyClaudeCommandPath(commandPath: string, env: NodeJS.ProcessEnv): boolean { |
| 310 | const normalized = normalizeCommandPath(commandPath); |
| 311 | if (chocolateyClaudeCommandPath.test(normalized)) return true; |
| 312 | const root = nonEmptyString(env.ChocolateyInstall); |
| 313 | if (!root) return false; |
| 314 | const prefix = normalizeCommandPath(root.replace(/[\\/]+$/, "")); |
| 315 | return ( |
| 316 | normalized === `${prefix}/bin/claude.exe` || |
| 317 | normalized === `${prefix}/lib/claude-code/tools/claude.exe` |
| 318 | ); |
| 319 | } |
| 320 | |
| 321 | /** `choco search --exact --limit-output` prints `<id>|<version>` for a match and nothing otherwise. */ |
| 322 | export function parseChocolateyLatestVersion(output: string, packageId: string): string | null { |
| 323 | for (const line of output.split(/\r?\n/)) { |
| 324 | const [id, version] = line.trim().split("|", 2); |
| 325 | if (id?.toLowerCase() === packageId.toLowerCase()) return nonEmptyString(version); |
| 326 | } |
| 327 | return null; |
| 328 | } |
| 329 | |
| 330 | function isPnpmGlobalCommandPath(commandPath: string): boolean { |
| 331 | const normalized = normalizeCommandPath(commandPath); |
| 332 | return ( |
| 333 | normalized.includes("/.local/share/pnpm/") || |
| 334 | normalized.includes("/library/pnpm/") || |
| 335 | normalized.includes("/local/share/pnpm/") || |
| 336 | normalized.includes("/appdata/local/pnpm/") || |
| 337 | normalized.includes("/pnpm/global/") |
| 338 | ); |
| 339 | } |
| 340 | |
| 341 | export function npmGlobalPrefixFromCommandPath( |
| 342 | realCommandPath: string, |
| 343 | packageName: string, |
| 344 | ): string | null { |
| 345 | const slashPath = realCommandPath.replaceAll("\\", "/"); |
| 346 | const normalized = slashPath.toLowerCase(); |
| 347 | const packageSegment = `/lib/node_modules/${packageName.toLowerCase()}/`; |
| 348 | const packageIndex = normalized.lastIndexOf(packageSegment); |
| 349 | if (packageIndex < 0 || normalized.slice(0, packageIndex).includes("/node_modules/")) { |
| 350 | return null; |
| 351 | } |
| 352 | // Mise tool layouts resemble npm globals; only globals under its Node install belong to npm. |
| 353 | const miseTool = /\/mise\/installs\/([^/]+)\/[^/]+$/.exec(normalized.slice(0, packageIndex))?.[1]; |
| 354 | if (miseTool && miseTool !== "node") { |
| 355 | return null; |
| 356 | } |
| 357 | return packageIndex === 0 ? "/" : slashPath.slice(0, packageIndex); |
| 358 | } |
| 359 | |
| 360 | const HOMEBREW_KEG_PATTERN = /^(.*)\/(cellar|caskroom)\/([^/]+)\/[^/]+\//i; |
| 361 | |
| 362 | export interface HomebrewOwnership { |
| 363 | readonly kind: "formula" | "cask"; |
| 364 | readonly name: string; |
| 365 | readonly prefix: string; |
| 366 | } |
| 367 | |
| 368 | export function homebrewOwnershipFromCommandPath( |
| 369 | realCommandPath: string, |
| 370 | ): HomebrewOwnership | null { |
| 371 | const match = HOMEBREW_KEG_PATTERN.exec(realCommandPath.replaceAll("\\", "/")); |
| 372 | if (!match) { |
| 373 | return null; |
| 374 | } |
| 375 | return { |
| 376 | kind: match[2]!.toLowerCase() === "cellar" ? "formula" : "cask", |
| 377 | name: match[3]!, |
| 378 | prefix: match[1]!, |
| 379 | }; |
| 380 | } |
| 381 | |
| 382 | const HomebrewInfoResponse = Schema.Struct({ |
| 383 | formulae: Schema.optional( |
| 384 | Schema.Array( |
| 385 | Schema.Struct({ |
| 386 | versions: Schema.optional(Schema.Struct({ stable: Schema.optional(Schema.String) })), |
| 387 | }), |
| 388 | ), |
| 389 | ), |
| 390 | casks: Schema.optional(Schema.Array(Schema.Struct({ version: Schema.optional(Schema.String) }))), |
| 391 | }); |
| 392 | |
| 393 | const decodeHomebrewInfo = Schema.decodeUnknownOption(Schema.fromJsonString(HomebrewInfoResponse)); |
| 394 | |
| 395 | export function parseHomebrewLatestVersion( |
| 396 | infoJson: string, |
| 397 | ownership: HomebrewOwnership, |
| 398 | ): string | null { |
| 399 | const decoded = decodeHomebrewInfo(infoJson); |
| 400 | if (Option.isNone(decoded)) { |
| 401 | return null; |
| 402 | } |
| 403 | const raw = |
| 404 | ownership.kind === "formula" |
| 405 | ? decoded.value.formulae?.[0]?.versions?.stable |
| 406 | : decoded.value.casks?.[0]?.version?.split(",", 1)[0]; |
| 407 | const version = nonEmptyString(raw); |
| 408 | return version === "latest" ? null : version; |
| 409 | } |
| 410 | |
| 411 | const runProbe = Effect.fn("runProbe")(function* ( |
| 412 | command: string, |
| 413 | args: ReadonlyArray<string>, |
| 414 | env: NodeJS.ProcessEnv, |
| 415 | okExitCodes: ReadonlyArray<number> = [0], |
| 416 | ) { |
| 417 | const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; |
| 418 | const collect = Effect.gen(function* () { |
| 419 | // Windows package managers are `.cmd` shims that need the shell. |
| 420 | const resolved = yield* resolveSpawnCommand(command, args, { env, extendEnv: true }); |
| 421 | const child = yield* spawner.spawn( |
| 422 | ChildProcess.make(resolved.command, resolved.args, { |
| 423 | env, |
| 424 | extendEnv: true, |
| 425 | shell: resolved.shell, |
| 426 | }), |
| 427 | ); |
| 428 | yield* Effect.addFinalizer(() => child.kill().pipe(Effect.ignore)); |
| 429 | // stderr is drained so a chatty tool cannot block on a full pipe. |
| 430 | const [stdout, exitCode] = yield* Effect.all( |
| 431 | [ |
| 432 | collectUint8StreamText({ stream: child.stdout, maxBytes: PROBE_MAX_BYTES }), |
| 433 | child.exitCode, |
| 434 | Stream.runDrain(child.stderr), |
| 435 | ], |
| 436 | { concurrency: "unbounded" }, |
| 437 | ); |
| 438 | return !okExitCodes.includes(Number(exitCode)) || stdout.truncated ? null : stdout.text; |
| 439 | }); |
| 440 | return yield* collect.pipe( |
| 441 | Effect.scoped, |
| 442 | Effect.timeoutOption(Duration.millis(PROBE_TIMEOUT_MS)), |
| 443 | Effect.map(Option.getOrNull), |
| 444 | Effect.catchCause((cause) => |
| 445 | Effect.logWarning("Maintenance probe failed", { |
| 446 | command, |
| 447 | subcommand: args[0], |
| 448 | errorTag: causeErrorTag(cause), |
| 449 | }).pipe(Effect.as(null)), |
| 450 | ), |
| 451 | ); |
| 452 | }); |
| 453 | |
| 454 | const decodeOutdated = Schema.decodeUnknownOption( |
| 455 | Schema.fromJsonString( |
| 456 | Schema.Record(Schema.String, Schema.Struct({ latest: Schema.optional(Schema.String) })), |
| 457 | ), |
| 458 | ); |
| 459 | const GlobalPackageList = Schema.Struct({ |
| 460 | dependencies: Schema.optional( |
| 461 | Schema.Record(Schema.String, Schema.Struct({ version: Schema.optional(Schema.String) })), |
| 462 | ), |
| 463 | }); |
| 464 | const decodePnpmList = Schema.decodeUnknownOption( |
| 465 | Schema.fromJsonString(Schema.Array(GlobalPackageList)), |
| 466 | ); |
| 467 | const decodeNpmList = Schema.decodeUnknownOption(Schema.fromJsonString(GlobalPackageList)); |
| 468 | |
| 469 | // Unlike the registry's latest tag, pnpm outdated respects minimumReleaseAge and its excludes. |
| 470 | const resolvePnpmGlobalLatestVersion = Effect.fn("resolvePnpmGlobalLatestVersion")(function* ( |
| 471 | packageName: string, |
| 472 | env: NodeJS.ProcessEnv, |
| 473 | ) { |
| 474 | // Match the updater's pnpm and environment. |
| 475 | const pnpmPath = yield* resolveCommandPath("pnpm", { |
| 476 | env: { ...(yield* HostProcess.Environment), ...env }, |
| 477 | }); |
| 478 | if (!pnpmPath) return null; |
| 479 | // Silent reporting keeps project package-manager warnings out of the JSON. |
| 480 | const outdated = yield* runProbe( |
| 481 | pnpmPath, |
| 482 | ["outdated", "-g", "--reporter=silent", "--format", "json", packageName], |
| 483 | env, |
| 484 | // pnpm outdated exits 1 when updates are available. |
| 485 | [0, 1], |
| 486 | ); |
| 487 | const outdatedEntries = outdated ? Option.getOrUndefined(decodeOutdated(outdated)) : undefined; |
| 488 | if (!outdatedEntries) return null; |
| 489 | const latest = nonEmptyString(outdatedEntries[packageName]?.latest); |
| 490 | if (latest) return latest; |
| 491 | // An empty result means the installed version is still the eligible release. |
| 492 | const listed = yield* runProbe( |
| 493 | pnpmPath, |
| 494 | ["ls", "-g", "--reporter=silent", "--depth", "0", "--json", packageName], |
| 495 | env, |
| 496 | ); |
| 497 | const listedEntries = listed ? Option.getOrUndefined(decodePnpmList(listed)) : undefined; |
| 498 | return nonEmptyString(listedEntries?.[0]?.dependencies?.[packageName]?.version); |
| 499 | }); |
| 500 | |
| 501 | // Unlike `npm view`, `outdated` applies min-release-age, before and their excludes. |
| 502 | const resolveNpmGlobalLatestVersion = Effect.fn("resolveNpmGlobalLatestVersion")(function* ( |
| 503 | packageName: string, |
| 504 | npmPrefix: string, |
| 505 | env: NodeJS.ProcessEnv, |
| 506 | ) { |
| 507 | // Match the updater's npm and environment. |
| 508 | const npmPath = yield* resolveCommandPath("npm", { |
| 509 | env: { ...(yield* HostProcess.Environment), ...env }, |
| 510 | }); |
| 511 | if (!npmPath) return null; |
| 512 | const outdated = yield* runProbe( |
| 513 | npmPath, |
| 514 | ["outdated", "-g", "--prefix", npmPrefix, "--json", packageName], |
| 515 | env, |
| 516 | // npm outdated exits 1 when updates are available. |
| 517 | [0, 1], |
| 518 | ); |
| 519 | const outdatedEntries = outdated ? Option.getOrUndefined(decodeOutdated(outdated)) : undefined; |
| 520 | // npm prints failures such as an unreachable registry as `{"error": ...}`, also exiting 1. |
| 521 | if (!outdatedEntries || "error" in outdatedEntries) return null; |
| 522 | const latest = nonEmptyString(outdatedEntries[packageName]?.latest); |
| 523 | if (latest) return latest; |
| 524 | // An empty result means the installed version is still the eligible release. |
| 525 | const listed = yield* runProbe( |
| 526 | npmPath, |
| 527 | ["ls", "-g", "--prefix", npmPrefix, "--depth", "0", "--json", packageName], |
| 528 | env, |
| 529 | // npm ls still prints the tree but exits 1 when other globals have problems. |
| 530 | [0, 1], |
| 531 | ); |
| 532 | const listedEntries = listed ? Option.getOrUndefined(decodeNpmList(listed)) : undefined; |
| 533 | return nonEmptyString(listedEntries?.dependencies?.[packageName]?.version); |
| 534 | }); |
| 535 | |
| 536 | // npm names the tarball `${name}-${version}.tgz`, dropping a scope's `@` and its `/`. |
| 537 | function parseNpmPackVersion(stdout: string, packageName: string): string | null { |
| 538 | const prefix = `${packageName.replace(/^@/, "").replace("/", "-")}-`; |
| 539 | const filename = stdout.trim(); |
| 540 | if (!filename.startsWith(prefix) || !filename.endsWith(".tgz")) return null; |
| 541 | const version = filename.slice(prefix.length, -".tgz".length); |
| 542 | return version && !/\s/.test(version) ? version : null; |
| 543 | } |
| 544 | |
| 545 | const decodeVitePlusCurrentEnv = Schema.decodeUnknownOption( |
| 546 | Schema.fromJsonString( |
| 547 | Schema.Struct({ |
| 548 | node: Schema.Struct({ |
| 549 | source: Schema.String, |
| 550 | bin_path: Schema.String, |
| 551 | installed: Schema.Boolean, |
| 552 | }), |
| 553 | }), |
| 554 | ), |
| 555 | ); |
| 556 | |
| 557 | // `vp i -g` installs through the npm beside Vite+'s managed Node, even under `vp env off`, and |
| 558 | // `vp env current` names that Node unless it reports a system one, which install does not use. |
| 559 | // Pack honours npm's min-release-age and `before`, which `npm view` ignores, and resolves |
| 560 | // `@latest` the way install does. `--json=false` keeps its output to the tarball name. |
| 561 | const resolveVitePlusInstallableLatestVersion = Effect.fn( |
| 562 | "resolveVitePlusInstallableLatestVersion", |
| 563 | )(function* (packageName: string, env: NodeJS.ProcessEnv, platform: NodeJS.Platform) { |
| 564 | const path = yield* Path.Path; |
| 565 | const current = yield* runProbe("vp", ["env", "current", "--json"], env); |
| 566 | const node = current ? Option.getOrUndefined(decodeVitePlusCurrentEnv(current))?.node : undefined; |
| 567 | if (!node?.installed || node.source === "system PATH" || !path.isAbsolute(node.bin_path)) { |
| 568 | return null; |
| 569 | } |
| 570 | const npmPath = path.join(path.dirname(node.bin_path), platform === "win32" ? "npm.cmd" : "npm"); |
| 571 | const packed = yield* runProbe( |
| 572 | npmPath, |
| 573 | ["pack", "--dry-run", "--json=false", "--global", `${packageName}@latest`], |
| 574 | env, |
| 575 | ); |
| 576 | return packed ? parseNpmPackVersion(packed, packageName) : null; |
| 577 | }); |
| 578 | |
| 579 | // `bun outdated` has no JSON output; its `Latest` column is what `@latest` installs |
| 580 | // under minimumReleaseAge (marked `*`). `Update` is only the global package.json range. |
| 581 | function parseBunOutdatedLatestVersion(output: string, packageName: string): string | null { |
| 582 | for (const line of output.split("\n")) { |
| 583 | const cells = line.split("|").map((cell) => cell.trim()); |
| 584 | if (cells.length === 6 && cells[1] === packageName) { |
| 585 | return nonEmptyString(cells[4]?.replace(/ \*$/, "")); |
| 586 | } |
| 587 | } |
| 588 | return null; |
| 589 | } |
| 590 | |
| 591 | // bun rejects an exact pin to a release inside minimumReleaseAge, so the update stays `@latest`. |
| 592 | const resolveBunGlobalLatestVersion = Effect.fn("resolveBunGlobalLatestVersion")(function* ( |
| 593 | packageName: string, |
| 594 | env: NodeJS.ProcessEnv, |
| 595 | ) { |
| 596 | // Match the updater's bun and environment. |
| 597 | const bunPath = yield* resolveCommandPath("bun", { |
| 598 | env: { ...(yield* HostProcess.Environment), ...env }, |
| 599 | }); |
| 600 | if (!bunPath) return null; |
| 601 | // FORCE_COLOR=1 draws the table with box characters and splits versions with ANSI codes. |
| 602 | const outdated = yield* runProbe(bunPath, ["outdated", "-g", packageName], { |
| 603 | ...env, |
| 604 | FORCE_COLOR: "0", |
| 605 | }); |
| 606 | // A missing row reads the same whether bun is current or its registry failed, so npm decides. |
| 607 | return outdated ? parseBunOutdatedLatestVersion(outdated, packageName) : null; |
| 608 | }); |
| 609 | |
| 610 | const MiseInstall = Schema.Struct({ |
| 611 | install_path: Schema.String, |
| 612 | requested_version: Schema.optional(Schema.NullOr(Schema.String)), |
| 613 | active: Schema.optional(Schema.Boolean), |
| 614 | }); |
| 615 | const decodeMiseToolInstalls = Schema.decodeUnknownOption( |
| 616 | Schema.fromJsonString(Schema.Array(MiseInstall)), |
| 617 | ); |
| 618 | const decodeMiseInstalls = Schema.decodeUnknownOption( |
| 619 | Schema.fromJsonString(Schema.Record(Schema.String, Schema.Array(MiseInstall))), |
| 620 | ); |
| 621 | |
| 622 | /** The installs `mise ls --json --installed <tool>` lists, refusing any other tool's. */ |
| 623 | function miseToolInstalls( |
| 624 | listing: string, |
| 625 | miseTool: string, |
| 626 | ): ReadonlyArray<typeof MiseInstall.Type> { |
| 627 | const installs = decodeMiseToolInstalls(listing); |
| 628 | if (Option.isSome(installs)) return installs.value; |
| 629 | const byTool = Option.getOrUndefined(decodeMiseInstalls(listing)); |
| 630 | return byTool && Object.keys(byTool).every((tool) => tool === miseTool) |
| 631 | ? (byTool[miseTool] ?? []) |
| 632 | : []; |
| 633 | } |
| 634 | |
| 635 | /** |
| 636 | * Null when mise does not own the executable. Upgrades need an active `latest` install of the |
| 637 | * driver's fixed mise tool, launched through a shim or the `latest` link `mise upgrade` moves; |
| 638 | * a fixed version's path would keep running the pruned binary, so it stays manual-only. |
| 639 | */ |
| 640 | export const resolveMiseProviderMaintenance = Effect.fn("resolveMiseProviderMaintenance")( |
| 641 | function* ( |
| 642 | owner: { readonly provider: ProviderDriverKind; readonly packageName: string | null }, |
| 643 | mise: MiseProviderTool | undefined, |
| 644 | context: ProviderMaintenanceResolutionContext, |
| 645 | ) { |
| 646 | const commandPaths = [context.resolvedCommandPath, context.realCommandPath]; |
| 647 | const isShim = isMiseExecutablePath(context.realCommandPath); |
| 648 | const looksMise = |
| 649 | isShim || |
| 650 | commandPaths.some((commandPath) => isMiseCommandPath(commandPath, context.env)) || |
| 651 | (yield* isMiseWrapperScript(context)); |
| 652 | const manual = (installPath: string) => |
| 653 | makeManualOnlyProviderMaintenanceCapabilities({ ...owner, installPath }); |
| 654 | const notOwned = (installPath: string) => (looksMise ? manual(installPath) : null); |
| 655 | const commandName = normalizeCommandPath(context.resolvedCommandPath) |
| 656 | .split("/") |
| 657 | .at(-1) |
| 658 | ?.replace(/\.(?:exe|cmd|bat|ps1)$/, ""); |
| 659 | if (!mise) return notOwned(context.realCommandPath); |
| 660 | const miseTool = mise.tool; |
| 661 | // A shim runs whatever mise resolves for its own name, which must be the mapped tool's. |
| 662 | if (isShim && commandName !== miseTool) return manual(context.realCommandPath); |
| 663 | |
| 664 | const fileSystem = yield* FileSystem.FileSystem; |
| 665 | const realPath = (target: string) => |
| 666 | fileSystem.realPath(target).pipe(Effect.orElseSucceed(() => target)); |
| 667 | const misePath = |
| 668 | (yield* resolveCommandPath("mise", { env: context.env })) ?? |
| 669 | (isShim ? context.realCommandPath : null); |
| 670 | if (!misePath) return notOwned(context.realCommandPath); |
| 671 | // Asked even off mise's usual paths, since `MISE_DATA_DIR` can put installs anywhere. |
| 672 | const which = nonEmptyString(yield* runProbe(misePath, ["which", miseTool], context.env)); |
| 673 | const resolvedPath = which ? yield* realPath(which) : null; |
| 674 | // Through a shim T3 Code runs whatever mise resolves; otherwise the configured binary. |
| 675 | const binaryPath = isShim ? resolvedPath : context.realCommandPath; |
| 676 | if (!binaryPath) return manual(context.realCommandPath); |
| 677 | const binary = normalizeCommandPath(binaryPath); |
| 678 | const runsBinary = resolvedPath !== null && normalizeCommandPath(resolvedPath) === binary; |
| 679 | const listing = yield* runProbe( |
| 680 | misePath, |
| 681 | ["ls", "--json", "--installed", miseTool], |
| 682 | context.env, |
| 683 | ); |
| 684 | if (!listing) return runsBinary ? manual(binaryPath) : notOwned(binaryPath); |
| 685 | const isUnder = (path: string, dir: string) => |
| 686 | path.startsWith(`${normalizeCommandPath(dir).replace(/\/+$/, "")}/`); |
| 687 | // An inactive or shadowed install is still mise's, even when `mise which` resolves another. |
| 688 | const owning = yield* Effect.filter(miseToolInstalls(listing, miseTool), (install) => |
| 689 | realPath(install.install_path).pipe( |
| 690 | Effect.map((installPath) => isUnder(binary, installPath)), |
| 691 | ), |
| 692 | ); |
| 693 | // `mise which` also resolves binaries from other tools, such as npm globals under mise's Node. |
| 694 | if (owning.length === 0) return notOwned(binaryPath); |
| 695 | if (!runsBinary) return manual(binaryPath); |
| 696 | const install = owning.find( |
| 697 | (candidate) => candidate.active === true && candidate.requested_version === "latest", |
| 698 | ); |
| 699 | if (!install || mise.upgrade === false) return manual(binaryPath); |
| 700 | if (!isShim) { |
| 701 | // Keep the path's case: `realPath` needs it on case-sensitive filesystems. |
| 702 | const toolDir = install.install_path |
| 703 | .replaceAll("\\", "/") |
| 704 | .replace(/\/+$/, "") |
| 705 | .replace(/\/[^/]+$/, ""); |
| 706 | const latestDirs = [toolDir, yield* realPath(toolDir)].map((dir) => `${dir}/latest`); |
| 707 | const resolved = normalizeCommandPath(context.resolvedCommandPath); |
| 708 | if (!latestDirs.some((dir) => isUnder(resolved, dir))) return manual(binaryPath); |
| 709 | } |
| 710 | // `mise upgrade <short name>` skips a tool configured by its backend name, like `npm:<pkg>`. |
| 711 | const configured = Option.getOrUndefined( |
| 712 | decodeMiseInstalls(yield* runProbe(misePath, ["ls", "--json", "--installed"], context.env)), |
| 713 | ); |
| 714 | const configuredTool = |
| 715 | Object.entries(configured ?? {}).find(([, installs]) => |
| 716 | installs.some((candidate) => candidate.install_path === install.install_path), |
| 717 | )?.[0] ?? miseTool; |
| 718 | const args = ["upgrade", configuredTool]; |
| 719 | const services = yield* Effect.context<ProviderMaintenanceResolverServices>(); |
| 720 | const capabilities = makeProviderMaintenanceCapabilities({ |
| 721 | ...owner, |
| 722 | updateExecutable: misePath, |
| 723 | updateArgs: args, |
| 724 | updateLockKey: "mise", |
| 725 | updateCommand: ["mise", ...args].join(" "), |
| 726 | platform: context.platform, |
| 727 | // Mise read its config from this environment, so the upgrade runs in it too. |
| 728 | env: context.env, |
| 729 | // Settings such as `minimum_release_age` can hold mise behind the registry, |
| 730 | // so only mise can say what it installs. It may go to the network, so ask lazily. |
| 731 | latestVersion: null, |
| 732 | lookupLatestVersion: runProbe(misePath, ["latest", miseTool], context.env).pipe( |
| 733 | Effect.map((latest) => { |
| 734 | const version = nonEmptyString(latest); |
| 735 | return version && /^\S+$/.test(version) ? version : null; |
| 736 | }), |
| 737 | Effect.provideContext(services), |
| 738 | ), |
| 739 | }); |
| 740 | return { |
| 741 | ...capabilities, |
| 742 | latestVersionCacheKey: ["mise", misePath, miseTool, environmentCacheKey(context.env)].join( |
| 743 | "\0", |
| 744 | ), |
| 745 | }; |
| 746 | }, |
| 747 | ); |
| 748 | |
| 749 | const decodeVitePlusConfig = Schema.decodeUnknownOption( |
| 750 | Schema.fromJsonString(Schema.Struct({ shimMode: Schema.optional(Schema.Unknown) })), |
| 751 | ); |
| 752 | |
| 753 | /** With `shimMode: "system_first"` (`vp env off`), a Vite+ shim runs the next same-named command on PATH. */ |
| 754 | const followVitePlusSystemFirstShim = Effect.fn("followVitePlusSystemFirstShim")(function* ( |
| 755 | context: ProviderMaintenanceResolutionContext, |
| 756 | ) { |
| 757 | if (!isVitePlusGlobalCommandPath(context.resolvedCommandPath)) return context; |
| 758 | const fileSystem = yield* FileSystem.FileSystem; |
| 759 | const path = yield* Path.Path; |
| 760 | const shimDir = path.dirname(context.resolvedCommandPath); |
| 761 | const dataDir = path.dirname(shimDir); |
| 762 | // Without VP_HOME, the XDG layout keeps shims in `~/.local/share/vite-plus` and config in `$XDG_CONFIG_HOME/vite-plus`. |
| 763 | const home = context.env.VP_HOME |
| 764 | ? undefined |
| 765 | : /^(.*)\/\.local\/share\/vite-plus$/.exec(dataDir.replaceAll("\\", "/"))?.[1]; |
| 766 | const configPaths = [ |
| 767 | ...(home !== undefined |
| 768 | ? [path.join(context.env.XDG_CONFIG_HOME || path.join(home, ".config"), "vite-plus")] |
| 769 | : []), |
| 770 | dataDir, |
| 771 | ].map((dir) => path.join(dir, "config.json")); |
| 772 | const config = yield* Effect.firstSuccessOf( |
| 773 | configPaths.map((configPath) => fileSystem.readFileString(configPath)), |
| 774 | ).pipe(Effect.orElseSucceed(() => "")); |
| 775 | if (Option.getOrUndefined(decodeVitePlusConfig(config))?.shimMode !== "system_first") { |
| 776 | return context; |
| 777 | } |
| 778 | const delimiter = context.platform === "win32" ? ";" : ":"; |
| 779 | const dirKey = (dir: string) => normalizeCommandPath(dir).replace(/\/+$/, ""); |
| 780 | const shimDirKey = dirKey(shimDir); |
| 781 | const env = Object.fromEntries( |
| 782 | Object.entries(context.env).map(([name, value]) => [ |
| 783 | name, |
| 784 | name.toLowerCase() === "path" && value |
| 785 | ? value |
| 786 | .split(delimiter) |
| 787 | .filter((entry) => dirKey(entry) !== shimDirKey) |
| 788 | .join(delimiter) |
| 789 | : value, |
| 790 | ]), |
| 791 | ); |
| 792 | const command = path.basename(context.resolvedCommandPath).replace(/\.(?:exe|cmd|bat|ps1)$/i, ""); |
| 793 | const resolvedCommandPath = yield* resolveCommandPath(command, { env }); |
| 794 | if (!resolvedCommandPath) return context; |
| 795 | const realCommandPath = yield* fileSystem |
| 796 | .realPath(resolvedCommandPath) |
| 797 | .pipe(Effect.orElseSucceed(() => resolvedCommandPath)); |
| 798 | return { ...context, resolvedCommandPath, realCommandPath }; |
| 799 | }); |
| 800 | |
| 801 | export const resolvePackageManagedProviderMaintenance = Effect.fn( |
| 802 | "resolvePackageManagedProviderMaintenance", |
| 803 | )(function* ( |
| 804 | definition: PackageManagedProviderMaintenanceDefinition, |
| 805 | configuredContext: ProviderMaintenanceResolutionContext | null, |
| 806 | ) { |
| 807 | if (!configuredContext) { |
| 808 | return makeManualOnlyProviderMaintenanceCapabilities({ |
| 809 | provider: definition.provider, |
| 810 | packageName: definition.npmPackageName, |
| 811 | }); |
| 812 | } |
| 813 | const context = yield* followVitePlusSystemFirstShim(configuredContext); |
| 814 | const manual = makeManualOnlyProviderMaintenanceCapabilities({ |
| 815 | provider: definition.provider, |
| 816 | packageName: definition.npmPackageName, |
| 817 | installPath: context.realCommandPath, |
| 818 | }); |
| 819 | const commandPaths = [context.resolvedCommandPath, context.realCommandPath]; |
| 820 | const packageName = definition.npmPackageName; |
| 821 | // WinGet-managed claude update exits 0 without updating; T3 does not run winget upgrade. |
| 822 | if ( |
| 823 | definition.provider === "claudeAgent" && |
| 824 | context.platform === "win32" && |
| 825 | commandPaths.some(isWinGetClaudeCommandPath) |
| 826 | ) { |
| 827 | return manual; |
| 828 | } |
| 829 | // Chocolatey's package directory is writable only by administrators, so an |
| 830 | // unelevated server cannot run `choco upgrade`; `claude update` through the |
| 831 | // shim installs a native copy elsewhere and leaves the shim's version alone. |
| 832 | if ( |
| 833 | definition.provider === "claudeAgent" && |
| 834 | context.platform === "win32" && |
| 835 | commandPaths.some((commandPath) => isChocolateyClaudeCommandPath(commandPath, context.env)) |
| 836 | ) { |
| 837 | const services = yield* Effect.context<ProviderMaintenanceResolverServices>(); |
| 838 | return makeManualOnlyProviderMaintenanceCapabilities({ |
| 839 | provider: definition.provider, |
| 840 | packageName, |
| 841 | installPath: context.realCommandPath, |
| 842 | manualCommand: "choco upgrade claude-code", |
| 843 | lookupLatestVersion: runProbe( |
| 844 | "choco", |
| 845 | ["search", CHOCOLATEY_CLAUDE_PACKAGE_ID, "--exact", "--limit-output"], |
| 846 | context.env, |
| 847 | ).pipe( |
| 848 | Effect.map((output) => |
| 849 | output ? parseChocolateyLatestVersion(output, CHOCOLATEY_CLAUDE_PACKAGE_ID) : null, |
| 850 | ), |
| 851 | Effect.provideContext(services), |
| 852 | ), |
| 853 | }); |
| 854 | } |
| 855 | |
| 856 | const mise = yield* resolveMiseProviderMaintenance( |
| 857 | { provider: definition.provider, packageName }, |
| 858 | definition.mise, |
| 859 | context, |
| 860 | ); |
| 861 | if (mise) return mise; |
| 862 | // After mise: a shim of a Nix-installed mise resolves into the store, yet its installs are writable. |
| 863 | if (commandPaths.some(isNixStoreCommandPath)) { |
| 864 | return manual; |
| 865 | } |
| 866 | const macPortsName = yield* resolveMacPortsOwner(context); |
| 867 | if (macPortsName !== null) { |
| 868 | return makeManualOnlyProviderMaintenanceCapabilities({ |
| 869 | provider: definition.provider, |
| 870 | packageName, |
| 871 | installPath: context.realCommandPath, |
| 872 | ...(macPortsName ? { manualCommand: `sudo port upgrade ${macPortsName}` } : {}), |
| 873 | }); |
| 874 | } |
| 875 | |
| 876 | const nativeUpdate = definition.nativeUpdate; |
| 877 | const nativeEnv = nativeUpdate?.env; |
| 878 | const native = nativeUpdate |
| 879 | ? makeProviderMaintenanceCapabilities({ |
| 880 | provider: definition.provider, |
| 881 | packageName, |
| 882 | updateExecutable: context.resolvedCommandPath, |
| 883 | updateArgs: nativeUpdate.args, |
| 884 | updateLockKey: `${definition.provider}-native`, |
| 885 | platform: context.platform, |
| 886 | ...(nativeEnv |
| 887 | ? { env: typeof nativeEnv === "function" ? nativeEnv(context) : nativeEnv } |
| 888 | : {}), |
| 889 | }) |
| 890 | : manual; |
| 891 | // A native-looking launcher can still delegate to an npm-owned install. |
| 892 | if ( |
| 893 | nativeUpdate?.isCommandPath && |
| 894 | commandPaths.some(nativeUpdate.isCommandPath) && |
| 895 | !npmGlobalPrefixFromCommandPath(context.realCommandPath, packageName) |
| 896 | ) { |
| 897 | return native; |
| 898 | } |
| 899 | // A `node_modules` path not proven below belongs to another package or a |
| 900 | // project, so the provider's own updater could act on the wrong install. |
| 901 | const fallback = |
| 902 | nativeUpdate?.requiresCommandPath || |
| 903 | commandPaths.some((commandPath) => normalizeCommandPath(commandPath).includes("/node_modules/")) |
| 904 | ? manual |
| 905 | : native; |
| 906 | if (commandPaths.some(isVitePlusGlobalCommandPath)) { |
| 907 | const services = yield* Effect.context<ProviderMaintenanceResolverServices>(); |
| 908 | const capabilities = makeProviderMaintenanceCapabilities({ |
| 909 | provider: definition.provider, |
| 910 | packageName, |
| 911 | updateExecutable: "vp", |
| 912 | updateArgs: ["i", "-g", packageName], |
| 913 | updateLockKey: "vite-plus-global", |
| 914 | env: context.env, |
| 915 | lookupLatestVersion: resolveVitePlusInstallableLatestVersion( |
| 916 | packageName, |
| 917 | context.env, |
| 918 | context.platform, |
| 919 | ).pipe(Effect.provideContext(services)), |
| 920 | }); |
| 921 | return { |
| 922 | ...capabilities, |
| 923 | latestVersionCacheKey: [ |
| 924 | "vite-plus-global", |
| 925 | packageName, |
| 926 | environmentCacheKey(context.env), |
| 927 | ].join("\0"), |
| 928 | }; |
| 929 | } |
| 930 | if (commandPaths.some(isBunGlobalCommandPath)) { |
| 931 | const services = yield* Effect.context<ProviderMaintenanceResolverServices>(); |
| 932 | return makeProviderMaintenanceCapabilities({ |
| 933 | provider: definition.provider, |
| 934 | packageName, |
| 935 | updateExecutable: "bun", |
| 936 | updateArgs: ["i", "-g", `${packageName}@latest`], |
| 937 | updateLockKey: "bun-global", |
| 938 | env: context.env, |
| 939 | lookupLatestVersion: resolveBunGlobalLatestVersion(packageName, context.env).pipe( |
| 940 | Effect.provideContext(services), |
| 941 | ), |
| 942 | }); |
| 943 | } |
| 944 | if (commandPaths.some(isPnpmGlobalCommandPath)) { |
| 945 | // pnpm 10 skips unapproved scripts; the approval flag requires 10.4+. |
| 946 | const pnpmVersion = yield* runProbe("pnpm", ["--version"], context.env); |
| 947 | const allowBuild = |
| 948 | pnpmVersion !== null && satisfiesSemverRange(pnpmVersion, ">=10.4.0") |
| 949 | ? [`--allow-build=${packageName}`] |
| 950 | : []; |
| 951 | const services = yield* Effect.context<ProviderMaintenanceResolverServices>(); |
| 952 | return makeProviderMaintenanceCapabilities({ |
| 953 | provider: definition.provider, |
| 954 | packageName, |
| 955 | updateExecutable: "pnpm", |
| 956 | updateArgs: ["add", "-g", ...allowBuild, `${packageName}@latest`], |
| 957 | updateLockKey: "pnpm-global", |
| 958 | env: context.env, |
| 959 | lookupLatestVersion: resolvePnpmGlobalLatestVersion(packageName, context.env).pipe( |
| 960 | Effect.provideContext(services), |
| 961 | ), |
| 962 | }); |
| 963 | } |
| 964 | |
| 965 | if (commandPaths.some(isYarnGlobalCommandPath)) { |
| 966 | return makeProviderMaintenanceCapabilities({ |
| 967 | provider: definition.provider, |
| 968 | packageName, |
| 969 | updateExecutable: "yarn", |
| 970 | updateArgs: ["global", "add", `${packageName}@latest`], |
| 971 | updateLockKey: "yarn-global", |
| 972 | env: context.env, |
| 973 | }); |
| 974 | } |
| 975 | if (yield* isVoltaPackageInstall(context, packageName)) { |
| 976 | return makeProviderMaintenanceCapabilities({ |
| 977 | provider: definition.provider, |
| 978 | packageName, |
| 979 | updateExecutable: "volta", |
| 980 | updateArgs: ["install", `${packageName}@latest`], |
| 981 | updateLockKey: "volta", |
| 982 | env: context.env, |
| 983 | }); |
| 984 | } |
| 985 | |
| 986 | // npm proof outranks a containing Homebrew keg; Homebrew Node globals still belong to npm. |
| 987 | const npmPrefix = yield* resolveNpmGlobalPrefix(context, packageName); |
| 988 | if (npmPrefix) { |
| 989 | const services = yield* Effect.context<ProviderMaintenanceResolverServices>(); |
| 990 | // npm 12 requires script approval to install native binaries; older npm only warns about the flag. |
| 991 | const capabilities = makeProviderMaintenanceCapabilities({ |
| 992 | provider: definition.provider, |
| 993 | packageName, |
| 994 | updateExecutable: "npm", |
| 995 | updateArgs: [ |
| 996 | "install", |
| 997 | "-g", |
| 998 | "--prefix", |
| 999 | npmPrefix, |
| 1000 | `--allow-scripts=${packageName}`, |
| 1001 | `${packageName}@latest`, |
| 1002 | ], |
| 1003 | updateLockKey: `npm-global:${normalizeCommandPath(npmPrefix)}`, |
| 1004 | env: context.env, |
| 1005 | // Inside min-release-age `@latest` installs an older release than the |
| 1006 | // registry's tag, so only npm's own answer is worth advertising. |
| 1007 | latestVersion: null, |
| 1008 | lookupLatestVersion: resolveNpmGlobalLatestVersion(packageName, npmPrefix, context.env).pipe( |
| 1009 | Effect.provideContext(services), |
| 1010 | ), |
| 1011 | }); |
| 1012 | return { |
| 1013 | ...capabilities, |
| 1014 | latestVersionCacheKey: [ |
| 1015 | "npm-global", |
| 1016 | normalizeCommandPath(npmPrefix), |
| 1017 | packageName, |
| 1018 | environmentCacheKey(context.env), |
| 1019 | ].join("\0"), |
| 1020 | }; |
| 1021 | } |
| 1022 | |
| 1023 | const homebrew = homebrewOwnershipFromCommandPath(context.realCommandPath); |
| 1024 | if (homebrew) { |
| 1025 | return ( |
| 1026 | (yield* resolveHomebrewProviderMaintenance( |
| 1027 | { provider: definition.provider, packageName }, |
| 1028 | homebrew, |
| 1029 | context, |
| 1030 | )) ?? fallback |
| 1031 | ); |
| 1032 | } |
| 1033 | |
| 1034 | return fallback; |
| 1035 | }); |
| 1036 | |
| 1037 | /** |
| 1038 | * `brew upgrade` capabilities once the keg's prefix is confirmed by a `brew` |
| 1039 | * that reports it as its own. Version checks defer `brew info` until needed. |
| 1040 | * Null when no `brew` is found or it owns another prefix. |
| 1041 | */ |
| 1042 | export const resolveHomebrewProviderMaintenance = Effect.fn("resolveHomebrewProviderMaintenance")( |
| 1043 | function* ( |
| 1044 | input: { readonly provider: ProviderDriverKind; readonly packageName: string | null }, |
| 1045 | homebrew: HomebrewOwnership, |
| 1046 | context: ProviderMaintenanceResolutionContext, |
| 1047 | ) { |
| 1048 | const fileSystem = yield* FileSystem.FileSystem; |
| 1049 | const path = yield* Path.Path; |
| 1050 | // GUI servers may lack Homebrew on PATH; use the keg brew with the same prefix check. |
| 1051 | const kegBrewPath = path.join(homebrew.prefix, "bin", "brew"); |
| 1052 | const brewPath = (yield* fileSystem.exists(kegBrewPath).pipe(Effect.orElseSucceed(() => false))) |
| 1053 | ? kegBrewPath |
| 1054 | : yield* resolveCommandPath("brew", { env: context.env }); |
| 1055 | if (!brewPath) { |
| 1056 | return null; |
| 1057 | } |
| 1058 | const brewPrefix = nonEmptyString(yield* runProbe(brewPath, ["--prefix"], context.env)); |
| 1059 | const realBrewPrefix = brewPrefix |
| 1060 | ? yield* fileSystem.realPath(brewPrefix).pipe(Effect.orElseSucceed(() => brewPrefix)) |
| 1061 | : null; |
| 1062 | if ( |
| 1063 | !realBrewPrefix || |
| 1064 | normalizeCommandPath(realBrewPrefix) !== normalizeCommandPath(homebrew.prefix) |
| 1065 | ) { |
| 1066 | return null; |
| 1067 | } |
| 1068 | const args = |
| 1069 | homebrew.kind === "cask" ? ["upgrade", "--cask", homebrew.name] : ["upgrade", homebrew.name]; |
| 1070 | const services = yield* Effect.context<ProviderMaintenanceResolverServices>(); |
| 1071 | return makeProviderMaintenanceCapabilities({ |
| 1072 | provider: input.provider, |
| 1073 | packageName: input.packageName, |
| 1074 | updateExecutable: brewPath, |
| 1075 | updateArgs: args, |
| 1076 | updateLockKey: "homebrew", |
| 1077 | updateCommand: ["brew", ...args].join(" "), |
| 1078 | // Brew's release can lag npm; only its own channel can say what upgrade installs. |
| 1079 | latestVersion: null, |
| 1080 | lookupLatestVersion: runProbe( |
| 1081 | brewPath, |
| 1082 | ["info", "--json=v2", homebrew.name], |
| 1083 | context.env, |
| 1084 | ).pipe( |
| 1085 | Effect.map((info) => (info ? parseHomebrewLatestVersion(info, homebrew) : null)), |
| 1086 | Effect.provideContext(services), |
| 1087 | ), |
| 1088 | }); |
| 1089 | }, |
| 1090 | ); |
| 1091 | |
| 1092 | /** The command's text when it is small enough to be a wrapper script, else "". */ |
| 1093 | const readWrapperScript = Effect.fn("readWrapperScript")(function* (commandPath: string) { |
| 1094 | const fileSystem = yield* FileSystem.FileSystem; |
| 1095 | const size = yield* fileSystem.stat(commandPath).pipe( |
| 1096 | Effect.map((info) => Number(info.size)), |
| 1097 | Effect.orElseSucceed(() => Infinity), |
| 1098 | ); |
| 1099 | if (size > WRAPPER_SCRIPT_MAX_BYTES) return ""; |
| 1100 | return yield* fileSystem.readFileString(commandPath).pipe(Effect.orElseSucceed(() => "")); |
| 1101 | }); |
| 1102 | |
| 1103 | const isMiseWrapperScript = Effect.fn("isMiseWrapperScript")(function* ( |
| 1104 | context: ProviderMaintenanceResolutionContext, |
| 1105 | ) { |
| 1106 | const script = yield* readWrapperScript(context.realCommandPath); |
| 1107 | return script.startsWith("#!") && /\bmise\s+(?:x|exec)\b/.test(script); |
| 1108 | }); |
| 1109 | |
| 1110 | /** |
| 1111 | * The port that installed the executable, "" when MacPorts owns it under an unusable name, |
| 1112 | * or null when it does not. MacPorts prefixes are root-owned and its Claude port disables |
| 1113 | * `claude update`, so neither npm nor the native updater can upgrade these installs. |
| 1114 | */ |
| 1115 | export const resolveMacPortsOwner = Effect.fn("resolveMacPortsOwner")(function* ( |
| 1116 | context: ProviderMaintenanceResolutionContext, |
| 1117 | ) { |
| 1118 | if (context.platform === "win32") return null; |
| 1119 | const fileSystem = yield* FileSystem.FileSystem; |
| 1120 | const path = yield* Path.Path; |
| 1121 | const siblingPort = path.join(path.dirname(context.resolvedCommandPath), "port"); |
| 1122 | const portPath = (yield* fileSystem.exists(siblingPort).pipe(Effect.orElseSucceed(() => false))) |
| 1123 | ? siblingPort |
| 1124 | : yield* resolveCommandPath("port", { env: context.env }); |
| 1125 | if (!portPath) return null; |
| 1126 | const prefix = `${normalizeCommandPath(path.dirname(path.dirname(portPath)))}/`; |
| 1127 | if (!normalizeCommandPath(context.realCommandPath).startsWith(prefix)) return null; |
| 1128 | const output = yield* runProbe(portPath, ["provides", context.realCommandPath], context.env); |
| 1129 | const name = output ? /\bis provided by: (\S+)/.exec(output)?.[1] : undefined; |
| 1130 | if (name === undefined) return null; |
| 1131 | return /^[\w.+-]+$/.test(name) ? name : ""; |
| 1132 | }); |
| 1133 | |
| 1134 | // Volta bin entries only identify its shim; the package image proves ownership. |
| 1135 | // POSIX links point at `volta-shim`; Windows Volta 2 writes `volta run %~n0 %*` scripts. |
| 1136 | const isVoltaPackageInstall = Effect.fn("isVoltaPackageInstall")(function* ( |
| 1137 | context: ProviderMaintenanceResolutionContext, |
| 1138 | packageName: string, |
| 1139 | ) { |
| 1140 | const path = yield* Path.Path; |
| 1141 | const fileSystem = yield* FileSystem.FileSystem; |
| 1142 | const voltaHome = path.dirname(path.dirname(context.resolvedCommandPath)); |
| 1143 | const packageDir = path.join(voltaHome, "tools", "image", "packages", ...packageName.split("/")); |
| 1144 | if (!(yield* fileSystem.exists(packageDir).pipe(Effect.orElseSucceed(() => false)))) { |
| 1145 | return false; |
| 1146 | } |
| 1147 | if (/^volta-shim(?:\.exe)?$/.test(path.basename(normalizeCommandPath(context.realCommandPath)))) { |
| 1148 | return true; |
| 1149 | } |
| 1150 | const script = (yield* readWrapperScript(context.realCommandPath)) |
| 1151 | .replace(/\r\n/g, "\n") |
| 1152 | .replace(/\n$/, ""); |
| 1153 | return ( |
| 1154 | script === "@echo off\nvolta run %~n0 %*" || |
| 1155 | script === '#!/bin/bash\nvolta run "$(basename $0)" "$@"' |
| 1156 | ); |
| 1157 | }); |
| 1158 | |
| 1159 | const resolveNpmGlobalPrefix = Effect.fn("resolveNpmGlobalPrefix")(function* ( |
| 1160 | context: ProviderMaintenanceResolutionContext, |
| 1161 | packageName: string, |
| 1162 | ) { |
| 1163 | const fromRealPath = npmGlobalPrefixFromCommandPath(context.realCommandPath, packageName); |
| 1164 | if (fromRealPath) { |
| 1165 | return fromRealPath; |
| 1166 | } |
| 1167 | if ((yield* HostProcess.Platform) !== "win32") { |
| 1168 | return null; |
| 1169 | } |
| 1170 | const fileSystem = yield* FileSystem.FileSystem; |
| 1171 | const path = yield* Path.Path; |
| 1172 | const shimDir = path.dirname(context.resolvedCommandPath); |
| 1173 | const manifestPath = path.join( |
| 1174 | shimDir, |
| 1175 | "node_modules", |
| 1176 | ...packageName.split("/"), |
| 1177 | "package.json", |
| 1178 | ); |
| 1179 | // Windows npm shims sit beside node_modules; POSIX project checkouts can mimic this layout. |
| 1180 | const hasManifest = yield* fileSystem |
| 1181 | .exists(manifestPath) |
| 1182 | .pipe(Effect.orElseSucceed(() => false)); |
| 1183 | return hasManifest ? shimDir : null; |
| 1184 | }); |
| 1185 | |
| 1186 | export function makePackageManagedProviderMaintenanceResolver( |
| 1187 | definition: PackageManagedProviderMaintenanceDefinition, |
| 1188 | ): ProviderMaintenanceCapabilitiesResolver { |
| 1189 | return { |
| 1190 | resolve: (context) => resolvePackageManagedProviderMaintenance(definition, context), |
| 1191 | }; |
| 1192 | } |
| 1193 | |
| 1194 | function makeManualProviderMaintenanceCapabilities( |
| 1195 | provider: ProviderDriverKind, |
| 1196 | ): ProviderMaintenanceCapabilities { |
| 1197 | return makeManualOnlyProviderMaintenanceCapabilities({ |
| 1198 | provider, |
| 1199 | packageName: null, |
| 1200 | }); |
| 1201 | } |
| 1202 | |
| 1203 | const decodeNpmViewVersion = Schema.decodeUnknownOption( |
| 1204 | Schema.fromJsonString(Schema.Union([Schema.String, Schema.Tuple([Schema.String])])), |
| 1205 | ); |
| 1206 | |
| 1207 | function environmentCacheKey(env: NodeJS.ProcessEnv): string { |
| 1208 | return NodeCrypto.createHash("sha256") |
| 1209 | .update( |
| 1210 | JSON.stringify(Object.entries(env).toSorted(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))), |
| 1211 | ) |
| 1212 | .digest("hex"); |
| 1213 | } |
| 1214 | |
| 1215 | const withConfiguredNpmVersionLookup = Effect.fn("withConfiguredNpmVersionLookup")(function* ( |
| 1216 | capabilities: ProviderMaintenanceCapabilities, |
| 1217 | ) { |
| 1218 | const packageName = capabilities.packageName; |
| 1219 | if (!packageName || capabilities.latestVersion !== undefined) { |
| 1220 | return capabilities; |
| 1221 | } |
| 1222 | const env = { ...(yield* HostProcess.Environment), ...capabilities.update?.env }; |
| 1223 | const npmPath = yield* resolveCommandPath("npm", { env }); |
| 1224 | if (!npmPath) return capabilities; |
| 1225 | const services = yield* Effect.context<ProviderMaintenanceResolverServices>(); |
| 1226 | const lookup = runProbe( |
| 1227 | npmPath, |
| 1228 | ["view", "--global", "--json", `${packageName}@latest`, "version"], |
| 1229 | env, |
| 1230 | ).pipe( |
| 1231 | Effect.map((stdout) => { |
| 1232 | const value = stdout ? Option.getOrNull(decodeNpmViewVersion(stdout.trim())) : null; |
| 1233 | return nonEmptyString(typeof value === "string" ? value : value?.[0]); |
| 1234 | }), |
| 1235 | Effect.tap((version) => |
| 1236 | version === null |
| 1237 | ? Effect.logWarning("Configured npm version lookup failed", { packageName }) |
| 1238 | : Effect.void, |
| 1239 | ), |
| 1240 | Effect.provideContext(services), |
| 1241 | ); |
| 1242 | return { |
| 1243 | ...capabilities, |
| 1244 | // npm owns registry, scoped auth and proxy configuration; failure must not retry public npm. |
| 1245 | latestVersion: null, |
| 1246 | latestVersionCacheKey: [ |
| 1247 | "configured-npm", |
| 1248 | npmPath, |
| 1249 | packageName, |
| 1250 | environmentCacheKey(env), |
| 1251 | installerLatestVersionKey(capabilities) ?? "", |
| 1252 | ].join("\0"), |
| 1253 | lookupLatestVersion: capabilities.lookupLatestVersion |
| 1254 | ? capabilities.lookupLatestVersion.pipe( |
| 1255 | Effect.filterOrElse( |
| 1256 | (version) => version !== null, |
| 1257 | () => lookup, |
| 1258 | ), |
| 1259 | ) |
| 1260 | : lookup, |
| 1261 | }; |
| 1262 | }); |
| 1263 | |
| 1264 | export const resolveProviderMaintenanceCapabilitiesEffect = Effect.fn( |
| 1265 | "resolveProviderMaintenanceCapabilitiesEffect", |
| 1266 | )(function* ( |
| 1267 | resolver: ProviderMaintenanceCapabilitiesResolver, |
| 1268 | options?: { |
| 1269 | readonly binaryPath?: string | null; |
| 1270 | readonly env?: NodeJS.ProcessEnv; |
| 1271 | }, |
| 1272 | ) { |
| 1273 | const binaryPath = nonEmptyString(options?.binaryPath); |
| 1274 | if (!binaryPath) { |
| 1275 | return yield* resolver.resolve(null); |
| 1276 | } |
| 1277 | |
| 1278 | const env = options?.env ?? (yield* readCommandLookupEnv); |
| 1279 | const resolvedCommandPath = yield* resolveCommandPath(binaryPath, { env }); |
| 1280 | if (!resolvedCommandPath) { |
| 1281 | return yield* resolver.resolve(null); |
| 1282 | } |
| 1283 | |
| 1284 | const fileSystem = yield* FileSystem.FileSystem; |
| 1285 | const realCommandPath = yield* fileSystem |
| 1286 | .realPath(resolvedCommandPath) |
| 1287 | .pipe(Effect.orElseSucceed(() => null)); |
| 1288 | if (!realCommandPath) { |
| 1289 | return yield* resolver.resolve(null); |
| 1290 | } |
| 1291 | return yield* resolver.resolve({ |
| 1292 | binaryPath, |
| 1293 | resolvedCommandPath, |
| 1294 | realCommandPath, |
| 1295 | env, |
| 1296 | platform: yield* HostProcess.Platform, |
| 1297 | }); |
| 1298 | }, Effect.flatMap(withConfiguredNpmVersionLookup)); |
| 1299 | |
| 1300 | export const makeCachedProviderMaintenanceResolution = Effect.fn( |
| 1301 | "makeCachedProviderMaintenanceResolution", |
| 1302 | )(function* (resolve: Effect.Effect<ProviderMaintenanceCapabilities>) { |
| 1303 | const cache = yield* Cache.make({ |
| 1304 | capacity: 1, |
| 1305 | timeToLive: MAINTENANCE_CAPABILITIES_CACHE_TTL, |
| 1306 | lookup: () => resolve, |
| 1307 | }); |
| 1308 | const cached = Cache.get(cache, undefined); |
| 1309 | return (options?: { readonly fresh?: boolean }) => |
| 1310 | options?.fresh ? Cache.invalidate(cache, undefined).pipe(Effect.andThen(cached)) : cached; |
| 1311 | }); |
| 1312 | |
| 1313 | function manualUpdateMessage(latestVersion: string, installPath: string | undefined): string { |
| 1314 | return installPath |
| 1315 | ? `Version ${latestVersion} is out. T3 Code runs ${installPath}; update it with the app or tool that installed it.` |
| 1316 | : `Version ${latestVersion} is out. Update it with the app or tool that installed it.`; |
| 1317 | } |
| 1318 | |
| 1319 | function deriveVersionAdvisory(input: { |
| 1320 | readonly currentVersion: string | null; |
| 1321 | readonly latestVersion: string | null; |
| 1322 | readonly capabilities: ProviderMaintenanceCapabilities; |
| 1323 | }): Pick<ServerProviderVersionAdvisory, "status" | "message"> { |
| 1324 | if (!input.currentVersion) { |
| 1325 | return { status: "unknown", message: null }; |
| 1326 | } |
| 1327 | if (!input.latestVersion) { |
| 1328 | return { status: "unknown", message: null }; |
| 1329 | } |
| 1330 | if ( |
| 1331 | (input.capabilities.compareVersions ?? compareSemverVersions)( |
| 1332 | input.currentVersion, |
| 1333 | input.latestVersion, |
| 1334 | ) < 0 |
| 1335 | ) { |
| 1336 | return { |
| 1337 | status: "behind_latest", |
| 1338 | message: |
| 1339 | input.capabilities.update === null |
| 1340 | ? manualUpdateMessage(input.latestVersion, input.capabilities.installPath) |
| 1341 | : PROVIDER_UPDATE_ACTION_TOAST_MESSAGE, |
| 1342 | }; |
| 1343 | } |
| 1344 | return { status: "current", message: null }; |
| 1345 | } |
| 1346 | |
| 1347 | export function createProviderVersionAdvisory(input: { |
| 1348 | readonly driver: ProviderDriverKind; |
| 1349 | readonly currentVersion: string | null; |
| 1350 | readonly latestVersion?: string | null; |
| 1351 | readonly checkedAt?: string | null; |
| 1352 | readonly maintenanceCapabilities?: ProviderMaintenanceCapabilities; |
| 1353 | }): ServerProviderVersionAdvisory { |
| 1354 | const capabilities = |
| 1355 | input.maintenanceCapabilities ?? makeManualProviderMaintenanceCapabilities(input.driver); |
| 1356 | const latestVersion = input.latestVersion ?? null; |
| 1357 | const advisory = deriveVersionAdvisory({ |
| 1358 | currentVersion: input.currentVersion, |
| 1359 | latestVersion, |
| 1360 | capabilities, |
| 1361 | }); |
| 1362 | |
| 1363 | return { |
| 1364 | status: advisory.status, |
| 1365 | currentVersion: input.currentVersion, |
| 1366 | latestVersion, |
| 1367 | updateCommand: |
| 1368 | resolveLatestProviderUpdateAction(capabilities, latestVersion)?.command ?? |
| 1369 | capabilities.manualCommand ?? |
| 1370 | null, |
| 1371 | canUpdate: capabilities.update !== null, |
| 1372 | canInstallVersion: makeTargetedProviderUpdateAction(capabilities, "0.0.0") !== null, |
| 1373 | checkedAt: input.checkedAt ?? null, |
| 1374 | message: advisory.message, |
| 1375 | }; |
| 1376 | } |
| 1377 | |
| 1378 | const fetchNpmLatestVersion = Effect.fn("fetchNpmLatestVersion")(function* (packageName: string) { |
| 1379 | const client = yield* HttpClient.HttpClient; |
| 1380 | const request = HttpClientRequest.get( |
| 1381 | `https://registry.npmjs.org/${encodeURIComponent(packageName)}/latest`, |
| 1382 | ).pipe(HttpClientRequest.setHeader("accept", "application/json")); |
| 1383 | // The deadline covers the body too: headers can arrive before the JSON stalls. |
| 1384 | const payload = yield* client.execute(request).pipe( |
| 1385 | Effect.flatMap(HttpClientResponse.filterStatusOk), |
| 1386 | Effect.flatMap(HttpClientResponse.schemaBodyJson(NpmLatestVersionResponse)), |
| 1387 | Effect.timeoutOption(LATEST_VERSION_TIMEOUT_MS), |
| 1388 | Effect.orElseSucceed(() => Option.none()), |
| 1389 | ); |
| 1390 | return Option.isSome(payload) ? nonEmptyString(payload.value.version) : null; |
| 1391 | }); |
| 1392 | |
| 1393 | /** |
| 1394 | * The installer's own answer is cached apart from the npm registry entry. A |
| 1395 | * manual-only install has no command to key on, so its executable stands in. |
| 1396 | */ |
| 1397 | function installerLatestVersionKey(capabilities: ProviderMaintenanceCapabilities) { |
| 1398 | if (!capabilities.lookupLatestVersion) return null; |
| 1399 | if (capabilities.latestVersionCacheKey) return capabilities.latestVersionCacheKey; |
| 1400 | const update = capabilities.update; |
| 1401 | if (update) return [update.lockKey, update.executable, ...update.args].join("\0"); |
| 1402 | return capabilities.installPath |
| 1403 | ? ["manual", capabilities.installPath].join("\0") |
| 1404 | : capabilities.packageName && `npm-registry\0${capabilities.packageName}`; |
| 1405 | } |
| 1406 | |
| 1407 | export function latestProviderVersionCacheKeys( |
| 1408 | capabilities: ProviderMaintenanceCapabilities, |
| 1409 | ): ReadonlyArray<string> { |
| 1410 | return [capabilities.packageName, installerLatestVersionKey(capabilities)].filter( |
| 1411 | (key) => key !== null, |
| 1412 | ); |
| 1413 | } |
| 1414 | |
| 1415 | export const resolveLatestProviderVersion = Effect.fn("resolveLatestProviderVersion")(function* ( |
| 1416 | maintenanceCapabilities: ProviderMaintenanceCapabilities, |
| 1417 | ) { |
| 1418 | const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions; |
| 1419 | const installerKey = installerLatestVersionKey(maintenanceCapabilities); |
| 1420 | if (installerKey && maintenanceCapabilities.lookupLatestVersion) { |
| 1421 | const installable = yield* latestVersions.cached( |
| 1422 | installerKey, |
| 1423 | maintenanceCapabilities.lookupLatestVersion, |
| 1424 | ); |
| 1425 | if (installable !== null) return installable; |
| 1426 | } |
| 1427 | if (maintenanceCapabilities.latestVersion !== undefined) { |
| 1428 | return maintenanceCapabilities.latestVersion; |
| 1429 | } |
| 1430 | const packageName = maintenanceCapabilities.packageName; |
| 1431 | if (!packageName) { |
| 1432 | return null; |
| 1433 | } |
| 1434 | |
| 1435 | return yield* latestVersions.cached(packageName, fetchNpmLatestVersion(packageName)); |
| 1436 | }); |
| 1437 | |
| 1438 | export const invalidateLatestProviderVersion = Effect.fn("invalidateLatestProviderVersion")( |
| 1439 | function* (maintenanceCapabilities: ProviderMaintenanceCapabilities) { |
| 1440 | const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions; |
| 1441 | yield* Effect.forEach( |
| 1442 | latestProviderVersionCacheKeys(maintenanceCapabilities), |
| 1443 | latestVersions.invalidate, |
| 1444 | { discard: true }, |
| 1445 | ); |
| 1446 | }, |
| 1447 | ); |
| 1448 | |
| 1449 | export const enrichProviderSnapshotWithVersionAdvisory = Effect.fn( |
| 1450 | "enrichProviderSnapshotWithVersionAdvisory", |
| 1451 | )(function* ( |
| 1452 | snapshot: ServerProvider, |
| 1453 | maintenanceCapabilities?: ProviderMaintenanceCapabilities, |
| 1454 | options?: { |
| 1455 | readonly enableProviderUpdateChecks: boolean | undefined; |
| 1456 | }, |
| 1457 | ) { |
| 1458 | const capabilities = |
| 1459 | maintenanceCapabilities ?? makeManualProviderMaintenanceCapabilities(snapshot.driver); |
| 1460 | const currentVersion = |
| 1461 | snapshot.installedVersion !== undefined ? snapshot.installedVersion : snapshot.version; |
| 1462 | const shouldResolveLatestVersion = |
| 1463 | options?.enableProviderUpdateChecks !== false && |
| 1464 | snapshot.enabled && |
| 1465 | snapshot.installed && |
| 1466 | Boolean(currentVersion); |
| 1467 | if (!shouldResolveLatestVersion) { |
| 1468 | return { |
| 1469 | ...snapshot, |
| 1470 | versionAdvisory: createProviderVersionAdvisory({ |
| 1471 | driver: snapshot.driver, |
| 1472 | currentVersion, |
| 1473 | checkedAt: snapshot.checkedAt, |
| 1474 | maintenanceCapabilities: capabilities, |
| 1475 | }), |
| 1476 | }; |
| 1477 | } |
| 1478 | |
| 1479 | const latestVersion = yield* resolveLatestProviderVersion(capabilities); |
| 1480 | return { |
| 1481 | ...snapshot, |
| 1482 | versionAdvisory: createProviderVersionAdvisory({ |
| 1483 | driver: snapshot.driver, |
| 1484 | currentVersion, |
| 1485 | latestVersion, |
| 1486 | checkedAt: DateTime.formatIso(yield* DateTime.now), |
| 1487 | maintenanceCapabilities: capabilities, |
| 1488 | }), |
| 1489 | }; |
| 1490 | }); |