From 40ca7a7c06d1d2b0097934d437a46f5b3e253b5b Mon Sep 17 00:00:00 2001 From: Jelle De Loecker Date: Mon, 29 Apr 2024 15:07:43 +0200 Subject: [PATCH] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20Change=20the=20way=20compi?= =?UTF-8?q?led=20template=20functions=20are=20exported?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/core/hawkejs.js | 20 ++++++++++++-------- lib/parser/builder.js | 11 +++++++---- 2 files changed, 19 insertions(+), 12 deletions(-) diff --git a/lib/core/hawkejs.js b/lib/core/hawkejs.js index 781d6f1..d2a9f17 100644 --- a/lib/core/hawkejs.js +++ b/lib/core/hawkejs.js @@ -538,7 +538,7 @@ let vm = require('vm'); * * @author Jelle De Loecker * @since 2.0.0 - * @version 2.2.0 + * @version 2.4.0 * * @param {String} code * @@ -547,34 +547,38 @@ let vm = require('vm'); Main.setMethod(function compileCodeToFunction(code, options) { let compiled, + exports, error; if (Blast.isNode) { - if (code[0] != '(') { - code = '(' + code + ')'; - } - // The function statements have to be wrapped in another scope because // we always reuse the same VM instance. If we didn't do this, // creating newer function statements would overwrite older ones. // We also have to define Blast & Hawkejs, because `runInThisContext` // does not have access to the local scope - code = `(function() { const Blast = __Protoblast, Hawkejs = Blast.Classes.Hawkejs; return ${code} }())`; + code = `(function() { const Blast = __Protoblast, Hawkejs = Blast.Classes.Hawkejs, exports = {}; ${code}; return exports; }())`; try { - compiled = vm.runInThisContext(code, options); + exports = vm.runInThisContext(code, options); } catch (err) { error = err; } } else { try { - eval('compiled = ' + code); + exports = {}; + eval(code); } catch (err) { error = err; } } + if (exports?.compiled) { + compiled = exports.compiled; + } else if (!error) { + error = new Error('No compiled function found'); + } + if (error) { error.code = code; throw error; diff --git a/lib/parser/builder.js b/lib/parser/builder.js index 035b501..4977484 100644 --- a/lib/parser/builder.js +++ b/lib/parser/builder.js @@ -580,7 +580,7 @@ Builder.setMethod(function closeElement(entry) { * * @author Jelle De Loecker * @since 2.2.0 - * @version 2.2.0 + * @version 2.4.0 * * @return {string} */ @@ -594,16 +594,19 @@ Builder.setMethod(function toCode() { let functions = {}, result = '', - header = '', sr; for (sr of this._subroutines) { functions[sr.name] = R(sr.name); - result += '\n\n'; + + if (result) { + result += '\n\n'; + } + result += sr.toString(); } - result = '(' + Hawkejs.Parser.Parser.uneval(functions) + ');\n' + result; + result += '\n\nexports.compiled = ' + Hawkejs.Parser.Parser.uneval(functions) + ';\n'; return result; });