Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

providerMaintenance.ts

723 lines25.6 KB

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 */
36const 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;
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;
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;
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>;
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;
115​
116export interface ProviderVersionCacheEntry {
117 readonly expiresAt: number;
118 readonly version: string | null;
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;
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("'", "'\\''")}'`;
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;
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 };
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 });
201​
202export function normalizeCommandPath(commandPath: string): string {
203 return commandPath.replaceAll("\\", "/").toLowerCase();
205​
206function isVitePlusGlobalCommandPath(commandPath: string): boolean {
207 return normalizeCommandPath(commandPath).includes("/.vite-plus/bin/");
209​
210function isBunGlobalCommandPath(commandPath: string): boolean {
211 return normalizeCommandPath(commandPath).includes("/.bun/bin/");
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 );
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);
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;
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 };
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);
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 // Mise shims resolve to the version manager, not the provider.
436 if (homebrew.kind === "formula" && homebrew.name.toLowerCase() === "mise") {
437 return manual;
438 }
439 const brewPath = yield* resolveCommandPath("brew", { env: context.env }).pipe(
440 Effect.catchTags({ CommandResolutionError: () => Effect.succeed(null) }),
441 );
442 if (!brewPath) {
443 return manual;
444 }
445 // A keg-shaped path is only Homebrew's if it sits under the prefix of the
446 // `brew` that would upgrade it; `brew --prefix` is a cheap shell script.
447 const fileSystem = yield* FileSystem.FileSystem;
448 const brewPrefix = nonEmptyString(yield* runHomebrew(brewPath, ["--prefix"], context.env));
449 const realBrewPrefix = brewPrefix
450 ? yield* fileSystem.realPath(brewPrefix).pipe(Effect.orElseSucceed(() => brewPrefix))
451 : null;
452 if (
453 !realBrewPrefix ||
454 normalizeCommandPath(realBrewPrefix) !== normalizeCommandPath(homebrew.prefix)
455 ) {
456 return manual;
457 }
458 const args =
459 homebrew.kind === "cask" ? ["upgrade", "--cask", homebrew.name] : ["upgrade", homebrew.name];
460 // Homebrew lags npm by hours on every release, so compare against what
461 // `brew upgrade` can actually deliver.
462 const info = yield* runHomebrew(brewPath, ["info", "--json=v2", homebrew.name], context.env);
463 return makeProviderMaintenanceCapabilities({
464 provider: definition.provider,
465 packageName,
466 updateExecutable: brewPath,
467 updateArgs: args,
468 updateLockKey: "homebrew",
469 updateCommand: ["brew", ...args].join(" "),
470 latestVersion: info ? parseHomebrewLatestVersion(info, homebrew) : null,
471 });
472 }
473​
474 return manual;
475});
476​
477/**
478 * POSIX npm links `<prefix>/bin/<cmd>` into the package, so the real path is
479 * proof. Windows npm writes `.cmd` shims beside `node_modules`, so the proof
480 * is the package manifest next to the shim.
481 */
482const resolveNpmGlobalPrefix = Effect.fn("resolveNpmGlobalPrefix")(function* (
483 context: ProviderMaintenanceResolutionContext,
484 packageName: string,
485) {
486 const fromRealPath = npmGlobalPrefixFromCommandPath(context.realCommandPath, packageName);
487 if (fromRealPath) {
488 return fromRealPath;
489 }
490 if ((yield* HostProcessPlatform) !== "win32") {
491 return null;
492 }
493 const fileSystem = yield* FileSystem.FileSystem;
494 const path = yield* Path.Path;
495 const shimDir = path.dirname(context.resolvedCommandPath);
496 const manifestPath = path.join(
497 shimDir,
498 "node_modules",
499 ...packageName.split("/"),
500 "package.json",
501 );
502 // npm writes both `<cmd>.cmd` and an extensionless sh script into the
503 // Windows prefix; either one sits directly beside `node_modules`. A POSIX
504 // project checkout has the same shape, which is why this is Windows-only.
505 const hasManifest = yield* fileSystem
506 .exists(manifestPath)
507 .pipe(Effect.orElseSucceed(() => false));
508 return hasManifest ? shimDir : null;
509});
510​
511export function makePackageManagedProviderMaintenanceResolver(
512 definition: PackageManagedProviderMaintenanceDefinition,
513): ProviderMaintenanceCapabilitiesResolver {
514 return {
515 resolve: (context) => resolvePackageManagedProviderMaintenance(definition, context),
516 };
518​
519function makeManualProviderMaintenanceCapabilities(
520 provider: ProviderDriverKind,
521): ProviderMaintenanceCapabilities {
522 return makeManualOnlyProviderMaintenanceCapabilities({
523 provider,
524 packageName: null,
525 });
527​
528/**
529 * Locate the configured provider executable, follow symlinks, and hand the
530 * result to the resolver. A binary that cannot be found yields the resolver's
531 * no-context answer.
532 */
533export const resolveProviderMaintenanceCapabilitiesEffect = Effect.fn(
534 "resolveProviderMaintenanceCapabilitiesEffect",
535)(function* (
536 resolver: ProviderMaintenanceCapabilitiesResolver,
537 options?: {
538 readonly binaryPath?: string | null;
539 readonly env?: NodeJS.ProcessEnv;
540 },
541) {
542 const binaryPath = nonEmptyString(options?.binaryPath);
543 if (!binaryPath) {
544 return yield* resolver.resolve(null);
545 }
546​
547 const env = options?.env ?? (yield* readCommandLookupEnv);
548 // resolveCommandPath checks explicit paths for existence too, so a missing
549 // binary always lands in the no-context branch and never gets an update
550 // command it cannot run.
551 const resolvedCommandPath = yield* resolveCommandPath(binaryPath, { env }).pipe(
552 Effect.catchTags({ CommandResolutionError: () => Effect.succeed(null) }),
553 );
554 if (!resolvedCommandPath) {
555 return yield* resolver.resolve(null);
556 }
557​
558 const fileSystem = yield* FileSystem.FileSystem;
559 const realCommandPath = yield* fileSystem
560 .realPath(resolvedCommandPath)
561 .pipe(Effect.orElseSucceed(() => null));
562 if (!realCommandPath) {
563 return yield* resolver.resolve(null);
564 }
565 return yield* resolver.resolve({
566 binaryPath,
567 resolvedCommandPath,
568 realCommandPath,
569 env,
570 platform: yield* HostProcessPlatform,
571 });
572});
573​
574/**
575 * Turn a one-shot resolution into the shape drivers expose: a cached read for
576 * advisories and a `fresh` read that update execution uses so it never trusts
577 * ownership derived before the user clicked.
578 */
579export const makeCachedProviderMaintenanceResolution = Effect.fn(
580 "makeCachedProviderMaintenanceResolution",
581)(function* (resolve: Effect.Effect<ProviderMaintenanceCapabilities>) {
582 const [cached, invalidate] = yield* Effect.cachedInvalidateWithTTL(
583 resolve,
584 MAINTENANCE_CAPABILITIES_CACHE_TTL,
585 );
586 return (options?: { readonly fresh?: boolean }) =>
587 options?.fresh ? invalidate.pipe(Effect.andThen(cached)) : cached;
588});
589​
590function deriveVersionAdvisory(input: {
591 readonly currentVersion: string | null;
592 readonly latestVersion: string | null;
593}): Pick<ServerProviderVersionAdvisory, "status" | "message"> {
594 if (!input.currentVersion) {
595 return { status: "unknown", message: null };
596 }
597 if (!input.latestVersion) {
598 return { status: "unknown", message: null };
599 }
600 if (compareSemverVersions(input.currentVersion, input.latestVersion) < 0) {
601 return {
602 status: "behind_latest",
603 message: PROVIDER_UPDATE_ACTION_TOAST_MESSAGE,
604 };
605 }
606 return { status: "current", message: null };
608​
609export function createProviderVersionAdvisory(input: {
610 readonly driver: ProviderDriverKind;
611 readonly currentVersion: string | null;
612 readonly latestVersion?: string | null;
613 readonly checkedAt?: string | null;
614 readonly maintenanceCapabilities?: ProviderMaintenanceCapabilities;
615}): ServerProviderVersionAdvisory {
616 const capabilities =
617 input.maintenanceCapabilities ?? makeManualProviderMaintenanceCapabilities(input.driver);
618 const latestVersion = input.latestVersion ?? null;
619 const advisory = deriveVersionAdvisory({
620 currentVersion: input.currentVersion,
621 latestVersion,
622 });
623​
624 return {
625 status: advisory.status,
626 currentVersion: input.currentVersion,
627 latestVersion,
628 updateCommand: capabilities.update?.command ?? null,
629 canUpdate: capabilities.update !== null,
630 checkedAt: input.checkedAt ?? null,
631 message: advisory.message,
632 };
634​
635const fetchNpmLatestVersion = Effect.fn("fetchNpmLatestVersion")(function* (packageName: string) {
636 const client = yield* HttpClient.HttpClient;
637 const request = HttpClientRequest.get(
638 `https://registry.npmjs.org/${encodeURIComponent(packageName)}/latest`,
639 ).pipe(HttpClientRequest.setHeader("accept", "application/json"));
640 const response = yield* client.execute(request).pipe(
641 Effect.timeoutOption(LATEST_VERSION_TIMEOUT_MS),
642 Effect.orElseSucceed(() => Option.none()),
643 );
644 if (Option.isNone(response)) {
645 return null;
646 }
647 const httpResponse = response.value;
648 if (httpResponse.status < 200 || httpResponse.status >= 300) {
649 return null;
650 }
651 const payload = yield* httpResponse.json.pipe(
652 Effect.flatMap(Schema.decodeUnknownEffect(NpmLatestVersionResponse)),
653 Effect.orElseSucceed(() => null),
654 );
655 return payload ? nonEmptyString(payload.version) : null;
656});
657​
658export const resolveLatestProviderVersion = Effect.fn("resolveLatestProviderVersion")(function* (
659 maintenanceCapabilities: ProviderMaintenanceCapabilities,
660) {
661 if (maintenanceCapabilities.latestVersion !== undefined) {
662 return maintenanceCapabilities.latestVersion;
663 }
664 const packageName = maintenanceCapabilities.packageName;
665 if (!packageName) {
666 return null;
667 }
668​
669 const latestVersionCache = yield* ProviderVersionCache;
670 const cached = latestVersionCache.get(packageName);
671 const now = DateTime.toEpochMillis(yield* DateTime.now);
672 if (cached && cached.expiresAt > now) {
673 return cached.version;
674 }
675​
676 const version = yield* fetchNpmLatestVersion(packageName);
677 latestVersionCache.set(packageName, {
678 expiresAt: now + LATEST_VERSION_CACHE_TTL_MS,
679 version,
680 });
681 return version;
682});
683​
684export const enrichProviderSnapshotWithVersionAdvisory = Effect.fn(
685 "enrichProviderSnapshotWithVersionAdvisory",
686)(function* (
687 snapshot: ServerProvider,
688 maintenanceCapabilities?: ProviderMaintenanceCapabilities,
689 options?: {
690 readonly enableProviderUpdateChecks: boolean | undefined;
691 },
692) {
693 const capabilities =
694 maintenanceCapabilities ?? makeManualProviderMaintenanceCapabilities(snapshot.driver);
695 const shouldResolveLatestVersion =
696 options?.enableProviderUpdateChecks !== false &&
697 snapshot.enabled &&
698 snapshot.installed &&
699 Boolean(snapshot.version);
700 if (!shouldResolveLatestVersion) {
701 return {
702 ...snapshot,
703 versionAdvisory: createProviderVersionAdvisory({
704 driver: snapshot.driver,
705 currentVersion: snapshot.version,
706 checkedAt: snapshot.checkedAt,
707 maintenanceCapabilities: capabilities,
708 }),
709 };
710 }
711​
712 const latestVersion = yield* resolveLatestProviderVersion(capabilities);
713 return {
714 ...snapshot,
715 versionAdvisory: createProviderVersionAdvisory({
716 driver: snapshot.driver,
717 currentVersion: snapshot.version,
718 latestVersion,
719 checkedAt: DateTime.formatIso(yield* DateTime.now),
720 maintenanceCapabilities: capabilities,
721 }),
722 };
723});