UNPKG

2.02 kBJavaScriptView Raw
1const AsyncFunction = Object.getPrototypeOf(async function () { }).constructor;
2
3const CompiledFunctions = {}
4
5const JS_TAG_PATTERN = /<\?js([\D\d]+?)\?>/ig;
6const SERVER_OPEN_TEMPLATE_PATTERN = /\!\{/ig;
7
8// const { Isolate } = require('isolated-vm');
9const path = require('path');
10
11const BlazeError = require(path.join(process.env.BLAZE_LIBRARY, '/error.js'));
12
13const modules = require(path.join(process.env.BLAZE_INSTANCE, '/modules/modules.json'));
14
15const RESERVED_letIABLES = require(path.join(__dirname, '/../reserved_keywords.json'));
16
17module.exports = class {
18 async parse(context, content) {
19 if ("string" === typeof (content)) {
20 // const engine = new Isolate();
21 // const jail = await enigne.createContext();
22 // await jail.global.set('Error', BlazeError);
23
24 let processor = await this.generate(content);
25 context.$_SERVER.Response = await processor(context.$_SERVER.Response);
26 // context.$_SERVER.Response = await code.run(jail);
27 } else {
28 context.$_SERVER.Response = content;
29 }
30
31 return context;
32 }
33
34 async compile(code, filename) {
35 let function_name = filename;
36 return (await this.generate(code)).toString().replace('anonymous', 'CompiledFunctions["' + function_name + '"]');
37 }
38
39 async generate(code) {
40 return new AsyncFunction('response', "response += \`" + code.replace(/\$\{/ig, '\*\*{')
41 .replace(SERVER_OPEN_TEMPLATE_PATTERN, '\${')
42 .replace(JS_TAG_PATTERN, (match) => {
43 let retVal = "\`;" + match.substring(4, match.length - 2) + "response += \`";
44 return retVal;
45 })
46 + "\`; return response;")
47 }
48
49 async unescape(code) {
50 return code.replace(/\\('|\\)/g, "$1").replace(/[\r\t\n]/g, " ");
51 }
52
53 async encode(doNotSkipEncoded) {
54 let encodeHTMLRules = { "&": "&#38;", "<": "&#60;", ">": "&#62;", '"': "&#34;", "'": "&#39;", "/": "&#47;" },
55 matchHTML = doNotSkipEncoded ? /[&<>"'\/]/g : /&(?!#?\w+;)|<|>|"|'|\//g;
56 return function (code) {
57 return code ? code.toString().replace(matchHTML, function (m) { return encodeHTMLRules[m] || m; }) : "";
58 }
59 }
60}
\No newline at end of file