import { toText } from "hast-util-to-text"; import remarkFrontmatter from "remark-frontmatter"; import remarkGfm from "remark-gfm"; import remarkParse from "remark-parse"; import remarkRehype from "remark-rehype"; import { unified } from "unified"; const processor = unified() .use(remarkParse) .use(remarkFrontmatter, ["yaml", "toml"]) .use(remarkGfm) .use(remarkRehype); function fallbackTitle(filePath) { return filePath.toLowerCase().endsWith(".md") ? filePath.slice(0, -3) : filePath; } export function analyzeMarkdown(markdown, filePath) { const mdast = processor.parse(markdown); const hast = processor.runSync(mdast); const heading = hast.children.find( (node) => node.type === "element" && node.tagName === "h1", ); return { title: heading ? toText(heading).trim() : fallbackTitle(filePath), textContent: toText(hast).trim(), }; }