vomebook commited on
Commit ·
551ecc9
1
Parent(s): 685b545
Enforce frontend unused checks and streamline chapter navigation
Browse filesFiles changed (43)
- config/types/jsconfig.chapter-worker-strict.json+2
- config/types/jsconfig.service-worker-strict.json+2
- config/types/jsconfig.strict.json+3
- scripts/check_strict_inventory.py+11-6
- static/app.js+10-66
- static/reader/core/reader-security.js-1
- static/reader/core/reader-source.mjs+2-2
- static/reader/formats/reader-chapter-format.mjs+35-8
- static/reader/pdf/reader-pdf-engine.mjs+6-7
- static/reader/pdf/reader-pdf-range-hints.mjs+3-3
- static/reader/pdf/reader-pdf-renderer.mjs+3-4
- static/reader/search/reader-dom-search.mjs+3-3
- static/reader/search/reader-pdf-book-validate.mjs+2-1
- static/reader/search/reader-pdf-hit-projection.mjs+2-1
- static/reader/ui/reader-speech.mjs+3-4
- static/search/results/virtual/application/controller.js-1
- static/search/results/window/domain/page.js+1-4
- tests/gates/test_quality_inventory.py+26-14
- tests/gates/test_static_checks.py+13
- tests/gates/test_static_contract.py+3-2
- tests/reader/browser/test_reader_host_history_races.py+8-3
- tests/reader/browser/test_reader_navigation_host.py+6-6
- tests/reader/browser/test_reader_pdf_first_page.py+2-2
- tests/reader/browser/test_reader_refactor.py+1-1
- tests/reader/chapters/test_chapter_format_validation.mjs+92
- tests/reader/core/test_reader_warming.js+14-14
- tests/search/baselines/test_sidebar_markup_baseline.mjs+13-17
- tests/search/browser/test_browser.py+8-8
- tests/search/browser/test_download_lifecycle.py+8-8
- tests/search/browser/test_initial_intent_reader_routes.py+10-10
- tests/search/browser/test_paging_recovery.py+9-9
- tests/search/browser/test_position_window.py+1-1
- tests/search/browser/test_prefetch_pipeline.py+5-4
- tests/search/browser/test_scroll_stability.py+7-3
- tests/search/browser/test_search_accessibility_browser.py+14-13
- tests/search/browser/test_search_positions.py+6-6
- tests/search/browser/test_sidebar_keyboard.py+13-13
- tests/search/reader-navigation/test_search_history_races.mjs+6-5
- tests/search/ui/history_quotation_contracts.mjs+12-12
- tests/search/ui/shell_contracts.mjs+3-3
- tests/search/ui/virtual_results_contracts.mjs+2-1
- typings/reader-chapter-format-strict.d.ts+1-1
- typings/reader-pdf-engine-strict.d.ts+2-2
8 unmodified lines910111213148 unmodified lines"noImplicitOverride": true,"noImplicitReturns": true,"noFallthroughCasesInSwitch": true,"target": "esnext","lib": ["esnext",8 unmodified lines9101112131415168 unmodified lines"noImplicitOverride": true,"noImplicitReturns": true,"noFallthroughCasesInSwitch": true,"noUnusedLocals": true,"noUnusedParameters": true,"target": "esnext","lib": ["esnext",
6 unmodified lines7891011126 unmodified lines"noImplicitOverride": true,"noImplicitReturns": true,"noFallthroughCasesInSwitch": true,"noUncheckedIndexedAccess": true,"exactOptionalPropertyTypes": true,"skipLibCheck": true,6 unmodified lines78910111213146 unmodified lines"noImplicitOverride": true,"noImplicitReturns": true,"noFallthroughCasesInSwitch": true,"noUnusedLocals": true,"noUnusedParameters": true,"noUncheckedIndexedAccess": true,"exactOptionalPropertyTypes": true,"skipLibCheck": true,
7 unmodified lines8910111213141516177 unmodified lines"noImplicitOverride": true,"noImplicitReturns": true,"noFallthroughCasesInSwitch": true,"exactOptionalPropertyTypes": true,"target": "esnext","module": "esnext","moduleResolution": "bundler","paths": {"/static/*": ["../../static/*"],"/search/static/*": ["../../static/*"]7 unmodified lines8910111213141516171819207 unmodified lines"noImplicitOverride": true,"noImplicitReturns": true,"noFallthroughCasesInSwitch": true,"noUnusedLocals": true,"noUnusedParameters": true,"exactOptionalPropertyTypes": true,"target": "esnext","module": "esnext","moduleResolution": "bundler","moduleDetection": "force","paths": {"/static/*": ["../../static/*"],"/search/static/*": ["../../static/*"]
21 unmodified lines2223242526272843 unmodified lines7273747576777879807 unmodified lines88899091929394959697989929 unmodified lines12913013113213313413513613713813914014114221 unmodified lines)REQUIRED_FRONTEND_FLAGS = ("noUncheckedIndexedAccess", "exactOptionalPropertyTypes", "noImplicitOverride","noImplicitReturns", "noFallthroughCasesInSwitch",)43 unmodified linesdef compiler_files(root: Path, config: str, *, strict: bool = False) -> set[str]:if config not in ("config/types/jsconfig.check.json", "config/types/jsconfig.service-worker.json","config/types/jsconfig.service-worker-strict.json", "config/types/jsconfig.chapter-worker-strict.json","config/types/jsconfig.strict.json"):raise ValueError("unknown TypeScript configuration")node = shutil.which("node")if node is None:7 unmodified linesif resolved.returncode:raise RuntimeError(f"{config}: {resolved.stdout}")options = json.loads(resolved.stdout).get("compilerOptions", {})for option in ("strictNullChecks", "noImplicitAny"):if options.get(option, options.get("strict", False)) is not True:raise RuntimeError(f"{config}: effective {option} must be enabled")for flag in REQUIRED_FRONTEND_FLAGS:if options.get(flag) is not True:raise RuntimeError(f"{config}: effective {flag} must be enabled")result = subprocess.run([node, str(compiler), "--project", config, "--listFilesOnly"], # noqa: S603cwd=root, text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=60)if result.returncode:29 unmodified linesbrowser = browser_sources(ROOT)errors = inventory_errors(ROOT, strict, basic, py_strict, debt, previous)for path in sorted((browser - strict) & set(debt.get("browser_js", []))):errors.append(f"browser source must be checked with all five frontend flags: {path}")if errors:print("\n".join(errors), file=sys.stderr)return 1python_sources = backend_sources(ROOT) | {"app.py"}print(f"Strict inventory: JS {len(browser & strict)}/{len(browser)}; "f"backend and entry {len(python_sources & py_strict)}/{len(python_sources)}; ""no new ungated files; all five frontend flags enforced")return 021 unmodified lines2223242526272843 unmodified lines72737475767778797 unmodified lines8788899091929394959697989910010110210310429 unmodified lines13413513613713813914014114214314414514614721 unmodified lines)REQUIRED_FRONTEND_FLAGS = ("noUncheckedIndexedAccess", "exactOptionalPropertyTypes", "noImplicitOverride","noImplicitReturns", "noFallthroughCasesInSwitch", "noUnusedLocals", "noUnusedParameters",)43 unmodified linesdef compiler_files(root: Path, config: str, *, strict: bool = False) -> set[str]:if config not in (*STRICT_FRONTEND_PROJECTS, "config/types/jsconfig.check.json","config/types/jsconfig.service-worker.json"):raise ValueError("unknown TypeScript configuration")node = shutil.which("node")if node is None:7 unmodified linesif resolved.returncode:raise RuntimeError(f"{config}: {resolved.stdout}")options = json.loads(resolved.stdout).get("compilerOptions", {})if (not all(options.get(key) is True for key in ("allowJs", "checkJs", "noEmit"))or options.get("noCheck", False) is not False):raise RuntimeError(f"{config}: strict JavaScript checking must remain enabled")for option in ("strictNullChecks", "noImplicitAny"):if options.get(option, options.get("strict", False)) is not True:raise RuntimeError(f"{config}: effective {option} must be enabled")for flag in REQUIRED_FRONTEND_FLAGS:if options.get(flag) is not True:raise RuntimeError(f"{config}: effective {flag} must be enabled")# Check top-level bindings even in browser classic scripts; this graph never emits.if options.get("moduleDetection") != "force":raise RuntimeError(f"{config}: effective moduleDetection must be force for top-level unused checking")result = subprocess.run([node, str(compiler), "--project", config, "--listFilesOnly"], # noqa: S603cwd=root, text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=60)if result.returncode:29 unmodified linesbrowser = browser_sources(ROOT)errors = inventory_errors(ROOT, strict, basic, py_strict, debt, previous)for path in sorted((browser - strict) & set(debt.get("browser_js", []))):errors.append(f"browser source must be checked with all seven frontend flags: {path}")if errors:print("\n".join(errors), file=sys.stderr)return 1python_sources = backend_sources(ROOT) | {"app.py"}print(f"Strict inventory: JS {len(browser & strict)}/{len(browser)}; "f"backend and entry {len(python_sources & py_strict)}/{len(python_sources)}; ""no new ungated files; all seven frontend flags enforced")return 0
96 unmodified lines9798991001011021031041051061073 unmodified lines11111211311411511614 unmodified lines1311321331341351361371381399 unmodified lines14915015115215315415515613 unmodified lines17017117217317417517619 unmodified lines19619719819920020120229 unmodified lines232233234235236237238631 unmodified lines870871872873874875876877878298 unmodified lines11771178117911801181118211831184118511861187154 unmodified lines13421343134413451346134713481349195 unmodified lines15451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567199 unmodified lines176717681769177017711772177394 unmodified lines186818691870187118721873187440 unmodified lines191519161917191819191920192120 unmodified lines1942194319441945194619471948106 unmodified lines2055205620572058205920602061320 unmodified lines2382238323842385238623872388238923902391239223932394239521 unmodified lines241724182419242024212422242324242425242624275 unmodified lines24332434243524362437243824392440244124422443244424452446244724482449245024512452245352 unmodified lines250625072508250925102511251296 unmodified lines26092610261126122613261426152616156 unmodified lines2773277427752776277727782779442 unmodified lines322232233224322532263227322832293230323132323233323432353236355 unmodified lines3592359335943595359635973598359996 unmodified lines_deferredAppendWhileDragging: false,};const {openSearchSessionDB,persistSearchSession,restoreSearchSession,} = VoiceOfMLSearchSession.createSearchSession({canPersist: () => !location.pathname.startsWith("/static/reader.html"),canRestore: target => {if (initialSearchDraft) return false;3 unmodified lines&& target.pathname !== "/static/reader.html";},});/** @type {AbortController | null} */let searchAbortController = null;/** @type {VoiceOfMLSearchPrefetchGroup | null} */14 unmodified lineslet scrollLoadTimer = null;/** @type {ReturnType<typeof setTimeout> | null} */let scrollRecoveryTimer = null;// Readable host compatibility bridge; only the input controller writes these.let searchComposing = false;let searchInputReady = false;let initialSearchDraft = false;/** @type {VoiceOfMLInputController} */let searchInputController;9 unmodified linesgetSearchViewKey: () => getSearchViewKey(),rememberSearchPageMetadata: data => rememberSearchPageMetadata(data),});// Retain direct cache diagnostics for browser checks.const searchResponseCache = searchResponseStore.cache;/** @type {BoundedResponseCache<{data: SearchInitialPayload, time: number}>} */const initialPayloadCache = new BoundedResponseCache(16, SEARCH_CACHE_TTL);const embeddedInitialAcquiredAt = Date.now();13 unmodified lines}const SEARCH_REQUEST_TIMEOUT = 25000;const APPEND_REQUEST_TIMEOUT = 5000;const pendingSearchPages = getSearchTransport().pending;// Detached compatibility projection for browser diagnostics; the controller owns recovery.let pagingFailures = 0;const DOWNLOAD_CHECK_TIMEOUT = 8000;19 unmodified linessubmitSearchQuery: (query, options) => submitSearchQuery(query, options)}));}function getHistory() { return searchHistoryStore.get(); }/** @param {string[]} list */function saveHistory(list) { searchHistoryStore.save(list); }29 unmodified lines}const SEARCH_VIEW_SNAPSHOT_VERSION = VoiceOfMLSnapshotPolicy.VERSION;const SEARCH_VIEW_SNAPSHOT_BYTES_MAX = VoiceOfMLSnapshotPolicy.BYTES_MAX;const resultSnapshots = VoiceOfMLResultSnapshots.create({cloneResult: record => cloneSearchResult(record),measurementKey: () => getHeightMeasurementKey(),631 unmodified linesreturn fetchSearchPage(url + "|" + stableSearchStringify(body), url, body, signal, SEARCH_REQUEST_TIMEOUT);}function trimSearchViewSnapshots() {resultSnapshots.trim();}/** @type {VoiceOfMLSearchViewMemo | null} */let searchViewKeyMemo = null;298 unmodified lines});}/** @param {string} cacheKey @param {string} url @param {VoiceOfMLSearchRequestBody} body @param {number} timeoutMs */function createSearchPageRequest(cacheKey, url, body, timeoutMs) {return getSearchTransport().createRequest(cacheKey, url, body, timeoutMs);}/** @param {string} cacheKey @param {string} url @param {VoiceOfMLSearchRequestBody} body @param {AbortSignal | null | undefined} signal @param {number} timeoutMs */function fetchSearchPage(cacheKey, url, body, signal, timeoutMs) {return getSearchTransport().fetchPage(cacheKey, url, body, signal, timeoutMs);154 unmodified linesfunction renderDropdown() { getSearchHistoryController().renderDropdown(); }function hideSearchHistory(restoreFocus = false) { getSearchHistoryController().hideSearchHistory(restoreFocus); }function setupSearchHistory() { getSearchHistoryController().setupSearchHistory(); }/** @param {string} q */function removeHistoryItem(q) { getSearchHistoryController().removeHistoryItem(q); }/** @type {Record<number, boolean>} */var selectedIndices = {};var lastSelectedIndex = -1;195 unmodified linesisBatchActive: downloadBatches.isActive,timeout: DOWNLOAD_CHECK_TIMEOUT,});const {downloadChecks,downloadCheckQueue,pendingDownloads,checkDownload,runDownloadCheck,pumpDownloadChecks,scheduleDownloadLaunch,downloadFile,} = downloadController;Object.defineProperty(globalThis, "activeDownloadChecks", {configurable: true,get: () => downloadController.activeDownloadChecks,});function renderDownloadBatch() { downloadBatches.render(); }function getSelectedFiles() {const files = Object.keys(selectedIndices).map(Number).flatMap(index => {if (resultSnapshots.cloneTask) materializeSnapshotRange(resultSnapshots.cloneTask, index, index + 1, true);199 unmodified linescloseOverlay: (focus, scroll) => closeReaderOverlay(focus, scroll), reconcile: () => reconcileSearchDestination()});const readerNavigation = readerHost.navigation;const READER_RETURN_SEARCH_KEYS = readerHost.keys;// Read-only compatibility projections for existing browser diagnostics.Object.defineProperties(window, {readerOverlay: { get: () => readerHost.overlay },94 unmodified lines// Match reader-resolve's metadata freshness without imposing a lifetime quota.const READER_WARMUP_TTL = 5 * 60 * 1000;const READER_WARMUP_MAX = 8;let readerWarmupInFlight = 0;/** @type {{key: string, cancel(superseded?: boolean): void} | null} */let readerWarmupPending = null;/** @type {Map<string, number>} */40 unmodified linesif (readerWarmupPending !== task) return;clearTimeout(timer);readerWarmupPending = null;readerWarmupInFlight = 0;if (success) {let metadataStored = false;if (readerId) {20 unmodified lines}};readerWarmupPending = task;readerWarmupInFlight = 1;const timer = setTimeout(() => task.cancel(), 8000);(async () => {try {106 unmodified linesfetchJSON: (url, timeout) => fetchJsonWithTimeout(url, timeout),getBootstrap: () => API.getBootstrap(),});const { sidebarInitialCache, sidebarInitialPending } = catalog;/** @type {VoiceOfMLSearchAppApi} */const API = {320 unmodified linesrenderRepos: repos => renderRepoListItems(repos), updateHeader: () => {},initial: repo => loadSidebarInitial(repo), fetchRepos: () => API.getRepos(),fetchContents: (repo, path) => API.getContents(repo, path).then(data => data ?? null),localContents: (repo, path) => Promise.resolve(null), ensureLocal: (force, silent) => Promise.resolve(false),cachedContents: key => API._browserCache?.get(key), publishRepos: repos => { STATE.repoList = repos || []; },refreshAssets: refreshSidebarReaderAssets,}));}/** @param {HTMLElement} list @param {string} currentRepo @param {string} path @param {number | undefined} routeId @param {() => VoiceOfMLSidebarEntries | null} readDisplayed @param {() => boolean} isCurrent */function refreshSidebarReaderAssets(list, currentRepo, path, routeId, readDisplayed, isCurrent) {// Directory navigation remains usable while optional converted assets load.const initialAssets = readerAssetController.state.assets;loadReaderAssets().then(() => {21 unmodified linesreturn getSidebarDirectoryView().repos(repos);}/** @param {number} [routeId] */function renderRepoList(routeId) {return getSidebarDirectory().repos(routeId);}/** @param {VoiceOfMLSidebarFile & {link?: string}} f @param {string} currentRepo @param {string} path */function getBrowserFileReadUrl(f, currentRepo, path) {const displayName = getBrowserFileName(f);5 unmodified linesreturn isReadableRecord(record) ? VoiceOfMLReader.readerUrl(record, "/static/reader.html") : "";}/** @param {HTMLElement} list @param {VoiceOfMLSidebarEntries} data @param {string} currentRepo @param {string} path */function renderBrowserListItems(list, data, currentRepo, path) {return getSidebarDirectoryView().items(list, data, currentRepo, path);}/** @param {string} path @param {number} [routeId] */function renderBrowser(path, routeId) {return getSidebarDirectory().browse(path, routeId);}/** @param {string} path */function createSidebarBreadcrumb(path) {return getSidebarDirectoryView().breadcrumb(path);}/** @param {string} query @param {{restore?: boolean, record?: boolean, refreshHistory?: boolean, clearResults?: boolean, blur?: boolean, updateInput?: boolean}} [options] */function submitSearchQuery(query, { restore = false, record = false, refreshHistory = false, clearResults = false, blur = false, updateInput = restore } = {}) {if (Array.from(query).length > 256) {52 unmodified linesonState: state => {searchTimer = state.timer;searchComposing = state.composing;searchInputReady = state.ready;initialSearchDraft = state.dirty;}});96 unmodified lines});return resultRows;}/** @param {VoiceOfMLResultRecord} rec @param {number} idx */function buildResultHTML(rec, idx) { return getResultRows().buildHTML(rec, idx); }/** @type {ReaderAssetMap | null} */let refreshedReaderAssets = null;156 unmodified linesfunction ensureVirtualHeights(len) { return getVirtualResults().ensureVirtualHeights(len); }function refreshVirtualAfterAppend(updateView = true) { return getVirtualResults().refreshVirtualAfterAppend(updateView); }function ensureVirtualViewportCovered() { return getVirtualResults().ensureVirtualViewportCovered(); }function measureHeights(start = VSCROLL.renderStart, end = VSCROLL.renderEnd, anchor = null) { return getVirtualResults().measureHeights(start, end, anchor); }function prepareRouteTransitionResults() {saveSearchViewSnapshot();442 unmodified lines/** @param {number} routeId */function retainFilterRenderingForRoute(routeId) { return getSidebarFilters().retain(routeId); }/** @param {number} [routeId] */function renderRepoFilter(routeId) { return getSidebarFilters().renderRepos(routeId); }/** @param {number} [routeId] */function renderExtensionFilter(routeId) { return getSidebarFilters().renderExtensions(routeId); }function getSidebarFolderTree() {getSidebarFilters();if (!sidebarFolderTree) throw new Error("Sidebar folder tree was not initialized");return sidebarFolderTree;}function renderFilterFolderTree() { getSidebarFolderTree().render(); }function refreshFilterFolderSelectionState() { getSidebarFolderTree().refresh(); }/** @param {boolean} collapsed */function setAllFoldersCollapsed(collapsed) { getSidebarFolderTree().setAllCollapsed(collapsed); }355 unmodified linesfunction toggleMobile() { getShell().toggleMobile(); }function applyMobileMode() { getShell().applyMobileMode(); }function autoDetectMobile() { return window.innerWidth <= 768; }/** @param {HTMLElement} sidebar */function focusSearchSidebar(sidebar) { VoiceOfMLShellView.focusSearchSidebar(sidebar); }/** @param {VoiceOfMLShellEvent} [event] */function toggleLeftSidebar(event) { getShell().toggleLeftSidebar(event); }/** @param {VoiceOfMLShellEvent} [event] */96 unmodified lines9798991001011021033 unmodified lines10710810911011111211314 unmodified lines1281291301311321331341359 unmodified lines14514614714814915013 unmodified lines16416516616716816919 unmodified lines18919019119219319429 unmodified lines224225226227228229631 unmodified lines861862863864865866298 unmodified lines116511661167116811691170154 unmodified lines132513261327132813291330195 unmodified lines152615271528152915301531153215331534153515361537199 unmodified lines17371738173917401741174294 unmodified lines18371838183918401841184240 unmodified lines18831884188518861887188820 unmodified lines190919101911191219131914106 unmodified lines202120222023202420252026320 unmodified lines2347234823492350235123522353235423552356235723582359236023612362236321 unmodified lines2385238623872388238923905 unmodified lines2396239723982399240024012402240324042405240652 unmodified lines24592460246124622463246496 unmodified lines256125622563256425652566156 unmodified lines272327242725272627272728442 unmodified lines317131723173317431753176317731783179318031813182355 unmodified lines35383539354035413542354396 unmodified lines_deferredAppendWhileDragging: false,};const searchSession = VoiceOfMLSearchSession.createSearchSession({canPersist: () => !location.pathname.startsWith("/static/reader.html"),canRestore: target => {if (initialSearchDraft) return false;3 unmodified lines&& target.pathname !== "/static/reader.html";},});const { persistSearchSession, restoreSearchSession } = searchSession;/** @type {AbortController | null} */let searchAbortController = null;/** @type {VoiceOfMLSearchPrefetchGroup | null} */14 unmodified lineslet scrollLoadTimer = null;/** @type {ReturnType<typeof setTimeout> | null} */let scrollRecoveryTimer = null;// Only the input controller writes these.let searchComposing = false;let initialSearchDraft = false;/** @type {VoiceOfMLInputController} */let searchInputController;9 unmodified linesgetSearchViewKey: () => getSearchViewKey(),rememberSearchPageMetadata: data => rememberSearchPageMetadata(data),});/** @type {BoundedResponseCache<{data: SearchInitialPayload, time: number}>} */const initialPayloadCache = new BoundedResponseCache(16, SEARCH_CACHE_TTL);const embeddedInitialAcquiredAt = Date.now();13 unmodified lines}const SEARCH_REQUEST_TIMEOUT = 25000;const APPEND_REQUEST_TIMEOUT = 5000;// Detached compatibility projection for browser diagnostics; the controller owns recovery.let pagingFailures = 0;const DOWNLOAD_CHECK_TIMEOUT = 8000;19 unmodified linessubmitSearchQuery: (query, options) => submitSearchQuery(query, options)}));}/** @param {string[]} list */function saveHistory(list) { searchHistoryStore.save(list); }29 unmodified lines}const SEARCH_VIEW_SNAPSHOT_VERSION = VoiceOfMLSnapshotPolicy.VERSION;const resultSnapshots = VoiceOfMLResultSnapshots.create({cloneResult: record => cloneSearchResult(record),measurementKey: () => getHeightMeasurementKey(),631 unmodified linesreturn fetchSearchPage(url + "|" + stableSearchStringify(body), url, body, signal, SEARCH_REQUEST_TIMEOUT);}/** @type {VoiceOfMLSearchViewMemo | null} */let searchViewKeyMemo = null;298 unmodified lines});}/** @param {string} cacheKey @param {string} url @param {VoiceOfMLSearchRequestBody} body @param {AbortSignal | null | undefined} signal @param {number} timeoutMs */function fetchSearchPage(cacheKey, url, body, signal, timeoutMs) {return getSearchTransport().fetchPage(cacheKey, url, body, signal, timeoutMs);154 unmodified linesfunction renderDropdown() { getSearchHistoryController().renderDropdown(); }function hideSearchHistory(restoreFocus = false) { getSearchHistoryController().hideSearchHistory(restoreFocus); }function setupSearchHistory() { getSearchHistoryController().setupSearchHistory(); }/** @type {Record<number, boolean>} */var selectedIndices = {};var lastSelectedIndex = -1;195 unmodified linesisBatchActive: downloadBatches.isActive,timeout: DOWNLOAD_CHECK_TIMEOUT,});const { checkDownload, downloadFile } = downloadController;Object.defineProperty(globalThis, "activeDownloadChecks", {configurable: true,get: () => downloadController.activeDownloadChecks,});function getSelectedFiles() {const files = Object.keys(selectedIndices).map(Number).flatMap(index => {if (resultSnapshots.cloneTask) materializeSnapshotRange(resultSnapshots.cloneTask, index, index + 1, true);199 unmodified linescloseOverlay: (focus, scroll) => closeReaderOverlay(focus, scroll), reconcile: () => reconcileSearchDestination()});const readerNavigation = readerHost.navigation;// Read-only compatibility projections for existing browser diagnostics.Object.defineProperties(window, {readerOverlay: { get: () => readerHost.overlay },94 unmodified lines// Match reader-resolve's metadata freshness without imposing a lifetime quota.const READER_WARMUP_TTL = 5 * 60 * 1000;const READER_WARMUP_MAX = 8;/** @type {{key: string, cancel(superseded?: boolean): void} | null} */let readerWarmupPending = null;/** @type {Map<string, number>} */40 unmodified linesif (readerWarmupPending !== task) return;clearTimeout(timer);readerWarmupPending = null;if (success) {let metadataStored = false;if (readerId) {20 unmodified lines}};readerWarmupPending = task;const timer = setTimeout(() => task.cancel(), 8000);(async () => {try {106 unmodified linesfetchJSON: (url, timeout) => fetchJsonWithTimeout(url, timeout),getBootstrap: () => API.getBootstrap(),});/** @type {VoiceOfMLSearchAppApi} */const API = {320 unmodified linesrenderRepos: repos => renderRepoListItems(repos), updateHeader: () => {},initial: repo => loadSidebarInitial(repo), fetchRepos: () => API.getRepos(),fetchContents: (repo, path) => API.getContents(repo, path).then(data => data ?? null),localContents: () => Promise.resolve(null), ensureLocal: () => Promise.resolve(false),cachedContents: key => API._browserCache?.get(key), publishRepos: repos => { STATE.repoList = repos || []; },refreshAssets: refreshSidebarReaderAssets,}));}/*** @param {[list: HTMLElement, repo: string, path: string, routeId: number | undefined,* readDisplayed: () => VoiceOfMLSidebarEntries | null, isCurrent: () => boolean]} args*/function refreshSidebarReaderAssets(...[list, currentRepo, path, , readDisplayed, isCurrent]) {// Directory navigation remains usable while optional converted assets load.const initialAssets = readerAssetController.state.assets;loadReaderAssets().then(() => {21 unmodified linesreturn getSidebarDirectoryView().repos(repos);}/** @param {VoiceOfMLSidebarFile & {link?: string}} f @param {string} currentRepo @param {string} path */function getBrowserFileReadUrl(f, currentRepo, path) {const displayName = getBrowserFileName(f);5 unmodified linesreturn isReadableRecord(record) ? VoiceOfMLReader.readerUrl(record, "/static/reader.html") : "";}/** @param {string} path @param {number} [routeId] */function renderBrowser(path, routeId) {return getSidebarDirectory().browse(path, routeId);}/** @param {string} query @param {{restore?: boolean, record?: boolean, refreshHistory?: boolean, clearResults?: boolean, blur?: boolean, updateInput?: boolean}} [options] */function submitSearchQuery(query, { restore = false, record = false, refreshHistory = false, clearResults = false, blur = false, updateInput = restore } = {}) {if (Array.from(query).length > 256) {52 unmodified linesonState: state => {searchTimer = state.timer;searchComposing = state.composing;initialSearchDraft = state.dirty;}});96 unmodified lines});return resultRows;}/** @type {ReaderAssetMap | null} */let refreshedReaderAssets = null;156 unmodified linesfunction ensureVirtualHeights(len) { return getVirtualResults().ensureVirtualHeights(len); }function refreshVirtualAfterAppend(updateView = true) { return getVirtualResults().refreshVirtualAfterAppend(updateView); }function ensureVirtualViewportCovered() { return getVirtualResults().ensureVirtualViewportCovered(); }function prepareRouteTransitionResults() {saveSearchViewSnapshot();442 unmodified lines/** @param {number} routeId */function retainFilterRenderingForRoute(routeId) { return getSidebarFilters().retain(routeId); }/** @param {number} [routeId] */function renderExtensionFilter(routeId) { return getSidebarFilters().renderExtensions(routeId); }function getSidebarFolderTree() {getSidebarFilters();if (!sidebarFolderTree) throw new Error("Sidebar folder tree was not initialized");return sidebarFolderTree;}function refreshFilterFolderSelectionState() { getSidebarFolderTree().refresh(); }/** @param {boolean} collapsed */function setAllFoldersCollapsed(collapsed) { getSidebarFolderTree().setAllCollapsed(collapsed); }355 unmodified linesfunction toggleMobile() { getShell().toggleMobile(); }function applyMobileMode() { getShell().applyMobileMode(); }function autoDetectMobile() { return window.innerWidth <= 768; }/** @param {VoiceOfMLShellEvent} [event] */function toggleLeftSidebar(event) { getShell().toggleLeftSidebar(event); }/** @param {VoiceOfMLShellEvent} [event] */
209 unmodified lines210211212213214215216209 unmodified linesreturn /** @type {import('../../../typings/reader-security-strict').ValidatedPdfPageManifest} */ (/** @type {unknown} */ (manifest));}const PDF_OCR_PATH = /^objects\/[0-9a-f]{2}\/[0-9a-f]{64}\/(?:[0-9a-f]{16}\/)?ocr\/(?:page-[0-9]{6}\.json\.gz|book-text\.json\.gz)$/;const PDF_OCR_MANIFEST_PATH = /^objects\/[0-9a-f]{2}\/[0-9a-f]{64}\/(?:[0-9a-f]{16}\/)?ocr-manifest\.json$/;const PDF_OCR_PAGE_PATH = /^objects\/[0-9a-f]{2}\/[0-9a-f]{64}\/(?:[0-9a-f]{16}\/)?pages\/page-[0-9]{6}\.(?:webp|jxl|png)$/;const PDF_OCR_ROOT = /^(objects\/[0-9a-f]{2}\/[0-9a-f]{64}(?:\/[0-9a-f]{16})?)/;/** @param {unknown} path */209 unmodified lines210211212213214215209 unmodified linesreturn /** @type {import('../../../typings/reader-security-strict').ValidatedPdfPageManifest} */ (/** @type {unknown} */ (manifest));}const PDF_OCR_PATH = /^objects\/[0-9a-f]{2}\/[0-9a-f]{64}\/(?:[0-9a-f]{16}\/)?ocr\/(?:page-[0-9]{6}\.json\.gz|book-text\.json\.gz)$/;const PDF_OCR_PAGE_PATH = /^objects\/[0-9a-f]{2}\/[0-9a-f]{64}\/(?:[0-9a-f]{16}\/)?pages\/page-[0-9]{6}\.(?:webp|jxl|png)$/;const PDF_OCR_ROOT = /^(objects\/[0-9a-f]{2}\/[0-9a-f]{64}(?:\/[0-9a-f]{16})?)/;/** @param {unknown} path */
341 unmodified lines342343344345346347348349341 unmodified lines}}/** @param {string} raw @param {string} base @param {string} attribute @param {string} manifestBase */function trustedChapterResourceUrl(raw, base, attribute, manifestBase) {const value = String(raw || "").trim();if (!value || /^(?:data:|mailto:|tel:|javascript:)/i.test(value)) return null;// Chapters and resources can be siblings within the manifest's asset directory.341 unmodified lines342343344345346347348349341 unmodified lines}}/** @param {string} raw @param {string} base @param {string} manifestBase */function trustedChapterResourceUrl(raw, base, manifestBase) {const value = String(raw || "").trim();if (!value || /^(?:data:|mailto:|tel:|javascript:)/i.test(value)) return null;// Chapters and resources can be siblings within the manifest's asset directory.
191 unmodified lines1921931941951961971981992 unmodified lines202203204205206207208209210211212155 unmodified lines368369370371372373374136 unmodified lines511512513514515516517518519224 unmodified lines744745746747748749750191 unmodified lines}}: null;/** @param {import("../../../typings/reader-chapter-format-strict").Chapter} chapter */const chapterUrl = (chapter) => readerContext.trustedChapterUrl(chapter.path, manifestBase);/** @param {number} index */const chapterAt = (index) => chapterByIndex.get(index) || null;/** @param {number} index @param {string} selector */2 unmodified linesif (Number(/** @type {HTMLElement} */ (node).dataset.chapter) > index) return node;return null;};/** @param {string} raw @param {string} base @param {string} attribute */const resourceUrl = (raw, base, attribute) => {const value = String(raw || "").trim();if (!value || value.startsWith("#")) return null;return readerContext.trustedChapterResourceUrl(value, base, attribute, manifestBase);};/** @param {HTMLElement} article */const insertChapter = (article) => {155 unmodified linesconst value = element.getAttribute(name) || "";if (name === "href" && element.localName === "a" &&readerContext.trustedChapterReferenceUrl(value, url, manifestBase)) continue;const resolved = resourceUrl(value, url, name === "href" ? "href" : "resource");if (resolved) element.setAttribute(name, resolved);else if (!(name === "href" && value.startsWith("#"))) element.removeAttribute(name);}136 unmodified linesreturn;const current = chapterAt(Number(article.dataset.chapter));const destination = readerContext.trustedChapterReferenceUrl(link.getAttribute("href"), chapterUrl(/** @type {import("../../../typings/reader-chapter-format-strict").Chapter} */ (current)), manifestBase);const target = destination ? new URL(destination.url) : null;const fragment = destination?.fragment || "";const chapter = target && manifest.chapters.find((item) => chapterUrl(item) === target.href);if (!chapter) {// A stale or missing book document must not navigate out to an asset 404.if (/\.(?:xhtml?|html?)(?:$|#)/i.test(link.getAttribute("href") || "")) {224 unmodified lineschapterWindowReady = true;if (readerContext.isReaderGenerationCurrent("navigation", openingGeneration)) readerContext.chapterScrollAnchors.invalidate();for (const article of frame.querySelectorAll(".reader-epub-chapter")) readerContext.chapterScrollAnchors.observe(article);frame.style.overflowAnchor = "none";scheduleChapterWindow();readerContext.assertReaderActive();readerContext.markReaderContentReady();191 unmodified lines1921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282 unmodified lines231232233234235236237238239240241155 unmodified lines397398399400401402403136 unmodified lines540541542543544545546547224 unmodified lines772773774775776777191 unmodified lines}}: null;/** @type {Map<string, string | null>} */const resolvedChapterUrls = new Map();/** @param {import("../../../typings/reader-chapter-format-strict").Chapter} chapter */const chapterUrl = (chapter) => {let url = resolvedChapterUrls.get(chapter.path);if (url === undefined) {url = readerContext.trustedChapterUrl(chapter.path, manifestBase);resolvedChapterUrls.set(chapter.path, url);}return url;};/** @type {Map<string, import("../../../typings/reader-chapter-format-strict").Chapter> | null} */let chaptersByUrl = null;let indexedChapterCount = 0;/** @param {string} href */const chapterAtUrl = (href) => {const byUrl = chaptersByUrl ??= new Map();const indexed = byUrl.get(href);if (indexed) return indexed;// Extend only on demand, in manifest order (not chapter load order),// so duplicate URLs still resolve to the first chapter.while (indexedChapterCount < manifest.chapters.length) {const chapter = /** @type {import("../../../typings/reader-chapter-format-strict").Chapter} */ (manifest.chapters[indexedChapterCount]);const url = chapterUrl(chapter);indexedChapterCount++;if (url === null || byUrl.has(url)) continue;byUrl.set(url, chapter);if (url === href) return chapter;}return null;};/** @param {number} index */const chapterAt = (index) => chapterByIndex.get(index) || null;/** @param {number} index @param {string} selector */2 unmodified linesif (Number(/** @type {HTMLElement} */ (node).dataset.chapter) > index) return node;return null;};/** @param {string} raw @param {string} base */const resourceUrl = (raw, base) => {const value = String(raw || "").trim();if (!value || value.startsWith("#")) return null;return readerContext.trustedChapterResourceUrl(value, base, manifestBase);};/** @param {HTMLElement} article */const insertChapter = (article) => {155 unmodified linesconst value = element.getAttribute(name) || "";if (name === "href" && element.localName === "a" &&readerContext.trustedChapterReferenceUrl(value, url, manifestBase)) continue;const resolved = resourceUrl(value, url);if (resolved) element.setAttribute(name, resolved);else if (!(name === "href" && value.startsWith("#"))) element.removeAttribute(name);}136 unmodified linesreturn;const current = chapterAt(Number(article.dataset.chapter));const destination = readerContext.trustedChapterReferenceUrl(link.getAttribute("href"), chapterUrl(/** @type {import("../../../typings/reader-chapter-format-strict").Chapter} */ (current)), manifestBase);const fragment = destination?.fragment || "";const chapter = destination && chapterAtUrl(new URL(destination.url).href);if (!chapter) {// A stale or missing book document must not navigate out to an asset 404.if (/\.(?:xhtml?|html?)(?:$|#)/i.test(link.getAttribute("href") || "")) {224 unmodified lineschapterWindowReady = true;if (readerContext.isReaderGenerationCurrent("navigation", openingGeneration)) readerContext.chapterScrollAnchors.invalidate();for (const article of frame.querySelectorAll(".reader-epub-chapter")) readerContext.chapterScrollAnchors.observe(article);scheduleChapterWindow();readerContext.assertReaderActive();readerContext.markReaderContentReady();
47 unmodified lines4849505152535428 unmodified lines83848586878889909192297 unmodified lines3903913923933943953963 unmodified lines40040140240340440540647 unmodified linescanPrefetchFirstPage: () => readerContext.capability?.mode === "pdf" &&readerContext.readerRestorationLoaded && !readerContext.restorationFailed &&(!readerContext.readerRestorationEntry || Number(readerContext.readerRestorationEntry.page) === 1),onError(error) {if (!documentReady || readerContext.readerAbortController.signal.aborted) return;if (readerContext.capability.mode !== "pdf") return;// Page retries cannot revive a destroyed PDF.js document. Capture an28 unmodified lines}));}/** @param {PdfModule} pdfjs @param {(url: string) => PdfOptions} options @param {string} originalUrl @param {string} proxyUrl @param {(url: string) => Initial} takeInitial */function loadPdfWithTimeout(pdfjs, options, originalUrl = readerContext.sourceUrl, proxyUrl = readerContext.contentUrl, takeInitial = (_url) => null) {// Keep a failed proxy on the proxied URL. Falling through to originalUrl// opens huggingface.co directly, which does not connect on this network.return readerContext.retryReaderProxy(() => readerContext.loadPdfTaskWithTimeout(pdfjs, options, proxyUrl, takeInitial(proxyUrl)));}297 unmodified linesstandardFontDataUrl: readerContext.PDFJS_STANDARD_FONT_URL,withCredentials: false});return readerContext.measurePdf(readerContext.loadPdfWithTimeout(pdfjs, options, target, proxyUrl, takeInitial), "document").catch(async error => {readerContext.assertReaderActive();if (!stagedWorker || (/** @type {{name?: string} | null | undefined} */ (error))?.name === "AbortError" || readerContext.retryableReaderProxyError(error) ||3 unmodified lines// original worker, not silently accept provisional page identities.readerContext.releasePdfWorker?.();await readerContext.preparePdfWorker(pdfjs);return readerContext.loadPdfWithTimeout(pdfjs, options, target, proxyUrl, takeInitial);});}).finally(() => {initial = null;47 unmodified lines4849505152535428 unmodified lines838485868788899091297 unmodified lines3893903913923933943953 unmodified lines39940040140240340440547 unmodified linescanPrefetchFirstPage: () => readerContext.capability?.mode === "pdf" &&readerContext.readerRestorationLoaded && !readerContext.restorationFailed &&(!readerContext.readerRestorationEntry || Number(readerContext.readerRestorationEntry.page) === 1),onError() {if (!documentReady || readerContext.readerAbortController.signal.aborted) return;if (readerContext.capability.mode !== "pdf") return;// Page retries cannot revive a destroyed PDF.js document. Capture an28 unmodified lines}));}/** @param {PdfModule} pdfjs @param {(url: string) => PdfOptions} options @param {string} proxyUrl @param {(url: string) => Initial} [takeInitial] */function loadPdfWithTimeout(pdfjs, options, proxyUrl, takeInitial = () => null) {// Retry the proxy URL only; never fall back to the original source URL.return readerContext.retryReaderProxy(() => readerContext.loadPdfTaskWithTimeout(pdfjs, options, proxyUrl, takeInitial(proxyUrl)));}297 unmodified linesstandardFontDataUrl: readerContext.PDFJS_STANDARD_FONT_URL,withCredentials: false});return readerContext.measurePdf(readerContext.loadPdfWithTimeout(pdfjs, options, proxyUrl, takeInitial), "document").catch(async error => {readerContext.assertReaderActive();if (!stagedWorker || (/** @type {{name?: string} | null | undefined} */ (error))?.name === "AbortError" || readerContext.retryableReaderProxyError(error) ||3 unmodified lines// original worker, not silently accept provisional page identities.readerContext.releasePdfWorker?.();await readerContext.preparePdfWorker(pdfjs);return readerContext.loadPdfWithTimeout(pdfjs, options, proxyUrl, takeInitial);});}).finally(() => {initial = null;
161 unmodified lines162163164165166167168169170171172161 unmodified lines// some edge cases rather than penalizing ordinary books.if (/** @type {number} */ (numbers[numbers.length - 1]) - /** @type {number} */ (numbers[0]) >= refs.length * 2) return PDF_ADAPTIVE_CHUNK_BYTES;}return chooseLargeFlatTreeChunkSize(bytes, total, fallback);}/** @param {Uint8Array} bytes @param {number} total @param {number} fallback */function chooseLargeFlatTreeChunkSize(bytes, total, fallback) {const head = new TextDecoder('latin1').decode(bytes.subarray(0, Math.min(bytes.length, PDF_LARGE_FLAT_HEADER_BYTES)));if (!head.startsWith('%PDF-') || /\/Linearized\b/.test(head.slice(0, 1024))) return fallback;// Walk only complete direct-length objects. Skip stream bytes exactly; this161 unmodified lines162163164165166167168169170171172161 unmodified lines// some edge cases rather than penalizing ordinary books.if (/** @type {number} */ (numbers[numbers.length - 1]) - /** @type {number} */ (numbers[0]) >= refs.length * 2) return PDF_ADAPTIVE_CHUNK_BYTES;}return chooseLargeFlatTreeChunkSize(bytes, fallback);}/** @param {Uint8Array} bytes @param {number} fallback */function chooseLargeFlatTreeChunkSize(bytes, fallback) {const head = new TextDecoder('latin1').decode(bytes.subarray(0, Math.min(bytes.length, PDF_LARGE_FLAT_HEADER_BYTES)));if (!head.startsWith('%PDF-') || /\/Linearized\b/.test(head.slice(0, 1024))) return fallback;// Walk only complete direct-length objects. Skip stream bytes exactly; this
197 unmodified lines19819920020120220320420584 unmodified lines290291292293294295296171 unmodified lines468469470471472473474197 unmodified lines}// Reveal ordinary image pages only after decoding; respect reduced motion./** @param {import('../../../typings/reader-pdf-renderer-strict').PdfShell} shell @param {HTMLElement} surface @param {boolean} fade */function revealPdfSurface(shell, surface, fade) {surface.classList.add("ready");if (fade && readerContext.capability?.mode === "image-pages")surface.animate?.([{ opacity: 0 }, { opacity: 1 }], { duration: 120, easing: "ease" });84 unmodified linesreaderContext.applyPdfShellGeometry(() => {shell.style.aspectRatio = `${image.naturalWidth || 1} / ${image.naturalHeight || 1}`;shell.dataset.pageGeometry = "1";revealPdfSurface(shell, image, fade);readerContext.seedPdfPageGeometry?.(image.naturalWidth, image.naturalHeight);});// A speculative page may become visible while its image is loading.171 unmodified linesrenderPdfImageShell,renderPdfShell,applyPdfShellGeometry,revealPdfSurface,pdfSurfaceFades};}197 unmodified lines19819920020120220320420584 unmodified lines290291292293294295296171 unmodified lines468469470471472473197 unmodified lines}// Reveal ordinary image pages only after decoding; respect reduced motion./** @param {HTMLElement} surface @param {boolean} fade */function revealPdfSurface(surface, fade) {surface.classList.add("ready");if (fade && readerContext.capability?.mode === "image-pages")surface.animate?.([{ opacity: 0 }, { opacity: 1 }], { duration: 120, easing: "ease" });84 unmodified linesreaderContext.applyPdfShellGeometry(() => {shell.style.aspectRatio = `${image.naturalWidth || 1} / ${image.naturalHeight || 1}`;shell.dataset.pageGeometry = "1";revealPdfSurface(image, fade);readerContext.seedPdfPageGeometry?.(image.naturalWidth, image.naturalHeight);});// A speculative page may become visible while its image is loading.171 unmodified linesrenderPdfImageShell,renderPdfShell,applyPdfShellGeometry,pdfSurfaceFades};}
345 unmodified lines346347348349350351352353106 unmodified lines460461462463464465466345 unmodified linesreturn { label: boundaries[low - 1]?.label };};}/** @param {Node} node @param {string} fallback @param {number} offset @param {number} total @param {DomSearch.HeadingLookup | null} [headingLookup] @param {HTMLElement | null} [parent] */function fullSearchLocation(node, fallback, offset, total, headingLookup = null, parent = node.parentElement) {const page = parent && parent.closest("[data-page]");if (page) return `第 ${/** @type {HTMLElement} */ (page).dataset.page} 页`;const indexed = headingLookup?.(offset);106 unmodified linesconst resultFor = (match) => {const part = offsets[locateIndex(match.index)];return {location: part ? fullSearchLocation(part.node || part.parent, fallback, match.index, text.length, headingLookup, part.parent) : fallback,snippet: fullSearchSnippet(text, match.index, match.value.length),async activate(navigationGeneration = runtime.currentGeneration("navigation")) {if (!isCurrent("navigation", navigationGeneration)) return false;345 unmodified lines346347348349350351352353106 unmodified lines460461462463464465466345 unmodified linesreturn { label: boundaries[low - 1]?.label };};}/** @param {Node} node @param {number} offset @param {number} total @param {DomSearch.HeadingLookup | null} [headingLookup] @param {HTMLElement | null} [parent] */function fullSearchLocation(node, offset, total, headingLookup = null, parent = node.parentElement) {const page = parent && parent.closest("[data-page]");if (page) return `第 ${/** @type {HTMLElement} */ (page).dataset.page} 页`;const indexed = headingLookup?.(offset);106 unmodified linesconst resultFor = (match) => {const part = offsets[locateIndex(match.index)];return {location: part ? fullSearchLocation(part.node || part.parent, match.index, text.length, headingLookup, part.parent) : fallback,snippet: fullSearchSnippet(text, match.index, match.value.length),async activate(navigationGeneration = runtime.currentGeneration("navigation")) {if (!isCurrent("navigation", navigationGeneration)) return false;
20 unmodified lines2122232425262720 unmodified lines/** @param {string} text */function codePointLength(text) {let length = 0;for (const point of text) length++;return length;}/** @param {unknown} value @returns {value is number[]} */20 unmodified lines212223242526272820 unmodified lines/** @param {string} text */function codePointLength(text) {let length = 0;const points = text[Symbol.iterator]();while (!points.next().done) length++;return length;}/** @param {unknown} value @returns {value is number[]} */
3 unmodified lines456789103 unmodified lines/** @param {string} text */export function codePointLength(text) {let length = 0;for (const point of text) length++;return length;}3 unmodified lines45678910113 unmodified lines/** @param {string} text */export function codePointLength(text) {let length = 0;const points = text[Symbol.iterator]();while (!points.next().done) length++;return length;}
45 unmodified lines46474849505152503 unmodified lines55655755855956056156256359 unmodified lines62362462562662762862945 unmodified lines// every offset) identical: a break not after sentence punctuation becomes a space./** @param {string} text */function spokenPageText(text) {return text.replace(/\n(?!\n)/g, (/** @type {string} */ match, /** @type {number} */ offset) => /[。!?!?;;::…”」』))\n]\s*$/u.test(text.slice(Math.max(0, offset - 2), offset)) ? "\n" : " ");}/** @param {Document} doc @param {number} x @param {number} y @param {ShadowRoot[]} roots */503 unmodified lines} };}/** @param {import('../../../typings/reader-speech-strict').SpeechSource} info */function needsProbe(info) {const current = mode();if (current === "epub-chapters") return false;if (current === "pdf-pages" && (readerContext.ocrManifestUrl || readerContext.pdfOcrManifest)) return false;59 unmodified linesif (!hasText()) return;const info = source();if (!info || info.units <= info.first) return;if (needsProbe(info)) { offerSource = info; offer(info); }else publish(createAdapter(info, info.units > 1 ? Math.max(info.first, (topPosition()?.unit ?? info.first) - 1) : info.first));/** @param {EventTarget | null | undefined} target @param {string} type @param {EventListener} handler @param {AddEventListenerOptions} [options] */const listen = (target, type, handler, options) => {45 unmodified lines46474849505152503 unmodified lines55655755855956056156259 unmodified lines62262362462562662762845 unmodified lines// every offset) identical: a break not after sentence punctuation becomes a space./** @param {string} text */function spokenPageText(text) {return text.replace(/\n(?!\n)/g, (/** @type {string} */ _match, /** @type {number} */ offset) => /[。!?!?;;::…”」』))\n]\s*$/u.test(text.slice(Math.max(0, offset - 2), offset)) ? "\n" : " ");}/** @param {Document} doc @param {number} x @param {number} y @param {ShadowRoot[]} roots */503 unmodified lines} };}function needsProbe() {const current = mode();if (current === "epub-chapters") return false;if (current === "pdf-pages" && (readerContext.ocrManifestUrl || readerContext.pdfOcrManifest)) return false;59 unmodified linesif (!hasText()) return;const info = source();if (!info || info.units <= info.first) return;if (needsProbe()) { offerSource = info; offer(info); }else publish(createAdapter(info, info.units > 1 ? Math.max(info.first, (topPosition()?.unit ?? info.first) - 1) : info.first));/** @param {EventTarget | null | undefined} target @param {string} type @param {EventListener} handler @param {AddEventListenerOptions} [options] */const listen = (target, type, handler, options) => {
209 unmodified lines210211212213214215216209 unmodified lines/** @param {number} [start] @param {number} [end] @param {{index: number, offset: number} | null} [anchor] */function measureHeights(start = VSCROLL.renderStart, end = VSCROLL.renderEnd, anchor = null) {if (VSCROLL.isDraggingThumb || start !== VSCROLL.renderStart || end !== VSCROLL.renderEnd) return false;const container = DOM.resultsContainer;const anchorIndex = anchor ? anchor.index : findVirtualIndex(getResultScrollTop());const anchorOffset = anchor ? anchor.offset : getResultScrollTop() - getVirtualOffset(anchorIndex);const rowMeasureKey = getHeightMeasurementKey();209 unmodified lines210211212213214215209 unmodified lines/** @param {number} [start] @param {number} [end] @param {{index: number, offset: number} | null} [anchor] */function measureHeights(start = VSCROLL.renderStart, end = VSCROLL.renderEnd, anchor = null) {if (VSCROLL.isDraggingThumb || start !== VSCROLL.renderStart || end !== VSCROLL.renderEnd) return false;const anchorIndex = anchor ? anchor.index : findVirtualIndex(getResultScrollTop());const anchorOffset = anchor ? anchor.offset : getResultScrollTop() - getVirtualOffset(anchorIndex);const rowMeasureKey = getHeightMeasurementKey();
12345678910// Validation of a page against the search window's pinned generation.// Fetching, cancellation and committing results belong to the host.(function () {/*** @typedef {{results: unknown[], page: number, page_size: number, total: number, generation?: string | undefined}} Page* @typedef {{total: number, generation?: string | undefined}} Expected*//** @param {SearchResponsePage} data @param {number} page @param {number} pageSize */function invalidContents(data, page, pageSize) {1234567// Validation of a page against the search window's pinned generation.// Fetching, cancellation and committing results belong to the host.(function () {/** @typedef {{total: number, generation?: string | undefined}} Expected *//** @param {SearchResponsePage} data @param {number} page @param {number} pageSize */function invalidContents(data, page, pageSize) {
522 unmodified lines5235245255265275285295305315325335342 unmodified lines537538539540541542543544545546547548549550551552553554555556557558522 unmodified lines(self.root / "node_modules/typescript").symlink_to(compiler, target_is_directory=True)config_dir = self.root / "config/types"config_dir.mkdir(parents=True)(config_dir / "input.ts").write_text("const value = 1;\n")base = config_dir / "base.json"config = config_dir / "jsconfig.strict.json"config.write_text(json.dumps({"extends": "./base.json", "files": ["input.ts"]}))name = "config/types/jsconfig.strict.json"required = dict.fromkeys(REQUIRED_FRONTEND_FLAGS, True)for options, accepted in (({"strict": True}, True),({"strictNullChecks": True, "noImplicitAny": True}, True),({"strict": True, "strictNullChecks": False}, False),2 unmodified lineswith self.subTest(options=options):base.write_text(json.dumps({"compilerOptions": {**required, **options}}))if accepted:self.assertIn("config/types/input.ts", compiler_files(self.root, name, strict=True))else:with self.assertRaisesRegex(RuntimeError, "effective (strictNullChecks|noImplicitAny) must be enabled"):compiler_files(self.root, name, strict=True)# An inherited strict setting can also be overridden in the child.base.write_text(json.dumps({"compilerOptions": {"strict": True, **required}}))config.write_text(json.dumps({"extends": "./base.json", "files": ["input.ts"],"compilerOptions": {"noImplicitAny": False}}))with self.assertRaisesRegex(RuntimeError, "effective noImplicitAny must be enabled"):compiler_files(self.root, name, strict=True)for flag in REQUIRED_FRONTEND_FLAGS:with self.subTest(flag=flag):config.write_text(json.dumps({"extends": "./base.json", "files": ["input.ts"],"compilerOptions": {flag: False}}))with self.assertRaisesRegex(RuntimeError, f"effective {flag} must be enabled"):compiler_files(self.root, name, strict=True)def test_promoting_a_file_requires_removing_its_old_debt_entry(self):self.py_strict.add("backend/old.py")522 unmodified lines5235245255265275285295305315325335345355362 unmodified lines539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570522 unmodified lines(self.root / "node_modules/typescript").symlink_to(compiler, target_is_directory=True)config_dir = self.root / "config/types"config_dir.mkdir(parents=True)(config_dir / "input.js").write_text("const value = 1;\nconsole.log(value);\n")base = config_dir / "base.json"config = config_dir / "jsconfig.strict.json"fixture = {"extends": "./base.json", "files": ["input.js"]}config.write_text(json.dumps(fixture))name = "config/types/jsconfig.strict.json"required = {**dict.fromkeys(REQUIRED_FRONTEND_FLAGS, True), "allowJs": True, "checkJs": True,"noEmit": True, "moduleDetection": "force"}for options, accepted in (({"strict": True}, True),({"strictNullChecks": True, "noImplicitAny": True}, True),({"strict": True, "strictNullChecks": False}, False),2 unmodified lineswith self.subTest(options=options):base.write_text(json.dumps({"compilerOptions": {**required, **options}}))if accepted:self.assertIn("config/types/input.js", compiler_files(self.root, name, strict=True))else:with self.assertRaisesRegex(RuntimeError, "effective (strictNullChecks|noImplicitAny) must be enabled"):compiler_files(self.root, name, strict=True)# An inherited strict setting can also be overridden in the child.strict_options = {"strict": True, **required}base.write_text(json.dumps({"compilerOptions": strict_options}))for option, value, message in (("noImplicitAny", False, "effective noImplicitAny must be enabled"),("moduleDetection", "legacy", "effective moduleDetection must be force"),("noCheck", True, "strict JavaScript checking must remain enabled"),("checkJs", False, "strict JavaScript checking must remain enabled"),):with self.subTest(option=option):config.write_text(json.dumps({**fixture, "compilerOptions": {option: value}}))with self.assertRaisesRegex(RuntimeError, message):compiler_files(self.root, name, strict=True)for flag in REQUIRED_FRONTEND_FLAGS:without_flag = strict_options.copy()del without_flag[flag]for base_options, overrides in ((strict_options, {flag: False}), (without_flag, {})):with self.subTest(flag=flag, overrides=overrides):base.write_text(json.dumps({"compilerOptions": base_options}))config.write_text(json.dumps({**fixture, "compilerOptions": overrides}))with self.assertRaisesRegex(RuntimeError, f"effective {flag} must be enabled"):compiler_files(self.root, name, strict=True)def test_promoting_a_file_requires_removing_its_old_debt_entry(self):self.py_strict.add("backend/old.py")
220 unmodified lines221222223224225226227228229230231232233234235236237238239240241242220 unmodified lines("noImplicitReturns", "TS7030", """/** @param {boolean} active */function readCount(active) { if (active) return 1; }"""),("noImplicitOverride", "TS4119", """class BaseProbe { clear() {} }class CacheProbe extends BaseProbe { clear() {} }"""),("noFallthroughCasesInSwitch", "TS7029", """/** @param {number} value */function update(value) { switch (value) { case 0: value++; case 1: break; } }"""),("noUncheckedIndexedAccess", "TS2322", """/** @param {string[]} values @returns {string} */function firstValue(values) { return values[0]; }"""),("exactOptionalPropertyTypes", "TS2375", """/** @type {{signal?: AbortSignal}} */const options = {signal: undefined};"""),)source = self.root / "static/strict-options-probe.js"220 unmodified lines221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255220 unmodified lines("noImplicitReturns", "TS7030", """/** @param {boolean} active */function readCount(active) { if (active) return 1; }readCount(true);"""),("noImplicitOverride", "TS4119", """class BaseProbe { clear() {} }class CacheProbe extends BaseProbe { clear() {} }new CacheProbe().clear();"""),("noFallthroughCasesInSwitch", "TS7029", """/** @param {number} value */function update(value) { switch (value) { case 0: value++; case 1: break; } }update(0);"""),("noUncheckedIndexedAccess", "TS2322", """/** @param {string[]} values @returns {string} */function firstValue(values) { return values[0]; }firstValue(["ok"]);"""),("exactOptionalPropertyTypes", "TS2375", """/** @type {{signal?: AbortSignal}} */const options = {signal: undefined};console.log(options);"""),("noUnusedLocals", "TS6133: 'unusedBinding'", """const unusedBinding = 1;"""),("noUnusedParameters", "TS6133: 'unusedParameter'", """/** @param {number} value @param {number} unusedParameter */function keepValue(value, unusedParameter) { return value; }keepValue(1, 2);"""),)source = self.root / "static/strict-options-probe.js"
661 unmodified lines662663664665666667668276 unmodified lines945946947948949950951661 unmodified lineschapter = (ROOT / "static/reader/formats/reader-chapter-format.mjs").read_text(encoding="utf-8")reader_html = (ROOT / "static/reader.html").read_text(encoding="utf-8")assert_source_contains(self, 'readerContext.trustedChapterReferenceUrl(value, url, manifestBase)', chapter)assert_source_contains(self, 'const resolved = resourceUrl(value, url, name === "href" ? "href" : "resource")', chapter)assert_source_contains(self, 'element.removeAttribute(name)', chapter)self.assertRegex(reader_html, r"connect-src[^\"]*\bblob:")276 unmodified linesdef test_result_rows_use_three_line_desktop_layout_and_equal_action_heights(self):self.assertRegex(self.result_rows, r'class="result-title"[\s\S]*class="result-path"[\s\S]*class="result-meta"')self.assertIn('function buildResultHTML(rec, idx) { return getResultRows().buildHTML(rec, idx); }', self.js)self.assertIn("body:not(.mobile) .result-title { grid-column: 3; grid-row: 1;", self.css)self.assertIn("body:not(.mobile) .result-path { grid-column: 3 / 5; grid-row: 2;", self.css)self.assertIn("body:not(.mobile) .result-meta { grid-column: 3 / 5; grid-row: 3;", self.css)661 unmodified lines662663664665666667668669276 unmodified lines946947948949950951952661 unmodified lineschapter = (ROOT / "static/reader/formats/reader-chapter-format.mjs").read_text(encoding="utf-8")reader_html = (ROOT / "static/reader.html").read_text(encoding="utf-8")assert_source_contains(self, 'readerContext.trustedChapterReferenceUrl(value, url, manifestBase)', chapter)assert_source_contains(self, 'const resolved = resourceUrl(value, url)', chapter)assert_source_contains(self, 'trustedChapterResourceUrl(value, base, manifestBase)', chapter)assert_source_contains(self, 'element.removeAttribute(name)', chapter)self.assertRegex(reader_html, r"connect-src[^\"]*\bblob:")276 unmodified linesdef test_result_rows_use_three_line_desktop_layout_and_equal_action_heights(self):self.assertRegex(self.result_rows, r'class="result-title"[\s\S]*class="result-path"[\s\S]*class="result-meta"')self.assertIn('function createResultRow(rec, idx) { return getResultRows().createRow(rec, idx); }', self.js)self.assertIn("body:not(.mobile) .result-title { grid-column: 3; grid-row: 1;", self.css)self.assertIn("body:not(.mobile) .result-path { grid-column: 3 / 5; grid-row: 2;", self.css)self.assertIn("body:not(.mobile) .result-meta { grid-column: 3 / 5; grid-row: 3;", self.css)
222 unmodified lines22322422522622722822966 unmodified lines296297298299300301302303304222 unmodified linesself.page.evaluate('''async url => {history.replaceState(null, '', url);await persistSearchSession();const db = await openSearchSessionDB();const saved = await new Promise((resolve, reject) => {const request = db.transaction('session', 'readonly').objectStore('session').get('last-search');request.onsuccess = () => resolve(request.result);66 unmodified linesself.page.wait_for_timeout(10)self.assertEqual(len(held), 1)route = held.pop()route.fulfill(response=route.fetch())self.page.unroute(pattern, hold_app)self.page.wait_for_function('typeof searchInputReady !== "undefined" && searchInputReady')self.assertFalse(field.evaluate('input => "_earlySearchInput" in input'))self.assertEqual(self.page.evaluate('searchComposing'), mode == 'spanning')current_query = 'paging-before-bind-B' if navigate else 'paging-before-bind'222 unmodified lines22322422522622722822966 unmodified lines296297298299300301302303304305306307308309222 unmodified linesself.page.evaluate('''async url => {history.replaceState(null, '', url);await persistSearchSession();const db = await searchSession.openSearchSessionDB();const saved = await new Promise((resolve, reject) => {const request = db.transaction('session', 'readonly').objectStore('session').get('last-search');request.onsuccess = () => resolve(request.result);66 unmodified linesself.page.wait_for_timeout(10)self.assertEqual(len(held), 1)route = held.pop()response = route.fetch()source = response.text()startup = 'finishInitialSearchInput(initialDraftCurrent);'self.assertEqual(source.count(startup), 1)route.fulfill(response=response, body=source.replace(startup, startup + ' window.__testSearchInputReady = true;'))self.page.unroute(pattern, hold_app)self.page.wait_for_function('window.__testSearchInputReady === true')self.assertFalse(field.evaluate('input => "_earlySearchInput" in input'))self.assertEqual(self.page.evaluate('searchComposing'), mode == 'spanning')current_query = 'paging-before-bind-B' if navigate else 'paging-before-bind'
109 unmodified lines110111112113114115116410 unmodified lines527528529530531532533229 unmodified lines7637647657667677687695 unmodified lines77577677777877978078194 unmodified lines876877878879880881882161 unmodified lines1044104510461047104810491050109 unmodified linesself.assertEqual(current.evaluate('''() => [formatSize(0), formatSize(1023), formatSize(1024),formatSize(1048576), formatSize(1073741824)]'''), ['', '1023 B', '1.0 KB', '1.0 MB', '1.00 GB'])row = current.evaluate('''() => {const html = buildResultHTML({Repo:'VoiceOfML/Test', File:'size', Extension:'txt', Folder:[], Size:1536}, 0);const node = document.createElement('div'); node.innerHTML = html;return node.textContent.includes('1.5 KB');}''')410 unmodified lines{name:'poster.jpg',ext:'jpg',size:1}, {name:'normal',ext:'jpg',size:1},{name:'book.PDF',ext:'pdf',size:1}, {name:'README',ext:'',size:1}];const list=document.createElement('div');list.className='browser-list';DOM.sidebarContent.append(list);renderBrowserListItems(list,{folders:[],files},repo,folder);return [...list.querySelectorAll('.browser-item')].map(row=>({filename:row.dataset.filename,link:decodeURIComponent(new URL(row.dataset.link).pathname),reader:row.dataset.readUrl ? new URL(row.dataset.readUrl,location.href).searchParams.get('id') : null}));229 unmodified linesreleaseBody({url:'https://source.test/stale'});await new Promise(resolve=>setTimeout(resolve,0));const stale=sessionStorage.getItem('reader-resolve:warm-hover');const slot=readerWarmupInFlight;calls[1].resolve({ok:true,json:async()=>({url:'https://source.test/click'})});await new Promise(resolve=>setTimeout(resolve,0));const cached=JSON.parse(sessionStorage.getItem('reader-resolve:warm-click') || 'null');5 unmodified linesawait new Promise(resolve=>setTimeout(resolve,0));return {before,replaced,stale,slot,cached:cached?.url,keyboardReplaced,keyboard:JSON.parse(sessionStorage.getItem('reader-resolve:warm-keyboard') || 'null')?.url,active:readerWarmupInFlight,errors};} finally {cancelReaderWarmup();window.fetch=originalFetch;window.removeEventListener('unhandledrejection',handler);hover.remove();click.remove();keyboard.remove();history.replaceState(null,'',savedUrl);94 unmodified linesself.assertIn('Reader independent of delayed warmup',frame.locator('.reader-text').inner_text())self.assertEqual(len(lookups),1)self.page.evaluate('''url=>__lateCalls[1].resolve({ok:true,json:async()=>({url,extension:'txt'})})''', source)self.page.wait_for_function('readerWarmupInFlight === 0')self.assertIn('Reader independent of delayed warmup',frame.locator('.reader-text').inner_text())self.assertEqual(len(lookups),1)finally:161 unmodified linesSTATE.useMirrorLinks=false; DOM.sortSelect.value='size';let target=new URL('/Test?folder_self=docs', location.origin);target=readerNavigation.mergeSearchParams(target, buildSearchURLParams(), {keys: READER_RETURN_SEARCH_KEYS});return Object.fromEntries(target.searchParams);}''')109 unmodified lines110111112113114115116410 unmodified lines527528529530531532533229 unmodified lines7637647657667677687695 unmodified lines77577677777877978078194 unmodified lines876877878879880881882161 unmodified lines1044104510461047104810491050109 unmodified linesself.assertEqual(current.evaluate('''() => [formatSize(0), formatSize(1023), formatSize(1024),formatSize(1048576), formatSize(1073741824)]'''), ['', '1023 B', '1.0 KB', '1.0 MB', '1.00 GB'])row = current.evaluate('''() => {const html = getResultRows().buildHTML({Repo:'VoiceOfML/Test', File:'size', Extension:'txt', Folder:[], Size:1536}, 0);const node = document.createElement('div'); node.innerHTML = html;return node.textContent.includes('1.5 KB');}''')410 unmodified lines{name:'poster.jpg',ext:'jpg',size:1}, {name:'normal',ext:'jpg',size:1},{name:'book.PDF',ext:'pdf',size:1}, {name:'README',ext:'',size:1}];const list=document.createElement('div');list.className='browser-list';DOM.sidebarContent.append(list);getSidebarDirectoryView().items(list,{folders:[],files},repo,folder);return [...list.querySelectorAll('.browser-item')].map(row=>({filename:row.dataset.filename,link:decodeURIComponent(new URL(row.dataset.link).pathname),reader:row.dataset.readUrl ? new URL(row.dataset.readUrl,location.href).searchParams.get('id') : null}));229 unmodified linesreleaseBody({url:'https://source.test/stale'});await new Promise(resolve=>setTimeout(resolve,0));const stale=sessionStorage.getItem('reader-resolve:warm-hover');const slot=Number(!!readerWarmupPending);calls[1].resolve({ok:true,json:async()=>({url:'https://source.test/click'})});await new Promise(resolve=>setTimeout(resolve,0));const cached=JSON.parse(sessionStorage.getItem('reader-resolve:warm-click') || 'null');5 unmodified linesawait new Promise(resolve=>setTimeout(resolve,0));return {before,replaced,stale,slot,cached:cached?.url,keyboardReplaced,keyboard:JSON.parse(sessionStorage.getItem('reader-resolve:warm-keyboard') || 'null')?.url,active:Number(!!readerWarmupPending),errors};} finally {cancelReaderWarmup();window.fetch=originalFetch;window.removeEventListener('unhandledrejection',handler);hover.remove();click.remove();keyboard.remove();history.replaceState(null,'',savedUrl);94 unmodified linesself.assertIn('Reader independent of delayed warmup',frame.locator('.reader-text').inner_text())self.assertEqual(len(lookups),1)self.page.evaluate('''url=>__lateCalls[1].resolve({ok:true,json:async()=>({url,extension:'txt'})})''', source)self.page.wait_for_function('!readerWarmupPending')self.assertIn('Reader independent of delayed warmup',frame.locator('.reader-text').inner_text())self.assertEqual(len(lookups),1)finally:161 unmodified linesSTATE.useMirrorLinks=false; DOM.sortSelect.value='size';let target=new URL('/Test?folder_self=docs', location.origin);target=readerNavigation.mergeSearchParams(target, buildSearchURLParams(), {keys: readerHost.keys});return Object.fromEntries(target.searchParams);}''')
708 unmodified lines709710711712713714715716717718719708 unmodified linespage=context.new_page();attempts=[]def fail_once(route):response=route.fetch();script=response.text()needle='return readerContext.measurePdf(readerContext.loadPdfWithTimeout(pdfjs, options, target, proxyUrl, takeInitial), "document")'self.assertIn(needle,script)script=script.replace(needle,'''return readerContext.measurePdf(stagedWorker? Promise.reject(new Error("injected staged parser failure")): readerContext.loadPdfWithTimeout(pdfjs, options, target, proxyUrl, takeInitial), "document")''')route.fulfill(response=response,body=script)page.route('**/static/reader/pdf/reader-pdf-engine.mjs*',fail_once)page.on('request',lambda req:attempts.append(req.url) if 'pdf-worker-wrapper.mjs' in req.url else None)708 unmodified lines709710711712713714715716717718719708 unmodified linespage=context.new_page();attempts=[]def fail_once(route):response=route.fetch();script=response.text()needle='return readerContext.measurePdf(readerContext.loadPdfWithTimeout(pdfjs, options, proxyUrl, takeInitial), "document")'self.assertIn(needle,script)script=script.replace(needle,'''return readerContext.measurePdf(stagedWorker? Promise.reject(new Error("injected staged parser failure")): readerContext.loadPdfWithTimeout(pdfjs, options, proxyUrl, takeInitial), "document")''')route.fulfill(response=response,body=script)page.route('**/static/reader/pdf/reader-pdf-engine.mjs*',fail_once)page.on('request',lambda req:attempts.append(req.url) if 'pdf-worker-wrapper.mjs' in req.url else None)
2647 unmodified lines26482649265026512652265326542647 unmodified linesconst page = part.node.parentElement.closest('[data-page]');const expected = page ? '第 ' + page.dataset.page + ' 页' :heading ? heading.label : '正文 ' + Math.min(100, Math.floor(part.start / Math.max(1,length) * 100)) + '%';return [window.__domSearchTools.location(part.node, '', part.start, length, lookup), expected];});const pairs = compare();setToc([...navigationState.tocEntries].reverse());2647 unmodified lines26482649265026512652265326542647 unmodified linesconst page = part.node.parentElement.closest('[data-page]');const expected = page ? '第 ' + page.dataset.page + ' 页' :heading ? heading.label : '正文 ' + Math.min(100, Math.floor(part.start / Math.max(1,length) * 100)) + '%';return [window.__domSearchTools.location(part.node, part.start, length, lookup), expected];});const pairs = compare();setToc([...navigationState.tocEntries].reverse());
12345650 unmodified lines57585960import assert from 'node:assert/strict';import { readFileSync } from 'node:fs';import vm from 'node:vm';import { createChapterProgress, createReaderChapterFormat, chapterPrefetchSize, isChapterSearchIndex } from '../../../static/reader/formats/reader-chapter-format.mjs';const sandbox = {};50 unmodified linesconst chapters = [{index:1,path:'1.html',title:{html:'<img onerror=alert(1)>'},source_path:{toString(){throw Error('coercion');}}}, {index:2,path:'2.html',title:'正常'}];await assert.rejects(createReaderChapterFormat(context).renderChapterManifest(new Response(JSON.stringify({version:1,kind:'epub-chapters',chapters}))), /stop/);assert.deepEqual(toc.map(item=>item.label), ['章节 1','正常']);console.log('chapter metadata validation and prefetch sizes passed');123456750 unmodified lines585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152import assert from 'node:assert/strict';import { readFileSync } from 'node:fs';import vm from 'node:vm';import { createReaderSource } from '../../../static/reader/core/reader-source.mjs';import { createChapterProgress, createReaderChapterFormat, chapterPrefetchSize, isChapterSearchIndex } from '../../../static/reader/formats/reader-chapter-format.mjs';const sandbox = {};50 unmodified linesconst chapters = [{index:1,path:'1.html',title:{html:'<img onerror=alert(1)>'},source_path:{toString(){throw Error('coercion');}}}, {index:2,path:'2.html',title:'正常'}];await assert.rejects(createReaderChapterFormat(context).renderChapterManifest(new Response(JSON.stringify({version:1,kind:'epub-chapters',chapters}))), /stop/);assert.deepEqual(toc.map(item=>item.label), ['章节 1','正常']);// Drive the actual click handler and trusted URL resolvers. Stub layout and// speculative loading so the resolution counts don't depend on timing.vm.runInNewContext(readFileSync(new URL('../../../static/reader/core/reader-contract.js', import.meta.url), 'utf8'), sandbox);globalThis.VoiceOfMLReader = sandbox.VoiceOfMLReader;const source = {};Object.assign(source, createReaderSource(source));const resolved = [], landings = [], articles = new Map();let click;globalThis.document.createElement = (tag) => {const node = {style:{}, dataset:{}, appendChild(){}, addEventListener(){}, setAttribute(){}, querySelectorAll:()=>[]};if (tag === 'article') node.querySelector = function (selector) { return [Number(this.dataset.chapter), selector]; };if (tag === 'div') Object.assign(node, {addEventListener(type, listener) { assert.equal(type, 'click'); click = listener; },querySelector: selector => articles.get(selector) || null,insertBefore(article) {if (article.className === 'reader-markdown reader-epub-chapter')articles.set(`.reader-epub-chapter[data-chapter="${article.dataset.chapter}"]`, article);}});return node;};globalThis.document.removeEventListener = globalThis.window.removeEventListener = () => {};globalThis.IntersectionObserver.prototype.disconnect = () => {};globalThis.requestAnimationFrame = () => 1;globalThis.cancelAnimationFrame = () => {};globalThis.CSS = {escape: value => value};globalThis.VoiceOfMLReaderChapters.createChapterScheduler = ({create}) => ({load: index => create(index, new AbortController().signal, 'high'), prefetch(){}, dispose(){}});globalThis.VoiceOfMLReaderVirtual.createSectionVirtualizer = () => ({dispose(){}});const linkContext = {...context, ...source, status:{}, readerAbortController:new AbortController(),viewport:{addEventListener(){}, removeEventListener(){}}, readerRestorationEntry:{chapterIndex:4},trustedChapterUrl(path, base) { resolved.push(path); return source.trustedChapterUrl(path, base); },fetchReaderUrl: async () => new Response(''), parseChapterDocument: () => ({querySelectorAll:()=>[]}),chapterScrollAnchors:{preserve: change => change(), observe(){}, invalidate(){}, remember(){}, whenIdle(){}},getInitialReaderRestoration: async () => {}, awaitReader: promise => promise, setToc: () => [],beginReaderNavigation: () => 1, isReaderGenerationCurrent: () => true,alignReaderDestination: anchor => landings.push(anchor), holdReaderDestination(){},syncHeadingLocation(){}, updateProgressTools(){}, scheduleSave(){}, markReaderContentReady(){},reportNavigationError(error) { throw error; }};const format = createReaderChapterFormat(linkContext);const chapterPath = index => `chapters/chapter-${String(index).padStart(4, '0')}.xhtml`;const linkChapters = Array.from({length:64}, (_, i) => ({index:i + 1, path:chapterPath(i + 1)}));linkChapters[1].path = 'chapters/invalid.xhtml'; // Valid manifest metadata, but not a trusted chapter URL.linkChapters[2].path = 'chapters/chapter-000%34.xhtml'; // Same resolved URL as the restored chapter 4.const paths = linkChapters.map(chapter => chapter.path);async function openBook(identity) {const prefix = `chapters/ebook/epub/${identity.repeat(64)}/${'a'.repeat(16)}/`;linkContext.chapterManifestUrl = `https://voiceofml-search.hf.space/api/reader-bucket-resource?path=${encodeURIComponent(prefix + 'chapter-manifest.json')}`;resolved.length = 0;articles.clear();await format.renderChapterManifest(new Response(JSON.stringify({version:1, kind:'epub-chapters', chapters:linkChapters})));assert.deepEqual(resolved, [chapterPath(4)], 'opening only resolves the loaded chapter path');}async function follow(href, chapterIndex, fragment) {const article = articles.get('.reader-epub-chapter[data-chapter="4"]');let prevented = false, error;const link = {closest:()=>article, getAttribute:()=>href, after: node => { error = node; }};landings.length = 0;await click({button:0, target:{closest:()=>link}, preventDefault(){ prevented = true; }});assert.equal(prevented, true);assert.equal(error?.className, chapterIndex ? undefined : 'reader-chapter-link-error');assert.deepEqual(landings, chapterIndex ? [[chapterIndex, `[id="${fragment}"], [name="${fragment}"]`]] : []);}await openBook('b');try {await follow('https://example.test/chapter-0004.xhtml#external');assert.equal(resolved.length, 1, 'a rejected reference does not start the scan');await follow('./chapter-0004.xhtml#%E7%9B%AE%E6%A0%87', 3, '目标');assert.deepEqual(resolved, [paths[3], ...paths.slice(0, 3)], 'stop at the first canonical match');await follow('chapter-0004.xhtml#again', 3, 'again');assert.equal(resolved.length, 4, 'repeated hit does not parse chapter paths again');await follow('chapter-0050.xhtml#late', 50, 'late');assert.deepEqual(resolved, [paths[3], ...paths.slice(0, 3), ...paths.slice(4, 50)], 'resume the prefix and reuse the fetch URL');await follow('chapter-0004.xhtml#first', 3, 'first');assert.equal(resolved.length, 50, 'the later duplicate did not replace the first match');await follow('chapter-0002.xhtml#missing');assert.deepEqual(resolved, [paths[3], ...paths.slice(0, 3), ...paths.slice(4)], 'a miss scans only the remaining suffix');await follow('chapter-0002.xhtml#missing');await follow('chapter-0099.xhtml#another-miss');assert.equal(resolved.length, paths.length, 'after exhaustion no miss parses another chapter path');} finally { linkContext.chapterManifestCleanup(); }await openBook('c');try {await follow('chapter-0004.xhtml#new-book', 3, 'new-book');assert.deepEqual(resolved, [paths[3], ...paths.slice(0, 3)], 'a new manifest starts with a fresh cache and cursor');} finally { linkContext.chapterManifestCleanup(); }console.log('chapter metadata validation and prefetch sizes passed');
99 unmodified lines1001011021031041051061071081091101111121131 unmodified line1151161171181191201212 unmodified lines12412512612712812913033 unmodified lines1641651661671681691701711721731745 unmodified lines1801811821831841851868 unmodified lines1951961971981992002012 unmodified lines2042052062072082092102112122132142153 unmodified lines2192202212222232242259 unmodified lines2352362372382392402412 unmodified lines2442452462472482492504 unmodified lines25525625725825926026199 unmodified linesassert.strictEqual(first.url,'/api/reader-resolve?id=one');first.resolve({ok:true,json:()=>new Promise(()=>{})});await tick();for(const timer of [...f.timers.values()])timer();await tick();assert.strictEqual(f.run('readerWarmupInFlight'),0,'stalled JSON must release the warming slot');assert.ok(first.options.signal.aborted);assert.strictEqual(f.run('warmedReaderSources.size'),0);f.run('warmReaderIntent("/reader?id=one&ext=txt")');assert.strictEqual(f.calls.filter(call=>call.url.includes('reader-resolve')).length,1,'failure must back off');f.advance();f.run('warmReaderIntent("/reader?id=one&ext=txt")');f.calls.at(-1).resolve({ok:true,json:async()=>({url:'https://source.test/book'})});await tick();assert.strictEqual(f.run('readerWarmupInFlight'),0);assert.ok(f.stored.has('reader-resolve:one'));assert.strictEqual(f.run('warmedReaderSources.size'),1);console.log('reader warming: whole-body deadline, coalescing, backoff and successful retry passed');1 unmodified linefor(const response of [{ok:false},{ok:true,json:async()=>({error:'bad'})}]) {const t=fixture();t.run('warmReaderIntent("/reader?id=bad&ext=txt")');t.calls.find(call=>call.url.includes('reader-resolve')).resolve(response);await tick();assert.strictEqual(t.run('warmedReaderSources.size'),0);assert.strictEqual(t.run('readerWarmupInFlight'),0);}for(const event of ['pagehide','offline','visibilitychange']) {const t=fixture();t.run('warmReaderIntent("/reader?id=old&ext=txt")');2 unmodified linesif(event==='visibilitychange')t.context.document.hidden=true;t.events[event]();await tick();assert.ok(pending.options.signal.aborted);resolveBody({url:'https://source.test/stale'});await tick();assert.strictEqual(t.stored.size,0);assert.strictEqual(t.run('readerWarmupInFlight'),0);}const t=fixture();t.context.document.hidden=true;t.run('warmReaderIntent("/reader?id=x")');t.context.document.hidden=false;t.context.navigator.onLine=false;t.run('warmReaderIntent("/reader?id=x")');33 unmodified linesconst next=resolverCalls(priority)[1];assert.ok(old.options.signal.aborted,'active intent must abort the previous speculative request');assert.ok(next.url.endsWith('id=new'));assert.strictEqual(priority.run('readerWarmupInFlight'),1);assert.strictEqual(priority.run('readerWarmupRetryAt.size'),0,'superseded work is not a failure');finishOld({url:'https://source.test/stale'});await tick();assert.strictEqual(priority.stored.has('reader-resolve:old'),false,'late old JSON cannot enter cache');assert.strictEqual(priority.run('readerWarmupInFlight'),1,'late completion cannot release new task');next.resolve({ok:true,json:async()=>({url:'https://source.test/new'})});await tick();assert.ok(priority.stored.has('reader-resolve:new'));emitIntent(priority,'pointerover','old');5 unmodified linesemitIntent(priority,'pointerdown','download',true);assert.strictEqual(resolverCalls(priority).length,4,'download actions never preempt');priority.events.offline();await tick();assert.strictEqual(priority.run('readerWarmupInFlight'),0);assert.ok(priority.run('readerWarmupRetryAt.has("id:keyboard")'),'offline cancellation retains backoff');const reentrant=fixture();8 unmodified linesassert.ok(owner.options.signal.aborted && reentrantCalls[1].url.endsWith('id=reentrant'));assert.strictEqual(reentrant.run('readerWarmupPending.key'),'id:reentrant');reentrantCalls[1].resolve({ok:true,json:async()=>({url:'https://source.test/reentrant'})});await tick();assert.strictEqual(reentrant.run('readerWarmupInFlight'),0);const rapid=fixture();emitIntent(rapid,'pointerover','rapid0');2 unmodified linesassert.strictEqual(rapidCalls.length,21);assert.ok(rapidCalls.slice(0,-1).every(call=>call.options.signal.aborted));assert.ok(!rapidCalls.at(-1).options.signal.aborted);assert.strictEqual(rapid.run('readerWarmupInFlight'),1);assert.strictEqual(rapid.run('readerWarmupRetryAt.size'),0);rapidCalls.at(-1).resolve({ok:true,json:async()=>({url:'https://source.test/final'})});await tick();assert.ok(rapid.stored.has('reader-resolve:rapid20'));assert.strictEqual(rapid.run('readerWarmupInFlight'),0);const sources=fixture();sources.run(`warmReaderIntent('/reader?url=https://source.test/hover');3 unmodified linesassert.ok(heads[0].options.signal.aborted);assert.ok(heads[1].url.includes(encodeURIComponent('https://source.test/activate')));heads[1].resolve({ok:true});await tick();assert.strictEqual(sources.run('readerWarmupInFlight'),0);assert.strictEqual(sources.run('warmedReaderSources.size'),1);const capacity=fixture();9 unmodified linesawait tick();assert.strictEqual(capacity.run('readerWarmupPending.key'),'id:limit','old rejection cannot release the urgent owner');resolverCalls(capacity).at(-1).resolve({ok:true,json:async()=>({url:'https://source.test/limit'})});await tick();assert.strictEqual(capacity.run('readerWarmupInFlight'),0);assert.strictEqual(capacity.run('warmedReaderSources.size'),8);const timeout=fixture();2 unmodified lines// Such a callback argument must not accidentally mark a timeout superseded.for (const timer of [...timeout.timers.values()]) timer({simulatedTimer:true});await tick();assert.strictEqual(timeout.run('readerWarmupInFlight'),0);assert.ok(timeout.run('readerWarmupRetryAt.has("id:timed-out")'));const previous=fixture();4 unmodified linesemitIntent(previous,'pointerdown','failed');assert.ok(busy.options.signal.aborted,'even a backed-off target should cancel unrelated speculation');assert.strictEqual(resolverCalls(previous).length,2,'priority does not bypass retry backoff');assert.strictEqual(previous.run('readerWarmupInFlight'),0);previous.advance();emitIntent(previous,'focusin','failed');assert.strictEqual(resolverCalls(previous).length,3);resolverCalls(previous)[2].resolve({ok:true,json:async()=>({url:'https://source.test/failed'})});await tick();99 unmodified lines1001011021031041051061071081091101111121131 unmodified line1151161171181191201212 unmodified lines12412512612712812913033 unmodified lines1641651661671681691701711721731745 unmodified lines1801811821831841851868 unmodified lines1951961971981992002012 unmodified lines2042052062072082092102112122132142153 unmodified lines2192202212222232242259 unmodified lines2352362372382392402412 unmodified lines2442452462472482492504 unmodified lines25525625725825926026199 unmodified linesassert.strictEqual(first.url,'/api/reader-resolve?id=one');first.resolve({ok:true,json:()=>new Promise(()=>{})});await tick();for(const timer of [...f.timers.values()])timer();await tick();assert.strictEqual(f.run('Number(!!readerWarmupPending)'),0,'stalled JSON must release the warming slot');assert.ok(first.options.signal.aborted);assert.strictEqual(f.run('warmedReaderSources.size'),0);f.run('warmReaderIntent("/reader?id=one&ext=txt")');assert.strictEqual(f.calls.filter(call=>call.url.includes('reader-resolve')).length,1,'failure must back off');f.advance();f.run('warmReaderIntent("/reader?id=one&ext=txt")');f.calls.at(-1).resolve({ok:true,json:async()=>({url:'https://source.test/book'})});await tick();assert.strictEqual(f.run('Number(!!readerWarmupPending)'),0);assert.ok(f.stored.has('reader-resolve:one'));assert.strictEqual(f.run('warmedReaderSources.size'),1);console.log('reader warming: whole-body deadline, coalescing, backoff and successful retry passed');1 unmodified linefor(const response of [{ok:false},{ok:true,json:async()=>({error:'bad'})}]) {const t=fixture();t.run('warmReaderIntent("/reader?id=bad&ext=txt")');t.calls.find(call=>call.url.includes('reader-resolve')).resolve(response);await tick();assert.strictEqual(t.run('warmedReaderSources.size'),0);assert.strictEqual(t.run('Number(!!readerWarmupPending)'),0);}for(const event of ['pagehide','offline','visibilitychange']) {const t=fixture();t.run('warmReaderIntent("/reader?id=old&ext=txt")');2 unmodified linesif(event==='visibilitychange')t.context.document.hidden=true;t.events[event]();await tick();assert.ok(pending.options.signal.aborted);resolveBody({url:'https://source.test/stale'});await tick();assert.strictEqual(t.stored.size,0);assert.strictEqual(t.run('Number(!!readerWarmupPending)'),0);}const t=fixture();t.context.document.hidden=true;t.run('warmReaderIntent("/reader?id=x")');t.context.document.hidden=false;t.context.navigator.onLine=false;t.run('warmReaderIntent("/reader?id=x")');33 unmodified linesconst next=resolverCalls(priority)[1];assert.ok(old.options.signal.aborted,'active intent must abort the previous speculative request');assert.ok(next.url.endsWith('id=new'));assert.strictEqual(priority.run('Number(!!readerWarmupPending)'),1);assert.strictEqual(priority.run('readerWarmupRetryAt.size'),0,'superseded work is not a failure');finishOld({url:'https://source.test/stale'});await tick();assert.strictEqual(priority.stored.has('reader-resolve:old'),false,'late old JSON cannot enter cache');assert.strictEqual(priority.run('Number(!!readerWarmupPending)'),1,'late completion cannot release new task');next.resolve({ok:true,json:async()=>({url:'https://source.test/new'})});await tick();assert.ok(priority.stored.has('reader-resolve:new'));emitIntent(priority,'pointerover','old');5 unmodified linesemitIntent(priority,'pointerdown','download',true);assert.strictEqual(resolverCalls(priority).length,4,'download actions never preempt');priority.events.offline();await tick();assert.strictEqual(priority.run('Number(!!readerWarmupPending)'),0);assert.ok(priority.run('readerWarmupRetryAt.has("id:keyboard")'),'offline cancellation retains backoff');const reentrant=fixture();8 unmodified linesassert.ok(owner.options.signal.aborted && reentrantCalls[1].url.endsWith('id=reentrant'));assert.strictEqual(reentrant.run('readerWarmupPending.key'),'id:reentrant');reentrantCalls[1].resolve({ok:true,json:async()=>({url:'https://source.test/reentrant'})});await tick();assert.strictEqual(reentrant.run('Number(!!readerWarmupPending)'),0);const rapid=fixture();emitIntent(rapid,'pointerover','rapid0');2 unmodified linesassert.strictEqual(rapidCalls.length,21);assert.ok(rapidCalls.slice(0,-1).every(call=>call.options.signal.aborted));assert.ok(!rapidCalls.at(-1).options.signal.aborted);assert.strictEqual(rapid.run('Number(!!readerWarmupPending)'),1);assert.strictEqual(rapid.run('readerWarmupRetryAt.size'),0);rapidCalls.at(-1).resolve({ok:true,json:async()=>({url:'https://source.test/final'})});await tick();assert.ok(rapid.stored.has('reader-resolve:rapid20'));assert.strictEqual(rapid.run('Number(!!readerWarmupPending)'),0);const sources=fixture();sources.run(`warmReaderIntent('/reader?url=https://source.test/hover');3 unmodified linesassert.ok(heads[0].options.signal.aborted);assert.ok(heads[1].url.includes(encodeURIComponent('https://source.test/activate')));heads[1].resolve({ok:true});await tick();assert.strictEqual(sources.run('Number(!!readerWarmupPending)'),0);assert.strictEqual(sources.run('warmedReaderSources.size'),1);const capacity=fixture();9 unmodified linesawait tick();assert.strictEqual(capacity.run('readerWarmupPending.key'),'id:limit','old rejection cannot release the urgent owner');resolverCalls(capacity).at(-1).resolve({ok:true,json:async()=>({url:'https://source.test/limit'})});await tick();assert.strictEqual(capacity.run('Number(!!readerWarmupPending)'),0);assert.strictEqual(capacity.run('warmedReaderSources.size'),8);const timeout=fixture();2 unmodified lines// Such a callback argument must not accidentally mark a timeout superseded.for (const timer of [...timeout.timers.values()]) timer({simulatedTimer:true});await tick();assert.strictEqual(timeout.run('Number(!!readerWarmupPending)'),0);assert.ok(timeout.run('readerWarmupRetryAt.has("id:timed-out")'));const previous=fixture();4 unmodified linesemitIntent(previous,'pointerdown','failed');assert.ok(busy.options.signal.aborted,'even a backed-off target should cancel unrelated speculation');assert.strictEqual(resolverCalls(previous).length,2,'priority does not bypass retry backoff');assert.strictEqual(previous.run('Number(!!readerWarmupPending)'),0);previous.advance();emitIntent(previous,'focusin','failed');assert.strictEqual(resolverCalls(previous).length,3);resolverCalls(previous)[2].resolve({ok:true,json:async()=>({url:'https://source.test/failed'})});await tick();
12341 unmodified line6789101112131413 unmodified lines282930313233343536373839404142434445464748495051525354558 unmodified lines6465666768697071727374757677787980818283// Capture the existing host renderer before replacing its HTML assembly.import assert from 'node:assert/strict';import fs from 'node:fs';import path from 'node:path';1 unmodified lineimport vm from 'node:vm';const root = process.cwd();const source = fs.readFileSync(path.join(root,'static/app.js'),'utf8');const match = source.match(/^function renderBrowserListItems\([^]*?^}/m);assert.ok(match, 'host sidebar renderer must exist');const space = fs.existsSync(path.join(root,'pyrightconfig.json'));function fixture() {13 unmodified linesvm.runInContext(fs.readFileSync(modulePath,'utf8'),c,{filename:modulePath});const directoryPath=path.join(root,'static/search/sidebar/presentation/directory.js');vm.runInContext(fs.readFileSync(directoryPath,'utf8'),c,{filename:directoryPath});c.getSidebarDirectoryView=()=>c.VoiceOfMLSidebarDirectoryView.create({surface:space?'space':'pages',scroll:{restore:()=>c.restoreSidebarScroll()},markup:{icon:key=>c.sidebarIconMarkup(key),escape:value=>c.escapeHTML(value),iconType:value=>c.getFileIconType(value),formatSize:value=>c.formatSize(value),name:file=>c.getBrowserFileName(file),link:(...args)=>c.getBrowserFileLink(...args),reader:(...args)=>space?c.getBrowserFileReadUrl(...args):c.getBrowserReaderUrl(...args)}});vm.runInContext(match[0],c,{filename:'sidebar-host.js'});return {c,calls};}test('empty sidebar preserves original output and scroll restore timing',()=>{const {c,calls}=fixture();const list={innerHTML:'old'};c.renderBrowserListItems(list,{},'Repo','');assert.equal(list.innerHTML,'');assert.deepEqual(calls,[['icon','folder'],['restore']]);});test('folder and file markup preserve site-specific attributes, escaping and order',()=>{const {c,calls}=fixture();const list={innerHTML:''};const data={folders:[{name:'<目录&',path:'a"/b',count:3}],files:[{name:'a<b',ext:'pdf',size:12},{name:'raw&',ext:'zip',size:0}]};c.renderBrowserListItems(list,data,'Repo','folder');const html=list.innerHTML;assert.match(html,/aria-label="打开文件夹:<目录&"/);assert.match(html,/data-path="a"\/b"/);8 unmodified lines});test('missing folder paths keep each site original serialization',()=>{const {c}=fixture();const list={innerHTML:''};c.renderBrowserListItems(list,{folders:[{name:'missing'}]},'R','');assert.match(list.innerHTML,space?/data-path="undefined"/:/data-path=""/);});test('exceptions before final assignment do not restore scroll or partially replace DOM',()=>{const {c,calls}=fixture();const list={innerHTML:'old'};c.getBrowserFileName=()=>{throw new Error('name failure');};assert.throws(()=>c.renderBrowserListItems(list,{folders:[],files:[{name:'x',ext:'pdf'}]},'R',''),/name failure/);assert.equal(list.innerHTML,'old');assert.equal(calls.some(x=>x[0]==='restore'),false);});test('DOM assignment exceptions prevent scroll restoration',()=>{const {c,calls}=fixture();const list={set innerHTML(_value){throw new Error('assignment failure');}};assert.throws(()=>c.renderBrowserListItems(list,{folders:[],files:[]},'R',''),/assignment failure/);assert.equal(calls.some(x=>x[0]==='restore'),false);});12341 unmodified line6789101113 unmodified lines2526272829303132333435363738394041424344454647484950518 unmodified lines6061626364656667686970717273747576777879// Keep the original sidebar behavior pinned against the directory view.import assert from 'node:assert/strict';import fs from 'node:fs';import path from 'node:path';1 unmodified lineimport vm from 'node:vm';const root = process.cwd();const space = fs.existsSync(path.join(root,'pyrightconfig.json'));function fixture() {13 unmodified linesvm.runInContext(fs.readFileSync(modulePath,'utf8'),c,{filename:modulePath});const directoryPath=path.join(root,'static/search/sidebar/presentation/directory.js');vm.runInContext(fs.readFileSync(directoryPath,'utf8'),c,{filename:directoryPath});const directory=c.VoiceOfMLSidebarDirectoryView.create({surface:space?'space':'pages',scroll:{restore:()=>c.restoreSidebarScroll()},markup:{icon:key=>c.sidebarIconMarkup(key),escape:value=>c.escapeHTML(value),iconType:value=>c.getFileIconType(value),formatSize:value=>c.formatSize(value),name:file=>c.getBrowserFileName(file),link:(...args)=>c.getBrowserFileLink(...args),reader:(...args)=>space?c.getBrowserFileReadUrl(...args):c.getBrowserReaderUrl(...args)}});return {c,calls,directory};}test('empty sidebar preserves original output and scroll restore timing',()=>{const {directory,calls}=fixture();const list={innerHTML:'old'};directory.items(list,{},'Repo','');assert.equal(list.innerHTML,'');assert.deepEqual(calls,[['icon','folder'],['restore']]);});test('folder and file markup preserve site-specific attributes, escaping and order',()=>{const {directory,calls}=fixture();const list={innerHTML:''};const data={folders:[{name:'<目录&',path:'a"/b',count:3}],files:[{name:'a<b',ext:'pdf',size:12},{name:'raw&',ext:'zip',size:0}]};directory.items(list,data,'Repo','folder');const html=list.innerHTML;assert.match(html,/aria-label="打开文件夹:<目录&"/);assert.match(html,/data-path="a"\/b"/);8 unmodified lines});test('missing folder paths keep each site original serialization',()=>{const {directory}=fixture();const list={innerHTML:''};directory.items(list,{folders:[{name:'missing'}]},'R','');assert.match(list.innerHTML,space?/data-path="undefined"/:/data-path=""/);});test('exceptions before final assignment do not restore scroll or partially replace DOM',()=>{const {c,calls,directory}=fixture();const list={innerHTML:'old'};c.getBrowserFileName=()=>{throw new Error('name failure');};assert.throws(()=>directory.items(list,{folders:[],files:[{name:'x',ext:'pdf'}]},'R',''),/name failure/);assert.equal(list.innerHTML,'old');assert.equal(calls.some(x=>x[0]==='restore'),false);});test('DOM assignment exceptions prevent scroll restoration',()=>{const {directory,calls}=fixture();const list={set innerHTML(_value){throw new Error('assignment failure');}};assert.throws(()=>directory.items(list,{folders:[],files:[]},'R',''),/assignment failure/);assert.equal(calls.some(x=>x[0]==='restore'),false);});
149 unmodified lines150151152153154155156209 unmodified lines366367368369370371372109 unmodified lines48248348448548648748830 unmodified lines519520521522523524525213 unmodified lines73974074174274374474597 unmodified lines843844845846847848849850851852853854415 unmodified lines1270127112721273127412751276149 unmodified lines}initialPayloadCache.clear();// The first-page response cache is independent of the initial payload cache.searchResponseCache.clear();STATE.query = ""; STATE.page = 1;const pending = searchWithInitialFallbackFresh();await new Promise(resolve => setTimeout(resolve, 50));209 unmodified lines}];STATE.folderTreeCollapsed = {};getSidebarFolderTree().initialize(STATE.folderTree);renderFilterFolderTree();}""")checkbox = page.locator("#filter-folder-tree .filter-folder-item input").lastwith page.expect_request(lambda request: request.url.split('?', 1)[0].endswith('/api/search/MLMRL-Hub') and109 unmodified linesname: `folder-${i}`, path: `folder-${i}`, count: 1,hasDirectFiles: true, hasChildren: false, children: []}));renderFilterFolderTree();window.__originalFilterRow = DOM.filterFolderTree.firstElementChild;window.__filterRuns = 0;window.__searchRuns = 0;30 unmodified linesshowSelfToggle:true, hasDirectFiles:true, hasChildren:true,children:[{name:'docs', path:'docs', count:1, hasDirectFiles:true, hasChildren:false, children:[]}]}];STATE.folderTreeCollapsed = {};renderFilterFolderTree();}""")button = page.locator("#filter-folder-tree .folder-self-toggle")button.click()213 unmodified linestry:# The visible input precedes asynchronous startup search/prefetch.# Observe composition only after those initial requests settle.page.wait_for_function("STATE._loadedPage >= 1 && !STATE.isLoading && pendingSearchPages.size === 0")requests.clear()page.locator("#search-input").dispatch_event("compositionstart")page.locator("#search-input").fill("手")97 unmodified linesconst originalRect = measuredRow.getBoundingClientRect.bind(measuredRow);measuredRow.getBoundingClientRect = () => { repeatedReads++; return originalRect(); };VSCROLL.measuredWindowKey = "";measureHeights(VSCROLL.renderStart, VSCROLL.renderEnd);const readsAtSameWidth = repeatedReads;const originalWidth = DOM.resultsContainer.style.width;DOM.resultsContainer.style.width = Math.max(200, container.clientWidth - 1) + "px";VSCROLL.measuredWindowKey = "";measureHeights(VSCROLL.renderStart, VSCROLL.renderEnd);DOM.resultsContainer.style.width = originalWidth;const preservedAfterAppend = preservedRow === DOM.resultsList.querySelector(`.result-item[data-index="${preservedIndex}"]`);const treeExtendedInPlace = heightTreeBeforeAppend === VSCROLL.heightTree;415 unmodified linespage.locator("#search-input").wait_for(state="visible")page.wait_for_function("() => STATE.query === '持久搜索' && STATE.filterExtensions.includes('pdf')")page.wait_for_function("""async () => {const db = await openSearchSessionDB();const tx = db.transaction('session', 'readonly');const request = tx.objectStore('session').get('last-search');const saved = await new Promise((resolve, reject) => { request.onsuccess = () => resolve(request.result); request.onerror = reject; });149 unmodified lines150151152153154155156209 unmodified lines366367368369370371372109 unmodified lines48248348448548648748830 unmodified lines519520521522523524525213 unmodified lines73974074174274374474597 unmodified lines843844845846847848849850851852853854415 unmodified lines1270127112721273127412751276149 unmodified lines}initialPayloadCache.clear();// The first-page response cache is independent of the initial payload cache.searchResponseStore.cache.clear();STATE.query = ""; STATE.page = 1;const pending = searchWithInitialFallbackFresh();await new Promise(resolve => setTimeout(resolve, 50));209 unmodified lines}];STATE.folderTreeCollapsed = {};getSidebarFolderTree().initialize(STATE.folderTree);getSidebarFolderTree().render();}""")checkbox = page.locator("#filter-folder-tree .filter-folder-item input").lastwith page.expect_request(lambda request: request.url.split('?', 1)[0].endswith('/api/search/MLMRL-Hub') and109 unmodified linesname: `folder-${i}`, path: `folder-${i}`, count: 1,hasDirectFiles: true, hasChildren: false, children: []}));getSidebarFolderTree().render();window.__originalFilterRow = DOM.filterFolderTree.firstElementChild;window.__filterRuns = 0;window.__searchRuns = 0;30 unmodified linesshowSelfToggle:true, hasDirectFiles:true, hasChildren:true,children:[{name:'docs', path:'docs', count:1, hasDirectFiles:true, hasChildren:false, children:[]}]}];STATE.folderTreeCollapsed = {};getSidebarFolderTree().render();}""")button = page.locator("#filter-folder-tree .folder-self-toggle")button.click()213 unmodified linestry:# The visible input precedes asynchronous startup search/prefetch.# Observe composition only after those initial requests settle.page.wait_for_function("STATE._loadedPage >= 1 && !STATE.isLoading && getSearchTransport().pending.size === 0")requests.clear()page.locator("#search-input").dispatch_event("compositionstart")page.locator("#search-input").fill("手")97 unmodified linesconst originalRect = measuredRow.getBoundingClientRect.bind(measuredRow);measuredRow.getBoundingClientRect = () => { repeatedReads++; return originalRect(); };VSCROLL.measuredWindowKey = "";getVirtualResults().measureHeights();const readsAtSameWidth = repeatedReads;const originalWidth = DOM.resultsContainer.style.width;DOM.resultsContainer.style.width = Math.max(200, container.clientWidth - 1) + "px";VSCROLL.measuredWindowKey = "";getVirtualResults().measureHeights();DOM.resultsContainer.style.width = originalWidth;const preservedAfterAppend = preservedRow === DOM.resultsList.querySelector(`.result-item[data-index="${preservedIndex}"]`);const treeExtendedInPlace = heightTreeBeforeAppend === VSCROLL.heightTree;415 unmodified linespage.locator("#search-input").wait_for(state="visible")page.wait_for_function("() => STATE.query === '持久搜索' && STATE.filterExtensions.includes('pdf')")page.wait_for_function("""async () => {const db = await searchSession.openSearchSessionDB();const tx = db.transaction('session', 'readonly');const request = tx.objectStore('session').get('last-search');const saved = await new Promise((resolve, reject) => { request.onsuccess = () => resolve(request.result); request.onerror = reject; });
47 unmodified lines4849505152535462 unmodified lines1171181191201211221236 unmodified lines13013113213313413513630 unmodified lines16716816917017117217317450 unmodified lines22522622722822923023158 unmodified lines2902912922932942952969 unmodified lines30630730830931031131247 unmodified linesself.assertEqual(self.page.locator('[data-action="download"]').first.text_content(), '准备中…')self.assertEqual(self.page.evaluate('launches.length'), 0)self.page.evaluate('finishCheck()')self.page.wait_for_function('launches.length === 1 && pendingDownloads.size === 0')self.page.locator('[data-action="download"]').first.click()self.page.wait_for_function('launches.length === 2')self.assertEqual(self.page.evaluate('checkCalls'), 1)62 unmodified linesif (handedOff !== link) return;const cancel=()=>{downloadBatches.cancel();handoffRetained=pendingDownloads.has(link);};if (timing==='sync') cancel(); else queueMicrotask(cancel);};6 unmodified linesself.assertEqual(self.page.evaluate('''[downloadBatches.batch.cancelled,downloadBatches.batch.started,downloadBatches.batch.next,downloadBatches.batch.failed.map(item=>item.link),handoffLaunches,handoffIndependent,handoffRetained,pendingDownloads.size]'''), [True, 1, 2, [link+'-queued', link+'-unclaimed'], [link], True, True, 0])self.assertIn('已发起 1/3', self.page.locator('#download-queue [role="status"]').text_content())self.page.locator('#download-queue [data-queue="retry"]').click()30 unmodified lines{status:link==='bad' && calls[link]===1 ? 503 : 200}));};for(let i=0;i<70;i++) await checkDownload('cache'+i);const size=downloadChecks.size;downloadChecks.get('cache69').expires=Date.now()-1;await checkDownload('cache69');const first=await downloadFile('bad.txt','bad');const second=await downloadFile('bad.txt','bad');50 unmodified linesconst real=checkDownload('real');const busy=await checkDownload('speculative',true);finishCheck(); await real;return {hidden,offline,busy,calls:checkCalls,queued:downloadCheckQueue.length};}''')self.assertEqual(result, dict(hidden=False,offline=False,busy=False,calls=1,queued=0))58 unmodified linesself.page.locator('[data-queue="cancel"]').click()self.page.evaluate('releases.forEach(release=>release())')self.page.wait_for_function('downloadBatches.batch.done')self.assertEqual(self.page.evaluate('[releases.length,launches.length,pendingDownloads.size]'), [2,0,0])self.page.locator('[data-queue="close"]').click()self.assertEqual(self.page.locator('#download-queue').count(), 0)9 unmodified lines}''')self.page.clock.fast_forward(8001)self.page.wait_for_function('window.downloadResult === false')self.assertEqual(self.page.evaluate('[activeDownloadChecks,downloadChecks.size,pendingDownloads.size]'), [0,0,0])self.assertIn('超时', self.page.locator('#toast').text_content())def test_attachment_handoff_keeps_search_page_and_filename(self):47 unmodified lines4849505152535462 unmodified lines1171181191201211221236 unmodified lines13013113213313413513630 unmodified lines16716816917017117217317450 unmodified lines22522622722822923023158 unmodified lines2902912922932942952969 unmodified lines30630730830931031131247 unmodified linesself.assertEqual(self.page.locator('[data-action="download"]').first.text_content(), '准备中…')self.assertEqual(self.page.evaluate('launches.length'), 0)self.page.evaluate('finishCheck()')self.page.wait_for_function('launches.length === 1 && downloadController.pendingDownloads.size === 0')self.page.locator('[data-action="download"]').first.click()self.page.wait_for_function('launches.length === 2')self.assertEqual(self.page.evaluate('checkCalls'), 1)62 unmodified linesif (handedOff !== link) return;const cancel=()=>{downloadBatches.cancel();handoffRetained=downloadController.pendingDownloads.has(link);};if (timing==='sync') cancel(); else queueMicrotask(cancel);};6 unmodified linesself.assertEqual(self.page.evaluate('''[downloadBatches.batch.cancelled,downloadBatches.batch.started,downloadBatches.batch.next,downloadBatches.batch.failed.map(item=>item.link),handoffLaunches,handoffIndependent,handoffRetained,downloadController.pendingDownloads.size]'''), [True, 1, 2, [link+'-queued', link+'-unclaimed'], [link], True, True, 0])self.assertIn('已发起 1/3', self.page.locator('#download-queue [role="status"]').text_content())self.page.locator('#download-queue [data-queue="retry"]').click()30 unmodified lines{status:link==='bad' && calls[link]===1 ? 503 : 200}));};for(let i=0;i<70;i++) await checkDownload('cache'+i);const size=downloadController.downloadChecks.size;downloadController.downloadChecks.get('cache69').expires=Date.now()-1;await checkDownload('cache69');const first=await downloadFile('bad.txt','bad');const second=await downloadFile('bad.txt','bad');50 unmodified linesconst real=checkDownload('real');const busy=await checkDownload('speculative',true);finishCheck(); await real;return {hidden,offline,busy,calls:checkCalls,queued:downloadController.downloadCheckQueue.length};}''')self.assertEqual(result, dict(hidden=False,offline=False,busy=False,calls=1,queued=0))58 unmodified linesself.page.locator('[data-queue="cancel"]').click()self.page.evaluate('releases.forEach(release=>release())')self.page.wait_for_function('downloadBatches.batch.done')self.assertEqual(self.page.evaluate('[releases.length,launches.length,downloadController.pendingDownloads.size]'), [2,0,0])self.page.locator('[data-queue="close"]').click()self.assertEqual(self.page.locator('#download-queue').count(), 0)9 unmodified lines}''')self.page.clock.fast_forward(8001)self.page.wait_for_function('window.downloadResult === false')self.assertEqual(self.page.evaluate('[activeDownloadChecks,downloadController.downloadChecks.size,downloadController.pendingDownloads.size]'), [0,0,0])self.assertIn('超时', self.page.locator('#toast').text_content())def test_attachment_handoff_keeps_search_page_and_filename(self):
130 unmodified lines13113213313413513613714 unmodified lines1521531541551561571582 unmodified lines16116216316416516616716816917017117217317417517617723 unmodified lines2012022032042052062072082092102112122132143 unmodified lines21821922022122222322484 unmodified lines309310311312313314315130 unmodified linesel.textContent = JSON.stringify(changed);}''')for age in (240000, 479999):self.page.evaluate('age => { initialNow = 1000000 + age; searchResponseCache.clear(); }', age)self.evaluate_bounded('async () => { await searchWithInitialFallbackFresh(); }')self.assert_initial_generation('G1')self.assertEqual((len(self.initial_requests), len(self.api_requests)), (0, 0))14 unmodified linesdef test_initial_payload_cannot_overwrite_newer_response(self):self.load_initial_clock_fixture()self.page.evaluate('''() => {initialNow += 1000; searchResponseCache.clear(); doSearch();}''')self.assert_initial_generation('G2')self.assertEqual(len(self.api_requests), 1)2 unmodified linesself.assertEqual(self.page.evaluate('getCachedSearchResponse(getCurrentSearchCacheKey(1)).generation'), 'G2')self.assertEqual((len(self.initial_requests), len(self.api_requests)), (0, 1))self.initial_generation = 'G3'self.page.evaluate('searchResponseCache.clear()')self.evaluate_bounded('async () => { await searchWithInitialFallbackFresh(); }')self.assert_initial_generation('G3')self.assertEqual((len(self.initial_requests), len(self.api_requests)), (1, 1))def test_newer_response_eviction_does_not_resurrect_initial(self):self.load_initial_clock_fixture()self.page.evaluate("initialNow += 1000; searchResponseCache.clear(); doSearch()")self.assert_initial_generation('G2')self.initial_generation = 'G3'self.page.evaluate('searchResponseCache.clear()')self.evaluate_bounded('async () => { await searchWithInitialFallbackFresh(); }')self.assert_initial_generation('G3')23 unmodified linesnow+=1000; const acquired=now;setCachedSearchResponse(key,data,true); now+=SEARCH_CACHE_TTL-1;flushWrite();const keptAge=searchResponseCache.get(key)?.time===acquired;now++; const expiredAtBoundary=getCachedSearchResponse(key)===null;setCachedSearchResponse(key,data,true); now+=SEARCH_CACHE_TTL;flushWrite();const flushDropsExpired=!searchResponseCache.has(key) && !searchResponseStore.pendingWrites.has(key);return {expiredPending,expiredAfterFlush,keptAge,expiredAtBoundary,flushDropsExpired};} finally {cancelPendingSearchCacheWrites();searchResponseCache.delete(key);Date.now=clock;requestAnimationFrame=raf;cancelAnimationFrame=cancel;}}''')3 unmodified linesdef hold_initial_and_search(self):self.page.evaluate('''() => {cancelSearchPrefetch();searchResponseCache.clear(); initialPayloadCache.clear(); resultSnapshots.snapshots.clear();STATE.query = ''; STATE.page = 1;if (typeof readInitialSearchPayload === 'function') readInitialSearchPayload = () => null;window.initialFlights = []; window.searchFlights = [];84 unmodified linesself.hold_initial_and_search()self.evaluate_bounded('''async () => {initialFlights[0].resolve(payload('seed')); await oldInitial;resultSnapshots.snapshots.clear(); initialPayloadCache.clear(); searchResponseCache.clear();displayedSearchView = null;getReturnPositionTarget = () => ({index:0});readSearchViewport = () => new Promise(resolve => { window.releaseViewport = resolve; });130 unmodified lines13113213313413513613714 unmodified lines1521531541551561571582 unmodified lines16116216316416516616716816917017117217317417517617723 unmodified lines2012022032042052062072082092102112122132143 unmodified lines21821922022122222322484 unmodified lines309310311312313314315130 unmodified linesel.textContent = JSON.stringify(changed);}''')for age in (240000, 479999):self.page.evaluate('age => { initialNow = 1000000 + age; searchResponseStore.cache.clear(); }', age)self.evaluate_bounded('async () => { await searchWithInitialFallbackFresh(); }')self.assert_initial_generation('G1')self.assertEqual((len(self.initial_requests), len(self.api_requests)), (0, 0))14 unmodified linesdef test_initial_payload_cannot_overwrite_newer_response(self):self.load_initial_clock_fixture()self.page.evaluate('''() => {initialNow += 1000; searchResponseStore.cache.clear(); doSearch();}''')self.assert_initial_generation('G2')self.assertEqual(len(self.api_requests), 1)2 unmodified linesself.assertEqual(self.page.evaluate('getCachedSearchResponse(getCurrentSearchCacheKey(1)).generation'), 'G2')self.assertEqual((len(self.initial_requests), len(self.api_requests)), (0, 1))self.initial_generation = 'G3'self.page.evaluate('searchResponseStore.cache.clear()')self.evaluate_bounded('async () => { await searchWithInitialFallbackFresh(); }')self.assert_initial_generation('G3')self.assertEqual((len(self.initial_requests), len(self.api_requests)), (1, 1))def test_newer_response_eviction_does_not_resurrect_initial(self):self.load_initial_clock_fixture()self.page.evaluate("initialNow += 1000; searchResponseStore.cache.clear(); doSearch()")self.assert_initial_generation('G2')self.initial_generation = 'G3'self.page.evaluate('searchResponseStore.cache.clear()')self.evaluate_bounded('async () => { await searchWithInitialFallbackFresh(); }')self.assert_initial_generation('G3')23 unmodified linesnow+=1000; const acquired=now;setCachedSearchResponse(key,data,true); now+=SEARCH_CACHE_TTL-1;flushWrite();const keptAge=searchResponseStore.cache.get(key)?.time===acquired;now++; const expiredAtBoundary=getCachedSearchResponse(key)===null;setCachedSearchResponse(key,data,true); now+=SEARCH_CACHE_TTL;flushWrite();const flushDropsExpired=!searchResponseStore.cache.has(key) && !searchResponseStore.pendingWrites.has(key);return {expiredPending,expiredAfterFlush,keptAge,expiredAtBoundary,flushDropsExpired};} finally {cancelPendingSearchCacheWrites();searchResponseStore.cache.delete(key);Date.now=clock;requestAnimationFrame=raf;cancelAnimationFrame=cancel;}}''')3 unmodified linesdef hold_initial_and_search(self):self.page.evaluate('''() => {cancelSearchPrefetch();searchResponseStore.cache.clear(); initialPayloadCache.clear(); resultSnapshots.snapshots.clear();STATE.query = ''; STATE.page = 1;if (typeof readInitialSearchPayload === 'function') readInitialSearchPayload = () => null;window.initialFlights = []; window.searchFlights = [];84 unmodified linesself.hold_initial_and_search()self.evaluate_bounded('''async () => {initialFlights[0].resolve(payload('seed')); await oldInitial;resultSnapshots.snapshots.clear(); initialPayloadCache.clear(); searchResponseStore.cache.clear();displayedSearchView = null;getReturnPositionTarget = () => ({index:0});readSearchViewport = () => new Promise(resolve => { window.releaseViewport = resolve; });
216 unmodified lines2172182192202212222232 unmodified lines22622722822923023123237 unmodified lines27027127227327427527623 unmodified lines30030130230330430530630730830931031131218 unmodified lines33133233333433533633733833934034134234345 unmodified lines38939039139239339439520 unmodified lines416417418419420421422216 unmodified linesconst body = {page:1, page_size:1};const first = fetchSearchPage(key, '/api/search/shared-rejection', body, firstOwner.signal, 5000);const second = fetchSearchPage(key, '/api/search/shared-rejection', body, secondOwner.signal, 5000);const entry = pendingSearchPages.get(key), joined = entry.listeners.size;const outcomes = Promise.allSettled([first, second]);release();const settled = await outcomes;2 unmodified linessafe:!!error && typeof error.name === 'string' && typeof error.message === 'string',same:error === settled[1].reason,preserved:i < 7 || error === reason,name:error?.name, cleaned:!pendingSearchPages.has(key) && entry.listeners.size === 0});}return cases;} finally { window.fetch = original; }37 unmodified linescases.push({phase, index:i, calls, statuses:settled.map(item => item.status),same:error === settled[1].reason, identity:i < 2 || error === reason,name:error?.name, message:error?.message, status:error?.status ?? null, code:error?.code ?? null,cleaned:![...pendingSearchPages.keys()].some(key => key.includes(query.query))});}return cases;} finally { window.fetch = original; frame.remove(); }23 unmodified linesconst body = {page:1, page_size:1};const first = fetchSearchPage(key, '/api/search/shared-getter', body, undefined, 5000);const second = fetchSearchPage(key, '/api/search/shared-getter', body, undefined, 5000);const entry = pendingSearchPages.get(key);const settled = await Promise.allSettled([first, second]), error = settled[0].reason;cases.push({field:String(field), statuses:settled.map(item => item.status),safe:error instanceof Error && typeof error.message === 'string',same:error === settled[1].reason, cause:error?.cause === getterError,recoverable:isRecoverableSearchError(error),cleaned:!pendingSearchPages.has(key) && entry.listeners.size === 0});}return cases;} finally { window.fetch = original; }18 unmodified linesconst body = {page:1, page_size:1}, key = 'shared-cancel';const cancelled = fetchSearchPage(key, '/api/search/shared-cancel', body, owner.signal, 5000);const remaining = fetchSearchPage(key, '/api/search/shared-cancel', body, undefined, 5000);const entry = pendingSearchPages.get(key);const outcomes = Promise.allSettled([cancelled, remaining]);owner.abort(); release();const settled = await outcomes;return {statuses:settled.map(item => item.status), names:settled.map(item => item.reason?.name),calls, aborted:transportSignal.aborted,cleaned:!pendingSearchPages.has(key) && entry.listeners.size === 0};} finally { window.fetch = original; }}''')self.assertEqual(result, dict(statuses=['rejected', 'rejected'], names=['AbortError', 'Error'],45 unmodified linesdef expire_pending(self, mode):self.page.evaluate('''mode => {window.pagingMode = mode;pendingSearchPages.forEach(entry => { entry.deadline = Date.now() - 1; });document.dispatchEvent(new Event('visibilitychange'));}''', mode)20 unmodified linesObject.defineProperty(document, 'hidden', {configurable: true, value: true});Object.defineProperty(document, 'visibilityState', {configurable: true, value: 'hidden'});document.dispatchEvent(new Event('visibilitychange'));pendingSearchPages.forEach(entry => entry.deadline = Date.now() + 25000);pagingMode = 'normal';Object.defineProperty(document, 'hidden', {configurable: true, value: false});Object.defineProperty(document, 'visibilityState', {configurable: true, value: 'visible'});216 unmodified lines2172182192202212222232 unmodified lines22622722822923023123237 unmodified lines27027127227327427527623 unmodified lines30030130230330430530630730830931031131218 unmodified lines33133233333433533633733833934034134234345 unmodified lines38939039139239339439520 unmodified lines416417418419420421422216 unmodified linesconst body = {page:1, page_size:1};const first = fetchSearchPage(key, '/api/search/shared-rejection', body, firstOwner.signal, 5000);const second = fetchSearchPage(key, '/api/search/shared-rejection', body, secondOwner.signal, 5000);const entry = getSearchTransport().pending.get(key), joined = entry.listeners.size;const outcomes = Promise.allSettled([first, second]);release();const settled = await outcomes;2 unmodified linessafe:!!error && typeof error.name === 'string' && typeof error.message === 'string',same:error === settled[1].reason,preserved:i < 7 || error === reason,name:error?.name, cleaned:!getSearchTransport().pending.has(key) && entry.listeners.size === 0});}return cases;} finally { window.fetch = original; }37 unmodified linescases.push({phase, index:i, calls, statuses:settled.map(item => item.status),same:error === settled[1].reason, identity:i < 2 || error === reason,name:error?.name, message:error?.message, status:error?.status ?? null, code:error?.code ?? null,cleaned:![...getSearchTransport().pending.keys()].some(key => key.includes(query.query))});}return cases;} finally { window.fetch = original; frame.remove(); }23 unmodified linesconst body = {page:1, page_size:1};const first = fetchSearchPage(key, '/api/search/shared-getter', body, undefined, 5000);const second = fetchSearchPage(key, '/api/search/shared-getter', body, undefined, 5000);const entry = getSearchTransport().pending.get(key);const settled = await Promise.allSettled([first, second]), error = settled[0].reason;cases.push({field:String(field), statuses:settled.map(item => item.status),safe:error instanceof Error && typeof error.message === 'string',same:error === settled[1].reason, cause:error?.cause === getterError,recoverable:isRecoverableSearchError(error),cleaned:!getSearchTransport().pending.has(key) && entry.listeners.size === 0});}return cases;} finally { window.fetch = original; }18 unmodified linesconst body = {page:1, page_size:1}, key = 'shared-cancel';const cancelled = fetchSearchPage(key, '/api/search/shared-cancel', body, owner.signal, 5000);const remaining = fetchSearchPage(key, '/api/search/shared-cancel', body, undefined, 5000);const entry = getSearchTransport().pending.get(key);const outcomes = Promise.allSettled([cancelled, remaining]);owner.abort(); release();const settled = await outcomes;return {statuses:settled.map(item => item.status), names:settled.map(item => item.reason?.name),calls, aborted:transportSignal.aborted,cleaned:!getSearchTransport().pending.has(key) && entry.listeners.size === 0};} finally { window.fetch = original; }}''')self.assertEqual(result, dict(statuses=['rejected', 'rejected'], names=['AbortError', 'Error'],45 unmodified linesdef expire_pending(self, mode):self.page.evaluate('''mode => {window.pagingMode = mode;getSearchTransport().pending.forEach(entry => { entry.deadline = Date.now() - 1; });document.dispatchEvent(new Event('visibilitychange'));}''', mode)20 unmodified linesObject.defineProperty(document, 'hidden', {configurable: true, value: true});Object.defineProperty(document, 'visibilityState', {configurable: true, value: 'hidden'});document.dispatchEvent(new Event('visibilitychange'));getSearchTransport().pending.forEach(entry => entry.deadline = Date.now() + 25000);pagingMode = 'normal';Object.defineProperty(document, 'hidden', {configurable: true, value: false});Object.defineProperty(document, 'visibilityState', {configurable: true, value: 'visible'});
160 unmodified lines161162163164165166167160 unmodified linesself.page.evaluate('for(let i=0;i<20;i++)renderVisible()')self.page.wait_for_timeout(800)self.assertEqual(self.page.evaluate('gapTransportCalls'), 3)self.assertFalse(self.page.evaluate('''[...pendingSearchPages.values()].some(entry=>entry.listeners.size && !entry.controller.signal.aborted)'''))self.page.evaluate('rejectGapTransport=false')self.page.locator('#search-window-status button').click()160 unmodified lines161162163164165166167160 unmodified linesself.page.evaluate('for(let i=0;i<20;i++)renderVisible()')self.page.wait_for_timeout(800)self.assertEqual(self.page.evaluate('gapTransportCalls'), 3)self.assertFalse(self.page.evaluate('''[...getSearchTransport().pending.values()].some(entry=>entry.listeners.size && !entry.controller.signal.aborted)'''))self.page.evaluate('rejectGapTransport=false')self.page.locator('#search-window-status button').click()
99 unmodified lines10010110210310410510610710810911011111211339 unmodified lines15315415515615715815911 unmodified lines17117217317417517617799 unmodified linesself.start_pipeline()self.fixture.reach_bottom()self.page.evaluate('''() => {window.pageWork=[];const list=DOM.resultsList,insert=list.insertBefore,write=searchResponseCache.set;// Observe actual row publication, including module-internal renders.list.insertBefore=function(row,before){const result=insert.call(this,row,before);if(STATE._loadedPage>=2 && row.classList?.contains('result-item')) pageWork.push('render');return result;};searchResponseCache.set=function(key,value){if(value.data.page===2) pageWork.push('cache');return write.call(this,key,value);};aheadReleases[2]();39 unmodified linesdef test_matching_saved_pages_avoid_network_and_old_generation_is_rejected(self):result = self.page.evaluate('''async () => {cancelSearchPrefetch();STATE._pageCache={};searchResponseCache.clear();positionPersistence.recentPages.clear();const key=getSearchViewKey();const template={q:STATE.query,page:1,page_size:100};const metadata={generation:'stable',page:1,page_size:100,total:STATE.total,results:STATE.results};rememberSearchPageMetadata(metadata);11 unmodified lineswhile(controllerActive()) await new Promise(resolve=>setTimeout(resolve,0));const reused=Object.keys(STATE._pageCache).map(Number);const calls=networkPages.slice();cancelSearchPrefetch();STATE._pageCache={};searchResponseCache.clear();cached.forEach(entry=>positionPersistence.recentPages.set(JSON.stringify(entry.id), {...entry,generation:'old'}));prefetchSearchPages('/api/search',template);while(controllerActive()) await new Promise(resolve=>setTimeout(resolve,0));99 unmodified lines10010110210310410510610710810911011111211311439 unmodified lines15415515615715815916011 unmodified lines17217317417517617717899 unmodified linesself.start_pipeline()self.fixture.reach_bottom()self.page.evaluate('''() => {window.pageWork=[];const list=DOM.resultsList,insert=list.insertBefore;const cache=searchResponseStore.cache,write=cache.set;// Observe actual row publication, including module-internal renders.list.insertBefore=function(row,before){const result=insert.call(this,row,before);if(STATE._loadedPage>=2 && row.classList?.contains('result-item')) pageWork.push('render');return result;};cache.set=function(key,value){if(value.data.page===2) pageWork.push('cache');return write.call(this,key,value);};aheadReleases[2]();39 unmodified linesdef test_matching_saved_pages_avoid_network_and_old_generation_is_rejected(self):result = self.page.evaluate('''async () => {cancelSearchPrefetch();STATE._pageCache={};searchResponseStore.cache.clear();positionPersistence.recentPages.clear();const key=getSearchViewKey();const template={q:STATE.query,page:1,page_size:100};const metadata={generation:'stable',page:1,page_size:100,total:STATE.total,results:STATE.results};rememberSearchPageMetadata(metadata);11 unmodified lineswhile(controllerActive()) await new Promise(resolve=>setTimeout(resolve,0));const reused=Object.keys(STATE._pageCache).map(Number);const calls=networkPages.slice();cancelSearchPrefetch();STATE._pageCache={};searchResponseStore.cache.clear();cached.forEach(entry=>positionPersistence.recentPages.set(JSON.stringify(entry.id), {...entry,generation:'old'}));prefetchSearchPages('/api/search',template);while(controllerActive()) await new Promise(resolve=>setTimeout(resolve,0));
292 unmodified lines2932942952962972982993003013023033044 unmodified lines309310311312313314315292 unmodified linestop:getResultScrollTop(),text:selection.toString(),revision:measuredHeightRevision};let storage=0,renders=0,measures=0;const native={set:Storage.prototype.setItem,remove:Storage.prototype.removeItem,schedule:scheduleVirtualRender,measure:measureHeights};const observer=new MutationObserver(()=>{});observer.observe(DOM.resultsList,{subtree:true,childList:true,attributes:true,characterData:true});Storage.prototype.setItem=function(...args){storage++;return native.set.apply(this,args)};Storage.prototype.removeItem=function(...args){storage++;return native.remove.apply(this,args)};scheduleVirtualRender=()=>{renders++};measureHeights=()=>{measures++};try {for(let i=0;i<5;i++) refreshResultReaderActions();return {writes:observer.takeRecords().length,storage,renders,measures,4 unmodified linestop:getResultScrollTop(),text:selection.toString(),revision:measuredHeightRevision})};} finally {observer.disconnect();Storage.prototype.setItem=native.set;Storage.prototype.removeItem=native.remove;scheduleVirtualRender=native.schedule;measureHeights=native.measure;}}''')self.assertEqual(result, dict(writes=0, storage=0, renders=0, measures=0,292 unmodified lines2932942952962972982993003013023033043053063073084 unmodified lines313314315316317318319292 unmodified linestop:getResultScrollTop(),text:selection.toString(),revision:measuredHeightRevision};let storage=0,renders=0,measures=0;const native={set:Storage.prototype.setItem,remove:Storage.prototype.removeItem,schedule:scheduleVirtualRender,rect:Element.prototype.getBoundingClientRect};const observer=new MutationObserver(()=>{});observer.observe(DOM.resultsList,{subtree:true,childList:true,attributes:true,characterData:true});Storage.prototype.setItem=function(...args){storage++;return native.set.apply(this,args)};Storage.prototype.removeItem=function(...args){storage++;return native.remove.apply(this,args)};scheduleVirtualRender=()=>{renders++};Element.prototype.getBoundingClientRect=function(){if(this.matches('.result-item')) measures++;return native.rect.call(this);};try {for(let i=0;i<5;i++) refreshResultReaderActions();return {writes:observer.takeRecords().length,storage,renders,measures,4 unmodified linestop:getResultScrollTop(),text:selection.toString(),revision:measuredHeightRevision})};} finally {observer.disconnect();Storage.prototype.setItem=native.set;Storage.prototype.removeItem=native.remove;scheduleVirtualRender=native.schedule;Element.prototype.getBoundingClientRect=native.rect;}}''')self.assertEqual(result, dict(writes=0, storage=0, renders=0, measures=0,
83 unmodified lines8485868788899039 unmodified lines130131132133134135136137138183 unmodified lines3223233243253263273283293303313323333343351 unmodified line3373383393403413423439 unmodified lines3533543553563573583591 unmodified line36136236336436536636719 unmodified lines387388389390391392393106 unmodified lines50050150250350450550650738 unmodified lines54654754854955055155283 unmodified linesisRoot:!path,hasChildren:!!children.length,hasDirectFiles:true,showSelfToggle:!!children.length});STATE.mode='repo';STATE.folderTree=[node('',[node('alpha',[node('alpha/deep',[node('alpha/deep/hit')])]),node('beta')])];STATE.folderTreeCollapsed={};STATE.filterFolderSubtrees=['alpha/deep/hit'];STATE.filterFolderSelfs=['beta'];STATE.filterFolders=['alpha/deep/hit','beta'];DOM.filterFolderSection.style.display='';renderFilterFolderTree();}''')self.page.wait_for_function('!sidebarFolderTree.pending()')before = self.page.evaluate('''()=>({selfs:STATE.filterFolderSelfs.slice(),subtrees:STATE.filterFolderSubtrees.slice(),39 unmodified linesself.page.evaluate('''()=>{STATE.folderTree=[{path:'wide',name:'wide',hasChildren:true,children:Array.from({length:256},(_,i)=>({path:'wide/'+i,name:String(i),hasChildren:false,children:[],hasDirectFiles:true}))}];renderFilterFolderTree();setAllFoldersCollapsed(false);setAllFoldersCollapsed(true);routeRenderId++;STATE.folderTree=[{path:'new',name:'new',hasChildren:false,children:[],hasDirectFiles:true}];renderFilterFolderTree();}''')self.page.wait_for_function('!sidebarFolderTree.pending()')self.assertEqual(self.page.locator('#filter-folder-tree .filter-folder-item').count(), 1)183 unmodified linesvalid += ['older-' + str(i) for i in range(maximum)]stored = [None, 42, True, {}, ['nested']] + validself.page.evaluate("value=>sessionStorage.setItem('voml_search_history', JSON.stringify(value))", stored)self.assertEqual(self.page.evaluate('getHistory()'), valid[:maximum])self.assertEqual(self.page.evaluate("JSON.parse(sessionStorage.getItem('voml_search_history'))"), stored)for raw in ('{broken', 'null', '42'):with self.subTest(raw=raw):self.page.evaluate("raw=>sessionStorage.setItem('voml_search_history', raw)", raw)self.assertEqual(self.page.evaluate('getHistory()'), [])self.page.evaluate("sessionStorage.removeItem('voml_search_history')")self.assertEqual(self.page.evaluate('getHistory()'), [])self.assertEqual(self.page.evaluate('''()=>{const original=Storage.prototype.getItem;try {1 unmodified lineif(key==='voml_search_history') throw new DOMException('Blocked', 'SecurityError');return original.call(this,key);};return getHistory();} finally { Storage.prototype.getItem=original; }}'''), [])9 unmodified linesself.page.wait_for_timeout(180)self.assertTrue(self.page.locator('#search-history-dropdown').is_visible())self.page.keyboard.press('Enter')self.assertEqual(self.page.evaluate('getHistory()'), ['second query'])self.assertTrue(self.page.get_by_role('button', name='搜索:second query', exact=True).evaluate('node=>node===document.activeElement'))self.page.keyboard.press('Escape')self.assertEqual(self.page.evaluate('document.activeElement.id'), 'search-input')1 unmodified linefield.blur()field.focus()self.page.get_by_role('button', name='清空历史', exact=True).press('Enter')self.assertEqual(self.page.evaluate('getHistory()'), [])self.assertEqual(self.page.evaluate('document.activeElement.id'), 'search-input')self.assertTrue(self.page.locator('#search-history-dropdown').is_hidden())19 unmodified linesdef test_single_repository_browser_order_is_not_count_sorted(self):observed = self.page.evaluate("""()=>{const list=document.createElement('div');renderBrowserListItems(list,{folders:[{name:'large',path:'large',count:30},{name:'small',path:'small',count:2},{name:'medium',path:'medium',count:10},106 unmodified linesself.assertEqual(self.page.evaluate('navigations'), [['repo', 'Test']])self.page.evaluate('''()=>{STATE.repo='Test';const list=document.createElement('div');list.className='browser-list';DOM.sidebarContent.replaceChildren(createSidebarBreadcrumb('docs/sub'),list);renderBrowserListItems(list,{folders:[{name:'inner',path:'docs/sub/inner',count:1}],files:[{name:'book',ext:'txt',size:1}]},'Test','docs/sub');window.downloads=[];list.addEventListener('click',event=>{if(event.target.closest('.browser-action')){downloads.push(event.target.textContent);event.stopImmediatePropagation();}38 unmodified linesDOM.filterFolderSection.style.display='';STATE.folderTree=[{name:'docs',path:'docs',count:1,showSelfToggle:true,children:[{name:'child',path:'docs/child',count:1,children:[]}]}];STATE.folderTreeCollapsed={docs:false};renderFilterFolderTree();}''')self.assertEqual(self.page.get_by_role('checkbox', name='选择文件夹:docs', exact=True).count(), 1)self.assertEqual(self.page.get_by_role('checkbox', name='选择文件夹:docs/child', exact=True).count(), 1)83 unmodified lines8485868788899039 unmodified lines130131132133134135136137138183 unmodified lines3223233243253263273283293303313323333343351 unmodified line3373383393403413423439 unmodified lines3533543553563573583591 unmodified line36136236336436536636719 unmodified lines387388389390391392393106 unmodified lines50050150250350450550650750838 unmodified lines54754854955055155255383 unmodified linesisRoot:!path,hasChildren:!!children.length,hasDirectFiles:true,showSelfToggle:!!children.length});STATE.mode='repo';STATE.folderTree=[node('',[node('alpha',[node('alpha/deep',[node('alpha/deep/hit')])]),node('beta')])];STATE.folderTreeCollapsed={};STATE.filterFolderSubtrees=['alpha/deep/hit'];STATE.filterFolderSelfs=['beta'];STATE.filterFolders=['alpha/deep/hit','beta'];DOM.filterFolderSection.style.display='';getSidebarFolderTree().render();}''')self.page.wait_for_function('!sidebarFolderTree.pending()')before = self.page.evaluate('''()=>({selfs:STATE.filterFolderSelfs.slice(),subtrees:STATE.filterFolderSubtrees.slice(),39 unmodified linesself.page.evaluate('''()=>{STATE.folderTree=[{path:'wide',name:'wide',hasChildren:true,children:Array.from({length:256},(_,i)=>({path:'wide/'+i,name:String(i),hasChildren:false,children:[],hasDirectFiles:true}))}];getSidebarFolderTree().render();setAllFoldersCollapsed(false);setAllFoldersCollapsed(true);routeRenderId++;STATE.folderTree=[{path:'new',name:'new',hasChildren:false,children:[],hasDirectFiles:true}];getSidebarFolderTree().render();}''')self.page.wait_for_function('!sidebarFolderTree.pending()')self.assertEqual(self.page.locator('#filter-folder-tree .filter-folder-item').count(), 1)183 unmodified linesvalid += ['older-' + str(i) for i in range(maximum)]stored = [None, 42, True, {}, ['nested']] + validself.page.evaluate("value=>sessionStorage.setItem('voml_search_history', JSON.stringify(value))", stored)self.assertEqual(self.page.evaluate('searchHistoryStore.get()'), valid[:maximum])self.assertEqual(self.page.evaluate("JSON.parse(sessionStorage.getItem('voml_search_history'))"), stored)for raw in ('{broken', 'null', '42'):with self.subTest(raw=raw):self.page.evaluate("raw=>sessionStorage.setItem('voml_search_history', raw)", raw)self.assertEqual(self.page.evaluate('searchHistoryStore.get()'), [])self.page.evaluate("sessionStorage.removeItem('voml_search_history')")self.assertEqual(self.page.evaluate('searchHistoryStore.get()'), [])self.assertEqual(self.page.evaluate('''()=>{const original=Storage.prototype.getItem;try {1 unmodified lineif(key==='voml_search_history') throw new DOMException('Blocked', 'SecurityError');return original.call(this,key);};return searchHistoryStore.get();} finally { Storage.prototype.getItem=original; }}'''), [])9 unmodified linesself.page.wait_for_timeout(180)self.assertTrue(self.page.locator('#search-history-dropdown').is_visible())self.page.keyboard.press('Enter')self.assertEqual(self.page.evaluate('searchHistoryStore.get()'), ['second query'])self.assertTrue(self.page.get_by_role('button', name='搜索:second query', exact=True).evaluate('node=>node===document.activeElement'))self.page.keyboard.press('Escape')self.assertEqual(self.page.evaluate('document.activeElement.id'), 'search-input')1 unmodified linefield.blur()field.focus()self.page.get_by_role('button', name='清空历史', exact=True).press('Enter')self.assertEqual(self.page.evaluate('searchHistoryStore.get()'), [])self.assertEqual(self.page.evaluate('document.activeElement.id'), 'search-input')self.assertTrue(self.page.locator('#search-history-dropdown').is_hidden())19 unmodified linesdef test_single_repository_browser_order_is_not_count_sorted(self):observed = self.page.evaluate("""()=>{const list=document.createElement('div');getSidebarDirectoryView().items(list,{folders:[{name:'large',path:'large',count:30},{name:'small',path:'small',count:2},{name:'medium',path:'medium',count:10},106 unmodified linesself.assertEqual(self.page.evaluate('navigations'), [['repo', 'Test']])self.page.evaluate('''()=>{STATE.repo='Test';const list=document.createElement('div');list.className='browser-list';const directory=getSidebarDirectoryView();DOM.sidebarContent.replaceChildren(directory.breadcrumb('docs/sub'),list);directory.items(list,{folders:[{name:'inner',path:'docs/sub/inner',count:1}],files:[{name:'book',ext:'txt',size:1}]},'Test','docs/sub');window.downloads=[];list.addEventListener('click',event=>{if(event.target.closest('.browser-action')){downloads.push(event.target.textContent);event.stopImmediatePropagation();}38 unmodified linesDOM.filterFolderSection.style.display='';STATE.folderTree=[{name:'docs',path:'docs',count:1,showSelfToggle:true,children:[{name:'child',path:'docs/child',count:1,children:[]}]}];STATE.folderTreeCollapsed={docs:false};getSidebarFolderTree().render();}''')self.assertEqual(self.page.get_by_role('checkbox', name='选择文件夹:docs', exact=True).count(), 1)self.assertEqual(self.page.get_by_role('checkbox', name='选择文件夹:docs/child', exact=True).count(), 1)
195 unmodified lines19619719819920020120260 unmodified lines263264265266267268269270180 unmodified lines45145245345445545645714 unmodified lines47247347447547647747814 unmodified lines493494495496497498499195 unmodified linesself.page.evaluate("ROUTER.navigate('global')")self.page.wait_for_function("STATE.mode==='global' && !STATE.isLoading")self.page.evaluate('''() => {resultSnapshots.snapshots.clear(); searchResponseCache.clear();STATE.filterExtensions=[]; STATE.query='paging-original'; DOM.searchInput.value=STATE.query;scheduleFilterSearch();}''')60 unmodified lineskept = self.page.evaluate('''() => {resultSnapshots.snapshots.clear();resultSnapshots.snapshots.set('small', {bytes: 1024});resultSnapshots.snapshots.set('large', {bytes: SEARCH_VIEW_SNAPSHOT_BYTES_MAX+1});trimSearchViewSnapshots(); return [...resultSnapshots.snapshots.keys()];}''')self.assertEqual(kept, ['small'])180 unmodified linesdef test_window_restore_does_not_fetch_unvisited_prefix(self):self.begin_rebuild('''() => {prefetchNextPage=()=>{}; // Measure the restore-critical set, independently of lookahead.pagingTotal=800;searchResponseCache.clear();const originalKey=[...positionPersistence.positions.keys()].find(key=>JSON.parse(key).query==='paging-original');positionPersistence.positions.get(originalKey).loadedPage=8;const original=fetchPositionPage;window.restoreCalls=[];window.restorePeak=0;let active=0;14 unmodified linesdef test_window_retry_reuses_completed_neighbor(self):self.begin_rebuild('''() => {prefetchNextPage=()=>{};pagingTotal=400;searchResponseCache.clear();const key=[...positionPersistence.positions.keys()].find(key=>JSON.parse(key).query==='paging-original');positionPersistence.positions.get(key).loadedPage=4;const original=fetchPositionPage;window.restoreCalls=[];window.failPage=true;14 unmodified linesdef test_parallel_generation_mismatch_discards_entire_buffer(self):self.begin_rebuild('''() => {pagingTotal=400;searchResponseCache.clear();const key=[...positionPersistence.positions.keys()].find(key=>JSON.parse(key).query==='paging-original');positionPersistence.positions.get(key).loadedPage=4;const original=fetchPositionPage;window.coherent=false;195 unmodified lines19619719819920020120260 unmodified lines263264265266267268269270180 unmodified lines45145245345445545645714 unmodified lines47247347447547647747814 unmodified lines493494495496497498499195 unmodified linesself.page.evaluate("ROUTER.navigate('global')")self.page.wait_for_function("STATE.mode==='global' && !STATE.isLoading")self.page.evaluate('''() => {resultSnapshots.snapshots.clear(); searchResponseStore.cache.clear();STATE.filterExtensions=[]; STATE.query='paging-original'; DOM.searchInput.value=STATE.query;scheduleFilterSearch();}''')60 unmodified lineskept = self.page.evaluate('''() => {resultSnapshots.snapshots.clear();resultSnapshots.snapshots.set('small', {bytes: 1024});resultSnapshots.snapshots.set('large', {bytes: VoiceOfMLSnapshotPolicy.BYTES_MAX+1});resultSnapshots.trim(); return [...resultSnapshots.snapshots.keys()];}''')self.assertEqual(kept, ['small'])180 unmodified linesdef test_window_restore_does_not_fetch_unvisited_prefix(self):self.begin_rebuild('''() => {prefetchNextPage=()=>{}; // Measure the restore-critical set, independently of lookahead.pagingTotal=800;searchResponseStore.cache.clear();const originalKey=[...positionPersistence.positions.keys()].find(key=>JSON.parse(key).query==='paging-original');positionPersistence.positions.get(originalKey).loadedPage=8;const original=fetchPositionPage;window.restoreCalls=[];window.restorePeak=0;let active=0;14 unmodified linesdef test_window_retry_reuses_completed_neighbor(self):self.begin_rebuild('''() => {prefetchNextPage=()=>{};pagingTotal=400;searchResponseStore.cache.clear();const key=[...positionPersistence.positions.keys()].find(key=>JSON.parse(key).query==='paging-original');positionPersistence.positions.get(key).loadedPage=4;const original=fetchPositionPage;window.restoreCalls=[];window.failPage=true;14 unmodified linesdef test_parallel_generation_mismatch_discards_entire_buffer(self):self.begin_rebuild('''() => {pagingTotal=400;searchResponseStore.cache.clear();const key=[...positionPersistence.positions.keys()].find(key=>JSON.parse(key).query==='paging-original');positionPersistence.positions.get(key).loadedPage=4;const original=fetchPositionPage;window.coherent=false;
25 unmodified lines2627282930313231 unmodified lines6465666768697011 unmodified lines82838485868788171 unmodified lines26026126226326426526664 unmodified lines33133233333433533633757 unmodified lines39539639739839940040129 unmodified lines43143243343443543643711 unmodified lines4494504514524534544551 unmodified line4574584594604614624634 unmodified lines46846947047147247347463 unmodified lines53853954054154254354451 unmodified lines59659759859960060160256 unmodified lines65966066166266366466525 unmodified lines# Let startup's shared requests settle before replacing their state.(page or self.page).wait_for_function('''() => getSidebarFilters().status().token > 0 &&getSidebarFilters().status().done === getSidebarFilters().status().token && !API._repoPending &&!API._bootstrapPending && sidebarInitialPending.size === 0''', timeout=15000)def test_deep_sidebar_toggles_skip_full_result_snapshots(self):result = self.page.evaluate('''async () => {31 unmodified linesresult = self.page.evaluate('''() => {const repo = 'x"><img src=x onerror="window.injected=true">';const row = document.createElement('div');row.innerHTML = buildResultHTML({Repo:repo, File:'book', Extension:'txt', Folder:['docs'], Size:1}, 0);DOM.resultsList.append(row);return {images:row.querySelectorAll('img').length,attributes:Array.from(row.querySelectorAll('[data-repo]'), node=>node.dataset.repo),11 unmodified linesDOM.historyToggle.dispatchEvent(new Event('change',{bubbles:true}));STATE.folderTree=[{name:'root',path:'root',count:1,selfCount:0,children:[{name:'child',path:'root/child',count:1,selfCount:1,children:[]}]}];STATE.folderTreeCollapsed={root:true};renderFilterFolderTree();DOM.filterFolderTree.querySelector('.tree-toggle').click();const neutral=captures;DOM.sortSelect.dispatchEvent(new Event('change',{bubbles:true}));171 unmodified linesSTATE.mode='repo';STATE.repo='Test';STATE.repoFull='VoiceOfML/Test';STATE.folderTree=[{path:'docs',name:'docs',count:1,children:[],hasDirectFiles:true}];STATE.filterFolderSelfs=[];STATE.filterFolderSubtrees=[];STATE.filterFolders=[];DOM.filterFolderSection.style.display='';renderFilterFolderTree();}''')self.page.locator('#filter-min-size').fill('3')self.page.locator('#filter-folder-tree input').check()64 unmodified linesSTATE.filterRepos=[];STATE.filterMinSize=null;STATE.filterMaxSize=null;history.replaceState(null,'','/');window.__breadcrumbClick=folder=>{const row=document.createElement('div');row.innerHTML=buildResultHTML({Repo:'VoiceOfML/Test',File:'deep',Extension:'txt',Folder:['docs','子'],Size:1},0);DOM.resultsList.append(row);Array.from(row.querySelectorAll('.path-folder')).find(link=>link.dataset.folder===folder).click();};}''')57 unmodified linesArray.from({length:1000},(_,i)=>({name:'child'+i,path:'root/'+i,count:1,selfCount:1,children:[]}))}];STATE.folderTreeCollapsed={root:true};STATE.filterFolderSubtrees=[]; STATE.filterFolderSelfs=[]; STATE.filterFolders=[];renderFilterFolderTree();const initial=DOM.filterFolderTree.querySelectorAll('.filter-folder-item').length;const root=DOM.filterFolderTree.querySelector('.filter-folder-item');root.querySelector('input').click();29 unmodified lines}return result;};try {renderFilterFolderTree();renderFilterFolderTree();deferred=sidebarFolderTree.pending()>0;}finally {Element.prototype.appendChild=append;}while(sidebarFolderTree.pending()) await new Promise(r=>setTimeout(r,0));const rows=DOM.filterFolderTree.querySelectorAll('.filter-folder-item').length;11 unmodified linesSTATE.folderTree=[{name:'root',path:'root',count:1000,hasChildren:true,children:Array.from({length:1000},(_,i)=>({name:String(i),path:'root/'+i,count:1,hasDirectFiles:true,children:[]}))}];STATE.folderTreeCollapsed={root:true};STATE.filterFolderSubtrees=[];STATE.filterFolderSelfs=[];renderFilterFolderTree();const toggle=DOM.filterFolderTree.querySelector('.tree-toggle');toggle.click();const partial=DOM.filterFolderTree.querySelectorAll('.filter-folder-item').length;toggle.click();await new Promise(r=>setTimeout(r,30));const stopped=DOM.filterFolderTree.querySelectorAll('.filter-folder-item').length===partial && !sidebarFolderTree.pending();1 unmodified linewhile(sidebarFolderTree.pending()) await new Promise(r=>setTimeout(r,10));const final=DOM.filterFolderTree.querySelectorAll('.filter-folder-item').length;const late=DOM.filterFolderTree.querySelector('[data-path="root/999"] input').checked;STATE.folderTree=[{name:'new',path:'new',count:1,hasDirectFiles:true,children:[]}];renderFilterFolderTree();await new Promise(r=>setTimeout(r,30));return {stopped,final,late,current:DOM.filterFolderTree.querySelectorAll('.filter-folder-item').length===1};}''')4 unmodified linesSTATE.folderTree=[{name:'root',path:'root',count:500,hasChildren:true,children:[{name:'branch',path:'root/b',count:500,hasChildren:true,children:Array.from({length:500},(_,i)=>({name:String(i),path:'root/b/'+i,count:1,hasDirectFiles:true,children:[]}))}]}];STATE.folderTreeCollapsed={root:true,'root/b':false};renderFilterFolderTree();const toggle=DOM.filterFolderTree.querySelector('.tree-toggle');toggle.click();toggle.click();const stopped=!sidebarFolderTree.pending();toggle.click();while(sidebarFolderTree.pending()) await new Promise(r=>setTimeout(r,10));63 unmodified linesresult = self.page.evaluate('''async () => {const native=window.fetch, calls=[];API._bootstrapCache=null;API._bootstrapPending=null;API._repoCache=null;API._repoPending=null;sidebarInitialCache.clear();sidebarInitialPending.clear();const expected=[{name:'VoiceOfML/Test',count:1}];window.fetch=url=>{calls.push(url);51 unmodified linesself.wait_for_startup_metadata()result = self.page.evaluate('''async () => {API._bootstrapCache=null;API._bootstrapPending=null;API._repoCache=null;API._repoPending=null;sidebarInitialCache.clear();sidebarInitialPending.clear();const native=window.fetch;let bootstrap=0,repos=0,sidebar=0;const expected=[{name:'VoiceOfML/Test',count:1}];window.fetch=(url,options)=>{56 unmodified linesself.wait_for_startup_metadata()result = self.page.evaluate('''async () => {API._bootstrapCache=null;API._bootstrapPending=null;API._repoCache=null;API._repoPending=null;sidebarInitialCache.clear();sidebarInitialPending.clear();const native=window.fetch, expected=[{name:'VoiceOfML/Test',count:1}], calls=[];window.fetch=url=>{calls.push(url);25 unmodified lines2627282930313231 unmodified lines6465666768697011 unmodified lines82838485868788171 unmodified lines26026126226326426526664 unmodified lines33133233333433533633757 unmodified lines39539639739839940040129 unmodified lines43143243343443543643711 unmodified lines4494504514524534544551 unmodified line4574584594604614624634 unmodified lines46846947047147247347463 unmodified lines53853954054154254354451 unmodified lines59659759859960060160256 unmodified lines65966066166266366466525 unmodified lines# Let startup's shared requests settle before replacing their state.(page or self.page).wait_for_function('''() => getSidebarFilters().status().token > 0 &&getSidebarFilters().status().done === getSidebarFilters().status().token && !API._repoPending &&!API._bootstrapPending && catalog.sidebarInitialPending.size === 0''', timeout=15000)def test_deep_sidebar_toggles_skip_full_result_snapshots(self):result = self.page.evaluate('''async () => {31 unmodified linesresult = self.page.evaluate('''() => {const repo = 'x"><img src=x onerror="window.injected=true">';const row = document.createElement('div');row.innerHTML = getResultRows().buildHTML({Repo:repo, File:'book', Extension:'txt', Folder:['docs'], Size:1}, 0);DOM.resultsList.append(row);return {images:row.querySelectorAll('img').length,attributes:Array.from(row.querySelectorAll('[data-repo]'), node=>node.dataset.repo),11 unmodified linesDOM.historyToggle.dispatchEvent(new Event('change',{bubbles:true}));STATE.folderTree=[{name:'root',path:'root',count:1,selfCount:0,children:[{name:'child',path:'root/child',count:1,selfCount:1,children:[]}]}];STATE.folderTreeCollapsed={root:true};getSidebarFolderTree().render();DOM.filterFolderTree.querySelector('.tree-toggle').click();const neutral=captures;DOM.sortSelect.dispatchEvent(new Event('change',{bubbles:true}));171 unmodified linesSTATE.mode='repo';STATE.repo='Test';STATE.repoFull='VoiceOfML/Test';STATE.folderTree=[{path:'docs',name:'docs',count:1,children:[],hasDirectFiles:true}];STATE.filterFolderSelfs=[];STATE.filterFolderSubtrees=[];STATE.filterFolders=[];DOM.filterFolderSection.style.display='';getSidebarFolderTree().render();}''')self.page.locator('#filter-min-size').fill('3')self.page.locator('#filter-folder-tree input').check()64 unmodified linesSTATE.filterRepos=[];STATE.filterMinSize=null;STATE.filterMaxSize=null;history.replaceState(null,'','/');window.__breadcrumbClick=folder=>{const row=document.createElement('div');row.innerHTML=getResultRows().buildHTML({Repo:'VoiceOfML/Test',File:'deep',Extension:'txt',Folder:['docs','子'],Size:1},0);DOM.resultsList.append(row);Array.from(row.querySelectorAll('.path-folder')).find(link=>link.dataset.folder===folder).click();};}''')57 unmodified linesArray.from({length:1000},(_,i)=>({name:'child'+i,path:'root/'+i,count:1,selfCount:1,children:[]}))}];STATE.folderTreeCollapsed={root:true};STATE.filterFolderSubtrees=[]; STATE.filterFolderSelfs=[]; STATE.filterFolders=[];getSidebarFolderTree().render();const initial=DOM.filterFolderTree.querySelectorAll('.filter-folder-item').length;const root=DOM.filterFolderTree.querySelector('.filter-folder-item');root.querySelector('input').click();29 unmodified lines}return result;};try {getSidebarFolderTree().render();getSidebarFolderTree().render();deferred=sidebarFolderTree.pending()>0;}finally {Element.prototype.appendChild=append;}while(sidebarFolderTree.pending()) await new Promise(r=>setTimeout(r,0));const rows=DOM.filterFolderTree.querySelectorAll('.filter-folder-item').length;11 unmodified linesSTATE.folderTree=[{name:'root',path:'root',count:1000,hasChildren:true,children:Array.from({length:1000},(_,i)=>({name:String(i),path:'root/'+i,count:1,hasDirectFiles:true,children:[]}))}];STATE.folderTreeCollapsed={root:true};STATE.filterFolderSubtrees=[];STATE.filterFolderSelfs=[];getSidebarFolderTree().render();const toggle=DOM.filterFolderTree.querySelector('.tree-toggle');toggle.click();const partial=DOM.filterFolderTree.querySelectorAll('.filter-folder-item').length;toggle.click();await new Promise(r=>setTimeout(r,30));const stopped=DOM.filterFolderTree.querySelectorAll('.filter-folder-item').length===partial && !sidebarFolderTree.pending();1 unmodified linewhile(sidebarFolderTree.pending()) await new Promise(r=>setTimeout(r,10));const final=DOM.filterFolderTree.querySelectorAll('.filter-folder-item').length;const late=DOM.filterFolderTree.querySelector('[data-path="root/999"] input').checked;STATE.folderTree=[{name:'new',path:'new',count:1,hasDirectFiles:true,children:[]}];getSidebarFolderTree().render();await new Promise(r=>setTimeout(r,30));return {stopped,final,late,current:DOM.filterFolderTree.querySelectorAll('.filter-folder-item').length===1};}''')4 unmodified linesSTATE.folderTree=[{name:'root',path:'root',count:500,hasChildren:true,children:[{name:'branch',path:'root/b',count:500,hasChildren:true,children:Array.from({length:500},(_,i)=>({name:String(i),path:'root/b/'+i,count:1,hasDirectFiles:true,children:[]}))}]}];STATE.folderTreeCollapsed={root:true,'root/b':false};getSidebarFolderTree().render();const toggle=DOM.filterFolderTree.querySelector('.tree-toggle');toggle.click();toggle.click();const stopped=!sidebarFolderTree.pending();toggle.click();while(sidebarFolderTree.pending()) await new Promise(r=>setTimeout(r,10));63 unmodified linesresult = self.page.evaluate('''async () => {const native=window.fetch, calls=[];API._bootstrapCache=null;API._bootstrapPending=null;API._repoCache=null;API._repoPending=null;catalog.sidebarInitialCache.clear();catalog.sidebarInitialPending.clear();const expected=[{name:'VoiceOfML/Test',count:1}];window.fetch=url=>{calls.push(url);51 unmodified linesself.wait_for_startup_metadata()result = self.page.evaluate('''async () => {API._bootstrapCache=null;API._bootstrapPending=null;API._repoCache=null;API._repoPending=null;catalog.sidebarInitialCache.clear();catalog.sidebarInitialPending.clear();const native=window.fetch;let bootstrap=0,repos=0,sidebar=0;const expected=[{name:'VoiceOfML/Test',count:1}];window.fetch=(url,options)=>{56 unmodified linesself.wait_for_startup_metadata()result = self.page.evaluate('''async () => {API._bootstrapCache=null;API._bootstrapPending=null;API._repoCache=null;API._repoPending=null;catalog.sidebarInitialCache.clear();catalog.sidebarInitialPending.clear();const native=window.fetch, expected=[{name:'VoiceOfML/Test',count:1}], calls=[];window.fetch=url=>{calls.push(url);
35 unmodified lines36373839404142408 unmodified lines45145245345445545645711 unmodified lines46947047147247347447547647747847948048135 unmodified linesfunction transportFixture() {let now = 0, timerId = 0;const timers = new Map(), calls = [];const c = fixture(['getSearchTransport', 'createSearchPageRequest', 'fetchSearchPage','expireSearchRequests', 'normalizeSearchError', 'suspendSearchRequests', 'resumeSearchRequests'],{DOMException, document:{hidden:false}, APPEND_REQUEST_TIMEOUT:50,Date:{now:()=>now}, scheduleScrollRecovery(){},408 unmodified linesassert.equal(c.state.ready, true);});test('app adapter publishes readable input state and delegates submit with history options', () => {const modules = vm.createContext({});for (const path of ['domain/ownership.js', 'application/controller.js'])vm.runInContext(fs.readFileSync('static/search/input/' + path, 'utf8'), modules);11 unmodified linessubmitSearchQuery(query, options) { queries.push([query, {...options}]); }});c.setupSearchInput();assert.equal(c.searchInputReady, false, 'mounting alone does not complete startup');input.dispatchEvent(new Event('input'));assert.equal(c.searchInputReady, false, 'early input waits for route initialization');assert.equal(c.searchTimer, null);assert.equal(callback, undefined);c.finishInitialSearchInput(c.initialSearchDraftIsCurrent());assert.equal(c.searchInputReady, true, 'the controller publishes completed startup');input.dispatchEvent(new Event('input'));assert.equal(c.searchTimer, 42);callback();35 unmodified lines36373839404142408 unmodified lines45145245345445545645711 unmodified lines46947047147247347447547647747847948048148235 unmodified linesfunction transportFixture() {let now = 0, timerId = 0;const timers = new Map(), calls = [];const c = fixture(['getSearchTransport', 'fetchSearchPage','expireSearchRequests', 'normalizeSearchError', 'suspendSearchRequests', 'resumeSearchRequests'],{DOMException, document:{hidden:false}, APPEND_REQUEST_TIMEOUT:50,Date:{now:()=>now}, scheduleScrollRecovery(){},408 unmodified linesassert.equal(c.state.ready, true);});test('app adapter waits for startup and delegates submit with history options', () => {const modules = vm.createContext({});for (const path of ['domain/ownership.js', 'application/controller.js'])vm.runInContext(fs.readFileSync('static/search/input/' + path, 'utf8'), modules);11 unmodified linessubmitSearchQuery(query, options) { queries.push([query, {...options}]); }});c.setupSearchInput();assert.equal(c.searchTimer, null, 'mounting alone does not schedule a search');input.dispatchEvent(new Event('input'));assert.equal(c.initialSearchDraft, true, 'early input waits for route initialization');assert.equal(c.searchTimer, null);assert.equal(callback, undefined);c.finishInitialSearchInput(c.initialSearchDraftIsCurrent());assert.equal(c.initialSearchDraft, false);assert.equal(c.searchTimer, 42, 'startup schedules the current draft');input.dispatchEvent(new Event('input'));assert.equal(c.searchTimer, 42);callback();
65 unmodified lines6667686970717228 unmodified lines1011021031041051061071081091101111121131141151161171181191204 unmodified lines12512612712812913013113213313413513613713823 unmodified lines16216316416516616716865 unmodified linesconst submissions = [];c.submitSearchQuery = (...args) => { submissions.push(plain(args)); };c.searchHistoryStore = c.VoiceOfMLSearchHistoryStore.create(() => c.sessionStorage);for (const name of ['getSearchHistoryController', 'getHistory', 'saveHistory', 'addHistoryItem', 'renderDropdown', 'hideSearchHistory', 'setupSearchHistory', 'removeHistoryItem']) {const source = app.match(new RegExp('^function ' + name + '\\([^]*?^}', 'm'));// Single-line host wrappers end on their declaration line.const line = app.split('\n').find(line => line.startsWith('function ' + name + '('));28 unmodified linestest('history rejects corrupt session JSON, storage failures, live preference, empty query and capped deduplication', () => {const f = historyFixture(), {c} = f;for (const value of [null, '{bad', 'false', '0', 'null']) { f.setStored(value); assert.deepEqual(plain(c.getHistory()), []); }f.setStored('{"unexpected":true}');assert.deepEqual(plain(c.getHistory()), []);f.setStored(JSON.stringify([null, {}, 1, "valid", ...Array.from({length:25}, (_, i)=>String(i))]));assert.deepEqual(plain(c.getHistory()), ["valid", ...Array.from({length:19}, (_, i)=>String(i))]);c.renderDropdown(); assert.equal(f.rows.length, 20); assert.match(f.dropdown.innerHTML, /history-clear-all/);c.saveHistory([]);for (let i = 0; i < 25; i++) c.addHistoryItem('q' + i);assert.equal(c.getHistory().length, 20); assert.equal(c.getHistory()[19], 'q5');c.addHistoryItem('q12'); assert.equal(c.getHistory()[0], 'q12'); assert.equal(c.getHistory().length, 20);c.addHistoryItem(''); c.STATE.recordHistory = false; c.addHistoryItem('disabled'); assert.equal(c.getHistory()[0], 'q12');c.STATE.recordHistory = true; c.addHistoryItem('live'); assert.equal(c.getHistory()[0], 'live');c.sessionStorage = {getItem() { throw Error('denied'); }, setItem() { throw Error('full'); }};assert.deepEqual(plain(c.getHistory()), []); assert.doesNotThrow(() => c.addHistoryItem('safe'));});test('history keyboard, delete focus, native activation, clear and submission ownership survive extraction', () => {4 unmodified linesf.key('ArrowDown', f.rows[0].text); assert.equal(c.document.activeElement, f.rows[1].text);f.rows[1].del.focus(); c.renderDropdown(); assert.equal(c.document.activeElement, f.rows[1].del);f.dropdown.fire('click', {target: f.rows[1].del, detail: 0});assert.deepEqual(plain(c.getHistory()), ['one', 'three']); assert.equal(c.document.activeElement, f.rows[1].text);f.dropdown.fire('click', {target: f.rows[1].text, detail: 0});assert.deepEqual(f.submissions, [['three', {restore: true, blur: true}]]); assert.equal(c.document.activeElement, f.results);f.input.focus(); assert.ok(f.key('Escape').stopped); assert.equal(c.document.activeElement, f.input); assert.equal(f.dropdown.style.display, 'none');f.input.focus(); f.key('ArrowUp'); assert.equal(c.document.activeElement, f.input);const clear = {closest: selector => selector === '.history-clear-all' ? clear : null};f.dropdown.fire('click', {target: clear, detail: 0});assert.deepEqual(plain(c.getHistory()), []); assert.equal(f.dropdown.style.display, 'none'); assert.equal(c.document.activeElement, f.input);});test('history arrow navigation lets the browser scroll the focused entry into view', () => {23 unmodified linesf.dropdown.fire('mouseleave'); await f.fire(150); assert.equal(f.dropdown.style.display, 'none');f.input.focus(); f.dropdown.fire('touchstart', {target: f.rows[0].text}); f.dropdown.fire('touchcancel'); assert.equal([...f.timers.values()].some(t => t.delay === 600), false);const old = f.rows[0].text; f.dropdown.fire('mousedown', {target: old}); await f.fire(600);f.dropdown.fire('click', {target: old, detail: 1}); assert.equal(f.submissions.length, 0); assert.deepEqual(plain(c.getHistory()), ['two']);f.dropdown.fire('click', {target: f.rows[0].text, detail: 0}); assert.equal(f.submissions.length, 1);f.input.focus(); c.document.fire('pointerdown', {target: f.results}); assert.equal(f.dropdown.style.display, 'none');});65 unmodified lines6667686970717228 unmodified lines1011021031041051061071081091101111121131141151161171181191204 unmodified lines12512612712812913013113213313413513613713823 unmodified lines16216316416516616716865 unmodified linesconst submissions = [];c.submitSearchQuery = (...args) => { submissions.push(plain(args)); };c.searchHistoryStore = c.VoiceOfMLSearchHistoryStore.create(() => c.sessionStorage);for (const name of ['getSearchHistoryController', 'saveHistory', 'addHistoryItem', 'renderDropdown', 'hideSearchHistory', 'setupSearchHistory']) {const source = app.match(new RegExp('^function ' + name + '\\([^]*?^}', 'm'));// Single-line host wrappers end on their declaration line.const line = app.split('\n').find(line => line.startsWith('function ' + name + '('));28 unmodified linestest('history rejects corrupt session JSON, storage failures, live preference, empty query and capped deduplication', () => {const f = historyFixture(), {c} = f;for (const value of [null, '{bad', 'false', '0', 'null']) { f.setStored(value); assert.deepEqual(plain(c.searchHistoryStore.get()), []); }f.setStored('{"unexpected":true}');assert.deepEqual(plain(c.searchHistoryStore.get()), []);f.setStored(JSON.stringify([null, {}, 1, "valid", ...Array.from({length:25}, (_, i)=>String(i))]));assert.deepEqual(plain(c.searchHistoryStore.get()), ["valid", ...Array.from({length:19}, (_, i)=>String(i))]);c.renderDropdown(); assert.equal(f.rows.length, 20); assert.match(f.dropdown.innerHTML, /history-clear-all/);c.saveHistory([]);for (let i = 0; i < 25; i++) c.addHistoryItem('q' + i);assert.equal(c.searchHistoryStore.get().length, 20); assert.equal(c.searchHistoryStore.get()[19], 'q5');c.addHistoryItem('q12'); assert.equal(c.searchHistoryStore.get()[0], 'q12'); assert.equal(c.searchHistoryStore.get().length, 20);c.addHistoryItem(''); c.STATE.recordHistory = false; c.addHistoryItem('disabled'); assert.equal(c.searchHistoryStore.get()[0], 'q12');c.STATE.recordHistory = true; c.addHistoryItem('live'); assert.equal(c.searchHistoryStore.get()[0], 'live');c.sessionStorage = {getItem() { throw Error('denied'); }, setItem() { throw Error('full'); }};assert.deepEqual(plain(c.searchHistoryStore.get()), []); assert.doesNotThrow(() => c.addHistoryItem('safe'));});test('history keyboard, delete focus, native activation, clear and submission ownership survive extraction', () => {4 unmodified linesf.key('ArrowDown', f.rows[0].text); assert.equal(c.document.activeElement, f.rows[1].text);f.rows[1].del.focus(); c.renderDropdown(); assert.equal(c.document.activeElement, f.rows[1].del);f.dropdown.fire('click', {target: f.rows[1].del, detail: 0});assert.deepEqual(plain(c.searchHistoryStore.get()), ['one', 'three']); assert.equal(c.document.activeElement, f.rows[1].text);f.dropdown.fire('click', {target: f.rows[1].text, detail: 0});assert.deepEqual(f.submissions, [['three', {restore: true, blur: true}]]); assert.equal(c.document.activeElement, f.results);f.input.focus(); assert.ok(f.key('Escape').stopped); assert.equal(c.document.activeElement, f.input); assert.equal(f.dropdown.style.display, 'none');f.input.focus(); f.key('ArrowUp'); assert.equal(c.document.activeElement, f.input);const clear = {closest: selector => selector === '.history-clear-all' ? clear : null};f.dropdown.fire('click', {target: clear, detail: 0});assert.deepEqual(plain(c.searchHistoryStore.get()), []); assert.equal(f.dropdown.style.display, 'none'); assert.equal(c.document.activeElement, f.input);});test('history arrow navigation lets the browser scroll the focused entry into view', () => {23 unmodified linesf.dropdown.fire('mouseleave'); await f.fire(150); assert.equal(f.dropdown.style.display, 'none');f.input.focus(); f.dropdown.fire('touchstart', {target: f.rows[0].text}); f.dropdown.fire('touchcancel'); assert.equal([...f.timers.values()].some(t => t.delay === 600), false);const old = f.rows[0].text; f.dropdown.fire('mousedown', {target: old}); await f.fire(600);f.dropdown.fire('click', {target: old, detail: 1}); assert.equal(f.submissions.length, 0); assert.deepEqual(plain(c.searchHistoryStore.get()), ['two']);f.dropdown.fire('click', {target: f.rows[0].text, detail: 0}); assert.equal(f.submissions.length, 1);f.input.focus(); c.document.fire('pointerdown', {target: f.results}); assert.equal(f.dropdown.style.display, 'none');});
9 unmodified lines10111213141516156 unmodified lines1731741751761771789 unmodified linesconst app = fs.readFileSync('static/app.js', 'utf8');const space = fs.existsSync('pyrightconfig.json');const functions = ['getShell', 'toggleTheme', 'applyTheme', 'toggleMobile', 'applyMobileMode','focusSearchSidebar', 'toggleLeftSidebar', 'toggleRightSidebar', 'closeLeftSidebar','closeRightSidebar', 'updateSidebarVisibility'];function fixture() {156 unmodified linesconst inertParent = f.element('inertParent', sidebar); inertParent.inert = true;const inert = f.element('inert', inertParent);sidebar.controls = [disabled, invisible, inert, f.leftControl];f.c.focusSearchSidebar(sidebar); assert.equal(f.document.activeElement, f.leftControl);sidebar.controls.pop(); f.c.focusSearchSidebar(sidebar); assert.equal(f.document.activeElement, sidebar);});9 unmodified lines10111213141516156 unmodified lines1731741751761771789 unmodified linesconst app = fs.readFileSync('static/app.js', 'utf8');const space = fs.existsSync('pyrightconfig.json');const functions = ['getShell', 'toggleTheme', 'applyTheme', 'toggleMobile', 'applyMobileMode','toggleLeftSidebar', 'toggleRightSidebar', 'closeLeftSidebar','closeRightSidebar', 'updateSidebarVisibility'];function fixture() {156 unmodified linesconst inertParent = f.element('inertParent', sidebar); inertParent.inert = true;const inert = f.element('inert', inertParent);sidebar.controls = [disabled, invisible, inert, f.leftControl];f.c.VoiceOfMLShellView.focusSearchSidebar(sidebar); assert.equal(f.document.activeElement, f.leftControl);sidebar.controls.pop(); f.c.VoiceOfMLShellView.focusSearchSidebar(sidebar); assert.equal(f.document.activeElement, sidebar);});
75 unmodified lines7677787980818283848575 unmodified lines} else {c.VSCROLL = c.VoiceOfMLVirtualHeights.createState();vm.runInContext(source.match(/^function getVirtualResults\([^]*?^}/m)[0], c);for (const name of names.filter(n => !['layoutResultScrollSegment', 'reconcileVirtualRows'].includes(n))) {const match = source.match(new RegExp('^function ' + name + '\\([^\\n]*', 'm'));vm.runInContext(match[0], c);}}return {c, STATE, list, container, events, frames, document,flush() { const pending = [...frames.values()]; frames.clear(); for (const fn of pending) fn(); },75 unmodified lines767778798081828384858675 unmodified lines} else {c.VSCROLL = c.VoiceOfMLVirtualHeights.createState();vm.runInContext(source.match(/^function getVirtualResults\([^]*?^}/m)[0], c);for (const name of names.filter(n => !['layoutResultScrollSegment', 'reconcileVirtualRows', 'measureHeights'].includes(n))) {const match = source.match(new RegExp('^function ' + name + '\\([^\\n]*', 'm'));vm.runInContext(match[0], c);}c.measureHeights = c.getVirtualResults().measureHeights;}return {c, STATE, list, container, events, frames, document,flush() { const pending = [...frames.values()]; frames.clear(); for (const fn of pending) fn(); },
27 unmodified lines2829303132333427 unmodified linesassertReaderActive(): void;trustedReaderAssetManifestUrl(url: string): string | null;trustedChapterUrl(path: string, base: string): string | null;trustedChapterResourceUrl(value: string, base: string, attribute: string, manifestBase: string): string | null;trustedChapterReferenceUrl(value: string | null, base: string | null, manifestBase: string): {url: string; fragment: string} | null;readerContentUrl(url: string): string;isReaderGenerationCurrent(kind: string, generation: number): boolean;27 unmodified lines2829303132333427 unmodified linesassertReaderActive(): void;trustedReaderAssetManifestUrl(url: string): string | null;trustedChapterUrl(path: string, base: string): string | null;trustedChapterResourceUrl(raw: string, base: string, manifestBase: string): string | null;trustedChapterReferenceUrl(value: string | null, base: string | null, manifestBase: string): {url: string; fragment: string} | null;readerContentUrl(url: string): string;isReaderGenerationCurrent(kind: string, generation: number): boolean;
32 unmodified lines333435363738395 unmodified lines4546474849505132 unmodified linesexport interface EngineContext {assertReaderActive(): void; readerAbortError(): Error; trackReaderResource(destroy: () => void): () => void;readerAbortController: AbortController; READER_PROXY_TIMEOUT_MS: number;sourceUrl: string; contentUrl: string; PDFJS_WORKER_URL: string; PDFJS_URL: string;PDFJS_WASM_URL: string; PDFJS_CMAP_URL: string; PDFJS_STANDARD_FONT_URL: string;capability: { mode?: string | null }; extension: string; ocrManifestUrl: string | null; pdfV3Manifest: unknown;readerRestorationLoaded: boolean; restorationFailed: boolean; readerRestorationEntry: Restoration | null;5 unmodified linespreparePdfInitialRange(options: {url: string; rangeChunkSize: number}, hooks: RangeHooks): Promise<InitialRange | null>;retryReaderProxy<T>(callback: () => Promise<T>): Promise<T>; retryableReaderProxyError(error: unknown): boolean;loadPdfTaskWithTimeout(pdfjs: PdfModule, options: (url: string) => PdfOptions, url: string, initial?: Initial): Promise<PdfDocument>;loadPdfWithTimeout(pdfjs: PdfModule, options: (url: string) => PdfOptions, target?: string, proxy?: string, takeInitial?: (url: string) => Initial): Promise<PdfDocument>;preloadPdfEngine(): Promise<PdfModule>; loadPdfEngine(): Promise<PdfModule>;preparePdfWorker(pdfjs: PdfModule, firstPage?: boolean, signal?: AbortSignal | null): Promise<PdfModule>;preparePdfWorkerAttempt(pdfjs: PdfModule, attempt: number, firstPage?: boolean, signal?: AbortSignal | null): Promise<PdfModule>;32 unmodified lines333435363738395 unmodified lines4546474849505132 unmodified linesexport interface EngineContext {assertReaderActive(): void; readerAbortError(): Error; trackReaderResource(destroy: () => void): () => void;readerAbortController: AbortController; READER_PROXY_TIMEOUT_MS: number;sourceUrl: string; PDFJS_WORKER_URL: string; PDFJS_URL: string;PDFJS_WASM_URL: string; PDFJS_CMAP_URL: string; PDFJS_STANDARD_FONT_URL: string;capability: { mode?: string | null }; extension: string; ocrManifestUrl: string | null; pdfV3Manifest: unknown;readerRestorationLoaded: boolean; restorationFailed: boolean; readerRestorationEntry: Restoration | null;5 unmodified linespreparePdfInitialRange(options: {url: string; rangeChunkSize: number}, hooks: RangeHooks): Promise<InitialRange | null>;retryReaderProxy<T>(callback: () => Promise<T>): Promise<T>; retryableReaderProxyError(error: unknown): boolean;loadPdfTaskWithTimeout(pdfjs: PdfModule, options: (url: string) => PdfOptions, url: string, initial?: Initial): Promise<PdfDocument>;loadPdfWithTimeout(pdfjs: PdfModule, options: (url: string) => PdfOptions, proxyUrl: string, takeInitial?: (url: string) => Initial): Promise<PdfDocument>;preloadPdfEngine(): Promise<PdfModule>; loadPdfEngine(): Promise<PdfModule>;preparePdfWorker(pdfjs: PdfModule, firstPage?: boolean, signal?: AbortSignal | null): Promise<PdfModule>;preparePdfWorkerAttempt(pdfjs: PdfModule, attempt: number, firstPage?: boolean, signal?: AbortSignal | null): Promise<PdfModule>;
config/types/jsconfig.chapter-worker-strict.json+2
config/types/jsconfig.service-worker-strict.json+2
config/types/jsconfig.strict.json+3
scripts/check_strict_inventory.py+11-6
static/app.js+10-66
static/reader/core/reader-security.js-1
static/reader/core/reader-source.mjs+2-2
static/reader/formats/reader-chapter-format.mjs+35-8
static/reader/pdf/reader-pdf-engine.mjs+6-7
static/reader/pdf/reader-pdf-range-hints.mjs+3-3
static/reader/pdf/reader-pdf-renderer.mjs+3-4
static/reader/search/reader-dom-search.mjs+3-3
static/reader/search/reader-pdf-book-validate.mjs+2-1
static/reader/search/reader-pdf-hit-projection.mjs+2-1
static/reader/ui/reader-speech.mjs+3-4
static/search/results/virtual/application/controller.js-1
static/search/results/window/domain/page.js+1-4
tests/gates/test_quality_inventory.py+26-14
tests/gates/test_static_checks.py+13
tests/gates/test_static_contract.py+3-2
tests/reader/browser/test_reader_host_history_races.py+8-3
tests/reader/browser/test_reader_navigation_host.py+6-6
tests/reader/browser/test_reader_pdf_first_page.py+2-2
tests/reader/browser/test_reader_refactor.py+1-1
tests/reader/chapters/test_chapter_format_validation.mjs+92
tests/reader/core/test_reader_warming.js+14-14
tests/search/baselines/test_sidebar_markup_baseline.mjs+13-17
tests/search/browser/test_browser.py+8-8
tests/search/browser/test_download_lifecycle.py+8-8
tests/search/browser/test_initial_intent_reader_routes.py+10-10
tests/search/browser/test_paging_recovery.py+9-9
tests/search/browser/test_position_window.py+1-1
tests/search/browser/test_prefetch_pipeline.py+5-4
tests/search/browser/test_scroll_stability.py+7-3
tests/search/browser/test_search_accessibility_browser.py+14-13
tests/search/browser/test_search_positions.py+6-6
tests/search/browser/test_sidebar_keyboard.py+13-13
tests/search/reader-navigation/test_search_history_races.mjs+6-5
tests/search/ui/history_quotation_contracts.mjs+12-12
tests/search/ui/shell_contracts.mjs+3-3
tests/search/ui/virtual_results_contracts.mjs+2-1
typings/reader-chapter-format-strict.d.ts+1-1
typings/reader-pdf-engine-strict.d.ts+2-2