import { mkdir, readFile, writeFile } from "node:fs/promises"; import path from "node:path"; import { type z } from "zod"; import { parseMarkdownFrontmatter, stringifyMarkdownFrontmatter, } from "./frontmatter.js"; import { type PonyProject, projectRelativePath } from "./project.js"; export interface MarkdownRecord { data: TData; body: string; absolutePath: string; path: string; } export async function readMarkdownRecord( project: PonyProject, filePath: string, schema: TSchema, ): Promise>> { const raw = await readFile(filePath, "utf8"); const parsed = parseMarkdownFrontmatter(raw); return { data: schema.parse(parsed.data), body: parsed.content.trimEnd(), absolutePath: filePath, path: projectRelativePath(project, filePath), }; } export async function writeMarkdownRecord( filePath: string, data: TData, body: string, ): Promise { await mkdir(path.dirname(filePath), { recursive: true }); await writeFile(filePath, serializeMarkdownRecord(data, body), "utf8"); } export function serializeMarkdownRecord( data: TData, body: string, ): string { const content = stringifyMarkdownFrontmatter(body.trimEnd(), data); return `${content.trimEnd()}\n`; } export function parseMarkdownRecord( raw: string, schema: TSchema, ): { data: z.infer; body: string } { const parsed = parseMarkdownFrontmatter(raw); return { data: schema.parse(parsed.data), body: parsed.content.trimEnd(), }; }