-
-
Save asvny/2778da8df385a01c97f5f9ddfbba24e1 to your computer and use it in GitHub Desktop.
Safe(ish) Eval
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Adopted from Alpine.js | |
// https://github.com/alpinejs/alpine/blob/b6e07b2775de444c5f9bdc4d94accb7b720fd6a7/src/utils.js#L59 | |
function saferEval(expression, context, additionalHelperVariables = {}) { | |
return (new Function(['$data', ...Object.keys(additionalHelperVariables)], `var result; with($data) { result = ${expression} }; return result`))( | |
context, ...Object.values(additionalHelperVariables) | |
) | |
} | |
export default function sandboxedEval(expression, context = {}) { | |
const resetGlobals = Object.keys(globalThis).reduce((a,k)=>{a[k]=undefined;return a;},{}); | |
return saferEval(expression, context, resetGlobals); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment