import { parse, stringify } from "yaml"; export interface ParsedMarkdownFrontmatter { data: Record; content: string; } const openingDelimiter = /^---[ \t]*(?:\r?\n|$)/; const closingDelimiter = /^---[ \t]*(?:\r?\n|$)/m; /** * Pony records intentionally support YAML frontmatter only. Keeping parsing * within the existing YAML dependency prevents executable JavaScript * frontmatter from entering either the CLI or the bundled web server. */ export function parseMarkdownFrontmatter( raw: string, ): ParsedMarkdownFrontmatter { const source = raw.startsWith("\uFEFF") ? raw.slice(1) : raw; const opening = openingDelimiter.exec(source); if (!opening) return { data: {}, content: source }; const afterOpening = source.slice(opening[0].length); if (afterOpening === "") return { data: {}, content: "" }; const closing = closingDelimiter.exec(afterOpening); if (!closing) { throw new SyntaxError("Missing closing YAML frontmatter delimiter."); } const parsed: unknown = parse(afterOpening.slice(0, closing.index)) ?? {}; if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) { throw new SyntaxError("YAML frontmatter must contain a mapping."); } return { data: parsed as Record, content: afterOpening.slice(closing.index + closing[0].length), }; } export function stringifyMarkdownFrontmatter( content: string, data: object, ): string { const frontmatter = stringify(data, { lineWidth: 0 }).trimEnd(); return `---\n${frontmatter}\n---\n${content}\n`; } /** * Rebuild frontmatter while retaining the Markdown payload byte-for-byte. * Identity-only migrations use this so trailing whitespace and line endings in * user-authored bodies are not normalized as an accidental side effect. */ export function stringifyMarkdownFrontmatterPreservingContent( content: string, data: object, ): string { const frontmatter = stringify(data, { lineWidth: 0 }).trimEnd(); return `---\n${frontmatter}\n---\n${content}`; }