From 21f71c2a974df743ef1eeab57b770598059935ff Mon Sep 17 00:00:00 2001 From: Yehyoung Kang Date: Thu, 30 Jun 2022 07:05:18 +0900 Subject: [PATCH] fix: support decoding data URL in Node < v16 (#3) Node < v16 do not provide a global `atob()` function for decoding base64 strings, and must use `Buffer.from()` instead. Furthermore, `Buffer.from(str, 'base64').toString()` is much faster than `atob()` in Node. Thus, we should use `Buffer.from()` whenever it is available. --- src/wasm-helper.ts | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/src/wasm-helper.ts b/src/wasm-helper.ts index 138262a..d94db79 100644 --- a/src/wasm-helper.ts +++ b/src/wasm-helper.ts @@ -9,10 +9,18 @@ export const id = "/__vite-plugin-wasm-helper"; const wasmHelper = async (opts = {}, url: string) => { let result: WebAssembly.WebAssemblyInstantiatedSource; if (url.startsWith("data:")) { - const binaryString = atob(url.replace(/^data:.*?base64,/, "")); - const bytes = new Uint8Array(binaryString.length); - for (let i = 0; i < binaryString.length; i++) { - bytes[i] = binaryString.charCodeAt(i); + const urlContent = url.replace(/^data:.*?base64,/, ""); + let bytes; + if (typeof Buffer === "function" && typeof Buffer.from === "function") { + bytes = Buffer.from(urlContent, "base64"); + } else if (typeof atob === "function") { + const binaryString = atob(urlContent); + bytes = new Uint8Array(binaryString.length); + for (let i = 0; i < binaryString.length; i++) { + bytes[i] = binaryString.charCodeAt(i); + } + } else { + throw new Error("Cannot decode base64-encoded data URL"); } result = await WebAssembly.instantiate(bytes, opts); } else {