Branchwell

Skillfarm / website · skillfarm.ai / src / lib / markdown.ts

Raw 2.6 KB on 1483ab8a067e2125e25ab4212527521810bbb6af
1import { Marked } from 'marked';
2import { escapeHtml } from './util';
3
4function cleanHref(href: string | null | undefined): string | null {
5 if (!href) return null;
6 const h = href.trim();
7 if (h.startsWith('#')) return h;
8 try {
9 const u = new URL(h);
10 if (u.protocol === 'https:' || u.protocol === 'http:' || u.protocol === 'mailto:') return u.toString();
11 } catch {
12 /* relative links have nowhere to point on a skill page */
13 }
14 return null;
15}
16
17const md = new Marked({ gfm: true, breaks: false });
18md.use({
19 renderer: {
20 // Raw HTML in a SKILL.md is shown as text, never rendered.
21 html(token) {
22 return escapeHtml(token.text);
23 },
24 link(token) {
25 const text = this.parser.parseInline(token.tokens);
26 const href = cleanHref(token.href);
27 if (!href) return text;
28 return `<a href="${escapeHtml(href)}" rel="nofollow noopener ugc">${text}</a>`;
29 },
30 // Remote images would let a skill author track readers, so they render as links.
31 image(token) {
32 const href = cleanHref(token.href);
33 const label = escapeHtml(token.text || 'image');
34 return href ? `<a href="${escapeHtml(href)}" rel="nofollow noopener ugc">[image: ${label}]</a>` : `[image: ${label}]`;
35 },
36 },
37});
38
39export function renderMarkdown(src: string): string {
40 return md.parse(src, { async: false }) as string;
41}
42
43export type Frontmatter = { name?: string; description?: string; [k: string]: string | undefined };
44
45/** Reads the simple `key: value` YAML header of a SKILL.md. */
46export function parseSkillMd(src: string): { meta: Frontmatter; body: string } {
47 const text = src.replace(/^/, '').replace(/\r\n/g, '\n');
48 const m = /^---\n([\s\S]*?)\n---[ \t]*(\n|$)/.exec(text);
49 if (!m) return { meta: {}, body: text };
50 const meta: Frontmatter = {};
51 const lines = m[1].split('\n');
52 for (let i = 0; i < lines.length; i++) {
53 const kv = /^([A-Za-z0-9_-]+):\s*(.*)$/.exec(lines[i]);
54 if (!kv) continue;
55 let value = kv[2].trim();
56 if (value === '' || /^[>|][+-]?$/.test(value)) {
57 const folded = value.startsWith('>') || value === '';
58 const parts: string[] = [];
59 while (i + 1 < lines.length && (/^\s+\S/.test(lines[i + 1]) || lines[i + 1].trim() === '')) {
60 parts.push(lines[++i].trim());
61 }
62 value = folded ? parts.join(' ').replace(/\s+/g, ' ').trim() : parts.join('\n').trim();
63 } else if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
64 value = value.slice(1, -1).replace(/\\"/g, '"');
65 }
66 meta[kv[1].toLowerCase()] = value;
67 }
68 return { meta, body: text.slice(m[0].length) };
69}