UNPKG

2.49 kBJavaScriptView Raw
1/*
2 * Licensed under the Apache License, Version 2.0 (the "License");
3 * you may not use this file except in compliance with the License.
4 * You may obtain a copy of the License at
5 *
6 * http://www.apache.org/licenses/LICENSE-2.0
7 *
8 * Unless required by applicable law or agreed to in writing, software
9 * distributed under the License is distributed on an "AS IS" BASIS,
10 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 * See the License for the specific language governing permissions and
12 * limitations under the License.
13 */
14
15'use strict';
16
17const Logger = require('@accordproject/ergo-compiler').Logger;
18const Util = require('@accordproject/ergo-compiler').Util;
19const moment = require('moment-mini');
20// Make sure Moment serialization preserves utcOffset. See https://momentjs.com/docs/#/displaying/as-json/
21moment.fn.toJSON = Util.momentToJson;
22
23const Engine = require('./engine');
24
25const {
26 VM,
27 VMScript
28} = require('vm2');
29
30/**
31 * <p>
32 * VMEngine class. Execution of template logic against a request object, returning a response to the caller.
33 * This is the vm2-based engine.
34 * </p>
35 * @class
36 * @public
37 * @memberof module:ergo-engine
38 */
39class VMEngine extends Engine {
40 /**
41 * Engine kind
42 * @return {string} which kind of engine
43 */
44 kind() {
45 return 'vm2';
46 }
47
48 /**
49 * Compile a script for a JavaScript machine
50 * @param {string} script - the script
51 * @return {object} the VM-ready script object
52 */
53 compileVMScript(script) {
54 return new VMScript(script);
55 }
56
57 /**
58 * Execute a call in a JavaScript machine
59 * @param {number} utcOffset - UTC Offset for this execution
60 * @param {object} now - the definition of 'now'
61 * @param {object} options to the text generation
62 * @param {object} context - global variables to set in the VM
63 * @param {object} script - the initial script to load
64 * @param {object} call - the execution call
65 * @return {object} the result of execution
66 */
67 runVMScriptCall(utcOffset,now,options,context,script,call) {
68 const vm = new VM({
69 timeout: 1000,
70 sandbox: {
71 moment: moment,
72 logger: Logger,
73 utcOffset: utcOffset,
74 now: now,
75 options: options
76 }
77 });
78 vm.freeze(context, 'context');
79 vm.run(script);
80 return vm.run(call);
81 }
82
83}
84
85module.exports = VMEngine;