-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
68 lines (50 loc) · 1.89 KB
/
index.js
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
const ivm = require('isolated-vm');
const Compiler = require('hertzscript-compiler');
const Dispatcher = require('hertzscript-dispatcher');
if (typeof SharedArrayBuffer === 'undefined') {
console.error('Please run with --harmony_sharedarraybuffer flag.');
if (process.argv[2] === '--harmony_sharedarraybuffer') {
console.error('You have to put the flag *before* the script name since you\'re passing the flag to v8 and not to this script.');
}
process.exit(1);
}
/* Coroutine to be launched by Hz on the Isolate */
function coroutine() {
console.log('Hello Dani');
}
/* Create Isolate */
const isolate = new ivm.Isolate({ memoryLimit: 128 });
const context = isolate.createContextSync();
const jail = context.global;
/* Setup Hz */
const source = Compiler(`(${coroutine})`, false, false, false);
const func = new Function('exports', 'require', 'module', '__filename', '__dirname', `return hzUserLib => { return ${source} };`);
const dispatcher = new Dispatcher();
dispatcher.import(func(exports, require, module, __filename, __dirname));
/* Bind references */
jail.setSync('global', jail.derefInto());
jail.setSync('_ivm', ivm);
jail.setSync('_log', new ivm.Reference(function(...args) {
console.log(...args);
}));
jail.setSync('_run', new ivm.Reference(function(...args) {
dispatcher.runComplete(); // ...args
}));
/* Bootstrap Isolate */
const bootstrap = isolate.compileScriptSync('new '+ function() {
const ivm = _ivm;
delete _ivm;
const log = _log;
delete _log;
const run = _run;
delete _run;
global.log = function(...args) {
log.applyIgnored(undefined, args.map(arg => new ivm.ExternalCopy(arg).copyInto()));
};
global.run = function(...args) {
run.applyIgnored(undefined, args.map(arg => new ivm.ExternalCopy(arg).copyInto()));
};
});
bootstrap.runSync(context);
/* Run Hz in a new Isolate */
isolate.compileScriptSync('log("Running Hz Script in a new Isolate"); run();').runSync(context);