-
Notifications
You must be signed in to change notification settings - Fork 0
/
context.ts
84 lines (70 loc) · 1.77 KB
/
context.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
import { Context, createContext, runInContext } from 'node:vm';
import { arrayDifference } from './utils';
const globalBuiltIns = Object.getOwnPropertyNames(globalThis);
const ctx = createContext({});
const contextifiedGlobal = runInContext(
'Object.getOwnPropertyNames(globalThis)',
ctx,
);
const missingBuiltIns = arrayDifference(globalBuiltIns, contextifiedGlobal);
function createProxyForBuiltIn(obj: PropertyDescriptor) {
if (obj.get) {
const targetObj = obj.get();
const val = new Proxy(targetObj, {
get(target, prop) {
return target[prop.toString()];
},
set() {
return false;
},
});
return {
...obj,
get: () => val,
set: () => {},
};
}
const targetObj = obj.value;
if (['string', 'boolean', 'symbol'].includes(typeof targetObj)) {
return obj;
}
return {
...obj,
value: new Proxy(targetObj, {
get(target, prop) {
return target[prop.toString()];
},
set() {
return false;
},
}),
};
}
function provideBuiltIn(name: string) {
let builtIn: PropertyDescriptor = {};
if (name === 'process') {
builtIn.value = {
version: process.version,
versions: process.versions,
env: {
NODE_ENV: 'production',
},
};
return builtIn;
}
if (name === 'crypto') {
builtIn.value = {};
return builtIn;
}
builtIn = Object.getOwnPropertyDescriptor(globalThis, name) || builtIn;
builtIn = createProxyForBuiltIn(builtIn);
return builtIn;
}
export function createContextWithNodeRealm(sandbox: Context) {
const context = createContext(sandbox);
missingBuiltIns.forEach((name) => {
const builtIn = provideBuiltIn(name);
Object.defineProperty(context, name, builtIn);
});
return context;
}