(raw: string, sourcePath?: string)
| 6 | } |
| 7 | |
| 8 | export function parseFrontmatter(raw: string, sourcePath?: string): FrontmatterResult { |
| 9 | const lines = raw.split(/\r?\n/) |
| 10 | if (lines.length === 0 || lines[0].trim() !== "---") { |
| 11 | return { data: {}, body: raw } |
| 12 | } |
| 13 | |
| 14 | let endIndex = -1 |
| 15 | for (let i = 1; i < lines.length; i += 1) { |
| 16 | if (lines[i].trim() === "---") { |
| 17 | endIndex = i |
| 18 | break |
| 19 | } |
| 20 | } |
| 21 | |
| 22 | if (endIndex === -1) { |
| 23 | return { data: {}, body: raw } |
| 24 | } |
| 25 | |
| 26 | const yamlText = lines.slice(1, endIndex).join("\n") |
| 27 | const body = lines.slice(endIndex + 1).join("\n") |
| 28 | try { |
| 29 | const parsed = load(yamlText) |
| 30 | const data = (parsed && typeof parsed === "object") ? (parsed as Record<string, unknown>) : {} |
| 31 | return { data, body } |
| 32 | } catch (err) { |
| 33 | const location = sourcePath ? ` in ${sourcePath}` : "" |
| 34 | const hint = "Tip: quote frontmatter values containing colons (e.g. description: 'Use for X: Y')" |
| 35 | throw new Error(`Invalid YAML frontmatter${location}: ${err instanceof Error ? err.message : err}\n${hint}`) |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | export function formatFrontmatter(data: Record<string, unknown>, body: string): string { |
| 40 | const yaml = Object.entries(data) |
no outgoing calls