dsh-ustc-campus 0.2.14 → 0.3.0

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.
@@ -0,0 +1,13 @@
1
+ export async function mapLimited(items, concurrency, worker) {
2
+ const results = new Array(items.length);
3
+ let next = 0;
4
+ async function run() {
5
+ while (next < items.length) {
6
+ const index = next++;
7
+ try { results[index] = { status: 'fulfilled', value: await worker(items[index], index) }; }
8
+ catch (reason) { results[index] = { status: 'rejected', reason }; }
9
+ }
10
+ }
11
+ await Promise.all(Array.from({ length: Math.min(concurrency, items.length) }, run));
12
+ return results;
13
+ }
@@ -0,0 +1,519 @@
1
+ import { isIP } from 'node:net';
2
+ import { load } from 'cheerio';
3
+
4
+ import {
5
+ errorText,
6
+ safeHttpUrl,
7
+ sanitizeText,
8
+ shanghaiEpoch
9
+ } from './public-fetch.mjs';
10
+
11
+ const STORE_KEY = 'custom-feeds';
12
+ const STORE_VERSION = 1;
13
+ const STALE_MS = 6 * 60 * 60 * 1000;
14
+ const RETRY_AFTER_FAILURE_MS = 10 * 60 * 1000;
15
+ const FETCH_TIMEOUT_MS = 10_000;
16
+ const MAX_SUBSCRIPTIONS = 15;
17
+ const MAX_ITEMS_PER_SOURCE = 100;
18
+ const MAX_BODY_BYTES = 1024 * 1024;
19
+ const MAX_REDIRECTS = 4;
20
+ const REFRESH_CONCURRENCY = 4;
21
+ const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
22
+
23
+ export class CustomFeedError extends Error {}
24
+
25
+ function isPrivateOrBlockedHost(hostname) {
26
+ const host = String(hostname ?? '').toLowerCase().replace(/^\[|\]$/g, '');
27
+ if (!host) return true;
28
+ if (
29
+ host === 'localhost' ||
30
+ host.endsWith('.localhost') ||
31
+ host.endsWith('.local') ||
32
+ host.endsWith('.internal') ||
33
+ host.endsWith('.lan') ||
34
+ host.endsWith('.home') ||
35
+ host.endsWith('.arpa')
36
+ ) {
37
+ return true;
38
+ }
39
+ if (isIP(host) !== 0) return true;
40
+ return false;
41
+ }
42
+
43
+ /** Validate a user-configured RSS/Atom/JSON subscription URL (HTTPS public host only). */
44
+ export function validateCustomFeedUrl(rawUrl) {
45
+ if (typeof rawUrl !== 'string' || !rawUrl.trim()) {
46
+ throw new CustomFeedError('请提供订阅地址(https:// 开头)。');
47
+ }
48
+ const trimmed = rawUrl.trim();
49
+ if (trimmed.length > 500 || /[\u0000-\u001f\u007f]/.test(trimmed)) {
50
+ throw new CustomFeedError('订阅地址格式无效。');
51
+ }
52
+ let parsed;
53
+ try {
54
+ parsed = new URL(trimmed);
55
+ } catch {
56
+ throw new CustomFeedError('订阅地址不是有效的网址。');
57
+ }
58
+ if (parsed.protocol !== 'https:') {
59
+ throw new CustomFeedError('自定义订阅仅支持 https:// 安全连接。');
60
+ }
61
+ if (parsed.username || parsed.password) {
62
+ throw new CustomFeedError('订阅地址不能包含账号或密码。');
63
+ }
64
+ if (isPrivateOrBlockedHost(parsed.hostname)) {
65
+ throw new CustomFeedError('不允许订阅本机或内网地址。');
66
+ }
67
+ return parsed.href;
68
+ }
69
+
70
+ function hashId(value) {
71
+ let hash = 0x811c9dc5;
72
+ const text = String(value);
73
+ for (let i = 0; i < text.length; i += 1) {
74
+ hash ^= text.charCodeAt(i);
75
+ hash = Math.imul(hash, 0x01000193);
76
+ }
77
+ return (hash >>> 0).toString(36);
78
+ }
79
+
80
+ function shanghaiDateFromEpoch(epochMs) {
81
+ if (!Number.isFinite(epochMs)) return null;
82
+ const d = new Date(epochMs + 8 * 60 * 60 * 1000);
83
+ const y = d.getUTCFullYear();
84
+ const m = String(d.getUTCMonth() + 1).padStart(2, '0');
85
+ const day = String(d.getUTCDate()).padStart(2, '0');
86
+ if (y < 1970 || y > 2100) return null;
87
+ return `${y}-${m}-${day}`;
88
+ }
89
+
90
+ function parseDateValue(raw) {
91
+ if (raw == null) return null;
92
+ if (Number.isFinite(raw)) {
93
+ const date = shanghaiDateFromEpoch(raw);
94
+ return date ? { date, epoch: raw } : null;
95
+ }
96
+ const text = sanitizeText(String(raw), 100);
97
+ if (!text) return null;
98
+
99
+ const ymd = text.match(/(\d{4})\s*[-/.年]\s*(\d{1,2})\s*[-/.月]\s*(\d{1,2})\s*日?/);
100
+ if (ymd) {
101
+ const epoch = shanghaiEpoch(Number(ymd[1]), Number(ymd[2]), Number(ymd[3]));
102
+ if (epoch != null) {
103
+ return {
104
+ date: `${ymd[1]}-${String(ymd[2]).padStart(2, '0')}-${String(ymd[3]).padStart(2, '0')}`,
105
+ epoch
106
+ };
107
+ }
108
+ }
109
+
110
+ const parsed = Date.parse(text);
111
+ if (Number.isFinite(parsed)) {
112
+ const date = shanghaiDateFromEpoch(parsed);
113
+ if (date) return { date, epoch: parsed };
114
+ }
115
+ return null;
116
+ }
117
+
118
+ function safeItemLink(raw, origin) {
119
+ const href = safeHttpUrl(raw, origin);
120
+ if (!href) return null;
121
+ try {
122
+ const host = new URL(href).hostname;
123
+ if (isPrivateOrBlockedHost(host)) return null;
124
+ } catch {
125
+ return null;
126
+ }
127
+ return href;
128
+ }
129
+
130
+ function resolveIntent(rawIntent, defaultIntent) {
131
+ if (rawIntent === 'activity' || rawIntent === 'notice') return rawIntent;
132
+ if (defaultIntent === 'activity' || defaultIntent === 'notice') return defaultIntent;
133
+ return undefined;
134
+ }
135
+
136
+ /** Parse RSS 2.0, Atom XML, or static JSON feed content into normalized campus feed items. */
137
+ export function parseCustomFeedContent(body, subscription, nowMs = Date.now()) {
138
+ const rawText = typeof body === 'string' ? body : JSON.stringify(body ?? '');
139
+ const trimmed = rawText.trim();
140
+ if (!trimmed) throw new Error('订阅返回内容为空');
141
+
142
+ const sourceOrigin = new URL(subscription.url).origin;
143
+ const format = subscription.format === 'json' || subscription.format === 'xml'
144
+ ? subscription.format
145
+ : (trimmed.startsWith('{') || trimmed.startsWith('[') ? 'json' : 'xml');
146
+
147
+ const items = [];
148
+ const seen = new Set();
149
+
150
+ if (format === 'json') {
151
+ let parsed;
152
+ try {
153
+ parsed = JSON.parse(trimmed);
154
+ } catch {
155
+ throw new Error('JSON 订阅内容解析失败');
156
+ }
157
+ const list = Array.isArray(parsed) ? parsed : (Array.isArray(parsed?.items) ? parsed.items : null);
158
+ if (!list) throw new Error('JSON 订阅缺少 items 数组');
159
+
160
+ for (const entry of list.slice(0, MAX_ITEMS_PER_SOURCE)) {
161
+ if (!entry || typeof entry !== 'object') continue;
162
+ const title = sanitizeText(String(entry.title ?? ''), 500);
163
+ if (!title) continue;
164
+ const url = entry.url ? safeItemLink(String(entry.url), sourceOrigin) : (entry.link ? safeItemLink(String(entry.link), sourceOrigin) : null);
165
+ const start = Number.isFinite(entry.start) ? entry.start : null;
166
+ const end = Number.isFinite(entry.end) && entry.end >= (start ?? 0) ? entry.end : null;
167
+ const dateParsed = parseDateValue(entry.date ?? entry.publishedAt ?? start);
168
+ const date = dateParsed?.date ?? shanghaiDateFromEpoch(nowMs);
169
+ const idBase = sanitizeText(String(entry.id ?? ''), 120) || hashId(`${url ?? ''}|${date ?? ''}|${title}`);
170
+ const id = `${subscription.id}:${idBase}`.slice(0, 200);
171
+ if (seen.has(id)) continue;
172
+ seen.add(id);
173
+
174
+ const intent = resolveIntent(entry.intent, subscription.defaultIntent);
175
+ items.push({
176
+ id,
177
+ source: subscription.id,
178
+ category: subscription.category || 'activity',
179
+ ...(intent ? { intent } : {}),
180
+ ...(entry.requiresRegistration === true ? { requiresRegistration: true } : {}),
181
+ title,
182
+ url,
183
+ date,
184
+ time: entry.time ? sanitizeText(String(entry.time), 40) : null,
185
+ location: entry.location ? sanitizeText(String(entry.location), 300) : null,
186
+ start,
187
+ end,
188
+ secondClassroom: entry.secondClassroom === true,
189
+ ...(entry.organizer ? { organizer: sanitizeText(String(entry.organizer), 120) } : {}),
190
+ reason: '',
191
+ past: false
192
+ });
193
+ }
194
+ return items;
195
+ }
196
+
197
+ // XML mode (RSS 2.0 <item> or Atom <entry>)
198
+ const $ = load(trimmed, { xmlMode: true });
199
+ const rssItems = $('item').toArray();
200
+ const atomEntries = rssItems.length === 0 ? $('entry').toArray() : [];
201
+ const nodes = rssItems.length > 0 ? rssItems : atomEntries;
202
+ if (nodes.length === 0 && !/<(?:rss|feed|channel)\b/i.test(trimmed)) {
203
+ throw new Error('无法识别的 RSS / Atom 订阅格式');
204
+ }
205
+
206
+ for (const node of nodes.slice(0, MAX_ITEMS_PER_SOURCE)) {
207
+ const el = $(node);
208
+ const title = sanitizeText(el.children('title').first().text(), 500);
209
+ if (!title) continue;
210
+
211
+ let rawLink = sanitizeText(el.children('link').first().text(), 500);
212
+ if (!rawLink) {
213
+ const linkAttr = el.children('link[rel="alternate"]').first().attr('href')
214
+ || el.children('link[href]').first().attr('href');
215
+ rawLink = linkAttr ? linkAttr.trim() : '';
216
+ }
217
+ const url = rawLink ? safeItemLink(rawLink, sourceOrigin) : null;
218
+
219
+ const rawDate = el.children('pubDate, published, updated, dc\\:date, date').first().text();
220
+ const dateParsed = parseDateValue(rawDate);
221
+ const date = dateParsed?.date ?? shanghaiDateFromEpoch(nowMs);
222
+
223
+ const guid = sanitizeText(el.children('guid, id').first().text(), 140);
224
+ const key = guid ? hashId(guid) : hashId(`${url ?? ''}|${date ?? ''}|${title}`);
225
+ const id = `${subscription.id}:${key}`.slice(0, 200);
226
+ if (seen.has(id)) continue;
227
+ seen.add(id);
228
+
229
+ const intent = resolveIntent(undefined, subscription.defaultIntent);
230
+ items.push({
231
+ id,
232
+ source: subscription.id,
233
+ category: subscription.category || 'activity',
234
+ ...(intent ? { intent } : {}),
235
+ title,
236
+ url,
237
+ date,
238
+ time: null,
239
+ location: null,
240
+ start: null,
241
+ end: null,
242
+ secondClassroom: false,
243
+ reason: '',
244
+ past: false
245
+ });
246
+ }
247
+ return items;
248
+ }
249
+
250
+ async function fetchSafeCustomBody(startUrl, fetchImpl, signal) {
251
+ let currentUrl = validateCustomFeedUrl(startUrl);
252
+ for (let hop = 0; hop <= MAX_REDIRECTS; hop += 1) {
253
+ const timeoutSignal = AbortSignal.timeout(FETCH_TIMEOUT_MS);
254
+ const combined = signal && typeof AbortSignal.any === 'function'
255
+ ? AbortSignal.any([timeoutSignal, signal])
256
+ : timeoutSignal;
257
+
258
+ const response = await fetchImpl(currentUrl, {
259
+ redirect: 'manual',
260
+ signal: combined,
261
+ headers: {
262
+ accept: 'application/rss+xml, application/atom+xml, application/xml, application/json, text/xml;q=0.9, */*;q=0.5',
263
+ 'user-agent': 'dsh-ustc-campus/0.2'
264
+ }
265
+ });
266
+
267
+ if (REDIRECT_STATUSES.has(response.status)) {
268
+ const loc = response.headers?.get?.('location');
269
+ if (!loc) throw new Error('订阅重定向缺少目标地址');
270
+ currentUrl = validateCustomFeedUrl(new URL(loc, currentUrl).href);
271
+ continue;
272
+ }
273
+
274
+ if (!response.ok) {
275
+ throw new Error(`订阅返回状态 ${response.status}`);
276
+ }
277
+
278
+ const text = await response.text();
279
+ if (typeof text !== 'string' || Buffer.byteLength(text, 'utf8') > MAX_BODY_BYTES) {
280
+ throw new Error('订阅内容超过 1 MiB 限制');
281
+ }
282
+ return text;
283
+ }
284
+ throw new Error('订阅重定向次数过多');
285
+ }
286
+
287
+ function emptyStore() {
288
+ return { version: STORE_VERSION, subscriptions: {} };
289
+ }
290
+
291
+ function loadStore(read) {
292
+ const out = emptyStore();
293
+ let raw;
294
+ try {
295
+ raw = read(STORE_KEY);
296
+ } catch {
297
+ return out;
298
+ }
299
+ if (!raw || typeof raw !== 'object' || !raw.subscriptions || typeof raw.subscriptions !== 'object') {
300
+ return out;
301
+ }
302
+ for (const [id, entry] of Object.entries(raw.subscriptions).slice(0, MAX_SUBSCRIPTIONS)) {
303
+ if (!entry || typeof entry !== 'object') continue;
304
+ try {
305
+ const url = validateCustomFeedUrl(entry.url);
306
+ const label = sanitizeText(String(entry.label ?? ''), 80);
307
+ if (!id || !label) continue;
308
+ out.subscriptions[id] = {
309
+ id,
310
+ label,
311
+ url,
312
+ format: ['auto', 'xml', 'json'].includes(entry.format) ? entry.format : 'auto',
313
+ defaultIntent: ['auto', 'activity', 'notice'].includes(entry.defaultIntent) ? entry.defaultIntent : 'auto',
314
+ category: sanitizeText(String(entry.category ?? 'activity'), 32) || 'activity',
315
+ items: Array.isArray(entry.items) ? entry.items.slice(0, MAX_ITEMS_PER_SOURCE) : [],
316
+ fetchedAt: Number.isFinite(entry.fetchedAt) ? entry.fetchedAt : null,
317
+ error: typeof entry.error === 'string' ? sanitizeText(entry.error, 200) : null
318
+ };
319
+ } catch {
320
+ /* drop corrupted invalid entry */
321
+ }
322
+ }
323
+ return out;
324
+ }
325
+
326
+ function memoryStore() {
327
+ const map = new Map();
328
+ return {
329
+ read: (k) => map.get(k),
330
+ write: (k, v) => map.set(k, v)
331
+ };
332
+ }
333
+
334
+ /** Manage user-configured custom RSS / Atom / static JSON feed subscriptions. */
335
+ export function createCustomFeeds(options = {}) {
336
+ const fallback = memoryStore();
337
+ const read = typeof options.read === 'function' ? options.read : fallback.read;
338
+ const write = typeof options.write === 'function' ? options.write : fallback.write;
339
+ const fetchImpl = options.fetch ?? globalThis.fetch;
340
+ const now = typeof options.now === 'function' ? options.now : Date.now;
341
+
342
+ const store = loadStore(read);
343
+ let revision = 0;
344
+ let refreshing = null;
345
+ let lastAttempt = 0;
346
+ let closed = false;
347
+ let controller = null;
348
+
349
+ function persist() {
350
+ revision++;
351
+ try {
352
+ write(STORE_KEY, store);
353
+ } catch {
354
+ /* best effort persistence */
355
+ }
356
+ }
357
+
358
+ function list() {
359
+ return Object.values(store.subscriptions).map((sub) => ({
360
+ id: sub.id,
361
+ label: sub.label,
362
+ url: sub.url,
363
+ format: sub.format,
364
+ defaultIntent: sub.defaultIntent,
365
+ category: sub.category,
366
+ itemCount: sub.items.length,
367
+ fetchedAt: sub.fetchedAt,
368
+ error: sub.error
369
+ }));
370
+ }
371
+
372
+ function add({ label, url, format = 'auto', defaultIntent = 'auto', category = 'activity' } = {}) {
373
+ const cleanUrl = validateCustomFeedUrl(url);
374
+ const cleanLabel = sanitizeText(String(label ?? ''), 80);
375
+ if (!cleanLabel) throw new CustomFeedError('请提供订阅名称(label)。');
376
+ const cleanFormat = ['auto', 'xml', 'json'].includes(format) ? format : 'auto';
377
+ const cleanIntent = ['auto', 'activity', 'notice'].includes(defaultIntent) ? defaultIntent : 'auto';
378
+ const cleanCat = sanitizeText(String(category ?? 'activity'), 32) || 'activity';
379
+
380
+ const duplicate = Object.values(store.subscriptions).find((s) => s.url === cleanUrl);
381
+ if (duplicate) {
382
+ return { status: 'already_exists', subscription: list().find((s) => s.id === duplicate.id) };
383
+ }
384
+ if (Object.keys(store.subscriptions).length >= MAX_SUBSCRIPTIONS) {
385
+ throw new CustomFeedError(`最多只能添加 ${MAX_SUBSCRIPTIONS} 个自定义订阅源。`);
386
+ }
387
+
388
+ const id = `custom:${hashId(cleanUrl)}`;
389
+ store.subscriptions[id] = {
390
+ id,
391
+ label: cleanLabel,
392
+ url: cleanUrl,
393
+ format: cleanFormat,
394
+ defaultIntent: cleanIntent,
395
+ category: cleanCat,
396
+ items: [],
397
+ fetchedAt: null,
398
+ error: null
399
+ };
400
+ persist();
401
+ return { status: 'added', subscription: list().find((s) => s.id === id) };
402
+ }
403
+
404
+ function remove({ id } = {}) {
405
+ const cleanId = sanitizeText(String(id ?? ''), 100);
406
+ if (!cleanId || !Object.hasOwn(store.subscriptions, cleanId)) {
407
+ throw new CustomFeedError('找不到该自定义订阅源。');
408
+ }
409
+ const removed = store.subscriptions[cleanId];
410
+ delete store.subscriptions[cleanId];
411
+ persist();
412
+ return { status: 'removed', id: cleanId, label: removed.label };
413
+ }
414
+
415
+ function getSourceStatuses() {
416
+ return Object.values(store.subscriptions).map((sub) => ({
417
+ id: sub.id,
418
+ label: sub.label,
419
+ category: sub.category,
420
+ fetchedAt: sub.fetchedAt ?? null,
421
+ error: sub.error ?? null
422
+ }));
423
+ }
424
+
425
+ function getItems() {
426
+ return Object.values(store.subscriptions).flatMap((sub) => sub.items);
427
+ }
428
+
429
+ function getItemById(id) {
430
+ for (const sub of Object.values(store.subscriptions)) {
431
+ const found = sub.items.find((x) => x.id === id);
432
+ if (found) return found;
433
+ }
434
+ return null;
435
+ }
436
+
437
+ function getSourceMeta(id) {
438
+ const sub = store.subscriptions[id];
439
+ if (!sub) return null;
440
+ return {
441
+ id: sub.id,
442
+ label: sub.label,
443
+ category: sub.category,
444
+ kind: sub.defaultIntent === 'activity' ? 'event' : 'news'
445
+ };
446
+ }
447
+
448
+ async function refresh({ force = false } = {}) {
449
+ const subs = Object.values(store.subscriptions);
450
+ if (closed || subs.length === 0) return { sources: getSourceStatuses() };
451
+ if (refreshing) return refreshing;
452
+
453
+ const nowMs = now();
454
+ const staleSubs = force
455
+ ? subs
456
+ : subs.filter((s) => !Number.isFinite(s.fetchedAt) || Boolean(s.error) || nowMs - s.fetchedAt >= STALE_MS);
457
+ if (staleSubs.length === 0) return { sources: getSourceStatuses() };
458
+ if (!force && lastAttempt > 0 && nowMs - lastAttempt < RETRY_AFTER_FAILURE_MS) {
459
+ return { sources: getSourceStatuses() };
460
+ }
461
+
462
+ lastAttempt = nowMs;
463
+ controller = new AbortController();
464
+ const signal = controller.signal;
465
+
466
+ refreshing = (async () => {
467
+ let nextIdx = 0;
468
+ async function worker() {
469
+ while (nextIdx < staleSubs.length && !closed) {
470
+ const sub = staleSubs[nextIdx];
471
+ nextIdx += 1;
472
+ try {
473
+ const body = await fetchSafeCustomBody(sub.url, fetchImpl, signal);
474
+ const items = parseCustomFeedContent(body, sub, now());
475
+ sub.items = items;
476
+ sub.fetchedAt = now();
477
+ sub.error = null;
478
+ } catch (error) {
479
+ sub.error = errorText(error, '订阅暂时不可用');
480
+ }
481
+ }
482
+ }
483
+ await Promise.all(
484
+ Array.from({ length: Math.min(REFRESH_CONCURRENCY, staleSubs.length) }, () => worker())
485
+ );
486
+ if (!closed) persist();
487
+ return { sources: getSourceStatuses() };
488
+ })().finally(() => {
489
+ refreshing = null;
490
+ controller = null;
491
+ });
492
+
493
+ return refreshing;
494
+ }
495
+
496
+ function close() {
497
+ closed = true;
498
+ try {
499
+ controller?.abort();
500
+ } catch {
501
+ /* ignore */
502
+ }
503
+ controller = null;
504
+ refreshing = null;
505
+ }
506
+
507
+ return {
508
+ list,
509
+ add,
510
+ remove,
511
+ refresh,
512
+ revision: () => revision,
513
+ getItems,
514
+ getSourceStatuses,
515
+ getItemById,
516
+ getSourceMeta,
517
+ close
518
+ };
519
+ }
package/src/exams.mjs CHANGED
@@ -526,7 +526,7 @@ export function parseExamTable(html, { from, through } = {}) {
526
526
  };
