on cd16bed help sign in
urbit.org/lib/cache.js
83 lines 2.1 kB history raw
1const fs = require("fs");
2const path = require("path");
3const matter = require("gray-matter");
4const toml = require("@iarna/toml");
5const markdoc = require("@urbit/markdoc");
7const options = {
8 engines: {
9 toml: toml.parse.bind(toml),
10 },
11 language: "toml",
12 delimiters: "+++",
13};
15const index = [];
17function buildSearchIndex(dir) {
18 const dirName = dir.split("/").slice(-1).join("");
19 let metadata = {
20 data: {
21 title: dirName.charAt(0).toUpperCase() + dirName.slice(1),
22 },
23 };
25 try {
26 metadata = matter(fs.readFileSync(path.join(dir, "_index.md")), options);
27 } catch (err) {}
29 const children = fs.readdirSync(dir, { withFileTypes: true });
30 const pages = children.filter((f) => f.isFile() && f.name !== "_index.md");
31 const subdirs = children.filter(
32 (f) => f.isDirectory() && f.name !== "ids" && f.name !== "glossary"
33 );
35 index.push(
36 ...pages.map((page) => {
37 const { data: pageData, content: pageContent } = matter(
38 fs.readFileSync(path.join(dir, page.name)),
39 options
40 );
41 const parsed = markdoc.parse(pageContent);
42 const transform = markdoc.transform(parsed);
43 return {
44 title: pageData.title,
45 base: page.name,
46 slug: path.join(
47 dir.substr(dir.indexOf("content") + 7),
48 "/",
49 page.name.replace(/.md$/, "")
50 ),
51 content: pageData.description || "",
52 headings: transform.children
53 .filter((e) => e.name === "h2" || e.name === "h3")
54 .map((e) => e.children)
55 .flat()
56 .filter((e) => typeof e === "string"),
57 parent: metadata.data.title,
58 };
59 })
60 );
62 Object.fromEntries(
63 subdirs.map((subdir) => [
64 subdir.name,
65 buildSearchIndex(path.join(dir, subdir.name)),
66 ])
67 );
70buildSearchIndex(path.join(process.cwd(), "content"));
72const fileContents = `export const index = ${JSON.stringify(index)}`;
74try {
75 fs.readdirSync("cache");
76} catch (err) {
77 fs.mkdirSync("cache");
80fs.writeFile("cache/data.js", fileContents, function (err) {
81 if (err) return console.error(err);
82 console.log("Site index created.");
83});