Skip to content
refs
History
25 lines · 997 BRaw
1import { Marked, type Token } from "marked";
2
3export type ResolveRelative = (href: string, kind: "blob" | "raw") => string;
4
5export function escapeHtml(text: string): string {
6 return text.replace(/[&<>"']/g, (char) => `&#${char.charCodeAt(0)};`);
7}
8
9export function renderMarkdown(source: string, resolveRelative?: ResolveRelative): string {
10 const resolve = (href: string, kind: "blob" | "raw"): string => {
11 if (href.startsWith("#") || /^(https?:|mailto:)/i.test(href)) return href;
12 if (/^[a-z][a-z0-9+.-]*:/i.test(href) || href.startsWith("//")) return "#";
13 return resolveRelative ? resolveRelative(href, kind) : href;
14 };
15
16 const markdown = new Marked({
17 gfm: true,
18 renderer: { html: ({ text }) => escapeHtml(text) },
19 walkTokens: (token: Token) => {
20 if (token.type === "link") token.href = resolve(token.href, "blob");
21 if (token.type === "image") token.href = resolve(token.href, "raw");
22 },
23 });
24 return markdown.parse(source, { async: false });
25}