markdown2html/src/frontmatter.ts

27 lines
601 B
TypeScript

import * as yaml from 'yaml';
export function process_frontmatter(raw_document: string, parse = true) {
if (! raw_document.startsWith('---\n')) {
return {
frontmatter: null,
document: raw_document,
};
}
const end_index = raw_document.slice(3).indexOf('\n---\n') + 3;
if (end_index === 2) {
return {
frontmatter: null,
document: raw_document,
};
}
const formatter_yaml = raw_document.slice(3, end_index);
const document = raw_document.slice(end_index + 4);
const frontmatter = parse ? yaml.parse(formatter_yaml) : formatter_yaml;
return { frontmatter, document };
}