trilium/src/public/javascripts/services/bundle.js

49 lines
1.5 KiB
JavaScript
Raw Normal View History

2018-03-26 09:29:35 +08:00
import ScriptContext from "./script_context.js";
import server from "./server.js";
2019-10-20 16:00:18 +08:00
import toastService from "./toast.js";
2018-08-10 19:30:20 +08:00
async function getAndExecuteBundle(noteId, originEntity = null) {
const bundle = await server.get('script/bundle/' + noteId);
2019-08-17 17:28:36 +08:00
return await executeBundle(bundle, originEntity);
}
2019-10-05 16:55:29 +08:00
async function executeBundle(bundle, originEntity, tabContext, $container) {
const apiContext = await ScriptContext(bundle.noteId, bundle.allNoteIds, originEntity, tabContext, $container);
try {
return await (function () {
return eval(`const apiContext = this; (async function() { ${bundle.script}\r\n})()`);
}.call(apiContext));
}
catch (e) {
2019-10-20 16:00:18 +08:00
toastService.showAndLogError(`Execution of ${bundle.noteId} failed with error: ${e.message}`);
}
}
async function executeStartupBundles() {
const scriptBundles = await server.get("script/startup");
for (const bundle of scriptBundles) {
await executeBundle(bundle);
}
}
async function executeRelationBundles(note, relationName, tabContext) {
note.bundleCache = note.bundleCache || {};
if (!note.bundleCache[relationName]) {
note.bundleCache[relationName] = await server.get("script/relation/" + note.noteId + "/" + relationName);
}
for (const bundle of note.bundleCache[relationName]) {
await executeBundle(bundle, note, tabContext);
}
}
export default {
executeBundle,
getAndExecuteBundle,
executeStartupBundles,
executeRelationBundles
}