From 93b85db4133e6065c94e5c94e1a7d75459d46d3a Mon Sep 17 00:00:00 2001 From: Aaqibhafeez Khan Date: Sun, 22 Nov 2026 03:00:40 +0530 Subject: [PATCH] fix: detect raw end tags and comments inside code blocks Signed-off-by: Aaqibhafeez Khan --- .../references/validation.md | 8 +- .../scripts/validate-output.js | 62 ++++++++++-- src/validate-output.ts | 96 +++++++++++++++---- .../fail/code-escaped/raw-code-end-tag.html | 11 +++ .../fail/code-escaped/raw-comment.html | 11 +++ .../raw-end-tag-after-comment.html | 11 +++ .../code-escaped/raw-end-tag-attributes.html | 11 +++ .../fail/code-escaped/raw-end-tag.html | 11 +++ .../fail/code-escaped/raw-pre-script.html | 11 +++ .../fail/code-escaped/raw-span-end-tag.html | 11 +++ .../ignored-comment-and-script-end-tags.html | 12 +++ tests/validate-output/validate-output.test.ts | 10 +- 12 files changed, 226 insertions(+), 39 deletions(-) create mode 100644 tests/validate-output/fail/code-escaped/raw-code-end-tag.html create mode 100644 tests/validate-output/fail/code-escaped/raw-comment.html create mode 100644 tests/validate-output/fail/code-escaped/raw-end-tag-after-comment.html create mode 100644 tests/validate-output/fail/code-escaped/raw-end-tag-attributes.html create mode 100644 tests/validate-output/fail/code-escaped/raw-end-tag.html create mode 100644 tests/validate-output/fail/code-escaped/raw-pre-script.html create mode 100644 tests/validate-output/fail/code-escaped/raw-span-end-tag.html create mode 100644 tests/validate-output/pass/ignored-comment-and-script-end-tags.html diff --git a/skills/explain-diff-html/references/validation.md b/skills/explain-diff-html/references/validation.md index 1bf84d0..247cbee 100644 --- a/skills/explain-diff-html/references/validation.md +++ b/skills/explain-diff-html/references/validation.md @@ -64,11 +64,9 @@ mistake fails instead of reporting on a page the script never opened. - Every code block is HTML-escaped: `&`, `<`, and `>` inside a `
` or
   `` block appear as `&`, `<`, `>`, with the `.del`, `.add`,
-  and `.hi` spans wrapping the escaped text. Raw angle brackets are parsed as
-  tags and silently break the document tree and every anchor below. The script
-  fails on any element inside a `
` or `` other than those spans,
-  which is what a raw `<` before a letter becomes. It does not see a raw end
-  tag such as `` or a raw ``),
+				...rawEndTags.map((tag) => `unmatched raw end tag in page source: ${tag}`)
+			];
+			return findings.length === 0 ? {
 				isFailed: false,
-				message: "every code block holds only text and .del, .add, .hi spans"
+				message: "code blocks are escaped; no stray elements, comments, or end tags"
 			} : {
 				isFailed: true,
-				message: "elements inside a code block other than .del, .add, and .hi spans:",
-				findings: [...stray].map((node) => {
-					return `<${[node.name, ...getAttributeValue(node, "class")?.split(" ") ?? []].filter(Boolean).join(".")}> in ${getText(node.parent)}`;
-				})
+				message: "unexpected code-block elements/comments or unmatched page end tags:",
+				findings
 			};
 		}
 	},
