-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsandbox.ts
63 lines (58 loc) · 1.3 KB
/
sandbox.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
// @ts-nocheck
// (c) easrng 2024 all rights reserved
import * as SuperJSON from 'npm:[email protected]';
type Log = {
level: string;
args: unknown[];
};
async function execute(
code: string
): Promise<{ok: true; logs: Log[]} | {ok: false; error: string}> {
globalThis.console = new Proxy(console, {
get(target, key) {
const real = target[key];
if (typeof real === 'function' && typeof key === 'string') {
const fn = function (...args: any[]) {
logs.push({
level: key,
args
});
return real.call(this, ...args);
};
return fn;
}
}
});
const logs: Log[] = [];
async function run() {
try {
await import(url);
} catch (e) {
logs.push({
level: 'error',
args: [e.message]
});
}
}
const blob = new Blob([code], {
type: 'text/tsx'
});
const url = URL.createObjectURL(blob);
const start = performance.now();
try {
await run();
return {
ok: true,
duration: performance.now() - start,
logs
};
} catch (error) {
return {
ok: false,
duration: performance.now() - start,
error: error.message
};
}
}
export const serializedExecute = async (code: string) =>
SuperJSON.stringify(await execute(code));