fantasy-console/runcode.ts

56 lines
1.0 KiB
TypeScript
Raw Normal View History

2023-05-03 15:17:27 -07:00
// deno-lint-ignore no-explicit-any
2023-05-04 20:14:48 -07:00
const G: any = {
eval: eval,
};
2023-05-08 21:48:16 -07:00
// deno-lint-ignore no-explicit-any
const builtins: any = {};
2023-05-03 15:17:27 -07:00
const context = new Proxy(G, {
get: (target, prop) => {
2023-05-08 21:48:16 -07:00
if (prop in builtins) {
return builtins[prop as keyof typeof builtins];
}
2023-05-03 15:17:27 -07:00
return target[prop];
},
set: (target, prop, value) => {
target[prop] = value;
return true;
},
has: () => {
return true;
},
});
export const runCode = (code: string) => {
try {
new Function(code);
} catch (err) {
throw err;
}
const fn = new Function("context", `
with (context) {
${code}
}
`);
return fn(context);
}
2023-05-04 20:14:48 -07:00
export const evalCode = (code: string) => {
try {
return runCode(`return eval("(${code.replaceAll('"', '\\"')})");`);
} catch (err) {
if (err.name === "SyntaxError") {
return runCode(`return eval("${code.replaceAll('"', '\\"')}");`);
} else {
throw err;
}
}
}
2023-05-03 15:17:27 -07:00
// deno-lint-ignore no-explicit-any
export const addToContext = (name: string, value: any) => {
2023-05-08 21:48:16 -07:00
builtins[name] = value;
2023-05-06 12:05:02 -07:00
}
2023-05-08 21:48:16 -07:00
export const getBuiltins = () => {
return builtins;
2023-05-03 15:17:27 -07:00
}