2022-10-28 14:17:40 +00:00
|
|
|
// This is some shocking stuff. My profession would kill me for this.
|
|
|
|
|
2023-08-28 15:12:15 +00:00
|
|
|
import { YAML } from "$sb/syscalls.ts";
|
2022-12-15 11:59:38 +00:00
|
|
|
import { ParseTree } from "$sb/lib/tree.ts";
|
2022-10-28 14:17:40 +00:00
|
|
|
import { jsonToMDTable, renderTemplate } from "./util.ts";
|
2023-08-28 15:12:15 +00:00
|
|
|
import type { PageMeta } from "../../web/types.ts";
|
|
|
|
import { replaceTemplateVars } from "../template/template.ts";
|
2022-10-28 14:17:40 +00:00
|
|
|
|
|
|
|
// Enables plugName.functionName(arg1, arg2) syntax in JS expressions
|
|
|
|
function translateJs(js: string): string {
|
|
|
|
return js.replaceAll(
|
|
|
|
/(\w+\.\w+)\s*\(/g,
|
|
|
|
'await invokeFunction("$1", ',
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Syntaxes to support:
|
|
|
|
// - random JS expression
|
|
|
|
// - random JS expression render [[some/template]]
|
|
|
|
const expressionRegex = /(.+?)(\s+render\s+\[\[([^\]]+)\]\])?$/;
|
|
|
|
|
|
|
|
// This is rather scary and fragile stuff, but it works.
|
|
|
|
export async function evalDirectiveRenderer(
|
|
|
|
_directive: string,
|
2023-07-02 09:25:32 +00:00
|
|
|
pageMeta: PageMeta,
|
2022-12-14 19:04:20 +00:00
|
|
|
expression: string | ParseTree,
|
2022-10-28 14:17:40 +00:00
|
|
|
): Promise<string> {
|
2022-12-14 19:04:20 +00:00
|
|
|
if (typeof expression !== "string") {
|
|
|
|
throw new Error("Expected a string");
|
|
|
|
}
|
2023-07-02 09:25:32 +00:00
|
|
|
// console.log("Got JS expression", expression);
|
2022-10-28 14:17:40 +00:00
|
|
|
const match = expressionRegex.exec(expression);
|
|
|
|
if (!match) {
|
|
|
|
throw new Error(`Invalid eval directive: ${expression}`);
|
|
|
|
}
|
|
|
|
let template = "";
|
|
|
|
if (match[3]) {
|
|
|
|
// This is the template reference
|
|
|
|
expression = match[1];
|
|
|
|
template = match[3];
|
|
|
|
}
|
|
|
|
try {
|
|
|
|
// Why the weird "eval" call? https://esbuild.github.io/content-types/#direct-eval
|
|
|
|
const result = await (0, eval)(
|
|
|
|
`(async () => {
|
|
|
|
function invokeFunction(name, ...args) {
|
2023-08-28 15:12:15 +00:00
|
|
|
return syscall("system.invokeFunction", name, ...args);
|
2022-10-28 14:17:40 +00:00
|
|
|
}
|
2023-07-02 09:25:32 +00:00
|
|
|
return ${replaceTemplateVars(translateJs(expression), pageMeta)};
|
2022-10-28 14:17:40 +00:00
|
|
|
})()`,
|
|
|
|
);
|
|
|
|
if (template) {
|
2023-07-02 09:25:32 +00:00
|
|
|
return await renderTemplate(pageMeta, template, result);
|
2022-10-28 14:17:40 +00:00
|
|
|
}
|
|
|
|
if (typeof result === "string") {
|
|
|
|
return result;
|
|
|
|
} else if (typeof result === "number") {
|
|
|
|
return "" + result;
|
|
|
|
} else if (Array.isArray(result)) {
|
|
|
|
return jsonToMDTable(result);
|
|
|
|
}
|
2023-05-23 18:53:53 +00:00
|
|
|
return await YAML.stringify(result);
|
2022-10-28 14:17:40 +00:00
|
|
|
} catch (e: any) {
|
|
|
|
return `**ERROR:** ${e.message}`;
|
|
|
|
}
|
|
|
|
}
|