Skip to content

Commit 9466d93

Browse files
TMHSDigitalclaude
andcommitted
site: block markdown renderer that fails on unsupported syntax
Paragraphs, ## headings with ids, and bullet lists with nesting and continuation lines. Tables, code fences, blockquotes, images, raw HTML, ### and numbered lists throw a MarkdownError naming the file and line. Plus splitEntryBody, sectionMarkdown and deprecationReason. 22 new assertions (44 total); all 319 catalog bodies render without error. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Wc67NX9MM964uaVGn4bpZJ
1 parent ed2ad6e commit 9466d93

2 files changed

Lines changed: 141 additions & 0 deletions

File tree

‎site/lib/lib.test.mjs‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,33 @@ eq("backslash escape", renderInline("\\*not italic\\*", passLink), "*not italic*
6464
eq("html in text is escaped", renderInline("<script>alert(1)</script>", passLink), "&lt;script&gt;alert(1)&lt;/script&gt;");
6565
eq("non-ASCII survives", renderInline("Johannes Sjölund", passLink), "Johannes Sjölund");
6666

67+
/* markdown: blocks --------------------------------------------------------- */
68+
import { deprecationReason, renderBlocks, sectionMarkdown, splitEntryBody } from "./markdown.mjs";
69+
const rb = (md) => renderBlocks(md, { file: "t.md", resolveLink: passLink });
70+
eq("paragraph joins lines", rb("a\nb"), "<p>a b</p>");
71+
eq("h1 is dropped", rb("# Title\n\nText"), "<p>Text</p>");
72+
eq("h2 gets an id", rb("## Notes"), '<h2 id="notes">Notes</h2>');
73+
eq("flat list", rb("- a\n- b"), "<ul><li>a</li><li>b</li></ul>");
74+
eq("nested list", rb("- a\n - b\n- c"), "<ul><li>a<ul><li>b</li></ul></li><li>c</li></ul>");
75+
eq("list item continuation", rb("- a\n more"), "<ul><li>a more</li></ul>");
76+
eq("list then paragraph", rb("- a\n\nText"), "<ul><li>a</li></ul>\n<p>Text</p>");
77+
eq("italic at line start is not a list", rb("*Measured:* 5"), "<p><em>Measured:</em> 5</p>");
78+
throws("table rejected", () => rb("| a | b |"), "t.md:1: a table row");
79+
throws("fence rejected", () => rb("x\n```"), "t.md:2: a code fence");
80+
throws("blockquote rejected", () => rb("> q"), "a blockquote");
81+
throws("image rejected", () => rb("![i](x.png)"), "an image");
82+
throws("raw html rejected", () => rb("<div>x</div>"), "raw HTML");
83+
throws("h3 rejected", () => rb("### Sub"), "a heading below level 2");
84+
throws("ordered list rejected", () => rb("1. one"), "an ordered list");
85+
throws("firstLine offsets line numbers", () => renderBlocks("ok\n> q", { file: "t.md", resolveLink: passLink, firstLine: 10 }), "t.md:11:");
86+
const body = "# T\n\nLead one.\n\nLead two.\n\n## Notes\n\n- n1\n- Deprecated: gone\n\n## Evidence\n\n- e1";
87+
eq("split lead", splitEntryBody(body).lead, "# T\n\nLead one.\n\nLead two.\n");
88+
eq("split rest starts at first h2", splitEntryBody(body).rest.split("\n")[0], "## Notes");
89+
eq("split restFirstLine", splitEntryBody(body).restFirstLine, 7);
90+
eq("sectionMarkdown Notes", sectionMarkdown(body, "Notes"), "- n1\n- Deprecated: gone");
91+
eq("sectionMarkdown missing", sectionMarkdown(body, "Nope"), null);
92+
eq("deprecationReason", deprecationReason(body), "gone");
93+
6794
/* report (keep last) ------------------------------------------------------ */
6895
if (failures.length) {
6996
console.error(`lib.test failed (${failures.length}):`);

‎site/lib/markdown.mjs‎

Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,3 +49,117 @@ export function renderInline(text, resolveLink) {
4949
} while (s !== before);
5050
return s;
5151
}
52+
53+
const UNSUPPORTED = [
54+
[/^\s*\|/, "a table row"],
55+
[/^\s*```/, "a code fence"],
56+
[/^\s*>/, "a blockquote"],
57+
[/^\s*!\[/, "an image"],
58+
[/^\s*<[A-Za-z!/]/, "raw HTML"],
59+
[/^#{3,}\s/, "a heading below level 2"],
60+
[/^\s*\d+[.)]\s/, "an ordered list"],
61+
];
62+
63+
const lines = (md) => String(md).replace(/\r\n?/g, "\n").split("\n");
64+
65+
export function renderBlocks(md, { file, resolveLink, firstLine = 1 }) {
66+
const html = [];
67+
const stack = [];
68+
let para = [];
69+
let item = null;
70+
let blank = false;
71+
const inline = (t) => renderInline(t, resolveLink);
72+
const flushPara = () => {
73+
if (para.length) html.push(`<p>${inline(para.join(" "))}</p>`);
74+
para = [];
75+
};
76+
const flushItem = () => {
77+
if (item !== null) html.push(inline(item));
78+
item = null;
79+
};
80+
const closeLists = () => {
81+
flushItem();
82+
while (stack.length) {
83+
html.push("</li></ul>");
84+
stack.pop();
85+
}
86+
};
87+
lines(md).forEach((line, i) => {
88+
for (const [re, what] of UNSUPPORTED) {
89+
if (re.test(line)) {
90+
throw new MarkdownError(`${file}:${firstLine + i}: ${what} is not supported by the site renderer`);
91+
}
92+
}
93+
if (!line.trim()) {
94+
flushPara();
95+
blank = true;
96+
return;
97+
}
98+
const li = line.match(/^(\s*)[-*]\s+(.*)$/);
99+
if (li) {
100+
flushPara();
101+
const indent = li[1].replace(/\t/g, " ").length;
102+
if (!stack.length) {
103+
html.push("<ul><li>");
104+
stack.push(indent);
105+
} else if (indent > stack[stack.length - 1]) {
106+
flushItem();
107+
html.push("<ul><li>");
108+
stack.push(indent);
109+
} else {
110+
flushItem();
111+
while (stack.length > 1 && indent < stack[stack.length - 1]) {
112+
html.push("</li></ul>");
113+
stack.pop();
114+
}
115+
html.push("</li><li>");
116+
}
117+
item = li[2];
118+
blank = false;
119+
return;
120+
}
121+
if (stack.length && !blank && /^\s/.test(line)) {
122+
item += ` ${line.trim()}`;
123+
return;
124+
}
125+
closeLists();
126+
blank = false;
127+
const h = line.match(/^(#{1,2})\s+(.*)$/);
128+
if (h) {
129+
flushPara();
130+
if (h[1] === "#") return; // the page shows the entry name as its h1
131+
const id = h[2].toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
132+
html.push(`<h2 id="${esc(id)}">${inline(h[2])}</h2>`);
133+
return;
134+
}
135+
para.push(line.trim());
136+
});
137+
flushPara();
138+
closeLists();
139+
// Items and their markup were pushed as separate strings; join tight.
140+
return html.join("").replace(/<\/p><(h2|p|ul)/g, "</p>\n<$1").replace(/<\/ul><(h2|p)/g, "</ul>\n<$1").replace(/<\/h2><(p|ul)/g, "</h2>\n<$1");
141+
}
142+
143+
/** Lead (before the first `## `) and the rest, with the rest's first line number. */
144+
export function splitEntryBody(body) {
145+
const ls = lines(body);
146+
const i = ls.findIndex((l) => /^##\s/.test(l));
147+
if (i === -1) return { lead: ls.join("\n"), rest: "", restFirstLine: ls.length + 1 };
148+
return { lead: ls.slice(0, i).join("\n"), rest: ls.slice(i).join("\n"), restFirstLine: i + 1 };
149+
}
150+
151+
/** Raw markdown under `## <heading>`, up to the next `## `, or null. */
152+
export function sectionMarkdown(body, heading) {
153+
const ls = lines(body);
154+
const start = ls.findIndex((l) => l.trim() === `## ${heading}`);
155+
if (start === -1) return null;
156+
let end = ls.findIndex((l, j) => j > start && /^##\s/.test(l));
157+
if (end === -1) end = ls.length;
158+
return ls.slice(start + 1, end).join("\n").trim();
159+
}
160+
161+
/** The text after the `- Deprecated:` marker line, or null. */
162+
export function deprecationReason(body) {
163+
const m = String(body).match(/^- Deprecated:\s*(.+)$/m);
164+
return m ? m[1].trim() : null;
165+
}

0 commit comments

Comments
 (0)