mirror of
https://github.com/Kaelio/ktx.git
synced 2026-06-10 08:05: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
|
|
@ -3,6 +3,30 @@ import type { KtxCliIo } from './cli-runtime.js';
|
|||
|
||||
const ESC = String.fromCharCode(0x1b);
|
||||
|
||||
export interface CliStyleEnv {
|
||||
NO_COLOR?: string;
|
||||
TERM?: string;
|
||||
}
|
||||
|
||||
function ansiEnabled(env: CliStyleEnv = process.env): boolean {
|
||||
return !env.NO_COLOR && env.TERM !== 'dumb';
|
||||
}
|
||||
|
||||
function ansiColor(text: string, open: number, close: number, env?: CliStyleEnv): string {
|
||||
if (!ansiEnabled(env)) {
|
||||
return text;
|
||||
}
|
||||
return `${ESC}[${open}m${text}${ESC}[${close}m`;
|
||||
}
|
||||
|
||||
export function dim(text: string, env?: CliStyleEnv): string {
|
||||
return ansiColor(text, 2, 22, env);
|
||||
}
|
||||
|
||||
export function cyan(text: string, env?: CliStyleEnv): string {
|
||||
return ansiColor(text, 36, 39, env);
|
||||
}
|
||||
|
||||
export interface RailBufferedSource {
|
||||
stdoutText(): string;
|
||||
stderrText(): string;
|
||||
|
|
@ -61,11 +85,11 @@ export function createClackSpinner(): KtxCliSpinner {
|
|||
}
|
||||
|
||||
function magenta(text: string): string {
|
||||
return `${ESC}[35m${text}${ESC}[39m`;
|
||||
return ansiColor(text, 35, 39);
|
||||
}
|
||||
|
||||
function red(text: string): string {
|
||||
return `${ESC}[31m${text}${ESC}[39m`;
|
||||
return ansiColor(text, 31, 39);
|
||||
}
|
||||
|
||||
export function createStaticCliSpinner(io: KtxCliSpinnerIo): KtxCliSpinner {
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@ import { renderMissingProjectMessage } from './doctor.js';
|
|||
import { findNearestKtxProjectDir, resolveKtxProjectDir } from './project-resolver.js';
|
||||
import { profileMark, profileSpan } from './startup-profile.js';
|
||||
import type { CommandOutcome } from './telemetry/index.js';
|
||||
import { prepareUpdateCheckNotice, type PrepareUpdateCheckNoticeOptions } from './update-check/update-check.js';
|
||||
|
||||
profileMark('module:cli-program');
|
||||
|
||||
|
|
@ -39,6 +40,8 @@ interface KtxCommanderProgramOptions {
|
|||
runInit: (args: { projectDir: string; force: boolean }, io: KtxCliIo) => Promise<number>;
|
||||
}
|
||||
|
||||
type KtxCliUpdateCheckOptions = Pick<PrepareUpdateCheckNoticeOptions, 'env' | 'fetchDistTags' | 'homeDir' | 'now'>;
|
||||
|
||||
export interface BuildKtxProgramOptions {
|
||||
io: KtxCliIo;
|
||||
deps: KtxCliDeps;
|
||||
|
|
@ -47,6 +50,7 @@ export interface BuildKtxProgramOptions {
|
|||
setExitCode?: (code: number) => void;
|
||||
argv?: string[];
|
||||
setTelemetryModule?: (telemetry: typeof import('./telemetry/index.js')) => void;
|
||||
updateCheck?: KtxCliUpdateCheckOptions;
|
||||
}
|
||||
|
||||
type CommanderExitLike = { exitCode: number; code: string; message: string };
|
||||
|
|
@ -431,16 +435,29 @@ export function collectCommandFlagsPresent(command: CommandUnknownOpts): Record<
|
|||
|
||||
export function buildKtxProgram(options: BuildKtxProgramOptions): Command {
|
||||
const program = createBaseProgram(options.packageInfo, options.io);
|
||||
let pendingUpdateNotice: string | null = null;
|
||||
|
||||
program.hook('preAction', async (_thisCommand, actionCommand) => {
|
||||
// The hidden completion command must stay silent and side-effect free: skip
|
||||
// the telemetry notice, command span, and project checks entirely.
|
||||
// the telemetry notice, command span, project checks, and update checks entirely.
|
||||
if (commandPath(actionCommand as CommandPathNode).includes('__complete')) {
|
||||
return;
|
||||
}
|
||||
const commandNode = actionCommand as CommandPathNode;
|
||||
const updateCheck = await prepareUpdateCheckNotice({
|
||||
io: options.io,
|
||||
env: options.updateCheck?.env,
|
||||
fetchDistTags: options.updateCheck?.fetchDistTags,
|
||||
homeDir: options.updateCheck?.homeDir,
|
||||
installedVersion: options.packageInfo.version,
|
||||
now: options.updateCheck?.now,
|
||||
commandOptions: commandOptions(commandNode),
|
||||
});
|
||||
pendingUpdateNotice = updateCheck.notice;
|
||||
|
||||
const telemetry = await import('./telemetry/index.js');
|
||||
options.setTelemetryModule?.(telemetry);
|
||||
await telemetry.showTelemetryNoticeIfNeeded(options.io, options.packageInfo);
|
||||
const commandNode = actionCommand as CommandPathNode;
|
||||
const path = commandPath(commandNode);
|
||||
const projectDir = resolveCommandProjectDir(commandNode);
|
||||
const hasProject = ktxYamlExists(projectDir);
|
||||
|
|
@ -457,6 +474,13 @@ export function buildKtxProgram(options: BuildKtxProgramOptions): Command {
|
|||
ensureProjectAvailable(options.io, commandNode);
|
||||
});
|
||||
|
||||
program.hook('postAction', () => {
|
||||
if (pendingUpdateNotice) {
|
||||
options.io.stderr.write(pendingUpdateNotice);
|
||||
pendingUpdateNotice = null;
|
||||
}
|
||||
});
|
||||
|
||||
const context: KtxCliCommandContext = {
|
||||
io: options.io,
|
||||
deps: options.deps,
|
||||
|
|
|
|||
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