extism / js-pdk

Write Extism plugins in JavaScript & TypeScript
BSD 3-Clause "New" or "Revised" License
56 stars 16 forks source link

feat: global `eval` function for better javascript support #64

Closed gabrielmfern closed 7 months ago

gabrielmfern commented 7 months ago

I am building a React Email component renderer with the purpose of allowing to render them in any language, but the current POC I have requires the use of eval, which is currently the simplest, and this PDK does not support it.

Since there is no way I know of that I can polyfill eval within JavaScript, at least not in a way that isn't extremely slow, I decided to try getting an implementation of this in the PDK.

This implementation simply calls out the quickjs eval_global inside the context and adds a eval property for a callback inside of Rust.

It also shouldn't be very hard to maintain, as eval does not need many safeguards.

Caveats

In my use case, and I wasn't able to figure out why, but calling eval plain without any property access (i.e., globalThis.eval) was yielding errors saying eval is not a function. Even though I didn't get the same errors when doing the same under C or when calling it through a property access globalThis.eval(...). Not sure if this is a quickjs_wasm_rs issue or not. Let me know if you have any more insights on this.

bhelx commented 7 months ago

Interesting, eval has always worked for me. Let see if i can reproduce. thanks for taking the time to fix it!

gabrielmfern commented 7 months ago

@bhelx Really? Is eval already added into the globals by quickjs? I thought it only did it when running with their REPL.

bhelx commented 7 months ago

I modified the simple example and wrapped the input in eval():

function greet() {
  Host.outputString(`Hello, ${eval(Host.inputString())}!`)
}

module.exports = { greet }
extism call examples/simple_js.wasm greet --wasi --input="20 + 22"
Hello, 42!

Is it possible that you're using a bundler or doing something that is monkey-patching the eval away?

gabrielmfern commented 7 months ago

Yeah, I think that I probably had something that was messing up the eval. Also tried it with my POC, and it works without my patch, going to close this one. Thanks for letting me know!

bhelx commented 7 months ago

Thanks for taking the time to post an issue. Anything else you need let me know. Feel free to reach out in our Discord too if you want to discuss looser ideas: https://extism.org/discord

gabrielmfern commented 7 months ago

@bhelx I actually have another issue and a patch for it to get it fixed, but wanted to know what is the expected behavior, here's my Discord message on this