mirror of
https://github.com/Kaelio/ktx.git
synced 2026-06-13 08:15:14 +02:00
feat(cli): add channel-aware update notifier (#265)
* feat(cli): show cached update notices after commands * docs(cli): describe update notices * fix(cli): type update check environment * fix(cli): decouple update notice display from refresh and harden suppression Display a cached "update available" notice based solely on the lastNoticeAt 24h throttle, independent of checkedAt refresh freshness, matching the design's independent display/refresh decisions. Suppress the check unconditionally under --json, CI, and non-TTY before consulting output-mode preferences, so a KTX_OUTPUT=pretty override can no longer make CI/non-TTY contexts phone npm.
This commit is contained in:
parent
377f21acd7
commit
698efdcef8
14 changed files with 1153 additions and 4 deletions
45
packages/cli/src/update-check/cache.ts
Normal file
45
packages/cli/src/update-check/cache.ts
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
import { renameSync, writeFileSync } from 'node:fs';
|
||||
import { mkdir, readFile } from 'node:fs/promises';
|
||||
import { homedir } from 'node:os';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { z } from 'zod';
|
||||
|
||||
const updateCheckCacheSchema = z
|
||||
.object({
|
||||
checkedAt: z.string(),
|
||||
channel: z.enum(['latest', 'next']),
|
||||
installedVersion: z.string(),
|
||||
latestForChannel: z.string(),
|
||||
lastNoticeAt: z.string().optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export type UpdateCheckCache = z.infer<typeof updateCheckCacheSchema>;
|
||||
|
||||
/** @internal */
|
||||
export function updateCheckCachePath(homeDir = homedir()): string {
|
||||
return join(homeDir, '.ktx', 'update-check.json');
|
||||
}
|
||||
|
||||
export async function readUpdateCheckCache(options: { homeDir?: string } = {}): Promise<UpdateCheckCache | null> {
|
||||
try {
|
||||
return updateCheckCacheSchema.parse(JSON.parse(await readFile(updateCheckCachePath(options.homeDir), 'utf-8')));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function writeUpdateCheckCache(
|
||||
value: UpdateCheckCache,
|
||||
options: { homeDir?: string } = {},
|
||||
): Promise<void> {
|
||||
try {
|
||||
const path = updateCheckCachePath(options.homeDir);
|
||||
await mkdir(dirname(path), { recursive: true });
|
||||
const tempPath = `${path}.${process.pid}.${Date.now()}.tmp`;
|
||||
writeFileSync(tempPath, `${JSON.stringify(value, null, 2)}\n`, 'utf-8');
|
||||
renameSync(tempPath, path);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
}
|
||||
43
packages/cli/src/update-check/channel.ts
Normal file
43
packages/cli/src/update-check/channel.ts
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
import semver from 'semver';
|
||||
|
||||
export type UpdateChannel = 'latest' | 'next';
|
||||
|
||||
export type UpdateDecision =
|
||||
| { status: 'skip' }
|
||||
| { status: 'upToDate'; channel: UpdateChannel; target: string }
|
||||
| { status: 'available'; channel: UpdateChannel; target: string };
|
||||
|
||||
/** @internal */
|
||||
export function inferUpdateChannel(installed: string): UpdateChannel | null {
|
||||
const parsed = semver.parse(installed);
|
||||
if (!parsed || installed === '0.0.0') {
|
||||
return null;
|
||||
}
|
||||
|
||||
const [prereleaseId] = parsed.prerelease;
|
||||
if (prereleaseId === undefined) {
|
||||
return 'latest';
|
||||
}
|
||||
if (prereleaseId === 'rc') {
|
||||
return 'next';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function decideUpdate(installed: string, distTags: Record<string, string>): UpdateDecision {
|
||||
const channel = inferUpdateChannel(installed);
|
||||
if (!channel || !semver.valid(installed)) {
|
||||
return { status: 'skip' };
|
||||
}
|
||||
|
||||
const target = distTags[channel];
|
||||
if (!target || !semver.valid(target)) {
|
||||
return { status: 'skip' };
|
||||
}
|
||||
|
||||
if (semver.gt(target, installed)) {
|
||||
return { status: 'available', channel, target };
|
||||
}
|
||||
|
||||
return { status: 'upToDate', channel, target };
|
||||
}
|
||||
52
packages/cli/src/update-check/registry.ts
Normal file
52
packages/cli/src/update-check/registry.ts
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
import { request as httpsRequest } from 'node:https';
|
||||
import { URL } from 'node:url';
|
||||
import { z } from 'zod';
|
||||
|
||||
const DIST_TAGS_URL = new URL('https://registry.npmjs.org/-/package/@kaelio/ktx/dist-tags');
|
||||
const distTagsSchema = z.record(z.string(), z.string());
|
||||
|
||||
function parseDistTags(raw: string): Record<string, string> {
|
||||
return distTagsSchema.parse(JSON.parse(raw));
|
||||
}
|
||||
|
||||
export function fetchDistTags(): Promise<Record<string, string>> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const request = httpsRequest(
|
||||
DIST_TAGS_URL,
|
||||
{
|
||||
method: 'GET',
|
||||
headers: {
|
||||
accept: 'application/json',
|
||||
},
|
||||
},
|
||||
(response) => {
|
||||
const chunks: Buffer[] = [];
|
||||
response.on('data', (chunk: Buffer | string) => {
|
||||
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
||||
});
|
||||
response.on('end', () => {
|
||||
const text = Buffer.concat(chunks).toString('utf8');
|
||||
const statusCode = response.statusCode ?? 0;
|
||||
if (statusCode < 200 || statusCode >= 300) {
|
||||
reject(new Error(`npm dist-tags request failed with ${statusCode}: ${text}`));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
resolve(parseDistTags(text));
|
||||
} catch (error) {
|
||||
reject(error);
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
request.on('socket', (socket) => {
|
||||
socket.unref();
|
||||
});
|
||||
request.on('error', reject);
|
||||
request.setTimeout(5000, () => {
|
||||
request.destroy(new Error('npm dist-tags request timed out'));
|
||||
});
|
||||
request.end();
|
||||
});
|
||||
}
|
||||
187
packages/cli/src/update-check/update-check.ts
Normal file
187
packages/cli/src/update-check/update-check.ts
Normal file
|
|
@ -0,0 +1,187 @@
|
|||
import type { KtxCliIo } from '../cli-runtime.js';
|
||||
import { cyan, dim, type CliStyleEnv } from '../clack.js';
|
||||
import { resolveOutputMode } from '../io/mode.js';
|
||||
import { type UpdateCheckCache, readUpdateCheckCache, writeUpdateCheckCache } from './cache.js';
|
||||
import { decideUpdate, inferUpdateChannel, type UpdateChannel } from './channel.js';
|
||||
import { fetchDistTags as defaultFetchDistTags } from './registry.js';
|
||||
|
||||
const DAY_MS = 24 * 60 * 60 * 1000;
|
||||
|
||||
/** @internal */
|
||||
export interface UpdateCheckEnv extends NodeJS.ProcessEnv, CliStyleEnv {
|
||||
CI?: string;
|
||||
DO_NOT_TRACK?: string;
|
||||
KTX_NO_UPDATE_CHECK?: string;
|
||||
KTX_OUTPUT?: string;
|
||||
NO_UPDATE_NOTIFIER?: string;
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
export interface UpdateCheckCommandOptions {
|
||||
format?: unknown;
|
||||
json?: unknown;
|
||||
output?: unknown;
|
||||
}
|
||||
|
||||
export interface PrepareUpdateCheckNoticeOptions {
|
||||
commandOptions?: UpdateCheckCommandOptions;
|
||||
env?: UpdateCheckEnv;
|
||||
fetchDistTags?: () => Promise<Record<string, string>>;
|
||||
homeDir?: string;
|
||||
installedVersion: string;
|
||||
io: KtxCliIo;
|
||||
now?: () => Date;
|
||||
}
|
||||
|
||||
export interface PreparedUpdateCheckNotice {
|
||||
notice: string | null;
|
||||
}
|
||||
|
||||
function truthy(value: string | undefined): boolean {
|
||||
return value !== undefined && value !== '' && value !== '0' && value !== 'false';
|
||||
}
|
||||
|
||||
function commandRequestsJson(options: UpdateCheckCommandOptions | undefined): boolean {
|
||||
return options?.json === true || options?.output === 'json' || options?.format === 'json';
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
export function shouldSuppressUpdateCheck(args: {
|
||||
commandOptions?: UpdateCheckCommandOptions;
|
||||
env?: UpdateCheckEnv;
|
||||
io: KtxCliIo;
|
||||
}): boolean {
|
||||
const env = args.env ?? process.env;
|
||||
if (truthy(env.KTX_NO_UPDATE_CHECK) || truthy(env.NO_UPDATE_NOTIFIER) || truthy(env.DO_NOT_TRACK)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (commandRequestsJson(args.commandOptions) || truthy(env.CI) || args.io.stdout.isTTY !== true) {
|
||||
return true;
|
||||
}
|
||||
|
||||
try {
|
||||
const mode = resolveOutputMode({
|
||||
json: false,
|
||||
io: args.io,
|
||||
env,
|
||||
});
|
||||
return mode !== 'pretty';
|
||||
} catch {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
export function renderUpdateNotice(args: {
|
||||
channel: UpdateChannel;
|
||||
env?: CliStyleEnv;
|
||||
installedVersion: string;
|
||||
targetVersion: string;
|
||||
}): string {
|
||||
const command = args.channel === 'next' ? 'npm i -g @kaelio/ktx@next' : 'npm i -g @kaelio/ktx';
|
||||
return `${cyan('↑', args.env)} Update available: ktx ${args.installedVersion} → ${args.targetVersion}\n ${dim(command, args.env)}\n`;
|
||||
}
|
||||
|
||||
function timestampMs(value: string | undefined): number | null {
|
||||
if (!value) {
|
||||
return null;
|
||||
}
|
||||
const parsed = Date.parse(value);
|
||||
return Number.isNaN(parsed) ? null : parsed;
|
||||
}
|
||||
|
||||
function elapsedAtLeast(value: string | undefined, now: Date, intervalMs: number): boolean {
|
||||
const previous = timestampMs(value);
|
||||
if (previous === null) {
|
||||
return true;
|
||||
}
|
||||
return now.getTime() - previous >= intervalMs;
|
||||
}
|
||||
|
||||
function shouldRefreshCache(cache: UpdateCheckCache | null, installedVersion: string, now: Date): boolean {
|
||||
if (!cache || cache.installedVersion !== installedVersion) {
|
||||
return true;
|
||||
}
|
||||
return elapsedAtLeast(cache.checkedAt, now, DAY_MS);
|
||||
}
|
||||
|
||||
async function refreshUpdateCache(args: {
|
||||
cache: UpdateCheckCache | null;
|
||||
fetchDistTags: () => Promise<Record<string, string>>;
|
||||
homeDir?: string;
|
||||
installedVersion: string;
|
||||
now: Date;
|
||||
}): Promise<void> {
|
||||
const distTags = await args.fetchDistTags();
|
||||
const decision = decideUpdate(args.installedVersion, distTags);
|
||||
if (decision.status === 'skip') {
|
||||
return;
|
||||
}
|
||||
|
||||
await writeUpdateCheckCache(
|
||||
{
|
||||
checkedAt: args.now.toISOString(),
|
||||
channel: decision.channel,
|
||||
installedVersion: args.installedVersion,
|
||||
latestForChannel: decision.target,
|
||||
...(args.cache?.installedVersion === args.installedVersion && args.cache.channel === decision.channel
|
||||
? { lastNoticeAt: args.cache.lastNoticeAt }
|
||||
: {}),
|
||||
},
|
||||
{ homeDir: args.homeDir },
|
||||
);
|
||||
}
|
||||
|
||||
export async function prepareUpdateCheckNotice(
|
||||
options: PrepareUpdateCheckNoticeOptions,
|
||||
): Promise<PreparedUpdateCheckNotice> {
|
||||
const env = options.env ?? process.env;
|
||||
const now = (options.now ?? (() => new Date()))();
|
||||
const fetchDistTags = options.fetchDistTags ?? defaultFetchDistTags;
|
||||
|
||||
if (
|
||||
shouldSuppressUpdateCheck({
|
||||
commandOptions: options.commandOptions,
|
||||
env,
|
||||
io: options.io,
|
||||
})
|
||||
) {
|
||||
return { notice: null };
|
||||
}
|
||||
|
||||
if (!inferUpdateChannel(options.installedVersion)) {
|
||||
return { notice: null };
|
||||
}
|
||||
|
||||
let cache = await readUpdateCheckCache({ homeDir: options.homeDir });
|
||||
let notice: string | null = null;
|
||||
|
||||
if (cache?.installedVersion === options.installedVersion) {
|
||||
const decision = decideUpdate(options.installedVersion, {
|
||||
[cache.channel]: cache.latestForChannel,
|
||||
});
|
||||
if (decision.status === 'available' && elapsedAtLeast(cache.lastNoticeAt, now, DAY_MS)) {
|
||||
notice = renderUpdateNotice({
|
||||
channel: decision.channel,
|
||||
env,
|
||||
installedVersion: options.installedVersion,
|
||||
targetVersion: decision.target,
|
||||
});
|
||||
cache = { ...cache, lastNoticeAt: now.toISOString() };
|
||||
await writeUpdateCheckCache(cache, { homeDir: options.homeDir });
|
||||
}
|
||||
}
|
||||
|
||||
if (shouldRefreshCache(cache, options.installedVersion, now)) {
|
||||
void refreshUpdateCache({
|
||||
cache,
|
||||
fetchDistTags,
|
||||
homeDir: options.homeDir,
|
||||
installedVersion: options.installedVersion,
|
||||
now,
|
||||
}).catch(() => {});
|
||||
}
|
||||
|
||||
return { notice };
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue