@nbtca/prompt 1.5.19 → 1.5.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,72 +1,64 @@
1
1
  # NBTCA Prompt
2
2
 
3
- Terminal client for NBTCA events, documentation, status and personal timetables.
3
+ Club events, the school calendar, your campus timetable, and the NBTCA knowledge
4
+ base in one terminal app. What you have loaded stays readable offline.
4
5
 
5
6
  [![npm version](https://img.shields.io/npm/v/@nbtca/prompt)](https://www.npmjs.com/package/@nbtca/prompt)
6
7
  [![License](https://img.shields.io/npm/l/@nbtca/prompt)](LICENSE)
7
8
 
8
- ## Requirements
9
-
10
- - Node.js 20.12 or newer
9
+ ![The Events tab: the next event with a countdown, upcoming events, and browse options](.github/screenshot.webp)
11
10
 
12
11
  ## Install
13
12
 
13
+ Requires Node.js 20.12 or newer.
14
+
14
15
  ```bash
15
16
  npm install --global @nbtca/prompt
16
17
  nbtca
17
18
  ```
18
19
 
19
- Run a command without installing:
20
-
21
- ```bash
22
- npx @nbtca/prompt --help
23
- ```
20
+ Or try it without installing: `npx @nbtca/prompt`.
24
21
 
25
22
  ## Interactive mode
26
23
 
27
- Run `nbtca` with no arguments to open the full-screen client. Press `1`–`5` or
28
- `Tab` to switch tabs, and `?` to list every key.
24
+ `nbtca` opens a full-screen client. Press `1`–`5` or `Tab` to switch tabs, and
25
+ `?` to list every key.
29
26
 
30
27
  - **Home**: today's classes and the next club events.
31
- - **Schedule**: the current term, week, and next break from the school
32
- calendar. Log in to the campus system to see your timetable and export it as
33
- an `.ics` file.
34
- - **Events**: the next event with a countdown, plus week, month, search,
28
+ - **Schedule**: the current term, week, and next break. Log in to the campus
29
+ system to see your timetable and export it to any calendar app as `.ics`.
30
+ - **Events**: a countdown to the next event, plus week and month views, search,
35
31
  history, and a one-year activity heatmap.
36
- - **Docs**: the NBTCA knowledge base, readable and searchable in the terminal.
37
- It is cached locally and served from a mirror when GitHub is unreachable.
38
- - **Settings**: language, icon and color modes, and version info.
32
+ - **Docs**: read and search the knowledge base. It works even when GitHub is
33
+ unreachable.
34
+ - **Settings**: language, icons, and colors.
39
35
 
40
- Events, docs, and the school calendar stay readable offline from the last
41
- successful fetch.
36
+ The first load needs a network connection. Cached events and school calendars
37
+ remain available without an age limit; a failed refresh shows a cached-data notice.
38
+ Docs are available offline after reading them or loading them through search,
39
+ subject to the local cache's 4 MiB size limit.
42
40
 
43
41
  ## Commands
44
42
 
45
43
  ```text
46
- nbtca events [--today|--week|--month] [--search=<q>] [--next=<n>] [--json]
47
- nbtca events --heatmap
44
+ nbtca events [--today|--week|--month] [--search=<q>] [--json]
45
+ nbtca schedule login|terms|export|logout
46
+ nbtca status [--watch]
48
47
  nbtca docs
49
- nbtca status [--watch] [--json]
50
- nbtca schedule login
51
- nbtca schedule status
52
- nbtca schedule terms
53
- nbtca schedule export --term=2026:3 --week-one=YYYY-MM-DD [--output=<path>]
54
- nbtca schedule logout
55
48
  nbtca website|github|roadmap|repair [--open]
56
- nbtca theme icon auto|ascii|unicode
57
- nbtca theme color auto|on|off
58
- nbtca theme reset
59
49
  nbtca lang zh|en
60
50
  nbtca update
61
51
  ```
62
52
 
63
- `nbtca --help` lists every flag. Use `--plain` for stable output without color
64
- and `--no-logo` to skip the startup logo. `schedule export --one-shot` avoids
65
- reading or saving a campus session.
53
+ `nbtca --help` lists every command and flag. Add `--plain` for output without
54
+ color.
55
+
56
+ Service checks wait up to 15 seconds by default. Use `--timeout=<ms>` to change
57
+ the limit. A timeout is shown separately from an offline result and appears as
58
+ `timedOut: true` in JSON. Failed public checks still return a nonzero exit code.
66
59
 
67
- Prompt never stores passwords. Persisted sessions contain only a masked account
68
- hint and a CookieJar, protected with user-only permissions on POSIX systems.
69
- Treat exported calendars and session files as private data. See [SECURITY.md](SECURITY.md).
60
+ Prompt never stores your password. A saved campus session gets user-only file
61
+ permissions. See [SECURITY.md](SECURITY.md).
70
62
 
71
63
  ## Development
72
64
 
@@ -75,9 +67,6 @@ npm ci
75
67
  npm run check
76
68
  ```
77
69
 
78
- `check` runs formatting, lint, full TypeScript validation, tests, build, package
79
- consumer checks and dependency audit.
80
-
81
70
  ## License
82
71
 
83
72
  MIT
@@ -7,6 +7,7 @@ import { renderNextClassBanner, renderWeekGrid, renderUnresolvedItems, renderTod
7
7
  import { sanitizeTerminalLine, truncate, truncateStart, visualWidth, wrapAnsiWithIndent, } from '../../core/text.js';
8
8
  import { isoDayDifference } from '../../core/calendar-day.js';
9
9
  import { loadingLines } from '../../core/components/spinner.js';
10
+ import { offlineNotice } from '../chrome.js';
10
11
  function heading(label) {
11
12
  return `${space.indent}${type.heading(label)}`;
12
13
  }
@@ -260,7 +261,7 @@ function daysUntil(now, date) {
260
261
  }
261
262
  function renderPublicBody(state, now, bodyRows, cols) {
262
263
  const trans = t();
263
- const lines = [];
264
+ const lines = state.publicStale ? offlineNotice(cols) : [];
264
265
  const w = state.publicWindow;
265
266
  if (w === undefined) {
266
267
  lines.push(...loadingLines(trans.common.loading, cols));
@@ -14,7 +14,7 @@ import { loginWithStudentPassword, restoreNbtSession, } from '../../auth/nbt-aut
14
14
  import { createSessionStore } from '../../auth/session-store.js';
15
15
  import { resolveTerm, relevantTerms, writePrivateIcs, isSessionExpired, JWXT_ORIGIN, safeMessage, } from '../../features/student-timetable.js';
16
16
  import { termKey, loadWeekOne, saveWeekOne, saveTimetableCache, saveCurrentPointer, loadCurrentPointer, loadTimetableCache, clearScheduleCache, } from '../../features/schedule-store.js';
17
- import { loadSchoolCalendar } from '../../features/calendar.js';
17
+ import { loadSchoolCalendarOrCache } from '../../features/calendar.js';
18
18
  import { currentAcademicWindow, inferWeekOneMonday, } from '@nbtca/nbtcal';
19
19
  import { sanitizeAcademicTerm, sanitizeTimetable } from '../../features/timetable-sanitize.js';
20
20
  import { addLocalDays, parseLocalMonday } from '../../core/calendar-day.js';
@@ -121,13 +121,13 @@ async function goToPublic(ctx, generation = lifecycleGeneration) {
121
121
  state = { mode: 'public', publicField: buildPublicField() };
122
122
  ctx.rerender();
123
123
  try {
124
- const cal = await loadSchoolCalendar(ctx.signal);
124
+ const { calendar: cal, stale } = await loadSchoolCalendarOrCache(ctx.signal);
125
125
  if (!isLifecycleActive(ctx, generation))
126
126
  return;
127
127
  const now = new Date();
128
128
  const windowEvents = cal.inRange(addLocalDays(now, -400), addLocalDays(now, 400));
129
129
  const publicWindow = currentAcademicWindow(windowEvents, now);
130
- state = { ...state, publicWindow };
130
+ state = { ...state, publicWindow, publicStale: stale };
131
131
  }
132
132
  catch {
133
133
  if (!isLifecycleActive(ctx, generation))
@@ -139,7 +139,7 @@ async function goToPublic(ctx, generation = lifecycleGeneration) {
139
139
  }
140
140
  async function tryInferWeekOne(ctx, generation) {
141
141
  try {
142
- const cal = await loadSchoolCalendar(ctx.signal);
142
+ const { calendar: cal } = await loadSchoolCalendarOrCache(ctx.signal);
143
143
  if (!isLifecycleActive(ctx, generation))
144
144
  return null;
145
145
  const now = new Date();
package/dist/cli.js CHANGED
@@ -3,7 +3,7 @@ import { main } from './main.js';
3
3
  import { loadCalendarOrCache, renderEventsTable, serializeEvents, toDisplayEvent, yearHeatmap, } from './features/calendar.js';
4
4
  import { renderHeatmap } from './features/calendar-heatmap.js';
5
5
  import { currentEvents, dayRange, monthRange, weekRange } from './features/calendar-query.js';
6
- import { checkServices, countServiceHealth, hasServiceFailures, renderServiceStatusTable, serializeServiceStatus, } from './features/status.js';
6
+ import { checkServices, DEFAULT_STATUS_TIMEOUT_MS, countServiceHealth, hasServiceFailures, renderServiceStatusTable, serializeServiceStatus, } from './features/status.js';
7
7
  import { pickIcon } from './core/icons.js';
8
8
  import { applyColorModePreference } from './config/preferences.js';
9
9
  import { openDocsInBrowser } from './features/docs.js';
@@ -314,7 +314,7 @@ async function runStatusCommand(flags) {
314
314
  : 10;
315
315
  const timeoutMs = timeoutFlag
316
316
  ? parseAsciiDecimalInteger(timeoutFlag.slice('--timeout='.length))
317
- : 6000;
317
+ : DEFAULT_STATUS_TIMEOUT_MS;
318
318
  const retries = retriesFlag
319
319
  ? parseAsciiDecimalInteger(retriesFlag.slice('--retries='.length))
320
320
  : 1;
@@ -374,7 +374,7 @@ async function runStatusCommand(flags) {
374
374
  const health = countServiceHealth(services);
375
375
  clearScreen();
376
376
  console.log(chalk.bold(`${trans.status.watchUpdated}: ${new Date().toLocaleString()}`));
377
- console.log(chalk.dim(`${trans.status.up}: ${health.up} | ${trans.status.down}: ${health.down} | ${trans.status.watchHint}`));
377
+ console.log(chalk.dim(`${trans.status.up}: ${health.up} | ${trans.status.down}: ${health.down} | ${trans.status.timeout}: ${health.timedOut} | ${trans.status.watchHint}`));
378
378
  console.log();
379
379
  const useColor = !flags.has('--plain') && isTty(process.stdout.isTTY);
380
380
  console.log(renderServiceStatusTable(services, { color: useColor }));
@@ -1,7 +1,6 @@
1
1
  import fs from 'fs';
2
2
  import path from 'path';
3
3
  import { getStateDir, getWritableStateDir } from '../config/paths.js';
4
- const MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
5
4
  const HEADER_VALUE = /^[\x21-\x7e][\x20-\x7e]*$/;
6
5
  function headerValue(value) {
7
6
  return typeof value === 'string' && HEADER_VALUE.test(value) ? value : undefined;
@@ -42,13 +41,11 @@ export function touchFeedCache(name, validators, dir) {
42
41
  /* best effort */
43
42
  }
44
43
  }
45
- export function loadFeedCache(name, dir, maxAgeMs = MAX_AGE_MS) {
44
+ export function loadFeedCache(name, dir) {
46
45
  try {
47
46
  const source = dir ?? getStateDir();
48
47
  const validators = readValidators(name, source);
49
48
  const file = path.join(source, `${name}.ics`);
50
- if (Date.now() - fs.statSync(file).mtimeMs > maxAgeMs)
51
- return null;
52
49
  return { text: fs.readFileSync(file, 'utf8'), validators };
53
50
  }
54
51
  catch {
@@ -76,23 +76,25 @@ function feedLoader(url, name) {
76
76
  });
77
77
  return inFlight;
78
78
  }
79
- return { peek, load };
79
+ async function loadOrCache(signal) {
80
+ try {
81
+ return { calendar: await load(signal), stale: false };
82
+ }
83
+ catch (err) {
84
+ const cached = peek();
85
+ if (!cached)
86
+ throw err;
87
+ return { calendar: cached, stale: true };
88
+ }
89
+ }
90
+ return { peek, load, loadOrCache };
80
91
  }
81
92
  const eventsFeed = feedLoader(undefined, 'calendar-feed');
82
93
  const schoolFeed = feedLoader(SCHOOL_FEED_URL, 'school-feed');
83
94
  export const peekCalendar = eventsFeed.peek;
84
95
  export const loadCalendarOrThrow = eventsFeed.load;
85
- export async function loadSchoolCalendar(signal) {
86
- try {
87
- return await schoolFeed.load(signal);
88
- }
89
- catch (err) {
90
- const cached = schoolFeed.peek();
91
- if (!cached)
92
- throw err;
93
- return cached;
94
- }
95
- }
96
+ export const loadCalendarOrCache = eventsFeed.loadOrCache;
97
+ export const loadSchoolCalendarOrCache = schoolFeed.loadOrCache;
96
98
  export function toDisplayEvent(e) {
97
99
  const trans = t();
98
100
  return {
@@ -122,17 +124,6 @@ export function eventTimeRange(e) {
122
124
  ? `${start}${dash}${formatTime(e.end)}`
123
125
  : `${start} ${dash} ${endDate} ${formatTime(e.end)}`;
124
126
  }
125
- export async function loadCalendarOrCache(signal) {
126
- try {
127
- return { calendar: await loadCalendarOrThrow(signal), stale: false };
128
- }
129
- catch (err) {
130
- const cached = peekCalendar();
131
- if (!cached)
132
- throw err;
133
- return { calendar: cached, stale: true };
134
- }
135
- }
136
127
  export function yearHeatmap(calendar, now) {
137
128
  return calendar.heatmap({ ...pastYearRange(now), bucket: 'day' });
138
129
  }
@@ -4,6 +4,7 @@ import { pickIcon } from '../core/icons.js';
4
4
  import { padEndV, sanitizeTerminalLine, visualWidth } from '../core/text.js';
5
5
  import { c } from '../core/theme.js';
6
6
  import { t } from '../i18n/index.js';
7
+ export const DEFAULT_STATUS_TIMEOUT_MS = 15_000;
7
8
  function abortError(signal) {
8
9
  return signal.reason instanceof Error
9
10
  ? signal.reason
@@ -80,6 +81,7 @@ function getServiceTargets() {
80
81
  async function checkService(name, url, timeoutMs, signal) {
81
82
  const start = Date.now();
82
83
  const controller = new AbortController();
84
+ const timeoutReason = Symbol('timeout');
83
85
  const onAbort = () => {
84
86
  controller.abort(signal?.reason);
85
87
  };
@@ -87,7 +89,7 @@ async function checkService(name, url, timeoutMs, signal) {
87
89
  if (signal?.aborted)
88
90
  onAbort();
89
91
  const timeout = setTimeout(() => {
90
- controller.abort();
92
+ controller.abort(timeoutReason);
91
93
  }, timeoutMs);
92
94
  let response;
93
95
  try {
@@ -106,12 +108,9 @@ async function checkService(name, url, timeoutMs, signal) {
106
108
  if (signal?.aborted)
107
109
  throw abortError(signal);
108
110
  const latencyMs = Date.now() - start;
109
- const error = sanitizeTerminalLine(err instanceof Error
110
- ? err.name === 'AbortError'
111
- ? 'Request timed out'
112
- : err.message
113
- : String(err));
114
- return { name, url, ok: false, latencyMs, error };
111
+ const timedOut = controller.signal.reason === timeoutReason;
112
+ const error = sanitizeTerminalLine(timedOut ? 'Request timed out' : err instanceof Error ? err.message : String(err));
113
+ return { name, url, ok: false, latencyMs, error, ...(timedOut ? { timedOut } : {}) };
115
114
  }
116
115
  finally {
117
116
  clearTimeout(timeout);
@@ -141,7 +140,7 @@ async function checkServiceWithRetry(target, timeoutMs, retries, signal) {
141
140
  };
142
141
  }
143
142
  export async function checkServices(options = {}) {
144
- const timeoutMs = options.timeoutMs ?? 6000;
143
+ const timeoutMs = options.timeoutMs ?? DEFAULT_STATUS_TIMEOUT_MS;
145
144
  const retries = options.retries ?? 1;
146
145
  if (options.signal?.aborted)
147
146
  throw abortError(options.signal);
@@ -157,6 +156,7 @@ export function serializeServiceStatus(items) {
157
156
  statusCode: item.statusCode ?? null,
158
157
  latencyMs: item.latencyMs ?? null,
159
158
  error: item.error ?? null,
159
+ timedOut: item.timedOut ?? false,
160
160
  group: item.group ?? null,
161
161
  intranet: item.intranet ?? false,
162
162
  }));
@@ -167,13 +167,16 @@ export function hasServiceFailures(items) {
167
167
  export function countServiceHealth(items) {
168
168
  let up = 0;
169
169
  let down = 0;
170
+ let timedOut = 0;
170
171
  for (const item of items.filter((i) => !i.intranet)) {
171
172
  if (item.ok)
172
173
  up++;
174
+ else if (item.timedOut)
175
+ timedOut++;
173
176
  else
174
177
  down++;
175
178
  }
176
- return { up, down };
179
+ return { up, down, timedOut };
177
180
  }
178
181
  export function renderServiceStatusTable(items, options) {
179
182
  const useColor = options?.color !== false;
@@ -181,11 +184,12 @@ export function renderServiceStatusTable(items, options) {
181
184
  const applyDim = useColor ? chalk.dim : id;
182
185
  const applyGreen = useColor ? chalk.green : id;
183
186
  const applyRed = useColor ? chalk.red : id;
187
+ const applyYellow = useColor ? chalk.yellow : id;
184
188
  const applyCyan = useColor ? chalk.cyan : id;
185
189
  const applyLatency = useColor ? c.latency : (ms) => `${ms}ms`;
186
190
  const trans = t();
187
191
  const nameWidth = Math.max(...items.map((i) => visualWidth(i.name)), visualWidth(trans.status.service));
188
- const statusWidth = 10;
192
+ const statusWidth = Math.max(10, visualWidth(trans.status.timeout) + 2);
189
193
  const onIcon = pickIcon('●', '+');
190
194
  const offIcon = pickIcon('✕', '!');
191
195
  const lanIcon = pickIcon('○', 'o');
@@ -219,6 +223,9 @@ export function renderServiceStatusTable(items, options) {
219
223
  else if (item.ok) {
220
224
  statusLabel = applyGreen(`${onIcon} ${trans.status.up}`);
221
225
  }
226
+ else if (item.timedOut) {
227
+ statusLabel = (item.intranet ? applyDim : applyYellow)(`${offIcon} ${trans.status.timeout}`);
228
+ }
222
229
  else if (item.intranet) {
223
230
  statusLabel = applyDim(`${lanIcon} ${trans.status.down}`);
224
231
  }
@@ -9,7 +9,7 @@
9
9
  "current": "current",
10
10
  "moreAbove": "{count} more above",
11
11
  "moreBelow": "{count} more below",
12
- "offline": "Offline, showing cached data"
12
+ "offline": "Refresh failed; showing cache"
13
13
  },
14
14
  "help": {
15
15
  "title": "Keys",
@@ -181,7 +181,7 @@
181
181
  "status": {
182
182
  "checking": "Checking service status...",
183
183
  "summaryOk": "All services are healthy",
184
- "summaryFail": "Some services are unavailable",
184
+ "summaryFail": "Some checks failed. A timeout does not confirm an outage.",
185
185
  "summaryIntranet": "Public services are healthy; intranet availability depends on your network",
186
186
  "service": "Service",
187
187
  "health": "Health",
@@ -190,6 +190,7 @@
190
190
  "url": "URL",
191
191
  "up": "online",
192
192
  "down": "offline",
193
+ "timeout": "timed out",
193
194
  "groupNbtca": "NBTCA Services",
194
195
  "groupExternal": "External",
195
196
  "groupIntranet": "Intranet (LAN only)",
@@ -9,7 +9,7 @@
9
9
  "current": "当前",
10
10
  "moreAbove": "上方还有 {count} 项",
11
11
  "moreBelow": "下方还有 {count} 项",
12
- "offline": "当前离线,显示的是上次获取的内容"
12
+ "offline": "无法刷新,显示上次获取的内容"
13
13
  },
14
14
  "help": {
15
15
  "title": "快捷键",
@@ -181,7 +181,7 @@
181
181
  "status": {
182
182
  "checking": "正在检查服务状态...",
183
183
  "summaryOk": "所有服务运行正常",
184
- "summaryFail": "部分服务不可用",
184
+ "summaryFail": "部分检查未通过,超时不代表服务已经停止运行。",
185
185
  "summaryIntranet": "公共服务运行正常;内网可用性取决于当前网络",
186
186
  "service": "服务",
187
187
  "health": "状态",
@@ -190,6 +190,7 @@
190
190
  "url": "URL",
191
191
  "up": "在线",
192
192
  "down": "离线",
193
+ "timeout": "超时",
193
194
  "groupNbtca": "NBTCA 服务",
194
195
  "groupExternal": "外部平台",
195
196
  "groupIntranet": "内网服务(仅校园网)",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nbtca/prompt",
3
- "version": "1.5.19",
3
+ "version": "1.5.20",
4
4
  "type": "module",
5
5
  "main": "dist/index.js",
6
6
  "exports": {
@@ -46,7 +46,7 @@
46
46
  "interactive"
47
47
  ],
48
48
  "dependencies": {
49
- "@nbtca/docs": "^0.3.4",
49
+ "@nbtca/docs": "^0.3.5",
50
50
  "@nbtca/nbtcal": "^0.4.4",
51
51
  "chalk": "^5.6.2",
52
52
  "marked": "^15.0.12"