From 0a03177a2273926d29674d6ad4631a9241656a13 Mon Sep 17 00:00:00 2001 From: m1ngsama Date: Wed, 18 Nov 2026 15:35:11 +0800 Subject: [PATCH 1/3] fix(update): wait longer for npm and say why a check failed --- scripts/test-cli.sh | 2 +- src/features/update.test.ts | 46 +++++++++++++++++++++++++ src/features/update.ts | 69 ++++++++++++++++++++++--------------- src/i18n/index.ts | 2 ++ src/i18n/locales/en.json | 2 ++ src/i18n/locales/zh.json | 2 ++ 6 files changed, 95 insertions(+), 28 deletions(-) create mode 100644 src/features/update.test.ts diff --git a/scripts/test-cli.sh b/scripts/test-cli.sh index d85f46e..8ca7b7d 100644 --- a/scripts/test-cli.sh +++ b/scripts/test-cli.sh @@ -146,7 +146,7 @@ assert_fails_with update-arguments 'Unexpected arguments for update.' node dist/ update_down_import='--import=data:text/javascript,globalThis.fetch=async()=>new%20Response(null,{status:503})' assert_fails_with update-network 'Could not check for updates' env NODE_OPTIONS="$update_down_import" node dist/index.js update --plain update_reject_import='--import=data:text/javascript,globalThis.fetch=async()=>{throw%20Error(%22offline%22)}' -assert_fails_with update-reject 'Could not check for updates' env NODE_OPTIONS="$update_reject_import" node dist/index.js update --plain +assert_fails_with update-reject 'Could not reach npm to check for updates.' env NODE_OPTIONS="$update_reject_import" node dist/index.js update --plain assert_fails_with version-arguments 'Unexpected arguments for version.' node dist/index.js version extra assert_fails_with help-arguments 'Unexpected arguments for help.' node dist/index.js help extra diff --git a/src/features/update.test.ts b/src/features/update.test.ts new file mode 100644 index 0000000..12662c4 --- /dev/null +++ b/src/features/update.test.ts @@ -0,0 +1,46 @@ +import { describe, it, expect, vi } from 'vitest'; +import { fetchLatestVersion } from './update.js'; + +const ok = (version: unknown) => + Promise.resolve(new Response(JSON.stringify({ version }), { status: 200 })); + +describe('fetchLatestVersion', () => { + it('returns the published version', async () => { + expect(await fetchLatestVersion(() => ok('1.6.1'))).toEqual({ version: '1.6.1' }); + }); + + it('retries a dropped connection once', async () => { + const fetcher = vi + .fn() + .mockRejectedValueOnce(new TypeError('fetch failed')) + .mockImplementationOnce(() => ok('1.6.1')); + expect(await fetchLatestVersion(fetcher)).toEqual({ version: '1.6.1' }); + expect(fetcher).toHaveBeenCalledTimes(2); + }); + + it('reports a connection that keeps failing as offline', async () => { + const fetcher = vi.fn().mockRejectedValue(new TypeError('fetch failed')); + expect(await fetchLatestVersion(fetcher)).toEqual({ error: 'network' }); + expect(fetcher).toHaveBeenCalledTimes(2); + }); + + it('gives up after a timeout without waiting a second time', async () => { + const fetcher = vi.fn( + (_url, init) => + new Promise((_resolve, reject) => { + init?.signal?.addEventListener('abort', () => { + reject(init.signal?.reason as Error); + }); + }), + ); + expect(await fetchLatestVersion(fetcher, 20)).toEqual({ error: 'timeout' }); + expect(fetcher).toHaveBeenCalledTimes(1); + }); + + it('treats an error status or a malformed body as a bad response', async () => { + expect( + await fetchLatestVersion(() => Promise.resolve(new Response('', { status: 503 }))), + ).toEqual({ error: 'response' }); + expect(await fetchLatestVersion(() => ok(42))).toEqual({ error: 'response' }); + }); +}); diff --git a/src/features/update.ts b/src/features/update.ts index d9cd083..03379d1 100644 --- a/src/features/update.ts +++ b/src/features/update.ts @@ -3,30 +3,36 @@ import { APP_INFO } from '../config/data.js'; import { t, fmt } from '../i18n/index.js'; const NPM_REGISTRY_URL = `https://registry.npmjs.org/@nbtca/prompt/latest`; +// The registry can take over 4 seconds to answer from mainland China, so a tight limit fails healthy checks. +const ATTEMPT_TIMEOUT_MS = 8000; +const ATTEMPTS = 2; interface NpmLatest { version?: unknown; } -async function fetchLatestVersion(): Promise { - const controller = new AbortController(); - const timeout = setTimeout(() => { - controller.abort(); - }, 3000); - timeout.unref(); - try { - const res = await fetch(NPM_REGISTRY_URL, { - signal: controller.signal, - headers: { Accept: 'application/json' }, - }); - if (!res.ok) return null; - const data = (await res.json()) as NpmLatest; - return typeof data.version === 'string' ? data.version : null; - } catch { - return null; - } finally { - clearTimeout(timeout); +export type LatestVersion = { version: string } | { error: 'timeout' | 'network' | 'response' }; + +/** Retries a connection error once; a timeout already spent the wait, so it is not retried. */ +export async function fetchLatestVersion( + fetcher: typeof fetch = fetch, + timeoutMs = ATTEMPT_TIMEOUT_MS, +): Promise { + for (let attempt = 0; attempt < ATTEMPTS; attempt++) { + try { + const res = await fetcher(NPM_REGISTRY_URL, { + signal: AbortSignal.timeout(timeoutMs), + headers: { Accept: 'application/json' }, + }); + if (!res.ok) return { error: 'response' }; + const data = (await res.json()) as NpmLatest; + return typeof data.version === 'string' ? { version: data.version } : { error: 'response' }; + } catch (error) { + if (error instanceof DOMException && error.name === 'TimeoutError') + return { error: 'timeout' }; + } } + return { error: 'network' }; } function isNewer(local: string, remote: string): boolean { @@ -40,20 +46,29 @@ function isNewer(local: string, remote: string): boolean { return false; } -export async function runUpdateCheck(): Promise { - const trans = t(); - const latest = await fetchLatestVersion(); +export async function runUpdateCheck(fetcher?: typeof fetch): Promise { + const trans = t().update; + const latest = await fetchLatestVersion(fetcher); - if (!latest) { - console.error(chalk.yellow(trans.update.checkFailed)); + if ('error' in latest) { + const reason = + latest.error === 'timeout' + ? trans.checkTimedOut + : latest.error === 'network' + ? trans.checkOffline + : trans.checkFailed; + console.error(chalk.yellow(reason)); + console.error(chalk.dim(trans.command)); return false; } - if (isNewer(APP_INFO.version, latest)) { - console.log(chalk.yellow(fmt(trans.update.available, { latest, current: APP_INFO.version }))); - console.log(chalk.dim(trans.update.command)); + if (isNewer(APP_INFO.version, latest.version)) { + console.log( + chalk.yellow(fmt(trans.available, { latest: latest.version, current: APP_INFO.version })), + ); + console.log(chalk.dim(trans.command)); } else { - console.log(chalk.green(fmt(trans.update.upToDate, { version: APP_INFO.version }))); + console.log(chalk.green(fmt(trans.upToDate, { version: APP_INFO.version }))); } return true; } diff --git a/src/i18n/index.ts b/src/i18n/index.ts index b636cee..465c19a 100644 --- a/src/i18n/index.ts +++ b/src/i18n/index.ts @@ -460,6 +460,8 @@ export interface Translations { available: string; upToDate: string; checkFailed: string; + checkTimedOut: string; + checkOffline: string; command: string; }; cli: { diff --git a/src/i18n/locales/en.json b/src/i18n/locales/en.json index 5308ebb..78c9078 100644 --- a/src/i18n/locales/en.json +++ b/src/i18n/locales/en.json @@ -540,6 +540,8 @@ "available": "Update available: {current} → {latest}", "upToDate": "You are on the latest version ({version})", "checkFailed": "Could not check for updates", + "checkTimedOut": "Timed out reaching npm, so no update check was made.", + "checkOffline": "Could not reach npm to check for updates.", "command": "Run: npm i -g @nbtca/prompt" }, "cli": { diff --git a/src/i18n/locales/zh.json b/src/i18n/locales/zh.json index 0360c75..424203f 100644 --- a/src/i18n/locales/zh.json +++ b/src/i18n/locales/zh.json @@ -540,6 +540,8 @@ "available": "有新版本可用:{current} → {latest}", "upToDate": "已是最新版本({version})", "checkFailed": "无法检查更新", + "checkTimedOut": "连接 npm 超时,无法检查更新。", + "checkOffline": "无法连接 npm,检查更新失败。", "command": "运行:npm i -g @nbtca/prompt" }, "cli": { From d4e9cd578fb37d376467db8e57523e9c5cd057c0 Mon Sep 17 00:00:00 2001 From: m1ngsama Date: Wed, 18 Nov 2026 15:42:47 +0800 Subject: [PATCH 2/3] fix(calendar): show an occurrence shared by two UIDs once --- src/features/calendar.ts | 80 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 78 insertions(+), 2 deletions(-) diff --git a/src/features/calendar.ts b/src/features/calendar.ts index 9fd43e1..db62798 100644 --- a/src/features/calendar.ts +++ b/src/features/calendar.ts @@ -7,7 +7,13 @@ import { eventToICS, SCHOOL_FEED_URL, } from '@nbtca/nbtcal'; -import type { Calendar, CalendarEvent, FeedValidators, HeatmapBucket } from '@nbtca/nbtcal'; +import type { + Calendar, + CalendarEvent, + FeedValidators, + HeatmapBucket, + HeatmapOptions, +} from '@nbtca/nbtcal'; import chalk from 'chalk'; import { c, type, space, glyph, bodyWidth } from '../core/theme.js'; import { pickIcon } from '../core/icons.js'; @@ -73,13 +79,83 @@ function formatTime(date: Date): string { } const MEMO_TTL_MS = 5 * 60 * 1000; +const DAY_MS = 86_400_000; + +const occurrenceKey = (event: CalendarEvent): string => + [event.title, event.start.getTime(), event.end?.getTime(), event.location].join('\u0000'); + +function splitDuplicates(events: CalendarEvent[]): { + unique: CalendarEvent[]; + repeats: CalendarEvent[]; +} { + const seen = new Set(); + const unique: CalendarEvent[] = []; + const repeats: CalendarEvent[] = []; + for (const event of events) { + const key = occurrenceKey(event); + (seen.has(key) ? repeats : unique).push(event); + seen.add(key); + } + return { unique, repeats }; +} + +/** The heatmap bucket an occurrence falls in, matching nbtcal: all-day events by their local date. */ +function heatmapKey(event: CalendarEvent, options: HeatmapOptions): string { + const day = event.isAllDay + ? `${event.start.getFullYear()}-${String(event.start.getMonth() + 1).padStart(2, '0')}-${String(event.start.getDate()).padStart(2, '0')}` + : new Intl.DateTimeFormat('en-CA', { + timeZone: options.timeZone ?? 'Asia/Shanghai', + year: 'numeric', + month: '2-digit', + day: '2-digit', + }).format(event.start); + if (options.bucket !== 'week') return day; + const proxy = new Date(`${day}T00:00:00Z`); + proxy.setUTCDate(proxy.getUTCDate() - ((proxy.getUTCDay() + 6) % 7)); + return proxy.toISOString().slice(0, 10); +} + +// The club feed carries some series twice under different UIDs (once per calendar app), so the +// same occurrence would show, and count, twice. +export function withoutDuplicateOccurrences(calendar: Calendar): Calendar { + const unique = (events: CalendarEvent[]) => splitDuplicates(events).unique; + return { + upcoming: (options) => unique(calendar.upcoming(options)), + past: (options) => unique(calendar.past(options)), + next: (count) => unique(calendar.next(count)), + inRange: (start, end) => unique(calendar.inRange(start, end)), + heatmap: (options) => { + const buckets = calendar.heatmap(options); + const { repeats } = splitDuplicates( + calendar.inRange( + new Date(options.start.getTime() - 2 * DAY_MS), + new Date(options.end.getTime() + 2 * DAY_MS), + ), + ); + if (repeats.length === 0) return buckets; + const extra = new Map(); + for (const event of repeats) { + const key = heatmapKey(event, options); + extra.set(key, (extra.get(key) ?? 0) + 1); + } + return buckets.map((bucket) => ({ + ...bucket, + count: Math.max(0, bucket.count - (extra.get(bucket.date) ?? 0)), + })); + }, + }; +} function feedLoader(url: string | undefined, name: string) { let memo: { calendar: Calendar; validators: FeedValidators; fetchedAt: number } | undefined; let inFlight: Promise | undefined; function remember(text: string, validators: FeedValidators, fetchedAt: number): Calendar { - memo = { calendar: createCalendar(parseCalendar(text)), validators, fetchedAt }; + memo = { + calendar: withoutDuplicateOccurrences(createCalendar(parseCalendar(text))), + validators, + fetchedAt, + }; return memo.calendar; } From 5cb0ae183509046811a7df0f76e1e1971c5143bb Mon Sep 17 00:00:00 2001 From: m1ngsama Date: Wed, 18 Nov 2026 15:42:48 +0800 Subject: [PATCH 3/3] test(calendar): cover duplicate series and pin the countdown to campus time --- src/features/calendar.test.ts | 49 ++++++++++++++++++++++++++++++++--- 1 file changed, 46 insertions(+), 3 deletions(-) diff --git a/src/features/calendar.test.ts b/src/features/calendar.test.ts index 6513620..cd5af4b 100644 --- a/src/features/calendar.test.ts +++ b/src/features/calendar.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect, beforeAll } from 'vitest'; -import type { CalendarEvent } from '@nbtca/nbtcal'; +import { createCalendar, parseCalendar, type CalendarEvent } from '@nbtca/nbtcal'; import { toDisplayEvent, renderEventsTable, @@ -8,6 +8,7 @@ import { renderEventBriefLines, exportEventIcs, eventTimeRange, + withoutDuplicateOccurrences, } from './calendar.js'; import chalk from 'chalk'; import { setLanguage } from '../i18n/index.js'; @@ -319,8 +320,8 @@ describe('renderCountdownBanner', () => { it('spells the countdown out in Chinese', () => { setLanguage('zh'); try { - const event = toDisplayEvent(makeEvent({ start: new Date('2026-09-27T13:00:00') })); - const out = stripAnsi(renderCountdownBanner(event, new Date('2026-09-26T19:06:00'))); + const event = toDisplayEvent(makeEvent({ start: new Date('2026-09-27T13:00:00+08:00') })); + const out = stripAnsi(renderCountdownBanner(event, new Date('2026-09-26T19:06:00+08:00'))); expect(out).toContain('还有 17 小时 54 分钟'); } finally { setLanguage('en'); @@ -432,3 +433,45 @@ describe('eventTimeRange', () => { expect(eventTimeRange(threeDays)).toBe('06-17 – 06-19'); }); }); + +describe('withoutDuplicateOccurrences', () => { + const series = (uid: string) => + [ + 'BEGIN:VEVENT', + `UID:${uid}`, + 'DTSTART:20261113T123000Z', + 'DTEND:20261113T143000Z', + 'RRULE:FREQ=WEEKLY;INTERVAL=2;BYDAY=FR', + 'SUMMARY:NWDC', + 'END:VEVENT', + ].join('\r\n'); + const feed = [ + 'BEGIN:VCALENDAR', + 'VERSION:2.0', + series('apple-uid'), + series('google-uid'), + 'BEGIN:VEVENT', + 'UID:other', + 'DTSTART:20261127T123000Z', + 'DTEND:20261127T143000Z', + 'SUMMARY:Study group', + 'END:VEVENT', + 'END:VCALENDAR', + ].join('\r\n'); + const calendar = withoutDuplicateOccurrences(createCalendar(parseCalendar(feed))); + const start = new Date('2026-11-01T00:00:00+08:00'); + const end = new Date('2026-12-01T00:00:00+08:00'); + + it('lists an occurrence that two UIDs share once', () => { + const titles = calendar.inRange(start, end).map((event) => event.title); + expect(titles).toEqual(['NWDC', 'NWDC', 'Study group']); + }); + + it('counts it once in day and week heatmaps', () => { + const days = calendar.heatmap({ start, end, bucket: 'day' }); + expect(days.find((bucket) => bucket.date === '2026-11-27')?.count).toBe(2); + expect(days.find((bucket) => bucket.date === '2026-11-13')?.count).toBe(1); + const weeks = calendar.heatmap({ start, end, bucket: 'week' }); + expect(weeks.find((bucket) => bucket.date === '2026-11-23')?.count).toBe(2); + }); +});