vomebook commited on
Commit ·
2b84661
1
Parent(s): ad4ff55
fix: retain nearby PDF pages and reduce Reader rendering work
Browse filesFiles changed (8)
19 unmodified lines20212223242526274 unmodified lines32333435363738394019 unmodified lines606162636465666768697071727319 unmodified lines!url.search && !!prefix && bookPath.test(decodeURIComponent(url.pathname.slice(prefix[0].length)));}async function readBounded(stream, signal) {const reader = stream.getReader(), chunks = [];let size = 0;const cancel = () => reader.cancel().catch(() => {});signal.addEventListener("abort", cancel, { once: true });4 unmodified linesif (signal.aborted) throw aborted();if (done) break;size += value.byteLength;if (size > limit) throw new Error("READER_RESOURCE_LIMIT");chunks.push(value);}const result = new Uint8Array(size);let offset = 0;for (const chunk of chunks) { result.set(chunk, offset); offset += chunk.byteLength; }19 unmodified linespendingBook = (async () => {const response = await fetch(configuration.url, { signal: request.signal, credentials: "omit" });if (!response.ok) throw new Error(`HTTP ${response.status}`);const packed = await readBounded(response.body, request.signal);if (packed.byteLength !== configuration.bytes) throw new Error("PDF_OCR_SIZE_MISMATCH");const digest = [...new Uint8Array(await crypto.subtle.digest("SHA-256", packed))].map(value => value.toString(16).padStart(2, "0")).join("");if (digest !== configuration.sha256) throw new Error("PDF_OCR_HASH_MISMATCH");const expanded = await readBounded(new Blob([packed]).stream().pipeThrough(new DecompressionStream("gzip")), request.signal);const decoded = JSON.parse(new TextDecoder().decode(expanded));if (request.signal.aborted) throw aborted();book = validateBookText(decoded, configuration.pageCount, configuration.sourceSha);return book;19 unmodified lines202122232425262728294 unmodified lines34353637383940414243444546474819 unmodified lines68697071727374757677787980818219 unmodified lines!url.search && !!prefix && bookPath.test(decodeURIComponent(url.pathname.slice(prefix[0].length)));}async function readBounded(stream, signal, expected = null, text = false) {const reader = stream.getReader(), chunks = [];const bytes = expected === null ? null : new Uint8Array(expected);const decoder = text ? new TextDecoder() : null;let size = 0;const cancel = () => reader.cancel().catch(() => {});signal.addEventListener("abort", cancel, { once: true });4 unmodified linesif (signal.aborted) throw aborted();if (done) break;size += value.byteLength;if (size > limit || (bytes && size > bytes.length)) throw new Error("READER_RESOURCE_LIMIT");if (bytes) bytes.set(value, size - value.byteLength);else chunks.push(decoder ? decoder.decode(value, {stream:true}) : value);}if (bytes) {if (size !== expected) throw new Error("PDF_OCR_SIZE_MISMATCH");return bytes;}if (decoder) { chunks.push(decoder.decode()); return chunks.join(""); }const result = new Uint8Array(size);let offset = 0;for (const chunk of chunks) { result.set(chunk, offset); offset += chunk.byteLength; }19 unmodified linespendingBook = (async () => {const response = await fetch(configuration.url, { signal: request.signal, credentials: "omit" });if (!response.ok) throw new Error(`HTTP ${response.status}`);let packed = await readBounded(response.body, request.signal, configuration.bytes);if (packed.byteLength !== configuration.bytes) throw new Error("PDF_OCR_SIZE_MISMATCH");const digest = [...new Uint8Array(await crypto.subtle.digest("SHA-256", packed))].map(value => value.toString(16).padStart(2, "0")).join("");if (digest !== configuration.sha256) throw new Error("PDF_OCR_HASH_MISMATCH");const stream = new ReadableStream({start(controller) {controller.enqueue(packed); controller.close();}});packed = null;const decoded = JSON.parse(await readBounded(stream.pipeThrough(new DecompressionStream("gzip")), request.signal, null, true));if (request.signal.aborted) throw aborted();book = validateBookText(decoded, configuration.pageCount, configuration.sourceSha);return book;
1104 unmodified lines1105110611071108110911101104 unmodified linesmonospace;color: #e7e9eb;}.reader-markdown {margin: 0 auto;max-width: 76ch;1104 unmodified lines110511061107110811091110111111121113111411151116111711181119112011211104 unmodified linesmonospace;color: #e7e9eb;}.reader-text-block {margin: 0;font: inherit;white-space: inherit;overflow-wrap: inherit;content-visibility: auto;contain-intrinsic-block-size: auto 1600px;}.reader-text-block:focus-within {content-visibility: visible;}.reader-markdown {margin: 0 auto;max-width: 76ch;
448 unmodified lines449450451452453454100 unmodified lines55555655755855956056156256356456556656756812 unmodified lines5815825835845855861459 unmodified lines20462047204820492050205120522053205420552056205720582059206020611515 unmodified lines3577357835793580358135823583358435853586358735883589179 unmodified lines3769377037713772377337743775196 unmodified lines397239733974397539763977397824 unmodified lines400340044005400640074008124 unmodified lines413341344135413641374138413941404141414241434144297 unmodified lines4442444344444445444644474448444944504 unmodified lines44554456445744584459446044614462446310 unmodified lines4474447544764477447844794480448144824483448444854486448728 unmodified lines451645174518451945204521516 unmodified lines5038503950405041504250431687 unmodified lines673167326733673467356736673767386739674067411 unmodified line67436744674567466747674867496750675167526753104 unmodified lines68586859686068616862686368646865686668676868686968706871687268736874687568766877448 unmodified lineslet bookmarkInvoker = null;const bookmarkInertSiblings = new Map();let pdfDocument = null;let pdfPageManifest = null;let pdfOcrManifest = null;let pdfOcrManifestPromise = null;100 unmodified lineslet canvases = shells.filter(shell => shell.querySelector("canvas.ready")).length;let images = shells.filter(shell => shell.querySelector("img.ready")).length;let pixels = pdfRetainedPixels();shells.sort((a, b) => Math.abs(Number(b.dataset.page) - documentState.page) -Math.abs(Number(a.dataset.page) - documentState.page) ||Number(a.dataset.renderUsedAt || 0) - Number(b.dataset.renderUsedAt || 0));for (const shell of shells) {const canvas = shell.querySelector("canvas.ready"), image = shell.querySelector("img.ready");if (pixels <= pdfPixelBudget() && !(canvas && canvases > canvasLimit) && !(image && images > 25)) continue;if (shell === protectedShell || shell.dataset.renderVisible === "1" ||Number(shell.dataset.page) === documentState.page || pdfSelectionIntersects(shell)) continue;shell._textEpoch = (shell._textEpoch || 0) + 1;if (canvas) {pixels -= pdfSurfacePixels(canvas);12 unmodified linesshell._bookmarkTextItems = [];shell.dataset.textReady = "0";shell.dataset.renderState = "idle";}fullSearchActiveMarks = fullSearchActiveMarks.filter(mark => mark.isConnected);}1459 unmodified lines}function pageAtMarker() {const y = bookmarkRibbon.getBoundingClientRect().bottom,pages = [...content.querySelectorAll(".reader-page, .reader-docx-page")];if (!pages.length) return null;return (pages.find((page) => {const rect = page.getBoundingClientRect();return rect.top <= y && rect.bottom > y;}) ||pages.find((page) => page.getBoundingClientRect().bottom > y) ||pages[pages.length - 1]);}function syncCurrentPageFromMarker() {if (performance.now() < pageNavigationLockUntil) return;1515 unmodified linestextLayer.setAttribute("role", "document");textLayer.setAttribute("aria-label", `第 ${page} 页正文`);shell.append(canvas, textLayer);shell.addEventListener("focus", () => renderPdfInBackground(shell));observeShell(shell);return shell;};const firstShell = createShell(1);content.appendChild(firstShell);markReaderContentReady();pdfShellWindow = createPdfShellWindow(pdf.numPages, firstShell, createShell, (shell) => {observer.unobserve(shell);visibleObserver.unobserve(shell);179 unmodified linesacquired = true;}const base = page.getViewport({ scale: 1 });const view = page.getViewport({ scale: Math.min(3, Math.max(0.5, shell.clientWidth / base.width)) });const outputScale = Math.min(2, Math.max(1, Number(window.devicePixelRatio) || 1));canvas = document.createElement("canvas");canvas.setAttribute("aria-hidden", "true");196 unmodified linesassertReaderActive();if (renderController.signal.aborted) throw readerAbortError();const base = page.getViewport({ scale: 1 }),scale = Math.min(3, Math.max(0.5, shell.clientWidth / base.width)),viewport = page.getViewport({ scale }),outputScale = Math.min(2, Math.max(1, Number(window.devicePixelRatio) || 1));const canvas = shell.querySelector("canvas");24 unmodified linesif (!isReaderGenerationCurrent("pdf", generation)) shell.dataset.pendingRerender = "1";} while (shell.dataset.pendingRerender);shell.querySelector("canvas").classList.add("ready");shell.dataset.renderState = "rendered";shell.dataset.renderUsedAt = String(Date.now());pdfShellWindow?.remember(shell);124 unmodified linesfunction releasePdfRenderSlot() {pdfActiveRenders = Math.max(0, pdfActiveRenders - 1);if (readerAbortController.signal.aborted) return;let index = -1, best = 0;for (let i = 0; i < pdfRenderWaiters.length; i++) {const waiter = pdfRenderWaiters[i], value = Math.max(waiter.priority, waiter.shell ? pdfPagePriority(waiter.shell) : 0);if (value > best) { best = value; index = i; }}if (index < 0) index = 0;const waiter = pdfRenderWaiters.splice(index, 1)[0];297 unmodified lines}async function renderPlainText(response) {assertReaderActive();const pre = document.createElement("pre");pre.className = "reader-text";content.appendChild(pre);const limit = VoiceOfMLReaderSecurity.LIMITS.documentBytes;VoiceOfMLReaderSecurity.assertResponseSize(response, limit);if (!response.body?.getReader) {4 unmodified linesthrow error;}assertReaderActive();pre.textContent = new TextDecoder(detectTextEncoding(bytes, documentState.title)).decode(bytes).replace(/\ufffd/g, "");return;}const reader = response.body.getReader(),10 unmodified linesdecoder = null,asciiPreviewPossible = true,asciiPrefixLength = 0;const appendDecoded = (value) => {const text = value.replace(/\ufffd/g, "");if (!text) return;// Search can split or normalize previous chunks while the response streams.const tail = pre.lastChild;if (tail?.nodeType === Node.TEXT_NODE) tail.appendData(text);else pre.appendChild(document.createTextNode(text));};const startDecoder = () => {const sample = new Uint8Array(sampleLength);let offset = 0;28 unmodified linesif (value[asciiLength] === 0) {// A split UTF-16 prefix must not leave an ASCII preview behind.pre.textContent = "";displayedSampleSize = 0;asciiPrefixLength = 0;asciiPreviewPossible = false;516 unmodified linesthrow new Error("DOCX rendered no supported content");}const pages = [...body.querySelectorAll(":scope > .reader-docx-wrapper > section.reader-docx")];if (pages.length) {updateDocumentState({ pageCount: pages.length });pageInput.max = String(documentState.pageCount);1687 unmodified linesfullSearchDomSnapshot?.resume();}}async function fullSearchTextNodes(root, generation, endOffset = Infinity, checkpoint = null) {const nodes = [],walker = root.ownerDocument.createTreeWalker(root, NodeFilter.SHOW_TEXT);if (checkpoint) walker.currentNode = checkpoint.target;let visited = 0, length = checkpoint?.start || 0;while (walker.nextNode()) {if (!isReaderGenerationCurrent("search", generation)) return null;const node = walker.currentNode;1 unmodified linenode.data &&!node.parentElement.closest("script,style,mark.full-search-highlight,.reader-pdf-text")) {nodes.push(node);length += node.data.length;if (length >= endOffset) break;}if (++visited % 1000 === 0) await waitForReader();}return nodes;}104 unmodified linesfullSearchDomSnapshot.value?.toc === navigationState.tocEntries ? fullSearchDomSnapshot.value : null;const snapshot = progressive ? (cached ? fullSearchDomSnapshot : createDomSearchSnapshot(root)) : null;const locator = progressive ? createFullSearchDomLocator(root, generation) : null;const nodes = cached ? [] : await fullSearchTextNodes(root, generation);if (!nodes || !isReaderGenerationCurrent("search", generation)) return [];const offsets = cached ? cached.offsets : [],chunks = [];let length = 0;for (const [index, node] of nodes.entries()) {offsets.push({ node, parent: node.parentElement, start: length, end: length + node.data.length });chunks.push(node.data);length += node.data.length;if (index % 1000 === 999) {await waitForReader();if (!isReaderGenerationCurrent("search", generation)) return [];}}if (cached) locator?.seed(cached.checkpoints);else locator?.build(offsets);const headingLookup = cached ? cached.headingLookup : createFullSearchHeadingLookup(root, offsets);448 unmodified lines449450451452453454455456100 unmodified lines55755855956056156256356456556656756856957012 unmodified lines5835845855865875885895901459 unmodified lines2050205120522053205420552056205720582059206020612062206320641515 unmodified lines3580358135823583358435853586358735883589359035913592359335943595179 unmodified lines3775377637773778377937803781196 unmodified lines397839793980398139823983398424 unmodified lines40094010401140124013401440154016124 unmodified lines41414142414341444145414641474148414941504151415241534154297 unmodified lines44524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794 unmodified lines448444854486448744884489449010 unmodified lines45014502450345044505450628 unmodified lines45354536453745384539454045414542516 unmodified lines50595060506150625063506450651687 unmodified lines675367546755675667576758675967606761676267631 unmodified line676567666767676867696770677167726773677467756776677767786779104 unmodified lines6884688568866887688868896890689168926893689468956896689768986899448 unmodified lineslet bookmarkInvoker = null;const bookmarkInertSiblings = new Map();let pdfDocument = null;let docxPageNodes = [];trackReaderResource(() => { docxPageNodes = []; });let pdfPageManifest = null;let pdfOcrManifest = null;let pdfOcrManifestPromise = null;100 unmodified lineslet canvases = shells.filter(shell => shell.querySelector("canvas.ready")).length;let images = shells.filter(shell => shell.querySelector("img.ready")).length;let pixels = pdfRetainedPixels();const retentionPage = Number(pageAtMarker()?.dataset.page) || documentState.page;shells.sort((a, b) => Math.abs(Number(b.dataset.page) - retentionPage) -Math.abs(Number(a.dataset.page) - retentionPage) ||Number(a.dataset.renderUsedAt || 0) - Number(b.dataset.renderUsedAt || 0));for (const shell of shells) {const canvas = shell.querySelector("canvas.ready"), image = shell.querySelector("img.ready");if (pixels <= pdfPixelBudget() && !(canvas && canvases > canvasLimit) && !(image && images > 25)) continue;if (isPdfPageVisible(shell) || Number(shell.dataset.page) === retentionPage || pdfSelectionIntersects(shell)) continue;shell._textEpoch = (shell._textEpoch || 0) + 1;if (canvas) {pixels -= pdfSurfacePixels(canvas);12 unmodified linesshell._bookmarkTextItems = [];shell.dataset.textReady = "0";shell.dataset.renderState = "idle";const pageState = shell.querySelector(".reader-page-state");if (pageState) pageState.hidden = false;}fullSearchActiveMarks = fullSearchActiveMarks.filter(mark => mark.isConnected);}1459 unmodified lines}function pageAtMarker() {const y = bookmarkRibbon.getBoundingClientRect().bottom,pages = docxPageNodes.length ? docxPageNodes : [...content.querySelectorAll(".reader-page, .reader-docx-page")];if (!pages.length) return null;let low = 0, high = pages.length;while (low < high) {const middle = (low + high) >> 1;if (pages[middle].getBoundingClientRect().bottom > y) high = middle;else low = middle + 1;}return pages[Math.min(low, pages.length - 1)];}function syncCurrentPageFromMarker() {if (performance.now() < pageNavigationLockUntil) return;1515 unmodified linestextLayer.setAttribute("role", "document");textLayer.setAttribute("aria-label", `第 ${page} 页正文`);shell.append(canvas, textLayer);const pageState = document.createElement("div");pageState.className = "reader-page-state";pageState.textContent = `正在加载第 ${page} 页...`;shell.appendChild(pageState);shell.addEventListener("focus", () => renderPdfInBackground(shell));observeShell(shell);return shell;};const firstShell = createShell(1);content.appendChild(firstShell);pdfShellWindow = createPdfShellWindow(pdf.numPages, firstShell, createShell, (shell) => {observer.unobserve(shell);visibleObserver.unobserve(shell);179 unmodified linesacquired = true;}const base = page.getViewport({ scale: 1 });const view = page.getViewport({ scale: Math.min(3, shell.clientWidth / base.width) });const outputScale = Math.min(2, Math.max(1, Number(window.devicePixelRatio) || 1));canvas = document.createElement("canvas");canvas.setAttribute("aria-hidden", "true");196 unmodified linesassertReaderActive();if (renderController.signal.aborted) throw readerAbortError();const base = page.getViewport({ scale: 1 }),scale = Math.min(3, shell.clientWidth / base.width),viewport = page.getViewport({ scale }),outputScale = Math.min(2, Math.max(1, Number(window.devicePixelRatio) || 1));const canvas = shell.querySelector("canvas");24 unmodified linesif (!isReaderGenerationCurrent("pdf", generation)) shell.dataset.pendingRerender = "1";} while (shell.dataset.pendingRerender);shell.querySelector("canvas").classList.add("ready");const pageState = shell.querySelector(".reader-page-state");if (pageState) pageState.hidden = true;shell.dataset.renderState = "rendered";shell.dataset.renderUsedAt = String(Date.now());pdfShellWindow?.remember(shell);124 unmodified linesfunction releasePdfRenderSlot() {pdfActiveRenders = Math.max(0, pdfActiveRenders - 1);if (readerAbortController.signal.aborted) return;let index = -1, best = -1, nearest = Infinity;for (let i = 0; i < pdfRenderWaiters.length; i++) {const waiter = pdfRenderWaiters[i], value = waiter.shell ? pdfPagePriority(waiter.shell) : waiter.priority;const rect = waiter.shell?.getBoundingClientRect(), bounds = viewport.getBoundingClientRect();const distance = rect ? Math.max(bounds.top - rect.bottom, rect.top - bounds.bottom, 0) : Infinity;if (value > best || (value === best && distance < nearest)) {best = value; nearest = distance; index = i;}}if (index < 0) index = 0;const waiter = pdfRenderWaiters.splice(index, 1)[0];297 unmodified lines}async function renderPlainText(response) {assertReaderActive();const pre = document.createElement("div");pre.className = "reader-text";content.appendChild(pre);let block = null, blockLength = 0;const appendDecoded = value => {let text = value.replace(/\ufffd/g, "");while (text) {if (!block) {block = document.createElement("pre");block.className = "reader-text-block";pre.appendChild(block);}const boundary = text.indexOf("\n", Math.max(0, 32768 - blockLength));const take = boundary < 0 ? text.length : boundary + 1;const tail = block.lastChild;if (tail?.nodeType === Node.TEXT_NODE) tail.appendData(text.slice(0, take));else block.appendChild(document.createTextNode(text.slice(0, take)));blockLength += take;text = text.slice(take);if (boundary >= 0) { block = null; blockLength = 0; }}};const limit = VoiceOfMLReaderSecurity.LIMITS.documentBytes;VoiceOfMLReaderSecurity.assertResponseSize(response, limit);if (!response.body?.getReader) {4 unmodified linesthrow error;}assertReaderActive();appendDecoded(new TextDecoder(detectTextEncoding(bytes, documentState.title)).decode(bytes));return;}const reader = response.body.getReader(),10 unmodified linesdecoder = null,asciiPreviewPossible = true,asciiPrefixLength = 0;const startDecoder = () => {const sample = new Uint8Array(sampleLength);let offset = 0;28 unmodified linesif (value[asciiLength] === 0) {// A split UTF-16 prefix must not leave an ASCII preview behind.pre.textContent = "";block = null;blockLength = 0;displayedSampleSize = 0;asciiPrefixLength = 0;asciiPreviewPossible = false;516 unmodified linesthrow new Error("DOCX rendered no supported content");}const pages = [...body.querySelectorAll(":scope > .reader-docx-wrapper > section.reader-docx")];docxPageNodes = pages;if (pages.length) {updateDocumentState({ pageCount: pages.length });pageInput.max = String(documentState.pageCount);1687 unmodified linesfullSearchDomSnapshot?.resume();}}async function fullSearchTextNodes(root, generation, endOffset = Infinity, checkpoint = null, collect = null) {const nodes = [],walker = root.ownerDocument.createTreeWalker(root, NodeFilter.SHOW_TEXT);if (checkpoint) walker.currentNode = checkpoint.target;let visited = 0, length = checkpoint?.start || 0, deadline = performance.now() + 8;while (walker.nextNode()) {if (!isReaderGenerationCurrent("search", generation)) return null;const node = walker.currentNode;1 unmodified linenode.data &&!node.parentElement.closest("script,style,mark.full-search-highlight,.reader-pdf-text")) {if (collect) collect(node);else nodes.push(node);length += node.data.length;if (length >= endOffset) break;}if (++visited % 256 === 0 && performance.now() >= deadline) {await waitForReader();deadline = performance.now() + 8;}}return nodes;}104 unmodified linesfullSearchDomSnapshot.value?.toc === navigationState.tocEntries ? fullSearchDomSnapshot.value : null;const snapshot = progressive ? (cached ? fullSearchDomSnapshot : createDomSearchSnapshot(root)) : null;const locator = progressive ? createFullSearchDomLocator(root, generation) : null;const offsets = cached ? cached.offsets : [],chunks = [];let length = 0;const collect = node => {offsets.push({ node, parent: node.parentElement, start: length, end: length + node.data.length });chunks.push(node.data);length += node.data.length;};const nodes = cached ? [] : await fullSearchTextNodes(root, generation, Infinity, null, collect);if (!nodes || !isReaderGenerationCurrent("search", generation)) return [];if (cached) locator?.seed(cached.checkpoints);else locator?.build(offsets);const headingLookup = cached ? cached.headingLookup : createFullSearchHeadingLookup(root, offsets);
52 unmodified lines53545556575859606152 unmodified linesassert.match(reader, /function pdfPagePriority\(shell\)/)assert.match(reader, /priority >= 3 \? "high" : priority >= 1 \? "auto" : "low"/)assert.match(reader, /const waiter = \{\s*shell,\s*priority,/)assert.match(reader, /waiter\.priority, waiter\.shell \? pdfPagePriority\(waiter\.shell\) : 0/)assert.match(reader, /function cancelSpeculativePdfRenders\(protectedShell\)/)assert.match(reader, /shell\.dataset\.renderVisible === "1"/)assert.match(reader, /shell\._renderCancel\?\.\(\)/)assert.match(reader, /const PDF_MANIFEST_PREFETCH_LIMIT = 12/)assert.match(reader, /const PDF_MANIFEST_PREFETCH_CONCURRENCY = 3/)52 unmodified lines53545556575859606152 unmodified linesassert.match(reader, /function pdfPagePriority\(shell\)/)assert.match(reader, /priority >= 3 \? "high" : priority >= 1 \? "auto" : "low"/)assert.match(reader, /const waiter = \{\s*shell,\s*priority,/)assert.match(reader, /waiter\.shell \? pdfPagePriority\(waiter\.shell\) : waiter\.priority/)assert.match(reader, /function cancelSpeculativePdfRenders\(protectedShell\)/)assert.match(reader, /isPdfPageVisible\(shell\)/)assert.match(reader, /shell\._renderCancel\?\.\(\)/)assert.match(reader, /const PDF_MANIFEST_PREFETCH_LIMIT = 12/)assert.match(reader, /const PDF_MANIFEST_PREFETCH_CONCURRENCY = 3/)
144 unmodified lines145146147148149150151144 unmodified linessend('pointerdown', action==='secondary'?{isPrimary:false}:{});if (action==='drag') send('pointermove',{clientX:120});if (action==='cancel') send('pointercancel');if (action==='changed') selection.setBaseAndExtent(node.firstChild,0,node.firstChild,3);send('pointerup');output.push(!!selection.toString());}144 unmodified lines145146147148149150151152153154144 unmodified linessend('pointerdown', action==='secondary'?{isPrimary:false}:{});if (action==='drag') send('pointermove',{clientX:120});if (action==='cancel') send('pointercancel');if (action==='changed') {const text = node.ownerDocument.createTreeWalker(node, NodeFilter.SHOW_TEXT).nextNode();selection.setBaseAndExtent(text, 0, text, Math.min(3, text.data.length));}send('pointerup');output.push(!!selection.toString());}
1234567891011121314151617181920import assert from 'node:assert/strict';import fs from 'node:fs';import vm from 'node:vm';
const source=fs.readFileSync(new URL('../static/reader-pdf-book-search-worker.mjs',import.meta.url),'utf8');const start=source.indexOf('async function readBounded('), end=source.indexOf('\nasync function loadBook()',start);const read=vm.runInNewContext('const limit=1024; const aborted=()=>new DOMException("cancelled","AbortError");'+ source.slice(start,end)+';readBounded',{TextDecoder,Uint8Array,DOMException});const stream=chunks=>new ReadableStream({start(controller){for(const chunk of chunks)controller.enqueue(chunk);controller.close();}});const signal=new AbortController().signal;const text='手机 😀 كتاب';const bytes=new TextEncoder().encode(text);assert.equal(await read(stream([...bytes].map(byte=>Uint8Array.of(byte))),signal,null,true),text);assert.deepEqual(Array.from(await read(stream([bytes.subarray(0,3),bytes.subarray(3)]),signal,bytes.length)),Array.from(bytes));await assert.rejects(()=>read(stream([bytes.subarray(0,3)]),signal,bytes.length),/SIZE_MISMATCH/);await assert.rejects(()=>read(stream([bytes]),signal,3),/RESOURCE_LIMIT/);await assert.rejects(()=>read(stream([new Uint8Array(1025)]),signal,null,true),/RESOURCE_LIMIT/);const controller=new AbortController();controller.abort();await assert.rejects(()=>read(stream([bytes]),controller.signal,null,true),error=>error.name==='AbortError');console.log('OCR transport byte bounds, split Unicode and cancellation passed');30 unmodified lines31323334353651 unmodified lines88899091929314 unmodified lines1081091101111121131141151161172 unmodified lines12012112212312412530 unmodified lines15615715815916016130 unmodified lineschapterManifestCleanup = () => {''')route.fulfill(response=response, body=script + '''window.__snapshot = () => fullSearchDomSnapshot;window.__pdfTools = {trim: trimPdfSurfaces, pixels: pdfRetainedPixels, budget: pdfPixelBudget,prefetch: pdfManifestPrefetches, setPage: page => updateDocumentState({page})};window.__startPdfProbe = () => {51 unmodified lines__pdfTools.setPage(1);for (let page=1; page<=8; page++) {const shell=document.createElement('div'); shell.className='reader-page';shell.dataset.page=page; shell.dataset.renderState='rendered';const canvas=document.createElement('canvas'); canvas.className='ready';canvas.width=2400; canvas.height=3400;14 unmodified linesprefetched.src='data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==';__pdfTools.prefetch.set('fixture', {image:prefetched, url:'fixture'});__pdfTools.trim(root.firstChild);const protectedSelection=selected.querySelector('canvas').width===2400 && getSelection().getRangeAt(0).toString()==='page 2';const prefetchedReleased=!prefetched.hasAttribute('src') && __pdfTools.prefetch.size===0;getSelection().removeAllRanges(); __pdfTools.trim(root.firstChild);return {protectedSelection,prefetchedReleased,pixels:__pdfTools.pixels(),budget:__pdfTools.budget(),retained:root.firstChild.querySelector('canvas').width,released:[...root.children].filter(shell=>!shell.querySelector('canvas.ready, img')).length};}''')2 unmodified linesself.assertEqual(result['retained'], 2400)self.assertGreaterEqual(result['released'], 5)def test_pdf_parallel_search_reserves_demand_slot_and_cancels_stale_totals(self):self.expose()self.serve('search scheduling fixture')30 unmodified linesself.open(self.docx_url())pages = self.page.locator('.reader-docx-page')self.assertEqual(pages.count(), 20)self.assertEqual(pages.last.evaluate('e => getComputedStyle(e).contentVisibility'), 'auto')self.page.evaluate('() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))')self.assertFalse(pages.last.evaluate('e => e.firstElementChild.checkVisibility({contentVisibilityAuto:true})'))30 unmodified lines3132333435363751 unmodified lines8990919293949514 unmodified lines1101111121131141151161171181191202 unmodified lines12312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816930 unmodified lines20020120220320420520620720820921030 unmodified lineschapterManifestCleanup = () => {''')route.fulfill(response=response, body=script + '''window.__snapshot = () => fullSearchDomSnapshot;window.__markerPage = () => pageAtMarker()?.dataset.page;window.__pdfTools = {trim: trimPdfSurfaces, pixels: pdfRetainedPixels, budget: pdfPixelBudget,prefetch: pdfManifestPrefetches, setPage: page => updateDocumentState({page})};window.__startPdfProbe = () => {51 unmodified lines__pdfTools.setPage(1);for (let page=1; page<=8; page++) {const shell=document.createElement('div'); shell.className='reader-page';shell.style.height='1200px';shell.dataset.page=page; shell.dataset.renderState='rendered';const canvas=document.createElement('canvas'); canvas.className='ready';canvas.width=2400; canvas.height=3400;14 unmodified linesprefetched.src='data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==';__pdfTools.prefetch.set('fixture', {image:prefetched, url:'fixture'});__pdfTools.trim(root.firstChild);const nearestRetained=!!root.children[2].querySelector('canvas.ready');const protectedSelection=selected.querySelector('canvas').width===2400 && getSelection().getRangeAt(0).toString()==='page 2';const prefetchedReleased=!prefetched.hasAttribute('src') && __pdfTools.prefetch.size===0;getSelection().removeAllRanges(); __pdfTools.trim(root.firstChild);return {protectedSelection,prefetchedReleased,nearestRetained,pixels:__pdfTools.pixels(),budget:__pdfTools.budget(),retained:root.firstChild.querySelector('canvas').width,released:[...root.children].filter(shell=>!shell.querySelector('canvas.ready, img')).length};}''')2 unmodified linesself.assertEqual(result['retained'], 2400)self.assertGreaterEqual(result['released'], 5)def test_mobile_large_page_pdf_keeps_nearby_canvases_at_display_resolution(self):self.context.close()self.context = self.browser.new_context(viewport=dict(width=390,height=844),device_scale_factor=3)self.page = self.context.new_page()self.page.add_init_script("Object.defineProperty(navigator,'deviceMemory',{value:2});window.__renderedPages=[];")engine = '''export const GlobalWorkerOptions={};export class PDFWorker {promise=Promise.resolve();destroy(){}}export function getDocument(){return {promise:Promise.resolve({numPages:40,getOutline:async()=>null,getPage:async number=>({getViewport:({scale})=>({width:1274*scale,height:1828*scale}),getTextContent:async()=>({items:[],styles:{}}),render:({canvasContext})=>{__renderedPages.push(number);canvasContext.fillStyle='white';canvasContext.fillRect(0,0,4000,6000);return {promise:Promise.resolve(),cancel(){}};}})}),destroy(){}};}'''self.page.route('**/static/vendor/pdf.min.*.mjs',lambda route:route.fulfill(content_type='text/javascript',body=engine))self.serve(b'pdf','application/pdf')self.open(self.reader_url('pdf'))self.page.wait_for_function('() => !!document.querySelector(".reader-page[data-page=\\"4\\"] canvas.ready")')self.page.wait_for_timeout(150)data = self.page.locator('.reader-page[data-page="1"]').evaluate('''shell=>{const canvas=shell.querySelector('canvas');return {css:shell.clientWidth,backing:canvas.width,next:[2,3,4].map(page=>!!document.querySelector('.reader-page[data-page="'+page+'"] canvas.ready'))};}''')self.assertLessEqual(data['backing'],data['css']*2+1,data)self.assertTrue(all(data['next']),data)self.page.evaluate('''()=>{const shell=document.querySelector('.reader-page[data-page="3"]'),v=document.querySelector('#viewport');window.__thirdCount=__renderedPages.filter(page=>page===3).length;v.scrollTop+=shell.getBoundingClientRect().top-v.getBoundingClientRect().top;}''')self.page.wait_for_timeout(150)self.assertEqual(self.page.evaluate('__renderedPages.filter(page=>page===3).length'),self.page.evaluate('__thirdCount'))def test_long_txt_blocks_preserve_exact_text_cross_block_hits_and_selection(self):self.expose()text=('ordinary line\n'*2400)+'needle\n'+('tail line\n'*6000)+'needle\n'self.serve(text)self.open(self.reader_url('txt'))self.assertEqual(self.page.locator('.reader-text').text_content(),text)self.assertGreater(self.page.locator('.reader-text-block').count(),2)self.assertEqual(self.page.evaluate('__query("needle")'),2)self.search('needle')self.page.locator('.full-search-result').last.click()self.assertEqual(self.page.locator('mark.full-search-highlight').text_content(),'needle')self.assertEqual(self.page.locator('.reader-text').text_content(),text)self.assertEqual(self.page.locator('.reader-text').evaluate('''root=>{const range=document.createRange();range.selectNodeContents(root);getSelection().removeAllRanges();getSelection().addRange(range);return range.toString();}'''),text)def test_pdf_parallel_search_reserves_demand_slot_and_cancels_stale_totals(self):self.expose()self.serve('search scheduling fixture')30 unmodified linesself.open(self.docx_url())pages = self.page.locator('.reader-docx-page')self.assertEqual(pages.count(), 20)marker = self.page.evaluate('''()=>{let reads=0;const pages=[...document.querySelectorAll('.reader-docx-page')];for(const page of pages){const native=page.getBoundingClientRect.bind(page);page.getBoundingClientRect=()=>{reads++;return native();};}const actual=__markerPage();return {actual,reads};}''')self.assertEqual(marker['actual'],'1')self.assertLessEqual(marker['reads'],6)self.assertEqual(pages.last.evaluate('e => getComputedStyle(e).contentVisibility'), 'auto')self.page.evaluate('() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))')self.assertFalse(pages.last.evaluate('e => e.firstElementChild.checkVisibility({contentVisibilityAuto:true})'))
1120 unmodified lines11211122112311241125112611271120 unmodified linesdef test_stale_foliate_fallback_cannot_highlight_after_navigation(self):def hold_fallback(route):response = route.fetch()needle = "const nodes = cached ? [] : await fullSearchTextNodes(root, generation);"script = response.text()self.assertIn(needle, script)script = script.replace(needle, """if (occurrence !== null && !window.__fallbackHeld) {1120 unmodified lines11211122112311241125112611271120 unmodified linesdef test_stale_foliate_fallback_cannot_highlight_after_navigation(self):def hold_fallback(route):response = route.fetch()needle = "const nodes = cached ? [] : await fullSearchTextNodes(root, generation, Infinity, null, collect);"script = response.text()self.assertIn(needle, script)script = script.replace(needle, """if (occurrence !== null && !window.__fallbackHeld) {
static/reader-pdf-book-search-worker.mjs+16-7
static/reader.css+11
static/reader.js+67-45
tests/test_reader_architecture.js+2-2
tests/test_reader_close_traffic.py+4-1
tests/test_reader_ocr_transport.mjsAdded+20
tests/test_reader_optimizations.py+50-1
tests/test_reader_refactor.py+1-1