Files
Trilium/apps/server/src/services/script.ts

263 lines
8.1 KiB
TypeScript
Raw Normal View History

import { transform } from "sucrase";
import becca from "../becca/becca.js";
import type BNote from "../becca/entities/bnote.js";
import type { ApiParams } from "./backend_script_api_interface.js";
import cls from "./cls.js";
import log from "./log.js";
import ScriptContext from "./script_context.js";
2024-04-04 22:47:58 +03:00
export interface Bundle {
2024-04-04 22:47:58 +03:00
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
}
}
export 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);
}
return JSON.stringify(p);
2025-01-09 18:07:02 +02:00
})
.join(",");
}
2024-04-06 22:38:17 +03:00
function getScriptBundleForFrontend(note: BNote, script?: string, params?: ScriptParams) {
2025-05-28 19:57:55 +03:00
let overrideContent: string | null = 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;
}
export 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() || note.isJsx())) {
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 = {
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
2025-05-28 19:57:55 +03:00
const modules: BNote[] = [];
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";
if (note.isJsx() || note.isJavaScript()) {
let scriptContent = note.getContent();
if (note.isJsx()) {
2025-12-20 21:35:52 +02:00
scriptContent = buildJsx(scriptContent).code;
}
2018-03-04 21:05:14 -05:00
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 || scriptContent};
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
}
2025-12-20 21:35:52 +02:00
export function buildJsx(contentRaw: string | Buffer) {
const content = Buffer.isBuffer(contentRaw) ? contentRaw.toString("utf-8") : contentRaw;
const output = transform(content, {
transforms: ["jsx", "imports"],
jsxPragma: "api.preact.h",
jsxFragmentPragma: "api.preact.Fragment",
2025-12-21 13:31:44 +02:00
production: true
});
2025-12-23 13:06:33 +02:00
let code = output.code;
// Rewrite ESM-like exports to `module.exports =`.
2025-12-23 13:06:33 +02:00
code = code.replaceAll(
/\bexports\s*\.\s*default\s*=\s*/g,
'module.exports = '
);
// Rewrite ESM-like imports to Preact, to `const { foo } = api.preact`
code = code.replaceAll(
/(?:var|let|const)\s+(\w+)\s*=\s*require\(['"]trilium:preact['"]\);?/g,
'const $1 = api.preact;'
);
2025-12-23 13:06:33 +02:00
// Rewrite ESM-like imports to internal API, to `const { foo } = api`
code = code.replaceAll(
/(?:var|let|const)\s+(\w+)\s*=\s*require\(['"]trilium:api['"]\);?/g,
'const $1 = api;'
);
output.code = code;
return output;
}
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
};