vomebook commited on
Commit
17df17b
·
1 Parent(s): 03490d9

Harden chapter search Worker protocol with strict checks

Browse files
Dockerfile CHANGED
@@ -80,6 +80,7 @@ RUN npx --no-install pyright --project pyrightconfig.json \
80
  && node scripts/reader/check_chapter_search_core_coverage.mjs \
81
  && node scripts/reader/check_chapter_search_proxy_coverage.mjs \
82
  && node scripts/reader/check_chapter_search_index_coverage.mjs \
 
83
  && node --test tests/gates/test_tap_contracts.mjs \
84
  && node tests/reader/pdf-v3/test_dataset_primary_policy.mjs \
85
  && node scripts/search/check_download_controller_coverage.mjs \
 
80
  && node scripts/reader/check_chapter_search_core_coverage.mjs \
81
  && node scripts/reader/check_chapter_search_proxy_coverage.mjs \
82
  && node scripts/reader/check_chapter_search_index_coverage.mjs \
83
+ && node scripts/reader/check_chapter_search_worker_coverage.mjs \
84
  && node --test tests/gates/test_tap_contracts.mjs \
85
  && node tests/reader/pdf-v3/test_dataset_primary_policy.mjs \
86
  && node scripts/search/check_download_controller_coverage.mjs \
config/types/jsconfig.chapter-worker-strict.json ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "compilerOptions": {
3
+ "allowJs": true,
4
+ "checkJs": true,
5
+ "noEmit": true,
6
+ "strict": true,
7
+ "target": "esnext",
8
+ "lib": [
9
+ "esnext",
10
+ "webworker"
11
+ ],
12
+ "module": "esnext",
13
+ "moduleResolution": "bundler",
14
+ "moduleDetection": "force"
15
+ },
16
+ "files": [
17
+ "../../static/reader/search/workers/reader-chapter-search-worker.mjs"
18
+ ]
19
+ }
package.json CHANGED
@@ -19,7 +19,7 @@
19
  "scripts": {
20
  "lint": "eslint static scripts tests --max-warnings 0",
21
  "markup": "node scripts/check_markup.mjs",
22
- "types": "tsc --project config/types/jsconfig.check.json && tsc --project config/types/jsconfig.service-worker.json && tsc --project config/types/jsconfig.service-worker-strict.json && tsc --project config/types/jsconfig.strict.json && tsc --project config/types/jsconfig.search-exact.json && tsc --project config/types/jsconfig.reader-exact.json",
23
  "check:static": "npm run lint && npm run markup && npm run types && python3 -B scripts/check_strict_inventory.py"
24
  },
25
  "_overrideNote": "minimatch 11.0.3 addresses GHSA-g3hv-75wg-m249 in the 10.x dependency; rerun checker regressions when updating ESLint.",
 
19
  "scripts": {
20
  "lint": "eslint static scripts tests --max-warnings 0",
21
  "markup": "node scripts/check_markup.mjs",
22
+ "types": "tsc --project config/types/jsconfig.check.json && tsc --project config/types/jsconfig.service-worker.json && tsc --project config/types/jsconfig.service-worker-strict.json && tsc --project config/types/jsconfig.chapter-worker-strict.json && tsc --project config/types/jsconfig.strict.json && tsc --project config/types/jsconfig.search-exact.json && tsc --project config/types/jsconfig.reader-exact.json",
23
  "check:static": "npm run lint && npm run markup && npm run types && python3 -B scripts/check_strict_inventory.py"
24
  },
25
  "_overrideNote": "minimatch 11.0.3 addresses GHSA-g3hv-75wg-m249 in the 10.x dependency; rerun checker regressions when updating ESLint.",
quality/baselines/strict-inventory-debt.json CHANGED
@@ -27,7 +27,6 @@
27
  "static/reader/search/reader-dom-search.mjs",
28
  "static/reader/search/reader-search-backends.mjs",
29
  "static/reader/search/reader-search-controller.mjs",
30
- "static/reader/search/workers/reader-chapter-search-worker.mjs",
31
  "static/reader/search/workers/reader-pdf-book-search-worker.mjs",
32
  "static/reader/ui/reader-bookmarks.mjs",
33
  "static/reader/ui/reader-navigation.mjs",
 
27
  "static/reader/search/reader-dom-search.mjs",
28
  "static/reader/search/reader-search-backends.mjs",
29
  "static/reader/search/reader-search-controller.mjs",
 
30
  "static/reader/search/workers/reader-pdf-book-search-worker.mjs",
31
  "static/reader/ui/reader-bookmarks.mjs",
32
  "static/reader/ui/reader-navigation.mjs",
