frontmatter.ts
796 Bytes
import * as yaml from "js-yaml";
export interface ParsedMarkdown {
data: Record<string, unknown> | null;
body: string;
}
const FRONTMATTER_RE = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/;
export function parseFrontmatter(content: string): ParsedMarkdown {
if (!content) {
return { data: null, body: content ?? "" };
}
const match = content.match(FRONTMATTER_RE);
if (!match) {
return { data: null, body: content };
}
const rawYaml = match[1];
const body = content.slice(match[0].length);
try {
const data = yaml.load(rawYaml);
if (data && typeof data === "object" && !Array.isArray(data)) {
return { data: data as Record<string, unknown>, body };
}
return { data: null, body: content };
} catch {
return { data: null, body: content };
}
}