@nbtca/prompt 1.5.14 → 1.5.16

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.
@@ -1,6 +1,14 @@
1
- import makeFetchCookie from 'fetch-cookie';
2
- import { CookieJar } from 'tough-cookie';
1
+ import { createCookieJar } from './cookie-jar.js';
3
2
  import { AuthError, SessionExpiredError } from './errors.js';
3
+ const MAX_REDIRECTS = 8;
4
+ const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
5
+ const BODY_HEADERS = [
6
+ 'content-type',
7
+ 'content-length',
8
+ 'content-encoding',
9
+ 'content-language',
10
+ 'content-location',
11
+ ];
4
12
  const WEBVPN_HOST = 'webvpn.nbt.edu.cn';
5
13
  const AUTH_HOST = 'authserver-443.webvpn.nbt.edu.cn';
6
14
  export const JWXT_HOST = 'jwxt-443.webvpn.nbt.edu.cn';
@@ -117,25 +125,8 @@ function safeFetchError(error, stage) {
117
125
  return new AuthError('NETWORK', stage, 'The campus service request failed.', { retryable: true });
118
126
  }
119
127
  export function createCampusCookieSession(options = {}) {
120
- // Tough Cookie's secure defaults reject public suffixes and use strict
121
- // parsing while tolerating legacy prefix mistakes. The campus WebVPN relies
122
- // on its default special-domain handling during the CAS callback.
123
- const jar = options.jar ?? new CookieJar();
128
+ const jar = options.jar ?? createCookieJar();
124
129
  const baseFetch = options.baseFetch ?? globalThis.fetch;
125
- const guardedFetch = async (input, init) => {
126
- const url = new URL(input instanceof Request ? input.url : input.toString());
127
- assertAllowedCampusUrl(url);
128
- // Caller headers were checked before fetch-cookie received them. A Cookie
129
- // header at this layer was added by the private jar and is expected.
130
- const headers = new Headers(input instanceof Request ? input.headers : undefined);
131
- for (const [name, value] of new Headers(init?.headers))
132
- headers.set(name, value);
133
- if (headers.has('authorization') || headers.has('host')) {
134
- throw new AuthError('UNTRUSTED_URL', 'session', 'Authentication headers are not allowed.');
135
- }
136
- return baseFetch(input, init);
137
- };
138
- const cookieFetch = makeFetchCookie(guardedFetch, jar, false);
139
130
  const timeoutMs = options.timeoutMs ?? 15_000;
140
131
  async function request(url, init = {}, stage = 'session') {
141
132
  assertAllowedCampusUrl(url);
@@ -150,13 +141,43 @@ export function createCampusCookieSession(options = {}) {
150
141
  }, timeoutMs).unref();
151
142
  // Keep the timer running after the headers: the caller still has to read the body.
152
143
  const signal = init.signal ? AbortSignal.any([init.signal, timeout.signal]) : timeout.signal;
144
+ const headers = new Headers(safeHeaders(init.headers));
145
+ let method = init.method ?? 'GET';
146
+ let body = init.body ?? null;
153
147
  try {
154
- return await cookieFetch(url, {
155
- ...init,
156
- headers: safeHeaders(init.headers),
157
- signal,
158
- maxRedirect: 8,
159
- });
148
+ for (let redirects = 0;; redirects += 1) {
149
+ const cookie = jar.cookieHeader(url);
150
+ if (cookie)
151
+ headers.set('cookie', cookie);
152
+ else
153
+ headers.delete('cookie');
154
+ const response = await baseFetch(url, {
155
+ ...init,
156
+ method,
157
+ body,
158
+ headers,
159
+ signal,
160
+ redirect: 'manual',
161
+ });
162
+ const responseUrl = new URL(response.url || url);
163
+ jar.store(responseUrl, response.headers.getSetCookie());
164
+ const location = response.headers.get('location');
165
+ if (!REDIRECT_STATUSES.has(response.status) || location === null) {
166
+ Object.defineProperty(response, 'url', { value: responseUrl.href });
167
+ return response;
168
+ }
169
+ await response.body?.cancel();
170
+ if (redirects >= MAX_REDIRECTS)
171
+ throw new Error('Too many campus redirects.');
172
+ if (response.status === 303 || (method === 'POST' && response.status <= 302)) {
173
+ method = 'GET';
174
+ body = null;
175
+ for (const name of BODY_HEADERS)
176
+ headers.delete(name);
177
+ }
178
+ url = new URL(location, responseUrl);
179
+ assertAllowedCampusUrl(url);
180
+ }
160
181
  }
161
182
  catch (error) {
162
183
  throw safeFetchError(error, stage);
@@ -189,13 +210,16 @@ export function createCampusCookieSession(options = {}) {
189
210
  request,
190
211
  timetableTransport,
191
212
  serialize: () => jar.serialize(),
192
- close: () => jar.removeAllCookies(),
213
+ close: () => {
214
+ jar.clear();
215
+ return Promise.resolve();
216
+ },
193
217
  };
194
218
  }
195
- export async function cookieSessionFromSerialized(serialized, options = {}) {
219
+ export function cookieSessionFromSerialized(serialized, options = {}) {
196
220
  let jar;
197
221
  try {
198
- jar = await CookieJar.deserialize(serialized);
222
+ jar = createCookieJar(serialized);
199
223
  }
200
224
  catch {
201
225
  throw new SessionExpiredError();
@@ -150,17 +150,17 @@ function createAuthenticatedSession(cookies, metadata) {
150
150
  return {
151
151
  accountHint: metadata.accountHint,
152
152
  timetableTransport: (url, init) => cookies.timetableTransport(url, init),
153
- async snapshot(validatedAt = new Date()) {
153
+ snapshot(validatedAt = new Date()) {
154
154
  const validatedAtText = validatedAt.toISOString();
155
- return {
155
+ return Promise.resolve({
156
156
  version: 1,
157
157
  provider: 'nbt-webvpn',
158
- jar: await cookies.serialize(),
158
+ jar: cookies.serialize(),
159
159
  ...(metadata.accountHint === undefined ? {} : { accountHint: metadata.accountHint }),
160
160
  authenticatedAt: metadata.authenticatedAt,
161
161
  validatedAt: validatedAtText,
162
162
  expiresAt: new Date(validatedAt.getTime() + SESSION_MAX_AGE_MS).toISOString(),
163
- };
163
+ });
164
164
  },
165
165
  close: () => cookies.close(),
166
166
  };
@@ -250,10 +250,11 @@ export async function loginWithStudentPassword(username, password, options = {})
250
250
  });
251
251
  }
252
252
  }
253
- export async function restoreNbtSession(persisted, options = {}) {
254
- const cookies = await cookieSessionFromSerialized(persisted.jar, options);
255
- return createAuthenticatedSession(cookies, {
256
- ...(persisted.accountHint === undefined ? {} : { accountHint: persisted.accountHint }),
257
- authenticatedAt: persisted.authenticatedAt,
253
+ export function restoreNbtSession(persisted, options = {}) {
254
+ return new Promise((resolve) => {
255
+ resolve(createAuthenticatedSession(cookieSessionFromSerialized(persisted.jar, options), {
256
+ ...(persisted.accountHint === undefined ? {} : { accountHint: persisted.accountHint }),
257
+ authenticatedAt: persisted.authenticatedAt,
258
+ }));
258
259
  });
259
260
  }
package/dist/cli.js CHANGED
@@ -264,7 +264,7 @@ async function runEventsCommand(flags) {
264
264
  }
265
265
  const { calendar, stale } = await loadCalendarOrCache();
266
266
  if (stale)
267
- console.error(chalk.yellow(t().calendar.stale));
267
+ console.error(chalk.yellow(t().common.offline));
268
268
  const now = new Date();
269
269
  if (flags.has('--heatmap')) {
270
270
  const buckets = yearHeatmap(calendar, now);
@@ -1,5 +1,6 @@
1
1
  import { glyph, type, space } from '../theme.js';
2
- import { visualWidth, padEndV, wrapAnsiToVisualWidth } from '../text.js';
2
+ import { visualWidth, padEndV, wrapAnsiToVisualWidth, clipAnsiToVisualWidth } from '../text.js';
3
+ import { pickIcon } from '../icons.js';
3
4
  import { createPainter } from './painter.js';
4
5
  import { startRawInput } from './input-session.js';
5
6
  import { t } from '../../i18n/index.js';
@@ -60,6 +61,12 @@ export function nextIndex(current, key, len, pageSize = 5) {
60
61
  return current;
61
62
  }
62
63
  }
64
+ export function menuColumns(options) {
65
+ return options.reduce((widths, option) => ({
66
+ label: Math.max(widths.label, visualWidth(option.label)),
67
+ hint: Math.max(widths.hint, option.hint ? visualWidth(option.hint) : 0),
68
+ }), { label: 0, hint: 0 });
69
+ }
63
70
  function normalizedWidth(cols) {
64
71
  return Number.isFinite(cols) ? Math.max(1, Math.floor(cols)) : Number.POSITIVE_INFINITY;
65
72
  }
@@ -69,7 +76,36 @@ function renderIndentedText(label, cols, style) {
69
76
  const contentWidth = Math.max(1, width - visualWidth(indent));
70
77
  return wrapAnsiToVisualWidth(style(label), contentWidth).map((line) => `${indent}${line}`);
71
78
  }
72
- export function renderMenuOption(option, selected, labelWidth = visualWidth(option.label), cols = Number.POSITIVE_INFINITY) {
79
+ const MIN_LABEL_COLUMN = 24;
80
+ function clipWithEllipsis(value, width) {
81
+ if (visualWidth(value) <= width)
82
+ return value;
83
+ const ellipsis = pickIcon('…', '~');
84
+ return clipAnsiToVisualWidth(value, width - visualWidth(ellipsis)) + ellipsis;
85
+ }
86
+ function fitColumns(columns, contentWidth) {
87
+ if (columns.label + 2 + columns.hint <= contentWidth)
88
+ return columns;
89
+ const hint = Math.min(columns.hint, Math.max(contentWidth - 2 - columns.label, Math.ceil(contentWidth / 3)));
90
+ const label = Math.min(columns.label, contentWidth - 2 - hint);
91
+ return label >= MIN_LABEL_COLUMN ? { label, hint } : undefined;
92
+ }
93
+ function optionCells(option, columns, contentWidth) {
94
+ const hint = option.hint ?? '';
95
+ if (option.hintColumn) {
96
+ const fitted = fitColumns(columns, contentWidth);
97
+ return fitted
98
+ ? {
99
+ label: padEndV(clipWithEllipsis(option.label, fitted.label), fitted.label),
100
+ hint: clipWithEllipsis(hint, fitted.hint),
101
+ }
102
+ : { label: option.label, hint: '' };
103
+ }
104
+ const hintWidth = hint ? 2 + visualWidth(hint) : 0;
105
+ const labelWidth = columns.label + hintWidth <= contentWidth ? columns.label : visualWidth(option.label);
106
+ return { label: padEndV(option.label, labelWidth), hint };
107
+ }
108
+ export function renderMenuOption(option, selected, columns = menuColumns([option]), cols = Number.POSITIVE_INFINITY) {
73
109
  const width = normalizedWidth(cols);
74
110
  const cursor = glyph.cursor();
75
111
  const gap = ' '.repeat(visualWidth(cursor));
@@ -78,18 +114,17 @@ export function renderMenuOption(option, selected, labelWidth = visualWidth(opti
78
114
  const prefix = prefixes.find((candidate) => visualWidth(candidate) < width) ?? '';
79
115
  const continuation = ' '.repeat(visualWidth(prefix));
80
116
  const contentWidth = Math.max(1, width - visualWidth(prefix));
81
- const hintWidth = option.hint ? 2 + visualWidth(option.hint) : 0;
82
- const paddedWidth = labelWidth + hintWidth <= contentWidth ? labelWidth : visualWidth(option.label);
83
- const padded = padEndV(option.label, paddedWidth);
84
- const label = selected ? type.active(padded) : type.body(padded);
85
- const hint = option.hint ? ` ${type.hint(option.hint)}` : '';
117
+ const cells = optionCells(option, columns, contentWidth);
118
+ const style = selected ? type.active : option.dim ? type.hint : type.body;
119
+ const hint = cells.hint ? ` ${type.hint(cells.hint)}` : '';
120
+ const label = style(cells.label);
86
121
  return wrapAnsiToVisualWidth(`${label}${hint}`, contentWidth).map((line, index) => `${index === 0 ? prefix : continuation}${line}`);
87
122
  }
88
123
  export function renderMenu(state, cols = Number.POSITIVE_INFINITY) {
89
- const labelWidth = state.options.reduce((width, option) => Math.max(width, visualWidth(option.label)), 0);
124
+ const columns = menuColumns(state.options);
90
125
  const lines = state.title ? [...renderIndentedText(state.title, cols, type.heading), ''] : [];
91
126
  state.options.forEach((option, index) => {
92
- lines.push(...renderMenuOption(option, index === state.selectedIndex, labelWidth, cols));
127
+ lines.push(...renderMenuOption(option, index === state.selectedIndex, columns, cols));
93
128
  });
94
129
  if (state.footer) {
95
130
  lines.push('');
package/dist/core/logo.js CHANGED
@@ -29,15 +29,7 @@ function dotmatrixFile() {
29
29
  return tier?.file ?? 'ca-dotmatrix-small.txt';
30
30
  }
31
31
  function paint(text, color) {
32
- if (!color)
33
- return text;
34
- const fn = brand;
35
- return typeof fn.multiline === 'function'
36
- ? fn.multiline(text)
37
- : text
38
- .split('\n')
39
- .map((line) => brand(line))
40
- .join('\n');
32
+ return color ? brand(text) : text;
41
33
  }
42
34
  function loadArt() {
43
35
  const art = useUnicodeIcons() ? readArt(dotmatrixFile()) : readArt('ascii-logo.txt');
@@ -61,6 +53,31 @@ export function buildLogoLines() {
61
53
  '',
62
54
  ];
63
55
  }
56
+ function skipOnKeypress() {
57
+ const controller = new AbortController();
58
+ const stdin = process.stdin;
59
+ if (!stdin.isTTY)
60
+ return { signal: controller.signal, release: () => undefined };
61
+ const onData = (chunk) => {
62
+ // Raw mode swallows SIGINT, so Ctrl+C has to exit by hand.
63
+ if (chunk.includes(0x03)) {
64
+ stdin.setRawMode(false);
65
+ process.exit(130);
66
+ }
67
+ controller.abort();
68
+ };
69
+ stdin.setRawMode(true);
70
+ stdin.on('data', onData);
71
+ stdin.resume();
72
+ return {
73
+ signal: controller.signal,
74
+ release() {
75
+ stdin.off('data', onData);
76
+ stdin.setRawMode(false);
77
+ stdin.pause();
78
+ },
79
+ };
80
+ }
64
81
  export async function runStartup() {
65
82
  if (!process.stdout.isTTY)
66
83
  return;
@@ -68,14 +85,16 @@ export async function runStartup() {
68
85
  if (!startupFitsTerminal(process.stdout.rows, process.stdout.columns, art))
69
86
  return;
70
87
  const color = !process.env['NO_COLOR'];
88
+ const skip = skipOnKeypress();
71
89
  process.stdout.write('\n');
72
- await materializeBraille(art, (s) => paint(s, color), {
73
- paintProgress: (s) => (color ? c.brand(s) : s),
74
- });
75
- await typeReveal([
76
- '',
77
- color ? brand(TAGLINE) : TAGLINE,
78
- chalk.dim(`@nbtca/prompt v${APP_INFO.version}`),
79
- '',
80
- ]);
90
+ try {
91
+ await materializeBraille(art, (s) => paint(s, color), {
92
+ paintProgress: (s) => (color ? c.brand(s) : s),
93
+ signal: skip.signal,
94
+ });
95
+ await typeReveal(['', color ? brand(TAGLINE) : TAGLINE, chalk.dim(`@nbtca/prompt v${APP_INFO.version}`), ''], { signal: skip.signal });
96
+ }
97
+ finally {
98
+ skip.release();
99
+ }
81
100
  }
@@ -1,8 +1,20 @@
1
1
  import { getCapabilities } from './capabilities.js';
2
2
  import { ansi } from './canvas.js';
3
3
  const GRAPHEME_SEGMENTER = new Intl.Segmenter(undefined, { granularity: 'grapheme' });
4
- export function sleep(ms) {
5
- return new Promise((resolve) => setTimeout(resolve, ms));
4
+ export function sleep(ms, signal) {
5
+ return new Promise((resolve) => {
6
+ if (signal?.aborted) {
7
+ resolve();
8
+ return;
9
+ }
10
+ const timer = setTimeout(done, ms);
11
+ signal?.addEventListener('abort', done, { once: true });
12
+ function done() {
13
+ clearTimeout(timer);
14
+ signal?.removeEventListener('abort', done);
15
+ resolve();
16
+ }
17
+ });
6
18
  }
7
19
  export async function typeReveal(lines, opts = {}) {
8
20
  const write = opts.write ??
@@ -15,9 +27,13 @@ export async function typeReveal(lines, opts = {}) {
15
27
  return;
16
28
  }
17
29
  const stepMs = opts.stepMs ?? 45;
18
- for (const line of lines) {
30
+ for (const [index, line] of lines.entries()) {
31
+ if (opts.signal?.aborted) {
32
+ write(lines.slice(index).join('\n') + '\n');
33
+ return;
34
+ }
19
35
  write(line + '\n');
20
- await sleep(stepMs);
36
+ await sleep(stepMs, opts.signal);
21
37
  }
22
38
  }
23
39
  const BRAILLE_BASE = 0x2800;
@@ -72,6 +88,8 @@ export async function materializeBraille(art, paint, opts = {}) {
72
88
  const frameMs = opts.frameMs ?? 35;
73
89
  let shown = 0;
74
90
  for (let f = 1; f <= frameCount; f++) {
91
+ if (opts.signal?.aborted)
92
+ f = frameCount;
75
93
  const target = Math.round((dots.length * f) / frameCount);
76
94
  while (shown < target) {
77
95
  const d = dots[shown];
@@ -86,7 +104,7 @@ export async function materializeBraille(art, paint, opts = {}) {
86
104
  const painter = f === frameCount ? paint : (opts.paintProgress ?? paint);
87
105
  write(painter(renderFrame()) + '\n');
88
106
  if (f < frameCount) {
89
- await sleep(frameMs);
107
+ await sleep(frameMs, opts.signal);
90
108
  write(ansi.cursorUp(lines.length) + ansi.cursorToCol0 + ansi.eraseDown);
91
109
  }
92
110
  }
package/dist/core/text.js CHANGED
@@ -69,12 +69,12 @@ export function padEndV(str, width) {
69
69
  const pad = width - visualWidth(str);
70
70
  return pad > 0 ? str + ' '.repeat(pad) : str;
71
71
  }
72
- export function truncate(str, maxWidth) {
72
+ export function truncate(str, maxWidth, ellipsis = '...') {
73
73
  if (visualWidth(str) <= maxWidth)
74
74
  return str;
75
75
  if (maxWidth <= 0)
76
76
  return '';
77
- const marker = maxWidth >= 3 ? '...' : '.'.repeat(maxWidth);
77
+ const marker = visualWidth(ellipsis) <= maxWidth ? ellipsis : '.'.repeat(maxWidth);
78
78
  const available = maxWidth - visualWidth(marker);
79
79
  let w = 0;
80
80
  let value = '';
@@ -1,11 +1,27 @@
1
1
  import chalk from 'chalk';
2
- import gradient from 'gradient-string';
3
2
  import { pickIcon } from './icons.js';
4
- export const brandGradient = gradient([
5
- { color: '#124689', pos: 0 },
6
- { color: '#0ea5e9', pos: 0.55 },
7
- { color: '#06b6d4', pos: 1 },
8
- ]);
3
+ const BRAND_STOPS = [
4
+ { at: 0, rgb: [0x12, 0x46, 0x89] },
5
+ { at: 0.55, rgb: [0x0e, 0xa5, 0xe9] },
6
+ { at: 1, rgb: [0x06, 0xb6, 0xd4] },
7
+ ];
8
+ function brandColorAt(position) {
9
+ const upper = BRAND_STOPS.findIndex((stop) => stop.at >= position);
10
+ const to = BRAND_STOPS[Math.max(upper, 1)] ?? BRAND_STOPS[2];
11
+ const from = BRAND_STOPS[Math.max(upper, 1) - 1] ?? BRAND_STOPS[0];
12
+ const ratio = (position - from.at) / (to.at - from.at);
13
+ const mix = (index) => Math.round(from.rgb[index] + (to.rgb[index] - from.rgb[index]) * ratio);
14
+ return [mix(0), mix(1), mix(2)];
15
+ }
16
+ export function brandGradient(text) {
17
+ const lines = text.split('\n').map((line) => Array.from(line));
18
+ const span = Math.max(1, ...lines.map((line) => line.length - 1));
19
+ return lines
20
+ .map((line) => line
21
+ .map((char, column) => char.trim() ? chalk.rgb(...brandColorAt(Math.min(1, column / span)))(char) : char)
22
+ .join(''))
23
+ .join('\n');
24
+ }
9
25
  export function brandMark(s) {
10
26
  if (process.env['NO_COLOR'])
11
27
  return s;
@@ -17,7 +33,7 @@ export const c = {
17
33
  success: (s) => chalk.green(s),
18
34
  error: (s) => chalk.red(s),
19
35
  warn: (s) => chalk.yellow(s),
20
- heading: (s) => chalk.bold.white(s),
36
+ heading: (s) => chalk.bold(s),
21
37
  muted: (s) => chalk.dim(s),
22
38
  subtle: (s) => chalk.gray(s),
23
39
  label: (s) => chalk.bold.cyan(s),
@@ -44,14 +60,13 @@ export const glyph = {
44
60
  barFilled: () => pickIcon('█', '#'),
45
61
  barEmpty: () => pickIcon('░', '-'),
46
62
  };
47
- /** Beyond this the app stops stretching; a terminal wider than this keeps the slack. */
48
- export const MAX_FRAME_COLS = 100;
63
+ export const MAX_FRAME_COLS = 120;
49
64
  export const space = {
50
65
  indent: ' ',
51
66
  };
52
67
  export const type = {
53
- heading: (s) => chalk.bold.white(s),
54
- label: (s) => chalk.white(s),
68
+ heading: (s) => chalk.bold(s),
69
+ label: (s) => s,
55
70
  body: (s) => s,
56
71
  hint: (s) => chalk.dim(s),
57
72
  active: (s) => chalk.bold(c.brand(s)),
@@ -1,4 +1,7 @@
1
+ import { addLocalDays } from '../core/calendar-day.js';
2
+ import { fmt, t } from '../i18n/index.js';
1
3
  const UPCOMING_DAYS = 30;
4
+ const YEAR_DAYS = 365;
2
5
  export function weekRange(now) {
3
6
  const start = new Date(now);
4
7
  start.setHours(0, 0, 0, 0);
@@ -13,18 +16,37 @@ export function dayRange(now) {
13
16
  const end = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1);
14
17
  return { start, end };
15
18
  }
19
+ export function eventEnd(event) {
20
+ return (event.end ??
21
+ (event.isAllDay
22
+ ? new Date(event.start.getFullYear(), event.start.getMonth(), event.start.getDate() + 1)
23
+ : event.start));
24
+ }
25
+ function hasEnded(event, now) {
26
+ return event.start < now && eventEnd(event) <= now;
27
+ }
16
28
  export function currentEvents(calendar, now) {
17
29
  const { start } = dayRange(now);
18
30
  const end = new Date(now.getTime() + UPCOMING_DAYS * 86_400_000);
19
- return calendar.inRange(start, end).filter((event) => {
20
- if (event.start >= now)
21
- return true;
22
- const eventEnd = event.end ??
23
- (event.isAllDay
24
- ? new Date(event.start.getFullYear(), event.start.getMonth(), event.start.getDate() + 1)
25
- : event.start);
26
- return eventEnd > now;
27
- });
31
+ return calendar.inRange(start, end).filter((event) => !hasEnded(event, now));
32
+ }
33
+ export function pastYearRange(now) {
34
+ return { start: addLocalDays(now, -YEAR_DAYS), end: now };
35
+ }
36
+ export function pastEvents(calendar, now) {
37
+ const { start, end } = pastYearRange(now);
38
+ return calendar
39
+ .inRange(start, end)
40
+ .filter((event) => hasEnded(event, now))
41
+ .reverse();
42
+ }
43
+ export function searchEvents(calendar, query, now) {
44
+ const pool = calendar.inRange(pastYearRange(now).start, addLocalDays(now, YEAR_DAYS));
45
+ const matches = filterEvents(pool, query);
46
+ return {
47
+ upcoming: matches.filter((event) => !hasEnded(event, now)),
48
+ past: matches.filter((event) => hasEnded(event, now)).reverse(),
49
+ };
28
50
  }
29
51
  export function monthRange(now) {
30
52
  const start = new Date(now.getFullYear(), now.getMonth(), 1, 0, 0, 0, 0);
@@ -49,6 +71,14 @@ export function countdownParts(target, now) {
49
71
  minutes: totalMin % 60,
50
72
  };
51
73
  }
74
+ export function formatDuration(p) {
75
+ const d = t().calendar.duration;
76
+ if (p.days > 0)
77
+ return fmt(d.days, { days: p.days, hours: p.hours });
78
+ if (p.hours > 0)
79
+ return fmt(d.hours, { hours: p.hours, minutes: p.minutes });
80
+ return fmt(d.minutes, { minutes: p.minutes });
81
+ }
52
82
  /** True once a countdown is close enough to call out visually (default: 15
53
83
  * minutes or less). A `past` countdown is never urgent — there's nothing
54
84
  * left to hurry for. */
@@ -2,10 +2,40 @@ import fs from 'fs';
2
2
  import path from 'path';
3
3
  import { getStateDir, getWritableStateDir } from '../config/paths.js';
4
4
  const FEED_FILE = 'calendar-feed.ics';
5
+ const VALIDATORS_FILE = 'calendar-feed.json';
5
6
  const MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
6
- export function saveFeedCache(text, dir) {
7
+ const HEADER_VALUE = /^[\x21-\x7e][\x20-\x7e]*$/;
8
+ function headerValue(value) {
9
+ return typeof value === 'string' && HEADER_VALUE.test(value) ? value : undefined;
10
+ }
11
+ function readValidators(dir) {
12
+ try {
13
+ const data = JSON.parse(fs.readFileSync(path.join(dir, VALIDATORS_FILE), 'utf8'));
14
+ const etag = headerValue(data['etag']);
15
+ const lastModified = headerValue(data['lastModified']);
16
+ return { ...(etag ? { etag } : {}), ...(lastModified ? { lastModified } : {}) };
17
+ }
18
+ catch {
19
+ return {};
20
+ }
21
+ }
22
+ // Validators are written after the text and read before it, so they can never be newer than the text.
23
+ export function saveFeedCache({ text, validators }, dir) {
24
+ try {
25
+ const target = dir ?? getWritableStateDir();
26
+ fs.writeFileSync(path.join(target, FEED_FILE), text, { encoding: 'utf8', mode: 0o600 });
27
+ touchFeedCache(validators, target);
28
+ }
29
+ catch {
30
+ /* best effort */
31
+ }
32
+ }
33
+ export function touchFeedCache(validators, dir) {
7
34
  try {
8
- fs.writeFileSync(path.join(dir ?? getWritableStateDir(), FEED_FILE), text, {
35
+ const target = dir ?? getWritableStateDir();
36
+ const now = new Date();
37
+ fs.utimesSync(path.join(target, FEED_FILE), now, now);
38
+ fs.writeFileSync(path.join(target, VALIDATORS_FILE), JSON.stringify(validators), {
9
39
  encoding: 'utf8',
10
40
  mode: 0o600,
11
41
  });
@@ -16,10 +46,12 @@ export function saveFeedCache(text, dir) {
16
46
  }
17
47
  export function loadFeedCache(dir, maxAgeMs = MAX_AGE_MS) {
18
48
  try {
19
- const file = path.join(dir ?? getStateDir(), FEED_FILE);
49
+ const source = dir ?? getStateDir();
50
+ const validators = readValidators(source);
51
+ const file = path.join(source, FEED_FILE);
20
52
  if (Date.now() - fs.statSync(file).mtimeMs > maxAgeMs)
21
53
  return null;
22
- return fs.readFileSync(file, 'utf8');
54
+ return { text: fs.readFileSync(file, 'utf8'), validators };
23
55
  }
24
56
  catch {
25
57
  return null;