vomebook commited on
Commit ·
9bfec5a
1
Parent(s): 74bdc1f
Extract search highlight formatting
Browse files- eslint.config.mjs +2 -1
- jsconfig.check.json +1 -0
- jsconfig.strict.json +1 -0
- scripts/build/check_reader_release.mjs +1 -0
- scripts/build/compose_app.mjs +2 -1
- scripts/check_search_highlight_coverage.mjs +23 -0
- static/app.js +0 -34
- static/index.html +1 -0
- static/reader-resources.js +1 -0
- static/search/highlight.js +47 -0
- tests/test_reader_navigation_host.py +12 -0
- tests/test_search_highlight_contract.js +69 -0
- tests/test_search_record_path_build.mjs +7 -0
- tests/test_static_checks.py +54 -0
- typings/reader-globals.d.ts +3 -0
eslint.config.mjs
CHANGED
|
@@ -37,7 +37,8 @@ export default [
|
|
| 37 |
{ files: ["static/**/*.js"], languageOptions: { sourceType: "script" } },
|
| 38 |
{ files: ["static/app.js"], languageOptions: { globals: {
|
| 39 |
bytesToDisplay: "readonly", fmtSizeUrl: "readonly", parseSizeStr: "readonly",
|
| 40 |
-
buildRecordRelativePath: "readonly", encodeRecordPath: "readonly"
|
|
|
|
| 41 |
} } },
|
| 42 |
{ files: ["static/**/*.mjs", "static/**/reader.js", "static/**/reader-pdf-text.js", "static/**/reader-book-text.js"],
|
| 43 |
languageOptions: { sourceType: "module" } },
|
|
|
|
| 37 |
{ files: ["static/**/*.js"], languageOptions: { sourceType: "script" } },
|
| 38 |
{ files: ["static/app.js"], languageOptions: { globals: {
|
| 39 |
bytesToDisplay: "readonly", fmtSizeUrl: "readonly", parseSizeStr: "readonly",
|
| 40 |
+
buildRecordRelativePath: "readonly", encodeRecordPath: "readonly",
|
| 41 |
+
escapeHTML: "readonly", getHighlightRegex: "readonly", highlightText: "readonly"
|
| 42 |
} } },
|
| 43 |
{ files: ["static/**/*.mjs", "static/**/reader.js", "static/**/reader-pdf-text.js", "static/**/reader-book-text.js"],
|
| 44 |
languageOptions: { sourceType: "module" } },
|
jsconfig.check.json
CHANGED
|
@@ -82,6 +82,7 @@
|
|
| 82 |
"static/search/search-session.js",
|
| 83 |
"static/search/size-format.js",
|
| 84 |
"static/search/record-path.js",
|
|
|
|
| 85 |
"static/tts-client.js",
|
| 86 |
"static/app.js",
|
| 87 |
"static/reader.js",
|
|
|
|
| 82 |
"static/search/search-session.js",
|
| 83 |
"static/search/size-format.js",
|
| 84 |
"static/search/record-path.js",
|
| 85 |
+
"static/search/highlight.js",
|
| 86 |
"static/tts-client.js",
|
| 87 |
"static/app.js",
|
| 88 |
"static/reader.js",
|
jsconfig.strict.json
CHANGED
|
@@ -18,6 +18,7 @@
|
|
| 18 |
"static/search/search-session.js",
|
| 19 |
"static/search/size-format.js",
|
| 20 |
"static/search/record-path.js",
|
|
|
|
| 21 |
"static/reader/pdf/reader-engine-preload.js",
|
| 22 |
"static/reader/formats/reader-chapter-repository.js",
|
| 23 |
"static/reader/formats/reader-section-virtualizer.js",
|
|
|
|
| 18 |
"static/search/search-session.js",
|
| 19 |
"static/search/size-format.js",
|
| 20 |
"static/search/record-path.js",
|
| 21 |
+
"static/search/highlight.js",
|
| 22 |
"static/reader/pdf/reader-engine-preload.js",
|
| 23 |
"static/reader/formats/reader-chapter-repository.js",
|
| 24 |
"static/reader/formats/reader-section-virtualizer.js",
|
scripts/build/check_reader_release.mjs
CHANGED
|
@@ -204,6 +204,7 @@ function crossCheck(githubRoot, hfRoot) {
|
|
| 204 |
"search/download-controller.js",
|
| 205 |
"search/size-format.js",
|
| 206 |
"search/record-path.js",
|
|
|
|
| 207 |
"search/reader-navigation.js",
|
| 208 |
"reader.css",
|
| 209 |
"reader/core/reader-request-manager.js",
|
|
|
|
| 204 |
"search/download-controller.js",
|
| 205 |
"search/size-format.js",
|
| 206 |
"search/record-path.js",
|
| 207 |
+
"search/highlight.js",
|
| 208 |
"search/reader-navigation.js",
|
| 209 |
"reader.css",
|
| 210 |
"reader/core/reader-request-manager.js",
|
scripts/build/compose_app.mjs
CHANGED
|
@@ -6,7 +6,8 @@ import { pathToFileURL } from "node:url";
|
|
| 6 |
// Keep classic-script globals for the host; each dependency owns its own scope.
|
| 7 |
export const APP_DEPENDENCIES = Object.freeze([
|
| 8 |
"reader-resources.js", "reader/core/reader-contract.js", "search/reader-navigation.js",
|
| 9 |
-
"search/search-session.js", "search/download-controller.js", "search/size-format.js", "search/record-path.js"
|
|
|
|
| 10 |
]);
|
| 11 |
|
| 12 |
export function stripBundledScripts(html) {
|
|
|
|
| 6 |
// Keep classic-script globals for the host; each dependency owns its own scope.
|
| 7 |
export const APP_DEPENDENCIES = Object.freeze([
|
| 8 |
"reader-resources.js", "reader/core/reader-contract.js", "search/reader-navigation.js",
|
| 9 |
+
"search/search-session.js", "search/download-controller.js", "search/size-format.js", "search/record-path.js",
|
| 10 |
+
"search/highlight.js"
|
| 11 |
]);
|
| 12 |
|
| 13 |
export function stripBundledScripts(html) {
|
scripts/check_search_highlight_coverage.mjs
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import {spawnSync} from "node:child_process";
|
| 2 |
+
|
| 3 |
+
// Node 26/V8 scope: search/highlight.js and its pinned behavior contracts.
|
| 4 |
+
// The unhit branch guards an empty RegExp match, which ordinary escaped terms
|
| 5 |
+
// cannot produce. Reject an unloaded source or any passing-but-empty report.
|
| 6 |
+
const minimum = [100, 95.45, 100];
|
| 7 |
+
const result = spawnSync(process.execPath, [
|
| 8 |
+
"--test", "--test-reporter=tap", "--experimental-test-coverage",
|
| 9 |
+
"--test-coverage-include=**/static/search/highlight.js",
|
| 10 |
+
...minimum.map((value, index) => `--test-coverage-${["lines", "branches", "functions"][index]}=${value}`),
|
| 11 |
+
"tests/test_search_highlight_contract.js"
|
| 12 |
+
], {encoding: "utf8"});
|
| 13 |
+
if (result.stdout) process.stdout.write(result.stdout);
|
| 14 |
+
if (result.stderr) process.stderr.write(result.stderr);
|
| 15 |
+
if (result.error) throw result.error;
|
| 16 |
+
const rows = (result.stdout || "").split(/\r?\n/).flatMap(line => {
|
| 17 |
+
const match = /^\s*#\s*highlight\.js\s*\|\s*(\d+(?:\.\d+)?)\s*\|\s*(\d+(?:\.\d+)?)\s*\|\s*(\d+(?:\.\d+)?)\s*\|/.exec(line);
|
| 18 |
+
return match ? [match.slice(1).map(Number)] : [];
|
| 19 |
+
});
|
| 20 |
+
if (result.status !== 0 || rows.length !== 1 || rows[0].some((value, index) => value < minimum[index])) {
|
| 21 |
+
console.error("Search highlight coverage requires passing tests and exactly one source row above each minimum");
|
| 22 |
+
process.exitCode = 1;
|
| 23 |
+
}
|
static/app.js
CHANGED
|
@@ -2187,11 +2187,6 @@ function setSearchInputValue(value) {
|
|
| 2187 |
syncSearchInputState();
|
| 2188 |
}
|
| 2189 |
|
| 2190 |
-
const HTML_ESCAPE_MAP = { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" };
|
| 2191 |
-
|
| 2192 |
-
function escapeHTML(str) {
|
| 2193 |
-
return String(str).replace(/[&<>"']/g, (ch) => HTML_ESCAPE_MAP[ch]);
|
| 2194 |
-
}
|
| 2195 |
const sizeCache = {};
|
| 2196 |
|
| 2197 |
function formatSize(bytes) {
|
|
@@ -2212,35 +2207,6 @@ function getFileIconType(ext) {
|
|
| 2212 |
return FILE_ICON_MAP[key] || "file";
|
| 2213 |
}
|
| 2214 |
|
| 2215 |
-
const highlightRegexCache = new Map();
|
| 2216 |
-
|
| 2217 |
-
// One alternation over the raw text (longest term first), so a later term can
|
| 2218 |
-
// never match inside an earlier <mark> tag or an HTML entity.
|
| 2219 |
-
function getHighlightRegex(query) {
|
| 2220 |
-
if (highlightRegexCache.has(query)) return highlightRegexCache.get(query);
|
| 2221 |
-
const terms = [...new Set(query.split(/\s+/).filter((t) => t.length > 0))]
|
| 2222 |
-
.sort((a, b) => b.length - a.length)
|
| 2223 |
-
.map((tok) => tok.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
|
| 2224 |
-
const regex = terms.length ? new RegExp(terms.join("|"), "gi") : null;
|
| 2225 |
-
if (highlightRegexCache.size >= 20) highlightRegexCache.delete(highlightRegexCache.keys().next().value);
|
| 2226 |
-
highlightRegexCache.set(query, regex);
|
| 2227 |
-
return regex;
|
| 2228 |
-
}
|
| 2229 |
-
|
| 2230 |
-
function highlightText(text, query) {
|
| 2231 |
-
if (!query || !text) return escapeHTML(text);
|
| 2232 |
-
const regex = getHighlightRegex(query);
|
| 2233 |
-
if (!regex) return escapeHTML(text);
|
| 2234 |
-
const source = String(text);
|
| 2235 |
-
let result = "", last = 0;
|
| 2236 |
-
for (const match of source.matchAll(regex)) {
|
| 2237 |
-
if (!match[0]) continue;
|
| 2238 |
-
result += escapeHTML(source.slice(last, match.index)) + "<mark>" + escapeHTML(match[0]) + "</mark>";
|
| 2239 |
-
last = match.index + match[0].length;
|
| 2240 |
-
}
|
| 2241 |
-
return result + escapeHTML(source.slice(last));
|
| 2242 |
-
}
|
| 2243 |
-
|
| 2244 |
function toMirrorURL(url) {
|
| 2245 |
if (!url) return url;
|
| 2246 |
try {
|
|
|
|
| 2187 |
syncSearchInputState();
|
| 2188 |
}
|
| 2189 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2190 |
const sizeCache = {};
|
| 2191 |
|
| 2192 |
function formatSize(bytes) {
|
|
|
|
| 2207 |
return FILE_ICON_MAP[key] || "file";
|
| 2208 |
}
|
| 2209 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2210 |
function toMirrorURL(url) {
|
| 2211 |
if (!url) return url;
|
| 2212 |
try {
|
static/index.html
CHANGED
|
@@ -311,6 +311,7 @@ if ("serviceWorker" in navigator) {
|
|
| 311 |
<script src="/static/search/download-controller.js"></script>
|
| 312 |
<script src="/static/search/size-format.js"></script>
|
| 313 |
<script src="/static/search/record-path.js"></script>
|
|
|
|
| 314 |
<script src="/static/app.js"></script>
|
| 315 |
</body>
|
| 316 |
</html>
|
|
|
|
| 311 |
<script src="/static/search/download-controller.js"></script>
|
| 312 |
<script src="/static/search/size-format.js"></script>
|
| 313 |
<script src="/static/search/record-path.js"></script>
|
| 314 |
+
<script src="/static/search/highlight.js"></script>
|
| 315 |
<script src="/static/app.js"></script>
|
| 316 |
</body>
|
| 317 |
</html>
|
static/reader-resources.js
CHANGED
|
@@ -192,6 +192,7 @@
|
|
| 192 |
"search/download-controller.js",
|
| 193 |
"search/size-format.js",
|
| 194 |
"search/record-path.js",
|
|
|
|
| 195 |
"style.css",
|
| 196 |
...(project === "github" ? ["search/index-worker.js"] : []),
|
| 197 |
"app.js"
|
|
|
|
| 192 |
"search/download-controller.js",
|
| 193 |
"search/size-format.js",
|
| 194 |
"search/record-path.js",
|
| 195 |
+
"search/highlight.js",
|
| 196 |
"style.css",
|
| 197 |
...(project === "github" ? ["search/index-worker.js"] : []),
|
| 198 |
"app.js"
|
static/search/highlight.js
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Escape before insertion and match raw text so terms never match markup or entities.
|
| 2 |
+
{
|
| 3 |
+
const HTML_ESCAPE_MAP = /** @type {Record<string, string>} */ ({"&": "&", "<": "<", ">": ">", '"': """, "'": "'"});
|
| 4 |
+
/** @param {unknown} str @returns {string} */
|
| 5 |
+
function escapeSearchHTML(str) {
|
| 6 |
+
return String(str).replace(/[&<>"']/g, (ch) => HTML_ESCAPE_MAP[ch]);
|
| 7 |
+
}
|
| 8 |
+
|
| 9 |
+
/** @type {Map<string, RegExp | null>} */
|
| 10 |
+
const highlightRegexCache = new Map();
|
| 11 |
+
|
| 12 |
+
// One alternation over the raw text (longest term first), so a later term can
|
| 13 |
+
// never match inside an earlier <mark> tag or an HTML entity.
|
| 14 |
+
/** @param {string} query @returns {RegExp | null} */
|
| 15 |
+
function searchHighlightRegex(query) {
|
| 16 |
+
if (highlightRegexCache.has(query)) return /** @type {RegExp | null} */ (highlightRegexCache.get(query));
|
| 17 |
+
const terms = [...new Set(query.split(/\s+/).filter((t) => t.length > 0))]
|
| 18 |
+
.sort((a, b) => b.length - a.length)
|
| 19 |
+
.map((tok) => tok.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
|
| 20 |
+
const regex = terms.length ? new RegExp(terms.join("|"), "gi") : null;
|
| 21 |
+
if (highlightRegexCache.size >= 20) highlightRegexCache.delete(/** @type {string} */ (highlightRegexCache.keys().next().value));
|
| 22 |
+
highlightRegexCache.set(query, regex);
|
| 23 |
+
return regex;
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
/** @param {unknown} text @param {string | null | undefined} query @returns {string} */
|
| 27 |
+
function highlightSearchText(text, query) {
|
| 28 |
+
if (!query || !text) return escapeSearchHTML(text);
|
| 29 |
+
const regex = searchHighlightRegex(query);
|
| 30 |
+
if (!regex) return escapeSearchHTML(text);
|
| 31 |
+
const source = String(text);
|
| 32 |
+
let result = "", last = 0;
|
| 33 |
+
for (const match of source.matchAll(regex)) {
|
| 34 |
+
if (!match[0]) continue;
|
| 35 |
+
const index = /** @type {number} */ (match.index);
|
| 36 |
+
result += escapeSearchHTML(source.slice(last, index)) + "<mark>" + escapeSearchHTML(match[0]) + "</mark>";
|
| 37 |
+
last = index + match[0].length;
|
| 38 |
+
}
|
| 39 |
+
return result + escapeSearchHTML(source.slice(last));
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
/** @type {typeof globalThis & {escapeHTML: typeof escapeHTML, getHighlightRegex: typeof getHighlightRegex, highlightText: typeof highlightText}} */
|
| 43 |
+
const globals = globalThis;
|
| 44 |
+
globals.escapeHTML = escapeSearchHTML;
|
| 45 |
+
globals.getHighlightRegex = searchHighlightRegex;
|
| 46 |
+
globals.highlightText = highlightSearchText;
|
| 47 |
+
}
|
tests/test_reader_navigation_host.py
CHANGED
|
@@ -48,6 +48,18 @@ process.stdout.write(stripBundledScripts(readFileSync('static/index.html','utf8'
|
|
| 48 |
self.assertTrue(page.evaluate('typeof VoiceOfMLDownloadController.createDownloadController === "function"'))
|
| 49 |
self.assertEqual(page.evaluate('parseSizeStr(fmtSizeUrl(1048577))'), 1048577)
|
| 50 |
self.assertEqual(page.evaluate('bytesToDisplay(0).unit'), 'B')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
record = {'Repo': 'VoiceOfML/Test', 'File': 'a #?%.jpg', 'Extension': 'jpg', 'Folder': ['目录', 'sub dir']}
|
| 52 |
encoded = '%E7%9B%AE%E5%BD%95/sub%20dir/a%20%23%3F%25.jpg.jpg'
|
| 53 |
base = 'https://huggingface.co/datasets/VoiceOfML/Test/'
|
|
|
|
| 48 |
self.assertTrue(page.evaluate('typeof VoiceOfMLDownloadController.createDownloadController === "function"'))
|
| 49 |
self.assertEqual(page.evaluate('parseSizeStr(fmtSizeUrl(1048577))'), 1048577)
|
| 50 |
self.assertEqual(page.evaluate('bytesToDisplay(0).unit'), 'B')
|
| 51 |
+
for current in (self.page, page):
|
| 52 |
+
highlighted = current.evaluate('''() => {
|
| 53 |
+
const input = '<img src=x onerror="alert(1)"> Tom & abcab';
|
| 54 |
+
const host = document.createElement('div');
|
| 55 |
+
host.innerHTML = highlightText(input, 'img tom amp ab abc');
|
| 56 |
+
return {html: host.innerHTML, text: host.textContent, images: host.querySelectorAll('img').length,
|
| 57 |
+
marks: [...host.querySelectorAll('mark')].map(node => node.textContent)};
|
| 58 |
+
}''')
|
| 59 |
+
self.assertEqual(highlighted['text'], '<img src=x onerror="alert(1)"> Tom & abcab')
|
| 60 |
+
self.assertEqual(highlighted['images'], 0)
|
| 61 |
+
self.assertEqual(highlighted['marks'], ['img', 'Tom', 'abc', 'ab'])
|
| 62 |
+
self.assertIn('&', highlighted['html'])
|
| 63 |
record = {'Repo': 'VoiceOfML/Test', 'File': 'a #?%.jpg', 'Extension': 'jpg', 'Folder': ['目录', 'sub dir']}
|
| 64 |
encoded = '%E7%9B%AE%E5%BD%95/sub%20dir/a%20%23%3F%25.jpg.jpg'
|
| 65 |
base = 'https://huggingface.co/datasets/VoiceOfML/Test/'
|
tests/test_search_highlight_contract.js
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const assert = require("node:assert/strict");
|
| 2 |
+
const fs = require("node:fs");
|
| 3 |
+
const path = require("node:path");
|
| 4 |
+
const test = require("node:test");
|
| 5 |
+
const vm = require("node:vm");
|
| 6 |
+
|
| 7 |
+
// Expectations were pinned against the original app.js before extraction.
|
| 8 |
+
function extractedFunctions() {
|
| 9 |
+
const context = vm.createContext({});
|
| 10 |
+
const filename = path.join(__dirname, "../static/search/highlight.js");
|
| 11 |
+
vm.runInContext(fs.readFileSync(filename, "utf8"), context, {filename});
|
| 12 |
+
return {context, escapeHTML: context.escapeHTML, highlightText: context.highlightText,
|
| 13 |
+
getHighlightRegex: context.getHighlightRegex};
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
test("HTML escaping preserves text and protects attribute and markup delimiters", () => {
|
| 17 |
+
const {escapeHTML} = extractedFunctions();
|
| 18 |
+
for (const [input, expected] of [
|
| 19 |
+
["A&B <tag> \" ' 中文", "A&B <tag> " ' 中文"],
|
| 20 |
+
["&", "&amp;"],
|
| 21 |
+
["", ""],
|
| 22 |
+
[null, "null"],
|
| 23 |
+
[undefined, "undefined"],
|
| 24 |
+
[0, "0"],
|
| 25 |
+
[false, "false"]
|
| 26 |
+
]) assert.equal(escapeHTML(input), expected);
|
| 27 |
+
});
|
| 28 |
+
|
| 29 |
+
test("highlighting matches raw text without marking tags or encoded entities", () => {
|
| 30 |
+
const {highlightText} = extractedFunctions();
|
| 31 |
+
const cases = [
|
| 32 |
+
["Tom & Jerry", "tom amp", "<mark>Tom</mark> & Jerry"],
|
| 33 |
+
["abcab", "ab abc", "<mark>abc</mark><mark>ab</mark>"],
|
| 34 |
+
["<img src=x onerror='x'>", "img", "<<mark>img</mark> src=x onerror='x'>"],
|
| 35 |
+
["<script>alert('x')</script>", "script", "<<mark>script</mark>>alert('x')</<mark>script</mark>>"],
|
| 36 |
+
["A+B a.b [C] $5 (x)", "a+b a.b [c] $5 (x)",
|
| 37 |
+
"<mark>A+B</mark> <mark>a.b</mark> <mark>[C]</mark> <mark>$5</mark> <mark>(x)</mark>"],
|
| 38 |
+
["中文😀 中文", "中文😀", "<mark>中文😀</mark> 中文"],
|
| 39 |
+
["a & b", " ", "a & b"],
|
| 40 |
+
["a & b", "", "a & b"],
|
| 41 |
+
[null, "a", "null"],
|
| 42 |
+
[undefined, "a", "undefined"],
|
| 43 |
+
[0, "a", "0"]
|
| 44 |
+
];
|
| 45 |
+
for (const [text, query, expected] of cases) assert.equal(highlightText(text, query), expected);
|
| 46 |
+
});
|
| 47 |
+
|
| 48 |
+
test("highlight regexp is case-insensitive, deduplicated, reusable and literal", () => {
|
| 49 |
+
const {getHighlightRegex, highlightText} = extractedFunctions();
|
| 50 |
+
const regex = getHighlightRegex("ab ABC ab");
|
| 51 |
+
assert.equal(regex.flags, "gi");
|
| 52 |
+
assert.equal(regex.source, "ABC|ab");
|
| 53 |
+
assert.equal(highlightText("AbC ab AB", "ab ABC ab"), "<mark>AbC</mark> <mark>ab</mark> <mark>AB</mark>");
|
| 54 |
+
assert.equal(highlightText("AB", "ab ABC ab"), "<mark>AB</mark>");
|
| 55 |
+
assert.equal(regex.lastIndex, 0);
|
| 56 |
+
assert.equal(getHighlightRegex(" "), null);
|
| 57 |
+
assert.throws(() => getHighlightRegex(42), {name: "TypeError"});
|
| 58 |
+
});
|
| 59 |
+
|
| 60 |
+
test("highlight cache is bounded FIFO and a hit does not change insertion order", () => {
|
| 61 |
+
const {getHighlightRegex} = extractedFunctions();
|
| 62 |
+
const first = getHighlightRegex("key0");
|
| 63 |
+
const second = getHighlightRegex("key1");
|
| 64 |
+
for (let i = 2; i < 20; i++) getHighlightRegex(`key${i}`);
|
| 65 |
+
assert.equal(getHighlightRegex("key0"), first);
|
| 66 |
+
getHighlightRegex("key20");
|
| 67 |
+
assert.equal(getHighlightRegex("key1"), second);
|
| 68 |
+
assert.notEqual(getHighlightRegex("key0"), first);
|
| 69 |
+
});
|
tests/test_search_record_path_build.mjs
CHANGED
|
@@ -7,15 +7,22 @@ const resources = createRequire(import.meta.url)("../static/reader-resources.js"
|
|
| 7 |
const html = readFileSync("static/index.html", "utf8");
|
| 8 |
const worker = readFileSync("static/sw.js", "utf8");
|
| 9 |
const moduleName = "search/record-path.js";
|
|
|
|
| 10 |
assert.equal(APP_DEPENDENCIES.filter(name => name === moduleName).length, 1);
|
| 11 |
assert.equal((html.match(/<script src="[^"\n]*search\/record-path\.js"><\/script>/g) || []).length, 1);
|
| 12 |
assert.ok(html.indexOf(moduleName) < html.lastIndexOf("app.js"));
|
| 13 |
const bundled = stripBundledScripts(html);
|
| 14 |
assert.doesNotMatch(bundled, /<script src="[^"\n]*search\/record-path\.js"/);
|
| 15 |
assert.equal((bundled.match(/<script\s+src=/g) || []).length, 1);
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
for (const project of ["github", "hf"]) {
|
| 17 |
assert.equal(resources.buildFiles(project).filter(name => name === moduleName).length, 1);
|
|
|
|
| 18 |
}
|
| 19 |
assert.match(worker, /["']\/(?:search\/)?static\/app\.js["']/);
|
| 20 |
assert.doesNotMatch(worker, /["']\/(?:search\/)?static\/search\/record-path\.js["']/);
|
|
|
|
| 21 |
console.log("record path source and bundled shell/SW contracts preserved");
|
|
|
|
| 7 |
const html = readFileSync("static/index.html", "utf8");
|
| 8 |
const worker = readFileSync("static/sw.js", "utf8");
|
| 9 |
const moduleName = "search/record-path.js";
|
| 10 |
+
const highlightName = "search/highlight.js";
|
| 11 |
assert.equal(APP_DEPENDENCIES.filter(name => name === moduleName).length, 1);
|
| 12 |
assert.equal((html.match(/<script src="[^"\n]*search\/record-path\.js"><\/script>/g) || []).length, 1);
|
| 13 |
assert.ok(html.indexOf(moduleName) < html.lastIndexOf("app.js"));
|
| 14 |
const bundled = stripBundledScripts(html);
|
| 15 |
assert.doesNotMatch(bundled, /<script src="[^"\n]*search\/record-path\.js"/);
|
| 16 |
assert.equal((bundled.match(/<script\s+src=/g) || []).length, 1);
|
| 17 |
+
assert.equal(APP_DEPENDENCIES.filter(name => name === highlightName).length, 1);
|
| 18 |
+
assert.equal((html.match(/<script src="[^"\n]*search\/highlight\.js"><\/script>/g) || []).length, 1);
|
| 19 |
+
assert.ok(html.indexOf(highlightName) < html.lastIndexOf("app.js"));
|
| 20 |
+
assert.doesNotMatch(bundled, /<script src="[^"\n]*search\/highlight\.js"/);
|
| 21 |
for (const project of ["github", "hf"]) {
|
| 22 |
assert.equal(resources.buildFiles(project).filter(name => name === moduleName).length, 1);
|
| 23 |
+
assert.equal(resources.buildFiles(project).filter(name => name === highlightName).length, 1);
|
| 24 |
}
|
| 25 |
assert.match(worker, /["']\/(?:search\/)?static\/app\.js["']/);
|
| 26 |
assert.doesNotMatch(worker, /["']\/(?:search\/)?static\/search\/record-path\.js["']/);
|
| 27 |
+
assert.doesNotMatch(worker, /["']\/(?:search\/)?static\/search\/highlight\.js["']/);
|
| 28 |
console.log("record path source and bundled shell/SW contracts preserved");
|
tests/test_static_checks.py
CHANGED
|
@@ -236,6 +236,60 @@ class StaticGateTests(unittest.TestCase):
|
|
| 236 |
self.assert_check(result, False, "TS2322")
|
| 237 |
|
| 238 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 239 |
def test_search_record_path_coverage_gate_fails_closed(self):
|
| 240 |
paths = ["static/search/record-path.js", "scripts/check_search_record_path_coverage.mjs",
|
| 241 |
"tests/test_search_record_path.js", "static/app.js"]
|
|
|
|
| 236 |
self.assert_check(result, False, "TS2322")
|
| 237 |
|
| 238 |
|
| 239 |
+
def test_search_highlight_coverage_gate_fails_closed(self):
|
| 240 |
+
paths = ["static/search/highlight.js", "scripts/check_search_highlight_coverage.mjs",
|
| 241 |
+
"tests/test_search_highlight_contract.js"]
|
| 242 |
+
for path in paths:
|
| 243 |
+
target = self.root / path
|
| 244 |
+
target.parent.mkdir(parents=True, exist_ok=True)
|
| 245 |
+
shutil.copyfile(ROOT / path, target)
|
| 246 |
+
check = ["node", "scripts/check_search_highlight_coverage.mjs"]
|
| 247 |
+
self.assert_check(self.run_check(*check), True, "highlight.js")
|
| 248 |
+
test = self.root / paths[2]
|
| 249 |
+
test.write_text('require("node:test")("empty", () => {});\n')
|
| 250 |
+
self.assert_check(self.run_check(*check), False, "exactly one source row")
|
| 251 |
+
test.write_text('throw new Error("failed highlight test");\n')
|
| 252 |
+
self.assert_check(self.run_check(*check), False, "failed highlight test")
|
| 253 |
+
test.write_text('const vm = require("vm"), fs = require("fs");\n'
|
| 254 |
+
'const filename = process.cwd() + "/static/search/highlight.js";\n'
|
| 255 |
+
'vm.runInNewContext(fs.readFileSync(filename, "utf8"), {}, {filename});\n')
|
| 256 |
+
self.assert_check(self.run_check(*check), False, "coverage")
|
| 257 |
+
|
| 258 |
+
def test_search_highlight_coverage_checks_fractional_minimum(self):
|
| 259 |
+
for path in ("static/search/highlight.js", "scripts/check_search_highlight_coverage.mjs",
|
| 260 |
+
"tests/test_search_highlight_contract.js"):
|
| 261 |
+
target = self.root / path
|
| 262 |
+
target.parent.mkdir(parents=True, exist_ok=True)
|
| 263 |
+
shutil.copyfile(ROOT / path, target)
|
| 264 |
+
gate = self.root / "scripts/check_search_highlight_coverage.mjs"
|
| 265 |
+
source = gate.read_text()
|
| 266 |
+
before = "const minimum = [100, 95.45, 100];"
|
| 267 |
+
self.assertEqual(source.count(before), 1)
|
| 268 |
+
gate.write_text(source.replace(before, "const minimum = [100, 95.99, 100];"))
|
| 269 |
+
self.assert_check(self.run_check("node", str(gate)), False, "above each minimum")
|
| 270 |
+
|
| 271 |
+
def test_search_highlight_declaration_matches_runtime(self):
|
| 272 |
+
config = self.root / "jsconfig.json"
|
| 273 |
+
declaration = self.root / "reader-globals.d.ts"
|
| 274 |
+
original = (ROOT / "typings/reader-globals.d.ts").read_text()
|
| 275 |
+
declaration.write_text(original)
|
| 276 |
+
self.assertIn("static/search/highlight.js", json.loads((ROOT / "jsconfig.strict.json").read_text())["files"])
|
| 277 |
+
config.write_text(json.dumps({"compilerOptions": {"allowJs": True, "checkJs": True, "noEmit": True,
|
| 278 |
+
"strict": True, "target": "esnext", "moduleDetection": "force"},
|
| 279 |
+
"files": [str(declaration), str(ROOT / "static/search/highlight.js")]}))
|
| 280 |
+
check = ["node", ROOT / "node_modules/typescript/bin/tsc", "--project", config]
|
| 281 |
+
self.assert_check(self.run_check(*check), True, "")
|
| 282 |
+
for before, after in [
|
| 283 |
+
("declare function escapeHTML(text: unknown): string;", "declare function escapeHTML(text: unknown): number;"),
|
| 284 |
+
("declare function getHighlightRegex(query: string): RegExp | null;",
|
| 285 |
+
"declare function getHighlightRegex(query: string): RegExp;"),
|
| 286 |
+
("declare function highlightText(text: unknown, query: string | null | undefined): string;",
|
| 287 |
+
"declare function highlightText(text: unknown, query: string | number | null | undefined): string;")
|
| 288 |
+
]:
|
| 289 |
+
self.assertEqual(original.count(before), 1)
|
| 290 |
+
declaration.write_text(original.replace(before, after))
|
| 291 |
+
self.assert_check(self.run_check(*check), False, "TS2322")
|
| 292 |
+
|
| 293 |
def test_search_record_path_coverage_gate_fails_closed(self):
|
| 294 |
paths = ["static/search/record-path.js", "scripts/check_search_record_path_coverage.mjs",
|
| 295 |
"tests/test_search_record_path.js", "static/app.js"]
|
typings/reader-globals.d.ts
CHANGED
|
@@ -6,6 +6,9 @@ declare function fmtSizeUrl(bytes: number | null | undefined): string | null;
|
|
| 6 |
declare function parseSizeStr(value: string | null | undefined): number | null;
|
| 7 |
declare function buildRecordRelativePath(record: {File?: string; Extension?: string; Folder?: string[] | null}): string;
|
| 8 |
declare function encodeRecordPath(path: string | null | undefined): string;
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
interface ReaderSecurityApi {
|
| 11 |
readonly LIMITS: Readonly<{
|
|
|
|
| 6 |
declare function parseSizeStr(value: string | null | undefined): number | null;
|
| 7 |
declare function buildRecordRelativePath(record: {File?: string; Extension?: string; Folder?: string[] | null}): string;
|
| 8 |
declare function encodeRecordPath(path: string | null | undefined): string;
|
| 9 |
+
declare function escapeHTML(text: unknown): string;
|
| 10 |
+
declare function getHighlightRegex(query: string): RegExp | null;
|
| 11 |
+
declare function highlightText(text: unknown, query: string | null | undefined): string;
|
| 12 |
|
| 13 |
interface ReaderSecurityApi {
|
| 14 |
readonly LIMITS: Readonly<{
|