2024-03-16 22:29:24 +08:00
|
|
|
import { findNodeOfType, traverseTree } from "./tree.ts";
|
|
|
|
import { markdown, space, YAML } from "../syscalls.ts";
|
2022-07-15 17:17:02 +08:00
|
|
|
|
2023-01-24 01:52:17 +08:00
|
|
|
export async function readCodeBlockPage(
|
2022-07-15 17:17:02 +08:00
|
|
|
pageName: string,
|
2023-01-24 01:52:17 +08:00
|
|
|
allowedLanguages?: string[],
|
|
|
|
): Promise<string | undefined> {
|
2022-10-14 21:11:33 +08:00
|
|
|
const text = await space.readPage(pageName);
|
|
|
|
const tree = await markdown.parseMarkdown(text);
|
2023-01-24 01:52:17 +08:00
|
|
|
let codeText: string | undefined;
|
2022-07-15 17:17:02 +08:00
|
|
|
|
|
|
|
traverseTree(tree, (t): boolean => {
|
|
|
|
// Find a fenced code block
|
|
|
|
if (t.type !== "FencedCode") {
|
|
|
|
return false;
|
|
|
|
}
|
2022-10-14 21:11:33 +08:00
|
|
|
const codeInfoNode = findNodeOfType(t, "CodeInfo");
|
2023-01-24 01:52:17 +08:00
|
|
|
if (allowedLanguages && !codeInfoNode) {
|
2022-07-15 17:17:02 +08:00
|
|
|
return false;
|
|
|
|
}
|
2023-01-24 01:52:17 +08:00
|
|
|
if (
|
|
|
|
allowedLanguages &&
|
|
|
|
!allowedLanguages.includes(codeInfoNode!.children![0].text!)
|
|
|
|
) {
|
2022-07-15 17:17:02 +08:00
|
|
|
return false;
|
|
|
|
}
|
2022-10-14 21:11:33 +08:00
|
|
|
const codeTextNode = findNodeOfType(t, "CodeText");
|
2022-07-15 17:17:02 +08:00
|
|
|
if (!codeTextNode) {
|
|
|
|
// Honestly, this shouldn't happen
|
|
|
|
return false;
|
|
|
|
}
|
2023-01-24 01:52:17 +08:00
|
|
|
codeText = codeTextNode.children![0].text!;
|
2022-07-15 17:17:02 +08:00
|
|
|
return true;
|
|
|
|
});
|
|
|
|
|
2023-01-24 01:52:17 +08:00
|
|
|
return codeText;
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function readYamlPage(
|
|
|
|
pageName: string,
|
|
|
|
allowedLanguages = ["yaml"],
|
|
|
|
): Promise<any> {
|
|
|
|
const codeText = await readCodeBlockPage(pageName, allowedLanguages);
|
|
|
|
if (codeText === undefined) {
|
|
|
|
return undefined;
|
|
|
|
}
|
|
|
|
try {
|
|
|
|
return YAML.parse(codeText);
|
|
|
|
} catch (e: any) {
|
|
|
|
console.error("YAML Page parser error", e);
|
|
|
|
throw new Error(`YAML Error: ${e.message}`);
|
|
|
|
}
|
2022-07-15 17:17:02 +08:00
|
|
|
}
|
2022-09-01 16:17:20 +08:00
|
|
|
|
|
|
|
export async function writeYamlPage(
|
|
|
|
pageName: string,
|
2022-10-10 20:50:21 +08:00
|
|
|
data: any,
|
2022-11-20 17:56:52 +08:00
|
|
|
prelude = "",
|
2022-09-01 16:17:20 +08:00
|
|
|
): Promise<void> {
|
2023-05-24 02:53:53 +08:00
|
|
|
const text = await YAML.stringify(data);
|
2022-11-20 17:56:52 +08:00
|
|
|
await space.writePage(pageName, prelude + "```yaml\n" + text + "\n```");
|
2022-09-01 16:17:20 +08:00
|
|
|
}
|