Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899const FRONTMATTER_RE = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n)?/;
function titleLine(title: string): string { return `title: ${JSON.stringify(title)}`;}
function parseTitleLine(line: string): string | null { const match = line.match(/^title:\s*(.+)$/); if (!match) { return null; }
const value = (match[1] ?? "").trim(); if (value.length === 0) { return ""; }
if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) { try { return JSON.parse(value); } catch { return value.slice(1, -1); } }
return value;}
function splitFrontmatter(text: string): { frontmatter: string | null; body: string } { const match = text.match(FRONTMATTER_RE); if (!match) { return { frontmatter: null, body: text }; }
const body = text.slice(match[0].length).replace(/^\r?\n/, ""); return { frontmatter: match[1] ?? null, body };}
export function applyDocumentTitle(text: string, title: string): string { const { frontmatter, body } = splitFrontmatter(text); if (frontmatter === null) { return `---\n${titleLine(title)}\n---\n\n${text}`; }
const lines = frontmatter.split(/\r?\n/); let replaced = false; const updatedLines: string[] = [];
for (const line of lines) { if (!replaced && parseTitleLine(line) !== null) { updatedLines.push(titleLine(title)); replaced = true; continue; } updatedLines.push(line); }
if (!replaced) { updatedLines.unshift(titleLine(title)); }
const frontmatterText = updatedLines.join("\n"); if (body.length === 0) { return `---\n${frontmatterText}\n---`; }
return `---\n${frontmatterText}\n---\n\n${body}`;}
export function extractDocumentTitle(text: string, fallbackTitle: string): { title: string; body: string } { const { frontmatter, body } = splitFrontmatter(text); if (frontmatter === null) { return { title: fallbackTitle, body: text }; }
const lines = frontmatter.split(/\r?\n/); let title = fallbackTitle; const keptLines: string[] = [];
for (const line of lines) { const parsed = parseTitleLine(line); if (parsed !== null) { title = parsed.length > 0 ? parsed : fallbackTitle; continue; } keptLines.push(line); }
if (keptLines.length === 0) { return { title, body }; }
const frontmatterText = `---\n${keptLines.join("\n")}\n---`; return { title, body: body.length > 0 ? `${frontmatterText}\n\n${body}` : frontmatterText, };}