import fs from "fs"; import path from "path"; import matter from "gray-matter"; import { AREAS } from "@/lib/catalog"; import type { LessonMeta } from "@/lib/lesson-types"; export * from "@/lib/lesson-types"; export type Lesson = LessonMeta & { body: string }; const CONTENT_DIR = path.join(process.cwd(), "content", "lessons"); // gray-matter parses unquoted YAML dates into Date objects function isoDay(value: unknown): string { return value instanceof Date ? value.toISOString().slice(0, 10) : String(value ?? "").slice(0, 10); } function readLesson(area: string, field: string, file: string): Lesson { const raw = fs.readFileSync(path.join(CONTENT_DIR, area, field, file), "utf8"); const { data, content } = matter(raw); const where = `${area}/${field}/${file}`; if (!data.title || !data.description || !data.updated) { throw new Error(`Lesson ${where} needs a title, description and updated date`); } return { area, field, slug: file.replace(/\.mdx$/, ""), title: data.title, description: data.description, level: data.level ?? "Beginner", minutes: data.minutes ?? 10, updated: isoDay(data.updated), order: typeof data.order === "number" ? data.order : 99, body: content, }; } let cache: Lesson[] | null = null; export function getAllLessons(): Lesson[] { if (cache) return cache; cache = AREAS.flatMap((area) => area.fields.flatMap((field) => { const dir = path.join(CONTENT_DIR, area.slug, field.slug); if (!fs.existsSync(dir)) return []; return fs .readdirSync(dir) .filter((f) => f.endsWith(".mdx")) .map((f) => readLesson(area.slug, field.slug, f)); }) ).sort((a, b) => a.order - b.order || a.title.localeCompare(b.title)); return cache; } export function getLessonMetas(): LessonMeta[] { return getAllLessons().map(({ body, ...meta }) => meta); } export function getFieldLessons(field: string): LessonMeta[] { return getLessonMetas().filter((l) => l.field === field); } export function getLesson(area: string, field: string, slug: string): Lesson | undefined { return getAllLessons().find((l) => l.area === area && l.field === field && l.slug === slug); }