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 return packageIndex === 0 ? "/" : slashPath.slice(0, packageIndex);
244}
245
246// `<prefix>/Cellar/<name>/<version>/…` or `<prefix>/Caskroom/<name>/<version>/…`.
247// Homebrew always nests a version directory under the keg.
248const HOMEBREW_KEG_PATTERN = /^(.*)\/(cellar|caskroom)\/([^/]+)\/[^/]+\//i;
249
250export interface HomebrewOwnership {
251 readonly kind: "formula" | "cask";
252 readonly name: string;
253 /** The Homebrew prefix the keg sits under; must match `brew --prefix`. */
254 readonly prefix: string;
255}
256
257/**
258 * Homebrew looks like the owner when the real path runs through a versioned
259 * keg or cask. It is only proven once the prefix matches the `brew` that will
260 * run the upgrade (see `resolvePackageManagedProviderMaintenance`).
261 */
262export function homebrewOwnershipFromCommandPath(
263 realCommandPath: string,
264): HomebrewOwnership | null {
265 const match = HOMEBREW_KEG_PATTERN.exec(realCommandPath.replaceAll("\\", "/"));
266 if (!match) {
267 return null;
268 }
269 return {
270 kind: match[2]!.toLowerCase() === "cellar" ? "formula" : "cask",
271 name: match[3]!,
272 prefix: match[1]!,
273 };
274}
275
276const HomebrewInfoResponse = Schema.Struct({
277 formulae: Schema.optional(
278 Schema.Array(
279 Schema.Struct({
280 versions: Schema.optional(Schema.Struct({ stable: Schema.optional(Schema.String) })),
281 }),
282 ),
283 ),
284 casks: Schema.optional(Schema.Array(Schema.Struct({ version: Schema.optional(Schema.String) }))),
285});
286
287const decodeHomebrewInfo = Schema.decodeUnknownOption(Schema.fromJsonString(HomebrewInfoResponse));
288
289/** Cask versions may carry a build suffix after a comma (`1.2.3,456`). */
290export function parseHomebrewLatestVersion(
291 infoJson: string,
292 ownership: HomebrewOwnership,
293): string | null {
294 const decoded = decodeHomebrewInfo(infoJson);
295 if (Option.isNone(decoded)) {
296 return null;
297 }
298 const raw =
299 ownership.kind === "formula"
300 ? decoded.value.formulae?.[0]?.versions?.stable
301 : decoded.value.casks?.[0]?.version?.split(",", 1)[0];
302 return nonEmptyString(raw);
303}
304
305/** Run `brew <args>` and return stdout, or null on failure, timeout, or oversized output. */
306const runHomebrew = Effect.fn("runHomebrew")(function* (
307 brewPath: string,
308 args: ReadonlyArray<string>,
309 env: NodeJS.ProcessEnv,
310) {
311 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
312 const collect = Effect.gen(function* () {
313 const child = yield* spawner.spawn(ChildProcess.make(brewPath, args, { env, extendEnv: true }));
314 yield* Effect.addFinalizer(() => child.kill().pipe(Effect.ignore));
315 // stderr is drained so a chatty brew cannot block on a full pipe.
316 const [stdout, exitCode] = yield* Effect.all(
317 [
318 collectUint8StreamText({ stream: child.stdout, maxBytes: HOMEBREW_INFO_MAX_BYTES }),
319 child.exitCode,
320 Stream.runDrain(child.stderr),
321 ],
322 { concurrency: "unbounded" },
323 );
324 return Number(exitCode) !== 0 || stdout.truncated ? null : stdout.text;
325 });
326 return yield* collect.pipe(
327 Effect.scoped,
328 Effect.timeoutOption(Duration.millis(HOMEBREW_INFO_TIMEOUT_MS)),
329 Effect.map(Option.getOrNull),
330 Effect.catchCause((cause) =>
331 Effect.logWarning("Homebrew probe failed", {
332 subcommand: args[0],
333 errorTag: causeErrorTag(cause),
334 }).pipe(Effect.as(null)),
335 ),
336 );
337});
338
339/**
340 * Derive update capabilities from where the executable actually lives. Every
341 * branch that yields a one-click command has evidence that the named tool
342 * owns that path; anything unproven stays manual-only so T3 Code never runs
343 * a package manager against an install it did not create.
344 */
345export const resolvePackageManagedProviderMaintenance = Effect.fn(
346 "resolvePackageManagedProviderMaintenance",
347)(function* (
348 definition: PackageManagedProviderMaintenanceDefinition,
349 context: ProviderMaintenanceResolutionContext | null,
350) {
351 const manual = makeManualOnlyProviderMaintenanceCapabilities({
352 provider: definition.provider,
353 packageName: definition.npmPackageName,
354 });
355 if (!context) {
356 return manual;
357 }
358 const commandPaths = [context.resolvedCommandPath, context.realCommandPath];
359 const packageName = definition.npmPackageName;
360
361 const nativeUpdate = definition.nativeUpdate;
362 if (nativeUpdate && commandPaths.some((commandPath) => nativeUpdate.isCommandPath(commandPath))) {
363 return makeProviderMaintenanceCapabilities({
364 provider: definition.provider,
365 packageName,
366 updateExecutable: context.resolvedCommandPath,
367 updateArgs: nativeUpdate.args,
368 updateLockKey: `${definition.provider}-native`,
369 platform: context.platform,
370 ...(nativeUpdate.env ? { env: nativeUpdate.env } : {}),
371 });
372 }
373 if (commandPaths.some(isVitePlusGlobalCommandPath)) {
374 return makeProviderMaintenanceCapabilities({
375 provider: definition.provider,
376 packageName,
377 updateExecutable: "vp",
378 updateArgs: ["i", "-g", packageName],
379 updateLockKey: "vite-plus-global",
380 });
381 }
382 if (commandPaths.some(isBunGlobalCommandPath)) {
383 return makeProviderMaintenanceCapabilities({
384 provider: definition.provider,
385 packageName,
386 updateExecutable: "bun",
387 updateArgs: ["i", "-g", `${packageName}@latest`],
388 updateLockKey: "bun-global",
389 });
390 }
391 if (commandPaths.some(isPnpmGlobalCommandPath)) {
392 return makeProviderMaintenanceCapabilities({
393 provider: definition.provider,
394 packageName,
395 updateExecutable: "pnpm",
396 updateArgs: ["add", "-g", `${packageName}@latest`],
397 updateLockKey: "pnpm-global",
398 });
399 }
400
401 // npm proof names the package, so it outranks a keg the path merely passes
402 // through: a Homebrew-installed Node keeps its globals under
403 // `Cellar/node/<ver>/lib/node_modules/`, and that is npm's install, not brew's.
404 const npmPrefix = yield* resolveNpmGlobalPrefix(context, packageName);
405 if (npmPrefix) {
406 // npm 12 blocks install scripts by default (empty allow-scripts allowlist)
407 // and still exits 0, so a package whose postinstall finishes the install
408 // (claude copies its native binary over a placeholder stub) is left broken
409 // while the update reports success. Allow this one package's scripts.
410 // Older npm warns about the unknown config and continues.
411 return makeProviderMaintenanceCapabilities({
412 provider: definition.provider,
413 packageName,
414 updateExecutable: "npm",
415 updateArgs: [
416 "install",
417 "-g",
418 "--prefix",
419 npmPrefix,
420 `--allow-scripts=${packageName}`,
421 `${packageName}@latest`,
422 ],
423 updateLockKey: `npm-global:${normalizeCommandPath(npmPrefix)}`,
424 });
425 }
426
427 const homebrew = homebrewOwnershipFromCommandPath(context.realCommandPath);
428 if (homebrew) {
429 const brewPath = yield* resolveCommandPath("brew", { env: context.env }).pipe(
430 Effect.catchTags({ CommandResolutionError: () => Effect.succeed(null) }),
431 );
432 if (!brewPath) {
433 return manual;
434 }
435 // A keg-shaped path is only Homebrew's if it sits under the prefix of the
436 // `brew` that would upgrade it; `brew --prefix` is a cheap shell script.
437 const fileSystem = yield* FileSystem.FileSystem;
438 const brewPrefix = nonEmptyString(yield* runHomebrew(brewPath, ["--prefix"], context.env));
439 const realBrewPrefix = brewPrefix
440 ? yield* fileSystem.realPath(brewPrefix).pipe(Effect.orElseSucceed(() => brewPrefix))
441 : null;
442 if (
443 !realBrewPrefix ||
444 normalizeCommandPath(realBrewPrefix) !== normalizeCommandPath(homebrew.prefix)
445 ) {
446 return manual;
447 }
448 const args =
449 homebrew.kind === "cask" ? ["upgrade", "--cask", homebrew.name] : ["upgrade", homebrew.name];
450 // Homebrew lags npm by hours on every release, so compare against what
451 // `brew upgrade` can actually deliver.
452 const info = yield* runHomebrew(brewPath, ["info", "--json=v2", homebrew.name], context.env);
453 return makeProviderMaintenanceCapabilities({
454 provider: definition.provider,
455 packageName,
456 updateExecutable: brewPath,
457 updateArgs: args,
458 updateLockKey: "homebrew",
459 updateCommand: ["brew", ...args].join(" "),
460 latestVersion: info ? parseHomebrewLatestVersion(info, homebrew) : null,
461 });
462 }
463
464 return manual;
465});
466
467/**
468 * POSIX npm links `<prefix>/bin/<cmd>` into the package, so the real path is
469 * proof. Windows npm writes `.cmd` shims beside `node_modules`, so the proof
470 * is the package manifest next to the shim.
471 */
472const resolveNpmGlobalPrefix = Effect.fn("resolveNpmGlobalPrefix")(function* (
473 context: ProviderMaintenanceResolutionContext,
474 packageName: string,
475) {
476 const fromRealPath = npmGlobalPrefixFromCommandPath(context.realCommandPath, packageName);
477 if (fromRealPath) {
478 return fromRealPath;
479 }
480 if ((yield* HostProcessPlatform) !== "win32") {
481 return null;
482 }
483 const fileSystem = yield* FileSystem.FileSystem;
484 const path = yield* Path.Path;
485 const shimDir = path.dirname(context.resolvedCommandPath);
486 const manifestPath = path.join(
487 shimDir,
488 "node_modules",
489 ...packageName.split("/"),
490 "package.json",
491 );
492 // npm writes both `<cmd>.cmd` and an extensionless sh script into the
493 // Windows prefix; either one sits directly beside `node_modules`. A POSIX
494 // project checkout has the same shape, which is why this is Windows-only.
495 const hasManifest = yield* fileSystem
496 .exists(manifestPath)
497 .pipe(Effect.orElseSucceed(() => false));
498 return hasManifest ? shimDir : null;
499});
500
501export function makePackageManagedProviderMaintenanceResolver(
502 definition: PackageManagedProviderMaintenanceDefinition,
503): ProviderMaintenanceCapabilitiesResolver {
504 return {
505 resolve: (context) => resolvePackageManagedProviderMaintenance(definition, context),
506 };
507}
508
509function makeManualProviderMaintenanceCapabilities(
510 provider: ProviderDriverKind,
511): ProviderMaintenanceCapabilities {
512 return makeManualOnlyProviderMaintenanceCapabilities({
513 provider,
514 packageName: null,
515 });
516}
517
518/**
519 * Locate the configured provider executable, follow symlinks, and hand the
520 * result to the resolver. A binary that cannot be found yields the resolver's
521 * no-context answer.
522 */
523export const resolveProviderMaintenanceCapabilitiesEffect = Effect.fn(
524 "resolveProviderMaintenanceCapabilitiesEffect",
525)(function* (
526 resolver: ProviderMaintenanceCapabilitiesResolver,
527 options?: {
528 readonly binaryPath?: string | null;
529 readonly env?: NodeJS.ProcessEnv;
530 },
531) {
532 const binaryPath = nonEmptyString(options?.binaryPath);
533 if (!binaryPath) {
534 return yield* resolver.resolve(null);
535 }
536
537 const env = options?.env ?? (yield* readCommandLookupEnv);
538 // resolveCommandPath checks explicit paths for existence too, so a missing
539 // binary always lands in the no-context branch and never gets an update
540 // command it cannot run.
541 const resolvedCommandPath = yield* resolveCommandPath(binaryPath, { env }).pipe(
542 Effect.catchTags({ CommandResolutionError: () => Effect.succeed(null) }),
543 );
544 if (!resolvedCommandPath) {
545 return yield* resolver.resolve(null);
546 }
547
548 const fileSystem = yield* FileSystem.FileSystem;
549 const realCommandPath = yield* fileSystem
550 .realPath(resolvedCommandPath)
551 .pipe(Effect.orElseSucceed(() => null));
552 if (!realCommandPath) {
553 return yield* resolver.resolve(null);
554 }
555 return yield* resolver.resolve({
556 binaryPath,
557 resolvedCommandPath,
558 realCommandPath,
559 env,
560 platform: yield* HostProcessPlatform,
561 });
562});
563
564/**
565 * Turn a one-shot resolution into the shape drivers expose: a cached read for
566 * advisories and a `fresh` read that update execution uses so it never trusts
567 * ownership derived before the user clicked.
568 */
569export const makeCachedProviderMaintenanceResolution = Effect.fn(
570 "makeCachedProviderMaintenanceResolution",
571)(function* (resolve: Effect.Effect<ProviderMaintenanceCapabilities>) {
572 const [cached, invalidate] = yield* Effect.cachedInvalidateWithTTL(
573 resolve,
574 MAINTENANCE_CAPABILITIES_CACHE_TTL,
575 );
576 return (options?: { readonly fresh?: boolean }) =>
577 options?.fresh ? invalidate.pipe(Effect.andThen(cached)) : cached;
578});
579
580function deriveVersionAdvisory(input: {
581 readonly currentVersion: string | null;
582 readonly latestVersion: string | null;
583}): Pick<ServerProviderVersionAdvisory, "status" | "message"> {
584 if (!input.currentVersion) {
585 return { status: "unknown", message: null };
586 }
587 if (!input.latestVersion) {
588 return { status: "unknown", message: null };
589 }
590 if (compareSemverVersions(input.currentVersion, input.latestVersion) < 0) {
591 return {
592 status: "behind_latest",
593 message: PROVIDER_UPDATE_ACTION_TOAST_MESSAGE,
594 };
595 }
596 return { status: "current", message: null };
597}
598
599export function createProviderVersionAdvisory(input: {
600 readonly driver: ProviderDriverKind;
601 readonly currentVersion: string | null;
602 readonly latestVersion?: string | null;
603 readonly checkedAt?: string | null;
604 readonly maintenanceCapabilities?: ProviderMaintenanceCapabilities;
605}): ServerProviderVersionAdvisory {
606 const capabilities =
607 input.maintenanceCapabilities ?? makeManualProviderMaintenanceCapabilities(input.driver);
608 const latestVersion = input.latestVersion ?? null;
609 const advisory = deriveVersionAdvisory({
610 currentVersion: input.currentVersion,
611 latestVersion,
612 });
613
614 return {
615 status: advisory.status,
616 currentVersion: input.currentVersion,
617 latestVersion,
618 updateCommand: capabilities.update?.command ?? null,
619 canUpdate: capabilities.update !== null,
620 checkedAt: input.checkedAt ?? null,
621 message: advisory.message,
622 };
623}
624
625const fetchNpmLatestVersion = Effect.fn("fetchNpmLatestVersion")(function* (packageName: string) {
626 const client = yield* HttpClient.HttpClient;
627 const request = HttpClientRequest.get(
628 `https://registry.npmjs.org/${encodeURIComponent(packageName)}/latest`,
629 ).pipe(HttpClientRequest.setHeader("accept", "application/json"));
630 const response = yield* client.execute(request).pipe(
631 Effect.timeoutOption(LATEST_VERSION_TIMEOUT_MS),
632 Effect.orElseSucceed(() => Option.none()),
633 );
634 if (Option.isNone(response)) {
635 return null;
636 }
637 const httpResponse = response.value;
638 if (httpResponse.status < 200 || httpResponse.status >= 300) {
639 return null;
640 }
641 const payload = yield* httpResponse.json.pipe(
642 Effect.flatMap(Schema.decodeUnknownEffect(NpmLatestVersionResponse)),
643 Effect.orElseSucceed(() => null),
644 );
645 return payload ? nonEmptyString(payload.version) : null;
646});
647
648export const resolveLatestProviderVersion = Effect.fn("resolveLatestProviderVersion")(function* (
649 maintenanceCapabilities: ProviderMaintenanceCapabilities,
650) {
651 if (maintenanceCapabilities.latestVersion !== undefined) {
652 return maintenanceCapabilities.latestVersion;
653 }
654 const packageName = maintenanceCapabilities.packageName;
655 if (!packageName) {
656 return null;
657 }
658
659 const latestVersionCache = yield* ProviderVersionCache;
660 const cached = latestVersionCache.get(packageName);
661 const now = DateTime.toEpochMillis(yield* DateTime.now);
662 if (cached && cached.expiresAt > now) {
663 return cached.version;
664 }
665
666 const version = yield* fetchNpmLatestVersion(packageName);
667 latestVersionCache.set(packageName, {
668 expiresAt: now + LATEST_VERSION_CACHE_TTL_MS,
669 version,
670 });
671 return version;
672});
673
674export const enrichProviderSnapshotWithVersionAdvisory = Effect.fn(
675 "enrichProviderSnapshotWithVersionAdvisory",
676)(function* (
677 snapshot: ServerProvider,
678 maintenanceCapabilities?: ProviderMaintenanceCapabilities,
679 options?: {
680 readonly enableProviderUpdateChecks: boolean | undefined;
681 },
682) {
683 const capabilities =
684 maintenanceCapabilities ?? makeManualProviderMaintenanceCapabilities(snapshot.driver);
685 const shouldResolveLatestVersion =
686 options?.enableProviderUpdateChecks !== false &&
687 snapshot.enabled &&
688 snapshot.installed &&
689 Boolean(snapshot.version);
690 if (!shouldResolveLatestVersion) {
691 return {
692 ...snapshot,
693 versionAdvisory: createProviderVersionAdvisory({
694 driver: snapshot.driver,
695 currentVersion: snapshot.version,
696 checkedAt: snapshot.checkedAt,
697 maintenanceCapabilities: capabilities,
698 }),
699 };
700 }
701
702 const latestVersion = yield* resolveLatestProviderVersion(capabilities);
703 return {
704 ...snapshot,
705 versionAdvisory: createProviderVersionAdvisory({
706 driver: snapshot.driver,
707 currentVersion: snapshot.version,
708 latestVersion,
709 checkedAt: DateTime.formatIso(yield* DateTime.now),
710 maintenanceCapabilities: capabilities,
711 }),
712 };
713});