-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinject.js
42 lines (37 loc) · 1.05 KB
/
inject.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
const fg = require('fast-glob');
const path = require('path');
const {NodeVM} = require('vm2');
const fs = require('fs');
const debug = require('debug')('inject');
const builtinModules = require('builtin-modules');
/**
*
* @param {String[]} globs
* @param {Object<String, Object>} toInject
*/
function inject(globs, toInject, parent) {
debug(`Parent filename: ${parent}`);
const paths = fg.sync(globs, {
cwd: path.dirname(parent)
}).map(p => path.join(path.dirname(parent), p));
debug(`Transformed Globs: ${paths}`);
paths.map(p => {
debug(`Create VM for ${p}`);
const vm = new NodeVM({
sandbox: toInject,
nesting: true,
require: {
external: true,
builtin: builtinModules
},
wrapper: 'commonjs'
});
const code = fs.readFileSync(p, { encoding: 'utf8' });
debug(`Code for ${p}: ${code}`);
vm.run(code, p);
debug(`Executed ${p}`);
});
}
module.exports = {
requireAndInject: inject
};