UNPKG

recime-bot-runtime

Version:

This runtime is intended to run inside a micro-service container with platform specific integration and module interpreter.

113 lines (112 loc) 4.48 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var fs = require("fs"); var path = require("path"); var vm = require("vm"); var HandleBars = require("handlebars"); var babel = require('babel-core'); var presetEnv = require('babel-preset-env'); var CodeBlock = /** @class */ (function () { function CodeBlock(message) { this.message = message; } CodeBlock.prototype.execute = function (sender, options) { var _this = this; var __ = options.__; return new Promise(function (resolve, reject) { var r = []; var sandbox = { console: { log: function (message) { if (typeof message === 'object') { return r.push(__.text(JSON.stringify(message))); } r.push(__.text(message || 'undefined')); } }, exports: exports, process: { env: { PLATFORM: options.context.platform, UID: options.context.bot.id } }, Buffer: Buffer, url: function (p) { var asset = p.replace(/(\/)?assets\//ig, ""); return "https://assets.recime.io/" + path.normalize(options.context.bot.id + "/" + asset); }, require: function (module) { var location = options.context.homedir + "/" + options.context.bot.id; if (module && module.charAt(0) === '.') { return path.resolve(location, module); } return require(module); }, __dirname: options.context.homedir + "/" + options.context.bot.id }; try { var local = require('domain').create(); local.run(function () { var config = _this.message.content.config; var o = { args: sender.options.context.args, nlp: sender.options.nlp, user: sender.options.user, vars: sender.options.vars }; if (config) { if (config.variable) { config.variable = config.variable.replace(/[\{\}\s]+/ig, ''); } var str = JSON.stringify(config); var template = HandleBars.compile(str); var sender_1 = { sender: o.args.sender }; var context_1 = Object.assign({}, o.user, o.vars.values, sender_1); o.config = JSON.parse(template(context_1)); } var message = _this.processMessage(_this.message); var handler = vm.runInNewContext(message, sandbox); handler(o, function (result) { if (Array.isArray(result)) { r.push.apply(r, result); } else if (result) { r.push(result); } resolve(r); }); }); local.on('error', function (ex) { reject(ex); }); } catch (ex) { reject(ex); } }); }; CodeBlock.prototype.processMessage = function (message) { switch (message.type) { case 'json-api': { var filePath = path.join(__dirname, 'plugins', message.type + ".js"); if (fs.existsSync(filePath)) { return this.transformCode(fs.readFileSync(filePath, 'utf-8')); } throw new Error("Unsupported message type \"" + message.type + "\"!"); } default: { return this.transformCode(message.content.code); } } }; CodeBlock.prototype.transformCode = function (code) { return babel.transform(code, { 'presets': [presetEnv] }).code; }; return CodeBlock; }()); exports.CodeBlock = CodeBlock;