Skip to content

Commit

Permalink
refactor: relocate scope arg in async function
Browse files Browse the repository at this point in the history
  • Loading branch information
jorenrui committed Feb 5, 2024
1 parent d5a8da4 commit c97d304
Showing 1 changed file with 10 additions and 15 deletions.
25 changes: 10 additions & 15 deletions lib/generators/interpreter.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,22 +9,23 @@ const DEFAULT_SCOPE = {
Function: {},
};

function safeAsyncFunction(context, code, isExpression) {
function safeAsyncFunction(context, scope, code, isExpression) {
try {
const expression = !isExpression
? `(async()=>{${code}})()`
: code

let func = new AsyncFunction(
['scope'],
`let __result; with (scope) { __result = ${expression} }; return __result;`
['__scope'],
`let __result; with (__scope) { __result = ${expression} }; return __result;`
).bind(context)

Object.defineProperty(func, "name", {
value: `[MiniJS] ${code}`,
})

return func
const result = func(scope)
return result
} catch (error) {
console.log(`Failed to run code for Entity#${context.id}:\n\n${code}`)
console.error(error)
Expand All @@ -41,13 +42,7 @@ export class Interpreter extends Lexer {
const code = super.output()
const scope = { ...DEFAULT_SCOPE, proxyWindow: MiniJS.window }

try {
return await safeAsyncFunction(context.element, code, this.isExpression)(scope)
} catch (error) {
console.log(code)
console.log(error)
return
}
return await safeAsyncFunction(context.element, scope, code, this.isExpression)
}
}

Expand All @@ -64,13 +59,13 @@ export class ClassInterpreter extends Lexer {
let newClassNames = [...this._baseClasses]

if (typeof classNames === 'string') {
const result = await safeAsyncFunction(context.element, classNames, this.isExpression)(scope)
const result = await safeAsyncFunction(context.element, scope, classNames, this.isExpression)
newClassNames = newClassNames.concat((result ?? '').split(' '))
} else if (Array.isArray(classNames)) {
for (const conditional of classNames) {
const condition = await safeAsyncFunction(context.element, conditional.test, true)(scope)
const consequent = await safeAsyncFunction(context.element, conditional.consequent, conditional.isExpression)(scope)
const alternate = await safeAsyncFunction(context.element, conditional.alternate, conditional.isExpression)(scope)
const condition = await safeAsyncFunction(context.element, scope, conditional.test, true)
const consequent = await safeAsyncFunction(context.element, scope, conditional.consequent, conditional.isExpression)
const alternate = await safeAsyncFunction(context.element, scope, conditional.alternate, conditional.isExpression)

const consequentClasses = consequent.split(' ')
const alternateClasses = alternate.split(' ')
Expand Down

0 comments on commit c97d304

Please sign in to comment.