-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhelper.ts
88 lines (84 loc) · 2.33 KB
/
helper.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import { parse, parseExpression } from '@babel/parser';
import { createContext, runInContext, run as VMRun } from '../src/vm';
const babel = require('@babel/core');
function minifySync(code: string) {
const child_process = require('child_process');
let out = '';
try {
out = child_process.execSync('node __tests__/minifysync.js', {
input: code,
encoding: 'utf-8',
//timeout: Infinity,
maxBuffer: Infinity,
windowsHide: true, // windows os
});
} catch (error) {
// timeout, exit(1), exit(2)
console.log('error in minify:\n' + error.stdout);
throw new Error('minify failed');
}
return out;
}
export const run = function (code, ctx = {}, hoisting = true, convertES5 = false) {
let transformCode = code;
if (convertES5) {
const result = babel.transformSync(code, {
presets: [
[
'@babel/preset-env',
{
targets: {
browsers: ['safari >= 9', 'android >= 4.4'],
},
useBuiltIns: false,
},
],
],
assumptions: {
noDocumentAll: true,
noClassCalls: true,
enumerableModuleMeta: true,
constantReexports: true,
iterableIsArray: true,
noNewArrows: true,
objectRestNoSymbols: true,
privateFieldsAsProperties: true,
setClassMethods: true,
setComputedProperties: true,
setPublicClassFields: true,
setSpreadProperties: true,
superIsCallableConstructor: true,
skipForOfIteratorClosing: true,
},
configFile: false,
babelrc: false,
});
transformCode = result.code;
}
if (hoisting) {
const result = babel.transformSync(transformCode, {
plugins: [require('../plugin/hoisting')],
configFile: false,
babelrc: false,
});
transformCode = result.code;
}
try {
if (process.env.TERSER === 'true') {
transformCode = minifySync(transformCode);
}
const ast = parse(transformCode, {
sourceType: 'module',
plugins: [],
});
const sandbox: any = createContext(ctx);
return runInContext(ast, sandbox);
} catch (err) {
console.log(transformCode);
throw err;
}
};
export const runExp = function (code: string, ctx = {}) {
const sandbox: any = createContext(ctx);
return VMRun(parseExpression(code), sandbox);
};