vomebook commited on
Commit ·
4fbb2dd
1
Parent(s): 4f4d61f
Add complete on-demand search for chapter books
Browse filesFiles changed (14)
- Dockerfile+1
- scripts/build_static_assets.mjs+6-1
- scripts/check_reader_release.mjs+2
- static/reader-chapter-search-worker.mjsAdded+177
- static/reader-chapter-search.mjsAdded+93
- static/reader-contract.js+1-1
- static/reader-runtime.js+1-1
- static/reader.css+22-3
- static/reader.js+174-5
- static/sw.js+2
- tests/test_reader_chapter_search.mjsAdded+32
- tests/test_reader_refactor.py+129
- tests/test_reader_regression.js+1-1
- tests/test_service_worker.js+18
21 unmodified lines22232425262721 unmodified lines&& esbuild static/reader-navigation.js --minify --target=es2019 --charset=utf8 --legal-comments=none --outfile=/out/reader-navigation.js \&& esbuild static/reader-store.js --minify --target=es2019 --charset=utf8 --legal-comments=none --outfile=/out/reader-store.js \&& esbuild static/reader.js --minify --target=es2019 --charset=utf8 --legal-comments=none --outfile=/out/reader.js \&& esbuild static/style.css --minify --outfile=/out/style.css \&& esbuild static/reader.css --minify --outfile=/out/reader.css \&& node /build/build_static_assets.mjs \21 unmodified lines2223242526272821 unmodified lines&& esbuild static/reader-navigation.js --minify --target=es2019 --charset=utf8 --legal-comments=none --outfile=/out/reader-navigation.js \&& esbuild static/reader-store.js --minify --target=es2019 --charset=utf8 --legal-comments=none --outfile=/out/reader-store.js \&& esbuild static/reader.js --minify --target=es2019 --charset=utf8 --legal-comments=none --outfile=/out/reader.js \&& esbuild static/reader-chapter-search.mjs static/reader-chapter-search-worker.mjs --minify --format=esm --target=es2020 --charset=utf8 --legal-comments=none --outdir=/out --out-extension:.js=.mjs \&& esbuild static/style.css --minify --outfile=/out/style.css \&& esbuild static/reader.css --minify --outfile=/out/reader.css \&& node /build/build_static_assets.mjs \
4 unmodified lines567891011124 unmodified linesconst outputDir = process.env.STATIC_OUTPUT_DIR || "/out";const replacements = new Map();for (const filename of ["app.js", "style.css", "reader-contract.js", "reader-navigation.js", "reader-store.js", "reader.js", "reader.css"]) {const source = join(outputDir, filename);const content = readFileSync(source);const hash = createHash("sha256").update(content).digest("hex").slice(0, 12);const extension = extname(filename);4 unmodified lines5678910111213141516174 unmodified linesconst outputDir = process.env.STATIC_OUTPUT_DIR || "/out";const replacements = new Map();for (const filename of ["reader-chapter-search-worker.mjs", "reader-chapter-search.mjs", "app.js", "style.css", "reader-contract.js", "reader-navigation.js", "reader-store.js", "reader.js", "reader.css"]) {const source = join(outputDir, filename);if (["reader-chapter-search.mjs", "reader.js"].includes(filename)) {let text = readFileSync(source, "utf8");for (const [original, versioned] of replacements) text = text.split(original).join(versioned);writeFileSync(source, text);}const content = readFileSync(source);const hash = createHash("sha256").update(content).digest("hex").slice(0, 12);const extension = extname(filename);
21 unmodified lines22232425262721 unmodified lines"reader-store.js","reader-request-manager.js","reader-chapter-repository.js","reader-scroll-anchor.js","reader-section-virtualizer.js","reader-runtime.js",21 unmodified lines222324252627282921 unmodified lines"reader-store.js","reader-request-manager.js","reader-chapter-repository.js","reader-chapter-search.mjs","reader-chapter-search-worker.mjs","reader-scroll-anchor.js","reader-section-virtualizer.js","reader-runtime.js",
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177const PACKED_LIMIT = 64 * 1024 * 1024;const TEXT_LIMIT = 256 * 1024 * 1024;const PAGE_SIZE = 50;const pause = () => new Promise(resolve => setTimeout(resolve, 0));function cooperativeYield() { let last = performance.now(); return async () => { if (performance.now() - last < 8) return; await pause(); last = performance.now(); };}const escapePattern = value => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");const aborted = () => new DOMException("Search cancelled", "AbortError");
async function readBounded(stream, limit, signal) { const reader = stream.getReader(), chunks = []; let size = 0; const cancel = () => reader.cancel().catch(() => {}); signal.addEventListener("abort", cancel, { once: true }); try { while (true) { if (signal.aborted) throw aborted(); const { value, done } = await reader.read(); if (signal.aborted) throw aborted(); if (done) break; size += value.byteLength; if (size > limit) throw new Error("全文搜索数据超过大小限制"); chunks.push(value); } const result = new Uint8Array(size); let offset = 0; for (const chunk of chunks) { result.set(chunk, offset); offset += chunk.length; } return result; } catch (error) { await reader.cancel().catch(() => {}); throw error; } finally { signal.removeEventListener("abort", cancel); reader.releaseLock(); }}
export function validateIndex(data, chapters) { if (data?.version !== 1 || data.kind !== "epub-search-index" || !Array.isArray(data.chapters) || data.chapters.length !== chapters.length) throw new Error("全文搜索索引不完整,请重试"); for (let i = 0; i < chapters.length; i++) { const item = data.chapters[i], expected = chapters[i]; if (item?.index !== expected.index || item.path !== expected.path || typeof item.text !== "string") throw new Error("全文搜索索引与章节不一致"); item.title = expected.title || `章节 ${expected.index}`; } return data.chapters;}
// Scan bounded pieces so a new query can cancel even one very large chapter.// Keep counts, rather than one object per hit; all matches remain pageable.export async function scanText(text, query, visit, current = () => true, yieldWork = pause) { const pattern = new RegExp(escapePattern(query), "giu"); let next = 0; for (let start = 0; start < text.length; start += 65536) { if (!current()) throw aborted(); const part = text.slice(start, start + 65536 + query.length + 1); pattern.lastIndex = Math.max(0, next - start); let match; while ((match = pattern.exec(part))) { if (match.index >= 65536) break; const offset = start + match.index; next = offset + match[0].length; if (visit(offset, match[0].length) === false) return; } await yieldWork(); } if (!current()) throw aborted();}
export async function countMatches(chapters, query, current) { const counts = []; const yieldWork = cooperativeYield(); let total = 0; for (const chapter of chapters) { let count = 0; await scanText(chapter.text, query, () => { count++; }, current, yieldWork); counts.push(count); total += count; } return { counts, total };}
export async function resultPage(chapters, query, counts, offset, current) { const results = []; const yieldWork = cooperativeYield(); let skip = offset; for (let i = 0; i < chapters.length && results.length < PAGE_SIZE; i++) { if (!current()) throw aborted(); if (skip >= counts[i]) { skip -= counts[i]; continue; } const chapter = chapters[i]; await scanText(chapter.text, query, (start, length) => { if (skip) { skip--; return; } const before = Math.max(0, start - 72), after = Math.min(chapter.text.length, start + length + 88); results.push({ chapterIndex: chapter.index, start, length, location: `第 ${chapter.index} 章 · ${chapter.title}`, snippet: { text: chapter.text.slice(before, after), matchStart: start - before, matchLength: length, prefix: before ? "…" : "", suffix: after < chapter.text.length ? "…" : "" } }); return results.length < PAGE_SIZE; }, current, yieldWork); } return results;}
let configuration, indexPromise, chapters, active = 0, session, loadController;async function loadIndex() { if (chapters) return chapters; if (indexPromise) return indexPromise; const controller = new AbortController(); loadController = controller; const timer = setTimeout(() => controller.abort(), 60000); indexPromise = (async () => { const { index, chapters: expected } = configuration; const url = new URL(index.url, self.location.origin); if (url.origin !== self.location.origin || url.pathname !== "/api/reader-content" || !Number.isSafeInteger(index.bytes) || index.bytes <= 0 || index.bytes > PACKED_LIMIT || !/^[0-9a-f]{64}$/.test(index.sha256)) throw new Error("全文搜索索引无效"); const response = await fetch(url, { signal: controller.signal, credentials: "same-origin" }); if (!response.ok) throw new Error(`全文搜索加载失败(HTTP ${response.status}),请重试`); const bytes = await readBounded(response.body, PACKED_LIMIT, controller.signal); const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)); const sha = [...digest].map(value => value.toString(16).padStart(2, "0")).join(""); if (bytes.length !== index.bytes || sha !== index.sha256) throw new Error("全文搜索索引校验失败,请重试"); const stream = new Blob([bytes]).stream().pipeThrough(new DecompressionStream("gzip")); const text = await readBounded(stream, TEXT_LIMIT, controller.signal); const loaded = validateIndex(JSON.parse(new TextDecoder().decode(text)), expected); if (controller.signal.aborted) throw aborted(); chapters = loaded; return loaded; })().finally(() => { clearTimeout(timer); indexPromise = null; if (loadController === controller) loadController = null; }); return indexPromise;}
if (typeof self !== "undefined" && typeof self.postMessage === "function") { self.onmessage = async ({ data }) => { if (data.type === "init") { configuration = data.configuration; return; } if (data.type === "cancel") { active++; session = null; loadController?.abort(); return; } const token = ++active, current = () => token === active; try { let offset = 0; if (data.type === "search") { session = null; const query = String(data.query || "").trim().replace(/\s+/gu, " "); if (!query || query.length > 2048) throw new Error("请输入 1–2048 个字符"); // A cancelled download must settle before a later search retries it. if (loadController?.signal.aborted) await indexPromise.catch(() => {}); const book = await loadIndex(); if (!current()) return; const counts = await countMatches(book, query, current); session = { ...counts, query, id: data.id }; } else if (data.type === "page") { if (!session || data.session !== session.id) throw aborted(); offset = Math.max(0, Math.min(Math.floor(data.offset / PAGE_SIZE) * PAGE_SIZE, Math.max(0, Math.ceil(session.total / PAGE_SIZE) - 1) * PAGE_SIZE)); } else return; const result = await resultPage(chapters, session.query, session.counts, offset, current); if (current()) self.postMessage({ id: data.id, session: session.id, total: session.total, offset, pageSize: PAGE_SIZE, results: result }); } catch (error) { if (current()) self.postMessage({ id: data.id, error: error.name === "AbortError" ? "全文搜索已取消或加载超时,请重试" : error.message }); } };}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293export function createChapterSearch(configuration) { const worker = new Worker("/static/reader-chapter-search-worker.mjs", { type: "module" }); let sequence = 0, pending = null, disposed = false, session = null, failure = null; const cancelPending = () => { pending?.reject(new DOMException("Search cancelled", "AbortError")); pending = null; }; worker.onmessage = ({ data }) => { if (!pending || pending.id !== data.id) return; const task = pending; pending = null; if (data.error) task.reject(new Error(data.error)); else { session = data.session; task.resolve(data); } }; worker.onerror = event => { event.preventDefault(); failure = new Error("全文搜索组件加载失败,请重试"); pending?.reject(failure); pending = null; }; worker.postMessage({ type: "init", configuration }); function request(type, values) { if (disposed) return Promise.reject(new DOMException("Reader closed", "AbortError")); if (failure) return Promise.reject(failure); cancelPending(); return new Promise((resolve, reject) => { const id = ++sequence; pending = { id, resolve, reject }; worker.postMessage({ type, id, ...values }); }); } return { get failed() { return !!failure; }, search: query => request("search", { query }), page: offset => request("page", { offset, session }), cancel() { cancelPending(); session = null; worker.postMessage({ type: "cancel" }); }, dispose() { disposed = true; cancelPending(); worker.terminate(); } };}
// Reproduce the bundle's HTMLParser text extraction: skip script/style/noscript,// separate text nodes, decode character references, and collapse whitespace.// Runs map normalized offsets back to the exact text nodes being displayed.export function chapterTextMap(roots) { const runs = [], chunks = []; let length = 0, pendingSpace = null; const decoder = document.createElement("textarea"); const append = (text, node, start, end, linear) => { if (!text) return; if (pendingSpace && length) { chunks.push(" "); runs.push({ ...pendingSpace, from: length, to: ++length, linear: false }); } pendingSpace = null; chunks.push(text); runs.push({ node, start, end, linear, from: length, to: length + text.length }); length += text.length; }; for (const root of roots.filter(Boolean)) { const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT); while (walker.nextNode()) { const node = walker.currentNode; if (node.parentElement?.closest("script,style,noscript")) continue; if (length) pendingSpace = { node: null, start: 0, end: 0 }; // Python's Unicode whitespace also includes NEL and the four separators. const pattern = /&(?:#[xX][0-9a-fA-F]+;?|#\d+;?|[a-zA-Z][a-zA-Z0-9]+;?)|[\s\u0085\u001c-\u001f]+|[^&\s\u0085\u001c-\u001f]+|&/gu; for (const match of node.data.matchAll(pattern)) { const raw = match[0], start = match.index, end = start + raw.length; let text = raw; if (raw.startsWith("&")) { decoder.innerHTML = raw; text = decoder.value; } if (/^[\s\u0085\u001c-\u001f]+$/u.test(text)) { pendingSpace ||= { node, start, end }; } else append(text, node, start, end, text === raw); } } } return { text: chunks.join(""), parts(start, end, body) { const output = []; for (const run of runs) { if (run.to <= start || run.from >= end || !run.node || !body.contains(run.node)) continue; const part = { node: run.node, start: run.linear ? run.start + Math.max(start - run.from, 0) : run.start, end: run.linear ? run.end - Math.max(run.to - end, 0) : run.end }; const last = output[output.length - 1]; if (last?.node === part.node) last.end = part.end; else output.push(part); } return output; } };}150 unmodified lines151152153154155156157150 unmodified lines},"epub-chapters": {toc: true,search: false,zoom: true,bookmarks: true,pagination: false,150 unmodified lines151152153154155156157150 unmodified lines},"epub-chapters": {toc: true,search: true,zoom: true,bookmarks: true,pagination: false,
20 unmodified lines2122232425262720 unmodified lines},"epub-chapters": {toc: true,search: false,zoom: true,bookmarks: true,pagination: false,20 unmodified lines2122232425262720 unmodified lines},"epub-chapters": {toc: true,search: true,zoom: true,bookmarks: true,pagination: false,
365 unmodified lines3663673683693703713722 unmodified lines3753763773783793803811 unmodified line38338438538638738823 unmodified lines412413414415416417418365 unmodified linesgap: 6px;padding: 0 12px 8px;}.full-search-nav button {flex: 1;min-height: 30px;border: 1px solid #464c52;2 unmodified linescolor: inherit;cursor: pointer;}.full-search-nav button:disabled {opacity: 0.4;cursor: default;}1 unmodified linemin-height: 0;overflow: auto;}.full-search-result {display: block;width: 100%;23 unmodified linesline-height: 1.55;overflow-wrap: anywhere;}:root[data-theme="light"] .full-search-nav button {border-color: #c7ccd0;}:root[data-theme="light"] .full-search-result {365 unmodified lines3663673683693703713723732 unmodified lines3763773783793803813823831 unmodified line38538638738838939039139239339439539639739839940040140240340440540623 unmodified lines430431432433434435436437365 unmodified linesgap: 6px;padding: 0 12px 8px;}.full-search-nav button,.full-search-pagination button {flex: 1;min-height: 30px;border: 1px solid #464c52;2 unmodified linescolor: inherit;cursor: pointer;}.full-search-nav button:disabled,.full-search-pagination button:disabled {opacity: 0.4;cursor: default;}1 unmodified linemin-height: 0;overflow: auto;}.full-search-pagination:not([hidden]) {display: flex;align-items: center;gap: 6px;padding: 0 12px 8px;font-size: 12px;}.full-search-pagination label { white-space: nowrap; }.full-search-pagination input {width: 4em;padding: 4px;border: 1px solid #929aa1;border-radius: 4px;color: inherit;background: transparent;}.full-search-result {display: block;width: 100%;23 unmodified linesline-height: 1.55;overflow-wrap: anywhere;}:root[data-theme="light"] .full-search-nav button,:root[data-theme="light"] .full-search-pagination button {border-color: #c7ccd0;}:root[data-theme="light"] .full-search-result {
336 unmodified lines3373383393403413421867 unmodified lines221022112212221322142215811 unmodified lines30273028302930303031303265 unmodified lines3098309931003101310231033104310531068 unmodified lines3115311631173118311931201095 unmodified lines4216421742184219422042214222232 unmodified lines44554456445744584459446016 unmodified lines447744784479448044814482448344844485448644873 unmodified lines44914492449344944495449614 unmodified lines451145124513451445154516451745184519452045214522452318 unmodified lines45424543454445454546454745484549455045515 unmodified lines455745584559456045614562336 unmodified lineslet saveTimer = 0;let saveDeadline = 0;let chapterManifestLoader = null;let folderNavigationTarget = null;let bookmarkInvoker = null;const bookmarkInertSiblings = new Map();1867 unmodified linesfunction sanitizeEpubDocument(doc) {return sanitizeReaderDocument(normalizeEpubDocument(doc), { preserveEpubStyles: true });}function epubContentBody(doc) {const nestedBody = [...doc.querySelectorAll("body")].find((body) => body !== doc.body);811 unmodified linesconst chapterPrefetchCount = 6;const chapterBudget = VoiceOfMLReaderSecurity.createByteBudget();if (!manifestBase) throw new Error("EPUB_INVALID_MANIFEST_PATH");const chapterUrl = (chapter) => trustedChapterUrl(chapter.path, manifestBase);const resourceUrl = (raw, base, attribute) => {const value = String(raw || "").trim();65 unmodified lineslet inserted = false;try {assertReaderActive();const doc = sanitizeEpubDocument(new DOMParser().parseFromString(new TextDecoder().decode(bytes), "text/html"));for (const element of doc.querySelectorAll("*")) {for (const name of ["src", "href", "poster", "xlink:href"])if (element.hasAttribute(name)) {8 unmodified linesarticle.className = "reader-markdown reader-epub-chapter";article.dataset.chapter = String(chapter.index);article.innerHTML = doc.body ? doc.body.innerHTML : "";const marker = frame.querySelector(`.reader-chapter-sentinel[data-chapter="${chapter.index}"]`);1095 unmodified linesconst fullSearchInput = fullSearchView.querySelector("#full-search-input"),fullSearchStatus = fullSearchView.querySelector("#full-search-status"),fullSearchResultsNode = fullSearchView.querySelector("#full-search-results");// Full-text search: format matching, result presentation, and navigation.async function fullSearchFoliateMatches(query, generation) {const results = [];if (!epubRendition?.search) return results;232 unmodified linesreturn output;}function renderFullSearchResults() {fullSearchResultsNode.textContent = "";for (const [index, result] of searchState.results.entries()) {const row = document.createElement("button"),16 unmodified linesbeginReaderNavigation();clearFullSearchMarks();updateSearchState({ query, results: [], index: -1 });fullSearchResultsNode.textContent = "";fullSearchView.querySelectorAll(".full-search-nav button").forEach((button) => {button.disabled = true;});if (!query) {fullSearchStatus.textContent = "输入关键词搜索正文";return;}3 unmodified linespublishSearchResults(generation, await fullSearchPdfMatches(query, generation));else if (capability.mode === "foliate")publishSearchResults(generation, await fullSearchFoliateMatches(query, generation));else if (["text", "markdown", "docx"].includes(capability.mode))publishSearchResults(generation,14 unmodified lineselse throw new Error("此格式没有可搜索文本");if (!isReaderGenerationCurrent("search", generation)) return;renderFullSearchResults();fullSearchStatus.textContent = searchState.results.length? `${searchState.results.length}${searchState.results.length === 100 ? "+" : ""} 个结果`: "未找到正文匹配";} catch (error) {if (isReaderGenerationCurrent("search", generation))fullSearchStatus.textContent = error.message || "正文搜索不可用";} finally {if (isReaderGenerationCurrent("search", generation))fullSearchView.querySelectorAll(".full-search-nav button").forEach((button) => {button.disabled = !searchState.results.length;18 unmodified linesif (closePanel) setReaderPanelOpen(false, true);else fullSearchResultsNode.children[index]?.scrollIntoView({ block: "nearest" });} catch (error) {reportNavigationError(error, generation);}}function moveFullSearch(step) {if (searchState.results.length)return activateFullSearchResult((searchState.index + step + searchState.results.length) % searchState.results.length,5 unmodified linesif (panel.classList.contains("is-open") && !fullSearchView.hidden) {beginReaderNavigation();nextReaderGeneration("search");clearFullSearchMarks();updateSearchState({ results: [], index: -1 });renderFullSearchResults();336 unmodified lines3373383393403413423433443453463471867 unmodified lines22152216221722182219222022212222222322242225222622272228811 unmodified lines304030413042304330443045304630473048304930503051305265 unmodified lines31183119312031213122312331248 unmodified lines313331343135313631373138313931401095 unmodified lines42364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363232 unmodified lines459645974598459946004601460216 unmodified lines46194620462146224623462446254626462746284629463046314632463346343 unmodified lines4638463946404641464246434644464514 unmodified lines46604661466246634664466546664667466846694670467146724673467446754676467718 unmodified lines4696469746984699470047014702470347044705470647074708470947104711471247134714471547165 unmodified lines4722472347244725472647274728472947304731336 unmodified lineslet saveTimer = 0;let saveDeadline = 0;let chapterManifestLoader = null;let chapterSearchConfiguration = null;let chapterSearchModulePromise = null;let chapterSearchClient = null;let chapterSearchPage = null;trackReaderResource(() => { chapterSearchClient?.dispose(); chapterSearchClient = null; });let folderNavigationTarget = null;let bookmarkInvoker = null;const bookmarkInertSiblings = new Map();1867 unmodified linesfunction sanitizeEpubDocument(doc) {return sanitizeReaderDocument(normalizeEpubDocument(doc), { preserveEpubStyles: true });}function parseChapterDocument(text) {// Parse generated XHTML before HTML's void-element rules can swallow children// of prefixed elements such as <html:meta/> (including the following title).const xml = new DOMParser().parseFromString(text, "application/xhtml+xml");if (!xml.querySelector("parsererror"))text = new XMLSerializer().serializeToString(normalizeEpubDocument(xml));return sanitizeEpubDocument(new DOMParser().parseFromString(text, "text/html"));}function epubContentBody(doc) {const nestedBody = [...doc.querySelectorAll("body")].find((body) => body !== doc.body);811 unmodified linesconst chapterPrefetchCount = 6;const chapterBudget = VoiceOfMLReaderSecurity.createByteBudget();if (!manifestBase) throw new Error("EPUB_INVALID_MANIFEST_PATH");const searchIndex = manifest.search_index;chapterSearchConfiguration = searchIndex?.path === "epub-search-index.json.gz" &&Number.isSafeInteger(searchIndex.bytes) && searchIndex.bytes > 0 &&/^[0-9a-f]{64}$/.test(searchIndex.sha256 || "")? { chapters: manifest.chapters, index: { ...searchIndex,url: readerContentUrl(new URL(searchIndex.path, manifestBase).href) } }: null;const chapterUrl = (chapter) => trustedChapterUrl(chapter.path, manifestBase);const resourceUrl = (raw, base, attribute) => {const value = String(raw || "").trim();65 unmodified lineslet inserted = false;try {assertReaderActive();const doc = parseChapterDocument(new TextDecoder().decode(bytes));for (const element of doc.querySelectorAll("*")) {for (const name of ["src", "href", "poster", "xlink:href"])if (element.hasAttribute(name)) {8 unmodified linesarticle.className = "reader-markdown reader-epub-chapter";article.dataset.chapter = String(chapter.index);article.innerHTML = doc.body ? doc.body.innerHTML : "";// The generated text index includes head text (e.g. the chapter title).article._chapterSearchHead = doc.head ? document.importNode(doc.head, true) : null;const marker = frame.querySelector(`.reader-chapter-sentinel[data-chapter="${chapter.index}"]`);1095 unmodified linesconst fullSearchInput = fullSearchView.querySelector("#full-search-input"),fullSearchStatus = fullSearchView.querySelector("#full-search-status"),fullSearchResultsNode = fullSearchView.querySelector("#full-search-results");const chapterSearchPagination = document.createElement("div");chapterSearchPagination.className = "full-search-pagination";chapterSearchPagination.hidden = true;chapterSearchPagination.innerHTML = '<button id="full-search-page-prev" type="button">上一页</button><label>第 <input id="full-search-page" type="number" min="1" value="1" aria-label="搜索结果页码"> 页 <span id="full-search-pages"></span></label><button id="full-search-page-next" type="button">下一页</button>';fullSearchResultsNode.before(chapterSearchPagination);const fullSearchCancel = document.createElement("button");fullSearchCancel.type = "button";fullSearchCancel.id = "full-search-cancel";fullSearchCancel.className = "text-action";fullSearchCancel.textContent = "取消搜索";fullSearchCancel.hidden = true;fullSearchStatus.after(fullSearchCancel);const fullSearchRetry = document.createElement("button");fullSearchRetry.type = "button";fullSearchRetry.id = "full-search-retry";fullSearchRetry.className = "text-action";fullSearchRetry.textContent = "重试搜索";fullSearchRetry.hidden = true;fullSearchCancel.after(fullSearchRetry);fullSearchRetry.addEventListener("click", runFullSearch);fullSearchCancel.addEventListener("click", () => {nextReaderGeneration("search");beginReaderNavigation();chapterSearchClient?.cancel();chapterSearchPage = null;updateSearchState({ results: [], index: -1 });renderFullSearchResults();fullSearchCancel.hidden = true;fullSearchRetry.hidden = false;fullSearchStatus.textContent = "搜索已取消";});chapterSearchPagination.querySelector("#full-search-page-prev").addEventListener("click", () =>loadChapterSearchPage(chapterSearchPage.offset - chapterSearchPage.pageSize));chapterSearchPagination.querySelector("#full-search-page-next").addEventListener("click", () =>loadChapterSearchPage(chapterSearchPage.offset + chapterSearchPage.pageSize));chapterSearchPagination.querySelector("#full-search-page").addEventListener("change", event => {if (!chapterSearchPage || !Number.isFinite(event.target.valueAsNumber)) return;loadChapterSearchPage((event.target.valueAsNumber - 1) * chapterSearchPage.pageSize);});// Full-text search: format matching, result presentation, and navigation.function chapterSearchModule() {if (!chapterSearchModulePromise)chapterSearchModulePromise = import("/static/reader-chapter-search.mjs").catch(error => { chapterSearchModulePromise = null; throw error; });return chapterSearchModulePromise;}async function searchChapterBook(query, generation) {if (!chapterSearchConfiguration) throw new Error("本书暂无完整全文搜索索引");const module = await chapterSearchModule();if (!isReaderGenerationCurrent("search", generation)) return;if (chapterSearchClient?.failed) { chapterSearchClient.dispose(); chapterSearchClient = null; }if (!chapterSearchClient) chapterSearchClient = module.createChapterSearch(chapterSearchConfiguration);const page = await chapterSearchClient.search(query);if (isReaderGenerationCurrent("search", generation)) applyChapterSearchPage(page);}function applyChapterSearchPage(page) {chapterSearchPage = page;updateSearchState({ results: page.results.map(result => ({ ...result,activate: generation => navigateChapterSearchResult(result, generation) })), index: -1 });}async function navigateChapterSearchResult(result, generation) {const article = await chapterManifestLoader?.(result.chapterIndex);if (!article || !isReaderGenerationCurrent("navigation", generation)) return false;const module = await chapterSearchModule();if (!isReaderGenerationCurrent("navigation", generation)) return false;clearFullSearchMarks();const mapping = module.chapterTextMap([article._chapterSearchHead, article]);const match = result.snippet.text.slice(result.snippet.matchStart,result.snippet.matchStart + result.snippet.matchLength);let start = result.start;if (mapping.text.slice(start, start + result.length) !== match) {// A browser may repair malformed source HTML differently from HTMLParser.// Relocate only by a unique full excerpt; never guess between repeated hits.const found = mapping.text.indexOf(result.snippet.text);if (found < 0 || mapping.text.indexOf(result.snippet.text, found + 1) >= 0)throw new Error("已加载章节,但未能准确定位这处文字");start = found + result.snippet.matchStart;}const parts = mapping.parts(start, start + result.length, article);const [mark] = highlightTextParts(parts);(mark || article).scrollIntoView({ block: "center" });const tocIndex = navigationState.tocEntries.findIndex(entry => entry.chapterIndex === result.chapterIndex);if (tocIndex >= 0) { updateNavigationState({ currentChapterIndex: tocIndex }); updateTocCurrentMark(); }updateProgressTools();scheduleSave();return true;}function updateChapterSearchPagination() {const page = chapterSearchPage;chapterSearchPagination.hidden = !page || !page.total;if (!page) return;const pages = Math.ceil(page.total / page.pageSize);const input = chapterSearchPagination.querySelector("#full-search-page");input.value = String(Math.floor(page.offset / page.pageSize) + 1);input.max = String(Math.max(1, pages));chapterSearchPagination.querySelector("#full-search-pages").textContent = `/ ${pages}`;chapterSearchPagination.querySelector("#full-search-page-prev").disabled = page.offset === 0;chapterSearchPagination.querySelector("#full-search-page-next").disabled = page.offset + page.pageSize >= page.total;}async function loadChapterSearchPage(offset, selectLast = null) {if (!chapterSearchPage || !chapterSearchClient) return;const generation = nextReaderGeneration("search");beginReaderNavigation();fullSearchCancel.hidden = false;fullSearchRetry.hidden = true;fullSearchStatus.textContent = "正在加载搜索结果…";try {const page = await chapterSearchClient.page(offset);if (!isReaderGenerationCurrent("search", generation)) return;applyChapterSearchPage(page);renderFullSearchResults();fullSearchStatus.textContent = `${page.total} 个结果`;if (selectLast !== null) await activateFullSearchResult(selectLast ? page.results.length - 1 : 0, false);} catch (error) {if (isReaderGenerationCurrent("search", generation)) {fullSearchStatus.textContent = error.message || "搜索结果加载失败";fullSearchRetry.hidden = false;}} finally {if (isReaderGenerationCurrent("search", generation)) fullSearchCancel.hidden = true;}}async function fullSearchFoliateMatches(query, generation) {const results = [];if (!epubRendition?.search) return results;232 unmodified linesreturn output;}function renderFullSearchResults() {updateChapterSearchPagination();fullSearchResultsNode.textContent = "";for (const [index, result] of searchState.results.entries()) {const row = document.createElement("button"),16 unmodified linesbeginReaderNavigation();clearFullSearchMarks();updateSearchState({ query, results: [], index: -1 });chapterSearchPage = null;updateChapterSearchPagination();fullSearchRetry.hidden = true;fullSearchCancel.hidden = capability.mode !== "epub-chapters" || !query;fullSearchResultsNode.textContent = "";fullSearchView.querySelectorAll(".full-search-nav button").forEach((button) => {button.disabled = true;});if (!query) {chapterSearchClient?.cancel();fullSearchStatus.textContent = "输入关键词搜索正文";return;}3 unmodified linespublishSearchResults(generation, await fullSearchPdfMatches(query, generation));else if (capability.mode === "foliate")publishSearchResults(generation, await fullSearchFoliateMatches(query, generation));else if (capability.mode === "epub-chapters")await searchChapterBook(query, generation);else if (["text", "markdown", "docx"].includes(capability.mode))publishSearchResults(generation,14 unmodified lineselse throw new Error("此格式没有可搜索文本");if (!isReaderGenerationCurrent("search", generation)) return;renderFullSearchResults();fullSearchStatus.textContent = chapterSearchPage? (chapterSearchPage.total ? `${chapterSearchPage.total} 个结果` : "未找到正文匹配"): searchState.results.length? `${searchState.results.length}${searchState.results.length === 100 ? "+" : ""} 个结果`: "未找到正文匹配";} catch (error) {if (isReaderGenerationCurrent("search", generation)) {fullSearchStatus.textContent = error.message || "正文搜索不可用";fullSearchRetry.hidden = capability.mode !== "epub-chapters";}} finally {if (isReaderGenerationCurrent("search", generation)) fullSearchCancel.hidden = true;if (isReaderGenerationCurrent("search", generation))fullSearchView.querySelectorAll(".full-search-nav button").forEach((button) => {button.disabled = !searchState.results.length;18 unmodified linesif (closePanel) setReaderPanelOpen(false, true);else fullSearchResultsNode.children[index]?.scrollIntoView({ block: "nearest" });} catch (error) {if (capability.mode === "epub-chapters" && isReaderGenerationCurrent("navigation", generation))fullSearchStatus.textContent = error.message || "搜索结果定位失败";reportNavigationError(error, generation);}}function moveFullSearch(step) {if (chapterSearchPage?.total) {const page = chapterSearchPage;const next = searchState.index < 0 ? (step > 0 ? 0 : -1) : searchState.index + step;if (next < 0) return loadChapterSearchPage(page.offset ? page.offset - page.pageSize: Math.floor((page.total - 1) / page.pageSize) * page.pageSize, true);if (next >= searchState.results.length) return loadChapterSearchPage(page.offset + page.pageSize < page.total ? page.offset + page.pageSize : 0, false);return activateFullSearchResult(next, false);}if (searchState.results.length)return activateFullSearchResult((searchState.index + step + searchState.results.length) % searchState.results.length,5 unmodified linesif (panel.classList.contains("is-open") && !fullSearchView.hidden) {beginReaderNavigation();nextReaderGeneration("search");chapterSearchClient?.cancel();chapterSearchPage = null;fullSearchCancel.hidden = true;fullSearchRetry.hidden = true;clearFullSearchMarks();updateSearchState({ results: [], index: -1 });renderFullSearchResults();
26 unmodified lines27282930313226 unmodified lines"/icons/icon-512.png"];const READER_RUNTIME_PATHS = new Set(["/static/reader-navigation.js","/static/reader-contract.js","/static/reader-store.js",26 unmodified lines272829303132333426 unmodified lines"/icons/icon-512.png"];const READER_RUNTIME_PATHS = new Set(["/static/reader-chapter-search.mjs","/static/reader-chapter-search-worker.mjs","/static/reader-navigation.js","/static/reader-contract.js","/static/reader-store.js",
1234567891011121314151617181920212223242526272829303132import assert from "node:assert/strict";import { countMatches, resultPage, scanText, validateIndex } from "../static/reader-chapter-search-worker.mjs";
const chapters = [ { index: 1, title: "开头", path: "chapters/1.xhtml", text: "手机 手。机 a+b [term] " + "needle ".repeat(125) }, { index: 2, title: "结尾", path: "chapters/2.xhtml", text: "needle ".repeat(130) + "远方命中" }];const counted = await countMatches(chapters, "needle", () => true);assert.equal(counted.total, 255);assert.deepEqual(counted.counts, [125, 130]);const all = [];for (let offset = 0; offset < counted.total; offset += 50) { const page = await resultPage(chapters, "needle", counted.counts, offset, () => true); assert.ok(page.length <= 50); all.push(...page);}assert.equal(new Set(all.map(item => `${item.chapterIndex}:${item.start}`)).size, 255);assert.equal(all.at(-1).chapterIndex, 2);for (const query of ["手机", "手。机", "a+b", "[term]", "远方命中"]) { assert.equal((await countMatches(chapters, query, () => true)).total, 1, query);}const boundaryText = "x".repeat(65534) + "跨边界😀" + "y".repeat(65536) + "跨边界😀";const found = [];await scanText(boundaryText, "跨边界😀", (start, length) => found.push([start, length]));assert.deepEqual(found.map(([start, length]) => boundaryText.slice(start, start + length)), ["跨边界😀", "跨边界😀"]);let current = true;const cancelled = scanText("x".repeat(1000000), "x", () => { current = false; }, () => current);await assert.rejects(cancelled, { name: "AbortError" });assert.equal(validateIndex({ version: 1, kind: "epub-search-index", chapters }, chapters).length, 2);assert.throws(() => validateIndex({ version: 1, kind: "epub-search-index", chapters: chapters.slice(0, 1) }, chapters));assert.throws(() => validateIndex({ version: 1, kind: "epub-search-index", chapters: [chapters[1], chapters[0]] }, chapters));console.log("chapter search: complete counts, paging, literal matches, Unicode boundaries, cancellation and index identity passed");123456477 unmodified lines484485486487488489"""Local Reader behavior regressions; all document/network fixtures stay offline."""import ioimport jsonimport unittestimport urllib.parse477 unmodified linesself.assertEqual(download["link"], [record["download"]])self.assertEqual(seen, [record["title"] + ".mobi" for record in records])def test_chapter_manifest_migrates_position_saved_by_foliate(self):source = "https://huggingface.co/datasets/vomebook/Reader-Assets/resolve/main/objects/aa/" + "b" * 64 + "/chapter-manifest.json"manifest = {"version": 1, "kind": "epub-chapters", "chapters": [12345678477 unmodified lines486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618"""Local Reader behavior regressions; all document/network fixtures stay offline."""import ioimport gzipimport hashlibimport jsonimport unittestimport urllib.parse477 unmodified linesself.assertEqual(download["link"], [record["download"]])self.assertEqual(seen, [record["title"] + ".mobi" for record in records])def serve_chapter_search(self, index_failure=None, namespaced=False):base = "https://huggingface.co/datasets/vomebook/Reader-Assets/resolve/main/objects/aa/" + "b" * 64 + "/foliate-original-v1/epub-chapters/"chapters, texts, bodies = [], [], {}for index in range(1, 13):path = f"chapters/chapter-{index:04d}.xhtml"title = f"Chapter {index}"if index == 12:body = ("<h1>最后一章</h1><p>前言 &amp; <span>独特</span><em>词语</em> 尾声</p>"+ "".join(f"<p>第{i}处needle结束</p>" for i in range(155))+ "<p>手机 手。机</p>")text = "最后一章 前言 & 独特 词语 尾声 " + " ".join(f"第{i}处needle结束" for i in range(155)) + " 手机 手。机"if namespaced:body = ('<html:html xmlns:html="http://www.w3.org/1999/xhtml"><html:head>''<html:meta/><html:title>原始标题</html:title></html:head><html:body>'+ body + '</html:body></html:html>')text = "原始标题 " + textelse:body = f"<h1>{title}</h1><p style='height:12000px'>普通正文</p>"text = title + " 普通正文"bodies[base + path] = bodychapters.append({"index": index, "path": path, "title": title, "bytes": len(body.encode())})texts.append({"index": index, "path": path, "title": title, "text": text})packed = gzip.compress(json.dumps({"version": 1, "kind": "epub-search-index", "chapters": texts}, ensure_ascii=False).encode(), mtime=0)manifest = {"version": 1, "kind": "epub-chapters", "chapters": chapters,"search_index": {"path": "epub-search-index.json.gz", "bytes": len(packed), "sha256": hashlib.sha256(packed).hexdigest()}}requests = []def serve(route):raw = urllib.parse.parse_qs(urllib.parse.urlsplit(route.request.url).query)["url"][0]requests.append(raw)if raw.endswith("chapter-manifest.json"):route.fulfill(content_type="application/json", body=json.dumps(manifest))elif raw.endswith("epub-search-index.json.gz"):attempt = sum(item.endswith("epub-search-index.json.gz") for item in requests)if index_failure and index_failure(route, attempt, packed):returnroute.fulfill(content_type="application/gzip", body=packed)else:route.fulfill(content_type="text/html", body=bodies[raw])# Worker fetches belong to the context, not to the page's route table.self.context.route("**/api/reader-content**", serve)self.open(self.reader_url("epub-chapters", url=base + "chapter-manifest.json"))return requests, basedef test_chapter_search_is_lazy_complete_paged_and_navigates_unloaded_repeated_hits(self):requests, base = self.serve_chapter_search()self.assertFalse(any(item.endswith("epub-search-index.json.gz") for item in requests))self.assertNotIn(base + "chapters/chapter-0012.xhtml", requests)self.search("needle")self.assertEqual(self.page.locator("#full-search-status").text_content(), "155 个结果")self.assertEqual(self.page.locator(".full-search-result").count(), 50)self.assertNotIn(base + "chapters/chapter-0012.xhtml", requests)page_input = self.page.locator("#full-search-page")page_input.fill("4")page_input.press("Enter")page_input.blur()self.page.wait_for_function("() => document.querySelectorAll('.full-search-result').length === 5")self.page.locator(".full-search-result").last.click()self.page.wait_for_function("() => document.querySelector('.reader-epub-chapter[data-chapter=\"12\"] mark.full-search-highlight')")mark = self.page.locator(".reader-epub-chapter mark.full-search-highlight")self.assertEqual(mark.text_content(), "needle")self.assertEqual(mark.locator("..").text_content(), "第154处needle结束")# Previous-result navigation crosses a result-page boundary exactly.self.page.locator("#history").click()self.page.locator("#full-search-toggle").click()self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '155 个结果'")self.page.locator("#full-search-prev").click()self.page.wait_for_function("() => document.querySelector('#full-search-page').value === '4'")self.page.locator("#full-search-next").click()self.page.wait_for_function("() => document.querySelector('.reader-epub-chapter mark')?.parentElement.textContent === '第0处needle结束'")self.assertEqual(self.page.locator("#full-search-page").input_value(), "1")self.assertEqual(sum(item.endswith("epub-search-index.json.gz") for item in requests), 1)def test_chapter_search_maps_inline_nodes_entities_and_repeated_searches(self):requests, _ = self.serve_chapter_search(namespaced=True)self.search("独特 词语")self.assertEqual(self.page.locator("#full-search-status").text_content(), "1 个结果")self.page.locator(".full-search-result").click()self.page.wait_for_function("() => document.querySelectorAll('.reader-epub-chapter mark.full-search-highlight').length === 2")self.assertEqual(self.page.locator(".reader-epub-chapter mark.full-search-highlight").all_text_contents(), ["独特", "词语"])self.page.locator("#history").click()self.page.locator("#full-search-toggle").click()self.page.locator("#full-search-input").fill("手机")self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '1 个结果' && document.querySelector('.full-search-result')?.textContent.includes('手机')")self.page.locator(".full-search-result").click()self.page.wait_for_function("() => document.querySelector('.reader-epub-chapter mark.full-search-highlight')?.textContent === '手机'")self.assertEqual(sum(item.endswith("epub-search-index.json.gz") for item in requests), 1)def test_chapter_search_retries_a_failed_index_and_rejects_corrupt_bytes(self):def failure(route, attempt, packed):if attempt == 1:route.fulfill(status=503, body="temporarily unavailable")return Trueif attempt == 2:route.fulfill(content_type="application/gzip", body=packed[:-1] + bytes([packed[-1] ^ 1]))return Truerequests, _ = self.serve_chapter_search(failure)self.page.locator("#history").click()self.page.locator("#full-search-toggle").click()self.page.locator("#full-search-input").fill("needle")self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent.includes('503')")self.page.locator("#full-search-retry").click()self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent.includes('校验失败')")self.page.locator("#full-search-retry").click()self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '155 个结果'")self.assertEqual(sum(item.endswith("epub-search-index.json.gz") for item in requests), 3)def test_chapter_search_cancelled_download_cannot_publish_stale_results(self):held = []def hold(route, attempt, packed):if attempt == 1:held.append((route, packed))return Truerequests, _ = self.serve_chapter_search(hold)self.page.locator("#history").click()self.page.locator("#full-search-toggle").click()with self.context.expect_event("request", predicate=lambda request: "epub-search-index" in request.url):self.page.locator("#full-search-input").fill("needle")self.page.locator("#full-search-cancel").click()self.assertEqual(self.page.locator("#full-search-status").text_content(), "搜索已取消")self.page.locator("#full-search-input").fill("手机")self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '1 个结果'")self.assertEqual(self.page.locator(".full-search-result").count(), 1)self.assertEqual(sum(item.endswith("epub-search-index.json.gz") for item in requests), 2)for route, packed in held:route.fulfill(content_type="application/gzip", body=packed)self.assertEqual(self.page.locator("#full-search-status").text_content(), "1 个结果")def test_chapter_manifest_migrates_position_saved_by_foliate(self):source = "https://huggingface.co/datasets/vomebook/Reader-Assets/resolve/main/objects/aa/" + "b" * 64 + "/chapter-manifest.json"manifest = {"version": 1, "kind": "epub-chapters", "chapters": [
17 unmodified lines1819202122232417 unmodified linesfor (const extension of sandbox.self.VoiceOfMLReader.articleExtensions) assert.deepStrictEqual(Object.keys(sandbox.self.VoiceOfMLReader.capability(extension).features).sort(), ['bookmarks', 'media', 'pagination', 'search', 'toc', 'zoom'])assert.strictEqual(sandbox.self.VoiceOfMLReader.capability('pdf-pages').mode, 'pdf-pages')assert.strictEqual(sandbox.self.VoiceOfMLReader.capability('pdf-pages').features.toc, true)assert.strictEqual(sandbox.self.VoiceOfMLReader.capability('epub-chapters').features.search, false)for (const extension of ['mp3', 'm4a', 'flac', 'mpga', 'audio']) assert.strictEqual(sandbox.self.VoiceOfMLReader.capability(extension).mode, 'audio')for (const extension of ['mp4', 'mov', 'video']) assert.strictEqual(sandbox.self.VoiceOfMLReader.capability(extension).mode, 'video')assert.strictEqual(sandbox.self.VoiceOfMLReader.capability('zip').mode, null)17 unmodified lines1819202122232417 unmodified linesfor (const extension of sandbox.self.VoiceOfMLReader.articleExtensions) assert.deepStrictEqual(Object.keys(sandbox.self.VoiceOfMLReader.capability(extension).features).sort(), ['bookmarks', 'media', 'pagination', 'search', 'toc', 'zoom'])assert.strictEqual(sandbox.self.VoiceOfMLReader.capability('pdf-pages').mode, 'pdf-pages')assert.strictEqual(sandbox.self.VoiceOfMLReader.capability('pdf-pages').features.toc, true)assert.strictEqual(sandbox.self.VoiceOfMLReader.capability('epub-chapters').features.search, true)for (const extension of ['mp3', 'm4a', 'flac', 'mpga', 'audio']) assert.strictEqual(sandbox.self.VoiceOfMLReader.capability(extension).mode, 'audio')for (const extension of ['mp4', 'mov', 'video']) assert.strictEqual(sandbox.self.VoiceOfMLReader.capability(extension).mode, 'video')assert.strictEqual(sandbox.self.VoiceOfMLReader.capability('zip').mode, null)
48 unmodified lines4950515253545548 unmodified linesevents.fetch({request:{url,mode},respondWith(){throw Error('unexpected interception: '+url)}});}}(async()=>{for(const failure of ['none','core','network','status','invalid','payload']) await check(failure);console.log('HF service worker: manifest failure isolation, fixed cache activation and API/TXT/navigation bypass passed');})().catch(error=>{console.error(error);process.exitCode=1;});48 unmodified lines4950515253545556575859606162636465666768697071727348 unmodified linesevents.fetch({request:{url,mode},respondWith(){throw Error('unexpected interception: '+url)}});}}async function checkSearchRuntimeCache(hasOldCache) {const events = {}, updates = [];const fresh = {ok:true, version:'current', clone(){return this;}};const old = hasOldCache ? {ok:true, version:'previous'} : undefined;vm.runInNewContext(source, {URL, Set, console,self:{location:{hostname:'localhost'},addEventListener:(name,fn)=>events[name]=fn},caches:{open:async()=>({match:async()=>old,put:async(key,value)=>updates.push(value.version)})},fetch:async()=>fresh,});for(const name of ['reader-chapter-search.mjs','reader-chapter-search-worker.mjs']) {let completion;events.fetch({request:{url:'https://localhost/static/'+name,mode:'cors'},respondWith(value){completion=value;}});assert.strictEqual((await completion).version,'current');}assert.deepStrictEqual(updates,['current','current']);}(async()=>{for(const failure of ['none','core','network','status','invalid','payload']) await check(failure);for(const old of [false,true]) await checkSearchRuntimeCache(old);console.log('HF service worker: manifest failure isolation, fixed cache activation and API/TXT/navigation bypass passed');})().catch(error=>{console.error(error);process.exitCode=1;});
Dockerfile+1
scripts/build_static_assets.mjs+6-1
scripts/check_reader_release.mjs+2
static/reader-chapter-search-worker.mjsAdded+177
static/reader-chapter-search.mjsAdded+93
static/reader-contract.js+1-1
static/reader-runtime.js+1-1
static/reader.css+22-3
static/reader.js+174-5
static/sw.js+2
tests/test_reader_chapter_search.mjsAdded+32
tests/test_reader_refactor.py+129
tests/test_reader_regression.js+1-1
tests/test_service_worker.js+18