UNPKG

polyfill-crypto-methods

Version:

Polyfill for Crypto instance methods of Web Crypto API

77 lines (76 loc) 2.23 kB
let i; typeof globalThis < "u" && (i = globalThis); if (typeof self < "u") i = self; else if (typeof window < "u") i = window; else if (typeof global < "u") i = global; else try { i = Function("return this")(); } catch { } function l() { return i; } function a(e) { if (!ArrayBuffer.isView(e)) throw new TypeError( "Failed to execute 'getRandomValues' on 'Crypto': parameter 1 is not of type 'ArrayBufferView'." ); if (e.byteLength > 65536) { const t = "Failed to execute 'getRandomValues' on 'Crypto': The ArrayBufferView's byte length (" + e.byteLength + ") exceeds the number of bytes of entropy available via this API (65536)."; throw "DOMException" in globalThis ? new globalThis.DOMException(t) : new Error(t); } const o = Math.pow(256, e.BYTES_PER_ELEMENT); for (let t = 0; t < e.byteLength; ++t) e[t] = Math.floor(o * Math.random()); return e; } function y(e, o) { if (typeof e != "number") throw new TypeError( `[ERR_INVALID_ARG_TYPE]: The "size" argument must be of type number. Received type ${typeof e} (${e})` ); if (e < 0 || e > 2147483647) throw new RangeError( `[ERR_OUT_OF_RANGE]: The value of "size" is out of range. It must be >= 0 && <= 2147483647. Received ${e}` ); if (o && typeof o != "function") throw new TypeError( `[ERR_INVALID_ARG_TYPE]: The "callback" argument must be of type function. Received type ${typeof o} (${o})` ); if (!o) { const t = new Uint8Array(e); return a(t); } return new Promise((t) => { const f = new Uint8Array(e); let r = null; try { o(null, a(f)); } catch { o(r, f); } t(f); }); } function s() { return y(16).reduce((t, f, r) => { let u = t + f.toString(16).padStart(2, "0"); return (r === 3 || r === 5 || r === 7 || r === 9) && (u += "-"), u; }, ""); } const n = l(); (function() { "crypto" in n ? ("getRandomValues" in n.crypto || (n.crypto.getRandomValues = a), "randomBytes" in n.crypto || (n.crypto.randomBytes = y), "randomUUID" in n.crypto || (n.crypto.randomUUID = s)) : n.crypto = { getRandomValues: a, randomBytes: y, randomUUID: s }; })(); const p = n.crypto; export { p as crypto };