Notes/src/services/script.ts

223 lines
6.9 KiB
TypeScript
Raw Normal View History

import ScriptContext from "./script_context.js";
import cls from "./cls.js";
import log from "./log.js";
import becca from "../becca/becca.js";
import BNote from "../becca/entities/bnote.js";
import type { ApiParams } from "./backend_script_api_interface.js";
2024-04-04 22:47:58 +03:00
interface Bundle {
note?: BNote;
noteId?: string;
script: string;
html: string;
allNotes?: BNote[];
allNoteIds?: string[];
}
type ScriptParams = any[];
2024-04-04 22:47:58 +03:00
function executeNote(note: BNote, apiParams: ApiParams) {
2025-01-09 18:07:02 +02:00
if (!note.isJavaScript() || note.getScriptEnv() !== "backend" || !note.isContentAvailable()) {
2022-01-05 19:48:18 +01:00
log.info(`Cannot execute note ${note.noteId} "${note.title}", note must be of type "Code: JS backend"`);
return;
}
2025-01-09 18:07:02 +02:00
const bundle = getScriptBundle(note, true, "backend");
2024-04-04 22:47:58 +03:00
if (!bundle) {
throw new Error("Unable to determine bundle.");
}
2020-06-20 12:31:38 +02:00
return executeBundle(bundle, apiParams);
}
2024-04-04 22:47:58 +03:00
function executeNoteNoException(note: BNote, apiParams: ApiParams) {
try {
executeNote(note, apiParams);
2025-01-09 18:07:02 +02:00
} catch (e) {
// just swallow, exception is logged already in executeNote
}
}
2024-04-04 22:47:58 +03:00
function executeBundle(bundle: Bundle, apiParams: ApiParams = {}) {
if (!apiParams.startNote) {
// this is the default case, the only exception is when we want to preserve frontend startNote
apiParams.startNote = bundle.note;
}
2025-01-09 18:07:02 +02:00
const originalComponentId = cls.get("componentId");
2025-01-09 18:07:02 +02:00
cls.set("componentId", "script");
cls.set("bundleNoteId", bundle.note?.noteId);
2019-10-19 15:12:25 +02:00
2023-06-30 11:18:34 +02:00
// last \r\n is necessary if the script contains line comment on its last line
const script = `function() {\r
${bundle.script}\r
}`;
2024-04-04 22:47:58 +03:00
const ctx = new ScriptContext(bundle.allNotes || [], apiParams);
2018-03-04 10:32:53 -05:00
try {
return execute(ctx, script);
2025-01-09 18:07:02 +02:00
} catch (e: any) {
2024-04-04 22:47:58 +03:00
log.error(`Execution of script "${bundle.note?.title}" (${bundle.note?.noteId}) failed with error: ${e.message}`);
throw e;
2025-01-09 18:07:02 +02:00
} finally {
cls.set("componentId", originalComponentId);
}
}
/**
* THIS METHOD CAN'T BE ASYNC, OTHERWISE TRANSACTION WRAPPER WON'T BE EFFECTIVE AND WE WILL BE LOSING THE
* ENTITY CHANGES IN CLS.
*
* This method preserves frontend startNode - that's why we start execution from currentNote and override
* bundle's startNote.
*/
2024-04-04 22:47:58 +03:00
function executeScript(script: string, params: ScriptParams, startNoteId: string, currentNoteId: string, originEntityName: string, originEntityId: string) {
2021-05-02 11:23:58 +02:00
const startNote = becca.getNote(startNoteId);
const currentNote = becca.getNote(currentNoteId);
2021-05-17 22:05:35 +02:00
const originEntity = becca.getEntity(originEntityName, originEntityId);
2024-04-04 22:47:58 +03:00
if (!currentNote) {
throw new Error("Cannot find note.");
}
// we're just executing an excerpt of the original frontend script in the backend context, so we must
// override normal note's content, and it's mime type / script environment
const overrideContent = `return (${script}\r\n)(${getParams(params)})`;
2025-01-09 18:07:02 +02:00
const bundle = getScriptBundle(currentNote, true, "backend", [], overrideContent);
2024-04-04 22:47:58 +03:00
if (!bundle) {
throw new Error("Unable to determine script bundle.");
}
return executeBundle(bundle, { startNote, originEntity });
2018-02-24 22:44:45 -05:00
}
2024-04-10 19:26:08 +03:00
function execute(ctx: ScriptContext, script: string) {
2025-01-09 18:07:02 +02:00
return function () {
return eval(`const apiContext = this;\r\n(${script}\r\n)()`);
}.call(ctx);
}
2024-04-06 22:38:17 +03:00
function getParams(params?: ScriptParams) {
if (!params) {
return params;
}
2025-01-09 18:07:02 +02:00
return params
.map((p) => {
if (typeof p === "string" && p.startsWith("!@#Function: ")) {
return p.substr(13);
} else {
return JSON.stringify(p);
}
})
.join(",");
}
2024-04-06 22:38:17 +03:00
function getScriptBundleForFrontend(note: BNote, script?: string, params?: ScriptParams) {
let overrideContent = null;
if (script) {
overrideContent = `return (${script}\r\n)(${getParams(params)})`;
}
2025-01-09 18:07:02 +02:00
const bundle = getScriptBundle(note, true, "frontend", [], overrideContent);
2019-08-25 21:55:36 +02:00
if (!bundle) {
return;
}
// for frontend, we return just noteIds because frontend needs to use its own entity instances
2024-04-04 22:47:58 +03:00
bundle.noteId = bundle.note?.noteId;
delete bundle.note;
2025-01-09 18:07:02 +02:00
bundle.allNoteIds = bundle.allNotes?.map((note) => note.noteId);
delete bundle.allNotes;
return bundle;
}
2024-04-04 22:47:58 +03:00
function getScriptBundle(note: BNote, root: boolean = true, scriptEnv: string | null = null, includedNoteIds: string[] = [], overrideContent: string | null = null): Bundle | undefined {
2021-05-17 22:35:36 +02:00
if (!note.isContentAvailable()) {
return;
}
if (!note.isJavaScript() && !note.isHtml()) {
2018-03-04 12:06:35 -05:00
return;
}
2018-03-04 10:32:53 -05:00
2025-01-09 18:07:02 +02:00
if (!root && note.hasOwnedLabel("disableInclusion")) {
2018-03-04 22:09:51 -05:00
return;
}
2025-01-09 18:07:02 +02:00
if (note.type !== "file" && !root && scriptEnv !== note.getScriptEnv()) {
return;
}
2024-04-04 22:47:58 +03:00
const bundle: Bundle = {
2018-03-04 12:06:35 -05:00
note: note,
2025-01-09 18:07:02 +02:00
script: "",
html: "",
2018-03-04 12:06:35 -05:00
allNotes: [note]
};
2018-03-03 09:11:41 -05:00
2018-03-04 12:06:35 -05:00
if (includedNoteIds.includes(note.noteId)) {
return bundle;
}
2018-03-03 09:11:41 -05:00
2018-03-04 12:06:35 -05:00
includedNoteIds.push(note.noteId);
2018-03-04 10:32:53 -05:00
2018-03-04 12:06:35 -05:00
const modules = [];
2018-03-03 09:11:41 -05:00
2020-06-20 12:31:38 +02:00
for (const child of note.getChildNotes()) {
const childBundle = getScriptBundle(child, false, scriptEnv, includedNoteIds);
2018-03-04 10:32:53 -05:00
2018-03-04 12:06:35 -05:00
if (childBundle) {
2024-04-04 22:47:58 +03:00
if (childBundle.note) {
modules.push(childBundle.note);
}
2018-03-04 12:06:35 -05:00
bundle.script += childBundle.script;
2018-03-04 21:05:14 -05:00
bundle.html += childBundle.html;
2024-04-04 22:47:58 +03:00
if (bundle.allNotes && childBundle.allNotes) {
bundle.allNotes = bundle.allNotes.concat(childBundle.allNotes);
}
2018-03-04 12:06:35 -05:00
}
2018-03-03 09:11:41 -05:00
}
2025-01-09 18:07:02 +02:00
const moduleNoteIds = modules.map((mod) => mod.noteId);
// only frontend scripts are async. Backend cannot be async because of transaction management.
2025-01-09 18:07:02 +02:00
const isFrontend = scriptEnv === "frontend";
2018-03-04 21:05:14 -05:00
if (note.isJavaScript()) {
bundle.script += `
apiContext.modules['${note.noteId}'] = { exports: {} };
2025-01-09 18:07:02 +02:00
${root ? "return " : ""}${isFrontend ? "await" : ""} ((${isFrontend ? "async" : ""} function(exports, module, require, api${modules.length > 0 ? ", " : ""}${modules.map((child) => sanitizeVariableName(child.title)).join(", ")}) {
2018-08-22 14:40:49 +02:00
try {
${overrideContent || note.getContent()};
2018-08-22 14:40:49 +02:00
} catch (e) { throw new Error("Load of script note \\"${note.title}\\" (${note.noteId}) failed with: " + e.message); }
2018-08-19 22:28:32 +02:00
for (const exportKey in exports) module.exports[exportKey] = exports[exportKey];
2019-08-17 11:28:36 +02:00
return module.exports;
2025-01-09 18:07:02 +02:00
}).call({}, {}, apiContext.modules['${note.noteId}'], apiContext.require(${JSON.stringify(moduleNoteIds)}), apiContext.apis['${note.noteId}']${modules.length > 0 ? ", " : ""}${modules.map((mod) => `apiContext.modules['${mod.noteId}'].exports`).join(", ")}));
2018-03-04 12:06:35 -05:00
`;
2025-01-09 18:07:02 +02:00
} else if (note.isHtml()) {
2020-06-20 12:31:38 +02:00
bundle.html += note.getContent();
2018-03-04 21:05:14 -05:00
}
2018-03-04 10:32:53 -05:00
2018-03-04 12:06:35 -05:00
return bundle;
2018-03-03 09:11:41 -05:00
}
2024-04-04 22:47:58 +03:00
function sanitizeVariableName(str: string) {
return str.replace(/[^a-z0-9_]/gim, "");
}
export default {
executeNote,
executeNoteNoException,
executeScript,
getScriptBundleForFrontend
2020-06-15 17:56:53 +02:00
};