Open History to see the last commit
1import {
2 ProviderDriverKind,
3 type ServerProvider,
4 type ServerProviderVersionAdvisory,
5} from "@t3tools/contracts";
6import { compareSemverVersions } from "@t3tools/shared/semver";
7import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
8import { causeErrorTag } from "@t3tools/shared/observability";
9import { resolveCommandPath } from "@t3tools/shared/shell";
10import * as Config from "effect/Config";
11import * as Context from "effect/Context";
12import * as DateTime from "effect/DateTime";
13import * as Duration from "effect/Duration";
14import * as Effect from "effect/Effect";
15import * as FileSystem from "effect/FileSystem";
16import * as Option from "effect/Option";
17import * as Path from "effect/Path";
18import * as Schema from "effect/Schema";
19import * as Stream from "effect/Stream";
20import { HttpClient, HttpClientRequest } from "effect/unstable/http";
21import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
22
23import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts";
24
25const LATEST_VERSION_CACHE_TTL_MS = 60 * 60 * 1_000;
26const LATEST_VERSION_TIMEOUT_MS = 4_000;
27const HOMEBREW_INFO_TIMEOUT_MS = 10_000;
28const HOMEBREW_INFO_MAX_BYTES = 256 * 1_024;
29const PROVIDER_UPDATE_ACTION_TOAST_MESSAGE = "Install the update now or review provider settings.";
30
31/**
32 * Ownership is re-derived from the executable this often. Installs do not
33 * move on their own, so this mostly bounds how stale a Homebrew "latest" can
34 * get; the npm registry check keeps its own cache.
35 */
36export const MAINTENANCE_CAPABILITIES_CACHE_TTL = Duration.hours(1);
37
38const compactEnv = (input: Record<string, Option.Option<string>>): NodeJS.ProcessEnv =>
39 Object.fromEntries(
40 Object.entries(input).flatMap(([key, value]) =>
41 Option.match(value, {
42 onNone: () => [],
43 onSome: (resolved) => [[key, resolved]],
44 }),
45 ),
46 );
47
48const CommandLookupEnvConfig = Config.all({
49 PATH: Config.string("PATH").pipe(Config.option),
50 Path: Config.string("Path").pipe(Config.option),
51 path: Config.string("path").pipe(Config.option),
52 PATHEXT: Config.string("PATHEXT").pipe(Config.option),
53}).pipe(Config.map(compactEnv));
54
55const readCommandLookupEnv = CommandLookupEnvConfig.pipe(Effect.orElseSucceed(() => ({})));
56
57export interface ProviderMaintenanceCapabilities {
58 readonly provider: ProviderDriverKind;
59 readonly packageName: string | null;
60 readonly update: ProviderMaintenanceCommandAction | null;
61 /**
62 * Latest version reported by the installer that owns the executable.
63 * `undefined` means the installer has no channel of its own and the npm
64 * registry entry for `packageName` is authoritative; `null` means the
65 * installer was asked and did not know.
66 */
67 readonly latestVersion?: string | null;
68}
69
70export interface ProviderMaintenanceCommandAction {
71 readonly command: string;
72 readonly executable: string;
73 readonly args: ReadonlyArray<string>;
74 readonly lockKey: string;
75 /**
76 * Extra environment for the spawned updater, on top of the server's own.
77 * A native updater finds its install through the same variables the
78 * provider runs with (e.g. `CODEX_HOME`), so an instance with a custom home
79 * must update that home and not the default one.
80 */
81 readonly env?: NodeJS.ProcessEnv;
82}
83
84/** Where the provider executable was found; every path is absolute. */
85export interface ProviderMaintenanceResolutionContext {
86 readonly binaryPath: string;
87 readonly resolvedCommandPath: string;
88 readonly realCommandPath: string;
89 readonly env: NodeJS.ProcessEnv;
90 /** Host platform; decides how the copyable command quotes the executable. */
91 readonly platform: NodeJS.Platform;
92}
93
94export type ProviderMaintenanceResolverServices =
95 | FileSystem.FileSystem
96 | Path.Path
97 | ChildProcessSpawner.ChildProcessSpawner;
98
99export interface ProviderMaintenanceCapabilitiesResolver {
100 readonly resolve: (
101 context: ProviderMaintenanceResolutionContext | null,
102 ) => Effect.Effect<ProviderMaintenanceCapabilities, never, ProviderMaintenanceResolverServices>;
103}
104
105export interface PackageManagedProviderMaintenanceDefinition {
106 readonly provider: ProviderDriverKind;
107 readonly npmPackageName: string;
108 readonly nativeUpdate: {
109 readonly args: ReadonlyArray<string>;
110 readonly isCommandPath: (commandPath: string) => boolean;
111 /** Environment the native updater needs to target this instance's install. */
112 readonly env?: NodeJS.ProcessEnv;
113 } | null;
114}
115
116export interface ProviderVersionCacheEntry {
117 readonly expiresAt: number;
118 readonly version: string | null;
119}
120
121export const ProviderVersionCache = Context.Reference<Map<string, ProviderVersionCacheEntry>>(
122 "@t3tools/server/providerMaintenance/ProviderVersionCache",
123 {
124 defaultValue: () => new Map(),
125 },
126);
127const NpmLatestVersionResponse = Schema.Struct({
128 version: Schema.optional(Schema.String),
129});
130
131function nonEmptyString(value: unknown): string | null {
132 return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
133}
134
135/**
136 * The copyable command must paste into a shell as-is, so an executable path
137 * with spaces or quotes is quoted for the host's default shell.
138 */
139function quoteShellWord(word: string, platform: NodeJS.Platform): string {
140 const safeWord = platform === "win32" ? /^[\w./:\\@=-]+$/ : /^[\w./:@=-]+$/;
141 if (safeWord.test(word)) return word;
142 return platform === "win32"
143 ? `'${word.replace(/['\u2018\u2019]/g, "$&$&")}'`
144 : `'${word.replaceAll("'", "'\\''")}'`;
145}
146
147function quoteUpdateExecutable(executable: string, platform: NodeJS.Platform): string {
148 const quoted = quoteShellWord(executable, platform);
149 // Windows terminals default to PowerShell, where a quoted executable needs &.
150 return platform === "win32" && quoted !== executable ? `& ${quoted}` : quoted;
151}
152
153export function makeProviderMaintenanceCapabilities(input: {
154 readonly provider: ProviderDriverKind;
155 readonly packageName: string | null;
156 readonly updateExecutable: string | null;
157 readonly updateArgs: ReadonlyArray<string>;
158 readonly updateLockKey: string | null;
159 /** Shown to the user instead of `<executable> <args>`; use for a bare tool name like `brew`. */
160 readonly updateCommand?: string;
161 readonly platform?: NodeJS.Platform;
162 readonly env?: NodeJS.ProcessEnv;
163 readonly latestVersion?: string | null;
164}): ProviderMaintenanceCapabilities {
165 const platform = input.platform ?? HostProcessPlatform.defaultValue();
166 const update =
167 input.updateExecutable === null || input.updateLockKey === null
168 ? null
169 : {
170 command:
171 input.updateCommand ??
172 [
173 quoteUpdateExecutable(input.updateExecutable, platform),
174 ...input.updateArgs.map((arg) => quoteShellWord(arg, platform)),
175 ].join(" "),
176 executable: input.updateExecutable,
177 args: input.updateArgs,
178 lockKey: input.updateLockKey,
179 ...(input.env ? { env: input.env } : {}),
180 };
181 return {
182 provider: input.provider,
183 packageName: input.packageName,
184 update,
185 ...("latestVersion" in input ? { latestVersion: input.latestVersion } : {}),
186 };
187}
188
189export function makeManualOnlyProviderMaintenanceCapabilities(input: {
190 readonly provider: ProviderDriverKind;
191 readonly packageName: string | null;
192}): ProviderMaintenanceCapabilities {
193 return makeProviderMaintenanceCapabilities({
194 provider: input.provider,
195 packageName: input.packageName,
196 updateExecutable: null,
197 updateArgs: [],
198 updateLockKey: null,
199 });
200}
201
202export function normalizeCommandPath(commandPath: string): string {
203 return commandPath.replaceAll("\\", "/").toLowerCase();
204}
205
206function isVitePlusGlobalCommandPath(commandPath: string): boolean {
207 return normalizeCommandPath(commandPath).includes("/.vite-plus/bin/");
208}
209
210function isBunGlobalCommandPath(commandPath: string): boolean {
211 return normalizeCommandPath(commandPath).includes("/.bun/bin/");
212}
213
214function isPnpmGlobalCommandPath(commandPath: string): boolean {
215 const normalized = normalizeCommandPath(commandPath);
216 return (
217 normalized.includes("/.local/share/pnpm/") ||
218 normalized.includes("/library/pnpm/") ||
219 normalized.includes("/local/share/pnpm/") ||
220 normalized.includes("/appdata/local/pnpm/") ||
221 normalized.includes("/pnpm/global/")
222 );
223}
224
225/**
226 * The npm global prefix that owns a package, derived from the real path of
227 * its entry point: `<prefix>/lib/node_modules/<pkg>/…`. Windows global
228 * installs have no `lib` segment and are proven by the shim instead (see
229 * `resolveNpmGlobalPrefix`). A project-local `node_modules` is not a global
230 * install and yields null.
231 */
232export function npmGlobalPrefixFromCommandPath(
233 realCommandPath: string,
234 packageName: string,
235): string | null {
236 const slashPath = realCommandPath.replaceAll("\\", "/");
237 const normalized = slashPath.toLowerCase();
238 const packageSegment = `/lib/node_modules/${packageName.toLowerCase()}/`;
239 const packageIndex = normalized.lastIndexOf(packageSegment);
240 if (packageIndex < 0 || normalized.slice(0, packageIndex).includes("/node_modules/")) {
241 return null;
242 }
243 // Mise's npm backend uses a global-looking layout inside a tool version.
244 // Globals under its Node installation still belong to npm.
245 const miseTool = /\/mise\/installs\/([^/]+)\/[^/]+$/.exec(normalized.slice(0, packageIndex))?.[1];
246 if (miseTool && miseTool !== "node") {
247 return null;
248 }
249 return packageIndex === 0 ? "/" : slashPath.slice(0, packageIndex);
250}
251
252// `<prefix>/Cellar/<name>/<version>/…` or `<prefix>/Caskroom/<name>/<version>/…`.
253// Homebrew always nests a version directory under the keg.
254const HOMEBREW_KEG_PATTERN = /^(.*)\/(cellar|caskroom)\/([^/]+)\/[^/]+\//i;
255
256export interface HomebrewOwnership {
257 readonly kind: "formula" | "cask";
258 readonly name: string;
259 /** The Homebrew prefix the keg sits under; must match `brew --prefix`. */
260 readonly prefix: string;
261}
262
263/**
264 * Homebrew looks like the owner when the real path runs through a versioned
265 * keg or cask. It is only proven once the prefix matches the `brew` that will
266 * run the upgrade (see `resolvePackageManagedProviderMaintenance`).
267 */
268export function homebrewOwnershipFromCommandPath(
269 realCommandPath: string,
270): HomebrewOwnership | null {
271 const match = HOMEBREW_KEG_PATTERN.exec(realCommandPath.replaceAll("\\", "/"));
272 if (!match) {
273 return null;
274 }
275 return {
276 kind: match[2]!.toLowerCase() === "cellar" ? "formula" : "cask",
277 name: match[3]!,
278 prefix: match[1]!,
279 };
280}
281
282const HomebrewInfoResponse = Schema.Struct({
283 formulae: Schema.optional(
284 Schema.Array(
285 Schema.Struct({
286 versions: Schema.optional(Schema.Struct({ stable: Schema.optional(Schema.String) })),
287 }),
288 ),
289 ),
290 casks: Schema.optional(Schema.Array(Schema.Struct({ version: Schema.optional(Schema.String) }))),
291});
292
293const decodeHomebrewInfo = Schema.decodeUnknownOption(Schema.fromJsonString(HomebrewInfoResponse));
294
295/** Cask versions may carry a build suffix after a comma (`1.2.3,456`). */
296export function parseHomebrewLatestVersion(
297 infoJson: string,
298 ownership: HomebrewOwnership,
299): string | null {
300 const decoded = decodeHomebrewInfo(infoJson);
301 if (Option.isNone(decoded)) {
302 return null;
303 }
304 const raw =
305 ownership.kind === "formula"
306 ? decoded.value.formulae?.[0]?.versions?.stable
307 : decoded.value.casks?.[0]?.version?.split(",", 1)[0];
308 return nonEmptyString(raw);
309}
310
311/** Run `brew <args>` and return stdout, or null on failure, timeout, or oversized output. */
312const runHomebrew = Effect.fn("runHomebrew")(function* (
313 brewPath: string,
314 args: ReadonlyArray<string>,
315 env: NodeJS.ProcessEnv,
316) {
317 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
318 const collect = Effect.gen(function* () {
319 const child = yield* spawner.spawn(ChildProcess.make(brewPath, args, { env, extendEnv: true }));
320 yield* Effect.addFinalizer(() => child.kill().pipe(Effect.ignore));
321 // stderr is drained so a chatty brew cannot block on a full pipe.
322 const [stdout, exitCode] = yield* Effect.all(
323 [
324 collectUint8StreamText({ stream: child.stdout, maxBytes: HOMEBREW_INFO_MAX_BYTES }),
325 child.exitCode,
326 Stream.runDrain(child.stderr),
327 ],
328 { concurrency: "unbounded" },
329 );
330 return Number(exitCode) !== 0 || stdout.truncated ? null : stdout.text;
331 });
332 return yield* collect.pipe(
333 Effect.scoped,
334 Effect.timeoutOption(Duration.millis(HOMEBREW_INFO_TIMEOUT_MS)),
335 Effect.map(Option.getOrNull),
336 Effect.catchCause((cause) =>
337 Effect.logWarning("Homebrew probe failed", {
338 subcommand: args[0],
339 errorTag: causeErrorTag(cause),
340 }).pipe(Effect.as(null)),
341 ),
342 );
343});
344
345/**
346 * Derive update capabilities from where the executable actually lives. Every
347 * branch that yields a one-click command has evidence that the named tool
348 * owns that path; anything unproven stays manual-only so T3 Code never runs
349 * a package manager against an install it did not create.
350 */
351export const resolvePackageManagedProviderMaintenance = Effect.fn(
352 "resolvePackageManagedProviderMaintenance",
353)(function* (
354 definition: PackageManagedProviderMaintenanceDefinition,
355 context: ProviderMaintenanceResolutionContext | null,
356) {
357 const manual = makeManualOnlyProviderMaintenanceCapabilities({
358 provider: definition.provider,
359 packageName: definition.npmPackageName,
360 });
361 if (!context) {
362 return manual;
363 }
364 const commandPaths = [context.resolvedCommandPath, context.realCommandPath];
365 const packageName = definition.npmPackageName;
366
367 const nativeUpdate = definition.nativeUpdate;
368 if (nativeUpdate && commandPaths.some((commandPath) => nativeUpdate.isCommandPath(commandPath))) {
369 return makeProviderMaintenanceCapabilities({
370 provider: definition.provider,
371 packageName,
372 updateExecutable: context.resolvedCommandPath,
373 updateArgs: nativeUpdate.args,
374 updateLockKey: `${definition.provider}-native`,
375 platform: context.platform,
376 ...(nativeUpdate.env ? { env: nativeUpdate.env } : {}),
377 });
378 }
379 if (commandPaths.some(isVitePlusGlobalCommandPath)) {
380 return makeProviderMaintenanceCapabilities({
381 provider: definition.provider,
382 packageName,
383 updateExecutable: "vp",
384 updateArgs: ["i", "-g", packageName],
385 updateLockKey: "vite-plus-global",
386 });
387 }
388 if (commandPaths.some(isBunGlobalCommandPath)) {
389 return makeProviderMaintenanceCapabilities({
390 provider: definition.provider,
391 packageName,
392 updateExecutable: "bun",
393 updateArgs: ["i", "-g", `${packageName}@latest`],
394 updateLockKey: "bun-global",
395 });
396 }
397 if (commandPaths.some(isPnpmGlobalCommandPath)) {
398 return makeProviderMaintenanceCapabilities({
399 provider: definition.provider,
400 packageName,
401 updateExecutable: "pnpm",
402 updateArgs: ["add", "-g", `${packageName}@latest`],
403 updateLockKey: "pnpm-global",
404 });
405 }
406
407 // npm proof names the package, so it outranks a keg the path merely passes
408 // through: a Homebrew-installed Node keeps its globals under
409 // `Cellar/node/<ver>/lib/node_modules/`, and that is npm's install, not brew's.
410 const npmPrefix = yield* resolveNpmGlobalPrefix(context, packageName);
411 if (npmPrefix) {
412 // npm 12 blocks install scripts by default (empty allow-scripts allowlist)
413 // and still exits 0, so a package whose postinstall finishes the install
414 // (claude copies its native binary over a placeholder stub) is left broken
415 // while the update reports success. Allow this one package's scripts.
416 // Older npm warns about the unknown config and continues.
417 return makeProviderMaintenanceCapabilities({
418 provider: definition.provider,
419 packageName,
420 updateExecutable: "npm",
421 updateArgs: [
422 "install",
423 "-g",
424 "--prefix",
425 npmPrefix,
426 `--allow-scripts=${packageName}`,
427 `${packageName}@latest`,
428 ],
429 updateLockKey: `npm-global:${normalizeCommandPath(npmPrefix)}`,
430 });
431 }
432
433 const homebrew = homebrewOwnershipFromCommandPath(context.realCommandPath);
434 if (homebrew) {
435 const brewPath = yield* resolveCommandPath("brew", { env: context.env }).pipe(
436 Effect.catchTags({ CommandResolutionError: () => Effect.succeed(null) }),
437 );
438 if (!brewPath) {
439 return manual;
440 }
441 // A keg-shaped path is only Homebrew's if it sits under the prefix of the
442 // `brew` that would upgrade it; `brew --prefix` is a cheap shell script.
443 const fileSystem = yield* FileSystem.FileSystem;
444 const brewPrefix = nonEmptyString(yield* runHomebrew(brewPath, ["--prefix"], context.env));
445 const realBrewPrefix = brewPrefix
446 ? yield* fileSystem.realPath(brewPrefix).pipe(Effect.orElseSucceed(() => brewPrefix))
447 : null;
448 if (
449 !realBrewPrefix ||
450 normalizeCommandPath(realBrewPrefix) !== normalizeCommandPath(homebrew.prefix)
451 ) {
452 return manual;
453 }
454 const args =
455 homebrew.kind === "cask" ? ["upgrade", "--cask", homebrew.name] : ["upgrade", homebrew.name];
456 // Homebrew lags npm by hours on every release, so compare against what
457 // `brew upgrade` can actually deliver.
458 const info = yield* runHomebrew(brewPath, ["info", "--json=v2", homebrew.name], context.env);
459 return makeProviderMaintenanceCapabilities({
460 provider: definition.provider,
461 packageName,
462 updateExecutable: brewPath,
463 updateArgs: args,
464 updateLockKey: "homebrew",
465 updateCommand: ["brew", ...args].join(" "),
466 latestVersion: info ? parseHomebrewLatestVersion(info, homebrew) : null,
467 });
468 }
469
470 return manual;
471});
472
473/**
474 * POSIX npm links `<prefix>/bin/<cmd>` into the package, so the real path is
475 * proof. Windows npm writes `.cmd` shims beside `node_modules`, so the proof
476 * is the package manifest next to the shim.
477 */
478const resolveNpmGlobalPrefix = Effect.fn("resolveNpmGlobalPrefix")(function* (
479 context: ProviderMaintenanceResolutionContext,
480 packageName: string,
481) {
482 const fromRealPath = npmGlobalPrefixFromCommandPath(context.realCommandPath, packageName);
483 if (fromRealPath) {
484 return fromRealPath;
485 }
486 if ((yield* HostProcessPlatform) !== "win32") {
487 return null;
488 }
489 const fileSystem = yield* FileSystem.FileSystem;
490 const path = yield* Path.Path;
491 const shimDir = path.dirname(context.resolvedCommandPath);
492 const manifestPath = path.join(
493 shimDir,
494 "node_modules",
495 ...packageName.split("/"),
496 "package.json",
497 );
498 // npm writes both `<cmd>.cmd` and an extensionless sh script into the
499 // Windows prefix; either one sits directly beside `node_modules`. A POSIX
500 // project checkout has the same shape, which is why this is Windows-only.
501 const hasManifest = yield* fileSystem
502 .exists(manifestPath)
503 .pipe(Effect.orElseSucceed(() => false));
504 return hasManifest ? shimDir : null;
505});
506
507export function makePackageManagedProviderMaintenanceResolver(
508 definition: PackageManagedProviderMaintenanceDefinition,
509): ProviderMaintenanceCapabilitiesResolver {
510 return {
511 resolve: (context) => resolvePackageManagedProviderMaintenance(definition, context),
512 };
513}
514
515function makeManualProviderMaintenanceCapabilities(
516 provider: ProviderDriverKind,
517): ProviderMaintenanceCapabilities {
518 return makeManualOnlyProviderMaintenanceCapabilities({
519 provider,
520 packageName: null,
521 });
522}
523
524/**
525 * Locate the configured provider executable, follow symlinks, and hand the
526 * result to the resolver. A binary that cannot be found yields the resolver's
527 * no-context answer.
528 */
529export const resolveProviderMaintenanceCapabilitiesEffect = Effect.fn(
530 "resolveProviderMaintenanceCapabilitiesEffect",
531)(function* (
532 resolver: ProviderMaintenanceCapabilitiesResolver,
533 options?: {
534 readonly binaryPath?: string | null;
535 readonly env?: NodeJS.ProcessEnv;
536 },
537) {
538 const binaryPath = nonEmptyString(options?.binaryPath);
539 if (!binaryPath) {
540 return yield* resolver.resolve(null);
541 }
542
543 const env = options?.env ?? (yield* readCommandLookupEnv);
544 // resolveCommandPath checks explicit paths for existence too, so a missing
545 // binary always lands in the no-context branch and never gets an update
546 // command it cannot run.
547 const resolvedCommandPath = yield* resolveCommandPath(binaryPath, { env }).pipe(
548 Effect.catchTags({ CommandResolutionError: () => Effect.succeed(null) }),
549 );
550 if (!resolvedCommandPath) {
551 return yield* resolver.resolve(null);
552 }
553
554 const fileSystem = yield* FileSystem.FileSystem;
555 const realCommandPath = yield* fileSystem
556 .realPath(resolvedCommandPath)
557 .pipe(Effect.orElseSucceed(() => null));
558 if (!realCommandPath) {
559 return yield* resolver.resolve(null);
560 }
561 return yield* resolver.resolve({
562 binaryPath,
563 resolvedCommandPath,
564 realCommandPath,
565 env,
566 platform: yield* HostProcessPlatform,
567 });
568});
569
570/**
571 * Turn a one-shot resolution into the shape drivers expose: a cached read for
572 * advisories and a `fresh` read that update execution uses so it never trusts
573 * ownership derived before the user clicked.
574 */
575export const makeCachedProviderMaintenanceResolution = Effect.fn(
576 "makeCachedProviderMaintenanceResolution",
577)(function* (resolve: Effect.Effect<ProviderMaintenanceCapabilities>) {
578 const [cached, invalidate] = yield* Effect.cachedInvalidateWithTTL(
579 resolve,
580 MAINTENANCE_CAPABILITIES_CACHE_TTL,
581 );
582 return (options?: { readonly fresh?: boolean }) =>
583 options?.fresh ? invalidate.pipe(Effect.andThen(cached)) : cached;
584});
585
586function deriveVersionAdvisory(input: {
587 readonly currentVersion: string | null;
588 readonly latestVersion: string | null;
589}): Pick<ServerProviderVersionAdvisory, "status" | "message"> {
590 if (!input.currentVersion) {
591 return { status: "unknown", message: null };
592 }
593 if (!input.latestVersion) {
594 return { status: "unknown", message: null };
595 }
596 if (compareSemverVersions(input.currentVersion, input.latestVersion) < 0) {
597 return {
598 status: "behind_latest",
599 message: PROVIDER_UPDATE_ACTION_TOAST_MESSAGE,
600 };
601 }
602 return { status: "current", message: null };
603}
604
605export function createProviderVersionAdvisory(input: {
606 readonly driver: ProviderDriverKind;
607 readonly currentVersion: string | null;
608 readonly latestVersion?: string | null;
609 readonly checkedAt?: string | null;
610 readonly maintenanceCapabilities?: ProviderMaintenanceCapabilities;
611}): ServerProviderVersionAdvisory {
612 const capabilities =
613 input.maintenanceCapabilities ?? makeManualProviderMaintenanceCapabilities(input.driver);
614 const latestVersion = input.latestVersion ?? null;
615 const advisory = deriveVersionAdvisory({
616 currentVersion: input.currentVersion,
617 latestVersion,
618 });
619
620 return {
621 status: advisory.status,
622 currentVersion: input.currentVersion,
623 latestVersion,
624 updateCommand: capabilities.update?.command ?? null,
625 canUpdate: capabilities.update !== null,
626 checkedAt: input.checkedAt ?? null,
627 message: advisory.message,
628 };
629}
630
631const fetchNpmLatestVersion = Effect.fn("fetchNpmLatestVersion")(function* (packageName: string) {
632 const client = yield* HttpClient.HttpClient;
633 const request = HttpClientRequest.get(
634 `https://registry.npmjs.org/${encodeURIComponent(packageName)}/latest`,
635 ).pipe(HttpClientRequest.setHeader("accept", "application/json"));
636 const response = yield* client.execute(request).pipe(
637 Effect.timeoutOption(LATEST_VERSION_TIMEOUT_MS),
638 Effect.orElseSucceed(() => Option.none()),
639 );
640 if (Option.isNone(response)) {
641 return null;
642 }
643 const httpResponse = response.value;
644 if (httpResponse.status < 200 || httpResponse.status >= 300) {
645 return null;
646 }
647 const payload = yield* httpResponse.json.pipe(
648 Effect.flatMap(Schema.decodeUnknownEffect(NpmLatestVersionResponse)),
649 Effect.orElseSucceed(() => null),
650 );
651 return payload ? nonEmptyString(payload.version) : null;
652});
653
654export const resolveLatestProviderVersion = Effect.fn("resolveLatestProviderVersion")(function* (
655 maintenanceCapabilities: ProviderMaintenanceCapabilities,
656) {
657 if (maintenanceCapabilities.latestVersion !== undefined) {
658 return maintenanceCapabilities.latestVersion;
659 }
660 const packageName = maintenanceCapabilities.packageName;
661 if (!packageName) {
662 return null;
663 }
664
665 const latestVersionCache = yield* ProviderVersionCache;
666 const cached = latestVersionCache.get(packageName);
667 const now = DateTime.toEpochMillis(yield* DateTime.now);
668 if (cached && cached.expiresAt > now) {
669 return cached.version;
670 }
671
672 const version = yield* fetchNpmLatestVersion(packageName);
673 latestVersionCache.set(packageName, {
674 expiresAt: now + LATEST_VERSION_CACHE_TTL_MS,
675 version,
676 });
677 return version;
678});
679
680export const enrichProviderSnapshotWithVersionAdvisory = Effect.fn(
681 "enrichProviderSnapshotWithVersionAdvisory",
682)(function* (
683 snapshot: ServerProvider,
684 maintenanceCapabilities?: ProviderMaintenanceCapabilities,
685 options?: {
686 readonly enableProviderUpdateChecks: boolean | undefined;
687 },
688) {
689 const capabilities =
690 maintenanceCapabilities ?? makeManualProviderMaintenanceCapabilities(snapshot.driver);
691 const shouldResolveLatestVersion =
692 options?.enableProviderUpdateChecks !== false &&
693 snapshot.enabled &&
694 snapshot.installed &&
695 Boolean(snapshot.version);
696 if (!shouldResolveLatestVersion) {
697 return {
698 ...snapshot,
699 versionAdvisory: createProviderVersionAdvisory({
700 driver: snapshot.driver,
701 currentVersion: snapshot.version,
702 checkedAt: snapshot.checkedAt,
703 maintenanceCapabilities: capabilities,
704 }),
705 };
706 }
707
708 const latestVersion = yield* resolveLatestProviderVersion(capabilities);
709 return {
710 ...snapshot,
711 versionAdvisory: createProviderVersionAdvisory({
712 driver: snapshot.driver,
713 currentVersion: snapshot.version,
714 latestVersion,
715 checkedAt: DateTime.formatIso(yield* DateTime.now),
716 maintenanceCapabilities: capabilities,
717 }),
718 };
719});