scripts/check_strict_inventory.py CHANGED
@@ -64,7 +64,8 @@ def inventory_errors(root: Path, js_strict: set[str], js_basic: set[str],
64
 
65
  def compiler_files(root: Path, config: str) -> set[str]:
66
  if config not in ("config/types/jsconfig.check.json", "config/types/jsconfig.service-worker.json",
67
- "config/types/jsconfig.service-worker-strict.json", "config/types/jsconfig.strict.json"):
 
68
  raise ValueError("unknown TypeScript configuration")
69
  node = shutil.which("node")
70
  if node is None:
@@ -88,7 +89,8 @@ def main() -> int:
88
  basic = (compiler_files(ROOT, "config/types/jsconfig.check.json")
89
  | compiler_files(ROOT, "config/types/jsconfig.service-worker.json"))
90
  strict = (compiler_files(ROOT, "config/types/jsconfig.strict.json")
91
- | compiler_files(ROOT, "config/types/jsconfig.service-worker-strict.json"))
 
92
  py_config = json.loads((ROOT / "pyrightconfig.strict.json").read_text())
93
  if py_config.get("typeCheckingMode") != "strict":
94
  raise RuntimeError("backend strict type gate must use strict mode")
 
64
 
65
  def compiler_files(root: Path, config: str) -> set[str]:
66
  if config not in ("config/types/jsconfig.check.json", "config/types/jsconfig.service-worker.json",
67
+ "config/types/jsconfig.service-worker-strict.json", "config/types/jsconfig.chapter-worker-strict.json",
68
+ "config/types/jsconfig.strict.json"):
69
  raise ValueError("unknown TypeScript configuration")
70
  node = shutil.which("node")
71
  if node is None:
 
89
  basic = (compiler_files(ROOT, "config/types/jsconfig.check.json")
90
  | compiler_files(ROOT, "config/types/jsconfig.service-worker.json"))
91
  strict = (compiler_files(ROOT, "config/types/jsconfig.strict.json")
92
+ | compiler_files(ROOT, "config/types/jsconfig.service-worker-strict.json")
93
+ | compiler_files(ROOT, "config/types/jsconfig.chapter-worker-strict.json"))
94
  py_config = json.loads((ROOT / "pyrightconfig.strict.json").read_text())
95
  if py_config.get("typeCheckingMode") != "strict":
96
  raise RuntimeError("backend strict type gate must use strict mode")
scripts/reader/check_chapter_search_worker_coverage.mjs ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // V8 coverage for chapter-search Worker protocol and loader, not complete Reader coverage.
2
+ import {spawnSync} from 'node:child_process';
3
+ import {hasPassingTapContracts} from '../check_tap_contracts.mjs';
4
+ const minimum = [100, 92, 100];
5
+ const test = 'tests/reader/chapter-search/test_reader_chapter_worker.mjs';
6
+ const marker = 'chapter Worker: transport, integrity, cancellation, retry and paging passed';
7
+ const result = spawnSync(process.execPath, ['--test', '--test-concurrency=1', '--test-reporter=tap',
8
+ '--experimental-test-coverage', '--test-coverage-include=**/static/reader/search/workers/reader-chapter-search-worker.mjs',
9
+ ...minimum.map((value,index)=>`--test-coverage-${['lines','branches','functions'][index]}=${value}`),test], {encoding:'utf8'});
10
+ if (result.stdout) process.stdout.write(result.stdout);
11
+ if (result.stderr) process.stderr.write(result.stderr);
12
+ if (result.error) throw result.error;
13
+ const text=result.stdout||'', lines=text.split(/\r?\n/);
14
+ const rows=lines.flatMap(line=>{
15
+ const match=/^\s*#\s*reader-chapter-search-worker\.mjs\s*\|\s*(\d+(?:\.\d+)?)\s*\|\s*(\d+(?:\.\d+)?)\s*\|\s*(\d+(?:\.\d+)?)\s*\|/.exec(line);
16
+ return match?[match.slice(1).map(Number)]:[];
17
+ });
18
+ const summaries=['1..1','# tests 1','# pass 1','# fail 0','# cancelled 0','# skipped 0','# todo 0'];
19
+ if(result.status!==0 || !hasPassingTapContracts(text,[{name:test,marker}]) || rows.length!==1 ||
20
+ rows[0].some((value,index)=>value<minimum[index]) ||
21
+ !summaries.every(value=>lines.filter(line=>line===value).length===1) ||
22
+ ['# tests ','# pass ','# fail ','# cancelled ','# skipped ','# todo '].some(prefix=>
23
+ lines.filter(line=>line.startsWith(prefix)).length!==1) ||
24
+ lines.filter(line=>/^# duration_ms \d+(?:\.\d+)?$/.test(line)).length!==1 ||
25
+ ['# start of coverage report','# end of coverage report'].some(value=>lines.filter(line=>line===value).length!==1)) {
26
+ console.error('Chapter search Worker requires its passing contract and exactly one source row above each minimum');
27
+ process.exitCode=1;
28
+ }
static/reader/search/reader-chapter-search-core.mjs CHANGED
@@ -1,4 +1,4 @@
1
- /** @typedef {{index: number, title: string, path: string, text: string, bigramFilter?: Uint8Array | undefined}} SearchChapter */
2
  /** @typedef {{ordinal: number, chapterIndex: number, start: number}} SearchCheckpoint */
3
  /** @typedef {{text: string, matchStart: number, matchLength: number, prefix: string, suffix: string}} SearchSnippet */
4
  /** @typedef {{chapterIndex: number, start: number, length: number, location: string, snippet: SearchSnippet}} SearchResult */
@@ -41,10 +41,11 @@ export function queryBigramFilters(query) {
41
  return characters.slice(1).map((character, index) => bigramHashes(characters[index] + character));
42
  }
43
 
44
- /** @param {SearchChapter} chapter @param {number[][] | null} filters */
45
- export function chapterMayContainBigrams(chapter, filters) {
46
- const bloom = chapter.bigramFilter;
47
- if (!filters || !bloom) return true;
 
48
  const mask = bloom.length * 8 - 1;
49
  for (const hashes of filters) for (const hash of hashes) {
50
  const bit = hash & mask;
@@ -52,6 +53,22 @@ export function chapterMayContainBigrams(chapter, filters) {
52
  }
53
  return true;
54
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
 
56
  /** @param {RegExp} pattern @param {string} part @param {number} start @param {number} next
57
  * @param {(start: number, length: number) => unknown} visit @returns {{next: number, stopped: boolean}} */
 
1
+ /** @typedef {{index: number, title?: unknown, path: string, text: string, bigramFilter?: unknown}} SearchChapter */
2
  /** @typedef {{ordinal: number, chapterIndex: number, start: number}} SearchCheckpoint */
3
  /** @typedef {{text: string, matchStart: number, matchLength: number, prefix: string, suffix: string}} SearchSnippet */
4
  /** @typedef {{chapterIndex: number, start: number, length: number, location: string, snippet: SearchSnippet}} SearchResult */
 
41
  return characters.slice(1).map((character, index) => bigramHashes(characters[index] + character));
42
  }
43
 
44
+ /** @param {unknown} value @param {string} key @returns {unknown} */
45
+ function filterProperty(value, key) { return Reflect.get(Object(value), key); }
46
+
47
+ /** @param {Uint8Array} bloom @param {number[][]} filters */
48
+ function typedBloomMayContain(bloom, filters) {
49
  const mask = bloom.length * 8 - 1;
50
  for (const hashes of filters) for (const hash of hashes) {
51
  const bit = hash & mask;
 
53
  }
54
  return true;
55
  }
56
+ /** @param {unknown} bloom @param {number[][]} filters */
57
+ function legacyBloomMayContain(bloom, filters) {
58
+ const mask = Number(filterProperty(bloom, "length")) * 8 - 1;
59
+ for (const hashes of filters) for (const hash of hashes) {
60
+ const bit = hash & mask;
61
+ if (!(Number(filterProperty(bloom, String(bit >> 3))) & (1 << (bit & 7)))) return false;
62
+ }
63
+ return true;
64
+ }
65
+
66
+ /** @param {SearchChapter} chapter @param {number[][] | null} filters */
67
+ export function chapterMayContainBigrams(chapter, filters) {
68
+ const bloom = chapter.bigramFilter;
69
+ if (!filters || !bloom) return true;
70
+ return bloom instanceof Uint8Array ? typedBloomMayContain(bloom, filters) : legacyBloomMayContain(bloom, filters);
71
+ }
72
 
73
  /** @param {RegExp} pattern @param {string} part @param {number} start @param {number} next
74
  * @param {(start: number, length: number) => unknown} visit @returns {{next: number, stopped: boolean}} */
static/reader/search/workers/reader-chapter-search-worker.mjs CHANGED
@@ -4,7 +4,9 @@ import {countMatches, resultPage, aborted, PAGE_SIZE} from "../reader-chapter-se
4
  import {isSearchIndexProxyURL} from "../reader-chapter-search-proxy-url.mjs";
5
  import {validateIndex} from "../reader-chapter-search-index.mjs";
6
 
 
7
  async function readBounded(stream, limit, signal) {
 
8
  const reader = stream.getReader(), chunks = [];
9
  let size = 0;
10
  const cancel = () => reader.cancel().catch(() => {});
@@ -33,72 +35,136 @@ async function readBounded(stream, limit, signal) {
33
  }
34
 
35
 
36
- let configuration, indexPromise, chapters, active = 0, session, loadController;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  async function loadIndex() {
38
  if (chapters) return chapters;
39
  if (indexPromise) return indexPromise;
40
  const controller = new AbortController();
41
  loadController = controller;
42
  const timer = setTimeout(() => controller.abort(), 60000);
43
- indexPromise = (async () => {
44
- const { index, chapters: expected } = configuration;
45
- const url = new URL(index.url, self.location.origin);
46
- if (!isSearchIndexProxyURL(url, self.location.origin) ||
47
- !Number.isSafeInteger(index.bytes) || index.bytes <= 0 || index.bytes > PACKED_LIMIT ||
48
- !/^[0-9a-f]{64}$/.test(index.sha256)) throw new Error("全文搜索索引无效");
49
- const response = await fetch(url, { signal: controller.signal, credentials: "same-origin" });
50
- if (!response.ok) throw new Error(`全文搜索加载失败(HTTP ${response.status}),请重试`);
51
- const bytes = await readBounded(response.body, PACKED_LIMIT, controller.signal);
52
- const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
53
- const sha = [...digest].map(value => value.toString(16).padStart(2, "0")).join("");
54
- if (bytes.length !== index.bytes || sha !== index.sha256) throw new Error("全文搜索索引校验失败,请重试");
55
- const stream = new Blob([bytes]).stream().pipeThrough(new DecompressionStream("gzip"));
56
- const text = await readBounded(stream, TEXT_LIMIT, controller.signal);
57
- const loaded = validateIndex(JSON.parse(new TextDecoder().decode(text)), expected, index.text_profile);
58
- if (controller.signal.aborted) throw aborted();
59
- chapters = loaded;
60
- return loaded;
61
- })().finally(() => {
62
  clearTimeout(timer);
63
- indexPromise = null;
64
  if (loadController === controller) loadController = null;
65
  });
66
  return indexPromise;
67
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
  if (typeof self !== "undefined" && typeof self.postMessage === "function") {
70
- self.onmessage = async ({ data }) => {
 
 
 
 
 
 
 
 
71
  if (data.type === "init") { configuration = data.configuration; return; }
72
  if (data.type === "cancel") { active++; session = null; loadController?.abort(); return; }
73
- const token = ++active, current = () => token === active;
74
- try {
75
- let offset = 0;
76
- if (data.type === "search") {
77
- session = null;
78
- const query = String(data.query || "").trim().replace(/\s+/gu, " ");
79
- if (!query || query.length > 2048) throw new Error("请输入 1–2048 个字符");
80
- // A cancelled download must settle before a later search retries it.
81
- if (loadController?.signal.aborted) await indexPromise.catch(() => {});
82
- const book = await loadIndex();
83
- if (!current()) return;
84
- const counts = await countMatches(book, query, current, async partial => {
85
- if (!current()) return;
86
- if (current()) self.postMessage({ id: data.id, progress: true,
87
- total: partial.total, scanned: partial.scanned, chapters: book.length,
88
- offset: 0, pageSize: PAGE_SIZE, results: partial.firstPage.slice() });
89
- });
90
- session = { ...counts, query, id: data.id };
91
- } else if (data.type === "page") {
92
- if (!session || data.session !== session.id) throw aborted();
93
- offset = Math.max(0, Math.min(Math.floor(data.offset / PAGE_SIZE) * PAGE_SIZE,
94
- Math.max(0, Math.ceil(session.total / PAGE_SIZE) - 1) * PAGE_SIZE));
95
- } else return;
96
- const result = offset ? await resultPage(chapters, session.query, session.counts, offset, current) : session.firstPage.slice();
97
- if (current()) self.postMessage({ id: data.id, session: session.id, total: session.total,
98
- offset, pageSize: PAGE_SIZE, results: result });
99
- } catch (error) {
100
- if (current()) self.postMessage({ id: data.id, error: error.name === "AbortError"
101
- ? "全文搜索已取消或加载超时,请重试" : error.message });
102
- }
103
  };
104
  }
 
4
  import {isSearchIndexProxyURL} from "../reader-chapter-search-proxy-url.mjs";
5
  import {validateIndex} from "../reader-chapter-search-index.mjs";
6
 
7
+ /** @param {ReadableStream<Uint8Array<ArrayBuffer>> | null} stream @param {number} limit @param {AbortSignal} signal */
8
  async function readBounded(stream, limit, signal) {
9
+ if (!stream) throw new Error("全文搜索索引无效");
10
  const reader = stream.getReader(), chunks = [];
11
  let size = 0;
12
  const cancel = () => reader.cancel().catch(() => {});
 
35
  }
36
 
37
 
38
+ /** @typedef {import('../reader-chapter-search-index.mjs').ExpectedChapter} ExpectedChapter */
39
+ /** @typedef {{url: string, bytes: number, sha256: string, text_profile?: string | undefined}} IndexReference */
40
+ /** @typedef {{index: IndexReference, chapters: ExpectedChapter[]}} Configuration */
41
+ /** @typedef {Awaited<ReturnType<typeof countMatches>> & {query: string, id: number}} SearchSession */
42
+ /** @typedef {{type: 'init', configuration: Configuration} | {type: 'cancel'} |
43
+ * {type: 'search', id: number, query: unknown} | {type: 'page', id: number, session: number, offset: number}} ChapterMessage */
44
+ /** @param {unknown} value @returns {value is Record<string, unknown>} */
45
+ function isRecord(value) { return value !== null && typeof value === 'object'; }
46
+ /** @param {unknown} value @returns {value is Configuration} */
47
+ function isConfiguration(value) {
48
+ return isRecord(value) && isRecord(value.index) && typeof value.index.url === 'string' &&
49
+ typeof value.index.bytes === 'number' && typeof value.index.sha256 === 'string' &&
50
+ (value.index.text_profile === undefined || typeof value.index.text_profile === 'string') &&
51
+ Array.isArray(value.chapters) && value.chapters.every(chapter => isRecord(chapter) &&
52
+ typeof chapter.index === 'number' && typeof chapter.path === 'string');
53
+ }
54
+ /** @param {unknown} value @returns {value is ChapterMessage} */
55
+ function isMessage(value) {
56
+ if (!isRecord(value)) return false;
57
+ if (value.type === 'init') return isConfiguration(value.configuration);
58
+ if (value.type === 'cancel') return true;
59
+ if (value.type === 'search') return typeof value.id === 'number';
60
+ return value.type === 'page' && typeof value.id === 'number' && typeof value.session === 'number' && typeof value.offset === 'number';
61
+ }
62
+ /** @type {Configuration | undefined} */
63
+ let configuration;
64
+ /** @type {Promise<import('../reader-chapter-search-core.mjs').SearchChapter[]> | undefined} */
65
+ let indexPromise;
66
+ /** @type {import('../reader-chapter-search-core.mjs').SearchChapter[] | undefined} */
67
+ let chapters;
68
+ /** @type {SearchSession | null} */
69
+ let session = null;
70
+ /** @type {AbortController | null} */
71
+ let loadController = null;
72
+ let active = 0;
73
+ /** @param {IndexReference} index @param {URL} url */
74
+ function validateIndexReference(index,url) {
75
+ if (!isSearchIndexProxyURL(url, self.location.origin) ||
76
+ !Number.isSafeInteger(index.bytes) || index.bytes <= 0 || index.bytes > PACKED_LIMIT ||
77
+ !/^[0-9a-f]{64}$/.test(index.sha256)) throw new Error("全文搜索索引无效");
78
+ }
79
+ /** @param {AbortController} controller @returns {Promise<import('../reader-chapter-search-core.mjs').SearchChapter[]>} */
80
+ async function fetchIndex(controller) {
81
+ if (!configuration) throw new Error("全文搜索索引无效");
82
+ const { index, chapters: expected } = configuration;
83
+ const url = new URL(index.url, self.location.origin);
84
+ validateIndexReference(index,url);
85
+ const response = await fetch(url, { signal: controller.signal, credentials: "same-origin" });
86
+ if (!response.ok) throw new Error(`全文搜索加载失败(HTTP ${response.status}),请重试`);
87
+ const bytes = await readBounded(response.body, PACKED_LIMIT, controller.signal);
88
+ const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
89
+ const sha = [...digest].map(value => value.toString(16).padStart(2, "0")).join("");
90
+ if (bytes.length !== index.bytes || sha !== index.sha256) throw new Error("全文搜索索引校验失败,请重试");
91
+ const stream = new Blob([bytes]).stream().pipeThrough(new DecompressionStream("gzip"));
92
+ const text = await readBounded(stream, TEXT_LIMIT, controller.signal);
93
+ /** @type {unknown} */
94
+ const raw = JSON.parse(new TextDecoder().decode(text));
95
+ const loaded = validateIndex(raw, expected, index.text_profile);
96
+ if (controller.signal.aborted) throw aborted();
97
+ chapters = loaded;
98
+ return loaded;
99
+ }
100
  async function loadIndex() {
101
  if (chapters) return chapters;
102
  if (indexPromise) return indexPromise;
103
  const controller = new AbortController();
104
  loadController = controller;
105
  const timer = setTimeout(() => controller.abort(), 60000);
106
+ indexPromise = fetchIndex(controller).finally(() => {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
  clearTimeout(timer);
108
+ indexPromise = undefined;
109
  if (loadController === controller) loadController = null;
110
  });
111
  return indexPromise;
112
  }
113
+ /** @param {string} query @param {number} id @param {() => boolean} current @param {{postMessage(message: unknown): void}} scope */
114
+ async function beginSearch(query,id,current,scope) {
115
+ session = null;
116
+ query = String(query || "").trim().replace(/\s+/gu, " ");
117
+ if (!query || query.length > 2048) throw new Error("请输入 1–2048 个字符");
118
+ if (loadController?.signal.aborted) await indexPromise?.catch(() => {});
119
+ const book=await loadIndex();
120
+ if (!current()) return;
121
+ const counts=await countMatches(book,query,current,async partial=>{
122
+ if (current()) scope.postMessage({id,progress:true,total:partial.total,scanned:partial.scanned,
123
+ chapters:book.length,offset:0,pageSize:PAGE_SIZE,results:partial.firstPage.slice()});
124
+ });
125
+ session={...counts,query,id};
126
+ }
127
+ /** @param {number} requested @param {number} expected */
128
+ function pageOffset(requested,expected) {
129
+ if (!session || expected !== session.id) throw aborted();
130
+ return Math.max(0,Math.min(Math.floor(requested/PAGE_SIZE)*PAGE_SIZE,
131
+ Math.max(0,Math.ceil(session.total/PAGE_SIZE)-1)*PAGE_SIZE));
132
+ }
133
 
134
+ /** @param {unknown} error */
135
+ function requestError(error) {
136
+ const detail=error instanceof Error ? error : new Error(String(error));
137
+ return detail.name === "AbortError" ? "全文搜索已取消或加载超时,请重试" : detail.message;
138
+ }
139
+ /** @param {Extract<ChapterMessage,{type:'search'|'page'}>} data @param {{postMessage(message: unknown): void}} scope */
140
+ async function handleRequest(data,scope) {
141
+ const token=++active,current=()=>token===active;
142
+ try {
143
+ let offset=0;
144
+ if (data.type === "search") {
145
+ await beginSearch(String(data.query || ""),data.id,current,scope);
146
+ if (!current()) return;
147
+ } else offset=pageOffset(data.offset,data.session);
148
+ if (!session || !chapters) throw aborted();
149
+ const result=offset ? await resultPage(chapters,session.query,session.counts,offset,current) : session.firstPage.slice();
150
+ if (current()) scope.postMessage({id:data.id,session:session.id,total:session.total,
151
+ offset,pageSize:PAGE_SIZE,results:result});
152
+ } catch (error) {
153
+ if (current()) scope.postMessage({id:data.id,error:requestError(error)});
154
+ }
155
+ }
156
  if (typeof self !== "undefined" && typeof self.postMessage === "function") {
157
+ const scope = self;
158
+ scope.onmessage = event => {
159
+ /** @type {unknown} */
160
+ const data=event.data;
161
+ if (!isMessage(data)) {
162
+ if (isRecord(data) && data.type === 'init') configuration=undefined;
163
+ if (isRecord(data) && typeof data.id === 'number') scope.postMessage({id:data.id,error:'全文搜索索引无效'});
164
+ return;
165
+ }
166
  if (data.type === "init") { configuration = data.configuration; return; }
167
  if (data.type === "cancel") { active++; session = null; loadController?.abort(); return; }
168
+ return handleRequest(data,scope);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
169
  };
170
  }
tests/gates/ci-test-inventory.json CHANGED
@@ -310,6 +310,10 @@
310
  "kind": "excluded",
311
  "reason": "Visual acceptance requires external pinned screenshot baselines not present here."
312
  },
 
 
 
 
313
  "tests/reader/chapter-search/test_reader_chapter_search.mjs": {
314
  "kind": "direct",
315
  "source": "@reader-workflow"
 
310
  "kind": "excluded",
311
  "reason": "Visual acceptance requires external pinned screenshot baselines not present here."
312
  },
313
+ "tests/reader/chapter-search/test_reader_chapter_worker.mjs": {
314
+ "kind": "script",
315
+ "source": "scripts/reader/check_chapter_search_worker_coverage.mjs"
316
+ },
317
  "tests/reader/chapter-search/test_reader_chapter_search.mjs": {
318
  "kind": "direct",
319
  "source": "@reader-workflow"
tests/gates/static_gate_ids.github.json CHANGED
@@ -6,6 +6,8 @@
6
  [
7
  "tests.gates.test_static_checks.StaticGateTests.test_adapter_coverage_gate_fails_when_contract_tests_are_removed",
8
  "tests.gates.test_static_checks.StaticGateTests.test_chapter_search_core_coverage_gate_fails_closed",
 
 
9
  "tests.gates.test_static_checks.StaticGateTests.test_chapter_search_index_coverage_gate_fails_closed",
10
  "tests.gates.test_static_checks.StaticGateTests.test_chapter_search_index_exact_signature_and_complexity",
11
  "tests.gates.test_static_checks.StaticGateTests.test_chapter_search_proxy_coverage_gate_fails_closed",
 
6
  [
7
  "tests.gates.test_static_checks.StaticGateTests.test_adapter_coverage_gate_fails_when_contract_tests_are_removed",
8
  "tests.gates.test_static_checks.StaticGateTests.test_chapter_search_core_coverage_gate_fails_closed",
9
+ "tests.gates.test_static_checks.StaticGateTests.test_chapter_search_worker_coverage_gate_fails_closed",
10
+ "tests.gates.test_static_checks.StaticGateTests.test_chapter_search_worker_strict_complexity_and_network_contract",
11
  "tests.gates.test_static_checks.StaticGateTests.test_chapter_search_index_coverage_gate_fails_closed",
12
  "tests.gates.test_static_checks.StaticGateTests.test_chapter_search_index_exact_signature_and_complexity",
13
  "tests.gates.test_static_checks.StaticGateTests.test_chapter_search_proxy_coverage_gate_fails_closed",
tests/gates/static_gate_ids.hf.json CHANGED
@@ -6,6 +6,8 @@
6
  [
7
  "tests.gates.test_static_checks.StaticGateTests.test_adapter_coverage_gate_fails_when_contract_tests_are_removed",
8
  "tests.gates.test_static_checks.StaticGateTests.test_chapter_search_core_coverage_gate_fails_closed",
 
 
9
  "tests.gates.test_static_checks.StaticGateTests.test_chapter_search_index_coverage_gate_fails_closed",
10
  "tests.gates.test_static_checks.StaticGateTests.test_chapter_search_index_exact_signature_and_complexity",
11
  "tests.gates.test_static_checks.StaticGateTests.test_chapter_search_proxy_coverage_gate_fails_closed",
 
6
  [
7
  "tests.gates.test_static_checks.StaticGateTests.test_adapter_coverage_gate_fails_when_contract_tests_are_removed",
8
  "tests.gates.test_static_checks.StaticGateTests.test_chapter_search_core_coverage_gate_fails_closed",
9
+ "tests.gates.test_static_checks.StaticGateTests.test_chapter_search_worker_coverage_gate_fails_closed",
10
+ "tests.gates.test_static_checks.StaticGateTests.test_chapter_search_worker_strict_complexity_and_network_contract",
11
  "tests.gates.test_static_checks.StaticGateTests.test_chapter_search_index_coverage_gate_fails_closed",
12
  "tests.gates.test_static_checks.StaticGateTests.test_chapter_search_index_exact_signature_and_complexity",
13
  "tests.gates.test_static_checks.StaticGateTests.test_chapter_search_proxy_coverage_gate_fails_closed",
tests/gates/test_static_checks.py CHANGED
@@ -2980,6 +2980,71 @@ lifecycle.trackReaderResource(() => {}); lifecycle.isReaderGenerationCurrent("se
2980
  source.write_text(source.read_text() + f"\nfunction overlyComplex(value) {{ {choices} return 0; }}\n")
2981
  self.assert_check(self.run_check(*check), False, "complexity")
2982
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2983
  def test_chapter_search_index_coverage_gate_fails_closed(self):
2984
  paths=['static/reader/search/reader-chapter-search-core.mjs',
2985
  'static/reader/search/reader-chapter-search-proxy-url.mjs',
 
2980
  source.write_text(source.read_text() + f"\nfunction overlyComplex(value) {{ {choices} return 0; }}\n")
2981
  self.assert_check(self.run_check(*check), False, "complexity")
2982
 
2983
+ def test_chapter_search_worker_coverage_gate_fails_closed(self):
2984
+ paths = ['static/reader/search/reader-chapter-search-core.mjs',
2985
+ 'static/reader/search/reader-chapter-search-proxy-url.mjs',
2986
+ 'static/reader/search/reader-chapter-search-index.mjs',
2987
+ 'static/reader/search/workers/reader-chapter-search-worker.mjs',
2988
+ 'tests/reader/chapter-search/test_reader_chapter_worker.mjs',
2989
+ 'scripts/reader/check_chapter_search_worker_coverage.mjs', 'scripts/check_tap_contracts.mjs']
2990
+ for name in paths:
2991
+ target=self.root / name;target.parent.mkdir(parents=True,exist_ok=True);shutil.copyfile(ROOT / name,target)
2992
+ check=['node',paths[5]]
2993
+ message='Chapter search Worker requires its passing contract and exactly one source row'
2994
+ self.assert_check(self.run_check(*check),True,'reader-chapter-search-worker.mjs |')
2995
+ test=self.root / paths[4];original=test.read_text()
2996
+ marker='chapter Worker: transport, integrity, cancellation, retry and paging passed'
2997
+ self.assertEqual(original.count(marker),1);test.write_text(original.replace(marker,'renamed completion marker'))
2998
+ self.assert_check(self.run_check(*check),False,message)
2999
+ test.write_text(original+"\nthrow new Error('injected chapter Worker failure');\n")
3000
+ self.assert_check(self.run_check(*check),False,'injected chapter Worker failure')
3001
+ test.unlink();self.assert_check(self.run_check(*check),False,message);test.write_text(original)
3002
+ test.write_text(original+'\nconsole.log("end of coverage report");\n')
3003
+ self.assert_check(self.run_check(*check),False,message);test.write_text(original)
3004
+ gate=self.root / paths[5];gate_original=gate.read_text()
3005
+ for minimum in ('[100.01, 92, 100]', '[100, 101, 100]', '[100, 92, 100.01]'):
3006
+ self.assertEqual(gate_original.count('[100, 92, 100]'),1)
3007
+ gate.write_text(gate_original.replace('[100, 92, 100]',minimum))
3008
+ self.assert_check(self.run_check(*check),False,message)
3009
+ self.assertEqual(gate_original.count('reader-chapter-search-worker\\.mjs'),1)
3010
+ gate.write_text(gate_original.replace('reader-chapter-search-worker\\.mjs','missing-chapter-worker\\.mjs'))
3011
+ self.assert_check(self.run_check(*check),False,message)
3012
+
3013
+ def test_chapter_search_worker_strict_complexity_and_network_contract(self):
3014
+ paths=['static/reader/search/reader-chapter-search-core.mjs',
3015
+ 'static/reader/search/reader-chapter-search-proxy-url.mjs',
3016
+ 'static/reader/search/reader-chapter-search-index.mjs',
3017
+ 'static/reader/search/workers/reader-chapter-search-worker.mjs']
3018
+ project=load_type_config('jsconfig.chapter-worker-strict.json')
3019
+ self.assertTrue(project['compilerOptions']['strict'])
3020
+ self.assertEqual(project['compilerOptions']['lib'],['esnext','webworker'])
3021
+ self.assertIn(paths[3],project['files'])
3022
+ self.assertIn('tsc --project config/types/jsconfig.chapter-worker-strict.json',
3023
+ json.loads((ROOT / 'package.json').read_text())['scripts']['types'])
3024
+ for name in paths:
3025
+ target=self.root / name;target.parent.mkdir(parents=True,exist_ok=True);shutil.copyfile(ROOT / name,target)
3026
+ config=self.root / 'jsconfig.json';config.write_text(json.dumps(project))
3027
+ check=['node',ROOT / 'node_modules/typescript/bin/tsc','--project',config]
3028
+ self.assert_check(self.run_check(*check),True,'')
3029
+ local=self.root / paths[3];original=local.read_text()
3030
+ annotation='/** @param {IndexReference} index @param {URL} url */'
3031
+ self.assertEqual(original.count(annotation),1);local.write_text(original.replace(annotation,''))
3032
+ self.assert_check(self.run_check(*check),False,'TS7006');local.write_text(original)
3033
+ lint=['node',ROOT / 'node_modules/eslint/bin/eslint.js','--config',ROOT / 'eslint.config.mjs',
3034
+ local,'--rule','complexity: [error, 10]','--max-warnings','0']
3035
+ self.assert_check(self.run_check(*lint),True,'')
3036
+ choices=''.join(f'if (value === {n}) return {n}; ' for n in range(11))
3037
+ local.write_text(original+f'\nfunction overlyComplex(value) {{ {choices} return 0; }}\n')
3038
+ self.assert_check(self.run_check(*lint),False,'complexity')
3039
+ if (ROOT / 'Dockerfile').exists():
3040
+ self.assertIn('isSearchIndexProxyURL(url, self.location.origin)',original)
3041
+ self.assertIn('credentials: "same-origin"',original)
3042
+ self.assertNotIn('credentials: "omit"',original)
3043
+ else:
3044
+ self.assertIn('isSearchIndexProxyURL(url, "https://voiceofml-search.hf.space")',original)
3045
+ self.assertIn('credentials: "omit"',original)
3046
+ self.assertNotIn('credentials: "same-origin"',original)
3047
+
3048
  def test_chapter_search_index_coverage_gate_fails_closed(self):
3049
  paths=['static/reader/search/reader-chapter-search-core.mjs',
3050
  'static/reader/search/reader-chapter-search-proxy-url.mjs',
tests/gates/test_static_contract.py CHANGED
@@ -527,6 +527,7 @@ class StaticFrontendContractTests(unittest.TestCase):
527
  self.assertIn("node scripts/reader/check_chapter_search_core_coverage.mjs", dockerfile)
528
  self.assertIn("node scripts/reader/check_chapter_search_proxy_coverage.mjs", dockerfile)
529
  self.assertIn("node scripts/reader/check_chapter_search_index_coverage.mjs", dockerfile)
 
530
  self.assertIn("node --test tests/search/baselines/test_search_response_validation_baseline.mjs", dockerfile)
531
  self.assertIn("node --test tests/search/baselines/test_search_stable_id_baseline.mjs", dockerfile)
532
  self.assertIn("COPY --from=source-check-node /check/ /check/", dockerfile)
 
527
  self.assertIn("node scripts/reader/check_chapter_search_core_coverage.mjs", dockerfile)
528
  self.assertIn("node scripts/reader/check_chapter_search_proxy_coverage.mjs", dockerfile)
529
  self.assertIn("node scripts/reader/check_chapter_search_index_coverage.mjs", dockerfile)
530
+ self.assertIn("node scripts/reader/check_chapter_search_worker_coverage.mjs", dockerfile)
531
  self.assertIn("node --test tests/search/baselines/test_search_response_validation_baseline.mjs", dockerfile)
532
  self.assertIn("node --test tests/search/baselines/test_search_stable_id_baseline.mjs", dockerfile)
533
  self.assertIn("COPY --from=source-check-node /check/ /check/", dockerfile)
tests/reader/chapter-search/test_reader_chapter_search.mjs CHANGED
@@ -79,6 +79,18 @@ assert.equal((await resultPage(literals, "&nbsp;", literalCounts.counts, 50, ()
79
  assert.equal(queryBigramFilters("A"), null);
80
  assert.equal((await countMatches([chapter], "手机", () => true)).total, 1);
81
  }
 
 
 
 
 
 
 
 
 
 
 
 
82
  // Force a cooperative yield without timing dependence. The currentness guard
83
  // executes inside the real scan; after the yield it must check cancellation.
84
  {
 
79
  assert.equal(queryBigramFilters("A"), null);
80
  assert.equal((await countMatches([chapter], "手机", () => true)).total, 1);
81
  }
82
+ // Version-1 historical JSON can contain array-like filter properties rather
83
+ // than the decoded Uint8Array; preserve the old coercion and bit decisions.
84
+ {
85
+ const filters = queryBigramFilters("手机");
86
+ const bloom = Object.assign({length:32}, Object.fromEntries(Array.from({length:32}, (_, i) => [i,255])));
87
+ const chapter = {index:1,title:42,path:"one",text:"手机",bigramFilter:bloom};
88
+ assert.equal(chapterMayContainBigrams(chapter, filters), true);
89
+ for (let i=0;i<32;i++) bloom[i]=0;
90
+ assert.equal(chapterMayContainBigrams(chapter, filters), false);
91
+ chapter.bigramFilter = {};
92
+ assert.equal(chapterMayContainBigrams(chapter, filters), false);
93
+ }
94
  // Force a cooperative yield without timing dependence. The currentness guard
95
  // executes inside the real scan; after the yield it must check cancellation.
96
  {
tests/reader/chapter-search/test_reader_chapter_worker.mjs ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import assert from "node:assert/strict";
2
+ import {webcrypto} from "node:crypto";
3
+ import {gzipSync} from "node:zlib";
4
+
5
+ // The real module's message handler, loader, SHA verification and search core
6
+ // execute with a controlled Worker-like global and a deterministic transport.
7
+ const isSpace = true;
8
+ const localOrigin = "https://reader.example";
9
+ const proxyOrigin = isSpace ? localOrigin : "https://voiceofml-search.hf.space";
10
+ const messages = [], requests = [];
11
+ const scope = {location: {origin: localOrigin}, postMessage: value => messages.push(structuredClone(value))};
12
+ Object.defineProperty(globalThis, "crypto", {configurable: true, value: webcrypto});
13
+ globalThis.self = scope;
14
+ let responseMode = "valid", packed, firstRead, firstFetch, releaseFetch, expire;
15
+ let streamCancelled = false;
16
+ const nativeSetTimeout = globalThis.setTimeout;
17
+ globalThis.setTimeout = (fn, delay, ...args) => {
18
+ if (delay === 60000) expire = fn;
19
+ return nativeSetTimeout(fn, delay, ...args);
20
+ };
21
+ globalThis.fetch = async (url, options) => {
22
+ requests.push({url: String(url), credentials: options.credentials, signal: options.signal});
23
+ if (responseMode === "http") return new Response("unavailable", {status: 503});
24
+ if (responseMode === "null") return new Response(null, {status: 204});
25
+ if (responseMode === "throw") throw new Error("transport failed");
26
+ if (responseMode === "throw-string") throw "transport string failure";
27
+ if (responseMode === "stream-error") return new Response(new ReadableStream({
28
+ pull() { throw new Error("stream read failed"); }
29
+ }));
30
+ if (responseMode === "wrong-bytes") return new Response(packed.subarray(1));
31
+ if (responseMode === "too-large") {
32
+ const chunk = new Uint8Array(16 * 1024 * 1024);
33
+ return new Response(new ReadableStream({
34
+ pull(controller) { controller.enqueue(chunk); },
35
+ cancel() { streamCancelled = true; }
36
+ }));
37
+ }
38
+ if (responseMode === "shared-fetch") {
39
+ firstFetch();
40
+ return new Promise(resolve => { releaseFetch = () => resolve(new Response(packed.subarray(1))); });
41
+ }
42
+ if (responseMode === "held-fetch") {
43
+ responseMode = "valid";
44
+ firstFetch();
45
+ return new Promise((resolve, reject) => {
46
+ options.signal.addEventListener("abort", () => reject(new DOMException("aborted", "AbortError")), {once: true});
47
+ });
48
+ }
49
+ if (responseMode === "held-stream") {
50
+ responseMode = "valid";
51
+ return new Response(new ReadableStream({
52
+ pull() { firstRead(); return new Promise(() => {}); },
53
+ cancel() { streamCancelled = true; throw new Error("injected stream cancel error"); }
54
+ }));
55
+ }
56
+ return new Response(packed);
57
+ };
58
+ await import("../../../static/reader/search/workers/reader-chapter-search-worker.mjs");
59
+ const send = async data => { await scope.onmessage({data}); };
60
+ const latest = () => messages.at(-1);
61
+ let id = 0;
62
+ async function search(query = "needle") { await send({type:"search", id:++id, query}); return latest(); }
63
+ async function buildConfiguration(data, chapters = [{index:1, path:"one", title:"First"}]) {
64
+ packed = gzipSync(Buffer.from(JSON.stringify(data)));
65
+ const sha256 = Buffer.from(await crypto.subtle.digest("SHA-256", packed)).toString("hex");
66
+ return {index:{url:proxyOrigin + "/api/reader-content?url=source", bytes:packed.length, sha256}, chapters};
67
+ }
68
+ // Legacy manifests may use non-string titles and version-1 filters represented
69
+ // as array-like JSON. Neither was rejected by the previous implementation.
70
+ const legacyFilter = Object.assign({length:32}, Object.fromEntries(Array.from({length:32}, (_, i) => [i,255])));
71
+ const goodIndex = {version:1, kind:"epub-search-index", chapters:[
72
+ {index:1,path:"one",text:"needle ".repeat(120)+"手机",bigramFilter:legacyFilter}
73
+ ]};
74
+ let config = await buildConfiguration(goodIndex, [{index:1,path:"one",title:42}]);
75
+ assert.match((await search()).error, /索引无效/);
76
+ await send({type:"init", configuration:null});
77
+ assert.match((await search()).error, /索引无效/);
78
+ const before = messages.length;
79
+ await send(null); await send({type:"cancel"});
80
+ assert.equal(messages.length, before);
81
+ await send({type:"page", id:++id, session:null, offset:"bad"});
82
+ assert.match(latest().error, /索引无效/);
83
+ await send({type:"unknown", id:++id});
84
+ assert.match(latest().error, /索引无效/);
85
+ for (const index of [
86
+ {...config.index, url:"https://evil.example/api/reader-content"},
87
+ {...config.index, bytes:0}, {...config.index, bytes:64*1024*1024+1},
88
+ {...config.index, sha256:"bad"},
89
+ {...config.index, url:proxyOrigin+"/api/reader-bucket-resource?path=../bad"}
90
+ ]) {
91
+ await send({type:"init", configuration:{...config,index}});
92
+ const count = requests.length;
93
+ assert.match((await search()).error, /索引无效/);
94
+ assert.equal(requests.length, count);
95
+ }
96
+ for (const [mode, expected] of [["http",/HTTP 503/],["null",/索引无效/],
97
+ ["throw",/transport failed/],["throw-string",/transport string failure/],
98
+ ["stream-error",/stream read failed/],["wrong-bytes",/校验失败/],["too-large",/超过大小限制/]]) {
99
+ responseMode = mode; await send({type:"init", configuration:config});
100
+ assert.match((await search()).error, expected, mode);
101
+ }
102
+ assert.equal(streamCancelled, true);
103
+ // Abort while the response stream is blocked in read(): the Worker must cancel
104
+ // the underlying stream and a subsequent fetch must still be possible.
105
+ responseMode = "held-stream"; streamCancelled = false;
106
+ await send({type:"init", configuration:config});
107
+ let reading = new Promise(resolve => { firstRead = resolve; });
108
+ const streamId = ++id, streamSearch = send({type:"search", id:streamId, query:"needle"});
109
+ await reading; await send({type:"cancel"}); await streamSearch;
110
+ assert.equal(streamCancelled, true);
111
+ assert.equal(messages.some(value => value.id === streamId), false);
112
+ responseMode = "valid";
113
+ config = await buildConfiguration({...goodIndex, kind:"invalid"});
114
+ await send({type:"init", configuration:config});
115
+ assert.match((await search()).error, /索引不完整/);
116
+ config = await buildConfiguration(goodIndex, [{index:1,path:"one",title:42}]);
117
+ await send({type:"init", configuration:config});
118
+ assert.match((await search(" ")).error, /1–2048/);
119
+ assert.match((await search("x".repeat(2049))).error, /1–2048/);
120
+
121
+ // Overlapping searches share one in-flight load; if that load fails, only the
122
+ // latest request receives the error and a later search is allowed to retry.
123
+ responseMode = "shared-fetch";
124
+ let sharedStarted = new Promise(resolve => { firstFetch = resolve; });
125
+ const requestCount = requests.length;
126
+ const oldId = ++id, old = send({type:"search", id:oldId, query:"needle"});
127
+ await sharedStarted;
128
+ const currentId = ++id, current = send({type:"search", id:currentId, query:"手机"});
129
+ assert.equal(requests.length, requestCount + 1);
130
+ releaseFetch(); await Promise.all([old, current]);
131
+ assert.equal(messages.some(value => value.id === oldId), false);
132
+ assert.equal(latest().id, currentId); assert.match(latest().error, /校验失败/);
133
+
134
+ // Drive the actual 60-second load deadline deterministically, without waiting.
135
+ responseMode = "held-fetch";
136
+ let timedStart = new Promise(resolve => { firstFetch = resolve; });
137
+ const timedId = ++id, timed = send({type:"search", id:timedId, query:"needle"});
138
+ await timedStart; assert.equal(typeof expire, "function"); expire(); await timed;
139
+ assert.equal(latest().id, timedId); assert.match(latest().error, /取消或加载超时/);
140
+
141
+ // Cancel while fetch is pending and retry before the aborted promise settles.
142
+ responseMode = "held-fetch";
143
+ let started = new Promise(resolve => { firstFetch = resolve; });
144
+ const abandonedId = ++id, abandoned = send({type:"search", id:abandonedId, query:"needle"});
145
+ await started; await send({type:"cancel"});
146
+ const resumedId = ++id, resumed = send({type:"search", id:resumedId, query:"needle"});
147
+ await Promise.all([abandoned, resumed]);
148
+ assert.equal(messages.some(value => value.id === abandonedId), false);
149
+ assert.equal(latest().id, resumedId); assert.equal(latest().total, 120);
150
+ assert.equal(latest().results.length, 50);
151
+ assert.equal(latest().results[0].location, "第 1 章 · 42");
152
+ const loadedRequests = requests.length;
153
+ const cached = await search("手机");
154
+ assert.equal(cached.total, 1);
155
+ assert.equal(requests.length, loadedRequests); // the validated index is cached
156
+ await send({type:"search", id:resumedId, query:"needle"});
157
+ assert.equal(latest().total, 120);
158
+ assert.equal(requests.at(-1).credentials, isSpace ? "same-origin" : "omit");
159
+ assert.ok(requests.at(-1).url.startsWith(proxyOrigin));
160
+ await send({type:"page", id:++id, session:resumedId, offset:100});
161
+ assert.equal(latest().offset, 100); assert.equal(latest().results.length, 20);
162
+ await send({type:"page", id:++id, session:resumedId, offset:9999});
163
+ assert.equal(latest().offset, 100); assert.equal(latest().results.length, 20);
164
+ await send({type:"page", id:++id, session:999, offset:0});
165
+ assert.match(latest().error, /取消/);
166
+ await send({type:"cancel"});
167
+ await send({type:"page", id:++id, session:resumedId, offset:0});
168
+ assert.match(latest().error, /取消/);
169
+ globalThis.setTimeout = nativeSetTimeout;
170
+ console.log("chapter Worker: transport, integrity, cancellation, retry and paging passed");