527
527
  }
528
528
 
529
- export function createExams({ withSchoolContext } = {}) {
529
+ export function createExams({ withSchoolContext, cache } = {}) {
530
530
  if (typeof withSchoolContext !== 'function') {
531
531
  throw new TypeError('withSchoolContext must be a function');
532
532
  }
@@ -567,8 +567,7 @@ export function createExams({ withSchoolContext } = {}) {
567
567
  return value;
568
568
  }
569
569
 
570
- async function read(input = {}) {
571
- const range = readRange(input);
570
+ function load() {
572
571
  return run(async (context) => {
573
572
  const studentId = await discoverStudentId(context);
574
573
  const path = `${EXAM_INFO_PREFIX}${studentId}`;
@@ -578,11 +577,9 @@ export function createExams({ withSchoolContext } = {}) {
578
577
  (candidate) => candidate === path,
579
578
  '考试安排'
580
579
  );
581
- const parsed = parseExamTable(page.text, range);
580
+ const parsed = parseExamTable(page.text);
582
581
  return {
583
582
  state: parsed.entries.length > 0 ? 'ok' : 'empty',
584
- from: range.from,
585
- through: range.through,
586
583
  timezone: 'Asia/Shanghai',
587
584
  source: EXAM_SOURCE,
588
585
  scope: 'current_semester',
@@ -601,5 +598,22 @@ export function createExams({ withSchoolContext } = {}) {
601
598
  });
602
599
  }
603
600
 
604
- return Object.freeze({ read });
601
+ function snapshot({ force = false } = {}) {
602
+ return cache ? cache.refresh('exams', load, {
603
+ maxAge: 2 * 60 * 60_000,
604
+ force,
605
+ backoff: error => !['not_connected', 'authentication_required', 'SCHOOL_NOT_CONNECTED'].includes(error?.code)
606
+ }) : load();
607
+ }
608
+
609
+ async function read(input = {}) {
610
+ const range = readRange(input);
611
+ const all = await snapshot();
612
+ if (!all) fail('学校会话已变化或暂不可用,请重新查询考试安排。', 'not_connected');
613
+ const entries = all.entries.filter(({ date }) => date >= range.from && date <= range.through);
614
+ return { ...all, ...range, state: entries.length ? 'ok' : 'empty', entries,
615
+ count: entries.length, outsideRange: all.entries.length - entries.length };
616
+ }
617
+
618
+ return Object.freeze({ read, snapshot });
605
619
  }