// Safe Markdown for OpenSpec artifacts (PEP-32): the subset proposals and designs use —
// headings, paragraphs, lists with checkboxes, code blocks, tables, quotes, rules, inline
// code/bold/italic/links. Everything becomes React elements; no HTML from the file is
// ever injected, and only http(s), mailto and relative links are kept.
import { Fragment, type ReactNode } from "react";
import { cn } from "@/lib/utils";
type Block =
| { t: "h"; level: number; text: string }
| { t: "p"; text: string }
| { t: "code"; lang: string; text: string }
| { t: "list"; ordered: boolean; items: Array<{ text: string; checked: boolean | null; depth: number }> }
| { t: "quote"; text: string }
| { t: "table"; head: string[]; rows: string[][] }
| { t: "hr" };
const LIST_RE = /^(\s*)([-*+]|\d+[.)])\s+(.*)$/;
const splitRow = (l: string) => l.trim().replace(/^\|/, "").replace(/\|$/, "").split("|").map((c) => c.trim());
export function parseMarkdown(src: string): Block[] {
const lines = src.replace(/\r\n?/g, "\n").split("\n");
const out: Block[] = [];
let i = 0;
while (i < lines.length) {
const line = lines[i]!;
if (!line.trim()) {
i++;
continue;
}
const fence = line.match(/^\s*(```|~~~)\s*(\S*)/);
if (fence) {
const body: string[] = [];
i++;
while (i < lines.length && !lines[i]!.trim().startsWith(fence[1]!)) body.push(lines[i++]!);
i++;
out.push({ t: "code", lang: fence[2] ?? "", text: body.join("\n") });
continue;
}
const h = line.match(/^(#{1,6})\s+(.*?)\s*#*\s*$/);
if (h) {
out.push({ t: "h", level: h[1]!.length, text: h[2]! });
i++;
continue;
}
if (/^\s*([-*_])(\s*\1){2,}\s*$/.test(line)) {
out.push({ t: "hr" });
i++;
continue;
}
if (line.includes("|") && /^\s*\|?\s*:?-{2,}/.test(lines[i + 1] ?? "") && (lines[i + 1] ?? "").includes("-")) {
const head = splitRow(line);
const rows: string[][] = [];
i += 2;
while (i < lines.length && lines[i]!.includes("|") && lines[i]!.trim()) rows.push(splitRow(lines[i++]!));
out.push({ t: "table", head, rows });
continue;
}
if (/^\s*>/.test(line)) {
const body: string[] = [];
while (i < lines.length && /^\s*>/.test(lines[i]!)) body.push(lines[i++]!.replace(/^\s*>\s?/, ""));
out.push({ t: "quote", text: body.join("\n") });
continue;
}
const li = line.match(LIST_RE);
if (li) {
const ordered = /\d/.test(li[2]!);
const items: Array<{ text: string; checked: boolean | null; depth: number }> = [];
while (i < lines.length) {
const m = lines[i]!.match(LIST_RE);
if (m) {
const box = m[3]!.match(/^\[([ xX])\]\s+(.*)$/);
items.push({ text: box ? box[2]! : m[3]!, checked: box ? box[1] !== " " : null, depth: Math.min(3, Math.floor(m[1]!.replace(/\t/g, " ").length / 2)) });
i++;
} else if (lines[i]!.trim() && /^\s{2,}/.test(lines[i]!) && items.length) {
items.at(-1)!.text += ` ${lines[i++]!.trim()}`; // continuation line
} else break;
}
out.push({ t: "list", ordered, items });
continue;
}
const para: string[] = [];
while (i < lines.length && lines[i]!.trim() && !/^(#{1,6}\s|\s*```|\s*~~~|\s*>)/.test(lines[i]!) && !LIST_RE.test(lines[i]!)) para.push(lines[i++]!.trim());
out.push({ t: "p", text: para.join(" ") });
}
return out;
}
export function safeHref(href: string): string | null {
const h = href.trim();
if (/^(https?:|mailto:)/i.test(h)) return h;
if (/^[a-z][a-z0-9+.-]*:/i.test(h) || h.startsWith("//")) return null; // javascript:, data:, protocol-relative…
return h;
}
// Inline: `code`, **bold**, *italic* or _italic_, [text](url), bare https links.
export function inline(text: string, key = "i"): ReactNode[] {
const out: ReactNode[] = [];
const re = /(`+)([^`]+?)\1|\*\*([^*]+)\*\*|__([^_]+)__|\[([^\]]+)\]\(([^)\s]+)\)|(? last) out.push(text.slice(last, m.index));
const k = `${key}-${n++}`;
if (m[2] != null) out.push({m[2]});
else if (m[3] != null || m[4] != null) out.push({inline(m[3] ?? m[4]!, k)});
else if (m[5] != null) {
const href = safeHref(m[6]!);
out.push(href ? {inline(m[5], k)} :
{inline(b.text, k)}
; case "code": return{b.text};
case "quote":
return {inline(b.text, k)}; case "hr": return
| {inline(c, `${k}h${j}`)} | )}
|---|
| {inline(c, `${k}r${ri}c${j}`)} | )}