diff --git a/src/public/javascripts/api.js b/src/public/javascripts/api.js index 9d5844232..266304ed1 100644 --- a/src/public/javascripts/api.js +++ b/src/public/javascripts/api.js @@ -1,4 +1,12 @@ -function Api(startNote, allNotes) { +function ApiContext(startNote, allNotes) { + return { + modules: {}, + notes: toObject(allNotes, note => [note.noteId, note]), + apis: toObject(allNotes, note => [note.noteId, Api(startNote, note)]), + }; +} + +function Api(startNote, currentNote) { const $pluginButtons = $("#plugin-buttons"); async function activateNote(notePath) { @@ -28,7 +36,7 @@ function Api(startNote, allNotes) { }); } - async function runOnServer(script, params) { + async function runOnServer(script, params = []) { if (typeof script === "function") { script = script.toString(); } @@ -36,16 +44,16 @@ function Api(startNote, allNotes) { const ret = await server.post('script/exec', { script: script, params: prepareParams(params), - startNoteId: startNote.noteId + startNoteId: startNote.noteId, + currentNoteId: currentNote.noteId }); return ret.executionResult; } return { - __startNote: startNote, - __notes: toObject(allNotes, note => [note.noteId, note]), - __modules: {}, + startNote: startNote, + currentNote: currentNote, addButtonToToolbar, activateNote, getInstanceName: noteTree.getInstanceName, diff --git a/src/public/javascripts/init.js b/src/public/javascripts/init.js index a9f445c27..51a31ade5 100644 --- a/src/public/javascripts/init.js +++ b/src/public/javascripts/init.js @@ -201,9 +201,9 @@ window.onerror = function (msg, url, lineNo, columnNo, error) { $("#logout-button").toggle(!isElectron()); $(document).ready(() => { - server.get("script/startup").then(scripts => { - for (const script of scripts) { - executeBundle(script); + server.get("script/startup").then(scriptBundles => { + for (const bundle of scriptBundles) { + executeBundle(bundle); } }); }); diff --git a/src/public/javascripts/note_editor.js b/src/public/javascripts/note_editor.js index 971f932f0..c685ed386 100644 --- a/src/public/javascripts/note_editor.js +++ b/src/public/javascripts/note_editor.js @@ -299,7 +299,7 @@ const noteEditor = (function() { await saveNoteIfChanged(); if (currentNote.detail.mime.endsWith("env=frontend")) { - const bundle = await server.get('script/subtree/' + getCurrentNoteId()); + const bundle = await server.get('script/bundle/' + getCurrentNoteId()); executeBundle(bundle); } diff --git a/src/public/javascripts/utils.js b/src/public/javascripts/utils.js index 254f309f4..69bb04d7f 100644 --- a/src/public/javascripts/utils.js +++ b/src/public/javascripts/utils.js @@ -116,9 +116,11 @@ async function stopWatch(what, func) { } async function executeBundle(bundle) { - const api = Api(bundle.note, bundle.allNotes); + const apiContext = ApiContext(bundle.note, bundle.allNotes); - return await (function() { return eval(`const api = this; (async function() { ${bundle.script}\r\n})()`); }.call(api)); + console.log((`const apiContext = this; (async function() { ${bundle.script}\r\n})()`)); + + return await (function() { return eval(`const apiContext = this; (async function() { ${bundle.script}\r\n})()`); }.call(apiContext)); } function formatValueWithWhitespace(val) { diff --git a/src/routes/api/script.js b/src/routes/api/script.js index 680796144..f12d1edd2 100644 --- a/src/routes/api/script.js +++ b/src/routes/api/script.js @@ -9,7 +9,7 @@ const script = require('../../services/script'); const Repository = require('../../services/repository'); router.post('/exec', auth.checkApiAuth, wrap(async (req, res, next) => { - const ret = await script.executeScript(req, req.body.script, req.body.params, req.body.startNoteId); + const ret = await script.executeScript(req, req.body.script, req.body.params, req.body.startNoteId, req.body.currentNoteId); res.send({ executionResult: ret @@ -20,7 +20,7 @@ router.post('/run/:noteId', auth.checkApiAuth, wrap(async (req, res, next) => { const repository = new Repository(req); const note = await repository.getNote(req.params.noteId); - const ret = await script.executeNote(note); + const ret = await script.executeNote(req, note); res.send({ executionResult: ret @@ -42,7 +42,7 @@ router.get('/startup', auth.checkApiAuth, wrap(async (req, res, next) => { res.send(scripts); })); -router.get('/subtree/:noteId', auth.checkApiAuth, wrap(async (req, res, next) => { +router.get('/bundle/:noteId', auth.checkApiAuth, wrap(async (req, res, next) => { const repository = new Repository(req); const note = await repository.getNote(req.params.noteId); const bundle = await script.getScriptBundle(note); diff --git a/src/services/scheduler.js b/src/services/scheduler.js index 048501307..a67c84ebc 100644 --- a/src/services/scheduler.js +++ b/src/services/scheduler.js @@ -15,7 +15,7 @@ async function runNotesWithAttribute(runAttrValue) { AND notes.isDeleted = 0`, [runAttrValue]); for (const note of notes) { - script.executeNote(note); + script.executeNote(null, note); } } diff --git a/src/services/script.js b/src/services/script.js index d3ce41193..895fdd72b 100644 --- a/src/services/script.js +++ b/src/services/script.js @@ -2,21 +2,28 @@ const sql = require('./sql'); const ScriptContext = require('./script_context'); const Repository = require('./repository'); -async function executeNote(note) { - if (note.isProtected || !note.isJavaScript()) { +async function executeNote(dataKey, note) { + if (!note.isJavaScript()) { return; } - const manualTransactionHandling = (await note.getAttributeMap()).manual_transaction_handling !== undefined; - const bundle = await getScriptBundle(note); + await executeBundle(dataKey, bundle); +} + +async function executeBundle(dataKey, bundle, startNote) { + if (!startNote) { + // this is the default case, the only exception is when we want to preserve frontend startNote + startNote = bundle.note; + } + // last \r\n is necessary if script contains line comment on its last line const script = "async function() {\r\n" + bundle.script + "\r\n}"; - const ctx = new ScriptContext(null, note, bundle.allNotes); + const ctx = new ScriptContext(dataKey, startNote, bundle.allNotes); - if (manualTransactionHandling) { + if (await bundle.note.hasAttribute('manual_transaction_handling')) { return await execute(ctx, script, ''); } else { @@ -24,18 +31,25 @@ async function executeNote(note) { } } -async function executeScript(dataKey, script, params, startNoteId) { +/** + * This method preserves frontend startNode - that's why we start execution from currentNote and override + * bundle's startNote. + */ +async function executeScript(dataKey, script, params, startNoteId, currentNoteId) { const repository = new Repository(dataKey); const startNote = await repository.getNote(startNoteId); + const currentNote = await repository.getNote(currentNoteId); - const ctx = new ScriptContext(dataKey, startNote, []); - const paramsStr = getParams(params); + currentNote.content = `(${script}\r\n)(${getParams(params)})`; + currentNote.mime = 'application/javascript;env=backend'; - return await sql.doInTransaction(async () => execute(ctx, script, paramsStr)); + const bundle = await getScriptBundle(currentNote); + + return await executeBundle(dataKey, bundle, startNote); } async function execute(ctx, script, paramsStr) { - return await (function() { return eval(`const api = this;const startNote = api.__startNote;\r\n(${script}\r\n)(${paramsStr})`); }.call(ctx)); + return await (function() { return eval(`const apiContext = this;\r\n(${script}\r\n)(${paramsStr})`); }.call(ctx)); } function getParams(params) { @@ -73,6 +87,10 @@ async function getScriptBundle(note, scriptEnv, includedNoteIds = []) { scriptEnv = note.getScriptEnv(); } + if (note.type !== 'file' && scriptEnv !== note.getScriptEnv()) { + return; + } + const bundle = { note: note, script: '', @@ -86,12 +104,6 @@ async function getScriptBundle(note, scriptEnv, includedNoteIds = []) { includedNoteIds.push(note.noteId); - bundle.script = `api.__modules['${note.noteId}'] = { __noteId: '${note.noteId}', __env: '${note.getScriptEnv()}'};`; - - if (note.type !== 'file' && scriptEnv !== note.getScriptEnv()) { - return bundle; - } - const modules = []; for (const child of await note.getChildren()) { @@ -107,11 +119,12 @@ async function getScriptBundle(note, scriptEnv, includedNoteIds = []) { if (note.isJavaScript()) { bundle.script += ` -await (async function(exports, module, api, startNote, currentNote` + (modules.length > 0 ? ', ' : '') + - modules.map(child => child.title).join(', ') + `) { +apiContext.modules['${note.noteId}'] = {}; +await (async function(exports, module, api` + (modules.length > 0 ? ', ' : '') + + modules.map(child => sanitizeVariableName(child.title)).join(', ') + `) { ${note.content} -})({}, api.__modules['${note.noteId}'], api, api.__startNote, api.__notes['${note.noteId}']` + (modules.length > 0 ? ', ' : '') + - modules.map(mod => `api.__modules['${mod.noteId}'].exports`).join(', ') + `); +})({}, apiContext.modules['${note.noteId}'], apiContext.apis['${note.noteId}']` + (modules.length > 0 ? ', ' : '') + + modules.map(mod => `apiContext.modules['${mod.noteId}'].exports`).join(', ') + `); `; } else if (note.isHtml()) { @@ -121,6 +134,10 @@ ${note.content} return bundle; } +function sanitizeVariableName(str) { + return str.replace(/[^a-z0-9_]/gim, ""); +} + module.exports = { executeNote, executeScript, diff --git a/src/services/script_context.js b/src/services/script_context.js index be94b3a45..687231bfa 100644 --- a/src/services/script_context.js +++ b/src/services/script_context.js @@ -11,11 +11,16 @@ const axios = require('axios'); function ScriptContext(dataKey, startNote, allNotes) { dataKey = protected_session.getDataKey(dataKey); - const repository = new Repository(dataKey); - this.__startNote = startNote; - this.__notes = utils.toObject(allNotes, note => [note.noteId, note]); - this.__modules = {}; + this.modules = {}; + this.notes = utils.toObject(allNotes, note => [note.noteId, note]); + this.apis = utils.toObject(allNotes, note => [note.noteId, new ScriptApi(dataKey, startNote, note)]); +} + +function ScriptApi(dataKey, startNote, currentNote) { + const repository = new Repository(dataKey); + this.startNote = startNote; + this.currentNote = currentNote; this.axios = axios; @@ -50,7 +55,7 @@ function ScriptContext(dataKey, startNote, allNotes) { this.updateEntity = repository.updateEntity; - this.log = message => log.info(`Script: ${message}`); + this.log = message => log.info(`Script ${currentNote.noteId}: ${message}`); this.getRootCalendarNoteId = date_notes.getRootCalendarNoteId; this.getDateNoteId = date_notes.getDateNoteId;