on 503ca8f help sign in
urbit.org/lib/cache.js
86 lines 2.3 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 const slug = dir.includes("/grants/")
44 ? `/grants/${page.name.replace(/.md$/, "")}`
45 : path.join(
46 dir.substr(dir.indexOf("content") + 7),
47 "/",
48 page.name.replace(/.md$/, "")
49 );
50 return {
51 title: pageData.title,
52 base: page.name,
53 slug,
54 content: pageData.description || "",
55 headings: transform.children
56 .filter((e) => e.name === "h2" || e.name === "h3")
57 .map((e) => e.children)
58 .flat()
59 .filter((e) => typeof e === "string"),
60 parent: metadata.data.title,
61 };
62 })
63 );
65 Object.fromEntries(
66 subdirs.map((subdir) => [
67 subdir.name,
68 buildSearchIndex(path.join(dir, subdir.name)),
69 ])
70 );
73buildSearchIndex(path.join(process.cwd(), "content"));
75const fileContents = `export const index = ${JSON.stringify(index)}`;
77try {
78 fs.readdirSync("cache");
79} catch (err) {
80 fs.mkdirSync("cache");
83fs.writeFile("cache/data.js", fileContents, function (err) {
84 if (err) return console.error(err);
85 console.log("Site index created.");
86});