import "server-only"; import fs from "node:fs/promises"; import path from "node:path"; export interface MarkdownCache { [key: string]: string; } let markdownCacheInstance: MarkdownCache | null = null; let initPromise: Promise | null = null; // Loads .md files from `contentDirPath` (relative to process.cwd()), strips // frontmatter, keys entries by `/blog/`. Singleton + in-flight // memo so SSR pages compiling in parallel share one read. export async function loadMarkdownContent({ contentDirPath, }: { contentDirPath: string; }): Promise { if (markdownCacheInstance !== null) return markdownCacheInstance; if (initPromise !== null) return initPromise; initPromise = (async () => { const cache: MarkdownCache = {}; const contentDir = path.join(process.cwd(), contentDirPath); const files = await fs.readdir(contentDir); await Promise.all( files .filter((file) => file.endsWith(".md")) .map(async (file) => { const filePath = path.join(contentDir, file); const content = await fs.readFile(filePath, "utf-8"); const body = content.replace(/^---\n[\s\S]*?\n---\n/, ""); const slug = `/blog/${file.replace(".md", "")}`; cache[slug] = body; }), ); markdownCacheInstance = cache; return cache; })(); return initPromise; } export function getMarkdownFromCache(cache: MarkdownCache, key: string): string | undefined { return cache[key]; } export function clearMarkdownCache(): void { markdownCacheInstance = null; initPromise = null; }