@nbtca/prompt 1.5.20 → 1.5.21

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,7 +1,8 @@
1
1
  # NBTCA Prompt
2
2
 
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.
3
+ Club events, the school calendar, your campus timetable, exams, grades, and the
4
+ NBTCA knowledge base in one terminal app. Cached public content and timetables
5
+ stay readable offline. Exam and grade queries require a connection.
5
6
 
6
7
  [![npm version](https://img.shields.io/npm/v/@nbtca/prompt)](https://www.npmjs.com/package/@nbtca/prompt)
7
8
  [![License](https://img.shields.io/npm/l/@nbtca/prompt)](LICENSE)
@@ -27,6 +28,8 @@ Or try it without installing: `npx @nbtca/prompt`.
27
28
  - **Home**: today's classes and the next club events.
28
29
  - **Schedule**: the current term, week, and next break. Log in to the campus
29
30
  system to see your timetable and export it to any calendar app as `.ics`.
31
+ Press `a` for personal exam arrangements or `g` for grades. Both are also
32
+ available from the public Schedule menu before login.
30
33
  - **Events**: a countdown to the next event, plus week and month views, search,
31
34
  history, and a one-year activity heatmap.
32
35
  - **Docs**: read and search the knowledge base. It works even when GitHub is
@@ -43,6 +46,9 @@ subject to the local cache's 4 MiB size limit.
43
46
  ```text
44
47
  nbtca events [--today|--week|--month] [--search=<q>] [--json]
45
48
  nbtca schedule login|terms|export|logout
49
+ nbtca exams [--term=2025-2] [--json] [--one-shot]
50
+ nbtca exams --output=exams.ics [--term=2025-2]
51
+ nbtca grades [--term=2025-2] [--json] [--one-shot]
46
52
  nbtca status [--watch]
47
53
  nbtca docs
48
54
  nbtca website|github|roadmap|repair [--open]
@@ -57,6 +63,19 @@ Service checks wait up to 15 seconds by default. Use `--timeout=<ms>` to change
57
63
  the limit. A timeout is shown separately from an offline result and appears as
58
64
  `timedOut: true` in JSON. Failed public checks still return a nonzero exit code.
59
65
 
66
+ Exam and grade queries default to the current term. Use `--term` to select
67
+ another term, or press `s` in the interactive results. Press `r` to refresh
68
+ or `x` to log out.
69
+ Exam times remain unavailable until the school publishes them. Grades retain
70
+ the school's original numeric or textual result; Prompt does not calculate an
71
+ overall GPA. Records stay in memory and are not cached. `--json` writes them to
72
+ standard output, so keep redirected output private.
73
+
74
+ Use `nbtca exams --output=exams.ics` to export a private calendar for a calendar
75
+ app. Export requires a published time for every exam; it fails before writing if
76
+ any time is unavailable. Authentication stays in Prompt. The `nbtcal/academic`
77
+ module owns academic queries, parsing, calendar conversion and ICS serialization.
78
+
60
79
  Prompt never stores your password. A saved campus session gets user-only file
61
80
  permissions. See [SECURITY.md](SECURITY.md).
62
81
 
@@ -67,6 +86,13 @@ npm ci
67
86
  npm run check
68
87
  ```
69
88
 
89
+ For unpublished changes shared with `nbtcal`, build and pack that repository,
90
+ then extract the candidate package into `node_modules/@nbtca/nbtcal` after
91
+ `npm ci`. Set `NBTCA_NBTCAL_TARBALL` to the tarball's absolute path when running
92
+ `npm run check` so the isolated package check uses the same candidate. `npm ci`
93
+ restores the published dependency. Publish `nbtcal` before updating Prompt's
94
+ registry dependency to the new API version.
95
+
70
96
  ## License
71
97
 
72
98
  MIT
package/SECURITY.md CHANGED
@@ -10,9 +10,14 @@ to the user's state directory with `0700` directory and `0600` file permissions
10
10
  on POSIX systems. Use `nbtca schedule logout` to remove it, or `--one-shot` to
11
11
  avoid reading or writing a session.
12
12
 
13
+ Exam and grade queries use allowlisted, read-only academic endpoints. Prompt
14
+ discards unrelated identity fields and does not cache these records. JSON output
15
+ contains personal academic information; redirected output and terminal scrollback
16
+ may retain it.
17
+
13
18
  Exported calendars may reveal a person's routine and location. Keep session and
14
19
  ICS files private.
15
20
 
16
21
  Report vulnerabilities through GitHub Security Advisories. Never include
17
- credentials, cookies, raw campus responses or personal calendars in public
18
- issues.
22
+ credentials, cookies, raw campus responses, exam arrangements, grades or personal
23
+ calendars in public issues.
@@ -30,6 +30,8 @@ export function hubShortcuts(tt) {
30
30
  { key: 't', label: trans.timetable.hubTermDensity },
31
31
  { key: 's', label: trans.timetable.hubSwitchTerm },
32
32
  { key: 'e', label: trans.timetable.hubExport },
33
+ { key: 'a', label: trans.records.exams },
34
+ { key: 'g', label: trans.records.grades },
33
35
  ];
34
36
  if (tt.unresolvedItems.length > 0) {
35
37
  shortcuts.push({
@@ -305,6 +307,8 @@ export function renderSchedule(state, now, bodyRows = 100, cols = 80) {
305
307
  return loadingLines(trans.common.loading, cols);
306
308
  case 'public':
307
309
  return renderPublicBody(state, now, bodyRows, cols);
310
+ case 'records':
311
+ return [];
308
312
  case 'needsLoginId':
309
313
  return [
310
314
  ...(state.errorMessage ? [...hintLines(state.errorMessage, cols), ''] : []),
@@ -18,11 +18,14 @@ 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';
21
+ import { StudentRecordsPanel } from './student-records.js';
21
22
  let state = { mode: 'loading' };
22
23
  let session = null;
23
24
  let client = null;
24
25
  let catalog = [];
25
26
  let pendingId = '';
27
+ let pendingRecordsKind = null;
28
+ let recordsPanel = null;
26
29
  let lifecycleGeneration = 0;
27
30
  const closingSessions = new WeakMap();
28
31
  function gridKeys() {
@@ -60,6 +63,7 @@ async function releaseSession(target = session) {
60
63
  if (session === target) {
61
64
  session = null;
62
65
  client = null;
66
+ catalog = [];
63
67
  }
64
68
  await closeSession(target);
65
69
  }
@@ -111,7 +115,11 @@ function goToLoginId(errorMessage) {
111
115
  }
112
116
  function buildPublicField() {
113
117
  return new ListField({
114
- options: [{ value: 'login', label: t().timetable.publicLoginAction }],
118
+ options: [
119
+ { value: 'login', label: t().timetable.publicLoginAction },
120
+ { value: 'exams', label: t().records.exams },
121
+ { value: 'grades', label: t().records.grades },
122
+ ],
115
123
  });
116
124
  }
117
125
  async function goToPublic(ctx, generation = lifecycleGeneration) {
@@ -169,6 +177,12 @@ async function afterAuthenticated(ctx, s, generation) {
169
177
  if (!isLifecycleActive(ctx, generation))
170
178
  return;
171
179
  catalog = nextCatalog;
180
+ if (pendingRecordsKind) {
181
+ const kind = pendingRecordsKind;
182
+ pendingRecordsKind = null;
183
+ await openStudentRecords(ctx, kind, generation);
184
+ return;
185
+ }
172
186
  const term = resolveTerm(catalog);
173
187
  const key = termKey(term);
174
188
  let weekOne = loadWeekOne(key);
@@ -279,11 +293,85 @@ async function refreshFromNetwork(ctx, generation) {
279
293
  }
280
294
  }
281
295
  }
296
+ async function openStudentRecords(ctx, kind, generation = ++lifecycleGeneration) {
297
+ if (!isLifecycleActive(ctx, generation))
298
+ return;
299
+ recordsPanel?.dispose();
300
+ recordsPanel = null;
301
+ pendingRecordsKind = kind;
302
+ try {
303
+ if (!session) {
304
+ const saved = createSessionStore().load();
305
+ if (!saved) {
306
+ goToLoginId();
307
+ ctx.rerender();
308
+ return;
309
+ }
310
+ state = { ...state, mode: 'loading' };
311
+ ctx.rerender();
312
+ const restored = await restoreNbtSession(saved);
313
+ await afterAuthenticated(ctx, restored, generation);
314
+ return;
315
+ }
316
+ if (catalog.length === 0) {
317
+ state = { ...state, mode: 'loading' };
318
+ ctx.rerender();
319
+ const nextCatalog = (await createNbtTimetableClient(session.timetableTransport, {
320
+ baseUrl: JWXT_ORIGIN,
321
+ }).listTerms(ctx.signal === undefined ? {} : { signal: ctx.signal })).map(sanitizeAcademicTerm);
322
+ if (!isLifecycleActive(ctx, generation))
323
+ return;
324
+ catalog = nextCatalog;
325
+ }
326
+ const previousTerm = state.term ?? state.timetable?.term;
327
+ const selected = catalog.find((term) => term.academicYear === previousTerm?.academicYear &&
328
+ term.semester === previousTerm.semester) ?? resolveTerm(catalog);
329
+ pendingRecordsKind = null;
330
+ const panel = new StudentRecordsPanel(kind, selected, relevantTerms(catalog), session.timetableTransport, () => isLifecycleActive(ctx, generation) && recordsPanel === panel, () => {
331
+ pendingRecordsKind = kind;
332
+ createSessionStore().clear();
333
+ recordsPanel?.dispose();
334
+ recordsPanel = null;
335
+ void releaseSession();
336
+ goToLoginId(t().timetable.expiredRelogin);
337
+ ctx.rerender();
338
+ });
339
+ recordsPanel = panel;
340
+ state = { ...state, mode: 'records' };
341
+ await panel.load(ctx);
342
+ }
343
+ catch (error) {
344
+ if (!isLifecycleActive(ctx, generation))
345
+ return;
346
+ if (isSessionExpired(error)) {
347
+ createSessionStore().clear();
348
+ await releaseSession();
349
+ goToLoginId(t().timetable.expiredRelogin);
350
+ }
351
+ else {
352
+ state = { ...state, mode: 'error', errorMessage: safeMessage(error) };
353
+ }
354
+ ctx.rerender();
355
+ }
356
+ }
357
+ function logout(ctx) {
358
+ const generation = ++lifecycleGeneration;
359
+ pendingRecordsKind = null;
360
+ recordsPanel?.dispose();
361
+ recordsPanel = null;
362
+ createSessionStore().clear();
363
+ clearScheduleCache();
364
+ void releaseSession();
365
+ void goToPublic(ctx, generation);
366
+ }
282
367
  export const scheduleView = {
283
368
  id: 'schedule',
284
369
  title: t().timetable.menuEntry,
285
370
  async load(ctx) {
286
371
  const generation = ++lifecycleGeneration;
372
+ pendingRecordsKind = null;
373
+ recordsPanel?.dispose();
374
+ recordsPanel = null;
287
375
  if (!isLifecycleActive(ctx, generation))
288
376
  return;
289
377
  const ptr = loadCurrentPointer();
@@ -306,17 +394,29 @@ export const scheduleView = {
306
394
  },
307
395
  async dispose() {
308
396
  lifecycleGeneration += 1;
397
+ pendingRecordsKind = null;
398
+ recordsPanel?.dispose();
399
+ recordsPanel = null;
309
400
  setVimKeysActive(true);
310
401
  await releaseSession();
311
402
  },
312
403
  render(ctx) {
404
+ if (state.mode === 'records' && recordsPanel)
405
+ return recordsPanel.render(ctx);
313
406
  state.termField?.setMaxVisible(computeMaxVisible(ctx.bodyRows));
314
407
  return renderSchedule(state, new Date(), ctx.bodyRows, ctx.size.cols);
315
408
  },
316
409
  isBusy() {
410
+ if (state.mode === 'records')
411
+ return recordsPanel?.isBusy() ?? false;
317
412
  return state.mode === 'loading';
318
413
  },
414
+ scrollsBody() {
415
+ return state.mode === 'records' && !recordsPanel?.capturesPageKeys();
416
+ },
319
417
  shortcuts() {
418
+ if (state.mode === 'records')
419
+ return recordsPanel?.shortcuts() ?? [];
320
420
  if ((state.mode !== 'hub' && state.mode !== 'week') || !state.timetable)
321
421
  return [];
322
422
  const trans = t();
@@ -336,9 +436,13 @@ export const scheduleView = {
336
436
  state.mode === 'needsWeekOne');
337
437
  },
338
438
  capturesPageKeys() {
439
+ if (state.mode === 'records')
440
+ return recordsPanel?.capturesPageKeys() ?? false;
339
441
  return state.mode === 'public' || state.mode === 'termPicker';
340
442
  },
341
443
  footerHint(tabCount, cols = Number.POSITIVE_INFINITY) {
444
+ if (state.mode === 'records')
445
+ return passiveFooterHint(tabCount, cols);
342
446
  const capturing = state.mode === 'needsLoginId' ||
343
447
  state.mode === 'needsLoginPassword' ||
344
448
  state.mode === 'needsWeekOne';
@@ -357,11 +461,25 @@ export const scheduleView = {
357
461
  : undefined;
358
462
  },
359
463
  handleBack(ctx) {
464
+ if (state.mode === 'records') {
465
+ if (recordsPanel?.handleBack())
466
+ return true;
467
+ recordsPanel?.dispose();
468
+ recordsPanel = null;
469
+ if (!returnToHub())
470
+ void goToPublic(ctx);
471
+ return true;
472
+ }
360
473
  if (state.mode === 'needsLoginId') {
474
+ pendingRecordsKind = null;
361
475
  void goToPublic(ctx);
362
476
  return true;
363
477
  }
364
- if (state.mode === 'needsLoginPassword' || state.mode === 'needsWeekOne') {
478
+ if (state.mode === 'needsWeekOne') {
479
+ void goToPublic(ctx);
480
+ return true;
481
+ }
482
+ if (state.mode === 'needsLoginPassword') {
365
483
  goToLoginId();
366
484
  return true;
367
485
  }
@@ -384,10 +502,24 @@ export const scheduleView = {
384
502
  switch (state.mode) {
385
503
  case 'public': {
386
504
  const result = state.publicField?.handleKey(key);
387
- if (result?.selected === 'login')
388
- goToLoginId();
505
+ if (result?.selected === 'exams' || result?.selected === 'grades') {
506
+ void openStudentRecords(ctx, result.selected);
507
+ }
508
+ else if (result?.selected === 'login') {
509
+ pendingRecordsKind = null;
510
+ if (session)
511
+ void afterAuthenticated(ctx, session, lifecycleGeneration);
512
+ else
513
+ goToLoginId();
514
+ }
389
515
  return;
390
516
  }
517
+ case 'records':
518
+ if (key === 'x' && !recordsPanel?.capturesPageKeys())
519
+ logout(ctx);
520
+ else
521
+ recordsPanel?.handleKey(key, ctx);
522
+ return;
391
523
  case 'needsLoginId': {
392
524
  const result = state.idField?.handleKey(key);
393
525
  if (result?.cancelled) {
@@ -451,7 +583,7 @@ export const scheduleView = {
451
583
  case 'needsWeekOne': {
452
584
  const result = state.weekOneField?.handleKey(key);
453
585
  if (result?.cancelled) {
454
- goToLoginId();
586
+ void goToPublic(ctx);
455
587
  return;
456
588
  }
457
589
  if (result?.submitted !== undefined) {
@@ -504,6 +636,10 @@ export const scheduleView = {
504
636
  const shortcut = hubShortcuts(tt).find((sc) => sc.key === key);
505
637
  if (!shortcut)
506
638
  return;
639
+ if (shortcut.key === 'a' || shortcut.key === 'g') {
640
+ void openStudentRecords(ctx, shortcut.key === 'a' ? 'exams' : 'grades');
641
+ return;
642
+ }
507
643
  if (shortcut.key === 'w') {
508
644
  state = { ...state, mode: 'week' };
509
645
  return;
@@ -560,13 +696,8 @@ export const scheduleView = {
560
696
  }
561
697
  return;
562
698
  }
563
- if (shortcut.key === 'x') {
564
- const generation = ++lifecycleGeneration;
565
- createSessionStore().clear();
566
- clearScheduleCache();
567
- void releaseSession();
568
- void goToPublic(ctx, generation);
569
- }
699
+ if (shortcut.key === 'x')
700
+ logout(ctx);
570
701
  return;
571
702
  }
572
703
  case 'week': {
@@ -0,0 +1,139 @@
1
+ import { JWXT_ORIGIN } from '../../config/campus.js';
2
+ import { loadingLines } from '../../core/components/spinner.js';
3
+ import { wrapAnsiWithIndent } from '../../core/text.js';
4
+ import { isSessionExpired, safeMessage, displaySemesterLabel, } from '../../features/student-timetable.js';
5
+ import { createStudentRecordsClient, } from '../../features/student-records-client.js';
6
+ import { renderStudentRecords } from '../../features/student-records-render.js';
7
+ import { t } from '../../i18n/index.js';
8
+ import { ListField, computeMaxVisible, renderListFieldWithContext } from '../fields/list-field.js';
9
+ export class StudentRecordsPanel {
10
+ kind;
11
+ term;
12
+ catalog;
13
+ transport;
14
+ isActive;
15
+ onSessionExpired;
16
+ data;
17
+ error;
18
+ termsField;
19
+ controller;
20
+ pending = false;
21
+ constructor(kind, term, catalog, transport, isActive, onSessionExpired) {
22
+ this.kind = kind;
23
+ this.term = term;
24
+ this.catalog = catalog;
25
+ this.transport = transport;
26
+ this.isActive = isActive;
27
+ this.onSessionExpired = onSessionExpired;
28
+ }
29
+ async load(ctx) {
30
+ this.controller?.abort();
31
+ const controller = new AbortController();
32
+ this.controller = controller;
33
+ const signal = ctx.signal
34
+ ? AbortSignal.any([ctx.signal, controller.signal])
35
+ : controller.signal;
36
+ this.pending = true;
37
+ this.error = undefined;
38
+ this.data = undefined;
39
+ this.termsField = undefined;
40
+ ctx.resetScroll();
41
+ ctx.rerender();
42
+ try {
43
+ const data = await createStudentRecordsClient(this.transport, JWXT_ORIGIN).fetchRecords(this.kind, this.term, signal);
44
+ if (signal.aborted || !this.isActive())
45
+ return;
46
+ this.data = data;
47
+ }
48
+ catch (error) {
49
+ if (signal.aborted || !this.isActive())
50
+ return;
51
+ if (isSessionExpired(error))
52
+ this.onSessionExpired();
53
+ else
54
+ this.error = safeMessage(error);
55
+ }
56
+ finally {
57
+ if (!signal.aborted && this.isActive()) {
58
+ this.pending = false;
59
+ ctx.rerender();
60
+ }
61
+ }
62
+ }
63
+ dispose() {
64
+ this.controller?.abort();
65
+ this.data = undefined;
66
+ this.termsField = undefined;
67
+ }
68
+ isBusy() {
69
+ return this.pending;
70
+ }
71
+ capturesPageKeys() {
72
+ return this.termsField !== undefined;
73
+ }
74
+ handleBack() {
75
+ if (!this.termsField)
76
+ return false;
77
+ this.termsField = undefined;
78
+ return true;
79
+ }
80
+ shortcuts() {
81
+ return this.pending || this.termsField
82
+ ? []
83
+ : [
84
+ { key: 's', label: t().records.switchTerm },
85
+ { key: 'r', label: t().records.refresh },
86
+ { key: 'x', label: t().timetable.hubLogout },
87
+ ];
88
+ }
89
+ render(ctx) {
90
+ if (this.termsField) {
91
+ this.termsField.setMaxVisible(computeMaxVisible(ctx.bodyRows));
92
+ return renderListFieldWithContext([], this.termsField, ctx.bodyRows, ctx.size.cols);
93
+ }
94
+ if (this.pending)
95
+ return loadingLines(t().common.loading, ctx.size.cols);
96
+ const lines = this.data
97
+ ? renderStudentRecords(this.data, this.term, ctx.size.cols)
98
+ : wrapAnsiWithIndent(this.error ?? t().timetable.genericError, ctx.size.cols, ' ');
99
+ return [
100
+ ...lines,
101
+ '',
102
+ ...wrapAnsiWithIndent(`[s] ${t().records.switchTerm} · [r] ${t().records.refresh} · [x] ${t().timetable.hubLogout}`, ctx.size.cols, ' '),
103
+ ];
104
+ }
105
+ handleKey(key, ctx) {
106
+ if (this.termsField) {
107
+ const result = this.termsField.handleKey(key);
108
+ if (result.cancelled || result.selected === '__back__') {
109
+ this.termsField = undefined;
110
+ }
111
+ else if (result.selected) {
112
+ const term = this.catalog.find((candidate) => `${candidate.academicYear}:${candidate.semester}` === result.selected);
113
+ if (term) {
114
+ this.term = term;
115
+ void this.load(ctx);
116
+ }
117
+ }
118
+ return;
119
+ }
120
+ if (this.pending)
121
+ return;
122
+ if (key === 'r')
123
+ void this.load(ctx);
124
+ if (key === 's') {
125
+ this.termsField = new ListField({
126
+ title: t().records.switchTerm,
127
+ options: [
128
+ ...this.catalog.map((term) => ({
129
+ value: `${term.academicYear}:${term.semester}`,
130
+ label: `${term.academicYearLabel} · ${displaySemesterLabel(term)}`,
131
+ })),
132
+ { value: '__back__', label: t().common.back },
133
+ ],
134
+ initialIndex: Math.max(0, this.catalog.findIndex((term) => term.academicYear === this.term.academicYear && term.semester === this.term.semester)),
135
+ });
136
+ ctx.resetScroll();
137
+ }
138
+ }
139
+ }
@@ -1,5 +1,6 @@
1
1
  import { createCookieJar } from './cookie-jar.js';
2
2
  import { AuthError, SessionExpiredError } from './errors.js';
3
+ import { JWXT_ORIGIN, STUDENT_RECORD_ROUTES } from '../config/campus.js';
3
4
  const MAX_REDIRECTS = 8;
4
5
  const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
5
6
  const BODY_HEADERS = [
@@ -11,7 +12,7 @@ const BODY_HEADERS = [
11
12
  ];
12
13
  const WEBVPN_HOST = 'webvpn.nbt.edu.cn';
13
14
  const AUTH_HOST = 'authserver-443.webvpn.nbt.edu.cn';
14
- export const JWXT_HOST = 'jwxt-443.webvpn.nbt.edu.cn';
15
+ export const JWXT_HOST = new URL(JWXT_ORIGIN).hostname;
15
16
  const WEBVPN_PATHS = new Set([
16
17
  '/',
17
18
  '/users/sign_in',
@@ -30,6 +31,7 @@ const JWXT_EXACT_PATHS = new Set([
30
31
  '/jwglxt/kbcx/xskbcx_cxXskbcxIndex.html',
31
32
  '/jwglxt/kbcx/xskbcx_cxXsgrkb.html',
32
33
  '/jwglxt/kbcx/xskbcx_cxRjc.html',
34
+ ...Object.values(STUDENT_RECORD_ROUTES).flatMap((route) => [route.index, route.query]),
33
35
  ]);
34
36
  function isAllowedJwxtPath(pathname) {
35
37
  return JWXT_EXACT_PATHS.has(pathname);
@@ -100,8 +102,12 @@ export function assertAllowedCampusUrl(url) {
100
102
  assertAllowedCasService(service);
101
103
  return;
102
104
  }
103
- if (hostname === JWXT_HOST && isAllowedJwxtPath(url.pathname))
105
+ if (hostname === JWXT_HOST && isAllowedJwxtPath(url.pathname)) {
106
+ const academicRoute = Object.values(STUDENT_RECORD_ROUTES).some((route) => route.index === url.pathname || route.query === url.pathname);
107
+ if (academicRoute && url.searchParams.getAll('doType').some((action) => action !== 'query'))
108
+ throw new AuthError('UNTRUSTED_URL', 'session', 'Only academic query operations are allowed.');
104
109
  return;
110
+ }
105
111
  if (hostname === AUTH_HOST && url.pathname === PROFILE_GATE_PATH) {
106
112
  throw new AuthError('PROFILE_INCOMPLETE', 'credentials', 'The campus requires this account to complete its profile.');
107
113
  }
package/dist/cli.js CHANGED
@@ -13,6 +13,7 @@ import { clearScreen, handleGracefulExit } from './core/ui.js';
13
13
  import { APP_INFO, URLS } from './config/data.js';
14
14
  import { runUpdateCheck } from './features/update.js';
15
15
  import { runStudentTimetableCommand } from './features/student-timetable.js';
16
+ import { runStudentRecordsCommand } from './features/student-records.js';
16
17
  import { showAbout } from './features/about.js';
17
18
  import { openUrlInBrowser } from './features/links.js';
18
19
  const ACTION_ALIASES = {
@@ -119,6 +120,12 @@ function getAllowedFlagsFor(command) {
119
120
  return allowed;
120
121
  if (command === 'theme')
121
122
  return allowed;
123
+ if (command === 'exams' || command === 'grades') {
124
+ allowed.add('--json');
125
+ allowed.add('--one-shot');
126
+ allowed.add('--no-save');
127
+ return allowed;
128
+ }
122
129
  if (command === 'schedule' || command === 'timetable') {
123
130
  allowed.add('--one-shot');
124
131
  allowed.add('--no-save');
@@ -154,6 +161,10 @@ function getAllowedFlagsFor(command) {
154
161
  function getAllowedFlagPrefixesFor(command) {
155
162
  if (!command)
156
163
  return [];
164
+ if (command === 'exams')
165
+ return ['--term=', '--output='];
166
+ if (command === 'grades')
167
+ return ['--term='];
157
168
  if (command === 'schedule' || command === 'timetable') {
158
169
  return ['--term=', '--output=', '--week-one='];
159
170
  }
@@ -213,6 +224,8 @@ function printHelp() {
213
224
  console.log(` status ${trans.menu.statusDesc}`);
214
225
  console.log(' schedule <login|logout|status|terms|export>');
215
226
  console.log(` ${c.cmdSchedule}`);
227
+ console.log(` exams ${trans.records.exams}`);
228
+ console.log(` grades ${trans.records.grades}`);
216
229
  console.log(` website ${c.cmdWebsite}`);
217
230
  console.log(` github ${c.cmdGithub}`);
218
231
  console.log(` roadmap ${c.cmdRoadmap}`);
@@ -450,6 +463,11 @@ async function runCommandMode(argv) {
450
463
  return;
451
464
  }
452
465
  validateFlags(command, flags);
466
+ if (command === 'exams' || command === 'grades') {
467
+ rejectUnexpectedArguments(command, args);
468
+ process.exitCode = await runStudentRecordsCommand(command, { flags });
469
+ return;
470
+ }
453
471
  if (!command) {
454
472
  if (!hasInteractiveTerminal()) {
455
473
  const cliTrans = t().cli;
@@ -0,0 +1,2 @@
1
+ export const JWXT_ORIGIN = 'https://jwxt-443.webvpn.nbt.edu.cn';
2
+ export { STUDENT_RECORD_ROUTES } from '@nbtca/nbtcal/academic';
@@ -0,0 +1,19 @@
1
+ import { createNbtStudentRecordsClient } from '@nbtca/nbtcal/academic';
2
+ import { sanitizeTerminalLine } from '../core/text.js';
3
+ function sanitizeRecord(record) {
4
+ return Object.fromEntries(Object.entries(record).map(([key, value]) => [
5
+ key,
6
+ typeof value === 'string' ? sanitizeTerminalLine(value) : value,
7
+ ]));
8
+ }
9
+ export function createStudentRecordsClient(transport, baseUrl) {
10
+ const client = createNbtStudentRecordsClient(transport, { baseUrl });
11
+ return {
12
+ async fetchRecords(kind, term, signal) {
13
+ const records = await client.fetchRecords(kind, term, signal ? { signal } : {});
14
+ return records.kind === 'exams'
15
+ ? { ...records, items: records.items.map(sanitizeRecord) }
16
+ : { ...records, items: records.items.map(sanitizeRecord) };
17
+ },
18
+ };
19
+ }
@@ -0,0 +1,50 @@
1
+ import { sanitizeTerminalLine, wrapAnsiWithIndent } from '../core/text.js';
2
+ import { fmt, t } from '../i18n/index.js';
3
+ import { displaySemesterLabel } from './student-timetable.js';
4
+ export function renderStudentRecords(data, term, cols = Number.POSITIVE_INFINITY) {
5
+ const trans = t().records;
6
+ const lines = [];
7
+ const add = (value) => {
8
+ lines.push(...wrapAnsiWithIndent(sanitizeTerminalLine(value), cols, ' '));
9
+ };
10
+ add(`${trans[data.kind]} · ${term.academicYearLabel} · ${displaySemesterLabel(term)}`);
11
+ lines.push('');
12
+ if (data.items.length === 0) {
13
+ add(data.kind === 'exams' ? trans.noExams : trans.noGrades);
14
+ return lines;
15
+ }
16
+ if (data.kind === 'exams') {
17
+ for (const exam of data.items) {
18
+ add(exam.courseName + (exam.courseCode ? ` (${exam.courseCode})` : ''));
19
+ add(exam.timeText ?? trans.timeUnavailable);
20
+ if (exam.examName)
21
+ add(exam.examName);
22
+ if (exam.location || exam.campus)
23
+ add([exam.campus, exam.location].filter(Boolean).join(' · '));
24
+ if (exam.seat)
25
+ add(fmt(trans.seat, { value: exam.seat }));
26
+ if (exam.assessment)
27
+ add(exam.assessment);
28
+ lines.push('');
29
+ }
30
+ }
31
+ else {
32
+ for (const grade of data.items) {
33
+ add(grade.courseName + (grade.courseCode ? ` (${grade.courseCode})` : ''));
34
+ add(fmt(trans.gradeValue, { value: grade.grade ?? trans.notPublished }));
35
+ if (grade.credits !== null)
36
+ add(fmt(trans.credits, { value: grade.credits }));
37
+ if (grade.gradePoint !== null)
38
+ add(fmt(trans.gradePoint, { value: grade.gradePoint }));
39
+ if (grade.examNature || grade.courseNature)
40
+ add([grade.examNature, grade.courseNature].filter(Boolean).join(' · '));
41
+ if (grade.voided === true)
42
+ add(trans.voided);
43
+ if (grade.remark)
44
+ add(grade.remark);
45
+ lines.push('');
46
+ }
47
+ }
48
+ add(trans.memoryOnly);
49
+ return lines;
50
+ }
@@ -0,0 +1,61 @@
1
+ import path from 'node:path';
2
+ import { studentExamsToIcs } from '@nbtca/nbtcal/academic';
3
+ import { createNbtTimetableClient } from '@nbtca/nbtcal/timetable';
4
+ import { AuthError } from '../auth/errors.js';
5
+ import { createSessionStore } from '../auth/session-store.js';
6
+ import { JWXT_ORIGIN } from '../config/campus.js';
7
+ import { resolveTerm, PromptCancelledError, safeMessage, withAuthenticatedSession, writePrivateIcs, } from './student-timetable.js';
8
+ import { sanitizeAcademicTerm } from './timetable-sanitize.js';
9
+ import { createStudentRecordsClient } from './student-records-client.js';
10
+ import { renderStudentRecords } from './student-records-render.js';
11
+ import { fmt, t } from '../i18n/index.js';
12
+ export async function runStudentRecordsCommand(kind, options) {
13
+ const stdout = options.stdout ?? process.stdout;
14
+ const stderr = options.stderr ?? process.stderr;
15
+ const isInteractive = options.isInteractive ?? (process.stdin.isTTY && process.stdout.isTTY);
16
+ const outputFlag = [...options.flags].find((flag) => flag.startsWith('--output='));
17
+ const output = outputFlag?.slice('--output='.length);
18
+ if (output !== undefined && (kind !== 'exams' || !output.trim() || options.flags.has('--json'))) {
19
+ stderr.write(`${t().records.invalidExportOptions}\n`);
20
+ return 1;
21
+ }
22
+ const termFlag = [...options.flags].find((flag) => flag.startsWith('--term='));
23
+ if (termFlag === '--term=') {
24
+ stderr.write(`${t().timetable.unknownTerm}\n`);
25
+ return 1;
26
+ }
27
+ try {
28
+ return await withAuthenticatedSession(async (session) => {
29
+ const client = createNbtTimetableClient(session.timetableTransport, {
30
+ baseUrl: JWXT_ORIGIN,
31
+ });
32
+ const terms = (await client.listTerms()).map(sanitizeAcademicTerm);
33
+ const term = resolveTerm(terms, termFlag?.slice('--term='.length));
34
+ const records = await createStudentRecordsClient(session.timetableTransport, JWXT_ORIGIN).fetchRecords(kind, term);
35
+ if (output !== undefined && records.kind === 'exams') {
36
+ writePrivateIcs(output, studentExamsToIcs(records));
37
+ stdout.write(`${fmt(t().records.exported, { file: path.resolve(output) })}\n`);
38
+ return 0;
39
+ }
40
+ stdout.write(options.flags.has('--json')
41
+ ? `${JSON.stringify(records, null, 2)}\n`
42
+ : `${renderStudentRecords(records, term).join('\n')}\n`);
43
+ return 0;
44
+ }, {
45
+ oneShot: options.flags.has('--one-shot') || options.flags.has('--no-save'),
46
+ isInteractive,
47
+ store: options.store ?? createSessionStore(),
48
+ stderr,
49
+ });
50
+ }
51
+ catch (error) {
52
+ if (error instanceof PromptCancelledError)
53
+ return 130;
54
+ if (!isInteractive && error instanceof AuthError && error.code === 'INVALID_CREDENTIALS') {
55
+ stderr.write(`${t().timetable.noSession}\n`);
56
+ return 2;
57
+ }
58
+ stderr.write(`${safeMessage(error)}\n`);
59
+ return 1;
60
+ }
61
+ }
@@ -1,3 +1,4 @@
1
+ import { StudentRecordsError } from '@nbtca/nbtcal/academic';
1
2
  import fs from 'node:fs';
2
3
  import path from 'node:path';
3
4
  import { randomUUID } from 'node:crypto';
@@ -11,7 +12,8 @@ import { clearScheduleCache, termKey } from './schedule-store.js';
11
12
  import { sanitizeTerminalLine } from '../core/text.js';
12
13
  import { fmt, t } from '../i18n/index.js';
13
14
  import { sanitizeAcademicTerm, sanitizeTimetable } from './timetable-sanitize.js';
14
- export const JWXT_ORIGIN = 'https://jwxt-443.webvpn.nbt.edu.cn';
15
+ import { JWXT_ORIGIN } from '../config/campus.js';
16
+ export { JWXT_ORIGIN };
15
17
  function flagValue(flags, prefix) {
16
18
  const flag = [...flags].find((value) => value.startsWith(prefix));
17
19
  return flag?.slice(prefix.length);
@@ -36,7 +38,7 @@ export function relevantTerms(catalog) {
36
38
  return Number.isInteger(year) && year <= currentYear && year >= currentYear - 4;
37
39
  });
38
40
  }
39
- function displaySemesterLabel(term) {
41
+ export function displaySemesterLabel(term) {
40
42
  const aliases = { '3': '1', '12': '2', '16': '3' };
41
43
  const aliased = aliases[term.semester];
42
44
  if (aliased)
@@ -74,7 +76,8 @@ class IcsWriteError extends Error {
74
76
  }
75
77
  export function isSessionExpired(error) {
76
78
  return ((error instanceof AuthError && error.code === 'SESSION_EXPIRED') ||
77
- (error instanceof TimetableError && error.code === 'SESSION_EXPIRED'));
79
+ (error instanceof TimetableError && error.code === 'SESSION_EXPIRED') ||
80
+ (error instanceof StudentRecordsError && error.code === 'SESSION_EXPIRED'));
78
81
  }
79
82
  export function safeMessage(error) {
80
83
  const trans = t().timetable;
@@ -117,6 +120,22 @@ export function safeMessage(error) {
117
120
  return trans.genericError;
118
121
  }
119
122
  }
123
+ if (error instanceof StudentRecordsError) {
124
+ switch (error.code) {
125
+ case 'SESSION_EXPIRED':
126
+ return trans.sessionExpired;
127
+ case 'HTTP_ERROR':
128
+ return trans.httpError;
129
+ case 'NETWORK_ERROR':
130
+ return trans.network;
131
+ case 'INVALID_RECORDS':
132
+ return trans.unexpectedResponse;
133
+ case 'TERM_MISMATCH':
134
+ return trans.termMismatch;
135
+ case 'UNPUBLISHED_EXAM_TIME':
136
+ return t().records.exportNeedsTime;
137
+ }
138
+ }
120
139
  if (error instanceof TimetableError) {
121
140
  switch (error.code) {
122
141
  case 'MISSING_CALENDAR_DATES':
@@ -148,7 +167,7 @@ export function safeMessage(error) {
148
167
  }
149
168
  return trans.genericError;
150
169
  }
151
- class PromptCancelledError extends Error {
170
+ export class PromptCancelledError extends Error {
152
171
  }
153
172
  function answered(value) {
154
173
  if (value === null)
@@ -212,6 +212,25 @@
212
212
  "watchJsonConflict": "--watch cannot be used with --json.",
213
213
  "intervalNeedsWatch": "--interval requires --watch."
214
214
  },
215
+ "records": {
216
+ "exams": "Exam schedule",
217
+ "grades": "Grades",
218
+ "noExams": "No exam arrangements have been published for this term.",
219
+ "noGrades": "No grades have been published for this term.",
220
+ "timeUnavailable": "Time not published",
221
+ "notPublished": "Not published",
222
+ "seat": "Seat: {value}",
223
+ "gradeValue": "Grade: {value}",
224
+ "credits": "Credits: {value}",
225
+ "gradePoint": "Grade points: {value}",
226
+ "voided": "The school has marked this grade as void.",
227
+ "memoryOnly": "Exam and grade query results are not cached.",
228
+ "refresh": "Refresh",
229
+ "switchTerm": "Switch term",
230
+ "exportNeedsTime": "Some exam times are unpublished. A complete exam calendar cannot be exported yet.",
231
+ "invalidExportOptions": "Use a nonempty --output path for exams without --json.",
232
+ "exported": "Exported the exam calendar to {file}."
233
+ },
215
234
  "timetable": {
216
235
  "menuTitle": "My Timetable",
217
236
  "actionExport": "Export ICS",
@@ -212,6 +212,25 @@
212
212
  "watchJsonConflict": "--watch 不能和 --json 同时使用。",
213
213
  "intervalNeedsWatch": "--interval 需要配合 --watch 使用。"
214
214
  },
215
+ "records": {
216
+ "exams": "个人考试安排",
217
+ "grades": "成绩查询",
218
+ "noExams": "这个学期尚无已公布的个人考试安排。",
219
+ "noGrades": "这个学期尚无已公布的成绩。",
220
+ "timeUnavailable": "考试时间尚未公布",
221
+ "notPublished": "尚未公布",
222
+ "seat": "座位号:{value}",
223
+ "gradeValue": "成绩:{value}",
224
+ "credits": "学分:{value}",
225
+ "gradePoint": "绩点:{value}",
226
+ "voided": "教务系统已将这条成绩标记为作废。",
227
+ "memoryOnly": "考试和成绩查询结果不会写入本地缓存。",
228
+ "refresh": "刷新查询",
229
+ "switchTerm": "切换学期",
230
+ "exportNeedsTime": "部分考试尚未公布时间,暂时无法导出完整的考试日历。",
231
+ "invalidExportOptions": "请使用非空的 --output 路径导出考试日历,并且不要同时使用 --json。",
232
+ "exported": "考试日历已导出至 {file}。"
233
+ },
215
234
  "timetable": {
216
235
  "menuTitle": "我的课表",
217
236
  "actionExport": "导出 ICS",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nbtca/prompt",
3
- "version": "1.5.20",
3
+ "version": "1.5.21",
4
4
  "type": "module",
5
5
  "main": "dist/index.js",
6
6
  "exports": {
@@ -47,7 +47,7 @@
47
47
  ],
48
48
  "dependencies": {
49
49
  "@nbtca/docs": "^0.3.5",
50
- "@nbtca/nbtcal": "^0.4.4",
50
+ "@nbtca/nbtcal": "^0.4.5",
51
51
  "chalk": "^5.6.2",
52
52
  "marked": "^15.0.12"
53
53
  },