Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion scripts/test-cli.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
49 changes: 46 additions & 3 deletions src/features/calendar.test.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -8,6 +8,7 @@ import {
renderEventBriefLines,
exportEventIcs,
eventTimeRange,
withoutDuplicateOccurrences,
} from './calendar.js';
import chalk from 'chalk';
import { setLanguage } from '../i18n/index.js';
Expand Down Expand Up @@ -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');
Expand Down Expand Up @@ -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);
});
});
80 changes: 78 additions & 2 deletions src/features/calendar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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<string>();
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<string, number>();
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<Calendar> | 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;
}

Expand Down
46 changes: 46 additions & 0 deletions src/features/update.test.ts
Original file line number Diff line number Diff line change
@@ -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<typeof fetch>()
.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<typeof fetch>().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<typeof fetch>(
(_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' });
});
});
69 changes: 42 additions & 27 deletions src/features/update.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string | null> {
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<LatestVersion> {
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 {
Expand All @@ -40,20 +46,29 @@ function isNewer(local: string, remote: string): boolean {
return false;
}

export async function runUpdateCheck(): Promise<boolean> {
const trans = t();
const latest = await fetchLatestVersion();
export async function runUpdateCheck(fetcher?: typeof fetch): Promise<boolean> {
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;
}
2 changes: 2 additions & 0 deletions src/i18n/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -460,6 +460,8 @@ export interface Translations {
available: string;
upToDate: string;
checkFailed: string;
checkTimedOut: string;
checkOffline: string;
command: string;
};
cli: {
Expand Down
2 changes: 2 additions & 0 deletions src/i18n/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down
2 changes: 2 additions & 0 deletions src/i18n/locales/zh.json
Original file line number Diff line number Diff line change
Expand Up @@ -540,6 +540,8 @@
"available": "有新版本可用:{current} → {latest}",
"upToDate": "已是最新版本({version})",
"checkFailed": "无法检查更新",
"checkTimedOut": "连接 npm 超时,无法检查更新。",
"checkOffline": "无法连接 npm,检查更新失败。",
"command": "运行:npm i -g @nbtca/prompt"
},
"cli": {
Expand Down
Loading