summaryrefslogtreecommitdiffhomepage
path: root/vhosts/blog/nuldoc-src/djot/parse.ts
blob: 884ab1547d23a755cb79601a6454841526486e38 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import { parse as parseDjot } from "@djot/djot";
import { parse as parseToml } from "@std/toml";
import { Config } from "../config.ts";
import {
  createNewDocumentFromDjotDocument,
  Document,
  PostMetadata,
  PostMetadataSchema,
} from "./document.ts";
import toHtml from "./to_html.ts";

export async function parseDjotFile(
  filePath: string,
  config: Config,
): Promise<Document> {
  try {
    const fileContent = await Deno.readTextFile(filePath);
    const parts = fileContent.split(/^---$/m);
    const meta = parseMetadata(parts[1]);
    const root = parseDjot(parts[2]);
    const doc = createNewDocumentFromDjotDocument(root, meta, filePath, config);
    return await toHtml(doc);
  } catch (e) {
    if (e instanceof Error) {
      e.message = `${e.message} in ${filePath}`;
    }
    throw e;
  }
}

function parseMetadata(s: string): PostMetadata {
  return PostMetadataSchema.parse(parseToml(s));
}