server: revert and use a global shim

This commit is contained in:
Koushik Dutta
2024-08-04 00:14:59 -07:00
parent ddb93b28cd
commit b8eec159bc

View File

@@ -4,19 +4,25 @@ export interface CompileFunctionOptions {
filename?: string;
}
function compileFunction(code: string, params?: ReadonlyArray<string>, options?: CompileFunctionOptions): any {
params = params || [];
if (options?.filename)
code = `${code}\n//# sourceURL=${options.filename}\n`;
const f = `(function(${params.join(',')}) {;${code}\n;})`;
return eval(f);
function compileFunction(): any {
// this is a hacky way of preventing the closure from capturing the code variable which may be a large blob.
try {
// "new Function" can't be used because it injects newlines per parameter.
// this causes source mapping to get misaligned.
return eval((globalThis as any).compileFunctionShim);
}
finally {
delete (globalThis as any).compileFunctionShim;
}
}
export function evalLocal<T>(peer: RpcPeer, script: string, filename?: string, coercedParams?: { [name: string]: any }): T {
const params = Object.assign({}, peer.params, coercedParams);
const f = compileFunction(script, Object.keys(params), {
filename,
});
let code = script;
if (filename)
code = `${code}\n//# sourceURL=${filename}\n`;
(globalThis as any).compileFunctionShim = `(function(${Object.keys(params).join(',')}) {;${code}\n;})`;
const f = compileFunction();
const value = f(...Object.values(params));
return value;
}