@@ -10347,7 +10384,10 @@ const checks = [
 	}
 ];
 function parsePage(html) {
-	return parse(html, { treeAdapter: adapter });
+	return parse(html, {
+		treeAdapter: adapter,
+		sourceCodeLocationInfo: true
+	});
 }
 function validate(page) {
 	return checks.map((check) => ({
@@ -10370,7 +10410,8 @@ function main(args) {
 		console.error(`FAIL: ${path} is not a non-empty file`);
 		return 1;
 	}
-	const document = parsePage(readFileSync(path, "utf8"));
+	const html = readFileSync(path, "utf8");
+	const document = parsePage(html);
 	const references = getReferences(document);
 	const linked = selectAll("a.srcref", document).length;
 	const marked = references.filter(isMarkedBare).length;
@@ -10378,6 +10419,7 @@ function main(args) {
 	let status = 0;
 	for (const { result } of validate({
 		document,
+		html,
 		sha
 	})) if (result.isFailed) {
 		console.log(`FAIL: ${result.message}`);
diff --git a/src/validate-output.ts b/src/validate-output.ts
index 9ee2f78..306383f 100644
--- a/src/validate-output.ts
+++ b/src/validate-output.ts
@@ -10,8 +10,8 @@
 
 import { readFileSync, statSync } from "node:fs";
 import { is, selectAll, selectOne } from "css-select";
-import { isTag, isText, type AnyNode, type Document, type Element } from "domhandler";
-import { getAttributeValue, textContent } from "domutils";
+import { isComment, isTag, isText, type AnyNode, type Document, type Element } from "domhandler";
+import { filter, getAttributeValue, textContent } from "domutils";
 import { parse } from "parse5";
 import { adapter } from "parse5-htmlparser2-tree-adapter";
 
@@ -21,6 +21,7 @@ export type Result =
 
 export interface Page {
   document: Document;
+  html: string;
   sha: string;
 }
 
@@ -262,26 +263,80 @@ export const checks: Check[] = [
     },
   },
   {
-    // A raw `<` that starts a tag becomes an element inside the block, so only the
-    // diff and highlight spans may sit in a code block.
+    // parse5 drops unmatched end tags from the tree, so scan the source.
+    // Comments stay in the tree.
     id: "code-escaped",
-    run({ document }) {
-      const stray = new Set(
-        selectAll("pre, code", document).flatMap((block) =>
-          selectAll("*", block.children).filter(
-            (node) => !is(node, "span.del, span.add, span.hi"),
-          ),
+    run({ document, html }) {
+      const blocks = selectAll("pre, code", document);
+      const stray = blocks.flatMap((block) =>
+        selectAll("*", block.children).filter(
+          (node) => !is(node, "span.del, span.add, span.hi"),
         ),
       );
-      return stray.size === 0
-        ? { isFailed: false, message: "every code block holds only text and .del, .add, .hi spans" }
+      const comments = blocks.flatMap((block) => filter(isComment, block.children, true));
+      const matchedEndTags = new Set();
+      const ignoredRanges: { start: number; end: number }[] = [];
+      const elements = filter(isTag, document.children, true) as Element[];
+      for (const element of elements) {
+        const location = element.sourceCodeLocation;
+        if (location && "startTag" in location && location.startTag) {
+          ignoredRanges.push({
+            start: location.startTag.startOffset,
+            end: location.startTag.endOffset,
+          });
+        }
+        if (location && "endTag" in location && location.endTag) {
+          matchedEndTags.add(location.endTag.startOffset);
+        }
+        if (
+          (element.name === "script" || element.name === "style") &&
+          location &&
+          "startTag" in location &&
+          location.startTag
+        ) {
+          const endOffset =
+            "endTag" in location && location.endTag
+              ? location.endTag.startOffset
+              : location.endOffset;
+          ignoredRanges.push({
+            start: location.startTag.endOffset,
+            end: endOffset,
+          });
+        }
+      }
+      for (const comment of filter(isComment, document.children, true)) {
+        const start = comment.startIndex ?? -1;
+        const end = comment.endIndex ?? start;
+        ignoredRanges.push({ start, end });
+      }
+      const rawEndTags = [...html.matchAll(/<\/\s*([a-z][a-z0-9:-]*)\b[^>]*>/gi)]
+        .filter((match) => {
+          const offset = match.index ?? -1;
+          return (
+            !matchedEndTags.has(offset) &&
+            !ignoredRanges.some(({ start, end }) => start <= offset && offset < end)
+          );
+        })
+        .map(([tag]) => tag);
+      const findings = [
+        ...stray.map((node) => {
+          const tag = [node.name, ...(getAttributeValue(node, "class")?.split(" ") ?? [])];
+          return `<${tag.filter(Boolean).join(".")}> in ${getText(node.parent as Element)}`;
+        }),
+        ...comments.map(
+          (node) => `raw HTML comment in code block: `,
+        ),
+        ...rawEndTags.map((tag) => `unmatched raw end tag in page source: ${tag}`),
+      ];
+      return findings.length === 0
+        ? {
+            isFailed: false,
+            message: "code blocks are escaped; no stray elements, comments, or end tags",
+          }
         : {
             isFailed: true,
-            message: "elements inside a code block other than .del, .add, and .hi spans:",
-            findings: [...stray].map((node) => {
-              const tag = [node.name, ...(getAttributeValue(node, "class")?.split(" ") ?? [])];
-              return `<${tag.filter(Boolean).join(".")}> in ${getText(node.parent as Element)}`;
-            }),
+            message: "unexpected code-block elements/comments or unmatched page end tags:",
+            findings,
           };
     },
   },
@@ -313,7 +368,7 @@ export const checks: Check[] = [
 ];
 
 export function parsePage(html: string): Document {
-  return parse(html, { treeAdapter: adapter });
+  return parse(html, { treeAdapter: adapter, sourceCodeLocationInfo: true });
 }
 
 export function validate(page: Page): { id: string; result: Result }[] {
@@ -337,14 +392,15 @@ function main(args: string[]): number {
     return 1;
   }
 
-  const document = parsePage(readFileSync(path, "utf8"));
+  const html = readFileSync(path, "utf8");
+  const document = parsePage(html);
   const references = getReferences(document);
   const linked = selectAll("a.srcref", document).length;
   const marked = references.filter(isMarkedBare).length;
   console.log(`references=${references.length} linked=${linked} marked-bare=${marked}`);
 
   let status = 0;
-  for (const { result } of validate({ document, sha })) {
+  for (const { result } of validate({ document, html, sha })) {
     if (result.isFailed) {
       console.log(`FAIL: ${result.message}`);
       for (const finding of result.findings) console.log(finding);
diff --git a/tests/validate-output/fail/code-escaped/raw-code-end-tag.html b/tests/validate-output/fail/code-escaped/raw-code-end-tag.html
new file mode 100644
index 0000000..6000bdb
--- /dev/null
+++ b/tests/validate-output/fail/code-escaped/raw-code-end-tag.html
@@ -0,0 +1,11 @@
+
+
+Validator regression
+
+
+

0123456789ab

+

Use a b here.

+
A quiz is present.
+
+ + diff --git a/tests/validate-output/fail/code-escaped/raw-comment.html b/tests/validate-output/fail/code-escaped/raw-comment.html new file mode 100644 index 0000000..9939f70 --- /dev/null +++ b/tests/validate-output/fail/code-escaped/raw-comment.html @@ -0,0 +1,11 @@ + + +Validator regression + +
+

0123456789ab

+
before  after
+
A quiz is present.
+
+ + diff --git a/tests/validate-output/fail/code-escaped/raw-end-tag-after-comment.html b/tests/validate-output/fail/code-escaped/raw-end-tag-after-comment.html new file mode 100644 index 0000000..f458195 --- /dev/null +++ b/tests/validate-output/fail/code-escaped/raw-end-tag-after-comment.html @@ -0,0 +1,11 @@ + + +Validator regression + +
+

0123456789ab

+

Before the comment.

+
A quiz is present.
+
+ + diff --git a/tests/validate-output/fail/code-escaped/raw-end-tag-attributes.html b/tests/validate-output/fail/code-escaped/raw-end-tag-attributes.html new file mode 100644 index 0000000..458fe0c --- /dev/null +++ b/tests/validate-output/fail/code-escaped/raw-end-tag-attributes.html @@ -0,0 +1,11 @@ + + +Validator regression + +
+

0123456789ab

+
before  after
+
A quiz is present.
+
+ + diff --git a/tests/validate-output/fail/code-escaped/raw-end-tag.html b/tests/validate-output/fail/code-escaped/raw-end-tag.html new file mode 100644 index 0000000..bfe089e --- /dev/null +++ b/tests/validate-output/fail/code-escaped/raw-end-tag.html @@ -0,0 +1,11 @@ + + +Validator regression + +
+

0123456789ab

+
before  after
+
A quiz is present.
+
+ + diff --git a/tests/validate-output/fail/code-escaped/raw-pre-script.html b/tests/validate-output/fail/code-escaped/raw-pre-script.html new file mode 100644 index 0000000..d5abe3d --- /dev/null +++ b/tests/validate-output/fail/code-escaped/raw-pre-script.html @@ -0,0 +1,11 @@ + + +Validator regression + +
+

0123456789ab

+
before 
after
+
A quiz is present.
+ + + diff --git a/tests/validate-output/fail/code-escaped/raw-span-end-tag.html b/tests/validate-output/fail/code-escaped/raw-span-end-tag.html new file mode 100644 index 0000000..11f3e30 --- /dev/null +++ b/tests/validate-output/fail/code-escaped/raw-span-end-tag.html @@ -0,0 +1,11 @@ + + +Validator regression + +
+

0123456789ab

+
before  after
+
A quiz is present.
+
+ + diff --git a/tests/validate-output/pass/ignored-comment-and-script-end-tags.html b/tests/validate-output/pass/ignored-comment-and-script-end-tags.html new file mode 100644 index 0000000..1a09ef0 --- /dev/null +++ b/tests/validate-output/pass/ignored-comment-and-script-end-tags.html @@ -0,0 +1,12 @@ + + +Validator regression + +
+

0123456789ab

+ + +
A quiz is present.
+
+ + diff --git a/tests/validate-output/validate-output.test.ts b/tests/validate-output/validate-output.test.ts index cee55d6..506bfb5 100644 --- a/tests/validate-output/validate-output.test.ts +++ b/tests/validate-output/validate-output.test.ts @@ -18,8 +18,9 @@ const script = fileURLToPath( const sha = "0123456"; function getFailedCheckIds(path: string): string[] { - const document = parsePage(readFileSync(path, "utf8")); - return validate({ document, sha }) + const html = readFileSync(path, "utf8"); + const document = parsePage(html); + return validate({ document, html, sha }) .filter(({ result }) => result.isFailed) .map(({ id }) => id); } @@ -71,8 +72,9 @@ for (const checkId of checkIds) { test("an unlinked reference is listed by its text", () => { const path = join(failFolder, "unlinked-reference", "spare-srcref.html"); - const document = parsePage(readFileSync(path, "utf8")); - const unlinked = validate({ document, sha }).find(({ id }) => id === "unlinked-reference"); + const html = readFileSync(path, "utf8"); + const document = parsePage(html); + const unlinked = validate({ document, html, sha }).find(({ id }) => id === "unlinked-reference"); expect(unlinked?.result.isFailed ? unlinked.result.findings : []).toEqual(["b.py:9"]); });