GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Merge pull request #5147 from developing-today/queue/8754-4007-html5-… · developing-today/code@19aa97c

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • pkgs/lab-ops-hub
    • src
      • html5-entities.ts
      • lib.ts
    • test
      • extractor-fixtures.json
      • generate_html5_entity_corpus.py
      • html5-entities.test.ts
      • html5-entity-corpus.json
      • test_html5_entity_corpus.py
    • tsconfig.json
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎pkgs/lab-ops-hub/src/html5-entities.ts‎

Copy file name to clipboardExpand all lines: pkgs/lab-ops-hub/src/html5-entities.ts
+2,235Lines changed: 2235 additions & 0 deletions
Large diffs are not rendered by default.
Collapse file

‎pkgs/lab-ops-hub/src/lib.ts‎

Copy file name to clipboardExpand all lines: pkgs/lab-ops-hub/src/lib.ts
+64-99Lines changed: 64 additions & 99 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import { HTML5_ENTITIES, MAX_HTML5_ENTITY_KEY_LENGTH } from "./html5-entities.ts";
2+
13
// Pure helpers for Lab Ops Hub: crawl-target validation (#441), the
24
// /api/budget computation (#442), and upload R2 key derivation (#2478).
35
// Kept free of Worker bindings so they can be unit-tested with plain
@@ -522,98 +524,12 @@ export async function fileResponseForKey(
522524
// (#4008): content is likewise literal up to the matching close tag
523525
// (anchors inside never count), and HTMLParser reports it verbatim —
524526
// no entity decoding — as ordinary character data.
525-
const NAMED_ENTITIES: Record<string, string> = {
526-
amp: "&",
527-
lt: "<",
528-
gt: ">",
529-
quot: '"',
530-
apos: "'",
531-
nbsp: " ",
532-
copy: "©",
533-
reg: "®",
534-
trade: "™",
535-
hellip: "…",
536-
mdash: "—",
537-
ndash: "–",
538-
lsquo: "‘",
539-
rsquo: "’",
540-
ldquo: "“",
541-
rdquo: "”",
542-
laquo: "«",
543-
raquo: "»",
544-
times: "×",
545-
divide: "÷",
546-
plusmn: "±",
547-
deg: "°",
548-
middot: "·",
549-
bull: "•",
550-
dagger: "†",
551-
permil: "‰",
552-
euro: "€",
553-
pound: "£",
554-
yen: "¥",
555-
cent: "¢",
556-
curren: "¤",
557-
sect: "§",
558-
para: "¶",
559-
micro: "µ",
560-
sup1: "¹",
561-
sup2: "²",
562-
sup3: "³",
563-
frac12: "½",
564-
frac14: "¼",
565-
frac34: "¾",
566-
iexcl: "¡",
567-
iquest: "¿",
568-
szlig: "ß",
569-
agrave: "à",
570-
aacute: "á",
571-
acirc: "â",
572-
atilde: "ã",
573-
auml: "ä",
574-
aring: "å",
575-
aelig: "æ",
576-
ccedil: "ç",
577-
egrave: "è",
578-
eacute: "é",
579-
ecirc: "ê",
580-
euml: "ë",
581-
igrave: "ì",
582-
iacute: "í",
583-
icirc: "î",
584-
iuml: "ï",
585-
ntilde: "ñ",
586-
ograve: "ò",
587-
oacute: "ó",
588-
ocirc: "ô",
589-
otilde: "õ",
590-
ouml: "ö",
591-
ugrave: "ù",
592-
uacute: "ú",
593-
ucirc: "û",
594-
uuml: "ü",
595-
yacute: "ý",
596-
yuml: "ÿ",
597-
Agrave: "À",
598-
Aacute: "Á",
599-
Auml: "Ä",
600-
Ccedil: "Ç",
601-
Egrave: "È",
602-
Eacute: "É",
603-
Euml: "Ë",
604-
Ntilde: "Ñ",
605-
Ograve: "Ò",
606-
Oacute: "Ó",
607-
Ouml: "Ö",
608-
Ugrave: "Ù",
609-
Uacute: "Ú",
610-
Uuml: "Ü",
611-
};
612527

613528
// HTML numeric character-reference normalization: the same remapping
614529
// html.unescape applies for the container's HTMLParser. C1 controls
615530
// 0x80-0x9F map to their Windows-1252 characters; NUL, surrogates, and
616-
// out-of-range values become U+FFFD.
531+
// out-of-range values become U+FFFD. Other invalid controls and Unicode
532+
// noncharacters are dropped, matching html.unescape.
617533
const NUMERIC_REF_REMAP: Record<number, number> = {
618534
0x80: 0x20ac,
619535
0x81: 0x0081,
@@ -649,23 +565,72 @@ const NUMERIC_REF_REMAP: Record<number, number> = {
649565
0x9f: 0x0178,
650566
};
651567

652-
function normalizeNumericRef(code: number): number {
568+
function normalizeNumericRef(code: number): number | null {
653569
if (code === 0 || code > 0x10ffff || (code >= 0xd800 && code <= 0xdfff)) return 0xfffd;
570+
if (
571+
(code >= 0x1 && code <= 0x8) ||
572+
code === 0xb ||
573+
(code >= 0xe && code <= 0x1f) ||
574+
code === 0x7f ||
575+
(code >= 0xfdd0 && code <= 0xfdef) ||
576+
(code & 0xffff) === 0xfffe ||
577+
(code & 0xffff) === 0xffff
578+
) {
579+
return null;
580+
}
654581
return NUMERIC_REF_REMAP[code] ?? code;
655582
}
656583

657584
export function decodeHtmlEntities(data: string): string {
658-
return data.replace(/&(#(?:[xX][0-9a-fA-F]+|\d+)|[a-zA-Z][a-zA-Z0-9]*);/g, (whole, body: string) => {
659-
if (body.startsWith("#")) {
660-
const hex = body[1] === "x" || body[1] === "X";
661-
const code = Number.parseInt(body.slice(hex ? 2 : 1), hex ? 16 : 10);
662-
return String.fromCodePoint(normalizeNumericRef(code));
585+
const decoded: string[] = [];
586+
let copyFrom = 0;
587+
let i = 0;
588+
const numericReference = /&#([xX][0-9a-fA-F]+|\d+);?/y;
589+
while (i < data.length) {
590+
if (data[i] !== "&") {
591+
i += 1;
592+
continue;
663593
}
664-
// Own-property lookup only: a plain index would resolve inherited
665-
// Object properties (&constructor;, &toString;) to JavaScript
666-
// functions, where HTMLParser leaves unknown names literal.
667-
return Object.prototype.hasOwnProperty.call(NAMED_ENTITIES, body) ? NAMED_ENTITIES[body] : whole;
668-
});
594+
595+
if (data[i + 1] === "#") {
596+
numericReference.lastIndex = i;
597+
const numeric = numericReference.exec(data);
598+
if (numeric) {
599+
const body = numeric[1];
600+
const hex = body[0] === "x" || body[0] === "X";
601+
const code = Number.parseInt(body.slice(hex ? 1 : 0), hex ? 16 : 10);
602+
const normalized = normalizeNumericRef(code);
603+
decoded.push(data.slice(copyFrom, i), normalized === null ? "" : String.fromCodePoint(normalized));
604+
i += numeric[0].length;
605+
copyFrom = i;
606+
continue;
607+
}
608+
} else {
609+
let end = i + 1;
610+
while (
611+
end < data.length &&
612+
end - (i + 1) < MAX_HTML5_ENTITY_KEY_LENGTH &&
613+
/[A-Za-z0-9;]/.test(data[end])
614+
) {
615+
end += 1;
616+
}
617+
let matched = false;
618+
for (let matchEnd = end; matchEnd > i + 1; matchEnd -= 1) {
619+
const entity = HTML5_ENTITIES.get(data.slice(i + 1, matchEnd));
620+
if (entity !== undefined) {
621+
decoded.push(data.slice(copyFrom, i), entity);
622+
i = matchEnd;
623+
copyFrom = i;
624+
matched = true;
625+
break;
626+
}
627+
}
628+
if (matched) continue;
629+
}
630+
i += 1;
631+
}
632+
decoded.push(data.slice(copyFrom));
633+
return decoded.join("");
669634
}
670635

671636
// A '/' marks a start tag self-closing only where a new attribute could
Collapse file

‎pkgs/lab-ops-hub/test/extractor-fixtures.json‎

Copy file name to clipboardExpand all lines: pkgs/lab-ops-hub/test/extractor-fixtures.json
+21Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -271,5 +271,26 @@
271271
"title": "",
272272
"links": 0,
273273
"text": "one x"
274+
},
275+
{
276+
"name": "HTML5 named and semicolonless numeric references match container extraction",
277+
"html": "<title>&Alpha; &AMP;</title><p>&rarr; &#65 &amp B</p>",
278+
"title": "Α &",
279+
"links": 0,
280+
"text": "→ A & B"
281+
},
282+
{
283+
"name": "ambiguous ampersands use the longest legacy HTML5 reference",
284+
"html": "<p>&amp B &notanentity; &doesnotexist;</p>",
285+
"title": "",
286+
"links": 0,
287+
"text": "& B ¬anentity; &doesnotexist;"
288+
},
289+
{
290+
"name": "multi-codepoint HTML5 named reference is preserved",
291+
"html": "<p>&NotEqualTilde;</p>",
292+
"title": "",
293+
"links": 0,
294+
"text": "≂̸"
274295
}
275296
]
Collapse file

‎pkgs/lab-ops-hub/test/generate_html5_entity_corpus.py‎

Copy file name to clipboard
+101Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
#!/usr/bin/env python3
2+
"""Generate the checked-in html.unescape oracle corpus for the Worker decoder."""
3+
4+
from __future__ import annotations
5+
6+
import html
7+
import html.entities
8+
import json
9+
from pathlib import Path
10+
11+
12+
HERE = Path(__file__).resolve().parent
13+
OUTPUT = HERE / "html5-entity-corpus.json"
14+
15+
16+
def main() -> None:
17+
cases: list[dict[str, str]] = []
18+
seen: set[str] = set()
19+
20+
def add(source: str) -> None:
21+
if source not in seen:
22+
seen.add(source)
23+
cases.append({"input": source, "expected": html.unescape(source)})
24+
25+
# Every HTML5 table key includes both semicolon and legacy semicolonless
26+
# spellings. Exercise each exact key, then ambiguous suffixes for the
27+
# semicolonless forms so longest-prefix behavior stays oracle-pinned.
28+
for key in sorted(html.entities.html5):
29+
add(f"&{key}")
30+
if not key.endswith(";"):
31+
add(f"&{key}x")
32+
add(f"&{key}=")
33+
34+
for source in (
35+
"&amp B",
36+
"&notanentity;",
37+
"&ampx",
38+
"&copy=",
39+
"&not=",
40+
"&#;",
41+
"&#x;",
42+
"&#xZZ;",
43+
"&#65x",
44+
"&#65=x",
45+
):
46+
add(source)
47+
48+
# Numeric normalization boundaries: C1 remapping, NUL/surrogate and
49+
# out-of-range replacement, and the valid scalar boundaries around them.
50+
for codepoint in (
51+
0,
52+
1,
53+
9,
54+
0x7F,
55+
0x80,
56+
0x81,
57+
0x82,
58+
0x8F,
59+
0x9F,
60+
0xA0,
61+
0xD7FF,
62+
0xD800,
63+
0xDFFF,
64+
0xE000,
65+
0xFDD0,
66+
0xFDEF,
67+
0xFFFD,
68+
0xFFFE,
69+
0xFFFF,
70+
0x10000,
71+
0x1FFFE,
72+
0x1FFFF,
73+
0x10FFFE,
74+
0x10FFFF,
75+
0x110000,
76+
):
77+
for digits in (str(codepoint), f"x{codepoint:X}"):
78+
add(f"&#{digits};")
79+
add(f"&#{digits}")
80+
81+
add("&#999999999999999999999999999999999999999999999;")
82+
add("&#xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;")
83+
84+
OUTPUT.write_text(
85+
json.dumps(
86+
{
87+
"oracle": "Python html.unescape",
88+
"entity_key_count": len(html.entities.html5),
89+
"cases": cases,
90+
},
91+
ensure_ascii=False,
92+
indent=2,
93+
)
94+
+ "\n",
95+
encoding="utf-8",
96+
)
97+
print(f"Wrote {len(cases)} cases for {len(html.entities.html5)} HTML5 keys to {OUTPUT}")
98+
99+
100+
if __name__ == "__main__":
101+
main()
Collapse file

‎pkgs/lab-ops-hub/test/html5-entities.test.ts‎

Copy file name to clipboard
+25Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// Generated oracle corpus for the Worker HTML5 entity decoder.
2+
import assert from "node:assert/strict";
3+
import { readFileSync } from "node:fs";
4+
import { test } from "node:test";
5+
import { HTML5_ENTITIES } from "../src/html5-entities.ts";
6+
import { decodeHtmlEntities } from "../src/lib.ts";
7+
8+
interface Corpus {
9+
oracle: string;
10+
entity_key_count: number;
11+
cases: Array<{ input: string; expected: string }>;
12+
}
13+
14+
const corpus = JSON.parse(
15+
readFileSync(new URL("./html5-entity-corpus.json", import.meta.url), "utf8"),
16+
) as Corpus;
17+
18+
test("decodeHtmlEntities matches the generated Python html.unescape corpus", () => {
19+
assert.equal(corpus.oracle, "Python html.unescape");
20+
assert.equal(corpus.entity_key_count, HTML5_ENTITIES.size, "all HTML5 table keys are covered");
21+
22+
for (const { input, expected } of corpus.cases) {
23+
assert.equal(decodeHtmlEntities(input), expected, `input ${JSON.stringify(input)}`);
24+
}
25+
});

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.