extism / js-sdk

Run Extism WebAssembly plug-ins / functions from JavaScript (supports major browsers, Node.js, Deno, Bun, and Cloudflare Workers)
https://extism.github.io/js-sdk/
BSD 3-Clause "New" or "Revised" License
65 stars 10 forks source link

runInWorker option didn't work with tsx command #87

Closed thucpn closed 2 months ago

thucpn commented 2 months ago

File: index.ts

import createPlugin from "@extism/extism";

async function main() {
    const plugin = await createPlugin(
        {
            wasm: [
                { url: "https://github.com/extism/plugins/releases/latest/download/count_vowels.wasm" },
            ],
        },
        {
            useWasi: true,
            runInWorker: true,
        }
    );

    let out = await plugin.call("count_vowels", "Yellow, World!");
    console.log(out?.text());
}

void main();

When I try running npx tsx index.ts, it throws an error about invalid worker URL:

Emitted 'error' event on Worker instance at:
    at [kOnErrorMessage] (node:internal/worker:326:10)
    at [kOnMessage] (node:internal/worker:337:37)
    at MessagePort.<anonymous> (node:internal/worker:232:57)
    at [nodejs.internal.kHybridDispatch] (node:internal/event_target:814:20)
    at exports.emitMessage (node:internal/per_context/messageport:23:28) {
  code: 'ERR_INVALID_URL',
  input: 'worker.js.map',
  base: 'data:text/javascript;base64,dmFyIE....

This error does not occur when running with the Node.js command: node index.js (index.js has the same content as index.ts above).

I guess the reason might be due to converting the URL to base64 here: https://github.com/extism/js-sdk/blob/b4aba72c01e9e8cf3218266312652d043745f3c1/src/worker-url.ts#L2

Changing from src/worker-url.ts to src/polyfills/bun-worker-url.ts accidentally make npx tsx index.ts run well!

I'm not sure about the root cause. Based on my research, using ts-import from tsx might help: https://tsx.is/dev-api/ts-import

thucpn commented 2 months ago

I created this PR: https://github.com/extism/js-sdk/pull/88. Hope it help

thucpn commented 2 months ago

It worked well now (v2.0.0-rc8). Thanks a lot @chrisdickinson @nilslice