epilogue.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. let inited = false;
  2. module.exports.loadWasmSync = function () {
  3. if (inited) {
  4. return;
  5. }
  6. if (initPromise) {
  7. throw new Error("Asynchronous initialisation already in progress: cannot initialise synchronously");
  8. }
  9. const bytes = unbase64(require("./cashu_sdk_js_bg.wasm.js"));
  10. const mod = new WebAssembly.Module(bytes);
  11. const instance = new WebAssembly.Instance(mod, imports);
  12. wasm = instance.exports;
  13. wasm.__wbindgen_start();
  14. inited = true;
  15. };
  16. let initPromise = null;
  17. /**
  18. * Load the WebAssembly module in the background, if it has not already been loaded.
  19. *
  20. * Returns a promise which will resolve once the other methods are ready.
  21. *
  22. * @returns {Promise<void>}
  23. */
  24. module.exports.loadWasmAsync = function () {
  25. if (inited) {
  26. return Promise.resolve();
  27. }
  28. if (!initPromise) {
  29. initPromise = Promise.resolve()
  30. .then(() => require("./cashu_sdk_js_bg.wasm.js"))
  31. .then((b64) => WebAssembly.instantiate(unbase64(b64), imports))
  32. .then((result) => {
  33. wasm = result.instance.exports;
  34. wasm.__wbindgen_start();
  35. inited = true;
  36. });
  37. }
  38. return initPromise;
  39. };
  40. const b64lookup = new Uint8Array([
  41. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  42. 0, 0, 0, 0, 62, 0, 62, 0, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7,
  43. 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 0, 0, 0, 0, 63, 0, 26, 27, 28, 29, 30, 31, 32,
  44. 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
  45. ]);
  46. // base64 decoder, based on the code at https://developer.mozilla.org/en-US/docs/Glossary/Base64#solution_2_%E2%80%93_rewriting_atob_and_btoa_using_typedarrays_and_utf-8
  47. function unbase64(sBase64) {
  48. const sB64Enc = sBase64.replace(/[^A-Za-z0-9+/]/g, "");
  49. const nInLen = sB64Enc.length;
  50. const nOutLen = (nInLen * 3 + 1) >> 2;
  51. const taBytes = new Uint8Array(nOutLen);
  52. let nMod3;
  53. let nMod4;
  54. let nUint24 = 0;
  55. let nOutIdx = 0;
  56. for (let nInIdx = 0; nInIdx < nInLen; nInIdx++) {
  57. nMod4 = nInIdx & 3;
  58. nUint24 |= b64lookup[sB64Enc.charCodeAt(nInIdx)] << (6 * (3 - nMod4));
  59. if (nMod4 === 3 || nInLen - nInIdx === 1) {
  60. nMod3 = 0;
  61. while (nMod3 < 3 && nOutIdx < nOutLen) {
  62. taBytes[nOutIdx] = (nUint24 >>> ((16 >>> nMod3) & 24)) & 255;
  63. nMod3++;
  64. nOutIdx++;
  65. }
  66. nUint24 = 0;
  67. }
  68. }
  69. return taBytes;
  70. }