diff --git a/languages/js/sdk-internal/index.js b/languages/js/sdk-internal/index.js index 0525f7aa..dcc7206f 100644 --- a/languages/js/sdk-internal/index.js +++ b/languages/js/sdk-internal/index.js @@ -1,8 +1,37 @@ +// https://stackoverflow.com/a/47880734 +const supported = (() => { + try { + if (typeof WebAssembly === "object" && typeof WebAssembly.instantiate === "function") { + const module = new WebAssembly.Module( + Uint8Array.of(0x0, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00), + ); + if (module instanceof WebAssembly.Module) { + return new WebAssembly.Instance(module) instanceof WebAssembly.Instance; + } + } + } catch (e) {} + return false; +})(); + import { __wbg_set_wasm } from "./bitwarden_wasm_internal_bg.js"; -// In order to support a fallback strategy for web we need to conditionally load the wasm file -export function init(wasm) { - __wbg_set_wasm(wasm); +let loaded_wasm; + +export async function init(wasm) { + if (loaded_wasm) { + return; + } + + // If the caller provided a wasm module, use it for backwards compatibility. + if (wasm) { + loaded_wasm = wasm; + } else if (supported) { + loaded_wasm = await import("./bitwarden_wasm_internal_bg.wasm"); + } else { + loaded_wasm = await import("./bitwarden_wasm_internal_bg.wasm.js"); + } + + __wbg_set_wasm(loaded_wasm); } export * from "./bitwarden_wasm_internal_bg.js"; diff --git a/languages/js/sdk-internal/package.json b/languages/js/sdk-internal/package.json index 29e5c5a5..acc37495 100644 --- a/languages/js/sdk-internal/package.json +++ b/languages/js/sdk-internal/package.json @@ -13,11 +13,12 @@ "node/bitwarden_wasm_internal_bg.wasm", "node/bitwarden_wasm_internal_bg.wasm.d.ts", "node/bitwarden_wasm_internal.d.ts", - "node/bitwarden_wasm_internal.js" + "node/bitwarden_wasm_internal.js", + "types.d.ts" ], "main": "node/bitwarden_wasm_internal.js", "module": "index.js", - "types": "bitwarden_wasm_internal.d.ts", + "types": "types.d.ts", "scripts": {}, "sideEffects": [ "./bitwarden_wasm_internal.js" diff --git a/languages/js/sdk-internal/types.d.ts b/languages/js/sdk-internal/types.d.ts new file mode 100644 index 00000000..e11ed53a --- /dev/null +++ b/languages/js/sdk-internal/types.d.ts @@ -0,0 +1,3 @@ +export * from "./bitwarden_wasm_internal"; + +export function init(module?: any): Promise;